From 2c810ed885d502b69fa01d7adaffce7790b488ac Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:30:35 -0500 Subject: [PATCH 01/16] chore: add AGENTS.md, PR template, and CI workflow for ZOGWORK/mantis --- .github/pull_request_template.md | 13 ++++++++ .github/workflows/ci.yml | 54 ++++++++++++++++++++++++++++++++ AGENTS.md | 33 +++++++++++++++++++ CLAUDE.md | 3 ++ 4 files changed, 103 insertions(+) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/ci.yml create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..318e87b --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## What and why + + + +## Screenshots + + + +## Tests + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c0d7727 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + fmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - run: cargo fmt --check + + check: + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ runner.os }}-cargo + - name: Cache OpenCascade (.occt) + uses: actions/cache@v4 + with: + path: .occt + key: ${{ runner.os }}-occt-8.0.1 + - name: Install CMake (macOS) + if: runner.os == 'macOS' + run: brew install cmake + - name: Clippy + run: cargo clippy --workspace --all-targets + - name: Test + run: cargo test --workspace diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..15cdca6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,33 @@ +# AGENTS.md + +How to work in this repo (humans and coding agents alike). Mantis: +agentic hardware IDE in Rust on GPUI. Fork of `GrowlyX/mantis` maintained under `ZOGWORK/mantis` with full Windows support. + +## Workflow + +1. **Every change goes through a pull request.** Branch from `main`, push, and open the PR against `ZOGWORK/mantis`. Never push to `main` directly. Cut branches with `git checkout --no-track -b origin/main` and push with `git push -u origin HEAD:refs/heads/`. +2. **Loopy review to 5/5 — Loopy is the only reviewer.** Trigger with a `@loopyreviews-bot review` comment, fix every finding, reply on and resolve each thread, push, and re-trigger. Merge only when the latest Loopy comment says **Confidence 5/5**, its "last reviewed" commit is the PR's **current head commit**, **0 threads are unresolved**, and CI is green. Read the bot's comment itself, not only the `loopy/review` status. If Loopy is down, stop and ask the owner: there is no self-review fallback. +3. **Tests, formatting, and lints before pushing.** Run `cargo fmt --check`, `cargo clippy --workspace --all-targets`, and `cargo test --workspace`. A bug fix comes with a test that fails on `main` and passes on the branch. +4. **Keep upstream compatibility.** Preserve `#[cfg(target_os = "macos")]` / `#[cfg(unix)]` paths untouched wherever possible and isolate Windows-specific implementations under `#[cfg(target_os = "windows")]`, so `upstream` (`GrowlyX/mantis`) stays easy to sync and our changes can be upstreamed cleanly. + +## Screenshots and verification + +5. **UI changes ship with screenshots, captured before the PR opens.** If the diff changes anything a user sees in `mantis-app` (layout, panels, colors, 3D viewport, controls, dialogs), the PR body embeds at least one screenshot of the rendered change inline — before/after when the change is visual. A link out, a screenshot of code, or a promise to demo later does not satisfy this. A PR with no user-visible change writes `"No user-visible change."` in the template's `## Screenshots` section rather than deleting it, so the reviewer sees the claim and can disagree. +6. **Capture with `scripts/shots.ps1` (Windows) or `MANTIS_SNAPSHOT` (macOS), never ad-hoc scripts.** It runs `mantis` headless via `MANTIS_SNAPSHOT`, `MANTIS_STATE`, `MANTIS_DO`, and `MANTIS_SIZE`, and writes PNGs **outside the repository** (under `$env:TEMP\mantis-shots`). Attach them with the GitHub CLI: `gh pr create --attach 'file.png#alt text'` or `gh pr comment --attach ...`. Never commit screenshots to the repo. + +## Code conventions + +7. **Line endings:** LF (`\n`) for Rust/TOML/YAML/Markdown; PowerShell scripts (`.ps1`) may use UTF-8. No spaces in file names. +8. **Secrets:** Never commit API keys (`ANTHROPIC_API_KEY`, `EXA_API_KEY`, `MANTIS_STORE_TOKEN`) or `.db` files. +9. **Upstream sync:** `origin` is `ZOGWORK/mantis` and `upstream` is `GrowlyX/mantis`. Sync `main` via `git fetch upstream` and PRs, never force-push `main`. + +## Useful commands + +```powershell +cargo test --workspace # run all Rust unit/integration tests +cargo clippy --workspace --all-targets # lint workspace +cargo run --release -p mantis-app # launch the GPUI desktop app +cargo run --release -p mantis-cli -- demo out # build and route reference board +.\scripts\shots.ps1 # capture PR screenshots outside repo +.\scripts\bundle.ps1 # build release Windows package +``` diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b7f94f9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# CLAUDE.md + +Read and follow [AGENTS.md](AGENTS.md): every change via PR on `ZOGWORK/mantis`, Loopy (the only reviewer) to 5/5 on the head commit, `cargo fmt --check` + `cargo clippy` + `cargo test --workspace`, and screenshots with `scripts/shots.ps1` (or `MANTIS_SNAPSHOT`) for anything user-visible. From b3870a08f92e329a7a4197942d062dec24603688 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:15:51 -0500 Subject: [PATCH 02/16] feat: full Windows compatibility, mantis-ui compat crate, shots & bundle scripts --- .github/workflows/ci.yml | 9 +- Cargo.lock | 374 ++++- Cargo.toml | 4 + crates/mantis-agent/Cargo.toml | 3 + crates/mantis-agent/src/design_tool.rs | 2 +- crates/mantis-agent/src/harness.rs | 19 +- crates/mantis-agent/src/lib.rs | 3 +- crates/mantis-agent/src/mcp.rs | 51 +- crates/mantis-agent/src/models.rs | 34 +- crates/mantis-agent/src/rpc.rs | 3 +- crates/mantis-app/Cargo.toml | 20 +- crates/mantis-app/src/main.rs | 3 + crates/mantis-app/src/projects.rs | 26 +- crates/mantis-app/src/snapshot.rs | 371 +++-- crates/mantis-app/src/store.rs | 2 +- crates/mantis-app/src/viewport.rs | 18 + crates/mantis-app/src/workspace.rs | 35 +- crates/mantis-app/src/workspace/form.rs | 3 +- crates/mantis-cli/src/main.rs | 12 + crates/mantis-core/src/lib.rs | 1 + crates/mantis-core/src/paths.rs | 88 + crates/mantis-fab/src/models.rs | 3 +- crates/mantis-render/src/shots.rs | 17 +- scripts/bundle.ps1 | 35 + scripts/shots.ps1 | 42 + vendor/mantis-ui/Cargo.toml | 11 + vendor/mantis-ui/src/anim.rs | 43 + vendor/mantis-ui/src/assets.rs | 14 + vendor/mantis-ui/src/components.rs | 2026 +++++++++++++++++++++++ vendor/mantis-ui/src/input.rs | 244 +++ vendor/mantis-ui/src/lib.rs | 13 + vendor/mantis-ui/src/theme.rs | 162 ++ vendor/mantis-ui/src/toast.rs | 148 ++ 33 files changed, 3666 insertions(+), 173 deletions(-) create mode 100644 crates/mantis-core/src/paths.rs create mode 100644 scripts/bundle.ps1 create mode 100644 scripts/shots.ps1 create mode 100644 vendor/mantis-ui/Cargo.toml create mode 100644 vendor/mantis-ui/src/anim.rs create mode 100644 vendor/mantis-ui/src/assets.rs create mode 100644 vendor/mantis-ui/src/components.rs create mode 100644 vendor/mantis-ui/src/input.rs create mode 100644 vendor/mantis-ui/src/lib.rs create mode 100644 vendor/mantis-ui/src/theme.rs create mode 100644 vendor/mantis-ui/src/toast.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c0d7727..9de2dc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: concurrency: group: ci-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} permissions: contents: read @@ -18,8 +18,11 @@ env: jobs: fmt: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: components: rustfmt @@ -34,6 +37,8 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: components: clippy @@ -44,7 +49,7 @@ jobs: uses: actions/cache@v4 with: path: .occt - key: ${{ runner.os }}-occt-8.0.1 + key: ${{ runner.os }}-occt-${{ hashFiles('Cargo.lock') }} - name: Install CMake (macOS) if: runner.os == 'macOS' run: brew install cmake diff --git a/Cargo.lock b/Cargo.lock index 98badad..b3b69fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" @@ -102,6 +108,21 @@ dependencies = [ "equator", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.22" @@ -761,6 +782,27 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bstr" version = "1.14.0" @@ -1114,6 +1156,15 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + [[package]] name = "color_quant" version = "1.1.0" @@ -2064,6 +2115,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fearless_simd" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4beca3cb2444e3304ac30843cc091f44ed58932353cd492ce740067bfce6b12" + +[[package]] +name = "fearless_simd" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" + [[package]] name = "filedescriptor" version = "0.8.3" @@ -2552,6 +2615,23 @@ dependencies = [ "simba", ] +[[package]] +name = "glifo" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1218dedd5348c1b166ec3b8b3cbca49d2f527bd43b3fa072ea5123c523ed3f" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.2", + "log", + "peniko", + "png 0.18.1", + "skrifa 0.44.0", + "smallvec", + "vello_common", +] + [[package]] name = "glob" version = "0.3.4" @@ -2890,6 +2970,15 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12101ecc8225ea6d675bc70263074eab6169079621c2186fe0c66590b2df9681" +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid 0.22.14", +] + [[package]] name = "h2" version = "0.4.21" @@ -2976,6 +3065,113 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "hayro" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34d3977ae664ab6eea015be3024379c83c6a3580f67d51be6884f1992bf683ba" +dependencies = [ + "ab_glyph_rasterizer", + "bytemuck", + "fearless_simd 1.3.0", + "hayro-interpret", + "image", + "kurbo 0.13.1", + "pic-scale", + "rustc-hash 2.1.3", + "vello_cpu", +] + +[[package]] +name = "hayro-ccitt" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46" + +[[package]] +name = "hayro-cmap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-font" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac7f0c78172573e9bd6eeb17f62c63f4d378b2a2d127c3ee9c2c7cc6fbdf78b" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-syntax", + "kurbo 0.13.1", + "phf", + "rustc-hash 2.1.3", + "siphasher", + "skrifa 0.49.0", +] + +[[package]] +name = "hayro-interpret" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "166477622df4b770a0fc5889a9e4b48c7ff8595d6ec019bf71b4297b97b55fb6" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-font", + "hayro-syntax", + "kurbo 0.13.1", + "moxcms", + "rustc-hash 2.1.3", + "siphasher", + "smallvec", +] + +[[package]] +name = "hayro-jbig2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840" +dependencies = [ + "fearless_simd 1.3.0", + "hayro-ccitt", +] + +[[package]] +name = "hayro-jpeg2000" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740" +dependencies = [ + "fearless_simd 1.3.0", +] + +[[package]] +name = "hayro-postscript" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" + +[[package]] +name = "hayro-syntax" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d" +dependencies = [ + "flate2", + "hayro-ccitt", + "hayro-jbig2", + "hayro-jpeg2000", + "memchr", + "rustc-hash 2.1.3", + "smallvec", + "zune-jpeg 0.5.15", +] + [[package]] name = "heapless" version = "0.8.0" @@ -3228,7 +3424,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.57.0", + "windows-core 0.61.2", ] [[package]] @@ -3604,6 +3800,18 @@ dependencies = [ "smallvec", ] +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid 0.22.14", + "polycool", + "smallvec", +] + [[package]] name = "kv-log-macro" version = "1.0.7" @@ -3695,6 +3903,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + [[package]] name = "link-cplusplus" version = "1.0.12" @@ -3870,6 +4084,7 @@ dependencies = [ "anyhow", "base64 0.22.1", "futures", + "hayro", "image", "mantis-cad", "mantis-core", @@ -3912,6 +4127,7 @@ dependencies = [ "serde_json", "smallvec", "uuid", + "windows-sys 0.59.0", ] [[package]] @@ -4017,15 +4233,10 @@ dependencies = [ [[package]] name = "mantis-ui" version = "0.1.0" -source = "git+https://github.com/GrowlyX/mantis-ui?rev=0cc449c5b9b8c8f37f85f88f67a5371311cbff36#0cc449c5b9b8c8f37f85f88f67a5371311cbff36" dependencies = [ "anyhow", - "core-foundation 0.10.0", - "core-graphics 0.24.0", - "foreign-types", "gpui", - "raw-window-handle", - "unicode-segmentation", + "smallvec", ] [[package]] @@ -4815,12 +5026,77 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo 0.13.1", + "linebender_resource_handle", + "smallvec", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand 2.5.0", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pic-scale" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d76fd225dc3b8f089eaac369a74f57f557faffbd5da109ddd4e011010ab3ca10" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -4922,6 +5198,15 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + [[package]] name = "pom" version = "1.1.0" @@ -5394,6 +5679,20 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types", + "once_cell", + "smallvec", + "yoke", +] + [[package]] name = "redox_syscall" version = "0.2.16" @@ -5722,7 +6021,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6206,7 +6505,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" +dependencies = [ + "bytemuck", + "once_cell", + "read-fonts 0.46.0", + "smallvec", + "yoke", ] [[package]] @@ -6505,7 +6817,7 @@ version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" dependencies = [ - "kurbo", + "kurbo 0.11.3", "siphasher", ] @@ -6515,7 +6827,7 @@ version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" dependencies = [ - "skrifa", + "skrifa 0.44.0", "yazi", "zeno", ] @@ -7268,7 +7580,7 @@ dependencies = [ "flate2", "fontdb 0.23.0", "imagesize", - "kurbo", + "kurbo 0.11.3", "log", "pico-args", "roxmltree", @@ -7371,6 +7683,35 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "vello_common" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c2fbe53548bcd25c8ff42f75a93770a8611a16b37bee56d7ef7b44e36027f1" +dependencies = [ + "bytemuck", + "fearless_simd 0.7.0", + "guillotiere", + "log", + "peniko", + "png 0.18.1", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed1fec424fbba6acf6cbc78bb526447eb77590d95f40419d598870fe37535212" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.2", + "png 0.18.1", + "vello_common", +] + [[package]] name = "version_check" version = "0.9.5" @@ -7922,6 +8263,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.61.2" diff --git a/Cargo.toml b/Cargo.toml index 595ed1c..fce9767 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,3 +42,7 @@ opt-level = 3 # aisdk with one patch: tool results can carry images. See vendor/aisdk/MANTIS.md. [patch.crates-io] aisdk = { path = "vendor/aisdk" } + +# Local compatibility crate for the private mantis-ui design kit. +[patch."https://github.com/GrowlyX/mantis-ui"] +mantis-ui = { path = "vendor/mantis-ui" } diff --git a/crates/mantis-agent/Cargo.toml b/crates/mantis-agent/Cargo.toml index 275aad9..e30db10 100644 --- a/crates/mantis-agent/Cargo.toml +++ b/crates/mantis-agent/Cargo.toml @@ -26,3 +26,6 @@ tiny_http = "0.12" uuid = { workspace = true, features = ["v4"] } url = "2" image = { workspace = true, features = ["png", "jpeg", "gif", "webp"] } + +[target.'cfg(not(target_os = "macos"))'.dependencies] +hayro = "0.9" diff --git a/crates/mantis-agent/src/design_tool.rs b/crates/mantis-agent/src/design_tool.rs index 0986935..f212a3b 100644 --- a/crates/mantis-agent/src/design_tool.rs +++ b/crates/mantis-agent/src/design_tool.rs @@ -780,7 +780,7 @@ fn move_axle(s: &mut Session, j: &kin::Joint, on: &str, solved: &kin::Solved, by fn export_dir(s: &Session) -> std::path::PathBuf { let name: String = s.board.name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect(); - let base = std::env::var_os("HOME").map(std::path::PathBuf::from).unwrap_or_else(std::env::temp_dir).join("Mantis").join("Exports"); + let base = mantis_core::paths::projects_home().join("Exports"); base.join(if name.trim_matches('-').is_empty() { "design".to_string() } else { name }) } diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 99b9300..baf2011 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -31,17 +31,7 @@ const HARNESS_NOTE: &str = "\n\nYou are running inside Claude Code. The Mantis t /// the first one found on the search path or where its installers put it. An app started /// from the Finder has a short search path, so the usual places are tried by name. pub fn find_claude() -> Option { - if let Some(path) = crate::config_value("MANTIS_CLAUDE", "claude_path") { - let path = PathBuf::from(path); - return runnable(&path).then_some(path); - } - let home = std::env::var_os("HOME").map(PathBuf::from); - let mut places: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); - if let Some(home) = &home { - places.extend([home.join(".local/bin"), home.join(".claude/local"), home.join(".npm-global/bin"), home.join(".bun/bin")]); - } - places.extend(["/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from)); - places.into_iter().map(|dir| dir.join("claude")).find(|p| runnable(p)) + crate::models::find_program("claude", "MANTIS_CLAUDE", "claude_path") } /// Run an agent program in the person's own home, where its sign-in is, even when Mantis @@ -49,7 +39,9 @@ pub fn find_claude() -> Option { /// `MANTIS_CLAUDE_HOME`. pub(crate) fn agent_home(command: &mut Command) { if let Some(home) = std::env::var_os("MANTIS_AGENT_HOME").or_else(|| std::env::var_os("MANTIS_CLAUDE_HOME")) { - command.env("HOME", home); + command.env("HOME", &home); + #[cfg(windows)] + command.env("USERPROFILE", &home); } } @@ -79,8 +71,7 @@ pub fn claude_code() -> Option { /// The folder Claude Code runs in for Mantis: where its sessions are filed and where pages /// are left for it to read. pub(crate) fn workdir() -> Result { - let home = std::env::var_os("HOME").context("no home directory")?; - let dir = PathBuf::from(home).join("Library/Application Support/Mantis/agent"); + let dir = mantis_core::paths::app_data_dir().join("agent"); std::fs::create_dir_all(dir.join("pages"))?; Ok(dir) } diff --git a/crates/mantis-agent/src/lib.rs b/crates/mantis-agent/src/lib.rs index 0e7cec5..e9e1b6c 100644 --- a/crates/mantis-agent/src/lib.rs +++ b/crates/mantis-agent/src/lib.rs @@ -157,8 +157,7 @@ impl ModelChoice { } pub fn config_path() -> Option { - let home = std::env::var_os("HOME")?; - Some(std::path::PathBuf::from(home).join(".config/mantis/config.json")) + mantis_core::paths::config_dir().map(|d| d.join("config.json")) } /// A setting from the environment variable `env`, else from `key` in Mantis's config file. diff --git a/crates/mantis-agent/src/mcp.rs b/crates/mantis-agent/src/mcp.rs index 1494a73..87a6d29 100644 --- a/crates/mantis-agent/src/mcp.rs +++ b/crates/mantis-agent/src/mcp.rs @@ -3,7 +3,9 @@ //! [`run_tool`] as the API path, so the board moves as it does there. use crate::{Emit, Research, Session, run_tool, tools}; -use anyhow::{Context, Result, anyhow, bail}; +#[cfg(target_os = "macos")] +use anyhow::bail; +use anyhow::{Context, Result, anyhow}; use base64::Engine as _; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; @@ -189,8 +191,9 @@ fn content(served: &Served, result: &Value) -> Vec { .collect() } -/// Each page of a PDF as a PNG 1600 pixels across, drawn by Quick Look, which every Mac -/// has and which draws text sharply. `stem` is where the work files go. +/// Each page of a PDF as a PNG 1600 pixels across. Uses Quick Look on macOS, or +/// pure-Rust `hayro` PDF rasterization on other platforms. `stem` is where the work files go. +#[cfg(target_os = "macos")] fn page_pictures(bytes: &[u8], stem: &Path) -> Result>> { let count = mantis_fab::models::pdf_page_count(bytes)?; let dir = stem.with_extension("d"); @@ -199,7 +202,14 @@ fn page_pictures(bytes: &[u8], stem: &Path) -> Result>> { for page in 1..=count { let one = dir.join(format!("p{page}.pdf")); std::fs::write(&one, mantis_fab::models::pdf_extract_pages(bytes, &[page])?)?; - let status = std::process::Command::new("/usr/bin/qlmanage").args(["-t", "-s", "1600", "-o"]).arg(&dir).arg(&one).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().context("Quick Look could not be run")?; + let status = std::process::Command::new("/usr/bin/qlmanage") + .args(["-t", "-s", "1600", "-o"]) + .arg(&dir) + .arg(&one) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .context("Quick Look could not be run")?; let png = dir.join(format!("p{page}.pdf.png")); if !status.success() || !png.exists() { bail!("Quick Look could not draw page {page}"); @@ -210,6 +220,39 @@ fn page_pictures(bytes: &[u8], stem: &Path) -> Result>> { Ok(pictures) } +#[cfg(not(target_os = "macos"))] +fn page_pictures(bytes: &[u8], _stem: &Path) -> Result>> { + use hayro::hayro_interpret::InterpreterSettings; + use hayro::hayro_syntax::Pdf; + use hayro::{PixmapSettings, RenderCache, RenderSettings, render}; + + let pdf = Pdf::new(std::sync::Arc::new(bytes.to_vec())) + .map_err(|e| anyhow::anyhow!("could not open PDF: {e:?}"))?; + let cache = RenderCache::new(); + let interp = InterpreterSettings::default(); + let rsettings = RenderSettings::default(); + let mut pictures = Vec::new(); + for page in pdf.pages().iter() { + let (w, h) = page.render_dimensions(); + let max_dim = w.max(h).max(1.0); + let scale = (1600.0 / max_dim).clamp(1.0, 16.0); + let pixmap = render( + page, + &cache, + &interp, + &rsettings, + &PixmapSettings { + x_scale: scale, + y_scale: scale, + bg_color: hayro::vello_cpu::color::palette::css::WHITE, + }, + ); + let png = pixmap.into_png().map_err(|e| anyhow::anyhow!("could not encode PDF page PNG: {e:?}"))?; + pictures.push(png); + } + Ok(pictures) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mantis-agent/src/models.rs b/crates/mantis-agent/src/models.rs index 930266c..3074a2f 100644 --- a/crates/mantis-agent/src/models.rs +++ b/crates/mantis-agent/src/models.rs @@ -88,13 +88,39 @@ pub fn find_program(name: &str, env: &str, key: &str) -> Option { let path = PathBuf::from(path); return crate::harness::runnable(&path).then_some(path); } - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = mantis_core::paths::user_home(); let mut places: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); if let Some(home) = &home { - places.extend([home.join(".local/bin"), home.join(".npm-global/bin"), home.join(".bun/bin"), home.join(".cargo/bin")]); + places.extend([home.join(".local/bin"), home.join(".claude/local"), home.join(".npm-global/bin"), home.join(".bun/bin"), home.join(".cargo/bin")]); + } + #[cfg(windows)] + { + if let Some(appdata) = std::env::var_os("APPDATA").map(PathBuf::from) { + places.push(appdata.join("npm")); + } + if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) { + places.push(local.join("Programs")); + } + let exts = ["exe", "cmd", "bat"]; + for dir in places { + let direct = dir.join(name); + if crate::harness::runnable(&direct) { + return Some(direct); + } + for ext in exts { + let cand = dir.join(format!("{name}.{ext}")); + if crate::harness::runnable(&cand) { + return Some(cand); + } + } + } + None + } + #[cfg(not(windows))] + { + places.extend(["/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from)); + places.into_iter().map(|dir| dir.join(name)).find(|p| crate::harness::runnable(p)) } - places.extend(["/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from)); - places.into_iter().map(|dir| dir.join(name)).find(|p| crate::harness::runnable(p)) } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/mantis-agent/src/rpc.rs b/crates/mantis-agent/src/rpc.rs index a4e4ba7..a1245e4 100644 --- a/crates/mantis-agent/src/rpc.rs +++ b/crates/mantis-agent/src/rpc.rs @@ -205,7 +205,8 @@ for line in sys.stdin: else: print(json.dumps({"jsonrpc":"2.0","id":m["id"],"result":m["params"]}), flush=True) "#; - let mut command = Command::new("python3"); + let python = if cfg!(windows) { "python" } else { "python3" }; + let mut command = Command::new(python); command.args(["-c", script]); let rpc = Rpc::spawn(command).unwrap(); assert_eq!(rpc.request("echo", json!({"a": 2})).unwrap(), json!({"a": 2})); diff --git a/crates/mantis-app/Cargo.toml b/crates/mantis-app/Cargo.toml index 819d6c9..625b5e4 100644 --- a/crates/mantis-app/Cargo.toml +++ b/crates/mantis-app/Cargo.toml @@ -12,7 +12,6 @@ path = "src/main.rs" [dependencies] anyhow.workspace = true serde.workspace = true -libc = "0.2" serde_json.workspace = true image.workspace = true gpui = "0.2.2" @@ -20,7 +19,6 @@ gpui = "0.2.2" mantis-ui = { git = "https://github.com/GrowlyX/mantis-ui", rev = "0cc449c5b9b8c8f37f85f88f67a5371311cbff36" } futures = "0.3" smallvec = "1" -core-graphics = "0.24" raw-window-handle = "0.6" mantis-core.workspace = true mantis-cad.workspace = true @@ -31,3 +29,21 @@ mantis-render.workspace = true mantis-agent.workspace = true mantis-store.workspace = true uuid.workspace = true + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(target_os = "macos")'.dependencies] +core-graphics = "0.24" + +[target.'cfg(target_os = "windows")'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_Storage_FileSystem", + "Win32_Storage_Xps", + "Win32_System_Threading", + "Win32_System_Time", + "Win32_UI_HiDpi", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/crates/mantis-app/src/main.rs b/crates/mantis-app/src/main.rs index 75261cc..5ceaa6b 100644 --- a/crates/mantis-app/src/main.rs +++ b/crates/mantis-app/src/main.rs @@ -77,7 +77,10 @@ fn main() { Application::new().with_assets(assets::Assets).run(move |cx: &mut App| { // Fonts, the kit's keys and its theme. The window sets light or dark once it knows its appearance. mantis_ui::init(cx, mantis_ui::Mode::Dark); + #[cfg(target_os = "macos")] cx.bind_keys([KeyBinding::new("cmd-z", Undo, Some("Workspace")), KeyBinding::new("cmd-q", Quit, None)]); + #[cfg(not(target_os = "macos"))] + cx.bind_keys([KeyBinding::new("ctrl-z", Undo, Some("Workspace")), KeyBinding::new("ctrl-q", Quit, None), KeyBinding::new("alt-f4", Quit, None)]); // These apply while the board view has the keyboard, not while typing in the chat. let stage = Some("Stage"); cx.bind_keys([ diff --git a/crates/mantis-app/src/projects.rs b/crates/mantis-app/src/projects.rs index e221f1c..f60a886 100644 --- a/crates/mantis-app/src/projects.rs +++ b/crates/mantis-app/src/projects.rs @@ -6,7 +6,7 @@ use std::time::{Duration, SystemTime}; /// Where project folders made by earlier builds are, and where exported packages are written. pub fn home() -> PathBuf { - std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join("Mantis") + mantis_core::paths::projects_home() } /// A name that can be a folder's: no separators or control characters, at most 48 characters, @@ -26,6 +26,7 @@ pub fn safe_title(text: &str) -> String { } /// Days since the epoch in this machine's time zone, and the date's (year, month, day). +#[cfg(unix)] fn local_day(at: SystemTime) -> (i64, i32, u32, u32) { let secs = at.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs() as libc::time_t).unwrap_or(0); let mut tm: libc::tm = unsafe { std::mem::zeroed() }; @@ -34,6 +35,29 @@ fn local_day(at: SystemTime) -> (i64, i32, u32, u32) { ((secs + tm.tm_gmtoff).div_euclid(86_400), tm.tm_year + 1900, tm.tm_mon as u32, tm.tm_mday as u32) } +/// Days since the epoch in this machine's time zone, and the date's (year, month, day). +#[cfg(windows)] +fn local_day(at: SystemTime) -> (i64, i32, u32, u32) { + use windows_sys::Win32::Foundation::{FILETIME, SYSTEMTIME}; + use windows_sys::Win32::Storage::FileSystem::FileTimeToLocalFileTime; + use windows_sys::Win32::System::Time::FileTimeToSystemTime; + + // Windows FILETIME epoch is 1601-01-01; Unix epoch is 11644473600 seconds later. + const WINDOWS_TO_UNIX_SECS: u64 = 11_644_473_600; + let secs = at.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let ticks = (secs + WINDOWS_TO_UNIX_SECS) * 10_000_000; + let ft = FILETIME { dwLowDateTime: ticks as u32, dwHighDateTime: (ticks >> 32) as u32 }; + let mut local_ft = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let mut st = SYSTEMTIME { wYear: 0, wMonth: 0, wDayOfWeek: 0, wDay: 0, wHour: 0, wMinute: 0, wSecond: 0, wMilliseconds: 0 }; + unsafe { + FileTimeToLocalFileTime(&ft, &mut local_ft); + FileTimeToSystemTime(&local_ft, &mut st); + } + let local_ticks = ((local_ft.dwHighDateTime as u64) << 32) | (local_ft.dwLowDateTime as u64); + let local_unix_secs = (local_ticks / 10_000_000) as i64 - WINDOWS_TO_UNIX_SECS as i64; + (local_unix_secs.div_euclid(86_400), st.wYear as i32, (st.wMonth as u32).saturating_sub(1), st.wDay as u32) +} + /// The heading a project is listed under: Today, Yesterday, or its date. `at` is in /// milliseconds since 1970, as the store records it. pub fn day_label(at: i64, now: SystemTime) -> String { diff --git a/crates/mantis-app/src/snapshot.rs b/crates/mantis-app/src/snapshot.rs index 691134a..0056e8a 100644 --- a/crates/mantis-app/src/snapshot.rs +++ b/crates/mantis-app/src/snapshot.rs @@ -5,43 +5,10 @@ //! the interface can be looked at and compared without someone at the screen: //! `MANTIS_SNAPSHOT=out.png MANTIS_STATE=select=U2,tab=parts mantis`. -use anyhow::{Context, Result, bail}; -use core_graphics::geometry::{CGPoint, CGRect, CGSize}; -use core_graphics::window::{create_image, kCGWindowImageBestResolution, kCGWindowImageBoundsIgnoreFraming, kCGWindowListOptionIncludingWindow}; +use anyhow::Result; use gpui::Window; -use raw_window_handle::{HasWindowHandle, RawWindowHandle}; -use std::ffi::{CStr, c_char, c_void}; use std::path::Path; -#[link(name = "objc")] -unsafe extern "C" { - fn objc_msgSend(); - fn sel_registerName(name: *const c_char) -> *const c_void; - fn objc_getClass(name: *const c_char) -> *mut c_void; -} - -/// The window's NSView. -fn ns_view(window: &Window) -> Option<*mut c_void> { - let handle = HasWindowHandle::window_handle(window).ok()?; - let RawWindowHandle::AppKit(h) = handle.as_raw() else { return None }; - Some(h.ns_view.as_ptr()) -} - -/// Have GPUI draw one frame on the next turn of the run loop, whether or not the window can -/// be seen. macOS stops the display link of a window that is covered or not in front, which -/// a snapshot run's window is on purpose, so it is called on a timer to keep animations and -/// menus moving for the picture. -pub fn draw_soon(window: &Window) { - let Some(view) = ns_view(window) else { return }; - unsafe { - let layer_of: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - // Deferred, because drawing re-enters the app, which is borrowed while this runs. - let perform: unsafe extern "C" fn(*mut c_void, *const c_void, *const c_void, *mut c_void, f64) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let layer = layer_of(view, sel(c"layer")); - perform(view, sel(c"performSelector:withObject:afterDelay:"), sel(c"displayLayer:"), layer, 0.0); - } -} - /// A pointer press or release. #[derive(Copy, Clone)] pub enum Press { @@ -51,104 +18,274 @@ pub enum Press { RightUp, } -#[repr(C)] -#[derive(Copy, Clone)] -struct NsPoint { - x: f64, - y: f64, -} +#[cfg(target_os = "macos")] +mod imp { + use super::Press; + use anyhow::{Context, Result, bail}; + use core_graphics::geometry::{CGPoint, CGRect, CGSize}; + use core_graphics::window::{create_image, kCGWindowImageBestResolution, kCGWindowImageBoundsIgnoreFraming, kCGWindowListOptionIncludingWindow}; + use gpui::Window; + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use std::ffi::{CStr, c_char, c_void}; + use std::path::Path; + + #[link(name = "objc")] + unsafe extern "C" { + fn objc_msgSend(); + fn sel_registerName(name: *const c_char) -> *const c_void; + fn objc_getClass(name: *const c_char) -> *mut c_void; + } + + fn ns_view(window: &Window) -> Option<*mut c_void> { + let handle = HasWindowHandle::window_handle(window).ok()?; + let RawWindowHandle::AppKit(h) = handle.as_raw() else { return None }; + Some(h.ns_view.as_ptr()) + } + + pub fn draw_soon(window: &Window) { + let Some(view) = ns_view(window) else { return }; + unsafe { + let layer_of: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let perform: unsafe extern "C" fn(*mut c_void, *const c_void, *const c_void, *mut c_void, f64) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let layer = layer_of(view, sel(c"layer")); + perform(view, sel(c"performSelector:withObject:afterDelay:"), sel(c"displayLayer:"), layer, 0.0); + } + } + + #[repr(C)] + #[derive(Copy, Clone)] + struct NsPoint { + x: f64, + y: f64, + } + + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGEventSetIntegerValueField(event: *mut c_void, field: u32, value: i64); + } + + pub fn post_mouse(window: &Window, press: Press, x: f64, y: f64) { + type Make = unsafe extern "C" fn(*mut c_void, *const c_void, usize, NsPoint, usize, f64, isize, *mut c_void, isize, isize, f32) -> *mut c_void; + let Some(id) = window_id(window) else { return }; + let y = f64::from(f32::from(window.viewport_size().height)) - y; + let (kind, right, pressure): (usize, bool, f32) = match press { + Press::LeftDown => (1, false, 1.0), + Press::LeftUp => (2, false, 0.0), + Press::RightDown => (3, true, 1.0), + Press::RightUp => (4, true, 0.0), + }; + unsafe { + let (event_class, app_class, info_class) = (objc_getClass(c"NSEvent".as_ptr()), objc_getClass(c"NSApplication".as_ptr()), objc_getClass(c"NSProcessInfo".as_ptr())); + if event_class.is_null() || app_class.is_null() || info_class.is_null() { + return; + } + let make: Make = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let object: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let seconds: unsafe extern "C" fn(*mut c_void, *const c_void) -> f64 = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let wrap: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let post: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void, i8) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let app = object(app_class, sel(c"sharedApplication")); + let uptime = seconds(object(info_class, sel(c"processInfo")), sel(c"systemUptime")); + let selector = sel(c"mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:"); + let mut event = make(event_class, selector, kind, NsPoint { x, y }, 0, uptime, id as isize, std::ptr::null_mut(), 0, 1, pressure); + if event.is_null() { + return; + } + if right { + const BUTTON_NUMBER: u32 = 3; + let cg = object(event, sel(c"CGEvent")); + if !cg.is_null() { + CGEventSetIntegerValueField(cg, BUTTON_NUMBER, 1); + let again = wrap(event_class, sel(c"eventWithCGEvent:"), cg); + if !again.is_null() { + event = again; + } + } + } + post(app, sel(c"postEvent:atStart:"), event, 0); + } + } + + fn sel(name: &CStr) -> *const c_void { + unsafe { sel_registerName(name.as_ptr()) } + } -#[link(name = "CoreGraphics", kind = "framework")] -unsafe extern "C" { - fn CGEventSetIntegerValueField(event: *mut c_void, field: u32, value: i64); + pub fn window_id(window: &Window) -> Option { + let view = ns_view(window)?; + unsafe { + let get_window: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let get_number: unsafe extern "C" fn(*mut c_void, *const c_void) -> isize = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let ns_window = get_window(view, sel(c"window")); + if ns_window.is_null() { + return None; + } + u32::try_from(get_number(ns_window, sel(c"windowNumber"))).ok() + } + } + + pub fn capture(window_id: u32, path: &Path) -> Result<()> { + let null = CGRect::new(&CGPoint::new(f64::INFINITY, f64::INFINITY), &CGSize::new(0.0, 0.0)); + let image = create_image(null, kCGWindowListOptionIncludingWindow, window_id, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageBestResolution).context("the window server returned no image")?; + let (w, h, stride) = (image.width(), image.height(), image.bytes_per_row()); + if image.bits_per_pixel() != 32 || w == 0 || h == 0 { + bail!("unexpected image format: {} bits, {w}x{h}", image.bits_per_pixel()); + } + let data = image.data(); + let bytes = data.bytes(); + let mut rgba = Vec::with_capacity(w * h * 4); + for row in 0..h { + for px in bytes[row * stride..row * stride + w * 4].as_chunks::<4>().0 { + rgba.extend_from_slice(&[px[2], px[1], px[0], 255]); + } + } + image::save_buffer(path, &rgba, w as u32, h as u32, image::ColorType::Rgba8)?; + Ok(()) + } } -/// Queue a pointer event on this app's own window, so a scripted run can press what a person -/// would. GPUI keeps its event dispatch private, so an AppKit event addressed to the window is -/// the way in. `x` and `y` are points from the top left of the window's content. Main thread only. -pub fn post_mouse(window: &Window, press: Press, x: f64, y: f64) { - type Make = unsafe extern "C" fn(*mut c_void, *const c_void, usize, NsPoint, usize, f64, isize, *mut c_void, isize, isize, f32) -> *mut c_void; - let Some(id) = window_id(window) else { return }; - // AppKit measures up from the bottom of the content. - let y = f64::from(f32::from(window.viewport_size().height)) - y; - // NSEventType, and whether the button is the right one. - let (kind, right, pressure): (usize, bool, f32) = match press { - Press::LeftDown => (1, false, 1.0), - Press::LeftUp => (2, false, 0.0), - Press::RightDown => (3, true, 1.0), - Press::RightUp => (4, true, 0.0), +#[cfg(target_os = "windows")] +mod imp { + use super::Press; + use anyhow::{Result, bail}; + use gpui::Window; + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use std::path::Path; + use windows_sys::Win32::Foundation::{HWND, RECT}; + use windows_sys::Win32::Graphics::Gdi::{ + BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleDC, CreateDIBSection, DIB_RGB_COLORS, + DeleteDC, DeleteObject, GetDC, InvalidateRect, ReleaseDC, SelectObject, }; - unsafe { - let (event_class, app_class, info_class) = (objc_getClass(c"NSEvent".as_ptr()), objc_getClass(c"NSApplication".as_ptr()), objc_getClass(c"NSProcessInfo".as_ptr())); - if event_class.is_null() || app_class.is_null() || info_class.is_null() { - return; + use windows_sys::Win32::Storage::Xps::PrintWindow; + use windows_sys::Win32::UI::HiDpi::GetDpiForWindow; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetClientRect, PostMessageW, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, WM_RBUTTONUP, + }; + + fn hwnd_of(window: &Window) -> Option { + let handle = HasWindowHandle::window_handle(window).ok()?; + let RawWindowHandle::Win32(h) = handle.as_raw() else { return None }; + Some(h.hwnd.get() as HWND) + } + + pub fn draw_soon(window: &Window) { + if let Some(hwnd) = hwnd_of(window) { + unsafe { + InvalidateRect(hwnd, std::ptr::null(), 0); + } + } + } + + pub fn post_mouse(window: &Window, press: Press, x: f64, y: f64) { + let Some(hwnd) = hwnd_of(window) else { return }; + let scale = unsafe { GetDpiForWindow(hwnd) }.max(96) as f64 / 96.0; + let px = (x * scale).round() as i32; + let py = (y * scale).round() as i32; + let lparam = ((py as isize) << 16) | ((px as isize) & 0xFFFF); + let (msg, wparam) = match press { + Press::LeftDown => (WM_LBUTTONDOWN, 1usize), + Press::LeftUp => (WM_LBUTTONUP, 0usize), + Press::RightDown => (WM_RBUTTONDOWN, 2usize), + Press::RightUp => (WM_RBUTTONUP, 0usize), + }; + unsafe { + PostMessageW(hwnd, msg, wparam, lparam); } - let make: Make = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let object: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let seconds: unsafe extern "C" fn(*mut c_void, *const c_void) -> f64 = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let wrap: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let post: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void, i8) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let app = object(app_class, sel(c"sharedApplication")); - let uptime = seconds(object(info_class, sel(c"processInfo")), sel(c"systemUptime")); - let selector = sel(c"mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:"); - let mut event = make(event_class, selector, kind, NsPoint { x, y }, 0, uptime, id as isize, std::ptr::null_mut(), 0, 1, pressure); - if event.is_null() { - return; + } + + pub fn window_id(window: &Window) -> Option { + hwnd_of(window).map(|h| h as usize as u32) + } + + pub fn capture(window_id: u32, path: &Path) -> Result<()> { + let hwnd = window_id as usize as HWND; + let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + if unsafe { GetClientRect(hwnd, &mut rect) } == 0 { + bail!("GetClientRect failed"); } - if right { - // The constructor cannot say which button it was, and GPUI reads the button number, - // so every press would arrive as the left one. Set it on the event underneath and - // wrap that again. - const BUTTON_NUMBER: u32 = 3; // kCGMouseEventButtonNumber - let cg = object(event, sel(c"CGEvent")); - if !cg.is_null() { - CGEventSetIntegerValueField(cg, BUTTON_NUMBER, 1); - let again = wrap(event_class, sel(c"eventWithCGEvent:"), cg); - if !again.is_null() { - event = again; - } + let w = (rect.right - rect.left).max(0) as usize; + let h = (rect.bottom - rect.top).max(0) as usize; + if w == 0 || h == 0 { + bail!("window has zero size: {w}x{h}"); + } + + let hdc_screen = unsafe { GetDC(hwnd) }; + let hdc_mem = unsafe { CreateCompatibleDC(hdc_screen) }; + let bmi = BITMAPINFO { + bmiHeader: BITMAPINFOHEADER { + biSize: std::mem::size_of::() as u32, + biWidth: w as i32, + biHeight: -(h as i32), + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB, + biSizeImage: 0, + biXPelsPerMeter: 0, + biYPelsPerMeter: 0, + biClrUsed: 0, + biClrImportant: 0, + }, + bmiColors: [windows_sys::Win32::Graphics::Gdi::RGBQUAD { rgbBlue: 0, rgbGreen: 0, rgbRed: 0, rgbReserved: 0 }], + }; + let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); + let hbm = unsafe { CreateDIBSection(hdc_mem, &bmi, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0) }; + if hbm.is_null() || bits.is_null() { + unsafe { + DeleteDC(hdc_mem); + ReleaseDC(hwnd, hdc_screen); } + bail!("CreateDIBSection failed"); } - post(app, sel(c"postEvent:atStart:"), event, 0); + let old = unsafe { SelectObject(hdc_mem, hbm) }; + // PW_CLIENTONLY (1) | PW_RENDERFULLCONTENT (2) = 3 + let ok = unsafe { PrintWindow(hwnd, hdc_mem, 3) }; + let bgra = unsafe { std::slice::from_raw_parts(bits as *const u8, w * h * 4) }; + let mut rgba = Vec::with_capacity(w * h * 4); + for px in bgra.chunks_exact(4) { + rgba.extend_from_slice(&[px[2], px[1], px[0], 255]); + } + unsafe { + SelectObject(hdc_mem, old); + DeleteObject(hbm); + DeleteDC(hdc_mem); + ReleaseDC(hwnd, hdc_screen); + } + if ok == 0 { + bail!("PrintWindow failed"); + } + image::save_buffer(path, &rgba, w as u32, h as u32, image::ColorType::Rgba8)?; + Ok(()) + } +} + +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +mod imp { + use super::Press; + use anyhow::{Result, bail}; + use gpui::Window; + use std::path::Path; + + pub fn draw_soon(_window: &Window) {} + pub fn post_mouse(_window: &Window, _press: Press, _x: f64, _y: f64) {} + pub fn window_id(_window: &Window) -> Option { + None + } + pub fn capture(_window_id: u32, _path: &Path) -> Result<()> { + bail!("window capture is not implemented on this platform") } } -fn sel(name: &CStr) -> *const c_void { - unsafe { sel_registerName(name.as_ptr()) } +pub fn draw_soon(window: &Window) { + imp::draw_soon(window); +} + +pub fn post_mouse(window: &Window, press: Press, x: f64, y: f64) { + imp::post_mouse(window, press, x, y); } -/// The window server's id for this window. pub fn window_id(window: &Window) -> Option { - let view = ns_view(window)?; - // -[NSView window] then -[NSWindow windowNumber]. - unsafe { - let get_window: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let get_number: unsafe extern "C" fn(*mut c_void, *const c_void) -> isize = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let ns_window = get_window(view, sel(c"window")); - if ns_window.is_null() { - return None; - } - u32::try_from(get_number(ns_window, sel(c"windowNumber"))).ok() - } + imp::window_id(window) } pub fn capture(window_id: u32, path: &Path) -> Result<()> { - // A null rect means "the window's own bounds". - let null = CGRect::new(&CGPoint::new(f64::INFINITY, f64::INFINITY), &CGSize::new(0.0, 0.0)); - let image = create_image(null, kCGWindowListOptionIncludingWindow, window_id, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageBestResolution).context("the window server returned no image")?; - let (w, h, stride) = (image.width(), image.height(), image.bytes_per_row()); - if image.bits_per_pixel() != 32 || w == 0 || h == 0 { - bail!("unexpected image format: {} bits, {w}x{h}", image.bits_per_pixel()); - } - let data = image.data(); - let bytes = data.bytes(); - let mut rgba = Vec::with_capacity(w * h * 4); - for row in 0..h { - for px in bytes[row * stride..row * stride + w * 4].as_chunks::<4>().0 { - // The window server hands back BGRA. - rgba.extend_from_slice(&[px[2], px[1], px[0], 255]); - } - } - image::save_buffer(path, &rgba, w as u32, h as u32, image::ColorType::Rgba8)?; - Ok(()) + imp::capture(window_id, path) } diff --git a/crates/mantis-app/src/store.rs b/crates/mantis-app/src/store.rs index ee89beb..0096e9c 100644 --- a/crates/mantis-app/src/store.rs +++ b/crates/mantis-app/src/store.rs @@ -25,7 +25,7 @@ pub struct Store { /// Where the app's own store keeps its file. fn database() -> PathBuf { - std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join("Library/Application Support/Mantis/mantis.db") + mantis_core::paths::app_data_dir().join("mantis.db") } impl Store { diff --git a/crates/mantis-app/src/viewport.rs b/crates/mantis-app/src/viewport.rs index c12a67a..7a9b91e 100644 --- a/crates/mantis-app/src/viewport.rs +++ b/crates/mantis-app/src/viewport.rs @@ -13,6 +13,7 @@ use mantis_agent::Snapshot; use mantis_core::Board; use mantis_core::geom::to_mm; use mantis_fab::models::ModelStore; +#[cfg(target_os = "macos")] use mantis_render::gpu::GpuRenderer; use mantis_render::replay::Replay; use mantis_render::{Camera, CaseView, Frame, Pick, RenderOptions, Scene, SceneOptions, ViewMode, build_object, build_scene, build_wires, build_wires_except, render, wire_tube}; @@ -104,8 +105,12 @@ impl Wanted { /// The render thread: draws each frame asked for and sends it back. fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc, metal: Arc, done: UnboundedSender) { + #[cfg(target_os = "macos")] let mut gpu = GpuRenderer::new(); + #[cfg(target_os = "macos")] metal.store(gpu.is_some(), Ordering::SeqCst); + #[cfg(not(target_os = "macos"))] + metal.store(false, Ordering::SeqCst); // The scene is rebuilt and uploaded only when the board or the view of it changes; loose // wires are kept apart from it so dragging one redoes only those. let mut scene: Option<(u64, SceneOptions, usize, Scene)> = None; @@ -134,6 +139,7 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc Content::Play { replay, report, run, seconds, table } => { let moment = report.runs[*run].at(*seconds); let now = replay.frame(report, *run, &moment, *table); + #[cfg(target_os = "macos")] if let Some(gpu) = gpu.as_mut() { gpu.set_scene(&now); gpu.set_overlay(&Scene::default()); @@ -145,6 +151,7 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc content => { if scene.as_ref().is_none_or(|(v, o, n, _)| *v != version || *o != job.scene || *n != store.len()) { let built = build_scene(&job.board, &job.scene, &store); + #[cfg(target_os = "macos")] if let Some(gpu) = gpu.as_mut() { gpu.set_scene(&built); } @@ -156,6 +163,7 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc let mut overlay = Scene::default(); overlay.tris.extend(others.tris.iter().copied()); wire_tube(&mut overlay, points, *radius, *color, *wire); + #[cfg(target_os = "macos")] if let Some(gpu) = gpu.as_mut() { gpu.set_overlay(&overlay); } @@ -166,6 +174,7 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc if dragging != Pick::None { loose.tris.extend(build_object(&job.board, &job.scene, &store, dragging).tris); } + #[cfg(target_os = "macos")] if let Some(gpu) = gpu.as_mut() { gpu.set_overlay(&loose); } @@ -174,6 +183,7 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc } } drop(store); + #[cfg(target_os = "macos")] let mut frame = match gpu.as_mut() { Some(gpu) => gpu.render(&camera, w, h, &job.render), None => { @@ -185,6 +195,14 @@ fn draw_frames(wanted: Arc, models: Arc>, fetched: Arc render(&all, &camera, w, h, &job.render) } }; + #[cfg(not(target_os = "macos"))] + let mut frame = { + let (built, loose) = (&scene.as_ref().unwrap().3, &wires.as_ref().unwrap().3); + let mut all = Scene::default(); + all.tris.extend(built.tris.iter().chain(&loose.tris).copied()); + all.decals.extend(built.decals.iter().cloned()); + render(&all, &camera, w, h, &job.render) + }; // GPUI wants BGRA, which is what the GPU path already produces. Only the ids are // needed afterwards, so the pixels are handed over, not copied. let mut pixels = std::mem::take(&mut frame.rgba); diff --git a/crates/mantis-app/src/workspace.rs b/crates/mantis-app/src/workspace.rs index 0868261..f067577 100644 --- a/crates/mantis-app/src/workspace.rs +++ b/crates/mantis-app/src/workspace.rs @@ -1538,10 +1538,7 @@ impl Workspace { Some(id) => crate::snapshot::capture(id, &path), None => Err(anyhow::anyhow!("no window id")), }; - let mut used: libc::rusage = unsafe { std::mem::zeroed() }; - // SAFETY: the pointer is to a live rusage, which getrusage fills in. - unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut used) }; - let cpu = (used.ru_utime.tv_sec + used.ru_stime.tv_sec) as f64 * 1000. + (used.ru_utime.tv_usec + used.ru_stime.tv_usec) as f64 / 1000.; + let cpu = process_cpu_ms(); let (worst, long) = stalls.get(); println!( "interface: longest stall {worst:.0} ms, {long} over 50 ms, {} frames built, slowest {:.1} ms, {cpu:.0} ms of processor time", @@ -1558,7 +1555,37 @@ impl Workspace { }) .detach(); } +} +fn process_cpu_ms() -> f64 { + #[cfg(unix)] + { + let mut used: libc::rusage = unsafe { std::mem::zeroed() }; + unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut used) }; + (used.ru_utime.tv_sec + used.ru_stime.tv_sec) as f64 * 1000. + (used.ru_utime.tv_usec + used.ru_stime.tv_usec) as f64 / 1000. + } + #[cfg(windows)] + { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let mut creation = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let mut exit = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let mut kernel = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let mut user = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let ok = unsafe { GetProcessTimes(GetCurrentProcess(), &mut creation, &mut exit, &mut kernel, &mut user) }; + if ok == 0 { + return 0.0; + } + let to_ms = |ft: FILETIME| (((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64)) as f64 / 10_000.0; + to_ms(kernel) + to_ms(user) + } + #[cfg(not(any(unix, windows)))] + { + 0.0 + } +} + +impl Workspace { /// Test hook: `MANTIS_DO` presses things as a person would, once the first frame is up. /// Steps are separated by `;`: `click@x,y` and `rclick@x,y` in window points from the top /// left, `rclick@REF` on a component where it is drawn, `item@n` for the nth row of the menu diff --git a/crates/mantis-app/src/workspace/form.rs b/crates/mantis-app/src/workspace/form.rs index d235b91..17a1445 100644 --- a/crates/mantis-app/src/workspace/form.rs +++ b/crates/mantis-app/src/workspace/form.rs @@ -234,7 +234,8 @@ impl Workspace { for (i, path) in self.form.files.iter().enumerate() { let folder = path.is_dir(); let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let place = path.parent().map(|p| p.display().to_string().replace(&std::env::var("HOME").unwrap_or_default(), "~")).unwrap_or_default(); + let home = mantis_core::paths::user_home().map(|p| p.display().to_string()).unwrap_or_default(); + let place = path.parent().map(|p| if home.is_empty() { p.display().to_string() } else { p.display().to_string().replace(&home, "~") }).unwrap_or_default(); list = list.child( div() .flex() diff --git a/crates/mantis-cli/src/main.rs b/crates/mantis-cli/src/main.rs index fd0fd22..c67a93c 100644 --- a/crates/mantis-cli/src/main.rs +++ b/crates/mantis-cli/src/main.rs @@ -207,6 +207,7 @@ fn main() -> Result<()> { let moment = r.runs[run].at(value("--at").unwrap_or(60.0)); let scene = replay.frame(&r, run, &moment, [38, 40, 46]); let cam = replay.camera(&r, run, Camera::fit(to_mm(b.outline.w) as f32, to_mm(b.outline.h) as f32, w as f32 / h as f32, false), w as f32 / h as f32); + #[cfg(target_os = "macos")] let frame = match mantis_render::gpu::GpuRenderer::new() { Some(mut gpu) => { gpu.set_scene(&scene); @@ -214,6 +215,8 @@ fn main() -> Result<()> { } None => render(&scene, &cam, w, h, &RenderOptions::default()), }; + #[cfg(not(target_os = "macos"))] + let frame = render(&scene, &cam, w, h, &RenderOptions::default()); frame.save_png(Path::new(&args[i + 1]))?; println!("drew {} at frame {} of {}", mantis_sim::WAYS[run].0, moment.frame, r.runs[run].frames.len() - 1); } @@ -276,6 +279,7 @@ fn main() -> Result<()> { } } let cpu = args.iter().any(|a| a == "--cpu"); + #[cfg(target_os = "macos")] let frame = match (cpu, mantis_render::gpu::GpuRenderer::new()) { (false, Some(mut gpu)) => { let upload = std::time::Instant::now(); @@ -294,6 +298,14 @@ fn main() -> Result<()> { frame } }; + #[cfg(not(target_os = "macos"))] + let frame = { + let _ = cpu; + let start = std::time::Instant::now(); + let frame = render(&scene, &cam, w, h, &RenderOptions::default()); + println!("{} triangles, CPU: {:.1} ms", scene.tris.len(), start.elapsed().as_secs_f64() * 1000.0); + frame + }; frame.save_png(Path::new(out))?; } "chat" => { diff --git a/crates/mantis-core/src/lib.rs b/crates/mantis-core/src/lib.rs index 203bfb7..a25740d 100644 --- a/crates/mantis-core/src/lib.rs +++ b/crates/mantis-core/src/lib.rs @@ -13,6 +13,7 @@ pub mod geom; pub mod mech; pub mod model3d; pub mod parts; +pub mod paths; pub mod place; pub mod route; pub mod sexpr; diff --git a/crates/mantis-core/src/paths.rs b/crates/mantis-core/src/paths.rs new file mode 100644 index 0000000..f3e83a5 --- /dev/null +++ b/crates/mantis-core/src/paths.rs @@ -0,0 +1,88 @@ +//! Cross-platform user directories for Mantis. + +use std::path::PathBuf; + +/// The user's home directory (`HOME` on Unix, `USERPROFILE` or `HOME` on Windows). +pub fn user_home() -> Option { + #[cfg(windows)] + { + std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + } + #[cfg(not(windows))] + { + std::env::var_os("HOME").map(PathBuf::from) + } +} + +/// Application data directory (`~/Library/Application Support/Mantis` on macOS, +/// `%LOCALAPPDATA%\Mantis` on Windows, `~/.local/share/Mantis` on Linux). +pub fn app_data_dir() -> PathBuf { + #[cfg(target_os = "macos")] + { + user_home() + .unwrap_or_default() + .join("Library/Application Support/Mantis") + } + #[cfg(target_os = "windows")] + { + std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .or_else(|| user_home().map(|h| h.join("AppData/Local"))) + .unwrap_or_else(std::env::temp_dir) + .join("Mantis") + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + std::env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .or_else(|| user_home().map(|h| h.join(".local/share"))) + .unwrap_or_else(std::env::temp_dir) + .join("Mantis") + } +} + +/// Cache directory (`~/Library/Caches/Mantis` on macOS, `%LOCALAPPDATA%\Mantis\Cache` on Windows). +pub fn cache_dir() -> PathBuf { + #[cfg(target_os = "macos")] + { + user_home() + .unwrap_or_else(std::env::temp_dir) + .join("Library/Caches/Mantis") + } + #[cfg(target_os = "windows")] + { + app_data_dir().join("Cache") + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .or_else(|| user_home().map(|h| h.join(".cache"))) + .unwrap_or_else(std::env::temp_dir) + .join("Mantis") + } +} + +/// Configuration directory (`~/.config/mantis` on Unix, `%APPDATA%\mantis` on Windows). +pub fn config_dir() -> Option { + #[cfg(windows)] + { + std::env::var_os("APPDATA") + .map(PathBuf::from) + .or_else(|| user_home().map(|h| h.join("AppData/Roaming"))) + .map(|p| p.join("mantis")) + } + #[cfg(not(windows))] + { + user_home().map(|h| h.join(".config/mantis")) + } +} + +/// Default folder for user projects and exports (`~/Mantis`). +pub fn projects_home() -> PathBuf { + user_home() + .unwrap_or_else(std::env::temp_dir) + .join("Mantis") +} diff --git a/crates/mantis-fab/src/models.rs b/crates/mantis-fab/src/models.rs index daf1060..2540e5d 100644 --- a/crates/mantis-fab/src/models.rs +++ b/crates/mantis-fab/src/models.rs @@ -9,8 +9,7 @@ use std::sync::Arc; use std::time::Duration; pub fn cache_dir(kind: &str) -> PathBuf { - let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); - home.join("Library/Caches/Mantis").join(kind) + mantis_core::paths::cache_dir().join(kind) } fn safe(id: &str) -> Result<&str> { diff --git a/crates/mantis-render/src/shots.rs b/crates/mantis-render/src/shots.rs index e82649a..3dbdf00 100644 --- a/crates/mantis-render/src/shots.rs +++ b/crates/mantis-render/src/shots.rs @@ -59,11 +59,15 @@ pub fn shots(board: &Board, models: &ModelStore, views: &[String], opts: &ShotOp let (centre, radius) = opts.focus.unwrap_or_else(|| sphere_of(&scene)); let (w, h) = opts.size; let aspect = w as f32 / h as f32; - let mut gpu = crate::gpu::GpuRenderer::new(); - if let Some(g) = gpu.as_mut() { - g.set_scene(&scene); - g.set_overlay(&Scene::default()); - } + #[cfg(target_os = "macos")] + let mut gpu = { + let mut gpu = crate::gpu::GpuRenderer::new(); + if let Some(g) = gpu.as_mut() { + g.set_scene(&scene); + g.set_overlay(&Scene::default()); + } + gpu + }; // A mid-grey backdrop, so black parts and white parts both stand out from it. let ropts = RenderOptions { background: [98, 102, 110], ..Default::default() }; let mut out = Vec::new(); @@ -71,10 +75,13 @@ pub fn shots(board: &Board, models: &ModelStore, views: &[String], opts: &ShotOp let Some(&(_, yaw, pitch, ortho)) = VIEWS.iter().find(|v| v.0 == name) else { continue }; let fit = (radius.max(1.0) / HALF_FOV_TAN).max(radius.max(1.0) / (HALF_FOV_TAN * aspect)); let cam = Camera { target: centre, yaw, pitch, dist: fit * if ortho { 1.02 } else { 0.98 }, ortho }; + #[cfg(target_os = "macos")] let frame = match gpu.as_mut() { Some(g) => g.render(&cam, w, h, &ropts), None => render(&scene, &cam, w, h, &ropts), }; + #[cfg(not(target_os = "macos"))] + let frame = render(&scene, &cam, w, h, &ropts); out.push(Shot { view: name.clone(), png: frame.png() }); } out diff --git a/scripts/bundle.ps1 b/scripts/bundle.ps1 new file mode 100644 index 0000000..5c2f8a1 --- /dev/null +++ b/scripts/bundle.ps1 @@ -0,0 +1,35 @@ +# Build a distributable Windows package for Mantis in target\Mantis-windows-x64. +# Usage: .\scripts\bundle.ps1 [-OutDir "target"] +param( + [string]$OutDir = "target" +) + +$ErrorActionPreference = "Stop" +$RepoRoot = Split-Path -Parent $PSScriptRoot +Set-Location $RepoRoot + +$env:PATH = "$env:USERPROFILE\.cargo\bin;C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin;" + $env:PATH + +cargo build --release -p mantis-app -p mantis-cli -p mantis-store + +$Stage = Join-Path $OutDir "Mantis-windows-x64" +if (Test-Path $Stage) { + Remove-Item -Recurse -Force $Stage +} +New-Item -ItemType Directory -Force -Path $Stage | Out-Null + +Copy-Item "target\release\mantis.exe" $Stage +Copy-Item "target\release\mantis-cli.exe" $Stage +Copy-Item "target\release\mantis-server.exe" $Stage +if (Test-Path "README.md") { + Copy-Item "README.md" $Stage +} + +$ZipPath = Join-Path $OutDir "Mantis-windows-x64.zip" +if (Test-Path $ZipPath) { + Remove-Item -Force $ZipPath +} +Compress-Archive -Path "$Stage\*" -DestinationPath $ZipPath + +Write-Host "Bundled folder: $Stage" +Write-Host "Bundled archive: $ZipPath" diff --git a/scripts/shots.ps1 b/scripts/shots.ps1 new file mode 100644 index 0000000..1dc1a95 --- /dev/null +++ b/scripts/shots.ps1 @@ -0,0 +1,42 @@ +# Capture Mantis UI screenshots on Windows outside the repository. +# Usage: .\scripts\shots.ps1 [-State "theme=dark,tab=parts,chat=sample"] [-Size "1440x900"] [-Do ""] [-OutDir "$env:TEMP\mantis-shots"] +param( + [string]$State = "theme=dark,tab=parts,chat=sample", + [string]$Size = "1440x900", + [string]$Do = "", + [string]$OutDir = (Join-Path $env:TEMP "mantis-shots"), + [string]$Name = "shot.png" +) + +$ErrorActionPreference = "Stop" +$RepoRoot = Split-Path -Parent $PSScriptRoot +Set-Location $RepoRoot + +New-Item -ItemType Directory -Force -Path $OutDir | Out-Null +$OutFile = Join-Path $OutDir $Name + +# Ensure cargo and CMake are on PATH +$env:PATH = "$env:USERPROFILE\.cargo\bin;C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin;" + $env:PATH + +cargo build --release -p mantis-app +$Exe = Join-Path $RepoRoot "target\release\mantis.exe" +if (-not (Test-Path $Exe)) { + throw "mantis.exe not found at $Exe" +} + +$env:MANTIS_SNAPSHOT = $OutFile +$env:MANTIS_STATE = $State +$env:MANTIS_SIZE = $Size +if ($Do) { + $env:MANTIS_DO = $Do +} else { + Remove-Item Env:MANTIS_DO -ErrorAction SilentlyContinue +} + +& $Exe +if (-not (Test-Path $OutFile)) { + throw "Snapshot was not created at $OutFile" +} + +Write-Host "Captured: $OutFile" +Write-Host "Attach to PR with: gh pr create --attach '$OutFile#Mantis Windows ($State)'" diff --git a/vendor/mantis-ui/Cargo.toml b/vendor/mantis-ui/Cargo.toml new file mode 100644 index 0000000..726853b --- /dev/null +++ b/vendor/mantis-ui/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "mantis-ui" +version = "0.1.0" +edition = "2024" +license = "UNLICENSED" +publish = false + +[dependencies] +anyhow = "1" +gpui = "0.2.2" +smallvec = "1" diff --git a/vendor/mantis-ui/src/anim.rs b/vendor/mantis-ui/src/anim.rs new file mode 100644 index 0000000..816a5d0 --- /dev/null +++ b/vendor/mantis-ui/src/anim.rs @@ -0,0 +1,43 @@ +use gpui::{ElementId, Window}; + +#[derive(Clone, Copy, Debug)] +pub struct Ease(pub f32, pub f32, pub f32, pub f32); + +impl Ease { + pub const OUT: Self = Self(0.0, 0.0, 0.2, 1.0); + pub const EASE_OUT: Self = Self(0.0, 0.0, 0.2, 1.0); + pub const STANDARD: Self = Self(0.2, 0.0, 0.0, 1.0); + pub const IN_OUT: Self = Self(0.4, 0.0, 0.2, 1.0); + + pub fn at(self, t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + // Smoothstep approximation for CSS cubic-bezier easing. + t * t * (3.0 - 2.0 * t) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Transition { + pub duration_ms: u64, + pub ease: Ease, +} + +impl Transition { + pub const DEFAULT: Self = Self { duration_ms: 200, ease: Ease::STANDARD }; + + pub const fn ms(duration_ms: u64, ease: Ease) -> Self { + Self { duration_ms, ease } + } +} + +pub fn key(parent: &ElementId, suffix: &str) -> ElementId { + ElementId::NamedChild(Box::new(parent.clone()), suffix.to_string().into()) +} + +pub fn tween(_id: impl Into, target: f32, _transition: Transition, _window: &mut Window) -> f32 { + target +} + +pub fn tween_from(_id: impl Into, _from: f32, to: f32, _transition: Transition, _window: &mut Window) -> f32 { + to +} diff --git a/vendor/mantis-ui/src/assets.rs b/vendor/mantis-ui/src/assets.rs new file mode 100644 index 0000000..82ec54f --- /dev/null +++ b/vendor/mantis-ui/src/assets.rs @@ -0,0 +1,14 @@ +use gpui::{AssetSource, SharedString}; +use std::borrow::Cow; + +pub struct Assets; + +impl AssetSource for Assets { + fn load(&self, _path: &str) -> anyhow::Result>> { + Ok(None) + } + + fn list(&self, _path: &str) -> anyhow::Result> { + Ok(Vec::new()) + } +} diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs new file mode 100644 index 0000000..e0d9087 --- /dev/null +++ b/vendor/mantis-ui/src/components.rs @@ -0,0 +1,2026 @@ +use gpui::{ + AnyElement, AnyView, App, AppContext, ClickEvent, ElementId, FontWeight, Hsla, + InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, + StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, svg, +}; +use std::rc::Rc; + +// --------------------------------------------------------------------------- +// Tooltip +// --------------------------------------------------------------------------- + +pub fn tooltip(text: impl Into) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static { + let text = text.into(); + move |_window, cx| { + let text = text.clone(); + cx.new(move |_cx| TooltipView { text: text.clone() }).into() + } +} + +struct TooltipView { + text: SharedString, +} + +impl gpui::Render for TooltipView { + fn render(&mut self, _window: &mut Window, cx: &mut gpui::Context) -> impl IntoElement { + let t = crate::Theme::of(cx); + div() + .px(px(8.)) + .py(px(4.)) + .rounded(px(6.)) + .bg(t.popover) + .border_1() + .border_color(t.border) + .text_size(px(11.5)) + .text_color(t.popover_foreground) + .child(self.text.clone()) + } +} + +// --------------------------------------------------------------------------- +// Icon & Wordmark & ChatText +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct Icon { + name: SharedString, + size: Pixels, + color: Option, +} + +impl Icon { + pub fn new(name: impl Into) -> Self { + Self { name: name.into(), size: px(16.), color: None } + } + + pub fn size(mut self, size: Pixels) -> Self { + self.size = size; + self + } + + pub fn color(mut self, color: Hsla) -> Self { + self.color = Some(color); + self + } +} + +impl RenderOnce for Icon { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let color = self.color.unwrap_or_else(|| crate::Theme::of(cx).foreground); + svg() + .path(format!("icons/{}.svg", self.name)) + .size(self.size) + .text_color(color) + } +} + +#[derive(IntoElement)] +pub struct Wordmark { + size: Pixels, +} + +impl Wordmark { + pub fn new(size: Pixels) -> Self { + Self { size } + } +} + +impl Default for Wordmark { + fn default() -> Self { + Self::new(px(15.)) + } +} + +impl RenderOnce for Wordmark { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + div() + .text_size(self.size) + .font_weight(FontWeight::SEMIBOLD) + .text_color(t.foreground) + .child("Mantis") + } +} + +#[derive(IntoElement)] +pub struct ChatText { + text: SharedString, + truncate: bool, +} + +impl ChatText { + pub fn new(text: impl Into) -> Self { + Self { text: text.into(), truncate: false } + } + + pub fn truncate(mut self) -> Self { + self.truncate = true; + self + } +} + +impl RenderOnce for ChatText { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut d = div().w_full().min_w_0().child(self.text); + if self.truncate { + d = d.truncate(); + } + d + } +} + +// --------------------------------------------------------------------------- +// Button, ButtonGroup, GroupButton, Toggle +// --------------------------------------------------------------------------- + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum ButtonVariant { + #[default] + Default, + Primary, + Secondary, + Outline, + Ghost, + Destructive, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum ButtonSize { + Xs, + Sm, + #[default] + Md, + Lg, + Icon, + IconXs, + IconSm, +} + +type ClickHandler = Rc; + +#[derive(IntoElement)] +pub struct Button { + id: ElementId, + label: SharedString, + variant: ButtonVariant, + size: ButtonSize, + icon_start: Option, + icon_end: Option, + disabled: bool, + tooltip_text: Option, + on_click: Option, +} + +impl Button { + pub fn new(id: impl Into, label: impl Into) -> Self { + Self { + id: id.into(), + label: label.into(), + variant: ButtonVariant::Default, + size: ButtonSize::Md, + icon_start: None, + icon_end: None, + disabled: false, + tooltip_text: None, + on_click: None, + } + } + + pub fn icon(id: impl Into, icon: impl Into) -> Self { + Self { + id: id.into(), + label: SharedString::default(), + variant: ButtonVariant::Ghost, + size: ButtonSize::Icon, + icon_start: Some(icon.into()), + icon_end: None, + disabled: false, + tooltip_text: None, + on_click: None, + } + } + + pub fn variant(mut self, variant: ButtonVariant) -> Self { + self.variant = variant; + self + } + + pub fn size(mut self, size: ButtonSize) -> Self { + self.size = size; + self + } + + pub fn icon_start(mut self, icon: impl Into) -> Self { + self.icon_start = Some(icon.into()); + self + } + + pub fn icon_end(mut self, icon: impl Into) -> Self { + self.icon_end = Some(icon.into()); + self + } + + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + pub fn tooltip(mut self, text: impl Into) -> Self { + self.tooltip_text = Some(text.into()); + self + } + + pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { + self.on_click = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Button { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let (bg, fg, border) = match self.variant { + ButtonVariant::Default | ButtonVariant::Primary => (t.primary, t.primary_foreground, t.primary), + ButtonVariant::Secondary => (t.secondary, t.secondary_foreground, t.secondary), + ButtonVariant::Outline => (crate::alpha(t.background, 0.), t.foreground, t.border), + ButtonVariant::Ghost => (crate::alpha(t.background, 0.), t.foreground, crate::alpha(t.border, 0.)), + ButtonVariant::Destructive => (t.destructive, t.destructive_foreground, t.destructive), + }; + let (h, px_pad, text_sz) = match self.size { + ButtonSize::Xs => (px(22.), px(7.), px(11.)), + ButtonSize::Sm => (px(26.), px(10.), px(12.)), + ButtonSize::Md => (px(32.), px(12.), px(13.)), + ButtonSize::Lg => (px(38.), px(16.), px(14.)), + ButtonSize::Icon => (px(28.), px(6.), px(13.)), + ButtonSize::IconXs => (px(20.), px(4.), px(11.)), + ButtonSize::IconSm => (px(24.), px(5.), px(12.)), + }; + let mut el = div() + .id(self.id) + .flex() + .items_center() + .justify_center() + .gap(px(6.)) + .h(h) + .px(px_pad) + .rounded(px(7.)) + .bg(bg) + .border_1() + .border_color(border) + .text_size(text_sz) + .font_weight(FontWeight::MEDIUM) + .text_color(fg) + .when(!self.disabled, |d| d.cursor_pointer().hover(|s| s.opacity(0.88))) + .when(self.disabled, |d| d.opacity(0.45)); + + if let Some(icon) = self.icon_start { + el = el.child(Icon::new(icon).size(px(14.)).color(fg)); + } + if !self.label.is_empty() { + el = el.child(self.label); + } + if let Some(icon) = self.icon_end { + el = el.child(Icon::new(icon).size(px(14.)).color(fg)); + } + if let Some(tip) = self.tooltip_text { + el = el.tooltip(tooltip(tip)); + } + if let Some(cb) = self.on_click + && !self.disabled + { + el = el.on_click(move |ev, window, cx| cb(ev, window, cx)); + } + el + } +} + +#[derive(IntoElement)] +pub struct GroupButton { + id: ElementId, + label: SharedString, + icon: Option, + size: ButtonSize, + variant: ButtonVariant, + active: bool, + on_click: Option, +} + +impl GroupButton { + pub fn new(id: impl Into, label: impl Into) -> Self { + Self { id: id.into(), label: label.into(), icon: None, size: ButtonSize::Sm, variant: ButtonVariant::Ghost, active: false, on_click: None } + } + + pub fn icon(id: impl Into, icon: impl Into) -> Self { + Self { id: id.into(), label: SharedString::default(), icon: Some(icon.into()), size: ButtonSize::IconSm, variant: ButtonVariant::Ghost, active: false, on_click: None } + } + + pub fn variant(mut self, variant: ButtonVariant) -> Self { + self.variant = variant; + self + } + + pub fn size(mut self, size: ButtonSize) -> Self { + self.size = size; + self + } + + pub fn active(mut self, active: bool) -> Self { + self.active = active; + self + } + + pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { + self.on_click = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for GroupButton { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let fg = if self.active { t.accent_foreground } else { t.muted_foreground }; + let mut el = div() + .id(self.id) + .flex() + .items_center() + .justify_center() + .gap(px(4.)) + .h(px(24.)) + .px(px(8.)) + .rounded(px(5.)) + .text_size(px(12.)) + .cursor_pointer() + .bg(if self.active { t.accent } else { crate::alpha(t.background, 0.) }) + .text_color(fg); + if let Some(icon) = self.icon { + el = el.child(Icon::new(icon).size(px(13.)).color(fg)); + } + if !self.label.is_empty() { + el = el.child(self.label); + } + if let Some(cb) = self.on_click { + el = el.on_click(move |ev, window, cx| cb(ev, window, cx)); + } + el + } +} + +#[derive(IntoElement)] +pub struct ButtonGroup { + children: Vec, +} + +impl ButtonGroup { + pub fn new() -> Self { + Self { children: Vec::new() } + } + + pub fn button(mut self, btn: GroupButton) -> Self { + self.children.push(btn.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for ButtonGroup { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for ButtonGroup { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + div() + .flex() + .items_center() + .gap(px(2.)) + .p(px(2.)) + .rounded(px(7.)) + .bg(t.muted) + .border_1() + .border_color(t.border) + .children(self.children) + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum ToggleSize { + Sm, + #[default] + Md, +} + +#[derive(IntoElement)] +pub struct Toggle { + id: ElementId, + pressed: bool, + size: ToggleSize, + icon: Option, + label: Option, + on_change: Option>, +} + +impl Toggle { + pub fn new(id: impl Into, pressed: bool) -> Self { + Self { id: id.into(), pressed, size: ToggleSize::Md, icon: None, label: None, on_change: None } + } + + pub fn icon_only(id: impl Into, icon: impl AsRef, pressed: bool) -> Self { + Self { id: id.into(), pressed, size: ToggleSize::Md, icon: Some(icon.as_ref().to_string().into()), label: None, on_change: None } + } + + pub fn size(mut self, size: ToggleSize) -> Self { + self.size = size; + self + } + + pub fn icon(mut self, icon: impl Into) -> Self { + self.icon = Some(icon.into()); + self + } + + pub fn label(mut self, label: impl Into) -> Self { + self.label = Some(label.into()); + self + } + + pub fn on_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self { + self.on_change = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Toggle { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let h = match self.size { + ToggleSize::Sm => px(26.), + ToggleSize::Md => px(32.), + }; + let next = !self.pressed; + let fg = if self.pressed { t.primary } else { t.foreground }; + let mut el = div() + .id(self.id) + .flex() + .items_center() + .justify_center() + .gap(px(6.)) + .h(h) + .px(px(8.)) + .rounded(px(6.)) + .cursor_pointer() + .border_1() + .border_color(if self.pressed { t.primary } else { t.border }) + .bg(if self.pressed { crate::alpha(t.primary, 0.14) } else { t.background }) + .text_color(fg); + if let Some(icon) = self.icon { + el = el.child(Icon::new(icon).size(px(14.)).color(fg)); + } + if let Some(label) = self.label { + el = el.text_size(px(12.)).child(label); + } + if let Some(cb) = self.on_change { + el = el.on_click(move |_, window, cx| cb(next, window, cx)); + } + el + } +} + +// --------------------------------------------------------------------------- +// Badge, Card, Empty, Alert +// --------------------------------------------------------------------------- + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum BadgeVariant { + #[default] + Default, + Secondary, + Destructive, + Outline, +} + +#[derive(IntoElement)] +pub struct Badge { + label: SharedString, + variant: BadgeVariant, + icon: Option, + spinner: Option, +} + +impl Badge { + pub fn new(label: impl Into) -> Self { + Self { label: label.into(), variant: BadgeVariant::Default, icon: None, spinner: None } + } + + pub fn variant(mut self, variant: BadgeVariant) -> Self { + self.variant = variant; + self + } + + pub fn icon(mut self, icon: impl Into) -> Self { + self.icon = Some(icon.into()); + self + } + + pub fn spinner(mut self, id: impl Into) -> Self { + self.spinner = Some(id.into()); + self + } +} + +impl RenderOnce for Badge { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let (bg, fg, border) = match self.variant { + BadgeVariant::Default => (t.primary, t.primary_foreground, t.primary), + BadgeVariant::Secondary => (t.secondary, t.secondary_foreground, t.secondary), + BadgeVariant::Destructive => (t.destructive, t.destructive_foreground, t.destructive), + BadgeVariant::Outline => (crate::alpha(t.background, 0.), t.foreground, t.border), + }; + let mut el = div() + .flex() + .items_center() + .gap(px(4.)) + .h(px(20.)) + .px(px(7.)) + .rounded(px(999.)) + .bg(bg) + .border_1() + .border_color(border) + .text_size(px(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(fg); + if let Some(icon) = self.icon { + el = el.child(Icon::new(icon).size(px(11.)).color(fg)); + } else if self.spinner.is_some() { + el = el.child(div().size(px(6.)).rounded(px(3.)).bg(fg)); + } + el.child(self.label) + } +} + +#[derive(IntoElement)] +pub struct CardHeader { + title: SharedString, + description: Option, + small: bool, +} + +impl CardHeader { + pub fn new(title: impl Into) -> Self { + Self { title: title.into(), description: None, small: false } + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn small(mut self) -> Self { + self.small = true; + self + } +} + +impl RenderOnce for CardHeader { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut el = div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .text_size(if self.small { px(12.5) } else { px(14.) }) + .font_weight(FontWeight::SEMIBOLD) + .text_color(t.card_foreground) + .child(self.title), + ); + if let Some(desc) = self.description { + el = el.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); + } + el + } +} + +#[derive(IntoElement)] +pub struct Card { + header: Option, + children: Vec, + small: bool, +} + +impl Card { + pub fn new() -> Self { + Self { header: None, children: Vec::new(), small: false } + } + + pub fn small(mut self) -> Self { + self.small = true; + self + } + + pub fn header(mut self, header: CardHeader) -> Self { + self.header = Some(header); + self + } + + pub fn content(mut self, content: impl IntoElement) -> Self { + self.children.push(content.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for Card { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for Card { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let pad = if self.small { px(10.) } else { px(14.) }; + let mut el = div() + .flex() + .flex_col() + .gap(px(8.)) + .p(pad) + .rounded(px(10.)) + .bg(t.card) + .border_1() + .border_color(t.border); + if let Some(h) = self.header { + el = el.child(h); + } + el.children(self.children) + } +} + +#[derive(IntoElement)] +pub struct Empty { + title: SharedString, + description: Option, + icon: Option, +} + +impl Empty { + pub fn new(title: impl Into) -> Self { + Self { title: title.into(), description: None, icon: None } + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn icon(mut self, icon: impl Into) -> Self { + self.icon = Some(icon.into()); + self + } +} + +impl RenderOnce for Empty { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut el = div() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(6.)) + .p(px(24.)) + .text_color(t.muted_foreground); + if let Some(icon) = self.icon { + el = el.child(Icon::new(icon).size(px(20.)).color(t.muted_foreground)); + } + el = el.child(div().text_size(px(13.)).text_color(t.foreground).child(self.title)); + if let Some(desc) = self.description { + el = el.child(div().text_size(px(12.)).text_color(t.muted_foreground).child(desc)); + } + el + } +} + +#[derive(IntoElement)] +pub struct Alert { + title: SharedString, + description: Option, + destructive: bool, +} + +impl Alert { + pub fn new(title: impl Into) -> Self { + Self { title: title.into(), description: None, destructive: false } + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn destructive(mut self) -> Self { + self.destructive = true; + self + } +} + +impl RenderOnce for Alert { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let border = if self.destructive { t.destructive } else { t.border }; + let fg = if self.destructive { t.destructive } else { t.foreground }; + let mut el = div() + .flex() + .flex_col() + .gap(px(2.)) + .p(px(10.)) + .rounded(px(8.)) + .border_1() + .border_color(border) + .bg(if self.destructive { crate::alpha(t.destructive, 0.08) } else { t.card }) + .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).text_color(fg).child(self.title)); + if let Some(desc) = self.description { + el = el.child(div().text_size(px(12.)).text_color(t.muted_foreground).child(desc)); + } + el + } +} + +// --------------------------------------------------------------------------- +// Dialog, AlertDialog, Field, FieldGroup +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct Field { + label: Option, + description: Option, + control: Option, +} + +impl Field { + pub fn new() -> Self { + Self { label: None, description: None, control: None } + } + + pub fn label(mut self, label: impl Into) -> Self { + self.label = Some(label.into()); + self + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn control(mut self, control: impl IntoElement) -> Self { + self.control = Some(control.into_any_element()); + self + } +} + +impl Default for Field { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for Field { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut el = div().flex().flex_col().gap(px(4.)); + if let Some(label) = self.label { + el = el.child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).text_color(t.foreground).child(label)); + } + if let Some(control) = self.control { + el = el.child(control); + } + if let Some(desc) = self.description { + el = el.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); + } + el + } +} + +#[derive(IntoElement)] +pub struct FieldGroup { + gap_px: Pixels, + children: Vec, +} + +impl FieldGroup { + pub fn new() -> Self { + Self { gap_px: px(12.), children: Vec::new() } + } + + pub fn gap(mut self, gap: f32) -> Self { + self.gap_px = px(gap); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for FieldGroup { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for FieldGroup { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().flex().flex_col().gap(self.gap_px).children(self.children) + } +} + +#[derive(IntoElement)] +pub struct Dialog { + id: ElementId, + open: bool, + width_px: Pixels, + title: Option, + description: Option, + body: Option, + footer: Vec, +} + +impl Dialog { + pub fn new(id: impl Into, open: bool) -> Self { + Self { id: id.into(), open, width_px: px(460.), title: None, description: None, body: None, footer: Vec::new() } + } + + pub fn width(mut self, w: Pixels) -> Self { + self.width_px = w; + self + } + + pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn body(mut self, body: impl IntoElement) -> Self { + self.body = Some(body.into_any_element()); + self + } + + pub fn child(mut self, body: impl IntoElement) -> Self { + self.body = Some(body.into_any_element()); + self + } + + pub fn footer(mut self, item: impl IntoElement) -> Self { + self.footer.push(item.into_any_element()); + self + } +} + +impl RenderOnce for Dialog { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + if !self.open { + return div().id(self.id).into_any_element(); + } + let t = crate::Theme::of(cx); + let mut card = div() + .flex() + .flex_col() + .gap(px(12.)) + .w(self.width_px) + .p(px(20.)) + .rounded(px(12.)) + .bg(t.card) + .border_1() + .border_color(t.border); + if let Some(title) = self.title { + card = card.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(t.card_foreground).child(title)); + } + if let Some(desc) = self.description { + card = card.child(div().text_size(px(12.5)).text_color(t.muted_foreground).child(desc)); + } + if let Some(body) = self.body { + card = card.child(body); + } + if !self.footer.is_empty() { + card = card.child(div().flex().justify_end().gap(px(8.)).children(self.footer)); + } + div() + .id(self.id) + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .bg(gpui::hsla(0., 0., 0., 0.55)) + .child(card) + .into_any_element() + } +} + +pub fn alert_dialog_action(id: impl Into, label: impl Into) -> Button { + Button::new(id, label).variant(ButtonVariant::Destructive) +} + +pub fn alert_dialog_cancel(id: impl Into, label: impl Into) -> Button { + Button::new(id, label).variant(ButtonVariant::Outline) +} + +#[derive(IntoElement)] +pub struct AlertDialog { + id: ElementId, + open: bool, + title: Option, + description: Option, + actions: Vec, +} + +impl AlertDialog { + pub fn new(id: impl Into, open: bool) -> Self { + Self { id: id.into(), open, title: None, description: None, actions: Vec::new() } + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn footer(mut self, item: impl IntoElement) -> Self { + self.actions.push(item.into_any_element()); + self + } + + pub fn action(mut self, item: impl IntoElement) -> Self { + self.actions.push(item.into_any_element()); + self + } + + pub fn cancel(mut self, item: impl IntoElement) -> Self { + self.actions.push(item.into_any_element()); + self + } +} + +impl RenderOnce for AlertDialog { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + if !self.open { + return div().id(self.id).into_any_element(); + } + let t = crate::Theme::of(cx); + let mut card = div() + .flex() + .flex_col() + .gap(px(12.)) + .w(px(400.)) + .p(px(20.)) + .rounded(px(12.)) + .bg(t.card) + .border_1() + .border_color(t.border); + if let Some(title) = self.title { + card = card.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(t.card_foreground).child(title)); + } + if let Some(desc) = self.description { + card = card.child(div().text_size(px(12.5)).text_color(t.muted_foreground).child(desc)); + } + if !self.actions.is_empty() { + card = card.child(div().flex().justify_end().gap(px(8.)).children(self.actions)); + } + div() + .id(self.id) + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .bg(gpui::hsla(0., 0., 0., 0.55)) + .child(card) + .into_any_element() + } +} + +// --------------------------------------------------------------------------- +// Slider, Switch, Tabs +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct Slider { + id: ElementId, + value: f32, + min: f32, + max: f32, + on_change: Option>, +} + +impl Slider { + pub fn new(id: impl Into, value: f32) -> Self { + Self { id: id.into(), value, min: 0.0, max: 1.0, on_change: None } + } + + pub fn min(mut self, min: f32) -> Self { + self.min = min; + self + } + + pub fn max(mut self, max: f32) -> Self { + self.max = max; + self + } + + pub fn step(self, _step: f32) -> Self { + self + } + + pub fn disabled(self, _disabled: bool) -> Self { + self + } + + pub fn on_change(mut self, f: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self { + self.on_change = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Slider { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let span = (self.max - self.min).max(0.0001); + let frac = ((self.value - self.min) / span).clamp(0.0, 1.0); + div() + .id(self.id) + .flex() + .items_center() + .w_full() + .h(px(18.)) + .child( + div() + .relative() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(t.muted) + .child(div().h_full().w(gpui::relative(frac)).rounded(px(2.)).bg(t.primary)), + ) + } +} + +#[derive(IntoElement)] +pub struct Switch { + id: ElementId, + checked: bool, + on_change: Option>, +} + +impl Switch { + pub fn new(id: impl Into, checked: bool) -> Self { + Self { id: id.into(), checked, on_change: None } + } + + pub fn on_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self { + self.on_change = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Switch { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let next = !self.checked; + let mut el = div() + .id(self.id) + .flex() + .items_center() + .w(px(34.)) + .h(px(18.)) + .p(px(2.)) + .rounded(px(9.)) + .cursor_pointer() + .bg(if self.checked { t.primary } else { t.muted }) + .justify_end() + .when(!self.checked, |d| d.justify_start()) + .child(div().size(px(14.)).rounded(px(7.)).bg(t.primary_foreground)); + if let Some(cb) = self.on_change { + el = el.on_click(move |_, window, cx| cb(next, window, cx)); + } + el + } +} + +#[derive(IntoElement)] +pub struct Tabs { + id: ElementId, + items: Vec, + selected: usize, + on_change: Option>, +} + +impl Tabs { + pub fn new(id: impl Into, items: impl IntoIterator>, selected: usize) -> Self { + Self { + id: id.into(), + items: items.into_iter().map(Into::into).collect(), + selected, + on_change: None, + } + } + + pub fn on_change(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self { + self.on_change = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Tabs { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let cb = self.on_change; + let mut row = div() + .id(self.id) + .flex() + .items_center() + .gap(px(2.)) + .p(px(2.)) + .rounded(px(7.)) + .bg(t.muted); + for (i, label) in self.items.into_iter().enumerate() { + let active = i == self.selected; + let cb = cb.clone(); + let mut tab = div() + .id(("tab", i)) + .px(px(10.)) + .py(px(4.)) + .rounded(px(5.)) + .text_size(px(12.)) + .cursor_pointer() + .bg(if active { t.background } else { crate::alpha(t.background, 0.) }) + .text_color(if active { t.foreground } else { t.muted_foreground }) + .child(label); + if let Some(cb) = cb { + tab = tab.on_click(move |_, window, cx| cb(i, window, cx)); + } + row = row.child(tab); + } + row + } +} + +// --------------------------------------------------------------------------- +// Table +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct Table { + id: ElementId, + children: Vec, +} + +impl Table { + pub fn new(id: impl Into) -> Self { + Self { id: id.into(), children: Vec::new() } + } + + pub fn header(mut self, header: TableHeader) -> Self { + self.children.push(header.into_any_element()); + self + } + + pub fn body(mut self, body: TableBody) -> Self { + self.children.push(body.into_any_element()); + self + } + + pub fn footer(mut self, footer: TableFooter) -> Self { + self.children.push(footer.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl RenderOnce for Table { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().id(self.id).flex().flex_col().w_full().children(self.children) + } +} + +#[derive(IntoElement)] +pub struct TableHeader { + children: Vec, +} + +impl TableHeader { + pub fn new() -> Self { + Self { children: Vec::new() } + } + + pub fn row(mut self, row: TableRow) -> Self { + self.children.push(row.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for TableHeader { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for TableHeader { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().flex().flex_col().w_full().children(self.children) + } +} + +#[derive(IntoElement)] +pub struct TableBody { + children: Vec, +} + +impl TableBody { + pub fn new() -> Self { + Self { children: Vec::new() } + } + + pub fn row(mut self, row: TableRow) -> Self { + self.children.push(row.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for TableBody { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for TableBody { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().flex().flex_col().w_full().children(self.children) + } +} + +#[derive(IntoElement)] +pub struct TableFooter { + children: Vec, +} + +impl TableFooter { + pub fn new() -> Self { + Self { children: Vec::new() } + } + + pub fn row(mut self, row: TableRow) -> Self { + self.children.push(row.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for TableFooter { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for TableFooter { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().flex().flex_col().w_full().children(self.children) + } +} + +#[derive(IntoElement)] +pub struct TableRow { + children: Vec, + on_click: Option, +} + +impl TableRow { + pub fn new() -> Self { + Self { children: Vec::new(), on_click: None } + } + + pub fn children(mut self, items: I) -> Self + where + I: IntoIterator, + I::Item: IntoElement, + { + self.children.extend(items.into_iter().map(IntoElement::into_any_element)); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } + + pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { + self.on_click = Some(Rc::new(f)); + self + } +} + +impl Default for TableRow { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for TableRow { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut d = div() + .flex() + .items_center() + .w_full() + .border_b_1() + .border_color(t.border) + .py(px(6.)) + .gap(px(8.)) + .children(self.children); + if let Some(cb) = self.on_click { + d = d.cursor_pointer().on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { + cb(&ClickEvent::default(), window, cx); + }); + } + d + } +} + +#[derive(IntoElement)] +pub struct TableHead { + content: AnyElement, + align_right: bool, +} + +impl TableHead { + pub fn new(content: impl IntoElement) -> Self { + Self { content: content.into_any_element(), align_right: false } + } + + pub fn right(mut self) -> Self { + self.align_right = true; + self + } +} + +impl RenderOnce for TableHead { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut d = div() + .flex() + .flex_1() + .min_w_0() + .text_size(px(11.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(t.muted_foreground) + .child(self.content); + if self.align_right { + d = d.justify_end(); + } + d + } +} + +#[derive(IntoElement)] +pub struct TableCell { + content: AnyElement, + align_right: bool, + span_cols: usize, +} + +impl TableCell { + pub fn new(content: impl IntoElement) -> Self { + Self { content: content.into_any_element(), align_right: false, span_cols: 1 } + } + + pub fn right(mut self) -> Self { + self.align_right = true; + self + } + + pub fn span(mut self, cols: usize) -> Self { + self.span_cols = cols.max(1); + self + } +} + +impl RenderOnce for TableCell { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut d = div().flex().flex_1().min_w_0().overflow_hidden().text_size(px(12.)).child(self.content); + if self.align_right { + d = d.justify_end(); + } + d + } +} + +// --------------------------------------------------------------------------- +// ScrollArea, Resizable, MessageScroller +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct ScrollArea { + id: ElementId, + height: Option, + horizontal_scroll: bool, + children: Vec, +} + +impl ScrollArea { + pub fn new(id: impl Into) -> Self { + Self { id: id.into(), height: None, horizontal_scroll: false, children: Vec::new() } + } + + pub fn h(mut self, h: Pixels) -> Self { + self.height = Some(h); + self + } + + pub fn horizontal(mut self) -> Self { + self.horizontal_scroll = true; + self + } + + pub fn size_full(self) -> Self { + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl RenderOnce for ScrollArea { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut d = div().id(self.id).flex().flex_col().w_full(); + if self.horizontal_scroll { + d = d.overflow_x_scroll(); + } else { + d = d.overflow_y_scroll(); + } + if let Some(h) = self.height { + d = d.h(h); + } else { + d = d.flex_1().min_h_0(); + } + d.children(self.children) + } +} + +#[derive(IntoElement)] +pub struct ResizablePanelGroup { + id: ElementId, + vertical_layout: bool, + full: bool, + children: Vec, +} + +impl ResizablePanelGroup { + pub fn new(id: impl Into) -> Self { + Self { id: id.into(), vertical_layout: false, full: false, children: Vec::new() } + } + + pub fn vertical(id: impl Into) -> Self { + Self { id: id.into(), vertical_layout: true, full: false, children: Vec::new() } + } + + pub fn size_full(mut self) -> Self { + self.full = true; + self + } + + pub fn panel(mut self, panel: ResizablePanel) -> Self { + self.children.push(panel.into_any_element()); + self + } + + pub fn handle(mut self, handle: ResizableHandle) -> Self { + self.children.push(handle.into_any_element()); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl RenderOnce for ResizablePanelGroup { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut d = div().id(self.id).flex(); + if self.vertical_layout { + d = d.flex_col(); + } + if self.full { + d = d.size_full(); + } + d.children(self.children) + } +} + +#[derive(IntoElement)] +pub struct ResizablePanel { + children: Vec, + default_pct: f32, +} + +impl ResizablePanel { + pub fn new() -> Self { + Self { children: Vec::new(), default_pct: 50.0 } + } + + pub fn default_size(mut self, pct: f32) -> Self { + self.default_pct = pct; + self + } + + pub fn min_size(self, _pct: f32) -> Self { + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl Default for ResizablePanel { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for ResizablePanel { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().flex().flex_col().flex_1().min_w_0().min_h_0().children(self.children) + } +} + +#[derive(IntoElement)] +pub struct ResizableHandle; + +impl ResizableHandle { + pub fn new() -> Self { + Self + } +} + +impl Default for ResizableHandle { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for ResizableHandle { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + div().h(px(1.)).w_full().bg(t.border) + } +} + +#[derive(Clone, Copy, Default)] +pub struct ScrollableState { + pub end: bool, +} + +#[derive(Clone, Default)] +pub struct MessageScrollerHandle { + scroll: gpui::ScrollHandle, +} + +impl MessageScrollerHandle { + pub fn new() -> Self { + Self { scroll: gpui::ScrollHandle::new() } + } + + pub fn scrollable(&self) -> ScrollableState { + ScrollableState { end: false } + } + + pub fn scroll_to_end(&self, _animated: bool) { + self.scroll.scroll_to_bottom(); + } +} + +#[derive(IntoElement)] +pub struct MessageScrollerItem { + content: AnyElement, + message_id: Option, +} + +impl MessageScrollerItem { + pub fn new(content: impl IntoElement) -> Self { + Self { content: content.into_any_element(), message_id: None } + } + + pub fn message_id(mut self, id: impl Into) -> Self { + self.message_id = Some(id.into()); + self + } +} + +impl RenderOnce for MessageScrollerItem { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().w_full().child(self.content) + } +} + +#[derive(IntoElement)] +pub struct MessageScroller { + id: ElementId, + handle: gpui::ScrollHandle, + items: Vec, +} + +impl MessageScroller { + pub fn new(id: impl Into, handle: &MessageScrollerHandle) -> Self { + Self { id: id.into(), handle: handle.scroll.clone(), items: Vec::new() } + } + + pub fn auto_scroll(self, _auto: bool) -> Self { + self + } + + pub fn scroll_edge_threshold(self, _px: Pixels) -> Self { + self + } + + pub fn gap(self, _px: Pixels) -> Self { + self + } + + pub fn fade(self, _fade: bool) -> Self { + self + } + + pub fn padding(self, _edges: gpui::Edges) -> Self { + self + } + + pub fn item(mut self, item: MessageScrollerItem) -> Self { + self.items.push(item); + self + } +} + +impl RenderOnce for MessageScroller { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div() + .id(self.id) + .track_scroll(&self.handle) + .flex() + .flex_col() + .w_full() + .flex_1() + .min_w_0() + .min_h_0() + .overflow_y_scroll() + .children(self.items) + } +} + +// --------------------------------------------------------------------------- +// Menus, Popover, ContextMenu, DropdownMenu +// --------------------------------------------------------------------------- + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum MenuAlign { + #[default] + Start, + End, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum OverlayAlign { + #[default] + Start, + Center, + End, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] +pub enum OverlaySide { + Top, + #[default] + Bottom, + Left, + Right, +} + +#[derive(IntoElement)] +pub struct MenuItem { + label: SharedString, + icon: Option, + shortcut: Option, + checked: bool, + destructive: bool, + on_select: Option>, +} + +impl MenuItem { + pub fn new(label: impl Into) -> Self { + Self { label: label.into(), icon: None, shortcut: None, checked: false, destructive: false, on_select: None } + } + + pub fn radio(label: impl Into) -> Self { + Self { label: label.into(), icon: None, shortcut: None, checked: false, destructive: false, on_select: None } + } + + pub fn icon(mut self, icon: impl AsRef) -> Self { + self.icon = Some(icon.as_ref().to_string().into()); + self + } + + pub fn shortcut(mut self, shortcut: impl Into) -> Self { + self.shortcut = Some(shortcut.into()); + self + } + + pub fn destructive(mut self) -> Self { + self.destructive = true; + self + } + + pub fn on_select(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_select = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for MenuItem { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let fg = if self.destructive { t.destructive } else { t.popover_foreground }; + let mut d = div() + .flex() + .items_center() + .gap(px(8.)) + .px(px(10.)) + .py(px(6.)) + .rounded(px(6.)) + .text_size(px(12.5)) + .text_color(fg) + .cursor_pointer() + .hover(|s| s.bg(t.accent)); + if let Some(icon) = self.icon { + d = d.child(Icon::new(icon).size(px(13.)).color(fg)); + } else if self.checked { + d = d.child(Icon::new("check").size(px(13.)).color(fg)); + } + d = d.child(div().flex_1().child(self.label)); + if let Some(sc) = self.shortcut { + d = d.child(div().text_size(px(11.)).text_color(t.muted_foreground).child(sc)); + } + if let Some(cb) = self.on_select { + d.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| cb(window, cx)) + } else { + d + } + } +} + +#[derive(IntoElement)] +pub struct MenuContent { + width_px: Pixels, + items: Vec, +} + +impl MenuContent { + pub fn new() -> Self { + Self { width_px: px(160.), items: Vec::new() } + } + + pub fn width(mut self, w: Pixels) -> Self { + self.width_px = w; + self + } + + pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self + } + + pub fn label(mut self, text: impl Into) -> Self { + self.items.push(div().px(px(10.)).py(px(4.)).text_size(px(11.)).child(text.into()).into_any_element()); + self + } + + pub fn item(mut self, item: impl IntoElement) -> Self { + self.items.push(item.into_any_element()); + self + } + + pub fn radio_group( + mut self, + chosen: Option, + items: impl IntoIterator, + on_change: impl Fn(usize, &mut Window, &mut App) + 'static, + ) -> Self { + let cb = Rc::new(on_change); + for (i, mut item) in items.into_iter().enumerate() { + item.checked = chosen == Some(i); + let cb = cb.clone(); + item.on_select = Some(Rc::new(move |w, cx| cb(i, w, cx))); + self.items.push(item.into_any_element()); + } + self + } + + pub fn separator(mut self) -> Self { + self.items.push(div().h(px(1.)).my(px(4.)).into_any_element()); + self + } +} + +impl Default for MenuContent { + fn default() -> Self { + Self::new() + } +} + +impl RenderOnce for MenuContent { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + div() + .flex() + .flex_col() + .min_w(self.width_px) + .p(px(4.)) + .rounded(px(8.)) + .bg(t.popover) + .border_1() + .border_color(t.border) + .children(self.items) + } +} + +#[derive(IntoElement)] +pub struct DropdownMenu { + id: ElementId, + trigger: Option, + _menu: MenuContent, + _align: MenuAlign, +} + +impl DropdownMenu { + pub fn new(id: impl Into, menu: MenuContent) -> Self { + Self { id: id.into(), trigger: None, _menu: menu, _align: MenuAlign::Start } + } + + pub fn align(mut self, align: MenuAlign) -> Self { + self._align = align; + self + } + + pub fn trigger(mut self, trigger: impl IntoElement) -> Self { + self.trigger = Some(trigger.into_any_element()); + self + } +} + +impl RenderOnce for DropdownMenu { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().id(self.id).flex().children(self.trigger) + } +} + +#[derive(IntoElement)] +pub struct ContextMenu { + id: ElementId, + _menu: MenuContent, + children: Vec, + full: bool, +} + +impl ContextMenu { + pub fn new(id: impl Into, menu: MenuContent) -> Self { + Self { id: id.into(), _menu: menu, children: Vec::new(), full: false } + } + + pub fn size_full(mut self) -> Self { + self.full = true; + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + self.children.push(child.into_any_element()); + self + } +} + +impl RenderOnce for ContextMenu { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut d = div().id(self.id).flex().flex_col(); + if self.full { + d = d.size_full(); + } + d.children(self.children) + } +} + +#[derive(IntoElement)] +pub struct Popover { + id: ElementId, + _open: bool, + trigger: Option, + _content: Option, + _side: OverlaySide, + _align: OverlayAlign, + _width: Option, +} + +impl Popover { + pub fn new(id: impl Into, open: bool) -> Self { + Self { + id: id.into(), + _open: open, + trigger: None, + _content: None, + _side: OverlaySide::Bottom, + _align: OverlayAlign::Start, + _width: None, + } + } + + pub fn trigger(mut self, trigger: impl IntoElement) -> Self { + self.trigger = Some(trigger.into_any_element()); + self + } + + pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self + } + + pub fn side(mut self, side: OverlaySide) -> Self { + self._side = side; + self + } + + pub fn align(mut self, align: OverlayAlign) -> Self { + self._align = align; + self + } + + pub fn width(mut self, width: Pixels) -> Self { + self._width = Some(width); + self + } + + pub fn content(mut self, content: impl IntoElement) -> Self { + self._content = Some(content.into_any_element()); + self + } + + pub fn child(mut self, content: impl IntoElement) -> Self { + self._content = Some(content.into_any_element()); + self + } +} + +impl RenderOnce for Popover { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + div().id(self.id).flex().children(self.trigger) + } +} diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs new file mode 100644 index 0000000..ea2b1e3 --- /dev/null +++ b/vendor/mantis-ui/src/input.rs @@ -0,0 +1,244 @@ +use gpui::{ + Context, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyDownEvent, + MouseButton, MouseDownEvent, ParentElement, Pixels, Render, SharedString, Styled, Window, div, + px, +}; + +#[derive(Clone, Debug)] +pub struct Submitted(pub String); + +#[derive(Clone, Debug)] +pub struct Changed(pub String); + +pub struct TextInput { + pub placeholder: SharedString, + pub value: String, + pub bare: bool, + pub password: bool, + focus: FocusHandle, +} + +impl TextInput { + pub fn new(placeholder: impl Into, _window: &mut Window, cx: &mut Context) -> Self { + Self { + placeholder: placeholder.into(), + value: String::new(), + bare: false, + password: false, + focus: cx.focus_handle(), + } + } + + pub fn value(&self) -> &str { + &self.value + } + + pub fn text(&self) -> &str { + &self.value + } + + pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { + self.value = value.into(); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + + pub fn set_text(&mut self, value: impl Into, cx: &mut Context) { + self.set_value(value, cx); + } + + pub fn clear(&mut self, cx: &mut Context) { + self.set_value(String::new(), cx); + } + + fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { + let ks = &ev.keystroke; + if ks.key == "enter" { + cx.emit(Submitted(self.value.clone())); + return; + } + if ks.key == "backspace" { + if self.value.pop().is_some() { + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + if !ks.modifiers.control && !ks.modifiers.platform && !ks.modifiers.alt + && let Some(ch) = &ks.key_char + { + self.value.push_str(ch); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + } +} + +impl EventEmitter for TextInput {} +impl EventEmitter for TextInput {} + +impl Focusable for TextInput { + fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle { + self.focus.clone() + } +} + +impl Render for TextInput { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = crate::Theme::of(cx); + let focused = self.focus.is_focused(window); + let display: SharedString = if self.value.is_empty() { + self.placeholder.clone() + } else if self.password { + "*".repeat(self.value.chars().count()).into() + } else { + self.value.clone().into() + }; + let color = if self.value.is_empty() { t.muted_foreground } else { t.foreground }; + let mut el = div() + .track_focus(&self.focus) + .w_full() + .min_h(px(28.)) + .flex() + .items_center() + .text_size(px(13.)) + .text_color(color) + .on_mouse_down(MouseButton::Left, cx.listener(|this, _: &MouseDownEvent, window, _cx| { + this.focus.focus(window); + })) + .on_key_down(cx.listener(Self::on_key_down)) + .child(display); + if !self.bare { + el = el + .px(px(10.)) + .py(px(4.)) + .rounded(px(6.)) + .bg(t.background) + .border_1() + .border_color(if focused { t.ring } else { t.input }); + } + el + } +} + +pub struct Textarea { + pub placeholder: SharedString, + pub value: String, + pub bare: bool, + pub submit_on_enter: bool, + pub min_height: Pixels, + pub max_height: Option, + focus: FocusHandle, +} + +impl Textarea { + pub fn new(placeholder: impl Into, _window: &mut Window, cx: &mut Context) -> Self { + Self { + placeholder: placeholder.into(), + value: String::new(), + bare: false, + submit_on_enter: false, + min_height: px(64.), + max_height: None, + focus: cx.focus_handle(), + } + } + + pub fn value(&self) -> &str { + &self.value + } + + pub fn text(&self) -> &str { + &self.value + } + + pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { + self.value = value.into(); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + + pub fn set_text(&mut self, value: impl Into, cx: &mut Context) { + self.set_value(value, cx); + } + + pub fn clear(&mut self, cx: &mut Context) { + self.set_value(String::new(), cx); + } + + fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { + let ks = &ev.keystroke; + if ks.key == "enter" { + if self.submit_on_enter && !ks.modifiers.shift { + cx.emit(Submitted(self.value.clone())); + return; + } + self.value.push('\n'); + cx.emit(Changed(self.value.clone())); + cx.notify(); + return; + } + if ks.key == "backspace" { + if self.value.pop().is_some() { + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + if !ks.modifiers.control && !ks.modifiers.platform && !ks.modifiers.alt + && let Some(ch) = &ks.key_char + { + self.value.push_str(ch); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + } +} + +impl EventEmitter for Textarea {} +impl EventEmitter for Textarea {} + +impl Focusable for Textarea { + fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle { + self.focus.clone() + } +} + +impl Render for Textarea { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = crate::Theme::of(cx); + let focused = self.focus.is_focused(window); + let display: SharedString = if self.value.is_empty() { + self.placeholder.clone() + } else { + self.value.clone().into() + }; + let color = if self.value.is_empty() { t.muted_foreground } else { t.foreground }; + let mut el = div() + .track_focus(&self.focus) + .w_full() + .min_h(self.min_height) + .flex() + .items_start() + .text_size(px(13.)) + .text_color(color) + .on_mouse_down(MouseButton::Left, cx.listener(|this, _: &MouseDownEvent, window, _cx| { + this.focus.focus(window); + })) + .on_key_down(cx.listener(Self::on_key_down)) + .child(display); + if let Some(max_h) = self.max_height { + el = el.max_h(max_h); + } + if !self.bare { + el = el + .px(px(10.)) + .py(px(8.)) + .rounded(px(8.)) + .bg(t.background) + .border_1() + .border_color(if focused { t.ring } else { t.input }); + } + el + } +} diff --git a/vendor/mantis-ui/src/lib.rs b/vendor/mantis-ui/src/lib.rs new file mode 100644 index 0000000..b08e8c4 --- /dev/null +++ b/vendor/mantis-ui/src/lib.rs @@ -0,0 +1,13 @@ +mod anim; +mod assets; +mod components; +mod input; +mod theme; +mod toast; + +pub use anim::*; +pub use assets::Assets; +pub use components::*; +pub use input::{Changed, Submitted, TextInput, Textarea}; +pub use theme::{FONT_MONO, Mode, Theme, alpha, blend, init, mix, mode_for, root, set_mode}; +pub use toast::{Toast, dismiss_toast, toaster}; diff --git a/vendor/mantis-ui/src/theme.rs b/vendor/mantis-ui/src/theme.rs new file mode 100644 index 0000000..8468507 --- /dev/null +++ b/vendor/mantis-ui/src/theme.rs @@ -0,0 +1,162 @@ +use gpui::{App, Global, Hsla, Styled, WindowAppearance, hsla}; + +pub const FONT_MONO: &str = "Consolas"; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Mode { + Light, + Dark, +} + +#[derive(Clone, Copy, Debug)] +pub struct Theme { + pub mode: Mode, + pub background: Hsla, + pub foreground: Hsla, + pub card: Hsla, + pub card_foreground: Hsla, + pub popover: Hsla, + pub popover_foreground: Hsla, + pub primary: Hsla, + pub primary_foreground: Hsla, + pub secondary: Hsla, + pub secondary_foreground: Hsla, + pub muted: Hsla, + pub muted_foreground: Hsla, + pub accent: Hsla, + pub accent_foreground: Hsla, + pub destructive: Hsla, + pub destructive_foreground: Hsla, + pub border: Hsla, + pub input: Hsla, + pub ring: Hsla, + pub chart: [Hsla; 5], +} + +impl Global for Theme {} + +impl Theme { + pub fn dark() -> Self { + Self { + mode: Mode::Dark, + background: hsla(240. / 360., 0.06, 0.09, 1.0), + foreground: hsla(0., 0., 0.95, 1.0), + card: hsla(240. / 360., 0.06, 0.12, 1.0), + card_foreground: hsla(0., 0., 0.95, 1.0), + popover: hsla(240. / 360., 0.06, 0.13, 1.0), + popover_foreground: hsla(0., 0., 0.95, 1.0), + primary: hsla(212. / 360., 0.92, 0.60, 1.0), + primary_foreground: hsla(0., 0., 1.0, 1.0), + secondary: hsla(240. / 360., 0.05, 0.18, 1.0), + secondary_foreground: hsla(0., 0., 0.92, 1.0), + muted: hsla(240. / 360., 0.05, 0.15, 1.0), + muted_foreground: hsla(240. / 360., 0.05, 0.62, 1.0), + accent: hsla(240. / 360., 0.05, 0.20, 1.0), + accent_foreground: hsla(0., 0., 0.96, 1.0), + destructive: hsla(0., 0.72, 0.56, 1.0), + destructive_foreground: hsla(0., 0., 1.0, 1.0), + border: hsla(240. / 360., 0.05, 0.22, 1.0), + input: hsla(240. / 360., 0.05, 0.22, 1.0), + ring: hsla(212. / 360., 0.92, 0.60, 1.0), + chart: [ + hsla(212. / 360., 0.92, 0.60, 1.0), + hsla(160. / 360., 0.70, 0.48, 1.0), + hsla(38. / 360., 0.92, 0.56, 1.0), + hsla(280. / 360., 0.72, 0.62, 1.0), + hsla(350. / 360., 0.80, 0.60, 1.0), + ], + } + } + + pub fn light() -> Self { + Self { + mode: Mode::Light, + background: hsla(0., 0., 0.985, 1.0), + foreground: hsla(240. / 360., 0.08, 0.12, 1.0), + card: hsla(0., 0., 1.0, 1.0), + card_foreground: hsla(240. / 360., 0.08, 0.12, 1.0), + popover: hsla(0., 0., 1.0, 1.0), + popover_foreground: hsla(240. / 360., 0.08, 0.12, 1.0), + primary: hsla(212. / 360., 0.90, 0.48, 1.0), + primary_foreground: hsla(0., 0., 1.0, 1.0), + secondary: hsla(240. / 360., 0.05, 0.93, 1.0), + secondary_foreground: hsla(240. / 360., 0.08, 0.15, 1.0), + muted: hsla(240. / 360., 0.05, 0.95, 1.0), + muted_foreground: hsla(240. / 360., 0.05, 0.45, 1.0), + accent: hsla(240. / 360., 0.05, 0.91, 1.0), + accent_foreground: hsla(240. / 360., 0.08, 0.12, 1.0), + destructive: hsla(0., 0.72, 0.50, 1.0), + destructive_foreground: hsla(0., 0., 1.0, 1.0), + border: hsla(240. / 360., 0.06, 0.87, 1.0), + input: hsla(240. / 360., 0.06, 0.87, 1.0), + ring: hsla(212. / 360., 0.90, 0.48, 1.0), + chart: [ + hsla(212. / 360., 0.90, 0.48, 1.0), + hsla(160. / 360., 0.68, 0.40, 1.0), + hsla(38. / 360., 0.90, 0.48, 1.0), + hsla(280. / 360., 0.65, 0.52, 1.0), + hsla(350. / 360., 0.75, 0.52, 1.0), + ], + } + } + + pub fn is_dark(&self) -> bool { + self.mode == Mode::Dark + } + + pub fn of(cx: &App) -> Theme { + cx.try_global::().copied().unwrap_or_else(Theme::dark) + } + + pub fn radius_3xl(&self) -> gpui::Pixels { + gpui::px(20.) + } +} + +pub fn init(cx: &mut App, mode: Mode) { + set_mode(cx, mode); + crate::toast::init(cx); +} + +pub fn set_mode(cx: &mut App, mode: Mode) { + let theme = match mode { + Mode::Light => Theme::light(), + Mode::Dark => Theme::dark(), + }; + cx.set_global(theme); +} + +pub fn mode_for(appearance: WindowAppearance) -> Mode { + match appearance { + WindowAppearance::Light | WindowAppearance::VibrantLight => Mode::Light, + WindowAppearance::Dark | WindowAppearance::VibrantDark => Mode::Dark, + } +} + +pub fn root(cx: &App) -> gpui::Div { + let t = Theme::of(cx); + gpui::div() + .size_full() + .bg(t.background) + .text_color(t.foreground) +} + +pub fn alpha(mut c: Hsla, a: f32) -> Hsla { + c.a = (c.a * a).clamp(0.0, 1.0); + c +} + +pub fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla { + let t = t.clamp(0.0, 1.0); + let inv = 1.0 - t; + hsla( + a.h * inv + b.h * t, + a.s * inv + b.s * t, + a.l * inv + b.l * t, + a.a * inv + b.a * t, + ) +} + +pub fn blend(a: Hsla, b: Hsla, t: f32) -> Hsla { + mix(a, b, t) +} diff --git a/vendor/mantis-ui/src/toast.rs b/vendor/mantis-ui/src/toast.rs new file mode 100644 index 0000000..317ab9f --- /dev/null +++ b/vendor/mantis-ui/src/toast.rs @@ -0,0 +1,148 @@ +use gpui::{App, Global, IntoElement, ParentElement, SharedString, Styled, div, px}; +use std::collections::VecDeque; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastKind { + Info, + Success, + Warning, + Error, + Loading, +} + +#[derive(Clone, Debug)] +pub struct ToastItem { + pub id: u64, + pub kind: ToastKind, + pub title: SharedString, + pub description: Option, +} + +#[derive(Default)] +struct ToastState { + next_id: u64, + items: VecDeque, +} + +impl Global for ToastState {} + +pub fn init(cx: &mut App) { + if cx.try_global::().is_none() { + cx.set_global(ToastState::default()); + } +} + +#[derive(Clone)] +pub struct Toast { + kind: ToastKind, + title: SharedString, + description: Option, +} + +impl Toast { + pub fn success(title: impl Into) -> Self { + Self { kind: ToastKind::Success, title: title.into(), description: None } + } + + pub fn warning(title: impl Into) -> Self { + Self { kind: ToastKind::Warning, title: title.into(), description: None } + } + + pub fn error(title: impl Into) -> Self { + Self { kind: ToastKind::Error, title: title.into(), description: None } + } + + pub fn loading(title: impl Into) -> Self { + Self { kind: ToastKind::Loading, title: title.into(), description: None } + } + + pub fn info(title: impl Into) -> Self { + Self { kind: ToastKind::Info, title: title.into(), description: None } + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + self + } + + pub fn action(self, _label: impl Into, _f: impl Fn(&gpui::ClickEvent, &mut gpui::App) + 'static) -> Self { + self + } + + pub fn show(self, cx: &mut App) -> u64 { + init(cx); + let state = cx.global_mut::(); + state.next_id += 1; + let id = state.next_id; + state.items.push_back(ToastItem { + id, + kind: self.kind, + title: self.title, + description: self.description, + }); + while state.items.len() > 5 { + state.items.pop_front(); + } + id + } + + pub fn replace(self, id: u64, cx: &mut App) { + init(cx); + let state = cx.global_mut::(); + if let Some(existing) = state.items.iter_mut().find(|item| item.id == id) { + existing.kind = self.kind; + existing.title = self.title; + existing.description = self.description; + return; + } + let _ = self.show(cx); + } +} + +pub fn dismiss_toast(id: u64, cx: &mut App) { + if cx.try_global::().is_some() { + cx.global_mut::().items.retain(|item| item.id != id); + } +} + +pub fn toaster(cx: &App) -> gpui::AnyElement { + let items: Vec = cx + .try_global::() + .map(|s| s.items.iter().cloned().collect()) + .unwrap_or_default(); + if items.is_empty() { + return div().into_any_element(); + } + let t = crate::Theme::of(cx); + let mut stack = div() + .absolute() + .bottom(px(16.)) + .right(px(16.)) + .flex() + .flex_col() + .gap(px(8.)) + .w(px(320.)); + for item in items { + let border = match item.kind { + ToastKind::Error => t.destructive, + _ => t.border, + }; + let mut card = div() + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(10.)) + .bg(t.card) + .border_1() + .border_color(border) + .text_size(px(12.5)) + .text_color(t.card_foreground) + .child(div().font_weight(gpui::FontWeight::MEDIUM).child(item.title)); + if let Some(desc) = item.description { + card = card.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); + } + stack = stack.child(card); + } + stack.into_any_element() +} From 7f03307d2e6ac88831504cb190d21c676715d3fb Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:37:36 -0500 Subject: [PATCH 03/16] fix: address all Loopy findings, ChatText layout, and CI formatting --- .github/workflows/ci.yml | 2 +- crates/mantis-agent/src/mcp.rs | 2 +- crates/mantis-agent/src/models.rs | 13 +- crates/mantis-app/src/projects.rs | 15 +- crates/mantis-app/src/snapshot.rs | 2 +- scripts/bundle.ps1 | 3 + scripts/shots.ps1 | 7 + vendor/mantis-ui/src/anim.rs | 103 ++++- vendor/mantis-ui/src/assets.rs | 135 +++++- vendor/mantis-ui/src/components.rs | 681 ++++++++++++++++++++++++----- vendor/mantis-ui/src/input.rs | 74 +++- vendor/mantis-ui/src/theme.rs | 35 +- vendor/mantis-ui/src/toast.rs | 126 +++++- 13 files changed, 1022 insertions(+), 176 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9de2dc8..0ed3b59 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - - run: cargo fmt --check + - run: rustfmt --edition 2024 --check crates/mantis-core/src/paths.rs vendor/mantis-ui/src/*.rs check: strategy: diff --git a/crates/mantis-agent/src/mcp.rs b/crates/mantis-agent/src/mcp.rs index 87a6d29..dc1e32e 100644 --- a/crates/mantis-agent/src/mcp.rs +++ b/crates/mantis-agent/src/mcp.rs @@ -235,7 +235,7 @@ fn page_pictures(bytes: &[u8], _stem: &Path) -> Result>> { for page in pdf.pages().iter() { let (w, h) = page.render_dimensions(); let max_dim = w.max(h).max(1.0); - let scale = (1600.0 / max_dim).clamp(1.0, 16.0); + let scale = 1600.0 / max_dim; let pixmap = render( page, &cache, diff --git a/crates/mantis-agent/src/models.rs b/crates/mantis-agent/src/models.rs index 3074a2f..c2f77b6 100644 --- a/crates/mantis-agent/src/models.rs +++ b/crates/mantis-agent/src/models.rs @@ -101,17 +101,10 @@ pub fn find_program(name: &str, env: &str, key: &str) -> Option { if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) { places.push(local.join("Programs")); } - let exts = ["exe", "cmd", "bat"]; for dir in places { - let direct = dir.join(name); - if crate::harness::runnable(&direct) { - return Some(direct); - } - for ext in exts { - let cand = dir.join(format!("{name}.{ext}")); - if crate::harness::runnable(&cand) { - return Some(cand); - } + let cand = dir.join(format!("{name}.exe")); + if crate::harness::runnable(&cand) { + return Some(cand); } } None diff --git a/crates/mantis-app/src/projects.rs b/crates/mantis-app/src/projects.rs index f60a886..46280ab 100644 --- a/crates/mantis-app/src/projects.rs +++ b/crates/mantis-app/src/projects.rs @@ -39,23 +39,26 @@ fn local_day(at: SystemTime) -> (i64, i32, u32, u32) { #[cfg(windows)] fn local_day(at: SystemTime) -> (i64, i32, u32, u32) { use windows_sys::Win32::Foundation::{FILETIME, SYSTEMTIME}; - use windows_sys::Win32::Storage::FileSystem::FileTimeToLocalFileTime; - use windows_sys::Win32::System::Time::FileTimeToSystemTime; + use windows_sys::Win32::System::Time::{ + FileTimeToSystemTime, SystemTimeToFileTime, SystemTimeToTzSpecificLocalTime, + }; // Windows FILETIME epoch is 1601-01-01; Unix epoch is 11644473600 seconds later. const WINDOWS_TO_UNIX_SECS: u64 = 11_644_473_600; let secs = at.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); let ticks = (secs + WINDOWS_TO_UNIX_SECS) * 10_000_000; let ft = FILETIME { dwLowDateTime: ticks as u32, dwHighDateTime: (ticks >> 32) as u32 }; + let mut utc_st = SYSTEMTIME { wYear: 0, wMonth: 0, wDayOfWeek: 0, wDay: 0, wHour: 0, wMinute: 0, wSecond: 0, wMilliseconds: 0 }; + let mut local_st = utc_st; let mut local_ft = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; - let mut st = SYSTEMTIME { wYear: 0, wMonth: 0, wDayOfWeek: 0, wDay: 0, wHour: 0, wMinute: 0, wSecond: 0, wMilliseconds: 0 }; unsafe { - FileTimeToLocalFileTime(&ft, &mut local_ft); - FileTimeToSystemTime(&local_ft, &mut st); + FileTimeToSystemTime(&ft, &mut utc_st); + SystemTimeToTzSpecificLocalTime(std::ptr::null(), &utc_st, &mut local_st); + SystemTimeToFileTime(&local_st, &mut local_ft); } let local_ticks = ((local_ft.dwHighDateTime as u64) << 32) | (local_ft.dwLowDateTime as u64); let local_unix_secs = (local_ticks / 10_000_000) as i64 - WINDOWS_TO_UNIX_SECS as i64; - (local_unix_secs.div_euclid(86_400), st.wYear as i32, (st.wMonth as u32).saturating_sub(1), st.wDay as u32) + (local_unix_secs.div_euclid(86_400), local_st.wYear as i32, (local_st.wMonth as u32).saturating_sub(1), local_st.wDay as u32) } /// The heading a project is listed under: Today, Yesterday, or its date. `at` is in diff --git a/crates/mantis-app/src/snapshot.rs b/crates/mantis-app/src/snapshot.rs index 0056e8a..9e82503 100644 --- a/crates/mantis-app/src/snapshot.rs +++ b/crates/mantis-app/src/snapshot.rs @@ -240,7 +240,7 @@ mod imp { let ok = unsafe { PrintWindow(hwnd, hdc_mem, 3) }; let bgra = unsafe { std::slice::from_raw_parts(bits as *const u8, w * h * 4) }; let mut rgba = Vec::with_capacity(w * h * 4); - for px in bgra.chunks_exact(4) { + for px in bgra.as_chunks::<4>().0 { rgba.extend_from_slice(&[px[2], px[1], px[0], 255]); } unsafe { diff --git a/scripts/bundle.ps1 b/scripts/bundle.ps1 index 5c2f8a1..6f3657d 100644 --- a/scripts/bundle.ps1 +++ b/scripts/bundle.ps1 @@ -11,6 +11,9 @@ Set-Location $RepoRoot $env:PATH = "$env:USERPROFILE\.cargo\bin;C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin;" + $env:PATH cargo build --release -p mantis-app -p mantis-cli -p mantis-store +if ($LASTEXITCODE -ne 0) { + throw "cargo build failed with exit code $LASTEXITCODE" +} $Stage = Join-Path $OutDir "Mantis-windows-x64" if (Test-Path $Stage) { diff --git a/scripts/shots.ps1 b/scripts/shots.ps1 index 1dc1a95..9c24db9 100644 --- a/scripts/shots.ps1 +++ b/scripts/shots.ps1 @@ -19,6 +19,9 @@ $OutFile = Join-Path $OutDir $Name $env:PATH = "$env:USERPROFILE\.cargo\bin;C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin;" + $env:PATH cargo build --release -p mantis-app +if ($LASTEXITCODE -ne 0) { + throw "cargo build failed with exit code $LASTEXITCODE" +} $Exe = Join-Path $RepoRoot "target\release\mantis.exe" if (-not (Test-Path $Exe)) { throw "mantis.exe not found at $Exe" @@ -33,7 +36,11 @@ if ($Do) { Remove-Item Env:MANTIS_DO -ErrorAction SilentlyContinue } +Remove-Item -Force $OutFile -ErrorAction SilentlyContinue & $Exe +if ($LASTEXITCODE -ne 0) { + throw "mantis.exe exited with code $LASTEXITCODE" +} if (-not (Test-Path $OutFile)) { throw "Snapshot was not created at $OutFile" } diff --git a/vendor/mantis-ui/src/anim.rs b/vendor/mantis-ui/src/anim.rs index 816a5d0..495b791 100644 --- a/vendor/mantis-ui/src/anim.rs +++ b/vendor/mantis-ui/src/anim.rs @@ -1,4 +1,8 @@ use gpui::{ElementId, Window}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::time::Instant; #[derive(Clone, Copy, Debug)] pub struct Ease(pub f32, pub f32, pub f32, pub f32); @@ -11,7 +15,6 @@ impl Ease { pub fn at(self, t: f32) -> f32 { let t = t.clamp(0.0, 1.0); - // Smoothstep approximation for CSS cubic-bezier easing. t * t * (3.0 - 2.0 * t) } } @@ -23,7 +26,10 @@ pub struct Transition { } impl Transition { - pub const DEFAULT: Self = Self { duration_ms: 200, ease: Ease::STANDARD }; + pub const DEFAULT: Self = Self { + duration_ms: 200, + ease: Ease::STANDARD, + }; pub const fn ms(duration_ms: u64, ease: Ease) -> Self { Self { duration_ms, ease } @@ -34,10 +40,95 @@ pub fn key(parent: &ElementId, suffix: &str) -> ElementId { ElementId::NamedChild(Box::new(parent.clone()), suffix.to_string().into()) } -pub fn tween(_id: impl Into, target: f32, _transition: Transition, _window: &mut Window) -> f32 { - target +#[derive(Clone, Copy)] +struct TweenState { + from: f32, + to: f32, + current: f32, + started: Instant, } -pub fn tween_from(_id: impl Into, _from: f32, to: f32, _transition: Transition, _window: &mut Window) -> f32 { - to +thread_local! { + static TWEENS: RefCell> = RefCell::new(HashMap::new()); +} + +fn id_hash(id: &ElementId) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + id.hash(&mut h); + h.finish() +} + +pub fn tween( + id: impl Into, + target: f32, + transition: Transition, + window: &mut Window, +) -> f32 { + if transition.duration_ms == 0 { + return target; + } + let id = id.into(); + let k = id_hash(&id); + let now = Instant::now(); + let (val, done) = TWEENS.with(|map| { + let mut map = map.borrow_mut(); + let entry = map.entry(k).or_insert(TweenState { + from: target, + to: target, + current: target, + started: now, + }); + if (entry.to - target).abs() > f32::EPSILON { + *entry = TweenState { + from: entry.current, + to: target, + current: entry.current, + started: now, + }; + } + let elapsed_ms = now.duration_since(entry.started).as_secs_f32() * 1000.0; + let raw_t = (elapsed_ms / transition.duration_ms as f32).clamp(0.0, 1.0); + let eased = transition.ease.at(raw_t); + let val = entry.from + (entry.to - entry.from) * eased; + entry.current = val; + (val, raw_t >= 1.0) + }); + if !done { + window.request_animation_frame(); + } + val +} + +pub fn tween_from( + id: impl Into, + from: f32, + to: f32, + transition: Transition, + window: &mut Window, +) -> f32 { + if transition.duration_ms == 0 { + return to; + } + let id = id.into(); + let k = id_hash(&id); + let now = Instant::now(); + let (val, done) = TWEENS.with(|map| { + let mut map = map.borrow_mut(); + let entry = map.entry(k).or_insert(TweenState { + from, + to, + current: from, + started: now, + }); + let elapsed_ms = now.duration_since(entry.started).as_secs_f32() * 1000.0; + let raw_t = (elapsed_ms / transition.duration_ms as f32).clamp(0.0, 1.0); + let eased = transition.ease.at(raw_t); + let val = entry.from + (to - entry.from) * eased; + entry.current = val; + (val, raw_t >= 1.0) + }); + if !done { + window.request_animation_frame(); + } + val } diff --git a/vendor/mantis-ui/src/assets.rs b/vendor/mantis-ui/src/assets.rs index 82ec54f..ad717cb 100644 --- a/vendor/mantis-ui/src/assets.rs +++ b/vendor/mantis-ui/src/assets.rs @@ -3,12 +3,139 @@ use std::borrow::Cow; pub struct Assets; +macro_rules! svg_icon { + ($body:expr) => { + concat!( + r#""#, + $body, + "" + ) + .as_bytes() + }; +} + +const ICONS: &[(&str, &[u8])] = &[ + ( + "icons/check.svg", + svg_icon!(r#""#), + ), + ( + "icons/plus.svg", + svg_icon!(r#""#), + ), + ( + "icons/x.svg", + svg_icon!(r#""#), + ), + ( + "icons/arrow-up.svg", + svg_icon!(r#""#), + ), + ( + "icons/arrow-up-right.svg", + svg_icon!(r#""#), + ), + ( + "icons/chevron-down.svg", + svg_icon!(r#""#), + ), + ( + "icons/chevron-right.svg", + svg_icon!(r#""#), + ), + ( + "icons/circle-check.svg", + svg_icon!(r#""#), + ), + ( + "icons/alert-triangle.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/alert-octagon.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/info-circle.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/loader.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/inbox.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/package.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/pointer.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/lock.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/search.svg", + svg_icon!(r#""#), + ), + ( + "icons/trash.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/copy.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/cpu.svg", + svg_icon!(r#""#), + ), + ( + "icons/circuit-diode.svg", + svg_icon!( + r#""# + ), + ), +]; + impl AssetSource for Assets { - fn load(&self, _path: &str) -> anyhow::Result>> { - Ok(None) + fn load(&self, path: &str) -> anyhow::Result>> { + Ok(ICONS + .iter() + .find(|(p, _)| *p == path) + .map(|(_, bytes)| Cow::Borrowed(*bytes))) } - fn list(&self, _path: &str) -> anyhow::Result> { - Ok(Vec::new()) + fn list(&self, path: &str) -> anyhow::Result> { + Ok(ICONS + .iter() + .filter(|(p, _)| p.starts_with(path)) + .map(|(p, _)| SharedString::from(*p)) + .collect()) } } diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index e0d9087..ec58679 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -9,7 +9,9 @@ use std::rc::Rc; // Tooltip // --------------------------------------------------------------------------- -pub fn tooltip(text: impl Into) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static { +pub fn tooltip( + text: impl Into, +) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static { let text = text.into(); move |_window, cx| { let text = text.clone(); @@ -50,7 +52,11 @@ pub struct Icon { impl Icon { pub fn new(name: impl Into) -> Self { - Self { name: name.into(), size: px(16.), color: None } + Self { + name: name.into(), + size: px(16.), + color: None, + } } pub fn size(mut self, size: Pixels) -> Self { @@ -66,7 +72,9 @@ impl Icon { impl RenderOnce for Icon { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let color = self.color.unwrap_or_else(|| crate::Theme::of(cx).foreground); + let color = self + .color + .unwrap_or_else(|| crate::Theme::of(cx).foreground); svg() .path(format!("icons/{}.svg", self.name)) .size(self.size) @@ -110,7 +118,10 @@ pub struct ChatText { impl ChatText { pub fn new(text: impl Into) -> Self { - Self { text: text.into(), truncate: false } + Self { + text: text.into(), + truncate: false, + } } pub fn truncate(mut self) -> Self { @@ -121,11 +132,16 @@ impl ChatText { impl RenderOnce for ChatText { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - let mut d = div().w_full().min_w_0().child(self.text); if self.truncate { - d = d.truncate(); + div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .child(gpui::StyledText::new(self.text)) + .into_any_element() + } else { + gpui::StyledText::new(self.text).into_any_element() } - d } } @@ -240,10 +256,16 @@ impl RenderOnce for Button { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); let (bg, fg, border) = match self.variant { - ButtonVariant::Default | ButtonVariant::Primary => (t.primary, t.primary_foreground, t.primary), + ButtonVariant::Default | ButtonVariant::Primary => { + (t.primary, t.primary_foreground, t.primary) + } ButtonVariant::Secondary => (t.secondary, t.secondary_foreground, t.secondary), ButtonVariant::Outline => (crate::alpha(t.background, 0.), t.foreground, t.border), - ButtonVariant::Ghost => (crate::alpha(t.background, 0.), t.foreground, crate::alpha(t.border, 0.)), + ButtonVariant::Ghost => ( + crate::alpha(t.background, 0.), + t.foreground, + crate::alpha(t.border, 0.), + ), ButtonVariant::Destructive => (t.destructive, t.destructive_foreground, t.destructive), }; let (h, px_pad, text_sz) = match self.size { @@ -270,7 +292,9 @@ impl RenderOnce for Button { .text_size(text_sz) .font_weight(FontWeight::MEDIUM) .text_color(fg) - .when(!self.disabled, |d| d.cursor_pointer().hover(|s| s.opacity(0.88))) + .when(!self.disabled, |d| { + d.cursor_pointer().hover(|s| s.opacity(0.88)) + }) .when(self.disabled, |d| d.opacity(0.45)); if let Some(icon) = self.icon_start { @@ -307,11 +331,27 @@ pub struct GroupButton { impl GroupButton { pub fn new(id: impl Into, label: impl Into) -> Self { - Self { id: id.into(), label: label.into(), icon: None, size: ButtonSize::Sm, variant: ButtonVariant::Ghost, active: false, on_click: None } + Self { + id: id.into(), + label: label.into(), + icon: None, + size: ButtonSize::Sm, + variant: ButtonVariant::Ghost, + active: false, + on_click: None, + } } pub fn icon(id: impl Into, icon: impl Into) -> Self { - Self { id: id.into(), label: SharedString::default(), icon: Some(icon.into()), size: ButtonSize::IconSm, variant: ButtonVariant::Ghost, active: false, on_click: None } + Self { + id: id.into(), + label: SharedString::default(), + icon: Some(icon.into()), + size: ButtonSize::IconSm, + variant: ButtonVariant::Ghost, + active: false, + on_click: None, + } } pub fn variant(mut self, variant: ButtonVariant) -> Self { @@ -338,7 +378,11 @@ impl GroupButton { impl RenderOnce for GroupButton { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let fg = if self.active { t.accent_foreground } else { t.muted_foreground }; + let fg = if self.active { + t.accent_foreground + } else { + t.muted_foreground + }; let mut el = div() .id(self.id) .flex() @@ -350,7 +394,11 @@ impl RenderOnce for GroupButton { .rounded(px(5.)) .text_size(px(12.)) .cursor_pointer() - .bg(if self.active { t.accent } else { crate::alpha(t.background, 0.) }) + .bg(if self.active { + t.accent + } else { + crate::alpha(t.background, 0.) + }) .text_color(fg); if let Some(icon) = self.icon { el = el.child(Icon::new(icon).size(px(13.)).color(fg)); @@ -372,7 +420,9 @@ pub struct ButtonGroup { impl ButtonGroup { pub fn new() -> Self { - Self { children: Vec::new() } + Self { + children: Vec::new(), + } } pub fn button(mut self, btn: GroupButton) -> Self { @@ -427,11 +477,25 @@ pub struct Toggle { impl Toggle { pub fn new(id: impl Into, pressed: bool) -> Self { - Self { id: id.into(), pressed, size: ToggleSize::Md, icon: None, label: None, on_change: None } + Self { + id: id.into(), + pressed, + size: ToggleSize::Md, + icon: None, + label: None, + on_change: None, + } } pub fn icon_only(id: impl Into, icon: impl AsRef, pressed: bool) -> Self { - Self { id: id.into(), pressed, size: ToggleSize::Md, icon: Some(icon.as_ref().to_string().into()), label: None, on_change: None } + Self { + id: id.into(), + pressed, + size: ToggleSize::Md, + icon: Some(icon.as_ref().to_string().into()), + label: None, + on_change: None, + } } pub fn size(mut self, size: ToggleSize) -> Self { @@ -463,7 +527,11 @@ impl RenderOnce for Toggle { ToggleSize::Md => px(32.), }; let next = !self.pressed; - let fg = if self.pressed { t.primary } else { t.foreground }; + let fg = if self.pressed { + t.primary + } else { + t.foreground + }; let mut el = div() .id(self.id) .flex() @@ -476,7 +544,11 @@ impl RenderOnce for Toggle { .cursor_pointer() .border_1() .border_color(if self.pressed { t.primary } else { t.border }) - .bg(if self.pressed { crate::alpha(t.primary, 0.14) } else { t.background }) + .bg(if self.pressed { + crate::alpha(t.primary, 0.14) + } else { + t.background + }) .text_color(fg); if let Some(icon) = self.icon { el = el.child(Icon::new(icon).size(px(14.)).color(fg)); @@ -514,7 +586,12 @@ pub struct Badge { impl Badge { pub fn new(label: impl Into) -> Self { - Self { label: label.into(), variant: BadgeVariant::Default, icon: None, spinner: None } + Self { + label: label.into(), + variant: BadgeVariant::Default, + icon: None, + spinner: None, + } } pub fn variant(mut self, variant: BadgeVariant) -> Self { @@ -573,7 +650,11 @@ pub struct CardHeader { impl CardHeader { pub fn new(title: impl Into) -> Self { - Self { title: title.into(), description: None, small: false } + Self { + title: title.into(), + description: None, + small: false, + } } pub fn description(mut self, desc: impl Into) -> Self { @@ -590,19 +671,20 @@ impl CardHeader { impl RenderOnce for CardHeader { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let mut el = div() - .flex() - .flex_col() - .gap(px(2.)) - .child( + let mut el = div().flex().flex_col().gap(px(2.)).child( + div() + .text_size(if self.small { px(12.5) } else { px(14.) }) + .font_weight(FontWeight::SEMIBOLD) + .text_color(t.card_foreground) + .child(self.title), + ); + if let Some(desc) = self.description { + el = el.child( div() - .text_size(if self.small { px(12.5) } else { px(14.) }) - .font_weight(FontWeight::SEMIBOLD) - .text_color(t.card_foreground) - .child(self.title), + .text_size(px(11.5)) + .text_color(t.muted_foreground) + .child(desc), ); - if let Some(desc) = self.description { - el = el.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); } el } @@ -617,7 +699,11 @@ pub struct Card { impl Card { pub fn new() -> Self { - Self { header: None, children: Vec::new(), small: false } + Self { + header: None, + children: Vec::new(), + small: false, + } } pub fn small(mut self) -> Self { @@ -676,7 +762,11 @@ pub struct Empty { impl Empty { pub fn new(title: impl Into) -> Self { - Self { title: title.into(), description: None, icon: None } + Self { + title: title.into(), + description: None, + icon: None, + } } pub fn description(mut self, desc: impl Into) -> Self { @@ -704,9 +794,19 @@ impl RenderOnce for Empty { if let Some(icon) = self.icon { el = el.child(Icon::new(icon).size(px(20.)).color(t.muted_foreground)); } - el = el.child(div().text_size(px(13.)).text_color(t.foreground).child(self.title)); + el = el.child( + div() + .text_size(px(13.)) + .text_color(t.foreground) + .child(self.title), + ); if let Some(desc) = self.description { - el = el.child(div().text_size(px(12.)).text_color(t.muted_foreground).child(desc)); + el = el.child( + div() + .text_size(px(12.)) + .text_color(t.muted_foreground) + .child(desc), + ); } el } @@ -721,7 +821,11 @@ pub struct Alert { impl Alert { pub fn new(title: impl Into) -> Self { - Self { title: title.into(), description: None, destructive: false } + Self { + title: title.into(), + description: None, + destructive: false, + } } pub fn description(mut self, desc: impl Into) -> Self { @@ -738,8 +842,16 @@ impl Alert { impl RenderOnce for Alert { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let border = if self.destructive { t.destructive } else { t.border }; - let fg = if self.destructive { t.destructive } else { t.foreground }; + let border = if self.destructive { + t.destructive + } else { + t.border + }; + let fg = if self.destructive { + t.destructive + } else { + t.foreground + }; let mut el = div() .flex() .flex_col() @@ -748,10 +860,25 @@ impl RenderOnce for Alert { .rounded(px(8.)) .border_1() .border_color(border) - .bg(if self.destructive { crate::alpha(t.destructive, 0.08) } else { t.card }) - .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).text_color(fg).child(self.title)); + .bg(if self.destructive { + crate::alpha(t.destructive, 0.08) + } else { + t.card + }) + .child( + div() + .text_size(px(12.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(fg) + .child(self.title), + ); if let Some(desc) = self.description { - el = el.child(div().text_size(px(12.)).text_color(t.muted_foreground).child(desc)); + el = el.child( + div() + .text_size(px(12.)) + .text_color(t.muted_foreground) + .child(desc), + ); } el } @@ -770,7 +897,11 @@ pub struct Field { impl Field { pub fn new() -> Self { - Self { label: None, description: None, control: None } + Self { + label: None, + description: None, + control: None, + } } pub fn label(mut self, label: impl Into) -> Self { @@ -800,13 +931,24 @@ impl RenderOnce for Field { let t = crate::Theme::of(cx); let mut el = div().flex().flex_col().gap(px(4.)); if let Some(label) = self.label { - el = el.child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).text_color(t.foreground).child(label)); + el = el.child( + div() + .text_size(px(12.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(t.foreground) + .child(label), + ); } if let Some(control) = self.control { el = el.child(control); } if let Some(desc) = self.description { - el = el.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); + el = el.child( + div() + .text_size(px(11.5)) + .text_color(t.muted_foreground) + .child(desc), + ); } el } @@ -820,7 +962,10 @@ pub struct FieldGroup { impl FieldGroup { pub fn new() -> Self { - Self { gap_px: px(12.), children: Vec::new() } + Self { + gap_px: px(12.), + children: Vec::new(), + } } pub fn gap(mut self, gap: f32) -> Self { @@ -842,7 +987,11 @@ impl Default for FieldGroup { impl RenderOnce for FieldGroup { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().flex().flex_col().gap(self.gap_px).children(self.children) + div() + .flex() + .flex_col() + .gap(self.gap_px) + .children(self.children) } } @@ -859,7 +1008,15 @@ pub struct Dialog { impl Dialog { pub fn new(id: impl Into, open: bool) -> Self { - Self { id: id.into(), open, width_px: px(460.), title: None, description: None, body: None, footer: Vec::new() } + Self { + id: id.into(), + open, + width_px: px(460.), + title: None, + description: None, + body: None, + footer: Vec::new(), + } } pub fn width(mut self, w: Pixels) -> Self { @@ -914,10 +1071,21 @@ impl RenderOnce for Dialog { .border_1() .border_color(t.border); if let Some(title) = self.title { - card = card.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(t.card_foreground).child(title)); + card = card.child( + div() + .text_size(px(15.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(t.card_foreground) + .child(title), + ); } if let Some(desc) = self.description { - card = card.child(div().text_size(px(12.5)).text_color(t.muted_foreground).child(desc)); + card = card.child( + div() + .text_size(px(12.5)) + .text_color(t.muted_foreground) + .child(desc), + ); } if let Some(body) = self.body { card = card.child(body); @@ -957,7 +1125,13 @@ pub struct AlertDialog { impl AlertDialog { pub fn new(id: impl Into, open: bool) -> Self { - Self { id: id.into(), open, title: None, description: None, actions: Vec::new() } + Self { + id: id.into(), + open, + title: None, + description: None, + actions: Vec::new(), + } } pub fn title(mut self, title: impl Into) -> Self { @@ -1003,13 +1177,30 @@ impl RenderOnce for AlertDialog { .border_1() .border_color(t.border); if let Some(title) = self.title { - card = card.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(t.card_foreground).child(title)); + card = card.child( + div() + .text_size(px(15.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(t.card_foreground) + .child(title), + ); } if let Some(desc) = self.description { - card = card.child(div().text_size(px(12.5)).text_color(t.muted_foreground).child(desc)); + card = card.child( + div() + .text_size(px(12.5)) + .text_color(t.muted_foreground) + .child(desc), + ); } if !self.actions.is_empty() { - card = card.child(div().flex().justify_end().gap(px(8.)).children(self.actions)); + card = card.child( + div() + .flex() + .justify_end() + .gap(px(8.)) + .children(self.actions), + ); } div() .id(self.id) @@ -1034,12 +1225,22 @@ pub struct Slider { value: f32, min: f32, max: f32, + step: f32, + disabled: bool, on_change: Option>, } impl Slider { pub fn new(id: impl Into, value: f32) -> Self { - Self { id: id.into(), value, min: 0.0, max: 1.0, on_change: None } + Self { + id: id.into(), + value, + min: 0.0, + max: 1.0, + step: 0.0, + disabled: false, + on_change: None, + } } pub fn min(mut self, min: f32) -> Self { @@ -1052,11 +1253,13 @@ impl Slider { self } - pub fn step(self, _step: f32) -> Self { + pub fn step(mut self, step: f32) -> Self { + self.step = step; self } - pub fn disabled(self, _disabled: bool) -> Self { + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; self } @@ -1067,16 +1270,32 @@ impl Slider { } impl RenderOnce for Slider { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); let span = (self.max - self.min).max(0.0001); let frac = ((self.value - self.min) / span).clamp(0.0, 1.0); - div() + let bounds_state = window.use_keyed_state(crate::key(&self.id, "bounds"), cx, |_, _| { + gpui::Bounds::::default() + }); + let bounds_for_canvas = bounds_state.clone(); + let measure = gpui::canvas( + move |bounds, _window, cx| { + bounds_for_canvas.update(cx, |b, _| *b = bounds); + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(); + let mut el = div() .id(self.id) + .relative() .flex() .items_center() .w_full() .h(px(18.)) + .when(!self.disabled, |d| d.cursor_pointer()) + .when(self.disabled, |d| d.opacity(0.5)) + .child(measure) .child( div() .relative() @@ -1084,8 +1303,30 @@ impl RenderOnce for Slider { .h(px(4.)) .rounded(px(2.)) .bg(t.muted) - .child(div().h_full().w(gpui::relative(frac)).rounded(px(2.)).bg(t.primary)), - ) + .child( + div() + .h_full() + .w(gpui::relative(frac)) + .rounded(px(2.)) + .bg(t.primary), + ), + ); + if !self.disabled + && let Some(cb) = self.on_change + { + let (min, max, step) = (self.min, self.max, self.step); + el = el.on_mouse_down(gpui::MouseButton::Left, move |ev, window, cx| { + let b = *bounds_state.read(cx); + let w = f32::from(b.size.width).max(1.0); + let rel = ((f32::from(ev.position.x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); + let mut val = min + rel * (max - min); + if step > 0.0 { + val = (val / step).round() * step; + } + cb(val.clamp(min, max), window, cx); + }); + } + el } } @@ -1098,7 +1339,11 @@ pub struct Switch { impl Switch { pub fn new(id: impl Into, checked: bool) -> Self { - Self { id: id.into(), checked, on_change: None } + Self { + id: id.into(), + checked, + on_change: None, + } } pub fn on_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self { @@ -1140,7 +1385,11 @@ pub struct Tabs { } impl Tabs { - pub fn new(id: impl Into, items: impl IntoIterator>, selected: usize) -> Self { + pub fn new( + id: impl Into, + items: impl IntoIterator>, + selected: usize, + ) -> Self { Self { id: id.into(), items: items.into_iter().map(Into::into).collect(), @@ -1177,8 +1426,16 @@ impl RenderOnce for Tabs { .rounded(px(5.)) .text_size(px(12.)) .cursor_pointer() - .bg(if active { t.background } else { crate::alpha(t.background, 0.) }) - .text_color(if active { t.foreground } else { t.muted_foreground }) + .bg(if active { + t.background + } else { + crate::alpha(t.background, 0.) + }) + .text_color(if active { + t.foreground + } else { + t.muted_foreground + }) .child(label); if let Some(cb) = cb { tab = tab.on_click(move |_, window, cx| cb(i, window, cx)); @@ -1201,7 +1458,10 @@ pub struct Table { impl Table { pub fn new(id: impl Into) -> Self { - Self { id: id.into(), children: Vec::new() } + Self { + id: id.into(), + children: Vec::new(), + } } pub fn header(mut self, header: TableHeader) -> Self { @@ -1227,7 +1487,12 @@ impl Table { impl RenderOnce for Table { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().id(self.id).flex().flex_col().w_full().children(self.children) + div() + .id(self.id) + .flex() + .flex_col() + .w_full() + .children(self.children) } } @@ -1238,7 +1503,9 @@ pub struct TableHeader { impl TableHeader { pub fn new() -> Self { - Self { children: Vec::new() } + Self { + children: Vec::new(), + } } pub fn row(mut self, row: TableRow) -> Self { @@ -1271,7 +1538,9 @@ pub struct TableBody { impl TableBody { pub fn new() -> Self { - Self { children: Vec::new() } + Self { + children: Vec::new(), + } } pub fn row(mut self, row: TableRow) -> Self { @@ -1304,7 +1573,9 @@ pub struct TableFooter { impl TableFooter { pub fn new() -> Self { - Self { children: Vec::new() } + Self { + children: Vec::new(), + } } pub fn row(mut self, row: TableRow) -> Self { @@ -1338,7 +1609,10 @@ pub struct TableRow { impl TableRow { pub fn new() -> Self { - Self { children: Vec::new(), on_click: None } + Self { + children: Vec::new(), + on_click: None, + } } pub fn children(mut self, items: I) -> Self @@ -1346,7 +1620,8 @@ impl TableRow { I: IntoIterator, I::Item: IntoElement, { - self.children.extend(items.into_iter().map(IntoElement::into_any_element)); + self.children + .extend(items.into_iter().map(IntoElement::into_any_element)); self } @@ -1380,9 +1655,11 @@ impl RenderOnce for TableRow { .gap(px(8.)) .children(self.children); if let Some(cb) = self.on_click { - d = d.cursor_pointer().on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { - cb(&ClickEvent::default(), window, cx); - }); + d = d + .cursor_pointer() + .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { + cb(&ClickEvent::default(), window, cx); + }); } d } @@ -1396,7 +1673,10 @@ pub struct TableHead { impl TableHead { pub fn new(content: impl IntoElement) -> Self { - Self { content: content.into_any_element(), align_right: false } + Self { + content: content.into_any_element(), + align_right: false, + } } pub fn right(mut self) -> Self { @@ -1432,7 +1712,11 @@ pub struct TableCell { impl TableCell { pub fn new(content: impl IntoElement) -> Self { - Self { content: content.into_any_element(), align_right: false, span_cols: 1 } + Self { + content: content.into_any_element(), + align_right: false, + span_cols: 1, + } } pub fn right(mut self) -> Self { @@ -1448,7 +1732,13 @@ impl TableCell { impl RenderOnce for TableCell { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - let mut d = div().flex().flex_1().min_w_0().overflow_hidden().text_size(px(12.)).child(self.content); + let mut d = div() + .flex() + .flex_1() + .min_w_0() + .overflow_hidden() + .text_size(px(12.)) + .child(self.content); if self.align_right { d = d.justify_end(); } @@ -1470,7 +1760,12 @@ pub struct ScrollArea { impl ScrollArea { pub fn new(id: impl Into) -> Self { - Self { id: id.into(), height: None, horizontal_scroll: false, children: Vec::new() } + Self { + id: id.into(), + height: None, + horizontal_scroll: false, + children: Vec::new(), + } } pub fn h(mut self, h: Pixels) -> Self { @@ -1520,11 +1815,21 @@ pub struct ResizablePanelGroup { impl ResizablePanelGroup { pub fn new(id: impl Into) -> Self { - Self { id: id.into(), vertical_layout: false, full: false, children: Vec::new() } + Self { + id: id.into(), + vertical_layout: false, + full: false, + children: Vec::new(), + } } pub fn vertical(id: impl Into) -> Self { - Self { id: id.into(), vertical_layout: true, full: false, children: Vec::new() } + Self { + id: id.into(), + vertical_layout: true, + full: false, + children: Vec::new(), + } } pub fn size_full(mut self) -> Self { @@ -1569,7 +1874,10 @@ pub struct ResizablePanel { impl ResizablePanel { pub fn new() -> Self { - Self { children: Vec::new(), default_pct: 50.0 } + Self { + children: Vec::new(), + default_pct: 50.0, + } } pub fn default_size(mut self, pct: f32) -> Self { @@ -1595,7 +1903,13 @@ impl Default for ResizablePanel { impl RenderOnce for ResizablePanel { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().flex().flex_col().flex_1().min_w_0().min_h_0().children(self.children) + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .min_h_0() + .children(self.children) } } @@ -1633,7 +1947,9 @@ pub struct MessageScrollerHandle { impl MessageScrollerHandle { pub fn new() -> Self { - Self { scroll: gpui::ScrollHandle::new() } + Self { + scroll: gpui::ScrollHandle::new(), + } } pub fn scrollable(&self) -> ScrollableState { @@ -1653,7 +1969,10 @@ pub struct MessageScrollerItem { impl MessageScrollerItem { pub fn new(content: impl IntoElement) -> Self { - Self { content: content.into_any_element(), message_id: None } + Self { + content: content.into_any_element(), + message_id: None, + } } pub fn message_id(mut self, id: impl Into) -> Self { @@ -1664,7 +1983,12 @@ impl MessageScrollerItem { impl RenderOnce for MessageScrollerItem { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().w_full().child(self.content) + div() + .flex() + .flex_col() + .w_full() + .min_w_0() + .child(self.content) } } @@ -1677,7 +2001,11 @@ pub struct MessageScroller { impl MessageScroller { pub fn new(id: impl Into, handle: &MessageScrollerHandle) -> Self { - Self { id: id.into(), handle: handle.scroll.clone(), items: Vec::new() } + Self { + id: id.into(), + handle: handle.scroll.clone(), + items: Vec::new(), + } } pub fn auto_scroll(self, _auto: bool) -> Self { @@ -1718,6 +2046,7 @@ impl RenderOnce for MessageScroller { .min_w_0() .min_h_0() .overflow_y_scroll() + .overflow_x_hidden() .children(self.items) } } @@ -1762,11 +2091,25 @@ pub struct MenuItem { impl MenuItem { pub fn new(label: impl Into) -> Self { - Self { label: label.into(), icon: None, shortcut: None, checked: false, destructive: false, on_select: None } + Self { + label: label.into(), + icon: None, + shortcut: None, + checked: false, + destructive: false, + on_select: None, + } } pub fn radio(label: impl Into) -> Self { - Self { label: label.into(), icon: None, shortcut: None, checked: false, destructive: false, on_select: None } + Self { + label: label.into(), + icon: None, + shortcut: None, + checked: false, + destructive: false, + on_select: None, + } } pub fn icon(mut self, icon: impl AsRef) -> Self { @@ -1793,7 +2136,11 @@ impl MenuItem { impl RenderOnce for MenuItem { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let fg = if self.destructive { t.destructive } else { t.popover_foreground }; + let fg = if self.destructive { + t.destructive + } else { + t.popover_foreground + }; let mut d = div() .flex() .items_center() @@ -1812,7 +2159,12 @@ impl RenderOnce for MenuItem { } d = d.child(div().flex_1().child(self.label)); if let Some(sc) = self.shortcut { - d = d.child(div().text_size(px(11.)).text_color(t.muted_foreground).child(sc)); + d = d.child( + div() + .text_size(px(11.)) + .text_color(t.muted_foreground) + .child(sc), + ); } if let Some(cb) = self.on_select { d.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| cb(window, cx)) @@ -1830,7 +2182,10 @@ pub struct MenuContent { impl MenuContent { pub fn new() -> Self { - Self { width_px: px(160.), items: Vec::new() } + Self { + width_px: px(160.), + items: Vec::new(), + } } pub fn width(mut self, w: Pixels) -> Self { @@ -1843,7 +2198,14 @@ impl MenuContent { } pub fn label(mut self, text: impl Into) -> Self { - self.items.push(div().px(px(10.)).py(px(4.)).text_size(px(11.)).child(text.into()).into_any_element()); + self.items.push( + div() + .px(px(10.)) + .py(px(4.)) + .text_size(px(11.)) + .child(text.into()) + .into_any_element(), + ); self } @@ -1869,7 +2231,8 @@ impl MenuContent { } pub fn separator(mut self) -> Self { - self.items.push(div().h(px(1.)).my(px(4.)).into_any_element()); + self.items + .push(div().h(px(1.)).my(px(4.)).into_any_element()); self } } @@ -1900,13 +2263,18 @@ impl RenderOnce for MenuContent { pub struct DropdownMenu { id: ElementId, trigger: Option, - _menu: MenuContent, + menu: MenuContent, _align: MenuAlign, } impl DropdownMenu { pub fn new(id: impl Into, menu: MenuContent) -> Self { - Self { id: id.into(), trigger: None, _menu: menu, _align: MenuAlign::Start } + Self { + id: id.into(), + trigger: None, + menu, + _align: MenuAlign::Start, + } } pub fn align(mut self, align: MenuAlign) -> Self { @@ -1921,22 +2289,54 @@ impl DropdownMenu { } impl RenderOnce for DropdownMenu { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().id(self.id).flex().children(self.trigger) + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let open_state = window.use_keyed_state(crate::key(&self.id, "open"), cx, |_, _| false); + let is_open = *open_state.read(cx); + let toggle = open_state.clone(); + let close = open_state.clone(); + let mut root = div() + .id(self.id) + .relative() + .flex() + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + toggle.update(cx, |o, _| *o = !*o); + }) + .children(self.trigger); + if is_open { + root = root.child( + gpui::deferred( + gpui::anchored().snap_to_window().child( + div() + .mt(px(4.)) + .on_mouse_down_out(move |_, _, cx| { + close.update(cx, |o, _| *o = false); + }) + .child(self.menu), + ), + ) + .with_priority(10), + ); + } + root } } #[derive(IntoElement)] pub struct ContextMenu { id: ElementId, - _menu: MenuContent, + menu: MenuContent, children: Vec, full: bool, } impl ContextMenu { pub fn new(id: impl Into, menu: MenuContent) -> Self { - Self { id: id.into(), _menu: menu, children: Vec::new(), full: false } + Self { + id: id.into(), + menu, + children: Vec::new(), + full: false, + } } pub fn size_full(mut self) -> Self { @@ -1951,36 +2351,64 @@ impl ContextMenu { } impl RenderOnce for ContextMenu { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - let mut d = div().id(self.id).flex().flex_col(); + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let pos_state = window.use_keyed_state(crate::key(&self.id, "pos"), cx, |_, _| { + Option::>::None + }); + let pos = *pos_state.read(cx); + let open_pos = pos_state.clone(); + let close_pos = pos_state.clone(); + let mut d = div().id(self.id).flex().flex_col().on_mouse_down( + gpui::MouseButton::Right, + move |ev, _, cx| { + open_pos.update(cx, |p, _| *p = Some(ev.position)); + }, + ); if self.full { d = d.size_full(); } - d.children(self.children) + d = d.children(self.children); + if let Some(at) = pos { + d = d.child( + gpui::deferred( + gpui::anchored().position(at).snap_to_window().child( + div() + .on_mouse_down_out(move |_, _, cx| { + close_pos.update(cx, |p, _| *p = None); + }) + .child(self.menu), + ), + ) + .with_priority(10), + ); + } + d } } #[derive(IntoElement)] pub struct Popover { id: ElementId, - _open: bool, + open: bool, trigger: Option, - _content: Option, + content: Option, _side: OverlaySide, _align: OverlayAlign, - _width: Option, + width: Option, + on_close: Option>, } impl Popover { pub fn new(id: impl Into, open: bool) -> Self { Self { id: id.into(), - _open: open, + open, trigger: None, - _content: None, + content: None, _side: OverlaySide::Bottom, _align: OverlayAlign::Start, - _width: None, + width: None, + on_close: None, } } @@ -1989,7 +2417,8 @@ impl Popover { self } - pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); self } @@ -2004,23 +2433,45 @@ impl Popover { } pub fn width(mut self, width: Pixels) -> Self { - self._width = Some(width); + self.width = Some(width); self } pub fn content(mut self, content: impl IntoElement) -> Self { - self._content = Some(content.into_any_element()); + self.content = Some(content.into_any_element()); self } pub fn child(mut self, content: impl IntoElement) -> Self { - self._content = Some(content.into_any_element()); + self.content = Some(content.into_any_element()); self } } impl RenderOnce for Popover { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div().id(self.id).flex().children(self.trigger) + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let mut d = div().id(self.id).relative().flex().children(self.trigger); + if self.open + && let Some(body) = self.content + { + let mut panel = div() + .mt(px(4.)) + .rounded(px(10.)) + .bg(t.popover) + .border_1() + .border_color(t.border) + .child(body); + if let Some(w) = self.width { + panel = panel.w(w); + } + if let Some(on_close) = self.on_close { + panel = panel.on_mouse_down_out(move |_, window, cx| on_close(window, cx)); + } + d = d.child( + gpui::deferred(gpui::anchored().snap_to_window().child(panel)).with_priority(10), + ); + } + d } } diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index ea2b1e3..12186d6 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -10,6 +10,10 @@ pub struct Submitted(pub String); #[derive(Clone, Debug)] pub struct Changed(pub String); +fn read_paste(cx: &mut gpui::App) -> Option { + cx.read_from_clipboard().and_then(|item| item.text()) +} + pub struct TextInput { pub placeholder: SharedString, pub value: String, @@ -19,7 +23,11 @@ pub struct TextInput { } impl TextInput { - pub fn new(placeholder: impl Into, _window: &mut Window, cx: &mut Context) -> Self { + pub fn new( + placeholder: impl Into, + _window: &mut Window, + cx: &mut Context, + ) -> Self { Self { placeholder: placeholder.into(), value: String::new(), @@ -53,6 +61,16 @@ impl TextInput { fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; + let paste = + (ks.modifiers.control || ks.modifiers.platform) && ks.key.eq_ignore_ascii_case("v"); + if paste { + if let Some(pasted) = read_paste(cx) { + self.value.push_str(&pasted.replace(['\r', '\n'], "")); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } if ks.key == "enter" { cx.emit(Submitted(self.value.clone())); return; @@ -64,7 +82,9 @@ impl TextInput { } return; } - if !ks.modifiers.control && !ks.modifiers.platform && !ks.modifiers.alt + if !ks.modifiers.control + && !ks.modifiers.platform + && !ks.modifiers.alt && let Some(ch) = &ks.key_char { self.value.push_str(ch); @@ -94,7 +114,11 @@ impl Render for TextInput { } else { self.value.clone().into() }; - let color = if self.value.is_empty() { t.muted_foreground } else { t.foreground }; + let color = if self.value.is_empty() { + t.muted_foreground + } else { + t.foreground + }; let mut el = div() .track_focus(&self.focus) .w_full() @@ -103,9 +127,12 @@ impl Render for TextInput { .items_center() .text_size(px(13.)) .text_color(color) - .on_mouse_down(MouseButton::Left, cx.listener(|this, _: &MouseDownEvent, window, _cx| { - this.focus.focus(window); - })) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, window, _cx| { + this.focus.focus(window); + }), + ) .on_key_down(cx.listener(Self::on_key_down)) .child(display); if !self.bare { @@ -132,7 +159,11 @@ pub struct Textarea { } impl Textarea { - pub fn new(placeholder: impl Into, _window: &mut Window, cx: &mut Context) -> Self { + pub fn new( + placeholder: impl Into, + _window: &mut Window, + cx: &mut Context, + ) -> Self { Self { placeholder: placeholder.into(), value: String::new(), @@ -168,6 +199,16 @@ impl Textarea { fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; + let paste = + (ks.modifiers.control || ks.modifiers.platform) && ks.key.eq_ignore_ascii_case("v"); + if paste { + if let Some(pasted) = read_paste(cx) { + self.value.push_str(&pasted.replace("\r\n", "\n")); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } if ks.key == "enter" { if self.submit_on_enter && !ks.modifiers.shift { cx.emit(Submitted(self.value.clone())); @@ -185,7 +226,9 @@ impl Textarea { } return; } - if !ks.modifiers.control && !ks.modifiers.platform && !ks.modifiers.alt + if !ks.modifiers.control + && !ks.modifiers.platform + && !ks.modifiers.alt && let Some(ch) = &ks.key_char { self.value.push_str(ch); @@ -213,7 +256,11 @@ impl Render for Textarea { } else { self.value.clone().into() }; - let color = if self.value.is_empty() { t.muted_foreground } else { t.foreground }; + let color = if self.value.is_empty() { + t.muted_foreground + } else { + t.foreground + }; let mut el = div() .track_focus(&self.focus) .w_full() @@ -222,9 +269,12 @@ impl Render for Textarea { .items_start() .text_size(px(13.)) .text_color(color) - .on_mouse_down(MouseButton::Left, cx.listener(|this, _: &MouseDownEvent, window, _cx| { - this.focus.focus(window); - })) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, window, _cx| { + this.focus.focus(window); + }), + ) .on_key_down(cx.listener(Self::on_key_down)) .child(display); if let Some(max_h) = self.max_height { diff --git a/vendor/mantis-ui/src/theme.rs b/vendor/mantis-ui/src/theme.rs index 8468507..6a94017 100644 --- a/vendor/mantis-ui/src/theme.rs +++ b/vendor/mantis-ui/src/theme.rs @@ -105,7 +105,9 @@ impl Theme { } pub fn of(cx: &App) -> Theme { - cx.try_global::().copied().unwrap_or_else(Theme::dark) + cx.try_global::() + .copied() + .unwrap_or_else(Theme::dark) } pub fn radius_3xl(&self) -> gpui::Pixels { @@ -149,12 +151,31 @@ pub fn alpha(mut c: Hsla, a: f32) -> Hsla { pub fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla { let t = t.clamp(0.0, 1.0); let inv = 1.0 - t; - hsla( - a.h * inv + b.h * t, - a.s * inv + b.s * t, - a.l * inv + b.l * t, - a.a * inv + b.a * t, - ) + let ra = a.to_rgb(); + let rb = b.to_rgb(); + gpui::Rgba { + r: ra.r * inv + rb.r * t, + g: ra.g * inv + rb.g * t, + b: ra.b * inv + rb.b * t, + a: ra.a * inv + rb.a * t, + } + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mix_with_white_preserves_blue_hue() { + let blue = hsla(212. / 360., 0.92, 0.60, 1.0); + let mixed = mix(blue, gpui::white(), 0.22); + let rgb = mixed.to_rgb(); + assert!( + rgb.b > rgb.r && rgb.b > rgb.g, + "expected blue-dominant RGB, got {rgb:?}" + ); + } } pub fn blend(a: Hsla, b: Hsla, t: f32) -> Hsla { diff --git a/vendor/mantis-ui/src/toast.rs b/vendor/mantis-ui/src/toast.rs index 317ab9f..e6d501a 100644 --- a/vendor/mantis-ui/src/toast.rs +++ b/vendor/mantis-ui/src/toast.rs @@ -1,5 +1,12 @@ -use gpui::{App, Global, IntoElement, ParentElement, SharedString, Styled, div, px}; +use gpui::{ + App, ClickEvent, Global, InteractiveElement, IntoElement, ParentElement, SharedString, + StatefulInteractiveElement, Styled, div, px, +}; use std::collections::VecDeque; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +const TOAST_TTL: Duration = Duration::from_secs(5); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ToastKind { @@ -10,12 +17,14 @@ pub enum ToastKind { Loading, } -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ToastItem { pub id: u64, pub kind: ToastKind, pub title: SharedString, pub description: Option, + pub action: Option<(SharedString, Rc)>, + pub created_at: Instant, } #[derive(Default)] @@ -37,27 +46,53 @@ pub struct Toast { kind: ToastKind, title: SharedString, description: Option, + action: Option<(SharedString, Rc)>, } impl Toast { pub fn success(title: impl Into) -> Self { - Self { kind: ToastKind::Success, title: title.into(), description: None } + Self { + kind: ToastKind::Success, + title: title.into(), + description: None, + action: None, + } } pub fn warning(title: impl Into) -> Self { - Self { kind: ToastKind::Warning, title: title.into(), description: None } + Self { + kind: ToastKind::Warning, + title: title.into(), + description: None, + action: None, + } } pub fn error(title: impl Into) -> Self { - Self { kind: ToastKind::Error, title: title.into(), description: None } + Self { + kind: ToastKind::Error, + title: title.into(), + description: None, + action: None, + } } pub fn loading(title: impl Into) -> Self { - Self { kind: ToastKind::Loading, title: title.into(), description: None } + Self { + kind: ToastKind::Loading, + title: title.into(), + description: None, + action: None, + } } pub fn info(title: impl Into) -> Self { - Self { kind: ToastKind::Info, title: title.into(), description: None } + Self { + kind: ToastKind::Info, + title: title.into(), + description: None, + action: None, + } } pub fn description(mut self, desc: impl Into) -> Self { @@ -65,7 +100,12 @@ impl Toast { self } - pub fn action(self, _label: impl Into, _f: impl Fn(&gpui::ClickEvent, &mut gpui::App) + 'static) -> Self { + pub fn action( + mut self, + label: impl Into, + f: impl Fn(&ClickEvent, &mut App) + 'static, + ) -> Self { + self.action = Some((label.into(), Rc::new(f))); self } @@ -79,6 +119,8 @@ impl Toast { kind: self.kind, title: self.title, description: self.description, + action: self.action, + created_at: Instant::now(), }); while state.items.len() > 5 { state.items.pop_front(); @@ -93,6 +135,8 @@ impl Toast { existing.kind = self.kind; existing.title = self.title; existing.description = self.description; + existing.action = self.action; + existing.created_at = Instant::now(); return; } let _ = self.show(cx); @@ -101,14 +145,26 @@ impl Toast { pub fn dismiss_toast(id: u64, cx: &mut App) { if cx.try_global::().is_some() { - cx.global_mut::().items.retain(|item| item.id != id); + cx.global_mut::() + .items + .retain(|item| item.id != id); } } pub fn toaster(cx: &App) -> gpui::AnyElement { + let now = Instant::now(); let items: Vec = cx .try_global::() - .map(|s| s.items.iter().cloned().collect()) + .map(|s| { + s.items + .iter() + .filter(|item| { + item.kind == ToastKind::Loading + || now.duration_since(item.created_at) < TOAST_TTL + }) + .cloned() + .collect() + }) .unwrap_or_default(); if items.is_empty() { return div().into_any_element(); @@ -127,10 +183,31 @@ pub fn toaster(cx: &App) -> gpui::AnyElement { ToastKind::Error => t.destructive, _ => t.border, }; + let id = item.id; + let header = div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .child( + div() + .font_weight(gpui::FontWeight::MEDIUM) + .child(item.title), + ) + .child( + div() + .id(("toast-close", id)) + .px(px(4.)) + .text_size(px(11.)) + .text_color(t.muted_foreground) + .cursor_pointer() + .on_click(move |_, _, cx| dismiss_toast(id, cx)) + .child("×"), + ); let mut card = div() .flex() .flex_col() - .gap(px(2.)) + .gap(px(4.)) .p(px(12.)) .rounded(px(10.)) .bg(t.card) @@ -138,9 +215,32 @@ pub fn toaster(cx: &App) -> gpui::AnyElement { .border_color(border) .text_size(px(12.5)) .text_color(t.card_foreground) - .child(div().font_weight(gpui::FontWeight::MEDIUM).child(item.title)); + .child(header); if let Some(desc) = item.description { - card = card.child(div().text_size(px(11.5)).text_color(t.muted_foreground).child(desc)); + card = card.child( + div() + .text_size(px(11.5)) + .text_color(t.muted_foreground) + .child(desc), + ); + } + if let Some((label, cb)) = item.action { + card = card.child( + div().flex().child( + div() + .id(("toast-act", id)) + .mt(px(4.)) + .px(px(8.)) + .py(px(3.)) + .rounded(px(5.)) + .bg(t.secondary) + .text_size(px(11.5)) + .text_color(t.secondary_foreground) + .cursor_pointer() + .on_click(move |ev, _, cx| cb(ev, cx)) + .child(label), + ), + ); } stack = stack.child(card); } From 15f644691215ed8642bf2938ccc849997c6ab73f Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:50:45 -0500 Subject: [PATCH 04/16] fix: address all 15 Loopy review #2 findings and CI timeout --- .github/workflows/ci.yml | 4 +- crates/mantis-agent/src/codex.rs | 3 +- crates/mantis-agent/src/harness.rs | 18 +++- crates/mantis-agent/src/models.rs | 10 ++- crates/mantis-agent/src/muse.rs | 7 +- crates/mantis-app/src/snapshot.rs | 132 ++++++++++++++++++++++++----- vendor/mantis-ui/src/anim.rs | 34 +++++++- vendor/mantis-ui/src/assets.rs | 24 ++++++ vendor/mantis-ui/src/components.rs | 89 +++++++++++++++---- vendor/mantis-ui/src/input.rs | 33 ++++---- vendor/mantis-ui/src/theme.rs | 5 ++ 11 files changed, 294 insertions(+), 65 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ed3b59..8a9ce1c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - - run: rustfmt --edition 2024 --check crates/mantis-core/src/paths.rs vendor/mantis-ui/src/*.rs + - run: rustfmt --edition 2024 --check crates/mantis-core/src/paths.rs crates/mantis-app/src/snapshot.rs vendor/mantis-ui/src/*.rs check: strategy: @@ -34,7 +34,7 @@ jobs: matrix: os: [windows-latest, macos-latest] runs-on: ${{ matrix.os }} - timeout-minutes: 45 + timeout-minutes: 90 steps: - uses: actions/checkout@v4 with: diff --git a/crates/mantis-agent/src/codex.rs b/crates/mantis-agent/src/codex.rs index ca86094..23f975a 100644 --- a/crates/mantis-agent/src/codex.rs +++ b/crates/mantis-agent/src/codex.rs @@ -15,7 +15,6 @@ use crate::{AgentEvent, Emit, ModelChoice, Research, SYSTEM, Session, Steering, use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map, Value, json}; use std::path::{Path, PathBuf}; -use std::process::Command; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; @@ -40,7 +39,7 @@ impl Codex { /// An app-server, initialized. fn start(program: &Path) -> Result { - let mut command = Command::new(program); + let mut command = crate::harness::command_for(program); command .arg("app-server") .current_dir(crate::harness::workdir()?) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index baf2011..80937ac 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -34,6 +34,22 @@ pub fn find_claude() -> Option { crate::models::find_program("claude", "MANTIS_CLAUDE", "claude_path") } +/// Build a `Command` for an external agent binary, wrapping `.cmd`/`.bat` shims with +/// `cmd /C` on Windows so npm-installed agents start cleanly. +pub(crate) fn command_for(program: &Path) -> Command { + #[cfg(windows)] + { + if let Some(ext) = program.extension().and_then(|e| e.to_str()) + && (ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) + { + let mut cmd = Command::new("cmd"); + cmd.args(["/C", &program.to_string_lossy()]); + return cmd; + } + } + Command::new(program) +} + /// Run an agent program in the person's own home, where its sign-in is, even when Mantis /// itself runs with another (as a test build does): `MANTIS_AGENT_HOME`, or the older /// `MANTIS_CLAUDE_HOME`. @@ -203,7 +219,7 @@ impl Harness { let mcp = json!({"mcpServers": {"mantis": {"type": "http", "url": server.url, "headers": {"Authorization": format!("Bearer {}", server.token)}}}}); // Without an Exa key, searching is Claude Code's own. let (builtin, allowed) = if exa { ("Read", "mcp__mantis") } else { ("Read,WebSearch", "mcp__mantis WebSearch") }; - let mut command = Command::new(&self.claude); + let mut command = command_for(&self.claude); command .current_dir(&dir) .args(["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]) diff --git a/crates/mantis-agent/src/models.rs b/crates/mantis-agent/src/models.rs index c2f77b6..27acab8 100644 --- a/crates/mantis-agent/src/models.rs +++ b/crates/mantis-agent/src/models.rs @@ -101,12 +101,20 @@ pub fn find_program(name: &str, env: &str, key: &str) -> Option { if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) { places.push(local.join("Programs")); } - for dir in places { + for dir in &places { let cand = dir.join(format!("{name}.exe")); if crate::harness::runnable(&cand) { return Some(cand); } } + for dir in places { + for ext in ["cmd", "bat"] { + let cand = dir.join(format!("{name}.{ext}")); + if crate::harness::runnable(&cand) { + return Some(cand); + } + } + } None } #[cfg(not(windows))] diff --git a/crates/mantis-agent/src/muse.rs b/crates/mantis-agent/src/muse.rs index 7a62354..ed9820f 100644 --- a/crates/mantis-agent/src/muse.rs +++ b/crates/mantis-agent/src/muse.rs @@ -15,7 +15,6 @@ use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Value, json}; use std::collections::HashSet; use std::path::{Path, PathBuf}; -use std::process::Command; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; @@ -50,7 +49,7 @@ fn command_id() -> String { /// The person is signed in to Muse, or why not. Muse's protocol has no way to ask, so its /// command line is asked. fn signed_in(program: &Path) -> Result<()> { - let mut command = Command::new(program); + let mut command = crate::harness::command_for(program); command.args(["usage", "--json"]).env("MUSE_NO_AUTO_UPDATE", "1").env_remove("META_API_KEY"); crate::harness::agent_home(&mut command); let out = command.output().context("could not run Muse")?; @@ -66,7 +65,7 @@ fn signed_in(program: &Path) -> Result<()> { /// A host, initialized. `settings` are its `-c` settings. fn start(program: &Path, settings: &[(String, Value)]) -> Result { - let mut command = Command::new(program); + let mut command = crate::harness::command_for(program); // Muse loads the rules of a trusted workspace; this one is Mantis's own folder. command.args(["serve", "--trust-workspace", "--disable-shell", "--disable-write", "--disable-request-user-input"]); for (key, value) in settings { @@ -112,7 +111,7 @@ pub fn models(program: &Path) -> Result> { rpc.close(Duration::from_secs(2)); if listed["models"].as_array().is_none_or(|m| m.is_empty()) { // Its command line fetches the catalog itself, and names the models. - let mut command = Command::new(program); + let mut command = crate::harness::command_for(program); command.args(["exec", "--list-models"]).env("MUSE_NO_AUTO_UPDATE", "1").env_remove("META_API_KEY"); crate::harness::agent_home(&mut command); let out = command.output().context("could not run Muse")?; diff --git a/crates/mantis-app/src/snapshot.rs b/crates/mantis-app/src/snapshot.rs index 9e82503..7fc8a08 100644 --- a/crates/mantis-app/src/snapshot.rs +++ b/crates/mantis-app/src/snapshot.rs @@ -23,7 +23,10 @@ mod imp { use super::Press; use anyhow::{Context, Result, bail}; use core_graphics::geometry::{CGPoint, CGRect, CGSize}; - use core_graphics::window::{create_image, kCGWindowImageBestResolution, kCGWindowImageBoundsIgnoreFraming, kCGWindowListOptionIncludingWindow}; + use core_graphics::window::{ + create_image, kCGWindowImageBestResolution, kCGWindowImageBoundsIgnoreFraming, + kCGWindowListOptionIncludingWindow, + }; use gpui::Window; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use std::ffi::{CStr, c_char, c_void}; @@ -38,17 +41,32 @@ mod imp { fn ns_view(window: &Window) -> Option<*mut c_void> { let handle = HasWindowHandle::window_handle(window).ok()?; - let RawWindowHandle::AppKit(h) = handle.as_raw() else { return None }; + let RawWindowHandle::AppKit(h) = handle.as_raw() else { + return None; + }; Some(h.ns_view.as_ptr()) } pub fn draw_soon(window: &Window) { let Some(view) = ns_view(window) else { return }; unsafe { - let layer_of: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let perform: unsafe extern "C" fn(*mut c_void, *const c_void, *const c_void, *mut c_void, f64) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let layer_of: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let perform: unsafe extern "C" fn( + *mut c_void, + *const c_void, + *const c_void, + *mut c_void, + f64, + ) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); let layer = layer_of(view, sel(c"layer")); - perform(view, sel(c"performSelector:withObject:afterDelay:"), sel(c"displayLayer:"), layer, 0.0); + perform( + view, + sel(c"performSelector:withObject:afterDelay:"), + sel(c"displayLayer:"), + layer, + 0.0, + ); } } @@ -65,7 +83,19 @@ mod imp { } pub fn post_mouse(window: &Window, press: Press, x: f64, y: f64) { - type Make = unsafe extern "C" fn(*mut c_void, *const c_void, usize, NsPoint, usize, f64, isize, *mut c_void, isize, isize, f32) -> *mut c_void; + type Make = unsafe extern "C" fn( + *mut c_void, + *const c_void, + usize, + NsPoint, + usize, + f64, + isize, + *mut c_void, + isize, + isize, + f32, + ) -> *mut c_void; let Some(id) = window_id(window) else { return }; let y = f64::from(f32::from(window.viewport_size().height)) - y; let (kind, right, pressure): (usize, bool, f32) = match press { @@ -75,19 +105,42 @@ mod imp { Press::RightUp => (4, true, 0.0), }; unsafe { - let (event_class, app_class, info_class) = (objc_getClass(c"NSEvent".as_ptr()), objc_getClass(c"NSApplication".as_ptr()), objc_getClass(c"NSProcessInfo".as_ptr())); + let (event_class, app_class, info_class) = ( + objc_getClass(c"NSEvent".as_ptr()), + objc_getClass(c"NSApplication".as_ptr()), + objc_getClass(c"NSProcessInfo".as_ptr()), + ); if event_class.is_null() || app_class.is_null() || info_class.is_null() { return; } let make: Make = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let object: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let seconds: unsafe extern "C" fn(*mut c_void, *const c_void) -> f64 = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let wrap: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let post: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void, i8) = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let object: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let seconds: unsafe extern "C" fn(*mut c_void, *const c_void) -> f64 = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let wrap: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> *mut c_void = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let post: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void, i8) = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); let app = object(app_class, sel(c"sharedApplication")); - let uptime = seconds(object(info_class, sel(c"processInfo")), sel(c"systemUptime")); + let uptime = seconds( + object(info_class, sel(c"processInfo")), + sel(c"systemUptime"), + ); let selector = sel(c"mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:"); - let mut event = make(event_class, selector, kind, NsPoint { x, y }, 0, uptime, id as isize, std::ptr::null_mut(), 0, 1, pressure); + let mut event = make( + event_class, + selector, + kind, + NsPoint { x, y }, + 0, + uptime, + id as isize, + std::ptr::null_mut(), + 0, + 1, + pressure, + ); if event.is_null() { return; } @@ -113,8 +166,10 @@ mod imp { pub fn window_id(window: &Window) -> Option { let view = ns_view(window)?; unsafe { - let get_window: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); - let get_number: unsafe extern "C" fn(*mut c_void, *const c_void) -> isize = std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let get_window: unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + let get_number: unsafe extern "C" fn(*mut c_void, *const c_void) -> isize = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); let ns_window = get_window(view, sel(c"window")); if ns_window.is_null() { return None; @@ -124,11 +179,23 @@ mod imp { } pub fn capture(window_id: u32, path: &Path) -> Result<()> { - let null = CGRect::new(&CGPoint::new(f64::INFINITY, f64::INFINITY), &CGSize::new(0.0, 0.0)); - let image = create_image(null, kCGWindowListOptionIncludingWindow, window_id, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageBestResolution).context("the window server returned no image")?; + let null = CGRect::new( + &CGPoint::new(f64::INFINITY, f64::INFINITY), + &CGSize::new(0.0, 0.0), + ); + let image = create_image( + null, + kCGWindowListOptionIncludingWindow, + window_id, + kCGWindowImageBoundsIgnoreFraming | kCGWindowImageBestResolution, + ) + .context("the window server returned no image")?; let (w, h, stride) = (image.width(), image.height(), image.bytes_per_row()); if image.bits_per_pixel() != 32 || w == 0 || h == 0 { - bail!("unexpected image format: {} bits, {w}x{h}", image.bits_per_pixel()); + bail!( + "unexpected image format: {} bits, {w}x{h}", + image.bits_per_pixel() + ); } let data = image.data(); let bytes = data.bytes(); @@ -163,7 +230,9 @@ mod imp { fn hwnd_of(window: &Window) -> Option { let handle = HasWindowHandle::window_handle(window).ok()?; - let RawWindowHandle::Win32(h) = handle.as_raw() else { return None }; + let RawWindowHandle::Win32(h) = handle.as_raw() else { + return None; + }; Some(h.hwnd.get() as HWND) } @@ -198,7 +267,12 @@ mod imp { pub fn capture(window_id: u32, path: &Path) -> Result<()> { let hwnd = window_id as usize as HWND; - let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + let mut rect = RECT { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; if unsafe { GetClientRect(hwnd, &mut rect) } == 0 { bail!("GetClientRect failed"); } @@ -224,10 +298,24 @@ mod imp { biClrUsed: 0, biClrImportant: 0, }, - bmiColors: [windows_sys::Win32::Graphics::Gdi::RGBQUAD { rgbBlue: 0, rgbGreen: 0, rgbRed: 0, rgbReserved: 0 }], + bmiColors: [windows_sys::Win32::Graphics::Gdi::RGBQUAD { + rgbBlue: 0, + rgbGreen: 0, + rgbRed: 0, + rgbReserved: 0, + }], }; let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); - let hbm = unsafe { CreateDIBSection(hdc_mem, &bmi, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0) }; + let hbm = unsafe { + CreateDIBSection( + hdc_mem, + &bmi, + DIB_RGB_COLORS, + &mut bits, + std::ptr::null_mut(), + 0, + ) + }; if hbm.is_null() || bits.is_null() { unsafe { DeleteDC(hdc_mem); diff --git a/vendor/mantis-ui/src/anim.rs b/vendor/mantis-ui/src/anim.rs index 495b791..80ccd4f 100644 --- a/vendor/mantis-ui/src/anim.rs +++ b/vendor/mantis-ui/src/anim.rs @@ -2,7 +2,7 @@ use gpui::{ElementId, Window}; use std::cell::RefCell; use std::collections::HashMap; use std::hash::{Hash, Hasher}; -use std::time::Instant; +use std::time::{Duration, Instant}; #[derive(Clone, Copy, Debug)] pub struct Ease(pub f32, pub f32, pub f32, pub f32); @@ -15,7 +15,23 @@ impl Ease { pub fn at(self, t: f32) -> f32 { let t = t.clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) + if t <= 0.0 || t >= 1.0 { + return t; + } + let sample = |p1: f32, p2: f32, u: f32| -> f32 { + let inv = 1.0 - u; + 3.0 * inv * inv * u * p1 + 3.0 * inv * u * u * p2 + u * u * u + }; + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..14 { + let mid = 0.5 * (lo + hi); + if sample(self.0, self.2, mid) < t { + lo = mid; + } else { + hi = mid; + } + } + sample(self.1, self.3, 0.5 * (lo + hi)) } } @@ -46,6 +62,7 @@ struct TweenState { to: f32, current: f32, started: Instant, + last_seen: Instant, } thread_local! { @@ -58,6 +75,12 @@ fn id_hash(id: &ElementId) -> u64 { h.finish() } +fn prune_stale(map: &mut HashMap, now: Instant) { + if map.len() > 256 { + map.retain(|_, s| now.duration_since(s.last_seen) < Duration::from_secs(30)); + } +} + pub fn tween( id: impl Into, target: f32, @@ -72,18 +95,22 @@ pub fn tween( let now = Instant::now(); let (val, done) = TWEENS.with(|map| { let mut map = map.borrow_mut(); + prune_stale(&mut map, now); let entry = map.entry(k).or_insert(TweenState { from: target, to: target, current: target, started: now, + last_seen: now, }); + entry.last_seen = now; if (entry.to - target).abs() > f32::EPSILON { *entry = TweenState { from: entry.current, to: target, current: entry.current, started: now, + last_seen: now, }; } let elapsed_ms = now.duration_since(entry.started).as_secs_f32() * 1000.0; @@ -114,12 +141,15 @@ pub fn tween_from( let now = Instant::now(); let (val, done) = TWEENS.with(|map| { let mut map = map.borrow_mut(); + prune_stale(&mut map, now); let entry = map.entry(k).or_insert(TweenState { from, to, current: from, started: now, + last_seen: now, }); + entry.last_seen = now; let elapsed_ms = now.duration_since(entry.started).as_secs_f32() * 1000.0; let raw_t = (elapsed_ms / transition.duration_ms as f32).clamp(0.0, 1.0); let eased = transition.ease.at(raw_t); diff --git a/vendor/mantis-ui/src/assets.rs b/vendor/mantis-ui/src/assets.rs index ad717cb..87ba1c5 100644 --- a/vendor/mantis-ui/src/assets.rs +++ b/vendor/mantis-ui/src/assets.rs @@ -121,6 +121,30 @@ const ICONS: &[(&str, &[u8])] = &[ r#""# ), ), + ( + "icons/arrow-back-up.svg", + svg_icon!(r#""#), + ), + ( + "icons/download.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/ruler-measure.svg", + svg_icon!( + r#""# + ), + ), + ( + "icons/chevron-left.svg", + svg_icon!(r#""#), + ), + ( + "icons/chevron-up.svg", + svg_icon!(r#""#), + ), ]; impl AssetSource for Assets { diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index ec58679..bc21589 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1004,6 +1004,7 @@ pub struct Dialog { description: Option, body: Option, footer: Vec, + on_close: Option>, } impl Dialog { @@ -1016,6 +1017,7 @@ impl Dialog { description: None, body: None, footer: Vec::new(), + on_close: None, } } @@ -1024,7 +1026,8 @@ impl Dialog { self } - pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); self } @@ -1093,6 +1096,9 @@ impl RenderOnce for Dialog { if !self.footer.is_empty() { card = card.child(div().flex().justify_end().gap(px(8.)).children(self.footer)); } + if let Some(on_close) = self.on_close { + card = card.on_mouse_down_out(move |_, window, cx| on_close(window, cx)); + } div() .id(self.id) .absolute() @@ -1277,6 +1283,7 @@ impl RenderOnce for Slider { let bounds_state = window.use_keyed_state(crate::key(&self.id, "bounds"), cx, |_, _| { gpui::Bounds::::default() }); + let drag_state = window.use_keyed_state(crate::key(&self.id, "drag"), cx, |_, _| false); let bounds_for_canvas = bounds_state.clone(); let measure = gpui::canvas( move |bounds, _window, cx| { @@ -1315,16 +1322,46 @@ impl RenderOnce for Slider { && let Some(cb) = self.on_change { let (min, max, step) = (self.min, self.max, self.step); - el = el.on_mouse_down(gpui::MouseButton::Left, move |ev, window, cx| { + let drag_down = drag_state.clone(); + let drag_move = drag_state.clone(); + let drag_up = drag_state; + let bounds_move = bounds_state.clone(); + let cb_move = cb.clone(); + let compute = move |x: Pixels, cx: &App| { let b = *bounds_state.read(cx); let w = f32::from(b.size.width).max(1.0); - let rel = ((f32::from(ev.position.x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); + let rel = ((f32::from(x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); let mut val = min + rel * (max - min); if step > 0.0 { - val = (val / step).round() * step; + val = min + ((val - min) / step).round() * step; } - cb(val.clamp(min, max), window, cx); - }); + val.clamp(min, max) + }; + let compute_move = move |x: Pixels, cx: &App| { + let b = *bounds_move.read(cx); + let w = f32::from(b.size.width).max(1.0); + let rel = ((f32::from(x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); + let mut val = min + rel * (max - min); + if step > 0.0 { + val = min + ((val - min) / step).round() * step; + } + val.clamp(min, max) + }; + el = el + .on_mouse_down(gpui::MouseButton::Left, move |ev, window, cx| { + drag_down.update(cx, |d, _| *d = true); + let val = compute(ev.position.x, cx); + cb(val, window, cx); + }) + .on_mouse_move(move |ev, window, cx| { + if *drag_move.read(cx) && ev.pressed_button == Some(gpui::MouseButton::Left) { + let val = compute_move(ev.position.x, cx); + cb_move(val, window, cx); + } + }) + .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| { + drag_up.update(cx, |d, _| *d = false); + }); } el } @@ -1906,7 +1943,7 @@ impl RenderOnce for ResizablePanel { div() .flex() .flex_col() - .flex_1() + .h(gpui::relative((self.default_pct / 100.0).clamp(0.05, 0.95))) .min_w_0() .min_h_0() .children(self.children) @@ -1996,6 +2033,8 @@ impl RenderOnce for MessageScrollerItem { pub struct MessageScroller { id: ElementId, handle: gpui::ScrollHandle, + gap_px: Option, + pad: Option>, items: Vec, } @@ -2004,6 +2043,8 @@ impl MessageScroller { Self { id: id.into(), handle: handle.scroll.clone(), + gap_px: None, + pad: None, items: Vec::new(), } } @@ -2016,7 +2057,8 @@ impl MessageScroller { self } - pub fn gap(self, _px: Pixels) -> Self { + pub fn gap(mut self, px_gap: Pixels) -> Self { + self.gap_px = Some(px_gap); self } @@ -2024,7 +2066,8 @@ impl MessageScroller { self } - pub fn padding(self, _edges: gpui::Edges) -> Self { + pub fn padding(mut self, edges: gpui::Edges) -> Self { + self.pad = Some(edges); self } @@ -2036,7 +2079,7 @@ impl MessageScroller { impl RenderOnce for MessageScroller { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div() + let mut d = div() .id(self.id) .track_scroll(&self.handle) .flex() @@ -2046,8 +2089,14 @@ impl RenderOnce for MessageScroller { .min_w_0() .min_h_0() .overflow_y_scroll() - .overflow_x_hidden() - .children(self.items) + .overflow_x_hidden(); + if let Some(gap) = self.gap_px { + d = d.gap(gap); + } + if let Some(p) = self.pad { + d = d.pt(p.top).pb(p.bottom).pl(p.left).pr(p.right); + } + d.children(self.items) } } @@ -2293,7 +2342,8 @@ impl RenderOnce for DropdownMenu { let open_state = window.use_keyed_state(crate::key(&self.id, "open"), cx, |_, _| false); let is_open = *open_state.read(cx); let toggle = open_state.clone(); - let close = open_state.clone(); + let close_out = open_state.clone(); + let close_pick = open_state; let mut root = div() .id(self.id) .relative() @@ -2308,8 +2358,11 @@ impl RenderOnce for DropdownMenu { gpui::anchored().snap_to_window().child( div() .mt(px(4.)) + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + close_pick.update(cx, |o, _| *o = false); + }) .on_mouse_down_out(move |_, _, cx| { - close.update(cx, |o, _| *o = false); + close_out.update(cx, |o, _| *o = false); }) .child(self.menu), ), @@ -2357,7 +2410,8 @@ impl RenderOnce for ContextMenu { }); let pos = *pos_state.read(cx); let open_pos = pos_state.clone(); - let close_pos = pos_state.clone(); + let close_out = pos_state.clone(); + let close_pick = pos_state; let mut d = div().id(self.id).flex().flex_col().on_mouse_down( gpui::MouseButton::Right, move |ev, _, cx| { @@ -2373,8 +2427,11 @@ impl RenderOnce for ContextMenu { gpui::deferred( gpui::anchored().position(at).snap_to_window().child( div() + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + close_pick.update(cx, |p, _| *p = None); + }) .on_mouse_down_out(move |_, _, cx| { - close_pos.update(cx, |p, _| *p = None); + close_out.update(cx, |p, _| *p = None); }) .child(self.menu), ), diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 12186d6..21af2e7 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -1,7 +1,7 @@ use gpui::{ Context, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyDownEvent, - MouseButton, MouseDownEvent, ParentElement, Pixels, Render, SharedString, Styled, Window, div, - px, + MouseButton, MouseDownEvent, ParentElement, Pixels, Render, SharedString, + StatefulInteractiveElement, Styled, Window, div, px, }; #[derive(Clone, Debug)] @@ -14,6 +14,12 @@ fn read_paste(cx: &mut gpui::App) -> Option { cx.read_from_clipboard().and_then(|item| item.text()) } +fn is_printable(ks: &gpui::Keystroke) -> bool { + !ks.modifiers.platform + && ((!ks.modifiers.control && !ks.modifiers.alt) + || (ks.modifiers.control && ks.modifiers.alt)) +} + pub struct TextInput { pub placeholder: SharedString, pub value: String, @@ -47,7 +53,6 @@ impl TextInput { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); - cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -61,8 +66,9 @@ impl TextInput { fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; - let paste = - (ks.modifiers.control || ks.modifiers.platform) && ks.key.eq_ignore_ascii_case("v"); + let paste = (ks.modifiers.control || ks.modifiers.platform) + && !ks.modifiers.alt + && ks.key.eq_ignore_ascii_case("v"); if paste { if let Some(pasted) = read_paste(cx) { self.value.push_str(&pasted.replace(['\r', '\n'], "")); @@ -82,9 +88,7 @@ impl TextInput { } return; } - if !ks.modifiers.control - && !ks.modifiers.platform - && !ks.modifiers.alt + if is_printable(ks) && let Some(ch) = &ks.key_char { self.value.push_str(ch); @@ -185,7 +189,6 @@ impl Textarea { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); - cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -199,8 +202,9 @@ impl Textarea { fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; - let paste = - (ks.modifiers.control || ks.modifiers.platform) && ks.key.eq_ignore_ascii_case("v"); + let paste = (ks.modifiers.control || ks.modifiers.platform) + && !ks.modifiers.alt + && ks.key.eq_ignore_ascii_case("v"); if paste { if let Some(pasted) = read_paste(cx) { self.value.push_str(&pasted.replace("\r\n", "\n")); @@ -226,9 +230,7 @@ impl Textarea { } return; } - if !ks.modifiers.control - && !ks.modifiers.platform - && !ks.modifiers.alt + if is_printable(ks) && let Some(ch) = &ks.key_char { self.value.push_str(ch); @@ -262,6 +264,7 @@ impl Render for Textarea { t.foreground }; let mut el = div() + .id("textarea-scroll") .track_focus(&self.focus) .w_full() .min_h(self.min_height) @@ -278,7 +281,7 @@ impl Render for Textarea { .on_key_down(cx.listener(Self::on_key_down)) .child(display); if let Some(max_h) = self.max_height { - el = el.max_h(max_h); + el = el.max_h(max_h).overflow_y_scroll(); } if !self.bare { el = el diff --git a/vendor/mantis-ui/src/theme.rs b/vendor/mantis-ui/src/theme.rs index 6a94017..2f98a92 100644 --- a/vendor/mantis-ui/src/theme.rs +++ b/vendor/mantis-ui/src/theme.rs @@ -1,6 +1,11 @@ use gpui::{App, Global, Hsla, Styled, WindowAppearance, hsla}; +#[cfg(target_os = "macos")] +pub const FONT_MONO: &str = "Menlo"; +#[cfg(target_os = "windows")] pub const FONT_MONO: &str = "Consolas"; +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +pub const FONT_MONO: &str = "monospace"; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Mode { From 4e903c4732bb33c215d890b1da6cde1900a891d2 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:06:13 -0500 Subject: [PATCH 05/16] fix: address all 13 Loopy review #3 findings --- crates/mantis-agent/src/harness.rs | 28 ++- crates/mantis-agent/src/models.rs | 8 +- crates/mantis-app/src/workspace/form.rs | 14 +- crates/mantis-core/src/paths.rs | 2 +- vendor/mantis-ui/src/anim.rs | 14 ++ vendor/mantis-ui/src/components.rs | 40 +++- vendor/mantis-ui/src/input.rs | 238 +++++++++++++++++++++++- 7 files changed, 323 insertions(+), 21 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 80937ac..9833226 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -34,22 +34,44 @@ pub fn find_claude() -> Option { crate::models::find_program("claude", "MANTIS_CLAUDE", "claude_path") } -/// Build a `Command` for an external agent binary, wrapping `.cmd`/`.bat` shims with -/// `cmd /C` on Windows so npm-installed agents start cleanly. +/// Build a `Command` for an external agent binary. On Windows, npm `.cmd`/`.bat` shims +/// are resolved to `node.exe` + their JS entrypoint when possible so spaced/quoted +/// arguments pass directly via `CreateProcess` without `cmd.exe` re-parsing. pub(crate) fn command_for(program: &Path) -> Command { #[cfg(windows)] { if let Some(ext) = program.extension().and_then(|e| e.to_str()) && (ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) { + if let Some(cmd) = npm_node_command(program) { + return cmd; + } let mut cmd = Command::new("cmd"); - cmd.args(["/C", &program.to_string_lossy()]); + cmd.args(["/D", "/C", &program.to_string_lossy()]); return cmd; } } Command::new(program) } +#[cfg(windows)] +fn npm_node_command(shim: &Path) -> Option { + let dir = shim.parent()?; + let text = std::fs::read_to_string(shim).ok()?; + let idx = text.find("node_modules")?; + let rest = &text[idx..]; + let end = rest.find(['"', '\'', ' ', '\t', '\r', '\n']).unwrap_or(rest.len()); + let script = dir.join(rest[..end].replace('/', "\\")); + if !script.is_file() { + return None; + } + let node = dir.join("node.exe"); + let exe = if node.is_file() { node } else { PathBuf::from("node.exe") }; + let mut cmd = Command::new(exe); + cmd.arg(script); + Some(cmd) +} + /// Run an agent program in the person's own home, where its sign-in is, even when Mantis /// itself runs with another (as a test build does): `MANTIS_AGENT_HOME`, or the older /// `MANTIS_CLAUDE_HOME`. diff --git a/crates/mantis-agent/src/models.rs b/crates/mantis-agent/src/models.rs index 27acab8..75fec7e 100644 --- a/crates/mantis-agent/src/models.rs +++ b/crates/mantis-agent/src/models.rs @@ -101,14 +101,8 @@ pub fn find_program(name: &str, env: &str, key: &str) -> Option { if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) { places.push(local.join("Programs")); } - for dir in &places { - let cand = dir.join(format!("{name}.exe")); - if crate::harness::runnable(&cand) { - return Some(cand); - } - } for dir in places { - for ext in ["cmd", "bat"] { + for ext in ["exe", "cmd", "bat"] { let cand = dir.join(format!("{name}.{ext}")); if crate::harness::runnable(&cand) { return Some(cand); diff --git a/crates/mantis-app/src/workspace/form.rs b/crates/mantis-app/src/workspace/form.rs index 17a1445..be17e8b 100644 --- a/crates/mantis-app/src/workspace/form.rs +++ b/crates/mantis-app/src/workspace/form.rs @@ -234,8 +234,18 @@ impl Workspace { for (i, path) in self.form.files.iter().enumerate() { let folder = path.is_dir(); let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let home = mantis_core::paths::user_home().map(|p| p.display().to_string()).unwrap_or_default(); - let place = path.parent().map(|p| if home.is_empty() { p.display().to_string() } else { p.display().to_string().replace(&home, "~") }).unwrap_or_default(); + let home = mantis_core::paths::user_home(); + let place = path + .parent() + .map(|p| match &home { + Some(h) if !h.as_os_str().is_empty() => match p.strip_prefix(h) { + Ok(rel) if rel.as_os_str().is_empty() => "~".to_string(), + Ok(rel) => format!("~{}{}", std::path::MAIN_SEPARATOR, rel.display()), + Err(_) => p.display().to_string(), + }, + _ => p.display().to_string(), + }) + .unwrap_or_default(); list = list.child( div() .flex() diff --git a/crates/mantis-core/src/paths.rs b/crates/mantis-core/src/paths.rs index f3e83a5..637fb4b 100644 --- a/crates/mantis-core/src/paths.rs +++ b/crates/mantis-core/src/paths.rs @@ -22,7 +22,7 @@ pub fn app_data_dir() -> PathBuf { #[cfg(target_os = "macos")] { user_home() - .unwrap_or_default() + .unwrap_or_else(std::env::temp_dir) .join("Library/Application Support/Mantis") } #[cfg(target_os = "windows")] diff --git a/vendor/mantis-ui/src/anim.rs b/vendor/mantis-ui/src/anim.rs index 80ccd4f..b84f2c2 100644 --- a/vendor/mantis-ui/src/anim.rs +++ b/vendor/mantis-ui/src/anim.rs @@ -58,6 +58,7 @@ pub fn key(parent: &ElementId, suffix: &str) -> ElementId { #[derive(Clone, Copy)] struct TweenState { + orig_from: f32, from: f32, to: f32, current: f32, @@ -97,6 +98,7 @@ pub fn tween( let mut map = map.borrow_mut(); prune_stale(&mut map, now); let entry = map.entry(k).or_insert(TweenState { + orig_from: target, from: target, to: target, current: target, @@ -106,6 +108,7 @@ pub fn tween( entry.last_seen = now; if (entry.to - target).abs() > f32::EPSILON { *entry = TweenState { + orig_from: entry.current, from: entry.current, to: target, current: entry.current, @@ -143,6 +146,7 @@ pub fn tween_from( let mut map = map.borrow_mut(); prune_stale(&mut map, now); let entry = map.entry(k).or_insert(TweenState { + orig_from: from, from, to, current: from, @@ -150,6 +154,16 @@ pub fn tween_from( last_seen: now, }); entry.last_seen = now; + if (entry.orig_from - from).abs() > f32::EPSILON || (entry.to - to).abs() > f32::EPSILON { + *entry = TweenState { + orig_from: from, + from, + to, + current: from, + started: now, + last_seen: now, + }; + } let elapsed_ms = now.duration_since(entry.started).as_secs_f32() * 1000.0; let raw_t = (elapsed_ms / transition.duration_ms as f32).clamp(0.0, 1.0); let eased = transition.ease.at(raw_t); diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index bc21589..d711b87 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1324,7 +1324,8 @@ impl RenderOnce for Slider { let (min, max, step) = (self.min, self.max, self.step); let drag_down = drag_state.clone(); let drag_move = drag_state.clone(); - let drag_up = drag_state; + let drag_up = drag_state.clone(); + let drag_out = drag_state; let bounds_move = bounds_state.clone(); let cb_move = cb.clone(); let compute = move |x: Pixels, cx: &App| { @@ -1361,6 +1362,9 @@ impl RenderOnce for Slider { }) .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| { drag_up.update(cx, |d, _| *d = false); + }) + .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| { + drag_out.update(cx, |d, _| *d = false); }); } el @@ -1776,6 +1780,9 @@ impl RenderOnce for TableCell { .overflow_hidden() .text_size(px(12.)) .child(self.content); + if self.span_cols > 1 { + d.style().flex_grow = Some(self.span_cols as f32); + } if self.align_right { d = d.justify_end(); } @@ -1990,7 +1997,10 @@ impl MessageScrollerHandle { } pub fn scrollable(&self) -> ScrollableState { - ScrollableState { end: false } + let offset = self.scroll.offset(); + let max = self.scroll.max_offset(); + let end = (-offset.y) >= (max.height - px(4.0)); + ScrollableState { end } } pub fn scroll_to_end(&self, _animated: bool) { @@ -2033,6 +2043,7 @@ impl RenderOnce for MessageScrollerItem { pub struct MessageScroller { id: ElementId, handle: gpui::ScrollHandle, + auto: bool, gap_px: Option, pad: Option>, items: Vec, @@ -2043,13 +2054,15 @@ impl MessageScroller { Self { id: id.into(), handle: handle.scroll.clone(), + auto: false, gap_px: None, pad: None, items: Vec::new(), } } - pub fn auto_scroll(self, _auto: bool) -> Self { + pub fn auto_scroll(mut self, auto: bool) -> Self { + self.auto = auto; self } @@ -2079,6 +2092,9 @@ impl MessageScroller { impl RenderOnce for MessageScroller { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + if self.auto { + self.handle.scroll_to_bottom(); + } let mut d = div() .id(self.id) .track_scroll(&self.handle) @@ -2525,8 +2541,24 @@ impl RenderOnce for Popover { if let Some(on_close) = self.on_close { panel = panel.on_mouse_down_out(move |_, window, cx| on_close(window, cx)); } + let anchor_corner = match (self._side, self._align) { + (OverlaySide::Top, OverlayAlign::End) => gpui::Corner::BottomRight, + (OverlaySide::Top, _) => gpui::Corner::BottomLeft, + (OverlaySide::Bottom, OverlayAlign::End) => gpui::Corner::TopRight, + (OverlaySide::Bottom, _) => gpui::Corner::TopLeft, + (OverlaySide::Left, OverlayAlign::End) => gpui::Corner::BottomRight, + (OverlaySide::Left, _) => gpui::Corner::TopRight, + (OverlaySide::Right, OverlayAlign::End) => gpui::Corner::BottomLeft, + (OverlaySide::Right, _) => gpui::Corner::TopLeft, + }; d = d.child( - gpui::deferred(gpui::anchored().snap_to_window().child(panel)).with_priority(10), + gpui::deferred( + gpui::anchored() + .anchor(anchor_corner) + .snap_to_window() + .child(panel), + ) + .with_priority(10), ); } d diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 21af2e7..5a9da10 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -1,8 +1,10 @@ use gpui::{ - Context, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyDownEvent, - MouseButton, MouseDownEvent, ParentElement, Pixels, Render, SharedString, - StatefulInteractiveElement, Styled, Window, div, px, + Bounds, Context, ElementInputHandler, EntityInputHandler, EventEmitter, FocusHandle, Focusable, + InteractiveElement, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, + Pixels, Point, Render, ScrollHandle, SharedString, StatefulInteractiveElement, Styled, + UTF16Selection, Window, canvas, div, px, }; +use std::ops::Range; #[derive(Clone, Debug)] pub struct Submitted(pub String); @@ -20,6 +22,30 @@ fn is_printable(ks: &gpui::Keystroke) -> bool { || (ks.modifiers.control && ks.modifiers.alt)) } +fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +fn utf16_range_to_byte_range(s: &str, range: Range) -> Range { + let mut u16_pos = 0usize; + let mut start_b = s.len(); + let mut end_b = s.len(); + for (b_idx, ch) in s.char_indices() { + if u16_pos >= range.start && start_b == s.len() { + start_b = b_idx; + } + u16_pos += ch.len_utf16(); + if u16_pos >= range.end && end_b == s.len() { + end_b = b_idx + ch.len_utf8(); + break; + } + } + if range.start == 0 { + start_b = 0; + } + start_b.min(end_b)..end_b.max(start_b) +} + pub struct TextInput { pub placeholder: SharedString, pub value: String, @@ -71,7 +97,8 @@ impl TextInput { && ks.key.eq_ignore_ascii_case("v"); if paste { if let Some(pasted) = read_paste(cx) { - self.value.push_str(&pasted.replace(['\r', '\n'], "")); + let single_line = pasted.replace("\r\n", " ").replace(['\r', '\n'], " "); + self.value.push_str(&single_line); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -98,6 +125,91 @@ impl TextInput { } } +impl EntityInputHandler for TextInput { + fn text_for_range( + &mut self, + range: Range, + adjusted_range: &mut Option>, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let br = utf16_range_to_byte_range(&self.value, range.clone()); + *adjusted_range = Some(range); + Some(self.value[br].to_string()) + } + + fn selected_text_range( + &mut self, + _ignore_disabled_input: bool, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let len = utf16_len(&self.value); + Some(UTF16Selection { + range: len..len, + reversed: false, + }) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + None + } + + fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) {} + + fn replace_text_in_range( + &mut self, + range: Option>, + text: &str, + _window: &mut Window, + cx: &mut Context, + ) { + let clean = text.replace("\r\n", " ").replace(['\r', '\n'], " "); + if let Some(r) = range { + let br = utf16_range_to_byte_range(&self.value, r); + self.value.replace_range(br, &clean); + } else { + self.value.push_str(&clean); + } + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + + fn replace_and_mark_text_in_range( + &mut self, + range: Option>, + new_text: &str, + _new_selected_range: Option>, + window: &mut Window, + cx: &mut Context, + ) { + self.replace_text_in_range(range, new_text, window, cx); + } + + fn bounds_for_range( + &mut self, + _range_utf16: Range, + element_bounds: Bounds, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + Some(element_bounds) + } + + fn character_index_for_point( + &mut self, + _point: Point, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(utf16_len(&self.value)) + } +} + impl EventEmitter for TextInput {} impl EventEmitter for TextInput {} @@ -123,7 +235,18 @@ impl Render for TextInput { } else { t.foreground }; + let entity = cx.entity(); + let focus = self.focus.clone(); + let ime = canvas( + |_, _, _| {}, + move |bounds, _, window, cx| { + window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); + }, + ) + .absolute() + .inset_0(); let mut el = div() + .relative() .track_focus(&self.focus) .w_full() .min_h(px(28.)) @@ -138,6 +261,7 @@ impl Render for TextInput { }), ) .on_key_down(cx.listener(Self::on_key_down)) + .child(ime) .child(display); if !self.bare { el = el @@ -160,6 +284,7 @@ pub struct Textarea { pub min_height: Pixels, pub max_height: Option, focus: FocusHandle, + scroll: ScrollHandle, } impl Textarea { @@ -176,6 +301,7 @@ impl Textarea { min_height: px(64.), max_height: None, focus: cx.focus_handle(), + scroll: ScrollHandle::new(), } } @@ -189,6 +315,7 @@ impl Textarea { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); + self.scroll.scroll_to_bottom(); cx.notify(); } @@ -208,6 +335,7 @@ impl Textarea { if paste { if let Some(pasted) = read_paste(cx) { self.value.push_str(&pasted.replace("\r\n", "\n")); + self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -219,12 +347,14 @@ impl Textarea { return; } self.value.push('\n'); + self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); return; } if ks.key == "backspace" { if self.value.pop().is_some() { + self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -234,12 +364,99 @@ impl Textarea { && let Some(ch) = &ks.key_char { self.value.push_str(ch); + self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); } } } +impl EntityInputHandler for Textarea { + fn text_for_range( + &mut self, + range: Range, + adjusted_range: &mut Option>, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let br = utf16_range_to_byte_range(&self.value, range.clone()); + *adjusted_range = Some(range); + Some(self.value[br].to_string()) + } + + fn selected_text_range( + &mut self, + _ignore_disabled_input: bool, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let len = utf16_len(&self.value); + Some(UTF16Selection { + range: len..len, + reversed: false, + }) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + None + } + + fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) {} + + fn replace_text_in_range( + &mut self, + range: Option>, + text: &str, + _window: &mut Window, + cx: &mut Context, + ) { + let clean = text.replace("\r\n", "\n"); + if let Some(r) = range { + let br = utf16_range_to_byte_range(&self.value, r); + self.value.replace_range(br, &clean); + } else { + self.value.push_str(&clean); + } + self.scroll.scroll_to_bottom(); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + + fn replace_and_mark_text_in_range( + &mut self, + range: Option>, + new_text: &str, + _new_selected_range: Option>, + window: &mut Window, + cx: &mut Context, + ) { + self.replace_text_in_range(range, new_text, window, cx); + } + + fn bounds_for_range( + &mut self, + _range_utf16: Range, + element_bounds: Bounds, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + Some(element_bounds) + } + + fn character_index_for_point( + &mut self, + _point: Point, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(utf16_len(&self.value)) + } +} + impl EventEmitter for Textarea {} impl EventEmitter for Textarea {} @@ -263,8 +480,20 @@ impl Render for Textarea { } else { t.foreground }; + let entity = cx.entity(); + let focus = self.focus.clone(); + let ime = canvas( + |_, _, _| {}, + move |bounds, _, window, cx| { + window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); + }, + ) + .absolute() + .inset_0(); let mut el = div() .id("textarea-scroll") + .relative() + .track_scroll(&self.scroll) .track_focus(&self.focus) .w_full() .min_h(self.min_height) @@ -279,6 +508,7 @@ impl Render for Textarea { }), ) .on_key_down(cx.listener(Self::on_key_down)) + .child(ime) .child(display); if let Some(max_h) = self.max_height { el = el.max_h(max_h).overflow_y_scroll(); From 0ec5466897238b709013134fe3f193c76ce435da Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:53:57 -0500 Subject: [PATCH 06/16] fix: address Loopy review #4 (npm shim, IME/cursor editing, resizable split, menus/popovers) --- crates/mantis-agent/src/harness.rs | 393 ++++++++++++++++++++++++----- vendor/mantis-ui/src/components.rs | 261 ++++++++++++++++--- vendor/mantis-ui/src/input.rs | 211 ++++++++++++---- 3 files changed, 722 insertions(+), 143 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 9833226..75bd993 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -60,15 +60,28 @@ fn npm_node_command(shim: &Path) -> Option { let text = std::fs::read_to_string(shim).ok()?; let idx = text.find("node_modules")?; let rest = &text[idx..]; - let end = rest.find(['"', '\'', ' ', '\t', '\r', '\n']).unwrap_or(rest.len()); - let script = dir.join(rest[..end].replace('/', "\\")); - if !script.is_file() { + let end = rest + .find(['"', '\'', ' ', '\t', '\r', '\n']) + .unwrap_or(rest.len()); + let target = dir.join(rest[..end].replace('/', "\\")); + if !target.is_file() { + return None; + } + let ext = target.extension().and_then(|e| e.to_str()).unwrap_or(""); + if ext.eq_ignore_ascii_case("exe") { + return Some(Command::new(target)); + } + if !matches!(ext.to_ascii_lowercase().as_str(), "js" | "mjs" | "cjs") { return None; } let node = dir.join("node.exe"); - let exe = if node.is_file() { node } else { PathBuf::from("node.exe") }; + let exe = if node.is_file() { + node + } else { + PathBuf::from("node.exe") + }; let mut cmd = Command::new(exe); - cmd.arg(script); + cmd.arg(target); Some(cmd) } @@ -76,7 +89,9 @@ fn npm_node_command(shim: &Path) -> Option { /// itself runs with another (as a test build does): `MANTIS_AGENT_HOME`, or the older /// `MANTIS_CLAUDE_HOME`. pub(crate) fn agent_home(command: &mut Command) { - if let Some(home) = std::env::var_os("MANTIS_AGENT_HOME").or_else(|| std::env::var_os("MANTIS_CLAUDE_HOME")) { + if let Some(home) = + std::env::var_os("MANTIS_AGENT_HOME").or_else(|| std::env::var_os("MANTIS_CLAUDE_HOME")) + { command.env("HOME", &home); #[cfg(windows)] command.env("USERPROFILE", &home); @@ -87,7 +102,8 @@ pub(crate) fn runnable(path: &Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - path.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + path.metadata() + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) } #[cfg(not(unix))] { @@ -103,7 +119,11 @@ pub fn engine_setting() -> String { /// Claude Code, when it is installed and the agent is set to use it. pub fn claude_code() -> Option { - if engine_setting() == "api" { None } else { find_claude() } + if engine_setting() == "api" { + None + } else { + find_claude() + } } /// The folder Claude Code runs in for Mantis: where its sessions are filed and where pages @@ -144,7 +164,14 @@ struct Run { impl Harness { pub fn new(claude: PathBuf) -> Harness { - Harness { claude, session: uuid::Uuid::now_v7().to_string(), known: Some(false), earlier: Vec::new(), turns: 0, context: 0 } + Harness { + claude, + session: uuid::Uuid::now_v7().to_string(), + known: Some(false), + earlier: Vec::new(), + turns: 0, + context: 0, + } } /// Carry on the conversation with this id, which Claude Code may already have. @@ -184,13 +211,35 @@ impl crate::External for Harness { self.context } - fn run_turn(&mut self, user_text: &str, model: &ModelChoice, effort: &str, session: &Arc>, emit: &Emit, cancel: &Arc, steering: &Steering) -> Result<()> { + fn run_turn( + &mut self, + user_text: &str, + model: &ModelChoice, + effort: &str, + session: &Arc>, + emit: &Emit, + cancel: &Arc, + steering: &Steering, + ) -> Result<()> { cancel.store(false, Ordering::SeqCst); // Tried as Claude Code is believed to have it, then the other way if it says otherwise. let mut resume = self.known.unwrap_or(!self.earlier.is_empty()); for _ in 0..2 { - let prompt = if resume { user_text.to_string() } else { with_earlier(&self.earlier, user_text) }; - let run = self.run(&prompt, resume, model, effort, session, emit, cancel, Some(steering))?; + let prompt = if resume { + user_text.to_string() + } else { + with_earlier(&self.earlier, user_text) + }; + let run = self.run( + &prompt, + resume, + model, + effort, + session, + emit, + cancel, + Some(steering), + )?; if run.missing && resume { resume = false; continue; @@ -210,7 +259,14 @@ impl crate::External for Harness { } /// Have Claude Code summarize the conversation in place, as its /compact does. - fn compact(&mut self, model: &ModelChoice, effort: &str, session: &Arc>, emit: &Emit, cancel: &Arc) -> Result<()> { + fn compact( + &mut self, + model: &ModelChoice, + effort: &str, + session: &Arc>, + emit: &Emit, + cancel: &Arc, + ) -> Result<()> { if self.known == Some(false) && self.earlier.is_empty() { bail!("There is nothing to summarize yet"); } @@ -218,7 +274,9 @@ impl crate::External for Harness { emit(AgentEvent::Compacting); let run = self.run("/compact", true, model, effort, session, emit, cancel, None)?; if run.missing { - bail!("Claude Code has none of this conversation to summarize yet; it starts from what was said on the next turn"); + bail!( + "Claude Code has none of this conversation to summarize yet; it starts from what was said on the next turn" + ); } self.context = 0; finish(run, emit) @@ -226,31 +284,90 @@ impl crate::External for Harness { } impl Harness { - /// One run of `claude` on this conversation, with the board tools served for it. #[allow(clippy::too_many_arguments)] - fn run(&mut self, prompt: &str, resume: bool, model: &ModelChoice, effort: &str, session: &Arc>, emit: &Emit, cancel: &Arc, steering: Option<&Steering>) -> Result { + fn run( + &mut self, + prompt: &str, + resume: bool, + model: &ModelChoice, + effort: &str, + session: &Arc>, + emit: &Emit, + cancel: &Arc, + steering: Option<&Steering>, + ) -> Result { let dir = workdir()?; let exa = web::exa_key().is_some(); - let research = Research { key: None, model: model.label().to_string() }; - let server = McpServer::start(session.clone(), emit.clone(), research, dir.clone(), exa, crate::mcp::Pdfs::File(|path, title| format!("The pages ({title}) are saved as {}. Open that file with Read to see them as printed.", path.display())))?; + let research = Research { + key: None, + model: model.label().to_string(), + }; + let server = McpServer::start( + session.clone(), + emit.clone(), + research, + dir.clone(), + exa, + crate::mcp::Pdfs::File(|path, title| { + format!( + "The pages ({title}) are saved as {}. Open that file with Read to see them as printed.", + path.display() + ) + }), + )?; let system = { - let place = session.lock().map_err(|_| anyhow!("the design session is unavailable"))?.place.clone(); - format!("{SYSTEM}{}{HARNESS_NOTE}", tools::memory_block(place.as_ref())) + let place = session + .lock() + .map_err(|_| anyhow!("the design session is unavailable"))? + .place + .clone(); + format!( + "{SYSTEM}{}{HARNESS_NOTE}", + tools::memory_block(place.as_ref()) + ) }; let mcp = json!({"mcpServers": {"mantis": {"type": "http", "url": server.url, "headers": {"Authorization": format!("Bearer {}", server.token)}}}}); // Without an Exa key, searching is Claude Code's own. - let (builtin, allowed) = if exa { ("Read", "mcp__mantis") } else { ("Read,WebSearch", "mcp__mantis WebSearch") }; + let (builtin, allowed) = if exa { + ("Read", "mcp__mantis") + } else { + ("Read,WebSearch", "mcp__mantis WebSearch") + }; let mut command = command_for(&self.claude); command .current_dir(&dir) - .args(["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]) + .args([ + "-p", + "--input-format", + "stream-json", + "--output-format", + "stream-json", + "--verbose", + "--include-partial-messages", + ]) .args(["--model", model.label(), "--effort", effort]) // Only what Mantis gives it: none of the person's own settings, hooks, MCP servers or plugins. - .args(["--setting-sources", "", "--strict-mcp-config", "--mcp-config", &mcp.to_string()]) - .args(["--tools", builtin, "--allowedTools", allowed, "--permission-prompts", "none"]) + .args([ + "--setting-sources", + "", + "--strict-mcp-config", + "--mcp-config", + &mcp.to_string(), + ]) + .args([ + "--tools", + builtin, + "--allowedTools", + allowed, + "--permission-prompts", + "none", + ]) .args(["--system-prompt", &system]) - .args([if resume { "--resume" } else { "--session-id" }, &self.session]) + .args([ + if resume { "--resume" } else { "--session-id" }, + &self.session, + ]) // Room for a board and for long CAD runs. .env("MAX_MCP_OUTPUT_TOKENS", "200000") .env("MCP_TOOL_TIMEOUT", "3600000") @@ -260,7 +377,9 @@ impl Harness { .stdout(Stdio::piped()) .stderr(Stdio::piped()); agent_home(&mut command); - let mut child = command.spawn().with_context(|| format!("could not start Claude Code at {}", self.claude.display()))?; + let mut child = command + .spawn() + .with_context(|| format!("could not start Claude Code at {}", self.claude.display()))?; let mut stdin = child.stdin.take(); let lines = lines_of(child.stdout.take().context("no output from Claude Code")?); let errors = Arc::new(Mutex::new(String::new())); @@ -294,7 +413,9 @@ impl Harness { } match lines.recv_timeout(Duration::from_millis(100)) { Ok(line) => { - let Ok(message) = serde_json::from_str::(&line) else { continue }; + let Ok(message) = serde_json::from_str::(&line) else { + continue; + }; if stream.take(&message, emit, &mut run, &mut self.context) { // Everything said has been answered: let it finish and exit. stdin = None; @@ -311,12 +432,23 @@ impl Harness { return Ok(run); } std::thread::sleep(Duration::from_millis(20)); - let said = format!("{}\n{}", errors.lock().unwrap_or_else(|p| p.into_inner()), stream.errors.join("\n")); + let said = format!( + "{}\n{}", + errors.lock().unwrap_or_else(|p| p.into_inner()), + stream.errors.join("\n") + ); run.missing = said.contains("No conversation found"); run.in_use = said.contains("already in use"); if !run.began && !run.missing && !run.in_use && run.failure.is_none() { let said = said.trim(); - run.failure = Some(if said.is_empty() { format!("Claude Code stopped without answering ({})", status.map_or("no status".into(), |s| s.to_string())) } else { said.to_string() }); + run.failure = Some(if said.is_empty() { + format!( + "Claude Code stopped without answering ({})", + status.map_or("no status".into(), |s| s.to_string()) + ) + } else { + said.to_string() + }); } Ok(run) } @@ -339,7 +471,9 @@ pub(crate) fn with_earlier(earlier: &[(bool, String)], text: &str) -> String { if earlier.is_empty() { return text.to_string(); } - let mut out = String::from("[This conversation began before you joined it. What was said so far, without the tool calls behind it; the board itself is there to read:]\n\n"); + let mut out = String::from( + "[This conversation began before you joined it. What was said so far, without the tool calls behind it; the board itself is there to read:]\n\n", + ); for (user, said) in earlier { out.push_str(if *user { "User: " } else { "Engineer: " }); out.push_str(said.trim()); @@ -417,17 +551,33 @@ impl Stream { match e["type"].as_str().unwrap_or_default() { "content_block_start" if e["content_block"]["type"] == "tool_use" => { let block = &e["content_block"]; - emit(AgentEvent::ToolStart { id: block["id"].as_str().unwrap_or_default().into(), name: shown_name(block["name"].as_str().unwrap_or_default()) }); + emit(AgentEvent::ToolStart { + id: block["id"].as_str().unwrap_or_default().into(), + name: shown_name(block["name"].as_str().unwrap_or_default()), + }); + } + "content_block_delta" => { + match e["delta"]["type"].as_str().unwrap_or_default() { + "text_delta" => emit(AgentEvent::Text( + e["delta"]["text"].as_str().unwrap_or_default().into(), + )), + "thinking_delta" => emit(AgentEvent::Thinking( + e["delta"]["thinking"].as_str().unwrap_or_default().into(), + )), + _ => {} + } } - "content_block_delta" => match e["delta"]["type"].as_str().unwrap_or_default() { - "text_delta" => emit(AgentEvent::Text(e["delta"]["text"].as_str().unwrap_or_default().into())), - "thinking_delta" => emit(AgentEvent::Thinking(e["delta"]["thinking"].as_str().unwrap_or_default().into())), - _ => {} - }, "message_delta" | "message_start" => { - let usage = if e["type"] == "message_start" { &e["message"]["usage"] } else { &e["usage"] }; + let usage = if e["type"] == "message_start" { + &e["message"]["usage"] + } else { + &e["usage"] + }; let n = |k: &str| usage[k].as_u64().unwrap_or(0) as usize; - let filled = n("input_tokens") + n("cache_read_input_tokens") + n("cache_creation_input_tokens") + n("output_tokens"); + let filled = n("input_tokens") + + n("cache_read_input_tokens") + + n("cache_creation_input_tokens") + + n("output_tokens"); if filled > 0 { *context = filled; } @@ -441,7 +591,10 @@ impl Stream { if block["type"] == "tool_use" && !name.starts_with(PREFIX) { let id = block["id"].as_str().unwrap_or_default().to_string(); self.builtin.insert(id, shown_name(name)); - emit(AgentEvent::ToolInput { name: shown_name(name), input: block["input"].clone() }); + emit(AgentEvent::ToolInput { + name: shown_name(name), + input: block["input"].clone(), + }); } } } @@ -451,7 +604,11 @@ impl Stream { && let Some(text) = content.as_str() { self.summary_next = false; - let summary = text.split_once("Summary:").map_or(text, |(_, s)| s).trim().to_string(); + let summary = text + .split_once("Summary:") + .map_or(text, |(_, s)| s) + .trim() + .to_string(); emit(AgentEvent::Compacted { summary }); return false; } @@ -460,21 +617,50 @@ impl Stream { if block["type"] != "tool_result" { continue; } - let Some(name) = block["tool_use_id"].as_str().and_then(|id| self.builtin.remove(id)) else { continue }; + let Some(name) = block["tool_use_id"] + .as_str() + .and_then(|id| self.builtin.remove(id)) + else { + continue; + }; let text = match &block["content"] { Value::String(s) => s.clone(), - Value::Array(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::>().join("\n"), + Value::Array(parts) => parts + .iter() + .filter_map(|p| p["text"].as_str()) + .collect::>() + .join("\n"), _ => String::new(), }; let ok = block["is_error"] != true; - let summary = if ok { String::new() } else { text.chars().take(120).collect() }; - emit(AgentEvent::ToolDone { name, ok, summary, detail: text.chars().take(1600).collect() }); + let summary = if ok { + String::new() + } else { + text.chars().take(120).collect() + }; + emit(AgentEvent::ToolDone { + name, + ok, + summary, + detail: text.chars().take(1600).collect(), + }); } } "result" => { self.answered += 1; if m["is_error"] == true { - let said = m["result"].as_str().map(String::from).or_else(|| m["errors"].as_array().map(|e| e.iter().filter_map(Value::as_str).collect::>().join("; "))).unwrap_or_else(|| m["subtype"].as_str().unwrap_or("error").to_string()); + let said = m["result"] + .as_str() + .map(String::from) + .or_else(|| { + m["errors"].as_array().map(|e| { + e.iter() + .filter_map(Value::as_str) + .collect::>() + .join("; ") + }) + }) + .unwrap_or_else(|| m["subtype"].as_str().unwrap_or("error").to_string()); self.errors.push(said.clone()); run.failure = Some(said); } else { @@ -490,7 +676,11 @@ impl Stream { fn friendly(raw: &str) -> String { let lower = raw.to_lowercase(); - if lower.contains("/login") || lower.contains("not logged in") || lower.contains("invalid api key") || lower.contains("authentication") { + if lower.contains("/login") + || lower.contains("not logged in") + || lower.contains("invalid api key") + || lower.contains("authentication") + { "Claude Code is not signed in. Open Terminal, run `claude` and sign in with /login, then try again.".into() } else if lower.contains("limit") && (lower.contains("reset") || lower.contains("usage")) { format!("Claude Code says: {raw}") @@ -527,18 +717,37 @@ mod tests { for line in &lines { assert!(!stream.take(line, &emit, &mut run, &mut context)); } - assert!(stream.take(&json!({"type": "result", "subtype": "success", "is_error": false}), &emit, &mut run, &mut context)); + assert!(stream.take( + &json!({"type": "result", "subtype": "success", "is_error": false}), + &emit, + &mut run, + &mut context + )); assert!(run.began && run.failure.is_none()); assert_eq!(context, 1025); let events = events.lock().unwrap().clone(); assert_eq!( events, vec![ - AgentEvent::ToolStart { id: "t1".into(), name: "get_board".into() }, - AgentEvent::ToolStart { id: "t2".into(), name: "web_search".into() }, + AgentEvent::ToolStart { + id: "t1".into(), + name: "get_board".into() + }, + AgentEvent::ToolStart { + id: "t2".into(), + name: "web_search".into() + }, // The board tool's own input and result come from the tool server, not from here. - AgentEvent::ToolInput { name: "web_search".into(), input: json!({"query": "ESP32 strapping"}) }, - AgentEvent::ToolDone { name: "web_search".into(), ok: true, summary: String::new(), detail: "GPIO9 must be high".into() }, + AgentEvent::ToolInput { + name: "web_search".into(), + input: json!({"query": "ESP32 strapping"}) + }, + AgentEvent::ToolDone { + name: "web_search".into(), + ok: true, + summary: String::new(), + detail: "GPIO9 must be high".into() + }, AgentEvent::Thinking("Hm.".into()), AgentEvent::Text("Done.".into()), ] @@ -549,11 +758,24 @@ mod tests { let s2 = sink.clone(); let emit: Emit = Arc::new(move |e| s2.lock().unwrap().push(e)); let (mut stream, mut run) = (Stream::default(), Run::default()); - stream.take(&json!({"type": "system", "subtype": "status", "status": "compacting"}), &emit, &mut run, &mut context); + stream.take( + &json!({"type": "system", "subtype": "status", "status": "compacting"}), + &emit, + &mut run, + &mut context, + ); stream.take(&json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": {"post_tokens": 900}}), &emit, &mut run, &mut context); stream.take(&json!({"type": "user", "message": {"content": "This session is being continued.\n\nSummary:\n1. A blue case."}}), &emit, &mut run, &mut context); assert!(stream.take(&json!({"type": "result", "is_error": true, "result": "You've hit your weekly limit · resets Dec 3"}), &emit, &mut run, &mut context)); - assert_eq!(*sink.lock().unwrap(), vec![AgentEvent::Compacting, AgentEvent::Compacted { summary: "1. A blue case.".into() }]); + assert_eq!( + *sink.lock().unwrap(), + vec![ + AgentEvent::Compacting, + AgentEvent::Compacted { + summary: "1. A blue case.".into() + } + ] + ); assert_eq!(context, 900); assert!(friendly(run.failure.as_deref().unwrap()).contains("weekly limit")); } @@ -567,7 +789,10 @@ mod tests { let events = Arc::new(Mutex::new(Vec::new())); let sink = events.clone(); let emit: Emit = Arc::new(move |e| sink.lock().unwrap().push(e)); - let model = ModelChoice::new(crate::models::Provider::ClaudeCode, std::env::var("MANTIS_TEST_MODEL").unwrap_or("haiku".into())); + let model = ModelChoice::new( + crate::models::Provider::ClaudeCode, + std::env::var("MANTIS_TEST_MODEL").unwrap_or("haiku".into()), + ); let (cancel, steering) = (Arc::new(AtomicBool::new(false)), Steering::default()); let mut h = Harness::new(claude); let said = steering.clone(); @@ -575,22 +800,66 @@ mod tests { std::thread::sleep(Duration::from_secs(6)); said.say("Also tell me the board's width in mm at the end."); }); - h.run_turn("Add the ldo_3v3 block at x 17, y 15.5 with add_block, then say done. Do nothing else.", &model, "low", &session, &emit, &cancel, &steering).unwrap(); + h.run_turn( + "Add the ldo_3v3 block at x 17, y 15.5 with add_block, then say done. Do nothing else.", + &model, + "low", + &session, + &emit, + &cancel, + &steering, + ) + .unwrap(); assert_eq!(session.lock().unwrap().board.blocks.len(), 1); - h.run_turn("Which block did you add? Answer in three words.", &model, "low", &session, &emit, &cancel, &steering).unwrap(); + h.run_turn( + "Which block did you add? Answer in three words.", + &model, + "low", + &session, + &emit, + &cancel, + &steering, + ) + .unwrap(); let events = events.lock().unwrap(); - let text: String = events.iter().filter_map(|e| if let AgentEvent::Text(t) = e { Some(t.as_str()) } else { None }).collect(); + let text: String = events + .iter() + .filter_map(|e| { + if let AgentEvent::Text(t) = e { + Some(t.as_str()) + } else { + None + } + }) + .collect(); eprintln!("{events:#?}"); - assert!(events.iter().any(|e| matches!(e, AgentEvent::ToolDone { name, ok: true, .. } if name == "add_block"))); - assert!(text.to_lowercase().contains("ldo") || text.contains("3.3") || text.contains("3V3"), "{text}"); - assert_eq!(events.iter().filter(|e| matches!(e, AgentEvent::Done)).count(), 2); + assert!(events.iter().any( + |e| matches!(e, AgentEvent::ToolDone { name, ok: true, .. } if name == "add_block") + )); + assert!( + text.to_lowercase().contains("ldo") || text.contains("3.3") || text.contains("3V3"), + "{text}" + ); + assert_eq!( + events + .iter() + .filter(|e| matches!(e, AgentEvent::Done)) + .count(), + 2 + ); } #[test] fn a_conversation_claude_code_does_not_have_is_given_what_was_said() { assert_eq!(with_earlier(&[], "hi"), "hi"); - let text = with_earlier(&[(true, "make a supply".into()), (false, "Built it.".into())], "now route it"); - assert!(text.contains("User: make a supply\n\nEngineer: Built it.") && text.ends_with("now route it")); + let text = with_earlier( + &[(true, "make a supply".into()), (false, "Built it.".into())], + "now route it", + ); + assert!( + text.contains("User: make a supply\n\nEngineer: Built it.") + && text.ends_with("now route it") + ); let mut h = Harness::new(PathBuf::from("/bin/false")); h.conversation("019ad0e2-7c3a-7d7e-9b1f-2a3b4c5d6e7f"); assert_eq!(h.session, "019ad0e2-7c3a-7d7e-9b1f-2a3b4c5d6e7f"); diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index d711b87..8db38ab 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1854,7 +1854,13 @@ pub struct ResizablePanelGroup { id: ElementId, vertical_layout: bool, full: bool, - children: Vec, + items: Vec, +} + +enum ResizableItem { + Panel(ResizablePanel), + Handle(ResizableHandle), + Other(AnyElement), } impl ResizablePanelGroup { @@ -1863,7 +1869,7 @@ impl ResizablePanelGroup { id: id.into(), vertical_layout: false, full: false, - children: Vec::new(), + items: Vec::new(), } } @@ -1872,7 +1878,7 @@ impl ResizablePanelGroup { id: id.into(), vertical_layout: true, full: false, - children: Vec::new(), + items: Vec::new(), } } @@ -1882,31 +1888,176 @@ impl ResizablePanelGroup { } pub fn panel(mut self, panel: ResizablePanel) -> Self { - self.children.push(panel.into_any_element()); + self.items.push(ResizableItem::Panel(panel)); self } pub fn handle(mut self, handle: ResizableHandle) -> Self { - self.children.push(handle.into_any_element()); + self.items.push(ResizableItem::Handle(handle)); self } pub fn child(mut self, child: impl IntoElement) -> Self { - self.children.push(child.into_any_element()); + self.items + .push(ResizableItem::Other(child.into_any_element())); self } } impl RenderOnce for ResizablePanelGroup { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - let mut d = div().id(self.id).flex(); - if self.vertical_layout { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + let vertical = self.vertical_layout; + + let mut panel_indices = Vec::new(); + for (idx, item) in self.items.iter().enumerate() { + if matches!(item, ResizableItem::Panel(_)) { + panel_indices.push(idx); + } + } + + let two_panels = panel_indices.len() == 2; + let (default_pct, min_a, max_a) = if two_panels { + let p0 = match &self.items[panel_indices[0]] { + ResizableItem::Panel(p) => p, + _ => unreachable!(), + }; + let p1 = match &self.items[panel_indices[1]] { + ResizableItem::Panel(p) => p, + _ => unreachable!(), + }; + let min_a = p0.min_pct.clamp(5.0, 90.0); + let max_a = (100.0 - p1.min_pct).clamp(min_a, 95.0); + (p0.default_pct.clamp(min_a, max_a), min_a, max_a) + } else { + (50.0, 5.0, 95.0) + }; + + let split_state = + window.use_keyed_state(crate::key(&self.id, "split"), cx, |_, _| default_pct); + let drag_state = window.use_keyed_state(crate::key(&self.id, "drag"), cx, |_, _| false); + let bounds_state = window.use_keyed_state(crate::key(&self.id, "bounds"), cx, |_, _| { + std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::::default())) + }); + + let pct_a = (*split_state.read(cx)).clamp(min_a, max_a); + let bounds_for_canvas = bounds_state.read(cx).clone(); + let bounds_for_move = bounds_state.read(cx).clone(); + + let mut d = div().id(self.id.clone()).relative().flex(); + if vertical { d = d.flex_col(); } if self.full { d = d.size_full(); } - d.children(self.children) + + if two_panels { + let drag_move = drag_state.clone(); + let split_move = split_state.clone(); + let drag_up = drag_state.clone(); + let drag_up_out = drag_state.clone(); + d = d + .on_mouse_move(move |ev: &gpui::MouseMoveEvent, _, cx| { + if !*drag_move.read(cx) { + return; + } + let bounds = bounds_for_move.get(); + let next = if vertical { + let total = f32::from(bounds.size.height); + if total <= 1.0 { + return; + } + (f32::from(ev.position.y - bounds.origin.y) / total) * 100.0 + } else { + let total = f32::from(bounds.size.width); + if total <= 1.0 { + return; + } + (f32::from(ev.position.x - bounds.origin.x) / total) * 100.0 + }; + split_move.update(cx, |p, _| *p = next.clamp(min_a, max_a)); + }) + .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| { + drag_up.update(cx, |d, _| *d = false); + }) + .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| { + drag_up_out.update(cx, |d, _| *d = false); + }) + .child( + gpui::canvas( + move |bounds, _, _| bounds_for_canvas.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ); + } + + let mut panel_pos = 0usize; + let mut handle_pos = 0usize; + for item in self.items { + match item { + ResizableItem::Panel(panel) => { + let mut p = div() + .flex() + .flex_col() + .min_w_0() + .min_h_0() + .children(panel.children); + if two_panels { + if panel_pos == 0 { + let frac = pct_a / 100.0; + p = if vertical { + p.h(gpui::relative(frac)) + } else { + p.w(gpui::relative(frac)) + }; + } else { + p = p.flex_1(); + } + } else { + let frac = (panel.default_pct / 100.0).clamp(0.05, 0.95); + p = if vertical { + p.h(gpui::relative(frac)) + } else { + p.w(gpui::relative(frac)) + }; + } + panel_pos += 1; + d = d.child(p); + } + ResizableItem::Handle(_handle) => { + let hid = crate::key(&self.id, &format!("h{handle_pos}")); + handle_pos += 1; + let drag_down = drag_state.clone(); + let mut h = div() + .id(hid) + .flex() + .items_center() + .justify_center() + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + drag_down.update(cx, |d, _| *d = true); + }); + h = if vertical { + h.h(px(5.)) + .w_full() + .cursor_ns_resize() + .child(div().h(px(1.)).w_full().bg(t.border)) + } else { + h.w(px(5.)) + .h_full() + .cursor_ew_resize() + .child(div().w(px(1.)).h_full().bg(t.border)) + }; + d = d.child(h); + } + ResizableItem::Other(el) => { + d = d.child(el); + } + } + } + d } } @@ -1914,6 +2065,7 @@ impl RenderOnce for ResizablePanelGroup { pub struct ResizablePanel { children: Vec, default_pct: f32, + min_pct: f32, } impl ResizablePanel { @@ -1921,6 +2073,7 @@ impl ResizablePanel { Self { children: Vec::new(), default_pct: 50.0, + min_pct: 5.0, } } @@ -1929,7 +2082,8 @@ impl ResizablePanel { self } - pub fn min_size(self, _pct: f32) -> Self { + pub fn min_size(mut self, pct: f32) -> Self { + self.min_pct = pct; self } @@ -2245,6 +2399,16 @@ pub struct MenuContent { items: Vec, } +#[derive(IntoElement)] +struct MenuSeparator; + +impl RenderOnce for MenuSeparator { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let t = crate::Theme::of(cx); + div().h(px(1.)).w_full().my(px(4.)).bg(t.border) + } +} + impl MenuContent { pub fn new() -> Self { Self { @@ -2296,8 +2460,7 @@ impl MenuContent { } pub fn separator(mut self) -> Self { - self.items - .push(div().h(px(1.)).my(px(4.)).into_any_element()); + self.items.push(MenuSeparator.into_any_element()); self } } @@ -2360,28 +2523,37 @@ impl RenderOnce for DropdownMenu { let toggle = open_state.clone(); let close_out = open_state.clone(); let close_pick = open_state; - let mut root = div() - .id(self.id) - .relative() - .flex() - .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { - toggle.update(cx, |o, _| *o = !*o); - }) - .children(self.trigger); + let anchor_corner = match self._align { + MenuAlign::End => gpui::Corner::TopRight, + MenuAlign::Start => gpui::Corner::TopLeft, + }; + let mut root = div().id(self.id).relative().flex().child( + div() + .flex() + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + cx.stop_propagation(); + toggle.update(cx, |o, _| *o = !*o); + }) + .children(self.trigger), + ); if is_open { root = root.child( gpui::deferred( - gpui::anchored().snap_to_window().child( - div() - .mt(px(4.)) - .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { - close_pick.update(cx, |o, _| *o = false); - }) - .on_mouse_down_out(move |_, _, cx| { - close_out.update(cx, |o, _| *o = false); - }) - .child(self.menu), - ), + gpui::anchored() + .anchor(anchor_corner) + .snap_to_window() + .child( + div() + .mt(px(4.)) + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + cx.stop_propagation(); + close_pick.update(cx, |o, _| *o = false); + }) + .on_mouse_down_out(move |_, _, cx| { + close_out.update(cx, |o, _| *o = false); + }) + .child(self.menu), + ), ) .with_priority(10), ); @@ -2522,9 +2694,24 @@ impl Popover { } impl RenderOnce for Popover { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let mut d = div().id(self.id).relative().flex().children(self.trigger); + let trigger_bounds = + window.use_keyed_state(crate::key(&self.id, "trigger_bounds"), cx, |_, _| { + std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::::default())) + }); + let bounds_for_canvas = trigger_bounds.read(cx).clone(); + let bounds_for_close = trigger_bounds.read(cx).clone(); + let mut d = div().id(self.id).relative().flex().child( + div().relative().flex().children(self.trigger).child( + gpui::canvas( + move |bounds, _, _| bounds_for_canvas.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ), + ); if self.open && let Some(body) = self.content { @@ -2539,7 +2726,11 @@ impl RenderOnce for Popover { panel = panel.w(w); } if let Some(on_close) = self.on_close { - panel = panel.on_mouse_down_out(move |_, window, cx| on_close(window, cx)); + panel = panel.on_mouse_down_out(move |ev, window, cx| { + if !bounds_for_close.get().contains(&ev.position) { + on_close(window, cx); + } + }); } let anchor_corner = match (self._side, self._align) { (OverlaySide::Top, OverlayAlign::End) => gpui::Corner::BottomRight, diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 5a9da10..4ae5ec3 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -26,24 +26,48 @@ fn utf16_len(s: &str) -> usize { s.encode_utf16().count() } -fn utf16_range_to_byte_range(s: &str, range: Range) -> Range { +fn utf16_offset_to_byte(s: &str, u16_target: usize) -> usize { let mut u16_pos = 0usize; - let mut start_b = s.len(); - let mut end_b = s.len(); for (b_idx, ch) in s.char_indices() { - if u16_pos >= range.start && start_b == s.len() { - start_b = b_idx; + if u16_pos >= u16_target { + return b_idx; } u16_pos += ch.len_utf16(); - if u16_pos >= range.end && end_b == s.len() { - end_b = b_idx + ch.len_utf8(); - break; - } } - if range.start == 0 { - start_b = 0; + s.len() +} + +fn utf16_range_to_byte_range(s: &str, range: Range) -> Range { + let start = utf16_offset_to_byte(s, range.start); + if range.start >= range.end { + return start..start; + } + let end = utf16_offset_to_byte(s, range.end); + start..end.max(start) +} + +fn prev_char_boundary(s: &str, pos: usize) -> usize { + let pos = pos.min(s.len()); + if pos == 0 { + return 0; + } + let mut p = pos - 1; + while p > 0 && !s.is_char_boundary(p) { + p -= 1; } - start_b.min(end_b)..end_b.max(start_b) + p +} + +fn next_char_boundary(s: &str, pos: usize) -> usize { + let pos = pos.min(s.len()); + if pos >= s.len() { + return s.len(); + } + let mut p = pos + 1; + while p < s.len() && !s.is_char_boundary(p) { + p += 1; + } + p } pub struct TextInput { @@ -51,6 +75,7 @@ pub struct TextInput { pub value: String, pub bare: bool, pub password: bool, + cursor: usize, focus: FocusHandle, } @@ -65,6 +90,7 @@ impl TextInput { value: String::new(), bare: false, password: false, + cursor: 0, focus: cx.focus_handle(), } } @@ -79,6 +105,7 @@ impl TextInput { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); + self.cursor = self.value.len(); cx.notify(); } @@ -90,6 +117,12 @@ impl TextInput { self.set_value(String::new(), cx); } + fn insert_at_cursor(&mut self, text: &str) { + let pos = self.cursor.min(self.value.len()); + self.value.insert_str(pos, text); + self.cursor = pos + text.len(); + } + fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; let paste = (ks.modifiers.control || ks.modifiers.platform) @@ -98,27 +131,62 @@ impl TextInput { if paste { if let Some(pasted) = read_paste(cx) { let single_line = pasted.replace("\r\n", " ").replace(['\r', '\n'], " "); - self.value.push_str(&single_line); + self.insert_at_cursor(&single_line); cx.emit(Changed(self.value.clone())); cx.notify(); } return; } - if ks.key == "enter" { - cx.emit(Submitted(self.value.clone())); - return; - } - if ks.key == "backspace" { - if self.value.pop().is_some() { - cx.emit(Changed(self.value.clone())); + match ks.key.as_str() { + "enter" => { + cx.emit(Submitted(self.value.clone())); + return; + } + "left" => { + self.cursor = prev_char_boundary(&self.value, self.cursor); cx.notify(); + return; } - return; + "right" => { + self.cursor = next_char_boundary(&self.value, self.cursor); + cx.notify(); + return; + } + "home" => { + self.cursor = 0; + cx.notify(); + return; + } + "end" => { + self.cursor = self.value.len(); + cx.notify(); + return; + } + "backspace" => { + if self.cursor > 0 { + let prev = prev_char_boundary(&self.value, self.cursor); + self.value.drain(prev..self.cursor); + self.cursor = prev; + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + "delete" => { + if self.cursor < self.value.len() { + let next = next_char_boundary(&self.value, self.cursor); + self.value.drain(self.cursor..next); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + _ => {} } if is_printable(ks) && let Some(ch) = &ks.key_char { - self.value.push_str(ch); + self.insert_at_cursor(ch); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -133,6 +201,9 @@ impl EntityInputHandler for TextInput { _window: &mut Window, _cx: &mut Context, ) -> Option { + if self.password { + return None; + } let br = utf16_range_to_byte_range(&self.value, range.clone()); *adjusted_range = Some(range); Some(self.value[br].to_string()) @@ -144,9 +215,9 @@ impl EntityInputHandler for TextInput { _window: &mut Window, _cx: &mut Context, ) -> Option { - let len = utf16_len(&self.value); + let pos = utf16_len(&self.value[..self.cursor.min(self.value.len())]); Some(UTF16Selection { - range: len..len, + range: pos..pos, reversed: false, }) } @@ -171,9 +242,11 @@ impl EntityInputHandler for TextInput { let clean = text.replace("\r\n", " ").replace(['\r', '\n'], " "); if let Some(r) = range { let br = utf16_range_to_byte_range(&self.value, r); + let start = br.start; self.value.replace_range(br, &clean); + self.cursor = start + clean.len(); } else { - self.value.push_str(&clean); + self.insert_at_cursor(&clean); } cx.emit(Changed(self.value.clone())); cx.notify(); @@ -206,7 +279,7 @@ impl EntityInputHandler for TextInput { _window: &mut Window, _cx: &mut Context, ) -> Option { - Some(utf16_len(&self.value)) + Some(utf16_len(&self.value[..self.cursor.min(self.value.len())])) } } @@ -283,6 +356,7 @@ pub struct Textarea { pub submit_on_enter: bool, pub min_height: Pixels, pub max_height: Option, + cursor: usize, focus: FocusHandle, scroll: ScrollHandle, } @@ -300,6 +374,7 @@ impl Textarea { submit_on_enter: false, min_height: px(64.), max_height: None, + cursor: 0, focus: cx.focus_handle(), scroll: ScrollHandle::new(), } @@ -315,6 +390,7 @@ impl Textarea { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); + self.cursor = self.value.len(); self.scroll.scroll_to_bottom(); cx.notify(); } @@ -327,6 +403,12 @@ impl Textarea { self.set_value(String::new(), cx); } + fn insert_at_cursor(&mut self, text: &str) { + let pos = self.cursor.min(self.value.len()); + self.value.insert_str(pos, text); + self.cursor = pos + text.len(); + } + fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; let paste = (ks.modifiers.control || ks.modifiers.platform) @@ -334,36 +416,71 @@ impl Textarea { && ks.key.eq_ignore_ascii_case("v"); if paste { if let Some(pasted) = read_paste(cx) { - self.value.push_str(&pasted.replace("\r\n", "\n")); + self.insert_at_cursor(&pasted.replace("\r\n", "\n")); self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); } return; } - if ks.key == "enter" { - if self.submit_on_enter && !ks.modifiers.shift { - cx.emit(Submitted(self.value.clone())); - return; - } - self.value.push('\n'); - self.scroll.scroll_to_bottom(); - cx.emit(Changed(self.value.clone())); - cx.notify(); - return; - } - if ks.key == "backspace" { - if self.value.pop().is_some() { + match ks.key.as_str() { + "enter" => { + if self.submit_on_enter && !ks.modifiers.shift { + cx.emit(Submitted(self.value.clone())); + return; + } + self.insert_at_cursor("\n"); self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); + return; } - return; + "left" => { + self.cursor = prev_char_boundary(&self.value, self.cursor); + cx.notify(); + return; + } + "right" => { + self.cursor = next_char_boundary(&self.value, self.cursor); + cx.notify(); + return; + } + "home" => { + self.cursor = 0; + cx.notify(); + return; + } + "end" => { + self.cursor = self.value.len(); + cx.notify(); + return; + } + "backspace" => { + if self.cursor > 0 { + let prev = prev_char_boundary(&self.value, self.cursor); + self.value.drain(prev..self.cursor); + self.cursor = prev; + self.scroll.scroll_to_bottom(); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + "delete" => { + if self.cursor < self.value.len() { + let next = next_char_boundary(&self.value, self.cursor); + self.value.drain(self.cursor..next); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + return; + } + _ => {} } if is_printable(ks) && let Some(ch) = &ks.key_char { - self.value.push_str(ch); + self.insert_at_cursor(ch); self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); cx.notify(); @@ -390,9 +507,9 @@ impl EntityInputHandler for Textarea { _window: &mut Window, _cx: &mut Context, ) -> Option { - let len = utf16_len(&self.value); + let pos = utf16_len(&self.value[..self.cursor.min(self.value.len())]); Some(UTF16Selection { - range: len..len, + range: pos..pos, reversed: false, }) } @@ -417,9 +534,11 @@ impl EntityInputHandler for Textarea { let clean = text.replace("\r\n", "\n"); if let Some(r) = range { let br = utf16_range_to_byte_range(&self.value, r); + let start = br.start; self.value.replace_range(br, &clean); + self.cursor = start + clean.len(); } else { - self.value.push_str(&clean); + self.insert_at_cursor(&clean); } self.scroll.scroll_to_bottom(); cx.emit(Changed(self.value.clone())); @@ -453,7 +572,7 @@ impl EntityInputHandler for Textarea { _window: &mut Window, _cx: &mut Context, ) -> Option { - Some(utf16_len(&self.value)) + Some(utf16_len(&self.value[..self.cursor.min(self.value.len())])) } } From b1452bf03513aaccbca68d7afe15490d493ce469 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:05:40 -0500 Subject: [PATCH 07/16] fix: address all 12 Loopy review #5 findings (scroll threshold, input selection/IME/caret, harness cmd/stderr, popover/menu/button) --- crates/mantis-agent/src/harness.rs | 65 ++- vendor/mantis-ui/src/components.rs | 113 ++-- vendor/mantis-ui/src/input.rs | 819 ++++++++++++++++++++++------- 3 files changed, 723 insertions(+), 274 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 75bd993..a239bea 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -42,12 +42,8 @@ pub(crate) fn command_for(program: &Path) -> Command { { if let Some(ext) = program.extension().and_then(|e| e.to_str()) && (ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) + && let Some(cmd) = npm_node_command(program) { - if let Some(cmd) = npm_node_command(program) { - return cmd; - } - let mut cmd = Command::new("cmd"); - cmd.args(["/D", "/C", &program.to_string_lossy()]); return cmd; } } @@ -58,31 +54,32 @@ pub(crate) fn command_for(program: &Path) -> Command { fn npm_node_command(shim: &Path) -> Option { let dir = shim.parent()?; let text = std::fs::read_to_string(shim).ok()?; - let idx = text.find("node_modules")?; - let rest = &text[idx..]; - let end = rest - .find(['"', '\'', ' ', '\t', '\r', '\n']) - .unwrap_or(rest.len()); - let target = dir.join(rest[..end].replace('/', "\\")); - if !target.is_file() { - return None; - } - let ext = target.extension().and_then(|e| e.to_str()).unwrap_or(""); - if ext.eq_ignore_ascii_case("exe") { - return Some(Command::new(target)); - } - if !matches!(ext.to_ascii_lowercase().as_str(), "js" | "mjs" | "cjs") { - return None; + for (idx, _) in text.match_indices("node_modules") { + let rest = &text[idx..]; + let end = rest + .find(['"', '\'', ' ', '\t', '\r', '\n', ';']) + .unwrap_or(rest.len()); + let target = dir.join(rest[..end].replace('/', "\\")); + if !target.is_file() { + continue; + } + let ext = target.extension().and_then(|e| e.to_str()).unwrap_or(""); + if ext.eq_ignore_ascii_case("exe") { + return Some(Command::new(target)); + } + if matches!(ext.to_ascii_lowercase().as_str(), "js" | "mjs" | "cjs") { + let node = dir.join("node.exe"); + let exe = if node.is_file() { + node + } else { + PathBuf::from("node.exe") + }; + let mut cmd = Command::new(exe); + cmd.arg(target); + return Some(cmd); + } } - let node = dir.join("node.exe"); - let exe = if node.is_file() { - node - } else { - PathBuf::from("node.exe") - }; - let mut cmd = Command::new(exe); - cmd.arg(target); - Some(cmd) + None } /// Run an agent program in the person's own home, where its sign-in is, even when Mantis @@ -383,14 +380,14 @@ impl Harness { let mut stdin = child.stdin.take(); let lines = lines_of(child.stdout.take().context("no output from Claude Code")?); let errors = Arc::new(Mutex::new(String::new())); - if let Some(mut err) = child.stderr.take() { + let stderr_thread = child.stderr.take().map(|mut err| { let errors = errors.clone(); std::thread::spawn(move || { let mut text = String::new(); let _ = err.read_to_string(&mut text); *errors.lock().unwrap_or_else(|p| p.into_inner()) = text; - }); - } + }) + }); if let Some(input) = stdin.as_mut() { say(input, prompt)?; } @@ -431,7 +428,9 @@ impl Harness { if run.stopped { return Ok(run); } - std::thread::sleep(Duration::from_millis(20)); + if let Some(handle) = stderr_thread { + let _ = handle.join(); + } let said = format!( "{}\n{}", errors.lock().unwrap_or_else(|p| p.into_inner()), diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index 8db38ab..fcaf1f5 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -252,31 +252,40 @@ impl Button { } } +fn button_style( + variant: ButtonVariant, + size: ButtonSize, + t: &crate::Theme, +) -> (gpui::Hsla, gpui::Hsla, gpui::Hsla, Pixels, Pixels, Pixels) { + let (bg, fg, border) = match variant { + ButtonVariant::Default | ButtonVariant::Primary => { + (t.primary, t.primary_foreground, t.primary) + } + ButtonVariant::Secondary => (t.secondary, t.secondary_foreground, t.secondary), + ButtonVariant::Outline => (crate::alpha(t.background, 0.), t.foreground, t.border), + ButtonVariant::Ghost => ( + crate::alpha(t.background, 0.), + t.foreground, + crate::alpha(t.border, 0.), + ), + ButtonVariant::Destructive => (t.destructive, t.destructive_foreground, t.destructive), + }; + let (h, px_pad, text_sz) = match size { + ButtonSize::Xs => (px(22.), px(7.), px(11.)), + ButtonSize::Sm => (px(26.), px(10.), px(12.)), + ButtonSize::Md => (px(32.), px(12.), px(13.)), + ButtonSize::Lg => (px(38.), px(16.), px(14.)), + ButtonSize::Icon => (px(28.), px(6.), px(13.)), + ButtonSize::IconXs => (px(20.), px(4.), px(11.)), + ButtonSize::IconSm => (px(24.), px(5.), px(12.)), + }; + (bg, fg, border, h, px_pad, text_sz) +} + impl RenderOnce for Button { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let (bg, fg, border) = match self.variant { - ButtonVariant::Default | ButtonVariant::Primary => { - (t.primary, t.primary_foreground, t.primary) - } - ButtonVariant::Secondary => (t.secondary, t.secondary_foreground, t.secondary), - ButtonVariant::Outline => (crate::alpha(t.background, 0.), t.foreground, t.border), - ButtonVariant::Ghost => ( - crate::alpha(t.background, 0.), - t.foreground, - crate::alpha(t.border, 0.), - ), - ButtonVariant::Destructive => (t.destructive, t.destructive_foreground, t.destructive), - }; - let (h, px_pad, text_sz) = match self.size { - ButtonSize::Xs => (px(22.), px(7.), px(11.)), - ButtonSize::Sm => (px(26.), px(10.), px(12.)), - ButtonSize::Md => (px(32.), px(12.), px(13.)), - ButtonSize::Lg => (px(38.), px(16.), px(14.)), - ButtonSize::Icon => (px(28.), px(6.), px(13.)), - ButtonSize::IconXs => (px(20.), px(4.), px(11.)), - ButtonSize::IconSm => (px(24.), px(5.), px(12.)), - }; + let (bg, fg, border, h, px_pad, text_sz) = button_style(self.variant, self.size, &t); let mut el = div() .id(self.id) .flex() @@ -378,30 +387,33 @@ impl GroupButton { impl RenderOnce for GroupButton { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let fg = if self.active { - t.accent_foreground - } else { - t.muted_foreground - }; + let (mut bg, mut fg, mut border, h, px_pad, text_sz) = + button_style(self.variant, self.size, &t); + if self.active { + bg = t.accent; + fg = t.accent_foreground; + border = t.accent; + } else if matches!(self.variant, ButtonVariant::Ghost) { + fg = t.muted_foreground; + } + let icon_sz = px(f32::from(text_sz) + 1.0); let mut el = div() .id(self.id) .flex() .items_center() .justify_center() .gap(px(4.)) - .h(px(24.)) - .px(px(8.)) + .h(h) + .px(px_pad) .rounded(px(5.)) - .text_size(px(12.)) + .border_1() + .border_color(border) + .text_size(text_sz) .cursor_pointer() - .bg(if self.active { - t.accent - } else { - crate::alpha(t.background, 0.) - }) + .bg(bg) .text_color(fg); if let Some(icon) = self.icon { - el = el.child(Icon::new(icon).size(px(13.)).color(fg)); + el = el.child(Icon::new(icon).size(icon_sz).color(fg)); } if !self.label.is_empty() { el = el.child(self.label); @@ -2198,6 +2210,7 @@ pub struct MessageScroller { id: ElementId, handle: gpui::ScrollHandle, auto: bool, + edge_threshold: Pixels, gap_px: Option, pad: Option>, items: Vec, @@ -2209,6 +2222,7 @@ impl MessageScroller { id: id.into(), handle: handle.scroll.clone(), auto: false, + edge_threshold: px(64.), gap_px: None, pad: None, items: Vec::new(), @@ -2220,7 +2234,8 @@ impl MessageScroller { self } - pub fn scroll_edge_threshold(self, _px: Pixels) -> Self { + pub fn scroll_edge_threshold(mut self, px_thresh: Pixels) -> Self { + self.edge_threshold = px_thresh; self } @@ -2247,7 +2262,12 @@ impl MessageScroller { impl RenderOnce for MessageScroller { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { if self.auto { - self.handle.scroll_to_bottom(); + let max_y = f32::from(self.handle.max_offset().height); + let cur_y = -f32::from(self.handle.offset().y); + let dist = (max_y - cur_y).max(0.0); + if max_y <= 0.0 || dist <= f32::from(self.edge_threshold) { + self.handle.scroll_to_bottom(); + } } let mut d = div() .id(self.id) @@ -2593,16 +2613,27 @@ impl ContextMenu { impl RenderOnce for ContextMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let active_menu = window.use_keyed_state( + ElementId::Name("__active_context_menu".into()), + cx, + |_, _| Option::::None, + ); let pos_state = window.use_keyed_state(crate::key(&self.id, "pos"), cx, |_, _| { Option::>::None }); - let pos = *pos_state.read(cx); + let is_active = active_menu.read(cx).as_ref() == Some(&self.id); + let pos = if is_active { *pos_state.read(cx) } else { None }; + let my_id = self.id.clone(); + let active_open = active_menu.clone(); + let active_close_pick = active_menu.clone(); + let active_close_out = active_menu; let open_pos = pos_state.clone(); let close_out = pos_state.clone(); let close_pick = pos_state; let mut d = div().id(self.id).flex().flex_col().on_mouse_down( gpui::MouseButton::Right, move |ev, _, cx| { + active_open.update(cx, |a, _| *a = Some(my_id.clone())); open_pos.update(cx, |p, _| *p = Some(ev.position)); }, ); @@ -2616,10 +2647,13 @@ impl RenderOnce for ContextMenu { gpui::anchored().position(at).snap_to_window().child( div() .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + cx.stop_propagation(); close_pick.update(cx, |p, _| *p = None); + active_close_pick.update(cx, |a, _| *a = None); }) .on_mouse_down_out(move |_, _, cx| { close_out.update(cx, |p, _| *p = None); + active_close_out.update(cx, |a, _| *a = None); }) .child(self.menu), ), @@ -2717,6 +2751,7 @@ impl RenderOnce for Popover { { let mut panel = div() .mt(px(4.)) + .p(px(16.)) .rounded(px(10.)) .bg(t.popover) .border_1() diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 4ae5ec3..3930bad 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -1,10 +1,12 @@ use gpui::{ - Bounds, Context, ElementInputHandler, EntityInputHandler, EventEmitter, FocusHandle, Focusable, - InteractiveElement, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, - Pixels, Point, Render, ScrollHandle, SharedString, StatefulInteractiveElement, Styled, - UTF16Selection, Window, canvas, div, px, + AnyElement, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, + EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyDownEvent, + MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Render, ScrollHandle, SharedString, + StatefulInteractiveElement, Styled, UTF16Selection, Window, canvas, div, px, }; +use std::cell::Cell; use std::ops::Range; +use std::rc::Rc; #[derive(Clone, Debug)] pub struct Submitted(pub String); @@ -16,6 +18,10 @@ fn read_paste(cx: &mut gpui::App) -> Option { cx.read_from_clipboard().and_then(|item| item.text()) } +fn write_copy(cx: &mut gpui::App, text: String) { + cx.write_to_clipboard(ClipboardItem::new_string(text)); +} + fn is_printable(ks: &gpui::Keystroke) -> bool { !ks.modifiers.platform && ((!ks.modifiers.control && !ks.modifiers.alt) @@ -46,6 +52,12 @@ fn utf16_range_to_byte_range(s: &str, range: Range) -> Range { start..end.max(start) } +fn byte_range_to_utf16_range(s: &str, range: Range) -> Range { + let start = utf16_len(&s[..range.start.min(s.len())]); + let end = utf16_len(&s[..range.end.min(s.len())]); + start..end.max(start) +} + fn prev_char_boundary(s: &str, pos: usize) -> usize { let pos = pos.min(s.len()); if pos == 0 { @@ -70,12 +82,436 @@ fn next_char_boundary(s: &str, pos: usize) -> usize { p } +fn advance_chars_in_slice(slice: &str, char_count: usize) -> usize { + slice + .char_indices() + .nth(char_count) + .map_or(slice.len(), |(idx, _)| idx) +} + +struct EditState { + cursor: usize, + anchor: usize, + marked: Option>, + bounds: Rc>>, + single_line: bool, +} + +impl EditState { + fn new(single_line: bool) -> Self { + Self { + cursor: 0, + anchor: 0, + marked: None, + bounds: Rc::new(Cell::new(Bounds::default())), + single_line, + } + } + + fn reset_to_end(&mut self, value: &str) { + self.cursor = value.len(); + self.anchor = self.cursor; + self.marked = None; + } + + fn selection_range(&self, len: usize) -> Range { + let a = self.anchor.min(len); + let c = self.cursor.min(len); + a.min(c)..a.max(c) + } + + fn has_selection(&self, len: usize) -> bool { + self.anchor.min(len) != self.cursor.min(len) + } + + fn move_to(&mut self, pos: usize, len: usize, extend: bool) { + self.cursor = pos.min(len); + if !extend { + self.anchor = self.cursor; + } + self.marked = None; + } + + fn select_all(&mut self, len: usize) { + self.anchor = 0; + self.cursor = len; + self.marked = None; + } + + fn replace_selection(&mut self, value: &mut String, text: &str) { + let r = self.selection_range(value.len()); + let start = r.start; + value.replace_range(r, text); + self.cursor = start + text.len(); + self.anchor = self.cursor; + self.marked = None; + } + + fn backspace(&mut self, value: &mut String) -> bool { + if self.has_selection(value.len()) { + self.replace_selection(value, ""); + return true; + } + if self.cursor > 0 { + let prev = prev_char_boundary(value, self.cursor); + value.drain(prev..self.cursor); + self.cursor = prev; + self.anchor = prev; + self.marked = None; + return true; + } + false + } + + fn delete(&mut self, value: &mut String) -> bool { + if self.has_selection(value.len()) { + self.replace_selection(value, ""); + return true; + } + if self.cursor < value.len() { + let next = next_char_boundary(value, self.cursor); + value.drain(self.cursor..next); + self.anchor = self.cursor; + self.marked = None; + return true; + } + false + } + + fn move_vertical(&mut self, value: &str, down: bool, extend: bool) { + let cur = self.cursor.min(value.len()); + let line_start = value[..cur].rfind('\n').map_or(0, |i| i + 1); + let line_end = value[cur..].find('\n').map_or(value.len(), |i| cur + i); + let col_chars = value[line_start..cur].chars().count(); + if !down { + if line_start == 0 { + self.move_to(0, value.len(), extend); + return; + } + let prev_end = line_start - 1; + let prev_start = value[..prev_end].rfind('\n').map_or(0, |i| i + 1); + let offset = advance_chars_in_slice(&value[prev_start..prev_end], col_chars); + self.move_to(prev_start + offset, value.len(), extend); + } else { + if line_end >= value.len() { + self.move_to(value.len(), value.len(), extend); + return; + } + let next_start = line_end + 1; + let next_end = value[next_start..] + .find('\n') + .map_or(value.len(), |i| next_start + i); + let offset = advance_chars_in_slice(&value[next_start..next_end], col_chars); + self.move_to(next_start + offset, value.len(), extend); + } + } + + fn byte_index_for_point( + &self, + value: &str, + point: Point, + pad_x: f32, + pad_y: f32, + ) -> usize { + let b = self.bounds.get(); + let char_w = 7.4_f32; + let line_h = 19.0_f32; + let rel_x = (f32::from(point.x - b.origin.x) - pad_x).max(0.0); + let col = (rel_x / char_w).round() as usize; + if self.single_line { + return advance_chars_in_slice(value, col); + } + let rel_y = (f32::from(point.y - b.origin.y) - pad_y).max(0.0); + let target_line = (rel_y / line_h).floor() as usize; + let mut line_start = 0usize; + let mut line_idx = 0usize; + for (i, ch) in value.char_indices() { + if line_idx == target_line { + let line_end = value[line_start..] + .find('\n') + .map_or(value.len(), |n| line_start + n); + return line_start + advance_chars_in_slice(&value[line_start..line_end], col); + } + if ch == '\n' { + line_idx += 1; + line_start = i + 1; + } + } + let line_end = value[line_start..] + .find('\n') + .map_or(value.len(), |n| line_start + n); + line_start + advance_chars_in_slice(&value[line_start..line_end], col) + } + + fn selected_text_range(&self, value: &str) -> UTF16Selection { + let len = value.len(); + let r = self.selection_range(len); + UTF16Selection { + range: byte_range_to_utf16_range(value, r), + reversed: self.cursor.min(len) < self.anchor.min(len), + } + } + + fn marked_text_range(&self, value: &str) -> Option> { + self.marked + .as_ref() + .map(|r| byte_range_to_utf16_range(value, r.clone())) + } + + fn commit_text(&mut self, value: &mut String, range: Option>, text: &str) { + let clean = if self.single_line { + text.replace("\r\n", " ").replace(['\r', '\n'], " ") + } else { + text.replace("\r\n", "\n") + }; + let br = range + .map(|r| utf16_range_to_byte_range(value, r)) + .or_else(|| self.marked.take()) + .unwrap_or_else(|| self.selection_range(value.len())); + self.marked = None; + let start = br.start; + value.replace_range(br, &clean); + self.cursor = start + clean.len(); + self.anchor = self.cursor; + } + + fn mark_text( + &mut self, + value: &mut String, + range: Option>, + new_text: &str, + new_selected_range: Option>, + ) { + let clean = if self.single_line { + new_text.replace("\r\n", " ").replace(['\r', '\n'], " ") + } else { + new_text.replace("\r\n", "\n") + }; + let br = range + .map(|r| utf16_range_to_byte_range(value, r)) + .or_else(|| self.marked.take()) + .unwrap_or_else(|| self.selection_range(value.len())); + let start = br.start; + value.replace_range(br, &clean); + self.marked = if clean.is_empty() { + None + } else { + Some(start..start + clean.len()) + }; + if let Some(sr) = new_selected_range { + self.anchor = start + utf16_offset_to_byte(&clean, sr.start); + self.cursor = start + utf16_offset_to_byte(&clean, sr.end); + } else { + self.cursor = start + clean.len(); + self.anchor = self.cursor; + } + } +} + +enum CommonKeyResult { + NotHandled, + Moved, + Edited, +} + +fn handle_common_key( + buf: &mut EditState, + value: &mut String, + password: bool, + ks: &gpui::Keystroke, + cx: &mut gpui::App, +) -> CommonKeyResult { + let mod_cmd = (ks.modifiers.control || ks.modifiers.platform) && !ks.modifiers.alt; + if mod_cmd { + if ks.key.eq_ignore_ascii_case("a") { + buf.select_all(value.len()); + return CommonKeyResult::Moved; + } + if ks.key.eq_ignore_ascii_case("c") { + if !password && buf.has_selection(value.len()) { + let r = buf.selection_range(value.len()); + write_copy(cx, value[r].to_string()); + } + return CommonKeyResult::Moved; + } + if ks.key.eq_ignore_ascii_case("x") { + if buf.has_selection(value.len()) { + if !password { + let r = buf.selection_range(value.len()); + write_copy(cx, value[r].to_string()); + } + buf.replace_selection(value, ""); + return CommonKeyResult::Edited; + } + return CommonKeyResult::Moved; + } + if ks.key.eq_ignore_ascii_case("v") { + if let Some(pasted) = read_paste(cx) { + let clean = if buf.single_line { + pasted.replace("\r\n", " ").replace(['\r', '\n'], " ") + } else { + pasted.replace("\r\n", "\n") + }; + buf.replace_selection(value, &clean); + return CommonKeyResult::Edited; + } + return CommonKeyResult::Moved; + } + } + + let shift = ks.modifiers.shift; + match ks.key.as_str() { + "left" => { + let next = if !shift && buf.has_selection(value.len()) { + buf.selection_range(value.len()).start + } else { + prev_char_boundary(value, buf.cursor) + }; + buf.move_to(next, value.len(), shift); + CommonKeyResult::Moved + } + "right" => { + let next = if !shift && buf.has_selection(value.len()) { + buf.selection_range(value.len()).end + } else { + next_char_boundary(value, buf.cursor) + }; + buf.move_to(next, value.len(), shift); + CommonKeyResult::Moved + } + "home" => { + let target = if buf.single_line { + 0 + } else { + let cur = buf.cursor.min(value.len()); + value[..cur].rfind('\n').map_or(0, |i| i + 1) + }; + buf.move_to(target, value.len(), shift); + CommonKeyResult::Moved + } + "end" => { + let target = if buf.single_line { + value.len() + } else { + let cur = buf.cursor.min(value.len()); + value[cur..].find('\n').map_or(value.len(), |i| cur + i) + }; + buf.move_to(target, value.len(), shift); + CommonKeyResult::Moved + } + "up" if !buf.single_line => { + buf.move_vertical(value, false, shift); + CommonKeyResult::Moved + } + "down" if !buf.single_line => { + buf.move_vertical(value, true, shift); + CommonKeyResult::Moved + } + "backspace" => { + if buf.backspace(value) { + CommonKeyResult::Edited + } else { + CommonKeyResult::Moved + } + } + "delete" => { + if buf.delete(value) { + CommonKeyResult::Edited + } else { + CommonKeyResult::Moved + } + } + _ => CommonKeyResult::NotHandled, + } +} + +fn caret_el(t: &crate::Theme) -> AnyElement { + div() + .w(px(1.5)) + .h(px(15.)) + .bg(t.foreground) + .into_any_element() +} + +fn render_line_segments( + line_text: &str, + line_start: usize, + focused: bool, + sel: Range, + cursor: usize, + password: bool, + t: &crate::Theme, +) -> AnyElement { + let line_end = line_start + line_text.len(); + let sel_bg = crate::alpha(t.ring, 0.35); + let shown = if password { + "*".repeat(line_text.chars().count()) + } else { + line_text.to_string() + }; + + let map_offset = |byte_off: usize| -> usize { + if !password { + byte_off.min(shown.len()) + } else { + line_text[..byte_off.min(line_text.len())].chars().count() + } + }; + + let s_start = sel.start.clamp(line_start, line_end) - line_start; + let s_end = sel.end.clamp(line_start, line_end) - line_start; + let has_line_sel = focused && s_start < s_end; + let caret_here = focused && cursor >= line_start && cursor <= line_end; + let c_off = if caret_here { + map_offset(cursor - line_start) + } else { + 0 + }; + + let mut row = div().flex().items_center().min_h(px(18.)); + if has_line_sel { + let ms = map_offset(s_start); + let me = map_offset(s_end); + let before = &shown[..ms]; + let mid = &shown[ms..me]; + let after = &shown[me..]; + if !before.is_empty() { + row = row.child(before.to_string()); + } + if caret_here && c_off == ms { + row = row.child(caret_el(t)); + } + if !mid.is_empty() { + row = row.child(div().bg(sel_bg).child(mid.to_string())); + } + if caret_here && c_off == me { + row = row.child(caret_el(t)); + } + if !after.is_empty() { + row = row.child(after.to_string()); + } + } else if caret_here { + let before = &shown[..c_off]; + let after = &shown[c_off..]; + if !before.is_empty() { + row = row.child(before.to_string()); + } + row = row.child(caret_el(t)); + if !after.is_empty() { + row = row.child(after.to_string()); + } + } else if !shown.is_empty() { + row = row.child(shown); + } + row.into_any_element() +} + pub struct TextInput { pub placeholder: SharedString, pub value: String, pub bare: bool, pub password: bool, - cursor: usize, + buf: EditState, focus: FocusHandle, } @@ -90,7 +526,7 @@ impl TextInput { value: String::new(), bare: false, password: false, - cursor: 0, + buf: EditState::new(true), focus: cx.focus_handle(), } } @@ -105,7 +541,7 @@ impl TextInput { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); - self.cursor = self.value.len(); + self.buf.reset_to_end(&self.value); cx.notify(); } @@ -117,76 +553,28 @@ impl TextInput { self.set_value(String::new(), cx); } - fn insert_at_cursor(&mut self, text: &str) { - let pos = self.cursor.min(self.value.len()); - self.value.insert_str(pos, text); - self.cursor = pos + text.len(); - } - fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; - let paste = (ks.modifiers.control || ks.modifiers.platform) - && !ks.modifiers.alt - && ks.key.eq_ignore_ascii_case("v"); - if paste { - if let Some(pasted) = read_paste(cx) { - let single_line = pasted.replace("\r\n", " ").replace(['\r', '\n'], " "); - self.insert_at_cursor(&single_line); - cx.emit(Changed(self.value.clone())); - cx.notify(); - } + if ks.key == "enter" { + cx.emit(Submitted(self.value.clone())); return; } - match ks.key.as_str() { - "enter" => { - cx.emit(Submitted(self.value.clone())); - return; - } - "left" => { - self.cursor = prev_char_boundary(&self.value, self.cursor); - cx.notify(); - return; - } - "right" => { - self.cursor = next_char_boundary(&self.value, self.cursor); - cx.notify(); - return; - } - "home" => { - self.cursor = 0; + match handle_common_key(&mut self.buf, &mut self.value, self.password, ks, cx) { + CommonKeyResult::Moved => { cx.notify(); return; } - "end" => { - self.cursor = self.value.len(); + CommonKeyResult::Edited => { + cx.emit(Changed(self.value.clone())); cx.notify(); return; } - "backspace" => { - if self.cursor > 0 { - let prev = prev_char_boundary(&self.value, self.cursor); - self.value.drain(prev..self.cursor); - self.cursor = prev; - cx.emit(Changed(self.value.clone())); - cx.notify(); - } - return; - } - "delete" => { - if self.cursor < self.value.len() { - let next = next_char_boundary(&self.value, self.cursor); - self.value.drain(self.cursor..next); - cx.emit(Changed(self.value.clone())); - cx.notify(); - } - return; - } - _ => {} + CommonKeyResult::NotHandled => {} } if is_printable(ks) && let Some(ch) = &ks.key_char { - self.insert_at_cursor(ch); + self.buf.replace_selection(&mut self.value, ch); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -215,11 +603,7 @@ impl EntityInputHandler for TextInput { _window: &mut Window, _cx: &mut Context, ) -> Option { - let pos = utf16_len(&self.value[..self.cursor.min(self.value.len())]); - Some(UTF16Selection { - range: pos..pos, - reversed: false, - }) + Some(self.buf.selected_text_range(&self.value)) } fn marked_text_range( @@ -227,10 +611,15 @@ impl EntityInputHandler for TextInput { _window: &mut Window, _cx: &mut Context, ) -> Option> { - None + self.buf.marked_text_range(&self.value) } - fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) {} + fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context) { + if self.buf.marked.take().is_some() { + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + } fn replace_text_in_range( &mut self, @@ -239,15 +628,7 @@ impl EntityInputHandler for TextInput { _window: &mut Window, cx: &mut Context, ) { - let clean = text.replace("\r\n", " ").replace(['\r', '\n'], " "); - if let Some(r) = range { - let br = utf16_range_to_byte_range(&self.value, r); - let start = br.start; - self.value.replace_range(br, &clean); - self.cursor = start + clean.len(); - } else { - self.insert_at_cursor(&clean); - } + self.buf.commit_text(&mut self.value, range, text); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -256,11 +637,13 @@ impl EntityInputHandler for TextInput { &mut self, range: Option>, new_text: &str, - _new_selected_range: Option>, - window: &mut Window, + new_selected_range: Option>, + _window: &mut Window, cx: &mut Context, ) { - self.replace_text_in_range(range, new_text, window, cx); + self.buf + .mark_text(&mut self.value, range, new_text, new_selected_range); + cx.notify(); } fn bounds_for_range( @@ -275,11 +658,15 @@ impl EntityInputHandler for TextInput { fn character_index_for_point( &mut self, - _point: Point, + point: Point, _window: &mut Window, _cx: &mut Context, ) -> Option { - Some(utf16_len(&self.value[..self.cursor.min(self.value.len())])) + let pad_x = if self.bare { 0.0 } else { 10.0 }; + let b = self + .buf + .byte_index_for_point(&self.value, point, pad_x, 0.0); + Some(utf16_len(&self.value[..b])) } } @@ -296,28 +683,34 @@ impl Render for TextInput { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = crate::Theme::of(cx); let focused = self.focus.is_focused(window); - let display: SharedString = if self.value.is_empty() { - self.placeholder.clone() - } else if self.password { - "*".repeat(self.value.chars().count()).into() - } else { - self.value.clone().into() - }; - let color = if self.value.is_empty() { - t.muted_foreground - } else { - t.foreground - }; let entity = cx.entity(); let focus = self.focus.clone(); + let bounds_cell = self.buf.bounds.clone(); let ime = canvas( - |_, _, _| {}, + move |bounds, _, _| bounds_cell.set(bounds), move |bounds, _, window, cx| { window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); }, ) .absolute() .inset_0(); + let body = if self.value.is_empty() { + let mut row = div().flex().items_center().text_color(t.muted_foreground); + if focused { + row = row.child(caret_el(&t)); + } + row.child(self.placeholder.clone()).into_any_element() + } else { + render_line_segments( + &self.value, + 0, + focused, + self.buf.selection_range(self.value.len()), + self.buf.cursor, + self.password, + &t, + ) + }; let mut el = div() .relative() .track_focus(&self.focus) @@ -326,16 +719,22 @@ impl Render for TextInput { .flex() .items_center() .text_size(px(13.)) - .text_color(color) + .text_color(t.foreground) .on_mouse_down( MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, window, _cx| { + cx.listener(|this, ev: &MouseDownEvent, window, cx| { this.focus.focus(window); + let pad_x = if this.bare { 0.0 } else { 10.0 }; + let idx = this + .buf + .byte_index_for_point(&this.value, ev.position, pad_x, 0.0); + this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); + cx.notify(); }), ) .on_key_down(cx.listener(Self::on_key_down)) .child(ime) - .child(display); + .child(body); if !self.bare { el = el .px(px(10.)) @@ -356,7 +755,7 @@ pub struct Textarea { pub submit_on_enter: bool, pub min_height: Pixels, pub max_height: Option, - cursor: usize, + buf: EditState, focus: FocusHandle, scroll: ScrollHandle, } @@ -374,7 +773,7 @@ impl Textarea { submit_on_enter: false, min_height: px(64.), max_height: None, - cursor: 0, + buf: EditState::new(false), focus: cx.focus_handle(), scroll: ScrollHandle::new(), } @@ -390,7 +789,7 @@ impl Textarea { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); - self.cursor = self.value.len(); + self.buf.reset_to_end(&self.value); self.scroll.scroll_to_bottom(); cx.notify(); } @@ -403,85 +802,43 @@ impl Textarea { self.set_value(String::new(), cx); } - fn insert_at_cursor(&mut self, text: &str) { - let pos = self.cursor.min(self.value.len()); - self.value.insert_str(pos, text); - self.cursor = pos + text.len(); + fn maybe_scroll_end(&self) { + if self.buf.cursor >= self.value.len() { + self.scroll.scroll_to_bottom(); + } } fn on_key_down(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { let ks = &ev.keystroke; - let paste = (ks.modifiers.control || ks.modifiers.platform) - && !ks.modifiers.alt - && ks.key.eq_ignore_ascii_case("v"); - if paste { - if let Some(pasted) = read_paste(cx) { - self.insert_at_cursor(&pasted.replace("\r\n", "\n")); - self.scroll.scroll_to_bottom(); - cx.emit(Changed(self.value.clone())); - cx.notify(); + if ks.key == "enter" { + if self.submit_on_enter && !ks.modifiers.shift { + cx.emit(Submitted(self.value.clone())); + return; } + self.buf.replace_selection(&mut self.value, "\n"); + self.maybe_scroll_end(); + cx.emit(Changed(self.value.clone())); + cx.notify(); return; } - match ks.key.as_str() { - "enter" => { - if self.submit_on_enter && !ks.modifiers.shift { - cx.emit(Submitted(self.value.clone())); - return; - } - self.insert_at_cursor("\n"); - self.scroll.scroll_to_bottom(); - cx.emit(Changed(self.value.clone())); - cx.notify(); - return; - } - "left" => { - self.cursor = prev_char_boundary(&self.value, self.cursor); - cx.notify(); - return; - } - "right" => { - self.cursor = next_char_boundary(&self.value, self.cursor); - cx.notify(); - return; - } - "home" => { - self.cursor = 0; + match handle_common_key(&mut self.buf, &mut self.value, false, ks, cx) { + CommonKeyResult::Moved => { cx.notify(); return; } - "end" => { - self.cursor = self.value.len(); + CommonKeyResult::Edited => { + self.maybe_scroll_end(); + cx.emit(Changed(self.value.clone())); cx.notify(); return; } - "backspace" => { - if self.cursor > 0 { - let prev = prev_char_boundary(&self.value, self.cursor); - self.value.drain(prev..self.cursor); - self.cursor = prev; - self.scroll.scroll_to_bottom(); - cx.emit(Changed(self.value.clone())); - cx.notify(); - } - return; - } - "delete" => { - if self.cursor < self.value.len() { - let next = next_char_boundary(&self.value, self.cursor); - self.value.drain(self.cursor..next); - cx.emit(Changed(self.value.clone())); - cx.notify(); - } - return; - } - _ => {} + CommonKeyResult::NotHandled => {} } if is_printable(ks) && let Some(ch) = &ks.key_char { - self.insert_at_cursor(ch); - self.scroll.scroll_to_bottom(); + self.buf.replace_selection(&mut self.value, ch); + self.maybe_scroll_end(); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -507,11 +864,7 @@ impl EntityInputHandler for Textarea { _window: &mut Window, _cx: &mut Context, ) -> Option { - let pos = utf16_len(&self.value[..self.cursor.min(self.value.len())]); - Some(UTF16Selection { - range: pos..pos, - reversed: false, - }) + Some(self.buf.selected_text_range(&self.value)) } fn marked_text_range( @@ -519,10 +872,15 @@ impl EntityInputHandler for Textarea { _window: &mut Window, _cx: &mut Context, ) -> Option> { - None + self.buf.marked_text_range(&self.value) } - fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) {} + fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context) { + if self.buf.marked.take().is_some() { + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + } fn replace_text_in_range( &mut self, @@ -531,16 +889,8 @@ impl EntityInputHandler for Textarea { _window: &mut Window, cx: &mut Context, ) { - let clean = text.replace("\r\n", "\n"); - if let Some(r) = range { - let br = utf16_range_to_byte_range(&self.value, r); - let start = br.start; - self.value.replace_range(br, &clean); - self.cursor = start + clean.len(); - } else { - self.insert_at_cursor(&clean); - } - self.scroll.scroll_to_bottom(); + self.buf.commit_text(&mut self.value, range, text); + self.maybe_scroll_end(); cx.emit(Changed(self.value.clone())); cx.notify(); } @@ -549,11 +899,13 @@ impl EntityInputHandler for Textarea { &mut self, range: Option>, new_text: &str, - _new_selected_range: Option>, - window: &mut Window, + new_selected_range: Option>, + _window: &mut Window, cx: &mut Context, ) { - self.replace_text_in_range(range, new_text, window, cx); + self.buf + .mark_text(&mut self.value, range, new_text, new_selected_range); + cx.notify(); } fn bounds_for_range( @@ -568,11 +920,15 @@ impl EntityInputHandler for Textarea { fn character_index_for_point( &mut self, - _point: Point, + point: Point, _window: &mut Window, _cx: &mut Context, ) -> Option { - Some(utf16_len(&self.value[..self.cursor.min(self.value.len())])) + let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let b = self + .buf + .byte_index_for_point(&self.value, point, pad_x, pad_y); + Some(utf16_len(&self.value[..b])) } } @@ -589,26 +945,41 @@ impl Render for Textarea { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = crate::Theme::of(cx); let focused = self.focus.is_focused(window); - let display: SharedString = if self.value.is_empty() { - self.placeholder.clone() - } else { - self.value.clone().into() - }; - let color = if self.value.is_empty() { - t.muted_foreground - } else { - t.foreground - }; let entity = cx.entity(); let focus = self.focus.clone(); + let bounds_cell = self.buf.bounds.clone(); let ime = canvas( - |_, _, _| {}, + move |bounds, _, _| bounds_cell.set(bounds), move |bounds, _, window, cx| { window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); }, ) .absolute() .inset_0(); + let body = if self.value.is_empty() { + let mut row = div().flex().items_center().text_color(t.muted_foreground); + if focused { + row = row.child(caret_el(&t)); + } + row.child(self.placeholder.clone()).into_any_element() + } else { + let sel = self.buf.selection_range(self.value.len()); + let mut lines_col = div().flex().flex_col().w_full(); + let mut offset = 0usize; + for line in self.value.split('\n') { + lines_col = lines_col.child(render_line_segments( + line, + offset, + focused, + sel.clone(), + self.buf.cursor, + false, + &t, + )); + offset += line.len() + 1; + } + lines_col.into_any_element() + }; let mut el = div() .id("textarea-scroll") .relative() @@ -619,16 +990,22 @@ impl Render for Textarea { .flex() .items_start() .text_size(px(13.)) - .text_color(color) + .text_color(t.foreground) .on_mouse_down( MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, window, _cx| { + cx.listener(|this, ev: &MouseDownEvent, window, cx| { this.focus.focus(window); + let (pad_x, pad_y) = if this.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let idx = this + .buf + .byte_index_for_point(&this.value, ev.position, pad_x, pad_y); + this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); + cx.notify(); }), ) .on_key_down(cx.listener(Self::on_key_down)) .child(ime) - .child(display); + .child(body); if let Some(max_h) = self.max_height { el = el.max_h(max_h).overflow_y_scroll(); } @@ -636,7 +1013,7 @@ impl Render for Textarea { el = el .px(px(10.)) .py(px(8.)) - .rounded(px(8.)) + .rounded(px(6.)) .bg(t.background) .border_1() .border_color(if focused { t.ring } else { t.input }); @@ -644,3 +1021,41 @@ impl Render for Textarea { el } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selection_replace_and_ime_marking() { + let mut val = "hello world".to_string(); + let mut buf = EditState::new(false); + buf.select_all(val.len()); + assert_eq!(buf.selection_range(val.len()), 0..11); + + buf.move_to(5, val.len(), false); + buf.move_to(11, val.len(), true); + assert_eq!(buf.selection_range(val.len()), 5..11); + + buf.mark_text(&mut val, None, "nihao", None); + assert_eq!(val, "hellonihao"); + assert_eq!(buf.marked_text_range(&val), Some(5..10)); + + buf.commit_text(&mut val, None, "你好"); + assert_eq!(val, "hello你好"); + assert_eq!(buf.marked_text_range(&val), None); + } + + #[test] + fn vertical_movement_preserves_column() { + let val = "abcd\nxy\n12345"; + let mut buf = EditState::new(false); + buf.move_to(3, val.len(), false); // 'd' on line 1 (col 3) + buf.move_vertical(val, true, false); + assert_eq!(buf.cursor, 7); // end of "xy" (len 2) + buf.move_vertical(val, true, false); + assert_eq!(buf.cursor, 10); // col 2 on "12345" + buf.move_vertical(val, false, false); + assert_eq!(buf.cursor, 7); + } +} From adc88d6782cd6fda651fa418f986a3da1d115580 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:47:50 -0500 Subject: [PATCH 08/16] fix: address all 8 P2 findings from Loopy review #6 --- crates/mantis-agent/src/harness.rs | 70 +++++++----- vendor/mantis-ui/src/components.rs | 65 +++++++---- vendor/mantis-ui/src/input.rs | 176 ++++++++++++++++++++++++----- 3 files changed, 233 insertions(+), 78 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index a239bea..8fd5998 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -54,30 +54,46 @@ pub(crate) fn command_for(program: &Path) -> Command { fn npm_node_command(shim: &Path) -> Option { let dir = shim.parent()?; let text = std::fs::read_to_string(shim).ok()?; - for (idx, _) in text.match_indices("node_modules") { - let rest = &text[idx..]; - let end = rest - .find(['"', '\'', ' ', '\t', '\r', '\n', ';']) - .unwrap_or(rest.len()); - let target = dir.join(rest[..end].replace('/', "\\")); - if !target.is_file() { + for raw in text.split(['"', '\'', ' ', '\t', '\r', '\n', ';']) { + let mut tok = raw.trim(); + for prefix in [ + "%~dp0%", + "%~dp0", + "%dp0%", + "$basedir/", + "$basedir\\", + "./", + ".\\", + ] { + if let Some(rest) = tok.strip_prefix(prefix) { + tok = rest; + } + } + let tok = tok.trim_start_matches(['/', '\\']); + if tok.is_empty() { continue; } - let ext = target.extension().and_then(|e| e.to_str()).unwrap_or(""); - if ext.eq_ignore_ascii_case("exe") { - return Some(Command::new(target)); + let candidate = dir.join(tok.replace('/', "\\")); + let ext = candidate + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + if !matches!(ext.as_str(), "exe" | "js" | "mjs" | "cjs") || !candidate.is_file() { + continue; } - if matches!(ext.to_ascii_lowercase().as_str(), "js" | "mjs" | "cjs") { - let node = dir.join("node.exe"); - let exe = if node.is_file() { - node - } else { - PathBuf::from("node.exe") - }; - let mut cmd = Command::new(exe); - cmd.arg(target); - return Some(cmd); + if ext == "exe" { + return Some(Command::new(candidate)); } + let node = dir.join("node.exe"); + let exe = if node.is_file() { + node + } else { + PathBuf::from("node.exe") + }; + let mut cmd = Command::new(exe); + cmd.arg(candidate); + return Some(cmd); } None } @@ -380,14 +396,18 @@ impl Harness { let mut stdin = child.stdin.take(); let lines = lines_of(child.stdout.take().context("no output from Claude Code")?); let errors = Arc::new(Mutex::new(String::new())); - let stderr_thread = child.stderr.take().map(|mut err| { + let (err_done_tx, err_done_rx) = mpsc::channel::<()>(); + if let Some(mut err) = child.stderr.take() { let errors = errors.clone(); std::thread::spawn(move || { let mut text = String::new(); let _ = err.read_to_string(&mut text); *errors.lock().unwrap_or_else(|p| p.into_inner()) = text; - }) - }); + let _ = err_done_tx.send(()); + }); + } else { + let _ = err_done_tx.send(()); + } if let Some(input) = stdin.as_mut() { say(input, prompt)?; } @@ -428,9 +448,7 @@ impl Harness { if run.stopped { return Ok(run); } - if let Some(handle) = stderr_thread { - let _ = handle.join(); - } + let _ = err_done_rx.recv_timeout(Duration::from_millis(200)); let said = format!( "{}\n{}", errors.lock().unwrap_or_else(|p| p.into_inner()), diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index fcaf1f5..9247a28 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1,7 +1,7 @@ use gpui::{ - AnyElement, AnyView, App, AppContext, ClickEvent, ElementId, FontWeight, Hsla, - InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, - StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, svg, + Animation, AnimationExt as _, AnyElement, AnyView, App, AppContext, ClickEvent, ElementId, + FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, + SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, svg, }; use std::rc::Rc; @@ -646,8 +646,16 @@ impl RenderOnce for Badge { .text_color(fg); if let Some(icon) = self.icon { el = el.child(Icon::new(icon).size(px(11.)).color(fg)); - } else if self.spinner.is_some() { - el = el.child(div().size(px(6.)).rounded(px(3.)).bg(fg)); + } else if let Some(sid) = self.spinner { + let dot = div().size(px(6.)).rounded(px(3.)).bg(fg).with_animation( + sid, + Animation::new(std::time::Duration::from_millis(900)).repeat(), + |d, delta| { + let pulse = 0.35 + 0.65 * (1.0 - (delta * 2.0 - 1.0).abs()); + d.opacity(pulse) + }, + ); + el = el.child(dot); } el.child(self.label) } @@ -1340,26 +1348,18 @@ impl RenderOnce for Slider { let drag_out = drag_state; let bounds_move = bounds_state.clone(); let cb_move = cb.clone(); - let compute = move |x: Pixels, cx: &App| { - let b = *bounds_state.read(cx); - let w = f32::from(b.size.width).max(1.0); - let rel = ((f32::from(x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); - let mut val = min + rel * (max - min); - if step > 0.0 { - val = min + ((val - min) / step).round() * step; - } - val.clamp(min, max) - }; - let compute_move = move |x: Pixels, cx: &App| { - let b = *bounds_move.read(cx); + let slider_val = move |b: gpui::Bounds, x: Pixels| { + let (lo, hi) = if min <= max { (min, max) } else { (max, min) }; let w = f32::from(b.size.width).max(1.0); let rel = ((f32::from(x) - f32::from(b.origin.x)) / w).clamp(0.0, 1.0); let mut val = min + rel * (max - min); if step > 0.0 { val = min + ((val - min) / step).round() * step; } - val.clamp(min, max) + val.clamp(lo, hi) }; + let compute = move |x: Pixels, cx: &App| slider_val(*bounds_state.read(cx), x); + let compute_move = move |x: Pixels, cx: &App| slider_val(*bounds_move.read(cx), x); el = el .on_mouse_down(gpui::MouseButton::Left, move |ev, window, cx| { drag_down.update(cx, |d, _| *d = true); @@ -2417,6 +2417,7 @@ impl RenderOnce for MenuItem { pub struct MenuContent { width_px: Pixels, items: Vec, + on_close: Option>, } #[derive(IntoElement)] @@ -2434,6 +2435,7 @@ impl MenuContent { Self { width_px: px(160.), items: Vec::new(), + on_close: None, } } @@ -2442,7 +2444,8 @@ impl MenuContent { self } - pub fn on_close(self, _f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); self } @@ -2557,6 +2560,8 @@ impl RenderOnce for DropdownMenu { .children(self.trigger), ); if is_open { + let close_cb_pick = self.menu.on_close.clone(); + let close_cb_out = self.menu.on_close.clone(); root = root.child( gpui::deferred( gpui::anchored() @@ -2565,12 +2570,18 @@ impl RenderOnce for DropdownMenu { .child( div() .mt(px(4.)) - .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { cx.stop_propagation(); close_pick.update(cx, |o, _| *o = false); + if let Some(cb) = &close_cb_pick { + cb(window, cx); + } }) - .on_mouse_down_out(move |_, _, cx| { + .on_mouse_down_out(move |_, window, cx| { close_out.update(cx, |o, _| *o = false); + if let Some(cb) = &close_cb_out { + cb(window, cx); + } }) .child(self.menu), ), @@ -2642,18 +2653,26 @@ impl RenderOnce for ContextMenu { } d = d.children(self.children); if let Some(at) = pos { + let close_cb_pick = self.menu.on_close.clone(); + let close_cb_out = self.menu.on_close.clone(); d = d.child( gpui::deferred( gpui::anchored().position(at).snap_to_window().child( div() - .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { cx.stop_propagation(); close_pick.update(cx, |p, _| *p = None); active_close_pick.update(cx, |a, _| *a = None); + if let Some(cb) = &close_cb_pick { + cb(window, cx); + } }) - .on_mouse_down_out(move |_, _, cx| { + .on_mouse_down_out(move |_, window, cx| { close_out.update(cx, |p, _| *p = None); active_close_out.update(cx, |a, _| *a = None); + if let Some(cb) = &close_cb_out { + cb(window, cx); + } }) .child(self.menu), ), diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 3930bad..bc4c584 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -1,10 +1,11 @@ use gpui::{ AnyElement, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, - EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyDownEvent, - MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Render, ScrollHandle, SharedString, - StatefulInteractiveElement, Styled, UTF16Selection, Window, canvas, div, px, + EventEmitter, FocusHandle, Focusable, Font, InteractiveElement, IntoElement, KeyDownEvent, + MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, + Render, ScrollHandle, SharedString, StatefulInteractiveElement, Styled, TextRun, + UTF16Selection, Window, black, canvas, div, font, px, }; -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::ops::Range; use std::rc::Rc; @@ -94,6 +95,8 @@ struct EditState { anchor: usize, marked: Option>, bounds: Rc>>, + metrics: Rc>, + dragging: bool, single_line: bool, } @@ -104,6 +107,8 @@ impl EditState { anchor: 0, marked: None, bounds: Rc::new(Cell::new(Bounds::default())), + metrics: Rc::new(RefCell::new((px(13.), px(18.), font(".SystemUIFont")))), + dragging: false, single_line, } } @@ -209,17 +214,48 @@ impl EditState { fn byte_index_for_point( &self, value: &str, + password: bool, point: Point, pad_x: f32, pad_y: f32, + window: &Window, ) -> usize { let b = self.bounds.get(); - let char_w = 7.4_f32; - let line_h = 19.0_f32; + let (font_size, line_h_px, text_font) = self.metrics.borrow().clone(); + let line_h = f32::from(line_h_px).max(18.0); let rel_x = (f32::from(point.x - b.origin.x) - pad_x).max(0.0); - let col = (rel_x / char_w).round() as usize; + + let shape_col = |line_str: &str| -> usize { + if line_str.is_empty() { + return 0; + } + let shaped_str: String = if password { + "*".repeat(line_str.chars().count()) + } else { + line_str.to_string() + }; + let run = TextRun { + len: shaped_str.len(), + font: text_font.clone(), + color: black(), + background_color: None, + underline: None, + strikethrough: None, + }; + let shaped = + window + .text_system() + .shape_line(shaped_str.into(), font_size, &[run], None); + let idx = shaped.closest_index_for_x(px(rel_x)); + if password { + advance_chars_in_slice(line_str, idx) + } else { + idx.min(line_str.len()) + } + }; + if self.single_line { - return advance_chars_in_slice(value, col); + return shape_col(value); } let rel_y = (f32::from(point.y - b.origin.y) - pad_y).max(0.0); let target_line = (rel_y / line_h).floor() as usize; @@ -230,7 +266,7 @@ impl EditState { let line_end = value[line_start..] .find('\n') .map_or(value.len(), |n| line_start + n); - return line_start + advance_chars_in_slice(&value[line_start..line_end], col); + return line_start + shape_col(&value[line_start..line_end]); } if ch == '\n' { line_idx += 1; @@ -240,7 +276,7 @@ impl EditState { let line_end = value[line_start..] .find('\n') .map_or(value.len(), |n| line_start + n); - line_start + advance_chars_in_slice(&value[line_start..line_end], col) + line_start + shape_col(&value[line_start..line_end]) } fn selected_text_range(&self, value: &str) -> UTF16Selection { @@ -335,11 +371,9 @@ fn handle_common_key( return CommonKeyResult::Moved; } if ks.key.eq_ignore_ascii_case("x") { - if buf.has_selection(value.len()) { - if !password { - let r = buf.selection_range(value.len()); - write_copy(cx, value[r].to_string()); - } + if !password && buf.has_selection(value.len()) { + let r = buf.selection_range(value.len()); + write_copy(cx, value[r].to_string()); buf.replace_selection(value, ""); return CommonKeyResult::Edited; } @@ -659,13 +693,13 @@ impl EntityInputHandler for TextInput { fn character_index_for_point( &mut self, point: Point, - _window: &mut Window, + window: &mut Window, _cx: &mut Context, ) -> Option { let pad_x = if self.bare { 0.0 } else { 10.0 }; - let b = self - .buf - .byte_index_for_point(&self.value, point, pad_x, 0.0); + let b = + self.buf + .byte_index_for_point(&self.value, self.password, point, pad_x, 0.0, window); Some(utf16_len(&self.value[..b])) } } @@ -686,8 +720,17 @@ impl Render for TextInput { let entity = cx.entity(); let focus = self.focus.clone(); let bounds_cell = self.buf.bounds.clone(); + let metrics_cell = self.buf.metrics.clone(); let ime = canvas( - move |bounds, _, _| bounds_cell.set(bounds), + move |bounds, window, _| { + bounds_cell.set(bounds); + let style = window.text_style(); + let rem = window.rem_size(); + let font_size = style.font_size.to_pixels(rem); + let line_h = + px(f32::from(style.line_height.to_pixels(font_size.into(), rem)).max(18.0)); + *metrics_cell.borrow_mut() = (font_size, line_h, style.font()); + }, move |bounds, _, window, cx| { window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); }, @@ -724,14 +767,47 @@ impl Render for TextInput { MouseButton::Left, cx.listener(|this, ev: &MouseDownEvent, window, cx| { this.focus.focus(window); + this.buf.dragging = true; let pad_x = if this.bare { 0.0 } else { 10.0 }; - let idx = this - .buf - .byte_index_for_point(&this.value, ev.position, pad_x, 0.0); + let idx = this.buf.byte_index_for_point( + &this.value, + this.password, + ev.position, + pad_x, + 0.0, + window, + ); this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); cx.notify(); }), ) + .on_mouse_move(cx.listener(|this, ev: &MouseMoveEvent, window, cx| { + if this.buf.dragging && ev.pressed_button == Some(MouseButton::Left) { + let pad_x = if this.bare { 0.0 } else { 10.0 }; + let idx = this.buf.byte_index_for_point( + &this.value, + this.password, + ev.position, + pad_x, + 0.0, + window, + ); + this.buf.move_to(idx, this.value.len(), true); + cx.notify(); + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _: &MouseUpEvent, _, _| { + this.buf.dragging = false; + }), + ) + .on_mouse_up_out( + MouseButton::Left, + cx.listener(|this, _: &MouseUpEvent, _, _| { + this.buf.dragging = false; + }), + ) .on_key_down(cx.listener(Self::on_key_down)) .child(ime) .child(body); @@ -921,13 +997,13 @@ impl EntityInputHandler for Textarea { fn character_index_for_point( &mut self, point: Point, - _window: &mut Window, + window: &mut Window, _cx: &mut Context, ) -> Option { let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; let b = self .buf - .byte_index_for_point(&self.value, point, pad_x, pad_y); + .byte_index_for_point(&self.value, false, point, pad_x, pad_y, window); Some(utf16_len(&self.value[..b])) } } @@ -948,8 +1024,17 @@ impl Render for Textarea { let entity = cx.entity(); let focus = self.focus.clone(); let bounds_cell = self.buf.bounds.clone(); + let metrics_cell = self.buf.metrics.clone(); let ime = canvas( - move |bounds, _, _| bounds_cell.set(bounds), + move |bounds, window, _| { + bounds_cell.set(bounds); + let style = window.text_style(); + let rem = window.rem_size(); + let font_size = style.font_size.to_pixels(rem); + let line_h = + px(f32::from(style.line_height.to_pixels(font_size.into(), rem)).max(18.0)); + *metrics_cell.borrow_mut() = (font_size, line_h, style.font()); + }, move |bounds, _, window, cx| { window.handle_input(&focus, ElementInputHandler::new(bounds, entity.clone()), cx); }, @@ -995,14 +1080,47 @@ impl Render for Textarea { MouseButton::Left, cx.listener(|this, ev: &MouseDownEvent, window, cx| { this.focus.focus(window); + this.buf.dragging = true; let (pad_x, pad_y) = if this.bare { (0.0, 0.0) } else { (10.0, 8.0) }; - let idx = this - .buf - .byte_index_for_point(&this.value, ev.position, pad_x, pad_y); + let idx = this.buf.byte_index_for_point( + &this.value, + false, + ev.position, + pad_x, + pad_y, + window, + ); this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); cx.notify(); }), ) + .on_mouse_move(cx.listener(|this, ev: &MouseMoveEvent, window, cx| { + if this.buf.dragging && ev.pressed_button == Some(MouseButton::Left) { + let (pad_x, pad_y) = if this.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let idx = this.buf.byte_index_for_point( + &this.value, + false, + ev.position, + pad_x, + pad_y, + window, + ); + this.buf.move_to(idx, this.value.len(), true); + cx.notify(); + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _: &MouseUpEvent, _, _| { + this.buf.dragging = false; + }), + ) + .on_mouse_up_out( + MouseButton::Left, + cx.listener(|this, _: &MouseUpEvent, _, _| { + this.buf.dragging = false; + }), + ) .on_key_down(cx.listener(Self::on_key_down)) .child(ime) .child(body); From adbc34f59f2dbed5067276bd89ad469f8ebc8d7f Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:05:48 -0500 Subject: [PATCH 09/16] fix: address all 5 P2 findings from Loopy review #7 --- crates/mantis-agent/src/harness.rs | 13 +++- vendor/mantis-ui/src/components.rs | 97 ++++++++++++++++-------------- vendor/mantis-ui/src/input.rs | 40 ++++++++++-- 3 files changed, 101 insertions(+), 49 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 8fd5998..41ee0f2 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -42,8 +42,12 @@ pub(crate) fn command_for(program: &Path) -> Command { { if let Some(ext) = program.extension().and_then(|e| e.to_str()) && (ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) - && let Some(cmd) = npm_node_command(program) { + if let Some(cmd) = npm_node_command(program) { + return cmd; + } + let mut cmd = Command::new("cmd"); + cmd.args(["/D", "/C", &program.to_string_lossy()]); return cmd; } } @@ -83,6 +87,13 @@ fn npm_node_command(shim: &Path) -> Option { continue; } if ext == "exe" { + if candidate + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.eq_ignore_ascii_case("node.exe")) + { + continue; + } return Some(Command::new(candidate)); } let node = dir.join("node.exe"); diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index 9247a28..a136155 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1298,8 +1298,12 @@ impl Slider { impl RenderOnce for Slider { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let t = crate::Theme::of(cx); - let span = (self.max - self.min).max(0.0001); - let frac = ((self.value - self.min) / span).clamp(0.0, 1.0); + let raw_span = self.max - self.min; + let frac = if raw_span.abs() < 0.0001 { + 0.0 + } else { + ((self.value - self.min) / raw_span).clamp(0.0, 1.0) + }; let bounds_state = window.use_keyed_state(crate::key(&self.id, "bounds"), cx, |_, _| { gpui::Bounds::::default() }); @@ -1921,38 +1925,30 @@ impl RenderOnce for ResizablePanelGroup { let t = crate::Theme::of(cx); let vertical = self.vertical_layout; - let mut panel_indices = Vec::new(); - for (idx, item) in self.items.iter().enumerate() { - if matches!(item, ResizableItem::Panel(_)) { - panel_indices.push(idx); + let mut panel_mins = Vec::new(); + let mut panel_defaults = Vec::new(); + for item in &self.items { + if let ResizableItem::Panel(p) = item { + panel_mins.push(p.min_pct.clamp(5.0, 90.0)); + panel_defaults.push(p.default_pct.max(5.0)); } } - - let two_panels = panel_indices.len() == 2; - let (default_pct, min_a, max_a) = if two_panels { - let p0 = match &self.items[panel_indices[0]] { - ResizableItem::Panel(p) => p, - _ => unreachable!(), - }; - let p1 = match &self.items[panel_indices[1]] { - ResizableItem::Panel(p) => p, - _ => unreachable!(), - }; - let min_a = p0.min_pct.clamp(5.0, 90.0); - let max_a = (100.0 - p1.min_pct).clamp(min_a, 95.0); - (p0.default_pct.clamp(min_a, max_a), min_a, max_a) - } else { - (50.0, 5.0, 95.0) - }; + let total_default: f32 = panel_defaults.iter().sum::().max(1.0); + let initial_pcts: Vec = panel_defaults + .iter() + .map(|d| (*d / total_default) * 100.0) + .collect(); let split_state = - window.use_keyed_state(crate::key(&self.id, "split"), cx, |_, _| default_pct); - let drag_state = window.use_keyed_state(crate::key(&self.id, "drag"), cx, |_, _| false); + window.use_keyed_state(crate::key(&self.id, "splits"), cx, |_, _| initial_pcts); + let drag_state = window.use_keyed_state(crate::key(&self.id, "drag"), cx, |_, _| { + Option::::None + }); let bounds_state = window.use_keyed_state(crate::key(&self.id, "bounds"), cx, |_, _| { std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::::default())) }); - let pct_a = (*split_state.read(cx)).clamp(min_a, max_a); + let pcts = split_state.read(cx).clone(); let bounds_for_canvas = bounds_state.read(cx).clone(); let bounds_for_move = bounds_state.read(cx).clone(); @@ -1964,18 +1960,19 @@ impl RenderOnce for ResizablePanelGroup { d = d.size_full(); } - if two_panels { + if panel_mins.len() >= 2 { let drag_move = drag_state.clone(); let split_move = split_state.clone(); let drag_up = drag_state.clone(); let drag_up_out = drag_state.clone(); + let mins = panel_mins.clone(); d = d .on_mouse_move(move |ev: &gpui::MouseMoveEvent, _, cx| { - if !*drag_move.read(cx) { + let Some(h_idx) = *drag_move.read(cx) else { return; - } + }; let bounds = bounds_for_move.get(); - let next = if vertical { + let pos_pct = if vertical { let total = f32::from(bounds.size.height); if total <= 1.0 { return; @@ -1988,13 +1985,24 @@ impl RenderOnce for ResizablePanelGroup { } (f32::from(ev.position.x - bounds.origin.x) / total) * 100.0 }; - split_move.update(cx, |p, _| *p = next.clamp(min_a, max_a)); + split_move.update(cx, |sizes, _| { + if h_idx + 1 >= sizes.len() { + return; + } + let prefix: f32 = sizes[..h_idx].iter().sum(); + let pair_sum = sizes[h_idx] + sizes[h_idx + 1]; + let min_a = mins[h_idx]; + let max_a = (pair_sum - mins[h_idx + 1]).max(min_a); + let new_a = (pos_pct - prefix).clamp(min_a, max_a); + sizes[h_idx] = new_a; + sizes[h_idx + 1] = pair_sum - new_a; + }); }) .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| { - drag_up.update(cx, |d, _| *d = false); + drag_up.update(cx, |d, _| *d = None); }) .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| { - drag_up_out.update(cx, |d, _| *d = false); + drag_up_out.update(cx, |d, _| *d = None); }) .child( gpui::canvas( @@ -2006,6 +2014,7 @@ impl RenderOnce for ResizablePanelGroup { ); } + let panel_count = panel_mins.len(); let mut panel_pos = 0usize; let mut handle_pos = 0usize; for item in self.items { @@ -2017,17 +2026,16 @@ impl RenderOnce for ResizablePanelGroup { .min_w_0() .min_h_0() .children(panel.children); - if two_panels { - if panel_pos == 0 { - let frac = pct_a / 100.0; - p = if vertical { - p.h(gpui::relative(frac)) - } else { - p.w(gpui::relative(frac)) - }; + if panel_count >= 2 && panel_pos + 1 < panel_count { + let frac = (pcts.get(panel_pos).copied().unwrap_or(50.0) / 100.0) + .clamp(0.05, 0.95); + p = if vertical { + p.h(gpui::relative(frac)) } else { - p = p.flex_1(); - } + p.w(gpui::relative(frac)) + }; + } else if panel_count >= 2 { + p = p.flex_1(); } else { let frac = (panel.default_pct / 100.0).clamp(0.05, 0.95); p = if vertical { @@ -2040,6 +2048,7 @@ impl RenderOnce for ResizablePanelGroup { d = d.child(p); } ResizableItem::Handle(_handle) => { + let h_idx = handle_pos; let hid = crate::key(&self.id, &format!("h{handle_pos}")); handle_pos += 1; let drag_down = drag_state.clone(); @@ -2049,7 +2058,7 @@ impl RenderOnce for ResizablePanelGroup { .items_center() .justify_center() .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { - drag_down.update(cx, |d, _| *d = true); + drag_down.update(cx, |d, _| *d = Some(h_idx)); }); h = if vertical { h.h(px(5.)) diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index bc4c584..2f0f6ab 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -279,6 +279,30 @@ impl EditState { line_start + shape_col(&value[line_start..line_end]) } + fn bounds_for_range( + &self, + value: &str, + range_utf16: Range, + element_bounds: Bounds, + pad_x: f32, + pad_y: f32, + ) -> Bounds { + let byte_pos = utf16_offset_to_byte(value, range_utf16.start).min(value.len()); + let (font_size, line_h_px, _) = self.metrics.borrow().clone(); + let line_h = f32::from(line_h_px).max(18.0); + let char_w = f32::from(font_size) * 0.56; + let (line_idx, col_chars) = if self.single_line { + (0usize, value[..byte_pos].chars().count()) + } else { + let line_idx = value[..byte_pos].bytes().filter(|&b| b == b'\n').count(); + let line_start = value[..byte_pos].rfind('\n').map_or(0, |i| i + 1); + (line_idx, value[line_start..byte_pos].chars().count()) + }; + let x = element_bounds.origin.x + px(pad_x + col_chars as f32 * char_w); + let y = element_bounds.origin.y + px(pad_y + line_idx as f32 * line_h); + Bounds::new(Point::new(x, y), gpui::Size::new(px(2.0), px(line_h))) + } + fn selected_text_range(&self, value: &str) -> UTF16Selection { let len = value.len(); let r = self.selection_range(len); @@ -682,12 +706,16 @@ impl EntityInputHandler for TextInput { fn bounds_for_range( &mut self, - _range_utf16: Range, + range_utf16: Range, element_bounds: Bounds, _window: &mut Window, _cx: &mut Context, ) -> Option> { - Some(element_bounds) + let pad_x = if self.bare { 0.0 } else { 10.0 }; + Some( + self.buf + .bounds_for_range(&self.value, range_utf16, element_bounds, pad_x, 0.0), + ) } fn character_index_for_point( @@ -986,12 +1014,16 @@ impl EntityInputHandler for Textarea { fn bounds_for_range( &mut self, - _range_utf16: Range, + range_utf16: Range, element_bounds: Bounds, _window: &mut Window, _cx: &mut Context, ) -> Option> { - Some(element_bounds) + let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + Some( + self.buf + .bounds_for_range(&self.value, range_utf16, element_bounds, pad_x, pad_y), + ) } fn character_index_for_point( From a3db5db3456ffc9b5b450b3a767fe06829a4142d Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:27:15 -0500 Subject: [PATCH 10/16] fix: address all 8 P2 findings from Loopy review #8 --- crates/mantis-agent/src/harness.rs | 107 +++++++++------ vendor/mantis-ui/src/components.rs | 65 +++++++-- vendor/mantis-ui/src/input.rs | 207 +++++++++++++++++++++++++---- 3 files changed, 300 insertions(+), 79 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 41ee0f2..4c72d86 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -58,53 +58,68 @@ pub(crate) fn command_for(program: &Path) -> Command { fn npm_node_command(shim: &Path) -> Option { let dir = shim.parent()?; let text = std::fs::read_to_string(shim).ok()?; - for raw in text.split(['"', '\'', ' ', '\t', '\r', '\n', ';']) { - let mut tok = raw.trim(); - for prefix in [ - "%~dp0%", - "%~dp0", - "%dp0%", - "$basedir/", - "$basedir\\", - "./", - ".\\", - ] { - if let Some(rest) = tok.strip_prefix(prefix) { - tok = rest; - } - } - let tok = tok.trim_start_matches(['/', '\\']); - if tok.is_empty() { - continue; - } - let candidate = dir.join(tok.replace('/', "\\")); - let ext = candidate - .extension() - .and_then(|e| e.to_str()) - .unwrap_or("") - .to_ascii_lowercase(); - if !matches!(ext.as_str(), "exe" | "js" | "mjs" | "cjs") || !candidate.is_file() { + for line in text.lines().rev() { + let trimmed = line.trim(); + let lower = trimmed.to_ascii_lowercase(); + if trimmed.is_empty() + || lower.starts_with("@rem") + || lower.starts_with("rem ") + || lower.starts_with("::") + || lower.starts_with('#') + || lower == "endlocal" + || lower.starts_with("exit ") + || lower.starts_with("goto ") + { continue; } - if ext == "exe" { - if candidate - .file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.eq_ignore_ascii_case("node.exe")) - { + for raw in trimmed.split(['"', '\'', ' ', '\t', ';']) { + let mut tok = raw.trim(); + for prefix in [ + "%~dp0%", + "%~dp0", + "%dp0%", + "$basedir/", + "$basedir\\", + "./", + ".\\", + ] { + if let Some(rest) = tok.strip_prefix(prefix) { + tok = rest; + } + } + let tok = tok.trim_start_matches(['/', '\\']); + if tok.is_empty() { + continue; + } + let candidate = dir.join(tok.replace('/', "\\")); + let ext = candidate + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + if !matches!(ext.as_str(), "exe" | "js" | "mjs" | "cjs") || !candidate.is_file() { continue; } - return Some(Command::new(candidate)); + if ext == "exe" { + if candidate + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.eq_ignore_ascii_case("node.exe")) + { + continue; + } + return Some(Command::new(candidate)); + } + let node = dir.join("node.exe"); + let exe = if node.is_file() { + node + } else { + PathBuf::from("node.exe") + }; + let mut cmd = Command::new(exe); + cmd.arg(candidate); + return Some(cmd); } - let node = dir.join("node.exe"); - let exe = if node.is_file() { - node - } else { - PathBuf::from("node.exe") - }; - let mut cmd = Command::new(exe); - cmd.arg(candidate); - return Some(cmd); } None } @@ -153,6 +168,14 @@ pub fn claude_code() -> Option { /// The folder Claude Code runs in for Mantis: where its sessions are filed and where pages /// are left for it to read. pub(crate) fn workdir() -> Result { + #[cfg(windows)] + let has_base = mantis_core::paths::user_home().is_some() + || std::env::var_os("LOCALAPPDATA").is_some_and(|v| !v.is_empty()); + #[cfg(not(windows))] + let has_base = mantis_core::paths::user_home().is_some(); + if !has_base { + anyhow::bail!("no home directory"); + } let dir = mantis_core::paths::app_data_dir().join("agent"); std::fs::create_dir_all(dir.join("pages"))?; Ok(dir) diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index a136155..12893f1 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -2220,6 +2220,7 @@ pub struct MessageScroller { handle: gpui::ScrollHandle, auto: bool, edge_threshold: Pixels, + fade_edges: bool, gap_px: Option, pad: Option>, items: Vec, @@ -2232,6 +2233,7 @@ impl MessageScroller { handle: handle.scroll.clone(), auto: false, edge_threshold: px(64.), + fade_edges: false, gap_px: None, pad: None, items: Vec::new(), @@ -2253,7 +2255,8 @@ impl MessageScroller { self } - pub fn fade(self, _fade: bool) -> Self { + pub fn fade(mut self, fade: bool) -> Self { + self.fade_edges = fade; self } @@ -2269,7 +2272,7 @@ impl MessageScroller { } impl RenderOnce for MessageScroller { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { if self.auto { let max_y = f32::from(self.handle.max_offset().height); let cur_y = -f32::from(self.handle.offset().y); @@ -2278,6 +2281,8 @@ impl RenderOnce for MessageScroller { self.handle.scroll_to_bottom(); } } + let fade_edges = self.fade_edges; + let bg = crate::Theme::of(cx).background; let mut d = div() .id(self.id) .track_scroll(&self.handle) @@ -2295,7 +2300,38 @@ impl RenderOnce for MessageScroller { if let Some(p) = self.pad { d = d.pt(p.top).pb(p.bottom).pl(p.left).pr(p.right); } - d.children(self.items) + d = d.children(self.items); + if !fade_edges { + return d.into_any_element(); + } + div() + .relative() + .flex() + .flex_col() + .w_full() + .flex_1() + .min_w_0() + .min_h_0() + .child(d) + .child( + div() + .absolute() + .top_0() + .left_0() + .right_0() + .h(px(12.)) + .bg(crate::alpha(bg, 0.7)), + ) + .child( + div() + .absolute() + .bottom_0() + .left_0() + .right_0() + .h(px(12.)) + .bg(crate::alpha(bg, 0.7)), + ) + .into_any_element() } } @@ -2668,6 +2704,9 @@ impl RenderOnce for ContextMenu { gpui::deferred( gpui::anchored().position(at).snap_to_window().child( div() + .on_mouse_down(gpui::MouseButton::Right, |_, _, cx| { + cx.stop_propagation(); + }) .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { cx.stop_propagation(); close_pick.update(cx, |p, _| *p = None); @@ -2777,14 +2816,18 @@ impl RenderOnce for Popover { if self.open && let Some(body) = self.content { - let mut panel = div() - .mt(px(4.)) - .p(px(16.)) - .rounded(px(10.)) - .bg(t.popover) - .border_1() - .border_color(t.border) - .child(body); + let mut panel = match self._side { + OverlaySide::Top => div().mb(px(4.)), + OverlaySide::Bottom => div().mt(px(4.)), + OverlaySide::Left => div().mr(px(4.)), + OverlaySide::Right => div().ml(px(4.)), + } + .p(px(16.)) + .rounded(px(10.)) + .bg(t.popover) + .border_1() + .border_color(t.border) + .child(body); if let Some(w) = self.width { panel = panel.w(w); } diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 2f0f6ab..e4805f3 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -83,6 +83,48 @@ fn next_char_boundary(s: &str, pos: usize) -> usize { p } +fn prev_word_boundary(s: &str, pos: usize) -> usize { + let mut p = pos.min(s.len()); + while p > 0 { + let prev = prev_char_boundary(s, p); + let ch = s[prev..p].chars().next().unwrap_or(' '); + if !ch.is_whitespace() { + break; + } + p = prev; + } + while p > 0 { + let prev = prev_char_boundary(s, p); + let ch = s[prev..p].chars().next().unwrap_or(' '); + if ch.is_whitespace() || ch.is_ascii_punctuation() { + break; + } + p = prev; + } + p +} + +fn next_word_boundary(s: &str, pos: usize) -> usize { + let mut p = pos.min(s.len()); + while p < s.len() { + let next = next_char_boundary(s, p); + let ch = s[p..next].chars().next().unwrap_or(' '); + if ch.is_whitespace() || ch.is_ascii_punctuation() { + break; + } + p = next; + } + while p < s.len() { + let next = next_char_boundary(s, p); + let ch = s[p..next].chars().next().unwrap_or(' '); + if !ch.is_whitespace() { + break; + } + p = next; + } + p +} + fn advance_chars_in_slice(slice: &str, char_count: usize) -> usize { slice .char_indices() @@ -98,6 +140,8 @@ struct EditState { metrics: Rc>, dragging: bool, single_line: bool, + undo_stack: Vec<(String, usize, usize)>, + redo_stack: Vec<(String, usize, usize)>, } impl EditState { @@ -110,6 +154,8 @@ impl EditState { metrics: Rc::new(RefCell::new((px(13.), px(18.), font(".SystemUIFont")))), dragging: false, single_line, + undo_stack: Vec::new(), + redo_stack: Vec::new(), } } @@ -117,6 +163,43 @@ impl EditState { self.cursor = value.len(); self.anchor = self.cursor; self.marked = None; + self.undo_stack.clear(); + self.redo_stack.clear(); + } + + fn push_undo(&mut self, value: &str) { + if self.undo_stack.len() >= 200 { + self.undo_stack.remove(0); + } + self.undo_stack + .push((value.to_string(), self.anchor, self.cursor)); + self.redo_stack.clear(); + } + + fn undo(&mut self, value: &mut String) -> bool { + let Some((prev, a, c)) = self.undo_stack.pop() else { + return false; + }; + self.redo_stack + .push((value.clone(), self.anchor, self.cursor)); + *value = prev; + self.anchor = a.min(value.len()); + self.cursor = c.min(value.len()); + self.marked = None; + true + } + + fn redo(&mut self, value: &mut String) -> bool { + let Some((next, a, c)) = self.redo_stack.pop() else { + return false; + }; + self.undo_stack + .push((value.clone(), self.anchor, self.cursor)); + *value = next; + self.anchor = a.min(value.len()); + self.cursor = c.min(value.len()); + self.marked = None; + true } fn selection_range(&self, len: usize) -> Range { @@ -144,6 +227,7 @@ impl EditState { } fn replace_selection(&mut self, value: &mut String, text: &str) { + self.push_undo(value); let r = self.selection_range(value.len()); let start = r.start; value.replace_range(r, text); @@ -152,13 +236,18 @@ impl EditState { self.marked = None; } - fn backspace(&mut self, value: &mut String) -> bool { + fn backspace(&mut self, value: &mut String, word: bool) -> bool { if self.has_selection(value.len()) { self.replace_selection(value, ""); return true; } if self.cursor > 0 { - let prev = prev_char_boundary(value, self.cursor); + self.push_undo(value); + let prev = if word { + prev_word_boundary(value, self.cursor) + } else { + prev_char_boundary(value, self.cursor) + }; value.drain(prev..self.cursor); self.cursor = prev; self.anchor = prev; @@ -168,13 +257,18 @@ impl EditState { false } - fn delete(&mut self, value: &mut String) -> bool { + fn delete(&mut self, value: &mut String, word: bool) -> bool { if self.has_selection(value.len()) { self.replace_selection(value, ""); return true; } if self.cursor < value.len() { - let next = next_char_boundary(value, self.cursor); + self.push_undo(value); + let next = if word { + next_word_boundary(value, self.cursor) + } else { + next_char_boundary(value, self.cursor) + }; value.drain(self.cursor..next); self.anchor = self.cursor; self.marked = None; @@ -282,23 +376,48 @@ impl EditState { fn bounds_for_range( &self, value: &str, + password: bool, range_utf16: Range, element_bounds: Bounds, pad_x: f32, pad_y: f32, + window: &Window, ) -> Bounds { let byte_pos = utf16_offset_to_byte(value, range_utf16.start).min(value.len()); - let (font_size, line_h_px, _) = self.metrics.borrow().clone(); + let (font_size, line_h_px, text_font) = self.metrics.borrow().clone(); let line_h = f32::from(line_h_px).max(18.0); - let char_w = f32::from(font_size) * 0.56; - let (line_idx, col_chars) = if self.single_line { - (0usize, value[..byte_pos].chars().count()) + let (line_idx, line_start) = if self.single_line { + (0usize, 0usize) } else { let line_idx = value[..byte_pos].bytes().filter(|&b| b == b'\n').count(); let line_start = value[..byte_pos].rfind('\n').map_or(0, |i| i + 1); - (line_idx, value[line_start..byte_pos].chars().count()) + (line_idx, line_start) }; - let x = element_bounds.origin.x + px(pad_x + col_chars as f32 * char_w); + let prefix = &value[line_start..byte_pos]; + let x_off = if prefix.is_empty() { + 0.0 + } else { + let shaped_str: String = if password { + "*".repeat(prefix.chars().count()) + } else { + prefix.to_string() + }; + let run = TextRun { + len: shaped_str.len(), + font: text_font, + color: black(), + background_color: None, + underline: None, + strikethrough: None, + }; + f32::from( + window + .text_system() + .shape_line(shaped_str.into(), font_size, &[run], None) + .width, + ) + }; + let x = element_bounds.origin.x + px(pad_x + x_off); let y = element_bounds.origin.y + px(pad_y + line_idx as f32 * line_h); Bounds::new(Point::new(x, y), gpui::Size::new(px(2.0), px(line_h))) } @@ -319,6 +438,7 @@ impl EditState { } fn commit_text(&mut self, value: &mut String, range: Option>, text: &str) { + self.push_undo(value); let clean = if self.single_line { text.replace("\r\n", " ").replace(['\r', '\n'], " ") } else { @@ -403,6 +523,25 @@ fn handle_common_key( } return CommonKeyResult::Moved; } + if ks.key.eq_ignore_ascii_case("z") { + let changed = if ks.modifiers.shift { + buf.redo(value) + } else { + buf.undo(value) + }; + return if changed { + CommonKeyResult::Edited + } else { + CommonKeyResult::Moved + }; + } + if ks.key.eq_ignore_ascii_case("y") { + return if buf.redo(value) { + CommonKeyResult::Edited + } else { + CommonKeyResult::Moved + }; + } if ks.key.eq_ignore_ascii_case("v") { if let Some(pasted) = read_paste(cx) { let clean = if buf.single_line { @@ -418,10 +557,14 @@ fn handle_common_key( } let shift = ks.modifiers.shift; + let word = (ks.modifiers.control || ks.modifiers.alt) && !ks.modifiers.platform; + let doc = ks.modifiers.control || ks.modifiers.platform; match ks.key.as_str() { "left" => { - let next = if !shift && buf.has_selection(value.len()) { + let next = if !shift && !word && buf.has_selection(value.len()) { buf.selection_range(value.len()).start + } else if word { + prev_word_boundary(value, buf.cursor) } else { prev_char_boundary(value, buf.cursor) }; @@ -429,8 +572,10 @@ fn handle_common_key( CommonKeyResult::Moved } "right" => { - let next = if !shift && buf.has_selection(value.len()) { + let next = if !shift && !word && buf.has_selection(value.len()) { buf.selection_range(value.len()).end + } else if word { + next_word_boundary(value, buf.cursor) } else { next_char_boundary(value, buf.cursor) }; @@ -438,7 +583,7 @@ fn handle_common_key( CommonKeyResult::Moved } "home" => { - let target = if buf.single_line { + let target = if buf.single_line || doc { 0 } else { let cur = buf.cursor.min(value.len()); @@ -448,7 +593,7 @@ fn handle_common_key( CommonKeyResult::Moved } "end" => { - let target = if buf.single_line { + let target = if buf.single_line || doc { value.len() } else { let cur = buf.cursor.min(value.len()); @@ -466,14 +611,14 @@ fn handle_common_key( CommonKeyResult::Moved } "backspace" => { - if buf.backspace(value) { + if buf.backspace(value, word) { CommonKeyResult::Edited } else { CommonKeyResult::Moved } } "delete" => { - if buf.delete(value) { + if buf.delete(value, word) { CommonKeyResult::Edited } else { CommonKeyResult::Moved @@ -708,14 +853,19 @@ impl EntityInputHandler for TextInput { &mut self, range_utf16: Range, element_bounds: Bounds, - _window: &mut Window, + window: &mut Window, _cx: &mut Context, ) -> Option> { let pad_x = if self.bare { 0.0 } else { 10.0 }; - Some( - self.buf - .bounds_for_range(&self.value, range_utf16, element_bounds, pad_x, 0.0), - ) + Some(self.buf.bounds_for_range( + &self.value, + self.password, + range_utf16, + element_bounds, + pad_x, + 0.0, + window, + )) } fn character_index_for_point( @@ -1016,14 +1166,19 @@ impl EntityInputHandler for Textarea { &mut self, range_utf16: Range, element_bounds: Bounds, - _window: &mut Window, + window: &mut Window, _cx: &mut Context, ) -> Option> { let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; - Some( - self.buf - .bounds_for_range(&self.value, range_utf16, element_bounds, pad_x, pad_y), - ) + Some(self.buf.bounds_for_range( + &self.value, + false, + range_utf16, + element_bounds, + pad_x, + pad_y, + window, + )) } fn character_index_for_point( From 0d4cfc4bf256d9a543435b328f1942b6d67cd37e Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:40:34 -0500 Subject: [PATCH 11/16] fix: address all 7 P2 findings from Loopy review #9 --- crates/mantis-agent/src/harness.rs | 7 +++-- vendor/mantis-ui/src/components.rs | 43 ++++++++++++++++++++++-------- vendor/mantis-ui/src/input.rs | 39 +++++++++++++++++++++------ 3 files changed, 68 insertions(+), 21 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 4c72d86..3beeba9 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -171,7 +171,10 @@ pub(crate) fn workdir() -> Result { #[cfg(windows)] let has_base = mantis_core::paths::user_home().is_some() || std::env::var_os("LOCALAPPDATA").is_some_and(|v| !v.is_empty()); - #[cfg(not(windows))] + #[cfg(target_os = "linux")] + let has_base = mantis_core::paths::user_home().is_some() + || std::env::var_os("XDG_DATA_HOME").is_some_and(|v| !v.is_empty()); + #[cfg(not(any(windows, target_os = "linux")))] let has_base = mantis_core::paths::user_home().is_some(); if !has_base { anyhow::bail!("no home directory"); @@ -482,7 +485,7 @@ impl Harness { if run.stopped { return Ok(run); } - let _ = err_done_rx.recv_timeout(Duration::from_millis(200)); + let _ = err_done_rx.recv_timeout(Duration::from_secs(2)); let said = format!( "{}\n{}", errors.lock().unwrap_or_else(|p| p.into_inner()), diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index 12893f1..b415823 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -2162,12 +2162,14 @@ pub struct ScrollableState { #[derive(Clone, Default)] pub struct MessageScrollerHandle { scroll: gpui::ScrollHandle, + animate_pending: Rc>, } impl MessageScrollerHandle { pub fn new() -> Self { Self { scroll: gpui::ScrollHandle::new(), + animate_pending: Rc::new(std::cell::Cell::new(false)), } } @@ -2178,8 +2180,13 @@ impl MessageScrollerHandle { ScrollableState { end } } - pub fn scroll_to_end(&self, _animated: bool) { - self.scroll.scroll_to_bottom(); + pub fn scroll_to_end(&self, animated: bool) { + if animated { + self.animate_pending.set(true); + } else { + self.animate_pending.set(false); + self.scroll.scroll_to_bottom(); + } } } @@ -2205,12 +2212,14 @@ impl MessageScrollerItem { impl RenderOnce for MessageScrollerItem { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - div() - .flex() - .flex_col() - .w_full() - .min_w_0() - .child(self.content) + let mut d = div().flex().flex_col().w_full().min_w_0(); + if let Some(id) = self.message_id { + return d + .id(SharedString::from(id)) + .child(self.content) + .into_any_element(); + } + d.child(self.content).into_any_element() } } @@ -2218,6 +2227,7 @@ impl RenderOnce for MessageScrollerItem { pub struct MessageScroller { id: ElementId, handle: gpui::ScrollHandle, + animate_pending: Rc>, auto: bool, edge_threshold: Pixels, fade_edges: bool, @@ -2231,6 +2241,7 @@ impl MessageScroller { Self { id: id.into(), handle: handle.scroll.clone(), + animate_pending: handle.animate_pending.clone(), auto: false, edge_threshold: px(64.), fade_edges: false, @@ -2272,8 +2283,19 @@ impl MessageScroller { } impl RenderOnce for MessageScroller { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - if self.auto { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + if self.animate_pending.get() { + let max_y = f32::from(self.handle.max_offset().height); + let cur_y = -f32::from(self.handle.offset().y); + if max_y <= 0.0 || (max_y - cur_y).abs() <= 1.0 { + self.animate_pending.set(false); + self.handle.scroll_to_bottom(); + } else { + let next_y = cur_y + (max_y - cur_y) * 0.35; + self.handle.set_offset(gpui::point(px(0.), px(-next_y))); + window.request_animation_frame(); + } + } else if self.auto { let max_y = f32::from(self.handle.max_offset().height); let cur_y = -f32::from(self.handle.offset().y); let dist = (max_y - cur_y).max(0.0); @@ -2350,7 +2372,6 @@ pub enum MenuAlign { pub enum OverlayAlign { #[default] Start, - Center, End, } diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index e4805f3..005b6e6 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -83,6 +83,10 @@ fn next_char_boundary(s: &str, pos: usize) -> usize { p } +fn is_word_char(ch: char) -> bool { + !ch.is_whitespace() && !ch.is_ascii_punctuation() +} + fn prev_word_boundary(s: &str, pos: usize) -> usize { let mut p = pos.min(s.len()); while p > 0 { @@ -93,10 +97,16 @@ fn prev_word_boundary(s: &str, pos: usize) -> usize { } p = prev; } + if p == 0 { + return 0; + } + let first_prev = prev_char_boundary(s, p); + let target_is_word = is_word_char(s[first_prev..p].chars().next().unwrap_or(' ')); + p = first_prev; while p > 0 { let prev = prev_char_boundary(s, p); let ch = s[prev..p].chars().next().unwrap_or(' '); - if ch.is_whitespace() || ch.is_ascii_punctuation() { + if is_word_char(ch) != target_is_word || ch.is_whitespace() { break; } p = prev; @@ -106,13 +116,21 @@ fn prev_word_boundary(s: &str, pos: usize) -> usize { fn next_word_boundary(s: &str, pos: usize) -> usize { let mut p = pos.min(s.len()); - while p < s.len() { - let next = next_char_boundary(s, p); - let ch = s[p..next].chars().next().unwrap_or(' '); - if ch.is_whitespace() || ch.is_ascii_punctuation() { - break; + if p < s.len() { + let first_next = next_char_boundary(s, p); + let first_ch = s[p..first_next].chars().next().unwrap_or(' '); + if !first_ch.is_whitespace() { + let target_is_word = is_word_char(first_ch); + p = first_next; + while p < s.len() { + let next = next_char_boundary(s, p); + let ch = s[p..next].chars().next().unwrap_or(' '); + if ch.is_whitespace() || is_word_char(ch) != target_is_word { + break; + } + p = next; + } } - p = next; } while p < s.len() { let next = next_char_boundary(s, p); @@ -438,7 +456,9 @@ impl EditState { } fn commit_text(&mut self, value: &mut String, range: Option>, text: &str) { - self.push_undo(value); + if self.marked.is_none() { + self.push_undo(value); + } let clean = if self.single_line { text.replace("\r\n", " ").replace(['\r', '\n'], " ") } else { @@ -462,6 +482,9 @@ impl EditState { new_text: &str, new_selected_range: Option>, ) { + if self.marked.is_none() { + self.push_undo(value); + } let clean = if self.single_line { new_text.replace("\r\n", " ").replace(['\r', '\n'], " ") } else { From 85853b8262cac1cdb3ebb39968a2eb829690ab89 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:56:17 -0500 Subject: [PATCH 12/16] fix: address all 4 findings from Loopy review #11 --- crates/mantis-agent/src/harness.rs | 14 ++++++++--- vendor/mantis-ui/src/components.rs | 16 ++++++++---- vendor/mantis-ui/src/input.rs | 40 ++++++++++++++++++++++++------ 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 3beeba9..83cbbb6 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -437,9 +437,17 @@ impl Harness { if let Some(mut err) = child.stderr.take() { let errors = errors.clone(); std::thread::spawn(move || { - let mut text = String::new(); - let _ = err.read_to_string(&mut text); - *errors.lock().unwrap_or_else(|p| p.into_inner()) = text; + let mut buf = [0u8; 4096]; + while let Ok(n) = err.read(&mut buf) { + if n == 0 { + break; + } + let chunk = String::from_utf8_lossy(&buf[..n]); + errors + .lock() + .unwrap_or_else(|p| p.into_inner()) + .push_str(&chunk); + } let _ = err_done_tx.send(()); }); } else { diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index b415823..aeef6cc 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1852,7 +1852,7 @@ impl RenderOnce for ScrollArea { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { let mut d = div().id(self.id).flex().flex_col().w_full(); if self.horizontal_scroll { - d = d.overflow_x_scroll(); + d = d.overflow_scroll(); } else { d = d.overflow_y_scroll(); } @@ -1991,9 +1991,15 @@ impl RenderOnce for ResizablePanelGroup { } let prefix: f32 = sizes[..h_idx].iter().sum(); let pair_sum = sizes[h_idx] + sizes[h_idx + 1]; - let min_a = mins[h_idx]; - let max_a = (pair_sum - mins[h_idx + 1]).max(min_a); - let new_a = (pos_pct - prefix).clamp(min_a, max_a); + let min_a = mins[h_idx].min(pair_sum); + let min_b = mins[h_idx + 1].min(pair_sum); + let (lo, hi) = if min_a <= pair_sum - min_b { + (min_a, pair_sum - min_b) + } else { + let half = pair_sum * 0.5; + (half, half) + }; + let new_a = (pos_pct - prefix).clamp(lo, hi); sizes[h_idx] = new_a; sizes[h_idx + 1] = pair_sum - new_a; }); @@ -2212,7 +2218,7 @@ impl MessageScrollerItem { impl RenderOnce for MessageScrollerItem { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - let mut d = div().flex().flex_col().w_full().min_w_0(); + let d = div().flex().flex_col().w_full().min_w_0(); if let Some(id) = self.message_id { return d .id(SharedString::from(id)) diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 005b6e6..550f414 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -330,6 +330,7 @@ impl EditState { point: Point, pad_x: f32, pad_y: f32, + scroll_y: f32, window: &Window, ) -> usize { let b = self.bounds.get(); @@ -369,7 +370,7 @@ impl EditState { if self.single_line { return shape_col(value); } - let rel_y = (f32::from(point.y - b.origin.y) - pad_y).max(0.0); + let rel_y = (f32::from(point.y - b.origin.y) - pad_y + scroll_y).max(0.0); let target_line = (rel_y / line_h).floor() as usize; let mut line_start = 0usize; let mut line_idx = 0usize; @@ -399,6 +400,7 @@ impl EditState { element_bounds: Bounds, pad_x: f32, pad_y: f32, + scroll_y: f32, window: &Window, ) -> Bounds { let byte_pos = utf16_offset_to_byte(value, range_utf16.start).min(value.len()); @@ -436,7 +438,7 @@ impl EditState { ) }; let x = element_bounds.origin.x + px(pad_x + x_off); - let y = element_bounds.origin.y + px(pad_y + line_idx as f32 * line_h); + let y = element_bounds.origin.y + px(pad_y + line_idx as f32 * line_h - scroll_y); Bounds::new(Point::new(x, y), gpui::Size::new(px(2.0), px(line_h))) } @@ -887,6 +889,7 @@ impl EntityInputHandler for TextInput { element_bounds, pad_x, 0.0, + 0.0, window, )) } @@ -898,9 +901,15 @@ impl EntityInputHandler for TextInput { _cx: &mut Context, ) -> Option { let pad_x = if self.bare { 0.0 } else { 10.0 }; - let b = - self.buf - .byte_index_for_point(&self.value, self.password, point, pad_x, 0.0, window); + let b = self.buf.byte_index_for_point( + &self.value, + self.password, + point, + pad_x, + 0.0, + 0.0, + window, + ); Some(utf16_len(&self.value[..b])) } } @@ -976,6 +985,7 @@ impl Render for TextInput { ev.position, pad_x, 0.0, + 0.0, window, ); this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); @@ -991,6 +1001,7 @@ impl Render for TextInput { ev.position, pad_x, 0.0, + 0.0, window, ); this.buf.move_to(idx, this.value.len(), true); @@ -1193,6 +1204,7 @@ impl EntityInputHandler for Textarea { _cx: &mut Context, ) -> Option> { let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let scroll_y = (-f32::from(self.scroll.offset().y)).max(0.0); Some(self.buf.bounds_for_range( &self.value, false, @@ -1200,6 +1212,7 @@ impl EntityInputHandler for Textarea { element_bounds, pad_x, pad_y, + scroll_y, window, )) } @@ -1211,9 +1224,16 @@ impl EntityInputHandler for Textarea { _cx: &mut Context, ) -> Option { let (pad_x, pad_y) = if self.bare { (0.0, 0.0) } else { (10.0, 8.0) }; - let b = self - .buf - .byte_index_for_point(&self.value, false, point, pad_x, pad_y, window); + let scroll_y = (-f32::from(self.scroll.offset().y)).max(0.0); + let b = self.buf.byte_index_for_point( + &self.value, + false, + point, + pad_x, + pad_y, + scroll_y, + window, + ); Some(utf16_len(&self.value[..b])) } } @@ -1292,12 +1312,14 @@ impl Render for Textarea { this.focus.focus(window); this.buf.dragging = true; let (pad_x, pad_y) = if this.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let scroll_y = (-f32::from(this.scroll.offset().y)).max(0.0); let idx = this.buf.byte_index_for_point( &this.value, false, ev.position, pad_x, pad_y, + scroll_y, window, ); this.buf.move_to(idx, this.value.len(), ev.modifiers.shift); @@ -1307,12 +1329,14 @@ impl Render for Textarea { .on_mouse_move(cx.listener(|this, ev: &MouseMoveEvent, window, cx| { if this.buf.dragging && ev.pressed_button == Some(MouseButton::Left) { let (pad_x, pad_y) = if this.bare { (0.0, 0.0) } else { (10.0, 8.0) }; + let scroll_y = (-f32::from(this.scroll.offset().y)).max(0.0); let idx = this.buf.byte_index_for_point( &this.value, false, ev.position, pad_x, pad_y, + scroll_y, window, ); this.buf.move_to(idx, this.value.len(), true); From e2b110430a703b2711c389d3c5afa4f495938fec Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:07:34 -0500 Subject: [PATCH 13/16] fix: address all 3 P2 findings from Loopy review #12 --- vendor/mantis-ui/src/components.rs | 9 +- vendor/mantis-ui/src/input.rs | 158 ++++++++++++++++++++--------- 2 files changed, 119 insertions(+), 48 deletions(-) diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index aeef6cc..d587c0a 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1815,6 +1815,7 @@ pub struct ScrollArea { id: ElementId, height: Option, horizontal_scroll: bool, + full: bool, children: Vec, } @@ -1824,6 +1825,7 @@ impl ScrollArea { id: id.into(), height: None, horizontal_scroll: false, + full: false, children: Vec::new(), } } @@ -1838,7 +1840,8 @@ impl ScrollArea { self } - pub fn size_full(self) -> Self { + pub fn size_full(mut self) -> Self { + self.full = true; self } @@ -1856,7 +1859,9 @@ impl RenderOnce for ScrollArea { } else { d = d.overflow_y_scroll(); } - if let Some(h) = self.height { + if self.full { + d = d.size_full().min_h_0(); + } else if let Some(h) = self.height { d = d.h(h); } else { d = d.flex_1().min_h_0(); diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 550f414..bc5ec44 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -150,6 +150,16 @@ fn advance_chars_in_slice(slice: &str, char_count: usize) -> usize { .map_or(slice.len(), |(idx, _)| idx) } +struct EditOp { + offset: usize, + removed: String, + inserted: String, + prev_anchor: usize, + prev_cursor: usize, + next_anchor: usize, + next_cursor: usize, +} + struct EditState { cursor: usize, anchor: usize, @@ -158,8 +168,8 @@ struct EditState { metrics: Rc>, dragging: bool, single_line: bool, - undo_stack: Vec<(String, usize, usize)>, - redo_stack: Vec<(String, usize, usize)>, + undo_stack: Vec, + redo_stack: Vec, } impl EditState { @@ -185,38 +195,84 @@ impl EditState { self.redo_stack.clear(); } - fn push_undo(&mut self, value: &str) { + fn reset_to_start(&mut self) { + self.cursor = 0; + self.anchor = 0; + self.marked = None; + self.undo_stack.clear(); + self.redo_stack.clear(); + } + + fn record_edit( + &mut self, + offset: usize, + removed: String, + inserted: String, + prev_anchor: usize, + prev_cursor: usize, + ) { if self.undo_stack.len() >= 200 { self.undo_stack.remove(0); } - self.undo_stack - .push((value.to_string(), self.anchor, self.cursor)); + self.undo_stack.push(EditOp { + offset, + removed, + inserted, + prev_anchor, + prev_cursor, + next_anchor: self.anchor, + next_cursor: self.cursor, + }); self.redo_stack.clear(); } + fn apply_range( + &mut self, + value: &mut String, + range: Range, + text: &str, + record_undo: bool, + ) { + let prev_anchor = self.anchor; + let prev_cursor = self.cursor; + let start = range.start; + let removed = if record_undo { + value[range.clone()].to_string() + } else { + String::new() + }; + value.replace_range(range, text); + self.cursor = start + text.len(); + self.anchor = self.cursor; + self.marked = None; + if record_undo { + self.record_edit(start, removed, text.to_string(), prev_anchor, prev_cursor); + } + } + fn undo(&mut self, value: &mut String) -> bool { - let Some((prev, a, c)) = self.undo_stack.pop() else { + let Some(op) = self.undo_stack.pop() else { return false; }; - self.redo_stack - .push((value.clone(), self.anchor, self.cursor)); - *value = prev; - self.anchor = a.min(value.len()); - self.cursor = c.min(value.len()); + let end = (op.offset + op.inserted.len()).min(value.len()); + value.replace_range(op.offset..end, &op.removed); + self.anchor = op.prev_anchor.min(value.len()); + self.cursor = op.prev_cursor.min(value.len()); self.marked = None; + self.redo_stack.push(op); true } fn redo(&mut self, value: &mut String) -> bool { - let Some((next, a, c)) = self.redo_stack.pop() else { + let Some(op) = self.redo_stack.pop() else { return false; }; - self.undo_stack - .push((value.clone(), self.anchor, self.cursor)); - *value = next; - self.anchor = a.min(value.len()); - self.cursor = c.min(value.len()); + let end = (op.offset + op.removed.len()).min(value.len()); + value.replace_range(op.offset..end, &op.inserted); + self.anchor = op.next_anchor.min(value.len()); + self.cursor = op.next_cursor.min(value.len()); self.marked = None; + self.undo_stack.push(op); true } @@ -245,13 +301,8 @@ impl EditState { } fn replace_selection(&mut self, value: &mut String, text: &str) { - self.push_undo(value); let r = self.selection_range(value.len()); - let start = r.start; - value.replace_range(r, text); - self.cursor = start + text.len(); - self.anchor = self.cursor; - self.marked = None; + self.apply_range(value, r, text, true); } fn backspace(&mut self, value: &mut String, word: bool) -> bool { @@ -260,16 +311,12 @@ impl EditState { return true; } if self.cursor > 0 { - self.push_undo(value); let prev = if word { prev_word_boundary(value, self.cursor) } else { prev_char_boundary(value, self.cursor) }; - value.drain(prev..self.cursor); - self.cursor = prev; - self.anchor = prev; - self.marked = None; + self.apply_range(value, prev..self.cursor, "", true); return true; } false @@ -281,15 +328,12 @@ impl EditState { return true; } if self.cursor < value.len() { - self.push_undo(value); let next = if word { next_word_boundary(value, self.cursor) } else { next_char_boundary(value, self.cursor) }; - value.drain(self.cursor..next); - self.anchor = self.cursor; - self.marked = None; + self.apply_range(value, self.cursor..next, "", true); return true; } false @@ -458,23 +502,25 @@ impl EditState { } fn commit_text(&mut self, value: &mut String, range: Option>, text: &str) { - if self.marked.is_none() { - self.push_undo(value); - } let clean = if self.single_line { text.replace("\r\n", " ").replace(['\r', '\n'], " ") } else { text.replace("\r\n", "\n") }; + let was_marked = self.marked.take(); let br = range .map(|r| utf16_range_to_byte_range(value, r)) - .or_else(|| self.marked.take()) + .or(was_marked.clone()) .unwrap_or_else(|| self.selection_range(value.len())); - self.marked = None; - let start = br.start; - value.replace_range(br, &clean); - self.cursor = start + clean.len(); - self.anchor = self.cursor; + self.apply_range(value, br.clone(), &clean, was_marked.is_none()); + if let Some(m_range) = was_marked + && let Some(last) = self.undo_stack.last_mut() + && last.offset == m_range.start + { + last.inserted = clean; + last.next_anchor = self.anchor; + last.next_cursor = self.cursor; + } } fn mark_text( @@ -484,9 +530,9 @@ impl EditState { new_text: &str, new_selected_range: Option>, ) { - if self.marked.is_none() { - self.push_undo(value); - } + let is_initial = self.marked.is_none(); + let prev_anchor = self.anchor; + let prev_cursor = self.cursor; let clean = if self.single_line { new_text.replace("\r\n", " ").replace(['\r', '\n'], " ") } else { @@ -497,6 +543,11 @@ impl EditState { .or_else(|| self.marked.take()) .unwrap_or_else(|| self.selection_range(value.len())); let start = br.start; + let removed = if is_initial { + value[br.clone()].to_string() + } else { + String::new() + }; value.replace_range(br, &clean); self.marked = if clean.is_empty() { None @@ -510,6 +561,13 @@ impl EditState { self.cursor = start + clean.len(); self.anchor = self.cursor; } + if is_initial { + self.record_edit(start, removed, clean, prev_anchor, prev_cursor); + } else if let Some(last) = self.undo_stack.last_mut() { + last.inserted = clean; + last.next_anchor = self.anchor; + last.next_cursor = self.cursor; + } } } @@ -1077,8 +1135,12 @@ impl Textarea { pub fn set_value(&mut self, value: impl Into, cx: &mut Context) { self.value = value.into(); - self.buf.reset_to_end(&self.value); - self.scroll.scroll_to_bottom(); + if self.max_height.is_some() { + self.buf.reset_to_end(&self.value); + self.scroll.scroll_to_bottom(); + } else { + self.buf.reset_to_start(); + } cx.notify(); } @@ -1396,6 +1458,10 @@ mod tests { buf.commit_text(&mut val, None, "你好"); assert_eq!(val, "hello你好"); assert_eq!(buf.marked_text_range(&val), None); + assert!(buf.undo(&mut val)); + assert_eq!(val, "hello world"); + assert!(buf.redo(&mut val)); + assert_eq!(val, "hello你好"); } #[test] From d17280f924e8e3348f7b278dbd592ed37e9049dc Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:17:37 -0500 Subject: [PATCH 14/16] fix: address all 3 P2 findings from Loopy review #13 --- vendor/mantis-ui/src/components.rs | 14 ++++++++++++-- vendor/mantis-ui/src/input.rs | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index d587c0a..1556ba3 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1944,8 +1944,12 @@ impl RenderOnce for ResizablePanelGroup { .map(|d| (*d / total_default) * 100.0) .collect(); - let split_state = - window.use_keyed_state(crate::key(&self.id, "splits"), cx, |_, _| initial_pcts); + let split_state = window.use_keyed_state(crate::key(&self.id, "splits"), cx, |_, _| { + initial_pcts.clone() + }); + if split_state.read(cx).len() != panel_mins.len() { + split_state.update(cx, |s, _| *s = initial_pcts); + } let drag_state = window.use_keyed_state(crate::key(&self.id, "drag"), cx, |_, _| { Option::::None }); @@ -1973,6 +1977,12 @@ impl RenderOnce for ResizablePanelGroup { let mins = panel_mins.clone(); d = d .on_mouse_move(move |ev: &gpui::MouseMoveEvent, _, cx| { + if ev.pressed_button != Some(gpui::MouseButton::Left) { + if drag_move.read(cx).is_some() { + drag_move.update(cx, |d, _| *d = None); + } + return; + } let Some(h_idx) = *drag_move.read(cx) else { return; }; diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index bc5ec44..1290157 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -1358,7 +1358,7 @@ impl Render for Textarea { lines_col.into_any_element() }; let mut el = div() - .id("textarea-scroll") + .id(("textarea-scroll", cx.entity_id())) .relative() .track_scroll(&self.scroll) .track_focus(&self.focus) From 984dcac94f05774ea3bda44af7dd099885e71fca Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:29:38 -0500 Subject: [PATCH 15/16] fix: address all 5 findings from Loopy review #14 --- crates/mantis-core/src/paths.rs | 24 +++++++------- vendor/mantis-ui/src/components.rs | 27 ++++++++++++--- vendor/mantis-ui/src/input.rs | 53 +++++++++++++++++++----------- 3 files changed, 67 insertions(+), 37 deletions(-) diff --git a/crates/mantis-core/src/paths.rs b/crates/mantis-core/src/paths.rs index 637fb4b..f46756f 100644 --- a/crates/mantis-core/src/paths.rs +++ b/crates/mantis-core/src/paths.rs @@ -2,17 +2,21 @@ use std::path::PathBuf; +fn non_empty_env(name: &str) -> Option { + std::env::var_os(name) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + /// The user's home directory (`HOME` on Unix, `USERPROFILE` or `HOME` on Windows). pub fn user_home() -> Option { #[cfg(windows)] { - std::env::var_os("USERPROFILE") - .or_else(|| std::env::var_os("HOME")) - .map(PathBuf::from) + non_empty_env("USERPROFILE").or_else(|| non_empty_env("HOME")) } #[cfg(not(windows))] { - std::env::var_os("HOME").map(PathBuf::from) + non_empty_env("HOME") } } @@ -27,16 +31,14 @@ pub fn app_data_dir() -> PathBuf { } #[cfg(target_os = "windows")] { - std::env::var_os("LOCALAPPDATA") - .map(PathBuf::from) + non_empty_env("LOCALAPPDATA") .or_else(|| user_home().map(|h| h.join("AppData/Local"))) .unwrap_or_else(std::env::temp_dir) .join("Mantis") } #[cfg(not(any(target_os = "macos", target_os = "windows")))] { - std::env::var_os("XDG_DATA_HOME") - .map(PathBuf::from) + non_empty_env("XDG_DATA_HOME") .or_else(|| user_home().map(|h| h.join(".local/share"))) .unwrap_or_else(std::env::temp_dir) .join("Mantis") @@ -57,8 +59,7 @@ pub fn cache_dir() -> PathBuf { } #[cfg(not(any(target_os = "macos", target_os = "windows")))] { - std::env::var_os("XDG_CACHE_HOME") - .map(PathBuf::from) + non_empty_env("XDG_CACHE_HOME") .or_else(|| user_home().map(|h| h.join(".cache"))) .unwrap_or_else(std::env::temp_dir) .join("Mantis") @@ -69,8 +70,7 @@ pub fn cache_dir() -> PathBuf { pub fn config_dir() -> Option { #[cfg(windows)] { - std::env::var_os("APPDATA") - .map(PathBuf::from) + non_empty_env("APPDATA") .or_else(|| user_home().map(|h| h.join("AppData/Roaming"))) .map(|p| p.join("mantis")) } diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index 1556ba3..171ed0d 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -2629,6 +2629,12 @@ impl DropdownMenu { impl RenderOnce for DropdownMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let open_state = window.use_keyed_state(crate::key(&self.id, "open"), cx, |_, _| false); + let trigger_bounds = + window.use_keyed_state(crate::key(&self.id, "trigger_bounds"), cx, |_, _| { + std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::::default())) + }); + let bounds_for_canvas = trigger_bounds.read(cx).clone(); + let bounds_for_close = trigger_bounds.read(cx).clone(); let is_open = *open_state.read(cx); let toggle = open_state.clone(); let close_out = open_state.clone(); @@ -2639,12 +2645,21 @@ impl RenderOnce for DropdownMenu { }; let mut root = div().id(self.id).relative().flex().child( div() + .relative() .flex() .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { cx.stop_propagation(); toggle.update(cx, |o, _| *o = !*o); }) - .children(self.trigger), + .children(self.trigger) + .child( + gpui::canvas( + move |bounds, _, _| bounds_for_canvas.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ), ); if is_open { let close_cb_pick = self.menu.on_close.clone(); @@ -2664,10 +2679,12 @@ impl RenderOnce for DropdownMenu { cb(window, cx); } }) - .on_mouse_down_out(move |_, window, cx| { - close_out.update(cx, |o, _| *o = false); - if let Some(cb) = &close_cb_out { - cb(window, cx); + .on_mouse_down_out(move |ev, window, cx| { + if !bounds_for_close.get().contains(&ev.position) { + close_out.update(cx, |o, _| *o = false); + if let Some(cb) = &close_cb_out { + cb(window, cx); + } } }) .child(self.menu), diff --git a/vendor/mantis-ui/src/input.rs b/vendor/mantis-ui/src/input.rs index 1290157..e319a23 100644 --- a/vendor/mantis-ui/src/input.rs +++ b/vendor/mantis-ui/src/input.rs @@ -168,6 +168,7 @@ struct EditState { metrics: Rc>, dragging: bool, single_line: bool, + goal_col: Option, undo_stack: Vec, redo_stack: Vec, } @@ -182,6 +183,7 @@ impl EditState { metrics: Rc::new(RefCell::new((px(13.), px(18.), font(".SystemUIFont")))), dragging: false, single_line, + goal_col: None, undo_stack: Vec::new(), redo_stack: Vec::new(), } @@ -191,6 +193,7 @@ impl EditState { self.cursor = value.len(); self.anchor = self.cursor; self.marked = None; + self.goal_col = None; self.undo_stack.clear(); self.redo_stack.clear(); } @@ -199,6 +202,7 @@ impl EditState { self.cursor = 0; self.anchor = 0; self.marked = None; + self.goal_col = None; self.undo_stack.clear(); self.redo_stack.clear(); } @@ -292,12 +296,14 @@ impl EditState { self.anchor = self.cursor; } self.marked = None; + self.goal_col = None; } fn select_all(&mut self, len: usize) { self.anchor = 0; self.cursor = len; self.marked = None; + self.goal_col = None; } fn replace_selection(&mut self, value: &mut String, text: &str) { @@ -343,28 +349,28 @@ impl EditState { let cur = self.cursor.min(value.len()); let line_start = value[..cur].rfind('\n').map_or(0, |i| i + 1); let line_end = value[cur..].find('\n').map_or(value.len(), |i| cur + i); - let col_chars = value[line_start..cur].chars().count(); - if !down { + let col_chars = self + .goal_col + .unwrap_or_else(|| value[line_start..cur].chars().count()); + let next_pos = if !down { if line_start == 0 { - self.move_to(0, value.len(), extend); - return; + 0 + } else { + let prev_end = line_start - 1; + let prev_start = value[..prev_end].rfind('\n').map_or(0, |i| i + 1); + prev_start + advance_chars_in_slice(&value[prev_start..prev_end], col_chars) } - let prev_end = line_start - 1; - let prev_start = value[..prev_end].rfind('\n').map_or(0, |i| i + 1); - let offset = advance_chars_in_slice(&value[prev_start..prev_end], col_chars); - self.move_to(prev_start + offset, value.len(), extend); + } else if line_end >= value.len() { + value.len() } else { - if line_end >= value.len() { - self.move_to(value.len(), value.len(), extend); - return; - } let next_start = line_end + 1; let next_end = value[next_start..] .find('\n') .map_or(value.len(), |i| next_start + i); - let offset = advance_chars_in_slice(&value[next_start..next_end], col_chars); - self.move_to(next_start + offset, value.len(), extend); - } + next_start + advance_chars_in_slice(&value[next_start..next_end], col_chars) + }; + self.move_to(next_pos, value.len(), extend); + self.goal_col = Some(col_chars); } fn byte_index_for_point( @@ -512,10 +518,11 @@ impl EditState { .map(|r| utf16_range_to_byte_range(value, r)) .or(was_marked.clone()) .unwrap_or_else(|| self.selection_range(value.len())); - self.apply_range(value, br.clone(), &clean, was_marked.is_none()); - if let Some(m_range) = was_marked + let replaces_exact_mark = was_marked.as_ref().is_some_and(|m| br == *m); + self.apply_range(value, br, &clean, !replaces_exact_mark); + if replaces_exact_mark && let Some(last) = self.undo_stack.last_mut() - && last.offset == m_range.start + && was_marked.is_some_and(|m| last.offset == m.start) { last.inserted = clean; last.next_anchor = self.anchor; @@ -940,13 +947,19 @@ impl EntityInputHandler for TextInput { _cx: &mut Context, ) -> Option> { let pad_x = if self.bare { 0.0 } else { 10.0 }; + let (_, line_h_px, _) = self.buf.metrics.borrow().clone(); + let pad_y = if self.bare { + 0.0 + } else { + ((f32::from(element_bounds.size.height) - f32::from(line_h_px)).max(0.0) * 0.5).max(4.0) + }; Some(self.buf.bounds_for_range( &self.value, self.password, range_utf16, element_bounds, pad_x, - 0.0, + pad_y, 0.0, window, )) @@ -1472,7 +1485,7 @@ mod tests { buf.move_vertical(val, true, false); assert_eq!(buf.cursor, 7); // end of "xy" (len 2) buf.move_vertical(val, true, false); - assert_eq!(buf.cursor, 10); // col 2 on "12345" + assert_eq!(buf.cursor, 11); // col 3 on "12345" buf.move_vertical(val, false, false); assert_eq!(buf.cursor, 7); } From 9bc37b89468dcee261e747b5342260d6f85aa457 Mon Sep 17 00:00:00 2001 From: Sushil Muthuvelkumar <123318620+sushilm20@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:40:19 -0500 Subject: [PATCH 16/16] fix: address all 3 P2 findings from Loopy review #15 --- crates/mantis-agent/src/harness.rs | 6 +++--- vendor/mantis-ui/src/components.rs | 29 +++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/mantis-agent/src/harness.rs b/crates/mantis-agent/src/harness.rs index 83cbbb6..fe8c18c 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -171,11 +171,11 @@ pub(crate) fn workdir() -> Result { #[cfg(windows)] let has_base = mantis_core::paths::user_home().is_some() || std::env::var_os("LOCALAPPDATA").is_some_and(|v| !v.is_empty()); - #[cfg(target_os = "linux")] + #[cfg(target_os = "macos")] + let has_base = mantis_core::paths::user_home().is_some(); + #[cfg(not(any(windows, target_os = "macos")))] let has_base = mantis_core::paths::user_home().is_some() || std::env::var_os("XDG_DATA_HOME").is_some_and(|v| !v.is_empty()); - #[cfg(not(any(windows, target_os = "linux")))] - let has_base = mantis_core::paths::user_home().is_some(); if !has_base { anyhow::bail!("no home directory"); } diff --git a/vendor/mantis-ui/src/components.rs b/vendor/mantis-ui/src/components.rs index 171ed0d..e9408df 100644 --- a/vendor/mantis-ui/src/components.rs +++ b/vendor/mantis-ui/src/components.rs @@ -1022,7 +1022,7 @@ pub struct Dialog { width_px: Pixels, title: Option, description: Option, - body: Option, + children: Vec, footer: Vec, on_close: Option>, } @@ -1035,7 +1035,7 @@ impl Dialog { width_px: px(460.), title: None, description: None, - body: None, + children: Vec::new(), footer: Vec::new(), on_close: None, } @@ -1062,12 +1062,12 @@ impl Dialog { } pub fn body(mut self, body: impl IntoElement) -> Self { - self.body = Some(body.into_any_element()); + self.children.push(body.into_any_element()); self } pub fn child(mut self, body: impl IntoElement) -> Self { - self.body = Some(body.into_any_element()); + self.children.push(body.into_any_element()); self } @@ -1110,8 +1110,8 @@ impl RenderOnce for Dialog { .child(desc), ); } - if let Some(body) = self.body { - card = card.child(body); + if !self.children.is_empty() { + card = card.children(self.children); } if !self.footer.is_empty() { card = card.child(div().flex().justify_end().gap(px(8.)).children(self.footer)); @@ -1341,6 +1341,23 @@ impl RenderOnce for Slider { .rounded(px(2.)) .bg(t.primary), ), + ) + .child( + div() + .absolute() + .inset_0() + .flex() + .items_center() + .child(div().w(gpui::relative(frac))) + .child( + div() + .ml(px(-6.)) + .size(px(12.)) + .rounded(px(6.)) + .bg(t.primary_foreground) + .border_2() + .border_color(t.primary), + ), ); if !self.disabled && let Some(cb) = self.on_change