diff --git a/.cargo/config.toml b/.cargo/config.toml index acb86eae..e65ef03e 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -5,3 +5,98 @@ xtask = "run -p xtask --" # macros use, and then clippy and test each build their own copy of them. [profile.dev.package."*"] debug = "line-tables-only" + +# Test builds compile the craft UI framework below the workspace's opt-level 2: the Windows test +# build spends most of its time on these crates and the generics they share, and their tests run +# no heavy pixel code. Crates whose tests run on the 2 MiB Windows test stack stay at 1; the rest +# and ui-egui use 0. `cargo run` and `cargo build` use the dev profile and are unaffected. + +[profile.test.package.craft-ui] +opt-level = 1 + +[profile.test.package.craft-ui-contract] +opt-level = 1 + +[profile.test.package.craft-ui-shell] +opt-level = 1 + +[profile.test.package.craft-ui-canvas] +opt-level = 1 + +[profile.test.package.craft-ui-panels] +opt-level = 1 + +[profile.test.package.craft-ui-widgets] +opt-level = 1 + +[profile.test.package.craft-host] +opt-level = 1 + +[profile.test.package.craft-theme] +opt-level = 1 + +[profile.test.package.craft-behavior] +opt-level = 1 + +[profile.test.package.craft-font-catalog] +opt-level = 1 + +[profile.test.package.craft-ui-patterns] +opt-level = 0 + +[profile.test.package.craft-update] +opt-level = 0 + +[profile.test.package.craft-keymap] +opt-level = 0 + +[profile.test.package.craft-dialogs] +opt-level = 0 + +[profile.test.package.craft-settings] +opt-level = 0 + +[profile.test.package.craft-platform] +opt-level = 0 + +[profile.test.package.craft-window] +opt-level = 0 + +[profile.test.package.craft-cloud-ui] +opt-level = 0 + +[profile.test.package.craft-pdf] +opt-level = 0 + +[profile.test.package.texturecraft-ui-egui] +opt-level = 0 + +# The TLS stack and the dialog, browser and screen capture crates: no test makes a TLS connection, opens a file dialog or +# captures the screen, so their optimized builds only cost test build time. + +[profile.test.package.ring] +opt-level = 0 + +[profile.test.package.rustls] +opt-level = 0 + +[profile.test.package.rustls-webpki] +opt-level = 0 + +[profile.test.package.rustls-platform-verifier] +opt-level = 0 + +[profile.test.package.ureq] +opt-level = 0 + +[profile.test.package.ureq-proto] +opt-level = 0 + +[profile.test.package.webbrowser] +opt-level = 0 + +[profile.test.package.rfd] +opt-level = 0 + +[profile.test.package.xcap] +opt-level = 0 diff --git a/.gitattributes b/.gitattributes index 12adf75e..de2d0fd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,4 @@ *.ico binary *.icns binary *.ps1 text eol=crlf +*.tcraft binary diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 00000000..a1c1f31e --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 92288670..35cb9eeb 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -2,13 +2,13 @@ "schema": "craft-nightly-release-policy/v3", "repository": "storytold/texturecraft", "repository_id": 1419654881, - "producer_workflow_id": null, + "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "release_branch": "release", + "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", "dylanmtaylor", @@ -49,13 +49,15 @@ "issue_types": [ "VULNERABILITY" ], - "accepted_conditions": [], - "required_conditions": [ + "accepted_conditions": [ { "metric": "new_security_rating", "comparator": "GT", - "error_threshold": "1" - }, + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ { "metric": "new_reliability_rating", "comparator": "GT", diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 00000000..bd40f765 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [TextureCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + if: >- + false && github.repository == 'storytold/texturecraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected signer-branch validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/texturecraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/texturecraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/texturecraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + run_id, attempt = producer.get('id'), producer.get('run_attempt') + require(type(run_id) is int and run_id > 0, 'invalid producer run id') + require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { + 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) + }}).encode('utf-8') + request = urllib.request.Request( + 'https://api.github.com/repos/storytold/texturecraft/actions/workflows/nightly-sign.yml/dispatches', + data=body, method='POST', headers={ + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'texturecraft-nightly-dispatch' + }) + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + require(response.status == 204, 'dispatch was not accepted') + print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index d07db551..998acbae 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -1,7 +1,8 @@ name: TextureCraft release-ref nightly signer -# Enabled for supervised manual dispatch on release. Main/release contents must match. -# A reusable callee does not change context; this must be a real top-level release dispatch. +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch dispatch. on: workflow_dispatch: inputs: @@ -22,21 +23,23 @@ concurrency: jobs: release: - # Actual context guards: official repository, manual dispatch, real release branch. + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. if: >- github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_dispatch' && - github.ref == 'refs/heads/release' && github.ref_type == 'branch' + github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch' permissions: contents: write actions: read checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} # No secrets: inherit or raw platform values in this caller. Only the isolated native - # callee job may bind the existing release environment and export keys in its signing step. + # callee job may bind the release environment and export its keys; that environment must + # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5345fe9a..1600b2e0 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,13 +22,13 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc # One producer run builds every listed platform for one all-or-nothing release. The pin is the - # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the - # Linux/macOS signer (#342). + # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, + # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a895078e..5bfb7129 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -17,6 +17,7 @@ licensed and keep their license file next to them. | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 | +| `assets/samples/Material Ball.tcraft` | Material Ball sample project | TextureCraft contributors | Original procedural mesh, smart materials, and baked maps generated with TextureCraft's [`sample_session`](https://github.com/storytold/texturecraft/blob/14f650202974b509524950048305f1f36fee4282/crates/engine/src/project_cmds.rs#L61), at 1024 px texture and 256 px bake resolution, then saved as a `.tcraft` project | MIT OR Apache-2.0 | | `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-export.png` | README screenshot: the Export textures dialog | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 7da98739..9257948e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,7 +80,7 @@ dependencies = [ "futures-lite", "futures-util", "serde", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -239,11 +239,20 @@ dependencies = [ "x11rb", ] +[[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" +dependencies = [ + "serde", +] [[package]] name = "as-raw-xcb-connection" @@ -260,22 +269,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "ashpd" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-util", - "getrandom 0.4.3", - "pipewire", - "serde", - "serde_repr", - "zbus 6.3.0", -] - [[package]] name = "async-broadcast" version = "0.7.2" @@ -327,7 +320,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -358,7 +351,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -384,7 +377,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -432,7 +425,7 @@ dependencies = [ "enumflags2", "serde", "static_assertions", - "zbus 5.19.0", + "zbus", "zbus-lockstep", "zbus-lockstep-macros", "zbus_names", @@ -447,7 +440,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" dependencies = [ "atspi-common", "serde", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -529,6 +522,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + [[package]] name = "block-buffer" version = "0.10.4" @@ -623,6 +622,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "calloop" version = "0.13.0" @@ -661,9 +670,9 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -676,7 +685,7 @@ dependencies = [ "cap-primitives", "io-extras", "io-lifetimes 3.0.1", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -895,12 +904,34 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" +dependencies = [ + "bitflags 2.13.2", + "block", + "cfg-if", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "core_detect" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -919,19 +950,68 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "rustix 1.1.6", +] + +[[package]] +name = "craft-behavior" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "accesskit", + "bitflags 2.13.2", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "emath", + "kurbo", + "serde", + "smallvec", +] + +[[package]] +name = "craft-cloud-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "egui", +] + [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "md-5", "rayon", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "rayon", ] @@ -939,27 +1019,73 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "block2 0.6.2", + "craft-atomic", + "craft-host", + "craft-i18n", + "craft-platform", + "futures-lite", + "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "raw-window-handle", "rfd", + "zbus", +] + +[[package]] +name = "craft-docpath" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "harfrust 0.13.3", + "kurbo", + "skrifa 0.47.0", + "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", + "windows-registry", ] [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + +[[package]] +name = "craft-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "bitflags 2.13.2", + "craft-i18n", + "egui", + "serde", + "toml", + "web-time", +] [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "chrono", "fixed_decimal", + "icu_calendar", + "icu_collator", + "icu_datetime", "icu_decimal", "icu_locale_core", "icu_locale_fallback", @@ -969,6 +1095,7 @@ dependencies = [ "icu_provider", "icu_provider_adapters", "icu_provider_blob", + "icu_time", "log", "objc2-foundation 0.3.2", "sys-locale", @@ -980,7 +1107,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-dds", "craft-jpeg", @@ -1007,7 +1134,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "thiserror 2.0.21", ] @@ -1015,8 +1142,13 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-host", + "craft-i18n", + "craft-tracked", + "craft-ui-macros", + "craft-xml", "egui", "serde", "serde_json", @@ -1025,18 +1157,18 @@ dependencies = [ [[package]] name = "craft-materialx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585)", + "craft-xml", "thiserror 2.0.21", ] [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89#7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -1045,23 +1177,28 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", "craft-keymap", "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", "egui", - "muda", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", + "serde", + "serde_json", ] [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3)", + "craft-xml", + "craft-zip", "miniz_oxide 0.9.1", "serde_json", ] @@ -1069,7 +1206,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "brotli-decompressor", "chrono", @@ -1078,10 +1215,49 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-pdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-platform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "async-channel", + "async-io", + "async-process", + "core-graphics2", + "craft-atomic", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-theme", + "futures-lite", + "js-sys", + "log", + "objc2-app-kit 0.3.2", + "rfd", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows", + "x11rb", + "xcap", + "zbus", +] + [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b130ac1fa44f923c3024884ab8ceb5ccdb88f15f#b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "encoding_rs", "flate2", @@ -1092,69 +1268,264 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "dispatch2", "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "craft-settings" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-atomic", + "craft-host", + "dirs", + "log", + "serde", + "serde_json", + "toml", + "toml_edit", + "web-sys", + "web-time", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-xml", + "flate2", + "kurbo", + "quick-xml 0.41.0", + "resvg", + "roxmltree", + "thiserror 2.0.21", + "usvg", + "vectorcraft-geom", + "vectorcraft-pathops", ] [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", ] +[[package]] +name = "craft-theme" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", + "ecolor", + "log", + "serde", + "serde_json", + "smallvec", +] + [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] +[[package]] +name = "craft-tracked" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-fonts-build", + "craft-cloud-ui", + "craft-ui-canvas", + "craft-ui-contract", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-shell", + "craft-ui-widgets", +] + +[[package]] +name = "craft-ui-canvas" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", "egui", - "epaint", - "js-sys", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-contract" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "accesskit", + "craft-behavior", + "craft-codepage", + "craft-font-catalog", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-quit", + "craft-settings", + "craft-svg", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "craft-window", + "egui", + "epaint_default_fonts", + "flate2", + "inventory", + "log", + "scoped-tls", + "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", - "wasm-bindgen", + "smallvec", + "toml", + "typeid", "wasm-bindgen-futures", - "web-sys", + "web-time", +] + +[[package]] +name = "craft-ui-macros" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "craft-ui-panels" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui-macros", + "craft-ui-widgets", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-patterns" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pdf", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "egui", + "serde", + "serde_json", + "toml", + "toml_edit", + "zeroize", +] + +[[package]] +name = "craft-ui-shell" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-svg", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-window", + "egui", + "raw-window-handle", + "serde", + "web-time", +] + +[[package]] +name = "craft-ui-widgets" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-svg", + "craft-theme", + "craft-ui-contract", + "craft-ui-macros", + "egui", + "log", + "serde", + "smallvec", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "chrono", + "craft-host", + "craft-theme", + "craft-ui", "dunce", "egui", "flate2", - "getrandom 0.3.4", "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -1171,38 +1542,49 @@ dependencies = [ [[package]] name = "craft-usd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "half", "lz4_flex", "thiserror 2.0.21", ] +[[package]] +name = "craft-win32" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-appkit", + "craft-atomic", + "craft-behavior", + "craft-host", + "craft-settings", + "craft-win32", "egui", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "serde", + "serde_json", "wayland-client", + "winsafe", + "x11rb", ] [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1212,37 +1594,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5631e99fe126cffb74c673eb458db04299f2bb9b#5631e99fe126cffb74c673eb458db04299f2bb9b" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89#7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1348,6 +1700,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "deranged" version = "0.5.9" @@ -1364,6 +1722,27 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +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.60.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1449,7 +1828,7 @@ dependencies = [ "drm-ffi", "drm-fourcc", "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1459,7 +1838,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" dependencies = [ "drm-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1493,7 +1872,7 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", @@ -1503,7 +1882,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1540,7 +1919,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -1568,7 +1947,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1587,7 +1966,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit_winit", "arboard", @@ -1611,7 +1990,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -1624,7 +2003,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "eframe", "egui", @@ -1647,12 +2026,24 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "serde", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.44" @@ -1708,7 +2099,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1716,7 +2107,7 @@ dependencies = [ "emath", "epaint_default_fonts", "font-types", - "harfrust", + "harfrust 0.12.0", "log", "nohash-hasher", "parking_lot", @@ -1735,7 +2126,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equivalent" @@ -1750,7 +2141,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1876,6 +2267,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "foldhash" version = "0.1.5" @@ -1941,8 +2338,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", - "windows-sys 0.59.0", + "rustix 1.1.6", + "windows-sys 0.52.0", ] [[package]] @@ -2086,7 +2483,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -2359,6 +2756,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "harfrust" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "once_cell", + "read-fonts 0.43.3", + "smallvec", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -2455,6 +2865,39 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_locale_core", + "icu_provider", + "serde", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_provider", + "serde", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -2463,12 +2906,37 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", + "serde", "utf8_iter", "yoke", "zerofrom", "zerovec", ] +[[package]] +name = "icu_datetime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44df99c4c5297b05653d1a1629f13bdc9fd4044acfbbaf30b15194a1eed4cd6" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "serde", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_decimal" version = "2.3.0" @@ -2530,6 +2998,7 @@ dependencies = [ "icu_normalizer_data", "icu_properties", "icu_provider", + "serde", "smallvec", "utf16_iter", "utf8_iter", @@ -2580,6 +3049,7 @@ dependencies = [ "icu_locale_core", "icu_properties_data", "icu_provider", + "serde", "zerotrie", "zerovec", ] @@ -2632,6 +3102,22 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_time" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af37e1c3b9f3ab564b619fdf4b22de169f6381eb0f7048e3ca454290c438126b" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2690,6 +3176,12 @@ dependencies = [ "quick-error", ] +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + [[package]] name = "indexmap" version = "2.14.2" @@ -2708,6 +3200,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -2891,6 +3392,7 @@ dependencies = [ "arrayvec", "euclid", "polycool", + "serde", "smallvec", ] @@ -2952,7 +3454,7 @@ dependencies = [ "libc", "libspa-sys", "nom 8.0.0", - "rustix 1.1.5", + "rustix 1.1.6", "system-deps", ] @@ -2979,7 +3481,7 @@ dependencies = [ "image", "khronos-egl", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tracing", "wayland-backend", @@ -2994,6 +3496,19 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" +[[package]] +name = "linesweeper" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18" +dependencies = [ + "arrayvec", + "kurbo", + "polycool", + "rustc-hash 2.1.3", + "smallvec", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -3159,7 +3674,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3371,8 +3886,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -3385,10 +3900,17 @@ 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]] @@ -3397,9 +3919,29 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", "objc2 0.6.5", + "objc2-avf-audio", + "objc2-core-audio-types", + "objc2-core-foundation", "objc2-core-graphics", - "objc2-core-media", + "objc2-core-image 0.3.2", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-image-io", + "objc2-media-toolbox", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -3416,6 +3958,17 @@ dependencies = [ "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" @@ -3461,6 +4014,17 @@ dependencies = [ "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" @@ -3468,7 +4032,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -3479,11 +4045,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3498,6 +4066,16 @@ dependencies = [ "objc2-metal 0.2.2", ] +[[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" @@ -3517,6 +4095,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", "objc2 0.6.5", "objc2-core-audio", @@ -3525,6 +4104,18 @@ dependencies = [ "objc2-core-video", ] +[[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" @@ -3532,10 +4123,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3565,10 +4158,22 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] +[[package]] +name = "objc2-image-io" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-io-kit" version = "0.3.2" @@ -3602,6 +4207,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-media-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30" +dependencies = [ + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-media", +] + [[package]] name = "objc2-metal" version = "0.2.2" @@ -3672,9 +4289,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "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", @@ -3732,6 +4349,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[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" @@ -3768,7 +4391,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3885,6 +4508,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.1.13" @@ -3933,7 +4562,7 @@ dependencies = [ "libspa", "libspa-sys", "pipewire-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -3995,7 +4624,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -4042,6 +4671,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" dependencies = [ "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", "serde", ] @@ -4273,6 +4904,28 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.43.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + [[package]] name = "read-fonts" version = "0.45.1" @@ -4319,6 +4972,16 @@ 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 = "ref-cast" version = "1.0.27" @@ -4374,6 +5037,21 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + [[package]] name = "rfd" version = "0.17.2" @@ -4401,6 +5079,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + [[package]] name = "ring" version = "0.17.14" @@ -4465,6 +5152,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -4496,20 +5192,20 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4519,7 +5215,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -4576,7 +5272,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4832,6 +5528,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -4860,6 +5565,16 @@ dependencies = [ "read-fonts 0.41.0", ] +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", +] + [[package]] name = "skrifa" version = "0.48.0" @@ -4935,7 +5650,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4959,6 +5674,15 @@ 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" +dependencies = [ + "float-cmp", +] + [[package]] name = "strsim" version = "0.11.1" @@ -4971,6 +5695,16 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + [[package]] name = "syn" version = "2.0.119" @@ -5066,10 +5800,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", - "rustix 1.1.5", - "windows-sys 0.61.2", + "rustix 1.1.6", + "windows-sys 0.52.0", ] [[package]] @@ -5114,7 +5848,7 @@ dependencies = [ "image", "rayon", "rmcp", - "rustix 1.1.5", + "rustix 1.1.6", "schemars", "serde", "serde_json", @@ -5180,7 +5914,7 @@ dependencies = [ "image", "processkit", "rayon", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "sysinfo", @@ -5212,8 +5946,7 @@ dependencies = [ "craft-psd", "craft-tcraft", "craft-usd", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5631e99fe126cffb74c673eb458db04299f2bb9b)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "exr", "flate2", "gltf", @@ -5248,7 +5981,7 @@ name = "texturecraft-paint" version = "0.6.1" dependencies = [ "epaint_default_fonts", - "harfrust", + "harfrust 0.12.0", "rayon", "serde", "skrifa 0.44.0", @@ -5288,16 +6021,18 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "chrono", + "craft-behavior", "craft-dialogs", + "craft-host", "craft-i18n", "craft-image-codecs", "craft-keymap", - "craft-quit", + "craft-theme", "craft-ui", "craft-update", "craft-usd", "craft-window", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "eframe", "egui", "egui-phosphor", @@ -5314,6 +6049,7 @@ dependencies = [ "skera", "skrifa 0.48.0", "sys-locale", + "tempfile", "texturecraft-engine", "texturecraft-render", "wasm-bindgen", @@ -5322,7 +6058,7 @@ dependencies = [ "winsafe", "x11rb", "xcap", - "zbus 5.19.0", + "zbus", "zip", ] @@ -5424,6 +6160,32 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -5519,8 +6281,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", + "serde_core", + "serde_spanned", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] @@ -5616,7 +6381,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5708,6 +6473,25 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "data-url", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", +] + [[package]] name = "utf16_iter" version = "1.1.0" @@ -5750,6 +6534,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vectorcraft-geom" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "vectorcraft-pathops" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "linesweeper", + "thiserror 2.0.21", + "vectorcraft-geom", +] + [[package]] name = "vello_common" version = "0.2.0" @@ -5888,7 +6693,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -5901,7 +6706,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -5923,7 +6728,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -5985,7 +6790,7 @@ checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" dependencies = [ "bitflags 2.13.2", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -6266,7 +7071,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6653,7 +7458,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6671,7 +7476,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -6728,7 +7533,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -6740,11 +7545,10 @@ checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" [[package]] name = "xcap" -version = "0.9.10" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384" +checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e" dependencies = [ - "ashpd", "dispatch2", "image", "libwayshot-xcap", @@ -6759,7 +7563,6 @@ dependencies = [ "objc2-foundation 0.3.2", "percent-encoding", "pipewire", - "pollster 1.0.1", "rand", "scopeguard", "serde", @@ -6768,6 +7571,7 @@ dependencies = [ "widestring", "windows", "xcb", + "zbus", ] [[package]] @@ -6864,7 +7668,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -6872,38 +7676,11 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow", - "zbus_macros 5.19.0", + "zbus_macros", "zbus_names", "zvariant", ] -[[package]] -name = "zbus" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" -dependencies = [ - "async-trait", - "bitflags 2.13.2", - "endi", - "futures-core", - "hex", - "libc", - "ordered-stream", - "rustix 1.1.5", - "serde", - "serde_repr", - "socket2", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow", - "zbus_macros 6.3.0", - "zbus_utils", - "zcheapstr", - "zruntime", -] - [[package]] name = "zbus-lockstep" version = "0.5.2" @@ -6943,18 +7720,6 @@ dependencies = [ "zvariant_utils", ] -[[package]] -name = "zbus_macros" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", - "zbus_utils", -] - [[package]] name = "zbus_names" version = "4.3.4" @@ -6966,19 +7731,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus_utils" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.9", - "winnow", -] - [[package]] name = "zbus_xml" version = "5.2.1" @@ -7142,19 +7894,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "zruntime" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" -dependencies = [ - "futures-core", - "futures-io", - "rustix 1.1.5", - "socket2", - "windows-sys 0.61.2", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index 656c9522..3259c129 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ edition = "2024" license = "MIT OR Apache-2.0" [workspace.dependencies] -craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } @@ -41,7 +41,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" log = "0.4" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } half = "2" exr = { version = "1.73", default-features = false } eframe = { version = "0.37", default-features = false } @@ -63,46 +63,50 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } -craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -# Isolated aligned writer; existing archive readers retain their pin and behavior. -craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } -# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# The UI runtime's host: who the app is to the framework's dialogs (crates/ui-egui/src/framework.rs). +craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md). egui-phosphor = { path = "vendor/egui-phosphor" } [workspace.lints.rust] unsafe_code = "forbid" +# cargo-llvm-cov always sets `cfg(coverage)`: a coverage build bakes on the CPU (texturecraft-engine +# picks no GPU tracer there) and the cfg would otherwise trip unexpected_cfgs under -D warnings. +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)'] } [workspace.lints.clippy] dbg_macro = "warn" diff --git a/README.md b/README.md index 345c32c1..76dfb0ea 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ cargo run --release -p texturecraft-cli -- new builtin:crate crate.tcraft --samp cargo run --release -p texturecraft-cli -- render crate.tcraft crate.png --samples 256 # path traced cargo run --release -p texturecraft-cli -- export crate.tcraft textures # headless export cd apps/texturecraft-web && trunk serve # web build -cargo xtask ci # fmt, clippy, tests, layering, wasm +cargo xtask ci # fmt, clippy, tests, layering, wasm (not on Windows) ``` You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). @@ -256,6 +256,7 @@ are built, signed and published. Every bundled asset is listed with its licence | Build | File | |---|---| | x86_64 | `texturecraft--freebsd-x86_64.tar.gz` | +| aarch64 (ARM64) | `texturecraft--freebsd-aarch64.tar.gz` | ### Web (WebAssembly) diff --git a/ROADMAP.md b/ROADMAP.md index cb114376..7dbebfbb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,13 +2,15 @@ Stage: alpha (readiness assessment) · next: beta, ~75% readiness plus scoped compatibility and integration gates; remaining effort unestimated -> Last reviewed: 2026-11-16 · Last updated: 2026-11-16 · Change: major (UI/functionality audit, possible format/package reworks, unfinished `.mcmat` integration and incoming ArtCraft UI/shared-library work) · Target: reference app 12.2.0 +> Last reviewed: 2026-11-25 · Last updated: 2026-11-25 · Change: major (implementation audit and revised readiness estimates) · Target: reference app 12.2.0 -TextureCraft is a clean-room implementation of the professional texture-painting workflow. This -assessment covers **main at [62b2b13](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815), -version 0.6.1**, compared with the installed reference app on 2026-11-16. It follows the -[PhotoCraft roadmap format](https://github.com/storytold/photocraft/blob/main/ROADMAP.md). -Detail: [UI gaps and functional task audit](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md), +The implementation audit covers main at +[`3c026860`](https://github.com/storytold/texturecraft/commit/3c026860e36e5fbe2147c6c78ca0bbc617575887), +with workspace version 0.6.1. Current estimates incorporate landed workflows, Linux regression +tests and the MaterialCraft round trip. The November 16 live comparison with reference app 12.2.0 +at [`62b2b13`](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815) +provides the starting scores. The live artist tasks still need a repeat on current main. +See [UI gaps and functional tasks](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md), [architecture](docs/architecture.md), [automation](docs/control-protocol.md), [localization](docs/localization-parity.md), [releasing](docs/releasing.md). @@ -19,65 +21,51 @@ still need investigation; no `.spp` reader is implemented. Writing `.spp`, round back into it and compatibility with other proprietary asset/preset formats are outside this goal. Pipeline exchange uses USD, glTF/GLB, MaterialX and texture maps. -The current `.tcraft` schema/container and output-package contracts may be reworked; their -present implementations are not a frozen design. MaterialCraft `.mcmat` import remains a goal -whose next format is unfinished upstream. ArtCraft UI refactoring and further shared-library -adoption also add integration and regression work. These dependencies are part of the remaining -roadmap, even where a current task already passes. +The current `.tcraft` schema/container and output-package contracts remain open to revision. +MaterialCraft and TextureCraft have landed procedural `.mcmat` v3 support. The source-build round trip passed at the revisions below. The exchange gate still needs +a supported release pair and artist workflow checks. ArtCraft UI refactoring and +further shared-library adoption also require integration and regression checks. ## Headline numbers | | Value | Kind | |---|---|---| -| Feature breadth | ~80% (75–85%) | Estimated across feature families; no exhaustive target inventory | -| Ready for real work | ~60% (50–70%) | Estimated readiness of the assessed revision; no completion credit for incoming reworks/integrations | -| Mainstream practitioner | ~60% (50–70%) | Estimated for regular asset texturing, baking, masking and pipeline delivery | -| Essentials user | ~75% (65–85%) | Estimated for a simple mesh, layered materials/paint and texture export | -| Desktop menu catalog | 59/59 live | Observed through the running app; this is TextureCraft's own catalog | -| Engine commands | 178 registered | Observed through the running app; registration does not prove every parameter path | -| Functional review | 20 scoped check groups | UI, mixed-surface and command cases [recorded separately](docs/ui-parity.md#functional-task-audit); not an exhaustive coverage score | -| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format/package/UI migrations | -| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft`/output reworks, upstream `.mcmat`, ArtCraft UI/shared-library adoption, `.spp` feasibility and workflow/fidelity work | +| Feature breadth | ~90% | Estimated across feature families. The November 16 baseline was ~80% | +| Ready for real work | ~68% | Weighted estimate, up from ~60% on November 16. The largest gains are in feature depth, UI and interchange | +| Mainstream practitioner | ~70% | Estimated for regular asset texturing, baking, masking and pipeline delivery. The November 16 baseline was ~60% | +| Essentials user | ~85% | Estimated for a simple mesh, layered materials and paint, and texture export. The November 16 baseline was ~75% | +| Desktop menu catalog | 59/59 live | Observed on November 16 in TextureCraft's desktop catalog | +| Engine commands | 178 registered | Observed on November 16 through the running app | +| Functional review | 20 scoped check groups | November 16 UI, mixed-surface and command cases. [Functional task audit](docs/ui-parity.md#functional-task-audit) | +| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format, package and UI migrations | +| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft` and output-package reworks, `.mcmat` release validation, ArtCraft UI and shared libraries, `.spp` feasibility, and workflow and fidelity checks | -The former ~94% figure mostly counted implementation paths. This review also asks whether an -artist gets equivalent controls, predictable output, responsive interaction and dependable -delivery. The change is a measurement rebaseline and an expanded import goal, not a measured -loss of functionality. Percentages are rounded judgments; ranges express uncertainty, not -statistical confidence intervals. The old “~6 h + baking TBD” remainder is withdrawn: this -review provides no calibrated engineering or agent-hour forecast. - -The percentages describe behavior at `62b2b13`, not how much of a settled delivery plan is -finished. Potential rework can revisit working code and require repeating the checks below. -Its scope and cost are not yet measured, so remaining effort cannot be calculated as -100 minus the readiness score. Incoming upstream work is not counted as landed functionality. +Feature breadth estimates how much of the scoped feature set is present. Readiness also weighs +control depth, output fidelity, responsiveness, project safety and delivery. The earlier ~94% +figure mostly counted implementation paths and used a narrower scope. The current figures are +audit judgments based on the evidence below. Potential format and UI rework can require repeating +earlier checks, and its scope and cost remain unestimated. ### Readiness by audience | Audience | Ready % | Hours to ~95% | Work that dominates | |---|---|---|---| -| Full scoped target | ~60% | Unestimated | Workflow depth, format/output-package decisions, `.mcmat`, ArtCraft UI/shared libraries, bake/display fidelity, color management, read-only `.spp` and platform validation | -| Mainstream practitioner | ~60% | Unestimated | Reliable masks/painting, MaterialCraft exchange once its contract is ready, project/package compatibility, larger projects and destination-app checks | -| Essentials user | ~75% | Unestimated | Discoverable controls, predictable startup/GPU selection and save/reopen reliability retained through format/UI migrations | +| Full scoped target | ~68% | Unestimated | Workflow depth, format and package decisions, ArtCraft UI and shared libraries, bake and display fidelity, color management, read-only `.spp` and platform validation | +| Mainstream practitioner | ~70% | Unestimated | Production-scale baking and masking, project and package compatibility, and destination-tool checks | +| Essentials user | ~85% | Unestimated | Startup and GPU coverage, discoverable controls, and dependable save/reopen for simple mesh, paint, material and texture-export tasks | -Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material drag and drop, mask -and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate -command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. -The interface is recognizably close in its painting, bake and export workspaces, but still lacks -mask-thumbnail effect menus and several fill controls. -Generator depth is limited, bake equivalence is open, -and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; -these include requests and older reports, not 96 reproduced defects. The published -[v0.6.1 release](https://github.com/storytold/texturecraft/releases/tag/v0.6.1) already exists; -“first release v0.1.0” is no longer an upcoming milestone. - -Native/output contracts and the future MaterialCraft, ArtCraft UI and shared-library integrations -also remain unsettled. Passing a legacy reader or a standalone export check does not complete -those future workflows. +The live baseline verified mouse and keyboard painting in 3D and 2D, undo and redo, material +drag and drop, mask and generator edits, UV rectangle fill, baking, native saving and texture +export. Separate command checks covered high-to-low transfer, UDIM packing and scene/material +export. Since then, the mask and fill controls, generator coverage, Bake Mode and export workflows +have expanded. Beta readiness still depends on representative projects, hardware and performance +coverage, project recovery and destination-tool checks. The latest published stable release is +[v0.6.1](https://github.com/storytold/texturecraft/releases/tag/v0.6.1). A proposed beta gate is ~75% readiness plus repeatable artist tasks on representative assets: high/low baking and smart masks, precise 3D/2D painting, a multi-set UDIM project, save/reopen without lost work, and exports checked in destination tools. Startup failures and data-loss -blockers on the supported test matrix must be resolved. This audit does not establish that gate. +blockers on the supported test matrix must be resolved. The gate remains open. Beta scope must identify which reworks/integrations it requires and which remain later goals. Every adopted project/package version needs a compatibility policy and regression checks; MaterialCraft exchange must be validated against a named producer/consumer version pair before @@ -85,66 +73,55 @@ it is advertised as ready. ## By dimension -All percentages below are estimates. The weights sum to 100; their additive result is 59.1%, -rounded to ~60%. Hardware, performance and stability scores include confidence discounts for -incomplete validation; they are not measured success rates or speed comparisons. +With the same weights, readiness rises from 59.1% to 68.0%. The table shows the November 25 scores. +The evidence column includes the November 16 scores for comparison. | Dimension | % ready | Weight | Hours to full | Evidence / remaining work | |---|---:|---:|---|---| -| Features (depth) | ~65% | 30 | TBD | Core editing tasks and high/low/UDIM outputs exercised; generators, properties and specialized workflows need depth. Mask anchors landed after this assessment; live UI validation remains | -| UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain | -| File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain | -| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete | -| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | -| Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review | -| Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations | -| Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only | -| Automation / ecosystem | ~75% | 5 | TBD | 178 commands and CLI/control/MCP architecture; shared-library adoption, command/UI compatibility and the future MaterialCraft contract need integration checks | +| Features (depth) | ~80% | 30 | TBD | Generators, mask actions, fill controls and bake workflows expanded. Specialized artist tasks and output fidelity still need repeatable checks. November 16 estimate ~65% | +| UI/UX fidelity | ~75% | 20 | TBD | Layer targeting, the workspace, Bake Mode and export dialogs changed. Live task, layout, shortcut and accessibility checks remain. November 16 estimate ~65% | +| File formats / interchange | ~70% | 10 | TBD | Shared import/export codecs, rebuilt UV persistence and linked `.mcmat` v3 have landed. Project/output contracts, `.spp` and destination-tool coverage remain open. November 16 estimate ~60% | +| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete. November 16 estimate ~50% | +| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% | +| Performance | ~45% | 10 | TBD | Main added dirty-region uploads, cheaper undo snapshots and faster glTF lookups. Establish response-time and memory budgets with representative large projects. November 16 estimate ~40% | +| Stability | ~60% | 10 | TBD | The live baseline covered small save/reopen and undo/redo. Rebuilt UV layouts gained persistence checks. Recovery, large projects and long sessions remain open. November 16 estimate ~55% | +| Platforms | ~70% | 3 | TBD | Desktop and web build paths exist. Nightly packaging and supervised signing workflows landed for Windows, Linux and macOS. Install, update and hardware checks remain. November 16 estimate ~65% | +| Automation / ecosystem | ~80% | 5 | TBD | CLI, control and MCP share engine commands. Bake settings sync, UV import and generator controls have command paths. The MaterialCraft source-build round trip passed. Surface-specific integration and release-pair checks remain. November 16 estimate ~75% | ## Features -These are approximate depth/readiness estimates, not percentages of matching pixels or completed -menu entries. Feature rows overlap and are not an additional additive score. +These depth estimates overlap. The overall readiness estimate uses the weighted dimensions above. | Area | % ready | Hours | What works / main gaps | |---|---:|---|---| -| Projects and files | ~80% | TBD | Current `.tcraft` new/save/reopen passed with layers, effects and baked maps retained. Schema/container rework remains possible; versioning/migration policy and renewed persistence/recovery tests are needed if adopted. Large cases, Alembic HDF5 and animation remain open; PBR folder/ZIP/selected-file import landed after this assessment: `file.importPbrFolder` creates one fill layer from named maps, including packed ORM and OpenGL/DirectX normals, with a UI dialog and optional native library copy; it is not credited in this score | -| Texture sets and UDIM | ~80% | TBD | Two tiles exported at independent 128/256 px sizes with expected packed-channel values; 21 channel kinds in source. Many-set/many-tile production coverage remains untested | -| Layers, masks and effects | ~75% | TBD | UI fill/black-mask creation, generator editing/duplication and native persistence passed at the assessed revision. Mask-thumbnail context actions remain missing; effect renaming and mask-stack anchors landed afterward, with live UI validation still open | -| Painting and precise 2D work | ~70% | TBD | Mouse painting in both views, keyboard undo/redo, view shortcuts, brush gesture and UV-island rectangle fill passed. Nine tool kinds exist; brush feel, pressure/tilt, other tool task suites and complete trim sheets need validation | -| Generators and smart masks | ~45% | TBD | Seven generator kinds and 24 smart-mask presets; Position/global-balance editing worked in the UI. Shared adjustments, resolution and input slots exist; richer generators, micro-detail workflows and saving user smart masks remain incomplete | -| Materials and asset library | ~60% | TBD | 72 procedural materials and 21 smart materials; shelf search/drop worked. Legacy MaterialCraft paths exist, but the planned `.mcmat` contract is unfinished upstream. Library variety, previews and cross-app integration remain work | -| MaterialCraft `.mcmat` integration | Incomplete; upstream-dependent | TBD after contract | Current reader accepts legacy v1/v2. The proposed MaterialX-based v3 still needs upstream completion, shared-library support, TextureCraft mapping/UI and tests with real producer outputs; this is not a completed material exchange workflow | -| Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | -| Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | -| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | -| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete | +| Projects and files | ~85% | TBD | November 16 estimate ~80%. PBR folders, ZIPs and selected files import into one fill layer, with packed ORM and OpenGL/DirectX normal support. New Project can rebuild mesh UVs and persist the rebuilt layout. The shipped Material Ball project is available as a starting point. Large saves, recovery and Alembic HDF5/animation remain open | +| Texture sets and UDIM | ~85% | TBD | November 16 estimate ~80%. Baseline command checks covered two tiles at different sizes and packed maps. Bake settings can sync across sets, export settings can vary by set and map, and hovering a set highlights it in the viewport. Validate many-set, many-tile projects at production sizes | +| Layers, masks and effects | ~85% | TBD | November 16 estimate ~75%. Mask thumbnails have their own effect menu and a Shift-click toggle. Effect renaming, mask anchors and user smart-mask saving/application are implemented. Repeat the workflow in a live desktop session with undo and reopen | +| Painting and precise 2D work | ~75% | TBD | November 16 estimate ~70%. The live baseline covered mouse painting, undo/redo and UV-island rectangle fill. Main added brush presets and fixes for steep-angle strokes and intermittent pen-pressure spikes. Brush feel, pressure and tilt across devices, and trim-sheet tasks still need live checks. [Presets #259](https://github.com/storytold/texturecraft/pull/259), [strokes #442](https://github.com/storytold/texturecraft/pull/442), [pressure #399](https://github.com/storytold/texturecraft/pull/399) | +| Generators and smart masks | ~75% | TBD | November 16 estimate ~45%. 16 selectable generator kinds. Added 3D distance and gradient, UV border and diagnostic generators, grayscale conversion, rust runoff, per-kind controls, custom grunge, anchored micro-details and an enlarged preview. Validate control coverage, fidelity and performance on production assets | +| Materials and asset library | ~70% | TBD | November 16 estimate ~60%. Procedural and smart materials, user smart masks, refreshed previews and resource import with usage assignment. Fill properties support independent U/V tiling, filtering, wrapping, physical-size controls, warp and per-UV-tile projection. Validate physical scale across meshes and fill persistence in artist tasks | +| MaterialCraft `.mcmat` integration | v3 round trip passed with source builds | TBD after release-pair validation | Shared reader and the desktop MaterialCraft CLI bring in a published graph as a linked fill. Exposed controls and mesh-map inputs can drive re-cooks at the texture set resolution. v1/v2 imports require republishing. Saved baked maps can be used in the browser | +| Baking | ~75% | TBD | November 16 estimate ~60%. Bake Mode adds texture-set synchronization, automatic fitted cages, background high-poly loading and a settings-driven selected-map preview. CPU/GPU map fidelity, high/low pairs on real assets and resolution-stable wear still need validation | +| Viewport, shading and rendering | ~75% | TBD | November 16 estimate ~70%. PBR/IBL, displacement and CPU/GPU path tracing are available. Main improved camera controls and 2D navigation, including the UV tile grid, and highlights hovered texture sets. Matching material/display behavior, larger scenes and hardware ray tracing remain open | +| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces, profile metadata and Linear/ACES-filmic tone mapping are available. The project form displays disabled OpenColorIO settings. Configurable project and display transforms remain open | +| Texture and scene export | ~85% | TBD | November 16 estimate ~75%. Desktop texture export can write companion OpenPBR MaterialX and a textured USD asset. Template editing, subfolder names, per-map overrides and URP/USD presets expanded. Standard Surface and browser companion outputs remain open. Validate complex materials, UDIM and destination tools | | Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | -| Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | -| Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | +| Workspace, panels and preferences | ~75% | TBD | November 16 estimate ~65%. Menu and layout work, camera and 2D navigation updates, and full-name tooltips for truncated layer labels. Verify small windows, keyboard navigation, docking and restart persistence on the integrated desktop build | +| Automation | ~85% | TBD | November 16 estimate ~80%. Commands cover UV import, bake sync, fill and generator controls and export. The November 16 review exercised control and CLI paths. Recheck UI reachability and direct/bridged MCP coverage on current main | -Source checks matter here: [generator kinds](crates/core/src/layer.rs) number seven even though -their shared controls have grown; [polygon fill](crates/engine/src/fill_mode.rs) already includes -triangle, polygon, UV-island and mesh modes. Current [MaterialCraft import](crates/formats/src/mcmat.rs) -accepts v2 and recognizes the newer source archive layout. That is legacy compatibility, not -completion of the next `.mcmat` integration. The [upstream v3 proposal](https://github.com/storytold/materialcraft/issues/190) -describes MaterialX plus resources in equivalent folder/ZIP deliveries and excludes native source. -Its proposed exposed controls differ from re-cooking an embedded authoring graph. The final -supported subset, version policy and authoring/re-cook workflow must be agreed and tested; -the legacy promise must not be carried forward automatically. - -The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction -routes and acceptance checks: mask context/save/export actions; independent U/V tiling, -filtering/wrap, physical-size and warp/per-tile projections; -and configurable color-management settings. Generator depth and narrow-layout readability are -tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already -exist; older reports must not turn them into fresh missing-feature claims. +The [generator catalog](crates/core/src/layer.rs) defines 16 kinds, and +[polygon fill](crates/engine/src/fill_mode.rs) includes triangle, polygon, UV-island and mesh modes. +The [fill properties](crates/ui-egui/src/fill_panel.rs) and +[layer-panel tests](crates/ui-egui/tests/it/layers_panel.rs) supersede the November 16 missing-control +findings UI-01 and UI-03 through UI-06 in the [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows). +Use those findings' acceptance checks for a new live run. Color management (UI-11), generator +control and output validation (UI-12) and small-window work (UI-13) still need coverage. ### Evidence from this review | Check | Result and limit | |---|---| -| Baseline/build | Fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision | +| Baseline/build | On November 16, fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision | | Reference UI/functionality | On an original UV cube, pointer painting, paint/fill/black-mask creation and an empty generator slot worked; seven-map self-bake at 1024 px completed. Inspected fill/projection/scale menus, mask menu and export dialog. The “Read only” title did not prevent these edits; reference save/export and output equivalence remain unchecked | | TextureCraft UI tasks | Mouse/keyboard new project, 3D/2D strokes, Ctrl+Z/Y, F1/F2/F3, brush gesture, shelf search/drop, black mask, Position generator/global balance and effect duplication worked. UV rectangle fill wrote 88 tiles per channel and undo removed it | | Persistence | Native UI save of the deeper four-layer case followed by command reopen preserved layers, effects, 21 painted tiles per channel and ten baked maps. Earlier command save/reopen also passed. UI-only open-dialog completion was not established | @@ -156,16 +133,32 @@ exist; older reports must not turn them into fresh missing-feature claims. | Rework/upstream scope | Possible `.tcraft`/output-package reworks and incoming ArtCraft UI/shared-library work are planning inputs, not completed changes. The `.mcmat` v3 proposal and current legacy reader were reviewed; no future contract or current MaterialCraft producer/consumer pair was validated | | Not run | Full Rust tests, clippy, wasm, other operating systems, pen/display hardware matrix, large UDIM projects, long sessions, matched performance benchmarks and reference image-difference corpus | +The November 25 audit verified the following on main at `3c026860`. + +- **Masks, fills and generators.** Mask target menus and toggles, linked or independent tiling, filtering and wrap, physical-size controls, warp and per-tile projection, and 16 generator kinds with per-kind controls and previews. [Layer targeting #771](https://github.com/storytold/texturecraft/pull/771), [mask toggle #841](https://github.com/storytold/texturecraft/pull/841), [fill controls #762](https://github.com/storytold/texturecraft/pull/762), [generators #826](https://github.com/storytold/texturecraft/pull/826) +- **Bake and UV import.** Per-group bake settings sync, fitted cages, background import of high-poly meshes and a settings-driven map preview. Rebuilt project UVs survive reopen. [Bake Mode #799](https://github.com/storytold/texturecraft/pull/799), [UV import #748](https://github.com/storytold/texturecraft/pull/748), [reopen regression](crates/engine/tests/it/rebuilt_uv_layout.rs) +- **Interchange and shared formats.** Merged transitions to shared glTF/GLB, COLLADA, Alembic, USD and raster I/O, with project mapping in TextureCraft. Desktop texture-export dialogs gained MaterialX and USD options, and browser downloads use shared ZIP handling. [Migration tracker](https://github.com/storytold/craft-libs/issues/778), [MaterialX #784](https://github.com/storytold/texturecraft/pull/784), [USD asset #788](https://github.com/storytold/texturecraft/pull/788), [browser ZIP #792](https://github.com/storytold/texturecraft/pull/792) +- **Procedural material exchange.** MaterialCraft publishes a ZIP containing a selected SBS graph, reachable dependencies and resources. TextureCraft inspects and cooks it through the CLI. MaterialX is an optional bake output. [Producer #270](https://github.com/storytold/materialcraft/pull/270), [consumer #644](https://github.com/storytold/texturecraft/pull/644), [commands](docs/control-protocol.md#materialcraft-materials) +- **MaterialCraft compatibility test.** With MaterialCraft CLI 0.4.1 at `998d9d8f`, the Linux integration test published a selected graph, imported its v3 archive, supplied a mesh-map input and re-cooked at the target texture set size. CLI 0.4.1 at `f9174cb` failed earlier in the test when editable `.mcraft` import passed `--graph-path`. [Producer revision](https://github.com/storytold/materialcraft/commit/998d9d8f74454df047b6fb131f57b01d00a4983b), [integration test](crates/engine/tests/it/materialcraft_link.rs) +- **Desktop startup.** Interactive launches without a project now open an empty workspace. Control launches can still request the sample. Measure startup on the supported GPU matrix. [Startup #634](https://github.com/storytold/texturecraft/pull/634), [native entry point](apps/texturecraft/src/main.rs) +- **Release automation.** Isolated nightly launch profiles and a supervised Windows x86-64, Linux x86-64 and macOS arm64 workflow, with a separate signing ref. Scheduled publication remains disabled in this revision. Publication and installation still need end-to-end evidence. [Nightly preparation](docs/nightly-release-preparation.md), [producer](.github/workflows/nightly.yml) +- **Build checks.** `cargo xtask layers` passed for all 15 workspace packages. `cargo xtask wasm` passed for ten library crates and the web app. +- **Linux regression suites.** Locked release unit and integration tests for bake, compositing, formats, engine and headless UI reported 2,978 passing, zero failing and 101 ignored. The engine session suite included the hostile-input command sweep. The real MaterialCraft test was run separately with the CLI configured. +- **Packaging checks.** The local nightly workflow and policy suite passed 28 tests. The Linux tarball launcher and Arch package handoff tests passed using a stub application. + +Live desktop artist tasks, browser interaction, destination-tool fidelity, hardware coverage and +signed release installation remain outside the November 25 test evidence. + ## Languages The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at build time; missing entries fall back to English, and builds without catalogs offer English only. The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” -rows are not a current measurement. This audit ran an English build without external catalogs. +rows are not a current measurement. The November 16 live audit ran an English build without external catalogs. | Language | Code | UI strings | Status | |---|---|---|---| -| English | `en` | Source language | Exercised in this audit | +| English | `en` | Source language | Exercised in the November 16 live audit | | Simplified Chinese | `zh-Hans` | Not remeasured | Catalog/font dependent; native review pending | | Spanish | `es` | Not remeasured | Catalog dependent; native review pending | | Hindi | `hi` | No picker entry | Not offered | @@ -188,16 +181,16 @@ here. Open pull requests are not credited until merged into the assessed main re | Rank | Milestone | Estimate | |---|---|---| -| 1 | Reliable startup and project safety across the supported GPU/platform matrix; reproduce startup/GPU reports and exercise recovery/large saves ([#541](https://github.com/storytold/texturecraft/issues/541), [#489](https://github.com/storytold/texturecraft/issues/489)) | TBD after reproduction | +| 1 | Verify empty-workspace startup, reproduce the DirectX startup report on affected hardware, and exercise large saves and recovery across supported platforms. [#489](https://github.com/storytold/texturecraft/issues/489), [#541](https://github.com/storytold/texturecraft/issues/541) | TBD after reproduction | | 2 | Define `.tcraft` and output-package direction, scope any reworks, and establish versioning, migration and producer/consumer acceptance cases | Unestimated; design scope open | -| 3 | Plan/adopt the incoming ArtCraft UI refactor and shared-library changes; preserve command reachability and repeat UI/persistence/platform checks after adoption | TBD after upstream contracts and consumer scope | -| 4 | Bring in the completed MaterialCraft `.mcmat` contract: agree the supported MaterialX/resources/controls subset, implement the consumer through shared APIs and validate folder/archive outputs from named versions | Upstream-dependent; format unfinished | -| 5 | Bake fidelity and dependable smart-material wear: matched assets/settings at multiple resolutions, all ten maps, high/low pairs and documented differences ([#536](https://github.com/storytold/texturecraft/issues/536), [#538](https://github.com/storytold/texturecraft/issues/538)) | TBD after map corpus | -| 6 | Generator, anchor and property depth; finish the artist-facing control inventory while preserving existing shared controls ([#374](https://github.com/storytold/texturecraft/issues/374), [#389](https://github.com/storytold/texturecraft/issues/389), [#433](https://github.com/storytold/texturecraft/issues/433)) | TBD after control audit | +| 3 | Scope ArtCraft UI adoption and remaining shared-library cutovers. Consolidate the current multiple craft-libs pins in a dedicated update, preserve command reachability and rerun acceptance checks | TBD after adoption scope | +| 4 | Set the supported MaterialCraft and TextureCraft release pair and verify its installed CLI. Extend the source-build check to bundled resources, presets, resolution changes, reopen, missing CLI behavior and v1/v2 republish guidance | TBD after producer/consumer matrix | +| 5 | Measure bake fidelity and wear across resolutions, high/low pairs, all ten maps and CPU/GPU paths. Include automatic cages, name matching, settings sync and final output versus live preview | TBD after map corpus | +| 6 | Exercise the expanded generator, anchor and property controls on production assets. Finish uncovered inputs and workflows after rechecking [#374](https://github.com/storytold/texturecraft/issues/374) and [#433](https://github.com/storytold/texturecraft/issues/433) against main | TBD after control audit | | 7 | Brush/pen precision, feedback and discoverability; complete 3D/2D/trim-sheet tasks and set responsiveness budgets ([#545](https://github.com/storytold/texturecraft/issues/545), [#485](https://github.com/storytold/texturecraft/issues/485), [#306](https://github.com/storytold/texturecraft/issues/306)) | TBD after task tests | | 8 | Color-managed pipeline and destination checks for USD, glTF/GLB, MaterialX and texture maps, including UDIM, complex materials and the adopted output packages | TBD after consumer matrix | | 9 | Read-only `.spp` discovery: clean-room feasibility, recoverable data and unsupported-content reporting; convert into the adopted native format without changing the source | Unestimated; feasibility unknown | -| 10 | Release/platform regression checks, web polish, current translation coverage and native review; expand the original asset library | TBD after validation | +| 10 | Verify supervised nightly signing, install, co-installation and update on the target platforms. Repeat web and localization checks and expand the original asset library | TBD after validation | ### Dependencies and possible rework @@ -207,26 +200,24 @@ TextureCraft adoption. | Track | Current state | Completion / revalidation gate | |---|---|---| -| Native `.tcraft` | Current save/load works in the audit; schema/container may change | Decide the native contract and compatibility policy. For any adopted rework, check existing projects and conversion explicitly: layers, masks, effects, resources, painted tiles, UDIM layouts and baked data; retain bounded reads, atomic saves and recovery behavior | -| Output packages | Current individual exports work within the recorded scope; future package format/content/layout is not settled | Define affected artifacts, manifests, naming, resource references and versioning. Test package relocation, folder/archive delivery where applicable, color/normal/displacement metadata and real consumers; repeat install/update checks if distribution artifacts change | -| MaterialCraft `.mcmat` | Legacy v1/v2 support exists; [v3](https://github.com/storytold/materialcraft/issues/190) is unfinished upstream | Agree the published contract and supported MaterialX subset, folder/ZIP equivalence, resources and exposed inputs. Adopt it through shared libraries and test actual MaterialCraft output in TextureCraft, including unsupported versions/features. Do not assume native-source recovery or the legacy re-cook behavior | +| Native `.tcraft` | The live baseline covered save/load. Main persists rebuilt mesh UV layouts. The future container/schema remains open | Decide the contract and compatibility policy. For any adopted migration, check layers, masks, effects, resources, painted tiles, UV layouts and baked data. Exercise bounded reads, atomic saves and recovery | +| Output packages | Export templates now support subfolders, and desktop USD/MaterialX companions reference exported textures | Define affected artifacts, manifests, naming and versioning. Check package relocation, applicable folder/archive delivery, color/normal/displacement metadata and destination tools | +| MaterialCraft `.mcmat` | The [v3 procedural ZIP contract](https://github.com/storytold/materialcraft/issues/190) and shared reader have landed. TextureCraft uses the desktop CLI for cooking and rejects v1/v2 with republish guidance | Validate supported producer and consumer versions with bundled assets, exposed controls and mesh-map inputs. Test archived sources after moving the authoring files, and saved baked maps in the browser | | ArtCraft UI refactor | Incoming suite/UI work; shared palette/theme proposals such as [craft-libs #102](https://github.com/storytold/craft-libs/pull/102) and [#397](https://github.com/storytold/craft-libs/pull/397) are examples, not the whole refactor or an adoption claim | Scope TextureCraft's adapters/components and design changes. Keep document behavior command-driven; repeat the [UI task audit](docs/ui-parity.md), input/accessibility checks, screenshots and layout/preferences persistence tests against the adopted design | -| Shared libraries | Several shared crates are already pinned in [Cargo.toml](Cargo.toml); [format migration work](https://github.com/storytold/craft-libs/issues/778) continues | Use reviewed public APIs and keep app-specific mapping/policy local. Each adoption needs consumer integration plus compatibility, security-limit, layering, wasm and regression checks; a library change alone does not complete the app's work | +| Shared libraries | Shared format adoption now includes glTF/GLB, COLLADA, Alembic, USD, runtime raster codecs and ZIP. [Cargo.toml](Cargo.toml) declares direct dependencies at six craft-libs revisions | Consolidate the pins under the repository's single-revision convention and rerun consumer compatibility, format limit, layering, wasm and regression checks. [Migration tracker](https://github.com/storytold/craft-libs/issues/778) | ### Current focus -Keep the current functional baseline while establishing project-safety and bake-fidelity checks. -Scope `.tcraft`/output-package changes and coordinate ArtCraft UI/shared-library adoption alongside -that work, so feature work budgets include possible migration and revalidation. Bring `.mcmat` -forward against the finished upstream contract rather than treating the legacy reader as completion. -Run `.spp` feasibility separately. Hardware ray tracing is a later enhancement; beta depends on -the scoped acceptance/integration gates above. [Release validation](docs/releasing.md) continues -for existing releases; there is no outstanding “first release” gate. +Establish project-recovery, startup and bake-fidelity checks on representative assets. Scope +`.tcraft` and output-package decisions and ArtCraft UI adoption alongside those checks. Repeat +the passing source-build `.mcmat` handoff with supported release builds. Read-only `.spp` remains a separate +feasibility track. Hardware ray tracing for Rendering mode remains a later enhancement. ## Progress log | Date | Entry | |---|---| +| 2026-11-25 | Audited main at `3c026860`. Recorded the expanded generator catalog, mask and fill controls, Bake Mode, UV rebuilds, export migrations, the v3 material handoff and supervised nightlies. Raised estimated breadth from ~80% to ~90% and weighted readiness from ~60% to ~68% | | 2026-11-16 | Added possible native/output-package reworks, unfinished MaterialCraft `.mcmat` integration and incoming ArtCraft UI/shared-library work as explicit roadmap tracks. Current audit scores stay tied to the tested revision; migration scope and effort remain unestimated | | 2026-11-16 | Deeper UI/functionality audit added in [docs/ui-parity.md](docs/ui-parity.md): twenty check groups, specific missing controls, reference editing/self-bake, UI export/save, analytic high/low transfer and UDIM packing. Overall percentages remain provisional estimates | | 2026-11-16 | Approximate live review against main `62b2b13` and reference 12.2.0. Basic edit/save/reopen, GPU bake and interchange smoke checks passed. Rebaselined reporting to ~80% breadth / ~60% readiness and recorded validation limits | @@ -238,6 +229,7 @@ for existing releases; there is no outstanding “first release” gate. | Date | Change | Summary | |---|---|---| +| 2026-11-25 | major | Updated implementation status and provisional readiness for current main. Retained the November 16 scores for comparison and kept the beta acceptance gates | | 2026-11-16 | major | Added dependency/rework scope and adoption gates; distinguished legacy `.mcmat` support from the unfinished MaterialX-based proposal; expanded upcoming work without crediting unlanded integrations | | 2026-11-16 | major | Expanded live UI tasks and output validation; added a separate UI gap inventory with acceptance checks; distinguished UI, mixed and command evidence and CPU/GPU bake paths | | 2026-11-16 | major | Adopted headline/audience/dimension/feature/language/upcoming tables; added main-revision evidence and uncertainty, read-only `.spp` scope, current release status and acceptance gates; removed the unsupported six-hour remainder | diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index c38b323a..80069d9d 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -280,21 +280,39 @@ fn run(a: &Args) -> R { } } -fn batch(a: &Args) -> R { - let path = a.pos(0, "")?; - let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?; - let script: Value = serde_json::from_str(&text).map_err(|e| format!("{path} is not JSON: {e}"))?; +fn batch(args: &Args) -> R { + let path = args.pos(0, "")?; + let script: Value = { + let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?; + serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))? + }; + let steps = script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?; - let field = |k: &str| script.get(k).and_then(Value::as_str); - let mut h = open(field("open").unwrap_or("builtin:material_ball"), None)?; - let reply = h.batch(steps); + let path_field = |field: &str| -> Result, String> { + match script.get(field) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) => Ok(Some(path.as_str())), + Some(_) => Err(format!("the script's `{field}` field must be a string")), + } + }; + let input = path_field("open")?.unwrap_or("builtin:material_ball"); + let output = path_field("save")?; + + let mut headless = open(input, None)?; + let reply = headless.batch(steps); print_json(&reply)?; - if let Some(f) = reply.get("failed").filter(|f| !f.is_null()) { - return Err(format!("step {} (`{}`) failed: {}", f["index"], f["id"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default())); + if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { + return Err(format!( + "step {} (`{}`) failed: {}", + failure["index"], + failure["id"].as_str().unwrap_or_default(), + failure["error"].as_str().unwrap_or_default() + )); } - match field("save") { - Some(out) => save(&mut h, out), + + match output { + Some(output_path) => save(&mut headless, output_path), None => Ok(()), } } diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index ce209c3e..6bef0017 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -95,6 +95,38 @@ fn new_info_run_bake_export_batch() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn batch_rejects_non_string_paths() { + let directory = tmp("batch-paths"); + let script = directory.join("script.json"); + let unexpected_project = directory.join("unexpected.tcraft"); + let invalid_open = serde_json::json!({"steps": [], "open": false, "save": p(&unexpected_project)}); + let invalid_save = serde_json::json!({ + "open": "builtin:cube", + "save": [p(&unexpected_project)], + "steps": [{"id": "file.saveCopy", "params": {"path": p(&unexpected_project)}}] + }); + + for (body, field) in [(invalid_open, "open"), (invalid_save, "save")] { + std::fs::write(&script, body.to_string()).unwrap(); + let output = cli(&["batch", p(&script)]); + + let error = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{field}: {error}"); + assert!(error.contains(&format!("`{field}` field must be a string")), "{error}"); + assert!(output.stdout.is_empty()); + assert!(!unexpected_project.exists()); + } + + std::fs::write(&script, r#"{"steps":[],"open":null,"save":null}"#).unwrap(); + let reply = json(&["batch", p(&script)]); + + assert_eq!(reply["completed"], 0); + assert!(reply["failed"].is_null()); + + let _ = std::fs::remove_dir_all(&directory); +} + #[test] fn info_on_a_mesh_reports_uvs() { let d = tmp("mesh"); diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index cb697e0b..99dfa223 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -58,6 +58,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { canvas, options, Box::new(|cc| { + texturecraft_ui_egui::framework::install_headless(&cc.egui_ctx); let mut app = TextureCraftApp::new(cc, session); if let Some(rs) = &cc.wgpu_render_state { let backend = rs.adapter.get_info().backend; diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 349b9275..4d48c210 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -203,8 +203,8 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std: entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() } -/// The app with the window chrome that needs the native window: the Windows borderless guard, and -/// on macOS the traffic lights and AppKit's `movable` flag. +/// The app with the window chrome that needs the native window: the Windows borderless guard, and the native window +/// the framework runtime answers the hit test of. struct Shell { app: TextureCraftApp, window_frame: Option, @@ -212,8 +212,6 @@ struct Shell { /// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before /// `eframe::run_native` returns, so the Nightly session record is finished here, not there. exit_hook: Option>, - #[cfg(target_os = "macos")] - movable: Option, } impl eframe::App for Shell { @@ -240,9 +238,8 @@ impl eframe::App for Shell { } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + texturecraft_ui_egui::framework::before_ui(ui.ctx(), &*frame); self.app.ui(ui, frame); - #[cfg(target_os = "macos")] - texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); } fn on_exit(&mut self) { @@ -262,13 +259,22 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) } -/// A refused Nightly start explains itself in a dialog where there is a desktop to show one. +/// Whether a refusal may also open a native message box. Standard error always carries the reason; +/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert +/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in +/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26). +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +/// A refused Nightly start explains itself in a dialog where the desktop shows one without the +/// app's run loop (Windows, X11/Wayland); macOS gets the standard-error line only. fn report_launch_profile_error(error: &str) { eprintln!("texturecraft: {error}"); let desktop_session = cfg!(windows) || cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); - if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { if let Err(error) = initialize_nightly_process_identity() { eprintln!("texturecraft: {error}"); return; @@ -387,7 +393,8 @@ fn main() { prefs.apply_work_threads(); prefs.apply_resource_limits(); let session = initial_session(&args); - let title_bar = TitleBar::decide(prefs.system_title_bar); + let frame_decision = TitleBar::decide(prefs.system_title_bar); + let title_bar = TitleBar::of(&frame_decision.frame); let mut viewport = egui::ViewportBuilder::default() .with_app_id(os_window::app_id()) .with_title(os_window::name()) @@ -396,7 +403,7 @@ fn main() { if let Some(i) = icon() { viewport = viewport.with_icon(i); } - let viewport = title_bar.viewport(viewport); + let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { fatal(&e.to_string(), true); @@ -443,7 +450,8 @@ fn main() { if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } - let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); + texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?; + let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; app.set_startup_update_check(checks_for_updates_at_start(control)); @@ -459,13 +467,7 @@ fn main() { }); notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed); } - Ok(Box::new(Shell { - app, - window_frame, - exit_hook: Some(Box::new(finish_at_exit)), - #[cfg(target_os = "macos")] - movable: None, - })) + Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) })) }), ); // A controlled return, including a handled startup error. On macOS a window already finished in @@ -635,13 +637,10 @@ mod tests { /// Points within which a put-back lands on the press point (the system rounds it to whole pixels) const PUT_BACK_REACH: f32 = 1.0; - /// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window + /// One frame of the window: the system's events go through the window's raw input hook (the harness runs it before + /// every pass, as eframe does); returns what the app asked of the window fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec) -> Vec { - let ctx = harness.ctx.clone(); - let mut raw = harness.input_mut().clone(); - raw.events.extend(events); - eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw); - *harness.input_mut() = raw; + harness.input_mut().events.extend(events); harness.step(); harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default() } @@ -650,14 +649,10 @@ mod tests { #[test] fn the_window_holds_the_pointer_while_the_preview_square_is_held() { let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); - let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1])); - let mut harness = builder.build_eframe(|cc| Shell { - app: TextureCraftApp::new(cc, session), - window_frame: None, - exit_hook: None, - #[cfg(target_os = "macos")] - movable: None, - }); + let builder = egui_kittest::Harness::builder() + .with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1])) + .with_context_setup(texturecraft_ui_egui::framework::install_headless); + let mut harness = builder.build_eframe(|cc| Shell { app: TextureCraftApp::new(cc, session), window_frame: None, exit_hook: None }); harness.run_steps(4); let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone(); harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap(); @@ -681,3 +676,17 @@ mod tests { assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}"); } } + +#[cfg(test)] +mod refusal_dialog_tests { + use super::refusal_dialog; + use crate::build_flavor::BuildFlavor; + + #[test] + fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box"); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box"); + } +} diff --git a/assets/samples/Material Ball.tcraft b/assets/samples/Material Ball.tcraft new file mode 100644 index 00000000..915697f3 Binary files /dev/null and b/assets/samples/Material Ball.tcraft differ diff --git a/assets/samples/README.md b/assets/samples/README.md new file mode 100644 index 00000000..bc366dd4 --- /dev/null +++ b/assets/samples/README.md @@ -0,0 +1,9 @@ +# Sample projects + +Projects that ship with desktop TextureCraft and are offered by File > Open Sample Project. + +- `Material Ball.tcraft`: the material ball with smart materials on both texture sets, generated by + TextureCraft's own `sample_session` (1024 px textures, mesh maps baked at 256 px to keep the file small). + +The app embeds these files and copies any missing sample into the `Samples` folder under the data +folder when the entry is used. A file that is already there is never overwritten. diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index db74dc2a..4212d787 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -9,12 +9,15 @@ use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, Conte pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; -/// Project file format. 3: bent normal maps are in tangent space (older files hold world-space ones). -pub const FORMAT_VERSION: u32 = 3; +/// Latest project file format that TextureCraft can read. +pub const FORMAT_VERSION: u32 = REBUILT_MESH_UVS_VERSION; /// First format whose baked bent normal maps are in tangent space pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3; +/// First format that can reopen a project using rebuilt mesh UVs. +pub const REBUILT_MESH_UVS_VERSION: u32 = 4; + /// Most colour swatches a project keeps pub const MAX_SWATCHES: usize = 64; @@ -429,6 +432,10 @@ pub struct Project { /// it, so parts the file leaves unnamed get the same name (from it) as on import. #[serde(default, skip_serializing_if = "String::is_empty")] pub mesh_file: String, + /// The mesh UVs were rebuilt on import. The project file keeps the generated layout for + /// reopening; reimporting the mesh from a file rebuilds them again. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub mesh_rebuild_uvs: bool, /// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads /// it again from there, so edits made to the file since are picked up. Empty when unknown /// (built-in meshes, web imports, projects saved before it was kept). @@ -450,10 +457,11 @@ pub struct Project { impl Project { pub fn new(name: impl Into, mesh: impl Into) -> Project { Project { - format_version: FORMAT_VERSION, + format_version: TANGENT_BENT_NORMAL_VERSION, name: name.into(), mesh: mesh.into(), mesh_file: String::new(), + mesh_rebuild_uvs: false, mesh_path: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), @@ -465,6 +473,11 @@ impl Project { } } + /// The on-disk version that preserves the project's UV layout when read back. + pub fn save_format_version(&self) -> u32 { + if self.mesh_rebuild_uvs { self.format_version.max(REBUILT_MESH_UVS_VERSION) } else { self.format_version } + } + pub fn alloc_id(&mut self) -> LayerId { let id = LayerId(self.next_id); self.next_id = self.next_id.saturating_add(1); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 3a32bfa9..f253e1e6 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -93,6 +93,14 @@ pub fn set_gpu_raytracing(enabled: bool) { /// The tracer a bake starting now uses: the installed one while GPU raytracing is on, else none (the CPU) fn chosen_tracer(installed: Option<&Arc>, enabled: bool) -> Option> { + // The coverage build bakes on the CPU, the fallback every GPU failure takes anyway. Its tests run on + // a headless runner, and the bake's GPU device is created on a worker thread there: tearing that + // GL context down crashes the test process at exit (a wgpu-hal GLES `BadDisplay` panic, or a + // SIGSEGV in the driver), which took a different test down on every run. The compute shaders are + // never line-covered, so nothing is lost. + if cfg!(coverage) { + return None; + } installed.filter(|_| enabled).cloned() } @@ -917,7 +925,9 @@ mod gpu_raytracing_tests { fn bakes_use_the_installed_gpu_tracer_only_while_gpu_raytracing_is_on() { let installed: Arc = Arc::new(NamedTracer); - assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), Some("gpu".to_string())); + // A coverage build keeps every bake on the CPU: its headless runner has no GPU to bake on + let gpu = (!cfg!(coverage)).then(|| "gpu".to_string()); + assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), gpu, "on casts the rays on the GPU"); assert!(chosen_tracer(Some(&installed), false).is_none(), "off keeps the rays on the CPU"); assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU"); } diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index e79e6d34..0a4f4411 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Select camera", [], None, - "{index? | name?} (neither, or name \"Default camera\": the default camera framing the mesh)", + "{index? | name?} (an omitted or null index and an omitted, null, or \"Default camera\" name frame the mesh)", always, select ), @@ -226,24 +226,29 @@ fn add(s: &mut Session, p: &Value) -> Result { }) } -fn select(s: &mut Session, p: &Value) -> Result { - if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) { - // The default camera: fov and projection from the display settings, framing the mesh - s.selected_camera_name = None; - s.camera.fov = s.doc.project.display.fov; - s.camera.ortho = false; - return crate::execute(s, "viewport.frame", &Value::Null); +fn select(session: &mut Session, params: &Value) -> Result { + if !params.is_object() && !params.is_null() { + return Err(bad("camera.select", "expected a parameter object or null")); } - let i = which(s, "camera.select", p)?; - if let Some(camera) = s.doc.project.cameras.get(i) { - // A saved view is clamped against the whole mesh, not against a part framed with F - s.camera.scene_radius = s.mesh.radius(); - apply(&mut s.camera, camera); - s.selected_camera_name = Some(camera.name.clone()); + let default_name = params.get("name").is_none_or(|name| name.is_null() || name.as_str() == Some(DEFAULT_CAMERA)); + if params.get("index").is_none_or(Value::is_null) && default_name { + session.selected_camera_name = None; + session.camera.fov = session.doc.project.display.fov; + session.camera.ortho = false; + return crate::execute(session, "viewport.frame", &Value::Null); } - s.revision = s.revision.wrapping_add(1); - Ok(crate::view_cmds::camera_json(s)) + + let camera_index = which(session, "camera.select", params)?; + if let Some(camera) = session.doc.project.cameras.get(camera_index) { + // Use the whole mesh radius even after framing a texture set + session.camera.scene_radius = session.mesh.radius(); + apply(&mut session.camera, camera); + session.selected_camera_name = Some(camera.name.clone()); + } + + session.revision = session.revision.wrapping_add(1); + Ok(crate::view_cmds::camera_json(session)) } /// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90 @@ -453,6 +458,49 @@ mod tests { assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable"); } + #[test] + fn malformed_camera_selectors_leave_the_current_view_intact() { + let mut session = session(); + execute(&mut session, "camera.set", &json!({"yaw": 30, "target": [1, 2, 3], "fov": 25, "ortho": true})).unwrap(); + let saved_view = session.camera; + execute(&mut session, "camera.add", &json!({"name": "Side"})).unwrap(); + execute(&mut session, "camera.orbit", &json!({"dx": 15})).unwrap(); + + execute(&mut session, "camera.select", &json!({"index": 0, "name": DEFAULT_CAMERA})).unwrap(); + + assert_eq!(session.camera, saved_view); + assert_eq!(session.selected_camera_name.as_deref(), Some("Side")); + + let revision = session.revision; + for params in [ + json!({"index": -1}), + json!({"index": -0.5}), + json!({"index": "0"}), + json!({"name": false}), + json!({"index": -1, "name": DEFAULT_CAMERA}), + json!([{"index": 0}]), + json!("Side"), + ] { + let result = execute(&mut session, "camera.select", ¶ms); + + assert!(matches!(result, Err(crate::EngineError::BadParams { .. })), "{params}: {result:?}"); + assert_eq!(session.camera, saved_view); + assert_eq!(session.selected_camera_name.as_deref(), Some("Side")); + assert_eq!(session.revision, revision); + } + + for params in [Value::Null, json!({"index": null, "name": null}), json!({"name": DEFAULT_CAMERA})] { + execute(&mut session, "camera.select", &json!({"index": null, "name": "Side"})).unwrap(); + assert_eq!(session.camera, saved_view); + + execute(&mut session, "camera.select", ¶ms).unwrap(); + + assert_eq!(session.selected_camera_name, None); + assert!(!session.camera.ortho); + assert_eq!(session.camera.fov, session.doc.project.display.fov); + } + } + #[test] fn number_shortcuts_go_to_the_first_nine_cameras() { let mut s = session(); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ae004bcf..97573916 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -12,7 +12,9 @@ use serde_json::{Value, json}; use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::PlannedFile; +use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile}; +use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; @@ -29,7 +31,7 @@ pub fn specs() -> Vec { "New project from a mesh file", [], None, - "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", + "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), rebuildUvs?: bool (default false: auto-unwrap where needed), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", always, new_from_mesh ), @@ -113,10 +115,13 @@ fn leaf_of(name: &str) -> String { } /// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported -/// with, so its unnamed parts keep their names (and the geometry masks that use them). -fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result { - let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh"); - texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe) +/// with, so its unnamed parts keep their names (and the geometry masks that use them). A saved +/// UV layout replaces the file's UVs and the automatic unwrap. +fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Option<&[Vec2]>) -> Result { + let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|stem| stem.to_str()).filter(|stem| !stem.is_empty()).unwrap_or("mesh"); + let file_name = format!("{stem}.{ext}"); + + import_mesh_geometry(&file_name, bytes, saved_layout.map_or(MeshUvSource::FromFile, MeshUvSource::Saved)).map_err(fe) } impl Session { @@ -175,11 +180,16 @@ impl Session { /// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]). pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option) -> Result { - Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles) + Self::from_mesh_bytes_with_uvs(file_name, bytes, resolution, name, uv_tiles, false) } - fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option) -> Result { - let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?; + /// Create a project with an explicit choice to rebuild the imported mesh's UVs. + pub fn from_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option, rebuild_uvs: bool) -> Result { + Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles, rebuild_uvs) + } + + fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option, rebuild_uvs: bool) -> Result { + let imported = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(file_name, &bytes, rebuild_uvs).map_err(fe)?; let extension = ext_of(file_name); let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?; @@ -188,6 +198,7 @@ impl Session { source.shrink_to_fit(); session.mesh_source = Some((extension, source)); session.doc.project.mesh_file = leaf_of(file_name); + session.doc.project.mesh_rebuild_uvs = rebuild_uvs; session.doc.project.cameras = imported.cameras; session.log.warnings("Importer", imported.report.warnings); @@ -211,29 +222,39 @@ impl Session { Session::from_project_file(pf) } - pub fn from_project_file(pf: ProjectFile) -> Result { - let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) { + pub fn from_project_file(project_file: ProjectFile) -> Result { + project_file.validate_mesh_uvs().map_err(fe)?; + + let mesh = match (&project_file.mesh, project_file.project.mesh.strip_prefix("builtin:")) { (_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?, - (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, + (Some((ext, bytes)), None) => read_stored_mesh(&project_file.project, ext, bytes, project_file.mesh_uvs.as_deref())?, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; - check_materials(&pf.project, &mesh)?; - let source = pf.mesh.clone(); - let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); + // Mesh construction consumed the layout data, so release it before building session caches + drop(project_file.mesh_uvs); + check_materials(&project_file.project, &mesh)?; + let resources = project_file.resources.into_iter().map(|(name, bytes)| (name, Arc::new(bytes))).collect(); - let mut s = Session::new( - Document { bake_meshes: Default::default(), bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, + let mut session = Session::new( + Document { + bake_meshes: Default::default(), + bake_paint: Default::default(), + project: project_file.project, + pixels: project_file.pixels, + baked: project_file.baked, + resources, + }, mesh, - source, + project_file.mesh, )?; - s.sync_images(); - s.load_bake_meshes(pf.high_poly, pf.cage); - s.load_bake_paint(pf.bake_paint); - s.log.warnings("Project", pf.warnings); + session.sync_images(); + session.load_bake_meshes(project_file.high_poly, project_file.cage); + session.load_bake_paint(project_file.bake_paint); + session.log.warnings("Project", project_file.warnings); - Ok(s) + Ok(session) } /// The project with independently owned resource bytes. @@ -247,6 +268,11 @@ impl Session { self.project_with_resources(self.doc.resources.clone()) } + /// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper. + fn saved_uv_layout(&self) -> Option> { + (self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source)) + } + fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile { let mut pixels = self.doc.pixels.clone(); @@ -265,11 +291,15 @@ impl Session { pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); let (high_poly, cage) = self.saved_bake_meshes(); + let mut project = self.doc.project.clone(); + project.format_version = project.save_format_version(); + ProjectFile { - project: self.doc.project.clone(), + project, pixels, baked: self.doc.baked.clone(), mesh: self.mesh_source.clone(), + mesh_uvs: self.saved_uv_layout(), high_poly, cage, bake_paint: self.saved_bake_paint(), @@ -621,7 +651,7 @@ mod native { #[cfg(not(target_arch = "wasm32"))] pub use native::{absolute, open_path, read_mesh}; -/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the +/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] fn new_from_mesh(session: &mut Session, params: &Value) -> Result { @@ -632,9 +662,11 @@ fn new_from_mesh(session: &mut Session, params: &Value) -> Result { let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX); let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); let uv_tiles = crate::commands::boolp(params, "uvTiles"); + let rebuild_uvs = crate::commands::boolp(params, "rebuildUvs").unwrap_or(false); let mesh_file = native::read_mesh("file.new", path)?; - let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?; + let mut next = + Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles, rebuild_uvs)?; next.doc.project.mesh_path = native::absolute(path); next.log.warnings("Importer", mesh_file.warnings); if crate::commands::boolp(params, "importCameras") == Some(false) { @@ -697,9 +729,11 @@ fn reimport(s: &mut Session, p: &Value) -> Result { fn change_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.changeMesh")?; let file = native::read_mesh("file.changeMesh", path)?; - let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; - // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + let reply = s.replace_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true), false)?; + + // Keep following the original path if the swap fails s.doc.project.mesh_path = native::absolute(path); + Ok(reply) } @@ -710,16 +744,24 @@ impl Session { Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) } - /// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}` + /// Replace the mesh with `file` or re-read the project's own copy. + /// With `preserve_strokes`, painted pixels follow the surface. The reply includes + /// `preserved` when preservation was requested. pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { - let (mesh, source, warnings, mesh_file) = match file { - Some(f) => { - let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; - (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) + self.replace_mesh(file, preserve_strokes, self.doc.project.mesh_rebuild_uvs) + } + + fn replace_mesh(&mut self, file: Option, preserve_strokes: bool, rebuild_uvs: bool) -> Result { + let (mesh, replacement_source, warnings, mesh_file) = match file { + Some(file) => { + let mesh = import_mesh_geometry(&file.name, &file.bytes, MeshUvSource::from_rebuild_setting(rebuild_uvs)).map_err(fe)?; + (mesh, Some((ext_of(&file.name), file.bytes)), file.warnings, leaf_of(&file.name)) } None => match &self.mesh_source { Some((ext, bytes)) => { - (read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone()) + let layout = self.saved_uv_layout(); + let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?; + (mesh, None, Vec::new(), self.doc.project.mesh_file.clone()) } None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, @@ -727,12 +769,13 @@ impl Session { check_materials(&self.doc.project, &mesh)?; let mut doc = self.doc.clone(); - if let Some((ext, _)) = &source { + if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; + doc.project.mesh_rebuild_uvs = rebuild_uvs; } - let mut next = Session::new(doc, mesh, source)?; + let mut next = Session::new(doc, mesh, replacement_source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); @@ -743,6 +786,7 @@ impl Session { next.doc.bake_meshes.cage = None; next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed"); } + if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode"); } @@ -750,6 +794,12 @@ impl Session { next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); + + // Keep the stored source in the current session until reimport succeeds + if next.mesh_source.is_none() { + next.mesh_source = self.mesh_source.take(); + } + self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4c31402b..b5b1f535 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { has_layer, add_color_mask ), - cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?}", has_layer, toggle), + cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?} — defaults to the selected layer", always, toggle), cmd!("mask.invertBackground", "Invert mask background", ["Layers", "Mask"], None, "{layer?}", has_layer, invert_background), cmd!("mask.invert", "Invert mask", ["Layers", "Mask"], None, "{layer?}", has_layer, invert), cmd!("mask.clear", "Clear mask", ["Layers", "Mask"], None, "{layer?}", has_layer, clear), @@ -132,6 +132,7 @@ pub fn specs() -> Vec { fn with_mask(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut Session, LayerId) -> Result) -> Result { let id = layer_param(s, cmd, p)?; + s.edit(label, |s| f(s, id)) } @@ -174,13 +175,14 @@ fn mask_of(s: &mut Session, id: LayerId) -> Result<&mut Mask> { l.mask.as_mut().ok_or_else(|| EngineError::Other(format!("\"{name}\" has no mask"))) } -fn toggle(s: &mut Session, p: &Value) -> Result { - let on = with_mask(s, p, "mask.toggle", "Toggle mask", |s, id| { - let m = mask_of(s, id)?; - m.enabled = boolp(p, "enabled").unwrap_or(!m.enabled); - Ok(m.enabled) +fn toggle(session: &mut Session, params: &Value) -> Result { + let enabled = with_mask(session, params, "mask.toggle", "Toggle mask", |session, layer| { + let mask = mask_of(session, layer)?; + mask.enabled = boolp(params, "enabled").unwrap_or(!mask.enabled); + Ok(mask.enabled) })?; - Ok(json!({ "enabled": on })) + + Ok(json!({ "enabled": enabled })) } fn invert_background(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index ac0b8636..d8b1dcef 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -104,6 +104,7 @@ impl Session { pixels: mini.pixels, baked: BTreeMap::new(), mesh: None, + mesh_uvs: None, high_poly: Vec::new(), cage: None, bake_paint: BTreeMap::new(), diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index eeaea8bd..9395ae2d 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -3,12 +3,13 @@ //! are mirrored as `.json` files in a library folder (see [`Session::load_export_presets`]). use std::borrow::Cow; +use std::collections::HashSet; use serde_json::{Value, json}; use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem}; use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json}; -use crate::commands::{CommandSpec, always, bad, boolp, strp}; +use crate::commands::{CommandSpec, always, bad, strp}; use crate::{Result, Session, cmd}; /// Most user presets kept (and read from the library folder). @@ -95,16 +96,18 @@ impl UserPresets { Ok(()) } - /// `name`, or `name 2`, `name 3`… (shortened to fit) when taken. - fn unique_name(&self, name: &str, skip: Option) -> String { + /// The first available name, adding a numbered suffix and shortening the base to fit. + fn unique_name(&self, name: &str, skip: Option) -> Option { + // File keys also cover case-insensitive name matches + let file_keys: HashSet<_> = self.list.iter().enumerate().filter(|(index, _)| Some(*index) != skip).map(|(_, preset)| file_key(&preset.name)).collect(); + (1..=MAX_USER_PRESETS + 1) - .map(|k| { - let suffix = if k == 1 { String::new() } else { format!(" {k}") }; + .map(|number| { + let suffix = if number == 1 { String::new() } else { format!(" {number}") }; let base: String = name.chars().take(MAX_PRESET_NAME.saturating_sub(suffix.len())).collect(); format!("{}{suffix}", base.trim_end()) }) - .find(|n| !self.taken(n, skip)) - .unwrap_or_else(|| name.to_string()) + .find(|candidate| !file_keys.contains(&file_key(candidate)) && builtin_preset(candidate).is_none()) } #[cfg(not(target_arch = "wasm32"))] @@ -207,32 +210,50 @@ pub fn preset_param(v: &Value, cmd: &str) -> Result { Ok(preset) } -fn save(s: &mut Session, p: &Value) -> Result { +fn save(session: &mut Session, params: &Value) -> Result { const CMD: &str = "export.preset.save"; - let mut preset = preset_param(p.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?, CMD)?; - let lib = &mut s.export_presets; - let renamed = match strp(p, "rename") { - Some(old) => Some(lib.find(old).ok_or_else(|| bad(CMD, format!("no user export preset `{old}` to rename")))?), - None => None, + let preset_value = params.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?; + let rename_from = match params.get("rename") { + None | Some(Value::Null) => None, + Some(Value::String(name)) => Some(name), + Some(_) => return Err(bad(CMD, "`rename` must be a preset name")), }; - let target = renamed.or_else(|| lib.find(&preset.name)); - if boolp(p, "unique") == Some(true) { - preset.name = lib.unique_name(&preset.name, renamed); - } else if lib.taken(&preset.name, target) { + let unique = match params.get("unique") { + None | Some(Value::Null) => false, + Some(Value::Bool(unique)) => *unique, + Some(_) => return Err(bad(CMD, "`unique` must be a boolean")), + }; + + let mut preset = preset_param(preset_value, CMD)?; + let library = &mut session.export_presets; + let target_index = match rename_from { + Some(old_name) => Some(library.find(old_name).ok_or_else(|| bad(CMD, format!("no user export preset `{old_name}` to rename")))?), + None if unique => None, + None => library.find(&preset.name), + }; + + if !unique && library.taken(&preset.name, target_index) { return Err(bad(CMD, format!("an export preset named \"{}\" exists already (built-in presets are read-only)", preset.name))); } - let target = renamed.or_else(|| lib.find(&preset.name)); - if target.is_none() && lib.list.len() >= MAX_USER_PRESETS { + + if target_index.is_none() && library.list.len() >= MAX_USER_PRESETS { return Err(bad(CMD, format!("at most {MAX_USER_PRESETS} user export presets"))); } - let previous = target.and_then(|i| lib.list.get(i)).map(|old| old.name.clone()); - lib.write(&preset, previous.as_deref()).map_err(|e| bad(CMD, e))?; - let name = preset.name.clone(); - match target.and_then(|i| lib.list.get_mut(i)) { - Some(slot) => *slot = preset, - None => lib.list.push(preset), + + if unique { + preset.name = library.unique_name(&preset.name, target_index).ok_or_else(|| bad(CMD, "no unique export preset name is available"))?; } - Ok(json!({ "name": name })) + + let previous_name = target_index.and_then(|index| library.list.get(index)).map(|previous| previous.name.as_str()); + library.write(&preset, previous_name).map_err(|error| bad(CMD, error))?; + + let response = json!({ "name": preset.name }); + match target_index.and_then(|index| library.list.get_mut(index)) { + Some(slot) => *slot = preset, + None => library.list.push(preset), + } + + Ok(response) } fn remove(s: &mut Session, p: &Value) -> Result { @@ -275,40 +296,113 @@ mod tests { assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset(" Mine ")})).unwrap()["name"], "Mine"); let got = run(&mut s, "export.preset.get", json!({"name": "mine"})).unwrap(); assert_eq!(got, preset("Mine"), "round trip through the command"); - // Saving the same name replaces; a clash with a built-in or with `unique` renames. + + // A same-name save replaces the current preset let mut edited = preset("Mine"); edited["maps"][0]["bit_depth"] = json!(16); run(&mut s, "export.preset.save", json!({"preset": edited})).unwrap(); assert_eq!(s.export_presets.list.len(), 1); assert_eq!(s.export_preset("Mine").unwrap().maps[0].bit_depth, 16); + + // Built-ins need a unique name for a user copy assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps")})).is_err()); assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps"), "unique": true})).unwrap()["name"], "Separate maps 2"); assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("mine"), "unique": true})).unwrap()["name"], "mine 2"); - // Renaming onto another preset fails; onto a free name keeps the position. + + // Renaming to a free name keeps the library position assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Mine"), "rename": "mine 2"})).is_err()); run(&mut s, "export.preset.save", json!({"preset": preset("Renamed"), "rename": "Mine"})).unwrap(); let names: Vec<&str> = s.export_presets.list.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["Renamed", "Separate maps 2", "mine 2"]); + let listed = run(&mut s, "export.presets", json!({})).unwrap(); assert!(listed.as_array().unwrap().iter().any(|p| p["name"] == "Renamed" && p["builtin"] == false)); assert!(run(&mut s, "export.preset.remove", json!({"name": "Separate maps"})).is_err(), "built-ins are read-only"); run(&mut s, "export.preset.remove", json!({"name": "renamed"})).unwrap(); assert!(run(&mut s, "export.preset.get", json!({"name": "Renamed"})).is_err()); - // Presets survive opening another project. + + // Presets survive opening another project run(&mut s, "project.new", json!({"resolution": 128})).unwrap(); assert_eq!(s.export_presets.list.len(), 2); } + #[test] + fn malformed_save_options_do_not_replace_a_user_preset() { + let mut session = session(); + let original = preset("Mine"); + run(&mut session, "export.preset.save", json!({"preset": original})).unwrap(); + let mut replacement = original.clone(); + replacement["maps"][0]["bit_depth"] = json!(16); + + for (key, invalid) in [("unique", json!("true")), ("rename", json!(7))] { + let mut params = json!({"preset": replacement}); + params[key] = invalid; + + let error = run(&mut session, "export.preset.save", params).unwrap_err(); + + assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), original); + assert!(error.to_string().contains(&format!("`{key}`")), "{error}"); + } + + run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": null, "rename": null})).unwrap(); + assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), replacement); + } + + #[test] + fn unique_saves_skip_presets_with_colliding_file_stems() { + let mut session = Session::closed().unwrap(); + for name in ["My Preset", "My_Preset_2"] { + run(&mut session, "export.preset.save", json!({"preset": preset(name)})).unwrap(); + } + + let saved = run(&mut session, "export.preset.save", json!({"preset": preset("My Preset"), "unique": true})).unwrap(); + + assert_eq!(saved["name"], "My Preset 3"); + for name in ["My Preset", "My_Preset_2", "My Preset 3"] { + assert_eq!(session.export_preset(name).unwrap().name, name); + } + } + + #[test] + fn unique_save_at_capacity_requires_an_explicit_rename() { + let mut session = Session::closed().unwrap(); + + // At the name length limit, adding the first suffix can reproduce the requested name + for number in 2..=MAX_USER_PRESETS + 1 { + let suffix = format!(" {number}"); + let name = format!("{}{suffix}", "x".repeat(MAX_PRESET_NAME - suffix.len())); + run(&mut session, "export.preset.save", json!({"preset": preset(&name)})).unwrap(); + } + + let first_name = session.export_presets.list[0].name.clone(); + let original = run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap(); + let mut replacement = original.clone(); + replacement["maps"][0]["bit_depth"] = json!(16); + + let result = run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true})); + + assert_eq!(run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap(), original); + assert!(result.is_err()); + + replacement["name"] = json!("Renamed"); + run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true, "rename": first_name})).unwrap(); + + assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Renamed"})).unwrap(), replacement); + assert!(run(&mut session, "export.preset.get", json!({"name": first_name})).is_err()); + } + #[test] fn hostile_presets_are_refused() { let mut s = session(); let mut evil = preset("Evil"); evil["maps"][0]["file"] = json!("../../$mesh"); + assert!(run(&mut s, "export.preset.save", json!({"preset": evil})).is_err()); assert!(run(&mut s, "export.preset.save", json!({"preset": "nope"})).is_err()); assert!(run(&mut s, "export.preset.save", json!({"preset": preset("")})).is_err()); assert!(run(&mut s, "export.preset.save", json!({"preset": preset(&"x".repeat(200))})).is_err()); assert!(run(&mut s, "export.preset.save", json!({"preset": preset("a"), "rename": "missing"})).is_err()); + assert!(s.export_presets.list.is_empty()); } @@ -340,7 +434,7 @@ mod tests { let set = s.doc.project.texture_sets[0].name.clone(); let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id())); - // By name and as an inline object: the same files + // Named and inline presets produce the same files for preset in [json!("packed"), packed] { let _ = std::fs::remove_dir_all(&dir); let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap(); @@ -404,10 +498,12 @@ mod tests { assert_eq!(s.load_export_presets(dir.clone()).len(), 1, "the broken file is reported"); run(&mut s, "export.preset.save", json!({"preset": preset("My Preset")})).unwrap(); assert!(dir.join("My_Preset.json").is_file()); - // Names sharing a file stem clash instead of overwriting each other's file. + + // Reject aliases that would overwrite the same library file assert!(run(&mut s, "export.preset.save", json!({"preset": preset("My_Preset")})).is_err()); run(&mut s, "export.preset.save", json!({"preset": preset("Other"), "rename": "My Preset"})).unwrap(); assert!(!dir.join("My_Preset.json").exists() && dir.join("Other.json").is_file()); + let mut fresh = session(); assert_eq!(fresh.load_export_presets(dir.clone()).len(), 1); assert_eq!(fresh.export_preset("other").unwrap().name, "Other"); diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index 5718f207..e417ce67 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -2,6 +2,7 @@ //! with the brush as its alpha or to place as a decal. use serde_json::{Value, json}; +use texturecraft_formats::sanitize_resource_name; use texturecraft_paint::text::render_text; use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp}; @@ -94,16 +95,57 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow: } } -fn add_text(s: &mut Session, p: &Value) -> Result { - let cmd = "resource.text"; - let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?; - let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; - let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); - let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; - let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); - let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; - // The resource is named after the text (its first line, shortened) unless a name is given. - let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); - let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?; - Ok(json!({ "name": name, "width": img.width, "height": img.height })) +fn add_text(session: &mut Session, params: &Value) -> Result { + const DEFAULT_TEXELS_PER_EM: f32 = 256.0; + const MIN_TEXELS_PER_EM: f32 = 8.0; + const MAX_TEXELS_PER_EM: f32 = 1024.0; + const MAX_LABEL_CHARS: usize = 32; + + let command = "resource.text"; + let text = strp(params, "text").ok_or_else(|| bad(command, "`text` is required"))?; + let (font, face_index) = font_bytes(strp(params, "font"), strp(params, "style"))?; + let texels_per_em = f32p(params, "size").unwrap_or(DEFAULT_TEXELS_PER_EM).clamp(MIN_TEXELS_PER_EM, MAX_TEXELS_PER_EM); + + let image = render_text(&font, face_index, text, texels_per_em).map_err(|error| bad(command, error))?; + drop(font); + + let srgb_bytes = color_param(command, params, "color")? + .unwrap_or([1.0; 3]) + .map(|channel| (texturecraft_texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0).round() as u8); + let (width, height) = (image.width, image.height); + let png_bytes = texturecraft_formats::coverage_png(width, height, &image.coverage, srgb_bytes).map_err(|error| bad(command, error.to_string()))?; + drop(image); + + let label: String = strp(params, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(MAX_LABEL_CHARS).collect(); + + // Treat the label as text before the importer extracts a basename + let file_name = sanitize_resource_name(&format!("Text {}.png", label.trim())); + + let name = session.import_resource_bytes(&file_name, png_bytes)?; + + Ok(json!({ "name": name, "width": width, "height": height })) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn text_resource_name_keeps_the_label_across_a_slash() { + let mut session = crate::sample_session(128, 32).unwrap(); + + let resource = crate::execute(&mut session, "resource.text", &json!({"text": "1/2", "font": "Hack", "size": 16})).unwrap(); + + assert_eq!(resource["name"], "Text_1_2.png"); + } + + #[test] + fn text_resource_name_keeps_the_explicit_label_across_separators() { + let mut session = crate::sample_session(128, 32).unwrap(); + + let resource = + crate::execute(&mut session, "resource.text", &json!({"text": "Plan", "name": "plan\\detail/page", "font": "Hack", "size": 16})).unwrap(); + + assert_eq!(resource["name"], "Text_plan_detail_page.png"); + } } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e02220c9..5ef73b8b 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -3,9 +3,8 @@ use serde_json::{Value, json}; use texturecraft_core::project::ENVIRONMENTS; use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping}; -use texturecraft_geom::glam::Vec3; -use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3}; use crate::frame_target::FrameTarget; use crate::session::ViewMode; use crate::{Result, Session, cmd}; @@ -52,7 +51,7 @@ pub fn specs() -> Vec { "Set camera", [], None, - "{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}", + "{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z] (three finite numbers, null keeps the current target), ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}", always, camera_set ), @@ -233,37 +232,49 @@ pub(crate) fn camera_json(s: &Session) -> Value { }) } -fn camera_set(s: &mut Session, p: &Value) -> Result { - let c = &mut s.camera; - match strp(p, "rotation") { - Some("free") => c.set_free(true), - Some("constrained") => c.set_free(false), - Some(o) => return Err(bad("camera.set", format!("unknown rotation `{o}`: constrained or free"))), +fn camera_set(session: &mut Session, params: &Value) -> Result { + const MAX_PITCH_DEGREES: f32 = 89.0; + const MIN_DISTANCE_RADII: f32 = 0.05; + const MAX_DISTANCE_RADII: f32 = 200.0; + const MIN_FOV_DEGREES: f32 = 5.0; + const MAX_FOV_DEGREES: f32 = 150.0; + + let target = vec3(params, "target"); + if target.is_none() && params.get("target").is_some_and(|value| !value.is_null()) { + return Err(bad("camera.set", "`target` must be an array of three finite numbers")); + } + + let camera = &mut session.camera; + match strp(params, "rotation") { + Some("free") => camera.set_free(true), + Some("constrained") => camera.set_free(false), + Some(other) => return Err(bad("camera.set", format!("unknown rotation `{other}`: constrained or free"))), None => {} } - if f32p(p, "yaw").is_some() || f32p(p, "pitch").is_some() { - // A free camera is put level at the angles - let yaw = f32p(p, "yaw").map_or(c.yaw, f32::to_radians); - let pitch = f32p(p, "pitch").map_or(c.pitch, |v| v.clamp(-89.0, 89.0).to_radians()); - c.set_angles(yaw, pitch); + + let yaw_degrees = f32p(params, "yaw"); + let pitch_degrees = f32p(params, "pitch"); + if yaw_degrees.is_some() || pitch_degrees.is_some() { + // Setting either angle levels a free camera + let yaw = yaw_degrees.map_or(camera.yaw, f32::to_radians); + let pitch = pitch_degrees.map_or(camera.pitch, |degrees| degrees.clamp(-MAX_PITCH_DEGREES, MAX_PITCH_DEGREES).to_radians()); + camera.set_angles(yaw, pitch); } - if let Some(v) = f32p(p, "distance") { - c.distance = v.clamp(c.scene_radius * 0.05, c.scene_radius * 200.0); + if let Some(distance) = f32p(params, "distance") { + camera.distance = distance.clamp(camera.scene_radius * MIN_DISTANCE_RADII, camera.scene_radius * MAX_DISTANCE_RADII); } - if let Some(v) = f32p(p, "fov") { - c.fov = v.clamp(5.0, 150.0); + if let Some(fov_degrees) = f32p(params, "fov") { + camera.fov = fov_degrees.clamp(MIN_FOV_DEGREES, MAX_FOV_DEGREES); } - if let Some(t) = p.get("target").and_then(Value::as_array) { - let v: Vec = t.iter().filter_map(Value::as_f64).map(|x| x as f32).collect(); - if v.len() == 3 && v.iter().all(|x| x.is_finite()) { - c.target = Vec3::new(v[0], v[1], v[2]); - } + if let Some(target) = target { + camera.target = target; } - if let Some(o) = boolp(p, "ortho") { - c.ortho = o; + if let Some(ortho) = boolp(params, "ortho") { + camera.ortho = ortho; } - s.revision = s.revision.wrapping_add(1); - Ok(camera_json(s)) + + session.revision = session.revision.wrapping_add(1); + Ok(camera_json(session)) } fn orbit(s: &mut Session, p: &Value) -> Result { @@ -399,6 +410,40 @@ mod tests { Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() } + #[test] + fn camera_set_rejects_an_invalid_target_without_changing_the_camera() { + let mut session = sphere_session(); + execute(&mut session, "camera.set", &json!({"target": [1.0, 2.0, 3.0], "fov": 40.0})).unwrap(); + let before = session.camera; + let revision = session.revision; + + for target in [json!([10, "typo", 20, 30]), json!([1, 2]), json!([1, "typo", 3]), json!([1, 2, 1e300]), json!({"x": 1})] { + let params = json!({"target": target, "yaw": 35.0, "fov": 90.0, "rotation": "free"}); + + let result = execute(&mut session, "camera.set", ¶ms); + + assert!(matches!(result, Err(crate::EngineError::BadParams { cmd, .. }) if cmd == "camera.set"), "{params}"); + assert_eq!(session.camera, before); + assert_eq!(session.revision, revision); + } + } + + #[test] + fn camera_set_keeps_the_target_when_it_is_omitted_or_null() { + let mut session = sphere_session(); + let target = json!([1.0, 2.0, 3.0]); + + let initial = execute(&mut session, "camera.set", &json!({"target": target, "fov": 40.0})).unwrap(); + let omitted = execute(&mut session, "camera.set", &json!({"fov": 60.0})).unwrap(); + let explicit_null = execute(&mut session, "camera.set", &json!({"target": null, "fov": 80.0})).unwrap(); + + assert_eq!(initial["target"], target); + assert_eq!(omitted["target"], target); + assert_eq!(explicit_null["target"], target); + assert_ne!(omitted["fov"], initial["fov"]); + assert_ne!(explicit_null["fov"], omitted["fov"]); + } + fn pressed(s: &mut Session, command: &str) -> ViewMode { execute(s, command, &json!({})).unwrap(); s.view diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 1669c2e0..7746c1dc 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -1,7 +1,7 @@ //! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there use serde_json::Value; -use texturecraft_core::{Decal, Projection}; +use texturecraft_core::{Decal, Projection, Projector}; use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, bad, has_layer}; @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Reset frame", [], None, - "{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", + "{layer? | effect?: content or mask fill effect id, keepCorners?: bool} — refit the warp's frame around the mesh. With `keepCorners: true`, also reset the projector's rotation and scale and keep the corners; otherwise reset the corners. Projection Depth, crop, and culling stay", has_layer, reset_frame )] @@ -44,26 +44,39 @@ pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal { /// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame) const SMALLEST_SIDE: f32 = 1e-3; -fn reset_frame(s: &mut Session, p: &Value) -> Result { - let target = fill_target(s, p, RESET_FRAME)?; - let fitted = fitted_frame(&s.mesh); - let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { +fn reset_frame(session: &mut Session, params: &Value) -> Result { + let target = fill_target(session, params, RESET_FRAME)?; + let keep_corners = match params.get("keepCorners") { + Some(value) => value.as_bool().ok_or_else(|| bad(RESET_FRAME, "`keepCorners` must be a boolean"))?, + None => false, + }; + let fitted = fitted_frame(&session.mesh); + let (projection, _) = placement_mut(session, target)?; + let mut reset = projection.clone(); + let Projection::Warp { frame, corners, projector, .. } = &mut reset else { return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); }; - // A frame already fitted with unpulled corners adds no undo step - if *frame == fitted && *corners == Projection::FRAME_CORNERS { + *frame = fitted; + if keep_corners { + // Older warps may still carry a transform separate from the frame + let defaults = Projector::default(); + projector.rotation = defaults.rotation; + projector.scale = defaults.scale; + } else { + *corners = Projection::FRAME_CORNERS; + } + + // An unchanged projection adds no undo step + if reset == *projection { return Ok(Value::Null); } - s.edit("Reset frame", |s| { - let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { - return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); - }; - - *frame = fitted; - *corners = Projection::FRAME_CORNERS; + let label = if keep_corners { "Reset warp transform" } else { "Reset frame" }; + session.edit(label, |session| { + *placement_mut(session, target)?.0 = reset; Ok(()) })?; + Ok(Value::Null) } diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 1a16d2ca..55322c1b 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -337,6 +337,67 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); } +/// Restore the global transformation refits a warp's frame and keeps its pulled corners, in one undo step, none when the frame is fitted +#[test] +fn a_warps_frame_resets_apart_from_its_corners() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") }; + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + set(&mut s, layer, json!({"warpCorners": pulled})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); + let steps = s.history_labels().len(); + + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap(); + let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("a warp") }; + + assert_eq!(frame, fitted, "the frame goes back around the mesh"); + assert_eq!(corners, pulled, "the pulled corners stay"); + assert_eq!(s.history_labels().len(), steps + 1); + + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap(); + + assert_eq!(s.history_labels().len(), steps + 1, "a fitted frame adds no undo step"); +} + +#[test] +fn a_warps_global_reset_clears_the_projector_transform() { + let mut session = session(); + let layer = checker_fill(&mut session); + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled, "depthCulling": false, "projectionDepth": 0.2})); + let fitted = projection(&session, layer); + set(&mut session, layer, json!({"projectorRotation": [12, 0, 20], "projectorScale": [2, 2, 1]})); + let edited = projection(&session, layer); + let steps = session.history_labels().len(); + + execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap(); + + assert_eq!(projection(&session, layer), fitted, "restore the displayed frame and keep its corners and projection settings"); + assert_eq!(session.history_labels().len(), steps + 1); + + session.undo().unwrap(); + + assert_eq!(projection(&session, layer), edited); +} + +#[test] +fn invalid_keep_corners_cannot_reset_the_warp() { + let mut session = session(); + let layer = checker_fill(&mut session); + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled})); + let before = projection(&session, layer); + let steps = session.history_labels().len(); + + let result = execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": "true"})); + + assert!(result.is_err()); + assert_eq!(projection(&session, layer), before); + assert_eq!(session.history_labels().len(), steps); +} + /// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it #[test] fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c67529cc..11cfaf41 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -62,6 +62,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod rebuilt_uv_layout; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/rebuilt_uv_layout.rs b/crates/engine/tests/it/rebuilt_uv_layout.rs new file mode 100644 index 00000000..23570231 --- /dev/null +++ b/crates/engine/tests/it/rebuilt_uv_layout.rs @@ -0,0 +1,68 @@ +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_engine::formats::mesh_import::{corner_uvs, import_mesh_bytes_with_uvs}; +use texturecraft_engine::geom::glam::Vec2; +use zip::{ZipWriter, write::SimpleFileOptions}; + +const QUAD_OBJ: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n"; + +/// A layout no unwrapper of this build makes: the quad turned a quarter and inset, per corner +const LOCKED_LAYOUT: [[f32; 2]; 6] = [[0.9, 0.1], [0.9, 0.9], [0.1, 0.9], [0.9, 0.1], [0.1, 0.9], [0.1, 0.1]]; + +/// `uv_layout.bin` written by hand: magic, version 1, corner count, then u and v per corner +fn layout_entry(layout: &[[f32; 2]]) -> Vec { + let mut bytes = b"TCUV".to_vec(); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(u32::try_from(layout.len()).unwrap().to_le_bytes()); + for [u, v] in layout { + bytes.extend(u.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + bytes +} + +/// A format 4 archive of the quad with rebuilt UVs and the locked layout +fn locked_archive() -> Vec { + let session = Session::from_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), 128, "quad", None, true).unwrap(); + let mut project = serde_json::to_value(&session.doc.project).unwrap(); + project["format_version"] = json!(4); + + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + for (name, bytes) in + [("project.json", serde_json::to_vec(&project).unwrap()), ("mesh.obj", QUAD_OBJ.as_bytes().to_vec()), ("uv_layout.bin", layout_entry(&LOCKED_LAYOUT))] + { + archive.start_file(name, SimpleFileOptions::default()).unwrap(); + archive.write_all(&bytes).unwrap(); + } + archive.finish().unwrap().into_inner() +} + +#[test] +fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() { + let locked: Vec = LOCKED_LAYOUT.iter().map(|uv| Vec2::from_array(*uv)).collect(); + let unwrapped = import_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), true).unwrap().mesh; + + let mut reopened = Session::from_project_bytes(&locked_archive()).unwrap(); + let opened_layout = corner_uvs(&reopened.source_mesh()); + reopened.reimport_mesh(None, false).unwrap(); + let reimported_layout = corner_uvs(&reopened.source_mesh()); + let resaved = Session::from_project_bytes(&reopened.to_project_bytes().unwrap()).unwrap(); + + assert_ne!(corner_uvs(&unwrapped), locked, "the locked layout differs from what the unwrapper makes now"); + assert_eq!(opened_layout, locked); + assert_eq!(reimported_layout, locked, "reimporting the project's own mesh keeps the saved layout"); + assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout"); +} + +#[test] +fn opening_a_builtin_project_refuses_rebuilt_mesh_uvs() { + let mut file = texturecraft_engine::formats::load_project_bytes(&locked_archive()).unwrap(); + file.project.mesh = "builtin:plane".into(); + file.mesh = None; + + let error = Session::from_project_file(file).map(|_| ()).expect_err("a built-in mesh cannot use the stored layout"); + + assert!(error.to_string().contains("uv_layout.bin"), "{error}"); +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index dff3f94d..8135b5b0 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -11,13 +11,12 @@ workspace = true [dependencies] craft-usd.workspace = true # ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local. -craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" } +craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-materialx = { workspace = true } craft-mesh = { workspace = true } craft-mcmat = { workspace = true } craft-tcraft = { workspace = true } craft-zip = { workspace = true } -craft-zip-usdz = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } @@ -26,7 +25,7 @@ image = { workspace = true } png = "0.18" bytemuck = { workspace = true, features = ["extern_crate_alloc"] } craft-image-codecs = { workspace = true } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } flate2 = { workspace = true } half = { workspace = true } zip = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index b92e715f..5f60e6ef 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -163,7 +163,8 @@ targets Sketchfab. ```rust pub struct ProjectFile { pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap, - pub mesh: Option<(String /* ext */, Vec)>, pub thumbnail: Option>, + pub mesh: Option<(String /* ext */, Vec)>, pub mesh_uvs: Option>, + pub thumbnail: Option>, pub warnings: Vec, // Import warnings, never saved } pub fn save_project_bytes(pf: &ProjectFile) -> Result>; @@ -180,12 +181,14 @@ pub fn project_open_limit_gib() -> u32; |---|---| | `project.json` | serde JSON of `Project` | | `mesh.` | the original mesh file bytes (absent for `builtin:` meshes) | +| `uv_layout.bin` | generated UVs for an explicitly rebuilt mesh (format 4) | | `pixels/layer__.bin` | painted layer (or content paint effect) channel | | `pixels/mask_.bin` | painted mask effect | | `baked/_.bin` | baked mesh map of texture set `` | | `thumbnail.png` | optional, stored | -`.bin`: header `TCTX`, version, width, height, components, tile count (u32 LE each), then per +Paint and bake `.bin` entries use a `TCTX` header with version, width, height, components and tile +count (u32 LE each), then per allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless). Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE. @@ -198,6 +201,10 @@ Project format version 3 stores baked bent normal maps in tangent space (OpenGL normal map). Version 2 and older files held them in world space: loading drops those maps, keeps the bake settings and warns that the Bent Normals map needs a re-bake. +Project format version 4 saves rebuilt mesh UVs so reopening can use the same layout. The +`uv_layout.bin` entry starts with `TCUV`, followed by the layout version and corner count (u32 LE). +Each triangle corner has one little-endian f32 pair in imported index order. + Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 1ccbdb67..9441b31e 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -287,7 +287,7 @@ pub(crate) fn material_maps(mesh: &Mesh, stem: &str, textures: &[Vec)]) -> Result> { - let mut zip = craft_zip_usdz::Writer::new(); + let mut zip = craft_zip::Writer::new(); let err = |e| FormatError::Invalid(format!("usdz package: {e}")); for (name, bytes) in std::iter::once((layer_name, layer)).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) { zip.add_stored_aligned(name, bytes, 64).map_err(err)?; diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index f94f497d..44ad0331 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -198,29 +198,36 @@ fn sample_file(with_tri: bool) -> Vec { #[test] fn imports_polymesh_through_xforms_with_face_sets_uvs_and_normals() { let raw = read(&sample_file(true)).unwrap(); - let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(m, p, _)| (m.as_str(), p.as_str())).collect(); + let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(material, part, _)| (material.as_str(), part.as_str())).collect(); names.sort(); + assert_eq!(names, vec![("Default", "tri"), ("left", "strip"), ("right", "strip")], "meshes take their transform's name"); assert_eq!(raw.triangle_count(), 5); - // UVs exist only on the strip, so the whole mesh is unwrapped (with a warning). + + // UVs exist only on the strip, so the whole mesh is unwrapped with a warning assert!(raw.uvs.is_none() && !raw.warnings.is_empty()); - // World positions: scaled by 2, then translated. + + // World positions are scaled first and then translated let (lo, hi) = raw.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); assert_eq!((lo, hi), (Vec3::new(0.0, 0.0, 3.0), Vec3::new(5.0, 4.0, 5.0))); - // Clockwise Alembic faces become counter-clockwise: the strip faces +Z. - for (m, _, tris) in &raw.groups { - if m == "Default" { + + // Clockwise Alembic faces are reversed so the strip faces +Z + for (material, _, triangles) in &raw.groups { + if material == "Default" { continue; } - for t in tris.chunks(3) { + + for t in triangles.chunks(3) { let p = |i: u32| raw.positions[i as usize]; assert!((p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])).z > 0.0); } } - let mesh = finish(raw).unwrap().mesh; + + let mesh = finish(raw, false).unwrap().mesh; assert_eq!(mesh.materials.len(), 3); - // The strip alone keeps its indexed face-varying UVs: u = x / 2 in the file's own space. - let strip = finish(read(&sample_file(false)).unwrap()).unwrap(); + + // The strip alone keeps its indexed face-varying UVs with u = x / 2 in local space + let strip = finish(read(&sample_file(false)).unwrap(), false).unwrap(); assert!(!strip.report.uvs_generated); for (p, uv) in strip.mesh.positions.iter().zip(&strip.mesh.uvs) { let local = (*p - Vec3::new(1.0, 2.0, 3.0)) / 2.0; @@ -318,21 +325,23 @@ fn hdf5_and_garbage_are_clear_errors() { #[test] fn truncated_and_corrupted_files_never_panic() { let bytes = sample_file(true); - for n in (0..bytes.len()).step_by(3) { - let _ = read(&bytes[..n]); + for end in (0..bytes.len()).step_by(3) { + let _ = read(&bytes[..end]); } + let mut rng = 0x9e37_79b9_7f4a_7c15u64; for _ in 0..4000 { - let mut b = bytes.clone(); + let mut corrupted = bytes.clone(); for _ in 0..4 { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; - let i = (rng % b.len() as u64) as usize; - b[i] = (rng >> 32) as u8; + let i = (rng % corrupted.len() as u64) as usize; + corrupted[i] = (rng >> 32) as u8; } - if let Ok(raw) = read(&b) { - let _ = finish(raw); + + if let Ok(raw) = read(&corrupted) { + let _ = finish(raw, false); } } } diff --git a/crates/formats/src/mesh_import/mesh_uv_source.rs b/crates/formats/src/mesh_import/mesh_uv_source.rs new file mode 100644 index 00000000..716bdcd0 --- /dev/null +++ b/crates/formats/src/mesh_import/mesh_uv_source.rs @@ -0,0 +1,17 @@ +use texturecraft_geom::glam::Vec2; + +/// How to obtain triangle UVs when reading mesh geometry. +pub enum MeshUvSource<'a> { + /// Keep complete authored UVs, or unwrap a mesh that needs them. + FromFile, + /// Generate a fresh layout even when the file contains UVs. + Rebuild, + /// Apply the project's saved UVs in triangle corner order. + Saved(&'a [Vec2]), +} + +impl MeshUvSource<'_> { + pub fn from_rebuild_setting(rebuild_uvs: bool) -> Self { + if rebuild_uvs { Self::Rebuild } else { Self::FromFile } + } +} diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 315e4337..6450878b 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -11,6 +11,7 @@ mod dae; mod external; mod fbx; mod gltf; +mod mesh_uv_source; mod obj; mod ply; #[cfg(test)] @@ -32,6 +33,7 @@ use crate::{FormatError, Result}; #[cfg(not(target_arch = "wasm32"))] pub use external::read_mesh_file; pub use external::{MeshFile, self_contained_mesh}; +pub use mesh_uv_source::MeshUvSource; /// Mesh files larger than this are refused before reading. pub const MAX_MESH_FILE_BYTES: u64 = 2 << 30; @@ -108,7 +110,7 @@ pub struct MeshReport { pub triangles: usize, pub vertices: usize, pub materials: usize, - /// The file had no UVs; they were generated by the automatic unwrap. + /// The UVs were generated by the automatic unwrap. pub uvs_generated: bool, /// Triangles with a UV outside 0..1. pub uv_out_of_range: usize, @@ -295,7 +297,32 @@ fn extension(file_name: &str) -> String { /// self-contained (see [`self_contained_mesh`]); OBJ material libraries are not read (usemtl /// names are). pub fn import_mesh_bytes(file_name: &str, bytes: &[u8]) -> Result { - finish(read(file_name, bytes)?) + import_mesh_bytes_with_uvs(file_name, bytes, false) +} + +/// Import mesh bytes, optionally rebuilding the UV layout even when the mesh already has UVs. +pub fn import_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], rebuild_uvs: bool) -> Result { + finish(read(file_name, bytes)?, rebuild_uvs) +} + +/// Import mesh bytes with a saved UV layout ([`corner_uvs`] of the mesh as first imported) +/// instead of the file's UVs or the automatic unwrap, so the layout does not depend on the +/// unwrapper of the running version. +pub fn import_mesh_bytes_with_layout(file_name: &str, bytes: &[u8], corner_uvs: &[Vec2]) -> Result { + finish_with_layout(read(file_name, bytes)?, MeshUvSource::Saved(corner_uvs)) +} + +/// Read validated geometry for project open and mesh replacement, which keep the project's cameras +/// and do not need the import dialog's UV coverage report. +pub fn import_mesh_geometry(file_name: &str, bytes: &[u8], uv_source: MeshUvSource<'_>) -> Result { + let (mesh, _, _) = complete_mesh(read(file_name, bytes)?, uv_source)?; + Ok(mesh) +} + +/// The UV of every triangle corner, in index order: a layout that [`import_mesh_bytes_with_layout`] +/// applies to the same mesh file again. +pub fn corner_uvs(mesh: &Mesh) -> Vec { + mesh.indices.iter().map(|index| mesh.uvs.get(*index as usize).copied().unwrap_or_default()).collect() } /// Import a mesh file with the files it references next to it ([`read_mesh_file`]). @@ -491,29 +518,96 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { } /// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report. -pub(crate) fn finish(mut raw: RawMesh) -> Result { +pub(crate) fn finish(raw: RawMesh, rebuild_uvs: bool) -> Result { + finish_with_layout(raw, MeshUvSource::from_rebuild_setting(rebuild_uvs)) +} + +fn finish_with_layout(mut raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result { let mut raw_cameras = std::mem::take(&mut raw.cameras); raw_cameras.truncate(MAX_CAMERAS); + let (mesh, warnings, uvs_generated) = complete_mesh(raw, uv_source)?; + + let report = report(&mesh, uvs_generated, warnings); + let cameras = orbit_cameras(&raw_cameras, &mesh); + Ok(ImportedMesh { mesh, report, cameras }) +} + +fn complete_mesh(raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result<(Mesh, Vec, bool)> { let (mut mesh, mut warnings, uvs) = geometry(raw)?; - let uvs_generated = match uvs { - Some(uv) if uv.len() == mesh.positions.len() => { + let uvs_generated = match (uv_source, uvs) { + (MeshUvSource::Saved(layout), authored_uvs) => { + drop(authored_uvs); + apply_corner_uvs(&mut mesh, layout)?; + true + } + (MeshUvSource::FromFile, Some(uv)) if uv.len() == mesh.positions.len() => { if uv.iter().any(|v| !v.is_finite()) { warnings.push("non-finite UVs were replaced with 0".into()); } + mesh.uvs = uv.into_iter().map(|v| if v.is_finite() { v } else { Vec2::ZERO }).collect(); mesh.compute_tangents(); false } - _ => { + (source, authored_uvs) => { + drop(authored_uvs); let charts = auto_unwrap(&mut mesh, UNWRAP_PADDING, UNWRAP_RESOLUTION)?; - warnings.push(format!("the mesh has no UVs; generated an automatic unwrap with {charts} charts")); + let reason = if matches!(source, MeshUvSource::Rebuild) { "rebuild UVs was selected" } else { "the mesh has no UVs" }; + warnings.push(format!("{reason}; generated an automatic unwrap with {charts} charts")); true } }; + mesh.validate()?; - let report = report(&mesh, uvs_generated, warnings); - let cameras = orbit_cameras(&raw_cameras, &mesh); - Ok(ImportedMesh { mesh, report, cameras }) + Ok((mesh, warnings, uvs_generated)) +} + +/// Give every triangle corner its UV from `layout`, keeping independently packed materials split. +fn apply_corner_uvs(mesh: &mut Mesh, layout: &[Vec2]) -> Result<()> { + if layout.len() != mesh.indices.len() { + return Err(FormatError::Invalid(format!("the saved UV layout has {} corners but the mesh has {}", layout.len(), mesh.indices.len()))); + } + + if layout.iter().any(|uv| !uv.is_finite()) { + return Err(FormatError::Invalid("the saved UV layout has non-finite UVs".into())); + } + + let mut remapped_vertices = HashMap::with_capacity((mesh.positions.len() * 2).min(layout.len())); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + + // Geometry supplies contiguous submesh ranges and validates their vertex indices + for submesh in &mesh.submeshes { + let start = submesh.start as usize; + let end = start + submesh.count as usize; + let material = submesh.material as u32; + for (&vertex, &uv) in mesh.indices[start..end].iter().zip(&layout[start..end]) { + let index = *remapped_vertices.entry((vertex, material, uv.to_array().map(f32::to_bits))).or_insert_with(|| { + let source = vertex as usize; + positions.push(mesh.positions[source]); + normals.push(mesh.normals[source]); + if let Some(color) = mesh.colors.get(source) { + colors.push(*color); + } + + uvs.push(uv); + (positions.len() - 1) as u32 + }); + indices.push(index); + } + } + + drop(remapped_vertices); + + mesh.positions = positions; + mesh.normals = normals; + mesh.uvs = uvs; + mesh.colors = colors; + mesh.indices = indices; + + mesh.compute_tangents(); + + Ok(()) } /// File cameras as orbit cameras: the target is where the view axis passes the mesh center diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 0cfbae61..cc7aa272 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -757,3 +757,45 @@ fn duplicate_gltf_material_names_keep_first_wins_and_order() { } assert_eq!(color_by_material.get("Dup").unwrap().factor, Vec4::new(1.0, 0.0, 0.0, 1.0)); } + +#[test] +fn a_saved_layout_reproduces_the_rebuilt_mesh_without_unwrapping() { + let rebuilt = import_mesh_bytes_with_uvs("a.obj", OBJ.as_bytes(), true).unwrap().mesh; + let layout = corner_uvs(&rebuilt); + + let reopened = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout).unwrap(); + let short = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout[1..]); + let mut non_finite = layout.clone(); + non_finite[0].x = f32::NAN; + + assert!(!reopened.report.warnings.iter().any(|warning| warning.contains("unwrap")), "{:?}", reopened.report.warnings); + assert_eq!((&reopened.mesh.positions, &reopened.mesh.indices, &reopened.mesh.uvs), (&rebuilt.positions, &rebuilt.indices, &rebuilt.uvs)); + assert_eq!(reopened.mesh.normals, rebuilt.normals); + assert!(short.is_err(), "a layout for another mesh is refused"); + assert!(import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &non_finite).is_err()); +} + +#[test] +fn a_saved_layout_keeps_coincident_vertices_in_different_materials_split() { + // Synthetic mesh with coincident triangles in independently packed materials + let source = br#"#usda 1.0 +def Mesh "Overlaid" { + int[] faceVertexCounts = [3, 3] + int[] faceVertexIndices = [0, 1, 2, 0, 1, 2] + point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] + rel material:binding = + def GeomSubset "second" { + uniform token familyName = "materialBind" + int[] indices = [1] + rel material:binding = + } +} +"#; + let rebuilt = import_mesh_bytes_with_uvs("overlaid.usda", source, true).unwrap().mesh; + let layout = corner_uvs(&rebuilt); + + let reopened = import_mesh_bytes_with_layout("overlaid.usda", source, &layout).unwrap().mesh; + + assert_eq!(&layout[..3], &layout[3..], "the independently packed triangles have equal UVs"); + assert_eq!(reopened, rebuilt); +} diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 9eef4537..ce07ab3c 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -707,7 +707,7 @@ def Xform "Root" } "#; let albedo = png([200, 10, 10]); - let mut writer = craft_zip_usdz::Writer::new(); + let mut writer = craft_zip::Writer::new(); writer.add_stored_aligned("sub/scene.usda", usda.as_bytes(), 64).unwrap(); writer.add_stored_aligned("sub/tex/albedo.png", &albedo, 64).unwrap(); let pkg = writer.finish().unwrap(); diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index c5bf3bdb..581d13d2 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -4,6 +4,7 @@ //! |---|---| //! | `project.json` | serde JSON of [`Project`] | //! | `mesh.` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:"`) | +//! | `uv_layout.bin` | the UV of every triangle corner of a mesh whose UVs were rebuilt (format 4+, see `uv_layout`) | //! | `highpoly/` | a high-definition mesh file for baking, in list order | //! | `cage/` | the baking cage mesh file | //! | `bake_paint/_.bin` | cage or skew paint, stored as a one-component baked map | @@ -18,19 +19,22 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). -use std::borrow::Borrow; +use std::borrow::{Borrow, Cow}; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; +use texturecraft_core::project::REBUILT_MESH_UVS_VERSION; use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project, TANGENT_BENT_NORMAL_VERSION}; +use texturecraft_geom::glam::Vec2; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; use self::load_budget::LoadBudget; +use self::uv_layout::{MAX_UV_LAYOUT_BYTES, UV_LAYOUT_ENTRY, read_uv_layout, uv_layout_bytes, write_uv_layout}; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; @@ -38,6 +42,7 @@ mod load_budget; mod project_open_limit; mod ram_operation; mod ram_reservation; +mod uv_layout; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources}; pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; @@ -72,6 +77,9 @@ pub struct ProjectFile> { pub baked: BTreeMap, /// Original mesh file: (extension, bytes). pub mesh: Option<(String, Vec)>, + /// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in + /// index order, as the mesh was first imported. + pub mesh_uvs: Option>, /// High-definition mesh files for baking: (file name, bytes). Names are /// [`sanitize_resource_name`]d on save. pub high_poly: Vec<(String, Vec)>, @@ -85,6 +93,21 @@ pub struct ProjectFile> { pub warnings: Vec, } +impl ProjectFile { + /// Check that the mesh source and the rebuild setting agree with the saved layout. + pub fn validate_mesh_uvs(&self) -> Result<()> { + if self.project.mesh_rebuild_uvs != self.mesh_uvs.is_some() { + return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} is required exactly when mesh UVs were rebuilt"))); + } + + if self.mesh_uvs.is_some() && (self.mesh.is_none() || self.project.mesh.starts_with("builtin:")) { + return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires a stored mesh"))); + } + + Ok(()) + } +} + /// Maximum length of a resource name after sanitization. pub const MAX_RESOURCE_NAME_LEN: usize = 120; @@ -187,12 +210,23 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) } /// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. -fn entries(pf: &ProjectFile>>) -> Result>> { +fn entries(project_file: &ProjectFile>>) -> Result>> { + project_file.validate_mesh_uvs()?; + let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); - let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; + let mut project = Cow::Borrowed(&project_file.project); + + // Callers can supply a document directly instead of a versioned save snapshot + let version = project.save_format_version(); + if project.format_version != version { + project.to_mut().format_version = version; + } + + let json = serde_json::to_vec_pretty(project.as_ref()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; - if let Some((ext, bytes)) = &pf.mesh { + + if let Some((ext, bytes)) = &project_file.mesh { out.push(Entry { name: format!("mesh.{}", sanitize_ext(ext)), options: deflate, @@ -200,8 +234,18 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |w| w.write_all(bytes)), }); } + + if let Some(layout) = &project_file.mesh_uvs { + out.push(Entry { + name: UV_LAYOUT_ENTRY.into(), + options: deflate, + weight: uv_layout_bytes(layout.len()), + body: Box::new(move |w| write_uv_layout(w, layout)), + }); + } + let mut used = HashSet::new(); - for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { + for (dir, (name, bytes)) in project_file.high_poly.iter().map(|m| ("highpoly", m)).chain(project_file.cage.iter().map(|m| ("cage", m))) { out.push(Entry { name: unique_entry_name(dir, name, &mut used), options: deflate, @@ -209,7 +253,8 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |w| w.write_all(bytes)), }); } - for ((texture_set, target), map) in &pf.bake_paint { + + for ((texture_set, target), map) in &project_file.bake_paint { if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) { return Err(FormatError::Invalid("bake paint map dimensions do not match its values".into())); } @@ -218,6 +263,7 @@ fn entries(pf: &ProjectFile>>) -> Result>> { BakePaintTarget::Cage => "cage", BakePaintTarget::Skew => "skew", }; + out.push(Entry { name: format!("bake_paint/{texture_set}_{target_name}.bin"), options: deflate, @@ -225,7 +271,8 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)), }); } - let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); + + let mut layers: Vec<_> = project_file.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); for ((id, c), img) in layers { let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; @@ -236,13 +283,14 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |mut w| write_tiles(&mut w, img)), }); } - let mut masks: Vec<_> = pf.pixels.masks.iter().collect(); + + let mut masks: Vec<_> = project_file.pixels.masks.iter().collect(); masks.sort_by_key(|(k, _)| **k); for (id, img) in masks { let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) }); } - for (ts, maps) in &pf.baked { + for (ts, maps) in &project_file.baked { let r = maps.resolution; for (m, data) in &maps.maps { // Skip inconsistent maps so the saved project can reopen and bake them again @@ -260,11 +308,13 @@ fn entries(pf: &ProjectFile>>) -> Result>> { }); } } - if let Some(png) = &pf.thumbnail { + + if let Some(png) = &project_file.thumbnail { out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) }); } + used.clear(); - for (name, resource) in &pf.resources { + for (name, resource) in &project_file.resources { let bytes = resource.borrow(); out.push(Entry { name: unique_entry_name("resources", name, &mut used), @@ -273,6 +323,7 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |w| w.write_all(bytes)), }); } + Ok(out) } @@ -406,10 +457,11 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) return Err(malformed(KIND, format!("texture set \"{}\" has resolution {} over {} UV tiles", ts.name, ts.resolution, ts.uv_tiles.len().max(1)))); } - let mut pf = ProjectFile { + let mut project_file = ProjectFile { pixels: PixelStore::default(), baked: BTreeMap::new(), mesh: None, + mesh_uvs: None, high_poly: Vec::new(), cage: None, bake_paint: BTreeMap::new(), @@ -419,36 +471,36 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) project, }; - for i in 0..zip.len() { - let mut f = zip.by_index(i).map_err(zip_err)?; - let declared_bytes = f.size(); - let name = f.name().map_err(zip_err)?.into_owned(); - let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); + for index in 0..zip.len() { + let mut entry = zip.by_index(index).map_err(zip_err)?; + let declared_bytes = entry.size(); + let name = entry.name().map_err(zip_err)?.into_owned(); + let size_of = |id: LayerId| texture_set_of(&project_file.project, id).and_then(|ts| project_file.project.texture_sets.get(ts)).map(|t| t.size()); // Unrecognized entries from newer minor revisions may be skipped if name == "thumbnail.png" { - pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?); + project_file.thumbnail = Some(read_all(&mut entry, MAX_THUMBNAIL, &mut budget, &name)?); } else if let Some(res_name) = name.strip_prefix("resources/") { if res_name.is_empty() || sanitize_resource_name(res_name) != res_name { return Err(malformed(KIND, format!("bad resource name {name}"))); } - let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?; - pf.resources.insert(res_name.to_string(), bytes); + let bytes = read_all(&mut entry, MAX_RESOURCE, &mut budget, &name)?; + project_file.resources.insert(res_name.to_string(), bytes); } else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") { if file.is_empty() || sanitize_resource_name(file) != file { return Err(malformed(KIND, format!("bad mesh name {name}"))); } - let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?); + let entry = (file.to_string(), read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?); match dir { - "cage" => pf.cage = Some(entry), - _ => pf.high_poly.push(entry), + "cage" => project_file.cage = Some(entry), + _ => project_file.high_poly.push(entry), } } else if let Some(rest) = name.strip_prefix("bake_paint/").and_then(|name| name.strip_suffix(".bin")) { let (texture_set, target) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry {name}")))?; let texture_set: usize = texture_set.parse().map_err(|_| malformed(KIND, format!("bad entry {name}")))?; - if texture_set >= pf.project.texture_sets.len() { + if texture_set >= project_file.project.texture_sets.len() { return Err(malformed(KIND, format!("unknown texture set in {name}"))); } @@ -457,11 +509,22 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) "skew" => BakePaintTarget::Skew, _ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))), }; - let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?; - pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); + let (width, height, values) = read_baked(&mut entry, declared_bytes, 1, &mut budget, &name)?; + project_file.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { - let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; - pf.mesh = Some((ext.to_string(), bytes)); + let bytes = read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; + project_file.mesh = Some((ext.to_string(), bytes)); + } else if name == UV_LAYOUT_ENTRY { + if version < REBUILT_MESH_UVS_VERSION || !project_file.project.mesh_rebuild_uvs { + return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires format {REBUILT_MESH_UVS_VERSION} or later and rebuilt mesh UVs"))); + } + + if declared_bytes > MAX_UV_LAYOUT_BYTES { + return Err(FormatError::TooLarge(format!("{UV_LAYOUT_ENTRY} is larger than {MAX_UV_LAYOUT_BYTES} bytes"))); + } + + budget.take(declared_bytes).map_err(FormatError::TooLarge)?; + project_file.mesh_uvs = Some(read_uv_layout(&mut entry, declared_bytes)?); } else if let Some(rest) = name.strip_prefix("pixels/layer_").and_then(|r| r.strip_suffix(".bin")) { let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); @@ -470,14 +533,14 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) // Drop pixels of layers that are no longer in any stack let Some(size) = size_of(id) else { continue }; - let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?; - pf.pixels.layers.insert((id, c), img); + let img = read_tiles(&mut entry, size, c.components() + 1, &mut budget, &name)?; + project_file.pixels.layers.insert((id, c), img); } else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) { let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let Some(size) = size_of(id) else { continue }; - let img = read_tiles(&mut f, size, 2, &mut budget, &name)?; - pf.pixels.masks.insert(id, img); + let img = read_tiles(&mut entry, size, 2, &mut budget, &name)?; + project_file.pixels.masks.insert(id, img); } else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) { let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?; @@ -486,12 +549,12 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) continue; }; - if ts >= pf.project.texture_sets.len() { + if ts >= project_file.project.texture_sets.len() { continue; } - let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?; - let maps = pf.baked.entry(ts).or_default(); + let (res, height, data) = read_baked(&mut entry, declared_bytes, m.components(), &mut budget, &name)?; + let maps = project_file.baked.entry(ts).or_default(); if maps.maps.is_empty() { maps.resolution = res; } else if maps.resolution != res || maps.maps.keys().next().is_some_and(|k| maps.height(*k) != height) { @@ -502,18 +565,22 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) } } + // Rerunning the unwrapper could lay the saved paint over a different layout + project_file.validate_mesh_uvs()?; + if version < TANGENT_BENT_NORMAL_VERSION { - drop_world_space_bent_normals(&mut pf); + drop_world_space_bent_normals(&mut project_file); } - pf.project.format_version = FORMAT_VERSION; + + project_file.project.format_version = version.max(TANGENT_BENT_NORMAL_VERSION); if recovered { - pf.warnings.push( + project_file.warnings.push( "Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(), ); } - Ok(pf) + Ok(project_file) } /// Older files hold bent normal maps in world space, which every reader now takes as tangent diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 4364f39e..c8143dc2 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -32,6 +32,7 @@ fn sample() -> Sample { pixels, baked: [(0, baked)].into(), mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])), + mesh_uvs: None, high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])], cage: Some(("cage.obj".into(), vec![5, 5])), bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })] @@ -55,6 +56,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) { } assert_eq!(a.baked, b.baked); assert_eq!(a.mesh, b.mesh); + assert_eq!(a.mesh_uvs, b.mesh_uvs); assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order"); assert_eq!(a.bake_paint, b.bake_paint); assert_eq!(a.thumbnail, b.thumbnail); @@ -104,7 +106,7 @@ fn legacy_bakes_load_as_is_without_layout_conversion() { sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }); let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap(); - assert_eq!(loaded.project.format_version, FORMAT_VERSION); + assert_eq!(loaded.project.format_version, TANGENT_BENT_NORMAL_VERSION); assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout"); assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout"); let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap(); @@ -920,3 +922,85 @@ fn zip64_entry_counts_remain_supported_and_bounded() { } } } + +fn rebuilt_uvs_sample() -> ProjectFile { + let mut project_file = sample().pf; + project_file.project.mesh_rebuild_uvs = true; + project_file.mesh_uvs = Some(vec![Vec2::new(0.25, 0.75), Vec2::new(1.0, 0.0), Vec2::new(0.5, 0.125)]); + project_file +} + +#[test] +fn a_saved_uv_layout_round_trips_in_format_4() { + const ADDITIONAL_CORNERS: usize = 3000; + + let mut project_file = rebuilt_uvs_sample(); + let layout = project_file.mesh_uvs.as_mut().unwrap(); + + // Exercise full batches and a partial final batch with distinct UVs + layout.extend((0..ADDITIONAL_CORNERS).map(|corner| Vec2::new(corner as f32 / ADDITIONAL_CORNERS as f32, 0.5))); + + let loaded = load_project_bytes(&save_project_bytes(&project_file).unwrap()).unwrap(); + + assert_eq!(loaded.mesh_uvs, project_file.mesh_uvs); + assert_eq!(loaded.project.format_version, REBUILT_MESH_UVS_VERSION); +} + +#[test] +fn a_saved_uv_layout_requires_format_4_and_the_rebuild_setting() { + let project_file = rebuilt_uvs_sample(); + let older_version = edit_project_json(&project_file, |json| json["format_version"] = TANGENT_BENT_NORMAL_VERSION.into()); + let disabled_rebuild = edit_project_json(&project_file, |json| json["mesh_rebuild_uvs"] = false.into()); + + for archive in [older_version, disabled_rebuild] { + let error = load_project_bytes(&archive).map(|_| ()).expect_err("the archive has inconsistent UV layout metadata"); + + assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}"); + } +} + +#[test] +fn a_rebuilt_project_cannot_be_saved_without_its_layout() { + let mut project_file = rebuilt_uvs_sample(); + project_file.mesh_uvs = None; + + let error = save_project_bytes(&project_file).map(|_| ()).expect_err("the snapshot is missing the rebuilt UV layout"); + + assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}"); +} + +#[test] +fn rebuilt_uvs_without_a_valid_saved_layout_are_refused() { + let project_file = rebuilt_uvs_sample(); + let without_layout = edit_archive(&project_file, |name, _| { + if name == UV_LAYOUT_ENTRY { + *name = "ignored.bin".into(); + } + }); + let edited_layout = |edit: fn(&mut Vec)| { + edit_archive(&project_file, |name, data| { + if name == UV_LAYOUT_ENTRY { + edit(data); + } + }) + }; + let truncated = edited_layout(|data| data.truncate(data.len() - 1)); + let trailing_bytes = edited_layout(|data| data.push(0)); + let short_header = edited_layout(|data| data.truncate(8)); + let wrong_count = edited_layout(|data| data[8] = 9); + let non_finite = edited_layout(|data| data[12..16].copy_from_slice(&f32::NAN.to_le_bytes())); + let bad_magic = edited_layout(|data| data[0] = b'X'); + + for (case, bytes) in [ + ("missing", without_layout), + ("truncated", truncated), + ("trailing bytes", trailing_bytes), + ("short header", short_header), + ("wrong count", wrong_count), + ("non-finite", non_finite), + ("bad magic", bad_magic), + ] { + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(!is_guard_error(&error), "{case}: {error}"); + } +} diff --git a/crates/formats/src/project_file/uv_layout.rs b/crates/formats/src/project_file/uv_layout.rs new file mode 100644 index 00000000..b87ac263 --- /dev/null +++ b/crates/formats/src/project_file/uv_layout.rs @@ -0,0 +1,99 @@ +//! `uv_layout.bin` stores the generated UVs independently of the running unwrapper. +//! After the magic `TCUV`, the header stores a version and a corner count as little-endian u32s. +//! The body stores a little-endian f32 pair for each triangle corner in index order. + +use std::io::{Read, Write}; + +use texturecraft_geom::MAX_TRIANGLES; +use texturecraft_geom::glam::Vec2; + +use super::KIND; +use crate::{Result, malformed}; + +/// Zip entry name of the saved layout. +pub const UV_LAYOUT_ENTRY: &str = "uv_layout.bin"; + +const UV_LAYOUT_MAGIC: &[u8; 4] = b"TCUV"; +const UV_LAYOUT_VERSION: u32 = 1; +const HEADER_BYTES: usize = 12; +const COORDINATE_BYTES: usize = 4; +const CORNER_BYTES: usize = 2 * COORDINATE_BYTES; +const BATCH_CORNERS: usize = 1024; +const MAX_LAYOUT_CORNERS: usize = MAX_TRIANGLES * 3; + +/// Largest entry a valid mesh can need: every corner of the most triangles accepted. +pub const MAX_UV_LAYOUT_BYTES: u64 = uv_layout_bytes(MAX_LAYOUT_CORNERS); + +/// Encoded size of a layout of `corners` UVs. +pub const fn uv_layout_bytes(corners: usize) -> u64 { + HEADER_BYTES as u64 + corners as u64 * CORNER_BYTES as u64 +} + +pub fn write_uv_layout(writer: &mut dyn Write, layout: &[Vec2]) -> std::io::Result<()> { + if layout.len() > MAX_LAYOUT_CORNERS { + return Err(std::io::Error::other("the UV layout has too many corners")); + } + + writer.write_all(UV_LAYOUT_MAGIC)?; + writer.write_all(&UV_LAYOUT_VERSION.to_le_bytes())?; + writer.write_all(&(layout.len() as u32).to_le_bytes())?; + + let mut buffer = [[0; CORNER_BYTES]; BATCH_CORNERS]; + for batch in layout.chunks(BATCH_CORNERS) { + let encoded = &mut buffer[..batch.len()]; + for (corner, uv) in encoded.iter_mut().zip(batch) { + if !uv.is_finite() { + return Err(std::io::Error::other("the UV layout has non-finite UVs")); + } + + corner.copy_from_slice([uv.x.to_le_bytes(), uv.y.to_le_bytes()].as_flattened()); + } + + writer.write_all(encoded.as_flattened())?; + } + + Ok(()) +} + +/// Decode one entry while holding only the decoded layout and a fixed-size buffer. +pub fn read_uv_layout(reader: &mut impl Read, entry_bytes: u64) -> Result> { + let bad = |why: &str| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {why}")); + let mut header = [[0; COORDINATE_BYTES]; 3]; + reader.read_exact(header.as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?; + let [magic, version, corners] = header; + if magic != *UV_LAYOUT_MAGIC { + return Err(bad("bad magic")); + } + + if u32::from_le_bytes(version) != UV_LAYOUT_VERSION { + return Err(bad("unsupported version")); + } + + let corners = u32::from_le_bytes(corners) as usize; + if corners > MAX_LAYOUT_CORNERS || uv_layout_bytes(corners) != entry_bytes { + return Err(bad("the corner count does not match the entry size")); + } + + let mut layout = Vec::with_capacity(corners); + let mut buffer = [[[0; COORDINATE_BYTES]; 2]; BATCH_CORNERS]; + while layout.len() < corners { + let count = (corners - layout.len()).min(BATCH_CORNERS); + let encoded = &mut buffer[..count]; + reader.read_exact(encoded.as_flattened_mut().as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?; + for &[u, v] in encoded.iter() { + let uv = Vec2::new(f32::from_le_bytes(u), f32::from_le_bytes(v)); + if !uv.is_finite() { + return Err(bad("non-finite UVs")); + } + + layout.push(uv); + } + } + + // Read through the end of the ZIP entry so its checksum is checked + match reader.read_exact(&mut [0]) { + Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(layout), + Err(error) => Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}"))), + Ok(()) => Err(bad("the corner count does not match the entry size")), + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 481cb6d4..0fd677bf 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -100,6 +100,7 @@ struct GlobalsRaw { refr: [f32; 4], highlight: [f32; 4], highlight_shift: [f32; 4], + set_hover: [f32; 4], bake_high: [f32; 4], bake_matching_error: [f32; 4], bake_cage: [f32; 4], @@ -137,6 +138,9 @@ const HIGHLIGHT_WIDTH_PX: f32 = 1.5; /// Opacity of the highlighted set's edge lines const HIGHLIGHT_OPACITY: f32 = 0.9; +/// Opacity of the texture-set hover tint over the shaded material. +const SET_HOVER_OPACITY: f32 = 0.35; + /// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`) const HIGHLIGHT_SHIFTS: u32 = 4; @@ -194,6 +198,8 @@ pub struct Shade { pub wireframe_opacity: f32, /// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag) pub highlight: Option, + /// The texture set whose visible surfaces are tinted in the 3D view. + pub set_hover: Option, /// Specular/glossiness shading: base color is the diffuse color and the Specular channel the /// F0 color (roughness arrives as 1 - glossiness from the display conversion). pub spec_gloss: bool, @@ -308,6 +314,7 @@ impl Default for Shade { wireframe_3d: false, wireframe_opacity: 0.4, highlight: None, + set_hover: None, spec_gloss: false, parallax: false, taa: false, @@ -1941,8 +1948,8 @@ impl Renderer { ranges: &'a [(u32, u32, usize)], visible: &'a [bool], only: Option, - ) -> impl Iterator, &'a SetGpu)> + 'a { - drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?))) + ) -> impl Iterator, usize, &'a SetGpu)> + 'a { + drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, texture_set)| Some((range, texture_set, self.sets.get(texture_set)?))) } /// Keep the key-light shadow map current; returns its view-projection. `light` points to @@ -2003,7 +2010,7 @@ impl Renderer { let geo = m.dense.as_ref().filter(|_| displacing).unwrap_or(&m.geo); pass.set_vertex_buffer(0, geo.vb.slice(..)); pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&geo.draws, visible, None) { + for (range, _, set) in self.drawable(&geo.draws, visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2125,8 +2132,9 @@ impl Renderer { fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], - highlight: highlight_globals(s, data), + highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), + set_hover: highlight_globals(s.set_hover, SET_HOVER_OPACITY, s, data), ..bake_globals(s.bake) }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; @@ -2135,11 +2143,12 @@ impl Renderer { b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD], c: dof_c, d: sss_d, - e: [flag(cam.ortho), sample as f32, 0.0, 0.0], + e: [flag(cam.ortho), sample as f32, raw.set_hover[3], 0.0], back_top: [s.background[0][0], s.background[0][1], s.background[0][2], 0.0], back_bottom: [s.background[1][0], s.background[1][1], s.background[1][2], 0.0], }; let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; + queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post)); upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev)); @@ -2214,9 +2223,13 @@ impl Renderer { let geo = self.geometry(m, frame); pass.set_vertex_buffer(0, geo.vb.slice(..)); pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&geo.draws, &frame.visible, None) { + + // Instance index 1 lets the G-buffer mark the hovered set for the scattering composite + let hover_set = frame.shade.set_hover.filter(|_| frame.kind == ViewKind::Scene).map(|hover| hover.set); + for (range, texture_set, set) in self.drawable(&geo.draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..1); + let first_instance = u32::from(hover_set == Some(texture_set)); + pass.draw_indexed(range, 0, first_instance..first_instance + 1); } } @@ -2341,22 +2354,25 @@ impl Renderer { let bake = frame.shade.bake.filter(|_| uv_set.is_none()); let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown); let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip(); + let hover_set = frame.shade.set_hover.filter(|_| uv_set.is_none()).map(|hover| hover.set); // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1), - (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), - (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1, hover_set), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1, None), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS, None), ]; - for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + for (pipeline, vertices, indices, ranges, only_set, instances, hover_set) in passes { let Some(pipeline) = pipeline else { continue }; pass.set_pipeline(pipeline); pass.set_vertex_buffer(0, vertices.slice(..)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only_set) { + for (range, texture_set, set) in self.drawable(ranges, &frame.visible, only_set) { + // Instance index 1 lets the mesh shader tint the hovered draw + let first_instance = u32::from(hover_set == Some(texture_set)); pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..instances); + pass.draw_indexed(range, 0, first_instance..first_instance + instances); } } @@ -2370,7 +2386,7 @@ impl Renderer { pass.set_pipeline(&self.uv_missing_seam_pipeline); pass.set_vertex_buffer(0, mesh.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { + for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2404,7 +2420,7 @@ impl Renderer { pass.set_pipeline(&self.missing_seam_pipeline); pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) { + for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2541,12 +2557,12 @@ fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTar } } -/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is -fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { - let Some(highlight) = shade.highlight else { return [0.0; 4] }; +/// The highlight's color and opacity. Data views take the color as it is. +fn highlight_globals(highlight: Option, opacity: f32, shade: &Shade, data: bool) -> [f32; 4] { + let Some(highlight) = highlight else { return [0.0; 4] }; let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) }; - [r, g, b, HIGHLIGHT_OPACITY] + [r, g, b, opacity] } /// The globals of bake mode's overlays and neutral material for `bake` (all zero without it) @@ -2678,8 +2694,8 @@ mod tests { let color = [0.8, 0.25, 0.08]; let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() }; - assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); - assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping"); + assert_eq!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); + assert_ne!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, false)[..3], color, "the material view undoes exposure and tone mapping"); } #[test] diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs index cc29879e..574b5bbd 100644 --- a/crates/render/src/set_highlight.rs +++ b/crates/render/src/set_highlight.rs @@ -1,4 +1,4 @@ -//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag) +//! Texture-set highlighting in the 3D viewport. /// Brightest on-screen value the tone curve can reach without an infinite scene value const MAX_ACES_SCREEN_VALUE: f32 = 0.99; @@ -6,16 +6,16 @@ const MAX_ACES_SCREEN_VALUE: f32 = 0.99; /// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl) const ACES_INPUT_SCALE: f32 = 0.6; -/// Draw texture set `set`'s mesh edges over the 3D view in `color` +/// A texture set to highlight in the 3D viewport. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SetHighlight { pub set: usize, - /// The lines' color on screen, linear RGB + /// The highlight color on screen, linear RGB. pub color: [f32; 3], } impl SetHighlight { - /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] + /// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as [`Self::color`]. pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { scene_color_showing(self.color, exposure_ev, aces) } diff --git a/crates/render/src/shaders/fx.wgsl b/crates/render/src/shaders/fx.wgsl index 333664ce..36235a72 100644 --- a/crates/render/src/shaders/fx.wgsl +++ b/crates/render/src/shaders/fx.wgsl @@ -1,7 +1,6 @@ -// Scene effects between the scene pass and the post pass, appended to util.wgsl and post.wgsl -// (uses `src`, `src_samp`, `post`, `fx_a`): the screen-space subsurface blur and depth of field. -// Both read the G-buffer of `fs_gbuf` (mesh.wgsl): rgb the scattering part of the diffuse light, -// a the view depth (0: background). Colors are linear HDR premultiplied by scene coverage. +// Screen-space subsurface blur and depth of field run between the scene and post passes +// G-buffer RGB holds scattering light in linear HDR premultiplied by scene coverage +// G-buffer alpha holds view depth, with zero for background and a negative sign for hover @group(0) @binding(5) var fx_b: texture_2d; @group(0) @binding(6) var fx_c: texture_2d; @@ -31,19 +30,22 @@ fn px_per_world(z: f32) -> f32 { return select(post.d.w / max(z, 1e-4), post.d.w, post.e.x > 0.5); } -// One direction of the blur over `src` (rgb light, a depth) at pixel `p` (same-size target). +// The blur changes RGB and carries the centre's signed depth unchanged fn sss_blur(p: vec2, dir: vec2) -> vec4 { let c = texel_at(src, p); - let sigma = post.d.xyz * px_per_world(c.a); + let z = abs(c.a); + let sigma = post.d.xyz * px_per_world(z); let smax = max(sigma.r, max(sigma.g, sigma.b)); - if (c.a <= 0.0 || smax < 0.5) { + + if (z <= 0.0 || smax < 0.5) { return c; } + let stride = dir * (smax * 3.0 / f32(SSS_TAPS)); let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z)); let inv = 1.0 / (2.0 * sigma * sigma + vec3(1e-4)); - // Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient - // noise) and per accumulated frame turns what would show as copies of edges into fine grain. + + // Jitter the wide blur taps so copies of edges become fine grain let ign = fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); let jitter = fract(ign + post.e.y * 0.618034) - 0.5; var sum = c.rgb; @@ -52,30 +54,35 @@ fn sss_blur(p: vec2, dir: vec2) -> vec4 { if (k == 0) { continue; } + let o = f32(k) + jitter; let t = texel_at(src, p + stride * o); let x = o * smax * 3.0 / f32(SSS_TAPS); - let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0); + let tz = abs(t.a); + let wd = select(0.0, max(1.0 - abs(tz - z) / depth_range, 0.0), tz > 0.0); let w = exp(-x * x * inv); sum += mix(c.rgb, t.rgb, wd) * w; wsum += w; } + return vec4(sum / wsum, c.a); } -// src: the G-buffer. +// Read scattering light and depth from the G-buffer @fragment fn fs_sss_h(i: FsOut) -> @location(0) vec4 { return sss_blur(i.pos.xy, vec2(1.0, 0.0)); } -// src: the horizontal pass, fx_a: the scene (without its scattering light, see `fs_mesh`). Adds -// the blurred scattering light. +// Restore scattering light from the horizontal pass to the main scene in fx_a +// Apply hover opacity at the destination so neighbouring sets keep the light they receive @fragment fn fs_sss_v(i: FsOut) -> @location(0) vec4 { - let blurred = sss_blur(i.pos.xy, vec2(0.0, 1.0)).rgb; + let blurred = sss_blur(i.pos.xy, vec2(0.0, 1.0)); let scene = texel_at(fx_a, i.pos.xy); - return scene + vec4(blurred * clamp(scene.a, 0.0, 1.0), 0.0); + let scattering_weight = select(1.0, 1.0 - post.e.z, blurred.a < 0.0); + + return scene + vec4(blurred.rgb * scattering_weight * clamp(scene.a, 0.0, 1.0), 0.0); } // ---- Depth of field: a thin lens. Scatter-as-gather over a golden-angle spiral at half @@ -103,27 +110,28 @@ struct DofOut { @location(1) near: vec4, }; -// src: the scene (full resolution), fx_a: the G-buffer. +// Read full-resolution scene colors from src and depths from fx_a @fragment fn fs_dof_gather(i: FsOut) -> DofOut { let px = 1.0 / vec2(textureDimensions(src)); - let zc = texel(fx_a, i.uv).a; + let zc = abs(texel(fx_a, i.uv).a); let cc = abs(coc(zc)); let rmax = post.c.z; - // Half the spacing of the taps: the soft edge of each tap's reach. + + // Half the spacing of the taps softens the edge of each tap's reach let h = max(rmax * sqrt(PI_FX / f32(DOF_TAPS)) * 0.5, 0.5); var acc = textureSampleLevel(src, src_samp, i.uv, 0.0); var tot = 1.0; var near = 0.0; - // The spiral turns per pixel (interleaved gradient noise) and per accumulated frame, so the - // taps' pattern averages into smooth discs instead of showing as dots in bright highlights. + + // Rotate the taps per pixel and frame so bright highlights average into smooth discs let ign = fract(52.9829189 * fract(dot(i.pos.xy, vec2(0.06711056, 0.00583715)))); let turn = (ign + post.c.w * 0.618034) * 6.2831853; for (var k = 0; k < DOF_TAPS; k++) { let r = rmax * sqrt((f32(k) + 0.5) / f32(DOF_TAPS)); let a = f32(k) * GOLDEN_ANGLE + turn; let uv = i.uv + vec2(cos(a), sin(a)) * (r * px); - let z = texel(fx_a, uv).a; + let z = abs(texel(fx_a, uv).a); let nearer = z > 0.0 && (zc <= 0.0 || z < zc); var size = abs(coc(z)); if (!nearer) { @@ -136,20 +144,23 @@ fn fs_dof_gather(i: FsOut) -> DofOut { near = max(near, m * smoothstep(0.5, 1.5, size)); } } + return DofOut(acc / tot, vec4(near)); } const PI_FX: f32 = 3.14159265; -// src: the sharp scene, fx_a: the gathered blur, fx_b: the G-buffer, fx_c: the near coverage. +// Use G-buffer depth and near coverage to blend the half-resolution blur into the scene @fragment fn fs_dof(i: FsOut) -> @location(0) vec4 { let sharp = texel_at(src, i.pos.xy); - let f = max(smoothstep(0.5, 1.5, abs(coc(texel_at(fx_b, i.pos.xy).a))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r); - // In focus with nothing blurred in front: the sharp pixel itself (no blend through the - // half-resolution blur at all). - if (f <= 0.0) { + let depth = abs(texel_at(fx_b, i.pos.xy).a); + let blur_weight = max(smoothstep(0.5, 1.5, abs(coc(depth))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r); + + // Preserve the full-resolution pixel where no blur reaches it + if (blur_weight <= 0.0) { return sharp; } - return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), f); + + return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), blur_weight); } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 31fd19df..8e82daa9 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -26,6 +26,7 @@ struct Globals { refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - + set_hover: vec4, // rgb hovered set's scene color, a opacity bake_high: vec4, // bake mode: rgb high poly color, a - bake_matching_error: vec4, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden) bake_cage: vec4, // rgb cage surface color, a opacity @@ -70,6 +71,7 @@ struct VOut { @location(1) nrm: vec3, @location(2) tan: vec4, @location(3) uv: vec2, + @location(4) @interpolate(flat) hover: u32, }; // The vertex moved along its normal by the height channel (displacement). @@ -81,7 +83,7 @@ fn displaced(v: VIn) -> vec3 { } @vertex -fn vs_mesh(v: VIn) -> VOut { +fn vs_mesh(v: VIn, @builtin(instance_index) instance_index: u32) -> VOut { var o: VOut; let p = displaced(v); o.clip = g.view_proj * vec4(p, 1.0); @@ -89,6 +91,7 @@ fn vs_mesh(v: VIn) -> VOut { o.nrm = v.nrm; o.tan = v.tan; o.uv = v.uv; + o.hover = instance_index; return o; } @@ -350,16 +353,26 @@ fn unlit(c: vec4) -> Shaded { fn mesh_color(i: VOut, front: bool) -> vec4 { let o = shade_mesh(i, front); + + // The subsurface pass restores the scattering light after blurring if (g.scatter.w > 0.5) { - // The subsurface blur pass adds the scattering light back, blurred (fx.wgsl). return o.color - vec4(o.sss, 0.0); } + return o.color; } +const HOVERED_SET_INSTANCE: u32 = 1u; + @fragment fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { - return mesh_color(i, front); + let color = mesh_color(i, front); + + if (i.hover == HOVERED_SET_INSTANCE) { + return vec4(mix(color.rgb, g.set_hover.rgb * color.a, g.set_hover.a), color.a); + } + + return color; } // The scene behind transmissive surfaces: everything but them (what they refract). @@ -373,17 +386,23 @@ fn fs_opaque(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4 @location(0) vec4 { - let z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4); + var z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4); var sss = vec3(0.0); + if (g.scatter.w > 0.5) { sss = shade_mesh(i, front).sss; + if (i.hover == HOVERED_SET_INSTANCE) { + z = -z; + } } else if (textureSample(t_base, samp, i.uv).a < hash12(i.clip.xy)) { discard; } + return vec4(sss, z); } diff --git a/crates/render/src/shaders/post.wgsl b/crates/render/src/shaders/post.wgsl index e5df0cd8..df984040 100644 --- a/crates/render/src/shaders/post.wgsl +++ b/crates/render/src/shaders/post.wgsl @@ -7,7 +7,7 @@ struct Post { b: vec4, // x vignette, y sharpen, z grain, w bloom threshold c: vec4, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample d: vec4, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1 - e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw - + e: vec4, // x orthographic camera, y accumulation sample, z hover tint opacity for the scattering composite, w - back_top: vec4, // rgb background color at the top of the view (linear), a - back_bottom: vec4, // rgb background color at the bottom of the view (linear), a - }; diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 042a59c9..62c9aa0a 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1076,6 +1076,58 @@ fn subsurface_blur_spreads_only_scattering_light() { assert!((m1 - m0).abs() < 2.0, "the blur moves light, it adds none: {m0} -> {m1}"); } +#[test] +fn the_hover_tint_covers_the_blurred_scattering_light_too() { + let Some((mut h, frame)) = setup() else { return }; + + // Read coverage in the flat base-color view so lighting cannot hide a set at its edge + let base_color_view = shaded(&frame, |shade| shade.view_mode = 1); + let hovered_set_mask = mesh_mask(&mut h, &base_color_view, &[0]); + let neighbour_mask = mesh_mask(&mut h, &base_color_view, &[1]); + let lit = shaded(&frame, |s| s.light = LIGHT); + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[150, 150, 150, 255]); + fill(&mut h, &[0, 1], DisplayKind::Emissive, &[0, 0, 0, 255]); + + let blur = shaded(&lit, |s| s.sss_blur = Some([0.06, 0.024, 0.015])); + let hover = |frame: &Frame| shaded(frame, |s| s.set_hover = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] })); + let mean = |img: &Img| region_mean(&hovered_set_mask, |x, y| img.luma(x, y)); + let plain = mean(&render(&mut h, &lit, "hover_sss_plain")); + let blurred = mean(&render(&mut h, &blur, "hover_sss_blur")); + let hovered_blur = mean(&render(&mut h, &hover(&blur), "hover_sss_blur_hovered")); + let hovered_plain = mean(&render(&mut h, &hover(&lit), "hover_sss_plain_hovered")); + + assert!(hovered_plain != plain, "the hover tint changes the set"); + + // Hover must dim the light restored by the blur along with the rest of the material + assert!( + ((hovered_blur - hovered_plain) - (blurred - plain)).abs() < 1.0, + "the blur changes the plain set by {} and the hovered set by {}", + blurred - plain, + hovered_blur - hovered_plain + ); + + // Use a wide blur so scattering light crosses the boundary between the two sets + let wide = shaded(&lit, |s| s.sss_blur = Some([0.2, 0.08, 0.05])); + let blurred_img = render(&mut h, &wide, "hover_sss_wide"); + let hovered_blur_img = render(&mut h, &hover(&wide), "hover_sss_wide_hovered"); + + // Skip pixels that legitimately include samples of the hovered set after MSAA resolve + let width = blurred_img.w; + let mut checked = 0; + let mut worst_delta = 0.0f32; + for (index, &neighbour) in neighbour_mask.iter().enumerate() { + if neighbour && !hovered_set_mask[index] { + let (x, y) = (index as u32 % width, index as u32 / width); + let delta = (hovered_blur_img.luma(x, y) - blurred_img.luma(x, y)).abs(); + checked += 1; + worst_delta = worst_delta.max(delta); + } + } + + assert!(checked > 0, "the neighbour has pixels with no coverage from the hovered set"); + assert!(worst_delta <= 1.0, "hovering set 0 changes the neighbouring set by up to {worst_delta} luma across {checked} pixels"); +} + /// An environment that is bright only around `dir` (world space, rotation 0). fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes { let (w, hh) = (256u32, 128u32); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9abb472c..5b85a7fe 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -15,10 +15,12 @@ texturecraft-render = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } +craft-behavior = { workspace = true } craft-i18n = { workspace = true } craft-window = { workspace = true } craft-keymap = { workspace = true } -craft-quit = { workspace = true } +craft-host = { workspace = true } +craft-theme = { workspace = true } egui-phosphor = { version = "0.14", features = ["regular", "fill"] } serde = { workspace = true } serde_json = { workspace = true } @@ -31,12 +33,11 @@ craft-image-codecs = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] sys-locale = "0.3" -# Floating panels open as OS windows. -craft-ui = { workspace = true, features = ["native-windows"] } # Help > Check for Updates and the check at start (updates_ui.rs). craft-update = { workspace = true } # Native file dialogs (file_dialogs.rs); the browser build has none. craft-dialogs = { workspace = true } +tempfile = "3" # Whether the app runs in a real window, where an eyedropper pick may take clicks outside it (screen_pick). raw-window-handle = "0.6" diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3acf83a0..1efb19d3 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -61,7 +61,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { .collect(); ui.push_id(set_index, |ui| { - ui.horizontal(|ui| { + let row = ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() { app.run("textureSet.visible", json!({ "ts": set_index })); @@ -88,6 +88,10 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { } }); + if ui.is_enabled() && ui.rect_contains_pointer(row.response.rect) { + app.next_hovered_texture_set = Some((app.session.project_id, set_index)); + } + if !tiles.is_empty() { egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| { for (tile, override_resolution, enabled) in &tiles { diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs index 7c0bc14d..1f244d3e 100644 --- a/crates/ui-egui/src/display_settings.rs +++ b/crates/ui-egui/src/display_settings.rs @@ -287,7 +287,11 @@ mod tests { fn display_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_step_dt(0.01) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(crate::docking::Panel::Display); harness.run_steps(4); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5b5bc1af..901ef0d4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -78,6 +78,9 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { for (i, (name, size, visible)) in sets.into_iter().enumerate() { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name)); + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active)); + let p = ui.painter(); let bg = if i == active { tk.row_selected @@ -90,10 +93,18 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { if i == active { p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } + if resp.has_focus() { + p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside); + } + let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); + if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) { + app.next_hovered_texture_set = Some((app.session.project_id, i)); + } + // Narrow panels drop the shader label, then the resolution, before cutting the name let cy = rect.center().y; let mut right = rect.right() - 6.0; @@ -186,7 +197,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { /// rename, a number field) keeps the key for itself, and the key is left alone over other panels. fn select_all_layers(app: &mut TextureCraftApp, ui: &Ui) { let ctx = ui.ctx(); - if ctx.egui_wants_keyboard_input() || !ui.ui_contains_pointer() { + if crate::framework::widget_has_keyboard(ctx) || !ui.ui_contains_pointer() { return; } @@ -454,7 +465,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); - // Background, folder lines, the selected rows' accent edge and the colour tag let painter = ui.painter().clone(); // The active layer gets the strong tint; the other selected rows the plain selected shade @@ -550,14 +560,21 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { content_glyph(&painter, &tokens, thumbnail, layer); } + let content_label = tr("Select the layer content"); let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(content_label); painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); if content_response.clicked() { let modifiers = ui.input(|input| input.modifiers); click_layer(app, modifiers, layer.id.0, Some("content")); + + if !modifiers.alt && matches!(app.session.view, texturecraft_engine::ViewMode::Mask(_)) { + app.run("viewport.view", json!({"mode": "material"})); + } } + thumbnail_context_menu(ui, &content_response, content_label, &layer.name, content_target, |ui| layer_context_menu(app, ui, layer, true)); + x = thumbnail.right() + THUMBNAIL_SPACING; // An instance draws its source's content, blending and (unless it has its own) mask @@ -574,9 +591,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some((mask_enabled, mask_background, mask_effect_count)) = mask { + if let Some((mut mask_enabled, mask_background, mask_effect_count)) = mask { let mask_target = selected && !targets_content(app); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + let mask_label = tr("Select the mask (Alt+click: show it in the viewport, Shift+click: switch it on or off)"); + let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label); + if mask_response.clicked() { + let modifiers = ui.input(|input| input.modifiers); + if modifiers.shift && !modifiers.alt { + if app.run("mask.toggle", json!({"layer": layer.id.0})).is_some() { + mask_enabled = !mask_enabled; + mask_response.request_focus(); + } + } else { + app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); + + if modifiers.alt { + let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); + } + } + } + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled) { let white = mask_background == texturecraft_engine::core::MaskBackground::White; painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); @@ -594,17 +631,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if !mask_enabled { painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mask_label = tr("Select the mask (Alt+click: show it in the viewport)"); - let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label); - if mask_response.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|input| input.modifiers.alt) { - let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", view); - } - } + thumbnail_context_menu(ui, &mask_response, mask_label, &layer.name, mask_target, |ui| mask_management_menu(app, ui, layer, true)); + ui.ctx().accesskit_node_builder(mask_response.id, |node| node.set_description(if mask_enabled { tr("Mask on") } else { tr("Mask off") })); + if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { painter.rect_stroke( mask_rect.expand(HIGHLIGHT_OUTSET), @@ -627,6 +657,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize egui::Popup::menu(&slot).show(|ui| crate::layer_toolbar::mask_slot_menu(app, ui, layer, picker)); crate::layer_toolbar::bitmap_picker(app, &row, picker, layer.id); } + x = mask_rect.right() + THUMBNAIL_GAP; // Name (or rename editor) with the quieter subtitle under it @@ -3298,3 +3329,39 @@ mod layer_layout_tests { assert!(show_blend); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod texture_set_list_tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + use super::*; + + #[test] + fn keyboard_selection_updates_the_texture_set_list_items() { + let session = texturecraft_engine::Session::new_project( + "Texture set selection", + texturecraft_engine::geom::primitives::material_ball(), + "builtin:material_ball", + None, + 128, + ) + .unwrap(); + let first = session.doc.project.texture_sets[0].name.clone(); + let second = session.doc.project.texture_sets[1].name.clone(); + let mut harness = Harness::builder() + .with_size(vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ListItem, &second).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1); + assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &first).accesskit_node().is_selected(), Some(false)); + assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &second).accesskit_node().is_selected(), Some(true)); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index c900230b..6c4f5f97 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -1,18 +1,22 @@ //! The dock host: every side panel (assets, texture set list, layers, texture set settings, //! properties, display/shader settings, history, log) is a tab that can be docked, tabbed, -//! resized, floated and closed around the viewport. craft-ui's shared docking -//! (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews and -//! owns the gestures; this module names the panels, builds the default arrangement, applies -//! the dock's changes and hosts the panel bodies. The bodies live in `dock.rs`, `shelf.rs` and -//! `windows.rs`. +//! resized, floated and closed around the viewport. craft-ui's `DockArea` draws the frames, tab +//! strips, floating windows and drop previews and owns the gestures; this module names the +//! panels, builds the default arrangement, applies the dock's changes and hosts the panel bodies. +//! The bodies live in `dock.rs`, `shelf.rs` and `windows.rs`. //! //! The viewport is the central canvas: it stays docked, never takes tabs and is the only panel -//! that cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`; -//! a layout that does not load or validate becomes the default. +//! that cannot close or float. The layout persists with `UiState` as a craft-behavior +//! `Workspace`; a layout that does not load or validate becomes the default. -use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement}; -use craft_ui::layout::{SplitAxis, SplitSize}; -use egui::{Id, Margin, RichText, Ui, Vec2, vec2}; +use std::sync::Arc; + +use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions, SplitSize}; +use craft_behavior::flow::Axis; +use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use egui::{Margin, Rect, Ui, Vec2, ViewportId, vec2}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -20,11 +24,6 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -mod header_band; -mod shown_group_tab; - -pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Panel { Viewport, @@ -130,8 +129,8 @@ impl Panel { } } - /// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded. - fn float_rect(self) -> Option<[f32; 4]> { + /// Where the panel floats when it has never been laid out, cascaded. + fn float_rect(self) -> Option { let slot = match self { Panel::Display => 0.0, Panel::Shader => 1.0, @@ -142,24 +141,24 @@ impl Panel { Panel::BakingLog => 6.0, _ => return None, }; - Some([960.0, 90.0 + 50.0 * slot, 300.0, 380.0]) + Some(Rect::from_min_size(egui::pos2(960.0, 90.0 + 50.0 * slot), vec2(300.0, 380.0))) } } -/// The saved panel arrangement: craft-ui's workspace over TextureCraft's panels. -pub type Workspace = craft_ui::docking::Workspace; +/// The saved panel arrangement: craft-behavior's workspace over TextureCraft's panels. +pub type Workspace = craft_behavior::dock::Workspace; /// The viewport never moves, floats, closes or takes tabs; panels dock beside it. pub fn permissions(panel: &Panel) -> Permissions { - if *panel == Panel::Viewport { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() } + if *panel == Panel::Viewport { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() } } fn tabs(panels: &[Panel]) -> Node { - Node::Tabs { panels: panels.to_vec(), active: 0 } + Node::tabs(panels.to_vec(), 0) } -fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { - Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } +fn split(axis: Axis, size: SplitSize, first: Node, second: Node) -> Node { + Node::split(axis, size, first, second) } /// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties @@ -175,57 +174,41 @@ pub fn default_workspace() -> Workspace { const LAYERS_SPLIT_RATIO: f32 = 0.31; let column = split( - SplitAxis::Vertical, + Axis::Y, SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO), tabs(&[TextureSetList]), - split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + split(Axis::Y, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), ); let root = split( - SplitAxis::Horizontal, + Axis::X, SplitSize::Ratio(ASSETS_SPLIT_RATIO), tabs(&[Assets]), - split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), + split(Axis::X, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), ); - let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); - - for panel in Panel::ALL { - if let Some(rect) = panel.float_rect() { - workspace.hidden.push((panel, floating_location(rect))); - } - } - + let mut hidden: Vec<(Panel, Location)> = Panel::ALL.into_iter().filter_map(|panel| Some((panel, floating_location(panel.float_rect()?)))).collect(); for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { - workspace.hidden.push(( - panel, - Location { - floating: None, - anchor: Some(TextureSetList), - placement: Placement::Tab { before: None }, - size: None, - stack: None, - sibling: Vec::new(), - group: None, - }, - )); + hidden.push((panel, Location::new(Some(TextureSetList), DockPlacement::tab(None)))); } - workspace + Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new()) } -/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`) -fn floating_location(rect: [f32; 4]) -> Location { - Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None } +/// Where a closed panel reopens as its own floating window at `rect` +fn floating_location(rect: Rect) -> Location { + let mut location = Location::new(None, DockPlacement::tab(None)); + location.floating = Some(rect); + location } /// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group /// or collapse it. pub fn validate(workspace: &Workspace) -> Result<(), String> { workspace.validate().map_err(|error| error.to_string())?; - let layout = &workspace.layout; + let layout = workspace.layout(); if layout.floating.iter().any(|window| window.contains(&Panel::Viewport)) { return Err("The viewport cannot float".into()); } - if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Viewport) { + if workspace.hidden().iter().any(|(panel, _)| *panel == Panel::Viewport) { return Err("The viewport cannot be hidden".into()); } let mut found = false; @@ -242,7 +225,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { } found = true; } - Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => { + Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => { return Err("The viewport cannot be collapsed".into()); } Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Viewport)) => { @@ -269,7 +252,7 @@ const BAKING_LOG_HEIGHT: f32 = 160.0; /// Share of the first bake column the texture set list takes above the mesh map bakers const TEXTURE_SET_LIST_SHARE: f32 = 0.4; -/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`). +/// The dock layout (part of `UiState`; serialized as a craft-behavior `Workspace`). #[derive(Clone, Debug)] pub struct Dock { workspace: Workspace, @@ -327,24 +310,25 @@ impl Dock { /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { - let mut workspace = default_workspace(); + let painting = default_workspace(); + let mut hidden = painting.hidden().to_vec(); for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { - if let Ok(location) = workspace.layout.location(&panel) { - workspace.hidden.push((panel, location)); + if let Ok(location) = painting.layout().location(&panel) { + hidden.push((panel, location)); } } let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; - workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel)); + hidden.retain(|(panel, _)| !bake_panels.contains(panel)); let gutter_width = f32::from(crate::theme::GUTTER); - let list_column = split(SplitAxis::Vertical, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); + let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); - let columns = split(SplitAxis::Horizontal, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); - let columns_over_log = split(SplitAxis::Vertical, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); + let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; - let root = split(SplitAxis::Horizontal, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); - workspace.layout = Layout { root: Some(root), floating: Vec::new() }; + let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); + let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec()); Dock { workspace, raise: None, replaced_unreadable: false } } @@ -353,12 +337,12 @@ impl Dock { } pub fn is_open(&self, p: Panel) -> bool { - self.workspace.layout.contains(&p) + self.workspace.layout().contains(&p) } /// Open and the front tab of its group. pub fn is_visible(&self, p: Panel) -> bool { - self.workspace.layout.panel_state(&p) == PanelState::Front + self.workspace.layout().panel_state(&p) == PanelState::Front } /// Hide a visible panel, otherwise bring it up. @@ -367,7 +351,7 @@ impl Dock { } pub fn close(&mut self, p: Panel) { - if let Err(error) = self.workspace.set_visible(p, false, None, permissions) { + if let Err(error) = self.workspace.set_visible(p, false, None, false, permissions) { log::warn!("panel {p:?} was not closed: {error}"); } } @@ -376,7 +360,7 @@ impl Dock { /// front. pub fn focus(&mut self, p: Panel) { let mut next = self.workspace.clone(); - match next.set_visible(p, true, None, permissions) { + match next.set_visible(p, true, None, false, permissions) { Ok(()) if validate(&next).is_ok() => { self.workspace = next; self.raise = Some(p); @@ -386,10 +370,12 @@ impl Dock { } } - /// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`) - pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) { - self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel); - self.workspace.hidden.push((panel, floating_location(rect))); + /// Open the closed `panel` as a floating window at `rect` + pub(crate) fn float_at(&mut self, panel: Panel, rect: Rect) { + let mut hidden = self.workspace.hidden().to_vec(); + hidden.retain(|(hidden_panel, _)| *hidden_panel != panel); + hidden.push((panel, floating_location(rect))); + self.workspace = Workspace::from_parts(self.workspace.layout().clone(), hidden, self.workspace.floated().to_vec()); self.focus(panel); } @@ -397,7 +383,7 @@ impl Dock { /// it was. fn apply(&mut self, action: Action) { let mut next = self.workspace.clone(); - match next.apply(action, permissions) { + match next.apply(action, false, permissions) { Ok(_) if validate(&next).is_ok() => self.workspace = next, Ok(_) => log::warn!("a panel move would break the viewport's rules"), Err(error) => log::warn!("a panel move was not applied: {error}"), @@ -405,58 +391,76 @@ impl Dock { } } +/// What the dock area keeps between passes: the workspace it shows and the panels' specs. +#[derive(Default)] +pub(crate) struct LiveDock { + shown: Option>, + specs: Tracked, + /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window. + continue_move: Option<(Panel, egui::Vec2)>, +} + +impl LiveDock { + /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`. + pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) { + self.continue_move = Some((panel, grab)); + } + + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, + /// so an idle pass keeps the workspace's revision and the dock reads no spec. + fn shown(&mut self, workspace: &Workspace) -> Arc { + if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { + return Arc::clone(shown); + } + let shown = Arc::new(workspace.clone()); + self.shown = Some(Arc::clone(&shown)); + shown + } +} + +/// What the dock reads of the panels: their tab names, in [`Panel::ALL`] order. +#[derive(Clone, Debug, Default, PartialEq, PlainData)] +struct DockSpecs { + labels: Vec, +} + +impl PanelSpecs for DockSpecs { + fn spec(&self, panel: &Panel) -> PanelSpec { + let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default(); + // Every panel body is TextureCraft's own egui code: the dock runs it with the window's style. + let spec = PanelSpec::new(label).limits(SizeLimits::at_least(min_size(*panel))).float_size(FLOATING_SIZE.max(min_size(*panel))).host_body(); + if *panel == Panel::Viewport { spec.canvas() } else { spec } + } + + fn permissions(&self, panel: &Panel) -> Permissions { + permissions(panel) + } +} + +/// The tab name of `panel` in the interface language. +fn label(app: &TextureCraftApp, panel: Panel) -> String { + match panel { + Panel::Properties => crate::dock::properties_title(app), + p => tr(p.name()).to_string(), + } +} + +/// Reads the tab names, moving the specs' revision only when one changed. +fn refresh_specs(app: &mut TextureCraftApp) { + let labels: Vec = Panel::ALL.iter().map(|panel| label(app, *panel)).collect(); + if app.docks.specs.labels != labels { + app.docks.specs.labels = labels; + } +} + // --------------------------------------------------------------------------------------------- // Drawing -fn area_id() -> Id { - Id::unique("texturecraft-docking") -} +/// From a panel's left edge to its contents' text (an empty panel's note) +pub(crate) const HEADER_TITLE_LEFT: f32 = 12.0; -/// Smallest panel extent a divider drag leaves, in points -const MIN_PANE_EXTENT: f32 = 60.0; - -/// Border width of a floating panel, in points -const FLOATING_BORDER_WIDTH: f32 = 1.0; - -/// Text size of the panel tabs, in points -const TAB_TEXT_SIZE: f32 = 12.5; - -/// Narrowest panel tab, in points -const MIN_TAB_WIDTH: f32 = 54.0; - -/// Mixing in title ink keeps the light dock's focus outline above 3:1 on both header surfaces -const LIGHT_DOCK_ACCENT_TEXT_MIX: f32 = 0.2; - -/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right -fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { - let mut dock_style = DockStyle::from_ui(ui); - dock_style.gap = f32::from(crate::theme::GUTTER); - dock_style.min_pane = MIN_PANE_EXTENT; - - dock_style.background = tokens.panel; - dock_style.tab_background = tokens.chrome; - - // The selected title is brighter while the strip keeps its colour - dock_style.active_background = tokens.chrome; - dock_style.text = tokens.text_strong; - dock_style.inactive_text = tokens.text_dim; - dock_style.border = egui::Stroke::NONE; - dock_style.accent = if tokens.dark { tokens.accent } else { tokens.accent.lerp_to_gamma(tokens.text_strong, LIGHT_DOCK_ACCENT_TEXT_MIX) }; - dock_style.floating_background = tokens.panel; - dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border); - - dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE); - dock_style.min_tab_width = MIN_TAB_WIDTH; - dock_style.tab_height = TAB_HEIGHT; - - // Panels arrange in a split tree around the viewport; floating title bars only move windows - dock_style.new_dock_zones = false; - dock_style.title_bar_docks = false; - dock_style -} - -/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included, -/// do not take it. +/// Whether one of TextureCraft's own modal layers or the update dialogs hold the input, so the +/// panels floated into windows of their own do not take it (`FrameInput::app_modal`). pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool { let modal = context.memory(|memory| memory.top_modal_layer()).is_some(); #[cfg(not(target_arch = "wasm32"))] @@ -478,57 +482,84 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } let context = ui.ctx().clone(); - let tokens = Tokens::get(&context); - let style = style(ui, &tokens); - let layout = app.ui.dock.workspace.layout.clone(); - let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context)); - if let Some(panel) = app.ui.dock.raise.take() { - area = area.raise_panel(panel); - } - - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, layout: &layout, style: &style }); - crate::rail_popup::hand_drag_to_dock(&context, area_id()); + refresh_specs(app); + let shown = app.docks.shown(&app.ui.dock.workspace); + // The specs leave the app while its panels borrow it, and come back with their revision. + let specs = std::mem::take(&mut app.docks.specs); + let hand_over = app.docks.continue_move.take(); + let raise = app.ui.dock.raise.take(); + // Panels arrange in a split tree around the viewport; floating title bars only move windows. + // Each closable tab has its close button, as each group header had one for its shown panel. + let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true); + let (output, focused_windows) = { + let tokens = Tokens::get(&context); + let mut panels = Panels { app: &mut *app, tokens, layout: shown.layout().clone(), focused_windows: Vec::new() }; + let mut area = DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, config); + if let Some(hand_over) = hand_over { + area = area.continue_move(hand_over); + } + if let Some(panel) = raise { + area = area.raise(panel); + } + let output = area.show(ui); + (output, panels.focused_windows) + }; + app.docks.specs = specs; // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); + // Keys pressed in a panel floated into a window of its own run the app's shortcuts there #[cfg(not(target_arch = "wasm32"))] - crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); + for (_, viewport) in &output.windows { + let (events, held) = forwarded_events(&context, *viewport, &focused_windows); + crate::menus::forwarded_shortcuts(app, &context, events, held); + } + #[cfg(target_arch = "wasm32")] + let _ = focused_windows; if let Some(error) = &output.error { - log::warn!("docking: {error}"); + log::warn!("docking: {:?}", error.error); } // A layout changed by a panel takes priority over gestures from the old layout - if app.ui.dock.workspace.layout != layout { - craft_ui::docking::cancel_drag::(&context, area_id()); + if app.ui.dock.workspace != *shown { + craft_ui::runtime::drag::cancel(&context, craft_behavior::CancelReason::HostChanged); return; } - for action in output.actions { + for action in output.actions.into_iter().chain(output.requested) { app.ui.dock.apply(action); } } -/// Size of the panel names on a header bar -const HEADER_TITLE_SIZE: f32 = 12.0; - -/// Side of the close × at the right end of a header bar -const HEADER_CLOSE_SIZE: f32 = 22.0; - -/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter) -const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0; - -/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes) -fn header_closes(active: &Panel, floating: bool) -> bool { - !floating && permissions(active).closable +/// Records in `focused_windows` whether a widget of the running pass's window has the keyboard, after one of the window's +/// panels drew +fn note_focus(context: &egui::Context, focused_windows: &mut Vec) { + let window = context.viewport_id(); + focused_windows.retain(|focused| *focused != window); + if context.memory(|memory| memory.focused().is_some()) { + focused_windows.push(window); + } } -/// The panels' contents, names and limits for the dock area +/// The keys, text and clipboard events `window` hands to the app's shortcuts, with the modifiers held there: nothing +/// while one of its widgets has the keyboard +#[cfg(not(target_arch = "wasm32"))] +fn forwarded_events(context: &egui::Context, window: ViewportId, focused_windows: &[ViewportId]) -> (Vec, egui::Modifiers) { + use egui::Event; + let focused = focused_windows.contains(&window); + let forwarded = |event: &&Event| !focused && matches!(event, Event::Key { .. } | Event::Text(_) | Event::Copy | Event::Cut | Event::Paste(_)); + context.input_for(window, |input| (input.events.iter().filter(forwarded).cloned().collect(), input.modifiers)) +} + +/// The panels' contents for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, tokens: Tokens, - layout: &'a Layout, - style: &'a DockStyle, + /// The arrangement the dock shows in this pass + layout: Layout, + /// The windows in which a widget had the keyboard once their panels drew + focused_windows: Vec, } /// Room between a panel's edges and its contents @@ -594,100 +625,42 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { }); } -impl DockContent for Panels<'_> { - fn body(&mut self, ui: &mut Ui, panel: &Panel) { - if *panel == Panel::Viewport { - crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); - ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); - crate::viewport::central(self.app, ui); - return; +impl DockPanels for Panels<'_> { + fn body(&mut self, panel: &Panel, ui: &mut Ui, _: &mut BodyCx<'_>) { + // The viewport is its group's `group_view` + if *panel != Panel::Viewport { + panel_body(self.app, ui, *panel); } - - // Before the rows, which draw over the foot of the shown tab's box - self.paint_shown_group_tab(ui, *panel); - panel_body(self.app, ui, *panel); + note_focus(ui.ctx(), &mut self.focused_windows); } - fn logical_label(&self, panel: &Panel) -> String { - match panel { - Panel::Properties => crate::dock::properties_title(self.app), - p => tr(p.name()).to_string(), + /// The viewport, edge to edge in its group. + fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + let GroupAt::Show(rect) = at else { return None }; + if !panels.contains(&Panel::Viewport) { + return None; } + crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); + ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); + crate::viewport::central(self.app, ui); + Some(rect.height()) } - fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - // Capitals on the bar only: menus and screen readers keep the logical name - let name = logical.to_uppercase(); - let font = crate::theme::semibold(HEADER_TITLE_SIZE); - - // Popup menu rows use their unpadded text metrics - if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) { - return RichText::new(name).font(font).color(color).into(); + /// A rail panel floating on its own carries the Dock button that sends it back to the rail + fn group_header(&mut self, panels: &[Panel], active: usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + let Some(active) = panels.get(active).copied() else { return }; + let floating = self.layout.floating.iter().any(|window| window.contains(&active)); + if redocks(panels, &active, floating) + && crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() + { + self.app.ui.dock.close(active); } - - header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into() - } - - fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { - if header_closes(active, floating) { - HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN - } else if redocks(panels, active, floating) { - DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN - } else { - 0.0 - } - } - - /// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail - fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { - if redocks(panels, active, floating) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { - self.app.ui.dock.close(*active); - } - }); - return; - } - - if !header_closes(active, floating) { - return; - } - - // Centre the close control on the header title line - let rect = ui.max_rect(); - let button = egui::Rect::from_center_size( - egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)), - vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE), - ); - let clicked = ui - .scope_builder(egui::UiBuilder::new().max_rect(button), |ui| { - crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked() - }) - .inner; - if clicked { - self.app.ui.dock.close(*active); - } - } - - fn permissions(&self, panel: &Panel) -> Permissions { - permissions(panel) - } - - fn limits(&self, panel: &Panel) -> PanelLimits { - PanelLimits { min: min_size(*panel), ..PanelLimits::default() } - } - - fn floating_size(&self, panel: &Panel) -> Option { - Some(FLOATING_SIZE.max(min_size(*panel))) } } -/// Size of the Dock button in a floating rail panel's tab strip +/// Size of the Dock button in a floating rail panel's header const DOCK_BUTTON_SIZE: f32 = 22.0; -/// Room right of the Dock button, so it clears the strip's end -const DOCK_BUTTON_MARGIN: f32 = 6.0; - /// Whether a floating window holds one rail panel alone: its Dock button closes it back onto the rail fn redocks(panels: &[Panel], active: &Panel, floating: bool) -> bool { floating && panels.len() == 1 && crate::rail_popup::is_rail_panel(*active) @@ -698,7 +671,60 @@ mod tests { use super::*; fn panels_of(w: &Workspace) -> Vec { - w.layout.panels().into_iter().copied().collect() + w.layout().panels().into_iter().copied().collect() + } + + /// What a floating panel's own window with a text field, focused when `typing`, hands on of `events` + #[cfg(not(target_arch = "wasm32"))] + fn handed_on(typing: bool, events: &[egui::Event]) -> Vec { + use std::{cell::RefCell, rc::Rc}; + + let window = ViewportId::from_hash_of("floating panel"); + let context = egui::Context::default(); + context.set_embed_viewports(false); + + // Runs the window's pass inside its parent's, as eframe does + let arriving = Rc::new(RefCell::new(Vec::new())); + let queued = Rc::clone(&arriving); + egui::Context::set_immediate_viewport_renderer(move |context, viewport| { + let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() }); + let mut output = context.run_ui(input, viewport.viewport_ui_cb); + output.textures_delta.clear(); + }); + + let mut name = String::new(); + let mut handed_on = Vec::new(); + // The field takes the keyboard a pass before the keys arrive + for arrived in [Vec::new(), events.to_vec()] { + *arriving.borrow_mut() = arrived; + let mut output = context.run_ui(egui::RawInput::default(), |ui| { + let mut focused_windows = Vec::new(); + ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |ui, _| { + let field = ui.text_edit_singleline(&mut name); + if typing { + field.request_focus(); + } + note_focus(ui.ctx(), &mut focused_windows); + }); + handed_on.extend(forwarded_events(ui.ctx(), window, &focused_windows).0); + }); + output.textures_delta.clear(); + } + + assert_eq!(name.is_empty(), !typing, "a focused field types the text"); + handed_on + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_floating_panel_hands_on_its_keys_unless_a_field_there_has_the_keyboard() { + use egui::{Event, Key, Modifiers}; + + let key = Event::Key { key: Key::B, physical_key: Some(Key::B), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let keys = [key, Event::Text("b".into()), Event::Paste("pasted".into())]; + assert!(handed_on(true, &keys).is_empty(), "the field's keys are its own"); + assert_eq!(handed_on(false, &keys), keys, "with nothing focused they are the app's"); } #[test] @@ -708,7 +734,10 @@ mod tests { assert!(validate(&workspace).is_ok()); for panel in Panel::ALL { - assert!(workspace.layout.contains(&panel) || workspace.hidden.iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden"); + assert!( + workspace.layout().contains(&panel) || workspace.hidden().iter().any(|(hidden, _)| *hidden == panel), + "{panel:?} is neither shown nor hidden" + ); } assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); @@ -716,12 +745,14 @@ mod tests { #[test] fn a_saved_split_keeps_its_own_share() { - let mut workspace = default_workspace(); - let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") }; + let default = default_workspace(); + let mut layout = default.layout().clone(); + let Some(Node::Split { second: right, .. }) = layout.root.as_mut() else { panic!("assets | rest") }; let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") }; let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") }; let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; *size = SplitSize::Ratio(0.57); + let workspace = Workspace::from_parts(layout, default.hidden().to_vec(), default.floated().to_vec()); let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); @@ -770,7 +801,23 @@ mod tests { let dock = Dock::from_value(saved); assert!(!dock.replaced_unreadable(), "the saved layout is kept"); - assert!(dock.workspace().hidden.iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed"); + assert!(dock.workspace().hidden().iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed"); + } + + #[test] + fn a_focused_panel_is_raised_for_one_frame() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = egui_kittest::Harness::builder() + .with_size(vec2(1600.0, 1200.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + let dock = &mut harness.state_mut().ui.dock; + dock.focus(Panel::Display); + assert_eq!(dock.raise, Some(Panel::Display)); + + harness.run_steps(4); + + assert_eq!(harness.state().ui.dock.raise, None); } #[test] @@ -779,8 +826,8 @@ mod tests { dock.close(Panel::Viewport); assert!(dock.is_open(Panel::Viewport)); let before = dock.clone(); - dock.apply(Action::Float { panel: Panel::Viewport, rect: [0.0, 0.0, 300.0, 300.0] }); - dock.apply(Action::Move { panel: Panel::Layers, anchor: Panel::Viewport, placement: Placement::Tab { before: None } }); + dock.apply(Action::float(Panel::Viewport, Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0)))); + dock.apply(Action::move_beside(Panel::Layers, Panel::Viewport, DockPlacement::tab(None))); assert_eq!(dock, before); } @@ -804,8 +851,8 @@ mod tests { let mut dock = Dock::default(); dock.focus(Panel::Display); assert!(dock.is_visible(Panel::Display)); - assert_eq!(dock.workspace().layout.floating.len(), 1); - assert!(dock.workspace().layout.floating[0].contains(&Panel::Display)); + assert_eq!(dock.workspace().layout().floating.len(), 1); + assert!(dock.workspace().layout().floating[0].contains(&Panel::Display)); // Hiding and showing the views one by one. dock.toggle(Panel::Display); assert!(!dock.is_open(Panel::Display)); diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs deleted file mode 100644 index 3cbd77d9..00000000 --- a/crates/ui-egui/src/docking/header_band.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Positions dock tab titles within the tab strip and the gutter above it. - -use craft_ui::docking::{Layout, Node}; -use craft_ui::layout::SplitAxis; -use egui::text::{LayoutJob, TextFormat}; -use egui::{Align, Color32, FontId, Ui}; - -use super::Panel; - -/// Gap left between a header band and the panel above it, in points. -const HEADER_SEPARATION: f32 = 2.0; - -/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation -pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - HEADER_SEPARATION; - -/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none -pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { - layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(false) -} - -fn group_is_below_panel(node: &Node, panel: Panel, below_panel: bool) -> Option { - match node { - Node::Split { axis, first, second, .. } => { - group_is_below_panel(second, panel, below_panel || *axis == SplitAxis::Vertical).or_else(|| group_is_below_panel(first, panel, below_panel)) - } - Node::Tabs { panels, .. } if panels.contains(&panel) => Some(below_panel), - Node::Dock { columns, .. } => { - columns.iter().find_map(|column| column.groups.iter().position(|group| group.panels.contains(&panel))).map(|index| below_panel || index > 0) - } - _ => None, - } -} - -/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders) -pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift_points: f32) -> LayoutJob { - let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() }; - let mut job = LayoutJob::single_section(name.to_owned(), format); - let galley = ui.painter().layout_job(job.clone()); - - // Scripts without capitals use the whole galley as their ink bounds - let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph))); - let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0); - - // Room below the name raises it when centred, room above lowers it - let shift = ink_middle - galley.size().y / 2.0 + lift_points; - if shift < 0.0 - && let Some(section) = job.sections.first_mut() - { - section.format.valign = Align::BOTTOM; - } - - job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); - job -} diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs deleted file mode 100644 index 2080d530..00000000 --- a/crates/ui-egui/src/docking/shown_group_tab.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! The active tab in a panel group, drawn as a raised box joined to the panel body - -use craft_ui::docking::{DockContent, Node}; -use egui::text::TextWrapping; -use egui::{Rect, Stroke, StrokeKind, Ui, pos2}; - -use super::header_band::{HEADER_RISE, header_name, under_a_panel}; -use super::{HEADER_TITLE_SIZE, Panel, Panels, area_id}; -use crate::property_sheet::{full_height_tab_rect, shown_tab_box}; -use crate::theme::semibold; - -/// Horizontal padding of craft-ui's dock tab, in points -const DOCK_TAB_PADDING: f32 = 24.0; - -/// From a panel's left edge to its header's name -pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0; - -/// Gap between the active tab's box and its neighbours, in points -const TAB_BOX_INSET: f32 = 4.0; - -/// Insets the focus outline inside the tab's actual hit rect -const TAB_FOCUS_INSET: f32 = 2.0; - -/// Width of the focus outline in points -const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0; - -/// The tab group containing `panel`; a collapsed stack has no tabs -fn group_of(node: &Node, panel: Panel) -> Option<&[Panel]> { - match node { - Node::Split { first, second, .. } => group_of(first, panel).or_else(|| group_of(second, panel)), - Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels), - Node::Dock { columns, .. } => { - columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.as_slice()) - } - _ => None, - } -} - -impl Panels<'_> { - /// How far a header band reaches above its tab strip - fn header_rise(&self, panel: Panel) -> f32 { - if under_a_panel(self.layout, panel) { HEADER_RISE } else { 0.0 } - } - - /// How far a header name sits above the tab strip's centre - pub(super) fn header_lift(&self, panel: Panel) -> f32 { - self.header_rise(panel) / 2.0 - } - - /// Paints the active tab and its focus outline above the renderer's fallback paint - pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { - let layout = self.layout; - let in_group = layout - .root - .iter() - .chain(layout.floating.iter().map(|window| &window.root)) - .find_map(|root| group_of(root, panel)) - .is_some_and(|group| group.len() > 1); - if !in_group { - return; - } - - // The shared renderer submits the active tab before it calls the panel body - let tab_id = area_id().with(("tab", &panel)); - let Some(tab) = ui.ctx().read_response(tab_id) else { return }; - let body = ui.max_rect(); - let tab_rect = tab.rect; - if tab.layer_id != ui.layer_id() || tab_rect.bottom() != body.top() || tab_rect.left() < body.left() || tab_rect.right() > body.right() { - return; - } - - let band_top = tab_rect.top() - self.header_rise(panel); - let box_left = if tab_rect.left() > body.left() { tab_rect.left() + TAB_BOX_INSET } else { tab_rect.left() }; - let box_right = tab_rect.right() - TAB_BOX_INSET; - if box_left >= box_right { - return; - } - - // Extend the body's clip over the header without widening it - let clip = ui.clip_rect(); - let mut painter = ui.painter().clone(); - painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band_top..=clip.bottom())); - let band = Rect::from_x_y_ranges(body.x_range(), band_top..=tab_rect.bottom()); - shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, box_right)); - - let name = self.logical_label(&panel).to_uppercase(); - let font = semibold(HEADER_TITLE_SIZE); - let mut job = header_name(ui, &name, font, self.style.text, (tab_rect.top() - band_top) / 2.0); - job.wrap = TextWrapping::truncate_at_width((tab_rect.width() - DOCK_TAB_PADDING).max(0.0)); - let galley = painter.layout_job(job); - let at = pos2(tab_rect.left() + HEADER_TITLE_LEFT, tab_rect.center().y - galley.size().y / 2.0); - painter.galley(at, galley, self.style.text); - - // Preserve the shared dock's keyboard focus ring above the opaque selected tab - let pointer_focus = ui.data(|data| data.get_temp::(tab_id.with("pointer-focus"))).unwrap_or(false); - let focus_rect = tab_rect.shrink(TAB_FOCUS_INSET); - if tab.has_focus() && !pointer_focus && focus_rect.is_positive() { - painter.rect_stroke(focus_rect, 0.0, Stroke::new(TAB_FOCUS_STROKE_WIDTH, self.style.accent), StrokeKind::Inside); - } - } -} diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 3832919c..a7ece23a 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1751,8 +1751,10 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } } }); - // The app can consume Escape before the popup sees it, so read the raw event - let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + // The app's shortcuts can consume Escape before the popup sees it, so read the raw event too; the runtime keeps an + // Escape nothing of TextureCraft's has focus for as the window's cancel, which the framework reads + let escaped = crate::framework::escape_pressed(ui.ctx()) + || ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); if picked.is_some() || escaped || shown.is_none_or(|menu| menu.response.should_close()) { *pending = None; } diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs index 0a81e9bc..468b57fd 100644 --- a/crates/ui-egui/src/file_dialogs.rs +++ b/crates/ui-egui/src/file_dialogs.rs @@ -6,7 +6,6 @@ use std::panic::Location; use std::path::PathBuf; -use std::sync::Arc; pub use craft_dialogs::{Answer, FileDialog, Override, Request}; @@ -57,7 +56,7 @@ impl FileDialogs { /// The dialogs of the app whose context is `ctx`: an answer wakes its event loop. pub fn new(ctx: egui::Context) -> FileDialogs { FileDialogs { - dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), + dialogs: craft_dialogs::Dialogs::new(craft_dialogs::Wake::new(move || ctx.request_repaint())), asked: Vec::new(), headless: false, shown_folders: Vec::new(), @@ -162,6 +161,7 @@ impl TextureCraftApp { let paths = match answer { Answer::Paths(paths) => paths, + Answer::Saved { path, .. } => vec![path], Answer::Unavailable(why) => { self.toast(trf("The file dialog couldn't be shown: {error}", &[("error", &why)]), true); Vec::new() diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b31b423a..95080619 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -161,7 +161,7 @@ impl UiFonts { defs.families.entry(family).or_default().push(name.clone()); } } - ctx.set_fonts(defs); + crate::theme::load_fonts(ctx, defs); self.installed = want; } diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs index 6dd6bd18..d4978f71 100644 --- a/crates/ui-egui/src/frame_gizmo.rs +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -5,8 +5,8 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_pattern}; use texturecraft_engine::compose::frame_placement::folded; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; -use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection}; -use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection, Source}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; use crate::TextureCraftApp; use crate::projection_gizmo::{Gizmo, dragging}; @@ -14,8 +14,10 @@ use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, use crate::viewport::{project, view_ray}; mod frame_grab; +pub(crate) mod warp_toolbar; pub(crate) use frame_grab::FrameGrab; +use warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings, to_step}; /// The selected fill's frame as the 3D view shows it #[derive(Clone, Copy, Debug)] @@ -35,11 +37,16 @@ pub(crate) struct FrameGizmo { pub arrows: [Option; 3], /// On screen, the turn ring round the centre in the frame's plane (None when it is edge on) pub ring: Option<[Pos2; TURN_RING_POINTS]>, + /// A warp's tool bar settings: which handles show, their size and snapping, and the space the arrows move in + pub tools: Option, /// In the world: the frame's centre, and its across, up and out directions origin: Vec3, axes: [Vec3; 3], /// Screen movement per world unit along each direction at the centre steps: [Option; 3], + /// The directions the arrows move along (the frame's own, or the world's in World space) and their screen movement per world unit + move_axes: [Vec3; 3], + move_steps: [Option; 3], } /// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others @@ -61,47 +68,20 @@ const MIN_SIDE_STRETCH: f32 = 0.02; /// The least distance from the centre a resize drag measures from, so a press on the centre never divides by zero (points) pub(crate) const MIN_HANDLE_REACH: f32 = 1.0; -impl FrameGizmo { - /// The frame as the 3D view shows it: none while the Projection row's eye hides the projection gizmos - pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { - FrameGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) +/// An unplaced axis planar can acquire a frame only if placing it preserves its pattern. +fn placeable_projection<'a>(projection: &'a Projection, sources: impl Iterator) -> Option<&'a Projection> { + let unplaced = matches!(projection, Projection::Planar { placed: None, .. }); + if unplaced && placing_moves_pattern(sources) { + return None; } + Some(projection) +} + +impl FrameGizmo { /// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { - use texturecraft_engine::StackTarget; - - if app.ui.mode != crate::state::Mode::Painting { - return None; - } - - let layers = &app.session.doc.project; - let selected = app.session.selected_layer()?; - let (layer, effect, projection, sources) = match app.session.target { - StackTarget::Content => { - let layer = layers.content_layer(selected)?; - let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; - - (layer.id, None, projection, sources.values().collect::>()) - } - StackTarget::Effect(effect) => { - // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask - let owner = layers.mask_owner(selected); - let mask = layers.layer(owner).ok()?.mask.as_ref()?; - let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; - let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; - - (owner, Some(effect), projection, vec![source]) - } - StackTarget::Mask => return None, - }; - - // An axis planar reading a pattern keeps its axis (see [`placing_moves_pattern`]): it has no frame to move - let unplaced = matches!(projection, Projection::Planar { placed: None, .. }); - if unplaced && placing_moves_pattern(sources.into_iter()) { - return None; - } - + let (layer, effect, projection) = selected_fill_projection(app)?; let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh)); // Match the panel by folding the projector transform into the frame first @@ -113,7 +93,7 @@ impl FrameGizmo { }; let (origin, across, up, out) = decal_axes(&decal)?; - // The corners on screen: a warp's pulled ones, or the frame's own + // Warp corners can sit away from the frame corners let at = |[x, y]: [f32; 2]| project(app, rect, origin + across * x * decal.size[0] + up * y * decal.size[1]); let corners = match warp { Some([top_left, top_right, bottom_right, bottom_left]) => [at(top_left)?, at(top_right)?, at(bottom_right)?, at(bottom_left)?], @@ -126,29 +106,35 @@ impl FrameGizmo { let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5)); let center = project(app, rect, origin)?; - // Screen movement per world unit along each direction, and an arrow along each one not pointing at the camera + let tools = warp.map(|_| app.ui.warp_toolbar); + let manipulator_scale = tools.map_or(1.0, |tools| tools.gizmo_scale()); + let show_move = tools.is_none_or(|tools| tools.mode == GizmoMode::Move); + let show_ring = tools.is_none_or(|tools| tools.mode == GizmoMode::Rotate); + + // Arrows use the same screen steps as the drag let reach = decal.size[0].max(decal.size[1]); let axes = [across, up, out]; - let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE))); - let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + let step_along = |axis: Vec3| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE)); + let steps = axes.map(step_along); + let (move_axes, move_steps) = if show_move && tools.is_some_and(|tools| tools.space == GizmoSpace::World) { + let world_axes = [Vec3::X, Vec3::Y, Vec3::Z]; + (world_axes, world_axes.map(step_along)) + } else { + (axes, steps) + }; + let arrows = if show_move { + move_steps + .map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW * manipulator_scale)) + } else { + [None; 3] + }; - // The turn ring, unless the frame is seen too near edge on to grab it - let ring = steps[0] - .zip(steps[1]) - .filter(|(across_step, up_step)| { - across_step.length() > f32::EPSILON && solve(*across_step, *up_step, egui::Vec2::X).is_some() && ring_open(app, rect, center, out) - }) - .and_then(|(step, _)| { - let radius = TURN_RING / step.length(); - let last = (TURN_RING_POINTS - 1) as f32; - let points = (0..TURN_RING_POINTS).map(|index| { - let (sin, cos) = (index as f32 / last * std::f32::consts::TAU).sin_cos(); - project(app, rect, origin + (across * cos + up * sin) * radius) - }); - points.collect::>>()?.try_into().ok() - }); + // The ring can still project when an arrow's endpoint is behind the camera + let ring_radius = TURN_RING * manipulator_scale; + let ring = + if show_ring && ring_open(app, rect, center, out, ring_radius) { turn_ring(app, rect, center, origin, across, up, ring_radius) } else { None }; - Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps }) + Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, tools, origin, axes, steps, move_axes, move_steps }) } /// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on) @@ -157,6 +143,16 @@ impl FrameGizmo { Some(self.slid(across, up)) } + /// The tool bar's grid step and angle step (0: no snapping) while a drag snaps + fn snap_steps(&self, snapping: bool) -> (f32, f32) { + self.tools.filter(|_| snapping).map_or((0.0, 0.0), |tools| (tools.grid_step(), tools.angle_step())) + } + + /// Whether the tool bar's mode offers `grab` (a planar's frame, with no tool bar, offers every handle but Place on surface's) + fn offers(&self, grab: FrameGrab) -> bool { + self.tools.map_or(grab != FrameGrab::Place, |tools| grab.offered_in(tools.mode)) + } + /// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> { let ray = view_ray(app, rect, p); @@ -178,6 +174,36 @@ impl FrameGizmo { } } +/// The selected fill layer or mask effect and its projection, if eligible to show a frame in Painting mode +fn selected_fill_projection(app: &TextureCraftApp) -> Option<(LayerId, Option, &Projection)> { + use texturecraft_engine::StackTarget; + + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; + + Some((layer.id, None, placeable_projection(projection, sources.values())?)) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; + + Some((owner, Some(effect), placeable_projection(projection, std::iter::once(source))?)) + } + StackTarget::Mask => None, + } +} + /// Half a turn in degrees: a ring drag's sweep is kept within one either way const HALF_TURN: f32 = 180.0; @@ -190,12 +216,53 @@ pub(crate) const EDGE_ON_FACING: f32 = 1e-4; /// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0; -/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre -const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING; +/// A ring seen edge-on reads as a line until its foreshortened radius clears its stroke. +pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3, radius_points: f32) -> bool { + view_ray(app, rect, center).dir.dot(axis).abs() >= (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / radius_points +} -/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab -pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool { - view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING +/// Project a circle in the frame's plane with the requested screen reach in points +fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, across: Vec3, up: Vec3, radius_points: f32) -> Option<[Pos2; TURN_RING_POINTS]> { + const RING_SEGMENTS: usize = TURN_RING_POINTS - 1; + + let view_projection = app.session.camera.view_proj(rect.width() / rect.height().max(1.0)); + let center_clip = view_projection * origin.extend(1.0); + let center_ndc = center_clip / center_clip.w; + let half_size = rect.size() * 0.5; + + // The z component tracks how the perspective divisor changes per world unit + let screen_step = |axis: Vec3| { + let clip_step = (view_projection * axis.extend(0.0)) / center_clip.w; + let ndc_numerator = clip_step - center_ndc * clip_step.w; + Vec3::new(ndc_numerator.x * half_size.x, -ndc_numerator.y * half_size.y, clip_step.w) + }; + let across_step = screen_step(across); + let up_step = screen_step(up); + let ring_steps: [Vec3; RING_SEGMENTS] = std::array::from_fn(|index| { + let (sin, cos) = (index as f32 / RING_SEGMENTS as f32 * std::f32::consts::TAU).sin_cos(); + across_step * cos + up_step * sin + }); + + // Solve radius * length(xy) / (1 + radius * z) <= radius_points for every sample + let limiting_growth = ring_steps.iter().map(|step| step.truncate().length() - radius_points * step.z).fold(0.0, f32::max); + if !limiting_growth.is_finite() || limiting_growth <= f32::EPSILON { + return None; + } + + let radius = radius_points / limiting_growth; + let mut ring = [center; TURN_RING_POINTS]; + for (point, step) in ring.iter_mut().zip(ring_steps) { + let depth = 1.0 + radius * step.z; + if !depth.is_finite() || depth <= f32::EPSILON { + return None; + } + + *point += vec2(step.x, step.y) * (radius / depth); + } + + ring[RING_SEGMENTS] = ring[0]; + + Some(ring) } /// `delta` as a mix of screen steps `across_step` and `up_step` (None when they are parallel on screen) @@ -226,6 +293,7 @@ pub(crate) fn nearest(handles: impl IntoIterator) -> O best = Some((handle, distance)); } } + best.map(|(handle, _)| handle) } @@ -244,37 +312,54 @@ impl Gizmo for FrameGizmo { /// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows fn grab(&self, at: Pos2) -> Option { - let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))]; - handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); - let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at))); - match self.warp { - Some(_) => handles.extend(near(self.corners, FrameGrab::Corner)), - None => handles.extend(near(self.corners, |_| FrameGrab::Scale)), - } - handles.extend(near(self.sides, FrameGrab::Side)); - if let Some(ring) = &self.ring { - handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min))); - } - nearest(handles) + let slide = self.offers(FrameGrab::Slide).then(|| (FrameGrab::Slide, center_distance(self.center, at))); + let arrows = self.arrows.into_iter().enumerate().filter_map(|(axis, tip)| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, tip?)))); + let corners = self.corners.into_iter().enumerate().map(|(index, corner)| { + let grab = if self.warp.is_some() { FrameGrab::Corner(index) } else { FrameGrab::Scale }; + (grab, corner.distance(at)) + }); + let sides = self.sides.into_iter().enumerate().filter_map(|(index, side)| { + let grab = FrameGrab::Side(index); + self.offers(grab).then(|| (grab, side.distance(at))) + }); + let turn = self.ring.as_ref().map(|ring| { + let distance = ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min); + (FrameGrab::Turn, distance) + }); + + // Place on surface takes any press the handles do not: just within reach, so a nearer corner wins + let place = self.offers(FrameGrab::Place).then_some((FrameGrab::Place, GRAB)); + nearest(slide.into_iter().chain(arrows).chain(corners).chain(sides).chain(turn).chain(place)) } fn same_projection(&self, other: &FrameGizmo) -> bool { - self.layer == other.layer && self.effect == other.effect + self.layer == other.layer && self.effect == other.effect && self.warp.is_some() == other.warp.is_some() } /// The command and params a drag of `grab` from `from` to `to` runs fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + self.edit_with_snap(app, rect, grab, from, to, false) + } + + /// As [`Gizmo::edit`]; with `snapping` a warp's moves and turns jump by the tool bar's grid and angle steps + fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2, snapping: bool) -> Option<(&'static str, Value)> { let delta = to - from; let center = self.center; + let (grid_step, angle_step) = self.snap_steps(snapping); + let world = self.tools.is_some_and(|tools| tools.space == GizmoSpace::World); + let mut params = match grab { - FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}), + FrameGrab::Slide => { + let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?; + json!({"offset": self.slid(to_step(across, grid_step), to_step(up, grid_step))}) + } FrameGrab::Axis(axis) => { - let step = (*self.steps.get(axis)?)?; - let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + let step = (*self.move_steps.get(axis)?)?; + let distance_world = to_step(delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE), grid_step); match axis { - 0 => json!({"offset": self.slid(distance, 0.0)}), - 1 => json!({"offset": self.slid(0.0, distance)}), - _ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}), + 0 if !world => json!({"offset": self.slid(distance_world, 0.0)}), + 1 if !world => json!({"offset": self.slid(0.0, distance_world)}), + _ => json!({"position": (self.origin + self.move_axes[axis] * distance_world).to_array(), "normal": self.axes[2].to_array()}), } } FrameGrab::Scale => { @@ -288,12 +373,25 @@ impl Gizmo for FrameGizmo { size[1 - side % 2] *= stretch; json!({"size": size}) } + FrameGrab::Place => { + let on_view = to - rect.min; + let hit = app.session.pick(Vec2::new(on_view.x, on_view.y), app.session.viewport)?; + let project = &app.session.doc.project; + let (owner_set, _, _) = project.locate(self.layer)?; + + // A world-space placement must belong to the edited fill's texture set + if hit.material != project.texture_set(owner_set).ok()?.material { + return None; + } + + json!({"position": hit.pos.to_array(), "normal": hit.nrm.to_array()}) + } FrameGrab::Turn => { // Measure the turn in the frame's own plane so a tilted frame follows the pointer let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); let swept = angle(to)? - angle(from)?; let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; - json!({"rotation": self.decal.rotation + swept}) + json!({"rotation": self.decal.rotation + to_step(swept, angle_step)}) } FrameGrab::Corner(corner) => { let mut corners = self.warp?; @@ -303,10 +401,12 @@ impl Gizmo for FrameGizmo { json!({"warpCorners": corners}) } }; + params["layer"] = json!(self.layer.0); if let Some(effect) = self.effect { params["effect"] = json!(effect.0); } + let command = if matches!(grab, FrameGrab::Corner(_)) { "layer.fill.projection" } else { "layer.decal.set" }; Some((command, params)) } @@ -325,14 +425,16 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; - let mut outline = gizmo.corners.to_vec(); - outline.push(gizmo.corners[0]); + let [first, second, third, fourth] = gizmo.corners; + let outline = [first, second, third, fourth, first]; dashed_outline(&painter, &outline); + if let Some(ring) = &gizmo.ring { let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] }; painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color))); } + match gizmo.warp { Some(_) => { for (index, corner) in gizmo.corners.into_iter().enumerate() { @@ -345,12 +447,15 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { } } } - for (index, side) in gizmo.sides.into_iter().enumerate() { + + for (index, side) in gizmo.sides.into_iter().enumerate().filter(|(index, _)| gizmo.offers(FrameGrab::Side(*index))) { handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index))); } let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; - move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); + if gizmo.offers(FrameGrab::Slide) { + move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); + } } /// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's @@ -418,11 +523,17 @@ pub(crate) mod tests { let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW); let builder = if render { builder.wgpu() } else { builder }; - let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = builder.with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); harness } + /// A warp's gizmo in `mode`, as the tool bar's buttons set it (a planar's has no modes) + pub(crate) fn show_handles(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, mode: GizmoMode) { + harness.state_mut().ui.warp_toolbar.mode = mode; + harness.run_steps(2); + } + /// The ball with a selected fill layer projecting `projection` pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { fill_app_with(json!({"projection": projection})) @@ -519,7 +630,7 @@ pub(crate) mod tests { ["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32) } - fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { + pub(crate) fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() } @@ -645,6 +756,7 @@ pub(crate) mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); for kind in ["warp", "planar"] { let (mut harness, _) = fill_app(kind); + show_handles(&mut harness, GizmoMode::Rotate); let start = gizmo(&harness); let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring")); let on_ring = *ring @@ -667,6 +779,7 @@ pub(crate) mod tests { } let (mut harness, layer) = fill_app("warp"); + show_handles(&mut harness, GizmoMode::Scale); let warp = gizmo(&harness); assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); @@ -676,6 +789,112 @@ pub(crate) mod tests { assert_eq!(corners, Projection::FRAME_CORNERS, "its corners stay where they are on the frame"); } + /// The longest reach stays near the intended screen radius as the camera orbits. + #[test] + fn the_ring_keeps_its_screen_size_at_oblique_angles() { + const MAX_RING_SHARE: f32 = 1.25; + const MIN_RING_SHARE: f32 = 0.6; + const ORBIT_DEGREES: [f32; 6] = [0.0, 40.0, 60.0, 75.0, 80.0, 84.0]; + const ZOOM_OUT_EXPONENT: f32 = 1.5; + const MAX_FORESHORTENED_ACROSS_TO_UP_RATIO: f32 = 0.4; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["planar", "warp"] { + let (mut harness, _) = fill_app(kind); + show_handles(&mut harness, GizmoMode::Rotate); + let mut foreshortened_shown = false; + + // A distant view isolates the foreshortening + harness.state_mut().session.camera.zoom(-ZOOM_OUT_EXPONENT); + for degrees in ORBIT_DEGREES { + harness.state_mut().session.camera.set_angles(degrees.to_radians(), 0.0); + harness.run_steps(2); + + let shown = gizmo(&harness); + let Some(ring) = shown.ring else { continue }; + let reach = ring.iter().map(|at| at.distance(shown.center)).fold(0.0, f32::max); + let across_step = shown.steps[0].unwrap().length(); + let up_step = shown.steps[1].unwrap().length(); + + assert!( + (TURN_RING * MIN_RING_SHARE..=TURN_RING * MAX_RING_SHARE).contains(&reach), + "{kind} orbited {degrees} degrees: the ring reaches {reach} points" + ); + + foreshortened_shown |= across_step < up_step * MAX_FORESHORTENED_ACROSS_TO_UP_RATIO; + } + + assert!(foreshortened_shown, "{kind}: the ring was checked with the across direction foreshortened"); + } + } + + #[test] + fn an_oblique_warp_ring_opens_when_its_scaled_height_clears_the_stroke() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + show_handles(&mut harness, GizmoMode::Rotate); + let camera = &mut harness.state_mut().session.camera; + camera.ortho = true; + camera.set_angles(87.0_f32.to_radians(), 0.0); + let base_size = harness.state().ui.warp_toolbar.manipulator_size; + + harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 0.5; + let small = gizmo(&harness); + harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 2.0; + let large = gizmo(&harness); + + assert!(small.ring.is_none(), "a ring narrower than its stroke stays hidden"); + let ring = large.ring.expect("the enlarged ring clears its stroke at the same angle"); + assert!(ring.iter().any(|point| large.grab(*point) == Some(FrameGrab::Turn))); + } + + #[test] + fn the_ring_keeps_its_screen_size_when_the_oblique_frame_is_turning_near_the_camera() { + const FRAME_SIDE: f32 = 4.0; + const LARGE_FRAME_SIDE: f32 = 5.0; + const CAMERA_DISTANCE: f32 = 4.0; + const ORBIT_DEGREES: f32 = 65.0; + const EDGE_ON_ANGLE: f32 = std::f32::consts::FRAC_PI_2; + const MIN_RING_SHARE: f32 = 0.75; + const MAX_RING_SHARE: f32 = 1.25; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["planar", "warp"] { + let (mut harness, layer) = fill_app(kind); + show_handles(&mut harness, GizmoMode::Rotate); + let expected_radius = if kind == "warp" { + harness.state_mut().ui.warp_toolbar.manipulator_size *= 2.0; + TURN_RING * 2.0 + } else { + TURN_RING + }; + let camera = &mut harness.state_mut().session.camera; + camera.distance = CAMERA_DISTANCE; + camera.set_angles(ORBIT_DEGREES.to_radians(), 0.0); + + // Reverse the frame axes, then put a large frame's across step behind the camera + for (rotation_degrees, side) in [(-45.0, FRAME_SIDE), (135.0, FRAME_SIDE), (0.0, LARGE_FRAME_SIDE)] { + let size = [side; 2]; + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "size": size, "rotation": rotation_degrees})).unwrap(); + harness.run_steps(2); + + let shown = gizmo(&harness); + let ring = shown.ring.unwrap_or_else(|| panic!("{kind} turned {rotation_degrees} degrees: the oblique ring should show")); + let reach = ring.iter().map(|point| point.distance(shown.center)).fold(0.0, f32::max); + + assert!( + (expected_radius * MIN_RING_SHARE..=expected_radius * MAX_RING_SHARE).contains(&reach), + "{kind} turned {rotation_degrees} degrees: the ring reaches {reach} points" + ); + } + + harness.state_mut().session.camera.set_angles(EDGE_ON_ANGLE, 0.0); + harness.run_steps(2); + + assert!(gizmo(&harness).ring.is_none(), "{kind}: hide the ring when the frame is edge-on"); + } + } + /// Losing the focus mid-drag (Alt+Tab) ends a frame drag as a release does: one undo step, and moves after it (egui still has the button down) leave the frame alone #[test] fn losing_the_window_focus_ends_a_frame_drag() { @@ -748,6 +967,38 @@ pub(crate) mod tests { harness.run_steps(2); } + #[test] + fn a_place_drag_ends_if_the_project_or_projection_is_replaced() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for replace_project in [true, false] { + let (mut harness, layer) = fill_app("warp"); + show_handles(&mut harness, GizmoMode::PlaceOnSurface); + let center = gizmo(&harness).center; + let held = center + vec2(24.0, 8.0); + press_and_move(&mut harness, center, held, Modifiers::NONE); + let start = std::sync::Arc::downgrade(&dragging::(&harness.ctx).unwrap().start); + + let next_kind = if replace_project { + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 128})).unwrap(); + let new_layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap(); + assert_eq!(new_layer["layer"], layer.0, "the new project reuses the local layer ID"); + "warp" + } else { + "planar" + }; + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": next_kind})).unwrap(); + let before = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + harness.event(egui::Event::PointerMoved(held + vec2(8.0, 8.0))); + harness.run_steps(2); + + assert_eq!(projection(&harness, layer), before, "the old drag must not move the replacement {next_kind}"); + assert_eq!(harness.state().session.history_labels().len(), steps); + assert!(start.upgrade().is_none(), "release the captured geometry while the pointer is still held"); + } + } + /// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it #[test] fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() { @@ -840,7 +1091,7 @@ pub(crate) mod tests { click(&mut harness, eye.center()); assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); - assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + assert!(crate::projection_gizmo::ShownGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); let before = projection(&harness, layer); drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); diff --git a/crates/ui-egui/src/frame_gizmo/frame_grab.rs b/crates/ui-egui/src/frame_gizmo/frame_grab.rs index a0733168..2d31d18d 100644 --- a/crates/ui-egui/src/frame_gizmo/frame_grab.rs +++ b/crates/ui-egui/src/frame_gizmo/frame_grab.rs @@ -1,3 +1,5 @@ +use super::warp_toolbar::GizmoMode; + /// What a drag on the frame does #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum FrameGrab { @@ -13,15 +15,29 @@ pub(crate) enum FrameGrab { Corner(usize), /// The ring: turn it round its normal Turn, + /// Place on surface: anywhere over the model puts the frame where the pointer touches it + Place, } impl FrameGrab { + /// Whether a warp's gizmo in `mode` offers this handle: its corners stay in every mode + pub(super) fn offered_in(self, mode: GizmoMode) -> bool { + match self { + FrameGrab::Slide | FrameGrab::Axis(_) => mode == GizmoMode::Move, + FrameGrab::Turn => mode == GizmoMode::Rotate, + FrameGrab::Side(_) => mode == GizmoMode::Scale, + FrameGrab::Place => mode == GizmoMode::PlaceOnSurface, + FrameGrab::Scale | FrameGrab::Corner(_) => true, + } + } + pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon { match self { FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing, FrameGrab::Slide => egui::CursorIcon::Grab, FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move, FrameGrab::Scale => egui::CursorIcon::ResizeNwSe, + FrameGrab::Place => egui::CursorIcon::Crosshair, FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical, FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal, } diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs new file mode 100644 index 00000000..e7c3b50a --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// What a warp's frame gizmo does: Move shows the arrows and centre square, Rotate the turn ring, Scale the edge dots that size the frame; Place on surface puts the frame where a drag over the model touches it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GizmoMode { + #[default] + Move, + Rotate, + Scale, + PlaceOnSurface, +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs new file mode 100644 index 00000000..a33269d7 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +/// The directions a warp's move arrows follow: the frame's own, or the world's +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GizmoSpace { + #[default] + Object, + World, +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs new file mode 100644 index 00000000..042f4f39 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs @@ -0,0 +1,380 @@ +//! The warp controls of the top tool bar while the selected fill projects through a warp, in place of the tool's own: the transform tool's settings, the warp mode, the gizmo's mode and space, the mirrors and the resets + +mod gizmo_mode; +mod gizmo_space; +mod snap; +mod warp_target; +mod warp_toolbar_settings; + +use egui::Ui; +use egui_phosphor::regular as ic; +use serde_json::json; + +pub use gizmo_mode::GizmoMode; +pub use gizmo_space::GizmoSpace; +pub(crate) use snap::to_step; +pub use warp_toolbar_settings::WarpToolbarSettings; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::toolbar::icon_dropdown; +use crate::widgets::{icon_button, icon_dropdown_button}; +use texturecraft_engine::core::Projection; +pub(crate) use warp_target::WarpTarget; +use warp_toolbar_settings::{ANGLE_STEPS, GRID_STEPS, MANIPULATOR_SIZES}; + +/// The width of the settings popup (points) +const POPUP_WIDTH: f32 = 220.0; + +/// The gizmo mode buttons: mode, icon, label +const MODES: [(GizmoMode, &str, &str); 4] = [ + (GizmoMode::Move, ic::ARROWS_OUT_CARDINAL, "Move"), + (GizmoMode::Rotate, ic::ARROWS_CLOCKWISE, "Rotate"), + (GizmoMode::Scale, ic::CORNERS_OUT, "Scale"), + (GizmoMode::PlaceOnSurface, ic::ARROW_LINE_DOWN, "Place on surface"), +]; + +/// The warp modes the bar lists; only the first works until the warp has a grid of vertices +const WARP_MODES: [&str; 5] = ["Transform warp", "Edit vertices", "Split both directions", "Split horizontally", "Split vertically"]; + +/// Why the warp modes past the first and the vertex reset are greyed out +const NEEDS_GRID: &str = "Needs the warp grid, which is not available yet"; + +/// The warp controls of the top tool bar, left to right +pub(crate) fn controls(app: &mut TextureCraftApp, ui: &mut Ui, target: WarpTarget) { + let size = ui.spacing().interact_size.y; + + // The only tool there is, so it stays on + icon_button(ui, ic::BOUNDING_BOX, tr("Transform tool"), true, size); + manipulator_settings(app, ui, size); + warp_mode(ui); + ui.separator(); + + let current = app.ui.warp_toolbar.mode; + for (mode, icon, label) in MODES { + if icon_button(ui, icon, tr(label), current == mode, size).clicked() { + app.ui.warp_toolbar.mode = mode; + } + } + gizmo_space(app, ui); + ui.separator(); + + for (axis, icon, label, field) in [(0, ic::FLIP_HORIZONTAL, "Mirror horizontally", "flipU"), (1, ic::FLIP_VERTICAL, "Mirror vertically", "flipV")] { + if icon_button(ui, icon, tr(label), target.flip[axis], size).clicked() { + let mut fields = json!({}); + fields[field] = json!(!target.flip[axis]); + app.run("layer.decal.set", target.params(fields)); + } + } + resets(app, ui, &target); +} + +/// The settings popup of the transform tool: the gizmo's size and the steps its drags snap to +fn manipulator_settings(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let popup_id = ui.make_persistent_id("warp_manipulator_settings"); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let response = icon_dropdown_button(ui, ic::GEAR, tr("Manipulator settings"), open, size); + let response = if open { response } else { response.on_hover_text(tr("Manipulator settings")) }; + + // Sliders sit in the popup, so a click inside must not close it + egui::Popup::menu(&response).id(popup_id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_width(POPUP_WIDTH); + ui.label(egui::RichText::new(tr("MANIPULATOR SETTINGS")).strong()); + + let settings = &mut app.ui.warp_toolbar; + ui.add(egui::Slider::new(&mut settings.manipulator_size, MANIPULATOR_SIZES).text(tr("Manipulator size")).fixed_decimals(2)); + ui.add(egui::Slider::new(&mut settings.grid_steps, GRID_STEPS).text(tr("Grid steps")).fixed_decimals(2)) + .on_hover_text(tr("Hold Ctrl while dragging to move in these steps")); + ui.add(egui::Slider::new(&mut settings.angle_steps, ANGLE_STEPS).text(tr("Angle steps")).fixed_decimals(0)) + .on_hover_text(tr("Hold Ctrl while dragging to turn in these steps")); + }); +} + +/// The warp mode list: Transform warp works; the others wait for the warp grid +fn warp_mode(ui: &mut Ui) { + icon_dropdown(ui, "warp_mode", ic::FRAME_CORNERS, tr(WARP_MODES[0]), |ui| { + for (index, label) in WARP_MODES.into_iter().enumerate() { + let unavailable = (index > 0).then(|| tr(NEEDS_GRID)); + menu_row(ui, tr(label), index == 0, unavailable); + } + }); +} + +/// Object space or World space: the directions the move arrows follow +fn gizmo_space(app: &mut TextureCraftApp, ui: &mut Ui) { + let spaces = [(GizmoSpace::Object, ic::CUBE, "Object space"), (GizmoSpace::World, ic::GLOBE, "World space")]; + let current = app.ui.warp_toolbar.space; + let (_, icon, label) = spaces.iter().find(|(space, ..)| *space == current).unwrap_or(&spaces[0]); + let mut chosen = None; + icon_dropdown(ui, "warp_space", icon, tr(label), |ui| { + for (space, _, label) in spaces { + if menu_row(ui, tr(label), current == space, None) { + chosen = Some(space); + } + } + }); + + if let Some(space) = chosen { + app.ui.warp_toolbar.space = space; + } +} + +/// The reset list: the frame back around the mesh, or the corners back on the frame +fn resets(app: &mut TextureCraftApp, ui: &mut Ui, target: &WarpTarget) { + let mut command = None; + icon_dropdown(ui, "warp_reset", ic::ARROW_COUNTER_CLOCKWISE, tr("Reset"), |ui| { + if menu_row(ui, tr("Reset warp transform"), false, None) { + command = Some(("layer.fill.resetFrame", json!({"keepCorners": true}))); + } + if menu_row(ui, tr("Reset all vertices"), false, None) { + command = Some(("layer.fill.projection", json!({"warpCorners": Projection::FRAME_CORNERS}))); + } + + // Vertices cannot be selected before the warp has a grid + menu_row(ui, tr("Reset selected vertices"), false, Some(tr(NEEDS_GRID))); + }); + + if let Some((id, fields)) = command { + app.run(id, target.params(fields)); + } +} + +/// One list entry; `unavailable` greys it out and says why on hover. Returns true when clicked +fn menu_row(ui: &mut Ui, label: &str, selected: bool, unavailable: Option<&str>) -> bool { + let response = ui.add_enabled(unavailable.is_none(), egui::Button::new(label).selected(selected)); + if let Some(reason) = unavailable { + response.on_disabled_hover_text(reason); + return false; + } + + response.clicked() +} + +#[cfg(test)] +mod tests { + use egui::accesskit::Role; + use egui::{Modifiers, Pos2, vec2}; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + use serde_json::json; + use texturecraft_engine::core::Projection; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + use super::*; + use crate::frame_gizmo::FrameGrab; + use crate::frame_gizmo::tests::{drag, fill_app, gizmo, projection}; + use crate::projection_gizmo::Gizmo; + + fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(2); + } + + /// The warp's frame and corners + fn warp_parts(harness: &Harness<'_, TextureCraftApp>, layer: texturecraft_engine::core::LayerId) -> (texturecraft_engine::core::Decal, [[f32; 2]; 4]) { + let Projection::Warp { frame, corners, .. } = projection(harness, layer) else { panic!("a warp") }; + (frame, corners) + } + + #[test] + fn the_bar_shows_for_a_warp_fill_only() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + assert!(harness.query_by_label("Transform tool").is_some()); + + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "planar"})); + harness.run_steps(2); + + assert!(harness.query_by_label("Transform tool").is_none(), "a planar frame has no warp tools"); + + let away = harness.state().viewport_rect.left_bottom() + vec2(10.0, -10.0); + assert_eq!(gizmo(&harness).grab(away), None, "a planar frame has no Place on surface"); + } + + #[test] + fn each_mode_offers_only_its_handles() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let start = gizmo(&harness); + click_label(&mut harness, "Rotate"); + let ring = gizmo(&harness).ring.expect("a frame facing the camera shows its ring"); + let ring_point = *ring.iter().max_by(|first, second| first.y.total_cmp(&second.y)).unwrap(); + let handles: [(FrameGrab, Pos2, GizmoMode); 4] = [ + (FrameGrab::Slide, start.center, GizmoMode::Move), + (FrameGrab::Axis(0), start.arrows[0].unwrap(), GizmoMode::Move), + (FrameGrab::Turn, ring_point, GizmoMode::Rotate), + (FrameGrab::Side(1), start.sides[1], GizmoMode::Scale), + ]; + + for (_, _, label) in MODES { + click_label(&mut harness, label); + let shown = gizmo(&harness); + let mode = shown.tools.unwrap().mode; + + for (grab, at, offered_in) in handles { + assert_eq!(shown.grab(at) == Some(grab), mode == offered_in, "{grab:?} in {mode:?}"); + } + + assert_eq!(shown.grab(shown.corners[1]), Some(FrameGrab::Corner(1)), "a warp's corners stay in {mode:?}"); + } + } + + #[test] + fn place_on_surface_puts_the_frame_where_the_pointer_touches_the_model() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let rect = harness.state().viewport_rect; + let middle = crate::viewport::project(harness.state(), rect, Vec3::ZERO).unwrap(); + let (from, onto) = (middle + vec2(30.0, 20.0), middle + vec2(-60.0, -40.0)); + let steps = harness.state().session.history_labels().len(); + let (before, corners_before) = warp_parts(&harness, layer); + click_label(&mut harness, "Place on surface"); + + drag(&mut harness, from, onto, Modifiers::NONE); + + let (placed, corners) = warp_parts(&harness, layer); + let on_view = onto - rect.min; + let hit = harness.state().session.pick(Vec2::new(on_view.x, on_view.y), harness.state().session.viewport).expect("the model is under the pointer"); + assert!(Vec3::from(placed.center).distance(hit.pos) < 1e-2, "the frame centre sits at the surface hit: {:?} {:?}", placed.center, hit.pos); + assert!(Vec3::from(placed.normal).dot(hit.nrm) > 0.99, "the frame faces along the surface normal"); + assert_eq!((placed.size, placed.rotation, corners), (before.size, before.rotation, corners_before), "its size, rotation and corners stay"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per drag"); + + // Past the model's edge the frame waits where it last touched it + drag(&mut harness, onto, rect.left_bottom() + vec2(10.0, -10.0), Modifiers::NONE); + + let (waiting, _) = warp_parts(&harness, layer); + assert!((Vec3::from(waiting.center).length() - 1.0).abs() < 0.05, "still on the ball: {:?}", waiting.center); + } + + #[test] + fn place_on_surface_keeps_a_warp_on_its_own_texture_set() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mesh = texturecraft_engine::geom::primitives::material_ball(); + let session = texturecraft_engine::Session::new_project("Warp placement", mesh, "builtin:material_ball", None, 128).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "projection": "warp"})).unwrap(); + harness.run_steps(2); + click_label(&mut harness, "Place on surface"); + + let app = harness.state(); + let rect = app.viewport_rect; + let frame = gizmo(&harness); + let on_other_set = |point: Pos2| { + let local = point - rect.min; + app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport).is_some_and(|set| set != app.session.ts()) + }; + let movement = vec2(12.0, 0.0); + let rows = (0..rect.height() as usize).step_by(8); + let columns = (0..rect.width() as usize).step_by(8); + let mut candidates = rows.flat_map(|y| columns.clone().map(move |x| rect.min + vec2(x as f32, y as f32))); + let from = candidates + .find(|point| frame.grab(*point) == Some(FrameGrab::Place) && (0..=4).all(|step| on_other_set(*point + movement * (step as f32 / 4.0)))) + .expect("a drag entirely on the material ball's other set"); + let layer = frame.layer; + let before = projection(&harness, layer); + let steps = app.session.history_labels().len(); + + drag(&mut harness, from, from + movement, Modifiers::NONE); + + assert_eq!(projection(&harness, layer), before, "the foreign surface must not take the warp"); + assert_eq!(harness.state().session.history_labels().len(), steps); + } + + #[test] + fn world_space_arrows_ignore_the_frames_turn() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let turn = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30})); + harness.run_steps(2); + }; + let arrow = |harness: &Harness<'_, TextureCraftApp>| { + let shown = gizmo(harness); + (shown.arrows[0].unwrap() - shown.center).normalized() + }; + let frame_arrow = arrow(&harness); + turn(&mut harness); + + assert!(arrow(&harness).dot(frame_arrow) < 0.95, "an object space arrow turns with the frame"); + + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 0})); + click_label(&mut harness, "Object space"); + click_label(&mut harness, "World space"); + let world_arrow = arrow(&harness); + turn(&mut harness); + + assert!(arrow(&harness).dot(world_arrow) > 0.999, "a world space arrow stays on its world axis"); + } + + #[test] + fn holding_ctrl_moves_in_whole_grid_steps() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let grid_step = harness.state().ui.warp_toolbar.grid_step(); + let start = gizmo(&harness); + let tip = start.arrows[0].unwrap(); + let along = (tip - start.center).normalized(); + + // On macOS Ctrl is independent of the platform Command modifier + drag(&mut harness, tip, tip + along * 37.0, Modifiers::CTRL); + + let (frame, _) = warp_parts(&harness, layer); + let steps = frame.offset[0] / grid_step; + assert!(frame.offset[0].abs() > 1e-3 && (steps - steps.round()).abs() < 1e-3, "moved by whole steps of {grid_step}: {:?}", frame.offset); + } + + #[test] + fn keyboard_changes_the_warp_drag_steps() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let before = harness.state().ui.warp_toolbar.grid_step(); + click_label(&mut harness, "Manipulator settings"); + harness.get_by_role_and_label(Role::Slider, "Grid steps").focus(); + harness.run_steps(2); + + harness.key_press(egui::Key::ArrowRight); + harness.run_steps(2); + + assert!(harness.get_by_role_and_label(Role::Slider, "Grid steps").is_focused()); + assert!(harness.state().ui.warp_toolbar.grid_step() > before); + assert!(harness.query_by_role_and_label(Role::Slider, "Angle steps").is_some()); + } + + #[test] + fn the_mirror_and_reset_buttons_edit_the_warp_in_one_undo_step_each() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + let (fitted, _) = warp_parts(&harness, layer); + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled})); + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30})); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + + click_label(&mut harness, "Mirror horizontally"); + + assert_eq!(warp_parts(&harness, layer).0.flip, [true, false]); + + click_label(&mut harness, "Mirror vertically"); + click_label(&mut harness, "Mirror horizontally"); + + assert_eq!(warp_parts(&harness, layer).0.flip, [false, true], "each button toggles its own direction"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3); + + click_label(&mut harness, "Reset"); + click_label(&mut harness, "Reset warp transform"); + + let (frame, corners) = warp_parts(&harness, layer); + assert_eq!((frame, corners), (fitted, pulled), "the frame goes back and the corners stay"); + + click_label(&mut harness, "Reset"); + click_label(&mut harness, "Reset all vertices"); + + assert_eq!(warp_parts(&harness, layer).1, Projection::FRAME_CORNERS); + assert_eq!(harness.state().session.history_labels().len(), steps + 5); + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs new file mode 100644 index 00000000..0245e81f --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs @@ -0,0 +1,24 @@ +/// `value` rounded to the nearest multiple of `step`; no step (0, negative or not a number) leaves it as it is +pub(crate) fn to_step(value: f32, step: f32) -> f32 { + if step.is_finite() && step > 0.0 { (value / step).round() * step } else { value } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_snaps_to_the_nearest_multiple_of_the_step() { + assert!((to_step(0.29, 0.2) - 0.2).abs() < 1e-6); + assert!((to_step(0.31, 0.2) - 0.4).abs() < 1e-6); + assert!((to_step(-0.31, 0.2) + 0.4).abs() < 1e-6, "negative moves snap the same way"); + assert_eq!(to_step(100.0, 45.0), 90.0); + } + + #[test] + fn no_step_leaves_the_value_alone() { + for step in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(to_step(0.37, step), 0.37, "{step}"); + } + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs new file mode 100644 index 00000000..d14286ba --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs @@ -0,0 +1,34 @@ +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, Projection}; + +use crate::TextureCraftApp; +use crate::frame_gizmo::selected_fill_projection; + +/// The selected fill with a warp projection that the tool bar edits: a fill layer, or a fill effect in its mask +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct WarpTarget { + pub layer: LayerId, + pub effect: Option, + /// The image mirrored left to right and top to bottom inside the frame + pub flip: [bool; 2], +} + +impl WarpTarget { + /// The selected fill when it projects through a warp, in the modes where the frame gizmo shows + pub(crate) fn of(app: &TextureCraftApp) -> Option { + let (layer, effect, projection) = selected_fill_projection(app)?; + let Projection::Warp { frame, .. } = projection else { return None }; + + Some(WarpTarget { layer, effect, flip: frame.flip }) + } + + /// `fields` addressed to this fill, as every command that edits a fill's projection takes it + pub(super) fn params(&self, mut params: Value) -> Value { + params["layer"] = json!(self.layer.0); + if let Some(effect) = self.effect { + params["effect"] = json!(effect.0); + } + + params + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs new file mode 100644 index 00000000..f6debfb6 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs @@ -0,0 +1,63 @@ +use std::ops::RangeInclusive; + +use serde::{Deserialize, Serialize}; + +use super::{GizmoMode, GizmoSpace}; + +/// The manipulator size the gizmo's measurements are given at +pub(super) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.2; +pub(super) const MANIPULATOR_SIZES: RangeInclusive = 0.1..=0.5; + +/// The default and range of the move step (world units) and of the turn step (degrees) +pub(super) const DEFAULT_GRID_STEP: f32 = 0.2; +pub(super) const GRID_STEPS: RangeInclusive = 0.01..=1.0; +pub(super) const DEFAULT_ANGLE_STEP: f32 = 45.0; +pub(super) const ANGLE_STEPS: RangeInclusive = 1.0..=90.0; + +/// The warp tool bar's settings: the gizmo's mode, space and size, and the steps its drags snap to while Ctrl is held +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct WarpToolbarSettings { + pub mode: GizmoMode, + pub space: GizmoSpace, + /// Manipulator size: [`DEFAULT_MANIPULATOR_SIZE`] draws the gizmo at its base size + pub manipulator_size: f32, + /// Move step in world units + pub grid_steps: f32, + /// Turn step in degrees + pub angle_steps: f32, +} + +impl Default for WarpToolbarSettings { + fn default() -> Self { + WarpToolbarSettings { + mode: GizmoMode::default(), + space: GizmoSpace::default(), + manipulator_size: DEFAULT_MANIPULATOR_SIZE, + grid_steps: DEFAULT_GRID_STEP, + angle_steps: DEFAULT_ANGLE_STEP, + } + } +} + +impl WarpToolbarSettings { + /// How many times its base size the gizmo's arrows and ring are drawn + pub(crate) fn gizmo_scale(&self) -> f32 { + within(self.manipulator_size, MANIPULATOR_SIZES, DEFAULT_MANIPULATOR_SIZE) / DEFAULT_MANIPULATOR_SIZE + } + + /// The move step in world units + pub(crate) fn grid_step(&self) -> f32 { + within(self.grid_steps, GRID_STEPS, DEFAULT_GRID_STEP) + } + + /// The turn step in degrees + pub(crate) fn angle_step(&self) -> f32 { + within(self.angle_steps, ANGLE_STEPS, DEFAULT_ANGLE_STEP) + } +} + +/// `value` held to `range`; `fallback` for a saved value that is not a number +fn within(value: f32, range: RangeInclusive, fallback: f32) -> f32 { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { fallback } +} diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs new file mode 100644 index 00000000..187d0de6 --- /dev/null +++ b/crates/ui-egui/src/framework.rs @@ -0,0 +1,241 @@ +//! The craft-ui runtime, hosted from TextureCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2). +//! The desktop app calls [`install`] once, [`TextureCraftApp::before_input`] in `raw_input_hook`, +//! [`TextureCraftApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests +//! install with [`install_headless`]. The framework dialogs run on [`TextureCraftApp::framework_dialogs`] after +//! TextureCraft's own UI. +//! +//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of TextureCraft's own egui +//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with +//! [`take_window_cancel`], its plain Enter taken with [`take_window_submit`]; the 3D and 2D views are declared to the runtime with [`host_canvas`], which keeps the edit +//! chords and the clipboard events in egui's input for TextureCraft's shortcuts. A bare Tab with nothing or a view +//! focused toggles the window's chrome in the runtime ([`RootEnv::tab_toggles_chrome`]), which `frame_input` turns into +//! Hide UI. A focused view leaves the keyboard to the shortcuts ([`widget_has_keyboard`]). + +use std::sync::{Arc, OnceLock}; + +use craft_host::target::ShellInfo; +use craft_host::{AppInfo, Host}; +use craft_keymap::Overrides; +use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts}; +use craft_ui::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _, EditCommands, NavCommand, QuitCommand}; +use craft_ui::runtime::env::{RootEnv, Scale}; +use craft_ui::runtime::focus::{EditSet, KeyUse}; +use craft_ui::runtime::frame::{ChromeToggle, FrameInput, FrameOutput}; +use craft_ui::runtime::keys::{Intent, with_window_intents}; +use craft_ui::shell::embed::{self, CloseDecision}; +use craft_window::policy::Decision; +use craft_window::system::WindowSystem; +use egui::ViewportId; + +use crate::TextureCraftApp; + +/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of +/// (Windows) and fits the window to its monitor once. +#[cfg(not(target_arch = "wasm32"))] +pub use craft_ui::shell::embed::before_ui; + +/// The scripts of the interface languages, for the font stack. +static SCRIPTS: I18nScripts = I18nScripts; + +/// The runtime's first font stack: egui's bundled faces and no installed system fonts. TextureCraft's own definitions +/// ([`crate::theme::install`]) replace it before anything is drawn. +fn ui_fonts() -> UiFonts<'static> { + UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off) +} + +fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc, frame: Option) -> Result<(), String> { + let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id()); + if let Some(frame) = frame { + spec = spec.frame(frame); + } + embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}")) +} + +/// Installs the runtime on the desktop window's context, once, before the first pass, with the window's `frame` +/// ([`crate::titlebar::TitleBar::decide`]). +#[cfg(not(target_arch = "wasm32"))] +pub fn install(ctx: &egui::Context, frame: Decision) -> Result<(), String> { + let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env()); + install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame)) +} + +/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows. +pub fn install_headless(ctx: &egui::Context) { + if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows), None) { + log::warn!("{error}"); + } +} + +/// Who TextureCraft is to the framework's dialogs (the update dialogs show its name and icon). +pub(crate) fn host() -> Arc { + Arc::new( + Host::builder(AppInfo { id: "texturecraft", name: "TextureCraft", version: texturecraft_engine::VERSION }) + .icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png")) + .build(), + ) +} + +/// TextureCraft's own shortcut table keeps the keys the framework binds by default: Ctrl+Q is `ui.quit`, F6 is +/// `camera.orthographic` (and Shift+F6 stays free for it), so the framework's quit and pane moves are unbound, as is +/// Shift+Tab's panels toggle except tools (TextureCraft has one Hide UI, on Tab). +/// Overrides are keyed by command id, which the command sets give. +fn command_overrides() -> Arc { + static OVERRIDES: OnceLock> = OnceLock::new(); + OVERRIDES + .get_or_init(|| { + let mut overrides = Overrides::new(); + for id in [QuitCommand::Quit.id(), NavCommand::NextPane.id(), NavCommand::PreviousPane.id(), ChromeCommand::TogglePanelsKeepTools.id()] { + overrides.insert(id, Vec::new()); + } + Arc::new(overrides) + }) + .clone() +} + +impl TextureCraftApp { + /// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime + /// gathered since the last frame and gives the coming passes the root values (theme mode and interface scale). + pub fn before_input(&mut self, ctx: &egui::Context) { + // TextureCraft applies the interface scale itself (`logic`), so the runtime keeps the zoom it applied last. + let scale = ctx.zoom_factor(); + embed::before_input(ctx, |output| self.frame_input(ctx, output, scale)); + } + + /// The root values of this frame. TextureCraft registers no commands with the runtime (its own shortcut table + /// runs every key, [`command_overrides`]). The runtime toggles the chrome on a bare Tab with nothing or a + /// view focused (`tab_toggles_chrome`, the views being the registered canvases) and takes it out of egui's input, and + /// each panels toggle it recorded for the root window flips Hide UI, as the `ui.hideUi` command does. While one of + /// TextureCraft's own egui modals shows in the root window, the runtime blocks the panels floated into windows of + /// their own. + pub(crate) fn frame_input(&mut self, ctx: &egui::Context, output: FrameOutput, scale: f32) -> FrameInput { + for (viewport, toggle) in &output.chrome_toggles { + if *viewport == ViewportId::ROOT && *toggle == ChromeToggle::Panels { + self.ui.hide_ui = !self.ui.hide_ui; + } + } + #[cfg(not(target_arch = "wasm32"))] + self.fired_clipboard.extend(clipboard_events(&output)); + use crate::theme::Brightness; + let mode = match self.ui.prefs.brightness { + Brightness::Light | Brightness::MediumLight => craft_theme::Mode::Light, + Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark, + }; + let mut root = RootEnv::new().mode(mode).scale(Scale::new(scale)); + // Hide UI on another key leaves Tab to focus traversal and the shortcuts + root.tab_toggles_chrome = crate::keymap::shortcut_of(&self.ui.keymap, "ui.hideUi") == Some("Tab"); + let app_modal = crate::docking::input_blocked(self, ctx).then_some(ViewportId::ROOT); + FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal) + } + + /// The framework's part of `App::logic`, after TextureCraft's own: the root window's close path. Unsaved changes + /// hold the window open while the Unsaved Changes dialog asks ([`crate::windows::close_requested`]); otherwise + /// it closes. + pub fn close_path(&mut self, ctx: &egui::Context) { + embed::logic(ctx, || if crate::windows::close_requested(self) { CloseDecision::Hold } else { CloseDecision::Close }); + } +} + +/// The Copy, Cut and Paste events the runtime took from windows with no canvas of their own (a floating panel) and ran as +/// its `edit.copy`, `edit.cut` and `edit.paste`: the clipboard events TextureCraft's shortcuts read in the root window. +/// The other edit commands are not read here: TextureCraft's own loop still forwards their keys. +#[cfg(not(target_arch = "wasm32"))] +fn clipboard_events(output: &FrameOutput) -> impl Iterator + '_ { + output.fired.iter().filter_map(|fired| match EditCommands::from_ref(&fired.command)? { + EditCommands::Copy => Some(egui::Event::Copy), + EditCommands::Cut => Some(egui::Event::Cut), + // The layer paste takes no content from the event; the shortcut only needs the paste chord. + EditCommands::Paste => Some(egui::Event::Paste(String::new())), + _ => None, + }) +} + +/// Declares the view `id`, an egui widget drawn in this pass, as a document canvas of the window. With nothing or the +/// view focused, the edit chords and the clipboard events stay in egui's input for TextureCraft's shortcuts, and a bare +/// Tab is the runtime's chrome toggle (`frame_input`). Tab and Shift+Tab stop at the view, Shift+Tab moves on from it, +/// and a click gives it no focus. +pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) { + const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL); + craft_ui::runtime::focus::host_canvas(ctx, id, KEYS); +} + +/// The widget that has the keyboard, the 3D and 2D views left out: a focused view leaves the keyboard to +/// TextureCraft's shortcuts, as with nothing focused. +pub(crate) fn focused_widget(ctx: &egui::Context) -> Option { + use crate::viewport::{view_2d_id, view_3d_id}; + ctx.memory(|memory| memory.focused()).filter(|focused| ![view_3d_id(), view_2d_id()].contains(focused)) +} + +/// Whether a widget other than the 3D and 2D views has the keyboard. +pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool { + focused_widget(ctx).is_some() +} + +/// Whether Escape was pressed in this pass: from egui while one of TextureCraft's own widgets or popups has the +/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers. +pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool { + ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false) +} + +/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it. +pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool { + window_cancel(ctx, true) +} + +/// Takes the window's submit (a plain Enter while nothing has framework focus) when it is there: no later reader sees +/// it. +pub(crate) fn take_window_submit(ctx: &egui::Context) -> bool { + window_intent(ctx, Intent::Submit, true) +} + +/// Whether the window's cancel is there and untaken; `take` takes it. +fn window_cancel(ctx: &egui::Context, take: bool) -> bool { + window_intent(ctx, Intent::Cancel, take) +} + +/// Whether the window's `intent` is there and untaken; `take` takes it. +fn window_intent(ctx: &egui::Context, intent: Intent, take: bool) -> bool { + let mut pending = false; + with_window_intents(ctx, false, |intents| { + pending = if take { intents.take(intent.clone()) } else { intents.untaken(&intent) }; + take && pending + }); + pending +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use craft_ui::runtime::commands::{FirePhase, FireSource, Fired}; + use egui_kittest::Harness; + + fn fired(command: EditCommands) -> Fired { + Fired::new(command.into(), FireSource::Key, FirePhase::Press, 0.0) + } + + /// With nothing focused in a floating panel, the runtime runs the chord as `edit.copy` and takes the clipboard event + /// from egui's input, so TextureCraft's own loop never sees it: the fired command reaches the layer clipboard once. + #[test] + fn fired_copy_and_paste_from_a_float_reach_the_layer_clipboard_once() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let ctx = h.ctx.clone(); + let layers = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.len(); + let before = layers(&h); + + let mut output = FrameOutput::default(); + output.fired.push(fired(EditCommands::Copy)); + h.state_mut().frame_input(&ctx, output, 1.0); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "the fired Copy copied the layer"); + assert_eq!(layers(&h), before); + + let mut output = FrameOutput::default(); + output.fired.push(fired(EditCommands::Paste)); + h.state_mut().frame_input(&ctx, output, 1.0); + h.run_steps(3); + assert_eq!(layers(&h), before + 1, "the fired Paste pasted the layer once"); + } +} diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index 6e979c85..df2523b6 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -14,6 +14,7 @@ use crate::i18n::{tr, trf}; use crate::state::{ImportResources, ImportRow, ResourceUsage}; use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS}; use crate::widgets::primary_button; +use crate::windows::MATERIALX_EXT; /// Width of the window const WINDOW_WIDTH_POINTS: f32 = 640.0; @@ -28,6 +29,8 @@ const USAGE_WIDTH_POINTS: f32 = 110.0; const TARGET_WIDTH_POINTS: f32 = 190.0; /// Keep space for the file name in a narrow row const MIN_NAME_WIDTH_POINTS: f32 = 40.0; +const CONTROL_GAP_POINTS: f32 = 4.0; +const SECTION_GAP_POINTS: f32 = 8.0; /// Opens the window with an empty list (an open window stays as it is) pub(crate) fn open(app: &mut TextureCraftApp) { @@ -62,18 +65,17 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, n } } -fn extension_of(row: &ImportRow) -> String { - row.path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default() +fn extension_of(row: &ImportRow) -> Option<&str> { + row.path.extension().and_then(|extension| extension.to_str()) } -/// Whether the file is a MaterialX document (added as a fill layer) -fn is_materialx(row: &ImportRow) -> bool { - extension_of(row) == crate::windows::MATERIALX_EXT +fn is_smart_material_extension(extension: &str) -> bool { + MATERIAL_EXTS.iter().any(|material_extension| extension.eq_ignore_ascii_case(material_extension)) } /// Whether the file is a material (a smart material or a MaterialX document, so it has no usage or prefix) fn is_material(row: &ImportRow) -> bool { - MATERIAL_EXTS.contains(&extension_of(row).as_str()) || is_materialx(row) + extension_of(row).is_some_and(|extension| extension.eq_ignore_ascii_case(MATERIALX_EXT) || is_smart_material_extension(extension)) } fn file_name(row: &ImportRow) -> String { @@ -136,10 +138,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { import |= ui.add_enabled(app.session.project_open && !window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); }); }); - ui.add_space(4.0); + ui.add_space(CONTROL_GAP_POINTS); if !app.session.project_open { ui.label(tr("Open a project to import resources. Importing into the asset library is not available yet.")); } + ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| { @@ -152,7 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("Destination")); }); }); - ui.add_space(8.0); + ui.add_space(SECTION_GAP_POINTS); ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { ui.horizontal(|ui| { ui.label(tr("Choose files and assign their roles")); @@ -163,7 +166,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { add = ui.button(tr("Add resources")).clicked(); }); }); - ui.add_space(4.0); + ui.add_space(CONTROL_GAP_POINTS); let all_label = trf("All files ({count})", &[("count", &window.rows.len())]); let filter_text = match window.filter { @@ -185,12 +188,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } }); - ui.add_space(4.0); + ui.add_space(CONTROL_GAP_POINTS); let filter = window.filter; let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage); let modifiers = ui.input(|i| i.modifiers); - let mut clicked = None; + let mut clicked_row = None; + let mut selected_usage = None; let list_height = ui.available_height().max(0.0); egui::ScrollArea::both().min_scrolled_width(0.0).min_scrolled_height(0.0).max_height(list_height).auto_shrink([false, false]).show( @@ -199,13 +203,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { for row in window.rows.iter_mut().filter(|row| visible(row)) { let material = is_material(row); let selected = window.selected.contains(&row.id); + ui.horizontal(|ui| { let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x) .max(MIN_NAME_WIDTH_POINTS); let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); if name.on_hover_text(row.path.display().to_string()).clicked() { - clicked = Some(row.id); + clicked_row = Some(row.id); } let prefix = ui.add_enabled( @@ -225,14 +230,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { .selected_text(row.usage.name()) .show_ui(ui, |ui| { for usage in ResourceUsage::ALL { - let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); - if usage.available() { - if item.clicked() { - row.usage = usage; - ui.close(); - } - } else { + let available = usage.available(); + let item = ui.add_enabled(available, egui::Button::selectable(row.usage == usage, usage.name())); + if !available { item.on_disabled_hover_text(tr("Not available yet")); + } else if item.clicked() { + if selected && window.selected.len() > 1 { + selected_usage = Some(usage); + } else { + row.usage = usage; + } + + ui.close(); } } }); @@ -244,7 +253,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }, ); - if let Some(id) = clicked { + // Include selected rows hidden by the filter + if let Some(usage) = selected_usage { + for row in &mut window.rows { + if window.selected.contains(&row.id) && !is_material(row) { + row.usage = usage; + } + } + } + + if let Some(id) = clicked_row { let visible: Vec = if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() }; click_row(&mut window, &visible, id, modifiers); @@ -266,7 +284,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if add { let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec(); extensions.extend_from_slice(MATERIAL_EXTS); - extensions.push(crate::windows::MATERIALX_EXT); + extensions.push(MATERIALX_EXT); let opening_id = window.opening_id; app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; @@ -297,19 +315,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.import_resources = Some(window); } -/// Import one row. A failed file is left in the dialog with its settings. +/// Returns true once the resource has been imported or a linked material cook has been queued. fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool { let Some(path) = row.path.to_str() else { app.toast(trf("Could not import a path that is not UTF-8: {path}", &[("path", &row.path.display())]), true); return false; }; - if is_materialx(row) { - return crate::windows::import_materialx(app, path); - } + if let Some(extension) = extension_of(row) { + if extension.eq_ignore_ascii_case(MATERIALX_EXT) { + return crate::windows::import_materialx(app, path); + } - if is_material(row) { - return app.run("material.load", json!({ "path": path })).is_some(); + if is_smart_material_extension(extension) { + return app.run("material.load", json!({ "path": path })).is_some(); + } } let Some(result) = app.run("resource.import", json!({ "path": path, "prefix": row.prefix })) else { return false }; diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index ee29ac48..47d6548d 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -4,8 +4,8 @@ use std::collections::BTreeMap; -use craft_keymap::egui::Dispatcher; -use craft_keymap::{Active, Bindable, Chord, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; +use crate::shortcut_dispatch::Dispatcher; +use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2}; use egui_phosphor::regular as ic; @@ -179,11 +179,11 @@ fn active(keymap: &Keymap) -> Vec { /// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared /// shortcut. -fn catalog() -> Vec { +fn catalog() -> Vec { bindings() .iter() .map(|b| { - let item = Bindable::new(b.id, b.label, Scope::app()); + let item = CommandDef::new(b.id, b.label, Scope::app()); match b.default.and_then(parse) { Some(chord) => item.with_default(craft_keymap::Binding::new(chord)), None => item, @@ -214,7 +214,7 @@ fn overrides(keymap: &Keymap) -> Overrides { /// The keymap with `keymap`'s shortcuts for `platform`. fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap { - craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)) + craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)).with_delete_keys(craft_keymap::DeleteKeys::Apart) } /// The resolved keymap and the dispatcher that runs it against each frame's keys. @@ -229,7 +229,7 @@ impl Default for Bindings { let stored = Keymap::new(); let map = resolved(&stored, Platform::current()); // Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V. - Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) } + Bindings { stored, map, dispatcher: Dispatcher::default() } } } @@ -245,7 +245,7 @@ impl Bindings { /// The ids of the commands this frame's key presses run, in press order. The presses are /// removed from the input. pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec { - self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect() + self.dispatcher.dispatch_filtered(input, &self.map, |_| true).into_iter().map(|hit| hit.command.id).collect() } /// The id of the command a key press outside the main window runs. The press is matched as @@ -253,11 +253,7 @@ impl Bindings { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn command_of(&self, press: &Event) -> Option { let input = KeyInput::from_egui(press, self.map.platform())?; - self.dispatcher.layout().candidates(&input).into_iter().find_map(|chord| match self.map.lookup(&chord, false, &Active::NONE) { - Lookup::Run(command) => Some(command.id), - Lookup::Cycle(commands) => commands.into_iter().next().map(|command| command.id), - _ => None, - }) + craft_keymap::Matcher::single(self.dispatcher.layout(), &self.map, &input, &Active::NONE, &[]).map(|hit| hit.command.id) } /// The shortcut a press records: the chord it runs, keeping the held Ctrl and Cmd as they are. @@ -391,7 +387,9 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi let tk = Tokens::get(&ctx); let capture_id = Id::unique(SETTINGS_CAPTURE); let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); - if let (Some(i), Some(sc)) = (capture, pressed(&ctx, recorder)) { + if let Some(i) = capture + && let Some(sc) = pressed(&ctx, recorder) + { if let Some(b) = bindings().get(i) { if sc.logical_key == Key::Delete && sc.modifiers.is_none() { rebind(keymap, b, ""); @@ -487,15 +485,17 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi }); } -/// The first key press this frame as a shortcut. +/// The first key press this frame as a shortcut. A plain Escape while none of TextureCraft's widgets has the keyboard +/// is the window's cancel, which the recorder takes as the Escape that cancels it. fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option { let platform = craft_keymap::egui::platform(ctx); - ctx.input(|i| { + let press = ctx.input(|i| { i.events.iter().find_map(|e| match e { Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)), _ => None, }) - }) + }); + press.or_else(|| crate::framework::take_window_cancel(ctx).then(|| KeyboardShortcut::new(Modifiers::NONE, Key::Escape))) } /// The shortcut editor window. @@ -509,7 +509,9 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { let capture_id = Id::unique(CAPTURE); let filter_id = Id::unique("keymap_filter"); let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); - if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) { + if let Some(i) = capture + && let Some(sc) = pressed(ctx, &app.bindings) + { if (sc.logical_key != Key::Escape || !sc.modifiers.is_none()) && let Some(b) = bindings().get(i) { @@ -808,6 +810,13 @@ mod tests { keymap.insert("file.save".into(), "Equals".into()); let resolved = bindings_for(&keymap); assert_eq!(resolved.command_of(&press(Key::Plus, Modifiers::NONE)).as_deref(), Some("file.save"), "+ stands for ="); + + // A layout that types = with Shift+0: the press is both chords, and the one with Shift runs. + keymap.insert("file.saveAs".into(), "Shift+Equals".into()); + let mut resolved = bindings_for(&keymap); + let equals = press_at(Key::Equals, Key::Num0, Modifiers::SHIFT); + assert_eq!(dispatched(&mut resolved, vec![equals.clone()], Modifiers::SHIFT), ["file.saveAs"]); + assert_eq!(resolved.command_of(&equals).as_deref(), Some("file.saveAs")); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 66200f60..401581e8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,6 +44,7 @@ mod filter_transform_rows; mod folder_properties; pub mod fonts; mod frame_gizmo; +pub mod framework; mod generator_input_card; mod generator_input_slot; mod generator_kind_rows; @@ -102,6 +103,7 @@ pub mod orb_previews; mod orb_shape; /// The channel's OS identity (app id, window and app names) — see its module docs. pub mod os_window; +mod pane_split; pub mod parity; mod past_end; mod path_hit; @@ -139,6 +141,8 @@ mod resource_picker; mod resource_picker_item; mod round_gizmo; mod running_bake; +#[cfg(not(target_arch = "wasm32"))] +mod sample_project; pub mod saved_search; mod screen_color_pick; pub mod screen_pick; @@ -155,6 +159,7 @@ pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_view; +mod shortcut_dispatch; mod slot_thumbnail; #[cfg(not(target_arch = "wasm32"))] mod smart_mask_menu; @@ -256,6 +261,9 @@ pub struct TextureCraftApp { pub session: Session, #[cfg(not(target_arch = "wasm32"))] pub(crate) session_log_file: Option, + /// The folder File > Open Sample Project starts in, under the data folder + #[cfg(not(target_arch = "wasm32"))] + pub samples_folder: std::path::PathBuf, viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds, /// A smooth move to a saved camera in progress. camera_glide: Option, @@ -294,6 +302,10 @@ pub struct TextureCraftApp { pub(crate) live_preview: bake_mode::LivePreview, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, + /// Project and texture-set index from the last completed UI pass. + hovered_texture_set: Option<(u64, usize)>, + /// The set under the pointer in this pass, independent of dock drawing order. + next_hovered_texture_set: Option<(u64, usize)>, pub fps: f32, /// User smart materials found in the library folder (refreshed on demand). pub library: Option>, @@ -331,6 +343,16 @@ pub struct TextureCraftApp { pub banner: Option<&'static str>, /// Who draws the window's title bar (decided at startup, before the window opens). pub title_bar: titlebar::TitleBar, + /// The dock area's workspace and panel specs between passes. + pub(crate) docks: docking::LiveDock, + /// The framework dialogs (the update dialogs), run once per pass after TextureCraft's own UI. + pub framework_dialogs: craft_ui::dialog::DialogHost, + /// Who TextureCraft is to the framework's dialogs. + pub(crate) framework_host: std::sync::Arc, + /// The Copy, Cut and Paste the runtime took from a floating panel's window (`framework::clipboard_events`), for the + /// shortcuts of the next `logic`. + #[cfg(not(target_arch = "wasm32"))] + fired_clipboard: Vec, last_time: f64, /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -416,6 +438,8 @@ impl TextureCraftApp { session, #[cfg(not(target_arch = "wasm32"))] session_log_file: None, + #[cfg(not(target_arch = "wasm32"))] + samples_folder: std::path::PathBuf::new(), viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(), ui, ui_store, @@ -437,6 +461,8 @@ impl TextureCraftApp { bake_map_thumbnails: bake_mode::MapThumbnails::default(), live_preview: bake_mode::LivePreview::default(), viewport_rect: egui::Rect::NOTHING, + hovered_texture_set: None, + next_hovered_texture_set: None, fps: 0.0, ui_ms: 0.0, profiler: profile::Profiler::default(), @@ -460,6 +486,11 @@ impl TextureCraftApp { fonts: fonts::UiFonts::default(), banner: None, title_bar: titlebar::TitleBar::default(), + docks: docking::LiveDock::default(), + framework_dialogs: craft_ui::dialog::DialogHost::new(), + framework_host: framework::host(), + #[cfg(not(target_arch = "wasm32"))] + fired_clipboard: Vec::new(), last_time: 0.0, next_autosave, styled: None, @@ -491,6 +522,7 @@ impl TextureCraftApp { { // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); + app.samples_folder = user_dir(sample_project::SAMPLES_FOLDER); if cc.winit_window().is_some() { match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) { @@ -1099,6 +1131,7 @@ impl TextureCraftApp { impl eframe::App for TextureCraftApp { /// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + self.before_input(ctx); pointer_lock::rewrite(ctx, raw_input); } @@ -1193,6 +1226,11 @@ impl eframe::App for TextureCraftApp { self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + { + let events = std::mem::take(&mut self.fired_clipboard); + menus::forwarded_shortcuts(self, ctx, events, egui::Modifiers::NONE); + } screen_pick::sync(self, ctx); move_on_model::end_when_gone(self, ctx); @@ -1213,7 +1251,7 @@ impl eframe::App for TextureCraftApp { self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32; // Last, so it sees every close request this frame's work made - windows::close_request(self, ctx); + self.close_path(ctx); } #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] @@ -1242,7 +1280,20 @@ impl eframe::App for TextureCraftApp { // The dock keeps the cards' gutter from the bars and rails around it let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; - egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); + egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| { + if hide_ui { + viewport::central(self, ui); + } else { + docking::show(self, ui); + } + }); + + let hovered_texture_set = self.next_hovered_texture_set.take(); + if self.hovered_texture_set != hovered_texture_set { + self.hovered_texture_set = hovered_texture_set; + ctx.request_repaint(); + } + windows::show(self, &ctx); // Finish after the dock and windows have requested their thumbnails @@ -1250,6 +1301,7 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] updates_ui::show(self, &ctx); + self.framework_dialogs.run(ui); toasts(self, &ctx); #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 53547d2f..7534420e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -179,6 +179,11 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { return false; } + // A shortcut has no explicit layer to toggle + if id == "mask.toggle" && app.session.selected_layer().is_none() { + return false; + } + if is_ui(id) { return app.session.project_open || !ui_needs_project(id); } @@ -414,7 +419,7 @@ pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, event continue; } let Some(id) = app.bindings.command_of(&event) else { continue }; - invoke(app, ctx, effect_command(app, &id)); + run_shortcut(app, ctx, &id); } } @@ -447,9 +452,9 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } -/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture +/// Runs the commands bound to the keys pressed this frame, with no widget but the viewport focused, outside key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { - if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + if crate::keymap::capturing(ctx) || crate::framework::widget_has_keyboard(ctx) { return; } @@ -458,6 +463,20 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } + // A plain Escape or Enter while no widget of TextureCraft's has the keyboard is the window's cancel or submit: back + // in egui's input, it runs the Escape and Enter handlers below, the shortcuts and the Path tool's keys + for (key, taken) in [(Key::Escape, crate::framework::take_window_cancel(ctx)), (Key::Enter, crate::framework::take_window_submit(ctx))] { + if taken { + let escape = craft_ui::runtime::keys::escape_mods(ctx).filter(|_| key == Key::Escape); + ctx.input_mut(|i| { + // A submit's Enter had no Ctrl or Cmd; one that came down later in the pass is not its own + let (shift, alt) = escape.map_or((i.modifiers.shift, i.modifiers.alt), |held| (held.shift, held.alt)); + let modifiers = Modifiers { shift, alt, ..Modifiers::NONE }; + i.events.insert(0, egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }); + }); + } + } + // The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V // Unbound Shift+Delete and Shift+Insert use the standard cut and paste shortcuts ctx.input_mut(|input| { @@ -472,14 +491,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { }); // Let the innermost popup consume Escape before cancelling the active tool - let popup_open = egui::Popup::is_any_open(ctx); + // (the drop popup of the Output templates tab is open without registering with egui, and reads Escape itself) + let popup_open = egui::Popup::is_any_open(ctx) || app.ui.export.pending_drop.is_some(); let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); let mut cancel_point_pick = false; let picker_open = crate::color_picker::open_window(ctx).is_some(); - let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); - #[cfg(not(target_arch = "wasm32"))] - let nothing_focused = ctx.memory(|memory| memory.focused().is_none()); + let nothing_focused = !crate::framework::widget_has_keyboard(ctx); let log_copies = crate::log_panel::takes_copy(app, ctx); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame @@ -491,7 +509,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Escape and Enter answer the Reset UI question first, even when a shortcut binds them let confirming_reset = app.ui.windows.confirm_reset_ui; if confirming_reset && !popup_open { - crate::windows::reset_ui_keys(app, input, no_widget_focused); + crate::windows::reset_ui_keys(app, input, nothing_focused); } // F2 renames the selected template on Output templates, before its 3D view binding @@ -561,17 +579,22 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } for id in &commands_to_invoke { - if matches!(id.as_str(), "layer.copy" | "layer.cut") - && let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer)) - { - // Ctrl+V reaches the app only while the system clipboard holds text or an image - ctx.copy_text(layer.name.clone()); - } - - invoke(app, ctx, effect_command(app, id)); + run_shortcut(app, ctx, id); } } +/// Runs the command a shortcut is bound to. A layer copy or cut also puts the layer's name on the system clipboard: +/// Ctrl+V reaches the app only while that clipboard holds text or an image. +fn run_shortcut(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { + if matches!(id, "layer.copy" | "layer.cut") + && let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer)) + { + ctx.copy_text(layer.name.clone()); + } + + invoke(app, ctx, effect_command(app, id)); +} + /// The desktop and web shells turn Ctrl+C, Ctrl+X and Ctrl+V (and Ctrl+Insert, Shift+Delete, /// Shift+Insert) into clipboard events instead of key presses. Outside a text field they are the /// shortcuts bound to Ctrl+C, Ctrl+X and Ctrl+V (copy, cut and paste a layer by default). diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index d5f4e349..e65105c7 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -292,7 +292,7 @@ mod tests { /// Presses the left button on Move on model (the preview square) and holds it; returns the system's pointer, resting there fn press_the_button(harness: &mut Harness) -> SystemPointer { let at = harness.get_by_label("Move on model").rect().center(); - let mut pointer = SystemPointer::at(harness, at); + let mut pointer = SystemPointer::in_app(harness, at); pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); pointer } @@ -439,7 +439,7 @@ mod tests { assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}"); let before = projection(&harness, layer); - let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0)); + let mut pointer = SystemPointer::in_app(&mut harness, pad.left_top() + vec2(4.0, 4.0)); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold"); diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 6931cd63..68593bea 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -13,8 +13,8 @@ use texturecraft_engine::template_cmds::template_label; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; use crate::project_form::{ - FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, - unavailable, uv_tile_radios, + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, + uv_tile_radios, }; use crate::state::{Mode, NewProject}; use crate::theme::{Tokens, caption}; @@ -151,6 +151,7 @@ pub fn create_command(new_project: &NewProject) -> Option { "uvTiles": new_project.uv_tiles == Some(true), "template": new_project.template, "importCameras": new_project.import_cameras, + "rebuildUvs": new_project.rebuild_uvs, })) } @@ -169,7 +170,14 @@ fn create_project(app: &mut TextureCraftApp) -> bool { let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); let template = app.session.template(&new_project.template); - match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { + match texturecraft_engine::Session::from_mesh_bytes_with_uvs( + name, + bytes, + new_project.resolution, + &stem, + Some(new_project.uv_tiles == Some(true)), + new_project.rebuild_uvs, + ) { Ok(mut next) => { if !new_project.import_cameras { next.doc.project.cameras.clear(); @@ -259,12 +267,18 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { new_project.uv_tiles = Some(uv_tiles); } + uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first")); ui.add_space(4.0); sub_title(ui, tr("Import settings"), None); check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {}); - auto_unwrap_row(ui); + check_row( + ui, + Some(tr("Generate a fresh UV layout even when the mesh already has UVs. Meshes without UVs are always unwrapped.")), + |ui| ui.checkbox(&mut new_project.rebuild_uvs, tr("Rebuild mesh UVs")), + |_| {}, + ); ui.add_space(4.0); collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| { diff --git a/crates/ui-egui/src/pane_split.rs b/crates/ui-egui/src/pane_split.rs new file mode 100644 index 00000000..ce441a9c --- /dev/null +++ b/crates/ui-egui/src/pane_split.rs @@ -0,0 +1,269 @@ +//! Two panes split by a focusable divider: the geometry of one split and its resize handle (pointer drag, arrow keys +//! and accessibility). The shelf's saved searches and path filter (`shelf_panes.rs`) use it. + +use std::ops::RangeInclusive; + +use craft_behavior::dock::SplitSize; +use craft_behavior::flow::Axis; +use egui::{Color32, EventFilter, Id, Key, Modifiers, Rect, Response, Sense, Ui, Vec2, accesskit}; + +/// Contained, non-overlapping rectangles of a single split, including its divider. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SplitLayout { + pub(crate) first: Rect, + pub(crate) divider: Rect, + pub(crate) second: Rect, + first_size: f32, + available: f32, +} + +impl SplitLayout { + /// The first pane's size along the split axis, in points. + pub(crate) fn first_size(self) -> f32 { + self.first_size + } + + /// Space for both panes, excluding the divider, in points. + pub(crate) fn available(self) -> f32 { + self.available + } + + /// The size after moving the divider by `delta` points, in the same sizing mode. When both minima cannot fit, + /// each pane gets half the available space. Invalid inputs and zero available space give `None`, so the caller + /// keeps its saved value. + pub(crate) fn resized(self, size: SplitSize, delta: f32, minimum: f32) -> Option { + if !value(size).is_finite() || !delta.is_finite() || !valid_nonnegative(minimum) || self.available <= 0.0 { + return None; + } + let available = f64::from(self.available); + let first = clamp_first(f64::from(self.first_size) + f64::from(delta), available, minimum); + Some(match size { + SplitSize::FixedFirst(_) => SplitSize::FixedFirst(first as f32), + SplitSize::FixedSecond(_) => SplitSize::FixedSecond((available - first) as f32), + _ => SplitSize::Ratio((first / available) as f32), + }) + } +} + +fn value(size: SplitSize) -> f32 { + match size { + SplitSize::Ratio(v) | SplitSize::FixedFirst(v) | SplitSize::FixedSecond(v) => v, + #[allow(unreachable_patterns)] + _ => f32::NAN, + } +} + +/// Divides `rect` into two panes and a divider `gap` points thick. Equal pane minima relax to half the remaining +/// span in tiny areas; finite sizes outside the available range are clamped. Inverted or non-finite rectangles, a +/// negative or non-finite gap or minimum and a non-finite size give `None`. +pub(crate) fn split_rect(rect: Rect, axis: Axis, size: SplitSize, gap: f32, minimum: f32) -> Option { + if !valid_rect(rect) || !valid_nonnegative(gap) || !valid_nonnegative(minimum) || !value(size).is_finite() { + return None; + } + let total = if axis == Axis::X { rect.width() } else { rect.height() }; + let gap = gap.min(total); + let available = total - gap; + let space = f64::from(available); + // f64: two finite f32 inputs can overflow when multiplied. + let wanted = match size { + SplitSize::FixedFirst(points) => f64::from(points), + SplitSize::FixedSecond(points) => space - f64::from(points), + other => space * f64::from(value(other)), + }; + let first_size = clamp_first(wanted, space, minimum) as f32; + let (mut first, mut divider, mut second) = (rect, rect, rect); + if axis == Axis::X { + first.max.x = (rect.min.x + first_size).min(rect.max.x); + divider.min.x = first.max.x; + divider.max.x = (divider.min.x + gap).min(rect.max.x); + second.min.x = divider.max.x; + } else { + first.max.y = (rect.min.y + first_size).min(rect.max.y); + divider.min.y = first.max.y; + divider.max.y = (divider.min.y + gap).min(rect.max.y); + second.min.y = divider.max.y; + } + Some(SplitLayout { first, divider, second, first_size, available }) +} + +fn valid_rect(rect: Rect) -> bool { + rect.min.is_finite() + && rect.max.is_finite() + && rect.width().is_finite() + && rect.height().is_finite() + && rect.min.x <= rect.max.x + && rect.min.y <= rect.max.y +} + +fn valid_nonnegative(value: f32) -> bool { + value.is_finite() && value >= 0.0 +} + +fn clamp_first(wanted: f64, available: f64, minimum: f32) -> f64 { + let low = f64::from(minimum).min(available * 0.5); + wanted.clamp(low, available - low) +} + +/// Colours of a resize handle. The handle at rest paints no fill. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ResizeHandleStyle { + pub(crate) hovered: Color32, + pub(crate) dragged: Color32, + pub(crate) focused: Color32, +} + +/// A focusable divider moved by a pointer drag, the arrows along its axis while it has focus, and accessibility's +/// Increment, Decrement and SetValue. It never stores a size: [`show`](ResizeHandle::show) returns the move along the +/// axis for the caller to apply. +pub(crate) struct ResizeHandle<'a> { + id: Id, + axis: Axis, + rect: Rect, + label: &'a str, + style: ResizeHandleStyle, + hit_margin: f32, + value: Option<(f32, RangeInclusive)>, +} + +/// Keyboard and accessibility step, in points. +const STEP: f32 = 8.0; + +impl<'a> ResizeHandle<'a> { + pub(crate) fn new(id: Id, axis: Axis, rect: Rect, label: &'a str, style: ResizeHandleStyle) -> Self { + Self { id, axis, rect, label, style, hit_margin: 3.0, value: None } + } + + /// Widens the hit rectangle along the movement axis, in points. Default: 3. + pub(crate) fn hit_margin(mut self, margin: f32) -> Self { + self.hit_margin = margin; + self + } + + /// The current size and its bounds, for accessibility and its SetValue action. + pub(crate) fn value(mut self, value: f32, range: RangeInclusive) -> Self { + self.value = Some((value, range)); + self + } + + /// Shows the handle and returns the requested move along the axis this pass, in points (0 for none). + pub(crate) fn show(self, ui: &mut Ui) -> f32 { + let horizontal = self.axis == Axis::X; + let hit = self.rect.expand2(if horizontal { Vec2::new(self.hit_margin, 0.0) } else { Vec2::new(0.0, self.hit_margin) }); + let valid = valid_rect(self.rect) + && self.rect.width() > 0.0 + && self.rect.height() > 0.0 + && valid_rect(hit) + && (0.0..=4096.0).contains(&self.hit_margin) + && self + .value + .as_ref() + .is_none_or(|(value, range)| value.is_finite() && range.start().is_finite() && range.end().is_finite() && range.start() <= range.end()); + let inert = Rect::from_min_size(ui.min_rect().min, Vec2::ZERO); + let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() }); + let enabled = valid && response.enabled(); + let mut delta = 0.0; + if enabled { + drag_focus(ui, &response); + if response.dragged() { + let drag = response.drag_delta(); + delta = if horizontal { drag.x } else { drag.y }; + } + if response.has_focus() { + let filter = EventFilter { horizontal_arrows: horizontal, vertical_arrows: !horizontal, ..Default::default() }; + ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, filter)); + let (back, forward) = if horizontal { (Key::ArrowLeft, Key::ArrowRight) } else { (Key::ArrowUp, Key::ArrowDown) }; + ui.input_mut(|input| { + if input.consume_key(Modifiers::NONE, back) { + delta -= STEP; + } + if input.consume_key(Modifiers::NONE, forward) { + delta += STEP; + } + }); + } + let mut change = 0.0; + ui.input_mut(|input| { + input.consume_accesskit_action_requests(response.id, |request| match request.action { + accesskit::Action::Increment => { + change += STEP; + true + } + accesskit::Action::Decrement => { + change -= STEP; + true + } + accesskit::Action::SetValue => { + if let (Some((value, range)), Some(accesskit::ActionData::NumericValue(new_value))) = (&self.value, &request.data) + && new_value.is_finite() + { + change = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32; + delta = 0.0; + } + true + } + _ => false, + }); + }); + delta += change; + } + if !delta.is_finite() { + delta = 0.0; + } + if delta != 0.0 { + response.mark_changed(); + } + response.widget_info(|| match &self.value { + Some((value, _)) if valid => egui::WidgetInfo::slider(enabled, f64::from(*value), self.label), + _ => egui::WidgetInfo::labeled(egui::Role::Unknown, enabled, self.label), + }); + ui.ctx().accesskit_node_builder(response.id, |node| { + node.set_role(accesskit::Role::Splitter); + // Orientation describes the divider itself, across its movement axis. + node.set_orientation(if horizontal { accesskit::Orientation::Vertical } else { accesskit::Orientation::Horizontal }); + if enabled { + node.add_action(accesskit::Action::Increment); + node.add_action(accesskit::Action::Decrement); + if let Some((value, range)) = &self.value { + node.set_numeric_value(f64::from(*value)); + node.set_min_numeric_value(f64::from(*range.start())); + node.set_max_numeric_value(f64::from(*range.end())); + node.set_numeric_value_step(f64::from(STEP)); + node.add_action(accesskit::Action::SetValue); + } + } + }); + if enabled { + let fill = if response.dragged() { + Some(self.style.dragged) + } else if response.has_focus() { + Some(self.style.focused) + } else if response.hovered() { + Some(self.style.hovered) + } else { + None + }; + if let Some(fill) = fill { + ui.painter().rect_filled(self.rect, 0.0, fill); + } + if response.hovered() || response.dragged() { + ui.ctx().set_cursor_icon(if horizontal { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical }); + } + } + delta + } +} + +/// A pointer drag focuses its handle for the gesture only and gives the focus up on release, so the app's shortcuts +/// and its canvas arrow keys work again. A handle focused from the keyboard before the drag keeps its focus. +fn drag_focus(ui: &Ui, response: &Response) { + let key = response.id.with("pointer-focus"); + if response.drag_started() { + if !response.has_focus() { + ui.ctx().data_mut(|d| d.insert_temp(key, ())); + } + response.request_focus(); + } + if response.drag_stopped() && ui.ctx().data_mut(|d| d.remove_temp::<()>(key)).is_some() { + response.surrender_focus(); + } +} diff --git a/crates/ui-egui/src/pointer_lock/system_pointer.rs b/crates/ui-egui/src/pointer_lock/system_pointer.rs index 156cd8ee..d41d817e 100644 --- a/crates/ui-egui/src/pointer_lock/system_pointer.rs +++ b/crates/ui-egui/src/pointer_lock/system_pointer.rs @@ -12,12 +12,25 @@ pub(crate) struct SystemPointer { pub(crate) put_backs: usize, /// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own pub(crate) folds: bool, + /// The harness has no eframe app, so the test runs the app's raw input rewrite itself; an app harness runs the + /// app's `raw_input_hook` before every pass, as eframe does + rewrites: bool, } impl SystemPointer { - /// The pointer resting at `at` over the window + /// The pointer resting at `at` over a window that shows a bare UI, whose raw input the test rewrites as the + /// app's hook would pub(crate) fn at(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer { - let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false }; + Self::start(harness, at, true) + } + + /// The pointer resting at `at` over the app's window, whose own raw input hook rewrites the input + pub(crate) fn in_app(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer { + Self::start(harness, at, false) + } + + fn start(harness: &mut Harness<'_, S>, at: Pos2, rewrites: bool) -> SystemPointer { + let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false, rewrites }; harness.input_mut().events.push(Event::PointerMoved(at)); pointer.frame(harness); pointer @@ -52,8 +65,10 @@ impl SystemPointer { /// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked pub(crate) fn frame(&mut self, harness: &mut Harness<'_, S>) { - let ctx = harness.ctx.clone(); - super::rewrite(&ctx, harness.input_mut()); + if self.rewrites { + let ctx = harness.ctx.clone(); + super::rewrite(&ctx, harness.input_mut()); + } harness.step(); let output = harness.output(); self.hidden = output.platform_output.cursor_icon == CursorIcon::None; diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs index 10de74ee..4118a280 100644 --- a/crates/ui-egui/src/pointer_lock/tests.rs +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -108,7 +108,7 @@ fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar"); hold_like(&harness.ctx, Hold::PutBack); let press = harness.get_by_label("Offset X").rect().center(); - let mut pointer = SystemPointer::at(&mut harness, press); + let mut pointer = SystemPointer::in_app(&mut harness, press); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); let window = harness.ctx.content_rect().width(); pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs index 171282e3..d340a344 100644 --- a/crates/ui-egui/src/project_form.rs +++ b/crates/ui-egui/src/project_form.rs @@ -158,6 +158,7 @@ pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) { /// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the /// box is ticked; turning it off and the options are not available yet. +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn auto_unwrap_row(ui: &mut Ui) { check_row( ui, diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs index edc56a76..f9196b37 100644 --- a/crates/ui-egui/src/projection_gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -29,12 +29,14 @@ pub(crate) fn let_go(ctx: &egui::Context) { /// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own) pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool { - let mut drag = dragging::(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start))); + let mesh_id = app.session.mesh_id; + let mut drag = dragging::(ctx).filter(|drag| drag.mesh_id == mesh_id && gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start))); + if response.drag_started_by(PointerButton::Primary) && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) && let Some(grab) = gizmo.grab(from) { - drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None }); + drag = Some(GizmoDrag { grab, from, mesh_id, start: Arc::new(gizmo.clone()), edited_revision: None }); } // Apply a final move on release and let focus loss end a drag without one @@ -51,19 +53,23 @@ pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, re // A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true)); - if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) - && let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer) + let (moved, snapping) = ctx.input(|input| (input.pointer.delta() != egui::Vec2::ZERO, input.modifiers.ctrl || input.modifiers.command)); + if moved + && let Some(pointer) = response.interact_pointer_pos() + && let Some((command, params)) = drag.start.edit_with_snap(app, rect, drag.grab, drag.from, pointer, snapping) { edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision); // The panel drew before this edit: one more frame shows its fields and preview where the projection is now ctx.request_repaint(); } + if released { let_go::(ctx); } else { ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag)); } + true } diff --git a/crates/ui-egui/src/projection_gizmo/gizmo.rs b/crates/ui-egui/src/projection_gizmo/gizmo.rs index e95c8270..fb3cbbcc 100644 --- a/crates/ui-egui/src/projection_gizmo/gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo/gizmo.rs @@ -20,6 +20,11 @@ pub(crate) trait Gizmo: Clone + Send + Sync + 'static { /// The command and params a drag of `grab` from `from` to `to` runs fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>; + /// As [`Gizmo::edit`], the drag snapping to the tool bar's steps while `snapping` (a gizmo with none ignores it) + fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2, _snapping: bool) -> Option<(&'static str, Value)> { + self.edit(app, rect, grab, from, to) + } + /// The cursor over `grab`, or dragging it fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon; } diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs index 184009c1..51a8028f 100644 --- a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -10,6 +10,8 @@ pub(crate) struct GizmoDrag { pub(crate) grab: G::Grab, /// Where the drag started pub(crate) from: Pos2, + /// The loaded mesh at press time, including its UV layout + pub(crate) mesh_id: u64, /// The starting gizmo shared by the pointer, edit and overlay paths pub(crate) start: Arc, /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there diff --git a/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs index 1fb9148e..151fa50b 100644 --- a/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs @@ -15,9 +15,13 @@ pub(crate) enum ShownGizmo { impl ShownGizmo { /// The gizmo of the selected fill's projection: none while the Projection row's eye hides it pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { - FrameGizmo::shown(app, rect) + if !app.session.doc.project.display.projection_gizmos { + return None; + } + + FrameGizmo::of(app, rect) .map(|frame| ShownGizmo::Frame(Box::new(frame))) - .or_else(|| RoundGizmo::shown(app, rect).map(|round| ShownGizmo::Round(Box::new(round)))) + .or_else(|| RoundGizmo::of(app, rect).map(|round| ShownGizmo::Round(Box::new(round)))) } fn frame(gizmo: Option<&ShownGizmo>) -> Option<&FrameGizmo> { diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index c2df268d..bf295906 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -285,9 +285,8 @@ impl PropertySheet<'_> { }); // Escape ends hex editing first even when egui has already dropped the field's focus - let escape = ctx.input(|input| input.key_pressed(egui::Key::Escape)) - && ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id)) - && !hex_took_escape(&ctx); + let escape = + crate::framework::escape_pressed(&ctx) && crate::framework::focused_widget(&ctx).is_none_or(|focused| focused == bar.id) && !hex_took_escape(&ctx); if closed || (!list_open && !waiting && (pressed_outside || escape)) { state.open = false; crate::color_picker::forget_window(&ctx); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index a9097cd7..51c6ecfb 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -74,8 +74,8 @@ pub(crate) use preview_size::PreviewSize; pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{ - SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, - full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, + SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope, + room_past_end, section_tabs, }; pub(crate) use sheet::PropertySheet; pub(crate) use size_columns_response::SizeColumnsResponse; diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 7a4e7d73..595116ca 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -109,13 +109,8 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW)) } -/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab -pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { - Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) -} - /// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip -pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { +fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index 615ff4cc..6c18282d 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -56,11 +56,6 @@ fn icons_id() -> Id { Id::unique("rail_popup_icons") } -/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over -fn pending_drag_id() -> Id { - Id::unique("rail_popup_pending_drag") -} - /// Where the dock drew the viewport on this frame fn viewport_id() -> Id { Id::unique("rail_popup_viewport") @@ -114,16 +109,6 @@ pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { } } -/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated -pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) { - let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return }; - - ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id())); - if ctx.input(|input| input.pointer.primary_down()) { - craft_ui::docking::begin_drag(ctx, dock_area, panel, title); - } -} - /// A rail popup and its dismissing press cannot start a paint stroke or move a decal pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> bool { let closing_id = area_id().with("closing"); @@ -196,13 +181,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // The floating window opens where the popup was, at its size app.ui.rail_panel = None; if let Some(rect) = shown { - app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); + app.ui.dock.float_at(panel, rect); } } else if let Some(title) = dragged_from { + // The floating window opens where the popup was app.ui.rail_panel = None; - let rect = shown.unwrap_or(title); - app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); - ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title))); + let window = shown.unwrap_or(title); + app.ui.dock.float_at(panel, window); + // The window takes over the held press in the next pass, so the drag carries on and docks where it is released + if let Some(pointer) = ctx.input(|input| input.pointer.latest_pos()) { + app.docks.hand_over(panel, pointer - window.min); + } } } diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index 114bef4c..08218627 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -39,7 +39,10 @@ fn environment_cache_retains_source_identity_until_replaced() { // The harness draws once; parallel translation tests must not change its language mid-frame let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + let mut app = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| crate::TextureCraftApp::new(context, session())) + .into_state(); app.session.doc.project.display.environment = "resource:environment".into(); let source = Arc::new(ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0]; 2], false)); let original_source = Arc::downgrade(&source); @@ -71,7 +74,10 @@ fn environment_cache_retains_source_identity_until_replaced() { #[test] fn a_new_display_background_restarts_the_render() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + let mut app = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| crate::TextureCraftApp::new(context, session())) + .into_state(); let before = super::key(&app, "scene", (64, 64)); assert_eq!(super::key(&app, "scene", (64, 64)), before); @@ -109,6 +115,7 @@ fn gpu_app() -> Option { let mut app = egui_kittest::Harness::builder() .with_size(egui::vec2(800.0, 600.0)) .renderer(WgpuTestRenderer::from_render_state(render_state)) + .with_context_setup(crate::framework::install_headless) .build_eframe(|context| crate::TextureCraftApp::new(context, session())) .into_state(); app.session.update(); diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 4bbba1a4..b25175f3 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -72,11 +72,6 @@ const BOX_AXIS_BITS: [usize; 3] = [1, 2, 4]; const STEP_PROBE_RADII: f32 = 0.5; impl RoundGizmo { - /// The projector as the 3D view shows it: none while the Projection row's eye hides the projection gizmos - pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { - RoundGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) - } - /// The projector of the selected tri-planar, spherical or cylindrical fill pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { if app.ui.mode != crate::state::Mode::Painting { @@ -153,7 +148,7 @@ impl RoundGizmo { let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach; let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE); self.rings = directions.map(|direction| { - if !ring_open(app, rect, center, direction) { + if !ring_open(app, rect, center, direction, TURN_RING) { return Vec::new(); } diff --git a/crates/ui-egui/src/sample_project.rs b/crates/ui-egui/src/sample_project.rs new file mode 100644 index 00000000..a5f63ec2 --- /dev/null +++ b/crates/ui-egui/src/sample_project.rs @@ -0,0 +1,33 @@ +//! Installs the bundled projects in the data folder for File > Open Sample Project. + +mod shipped_sample; + +use std::io::ErrorKind; +use std::path::Path; + +use shipped_sample::ShippedSample; + +/// The folder under the data folder that holds the sample projects +pub(crate) const SAMPLES_FOLDER: &str = "Samples"; + +const SHIPPED_SAMPLES: &[ShippedSample] = + &[ShippedSample { file_name: "Material Ball.tcraft", bytes: include_bytes!("../../../assets/samples/Material Ball.tcraft") }]; + +/// Makes sure `folder` exists and holds every shipped sample. A file that is already there is +/// kept as it is, so a sample the user edited and saved stays. +pub(crate) fn install(folder: &Path) -> Result<(), String> { + std::fs::create_dir_all(folder).map_err(|error| format!("{}: {error}", folder.display()))?; + + for sample in SHIPPED_SAMPLES { + let destination = folder.join(sample.file_name); + match destination.symlink_metadata() { + Ok(_) => continue, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(format!("{}: {error}", destination.display())), + } + + sample.install_missing(folder, &destination).map_err(|error| format!("{}: {error}", destination.display()))?; + } + + Ok(()) +} diff --git a/crates/ui-egui/src/sample_project/shipped_sample.rs b/crates/ui-egui/src/sample_project/shipped_sample.rs new file mode 100644 index 00000000..40a62847 --- /dev/null +++ b/crates/ui-egui/src/sample_project/shipped_sample.rs @@ -0,0 +1,42 @@ +use std::io::{self, ErrorKind, Write as _}; +use std::path::Path; + +/// A built-in sample project and its installed filename. +pub(super) struct ShippedSample { + pub(super) file_name: &'static str, + pub(super) bytes: &'static [u8], +} + +impl ShippedSample { + pub(super) fn install_missing(&self, folder: &Path, destination: &Path) -> io::Result<()> { + let mut staged_sample = tempfile::NamedTempFile::new_in(folder)?; + staged_sample.write_all(self.bytes)?; + staged_sample.as_file().sync_all()?; + + // A user can save to the destination while the bundled copy is being written + match staged_sample.persist_noclobber(destination) { + Ok(_) => Ok(()), + Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(()), + Err(error) => Err(error.error), + } + } +} + +#[cfg(test)] +mod tests { + use super::ShippedSample; + + #[test] + fn a_sample_that_appears_during_install_is_kept() { + let folder = tempfile::tempdir().unwrap(); + let sample = ShippedSample { file_name: "Sample.tcraft", bytes: b"bundled sample" }; + let destination = folder.path().join(sample.file_name); + assert!(!destination.exists()); + std::fs::write(&destination, b"user project").unwrap(); + + sample.install_missing(folder.path(), &destination).unwrap(); + + assert_eq!(std::fs::read(&destination).unwrap(), b"user project"); + assert_eq!(std::fs::read_dir(folder.path()).unwrap().count(), 1, "the temporary copy was removed"); + } +} diff --git a/crates/ui-egui/src/screen_color_pick.rs b/crates/ui-egui/src/screen_color_pick.rs index 6da89f2b..9892dbdf 100644 --- a/crates/ui-egui/src/screen_color_pick.rs +++ b/crates/ui-egui/src/screen_color_pick.rs @@ -44,8 +44,8 @@ fn pick_with(ui: &mut Ui, id: Id, linear: &mut [f32; 3], button: impl FnOnce(&mu pick.target = if picking { None } else { Some(id) }; } else if picking { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - let (clicked, escaped, pointer) = - ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos())); + let (clicked, pointer) = ui.input(|input| (input.pointer.primary_clicked(), input.pointer.interact_pos())); + let escaped = crate::framework::escape_pressed(ui.ctx()); if escaped { pick.target = None; } else if clicked && let Some(point) = pointer { diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 96f5c25f..42b8494e 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -1,12 +1,14 @@ //! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree -use craft_ui::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitLayout, SplitSize, split_rect}; +use craft_behavior::dock::SplitSize; +use craft_behavior::flow::Axis; use egui::{Rect, RichText, Ui, UiBuilder}; use egui_phosphor::regular as ic; use serde::{Deserialize, Serialize}; use crate::TextureCraftApp; use crate::i18n::{n_, tr}; +use crate::pane_split::{ResizeHandle, ResizeHandleStyle, SplitLayout, split_rect}; use crate::saved_search::SavedSearch; use crate::shelf::TABS; use crate::theme::Tokens; @@ -93,7 +95,7 @@ fn splitter(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) -> Option Option 2.0 * minimum_points { let colors = ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill }; - let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors) + let delta = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors) .hit_margin(0.0) .value(layout.first_size(), minimum_points..=available_points - minimum_points) .show(ui); - if resize.delta != 0.0 - && let Some(SplitSize::Ratio(share)) = layout.resized(size, resize.delta, minimum_points) + if delta != 0.0 + && let Some(SplitSize::Ratio(share)) = layout.resized(size, delta, minimum_points) { app.ui.shelf_panes_split = share; layout = split_rect(rect, axis, SplitSize::Ratio(share), SPLITTER_HEIGHT_POINTS, minimum_points)?; diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rs new file mode 100644 index 00000000..b09dd531 --- /dev/null +++ b/crates/ui-egui/src/shortcut_dispatch.rs @@ -0,0 +1,255 @@ +//! The frame's key presses and clipboard events as the shortcuts they run: egui's events fed to +//! `craft_keymap::Matcher`, one press at a time in press order. +//! +//! - A press that runs a command is removed from egui's input, with the text it typed; one that +//! runs nothing, or whose hit the caller declines, stays. +//! - Held keys run their command again on each repeat (a held arrow nudges); repeats never count +//! toward a double press. +//! - egui's Copy, Cut and Paste events count as their plain chords (Cmd+C, Cmd+X, Cmd+V; +//! Shift+Delete and Shift+Insert), so the desktop's clipboard events run the edit commands. The +//! web build sends a clipboard press and the clipboard event it causes: the press decides, and +//! its event goes with it when it runs a command and stays otherwise. +//! - The keyboard layout is learned from what plain presses type, and taken from egui when the +//! integration reports whether it is Latin. + +use craft_keymap::{Active, Hit, Key, KeyInput, Keymap, Layout, Matcher, Mods, Platform, Press}; +use egui::{Event, InputState, Key as EguiKey}; + +/// eframe's web build sends a press's Text event first when no text field has focus. +const TEXT_FIRST: bool = cfg!(target_arch = "wasm32"); + +/// What matching carries between frames: the previous press (double presses) and the layout. +#[derive(Default)] +pub(crate) struct Dispatcher { + matcher: Matcher, + layout: Layout, + /// Whether right Alt is held. egui-winit reports AltGr with neither Ctrl nor Alt, so its + /// presses would otherwise teach the layout as plain ones. + right_alt: bool, +} + +impl Dispatcher { + /// The keyboard layout learned so far: what a press stands for as a chord. + pub(crate) fn layout(&self) -> &Layout { + &self.layout + } + + /// The commands this frame's key presses and clipboard events run, in press order, with + /// `accept` deciding each hit before its event is removed. A declined hit is left out and its + /// event, with any text it typed, stays in egui's input in its place. + pub(crate) fn dispatch_filtered(&mut self, input: &mut InputState, keymap: &Keymap, mut accept: impl FnMut(&Hit) -> bool) -> Vec { + let platform = keymap.platform(); + let now = input.time; + let frame_mods = Mods::from_egui(&input.modifiers, platform); + let events = std::mem::take(&mut input.events); + let text_of = text_of_press(&events, TEXT_FIRST); + if let Some(latin) = input.keyboard_layout_is_latin() { + self.layout.set_latin(Some(latin)); + } + self.learn(&events, &text_of, platform); + let causes = clipboard_event_follows(&events, &self.layout, platform, input); + let mut caused_taken: Vec> = vec![None; events.len()]; + let mut drop = vec![false; events.len()]; + let mut hits = Vec::new(); + let mut kept = Vec::with_capacity(events.len()); + for (i, event) in events.into_iter().enumerate() { + match &event { + Event::Key { pressed: true, repeat, .. } => { + let key = key_input(&event, platform, input); + if self.layout.resolve(&key).is_some() { + let press = Press { input: &key, repeat: *repeat, now, active: &Active::NONE, outer: &[] }; + let hit = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept); + if let Some((j, _)) = causes[i] { + caused_taken[j] = Some(hit.is_some()); + } + if let Some(hit) = hit { + hits.push(hit); + if let Some(j) = text_of[i].filter(|_| !(key.mods.cmd || key.mods.ctrl)) { + drop[j] = true; + } + continue; + } + } + } + // Desktop clipboard events, and web ones whose press ran nothing. + Event::Copy | Event::Cut | Event::Paste(_) => match caused_taken[i] { + Some(true) => continue, + Some(false) => {} + None => { + let (key, held) = clipboard_chord(&event, frame_mods); + let press = Press { input: &KeyInput::new(held).with_typed(key), repeat: false, now, active: &Active::NONE, outer: &[] }; + if let Some(hit) = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept) { + hits.push(hit); + continue; + } + } + }, + _ => {} + } + kept.push((i, event)); + } + input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect(); + hits + } + + /// Teaches the layout what this frame's presses typed. + fn learn(&mut self, events: &[Event], text_of: &[Option], platform: Platform) { + for (event, text) in events.iter().zip(text_of) { + match event { + Event::Key { physical_key: Some(EguiKey::AltRight), pressed, .. } => self.right_alt = *pressed, + Event::WindowFocused(false) => self.right_alt = false, + _ => {} + } + if self.right_alt { + continue; + } + let Some(Event::Text(text)) = text.and_then(|j| events.get(j)) else { continue }; + if let Some(KeyInput { mods, physical: Some(physical), .. }) = KeyInput::from_egui(event, platform) { + self.layout.observe(physical, mods, text); + } + } + } +} + +/// A press as [`KeyInput::from_egui`] reads it, with the Latin layout's character `input` reports +/// for its key. +fn key_input(event: &Event, platform: Platform, input: &InputState) -> KeyInput { + let mut key = KeyInput::from_egui(event, platform).unwrap_or(KeyInput::new(Mods::NONE)); + if let Event::Key { physical_key: Some(physical), .. } = event { + key.latin = input.latin_layout_char(*physical); + } + key +} + +/// A clipboard event's kind. +#[derive(Clone, Copy)] +enum Clip { + Copy, + Cut, + Paste, +} + +fn event_clip(event: &Event) -> Option { + match event { + Event::Copy => Some(Clip::Copy), + Event::Cut => Some(Clip::Cut), + Event::Paste(_) => Some(Clip::Paste), + _ => None, + } +} + +/// The clipboard event a backend sends for a press, if any. +fn clipboard_kind(key: Key, held: Mods) -> Option { + match key { + Key::C if held.cmd => Some(Clip::Copy), + Key::X if held.cmd => Some(Clip::Cut), + Key::V if held.cmd => Some(Clip::Paste), + Key::Delete if held.shift => Some(Clip::Cut), + Key::Insert if held.shift => Some(Clip::Paste), + Key::Insert if held.cmd || held.ctrl => Some(Clip::Copy), + _ => None, + } +} + +/// For each clipboard key press whose clipboard event comes later in the frame, as the web build +/// sends them: the index of that event, and the text of a Paste event. +fn clipboard_event_follows(events: &[Event], layout: &Layout, platform: Platform, input: &InputState) -> Vec)>> { + let mut out = vec![None; events.len()]; + let mut ahead: [Option; 3] = [None; 3]; + for (i, event) in events.iter().enumerate().rev() { + if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) { + *seen = Some(i); + } else if let Event::Key { pressed: true, .. } = event { + let chord = layout.resolve(&key_input(event, platform, input)); + let clip = chord.and_then(|c| clipboard_kind(c.key, c.mods)); + if let Some(j) = clip.and_then(|c| ahead.get_mut(c as usize)).and_then(Option::take) { + let text = if let Some(Event::Paste(text)) = events.get(j) { Some(text.clone()) } else { None }; + out[i] = Some((j, text)); + } + } + } + out +} + +/// For each key press, the index of the Text event it typed. egui-winit, and eframe's web text +/// agent while a text field has focus, send the Text after the press, before the next one. +/// With `text_first`, eframe's web build with no text field focused, the Text comes right before +/// its press, and only for a press without Ctrl or Cmd. +fn text_of_press(events: &[Event], text_first: bool) -> Vec> { + let is_text = |e: Option<&Event>| matches!(e, Some(Event::Text(t)) if !t.is_empty()); + let mut out = vec![None; events.len()]; + if text_first { + for (i, event) in events.iter().enumerate().skip(1) { + if let Event::Key { pressed: true, modifiers, .. } = event + && !(modifiers.ctrl || modifiers.command || modifiers.mac_cmd) + && is_text(events.get(i - 1)) + { + out[i] = Some(i - 1); + } + } + return out; + } + let mut text_ahead = None; + for (i, event) in events.iter().enumerate().rev() { + match event { + Event::Key { pressed: true, .. } => out[i] = text_ahead.take(), + _ if is_text(Some(event)) => text_ahead = Some(i), + _ => {} + } + } + out +} + +/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also +/// sends Cut for Shift+Delete and Paste for Shift+Insert. +fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { + let with_cmd = Mods { cmd: true, ..held }; + let shift_only = held.shift && !held.cmd; + match event { + Event::Cut if shift_only => (Key::Delete, held), + Event::Cut => (Key::X, with_cmd), + Event::Paste(_) if shift_only => (Key::Insert, held), + Event::Paste(_) => (Key::V, with_cmd), + _ => (Key::C, with_cmd), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_keymap::{Binding, CommandDef, Scope, Scopes}; + + fn keymap() -> Keymap { + let def = |id: &'static str, binding: &str| CommandDef::new(id, id, Scope::app()).with_default(Binding::parse(binding).unwrap()); + Keymap::new(vec![def("tool.marquee", "M"), def("edit.copy", "Ctrl+C")], Scopes::new(), Platform::Windows) + } + + fn press(key: EguiKey, modifiers: egui::Modifiers) -> Event { + Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers } + } + + /// A press that runs a command leaves egui's input with the text it typed; the others stay, in order. + #[test] + fn a_bound_press_and_its_text_leave_the_input() { + let mut input = InputState::default(); + input.events = + vec![press(EguiKey::M, egui::Modifiers::NONE), Event::Text("m".into()), press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())]; + let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true); + assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::>(), ["tool.marquee"]); + assert_eq!(input.events, [press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())]); + } + + /// The desktop's Copy event runs the copy command; declined, it stays for egui. + #[test] + fn a_clipboard_event_runs_its_chord_unless_declined() { + let mut input = InputState::default(); + input.events = vec![Event::Copy]; + let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true); + assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::>(), ["edit.copy"]); + assert!(input.events.is_empty()); + + input.events = vec![Event::Copy]; + assert!(Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| false).is_empty()); + assert_eq!(input.events, [Event::Copy]); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7fad78a2..c4836bc6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -295,6 +295,9 @@ pub struct NewProject { /// Import settings > Import cameras: keep the cameras stored in the mesh file #[serde(default = "import_cameras_default")] pub import_cameras: bool, + /// Import settings > Rebuild mesh UVs. + #[serde(default)] + pub rebuild_uvs: bool, /// Color management as chosen in the window (the project is always created as Legacy) #[serde(skip)] pub color_management: crate::project_form::ColorManagement, @@ -332,6 +335,7 @@ impl Default for NewProject { template: default_template(), normal_format: None, import_cameras: true, + rebuild_uvs: false, color_management: crate::project_form::ColorManagement::Legacy, baked_maps: Vec::new(), } @@ -635,6 +639,9 @@ pub struct UiState { /// How the 3D view shows symmetry #[serde(default)] pub symmetry: crate::symmetry::SymmetryDisplay, + /// The warp tool bar: the gizmo's mode and space, its size, and the steps its drags snap to + #[serde(default)] + pub warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings, /// The brush, symmetry and other tool settings of the last session, which the next one starts with #[serde(default)] pub tool_settings: texturecraft_engine::ToolSettings, @@ -742,6 +749,7 @@ impl UiState { self.nav_buttons = keep.nav_buttons; self.keymap = keep.keymap; self.tool_settings = keep.tool_settings; + self.warp_toolbar = keep.warp_toolbar; self.named_layouts = keep.named_layouts; self.bake_presets = keep.bake_presets; self.layout_dialog = None; @@ -802,6 +810,7 @@ impl Default for UiState { keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), symmetry: crate::symmetry::SymmetryDisplay::default(), + warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings::default(), tool_settings: Default::default(), bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), named_layouts: Vec::new(), @@ -856,8 +865,12 @@ mod tests { } #[test] - fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() { + fn adopting_a_layout_keeps_recent_files_and_user_settings() { + use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings}; + + let warp_toolbar = WarpToolbarSettings { mode: GizmoMode::Rotate, space: GizmoSpace::World, manipulator_size: 0.4, grid_steps: 0.5, angle_steps: 30.0 }; let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; + ui.warp_toolbar = warp_toolbar; ui.export.preset = "Mine".into(); ui.keymap.insert("file.save".into(), "F5".into()); let mut layout = UiState::default(); @@ -869,6 +882,7 @@ mod tests { assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); + assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings"); } #[test] diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 5b32a6c0..30af4f1e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -324,9 +324,21 @@ pub fn font_definitions() -> egui::FontDefinitions { fonts } +/// Gives the context `fonts` through the framework runtime, which keeps its layout memory in step with them. The +/// framework's chrome (the dock, the update dialogs) also draws in the signature and semibold families: signature +/// takes the proportional faces and semibold TextureCraft's own semibold list. A family left out draws missing-glyph +/// boxes. +pub fn load_fonts(ctx: &egui::Context, mut fonts: egui::FontDefinitions) { + let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); + let semibold = fonts.families.get(&FontFamily::Name(SEMIBOLD.into())).cloned().unwrap_or_else(|| proportional.clone()); + fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional); + fonts.families.insert(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()), semibold); + craft_ui::fonts::load(ctx, fonts); +} + /// Install the fonts (once, at startup; the app applies the style from its settings). pub fn install(ctx: &egui::Context) { - ctx.set_fonts(font_definitions()); + load_fonts(ctx, font_definitions()); } /// Apply brightness `b` and `accent`: store the tokens for [`Tokens::get`] and style egui with @@ -371,8 +383,18 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) { v.selection.stroke = Stroke::new(1.0, t.text_strong); v.hyperlink_color = t.accent; let w = &mut v.widgets; - craft_ui::theme::WidgetPalette { noninteractive: t.panel, inactive: t.button, hovered: t.row_hover, active: t.tool_active, open: t.row_hover } - .apply_to(w, t.cr(), Stroke::new(1.0, t.text)); + for (widget, fill) in [ + (&mut w.noninteractive, t.panel), + (&mut w.inactive, t.button), + (&mut w.hovered, t.row_hover), + (&mut w.active, t.tool_active), + (&mut w.open, t.row_hover), + ] { + widget.bg_fill = fill; + widget.weak_bg_fill = fill; + widget.corner_radius = t.cr(); + widget.fg_stroke = Stroke::new(1.0, t.text); + } // Hovered and pressed lettering, and `RichText::strong` (captions), in the strong colour w.hovered.fg_stroke.color = t.text_strong; diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 4f328a85..024675b1 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -1,8 +1,9 @@ //! The strip at the top of the window: the app icon at the very left, the menus and the mode label, -//! and the window's title bar unless the system draws one. As the title bar its empty space moves -//! the window and follows the system's double-click setting (craft-window's `title_bar`), and on a -//! window without an OS frame it also has the minimize, maximize/restore and close buttons and -//! invisible resize zones along the window's edges. +//! and the window's title bar unless the system draws one. As the title bar it is craft-ui's +//! `shell::TitleBar`: its free area moves the window and follows the system's double-click +//! setting, and on a window without an OS frame it has the caption buttons of the desktop's +//! layout; the window keeps invisible resize zones along its edges where the runtime does not +//! answer the window's hit test itself (everywhere but Windows). //! //! Who draws the frame is decided once at startup ([`TitleBar::decide`]): Windows draws no OS //! frame, macOS keeps its traffic lights over the strip (a full-size content view with a hidden @@ -11,12 +12,14 @@ //! overrides that, and Settings › Interface › System title bar brings the OS frame back on the //! next start. The web build has no window frame: the strip is the menu bar. -use craft_window::{Button, Frame, Layout}; +use craft_ui::contract::ShowContainer as _; +use craft_ui::runtime::windows::WindowHost; +use craft_window::policy::{Decision, TitleBarPref}; +use craft_window::{Frame, Layout}; use egui::emath::GuiRounding as _; -use egui::{Align, Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2}; +use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Ui, ViewportCommand, pos2, vec2}; use crate::TextureCraftApp; -use crate::i18n::tr; use crate::theme::Tokens; /// Who draws the window's title bar. @@ -31,13 +34,9 @@ pub enum TitleBar { App(Layout), } -/// One caption button: as wide as Windows' own. -pub const BUTTON_WIDTH: f32 = 46.0; -/// The room at the strip's left for the macOS traffic lights (their width and the gaps around them). -const TRAFFIC_LIGHTS: f32 = 78.0; /// The app icon's side, in points. const ICON: f32 = 16.0; -/// The space between the strip's edges (or its caption buttons) and its content. +/// The space between the icon and the menus. const PAD: f32 = 8.0; /// Resize zone thickness along an edge, and the side of a corner zone. const EDGE: f32 = 5.0; @@ -53,6 +52,9 @@ const ICONS: [(f32, &[u8]); 5] = [ (64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")), ]; +/// The override variable's prefix: `TEXTURECRAFT_TITLEBAR`. +const PREFIX: craft_window::Prefix = craft_window::Prefix::new("TEXTURECRAFT"); + /// The Nightly strip's icon PNGs, same sizes: the deeper background tells the two windows apart at /// a glance and matches the packaged Nightly icon. const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ @@ -64,11 +66,24 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ ]; impl TitleBar { - /// Decide who draws the title bar; call once at startup, before the window is created. + /// Decide who draws the title bar; call once at startup, before the window is created, and + /// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`). /// `system` is Settings › Interface › System title bar. - pub fn decide(system: bool) -> TitleBar { - let choice = craft_window::Choice::probe(craft_window::Prefix::new("TEXTURECRAFT")); - Self::from_choice(choice.frame(), choice.overridden(), system) + pub fn decide(system: bool) -> Decision { + let choice = craft_window::Choice::probe(PREFIX); + let wanted = Self::from_choice(choice.frame(), choice.overridden(), system); + let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated }; + craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref) + } + + /// The bar a decided `frame` gives. + pub fn of(frame: &craft_window::policy::Frame) -> TitleBar { + use craft_window::policy::Frame as Decided; + match frame { + Decided::Native => TitleBar::System, + Decided::Inset(_) => TitleBar::Integrated, + Decided::Integrated(captions) => TitleBar::App(captions.layout.clone()), + } } /// `TEXTURECRAFT_TITLEBAR` (`overridden`) wins, then the System title bar setting. Otherwise @@ -87,17 +102,6 @@ impl TitleBar { } } - /// `builder` with this frame: decorations off for the app's own, and on macOS the content - /// under a transparent title bar without its title. - pub fn viewport(&self, builder: egui::ViewportBuilder) -> egui::ViewportBuilder { - let frame = match self { - TitleBar::App(layout) => Frame::App(layout.clone()), - _ => Frame::Desktop, - }; - let builder = craft_window::decorate(builder, &frame); - if *self == TitleBar::Integrated { builder.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false) } else { builder } - } - /// The name `ui.inspect` reports: `app`, `integrated` or `system`. pub fn name(&self) -> &'static str { match self { @@ -108,38 +112,48 @@ impl TitleBar { } } +/// `builder` with the decided frame: decorations off for the app's own, and on macOS the content +/// under a transparent title bar without its title. +pub fn viewport(decision: &Decision, builder: egui::ViewportBuilder) -> egui::ViewportBuilder { + craft_window::policy::apply(builder, &decision.frame) +} + /// The strip's height: the body text with room around it, 28 to 32 points (so the macOS traffic /// lights and Windows-sized caption buttons fit it). pub fn height(ui: &Ui) -> f32 { (ui.text_style_height(&egui::TextStyle::Body) + 14.0).clamp(28.0, 32.0) } -/// The strip: menus between the app icon and the mode label, the window buttons at the ends the -/// layout names, and as the title bar its empty space moving the window. +/// The strip: the app icon, then the menus. Where the system draws the frame it is the menu bar; +/// otherwise it is the window's title bar (craft-ui's), with the caption buttons where the frame +/// has them and resize zones along the window's edges. pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - let bar = app.title_bar.clone(); - let (left, right) = match &bar { - TitleBar::App(layout) => (layout.left.as_slice(), layout.right.as_slice()), - _ => (&[][..], &[][..]), - }; - egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| { - let rect = ui.max_rect(); - // First, so the strip's controls drawn over it keep their own clicks. - if bar != TitleBar::System { - craft_window::title_bar::empty_area(ui, rect); - } - let ends = |n: usize| n as f32 * BUTTON_WIDTH; - let inset = if bar == TitleBar::Integrated { TRAFFIC_LIGHTS } else { ends(left.len()) + PAD }; - let content = Rect::from_min_max(pos2(rect.left() + inset, rect.top()), pos2(rect.right() - ends(right.len()) - PAD, rect.bottom())); - ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(Align::Center)), |ui| { - paint_icon(ui); - crate::menus::menu_bar(app, ui); + let frame = WindowHost::of(ui.ctx()).frame(); + if matches!(frame, craft_window::policy::Frame::Native) { + egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| { + let rect = ui.max_rect(); + let content = Rect::from_min_max(pos2(rect.left() + PAD, rect.top()), pos2(rect.right() - PAD, rect.bottom())); + ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + paint_icon(ui); + crate::menus::menu_bar(app, ui); + }); }); - caption_buttons(ui, left, rect.left(), rect); - caption_buttons(ui, right, rect.right() - ends(right.len()), rect); + return; + } + egui::Panel::top("menu_bar").show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| { + let bar = craft_ui::shell::TitleBar::new() + .show(ui, |ui, _| { + paint_icon(ui); + crate::menus::menu_bar(app, ui); + }) + .output; + if bar.close_requested { + ui.ctx().send_viewport_cmd(ViewportCommand::Close); + } }); - if matches!(bar, TitleBar::App(_)) { + // Windows' frame answers the resize edges itself (the runtime's hit test). + if matches!(frame, craft_window::policy::Frame::Integrated(_)) && !cfg!(windows) { resize_zones(ui); } } @@ -177,92 +191,6 @@ fn maximized(ctx: &egui::Context) -> bool { ctx.input(|i| i.viewport().maximized.unwrap_or(false)) } -/// Caption button ids (stable, so tests and agents can find them). -fn caption_id(b: Button) -> Id { - Id::unique(("titlebar_caption", b as u8)) -} - -/// `buttons` from `x` rightwards, the strip's full height, flush with its top so a maximized -/// window's corner hits the outermost one. -fn caption_buttons(ui: &mut Ui, buttons: &[Button], x: f32, bar: Rect) { - let tk = Tokens::get(ui.ctx()); - let max = maximized(ui.ctx()); - let focused = ui.input(|i| i.viewport().focused.unwrap_or(true)); - for (i, &b) in buttons.iter().enumerate() { - let r = Rect::from_min_size(pos2(x + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height())); - let resp = ui.interact(r, caption_id(b), Sense::click()); - let tip = match b { - Button::Minimize => tr("Minimize"), - Button::Maximize if max => tr("Restore"), - Button::Maximize => tr("Maximize"), - Button::Close => tr("Close"), - }; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - let close = b == Button::Close; - let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) { - (true, _) if close => tk.danger.gamma_multiply(0.8), - (_, true) if close => tk.danger, - (true, _) => tk.button, - (_, true) => tk.row_hover, - _ => Color32::TRANSPARENT, - }; - ui.painter().rect_filled(r, 0.0, fill); - // White on the red, as every system's close button; dimmed while the window is inactive. - let ink = if close && resp.hovered() { - Color32::WHITE - } else if focused { - tk.text - } else { - tk.text_dim - }; - paint_glyph(ui, b, max, r.center(), ink); - if resp.on_hover_text(tip).clicked() { - ui.ctx().send_viewport_cmd(match b { - Button::Minimize => ViewportCommand::Minimized(true), - Button::Maximize => ViewportCommand::Maximized(!max), - // The same request as the system's close button. - Button::Close => ViewportCommand::Close, - }); - } - } -} - -/// The 10-point line glyphs, one physical pixel wide per whole step of the screen's scale and on -/// pixel centres, so they stay crisp at any scale. -fn paint_glyph(ui: &Ui, b: Button, maximized: bool, at: egui::Pos2, ink: Color32) { - let ppp = ui.ctx().pixels_per_point(); - let px = ppp.round().max(1.0); - let stroke = Stroke::new(px / ppp, ink); - // An odd width centres the line in a pixel, an even one on a pixel edge. - let snap = |v: f32| if px as u32 % 2 == 1 { v.round_to_pixel_center(ppp) } else { v.round_to_pixels(ppp) }; - let g = Rect::from_min_max(pos2(snap(at.x - 5.0), snap(at.y - 5.0)), pos2(snap(at.x + 5.0), snap(at.y + 5.0))); - let p = ui.painter(); - match b { - Button::Minimize => { - p.line_segment([g.left_center(), g.right_center()].map(|q| pos2(q.x, snap(q.y))), stroke); - } - // Restore: a front square with the corner of the one behind it. - Button::Maximize if maximized => { - let front = Rect::from_min_max(pos2(g.left(), snap(g.top() + 2.0)), pos2(snap(g.right() - 2.0), g.bottom())); - p.rect_stroke(front, 0.0, stroke, egui::StrokeKind::Middle); - let (l, t) = (snap(g.left() + 2.0), front.top()); - p.line( - vec![pos2(l, t), pos2(l, g.top()), g.right_top(), pos2(g.right(), snap(g.bottom() - 2.0)), pos2(front.right(), snap(g.bottom() - 2.0))], - stroke, - ); - } - Button::Maximize => { - p.rect_stroke(g, 0.0, stroke, egui::StrokeKind::Middle); - } - Button::Close => { - p.line_segment([g.left_top(), g.right_bottom()], stroke); - p.line_segment([g.right_top(), g.left_bottom()], stroke); - } - } -} - -/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners -/// come last so they win where they overlap the edges. fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] { use ResizeDirection::*; let (e, c) = (EDGE, CORNER); @@ -303,17 +231,6 @@ fn resize_zones(ui: &mut Ui) { /// Once per frame after the UI, on macOS with the integrated strip: the traffic lights centred on /// the strip, inset from its left as far as from its top, and AppKit's `movable` flag following /// what is under the pointer (`movable` keeps the value last set). -#[cfg(target_os = "macos")] -pub fn sync_native(bar: &TitleBar, ui: &Ui, frame: &eframe::Frame, movable: &mut Option) { - if *bar != TitleBar::Integrated { - return; - } - let h = height(ui); - // AppKit's buttons are 14 points tall. - frame.set_traffic_lights_position(ui.ctx(), egui::Rangef::new(0.0, h), (h - 14.0) / 2.0); - craft_window::title_bar::sync_movable(ui.ctx(), movable); -} - #[cfg(test)] mod tests { use super::*; @@ -342,16 +259,6 @@ mod tests { assert_eq!(desktop, expected); } - #[test] - fn only_the_app_frame_turns_decorations_off() { - let b = TitleBar::App(Layout::default()).viewport(egui::ViewportBuilder::default()); - assert_eq!(b.decorations, Some(false)); - let b = TitleBar::Integrated.viewport(egui::ViewportBuilder::default()); - assert_eq!((b.decorations, b.fullsize_content_view, b.title_shown), (Some(true), Some(true), Some(false))); - let b = TitleBar::System.viewport(egui::ViewportBuilder::default()); - assert_eq!((b.decorations, b.fullsize_content_view), (Some(true), None)); - } - #[test] fn resize_corners_win_over_edges() { let w = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0)); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 27274a1d..21cf3c93 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -7,6 +7,7 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::drawn_icon::DrawnIcon; +use crate::frame_gizmo::warp_toolbar::{self, WarpTarget}; use crate::i18n::{tr, trf}; use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; @@ -58,16 +59,18 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { return; } + let warp_target = WarpTarget::of(app); + let tool_usable = warp_target.is_none() && app.session.tool_usable(app.session.tool.tool); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); if !scroll_views { view_buttons(app, ui); - if app.session.tool_usable(app.session.tool.tool) { + if warp_target.is_some() || tool_usable { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); } } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - scrolling_tool_controls(app, ui, &tokens, scroll_views); + scrolling_tool_controls(app, ui, &tokens, scroll_views, warp_target, tool_usable); }); }); }); @@ -175,7 +178,7 @@ fn rotation_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } /// An icon button with a caret that opens `menu` below it, highlighted while open -fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { +pub(crate) fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { let button_size = ui.spacing().interact_size.y; let popup_id = ui.make_persistent_id(id_salt); let open = egui::Popup::is_id_open(ui.ctx(), popup_id); @@ -198,7 +201,14 @@ fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&st } /// Scroll tool controls and, in narrow viewports, the view buttons -fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { +fn scrolling_tool_controls( + app: &mut TextureCraftApp, + ui: &mut egui::Ui, + tokens: &Tokens, + scroll_views: bool, + warp_target: Option, + tool_usable: bool, +) { let button_size = ui.spacing().interact_size.y; let strip_width = ui.available_width(); let overflow_id = egui::Id::unique("tool_controls_overflow"); @@ -224,13 +234,14 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); ui.horizontal_centered(|ui| { - // A tool that can't act on the selection leaves the bar, as the shelf greys it - let tool_usable = app.session.tool_usable(app.session.tool.tool); - if tool_usable { + if let Some(target) = warp_target { + warp_toolbar::controls(app, ui, target); + } else if tool_usable { tool_controls(app, ui, tokens); } + if scroll_views { - if tool_usable { + if warp_target.is_some() || tool_usable { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); } let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index f49804c9..b9dd4ee7 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -300,7 +300,7 @@ pub(crate) mod tests { use super::memory_storage::MemoryStorage; use super::*; use crate::docking::{Dock, Panel, default_workspace, permissions}; - use craft_ui::docking::{Action, Placement}; + use craft_behavior::dock::{Action, DockPlacement}; /// Save `ui` and load it back, as closing and reopening the app does pub(crate) fn restart(ui: &UiState) -> UiState { @@ -321,10 +321,10 @@ pub(crate) mod tests { fn moved_panels() -> Dock { let mut workspace = default_workspace(); let actions = [ - Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, - Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + Action::move_beside(Panel::Layers, Panel::Assets, DockPlacement::tab(None)), + Action::float(Panel::Properties, egui::Rect::from_min_size(egui::pos2(900.0, 120.0), egui::vec2(320.0, 400.0))), ]; - workspace.apply_all(actions, permissions).unwrap(); + workspace.apply_all(actions, false, permissions).unwrap(); let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); assert!(!dock.replaced_unreadable(), "the moved layout is valid"); @@ -385,13 +385,14 @@ pub(crate) mod tests { let mut storage = MemoryStorage::default(); UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); let saved = std::fs::read_to_string(&file).unwrap(); - assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + let version = format!("\"version\": {}", crate::docking::Workspace::VERSION); + assert!(saved.contains("\"Assets\"") && saved.contains(&version), "{saved}"); let unreadable = [ // A panel this build does not know saved.replacen("\"Assets\"", "\"Bogus\"", 1), // A layout from a newer format - saved.replacen("\"version\": 2", "\"version\": 99", 1), + saved.replacen(&version, "\"version\": 99", 1), // Not a saved state "not json".to_owned(), ]; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 7b6f0442..4305dd0f 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -1,8 +1,10 @@ //! Software updates on the desktop: the check at start, Help > Check for Updates and the update -//! prompt. An update that is ready starts its install helper when the app is dropped at exit. +//! prompt, as craft-update's dialogs on the app's [`DialogHost`](craft_ui::dialog::DialogHost). An +//! update that is ready starts its install helper when the app is dropped at exit. +use craft_ui::dialog::DialogResult; +use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog}; use craft_update::updater::{Action, Status, Updater}; -use craft_update::{CheckResultDialog, CheckResultResponse}; use crate::TextureCraftApp; @@ -57,9 +59,9 @@ pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) { } let rt = &mut app.updates_rt; if std::mem::take(&mut rt.check_requested) { - rt.updater.check_now(ctx); + rt.updater.check_now(); } else if rt.startup_check { - rt.updater.check_at_start(ctx); + rt.updater.check_at_start(); } rt.updater.tick(ctx); } @@ -77,21 +79,44 @@ fn safe_to_close(app: &TextureCraftApp) -> bool { !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() && app.high_poly_job.is_none() } +/// One pass of the update flow, before the dialog host runs: answers the result dialog closed in +/// the last pass, drives the update prompt, and keeps the result dialog open and current while the +/// updater has something to report. pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let safe = safe_to_close(app); - match app.updates_rt.updater.show_if(ctx, safe) { + // Answered before the dialog is kept open below, so a dismissed outcome does not open again at once + match app.framework_dialogs.take::() { + Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.check_requested = true, + // The next `run` asks the window to close once it is safe to + Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(), + Some(DialogResult::Ok(CheckChoice::Update)) => { + app.updates_rt.updater.request_install(safe); + } + Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())), + // Closing the dialog dismisses the outcome it showed + Some(_) => app.updates_rt.updater.dismiss_status(), + None => {} + } + match app.updates_rt.updater.run(&mut app.framework_dialogs, safe) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - Action::None => {} + _ => {} } - let rt = &mut app.updates_rt; - if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { - match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) { - CheckResultResponse::None => {} - CheckResultResponse::Close => rt.updater.dismiss_status(), - CheckResultResponse::CheckAgain => rt.check_requested = true, - CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), - } + let updater = &app.updates_rt.updater; + let shows = result_window_shows(updater.status(), updater.prompt_open()); + let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message()); + let dialogs = &mut app.framework_dialogs; + if shows && !dialogs.is_open::() { + dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION"))); + } else if !shows && dialogs.is_open::() { + dialogs.cancel::(ctx); + // Hidden for the prompt, not dismissed: the outcome shows again after it + let _ = dialogs.take::(); + } + if let Some(dialog) = dialogs.get_mut::() { + dialog.set_status(status); + dialog.set_installing(installing); + dialog.set_message(message); } } @@ -133,7 +158,10 @@ mod tests { let root = std::env::temp_dir().join(format!("texturecraft-updates-{}-{test}", std::process::id())); let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().updates_rt.updater = Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json")); h.run_steps(2); @@ -149,6 +177,13 @@ mod tests { ..Default::default() }; h.state_mut().updates_rt.updater.offer(release); + // The offer reads on a thread whether this copy can install the release itself; a later frame's tick opens + // the prompt. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !h.state().updates_rt.updater.prompt_open() && std::time::Instant::now() < deadline { + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(2)); + } h.run_steps(2); } @@ -187,7 +222,7 @@ mod tests { let mut h = harness(false, "prompt", ask); offer(&mut h); assert!(h.state().updates_rt.updater.prompt_open()); - h.get_by_label("LATER").click(); + h.get_by_label("Later").click(); h.run_steps(2); assert!(!h.state().updates_rt.updater.prompt_open()); } @@ -203,7 +238,7 @@ mod tests { h.key_press(egui::Key::F8); h.step(); assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard"); - h.get_by_label("LATER").click(); + h.get_by_label("Later").click(); h.run_steps(2); assert!(!crate::docking::input_blocked(h.state(), &h.ctx)); h.key_press(egui::Key::F8); @@ -226,7 +261,7 @@ mod tests { h.key_press(egui::Key::Backspace); h.step(); assert_eq!(points(&h), 2, "the prompt holds the keyboard"); - h.get_by_label("LATER").click(); + h.get_by_label("Later").click(); h.run_steps(2); h.key_press(egui::Key::Backspace); h.step(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index bcddd78f..3ae2bfbd 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -60,6 +60,24 @@ fn aux_view(app: &TextureCraftApp) -> Option { } } +/// The 3D view's widget: the same in the dock and with the UI hidden, so it keeps the focus when Tab hides the UI +pub fn view_3d_id() -> egui::Id { + egui::Id::unique("texturecraft-view3d") +} + +/// The 2D view's widget, as [`view_3d_id`] +pub fn view_2d_id() -> egui::Id { + egui::Id::unique("texturecraft-view2d") +} + +/// Draw the widget of a view and declare it as a document canvas of the window. In a split view both are, so the keys +/// are the same in either. +fn view_widget(ui: &Ui, rect: Rect, id: egui::Id, sense: Sense) -> egui::Response { + let response = ui.interact(rect, id, sense); + crate::framework::host_canvas(ui.ctx(), id); + response +} + /// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; @@ -183,6 +201,8 @@ fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { }; for (rect, id) in regions { + // Nothing to click or drag, but still the window's canvas: Tab hides and shows the UI + view_widget(ui, rect, if id == "v2d" { view_2d_id() } else { view_3d_id() }, Sense::focusable_noninteractive()); ui.painter().rect_filled(rect, 0.0, tokens.viewport); view_header(app, ui, rect, id); } @@ -381,9 +401,14 @@ fn shade(app: &TextureCraftApp) -> Shade { /// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { let set = crate::shelf::drop_set(app, ui, response)?; + + Some(set_highlight(ui, set)) +} + +fn set_highlight(ui: &Ui, texture_set: usize) -> SetHighlight { let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); - Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) + SetHighlight { set: texture_set, color: [accent.r(), accent.g(), accent.b()] } } /// Show what the GPU side reported (each message once while its toast is up). @@ -450,7 +475,15 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] } +#[cfg(test)] +const TEST_SCENE_SET_HOVER: &str = "scene_frame_set_hover"; + fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { + #[cfg(test)] + if frame.view_id == VIEW_3D { + ui.data_mut(|data| data.insert_temp(egui::Id::unique(TEST_SCENE_SET_HOVER), frame.shade.set_hover.map(|highlight| highlight.set))); + } + let tokens = Tokens::get(ui.ctx()); let bake = bake_visualization(app); frame.shade.bake = bake; @@ -732,7 +765,7 @@ pub(crate) fn orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { } fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); + let response = view_widget(ui, rect, view_3d_id(), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); @@ -747,7 +780,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !ui.ctx().egui_wants_keyboard_input(); + let s_held = + app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; @@ -1044,12 +1078,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } + let set_hover = app + .hovered_texture_set + .filter(|&(project_id, _)| project_id == app.session.project_id && !app.ui.hide_ui && !crate::docking::input_blocked(app, ui.ctx())) + .map(|(_, texture_set)| set_highlight(ui, texture_set)); let frame = Frame { view_id: crate::viewport::VIEW_3D, size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + shade: Shade { highlight: drop_highlight(app, ui, &response), set_hover, ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), overlay: crate::symmetry::scene_overlay(app, ui, rect), }; @@ -1229,7 +1267,7 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { return; } - if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() { + if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || crate::framework::widget_has_keyboard(ui.ctx()) { return; } @@ -1706,7 +1744,10 @@ fn uv_fill_box_corners(view: crate::uv_view_map::UvViewMap, [origin, opposite]: /// V held with the Clone tool in painting mode: clicks set the clone source fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) + && app.session.tool.tool == Tool::Clone + && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) + && !crate::framework::widget_has_keyboard(ui.ctx()) } /// Crosshair where the Clone tool reads from. @@ -2089,7 +2130,7 @@ fn framed_tile_view(set: &texturecraft_engine::core::TextureSet, size: egui::Vec /// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); + let response = view_widget(ui, rect, view_2d_id(), Sense::click_and_drag()); let size = rect.size(); let (alt, shift, snap) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift, input.modifiers.shift && input.modifiers.command)); let ctrl = ui.input(|input| input.modifiers.ctrl); @@ -2519,6 +2560,49 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: #[cfg(test)] mod tests { use super::*; + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn hovering_a_texture_set_row_previews_it_without_selecting_it() { + use crate::state::Mode; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + // App creation and frames both set the shared UI language + let _language_guard = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + let session = + Session::new_project("Texture set hover", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let hovered_set = 1; + let name = session.doc.project.texture_sets[hovered_set].name.clone(); + let selected_set = session.ts(); + assert_ne!(hovered_set, selected_set); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + let preview = |harness: &Harness<'_, TextureCraftApp>| { + harness.ctx.data(|data| data.get_temp::>(egui::Id::unique(TEST_SCENE_SET_HOVER))).expect("the 3D view submitted a scene frame") + }; + + for mode in [Mode::Painting, Mode::Baking] { + harness.state_mut().ui.mode = mode; + harness.run_steps(4); + assert_eq!(preview(&harness), None, "{mode:?}: the preview starts clear"); + + harness.get_by_label(&name).hover(); + harness.run_steps(3); + assert_eq!(preview(&harness), Some(hovered_set), "{mode:?}: the hovered set reaches the viewport"); + assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: hover keeps the selected set"); + + let away = harness.state().viewport_rect.center(); + harness.event(egui::Event::PointerMoved(away)); + harness.run_steps(3); + assert_eq!(preview(&harness), None, "{mode:?}: leaving the row clears the preview"); + assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: leaving the row keeps the selected set"); + } + } + #[test] fn the_hover_label_finds_the_tile_under_the_cursor_in_a_turned_view() { let session = Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); @@ -2632,7 +2716,9 @@ mod tests { for tool in [Tool::Paint, Tool::PolygonFill] { let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); app.session.tool.tool = tool; let history = app.session.history_labels().len(); @@ -2661,7 +2747,9 @@ mod tests { // The harness draws the UI, so another test's interface language must not be active let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Painting; app.session.view = ViewMode::Mask(LayerId(7)); @@ -2687,7 +2775,9 @@ mod tests { execute(&mut session, "layer.add.fill", &json!(null)).unwrap(); let effect = texturecraft_engine::core::LayerId(execute(&mut session, "mask.add.colorSelection", &json!(null)).unwrap()["effect"].as_u64().unwrap()); session.target = StackTarget::Effect(effect); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(2); crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None); @@ -2704,7 +2794,10 @@ mod tests { fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.state_mut().session.tool.tool = Tool::PolygonFill; harness.run_steps(4); @@ -2750,7 +2843,9 @@ mod tests { let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap()); let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; paths.resize(8, paths[0].clone()); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let context = egui::Context::default(); let mut previous = Vec::>>>>::new(); @@ -2799,7 +2894,7 @@ mod tests { Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)); let builder = if render { builder.wgpu() } else { builder }; - let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = builder.with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let mut png = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); @@ -2949,7 +3044,9 @@ mod tests { // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Baking; let before = bake_visualization(app).unwrap(); @@ -2972,7 +3069,9 @@ mod tests { #[test] fn the_automatic_cage_shows_no_matching_error() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Baking; assert!(bake_visualization(app).unwrap().matching_error.shown); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 72227984..611864a8 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -449,7 +449,8 @@ mod tests { #[test] fn mesh_picks_only_update_the_current_new_project_request() { let session = Session::closed().unwrap(); - let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); crate::new_project_advanced::open(app); app.ui.new_project.mesh_request_id = 2; @@ -471,7 +472,8 @@ mod tests { #[test] fn environment_pick_after_close_does_not_edit_the_placeholder() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); let old_project_id = harness.state().session.project_id; @@ -493,7 +495,8 @@ mod tests { #[test] fn environment_pick_from_replaced_project_does_not_edit_the_new_project() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); let old_project_id = harness.state().session.project_id; @@ -511,7 +514,8 @@ mod tests { #[test] fn bake_mesh_picks_after_close_do_not_edit_the_placeholder() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); let old_project_id = harness.state().session.project_id; assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); let cage = harness.state().session.mesh_obj_bytes().unwrap(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 126f7be5..991585dc 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1,8 +1,7 @@ //! Compact widgets matching the app's look: labelled slim sliders, icon buttons, section //! headers, channel toggle chips and color swatches. -use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; -use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, StrokeKind, Ui, Vec2, vec2}; use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; @@ -279,6 +278,98 @@ pub fn icon_badge_dropdown_button(ui: &mut Ui, icon: &str, badge: &str, label: & }) } +/// The background, border and icon colour of an icon button in one interaction state. +#[derive(Clone, Copy, Debug, PartialEq)] +struct ButtonVisuals { + fill: Color32, + stroke: Stroke, + icon: Color32, +} + +/// The look of an icon button in each state. Selection takes precedence over press and hover. +#[derive(Clone, Copy, Debug)] +struct IconButtonStyle { + normal: ButtonVisuals, + hovered: ButtonVisuals, + /// `None` keeps the hover or normal look while pressed. + pressed: Option, + selected: ButtonVisuals, + corner_radius: CornerRadius, + /// An inset outline while the button has keyboard focus. + focus_stroke: Stroke, +} + +impl IconButtonStyle { + fn visuals(&self, selected: bool, hovered: bool, pressed: bool) -> ButtonVisuals { + if selected { + self.selected + } else if let Some(visuals) = self.pressed.filter(|_| pressed) { + visuals + } else if hovered { + self.hovered + } else { + self.normal + } + } +} + +/// An icon-only button painted in TextureCraft's own colours. The label is its accessible name; the caller paints +/// the icon, attaches a tooltip and acts on the response. Selection is the caller's. +struct IconButton<'a> { + label: &'a str, + size: Vec2, + selected: bool, + style: &'a IconButtonStyle, +} + +impl<'a> IconButton<'a> { + fn new(label: &'a str, size: Vec2, style: &'a IconButtonStyle) -> Self { + Self { label, size, selected: false, style } + } + + fn selected(mut self, selected: bool) -> Self { + self.selected = selected; + self + } + + /// Paints the button and returns its response. `paint_icon` gets the button's rect and the icon tint. A + /// non-finite, non-positive or oversized (over 4096 points) size gives an inert zero-size response. + fn show(self, ui: &mut Ui, paint_icon: impl FnOnce(&Ui, Rect, Color32)) -> Response { + let valid = self.size.is_finite() && self.size.x > 0.0 && self.size.y > 0.0 && self.size.x <= 4096.0 && self.size.y <= 4096.0; + let (rect, response) = ui.allocate_exact_size(if valid { self.size } else { Vec2::ZERO }, if valid { Sense::click() } else { Sense::hover() }); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, valid && ui.is_enabled(), self.selected, self.label)); + if !valid { + return response; + } + let visuals = self.style.visuals(self.selected, response.hovered(), response.is_pointer_button_down_on()); + let stroke = bounded_stroke(visuals.stroke, rect); + if visuals.fill != Color32::TRANSPARENT { + ui.painter().rect_filled(rect, self.style.corner_radius, visuals.fill); + } + if !stroke.is_empty() { + ui.painter().rect_stroke(rect, self.style.corner_radius, stroke, StrokeKind::Inside); + } + paint_icon(ui, rect, visuals.icon); + if response.has_focus() && rect.width() > 4.0 && rect.height() > 4.0 { + let focus_rect = rect.shrink(2.0); + let stroke = bounded_stroke(self.style.focus_stroke, focus_rect); + if !stroke.is_empty() { + ui.painter().rect_stroke(focus_rect, self.style.corner_radius, stroke, StrokeKind::Inside); + } + } + response + } +} + +/// `stroke` no wider than half of `rect`'s smaller side; none when its width is not positive. +fn bounded_stroke(stroke: Stroke, rect: Rect) -> Stroke { + if stroke.width.is_finite() && stroke.width > 0.0 { + Stroke::new(stroke.width.min(rect.width().min(rect.height()) * 0.5), stroke.color) + } else { + Stroke::NONE + } +} + /// Transparent at rest, a hover well, and the active-tool well when pressed or selected fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b0cd57b7..ba6c3179 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -83,26 +83,18 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved app.session.modified } -/// The close decision, once per frame in `logic` (which also runs while the window is minimized): -/// a close with unsaved changes waits on the dialog, in a window brought back so it can be -/// answered. A close nothing holds open quits through the platform's own path (craft-quit). -pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { - let closing = ctx.input(|i| i.viewport().close_requested()); +/// The close decision, which the runtime asks for when the root window was asked to close (it runs in `logic`, +/// also while the window is minimized): a close with unsaved changes waits on the dialog (`true`), and the runtime +/// brings the window back so it can be answered. A close nothing holds open goes ahead through the platform's own +/// quit. +pub(crate) fn close_requested(app: &mut TextureCraftApp) -> bool { // A stroke still open at the close, or released in this frame, is a change to ask about. - if closing - && app.session.stroke_active() + if app.session.stroke_active() && let Err(error) = app.session.end_stroke() { app.toast(error.to_string(), true); } - if closing && ask_to_save(app, crate::state::Unsaved::Quit) { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - if ctx.input(|i| i.viewport().minimized == Some(true)) { - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - } - craft_quit::on_close_request(ctx); + ask_to_save(app, crate::state::Unsaved::Quit) } /// Quitting, opening or closing a project with unsaved changes asks whether to save them first @@ -542,17 +534,21 @@ pub(crate) fn import_materialx(app: &mut TextureCraftApp, path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { match id { - "file.open" | "project.sample" => { - let dialog = if id == "project.sample" { - FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]) - } else { - FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS) - }; - app.ask_file(dialog, Bound::App, |app, paths| { - if let Some(path) = paths.first() { - open_path(app, &path.display().to_string()); + "file.open" => { + let dialog = FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS); + app.ask_file(dialog, Bound::App, open_picked); + true + } + "project.sample" => { + let dialog = FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]); + let dialog = match crate::sample_project::install(&app.samples_folder) { + Ok(()) => dialog.directory(app.samples_folder.clone()), + Err(error) => { + app.toast(trf("Could not prepare the sample project: {error}", &[("error", &error)]), true); + dialog } - }); + }; + app.ask_file(dialog, Bound::App, open_picked); true } "file.save" if app.session.path.is_some() => { @@ -632,6 +628,14 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } } +/// Opens the project or mesh a file dialog picked +#[cfg(not(target_arch = "wasm32"))] +fn open_picked(app: &mut TextureCraftApp, paths: Vec) { + if let Some(path) = paths.first() { + open_path(app, &path.display().to_string()); + } +} + /// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog /// request, so Save As and Save a Copy queue separately. #[cfg(not(target_arch = "wasm32"))] @@ -715,7 +719,10 @@ mod tests { fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // Match English labels independently of the system locale h.state_mut().ui.prefs.language = "en".into(); @@ -735,7 +742,7 @@ mod tests { harness.state_mut().ui.windows.export = true; harness.run_steps(5); let footer = harness.get_by_role_and_label(egui::Role::Button, "Reset all").rect(); - let first = harness.get_by_label("Export set 1"); + let first = harness.get_by_role_and_label(egui::Role::Button, "Export set 1"); first.hover(); harness.run_steps(2); @@ -747,7 +754,7 @@ mod tests { source: egui::MouseWheelSource::Wheel, }); harness.run_steps(15); - let last = harness.get_by_label("Export set 39"); + let last = harness.get_by_role_and_label(egui::Role::Button, "Export set 39"); last.click(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 02f3ac31..6de467e4 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -19,7 +19,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { } session.view = ViewMode::UvChecker; - let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(3); harness diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index c99708ab..70e75731 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/display_panel.rs b/crates/ui-egui/tests/display_panel.rs index 9c72f884..d38c1af8 100644 --- a/crates/ui-egui/tests/display_panel.rs +++ b/crates/ui-egui/tests/display_panel.rs @@ -18,7 +18,10 @@ const STARTUP_FRAMES: usize = 4; #[test] fn display_picks_the_tone_mapping_from_a_dropdown() { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(Panel::Display); diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index 09e48082..acbd588f 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -17,7 +17,10 @@ fn changed_params() -> AlphaParams { /// The app showing the Alpha tab of Properties, with `brush` fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.brush = brush; harness.state_mut().ui.props_tab = PropsTab::Alpha; diff --git a/crates/ui-egui/tests/it/anchor_point.rs b/crates/ui-egui/tests/it/anchor_point.rs index f161b534..17f0f440 100644 --- a/crates/ui-egui/tests/it/anchor_point.rs +++ b/crates/ui-egui/tests/it/anchor_point.rs @@ -23,7 +23,11 @@ fn anchor_harness() -> (Harness<'static, TextureCraftApp>, LayerId, LayerId, Lay execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); let reader = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": top, "anchor": anchor.0})).unwrap()["effect"].as_u64().unwrap()); execute(&mut session, "layer.select", &json!({"layer": low, "target": anchor.0})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); (harness, anchor, LayerId(top.as_u64().unwrap()), reader) diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 49fe0501..309bb67e 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -11,7 +11,10 @@ use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; /// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let progress = Arc::new(Progress::new()); let (_result_sender, receiver) = std::sync::mpsc::channel(); diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index bbf5d13e..4c7d6c7c 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -22,7 +22,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { // No earlier bake to start the preview from: its first picture is a preview bake at the chosen size session.doc.baked.clear(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R256; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs index bdc67b93..c12cd9fa 100644 --- a/crates/ui-egui/tests/it/bake_map_rows.rs +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -15,7 +15,10 @@ const DRAGGED: [(BakedMap, &str); 3] = [(BakedMap::Normal, "Normal"), (BakedMap: fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.doc.project.texture_sets[0].bake.maps.select(BakedMap::ALL); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index cb0bd007..1f7253ac 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -12,7 +12,10 @@ fn harness(map: Option) -> Harness<'static, TextureCraftApp> { session.doc.project.texture_sets[0].bake = Default::default(); session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; session.doc.project.texture_sets[0].bake.maps.select(map); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); @@ -223,7 +226,10 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { 256, ) .unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); let before = harness.state().session.doc.project.clone(); @@ -274,7 +280,10 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { .unwrap(); texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); let before = session.doc.project.clone(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); @@ -354,8 +363,8 @@ fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { #[test] fn output_axes_unlock_independently_and_relock_to_width() { let mut harness = harness(None); - harness.get_by_label("Texture Sets"); - harness.get_by_label("Mesh Map Settings"); + harness.get_by_role_and_label(Role::Tab, "Texture Sets"); + harness.get_by_role_and_label(Role::Tab, "Mesh Map Settings"); harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 705c2347..395d6d0a 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -17,7 +17,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { texture_set.bake.maps.select([BakedMap::Id]); } - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); @@ -178,7 +181,10 @@ fn a_partial_bake_does_not_count_preserved_unchecked_maps() { set.bake.common.resolution = BakeResolution::R64; set.bake.maps.select([BakedMap::Id]); set.bake_excluded_tiles.insert(1002); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.state_mut().start_bake(vec![0]); diff --git a/crates/ui-egui/tests/it/bake_reset_menus.rs b/crates/ui-egui/tests/it/bake_reset_menus.rs index 4c5c579c..b11fa9b6 100644 --- a/crates/ui-egui/tests/it/bake_reset_menus.rs +++ b/crates/ui-egui/tests/it/bake_reset_menus.rs @@ -13,7 +13,10 @@ use texturecraft_ui_egui::state::Mode; fn harness(target: BakePaintTarget) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::CommonSettings); diff --git a/crates/ui-egui/tests/it/bake_sync.rs b/crates/ui-egui/tests/it/bake_sync.rs index 7c497cc6..c9bd6993 100644 --- a/crates/ui-egui/tests/it/bake_sync.rs +++ b/crates/ui-egui/tests/it/bake_sync.rs @@ -15,7 +15,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { set.bake = Default::default(); set.bake.common.resolution = BakeResolution::R64; } - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); diff --git a/crates/ui-egui/tests/it/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs index ecc5393f..ed9eae98 100644 --- a/crates/ui-egui/tests/it/brush_drag.rs +++ b/crates/ui-egui/tests/it/brush_drag.rs @@ -22,7 +22,10 @@ fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, #[test] fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let c = h.state().viewport_rect.center(); let (brush, yaw, history) = { @@ -50,7 +53,10 @@ fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { fn app(layout: texturecraft_ui_egui::state::ViewLayout) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.layout = layout; h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 8504adc1..16270401 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -69,7 +69,10 @@ fn changed_brush() -> BrushSettings { /// The app showing the brush in Properties, set to `brush` fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index dd11c863..7680561c 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -11,7 +11,10 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } @@ -108,7 +111,11 @@ fn alt_shift_drag_orbits_in_quarter_turns() { /// A harness whose frames are 10 ms apart, so a 0.35 s glide spans about 35 frames and a drag fits inside it. fn slow_glide_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_step_dt(0.01) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/clone_source_view.rs b/crates/ui-egui/tests/it/clone_source_view.rs index 16297442..611de1a7 100644 --- a/crates/ui-egui/tests/it/clone_source_view.rs +++ b/crates/ui-egui/tests/it/clone_source_view.rs @@ -15,7 +15,10 @@ const MARKER_STROKE: f32 = 1.2; fn clone_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; execute(&mut harness.state_mut().session, "tool.clone", &serde_json::Value::Null).unwrap(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs index e1b74688..77a29442 100644 --- a/crates/ui-egui/tests/it/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -10,7 +10,10 @@ use texturecraft_ui_egui::state::Unsaved; fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index c5f2979e..8fe0dad5 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -55,7 +55,10 @@ fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let (session, effect) = color_selection_session(with_id_map); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); (harness, effect) } @@ -294,11 +297,16 @@ fn removing_an_image_during_id_picking_falls_back_to_material() { #[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered views"] fn color_selection_snapshots_and_quick_mask_pick() { let (session, _) = color_selection_session(true); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { - let mut app = TextureCraftApp::new(context, session); - app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; - app - }); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| { + let mut app = TextureCraftApp::new(context, session); + app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; + app + }); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {adapter:?}"); @@ -393,7 +401,10 @@ fn the_background_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click fn the_id_mask_slot_picks_a_texture_and_its_x_goes_back_to_the_mesh_map() { let (mut session, effect) = color_selection_session(true); let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); @@ -419,7 +430,10 @@ fn tile_is_current(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool fn reading_the_mesh_map_shows_no_tile_as_the_current_id_mask() { let (mut session, effect) = color_selection_session(true); let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); assert_eq!(selection(&harness, effect).id_map, None, "the selection reads the ID mesh map"); @@ -456,8 +470,12 @@ fn the_invert_tooltip_shows_right_above_its_button() { #[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered view"] fn invert_tooltip_snapshot() { let (session, _) = color_selection_session(true); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect(); harness.hover_at(invert.center()); @@ -474,7 +492,10 @@ fn a_hand_picked_id_mask_picks_without_a_bake() { session.doc.baked.clear(); let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); harness.get_by_label(PICK_COLOR).click(); @@ -496,7 +517,10 @@ fn clearing_the_only_id_mask_ends_a_waiting_pick() { session.doc.baked.clear(); let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); harness.get_by_label(PICK_COLOR).click(); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/compare_mask_rows.rs b/crates/ui-egui/tests/it/compare_mask_rows.rs index fff39d24..1afaddc6 100644 --- a/crates/ui-egui/tests/it/compare_mask_rows.rs +++ b/crates/ui-egui/tests/it/compare_mask_rows.rs @@ -17,7 +17,11 @@ fn compare_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { let layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone(); let effect = LayerId(execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].as_u64().unwrap()); execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); (harness, effect) diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index 67ed3eca..dc18064a 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -18,7 +18,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { session.update(); let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)); let builder = if render { builder.wgpu() } else { builder }; - let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); diff --git a/crates/ui-egui/tests/it/display_environment.rs b/crates/ui-egui/tests/it/display_environment.rs index 66cfff9f..eab3f207 100644 --- a/crates/ui-egui/tests/it/display_environment.rs +++ b/crates/ui-egui/tests/it/display_environment.rs @@ -13,7 +13,10 @@ const SETTLE: usize = 3; fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.dock.focus(Panel::Display); diff --git a/crates/ui-egui/tests/it/display_post_effects.rs b/crates/ui-egui/tests/it/display_post_effects.rs index df35a767..67943dd0 100644 --- a/crates/ui-egui/tests/it/display_post_effects.rs +++ b/crates/ui-egui/tests/it/display_post_effects.rs @@ -24,7 +24,10 @@ fn display(harness: &Harness<'_, TextureCraftApp>) -> DisplaySettings { /// The app with Display Settings open from the rail and the Post effects section unfolded fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 54157bba..debb9ba9 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -37,7 +37,10 @@ fn dragging_an_effect_row_reorders_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); @@ -66,7 +69,10 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); @@ -112,7 +118,10 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); @@ -151,7 +160,10 @@ fn an_effect_rows_blending_options_reach_every_channel() { let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); execute(&mut session, "effect.set", &json!({"effect": effect, "channel": "baseColor", "blend": "Multiply"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index edce0259..23b262d0 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -26,7 +26,10 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); (harness, effect) } diff --git a/crates/ui-egui/tests/it/empty_menus.rs b/crates/ui-egui/tests/it/empty_menus.rs index 3e669830..921b1b6d 100644 --- a/crates/ui-egui/tests/it/empty_menus.rs +++ b/crates/ui-egui/tests/it/empty_menus.rs @@ -8,7 +8,10 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, docking::Panel, menus}; fn app() -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|cc| TextureCraftApp::new(cc, Session::closed().unwrap())); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, Session::closed().unwrap())); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 09f3c1ca..520e006e 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -7,7 +7,10 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The exact-text checks below need English, whatever the OS language is harness.state_mut().ui.prefs.language = "en".into(); @@ -165,15 +168,26 @@ fn creating_or_opening_a_project_from_the_empty_state_works() { assert!(harness.state().ui.windows.new_project, "New project opens its dialog from the empty state"); let directory = super::temp_dir::TempDir::new("picked-sample"); - let file = directory.join("sample.tcraft"); + let samples_folder = directory.join("Samples"); + std::fs::create_dir(&samples_folder).unwrap(); + let file = samples_folder.join("Material Ball.tcraft"); let sample = Session::new_project("Chosen sample", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); std::fs::write(&file, sample.to_project_bytes().unwrap()).unwrap(); let mut harness = empty(); + harness.state_mut().samples_folder = samples_folder.clone(); let picked = file.clone(); - harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| texturecraft_ui_egui::file_dialogs::Answer::Paths(vec![picked.clone()])))); + let started_in = std::rc::Rc::new(std::cell::RefCell::new(None)); + let recorded = started_in.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |request| { + if let texturecraft_ui_egui::file_dialogs::Request::File(dialog) = request { + *recorded.borrow_mut() = dialog.directory.clone(); + } + texturecraft_ui_egui::file_dialogs::Answer::Paths(vec![picked.clone()]) + }))); invoke(&mut harness, "project.sample"); + assert_eq!(*started_in.borrow(), Some(samples_folder), "the picker starts in the Samples folder"); assert!(harness.state().session.project_open); assert_eq!(harness.state().session.doc.project.name, sample.doc.project.name, "the selected sample project opens"); } @@ -411,12 +425,3 @@ fn close_releases_the_layer_thumbnail_snapshot() { ); } } - -#[test] -fn the_empty_properties_note_starts_at_its_header_names_left_edge() { - let harness = empty(); - let texts = painted(&harness); - let left_of = |wanted: &str| texts.iter().find(|(text, _)| text == wanted).map(|(_, left)| *left).unwrap_or_else(|| panic!("{wanted} is painted")); - - assert_eq!(left_of("No properties found"), left_of("PROPERTIES")); -} diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs index 8967fe80..e8a25aa3 100644 --- a/crates/ui-egui/tests/it/export_file_types.rs +++ b/crates/ui-egui/tests/it/export_file_types.rs @@ -8,7 +8,10 @@ use texturecraft_ui_egui::TextureCraftApp; /// The Export textures window open on SETTINGS fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; @@ -138,7 +141,10 @@ fn export_writes_the_chosen_type_and_depth() { #[test] fn an_old_hidden_bit_depth_is_not_exported() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); // Saved by an older build: "From template" with 16 bits diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 497acf60..15b326b3 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -15,7 +15,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { fn harness_at(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 829fc2d6..d550af41 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -11,7 +11,10 @@ const OPENPBR: &str = "OpenPBR (separate maps)"; /// The Export textures window writing into a scratch folder of its own for `name` fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut app_harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut app_harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); app_harness.state_mut().ui.prefs.language = "en".into(); app_harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 0875dc2f..3579ece6 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -12,7 +12,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { } fn harness_with_session(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; @@ -270,7 +273,10 @@ fn reset_all_then_cancel_restores_the_ticks_and_overrides() { #[test] fn ticks_saved_before_settings_named_their_project_are_kept() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index f264b092..06d3f913 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -11,7 +11,10 @@ use texturecraft_ui_egui::state::{ConsoleLine, ExportJob}; /// The Export textures window writing into a scratch folder of its own for `name` fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let dir = std::env::temp_dir().join(format!("tc-export-progress-{name}-{}", std::process::id())); @@ -126,8 +129,10 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { h.state_mut().ui.export.tab = 2; h.run_steps(4); let set = h.state().session.doc.project.texture_sets[0].name.clone(); - - assert!(h.query_by_label(&set).is_some()); + assert!( + h.query_by_role_and_label(egui::Role::DisclosureTriangle, &set).is_some(), + "the export tree has a node for the set (the dock list row carries the same name)" + ); assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none()); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 94e77c81..041174fb 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -18,7 +18,10 @@ const RAIL_WIDTH_POINTS: f32 = 38.0; /// The Export textures window open on SETTINGS in a screen of `screen_size` fn harness(screen_size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(screen_size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(screen_size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 2c79474b..d3309e43 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -8,7 +8,10 @@ use texturecraft_ui_egui::TextureCraftApp; /// The Export textures window open on SETTINGS fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 80095b94..f9a72c03 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -14,7 +14,10 @@ use library::Library; /// The Output templates tab with two user templates, "Alpha tpl" (selected) and "Beta tpl", saved in `library`. fn harness(library: &Library) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h.state_mut().session.load_export_presets(library.0.clone()); let base = texturecraft_engine::formats::builtin_presets().remove(0); diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index 68f310df..508aa48d 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -26,7 +26,10 @@ impl Drop for Scratch { /// The Export textures window writing into a scratch folder of its own for `name` fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, Scratch) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let dir = std::env::temp_dir().join(format!("tc-export-usd-asset-{name}-{}", std::process::id())); diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index 62c305ea..bfde2258 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -13,7 +13,10 @@ use texturecraft_ui_egui::state::Unsaved; fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } @@ -77,7 +80,12 @@ fn a_canceled_dialog_changes_nothing() { #[test] fn the_sample_picker_asks_to_save_only_after_a_path_is_chosen() { + let samples = super::temp_dir::TempDir::new("sample-picker"); let mut h = harness(true); + let samples_folder = samples.join("Samples"); + std::fs::create_dir(&samples_folder).unwrap(); + std::fs::write(samples_folder.join("Material Ball.tcraft"), b"stand-in").unwrap(); + h.state_mut().samples_folder = samples_folder; answer(&mut h, |_| Answer::Cancelled); invoke(&mut h, "project.sample"); assert_eq!(h.state().file_dialogs.pending(), 1); diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index f369d475..b4972b36 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -26,7 +26,10 @@ fn a_fill_channel_takes_an_image_from_its_source_picker() { let name = session.import_resource_bytes("rough.png", png_bytes).unwrap(); let result = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap(); let layer = LayerId(result["layer"].as_u64().unwrap()); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // Use English so first-run locale does not change queried labels harness.state_mut().ui.prefs.language = "en".into(); @@ -51,7 +54,10 @@ fn the_source_picker_offers_only_images_that_were_decoded() { // Bytes that are not an image never reach the decoded images session.doc.resources.insert("broken.png".into(), std::sync::Arc::new(vec![1, 2, 3])); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // Use English so first-run locale does not change queried labels harness.state_mut().ui.prefs.language = "en".into(); @@ -122,7 +128,10 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { texturecraft_engine::execute(&mut session, "mask.add.black", &json!({})).unwrap(); let output = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"target": "mask"})).unwrap(); let effect_id = LayerId(output["effect"].as_u64().unwrap()); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); @@ -166,7 +175,10 @@ fn a_normal_image_can_be_marked_directx() { let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); let layer = LayerId(out["layer"].as_u64().unwrap()); texturecraft_engine::execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "normal", "image": name})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); diff --git a/crates/ui-egui/tests/it/fill_material_rows.rs b/crates/ui-egui/tests/it/fill_material_rows.rs index 7aae83bf..fe0091a1 100644 --- a/crates/ui-egui/tests/it/fill_material_rows.rs +++ b/crates/ui-egui/tests/it/fill_material_rows.rs @@ -503,6 +503,14 @@ fn the_picker_is_a_window_beside_the_panel_that_its_title_drags_and_its_close_or harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it"); + + click(&mut harness, Role::Button, "Base color"); + harness.ctx.memory_mut(|memory| memory.request_focus(texturecraft_ui_egui::viewport::view_3d_id())); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it with the viewport focused"); } #[test] diff --git a/crates/ui-egui/tests/it/fill_support.rs b/crates/ui-egui/tests/it/fill_support.rs index 6adf3212..543c2269 100644 --- a/crates/ui-egui/tests/it/fill_support.rs +++ b/crates/ui-egui/tests/it/fill_support.rs @@ -18,7 +18,10 @@ pub(crate) fn fill_app(settings: Value, projection: Option<&str>, tab: Option<&s if let Some(projection) = projection { texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); } - let mut harness = Harness::builder().with_size(window).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(window) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/fill_symmetry_rows.rs b/crates/ui-egui/tests/it/fill_symmetry_rows.rs index 158c3b29..42406c5b 100644 --- a/crates/ui-egui/tests/it/fill_symmetry_rows.rs +++ b/crates/ui-egui/tests/it/fill_symmetry_rows.rs @@ -134,7 +134,9 @@ fn commit_value_by_clicking_track(harness: &mut Harness<'_, TextureCraftApp>, va let pos = along(track, 0.75); let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; harness.input_mut().events.extend([egui::Event::PointerMoved(pos), button(true), button(false)]); - harness.step(); + // The runtime takes one press per pass: the click's release, and the field's commit on losing focus, land in the + // next frame + harness.run_steps(2); } #[test] diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 36a1bfc9..6db598f5 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -185,10 +185,14 @@ fn filter_picker_snapshots_and_frame_timings() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)).wgpu().build_eframe(|cc| { - eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); - TextureCraftApp::new(cc, session) - }); + let mut harness = Harness::builder() + .with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| { + eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); + TextureCraftApp::new(cc, session) + }); harness.run_steps(20); let start = std::time::Instant::now(); open_picker(&mut harness); diff --git a/crates/ui-egui/tests/it/filter_support.rs b/crates/ui-egui/tests/it/filter_support.rs index cd8a750e..f070b1f1 100644 --- a/crates/ui-egui/tests/it/filter_support.rs +++ b/crates/ui-egui/tests/it/filter_support.rs @@ -29,7 +29,10 @@ pub(crate) fn app_with(filter: &str, target: &str, height: f32) -> (Harness<'sta execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); session.target = StackTarget::Effect(effect); - let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, height)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(WINDOW_WIDTH, height)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, effect) diff --git a/crates/ui-egui/tests/it/folder_properties.rs b/crates/ui-egui/tests/it/folder_properties.rs index c92c429c..e298e8d3 100644 --- a/crates/ui-egui/tests/it/folder_properties.rs +++ b/crates/ui-egui/tests/it/folder_properties.rs @@ -28,7 +28,11 @@ fn folder_harness(with_fill: bool) -> (Harness<'static, TextureCraftApp>, LayerI LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap()) }; execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "content"})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); (harness, folder, fill) @@ -107,20 +111,3 @@ fn randomize_seeds_is_one_undo_step_the_contents_reset_puts_them_back_and_an_emp assert!(harness.query_by_label("No properties found").is_some()); assert!(harness.query_by_role_and_label(Role::Slider, "Scale").is_none()); } - -/// An empty folder's note starts at the Properties header name's left edge, as the note with no project open does (it was centred) -#[test] -fn an_empty_folders_note_starts_at_its_header_names_left_edge() { - let (harness, _, _) = folder_harness(false); - - let painted_left = |wanted: &dyn Fn(&str) -> bool| { - harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x), - _ => None, - }) - }; - let note = painted_left(&|text| text == "No properties found"); - let header = painted_left(&|text| text.starts_with("PROPERTIES")); - - assert!(note.is_some() && note == header, "the note starts at {note:?}, the header name at {header:?}"); -} diff --git a/crates/ui-egui/tests/it/frame_selection.rs b/crates/ui-egui/tests/it/frame_selection.rs index f93c8b51..e36c95b6 100644 --- a/crates/ui-egui/tests/it/frame_selection.rs +++ b/crates/ui-egui/tests/it/frame_selection.rs @@ -10,7 +10,10 @@ o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0 fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 806c8fb2..ae1eb182 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -30,7 +30,8 @@ fn harness_with(render: bool, added: serde_json::Value) -> (Harness<'static, Tex session.update(); let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); let builder = if render { builder.wgpu() } else { builder }; - let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); @@ -336,7 +337,10 @@ fn an_inherited_generators_micro_height_lists_only_anchors_below_its_owner() { let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap(); session.target = texturecraft_engine::StackTarget::Effect(effect); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.focus(Panel::Properties); harness.run_steps(6); diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index cc2b1d68..02a2e81b 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -18,7 +18,10 @@ fn app_with_dirt() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); session.target = StackTarget::Effect(effect); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); (harness, effect) } @@ -92,7 +95,11 @@ fn generator_picker_snapshots() { let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "EdgeWear"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); session.target = StackTarget::Effect(LayerId(effect["effect"].as_u64().unwrap())); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(20); harness.get_by_role_and_label(Role::ComboBox, "Worn Metal Edges").click(); diff --git a/crates/ui-egui/tests/it/help_menu_664.rs b/crates/ui-egui/tests/it/help_menu_664.rs index da4b9f98..e3dbadd3 100644 --- a/crates/ui-egui/tests/it/help_menu_664.rs +++ b/crates/ui-egui/tests/it/help_menu_664.rs @@ -11,7 +11,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); session.log.push("first line".into()); session.log.warn(texturecraft_engine::log::DEFAULT_SOURCE, "second line"); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs index c8d3c246..8861ea55 100644 --- a/crates/ui-egui/tests/it/high_poly_loading.rs +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -18,7 +18,10 @@ const STROKE_FRAMES: usize = 200; /// A bake-mode app with Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::CommonSettings); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 7103161b..889b3df7 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -10,7 +10,10 @@ use texturecraft_ui_egui::docking::Panel; /// Show document history so row clicks exercise the same command dispatch as the application fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.dock.focus(Panel::History); harness.run_steps(4); harness @@ -167,7 +170,10 @@ fn clicking_a_history_step_returns_to_it() { texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); } let done = session.history_labels().len(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.dock.focus(Panel::History); h.run_steps(4); let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index 26badb0f..7ff6857a 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -18,7 +18,10 @@ const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other fn app() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); @@ -131,8 +134,17 @@ fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { add(&mut h, &[png(&dir, "plain.png"), png(&dir, "brush.png"), png(&dir, "sky.png")]); assert_eq!(combos(&h, "undefined").count(), 3); + click(&mut h, "brush.png"); choose_usage(&mut h, 1, "alpha"); + + h.get_by_label("plain.png").click_modifiers(egui::Modifiers::SHIFT); + h.run_steps(3); + assert_eq!(h.state().ui.windows.import_resources.as_ref().unwrap().selected.len(), 2); + choose_usage(&mut h, 1, "environment"); + + assert_eq!(combos(&h, "undefined").count(), 1, "editing an unselected row keeps the selected images' usages"); + click(&mut h, "Import"); assert_eq!(resources(&h), ["brush.png", "plain.png", "sky.png"]); @@ -141,6 +153,31 @@ fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush.png"), "the alpha usage sets the brush alpha"); } +#[test] +fn choosing_a_usage_updates_the_selected_images() { + let dir = TempDir::new("import-resources-multi-usage"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "one.png"), png(&dir, "two.png"), dir.join("material.TCMAT"), dir.join("coat.MTLX"), png(&dir, "three.png")]); + choose_usage(&mut h, 1, "alpha"); + + click(&mut h, "one.png"); + h.get_by_label("coat.MTLX").click_modifiers(egui::Modifiers::SHIFT); + h.run_steps(3); + combos(&h, "All files (5)").next().expect("the filter dropdown").click(); + h.run_steps(3); + h.get_by_label("undefined (4)").click(); + h.run_steps(3); + + assert_eq!(h.state().ui.windows.import_resources.as_ref().unwrap().selected.len(), 4); + assert!(h.query_by_label("two.png").is_none(), "the selected image with a different usage is filtered out"); + + choose_usage(&mut h, 0, "texture"); + + let rows = &h.state().ui.windows.import_resources.as_ref().unwrap().rows; + assert_eq!(rows.iter().map(|row| row.usage.name()).collect::>(), ["texture", "texture", "undefined", "undefined", "undefined"]); +} + #[test] fn a_prefix_goes_in_front_of_the_resource_name() { let dir = TempDir::new("import-resources-prefix"); @@ -211,7 +248,7 @@ fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { #[test] fn a_materialx_document_imports_as_a_layer() { let dir = TempDir::new("import-resources-materialx"); - let file = dir.join("paint.mtlx"); + let file = dir.join("paint.MTLX"); std::fs::write( &file, r#" @@ -285,7 +322,12 @@ fn import_resources_snapshot() { let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); let dir = TempDir::new("import-resources-snapshot"); let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); invoke(&mut h); diff --git a/crates/ui-egui/tests/it/inactive_set_hint.rs b/crates/ui-egui/tests/it/inactive_set_hint.rs index c6f1f8f1..33f48c48 100644 --- a/crates/ui-egui/tests/it/inactive_set_hint.rs +++ b/crates/ui-egui/tests/it/inactive_set_hint.rs @@ -12,7 +12,10 @@ const SEARCH_STEP: f32 = 8.0; /// The sample project (the ball is set 0, the base set 1) with the Ball active and the paint tool, at 1600 x 960 fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); assert_eq!(harness.state().session.ts(), 0); assert_eq!(harness.state().session.tool.tool, Tool::Paint); diff --git a/crates/ui-egui/tests/it/instance_properties.rs b/crates/ui-egui/tests/it/instance_properties.rs index d54463ee..da0a8194 100644 --- a/crates/ui-egui/tests/it/instance_properties.rs +++ b/crates/ui-egui/tests/it/instance_properties.rs @@ -23,7 +23,11 @@ fn instance_harness(dangling: bool) -> (Harness<'static, TextureCraftApp>, Layer session.doc.project.layers.get_mut(&instance).unwrap().kind = LayerKind::Instance { source: GONE }; } execute(&mut session, "layer.select", &json!({"layer": instance.0, "target": "content"})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); (harness, instance, source) diff --git a/crates/ui-egui/tests/it/layer_blending_options.rs b/crates/ui-egui/tests/it/layer_blending_options.rs index d20dc7b4..19cff699 100644 --- a/crates/ui-egui/tests/it/layer_blending_options.rs +++ b/crates/ui-egui/tests/it/layer_blending_options.rs @@ -8,7 +8,10 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/layer_clipboard.rs b/crates/ui-egui/tests/it/layer_clipboard.rs index efcf40c0..37a4a150 100644 --- a/crates/ui-egui/tests/it/layer_clipboard.rs +++ b/crates/ui-egui/tests/it/layer_clipboard.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::TextureCraftApp; /// The sample session with its selected layer clicked in the stack, and that layer. fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let layer = h.state().session.selected_layer().unwrap(); let name = h.state().session.doc.project.layers[&layer].name.clone(); @@ -79,7 +82,10 @@ fn layer_shortcuts_act_on_a_selected_effect() { let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer"); let p = serde_json::json!({"target": "content", "filter": "invert"}); let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len()); h.event(egui::Event::Copy); diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index c0d0054c..dbbf8cae 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -15,7 +15,10 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let rows = ["Row A", "Row B", "Row C", "Row D"] .map(|name| LayerId(execute(&mut session, "layer.add.paint", &json!({ "name": name })).unwrap()["layer"].as_u64().unwrap())); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); (h, rows) } diff --git a/crates/ui-egui/tests/it/layer_rename.rs b/crates/ui-egui/tests/it/layer_rename.rs index 55b47bd9..b8de5ad9 100644 --- a/crates/ui-egui/tests/it/layer_rename.rs +++ b/crates/ui-egui/tests/it/layer_rename.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> (Harness<'static, TextureCraftApp>, u64) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let layer = h.state().session.selected_layer().unwrap().0; (h, layer) diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index 9466a76f..000ed20d 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -26,7 +26,10 @@ fn app() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); (harness, layer) @@ -130,15 +133,21 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer() /// A floating Layers panel this narrow cannot hold the toolbar on one row const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0]; +/// [`NARROW_LAYERS`] as a rect +fn narrow_layers() -> egui::Rect { + let [left, top, width, height] = NARROW_LAYERS; + egui::Rect::from_min_size(egui::pos2(left, top), egui::vec2(width, height)) +} + /// In a narrow floating Layers panel the add-layer buttons and Remove wrap inside it, where a click still reaches them #[test] fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { - use craft_ui::docking::Action; + use craft_behavior::dock::Action; use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; let (mut harness, _) = app(); let mut workspace = harness.state().ui.dock.workspace().clone(); - workspace.apply_all([Action::Float { panel: Panel::Layers, rect: NARROW_LAYERS }], permissions).unwrap(); + workspace.apply_all([Action::float(Panel::Layers, narrow_layers())], false, permissions).unwrap(); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); harness.run_steps(SETTLE_FRAMES); let [left, _, width, _] = NARROW_LAYERS; diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 2e498524..2638cdf9 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -24,7 +24,10 @@ fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "mask.add.black", &Value::Null).unwrap(); execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); (h, layer) } @@ -37,6 +40,9 @@ fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 egui::pos2(x, row.center().y) } +/// The accessible name of the mask thumbnail of the layer "Masked fill" +const MASK_THUMBNAIL_NAME: &str = "Select the mask (Alt+click: show it in the viewport, Shift+click: switch it on or off) (Masked fill)"; + /// The `label` header that follows the "Masked fill" row (other layers have groups too). fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { let top = h.get_by_label("Masked fill").rect().top(); @@ -99,8 +105,8 @@ fn visible_rows_get_their_thumbnails() { #[test] fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { - use craft_ui::docking::Node; - use craft_ui::layout::SplitSize; + use craft_behavior::dock::Node; + use craft_behavior::dock::SplitSize; use texturecraft_ui_egui::docking::Dock; let (mut harness, layer) = harness(); @@ -108,8 +114,9 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { execute(&mut harness.state_mut().session, "layer.group", &Value::Null).unwrap(); } - let mut workspace = harness.state().ui.dock.workspace().clone(); - let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let workspace = harness.state().ui.dock.workspace().clone(); + let mut layout = workspace.layout().clone(); + let Some(Node::Split { second, .. }) = layout.root.as_mut() else { panic!("default columns") }; let Node::Split { size, second: column, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::Ratio(0.99); @@ -117,6 +124,7 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets and the rest") }; let Node::Split { size: layers_share, .. } = below_sets.as_mut() else { panic!("layers and properties") }; *layers_share = SplitSize::Ratio(0.9); + let workspace = texturecraft_ui_egui::docking::Workspace::from_parts(layout, workspace.hidden().to_vec(), workspace.floated().to_vec()); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); // Closing Properties lets the column shrink to the Layers minimum @@ -151,7 +159,11 @@ fn hidpi_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Active one"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1200.0, 800.0)) + .with_pixels_per_point(2.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); (h, layer) } @@ -257,7 +269,10 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); execute(&mut session, "layer.rename", &json!({"layer": layer, "name": LONG_NAME})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h @@ -295,7 +310,10 @@ fn an_effect_name_cut_short_shows_in_full_on_hover() { let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); @@ -355,26 +373,25 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { #[test] fn focused_mask_thumbnail_opens_and_dismisses_its_menu_from_the_keyboard() { - let (mut h, _) = harness(); - let thumbnail = "Select the mask (Alt+click: show it in the viewport) (Masked fill)"; - h.get_by_label(thumbnail).focus(); - h.run_steps(3); + let (mut harness, _) = harness(); - assert!(h.get_by_label(thumbnail).is_focused()); + harness.get_by_label(MASK_THUMBNAIL_NAME).focus(); + harness.run_steps(3); + assert!(harness.get_by_label(MASK_THUMBNAIL_NAME).is_focused()); - h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); - h.run_steps(3); + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + assert!(harness.query_by_label("Toggle mask").is_some()); - assert!(h.query_by_label("Toggle mask").is_some()); - h.key_press(egui::Key::ArrowDown); - h.run_steps(3); + harness.key_press(egui::Key::ArrowDown); + harness.run_steps(3); + assert!(harness.get_by_label("Toggle mask").is_focused()); - assert!(h.get_by_label("Toggle mask").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); - assert!(h.query_by_label("Toggle mask").is_none()); - assert!(h.get_by_label(thumbnail).is_focused()); + assert!(harness.query_by_label("Toggle mask").is_none()); + assert!(harness.get_by_label(MASK_THUMBNAIL_NAME).is_focused()); } /// Click the eye of the top-level row `name` with `modifiers` held (the eye sits in the first 20 points after the 7-point edge). @@ -433,12 +450,18 @@ fn alt_click_on_the_eye_solos_and_a_plain_click_still_hides() { } fn alt_click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { - h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); - h.hover_at(at); + click_with(h, at, egui::Modifiers::ALT); +} + +/// A primary click at `position` with `modifiers` held +fn click_with(h: &mut Harness<'_, TextureCraftApp>, position: egui::Pos2, modifiers: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(modifiers)); + h.hover_at(position); for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }); + h.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers }); h.run_steps(2); } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); h.run_steps(3); } @@ -468,11 +491,122 @@ fn alt_click_on_a_mask_thumbnail_shows_that_mask_alone_without_changing_the_docu #[test] fn alt_click_on_the_content_thumbnail_leaves_the_view_alone() { - let (mut h, _) = harness(); - let at = thumb(&h, "Masked fill", false); - alt_click(&mut h, at); + let (mut h, layer) = harness(); + let content_thumbnail = thumb(&h, "Masked fill", false); + let mask_thumbnail = thumb(&h, "Masked fill", true); + + alt_click(&mut h, content_thumbnail); assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); + + alt_click(&mut h, mask_thumbnail); + + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Mask(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask); + + alt_click(&mut h, content_thumbnail); + + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Mask(layer)); + assert_eq!(h.state().session.target, StackTarget::Content); +} + +/// Whether a bypassed mask's strike is painted across the thumbnail at `position` +fn mask_strike_shown(h: &Harness<'_, TextureCraftApp>, position: egui::Pos2) -> bool { + let danger = texturecraft_ui_egui::theme::Tokens::get(&h.ctx).danger; + shapes(h).iter().any(|shape| matches!(shape, egui::Shape::LineSegment { points, stroke } if stroke.color == danger && egui::Rect::from_two_pos(points[0], points[1]).contains(position))) +} + +#[test] +fn shift_click_on_a_mask_thumbnail_switches_the_mask_off_and_on_in_one_undo_step_each() { + let (mut h, layer) = harness(); + let at = thumb(&h, "Masked fill", true); + let target = h.state().session.target; + let history = h.state().session.history_labels().len(); + let mask = h.state().session.doc.project.layers[&layer].mask.clone().unwrap(); + + assert!(!mask_strike_shown(&h, at)); + assert_eq!(h.get_by_label(MASK_THUMBNAIL_NAME).accesskit_node().description().as_deref(), Some("Mask on")); + + click_with(&mut h, at, egui::Modifiers::SHIFT); + + let bypassed = h.state().session.doc.project.layers[&layer].mask.as_ref().unwrap(); + assert!(!bypassed.enabled); + assert_eq!(bypassed.effects, mask.effects, "the mask keeps its effects while bypassed"); + assert_eq!(h.state().session.history_labels().len(), history + 1); + assert_eq!(h.state().session.target, target, "Shift+click toggles instead of selecting the mask"); + assert!(mask_strike_shown(&h, at), "the disabled indicator shows while the mask is bypassed"); + + let thumbnail = h.get_by_label(MASK_THUMBNAIL_NAME); + assert!(thumbnail.is_focused()); + assert_eq!(thumbnail.accesskit_node().description().as_deref(), Some("Mask off")); + + click_with(&mut h, at, egui::Modifiers::SHIFT); + + assert_eq!(h.state().session.doc.project.layers[&layer].mask, Some(mask), "toggling back restores the mask as it was"); + assert_eq!(h.state().session.history_labels().len(), history + 2); + assert!(!mask_strike_shown(&h, at)); + assert_eq!(h.get_by_label(MASK_THUMBNAIL_NAME).accesskit_node().description().as_deref(), Some("Mask on")); + + h.state_mut().session.undo().unwrap(); + + assert!(!h.state().session.doc.project.layers[&layer].mask.as_ref().unwrap().enabled, "one undo undoes one toggle"); +} + +#[test] +fn shift_click_on_a_mask_thumbnail_works_with_no_layer_selected() { + let (mut harness, layer) = harness(); + let row = harness.get_by_label("Masked fill").rect(); + let mask_thumbnail = thumb(&harness, "Masked fill", true); + let history = harness.state().session.history_labels().len(); + + click_with(&mut harness, row.center(), egui::Modifiers::COMMAND); + + assert!(harness.state().session.selected_layers().is_empty()); + assert!(harness.state().session.doc.project.layers[&layer].mask.as_ref().unwrap().enabled); + + click_with(&mut harness, mask_thumbnail, egui::Modifiers::SHIFT); + + assert!(!harness.state().session.doc.project.layers[&layer].mask.as_ref().unwrap().enabled); + assert!(harness.state().session.selected_layers().is_empty()); + assert_eq!(harness.state().session.history_labels().len(), history + 1); +} + +#[test] +fn the_mask_toggle_shortcut_requires_a_selected_layer() { + let (mut harness, layer) = harness(); + let row = harness.get_by_label("Masked fill").rect(); + harness.state_mut().ui.keymap.insert("mask.toggle".into(), "F7".into()); + + harness.key_press(egui::Key::F7); + harness.run_steps(3); + + assert!(!harness.state().session.doc.project.layers[&layer].mask.as_ref().unwrap().enabled); + + click_with(&mut harness, row.center(), egui::Modifiers::COMMAND); + assert!(harness.state().session.selected_layers().is_empty()); + let toast_count = harness.state().toasts.len(); + + harness.key_press(egui::Key::F7); + harness.run_steps(3); + + assert_eq!(harness.state().toasts.len(), toast_count, "the shortcut is inactive when it has no target"); + assert!(!harness.state().session.doc.project.layers[&layer].mask.as_ref().unwrap().enabled); +} + +#[test] +fn clicking_the_material_thumbnail_leaves_the_mask_view() { + let (mut h, layer) = harness(); + let mask_thumbnail = thumb(&h, "Masked fill", true); + let material_thumbnail = thumb(&h, "Masked fill", false); + + alt_click(&mut h, mask_thumbnail); + + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Mask(layer)); + + click(&mut h, material_thumbnail); + + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); + assert_eq!(h.state().session.target, StackTarget::Content, "the layer content is selected"); } /// Pointer moves of the opacity cell drag, one per frame diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index 0a1656a3..ead001b2 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -40,7 +40,11 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); (harness, effect) } diff --git a/crates/ui-egui/tests/it/log_panel_680.rs b/crates/ui-egui/tests/it/log_panel_680.rs index 52977118..eba3e084 100644 --- a/crates/ui-egui/tests/it/log_panel_680.rs +++ b/crates/ui-egui/tests/it/log_panel_680.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::docking::Panel; fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); { let log = &mut h.state_mut().session.log; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index eb1b95da..17d25f98 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -84,6 +84,7 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod sample_project; mod settings_window; mod shelf_click; mod shelf_drop; @@ -109,6 +110,7 @@ mod user_smart_mask; mod view2d_navigation; mod view2d_tiles; mod view_mode_picker; +mod viewport_focus; mod window_menu_684; mod filter_card; @@ -209,13 +211,13 @@ fn click_widget(harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, la click_at(harness, at); } -/// The close button nearest the right of a docked panel's `title` (its tab or header title), on the same row +/// The close button of a docked panel's tab `title`: in the tab's right half, on its row fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect { harness .get_all_by_role(egui::Role::Button) - .filter(|button| button.accesskit_node().label().as_deref() == Some("Close Panel")) + .filter(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("Close "))) .map(|button| button.rect()) - .filter(|close| close.min.x > title.max.x && title.y_range().contains(close.center().y)) + .filter(|close| close.center().x > title.center().x && title.y_range().contains(close.center().y)) .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) .expect("a close button right of the title") } diff --git a/crates/ui-egui/tests/it/mask_export.rs b/crates/ui-egui/tests/it/mask_export.rs index c58fd4ff..453672b6 100644 --- a/crates/ui-egui/tests/it/mask_export.rs +++ b/crates/ui-egui/tests/it/mask_export.rs @@ -22,7 +22,10 @@ fn harness(mask: bool) -> Harness<'static, TextureCraftApp> { execute(&mut session, "mask.add.black", &Value::Null).unwrap(); execute(&mut session, "effect.add.fill", &json!({"value": 0.5})).unwrap(); } - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/mask_fill_rows.rs b/crates/ui-egui/tests/it/mask_fill_rows.rs index efd75314..a916fa9f 100644 --- a/crates/ui-egui/tests/it/mask_fill_rows.rs +++ b/crates/ui-egui/tests/it/mask_fill_rows.rs @@ -26,7 +26,10 @@ fn app_with_mask_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, L let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": projection})).unwrap(); let effect = LayerId(added["effect"].as_u64().unwrap()); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); @@ -146,7 +149,10 @@ fn a_mask_fill_reading_a_content_anchor_picks_its_channel() { let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": top, "target": "mask", "anchor": anchor})).unwrap(); let effect = LayerId(added["effect"].as_u64().unwrap()); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": top, "target": effect.0})).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("an anchor source") }; @@ -176,7 +182,10 @@ fn an_inherited_mask_fill_lists_only_anchors_below_its_owner() { let instance = texturecraft_engine::execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap(); session.target = texturecraft_engine::StackTarget::Effect(effect); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs index cc70af4f..059beb4f 100644 --- a/crates/ui-egui/tests/it/mask_paint_grayscale.rs +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -26,7 +26,11 @@ fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { let folder = LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap()); execute(&mut session, "mask.add.white", &json!({"layer": folder.0})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "mask"})).unwrap(); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.props_tab = PropsTab::Material; harness.run_steps(STARTUP_FRAMES); diff --git a/crates/ui-egui/tests/it/mask_value_swap.rs b/crates/ui-egui/tests/it/mask_value_swap.rs index d5f22ebc..0d1e44fc 100644 --- a/crates/ui-egui/tests/it/mask_value_swap.rs +++ b/crates/ui-egui/tests/it/mask_value_swap.rs @@ -9,7 +9,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); session.target = StackTarget::Mask; - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs index 2c577f9d..ab44b3b8 100644 --- a/crates/ui-egui/tests/it/named_layouts.rs +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -9,8 +9,11 @@ use texturecraft_ui_egui::state::Mode; fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_accessibility_check(false) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/it/nav_buttons.rs b/crates/ui-egui/tests/it/nav_buttons.rs index b21569e0..a624445a 100644 --- a/crates/ui-egui/tests/it/nav_buttons.rs +++ b/crates/ui-egui/tests/it/nav_buttons.rs @@ -17,7 +17,11 @@ const WINDOW: egui::Vec2 = vec2(1280.0, 800.0); /// The app showing only one view, so that the view fills the viewport rect the 3D view reports fn app(layout: ViewLayout) -> (Harness<'static, TextureCraftApp>, Rect) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_pixels_per_point(1.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; harness.state_mut().ui.layout = ViewLayout::Only3D; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index d171b8ef..4fae5942 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -19,7 +19,10 @@ fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> { let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); @@ -129,11 +132,16 @@ fn new_project_baked_maps_snapshots() { let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| { - let adapter = cc.wgpu_render_state.as_ref().unwrap().adapter.get_info(); - eprintln!("snapshot adapter: {adapter:?}"); - TextureCraftApp::new(cc, session) - }); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| { + let adapter = cc.wgpu_render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("snapshot adapter: {adapter:?}"); + TextureCraftApp::new(cc, session) + }); let dir = TempDir::new("new-project-baked-maps-snapshots"); let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 401cf728..ba657ddc 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -21,7 +21,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(2); let ctx = h.ctx.clone(); @@ -97,6 +100,24 @@ fn the_uv_layout_control_is_disabled_when_uv_tiles_are_off() { assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); } +#[test] +fn rebuild_mesh_uvs_is_off_by_default_and_toggles_with_space() { + let mut h = harness(); + let rebuild = h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs"); + + assert!(!rebuild.accesskit_node().is_disabled()); + assert_eq!(rebuild.accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + + rebuild.focus(); + h.run_steps(2); + h.key_press(egui::Key::Space); + h.run_steps(2); + + let rebuild = h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs"); + assert_eq!(rebuild.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); + assert!(h.state().ui.new_project.rebuild_uvs); +} + #[test] fn create_waits_for_a_mesh_file() { let mut h = harness(); @@ -117,8 +138,6 @@ fn settings_not_available_yet_are_disabled_with_a_hint() { let unavailable = [ (Role::CheckBox, "Compute tangent space per fragment"), (Role::RadioButton, "Use a separate texture set for each tile"), - (Role::CheckBox, "Auto-unwrap"), - (Role::Button, "Auto-unwrap options"), (Role::RadioButton, "Custom unit scale"), (Role::CheckBox, "Scale material fills in real-world units"), ]; @@ -257,17 +276,22 @@ fn the_supported_settings_reach_the_create_command() { #[test] fn ticking_uv_tiles_creates_a_uv_tile_project() { - for (tick, expected) in [(false, Vec::::new()), (true, vec![1002])] { + for (enable_uv_tiles, rebuild_uvs, expected_tiles) in [(false, false, vec![]), (true, false, vec![1002]), (true, true, vec![1001])] { let mut h = harness(); let dir = TempDir::new("new-project-udim"); h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); h.state_mut().ui.new_project.resolution = 128; h.run_steps(2); - if tick { + if enable_uv_tiles { h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click(); h.run_steps(3); assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); } + + if rebuild_uvs { + h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs").click(); + h.run_steps(3); + } h.get_by_role_and_label(Role::CheckBox, "Import cameras").click(); h.run_steps(2); h.get_by_role_and_label(Role::Button, "Create").click(); @@ -276,8 +300,14 @@ fn ticking_uv_tiles_creates_a_uv_tile_project() { let app = h.state(); assert!(!app.ui.windows.new_project, "the window closes"); assert_eq!(app.session.doc.project.name, "tiles"); - assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}"); + assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected_tiles, "UV tiles enabled: {enable_uv_tiles}, rebuild UVs: {rebuild_uvs}"); assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128); + if rebuild_uvs { + let bytes = texturecraft_engine::formats::save_project_bytes(&app.session.project_file()).unwrap(); + let reopened = texturecraft_engine::Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(reopened.source_mesh().uvs, app.session.source_mesh().uvs); + assert_eq!(reopened.doc.project.format_version, texturecraft_engine::core::project::REBUILT_MESH_UVS_VERSION); + } } } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index c40deb73..edb10bfe 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -23,7 +23,10 @@ fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> { fn harness_at(library: &TemplateLibrary, size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().session.load_export_presets(library.0.clone()); @@ -632,7 +635,10 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let library = TemplateLibrary::new("small-screen"); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().session.load_export_presets(library.0.clone()); diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index ba34023c..a7202ad4 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -1,22 +1,21 @@ -//! Every docked panel group sits under one header bar: its names at the left, the shown one raised as a box when the group has several, a close × at the right +//! Every docked panel group's header ends in its close button, and the Properties header names what it shows -use craft_ui::docking::{Action, Placement}; use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; +use texturecraft_ui_egui::docking::Panel; use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, panel_close_button}; const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); -/// A floating window over the viewport, `[x, y, width, height]` -const FLOATING_RECT: [f32; 4] = [600.0, 200.0, 320.0, 400.0]; - fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); @@ -85,178 +84,6 @@ fn the_properties_header_names_the_selected_effects_type() { tab_rect(&harness, "Properties - Levels"); } -/// How far a header under another panel reaches above its tab strip: the 6 px gutter less a 2 px separation (docking/header_band.rs) -const HEADER_RISE: f32 = 4.0; - -/// Room between a later tab's box and its tab's left edge (docking/shown_group_tab.rs, private to the crate) -const BOX_INSET: f32 = 4.0; - -/// Rounded boxes painted this frame over `tab` whose top is `rise` above it: the raised box of a shown tab -fn tab_boxes(harness: &Harness<'_, TextureCraftApp>, tab: egui::Rect, rise: f32) -> Vec { - harness - .output() - .shapes - .iter() - .filter_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) => { - let rises = (rect.rect.top() - (tab.top() - rise)).abs() < 0.5; - let raised = rises && rect.corner_radius != egui::CornerRadius::ZERO && tab.x_range().contains(rect.rect.center().x); - raised.then_some(rect.rect) - } - _ => None, - }) - .collect() -} - -#[test] -fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() { - let mut harness = app(); - let layers = tab_rect(&harness, "Layers"); - let settings = tab_rect(&harness, "Texture Set Settings"); - - assert_eq!(tab_boxes(&harness, layers, HEADER_RISE).len(), 1, "the shown Layers tab has its box, from the top of its header band"); - assert_eq!(tab_boxes(&harness, settings, HEADER_RISE).len(), 0, "the hidden tab is its name only"); - assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Properties - "), HEADER_RISE).len(), 0, "a panel alone keeps its plain header"); - - click_at(&mut harness, settings.center()); - harness.run_steps(SETTLE_FRAMES); - - assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Texture Set Settings"), HEADER_RISE).len(), 1, "the box goes with the shown tab"); - assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0); -} - -#[test] -fn the_selected_dock_tab_keeps_its_keyboard_focus_outline_visible() { - let mut harness = app(); - let layers = tab_rect(&harness, "Layers"); - let tab_id = egui::Id::unique("texturecraft-docking").with(("tab", Panel::Layers)); - harness.ctx.memory_mut(|memory| memory.request_focus(tab_id)); - harness.run_steps(SETTLE_FRAMES); - - assert_eq!(harness.ctx.memory(|memory| memory.focused()), Some(tab_id)); - let raised_box = tab_boxes(&harness, layers, HEADER_RISE)[0]; - let shapes = &harness.output().shapes; - let box_index = shapes.iter().position(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) if rect.rect == raised_box)).unwrap(); - assert!( - shapes[box_index + 1..].iter().any(|shape| { - matches!(&shape.shape, egui::Shape::Rect(rect) - if rect.stroke.width > 0.0 && layers.contains_rect(rect.rect) && rect.rect.contains(layers.center())) - }), - "the focus outline is painted above the selected tab" - ); -} - -#[test] -fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() { - let mut harness = app(); - let layers = tab_rect(&harness, "Layers"); - let boxes = tab_boxes(&harness, layers, HEADER_RISE); - assert!(!boxes.is_empty(), "the shown Layers tab has its box"); - assert!(boxes.iter().all(|shown| (shown.left() - layers.left()).abs() < 0.5), "{boxes:?} starts on the panel's left edge {}", layers.left()); - - let settings = tab_rect(&harness, "Texture Set Settings"); - - click_at(&mut harness, settings.center()); - harness.run_steps(SETTLE_FRAMES); - - let boxes = tab_boxes(&harness, settings, HEADER_RISE); - assert!(!boxes.is_empty(), "the shown Texture Set Settings tab has its box"); - assert!(boxes.iter().all(|shown| (shown.left() - (settings.left() + BOX_INSET)).abs() < 0.5), "{boxes:?} keeps its air from the Layers tab"); -} - -/// The middle of the first capital's ink in each painted text reading `name` -fn capital_middles(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { - harness - .output() - .shapes - .iter() - .filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == name => { - let row = text.galley.rows.first()?; - let glyph = row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase())?; - Some(text.pos.y + row.pos.y + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0) - } - _ => None, - }) - .collect() -} - -/// Names' capitals and the close × share the header band's middle: the tab strip plus, under another panel, the gutter above it less the separation -#[test] -fn header_names_capitals_and_close_buttons_sit_on_the_header_bands_middle() { - let harness = app(); - let headers = [ - ("Texture Sets", "TEXTURE SETS", 0.0), - ("Layers", "LAYERS", HEADER_RISE), - ("Texture Set Settings", "TEXTURE SET SETTINGS", HEADER_RISE), - ("Properties - ", "PROPERTIES - PAINT", HEADER_RISE), - ]; - for (tab, name, rise) in headers { - let tab = tab_rect(&harness, tab); - let middle = (tab.top() - rise + tab.bottom()) / 2.0; - let capitals = capital_middles(&harness, name); - assert!(!capitals.is_empty(), "{name} is painted"); - assert!(capitals.iter().all(|capital| (capital - middle).abs() < 0.75), "{name}'s capitals at {capitals:?}, its band's middle at {middle}"); - } - - let properties = tab_rect(&harness, "Properties - "); - let close = panel_close_button(&harness, properties); - let middle = (properties.top() - HEADER_RISE + properties.bottom()) / 2.0; - assert!((close.center().y - middle).abs() < 0.5, "the close × at {}, the band's middle at {middle}", close.center().y); -} - -/// A floating group's names sit on one line: the shown name, painted again over its tab, and the dimmed one beside it (the dimmed one kept its galley's middle) -#[test] -fn a_floating_groups_names_share_one_line() { - let mut harness = app(); - let mut workspace = harness.state().ui.dock.workspace().clone(); - let actions = [ - Action::Float { panel: Panel::Properties, rect: FLOATING_RECT }, - Action::Move { panel: Panel::TextureSetSettings, anchor: Panel::Properties, placement: Placement::Tab { before: None } }, - Action::Activate { panel: Panel::Properties }, - ]; - workspace.apply_all(actions, permissions).unwrap(); - harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); - harness.run_steps(SETTLE_FRAMES); - - let shown = capital_middles(&harness, "PROPERTIES - PAINT"); - let dimmed = capital_middles(&harness, "TEXTURE SET SETTINGS"); - assert!(!shown.is_empty() && !dimmed.is_empty(), "both names are painted"); - assert!(shown.iter().chain(&dimmed).all(|capital| (capital - shown[0]).abs() < 0.5), "the shown name's capitals at {shown:?}, the other's at {dimmed:?}"); -} - -/// The tab menu's panel names keep their plain layout: only the header bar pads a name to centre its capitals on the band -#[test] -fn a_tab_menus_panel_names_keep_their_plain_layout() { - let mut harness = app(); - let properties = tab_rect(&harness, "Properties - "); - let button = egui::PointerButton::Secondary; - harness.hover_at(properties.center()); - for pressed in [true, false] { - harness.event(egui::Event::PointerButton { pos: properties.center(), button, pressed, modifiers: egui::Modifiers::NONE }); - harness.run_steps(1); - } - harness.run_steps(SETTLE_FRAMES); - - let move_to = harness.get_by_role_and_label(Role::Button, "Move Panel to Group").rect(); - harness.hover_at(move_to.center()); - harness.run_steps(SETTLE_FRAMES); - - let entry = harness.get_by_role_and_label(Role::Button, "Layers").rect(); - let padded: Vec = harness - .output() - .shapes - .iter() - .filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "LAYERS" && entry.contains(text.pos) => Some(text.galley.job.first_row_min_height), - _ => None, - }) - .collect(); - - assert!(!padded.is_empty(), "the menu paints the Layers entry"); - assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); -} - /// Where the label on `name`'s row and to its right ends, for each label named `name` fn row_ends(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { let names = harness.get_all_by_role_and_label(Role::Label, name).map(|node| node.rect()); diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index f24e6b46..18b92420 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -22,7 +22,10 @@ fn harness() -> AppHarness<'static> { execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); // Tall enough that the 2D view's texture square takes A, B and C - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); h @@ -156,7 +159,10 @@ fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { let before = session.doc.clone(); let path = session.tool.path.clone(); let history = session.history_labels(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; @@ -213,7 +219,10 @@ fn split_harness() -> (AppHarness<'static>, Pos2, Pos2) { session.update(); execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; diff --git a/crates/ui-egui/tests/it/path_list.rs b/crates/ui-egui/tests/it/path_list.rs index 799ba000..d56feb79 100644 --- a/crates/ui-egui/tests/it/path_list.rs +++ b/crates/ui-egui/tests/it/path_list.rs @@ -14,7 +14,10 @@ fn path_rows_edit_and_remove_paths() { let r = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})).unwrap(); let eid = LayerId(r["committed"]["effect"].as_u64().unwrap()); execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let editing = |h: &Harness<'_, TextureCraftApp>| h.state().session.tool.path.editing; let count = |h: &Harness<'_, TextureCraftApp>| h.state().session.paths(eid).map_or(0, <[_]>::len); diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index 36b67d2b..63f347c0 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -24,7 +24,10 @@ fn frame(harness: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Op /// Paint in the 2D view with `input` and return the summed base color alpha it added. fn paint_2d(input: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) -> f64 { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.state_mut().session.tool.brush.min_size = 0.0; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index ac418f44..0873b85e 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::TextureCraftApp; /// The sample project in the default split layout at 1600 x 960 with the polygon fill tool fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = Tool::PolygonFill; harness.run_steps(4); harness @@ -138,7 +141,11 @@ fn polygon_fill_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(vec2(1600.0, 960.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info); harness.state_mut().session.tool.tool = Tool::PolygonFill; @@ -165,22 +172,3 @@ fn polygon_fill_snapshots() { harness.run_steps(6); harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap(); } - -/// A Properties body not yet on the property sheet starts under the panel's name, at the sheet's side padding (it started 4 px left of it) -#[test] -fn the_polygon_fill_body_starts_under_the_properties_name() { - let mut harness = polygon_fill_app(); - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(2); - - let painted_left = |wanted: &dyn Fn(&str) -> bool| { - harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x), - _ => None, - }) - }; - let caption = painted_left(&|text| text == "POLYGON FILL"); - let header = painted_left(&|text| text.starts_with("PROPERTIES")); - - assert!(caption.is_some() && caption == header, "the body starts at {caption:?}, the header name at {header:?}"); -} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 05f4f673..72605f64 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -27,7 +27,7 @@ fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { // The view has no accessible name of its own; these tests drive it by position let builder = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false); - let mut harness = builder.build_eframe(|context| { + let mut harness = builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| { let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); creation.storage = Some(storage); TextureCraftApp::new(&creation, session) @@ -93,7 +93,7 @@ fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifi /// Opens the paint tool's Base color swatch from its Properties' Material tab fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { - let header = harness.get_by_label("Properties - Paint").rect(); + let header = harness.get_by_role_and_label(egui::Role::Tab, "Properties - Paint").rect(); let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); material.click(); diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 2bbd3939..a44c4640 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -28,7 +28,10 @@ fn app_on_a_quad(dir: &std::path::Path) -> Harness<'static, TextureCraftApp> { let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); session.doc.project.mesh_path = file.display().to_string(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); @@ -742,7 +745,12 @@ fn project_config_snapshots() { std::fs::write(&file, QUAD).unwrap(); let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); session.doc.project.mesh_path = file.display().to_string(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(6); open_window(&mut h); h.run_steps(6); diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index 768b5d06..3486b719 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -29,7 +29,11 @@ const ESCAPES_TO_CLEAR: usize = 2; fn screen(setup: impl FnOnce(&mut Session)) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); setup(&mut session); - let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_accessibility_check(false) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs index 93e232d2..9d9ed6fb 100644 --- a/crates/ui-egui/tests/it/properties_min_width.rs +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -1,32 +1,23 @@ //! The Properties panel never gets narrower than its rows need: the column it docks in stops shrinking there -use craft_ui::docking::Node; -use craft_ui::layout::SplitSize; -use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; +use craft_behavior::dock::Node; +use craft_behavior::dock::SplitSize; +use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::{Dock, PROPERTIES_MIN_WIDTH}; -use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, panel_close_button}; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, panel_close_button}; const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); -/// A right column comfortably wider than the minimum, where a drag starts -const WIDE_COLUMN: f32 = 420.0; - -/// Half the gutter between the views and the right column, where its divider is grabbed -const DIVIDER_OFFSET: f32 = 3.0; - -/// How far under the Properties header the divider is grabbed: beside the panel's rows, clear of the header bar -const DIVIDER_GRAB_BELOW_HEADER: f32 = 100.0; - -/// How far right of the window's edge a drag aims, past any width the column could stop at -const WINDOW_RIGHT_INSET: f32 = 4.0; - fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The header names below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); @@ -36,11 +27,13 @@ fn app() -> Harness<'static, TextureCraftApp> { /// Gives the right column (Layers over Properties) `width` points, as a layout saved at that width would fn set_column_width(harness: &mut Harness<'_, TextureCraftApp>, width: f32) { - let mut workspace = harness.state().ui.dock.workspace().clone(); - let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("the assets column and the rest") }; + let workspace = harness.state().ui.dock.workspace().clone(); + let mut layout = workspace.layout().clone(); + let Some(Node::Split { second, .. }) = layout.root.as_mut() else { panic!("the assets column and the rest") }; let Node::Split { size, .. } = second.as_mut() else { panic!("the 3D view and the right column") }; *size = SplitSize::FixedSecond(width); + let workspace = texturecraft_ui_egui::docking::Workspace::from_parts(layout, workspace.hidden().to_vec(), workspace.floated().to_vec()); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); harness.run_steps(SETTLE_FRAMES); } @@ -60,45 +53,6 @@ fn properties_header_width(harness: &Harness<'_, TextureCraftApp>) -> f32 { panel_close_button(harness, title).max.x - title.min.x } -/// Moves of a divider drag, so the dock follows the pointer as it does by hand -const DRAG_MOVES: usize = 4; - -/// Drags with the primary button from `from` to `to` in [`DRAG_MOVES`] moves -fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { - harness.hover_at(from); - harness.run_steps(1); - harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(DRAG_STEP_FRAMES); - - for step in 1..=DRAG_MOVES { - harness.hover_at(from + (to - from) * (step as f32 / DRAG_MOVES as f32)); - harness.run_steps(1); - } - - harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn dragging_the_right_column_narrow_stops_at_the_properties_minimum_width() { - let mut harness = app(); - set_column_width(&mut harness, PROPERTIES_MIN_WIDTH); - let at_minimum = properties_header_width(&harness); - - set_column_width(&mut harness, WIDE_COLUMN); - let before = properties_title(&harness).min.x; - - assert!(properties_header_width(&harness) > at_minimum, "a wide column gives Properties more than its minimum"); - - let y = properties_title(&harness).max.y + DIVIDER_GRAB_BELOW_HEADER; - drag(&mut harness, pos2(before - DIVIDER_OFFSET, y), pos2(WINDOW_SIZE.x - WINDOW_RIGHT_INSET, y)); - - assert!(properties_title(&harness).min.x > before, "the divider moved right"); - - let width = properties_header_width(&harness); - assert!((width - at_minimum).abs() < 0.5, "Properties stopped at its minimum: header {width}, {at_minimum} at the minimum"); -} - #[test] fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { let mut harness = app(); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index fd2bc6be..19de942d 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -42,7 +42,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { /// The sample project's app in a window of `size`, speaking English fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/properties_scroll.rs b/crates/ui-egui/tests/it/properties_scroll.rs index e4c15155..de6fa415 100644 --- a/crates/ui-egui/tests/it/properties_scroll.rs +++ b/crates/ui-egui/tests/it/properties_scroll.rs @@ -50,7 +50,10 @@ fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); } - let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index b6b3617b..7dbd97f2 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -33,7 +33,10 @@ fn app() -> Harness<'static, TextureCraftApp> { fn app_of_size(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); @@ -74,10 +77,15 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { /// The popup's Close button, left of the rail (the window's own Close sits above the rail) fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option { - harness - .query_all(by().role(Role::Button)) - .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some("Close")) - .map(|button| button.rect()) + let labelled = |label: &'static str| { + harness + .query_all(by().role(Role::Button)) + .filter(move |button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) + .map(|button| button.rect()) + }; + // The popup's title row holds Undock then Close; a floating panel window's Close has no Undock beside it + let undock: Vec = labelled("Undock").collect(); + labelled("Close").find(|close| undock.iter().any(|undock| undock.right() <= close.left() && undock.y_range().contains(close.center().y))) } /// The title of the popup open on the panel named `name`: that name in capitals, level with the popup's Close button @@ -184,12 +192,12 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { let title = popup_title(&harness, "Log"); // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it - let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); + let texture_sets_tab = harness.get_by_role_and_label(egui::Role::Tab, "Texture Sets").rect(); assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); drag(&mut harness, title.center(), texture_sets_tab.center()); - let layout = &harness.state().ui.dock.workspace().layout; + let layout = harness.state().ui.dock.workspace().layout(); assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); } diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index f41e2529..36de6ad1 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -8,7 +8,10 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index 9c29a765..37f5d9ff 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -22,7 +22,10 @@ fn id(v: &Value, key: &str) -> u64 { } fn harness_for(session: Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // English, so a first-run locale does not change the queried labels h.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/reset_ui.rs b/crates/ui-egui/tests/it/reset_ui.rs index d2ca7864..445993f4 100644 --- a/crates/ui-egui/tests/it/reset_ui.rs +++ b/crates/ui-egui/tests/it/reset_ui.rs @@ -10,7 +10,10 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; /// An app with the Assets panel closed, a changed view split, zoom, wireframe and mode. fn changed_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let ui = &mut h.state_mut().ui; diff --git a/crates/ui-egui/tests/it/sample_project.rs b/crates/ui-egui/tests/it/sample_project.rs new file mode 100644 index 00000000..1c806bb9 --- /dev/null +++ b/crates/ui-egui/tests/it/sample_project.rs @@ -0,0 +1,89 @@ +//! File > Open Sample Project starts its file dialog in a Samples folder that holds the built-in sample. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use egui_kittest::Harness; +use texturecraft_engine::Session; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +const SAMPLE_FILE_NAME: &str = "Material Ball.tcraft"; + +fn closed_app(samples_folder: &Path) -> Harness<'static, TextureCraftApp> { + let session = Session::closed().unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().samples_folder = samples_folder.to_path_buf(); + harness.run_steps(4); + harness +} + +/// Answers every file dialog with `pick(folder the dialog starts in)` and records that folder +fn answer_with(harness: &mut Harness<'static, TextureCraftApp>, pick: impl Fn(Option<&Path>) -> Answer + 'static) -> Rc>>> { + let started_in = Rc::new(RefCell::new(Vec::new())); + let recorded = started_in.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |request| { + let Request::File(dialog) = request else { return Answer::Cancelled }; + recorded.borrow_mut().push(dialog.directory.clone()); + pick(dialog.directory.as_deref()) + }))); + started_in +} + +fn open_sample_menu_entry(harness: &mut Harness<'static, TextureCraftApp>) { + let ctx = harness.ctx.clone(); + menus::invoke(harness.state_mut(), &ctx, "project.sample"); + harness.run_steps(3); +} + +#[test] +fn the_menu_entry_copies_the_shipped_sample_and_the_dialog_starts_in_its_folder() { + let root = super::temp_dir::TempDir::new("sample-project"); + let samples_folder = root.join("Samples"); + let mut harness = closed_app(&samples_folder); + let started_in = answer_with(&mut harness, |folder| Answer::Paths(vec![folder.unwrap().join(SAMPLE_FILE_NAME)])); + + open_sample_menu_entry(&mut harness); + + assert!(samples_folder.join(SAMPLE_FILE_NAME).is_file(), "the shipped sample is copied on first use"); + assert_eq!(*started_in.borrow(), vec![Some(samples_folder.clone())], "the dialog starts in the Samples folder"); + assert!(harness.state().session.project_open, "the picked sample opens"); + assert_eq!(harness.state().session.doc.project.name, "Material Ball"); + assert_eq!(harness.state().session.set_count(), 2, "the sample keeps its texture sets"); + assert!(!harness.state().session.modified, "an opened sample is a clean file"); +} + +#[test] +fn a_file_already_in_the_samples_folder_is_not_overwritten() { + let root = super::temp_dir::TempDir::new("sample-project-kept"); + let samples_folder = root.join("Samples"); + std::fs::create_dir_all(&samples_folder).unwrap(); + let existing = samples_folder.join(SAMPLE_FILE_NAME); + std::fs::write(&existing, b"the user's own file").unwrap(); + let mut harness = closed_app(&samples_folder); + let started_in = answer_with(&mut harness, |_| Answer::Cancelled); + + open_sample_menu_entry(&mut harness); + + assert_eq!(std::fs::read(&existing).unwrap(), b"the user's own file"); + assert_eq!(*started_in.borrow(), vec![Some(samples_folder)], "the dialog still starts in the Samples folder"); +} + +#[test] +fn a_samples_folder_that_cannot_be_made_is_reported_and_the_dialog_still_opens() { + let root = super::temp_dir::TempDir::new("sample-project-blocked"); + let blocker = root.join("Samples"); + std::fs::write(&blocker, b"a file where the folder should be").unwrap(); + let mut harness = closed_app(&blocker); + let started_in = answer_with(&mut harness, |_| Answer::Cancelled); + + open_sample_menu_entry(&mut harness); + + assert!(harness.state().toasts.iter().any(|toast| toast.error), "the failure is shown"); + assert_eq!(*started_in.borrow(), vec![None], "the dialog opens without a start folder"); + assert!(!harness.state().session.project_open); +} diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index 4e8508b1..df1b1d06 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -12,7 +12,10 @@ use texturecraft_ui_egui::{TextureCraftApp, menus}; use crate::memory_storage::MemoryStorage; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The exact-text checks need English, whatever the OS language is h.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/it/shelf_click.rs b/crates/ui-egui/tests/it/shelf_click.rs index bc11cfdb..b5b6b497 100644 --- a/crates/ui-egui/tests/it/shelf_click.rs +++ b/crates/ui-egui/tests/it/shelf_click.rs @@ -12,7 +12,10 @@ const SMART_TYPE: usize = 1; /// The sample project with the shelf on type `tab`, filtered to `label` fn shelf(tab: usize, label: &str) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1920.0, 1032.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.shelf_tab = tab; harness.state_mut().ui.shelf_filter = label.to_lowercase(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index d1c732fd..7ad7b187 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -19,7 +19,10 @@ const MENU_REACH: f32 = 60.0; /// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); assert_eq!(harness.state().session.ts(), 0); harness @@ -291,7 +294,11 @@ fn image_drop_menu_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); let image = import_white_image(&mut harness); diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index 237de107..c2809684 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -27,6 +27,7 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static .with_size(egui::vec2(1600.0, 960.0)) .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.shelf_tab = MATERIALS_TAB; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index cbfdf687..f576fb7f 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -27,7 +27,10 @@ const REFERENCE_COLUMNS: usize = 4; /// The sample project with the shelf on the Materials type fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(size) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs index 08537f4f..a86ce476 100644 --- a/crates/ui-egui/tests/it/shift_lines_2d.rs +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -30,7 +30,10 @@ const BESIDE_LINE_IN_RADII: f32 = 3.0; /// The sample project with only the 2D view, at 1600 x 960 fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness @@ -249,11 +252,16 @@ fn shift_line_snapshots() { let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS to the output directory")); std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { - let adapter = &context.wgpu_render_state.as_ref().expect("wgpu render state").adapter; - eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); - TextureCraftApp::new(context, session) - }); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| { + let adapter = &context.wgpu_render_state.as_ref().expect("wgpu render state").adapter; + eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); + TextureCraftApp::new(context, session) + }); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); click(&mut harness, FIRST_CLICK, false); diff --git a/crates/ui-egui/tests/it/shift_lines_3d.rs b/crates/ui-egui/tests/it/shift_lines_3d.rs index 2c009a9b..0f437127 100644 --- a/crates/ui-egui/tests/it/shift_lines_3d.rs +++ b/crates/ui-egui/tests/it/shift_lines_3d.rs @@ -22,7 +22,10 @@ const SEARCH_REACH: f32 = 300.0; /// The sample project with only the 3D view and the Paint tool fn view_3d_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = ViewLayout::Only3D; harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 927edd86..80aae4b3 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::state::ViewLayout; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs index c603cbde..88a92296 100644 --- a/crates/ui-egui/tests/it/shortcut_list.rs +++ b/crates/ui-egui/tests/it/shortcut_list.rs @@ -9,7 +9,10 @@ use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 10c477c6..94da9905 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -24,7 +24,10 @@ const TOOLTIP_FRAMES: usize = 30; fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); harness @@ -52,7 +55,7 @@ fn button_left_of_rail<'h>(harness: &'h Harness<'_, TextureCraftApp>, label: &st } fn is_floating(harness: &Harness<'_, TextureCraftApp>, panel: Panel) -> bool { - harness.state().ui.dock.workspace().layout.floating.iter().any(|window| window.contains(&panel)) + harness.state().ui.dock.workspace().layout().floating.iter().any(|window| window.contains(&panel)) } /// Hover the control labelled `label` until its tooltip shows, and tell whether that says it is not available yet @@ -83,7 +86,7 @@ fn undock_floats_the_panel_dock_returns_it_to_the_rail_and_the_float_persists() let saved = serde_json::to_value(&harness.state().ui).unwrap(); let restored: UiState = serde_json::from_value(saved).unwrap(); assert_eq!(restored.dock, harness.state().ui.dock); - assert!(restored.dock.workspace().layout.floating.iter().any(|window| window.contains(&Panel::History))); + assert!(restored.dock.workspace().layout().floating.iter().any(|window| window.contains(&Panel::History))); button_left_of_rail(&harness, "Dock").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index a6ce38d6..dea712d0 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -14,7 +14,10 @@ const STROKE_END: egui::Pos2 = egui::pos2(900.0, 500.0); fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 63826cd1..024377d6 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -12,7 +12,10 @@ use texturecraft_ui_egui::state::PropsTab; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); run(&mut harness, "tool.smudge", Value::Null); harness diff --git a/crates/ui-egui/tests/it/snapped_lines.rs b/crates/ui-egui/tests/it/snapped_lines.rs index 44a37b86..1813f3b8 100644 --- a/crates/ui-egui/tests/it/snapped_lines.rs +++ b/crates/ui-egui/tests/it/snapped_lines.rs @@ -27,7 +27,10 @@ const MAX_DIFFERENCE: f32 = 0.01; fn app(layout: ViewLayout) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = layout; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs index 378b1a87..705d897c 100644 --- a/crates/ui-egui/tests/it/source_picker.rs +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -32,7 +32,10 @@ fn app_with_fill(prepare: impl FnOnce(&mut texturecraft_engine::Session, LayerId let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); let layer = LayerId(added["layer"].as_u64().unwrap()); prepare(&mut session, layer); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); @@ -225,7 +228,12 @@ fn near_the_windows_bottom_the_picker_opens_above_its_slot_at_full_size() { fn picker_above_its_slot_snapshot() { let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - let mut harness = Harness::builder().with_size(SNAPSHOT_WINDOW_SIZE).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(SNAPSHOT_WINDOW_SIZE) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(STARTUP_FRAMES); click_widget(&mut harness, Role::Tab, "Material"); diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 63ce4ee7..10b1c372 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -1,12 +1,10 @@ //! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views -use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::UiState; -use texturecraft_ui_egui::theme::GUTTER; +use texturecraft_ui_egui::state::{UiState, ViewLayout}; use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` @@ -38,7 +36,10 @@ impl eframe::Storage for MemoryStorage { /// The sample project in the default split layout at 1600 x 960 fn split_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The Layers tab is found by its English name, whatever the OS language is harness.state_mut().ui.prefs.language = "en".into(); @@ -62,15 +63,15 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: harness.run_steps(3); } -/// The views' right edge: a gutter left of the right column, whose Layers header starts at the column's left edge -fn views_right(harness: &Harness<'_, TextureCraftApp>) -> f32 { - let column_left = harness - .get_all_by_role(Role::Tab) - .filter(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Layers"))) - .map(|tab| tab.rect().left()) - .next() - .expect("the right column's Layers header"); - column_left - f32::from(GUTTER) +/// The views' right edge: where the 3D view ends when it is the only view, filling the views' area +fn views_right(harness: &mut Harness<'_, TextureCraftApp>) -> f32 { + let layout = harness.state().ui.layout; + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(2); + let right = harness.state().viewport_rect.right(); + harness.state_mut().ui.layout = layout; + harness.run_steps(2); + right } /// The divider's x position: the 3D view ends 1 point left of it @@ -127,7 +128,7 @@ fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { let mut harness = split_app(); let views_left = harness.state().viewport_rect.left(); let start_x = divider_x(&harness); - let views_right = views_right(&harness); + let views_right = views_right(&mut harness); let views_width = views_right - views_left; let y = harness.state().viewport_rect.center().y; assert_eq!(harness.state().ui.split_ratio, 0.5); @@ -224,7 +225,7 @@ fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { harness.run_steps(2); let views_left = harness.state().viewport_rect.left(); - let views_right = views_right(&harness); + let views_right = views_right(&mut harness); let y = harness.state().viewport_rect.center().y; let before = uv_texture_on_screen(&harness, views_right); diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index c746d213..8ec6b680 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -18,7 +18,10 @@ fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = session.import_resource_bytes("logo.png", png).unwrap(); session.tool.tool = Tool::Projection; - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, name) diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index e5ea44f6..091ab2ca 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -27,7 +27,12 @@ const VIEW_CORNER_INSET: f32 = 40.0; fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/symmetry_2d.rs b/crates/ui-egui/tests/it/symmetry_2d.rs index 29025dcd..8c42935a 100644 --- a/crates/ui-egui/tests/it/symmetry_2d.rs +++ b/crates/ui-egui/tests/it/symmetry_2d.rs @@ -13,7 +13,10 @@ const CLICK: Pos2 = pos2(700.0, 420.0); /// The sample project with only the 2D view, at 1600 x 960 fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index bdb1ee65..072a5cfd 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -16,7 +16,10 @@ use library::Library; fn harness() -> (Harness<'static, TextureCraftApp>, Library) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); // The user's template library is a folder; use a temporary one, not the real one diff --git a/crates/ui-egui/tests/it/templates_681.rs b/crates/ui-egui/tests/it/templates_681.rs index 06f3f650..bccfbe62 100644 --- a/crates/ui-egui/tests/it/templates_681.rs +++ b/crates/ui-egui/tests/it/templates_681.rs @@ -13,7 +13,10 @@ use super::temp_dir::TempDir; fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(128, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.state_mut().session.templates.dir = None; h.run_steps(4); diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index ebe3746b..993f85ef 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -24,7 +24,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { session.update(); let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); let builder = if render { builder.wgpu() } else { builder }; - let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = + builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); @@ -137,7 +138,10 @@ fn the_slot_names_the_anchor_in_a_mask_it_reads() { execute(&mut session, "mask.add.black", &json!({})).unwrap(); execute(&mut session, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); session.update(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(Panel::Properties); harness.run_steps(6); diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index 2d55e09f..78cc70d2 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -24,7 +24,10 @@ fn select_nothing(session: &mut Session) { fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); harness } @@ -68,7 +71,7 @@ fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); - assert!(shows_text(&harness, "PROPERTIES - FILL"), "a fill layer shows its fill whatever the tool"); + assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); } @@ -138,7 +141,10 @@ fn a_tool_that_cant_act_ignores_the_view() { fn bake_painting_turns_on_the_shelf_paint_tool() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); @@ -188,7 +194,11 @@ fn tool_availability_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; diff --git a/crates/ui-egui/tests/it/tool_settings_saved.rs b/crates/ui-egui/tests/it/tool_settings_saved.rs index b5c5fd73..9ac553d3 100644 --- a/crates/ui-egui/tests/it/tool_settings_saved.rs +++ b/crates/ui-egui/tests/it/tool_settings_saved.rs @@ -10,7 +10,10 @@ use memory_storage::MemoryStorage; #[test] fn saving_the_app_stores_the_current_brush_and_tool_settings() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(2); let tool = &mut harness.state_mut().session.tool; tool.brush.size = 0.37; diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index 7d91e558..c9271888 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -197,7 +197,11 @@ fn toolbar_window_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().session.tool.tool = Tool::Path; harness.state_mut().session.tool.brush.lazy = 20.0; for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index da94ccda..7547e74c 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -15,7 +15,10 @@ const SMART_MATERIALS_TYPE: usize = 1; fn harness(prepare: impl FnOnce(&mut texturecraft_engine::Session)) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); prepare(&mut session); - let mut harness = Harness::builder().with_size(WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/it/view2d_navigation.rs b/crates/ui-egui/tests/it/view2d_navigation.rs index 72815299..fdd61c55 100644 --- a/crates/ui-egui/tests/it/view2d_navigation.rs +++ b/crates/ui-egui/tests/it/view2d_navigation.rs @@ -14,8 +14,12 @@ const WINDOW: egui::Vec2 = vec2(1280.0, 800.0); /// The app showing only the 2D view, and the rect that view fills fn app_with(session: Session) -> (Harness<'static, TextureCraftApp>, Rect) { - let mut harness = - Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_pixels_per_point(1.0) + .with_step_dt(1.0 / 60.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; harness.state_mut().ui.layout = ViewLayout::Only3D; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/view2d_tiles.rs b/crates/ui-egui/tests/it/view2d_tiles.rs index 587b58b1..ef3b9b50 100644 --- a/crates/ui-egui/tests/it/view2d_tiles.rs +++ b/crates/ui-egui/tests/it/view2d_tiles.rs @@ -12,7 +12,11 @@ const BUTTON: &str = "uvtile_info_menu_button"; const SETTLE_FRAMES: usize = 3; fn app_with(session: Session) -> Harness<'static, TextureCraftApp> { - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_pixels_per_point(1.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_pixels_per_point(1.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only3D; harness.run_steps(4); @@ -72,7 +76,10 @@ fn the_tile_info_button_sits_left_of_the_view_mode_picker_and_has_no_tooltip() { /// The app with Display Settings open from the rail fn display_settings_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/view_mode_picker.rs b/crates/ui-egui/tests/it/view_mode_picker.rs index e0009a84..56619e08 100644 --- a/crates/ui-egui/tests/it/view_mode_picker.rs +++ b/crates/ui-egui/tests/it/view_mode_picker.rs @@ -8,7 +8,10 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/viewport_focus.rs b/crates/ui-egui/tests/it/viewport_focus.rs new file mode 100644 index 00000000..20eca85c --- /dev/null +++ b/crates/ui-egui/tests/it/viewport_focus.rs @@ -0,0 +1,228 @@ +//! The 3D and 2D views as Tab stops: they keep the focus Tab gives them, Tab on one hides and shows the UI, Shift+Tab +//! moves on from it, and the keys of the viewport work as with nothing focused. + +use craft_ui::runtime::focus::{FocusTarget, request}; +use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use serde_json::json; +use texturecraft_engine::{Session, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; +use texturecraft_ui_egui::viewport::{view_2d_id, view_3d_id}; + +type AppHarness = Harness<'static, TextureCraftApp>; + +fn harness(session: Session, layout: ViewLayout) -> AppHarness { + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.state_mut().ui.layout = layout; + h.run_steps(4); + h +} + +fn sample() -> Session { + texturecraft_engine::sample_session(256, 64).unwrap() +} + +fn focused(h: &AppHarness) -> Option { + h.ctx.memory(|memory| memory.focused()) +} + +/// Focus `view` as Tab does +fn focus(h: &mut AppHarness, view: Id) { + request(&h.ctx, FocusTarget::Id(view)); + h.run_steps(2); + assert_eq!(focused(h), Some(view)); +} + +fn press(h: &mut AppHarness, modifiers: Modifiers, key: Key) { + h.key_press_modifiers(modifiers, key); + h.run_steps(3); +} + +fn hidden(h: &AppHarness) -> bool { + h.state().ui.hide_ui +} + +/// The views each layout draws +const DRAWN: [(ViewLayout, bool, bool); 3] = [(ViewLayout::Only3D, true, false), (ViewLayout::Only2D, false, true), (ViewLayout::Split, true, true)]; + +#[test] +fn shift_tab_walks_over_the_views_and_tab_on_one_toggles_the_ui_once() { + let mut h = harness(sample(), ViewLayout::Split); + let mut walked = Vec::new(); + while focused(&h) != Some(view_3d_id()) { + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert!(focused(&h).is_some(), "Shift+Tab {} keeps a focus", walked.len()); + walked.push(focused(&h).unwrap()); + assert!(walked.len() < 400, "Shift+Tab reaches the 3D view"); + } + assert!(walked.iter().position(|stop| *stop == view_2d_id()).is_some_and(|at| at > 0), "it passes the stops after the views, then the 2D view"); + + press(&mut h, Modifiers::SHIFT, Key::Tab); + let before = focused(&h).expect("Shift+Tab moves on from the view"); + assert!(!walked.contains(&before)); + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(focused(&h), Some(view_3d_id()), "Tab from the stop before the view stops at it"); + assert!(!hidden(&h)); + + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(hidden(&h), "Tab on the focused view hides the UI"); + assert_eq!(focused(&h), Some(view_3d_id()), "which keeps the focus"); + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(!hidden(&h), "the next Tab shows it"); + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert_eq!(focused(&h), Some(before), "Shift+Tab leaves the view backward"); +} + +#[test] +fn every_drawn_view_holds_the_focus_and_toggles_the_ui_with_and_without_a_project() { + for (layout, in_3d, in_2d) in DRAWN { + for project in [true, false] { + for view in [view_3d_id(), view_2d_id()].into_iter().zip([in_3d, in_2d]).filter_map(|(view, drawn)| drawn.then_some(view)) { + let mut h = harness(if project { sample() } else { Session::closed().unwrap() }, layout); + for focus_view in [false, true] { + if focus_view { + focus(&mut h, view); + } + for shown_next in [false, true] { + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(hidden(&h), !shown_next, "project {project}, focused {focus_view}"); + assert_eq!(focused(&h), focus_view.then_some(view), "project {project}"); + } + } + } + } + } +} + +#[test] +fn a_click_in_either_view_leaves_tab_to_the_ui_toggle() { + for (clicked, with_focus) in [(view_3d_id(), view_3d_id()), (view_2d_id(), view_2d_id()), (view_2d_id(), view_3d_id())] { + let mut h = harness(sample(), ViewLayout::Split); + focus(&mut h, with_focus); + let at = h.ctx.read_response(clicked).unwrap().rect.center(); + for pressed in [true, false] { + h.hover_at(at); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(3); + } + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(hidden(&h)); + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(!hidden(&h)); + } +} + +#[test] +fn shortcuts_run_with_a_view_focused() { + for view in [view_3d_id(), view_2d_id()] { + let mut h = harness(sample(), ViewLayout::Split); + let name = h.state().session.doc.project.layers[&h.state().session.selected_layer().unwrap()].name.clone(); + let row = h.get_by_label(&name).rect().center(); + focus(&mut h, view); + let layers = |h: &AppHarness| h.state().session.doc.project.layers.len(); + let before = layers(&h); + h.event(Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "Ctrl+C copies the layer"); + h.event(Event::Paste("Layer".into())); + h.run_steps(3); + assert!(layers(&h) > before, "Ctrl+V pastes it"); + press(&mut h, Modifiers::COMMAND, Key::Z); + assert_eq!(layers(&h), before, "Ctrl+Z takes it back"); + + let size = h.state().session.tool.brush.size; + press(&mut h, Modifiers::NONE, Key::CloseBracket); + assert!(h.state().session.tool.brush.size > size, "] grows the brush"); + + h.hover_at(row); + h.run_steps(1); + press(&mut h, Modifiers::COMMAND, Key::A); + let session = &h.state().session; + let every_row = texturecraft_engine::layer_selection::stack_rows(&session.doc.project, 0, true); + assert_eq!(session.selected_layers().len(), every_row.len(), "Ctrl+A over the Layers panel selects every row"); + assert_eq!(focused(&h), Some(view)); + } +} + +#[test] +fn the_path_keys_work_with_the_view_focused() { + let mut session = sample(); + execute(&mut session, "layer.add.paint", &json!(null)).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let mut h = harness(session, ViewLayout::Only2D); + let place = |h: &mut AppHarness| { + execute(&mut h.state_mut().session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.5], [0.8, 0.5]], "commit": false})).unwrap(); + h.run_steps(3); + }; + let points = |h: &AppHarness| h.state().session.tool.path.points.len(); + focus(&mut h, view_2d_id()); + + place(&mut h); + press(&mut h, Modifiers::NONE, Key::Backspace); + assert_eq!(points(&h), 2, "Backspace removes one point"); + let (effect, index) = h.state().session.tool.path.editing.unwrap(); + press(&mut h, Modifiers::NONE, Key::Enter); + assert!(points(&h) == 0 && h.state().session.paths(effect).is_some_and(|paths| paths.get(index).is_some()), "Enter applies the path"); + + place(&mut h); + assert_eq!(points(&h), 3); + press(&mut h, Modifiers::NONE, Key::Escape); + assert_eq!(points(&h), 0, "Escape cancels the next one"); + assert_eq!(focused(&h), Some(view_2d_id())); +} + +#[test] +fn held_keys_work_with_the_view_focused() { + let mut session = sample(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("logo.png", png).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap(); + session.tool.tool = Tool::Projection; + let mut h = harness(session, ViewLayout::Only3D); + focus(&mut h, view_3d_id()); + + let scale = |h: &AppHarness| h.state().session.tool.stencil.as_ref().unwrap().scale; + let (before, yaw) = (scale(&h), h.state().session.camera.yaw); + hold_and_right_drag(&mut h, Key::S); + assert_ne!(scale(&h), before, "S + right drag scales the stencil"); + assert_eq!(h.state().session.camera.yaw, yaw, "instead of turning the camera"); + assert_eq!(focused(&h), Some(view_3d_id())); +} + +fn hold_and_right_drag(h: &mut AppHarness, key: Key) { + let from = h.state().viewport_rect.center(); + let button = |h: &mut AppHarness, pos: Pos2, pressed| { + h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + }; + h.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.hover_at(from); + button(h, from, true); + h.run_steps(2); + for step in 1..=4 { + h.hover_at(from + egui::vec2(15.0 * step as f32, 0.0)); + h.run_steps(1); + } + button(h, from + egui::vec2(60.0, 0.0), false); + h.event(Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +#[test] +fn escape_and_enter_answer_a_question_with_a_view_focused() { + for (key, reset) in [(Key::Escape, false), (Key::Enter, true)] { + let mut h = harness(sample(), ViewLayout::Only3D); + h.state_mut().ui.windows.confirm_reset_ui = true; + h.run_steps(3); + focus(&mut h, view_3d_id()); + press(&mut h, Modifiers::NONE, key); + assert!(!h.state().ui.windows.confirm_reset_ui, "{key:?} answers the question"); + assert_eq!(h.state().ui.layout == ViewLayout::Split, reset, "only Enter resets the layout"); + } +} diff --git a/crates/ui-egui/tests/it/window_menu_684.rs b/crates/ui-egui/tests/it/window_menu_684.rs index 2480e326..bed82cd3 100644 --- a/crates/ui-egui/tests/it/window_menu_684.rs +++ b/crates/ui-egui/tests/it/window_menu_684.rs @@ -15,7 +15,10 @@ use texturecraft_ui_egui::{TextureCraftApp, menus}; use super::temp_dir::TempDir; fn app_with(session: Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs index afec1051..872215fe 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -50,7 +50,10 @@ fn the_history_list_fills_a_tall_panel() { texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": format!("Step {step}")})).unwrap(); } - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); dock_in_left_column(&mut harness, "History"); harness.run_steps(STARTUP_FRAMES); @@ -62,7 +65,10 @@ fn the_history_list_fills_a_tall_panel() { #[test] fn the_log_list_fills_a_tall_panel() { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); for line in 0..ROWS { harness.state_mut().session.log.push(format!("Log line {line}")); } diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs index c6c3e34a..f9626b4b 100644 --- a/crates/ui-egui/tests/project_limits.rs +++ b/crates/ui-egui/tests/project_limits.rs @@ -21,8 +21,12 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() storage.values.insert("ui.json".into(), serde_json::to_string(&state).unwrap()); let session = Session::new_project("Limits", geom::primitives::plane(2.0, 1), "builtin:plane", None, 128).unwrap(); let available_cores = u32::try_from(std::thread::available_parallelism().unwrap().get()).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).with_accessibility_check(false).build_eframe(|context| { + let mut harness = Harness::builder() + .with_size(egui::vec2(1200.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .with_accessibility_check(false) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| { context.egui_ctx.data_mut(|data| data.insert_temp(egui::Id::unique("settings_resources"), (0.0_f64, available_cores, 16_u64 << 30))); let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); creation.storage = Some(&storage); diff --git a/crates/ui-egui/tests/shader_panel.rs b/crates/ui-egui/tests/shader_panel.rs index 4e93d0df..9318e2d3 100644 --- a/crates/ui-egui/tests/shader_panel.rs +++ b/crates/ui-egui/tests/shader_panel.rs @@ -17,7 +17,10 @@ const STARTUP_FRAMES: usize = 4; #[test] fn shader_settings_leave_the_height_strength_to_the_texture_set_settings() { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 6ec8ac52..367fccb8 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -62,7 +62,10 @@ fn empty_start_snapshot() { let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::Session::closed().unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); save(&mut harness, &output_dir, "empty-start"); @@ -95,7 +98,11 @@ fn empty_start_snapshot() { #[ignore] fn close_releases_view_targets_and_rejects_immediate_capture() { let session = texturecraft_engine::Session::closed().unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(960.0, 640.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(960.0, 640.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); for mesh in ["cube", "plane"] { @@ -157,8 +164,11 @@ fn brush_presets_popover_snapshot() { std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_pixels_per_point(1.0).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .with_pixels_per_point(1.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let brush = harness.state().session.tool.brush.clone(); harness.state_mut().session.brush_presets.list.clear(); harness.state_mut().ui.prefs.language = "en".into(); @@ -195,6 +205,7 @@ fn pbr_import_dialog_keeps_choices_after_error() { .with_size(egui::vec2(1280.0, 800.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); texturecraft_ui_egui::pbr_import::begin(harness.state_mut(), serde_json::json!({"path": source_dir.display().to_string()})); @@ -230,6 +241,7 @@ fn pbr_import_uses_displayed_default_after_folder_changes() { .with_size(egui::vec2(1280.0, 800.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); texturecraft_ui_egui::pbr_import::begin(harness.state_mut(), serde_json::json!({"path": source_dir.display().to_string()})); std::fs::write(source_dir.join("tile_albedo_8k.png"), &bytes).unwrap(); @@ -264,6 +276,7 @@ fn pbr_drop_candidates_and_project_replacement() { .with_size(egui::vec2(1280.0, 800.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); harness.input_mut().dropped_files = files.iter().cloned().map(dropped_path::handle).collect(); harness.run_steps(1); @@ -298,6 +311,7 @@ fn pbr_dialog_is_cleared_when_project_changes() { .with_size(egui::vec2(1280.0, 800.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); texturecraft_ui_egui::pbr_import::begin(harness.state_mut(), serde_json::json!({"path": source_dir.display().to_string()})); assert!(harness.state().pbr_import.is_some()); @@ -319,6 +333,7 @@ fn rendering_mode_snapshots() { .with_size(egui::vec2(1280.0, 800.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Rendering; harness.state_mut().ui.render.max_samples = 16; @@ -348,8 +363,12 @@ fn symmetry_snapshots() { std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": true, "symmetryOffset": [0, 0.1, 0]})).unwrap(); harness.state_mut().ui.symmetry.show_plane = true; @@ -384,8 +403,12 @@ fn window_snapshots() { std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); for (brightness, name) in [(Brightness::MediumDark, "main"), (Brightness::Dark, "brightness-dark"), (Brightness::Light, "brightness-light")] { harness.state_mut().ui.prefs.brightness = brightness; save(&mut harness, &output_dir, name); @@ -568,6 +591,7 @@ fn bake_uv_tiles_snapshot() { .with_size(egui::vec2(1600.0, 960.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "bake-uv-tiles"); @@ -607,8 +631,12 @@ fn smart_mask_shelf_snapshot() { std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::Session::new_project("Mask previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.shelf_tab = 2; let context = harness.ctx.clone(); let started = std::time::Instant::now(); @@ -656,11 +684,16 @@ fn smart_material_shelf_snapshot() { let session = texturecraft_engine::Session::new_project("Smart material previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128) .unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { - let render_state = context.wgpu_render_state.as_ref().expect("the snapshot uses wgpu"); - eprintln!("snapshot adapter: {:?}", render_state.adapter.get_info()); - TextureCraftApp::new(context, session) - }); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| { + let render_state = context.wgpu_render_state.as_ref().expect("the snapshot uses wgpu"); + eprintln!("snapshot adapter: {:?}", render_state.adapter.get_info()); + TextureCraftApp::new(context, session) + }); harness.state_mut().ui.shelf_tab = 1; let context = harness.ctx.clone(); let started = std::time::Instant::now(); @@ -697,8 +730,8 @@ fn smart_material_shelf_snapshot() { #[test] #[ignore] fn nested_layers_snapshot() { - use craft_ui::docking::Node; - use craft_ui::layout::SplitSize; + use craft_behavior::dock::Node; + use craft_behavior::dock::SplitSize; use serde_json::{Value, json}; use texturecraft_engine::execute; use texturecraft_ui_egui::docking::Dock; @@ -712,13 +745,19 @@ fn nested_layers_snapshot() { for _ in 0..6 { execute(&mut session, "layer.group", &Value::Null).unwrap(); } - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1600.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1600.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); - let mut workspace = harness.state().ui.dock.workspace().clone(); - let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let workspace = harness.state().ui.dock.workspace().clone(); + let mut layout = workspace.layout().clone(); + let Some(Node::Split { second, .. }) = layout.root.as_mut() else { panic!("default columns") }; let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::Ratio(0.99); + let workspace = texturecraft_ui_egui::docking::Workspace::from_parts(layout, workspace.hidden().to_vec(), workspace.floated().to_vec()); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); for _ in 0..100 { harness.run_steps(1); @@ -754,6 +793,7 @@ fn mask_anchor_micro_detail_snapshot() { .with_size(egui::vec2(1600.0, 1200.0)) .with_pixels_per_point(1.0) .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.dock.focus(Panel::Properties); harness.run_steps(6); @@ -777,8 +817,12 @@ fn path_tool_snapshots() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); texturecraft_engine::execute(&mut session, "tool.path", &serde_json::json!({"uvPoints": [[0.25, 0.5], [0.5, 0.3], [0.75, 0.5]]})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; harness.state_mut().session.select_path_point(1); harness.hover_at(egui::pos2(800.0, 600.0)); @@ -798,8 +842,12 @@ fn rail_window_snapshots() { std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); let context = harness.ctx.clone(); @@ -835,8 +883,12 @@ fn i18n_snapshots() { for code in ["en", "es", "ar"] { assert!(texturecraft_ui_egui::i18n::available(code), "build with migrated catalogs for {code}"); let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = code.into(); harness.state_mut().ui.windows.settings = true; save(&mut harness, &output_dir, &format!("i18n-{code}")); @@ -870,7 +922,11 @@ fn mask_fill_image_snapshot() { execute(&mut session, "mask.add.black", &json!({})).unwrap(); let effect = execute(&mut session, "effect.add.fill", &json!({"target": "mask", "value": 1.0})).unwrap()["effect"].as_u64().unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1100.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); @@ -910,8 +966,12 @@ fn panel_header_snapshots() { std::fs::create_dir_all(&output_dir).unwrap(); let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -937,8 +997,12 @@ fn settings_pages_snapshot() { let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(128, 32).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.windows.settings = true; save(&mut harness, &output_dir, "settings-general"); @@ -981,8 +1045,12 @@ fn default_layout_snapshots() { for color in [[0.2, 0.4, 0.7], [0.5, 0.5, 0.5], [0.8, 0.3, 0.1]] { execute(&mut session, "layer.add.fill", &json!({ "color": color })).unwrap(); } - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -1010,8 +1078,12 @@ fn fill_reset_snapshots() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "tiling": [2.0, 2.0], "filtering": "nearest"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -1064,8 +1136,12 @@ fn fill_properties_snapshots() { &json!({"layer": layer, "tiling": [2.0, 2.0], "rotation": 30.0, "offset": [0.25, 0.0], "wrap": "repeat", "filtering": "bilinearHq"}), ) .unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -1195,8 +1271,12 @@ fn fill_symmetry_snapshots() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness.get_by_role_and_label(egui::Role::Tab, "Symmetry").click(); @@ -1279,8 +1359,12 @@ fn fill_color_picker_snapshots() { for swatch in ["#E58A4E", "#BEBEBE", "#3C4046", "#7A7AF5", "#B0623A"] { execute(&mut session, "swatch.add", &json!({"color": swatch})).unwrap(); } - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2000.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); @@ -1375,8 +1459,12 @@ fn fill_material_snapshots() { settings["layer"] = json!(layer); execute(&mut session, "layer.fill.set", &settings).unwrap(); } - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); @@ -1527,8 +1615,12 @@ fn eyedropper_pointer_snapshots() { for (name, color) in [("light", [0.92, 0.92, 0.9]), ("dark", [0.01, 0.01, 0.012])] { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.fill", &json!({"color": color})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); // Only the app's own pointer shows, not the test's stand-in arrow @@ -1583,8 +1675,12 @@ fn source_picker_snapshots() { let below = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); execute(&mut session, "effect.add.anchor", &json!({"layer": below, "name": "Edge wear"})).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.45, 0.13, 0.05]})).unwrap()["layer"].clone(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); @@ -1670,8 +1766,12 @@ fn info_icon_snapshots() { let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "scaleMode": "physicalSize", "backfaceCulling": true})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); // The test's stand-in arrow would hide the hovered i @@ -1709,8 +1809,12 @@ fn popup_tabs_snapshots() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.set_render_cursor(false); harness.run_steps(4); @@ -1782,8 +1886,12 @@ fn mask_fill_snapshots() { let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone(); let effect = execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); save(&mut harness, &output_dir, "mask-fill-fill"); @@ -1859,8 +1967,12 @@ fn compare_snapshots() { } let compare = execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].clone(); execute(&mut session, "layer.select", &json!({"layer": layer, "target": compare})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); save(&mut harness, &output_dir, "compare-default"); @@ -1910,8 +2022,12 @@ fn anchor_snapshots() { let fresh = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); let content = execute(&mut session, "effect.add.anchor", &json!({"layer": fresh})).unwrap()["effect"].clone(); execute(&mut session, "layer.select", &json!({"layer": fresh, "target": content})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); harness.get_by_role_and_label(egui::Role::TextInput, "Anchor point name").click(); @@ -1949,8 +2065,12 @@ fn folder_snapshots() { execute(&mut session, "layer.fill.set", &json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds"})).unwrap(); let folder = execute(&mut session, "layer.group", &json!({"layer": fill})).unwrap()["layer"].clone(); execute(&mut session, "layer.select", &json!({"layer": folder, "target": "content"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); save(&mut harness, &output_dir, "folder-rest"); @@ -1989,8 +2109,12 @@ fn instance_snapshots() { execute(&mut session, "layer.fill.set", &json!({"layer": source, "channel": "baseColor", "color": [0.78, 0.29, 0.09]})).unwrap(); let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); execute(&mut session, "layer.select", &json!({"layer": instance, "target": "content"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); save(&mut harness, &output_dir, "instance-rest"); @@ -2032,8 +2156,12 @@ fn folder_mask_snapshots() { let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); execute(&mut session, "mask.add.white", &json!({"layer": folder})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; harness.run_steps(6); @@ -2078,8 +2206,12 @@ fn color_selection_snapshots() { execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors})).unwrap(); } execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); harness @@ -2161,8 +2293,12 @@ fn levels_snapshots() { let mask_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); let content_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].clone(); execute(&mut session, "layer.select", &json!({"layer": layer, "target": mask_levels})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); save(&mut harness, &output_dir, "levels-mask"); @@ -2218,8 +2354,12 @@ fn layer_toolbar_snapshots() { execute(&mut session, "effect.add.generator", &json!({"layer": dirt, "generator": "dirt"})).unwrap(); let fill = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); execute(&mut session, "layer.select", &json!({"layer": fill})).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); harness.state_mut().ui.dock.focus(Panel::Layers); @@ -2286,8 +2426,12 @@ fn filter_card_snapshots() { let invert = add(&mut session, json!({"layer": layer, "target": "content", "filter": "invert"})); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(empty); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); @@ -2340,8 +2484,12 @@ fn material_picker_snapshots() { execute(&mut session, "layer.fill.material", &json!({"layer": layer, "material": "copper"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Content; - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2000.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); @@ -2394,8 +2542,12 @@ fn colour_filter_snapshots() { ]; execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2445,8 +2597,12 @@ fn gradient_filter_snapshots() { ]; execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2495,8 +2651,12 @@ fn light_filter_snapshots() { let effects = [("glow", add("glow")), ("drop-shadow", add("dropShadow"))]; execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2529,8 +2689,12 @@ fn light_filter_snapshots() { let environment = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(lighting); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 2600.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2600.0)) + .with_pixels_per_point(1.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(8); save(&mut harness, &output_dir, "filter-baked-lighting-stylized"); @@ -2602,8 +2766,12 @@ fn shape_filter_snapshots() { ]; execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2723,8 +2891,12 @@ fn simple_filter_snapshots() { let replace = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2847,8 +3019,12 @@ fn image_input_snapshots() { ]; execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(effects[0].1); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 2200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); for (name, effect) in effects { @@ -2920,8 +3096,12 @@ fn filter_picker_snapshots() { let masked = add(&mut session, json!({"layer": layer, "target": "mask", "filter": "none"})); execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); session.target = StackTarget::Effect(empty); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); let open = |harness: &mut Harness<'_, TextureCraftApp>, card: &str, hover: &str| { @@ -2951,8 +3131,8 @@ fn filter_picker_snapshots() { #[test] #[ignore] fn properties_min_width_snapshot() { - use craft_ui::docking::Node; - use craft_ui::layout::SplitSize; + use craft_behavior::dock::Node; + use craft_behavior::dock::SplitSize; use serde_json::json; use texturecraft_engine::execute; use texturecraft_ui_egui::docking::Dock; @@ -2963,13 +3143,19 @@ fn properties_min_width_snapshot() { let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); let settings = json!({"layer": layer, "projection": "planar", "scaleMode": "physicalSize", "backfaceCulling": true, "shapeCrop": "cropped"}); execute(&mut session, "layer.fill.projection", &settings).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1500.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(4); - let mut workspace = harness.state().ui.dock.workspace().clone(); - let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let workspace = harness.state().ui.dock.workspace().clone(); + let mut layout = workspace.layout().clone(); + let Some(Node::Split { second, .. }) = layout.root.as_mut() else { panic!("default columns") }; let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::FixedSecond(0.0); + let workspace = texturecraft_ui_egui::docking::Workspace::from_parts(layout, workspace.hidden().to_vec(), workspace.floated().to_vec()); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -2993,7 +3179,11 @@ fn sheet_scroll_end_snapshots() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 2000.0)) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.set_render_cursor(false); harness.run_steps(4); diff --git a/crates/ui-egui/tests/ui_state_persistence.rs b/crates/ui-egui/tests/ui_state_persistence.rs index a2008864..ef3608a7 100644 --- a/crates/ui-egui/tests/ui_state_persistence.rs +++ b/crates/ui-egui/tests/ui_state_persistence.rs @@ -13,7 +13,7 @@ fn app(storage: &MemoryStorage, render: bool) -> Harness<'static, TextureCraftAp // Existing viewport controls lack accessible names; these tests check persistence and rendering let builder = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false); let builder = if render { builder.wgpu() } else { builder }; - builder.build_eframe(|context| { + builder.with_context_setup(texturecraft_ui_egui::framework::install_headless).build_eframe(|context| { let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); creation.storage = Some(storage); creation.wgpu_render_state = context.wgpu_render_state.clone(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 34f65fec..7ae61e2f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -260,7 +260,7 @@ keeps its state in a throwaway file. | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | -| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. | +| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a picker for a `.tcraft` file. On desktop, it copies any missing bundled samples (currently `Material Ball.tcraft`) into `Samples` under the data folder and opens the picker there. If preparation fails, it shows an error and opens the picker without a start folder. In the browser, the picker uses local files. The direct `project.sample` engine command generates a sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | @@ -391,6 +391,11 @@ takes a font family, not a path: it reads only the system's font folders. `file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. +The desktop control channel accepts `rebuildUvs: true` on `file.new` to generate a new UV layout. +The default keeps a complete authored layout and unwraps meshes that need UVs, including on reopen. +With `rebuildUvs: true`, the project file saves the generated layout. Reopening or calling +`file.reimportMesh` without a path reuses it. Reimporting from a mesh file on disk rebuilds its UVs. + | Tool | Params | Notes | |---|---|---| | `session_inspect` | | The whole session as JSON | @@ -697,9 +702,11 @@ with `material.apply` instead. The command rejects linked MaterialCraft fills. T - `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, channels and blending stay) and returns `{changed}`. - `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same - projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a - warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when - nothing changes. + projection kind; a placed frame, the symmetry and the sources stay). `layer.fill.resetFrame + {layer? | effect?, keepCorners?: bool}` puts a warp's frame back around the mesh. By default it + resets the corners. With `keepCorners: true` it preserves the corners and also resets projector + rotation and scale. Projection Depth, crop and culling stay. Each reset is one undo step, or none + when nothing changes. ## MaterialCraft materials diff --git a/docs/features.md b/docs/features.md index a7e2f0b9..ed131f6e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -114,9 +114,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA ## Files and texture sets - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, - OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* opens the - material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers - and images and a loose USD layer's textures are read from its folder and kept in the project. + OBJ, PLY and STL, or a built-in mesh with the `project.new` command. UVs are generated when a mesh + has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder + and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the @@ -124,12 +124,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and shows its UV tiles in the UV workflow tooltip. Edit the tiles in Texture Set Settings. Physical size and color management show the same settings as New project. +- **File › Open Sample Project** opens a `.tcraft` picker. On desktop, the picker starts in + `Samples` under the data folder and offers the bundled `Material Ball.tcraft`. In the browser, + the picker uses local files. - **File › New project...** opens a setup form with BASIC SETTINGS (*Select...* a mesh file, the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal - map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color + map format, *Use UV Tile workflow*, *Import cameras*, *Rebuild mesh UVs*, *Import baked maps*, physical size, color management). The project is named after the mesh file. Settings TextureCraft does not have yet - (tangent space per fragment, UV tiles as separate texture sets, turning auto-unwrap off and its - options, a custom unit scale, OpenColorIO) are shown disabled with a hint; projects use Legacy color + (tangent space per fragment, UV tiles as separate texture sets, a custom unit scale, OpenColorIO) + are shown disabled with a hint; projects use Legacy color management. In the browser, *Select...* opens the browser's file picker. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) @@ -138,7 +141,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel types to add or remove. Show, hide or invert them all at once, or **focus** on the active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings) says how a normal map image set as a mesh map is read, and is the default for export. -- **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps +- **Projects** are a single `.tcraft` file: the mesh (with its generated UV layout when *Rebuild mesh UVs* was chosen), every layer (sparse and lossless), baked maps and imported images. **Project templates** start new work from a saved setup. *File › More save options › Save as template...* saves the open project's setup (dialog "Save template", in the user templates folder, no confirmation); New project lists "Default (OpenPBR)", the other built-ins with " (starter_assets)", yours with " (your_assets)", and opens on the template of the last project. *More save options* also has *Save as copy...* and *Save and reduce file size* (greyed, "Not available yet"). Closing the app, or opening, starting or closing another project, with unsaved changes asks whether to save them first (in the browser too, where Save downloads the project and closing or reloading the tab diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 28114854..6ed80ba0 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -1,10 +1,12 @@ # Windows, Linux and macOS release-ref nightly: supervised manual go-live -**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the -signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed -manual actors dispatches them. There is no schedule yet. The installed policy -[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 -policy. Once `nightly.yml` is registered on `main`, populate `producer_workflow_id` by reading: +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and +the signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact +context guards and run when one of the reviewed manual actors dispatches them. +`nightly-dispatch.yml` stays literally off: it only forwards scheduled producers. There is no +schedule. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy. +Its `producer_workflow_id` is the registration of `nightly.yml` on main, read with: ```bash gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id @@ -13,22 +15,49 @@ gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions -main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded -lineage compares and an issue reread at the end of candidate admission) on top of -[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input -and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed -source availability, not provider, queue, native signing or crypto qualification. -Existing stable workflows are unchanged. +Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions +main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +candidate is admitted on the built commit's own Sonar analysis, not main's latest) after +[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly +registry rows for the 14 apps) and +[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out +of the app's clean-source check, and macOS on `macos-15`), following +[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the +policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the +multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed +registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`) +earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source +availability, not provider, queue, native signing or crypto qualification. Existing stable workflows are unchanged. **First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a -listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that -producer run ID and attempt, by a listed manual actor. +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` +with that producer run ID and attempt, by a listed manual actor. `nightly-dispatch.yml` only matters +once a schedule is approved. + +**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` +branch, so nightly signer files never need a stable release sync. The policy's `release_branch` +names it, the signer's guard requires it and the dispatcher targets it. The branch only +fast-forwards to reviewed main commits, through the settings script's `advance` (no queued signer +run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the existing +`release` environment must admit `nightly-signer` alongside `release` before the first dispatch (a +repository settings change, not a workflow one). Its trust closure is all of `.github/` and +`packaging/`, including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with the +Apple keys. On that branch only the pinned `nightly-sign.yml` caller may reach an environment: no +app workflow binds one, nothing else calls `nightly-release.yml`, and the only caller of the shared +stable `release.yml` is `release.yml`, whose callee must carry the stable-only environment guard. +The contract tests check the in-repo part on every main PR; the settings scan also resolves the +callee. Stable releases still come only from `refs/heads/release`. History does not carry over a +switch between `release` and `nightly-signer`, so the switch happens before the first publication. + +**Registry admission.** The signer requires the protected policy's `platforms` map to equal the +run app's admitted targets in craft-common-actions' `nightly-apps.json`, and it refuses rather +than sign a subset. TextureCraft's row admits `linux-x86_64`, `windows-x86_64` and `macos-aarch64`, with +each target's entrypoint and asset pattern, since craft-common-actions #370 (in the pin). **Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers -team (id 19837241), leaving out `echelon-robot`, which only has read access; update it by PR -in both places when the team changes. +team (id 19837241), leaving out `echelon-robot`, which only has read access; update it by PR in both +places when the team changes. **Admission timing.** The candidate check reads the newest CI run on the candidate commit and main's latest finished Sonar analysis, so when to dispatch matters: @@ -39,19 +68,19 @@ main's latest finished Sonar analysis, so when to dispatch matters: **Platform rows.** The producer caller lists `platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer run builds every listed platform for one all-or-nothing release (one failed or -skipped platform stops that night's release, Windows included), and the release-ref signer admits +skipped platform stops that night's release, Windows included), and the signer admits platforms only from the protected policy, so there is no separate Linux or macOS caller job and the signer caller has no platform input. ## Installed policy values and their sources -Read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`. +Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` is advanced to it. | Field | Value | Source | |---|---|---| | `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | -| `producer_workflow_id` | `null` (pending registration on `main`) | Populate via `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` reaches `main` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `producer_workflow_id` | `429738073` | `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | Stable suite signing identities (`Learning Machines Inc` Authenticode subject, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | @@ -68,11 +97,15 @@ those values in the same reviewed change that promotes the policy to `release`. - `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named `TextureCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets may be passed or inherited. -- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, - and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, +- `.github/workflows/nightly-sign.yml`: top-level registration on `nightly-signer`, enabled for manual dispatch, + and only ever fast-forwards to reviewed main commits. It rejects wrong repository/event/actual branch, including same-name tags. Its constant whole-run concurrency is distinct from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no - credentials; only the shared callee's sign jobs bind the `release` environment. + credentials; only the shared callee's sign jobs bind the `release` environment, which must admit + `nightly-signer` alongside `release` before the first dispatch. +- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally + off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on + `nightly-signer`. No schedule is registered until activation is reviewed. - Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable commit**; the defining workflow SHA and tooling input must match. @@ -89,7 +122,15 @@ those values in the same reviewed change that promotes the policy to `release`. - `nightly-sign.yml` keeps its literal root `concurrency:` block (`texturecraft-nightly-release`, `cancel-in-progress: false`, `queue: max`). - `.github/nightly-signing-policy.json` matches the v3 schema, repository identity, platform - trust anchors, CI workflow trigger contract, and SonarCloud project identity. + trust anchors, CI workflow trigger contract, SonarCloud project identity, and the reviewed Sonar + gate shape (accepted failures inside the issue scope, every live gate condition present once). +- The signer guards `refs/heads/nightly-signer`, passes `app-name: texturecraft`, and the policy's + `release_branch` names it. +- A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml` + calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml` + is `release.yml`. +- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a + `refs/heads/nightly-signer` request. ## App-side producer scripts (Windows and macOS) @@ -134,3 +175,15 @@ release-dispatch and macOS signing suites, plus the Nightly icons must be byte-i `nightly-signing-tests.ps1` (Windows, with `-FixtureRoot`), and `bash -n` plus shellcheck over the three macOS scripts. The full-ci macOS job (`nightly-macos.yml`) is the only place the bundle and its version query actually run before the first supervised release. + +## The Sonar issue scope + +The pinned candidate validator requires every entry in `candidate_policy.sonar.issue_types` to map +from a reviewed `accepted_conditions` row, and it requires the gate condition set to equal +`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with +`new_security_rating` accepted (max 5) and the other five gate conditions required - the same shape +PhotoCraft and WordCraft ship - so it satisfies that contract before SonarCloud is read. `debt` stays +empty, so any unresolved vulnerability on `main` is still refused, and the live gate is still compared +condition by condition against the policy. `producer_workflow_id` is now populated and the signer runs +on `nightly-signer`; the registry's Windows and macOS targets are what still stand between this tree +and a first signed nightly. diff --git a/docs/releasing.md b/docs/releasing.md index 2658af20..8dbec3c4 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -31,9 +31,8 @@ release push. An org admin completes the following setup for this repo: Those twelve (`APPLE_*` and `KEYCHAIN_PASSWORD`, `AZURE_*`) are all a signed release needs; `GITHUB_TOKEN` is provided by Actions. -4. Add the repo to the org's **Default runner group** (Settings → Actions → Runner groups). The - macOS job (`macos-15-xlarge`) and the FreeBSD job (`github-ubuntu-16core`) run on larger runners, - which only serve repos in that group; outside it they wait for a runner forever, with no error. +4. Add the repo to the org's **Default runner group** (Settings → Actions → Runner groups) for the + larger macOS runner (`macos-15-xlarge`). The FreeBSD release job runs its VM on `ubuntu-latest`. ### 2. Set the version @@ -109,15 +108,16 @@ All file names are `texturecraft---.`, written to | Windows x64, x86, arm64 | `-windows-.msi`, `-windows--portable.zip` | `packaging/windows/package.ps1` | | Linux x86_64, aarch64 (Ubuntu 22.04, glibc 2.35) | `.AppImage` + `.AppImage.zsync`, `.deb`, `.rpm`, `.tar.gz` | `packaging/linux/package.sh` | | Flatpak x86_64, aarch64 | `-linux-.flatpak`, repackaged from the Linux tarball | `packaging/linux/flatpak-bundle.sh` | -| FreeBSD x86_64 (14.3 VM on `github-ubuntu-16core`) | `-freebsd-x86_64.tar.gz` | `packaging/freebsd/package.sh` | +| FreeBSD x86_64 and aarch64 (aarch64 is cross-compiled in the x86_64 VM) | `-freebsd-.tar.gz` | `packaging/freebsd/package.sh` | | Web | `texturecraft-web-.zip` (trunk, `wasm-release` profile; hosting notes in `packaging/web/README.md`) | `packaging/web/package.sh` | Every desktop package ships both binaries, `texturecraft` and `texturecraft-cli` (on macOS the CLI is its own zip next to the DMG). Release builds embed the craft-fonts interface font (Inter) and CJK UI fonts (`CRAFT_FONTS_REF` in `release.yml`) and ship their `OFL-.txt` licences with the other -notices. The packaging -scripts smoke-test `texturecraft-cli --version`, and the Linux job also runs the AppImage with -`--version`, so both binaries must print their version and exit without opening a window. +notices. The packaging scripts smoke-test `texturecraft-cli --version` where they can run the +staged binary. The FreeBSD aarch64 release cross-build skips that check. The Linux job also runs +the AppImage with `--version` as a non-blocking check. Both binaries must print their version and +exit without opening a window. ## TextureCraft-specific values @@ -155,6 +155,13 @@ entry and icons). Secrets live only in the `release` environment and are all optional: a missing one gives an unsigned artifact and a `::warning::`, never a failed build. +The supervised nightly signer does not sign from `release`: it runs on `refs/heads/nightly-signer`, +which only ever fast-forwards to reviewed main commits, and the `release` environment must admit +`nightly-signer` alongside `release` before the first dispatch. Everything that can reach it is the +trust closure: all of `.github/` and `packaging/`, including `packaging/env.sh`, which +`packaging/macos/import-cert.sh` sources with the Apple keys. Stable releases still come only from +`refs/heads/release`. + - macOS: `APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD` (import into a temporary keychain, `packaging/macos/import-cert.sh`), then `APPLE_ID`, `APPLE_PASSWORD`, `APPLE_TEAM_ID` for `notarytool` and stapling. Without them the app is ad-hoc signed. @@ -173,7 +180,7 @@ artwork and keep `ATTRIBUTION.md` in step. See `assets/app-icon/README.md`. ## Local checks -- `cargo xtask ci`: fmt, clippy, tests, `cargo xtask layers`, `cargo xtask wasm`. +- `cargo xtask ci`: fmt, clippy, tests, `cargo xtask layers`, `cargo xtask wasm` (not run by `ci` on Windows; the other hosts cover it). - `bash packaging/linux/apprun-test.sh` and `bash packaging/freebsd/package.sh --dry-run` run anywhere with bash. - `packaging/macos/package.sh --arch aarch64` on a Mac builds an ad-hoc signed DMG. diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index bf2b46ca..6927f0a4 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -1,12 +1,12 @@ #!/usr/bin/env bash -# Build and package TextureCraft for FreeBSD: +# Build and package TextureCraft for FreeBSD. The archive's is x86_64 or aarch64. # -# $DIST/texturecraft--freebsd-x86_64.tar.gz a /usr/local-style tree: -# texturecraft--freebsd-x86_64/{bin, share/applications, share/icons, share/mime, +# $DIST/texturecraft--freebsd-.tar.gz a /usr/local-style tree: +# texturecraft--freebsd-/{bin, share/applications, share/icons, share/mime, # share/metainfo, share/doc/texturecraft} # # Install by copying the tree's contents into /usr/local: -# tar -xzf texturecraft--freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local +# tar -xzf texturecraft--freebsd-.tar.gz --strip-components 1 -C /usr/local # # Usage: packaging/freebsd/package.sh [--skip-build] [--dry-run] # --dry-run stage the tree from stub binaries and list it, without building (works on any OS) @@ -24,7 +24,7 @@ while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; - -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + -h | --help) sed -n '1d; /^#/!q; p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac done diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index ee421e95..c55e54c1 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -9,6 +9,9 @@ import unittest ROOT = Path(__file__).resolve().parents[1] INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" +APP_NAME = "texturecraft" +PRODUCER_WORKFLOW_NAME = "TextureCraft unsigned nightly" + NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") NIGHTLY_TRUST = { "windows-x86_64": ("publisher_subject", @@ -42,6 +45,30 @@ def assert_nightly_serialization(source): raise ValueError("nightly serialization must use its stable group and no cancellation") +def literal_off(condition): + """True only for a guard that a reviewed test update can still see is switched off.""" + expression = " ".join(condition.split()) + if expression.startswith("${{") and expression.endswith("}}"): + expression = expression[3:-2].strip() + if expression == "false": + return True + if not expression.startswith("false && "): + return False + # A top-level OR could override the leading false; parentheses must balance. + expression = re.sub(r"'(?:''|[^'])*'", "''", expression) + depth = 0 + for token in re.findall(r"\(|\)|\|\|", expression): + if token == "(": + depth += 1 + elif token == ")": + depth -= 1 + if depth < 0: + return False + elif depth == 0: + return False + return depth == 0 + + def job_conditions(jobs): """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" lines = jobs.splitlines() @@ -226,7 +253,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.ref_type == 'branch' && (github.event_name == 'schedule' || " "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_dispatch' && " - "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + "github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'", } def test_enabled_jobs_keep_exact_context_guards(self): @@ -298,7 +325,8 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertEqual(set(self.policy), expected) self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") self.assertEqual(self.policy["repository"], "storytold/texturecraft") - self.assertEqual(self.policy["release_branch"], "release") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, + "the signer runs on its dedicated branch") self.assertIs(type(self.policy["repository_id"]), int) self.assertGreater(self.policy["repository_id"], 0) # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. @@ -384,6 +412,353 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertIn(item["type"], sonar["issue_types"]) self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + def test_sonar_policy_keeps_the_shared_candidate_contract(self): + """The Sonar shape craft-common-actions' candidate contract() admits, refused here first. + + An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both + lists, a missing live gate condition or a widened security bound is refused at admission, so + this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved + vulnerability on main is still refused; accepting the new-code rating only records the + reviewed A threshold instead of demanding a clean rating the live gate does not. + """ + sonar = self.policy["candidate_policy"]["sonar"] + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating", + "new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"} + self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed") + self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"]))) + metrics = {} + for field in ("accepted_conditions", "required_conditions"): + for condition in sonar[field]: + with self.subTest(field=field, metric=condition.get("metric")): + expected = {"metric", "comparator", "error_threshold"} + if field == "accepted_conditions": + expected.add("maximum") + self.assertEqual(set(condition), expected) + self.assertNotIn(condition["metric"], metrics, "one condition per gate metric") + metrics[condition["metric"]] = condition + self.assertIn(condition["comparator"], ("GT", "LT")) + self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + if field != "accepted_conditions": + continue + self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map") + self.assertIn(accepted[condition["metric"]], sonar["issue_types"], + "an accepted failure must lie inside the reviewed issue scope") + self.assertEqual(condition["comparator"], "GT") + self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + maximum = float(condition["maximum"]) + if condition["metric"] in ("security_rating", "new_security_rating"): + self.assertEqual(int(maximum), maximum, "the A..E bound is a whole rating") + self.assertTrue(1 <= maximum <= 5, "the security bound stays A..E") + self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays") + else: + self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt") + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]), + "accepted conditions and reviewed issue types must cover the same scope") + self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once") + + +SIGNER_BRANCH = "nightly-signer" +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif masked is None or flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + # The masked text only proves the shape: a quoted key ("uses", 'environment') keeps + # its identity, so the entries are read from the original mapping text, never ''. + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'}, + "a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"}, + "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self): + entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n') + self.assertEqual(refused, []) + self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity") + self.assertIn((2, "runs-on", "ubuntu-latest", False), entries) + _, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n") + self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"]) + + def test_signer_dispatch_guard_and_policy_name_the_same_branch(self): + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [APP_NAME], + "the shared signer needs the reviewed registry app") + dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + self.assertEqual(re.findall(r"'ref': '([^']+)'", dispatch), ["refs/heads/" + SIGNER_BRANCH]) + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + + +def dispatch_triggers(source): + """The dispatch workflow's own triggers, one per line, as a caller may register them.""" + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + return [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") + and line.strip() and not line.lstrip().startswith("#")] + + +class NightlyDispatchTransport(unittest.TestCase): + """The scheduled transport stays literally off and can only reach the signer branch.""" + + def setUp(self): + self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + + def test_every_dispatch_job_is_literal_off(self): + jobs = self.source.split("\njobs:\n", 1)[1] + headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + conditions = job_conditions(jobs) + self.assertTrue(headers) + self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") + for _, expression in conditions: + self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + + def test_only_a_completed_scheduled_producer_is_transported(self): + self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source), + ["[" + PRODUCER_WORKFLOW_NAME + "]"]) + self.assertEqual(dispatch_triggers(self.source), [" workflow_run:"], + "the transport is not a second entry point") + self.assertNotIn("schedule:", self.source) + self.assertIn("producer.get('event') == 'schedule'", self.source) + + def test_the_request_names_the_signer_workflow_and_branch(self): + self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source) + self.assertNotIn("'ref': 'release'", self.source) if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2ff6178a..e1ce8ee1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -155,13 +155,20 @@ fn cmd_ci() -> Result<(), String> { }; type Step = (&'static str, Box Result<(), String>>); // Reject invalid dependency layering before spending time compiling and running the workspace. - let steps: Vec = vec![ + let mut steps: Vec = vec![ ("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))), ("layers", Box::new(cmd_layers)), ("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))), ("test", Box::new(cargo_step(&["test", "--workspace"]))), - ("wasm", Box::new(cmd_wasm)), ]; + // The check compiles for wasm32 and gives the same answer on any host, so the non-Windows legs + // cover it and the slower Windows leg skips it. A skipped step is not in the list, so the + // summary never reports it as ok. + if cfg!(windows) { + eprintln!("ci: wasm check not run on Windows (the other hosts cover it)"); + } else { + steps.push(("wasm", Box::new(cmd_wasm))); + } for (i, (name, step)) in steps.iter().enumerate() { eprintln!("\n=== ci: {name} ==="); if let Err(e) = step() {