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..8a9ce1c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +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 + - run: rustfmt --edition 2024 --check crates/mantis-core/src/paths.rs crates/mantis-app/src/snapshot.rs vendor/mantis-ui/src/*.rs + + check: + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - 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-${{ hashFiles('Cargo.lock') }} + - 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. 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/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/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..fe8c18c 100644 --- a/crates/mantis-agent/src/harness.rs +++ b/crates/mantis-agent/src/harness.rs @@ -31,25 +31,109 @@ 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); + crate::models::find_program("claude", "MANTIS_CLAUDE", "claude_path") +} + +/// 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(["/D", "/C", &program.to_string_lossy()]); + return cmd; + } } - 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")]); + 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()?; + 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; + } + 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; + } + 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); + } } - places.extend(["/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from)); - places.into_iter().map(|dir| dir.join("claude")).find(|p| runnable(p)) + None } /// 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`. 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); + 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); } } @@ -57,7 +141,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))] { @@ -73,14 +158,28 @@ 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 /// 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"); + #[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 = "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()); + 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) } @@ -115,7 +214,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. @@ -155,13 +261,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; @@ -181,7 +309,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"); } @@ -189,7 +324,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) @@ -197,31 +334,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 mut command = Command::new(&self.claude); + 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") @@ -231,17 +427,31 @@ 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())); + 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 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 { + let _ = err_done_tx.send(()); } if let Some(input) = stdin.as_mut() { say(input, prompt)?; @@ -265,7 +475,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; @@ -281,13 +493,24 @@ impl Harness { if run.stopped { 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 _ = err_done_rx.recv_timeout(Duration::from_secs(2)); + 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) } @@ -310,7 +533,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()); @@ -388,17 +613,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; } @@ -412,7 +653,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(), + }); } } } @@ -422,7 +666,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; } @@ -431,21 +679,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 { @@ -461,7 +738,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}") @@ -498,18 +779,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()), ] @@ -520,11 +820,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")); } @@ -538,7 +851,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(); @@ -546,22 +862,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/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..dc1e32e 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; + 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..75fec7e 100644 --- a/crates/mantis-agent/src/models.rs +++ b/crates/mantis-agent/src/models.rs @@ -88,13 +88,34 @@ 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")); + } + for dir in places { + for ext in ["exe", "cmd", "bat"] { + 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/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-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..46280ab 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,32 @@ 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::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 }; + unsafe { + 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), 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 /// 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..7fc8a08 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,362 @@ 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 = "CoreGraphics", kind = "framework")] -unsafe extern "C" { - fn CGEventSetIntegerValueField(event: *mut c_void, field: u32, value: i64); -} + #[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; + } -/// 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), - }; - 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; + 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, + ); } - 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; + } + + #[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); } - post(app, sel(c"postEvent:atStart:"), event, 0); } -} -fn sel(name: &CStr) -> *const c_void { - unsafe { sel_registerName(name.as_ptr()) } + fn sel(name: &CStr) -> *const c_void { + unsafe { sel_registerName(name.as_ptr()) } + } + + 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(()) + } } -/// 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() { +#[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, + }; + 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); + } } - u32::try_from(get_number(ns_window, sel(c"windowNumber"))).ok() } -} -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. + 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); + } + } + + 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"); + } + 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"); + } + 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.as_chunks::<4>().0 { 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") } - image::save_buffer(path, &rgba, w as u32, h as u32, image::ColorType::Rgba8)?; - Ok(()) +} + +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); +} + +pub fn window_id(window: &Window) -> Option { + imp::window_id(window) +} + +pub fn capture(window_id: u32, path: &Path) -> Result<()> { + 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..be17e8b 100644 --- a/crates/mantis-app/src/workspace/form.rs +++ b/crates/mantis-app/src/workspace/form.rs @@ -234,7 +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 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(); + 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-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..f46756f --- /dev/null +++ b/crates/mantis-core/src/paths.rs @@ -0,0 +1,88 @@ +//! Cross-platform user directories for Mantis. + +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)] + { + non_empty_env("USERPROFILE").or_else(|| non_empty_env("HOME")) + } + #[cfg(not(windows))] + { + non_empty_env("HOME") + } +} + +/// 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_else(std::env::temp_dir) + .join("Library/Application Support/Mantis") + } + #[cfg(target_os = "windows")] + { + 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")))] + { + 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") + } +} + +/// 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")))] + { + non_empty_env("XDG_CACHE_HOME") + .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)] + { + non_empty_env("APPDATA") + .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..6f3657d --- /dev/null +++ b/scripts/bundle.ps1 @@ -0,0 +1,38 @@ +# 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 +if ($LASTEXITCODE -ne 0) { + throw "cargo build failed with exit code $LASTEXITCODE" +} + +$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..9c24db9 --- /dev/null +++ b/scripts/shots.ps1 @@ -0,0 +1,49 @@ +# 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 +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" +} + +$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 +} + +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" +} + +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..b84f2c2 --- /dev/null +++ b/vendor/mantis-ui/src/anim.rs @@ -0,0 +1,178 @@ +use gpui::{ElementId, Window}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::time::{Duration, Instant}; + +#[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); + 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)) + } +} + +#[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()) +} + +#[derive(Clone, Copy)] +struct TweenState { + orig_from: f32, + from: f32, + to: f32, + current: f32, + started: Instant, + last_seen: Instant, +} + +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() +} + +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, + 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(); + prune_stale(&mut map, now); + let entry = map.entry(k).or_insert(TweenState { + orig_from: target, + from: target, + to: target, + current: target, + started: now, + last_seen: now, + }); + 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, + 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); + 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(); + prune_stale(&mut map, now); + let entry = map.entry(k).or_insert(TweenState { + orig_from: from, + from, + to, + current: from, + started: now, + 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); + 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 new file mode 100644 index 0000000..87ba1c5 --- /dev/null +++ b/vendor/mantis-ui/src/assets.rs @@ -0,0 +1,165 @@ +use gpui::{AssetSource, SharedString}; +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#""# + ), + ), + ( + "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 { + 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(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 new file mode 100644 index 0000000..e9408df --- /dev/null +++ b/vendor/mantis-ui/src/components.rs @@ -0,0 +1,2939 @@ +use gpui::{ + 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; + +// --------------------------------------------------------------------------- +// 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 { + if self.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() + } + } +} + +// --------------------------------------------------------------------------- +// 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 + } +} + +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, h, px_pad, text_sz) = button_style(self.variant, self.size, &t); + 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 (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(h) + .px(px_pad) + .rounded(px(5.)) + .border_1() + .border_color(border) + .text_size(text_sz) + .cursor_pointer() + .bg(bg) + .text_color(fg); + if let Some(icon) = self.icon { + el = el.child(Icon::new(icon).size(icon_sz).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 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) + } +} + +#[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, + children: Vec, + footer: Vec, + on_close: Option>, +} + +impl Dialog { + pub fn new(id: impl Into, open: bool) -> Self { + Self { + id: id.into(), + open, + width_px: px(460.), + title: None, + description: None, + children: Vec::new(), + footer: Vec::new(), + on_close: None, + } + } + + pub fn width(mut self, w: Pixels) -> Self { + self.width_px = w; + self + } + + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); + 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.children.push(body.into_any_element()); + self + } + + pub fn child(mut self, body: impl IntoElement) -> Self { + self.children.push(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 !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)); + } + 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() + .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, + 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, + step: 0.0, + disabled: false, + 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(mut self, step: f32) -> Self { + self.step = step; + self + } + + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + 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 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() + }); + 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| { + 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() + .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), + ), + ) + .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 + { + 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.clone(); + let drag_out = drag_state; + let bounds_move = bounds_state.clone(); + let cb_move = cb.clone(); + 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(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); + 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); + }) + .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| { + drag_out.update(cx, |d, _| *d = false); + }); + } + el + } +} + +#[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.span_cols > 1 { + d.style().flex_grow = Some(self.span_cols as f32); + } + if self.align_right { + d = d.justify_end(); + } + d + } +} + +// --------------------------------------------------------------------------- +// ScrollArea, Resizable, MessageScroller +// --------------------------------------------------------------------------- + +#[derive(IntoElement)] +pub struct ScrollArea { + id: ElementId, + height: Option, + horizontal_scroll: bool, + full: bool, + children: Vec, +} + +impl ScrollArea { + pub fn new(id: impl Into) -> Self { + Self { + id: id.into(), + height: None, + horizontal_scroll: false, + full: 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(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 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_scroll(); + } else { + d = d.overflow_y_scroll(); + } + 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(); + } + d.children(self.children) + } +} + +#[derive(IntoElement)] +pub struct ResizablePanelGroup { + id: ElementId, + vertical_layout: bool, + full: bool, + items: Vec, +} + +enum ResizableItem { + Panel(ResizablePanel), + Handle(ResizableHandle), + Other(AnyElement), +} + +impl ResizablePanelGroup { + pub fn new(id: impl Into) -> Self { + Self { + id: id.into(), + vertical_layout: false, + full: false, + items: Vec::new(), + } + } + + pub fn vertical(id: impl Into) -> Self { + Self { + id: id.into(), + vertical_layout: true, + full: false, + items: Vec::new(), + } + } + + pub fn size_full(mut self) -> Self { + self.full = true; + self + } + + pub fn panel(mut self, panel: ResizablePanel) -> Self { + self.items.push(ResizableItem::Panel(panel)); + self + } + + pub fn handle(mut self, handle: ResizableHandle) -> Self { + self.items.push(ResizableItem::Handle(handle)); + self + } + + pub fn child(mut self, child: impl IntoElement) -> Self { + 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 t = crate::Theme::of(cx); + let vertical = self.vertical_layout; + + 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 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, "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 + }); + 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 pcts = split_state.read(cx).clone(); + 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(); + } + + 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 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; + }; + let bounds = bounds_for_move.get(); + let pos_pct = 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, |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].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; + }); + }) + .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| { + drag_up.update(cx, |d, _| *d = None); + }) + .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| { + drag_up_out.update(cx, |d, _| *d = None); + }) + .child( + gpui::canvas( + move |bounds, _, _| bounds_for_canvas.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ); + } + + let panel_count = panel_mins.len(); + 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 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.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 { + p.h(gpui::relative(frac)) + } else { + p.w(gpui::relative(frac)) + }; + } + panel_pos += 1; + 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(); + 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 = Some(h_idx)); + }); + 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 + } +} + +#[derive(IntoElement)] +pub struct ResizablePanel { + children: Vec, + default_pct: f32, + min_pct: f32, +} + +impl ResizablePanel { + pub fn new() -> Self { + Self { + children: Vec::new(), + default_pct: 50.0, + min_pct: 5.0, + } + } + + pub fn default_size(mut self, pct: f32) -> Self { + self.default_pct = pct; + self + } + + pub fn min_size(mut self, pct: f32) -> Self { + self.min_pct = pct; + 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() + .h(gpui::relative((self.default_pct / 100.0).clamp(0.05, 0.95))) + .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, + animate_pending: Rc>, +} + +impl MessageScrollerHandle { + pub fn new() -> Self { + Self { + scroll: gpui::ScrollHandle::new(), + animate_pending: Rc::new(std::cell::Cell::new(false)), + } + } + + pub fn scrollable(&self) -> ScrollableState { + 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) { + if animated { + self.animate_pending.set(true); + } else { + self.animate_pending.set(false); + 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 { + let 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() + } +} + +#[derive(IntoElement)] +pub struct MessageScroller { + id: ElementId, + handle: gpui::ScrollHandle, + animate_pending: Rc>, + auto: bool, + edge_threshold: Pixels, + fade_edges: bool, + gap_px: Option, + pad: Option>, + items: Vec, +} + +impl MessageScroller { + pub fn new(id: impl Into, handle: &MessageScrollerHandle) -> Self { + Self { + id: id.into(), + handle: handle.scroll.clone(), + animate_pending: handle.animate_pending.clone(), + auto: false, + edge_threshold: px(64.), + fade_edges: false, + gap_px: None, + pad: None, + items: Vec::new(), + } + } + + pub fn auto_scroll(mut self, auto: bool) -> Self { + self.auto = auto; + self + } + + pub fn scroll_edge_threshold(mut self, px_thresh: Pixels) -> Self { + self.edge_threshold = px_thresh; + self + } + + pub fn gap(mut self, px_gap: Pixels) -> Self { + self.gap_px = Some(px_gap); + self + } + + pub fn fade(mut self, fade: bool) -> Self { + self.fade_edges = fade; + self + } + + pub fn padding(mut self, edges: gpui::Edges) -> Self { + self.pad = Some(edges); + 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 { + 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); + if max_y <= 0.0 || dist <= f32::from(self.edge_threshold) { + 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) + .flex() + .flex_col() + .w_full() + .flex_1() + .min_w_0() + .min_h_0() + .overflow_y_scroll() + .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 = 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() + } +} + +// --------------------------------------------------------------------------- +// 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, + 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, + on_close: Option>, +} + +#[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 { + width_px: px(160.), + items: Vec::new(), + on_close: None, + } + } + + pub fn width(mut self, w: Pixels) -> Self { + self.width_px = w; + self + } + + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); + 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(MenuSeparator.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, + _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 { + 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(); + let close_pick = open_state; + 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() + .relative() + .flex() + .on_mouse_down(gpui::MouseButton::Left, move |_, _, cx| { + cx.stop_propagation(); + toggle.update(cx, |o, _| *o = !*o); + }) + .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(); + let close_cb_out = self.menu.on_close.clone(); + root = root.child( + gpui::deferred( + gpui::anchored() + .anchor(anchor_corner) + .snap_to_window() + .child( + div() + .mt(px(4.)) + .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 |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), + ), + ) + .with_priority(10), + ); + } + root + } +} + +#[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, + 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 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 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)); + }, + ); + if self.full { + d = d.size_full(); + } + 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::Right, |_, _, cx| { + cx.stop_propagation(); + }) + .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 |_, 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), + ), + ) + .with_priority(10), + ); + } + d + } +} + +#[derive(IntoElement)] +pub struct Popover { + id: ElementId, + open: bool, + trigger: Option, + content: Option, + _side: OverlaySide, + _align: OverlayAlign, + width: Option, + on_close: Option>, +} + +impl Popover { + pub fn new(id: impl Into, open: bool) -> Self { + Self { + id: id.into(), + open, + trigger: None, + content: None, + _side: OverlaySide::Bottom, + _align: OverlayAlign::Start, + width: None, + on_close: None, + } + } + + pub fn trigger(mut self, trigger: impl IntoElement) -> Self { + self.trigger = Some(trigger.into_any_element()); + self + } + + pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self { + self.on_close = Some(Rc::new(f)); + 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 { + let t = crate::Theme::of(cx); + 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 + { + 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); + } + if let Some(on_close) = self.on_close { + 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, + (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() + .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 new file mode 100644 index 0000000..e319a23 --- /dev/null +++ b/vendor/mantis-ui/src/input.rs @@ -0,0 +1,1492 @@ +use gpui::{ + AnyElement, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, + 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, RefCell}; +use std::ops::Range; +use std::rc::Rc; + +#[derive(Clone, Debug)] +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()) +} + +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) + || (ks.modifiers.control && ks.modifiers.alt)) +} + +fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +fn utf16_offset_to_byte(s: &str, u16_target: usize) -> usize { + let mut u16_pos = 0usize; + for (b_idx, ch) in s.char_indices() { + if u16_pos >= u16_target { + return b_idx; + } + u16_pos += ch.len_utf16(); + } + 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 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 { + return 0; + } + let mut p = pos - 1; + while p > 0 && !s.is_char_boundary(p) { + p -= 1; + } + 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 +} + +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 { + let prev = prev_char_boundary(s, p); + let ch = s[prev..p].chars().next().unwrap_or(' '); + if !ch.is_whitespace() { + break; + } + 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 is_word_char(ch) != target_is_word || ch.is_whitespace() { + break; + } + p = prev; + } + p +} + +fn next_word_boundary(s: &str, pos: usize) -> usize { + let mut p = pos.min(s.len()); + 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; + } + } + } + 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() + .nth(char_count) + .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, + marked: Option>, + bounds: Rc>>, + metrics: Rc>, + dragging: bool, + single_line: bool, + goal_col: Option, + undo_stack: Vec, + redo_stack: Vec, +} + +impl EditState { + fn new(single_line: bool) -> Self { + Self { + cursor: 0, + 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, + goal_col: None, + undo_stack: Vec::new(), + redo_stack: Vec::new(), + } + } + + fn reset_to_end(&mut self, value: &str) { + self.cursor = value.len(); + self.anchor = self.cursor; + self.marked = None; + self.goal_col = None; + self.undo_stack.clear(); + self.redo_stack.clear(); + } + + fn reset_to_start(&mut self) { + self.cursor = 0; + self.anchor = 0; + self.marked = None; + self.goal_col = 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(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(op) = self.undo_stack.pop() else { + return false; + }; + 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(op) = self.redo_stack.pop() else { + return false; + }; + 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 + } + + 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; + 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) { + let r = self.selection_range(value.len()); + self.apply_range(value, r, text, true); + } + + 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 = if word { + prev_word_boundary(value, self.cursor) + } else { + prev_char_boundary(value, self.cursor) + }; + self.apply_range(value, prev..self.cursor, "", true); + return true; + } + false + } + + 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 = if word { + next_word_boundary(value, self.cursor) + } else { + next_char_boundary(value, self.cursor) + }; + self.apply_range(value, self.cursor..next, "", true); + 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 = self + .goal_col + .unwrap_or_else(|| value[line_start..cur].chars().count()); + let next_pos = if !down { + if line_start == 0 { + 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) + } + } else if line_end >= value.len() { + value.len() + } else { + let next_start = line_end + 1; + let next_end = value[next_start..] + .find('\n') + .map_or(value.len(), |i| next_start + i); + 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( + &self, + value: &str, + password: bool, + point: Point, + pad_x: f32, + pad_y: f32, + scroll_y: f32, + window: &Window, + ) -> usize { + let b = self.bounds.get(); + 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 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 shape_col(value); + } + 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; + 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 + shape_col(&value[line_start..line_end]); + } + 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 + shape_col(&value[line_start..line_end]) + } + + fn bounds_for_range( + &self, + value: &str, + password: bool, + range_utf16: Range, + 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()); + let (font_size, line_h_px, text_font) = self.metrics.borrow().clone(); + let line_h = f32::from(line_h_px).max(18.0); + 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, line_start) + }; + 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 - scroll_y); + 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); + 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 was_marked = self.marked.take(); + let br = range + .map(|r| utf16_range_to_byte_range(value, r)) + .or(was_marked.clone()) + .unwrap_or_else(|| self.selection_range(value.len())); + 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() + && was_marked.is_some_and(|m| last.offset == m.start) + { + last.inserted = clean; + last.next_anchor = self.anchor; + last.next_cursor = self.cursor; + } + } + + fn mark_text( + &mut self, + value: &mut String, + range: Option>, + new_text: &str, + new_selected_range: Option>, + ) { + 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 { + 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; + 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 + } 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; + } + 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; + } + } +} + +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 !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; + } + 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 { + 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; + 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 && !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) + }; + buf.move_to(next, value.len(), shift); + CommonKeyResult::Moved + } + "right" => { + 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) + }; + buf.move_to(next, value.len(), shift); + CommonKeyResult::Moved + } + "home" => { + let target = if buf.single_line || doc { + 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 || doc { + 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, word) { + CommonKeyResult::Edited + } else { + CommonKeyResult::Moved + } + } + "delete" => { + if buf.delete(value, word) { + 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, + buf: EditState, + 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, + buf: EditState::new(true), + 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(); + self.buf.reset_to_end(&self.value); + 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; + } + match handle_common_key(&mut self.buf, &mut self.value, self.password, ks, cx) { + CommonKeyResult::Moved => { + cx.notify(); + return; + } + CommonKeyResult::Edited => { + cx.emit(Changed(self.value.clone())); + cx.notify(); + return; + } + CommonKeyResult::NotHandled => {} + } + if is_printable(ks) + && let Some(ch) = &ks.key_char + { + self.buf.replace_selection(&mut self.value, ch); + cx.emit(Changed(self.value.clone())); + cx.notify(); + } + } +} + +impl EntityInputHandler for TextInput { + fn text_for_range( + &mut self, + range: Range, + adjusted_range: &mut Option>, + _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()) + } + + fn selected_text_range( + &mut self, + _ignore_disabled_input: bool, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(self.buf.selected_text_range(&self.value)) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + self.buf.marked_text_range(&self.value) + } + + 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, + range: Option>, + text: &str, + _window: &mut Window, + cx: &mut Context, + ) { + self.buf.commit_text(&mut self.value, range, text); + 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.buf + .mark_text(&mut self.value, range, new_text, new_selected_range); + cx.notify(); + } + + fn bounds_for_range( + &mut self, + range_utf16: Range, + element_bounds: Bounds, + window: &mut Window, + _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, + pad_y, + 0.0, + window, + )) + } + + fn character_index_for_point( + &mut self, + point: Point, + 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, + self.password, + point, + pad_x, + 0.0, + 0.0, + window, + ); + Some(utf16_len(&self.value[..b])) + } +} + +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 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, 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); + }, + ) + .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) + .w_full() + .min_h(px(28.)) + .flex() + .items_center() + .text_size(px(13.)) + .text_color(t.foreground) + .on_mouse_down( + 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, + this.password, + ev.position, + pad_x, + 0.0, + 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, + 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); + 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, + buf: EditState, + focus: FocusHandle, + scroll: ScrollHandle, +} + +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, + buf: EditState::new(false), + focus: cx.focus_handle(), + scroll: ScrollHandle::new(), + } + } + + 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(); + 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(); + } + + 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 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; + 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 handle_common_key(&mut self.buf, &mut self.value, false, ks, cx) { + CommonKeyResult::Moved => { + cx.notify(); + return; + } + CommonKeyResult::Edited => { + self.maybe_scroll_end(); + cx.emit(Changed(self.value.clone())); + cx.notify(); + return; + } + CommonKeyResult::NotHandled => {} + } + if is_printable(ks) + && let Some(ch) = &ks.key_char + { + self.buf.replace_selection(&mut self.value, ch); + self.maybe_scroll_end(); + 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 { + Some(self.buf.selected_text_range(&self.value)) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + self.buf.marked_text_range(&self.value) + } + + 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, + range: Option>, + text: &str, + _window: &mut Window, + cx: &mut Context, + ) { + self.buf.commit_text(&mut self.value, range, text); + self.maybe_scroll_end(); + 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.buf + .mark_text(&mut self.value, range, new_text, new_selected_range); + cx.notify(); + } + + fn bounds_for_range( + &mut self, + range_utf16: Range, + element_bounds: Bounds, + 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 scroll_y = (-f32::from(self.scroll.offset().y)).max(0.0); + Some(self.buf.bounds_for_range( + &self.value, + false, + range_utf16, + element_bounds, + pad_x, + pad_y, + scroll_y, + window, + )) + } + + fn character_index_for_point( + &mut self, + point: Point, + 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 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])) + } +} + +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 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, 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); + }, + ) + .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", cx.entity_id())) + .relative() + .track_scroll(&self.scroll) + .track_focus(&self.focus) + .w_full() + .min_h(self.min_height) + .flex() + .items_start() + .text_size(px(13.)) + .text_color(t.foreground) + .on_mouse_down( + 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 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); + 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 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); + 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); + if let Some(max_h) = self.max_height { + el = el.max_h(max_h).overflow_y_scroll(); + } + if !self.bare { + el = el + .px(px(10.)) + .py(px(8.)) + .rounded(px(6.)) + .bg(t.background) + .border_1() + .border_color(if focused { t.ring } else { t.input }); + } + 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); + assert!(buf.undo(&mut val)); + assert_eq!(val, "hello world"); + assert!(buf.redo(&mut val)); + assert_eq!(val, "hello你好"); + } + + #[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, 11); // col 3 on "12345" + buf.move_vertical(val, false, false); + assert_eq!(buf.cursor, 7); + } +} 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..2f98a92 --- /dev/null +++ b/vendor/mantis-ui/src/theme.rs @@ -0,0 +1,188 @@ +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 { + 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; + 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 { + 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..e6d501a --- /dev/null +++ b/vendor/mantis-ui/src/toast.rs @@ -0,0 +1,248 @@ +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 { + Info, + Success, + Warning, + Error, + Loading, +} + +#[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)] +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, + action: Option<(SharedString, Rc)>, +} + +impl Toast { + pub fn success(title: impl Into) -> Self { + 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, + action: None, + } + } + + pub fn error(title: impl Into) -> Self { + 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, + action: None, + } + } + + pub fn info(title: impl Into) -> Self { + Self { + kind: ToastKind::Info, + title: title.into(), + description: None, + action: None, + } + } + + pub fn description(mut self, desc: impl Into) -> Self { + self.description = Some(desc.into()); + 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 + } + + 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, + action: self.action, + created_at: Instant::now(), + }); + 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; + existing.action = self.action; + existing.created_at = Instant::now(); + 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 now = Instant::now(); + let items: Vec = cx + .try_global::() + .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(); + } + 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 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(4.)) + .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(header); + if let Some(desc) = item.description { + 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); + } + stack.into_any_element() +}