Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98eaede2dd |
No files matched your search
@@ -1,13 +1,2 @@
|
||||
# Every change to FieldCraft needs the maintainer's review before it merges.
|
||||
* @jyviko
|
||||
|
||||
# Release and supply-chain paths, named explicitly so they stay owner-reviewed if the rule above
|
||||
# is ever relaxed: workflows and secrets use, packaging and signing, the updater, dependencies,
|
||||
# licences.
|
||||
/.github/ @jyviko
|
||||
/packaging/ @jyviko
|
||||
/crates/update/ @jyviko
|
||||
/Cargo.toml @jyviko
|
||||
/Cargo.lock @jyviko
|
||||
/ATTRIBUTION.md @jyviko
|
||||
/deny.toml @jyviko
|
||||
@@ -24,8 +24,7 @@ body:
|
||||
id: evidence
|
||||
attributes:
|
||||
label: Evidence
|
||||
description: |
|
||||
Pictures first: for anything you can see (the view, a mesh, a panel, a plot), drag a screenshot or a short screen recording in here, and mark the problem on it. For a mesh, a section through it (`fieldcraft-cli snapshot … --section`) shows what the outside hides. Then log output and numbers. For a crash, attach the crash report (`fieldcraft-cli crashes`, then `crashes show <id>`).
|
||||
description: Screenshots, log output, numbers. For a crash, attach the crash report (`fieldcraft-cli crashes`, then `crashes show <id>`).
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
@@ -42,6 +41,6 @@ body:
|
||||
id: version
|
||||
attributes:
|
||||
label: Version and platform
|
||||
placeholder: "v0.6.0 (or commit), macOS 15 arm64"
|
||||
placeholder: "v0.5.7 (or commit), macOS 15 arm64"
|
||||
validations:
|
||||
required: true
|
||||
@@ -21,11 +21,6 @@ body:
|
||||
attributes:
|
||||
label: Expected behaviour
|
||||
description: What FieldCraft should do, as precisely as you can.
|
||||
- type: textarea
|
||||
id: pictures
|
||||
attributes:
|
||||
label: Pictures
|
||||
description: A screenshot of where it would go, a sketch, or a picture of the result you are after. Drag images in here.
|
||||
- type: textarea
|
||||
id: reference
|
||||
attributes:
|
||||
|
||||
@@ -2,14 +2,10 @@ Closes #
|
||||
|
||||
## What and why
|
||||
|
||||
## Before and after
|
||||
<!-- For any visible change (the view, meshes, panels, results, icons): a picture before and after. Drag them in here. -->
|
||||
|
||||
## How it was verified
|
||||
<!-- Tests added or changed; oracle cases (tests/oracle) for solver and meshing results, with their cited references. -->
|
||||
|
||||
## Checklist
|
||||
- [ ] The issue was assigned to me before I started (see CONTRIBUTING.md)
|
||||
- [ ] `cargo fmt --all`, `cargo clippy -p <crates I touched> --all-targets -- -D warnings` and their tests pass
|
||||
- [ ] Before/after pictures for any visible change
|
||||
- [ ] No code, text or data from GPL-family projects or commercial CAE products
|
||||
@@ -1,14 +1,13 @@
|
||||
FieldCraft is open-source CAE pre-processing in Rust: it turns geometry into analysis-ready
|
||||
finite element models, writes Abaqus, Nastran and LS-DYNA decks, and solves linear static and
|
||||
modal problems with its own solver. AI agents can drive it over MCP (`fieldcraft-cli mcp`).
|
||||
[README](https://github.com/tangency-labs/fieldcraft#readme) ·
|
||||
[roadmap](https://github.com/tangency-labs/fieldcraft/blob/main/ROADMAP.md) ·
|
||||
[issues](https://github.com/tangency-labs/fieldcraft/issues)
|
||||
[README](https://github.com/jyviko/fieldcraft#readme) ·
|
||||
[roadmap](https://github.com/jyviko/fieldcraft/blob/main/ROADMAP.md) ·
|
||||
[issues](https://github.com/jyviko/fieldcraft/issues)
|
||||
|
||||
**Which file?**
|
||||
- **macOS 11+** (Apple silicon and Intel): open `fieldcraft-{version}-macos-universal.dmg` and
|
||||
drag `FieldCraft.app` onto Applications. The command-line tool is included at
|
||||
`/Applications/FieldCraft.app/Contents/MacOS/fieldcraft-cli` and also available separately in
|
||||
drag `FieldCraft.app` onto Applications. The command-line tool is in
|
||||
`fieldcraft-cli-{version}-macos-universal.zip`.
|
||||
- **Linux** (x86_64, glibc 2.35+: Ubuntu 22.04, Debian 12, Fedora 36 or newer):
|
||||
`fieldcraft-{version}-linux-x86_64.AppImage` (`chmod +x`, then run it), or unpack
|
||||
@@ -22,8 +21,6 @@ modal problems with its own solver. AI agents can drive it over MCP (`fieldcraft
|
||||
To start with a sample model, run the app with `--sample cantilever` (macOS:
|
||||
`/Applications/FieldCraft.app/Contents/MacOS/FieldCraft --sample cantilever`).
|
||||
|
||||
**Updates.** {update_signing}
|
||||
|
||||
**Signing.** {macos_signing} The Linux and Windows builds are not signed; on Windows, SmartScreen
|
||||
may say "Windows protected your PC": choose **More info**, then **Run anyway**.
|
||||
|
||||
|
||||
@@ -6,17 +6,8 @@ name: CI
|
||||
# Pull requests from forks (outside contributors) run the full gate, once the maintainer approves
|
||||
# the run, so the review sees it; so do Dependabot's (.github/dependabot.yml), which nobody tests
|
||||
# locally. The heavy job stays off pull requests.
|
||||
#
|
||||
# What runs when (docs/releasing.md, "What CI runs when"): the `plan` job picks a base, the last
|
||||
# `develop` commit whose CI run passed (a pull request: its merge base; nightly and manual runs:
|
||||
# none), and `cargo xtask affected` maps the change since it to crates. `cargo xtask ci --affected`
|
||||
# then lints and tests those crates and their dependents only; the heavy and oracle jobs run when
|
||||
# the change reaches the solvers, the oracle or everything (Cargo.toml/Cargo.lock/xtask/workflows).
|
||||
# Nightly and manual runs, and every release (release.yml), run all of it.
|
||||
on:
|
||||
pull_request:
|
||||
# A draft starts no run; marking it ready for review does.
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
paths:
|
||||
- '**'
|
||||
- '!**/*.md'
|
||||
@@ -35,7 +26,7 @@ on:
|
||||
- 'docs/features.md'
|
||||
- 'docs/oracle.md'
|
||||
schedule:
|
||||
# Nightly, on the default branch (develop): the whole gate, the heavy tests and the oracle.
|
||||
# Nightly, on the default branch (develop): the heavy tests.
|
||||
- cron: '23 3 * * *'
|
||||
# Weekly: the oracle on macOS too, so results that differ by platform show up in CI (the
|
||||
# fixtures are often blessed on a Mac; #115).
|
||||
@@ -46,8 +37,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
# A newer merge cancels the run still going for the one before it, so a burst of merges is tested
|
||||
# once, at the tip; nothing is missed, since the tip's run tests everything since the last green
|
||||
# run. Nightly and manual runs are grouped apart and never cancelled by a merge.
|
||||
# once, at the tip. Nightly and manual runs are grouped apart and never cancelled by a merge.
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}-${{ github.event_name }}
|
||||
cancel-in-progress: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }}
|
||||
@@ -56,141 +46,56 @@ env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
plan:
|
||||
name: Plan (affected crates)
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || (!github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')))
|
||||
runs-on: ${{ github.event_name != 'pull_request' && vars.SELF_HOSTED_RUNNER || 'ubuntu-24.04' }}
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
# To find the last green run on develop.
|
||||
actions: read
|
||||
outputs:
|
||||
base: ${{ steps.base.outputs.base }}
|
||||
everything: ${{ steps.affected.outputs.everything }}
|
||||
solver: ${{ steps.affected.outputs.solver }}
|
||||
wasm: ${{ steps.affected.outputs.wasm }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: plan
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- name: Pick the base
|
||||
id: base
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
EVENT: ${{ github.event_name }}
|
||||
PR_BASE: ${{ github.base_ref }}
|
||||
run: |
|
||||
base=""
|
||||
case "$EVENT" in
|
||||
push)
|
||||
# The newest develop commit whose push run passed and that this commit contains.
|
||||
# Runs that were cancelled or failed are skipped, so their changes are tested here.
|
||||
for sha in $(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs?branch=develop&event=push&status=success&per_page=100" --jq '.workflow_runs[].head_sha'); do
|
||||
if [ "$sha" != "$GITHUB_SHA" ] && git merge-base --is-ancestor "$sha" HEAD; then
|
||||
base="$sha"
|
||||
break
|
||||
fi
|
||||
done
|
||||
;;
|
||||
pull_request)
|
||||
base="$(git merge-base "origin/$PR_BASE" HEAD || true)"
|
||||
;;
|
||||
esac
|
||||
# Nightly and manual runs, or no green run to start from: everything.
|
||||
echo "base=$base" >>"$GITHUB_OUTPUT"
|
||||
echo "### Base: \`${base:-none (everything)}\`" >>"$GITHUB_STEP_SUMMARY"
|
||||
- name: cargo xtask affected
|
||||
id: affected
|
||||
env:
|
||||
BASE: ${{ steps.base.outputs.base }}
|
||||
run: |
|
||||
if [ -n "$BASE" ]; then
|
||||
cargo xtask affected --base "$BASE" --github-output | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
printf 'everything=true\nsolver=true\nwasm=true\n' >>"$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
bots:
|
||||
name: Claim and triage bot tests
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || (!github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')))
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
sparse-checkout: scripts
|
||||
# scripts/claim and scripts/triage run in .github/workflows/claim.yml and triage.yml through
|
||||
# actions/github-script; their tests use only node:test against a fake client.
|
||||
- run: node --test scripts/claim/*.test.js scripts/triage/*.test.js
|
||||
|
||||
ci:
|
||||
name: cargo xtask ci
|
||||
needs: plan
|
||||
runs-on: ${{ github.event_name != 'pull_request' && vars.SELF_HOSTED_RUNNER || 'ubuntu-24.04' }}
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
# Shared keys: release.yml's verify jobs restore these caches (they save only on main).
|
||||
shared-key: ci
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- name: Software GPU (lavapipe), so headless snapshots run the GPU pipeline
|
||||
run: sudo apt-get update -q && sudo apt-get install -y -q --no-install-recommends mesa-vulkan-drivers libvulkan1
|
||||
- name: cargo xtask ci (the affected crates, or everything)
|
||||
env:
|
||||
BASE: ${{ needs.plan.outputs.base }}
|
||||
# The drawing tests run on lavapipe and fail, instead of skipping, without it.
|
||||
FIELDCRAFT_GPU: software
|
||||
FIELDCRAFT_REQUIRE_GPU: "1"
|
||||
run: |
|
||||
if [ -n "$BASE" ]; then cargo xtask ci --affected "$BASE"; else cargo xtask ci; fi
|
||||
# A dependency update changes THIRD-PARTY-LICENSES.txt, which Dependabot cannot regenerate:
|
||||
# regenerate it here so the gate checks everything else, and dependabot-licences.yml commits
|
||||
# it to the pull request.
|
||||
- name: Regenerate THIRD-PARTY-LICENSES.txt (Dependabot)
|
||||
if: github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
run: cargo xtask licences
|
||||
- run: cargo xtask ci
|
||||
|
||||
heavy:
|
||||
# The heavy verification and corpus tests (#[ignore]d) and the doc tests, when the change
|
||||
# reaches them.
|
||||
# The heavy verification and corpus tests (#[ignore]d) and the doc tests.
|
||||
name: cargo xtask test --heavy
|
||||
needs: plan
|
||||
if: github.event_name != 'pull_request' && (needs.plan.outputs.solver == 'true' || needs.plan.outputs.everything == 'true')
|
||||
runs-on: ${{ github.event_name != 'pull_request' && vars.SELF_HOSTED_RUNNER || 'ubuntu-24.04' }}
|
||||
if: github.event.schedule != '41 4 * * 0' && github.event_name != 'pull_request'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: heavy
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- run: cargo xtask test --heavy
|
||||
|
||||
oracle:
|
||||
# Verification and validation (docs/verification.md): every case against its reference and
|
||||
# its fixture, and docs/oracle.md must be the table the cases produce. Cases marked `slow`
|
||||
# run here too while the whole set stays within a few minutes; `--quick` skips them. It runs
|
||||
# when the change reaches the solvers or the oracle's package.
|
||||
# run here too while the whole set stays within a few minutes; `--quick` skips them.
|
||||
name: cargo xtask oracle
|
||||
needs: plan
|
||||
if: needs.plan.outputs.solver == 'true' || needs.plan.outputs.everything == 'true'
|
||||
runs-on: ${{ github.event_name != 'pull_request' && vars.SELF_HOSTED_RUNNER || 'ubuntu-24.04' }}
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: oracle
|
||||
key: oracle
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- run: cargo xtask oracle
|
||||
- name: docs/oracle.md is current
|
||||
@@ -208,37 +113,20 @@ jobs:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: oracle-macos
|
||||
key: oracle-macos
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- run: cargo xtask oracle
|
||||
- name: docs/oracle.md is current
|
||||
run: git diff --exit-code docs/oracle.md
|
||||
|
||||
windows:
|
||||
# The desktop app's tests on Windows, nightly and on demand: the Windows-only code
|
||||
# (apps/fieldcraft/src/native_crash.rs, the exception filter) builds and a child process that
|
||||
# faults on purpose leaves its native crash report (#299). Releases build Windows too.
|
||||
name: Windows app tests
|
||||
if: github.event.schedule == '23 3 * * *' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: windows
|
||||
save-if: ${{ github.ref == 'refs/heads/develop' }}
|
||||
- run: cargo test --locked --profile ci -p fieldcraft
|
||||
|
||||
advisories:
|
||||
name: Dependency licences, advisories and sources
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || (!github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')))
|
||||
runs-on: ${{ github.event_name != 'pull_request' && vars.SELF_HOSTED_RUNNER || 'ubuntu-24.04' }}
|
||||
name: Dependency advisories and sources
|
||||
if: github.event.schedule != '41 4 * * 0' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install cargo-deny
|
||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||
- run: cargo deny --locked check --warn unmaintained advisories bans licenses sources
|
||||
- run: cargo deny --locked check --warn unmaintained advisories bans sources
|
||||
@@ -1,53 +0,0 @@
|
||||
# `/claim` and `/unclaim` on issues (CONTRIBUTING.md, "Before you start: claim an issue"), and a
|
||||
# daily sweep that frees claims with no visible progress for 14 days. A pull request that
|
||||
# references an issue (`Closes #N`, `<summary> (#N)`) claims it too. The logic is in
|
||||
# scripts/claim/claim.js (tested in ci.yml).
|
||||
name: Claim
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
# pull_request_target so PRs from forks can label and assign. It runs the base branch's
|
||||
# scripts/claim and only reads the PR's title, body and author; the PR's code is never checked out.
|
||||
pull_request_target:
|
||||
types: [opened, reopened]
|
||||
schedule:
|
||||
- cron: '17 5 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read # to check out scripts/claim
|
||||
issues: write
|
||||
pull-requests: read
|
||||
|
||||
# One run at a time per issue, so two simultaneous /claim comments can't both win.
|
||||
concurrency:
|
||||
group: claim-${{ github.event.issue.number || github.event.pull_request.number || 'sweep' }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
claim:
|
||||
name: Claim bot
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
if: >-
|
||||
github.event_name != 'issue_comment' ||
|
||||
(!github.event.issue.pull_request && github.event.comment.user.type != 'Bot' &&
|
||||
(startsWith(github.event.comment.body, '/claim') || startsWith(github.event.comment.body, '/unclaim')))
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
sparse-checkout: scripts/claim
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const claim = require('./scripts/claim/claim.js');
|
||||
if (context.eventName === 'issue_comment') {
|
||||
await claim.handleComment({ github, context });
|
||||
} else if (context.eventName === 'pull_request_target') {
|
||||
const claimed = await claim.handlePull({ github, context });
|
||||
core.info(`Claimed: ${claimed.join(', ') || 'none'}`);
|
||||
} else {
|
||||
const released = await claim.sweep({ github, context });
|
||||
core.info(`Released: ${released.join(', ') || 'none'}`);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# Dependabot's Cargo updates change THIRD-PARTY-LICENSES.txt (`cargo xtask licences`), which
|
||||
# Dependabot cannot regenerate: this commits the regenerated file to its pull request. CI's own
|
||||
# run on the pull request regenerates it too, so its result covers everything else.
|
||||
name: Dependabot licences
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [develop]
|
||||
paths: [Cargo.lock]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: dependabot-licences-${{ github.head_ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
licences:
|
||||
if: github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- run: cargo xtask licences
|
||||
- name: Commit the regenerated file
|
||||
run: |
|
||||
if git diff --quiet -- THIRD-PARTY-LICENSES.txt; then
|
||||
echo "THIRD-PARTY-LICENSES.txt is up to date"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
# [skip ci]: the pull request's CI run already regenerated this file and tested the
|
||||
# tree with it; a bot-authored commit would otherwise wait for a maintainer's approval.
|
||||
git commit -m "deps: regenerate THIRD-PARTY-LICENSES.txt [skip ci]" -- THIRD-PARTY-LICENSES.txt
|
||||
git push origin "HEAD:${GITHUB_HEAD_REF}"
|
||||
@@ -9,8 +9,6 @@ on:
|
||||
branches: [develop]
|
||||
paths: [".github/workflows/**", "packaging/**"]
|
||||
pull_request:
|
||||
# A draft starts no run; marking it ready for review does.
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
paths: [".github/workflows/**", "packaging/**"]
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -24,7 +22,6 @@ concurrency:
|
||||
jobs:
|
||||
lint:
|
||||
name: Packaging lint
|
||||
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# The web app (apps/fieldcraft-web, docs/web.md) on GitHub Pages: https://tangency-labs.github.io/fieldcraft/
|
||||
# The web app (apps/fieldcraft-web, docs/web.md) on GitHub Pages: https://jyviko.github.io/fieldcraft/
|
||||
# After SolidCraft's pages.yml (MIT OR Apache-2.0; see ATTRIBUTION.md).
|
||||
#
|
||||
# A push to `main` (a release; main holds released code only) builds the app with Trunk (release,
|
||||
@@ -33,10 +33,6 @@ env:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# POSTHOG_KEY lives in the `release` environment (main only, docs/releasing.md). The deploy job
|
||||
# already uses github-pages and a job has one environment, so the build job reads the key: on
|
||||
# main it runs in `release`, elsewhere in no environment and with an empty key.
|
||||
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
@@ -57,10 +53,6 @@ jobs:
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
- name: Build the web app
|
||||
working-directory: apps/fieldcraft-web
|
||||
env:
|
||||
# Usage analytics only in the deployed build (main), and only with the user's consent
|
||||
# (docs/privacy.md); develop builds get an empty key, which sends nothing.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ github.ref == 'refs/heads/main' && secrets.POSTHOG_KEY || '' }}
|
||||
run: trunk build --release --public-url /fieldcraft/
|
||||
- name: Bundle size
|
||||
run: |
|
||||
|
||||
@@ -3,28 +3,19 @@
|
||||
#
|
||||
# A push to `main` (fast-forwarded from a verified `develop` commit; main holds released code only)
|
||||
# builds every package and creates or updates the
|
||||
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt (signed with the release key
|
||||
# into SHA256SUMS.txt.minisig when the FIELDCRAFT_SIGNING_KEY secret exists) and generated notes. The
|
||||
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt and generated notes. The
|
||||
# version is [workspace.package] version in Cargo.toml; a suffix (0.2.0-rc.1) makes a
|
||||
# pre-release. Every package, and the release itself, carries THIRD-PARTY-LICENSES.txt, generated
|
||||
# here by `cargo xtask licences` (it is not committed). A person verifies the draft and publishes
|
||||
# it; this workflow never publishes, and pushes to develop or tags never start it.
|
||||
# pre-release. A person verifies the draft and publishes it; this workflow never publishes,
|
||||
# and pushes to develop or tags never start it.
|
||||
#
|
||||
# macOS universal (arm64 + x86_64) .dmg with FieldCraft.app, the CLI as a .zip packaging/macos
|
||||
# Linux x86_64 (glibc 2.35+) .tar.gz, .AppImage, .deb and .rpm packaging/linux
|
||||
# Linux x86_64 (glibc 2.35+) .tar.gz and .AppImage packaging/linux
|
||||
# Windows x64 .zip with fieldcraft.exe and fieldcraft-cli.exe packaging/windows
|
||||
#
|
||||
# macOS: signed with a Developer ID and notarized when the APPLE_* secrets exist, ad-hoc
|
||||
# otherwise (the release notes say which). Linux and Windows builds are not signed.
|
||||
#
|
||||
# The verify jobs run everything CI can: the full `cargo xtask ci`, `cargo xtask test --heavy` and
|
||||
# `cargo xtask oracle` on Linux, and the oracle on macOS. Develop's CI tests only what each change
|
||||
# affects (ci.yml), so this is where a release proves all of it. The packaging jobs build in
|
||||
# parallel with them and only upload workflow artifacts; the `release` job, the only one that
|
||||
# signs SHA256SUMS.txt or touches a GitHub Release, needs every verify and packaging job, so a
|
||||
# failing verify means no draft and no signature.
|
||||
#
|
||||
# Dry run: `gh workflow run release.yml --ref <branch>` verifies and builds everything and uploads the
|
||||
# Dry run: `gh workflow run release.yml --ref <branch>` builds everything and uploads the
|
||||
# `release-assets` artifact without creating a release. `-f draft=true` on `main` retries
|
||||
# the draft.
|
||||
name: Release
|
||||
@@ -48,10 +39,8 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
# The same CARGO_* environment as ci.yml: rust-cache hashes it into the cache key, so a
|
||||
# difference would stop the verify jobs restoring develop's caches. (rust-cache already sets
|
||||
# CARGO_INCREMENTAL=0 for every job.)
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
|
||||
jobs:
|
||||
version:
|
||||
@@ -80,68 +69,9 @@ jobs:
|
||||
{ echo "version=$VERSION"; echo "prerelease=$pre"; echo "draft=$REQUEST_DRAFT"; } >>"$GITHUB_OUTPUT"
|
||||
echo "### FieldCraft v$VERSION (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# The full gate, the heavy tests and the oracle on Linux and macOS: the `release` job needs them,
|
||||
# so a release never drafts or signs a commit that fails any of them. Each restores the cache of
|
||||
# its ci.yml counterpart on develop (same shared-key), so it starts warm.
|
||||
verify-ci:
|
||||
name: Verify (cargo xtask ci)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: ci
|
||||
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- run: cargo xtask ci
|
||||
|
||||
verify-heavy:
|
||||
name: Verify (cargo xtask test --heavy)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: heavy
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- run: cargo xtask test --heavy
|
||||
|
||||
verify-oracle:
|
||||
name: Verify (cargo xtask oracle, ${{ matrix.os }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-24.04
|
||||
cache: oracle
|
||||
- os: macos-14
|
||||
cache: oracle-macos
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
shared-key: ${{ matrix.cache }}
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- run: cargo xtask oracle
|
||||
- name: docs/oracle.md is current
|
||||
run: git diff --exit-code docs/oracle.md
|
||||
|
||||
macos:
|
||||
name: macOS universal
|
||||
needs: version
|
||||
# Signing, notarization and analytics secrets live in the `release` environment, which only
|
||||
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
|
||||
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
|
||||
runs-on: macos-14
|
||||
timeout-minutes: 120
|
||||
outputs:
|
||||
@@ -158,8 +88,6 @@ jobs:
|
||||
key: release-macos-universal
|
||||
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
|
||||
run: cargo xtask licences
|
||||
- name: Import the signing certificate (skipped without APPLE_CERTIFICATE)
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
@@ -169,8 +97,6 @@ jobs:
|
||||
- name: Build, sign, notarize and package (the dmg is mounted and checked)
|
||||
id: package
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
@@ -189,85 +115,37 @@ jobs:
|
||||
name: Linux x86_64
|
||||
needs: version
|
||||
# The oldest GitHub-hosted image, so the binaries need only glibc >= 2.35.
|
||||
# Signing, notarization and analytics secrets live in the `release` environment, which only
|
||||
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
|
||||
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FIELDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
# The .deb and .rpm builders (both MIT), pinned.
|
||||
CARGO_DEB_VERSION: 3.8.0
|
||||
CARGO_GENERATE_RPM_VERSION: 0.21.0
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install packaging tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends desktop-file-utils lintian rpm
|
||||
sudo apt-get install -y --no-install-recommends desktop-file-utils
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-linux-x86_64
|
||||
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
|
||||
run: cargo xtask licences
|
||||
- name: Install cargo-deb and cargo-generate-rpm
|
||||
run: |
|
||||
cargo install --locked --version "$CARGO_DEB_VERSION" cargo-deb
|
||||
cargo install --locked --version "$CARGO_GENERATE_RPM_VERSION" cargo-generate-rpm
|
||||
- name: Build and package (tar.gz, AppImage, deb, rpm)
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
- name: Build and package (tar.gz, AppImage)
|
||||
run: packaging/linux/package.sh
|
||||
- name: Check the packages
|
||||
run: |
|
||||
. packaging/env.sh
|
||||
base="fieldcraft-$VERSION-linux-x86_64"
|
||||
deb="dist/release/fieldcraft_${VERSION}_amd64.deb"
|
||||
rpm="dist/release/fieldcraft-$VERSION.x86_64.rpm"
|
||||
list="$(tar -tzf "dist/release/$base.tar.gz")"
|
||||
list="$(tar -tzf dist/release/*.tar.gz)"
|
||||
for f in bin/fieldcraft bin/fieldcraft-cli "share/applications/$APP_ID.desktop" \
|
||||
share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt; do
|
||||
grep -Fx -- "$base/$f" <<<"$list"
|
||||
grep -Fx -- "fieldcraft-$VERSION-linux-x86_64/$f" <<<"$list"
|
||||
done
|
||||
# The .deb and .rpm carry the tar.gz's files under /usr (the .deb adds its copyright
|
||||
# file); their lists live in apps/fieldcraft/Cargo.toml, so a drift fails here.
|
||||
files() { grep -v '/$' | sed -E "s#^(\./|/|$base/)##; s#^usr/##" | grep -vx 'share/doc/fieldcraft/copyright' | sort; }
|
||||
diff <(files <<<"$list") <(dpkg-deb --fsys-tarfile "$deb" | tar -t | files)
|
||||
diff <(files <<<"$list") <(rpm -qpl "$rpm" | files)
|
||||
dpkg-deb --info "$deb"
|
||||
rpm -qpi "$rpm"
|
||||
echo "rpm requires:"; rpm -qpR "$rpm"
|
||||
# The release notes live on GitHub, so the package has no Debian changelog (a native
|
||||
# package built upstream, not by a distribution).
|
||||
lintian --info --fail-on error --suppress-tags no-changelog "$deb"
|
||||
ldd target/release/fieldcraft
|
||||
for appimage in dist/release/*.AppImage; do
|
||||
chmod +x "$appimage"
|
||||
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
|
||||
done
|
||||
- name: Install the .deb and .rpm in containers
|
||||
run: |
|
||||
# The oldest supported Ubuntu (the build's glibc) and a current Fedora. Recommended and
|
||||
# weak dependencies (GPU drivers) are skipped to keep it quick; the hard ones must resolve.
|
||||
# Both images leave out documentation when installing (dpkg path-exclude, dnf nodocs), so
|
||||
# the licences are checked in the package's file list rather than on disk.
|
||||
docker run --rm -v "$PWD/dist/release:/dist:ro" ubuntu:22.04 bash -euxc '
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends /dist/*.deb
|
||||
fieldcraft-cli --version
|
||||
fieldcraft --version
|
||||
dpkg -L fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt'
|
||||
docker run --rm -v "$PWD/dist/release:/dist:ro" fedora:44 bash -euxc '
|
||||
dnf install -y -q --setopt=install_weak_deps=False /dist/*.rpm
|
||||
fieldcraft-cli --version
|
||||
fieldcraft --version
|
||||
rpm -ql fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt
|
||||
dnf install -y -q rpmlint
|
||||
rpmlint /dist/*.rpm || true'
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: release-linux-x86_64
|
||||
@@ -277,9 +155,6 @@ jobs:
|
||||
windows:
|
||||
name: Windows x64
|
||||
needs: version
|
||||
# Signing, notarization and analytics secrets live in the `release` environment, which only
|
||||
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
|
||||
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
@@ -294,13 +169,8 @@ jobs:
|
||||
key: release-windows-x64
|
||||
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Generate THIRD-PARTY-LICENSES.txt (fails when a crate's licence can't be resolved)
|
||||
run: cargo xtask licences
|
||||
- name: Build and package (zip)
|
||||
shell: pwsh
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
run: ./packaging/windows/package.ps1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
@@ -310,11 +180,7 @@ jobs:
|
||||
|
||||
release:
|
||||
name: Draft release (or dry-run artifacts)
|
||||
# The only job that publishes anything: it waits for every verify and packaging job.
|
||||
needs: [version, verify-ci, verify-heavy, verify-oracle, macos, linux, windows]
|
||||
# Signing, notarization and analytics secrets live in the `release` environment, which only
|
||||
# `main` may use; a dry run on another branch asks for no environment and builds unsigned.
|
||||
environment: ${{ github.ref == 'refs/heads/main' && 'release' || '' }}
|
||||
needs: [version, macos, linux, windows]
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -331,58 +197,21 @@ jobs:
|
||||
pattern: release-*
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# The same file every package carries, attached to the release on its own.
|
||||
- name: Generate THIRD-PARTY-LICENSES.txt
|
||||
run: cargo xtask licences && cp THIRD-PARTY-LICENSES.txt artifacts/
|
||||
- name: Check the set and write the checksums
|
||||
- name: Check the set, checksums and notes
|
||||
run: |
|
||||
for f in "fieldcraft-$VERSION-macos-universal.dmg" "fieldcraft-cli-$VERSION-macos-universal.zip" \
|
||||
"fieldcraft-$VERSION-linux-x86_64.tar.gz" "fieldcraft-$VERSION-linux-x86_64.AppImage" \
|
||||
"fieldcraft_${VERSION}_amd64.deb" "fieldcraft-$VERSION.x86_64.rpm" \
|
||||
"fieldcraft-$VERSION-windows-x64.zip" THIRD-PARTY-LICENSES.txt; do
|
||||
"fieldcraft-$VERSION-windows-x64.zip"; do
|
||||
test -s "artifacts/$f" || { echo "::error::missing $f"; exit 1; }
|
||||
done
|
||||
(cd artifacts && sha256sum -- * | tee SHA256SUMS.txt)
|
||||
- name: Sign SHA256SUMS.txt with the release key (skipped without FIELDCRAFT_SIGNING_KEY)
|
||||
id: sign
|
||||
env:
|
||||
FIELDCRAFT_SIGNING_KEY: ${{ secrets.FIELDCRAFT_SIGNING_KEY }}
|
||||
# rsign2 (MIT), a minisign-compatible signer, pinned.
|
||||
RSIGN_VERSION: 0.6.7
|
||||
run: |
|
||||
if [ -z "$FIELDCRAFT_SIGNING_KEY" ]; then
|
||||
echo "::warning::FIELDCRAFT_SIGNING_KEY is not set: SHA256SUMS.txt is not signed, so the app cannot install this release itself (docs/releasing.md)"
|
||||
echo "signed=false" >>"$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
cargo install --locked --quiet --root "$RUNNER_TEMP/rsign" rsign2 --version "$RSIGN_VERSION"
|
||||
rsign="$RUNNER_TEMP/rsign/bin/rsign"
|
||||
key="$RUNNER_TEMP/release.key"
|
||||
(umask 077 && printf '%s\n' "$FIELDCRAFT_SIGNING_KEY" >"$key")
|
||||
"$rsign" sign -W -s "$key" -t "FieldCraft v$VERSION SHA256SUMS.txt" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
|
||||
rm -f "$key"
|
||||
# The signature must verify with the public key the app is built with.
|
||||
public="$(sed -n 's/^pub const PUBLIC_KEY: &str = "\(.*\)";$/\1/p' crates/update/src/lib.rs)"
|
||||
"$rsign" verify -q -P "$public" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
|
||||
echo "signed=true" >>"$GITHUB_OUTPUT"
|
||||
- name: Write the notes
|
||||
env:
|
||||
SIGNED: ${{ steps.sign.outputs.signed }}
|
||||
run: |
|
||||
# The macOS paragraph says how the app was signed (packaging/macos/package.sh).
|
||||
case "$MACOS_SIGNING" in
|
||||
notarized) macos="The macOS app is signed with a Developer ID and notarized by Apple." ;;
|
||||
signed) macos="The macOS app is signed with a Developer ID but **not notarized**: the first time, right-click \`FieldCraft.app\` in Applications and choose **Open**." ;;
|
||||
*) macos="The macOS app is **ad-hoc signed and not notarized**: macOS blocks the first launch. Right-click \`FieldCraft.app\` in Applications and choose **Open** (then **Open** again), or run \`xattr -dr com.apple.quarantine /Applications/FieldCraft.app\`." ;;
|
||||
esac
|
||||
# The updates paragraph says whether the app can install this release itself.
|
||||
if [ "$SIGNED" = true ]; then
|
||||
updates="\`SHA256SUMS.txt\` is signed with the FieldCraft release key (\`SHA256SUMS.txt.minisig\`), so FieldCraft's Help › Check for Updates can verify and install this release."
|
||||
else
|
||||
updates="This release's \`SHA256SUMS.txt\` is **not signed**: FieldCraft's in-app updates can't verify it and won't install it; download it from this page instead."
|
||||
fi
|
||||
awk -v v="$VERSION" -v m="$macos" -v u="$updates" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); gsub(/\{update_signing\}/, u); print }' \
|
||||
awk -v v="$VERSION" -v m="$macos" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); print }' \
|
||||
.github/release-notes.md >notes.md
|
||||
cat notes.md >>"$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload the dry-run artifacts
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
# Labels new issues and PRs from fixed rules, `/triage` for maintainers, asks short bug reports
|
||||
# for reproduction steps (`needs-info`, closed after 14 days unanswered), and a manual backfill
|
||||
# (CONTRIBUTING.md, "Labels and triage"). The logic is in scripts/triage/ (tested in ci.yml).
|
||||
name: Triage
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, labeled, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
# pull_request_target so PRs from forks can be labelled. It runs the base branch's
|
||||
# scripts/triage and only lists the PR's changed paths; the PR's code is never checked out.
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
schedule:
|
||||
- cron: '41 5 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Only report what would be labelled'
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: read # to check out scripts/triage
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: triage-${{ github.event.issue.number || github.event.pull_request.number || 'repo' }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
name: Triage bot
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
# Filtered here so the common events (every comment, every label) start no runner.
|
||||
if: >-
|
||||
(github.event_name == 'issue_comment' &&
|
||||
github.event.comment.user.type != 'Bot' && startsWith(github.event.comment.body, '/triage')) ||
|
||||
((github.event_name == 'issue_comment' || github.event.action == 'edited') &&
|
||||
contains(github.event.issue.labels.*.name, 'needs-info') &&
|
||||
github.event.sender.login == github.event.issue.user.login) ||
|
||||
(github.event.action == 'labeled' && startsWith(github.event.label.name, 'priority') &&
|
||||
contains(github.event.issue.labels.*.name, 'needs-triage')) ||
|
||||
(github.event_name != 'issue_comment' && github.event.action != 'labeled' && github.event.action != 'edited')
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
sparse-checkout: scripts/triage
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
with:
|
||||
script: |
|
||||
const triage = require('./scripts/triage/triage.js');
|
||||
const info = require('./scripts/triage/needs-info.js');
|
||||
const event = context.eventName;
|
||||
const action = context.payload.action;
|
||||
const esc = (t) => String(t).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
||||
const th = (...names) => names.map((data) => ({ data, header: true }));
|
||||
if (event === 'issue_comment') {
|
||||
core.info(await triage.handleComment({ github, context }));
|
||||
await info.handleReply({ github, context });
|
||||
} else if (event === 'issues' && action === 'labeled') {
|
||||
await triage.handleLabeled({ github, context });
|
||||
} else if (event === 'issues' && action === 'edited') {
|
||||
await info.handleReply({ github, context });
|
||||
} else if (event === 'schedule') {
|
||||
const closed = await info.sweep({ github, context });
|
||||
core.info(`Closed for missing information: ${closed.join(', ') || 'none'}`);
|
||||
} else if (event === 'workflow_dispatch') {
|
||||
const dryRun = process.env.DRY_RUN !== 'false';
|
||||
const plan = await triage.backfill({ github, context, dryRun });
|
||||
const asks = await info.backfill({ github, context, dryRun });
|
||||
await core.summary
|
||||
.addHeading(dryRun ? `Backfill dry run: ${plan.length} unlabelled` : `Backfill: ${plan.length} labelled`)
|
||||
.addTable([th('Item', 'Kind', 'Labels', 'Title'), ...plan.map((p) => [`#${p.number}`, p.pull ? 'PR' : 'issue', esc(p.labels.join(', ') || '—'), esc(p.title)])])
|
||||
.addHeading(dryRun ? `needs-info dry run: ${asks.length} would be asked` : `needs-info: ${asks.length} asked`)
|
||||
.addTable([th('Issue', 'Asks', 'Title'), ...asks.map((p) => [`#${p.number}`, esc(p.asks.join(', ')), esc(p.title)])])
|
||||
.write();
|
||||
} else {
|
||||
core.info(`Labelled: ${(await triage.handleOpened({ github, context })).join(', ') || 'nothing'}`);
|
||||
if (event === 'issues') await info.handleOpened({ github, context });
|
||||
}
|
||||
@@ -7,4 +7,3 @@
|
||||
.DS_Store
|
||||
*.swp
|
||||
__pycache__/
|
||||
/THIRD-PARTY-LICENSES.txt
|
||||
@@ -24,9 +24,7 @@ FieldCraft everywhere: crates `fieldcraft-*`, binaries `fieldcraft` and `fieldcr
|
||||
## Never crash
|
||||
People trust FieldCraft with their models; a crash loses their work. **This outranks feature work.**
|
||||
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`,
|
||||
`unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The one exception, in the app crate
|
||||
(which denies it instead), has no safe API: the Windows-only `apps/fieldcraft/src/native_crash.rs`
|
||||
(the exception filter that records crashes inside native code such as graphics drivers).
|
||||
`unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
|
||||
- **Errors are `Result<T, E>`** through the crate's error type and `?`. An unfinished feature
|
||||
returns an error ("not supported yet: …"); it never panics.
|
||||
- **Input-derived numbers are hostile** (command parameters, model files, solver decks,
|
||||
@@ -94,10 +92,7 @@ People trust FieldCraft with their models; a crash loses their work. **This outr
|
||||
adaptive-precision predicates, never a bare floating-point sign.
|
||||
- **Units.** The model is unit-consistent and never converts (the user picks e.g. mm, t, s, N,
|
||||
MPa); geometry from SolidCraft is in millimetres. Z is up.
|
||||
- **Rust only.** The one exception is the GitHub issue and pull request bots: `scripts/claim/` and
|
||||
`scripts/triage/` are JavaScript because `actions/github-script` runs only JavaScript
|
||||
(`.github/workflows/claim.yml`, `triage.yml`). Keep them small, with their `node --test` tests
|
||||
beside them (CI's bot tests job). **Never break wasm**: everything below the apps builds for
|
||||
- **Rust only.** **Never break wasm**: everything below the apps builds for
|
||||
`wasm32-unknown-unknown` (`cargo xtask wasm`, part of `cargo xtask ci`).
|
||||
- **Workflow for every change** (this section overrides any other instruction an agent carries,
|
||||
such as a parent repository's CLAUDE.md or a task runner's "run tests and linters" step):
|
||||
@@ -124,25 +119,20 @@ People trust FieldCraft with their models; a crash loses their work. **This outr
|
||||
contributors' pull requests wait for the maintainer's review (CONTRIBUTING.md). Never squash.
|
||||
Then remove your worktree and delete your local branch.
|
||||
5. Never run the full gate locally: no `cargo xtask ci`, no `cargo clippy --workspace`, no
|
||||
`cargo xtask wasm` or `oracle` unless step 2 calls for it. Never watch CI. GitHub CI runs,
|
||||
per merge on `develop`, `cargo xtask ci --affected <last green commit>` (fmt, assets,
|
||||
layers on the whole tree; clippy and tests on the crates the change reaches; wasm when one
|
||||
of them builds for it), the oracle and heavy tests when the change reaches the solvers or
|
||||
the oracle, and the dependency licences and advisories; a change to Cargo.toml, Cargo.lock,
|
||||
xtask or the workflows, the nightly run and every release run all of it (docs/releasing.md,
|
||||
"What CI runs when"). `cargo xtask affected --base origin/develop` shows what your branch
|
||||
reaches. The coordinator
|
||||
`cargo xtask wasm` or `oracle` unless step 2 calls for it. Never watch CI. GitHub CI runs
|
||||
`cargo xtask ci` (fmt, assets, licences, layers, clippy -D warnings, tests, wasm), the
|
||||
oracle, the heavy tests and the advisories once per merge on `develop`; the coordinator
|
||||
watches it and sends a failure back to the change that caused it, which is fixed forward
|
||||
at once.
|
||||
- **Keep the trunk gate fast** (under ~3 minutes on CI). A test that takes more than a few seconds
|
||||
(convergence studies, the whole corpus, cross-checks between solvers) is
|
||||
`#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]`, with a fast representative
|
||||
test left in the trunk gate. The `heavy` CI job runs `cargo xtask test --heavy` (every ignored
|
||||
test, benchmarks included, and the doc tests) on merges to `develop` that reach a crate with
|
||||
heavy tests, nightly, before every release and on demand (`gh workflow run CI --ref <branch>`). Hostile-input tests run commands on sessions with small
|
||||
test, benchmarks included, and the doc tests) on every merge to `develop`, nightly and on
|
||||
demand (`gh workflow run CI --ref <branch>`). Hostile-input tests run commands on sessions with small
|
||||
work caps (`Session::limits`) so refusals are instant; never lower the production caps for a
|
||||
test.
|
||||
- **Publishing**: `origin` is github.com/tangency-labs/fieldcraft. Changes land through pull requests
|
||||
- **Publishing**: `origin` is github.com/jyviko/fieldcraft. Changes land through pull requests
|
||||
as the workflow above describes; the coordinator reads every merged diff and sends findings
|
||||
back as fix-forward work. Never force-push `develop` or `main`; `main` holds released code and moves only by
|
||||
fast-forward at a release (docs/releasing.md). Never commit `plan/`, `.agent-files/`,
|
||||
|
||||
@@ -23,36 +23,12 @@ is committed and listed here with its exports.
|
||||
| docs/media/examples/heated-bracket.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved heated-bracket sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/bracket-hex.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved bracket-hex sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/crank-arm.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-arm sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/crank-mirror.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-mirror sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/meshing/skill/analytic-cylinder.png, docs/meshing/skill/analytic-pipe.png, docs/meshing/skill/analytic-plate-hole.png, docs/meshing/skill/analytic-sphere.png, docs/meshing/skill/analytic-torus.png, docs/meshing/skill/bent-tube.png, docs/meshing/skill/bolted-assembly.png, docs/meshing/skill/cantilever-i-beam.png, docs/meshing/skill/crank-arm.png, docs/meshing/skill/cup.png, docs/meshing/skill/filleted-bracket-blocks.png, docs/meshing/skill/filleted-bracket.png, docs/meshing/skill/i-beam.png, docs/meshing/skill/loft-transition.png, docs/meshing/skill/perforated-plate.png, docs/meshing/skill/pi5-base.png, docs/meshing/skill/pi5-lid.png, docs/meshing/skill/pinhole-block.png, docs/meshing/skill/plain-cup.png, docs/meshing/skill/rounded-box.png, docs/meshing/skill/shallow-groove.png, docs/meshing/skill/sharp-wedge.png, docs/meshing/skill/sphere-on-plate.png, docs/meshing/skill/spline-vase.png, docs/meshing/skill/stepped-block.png, docs/meshing/skill/thin-ribs.png, docs/meshing/skill/thin-wall-enclosure.png, docs/meshing/skill/upright-bracket.png | FieldCraft contributors | Original: section pictures of the corpus parts and samples meshed by the meshing skill, drawn by `fieldcraft-cli snapshot` (`cargo xtask skill-results`, docs/meshing/skill-results.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/flow-past.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the flow-past sample before solving (its bracket as the sample opens) (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/flow-past-flow.png | FieldCraft contributors | Original: the solved flow-past sample rendered by FieldCraft (`ui.render`, light theme), velocity on the mid-slice with the bracket and upstream streamlines, generated by `tools/flow-clip/make.py` | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/flow-past-transient.mp4 | FieldCraft contributors | Original: the flow-past start-up transient rendered frame by frame by FieldCraft (`ui.render`), generated by `tools/flow-clip/make.py` (captions drawn by `tools/demo-video/caption.py` in Inter, OFL, crates/ui-egui/fonts) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/cantilever.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved cantilever sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/impact.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved impact sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/ibeam.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved ibeam sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/ibeam.png | FieldCraft contributors | Original: the solved ibeam sample rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the ibeam sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/heated-flow.png | FieldCraft contributors | Original: the heated-flow sample's temperature slice rendered directly at 320 × 213 by `fieldcraft-cli snapshot` with the CPU renderer; geometry is the original upright-bracket recipe | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/parts.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the parts sample (meshes only, nothing to solve) (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/flow-past.png | FieldCraft contributors | Original: the flow-past sample as docs/media/examples/flow-past.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the flow-past sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/cantilever.png | FieldCraft contributors | Original: the cantilever sample as docs/media/examples/cantilever.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the cantilever sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/impact.png | FieldCraft contributors | Original: the impact sample as docs/media/examples/impact.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the impact sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/parts.png | FieldCraft contributors | Original: the parts sample as docs/media/examples/parts.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the parts sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/bracket-hex.png | FieldCraft contributors | Original: the bracket-hex sample as docs/media/examples/bracket-hex.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the bracket-hex sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/crank-arm.png | FieldCraft contributors | Original: the crank-arm sample as docs/media/examples/crank-arm.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-arm sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/crank-mirror.png | FieldCraft contributors | Original: the crank-mirror sample as docs/media/examples/crank-mirror.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-mirror sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/drop-test.png | FieldCraft contributors | Original: the drop-test sample as docs/media/examples/drop-test.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the drop-test sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/heated-bracket.png | FieldCraft contributors | Original: the heated-bracket sample as docs/media/examples/heated-bracket.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the heated-bracket sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/rubber-seal.png | FieldCraft contributors | Original: the rubber-seal sample as docs/media/examples/rubber-seal.png shows it, rendered by FieldCraft (`ui.render`, light theme), cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the rubber-seal sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/decks/tests/golden/nastran/*.bdf | FieldCraft contributors | Written by our Nastran writer from our own test models (crates/decks/tests/nastran.rs) | MIT OR Apache-2.0 |
|
||||
| crates/engine/tests/designs/pi5-enclosure.json | FieldCraft contributors | Original SolidCraft recipe (solid.* commands) of an enclosure for a single-board computer, for thermal analysis: base, lid, heat sink, board, chips, connectors and the air inside | MIT OR Apache-2.0 |
|
||||
| crates/geometry/tests/designs/hollow-box.solidcraft, crates/geometry/tests/designs/hollow-box-post.solidcraft, crates/geometry/tests/designs/open-tray-post.solidcraft | FieldCraft contributors | Built with `solidcraft-cli run` from the recipes beside them (crates/geometry/tests/designs/*.json) | MIT OR Apache-2.0 |
|
||||
| assets/icons/assembly.instance.svg, assets/icons/assembly.instance.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/assembly.instance.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.read.svg, assets/icons/deck.read.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.read.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.abaqus.svg, assets/icons/deck.write.abaqus.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.abaqus.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.lsdyna.svg, assets/icons/deck.write.lsdyna.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.lsdyna.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.nastran.svg, assets/icons/deck.write.nastran.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.nastran.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/diagnostics.bug_report.svg, assets/icons/diagnostics.bug_report.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/diagnostics.bug_report.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/edit.redo.svg, assets/icons/edit.redo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.redo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/edit.undo.svg, assets/icons/edit.undo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.undo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/file.open.svg, assets/icons/file.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -60,19 +36,11 @@ is committed and listed here with its exports.
|
||||
| assets/icons/file.save_as.svg, assets/icons/file.save_as.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.save_as.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/file.save.svg, assets/icons/file.save.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.save.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.bodies.svg, assets/icons/geometry.bodies.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.bodies.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.check.svg, assets/icons/geometry.check.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.check.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.svg, assets/icons/geometry.datum.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.axis.svg, assets/icons/geometry.datum.axis.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.axis.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.point.svg, assets/icons/geometry.datum.point.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.point.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.import.mesh.svg, assets/icons/geometry.import.mesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.import.mesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.midsurface.svg, assets/icons/geometry.midsurface.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.midsurface.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.open.svg, assets/icons/geometry.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.partition.svg, assets/icons/geometry.partition.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.partition.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.faces.merge.svg, assets/icons/geometry.faces.merge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.faces.merge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.face.absorb.svg, assets/icons/geometry.face.absorb.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.face.absorb.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.face.split.svg, assets/icons/geometry.face.split.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.face.split.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.defeature.svg, assets/icons/geometry.defeature.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.defeature.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.stitch.svg, assets/icons/geometry.stitch.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.stitch.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.tessellate.svg, assets/icons/geometry.tessellate.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.tessellate.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/interaction.bolt.svg, assets/icons/interaction.bolt.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.bolt.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/interaction.connector.svg, assets/icons/interaction.connector.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.connector.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -80,8 +48,6 @@ is committed and listed here with its exports.
|
||||
| assets/icons/interaction.contact.general.svg, assets/icons/interaction.contact.general.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.contact.general.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/interaction.contact.pair.svg, assets/icons/interaction.contact.pair.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.contact.pair.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/interaction.fsi.svg, assets/icons/interaction.fsi.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.fsi.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.block.svg, assets/icons/mesh.block.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.block.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.mirror.svg, assets/icons/mesh.mirror.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.mirror.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/model.mass.create.svg, assets/icons/model.mass.create.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/model.mass.create.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/interaction.rigid_wall.svg, assets/icons/interaction.rigid_wall.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/interaction.rigid_wall.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/model.spring.create.svg, assets/icons/model.spring.create.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/model.spring.create.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -90,34 +56,28 @@ is committed and listed here with its exports.
|
||||
| assets/icons/mesh.element.add.svg, assets/icons/mesh.element.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.element.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.decompose.svg, assets/icons/mesh.hex.decompose.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.decompose.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.dominant.svg, assets/icons/mesh.hex.dominant.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.dominant.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.cells.svg, assets/icons/mesh.cells.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.cells.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.generate.svg, assets/icons/mesh.hex.generate.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.generate.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.blocks.svg, assets/icons/mesh.hex.blocks.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.blocks.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.mapped.svg, assets/icons/mesh.hex.mapped.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.mapped.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.octree.svg, assets/icons/mesh.hex.octree.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.octree.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.polycube.svg, assets/icons/mesh.hex.polycube.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.polycube.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.sweep.svg, assets/icons/mesh.hex.sweep.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.sweep.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.import.orphan.svg, assets/icons/mesh.import.orphan.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.import.orphan.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.layers.svg, assets/icons/mesh.layers.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.layers.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.node.add.svg, assets/icons/mesh.node.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.node.merge.svg, assets/icons/mesh.node.merge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.merge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.node.relax.svg, assets/icons/mesh.node.relax.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.relax.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.node.move.svg, assets/icons/mesh.node.move.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.move.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.order.quadratic.svg, assets/icons/mesh.order.quadratic.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.order.quadratic.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.quad.faces.svg, assets/icons/mesh.quad.faces.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.quad.faces.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.quality.svg, assets/icons/mesh.quality.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.quality.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.quality.mark.svg, assets/icons/mesh.quality.mark.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.quality.mark.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/results.export.vtu.svg, assets/icons/results.export.vtu.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/results.export.vtu.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.export.stl.svg, assets/icons/mesh.export.stl.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.export.stl.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.region.remesh.svg, assets/icons/mesh.region.remesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.region.remesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.adapt.svg, assets/icons/mesh.size.adapt.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.adapt.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.global.svg, assets/icons/mesh.size.global.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.global.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.set.svg, assets/icons/mesh.size.set.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.set.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.seed.edge.svg, assets/icons/mesh.seed.edge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.seed.edge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.seed.svg, assets/icons/mesh.size.seed.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.seed.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.smooth.svg, assets/icons/mesh.smooth.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.smooth.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.surface.check.svg, assets/icons/mesh.surface.check.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.surface.check.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.tag.svg, assets/icons/mesh.tag.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.tag.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.tet.generate.svg, assets/icons/mesh.tet.generate.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.tet.generate.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.extrude.svg, assets/icons/mesh.hex.extrude.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.extrude.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.plan.svg, assets/icons/mesh.plan.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.plan.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.planar.svg, assets/icons/mesh.planar.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.planar.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.transition.svg, assets/icons/mesh.transition.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.transition.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.untangle.svg, assets/icons/mesh.untangle.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.untangle.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.verify.svg, assets/icons/mesh.verify.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.verify.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/model.activity.svg, assets/icons/model.activity.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/model.activity.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -181,7 +141,6 @@ is committed and listed here with its exports.
|
||||
| assets/icons/ui.sun.svg, assets/icons/ui.sun.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.sun.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/ui.views.svg, assets/icons/ui.views.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.views.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/ui.zoom.svg, assets/icons/ui.zoom.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.zoom.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/view.show_all.svg, assets/icons/view.show_all.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/view.show_all.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/icon.vectorcraft, assets/app-icon/icon.svg, assets/app-icon/icon.png | FieldCraft contributors | Original application icon (a hexahedral-meshed cube with a banded colour fringe on its faces on a rounded-square backdrop), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs); editable source, SVG and 1024 × 1024 PNG export | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/icon-small.vectorcraft, assets/app-icon/icon-small.svg, assets/app-icon/icon-small.png | FieldCraft contributors | Original simplified application icon for 16–32 px (the fringe cube alone; no mesh or floor grid), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/layers/01-floor.vectorcraft, assets/app-icon/FieldCraft.icon/Assets/01-floor.svg | FieldCraft contributors | Original isometric floor grid with a radial fade (Default appearance), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
|
||||
@@ -213,17 +172,14 @@ is committed and listed here with its exports.
|
||||
| clippy.toml, rustfmt.toml | SolidCraft | MIT OR Apache-2.0 |
|
||||
| crates/geometry/src/tagged_mesh.rs (package and part reading, transforms, units, caps) | SolidCraft `crates/io/src/threemf.rs` | MIT OR Apache-2.0 |
|
||||
| crates/render/src/camera.rs, crates/render/src/raster.rs | SolidCraft `crates/render/src/camera.rs`, `raster.rs` | MIT OR Apache-2.0 |
|
||||
| crates/gpu/src/view.rs (viewport pipelines and shaders), crates/ui-egui/src/gpu.rs, crates/ui-egui/src/theme.rs (tokens and their values), crates/ui-egui/src/control.rs, crates/ui-egui/src/lib.rs (input injection, screenshots), crates/ui-egui/src/toolbar.rs (workspace switcher, tabs, panels with drop-downs, fitting), crates/ui-egui/src/appbar.rs (application bar; the mark is drawn from assets/app-icon/icon-small.svg's coordinates), crates/ui-egui/src/titlebar.rs (caption buttons, drag and resize zones; SolidCraft took it from VectorCraft), crates/ui-egui/src/frame.rs (windows, heading bands), crates/ui-egui/src/browser.rs (row drawing), crates/ui-egui/src/palette.rs (command line and search), crates/ui-egui/src/timeline.rs (timeline strip, transport), crates/ui-egui/src/viewport.rs (navigation bar, orientation gizmo), crates/ui-egui/src/files.rs (background opening, file pickers as host services) | SolidCraft `crates/ui-egui/src/` (titlebar.rs also VectorCraft `crates/ui-egui/src/titlebar.rs`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/navigation.rs (navigation presets and bindings), crates/ui-egui/src/viewport.rs (orbit about the point under the cursor, or the drawn centre from empty space; Ctrl + left drag orbits) | SolidCraft `crates/ui-egui/src/prefs.rs` (`NavPreset`, `NavBinding`, `NAV_PRESETS`, `orbit`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/gpu.rs, crates/ui-egui/src/theme.rs (tokens and their values), crates/ui-egui/src/control.rs, crates/ui-egui/src/lib.rs (input injection, screenshots), crates/ui-egui/src/toolbar.rs (workspace switcher, tabs, panels with drop-downs, fitting), crates/ui-egui/src/appbar.rs (application bar; the mark is drawn from assets/app-icon/icon-small.svg's coordinates), crates/ui-egui/src/titlebar.rs (caption buttons, drag and resize zones; SolidCraft took it from VectorCraft), crates/ui-egui/src/frame.rs (windows, heading bands), crates/ui-egui/src/browser.rs (row drawing), crates/ui-egui/src/palette.rs (command line and search), crates/ui-egui/src/timeline.rs (timeline strip, transport), crates/ui-egui/src/viewport.rs (navigation bar, orientation gizmo), crates/ui-egui/src/files.rs (background opening, file pickers as host services) | SolidCraft `crates/ui-egui/src/` (titlebar.rs also VectorCraft `crates/ui-egui/src/titlebar.rs`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/fields.rs (form rows: a label column of fixed width, then the field) | SolidCraft `crates/ui-egui/src/dialogs.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/fs.rs (atomic writes) | SolidCraft `crates/io/src/safe_write.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/recovery.rs (recovery folder, entries, locks) | SolidCraft `crates/engine/src/recovery.rs` | MIT OR Apache-2.0 |
|
||||
| crates/engine/src/crash.rs, crates/engine/src/crash_tests.rs (crash reports: panic hook, locked command journal, unclean-exit detection, startup steps, native crash reports, report folders and limits, replay), apps/fieldcraft/src/native_crash.rs (Windows exception filter and minidump), apps/fieldcraft-cli/src/crashes.rs, docs/crash-reports.md (structure) | SolidCraft `crates/engine/src/crash.rs`, `crash_tests.rs`, `apps/solidcraft/src/native_crash.rs`, `apps/solidcraft-cli/src/crashes.rs`, `docs/crash-reports.md` | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft/src/control_server.rs | SolidCraft `apps/solidcraft/src/control_server.rs` | MIT OR Apache-2.0 |
|
||||
| crates/mcp/src/ (JSON-RPC framing, MCP lifecycle, tool schema checks, the control-channel backend, base64) | SolidCraft `crates/mcp/src/` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/roots.rs (the rules of read and write roots) | VectorCraft's automation roots (docs/mcp.md there) | MIT OR Apache-2.0 |
|
||||
| packaging/env.sh, packaging/.shellcheckrc, packaging/macos/package.sh, packaging/macos/Info.plist.in, packaging/linux/package.sh, packaging/linux/AppRun, packaging/windows/package.ps1 | SolidCraft `packaging/` and VectorCraft `packaging/` (signing and notarization in macos/package.sh) | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft/Cargo.toml (the run-time dependency lists of `[package.metadata.deb]` and `[package.metadata.generate-rpm]`) | SolidCraft `packaging/linux/nfpm.yaml` | MIT OR Apache-2.0 |
|
||||
| packaging/macos/import-cert.sh | VectorCraft `packaging/macos/import-cert.sh` | MIT OR Apache-2.0 |
|
||||
| packaging/windows/check-exe.ps1 | SolidCraft `packaging/windows/check-icon.ps1` | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft-web/ (the web runner, browser file services and downloads, Trunk configuration, index.html) | VectorCraft `apps/vectorcraft-web/` and SolidCraft `apps/solidcraft-web/` | MIT OR Apache-2.0 |
|
||||
@@ -232,7 +188,6 @@ is committed and listed here with its exports.
|
||||
| .github/workflows/release.yml, .github/release-notes.md, docs/releasing.md | SolidCraft `.github/workflows/release.yml`, `.github/release-notes.md`, `docs/releasing.md`; VectorCraft `.github/workflows/release.yml` | MIT OR Apache-2.0 |
|
||||
| .github/workflows/packaging-lint.yml | SolidCraft `.github/workflows/packaging-lint.yml` (itself adapted from PhotoCraft, https://github.com/storytold/photocraft, Apache-2.0) | MIT OR Apache-2.0 |
|
||||
| .github/workflows/arch-check.yml (the riscv64 cross build) | SolidCraft `.github/workflows/ci.yml` (`riscv64-gates`) | MIT OR Apache-2.0 |
|
||||
| .github/workflows/claim.yml, .github/workflows/triage.yml, scripts/claim/, scripts/triage/ (the claim and triage bots and their tests) | SolidCraft `.github/workflows/claim.yml`, `triage.yml`, `scripts/claim/`, `scripts/triage/` | MIT OR Apache-2.0 |
|
||||
|
||||
## Test oracles
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ needed most, and how to claim work. The rules every change follows, by a person
|
||||
You need stable Rust 1.95 or newer.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/tangency-labs/fieldcraft && cd fieldcraft
|
||||
git clone https://github.com/jyviko/fieldcraft && cd fieldcraft
|
||||
cargo run --release -p fieldcraft -- --sample cantilever # the desktop app on a sample model
|
||||
cargo run -p fieldcraft-cli -- commands # every command and its parameters
|
||||
cargo test -p fieldcraft-solver # the tests of one crate
|
||||
@@ -28,32 +28,32 @@ cargo xtask oracle --quick # the verification ca
|
||||
|
||||
## Where help is wanted most
|
||||
|
||||
See the [`help wanted`](https://github.com/tangency-labs/fieldcraft/labels/help%20wanted) and
|
||||
[`good first issue`](https://github.com/tangency-labs/fieldcraft/labels/good%20first%20issue) labels, and
|
||||
See the [`help wanted`](https://github.com/jyviko/fieldcraft/labels/help%20wanted) and
|
||||
[`good first issue`](https://github.com/jyviko/fieldcraft/labels/good%20first%20issue) labels, and
|
||||
the `area:` labels for your field. In order of how much they would help users:
|
||||
|
||||
1. **Reproducible meshes** ([#115](https://github.com/tangency-labs/fieldcraft/issues/115)). The same part
|
||||
1. **Reproducible meshes** ([#115](https://github.com/jyviko/fieldcraft/issues/115)). The same part
|
||||
must give the same tet mesh on every platform and every run, as the solvers already do.
|
||||
2. **All-hex meshing of thin and curved parts** ([#85](https://github.com/tangency-labs/fieldcraft/issues/85)).
|
||||
2. **All-hex meshing of thin and curved parts** ([#85](https://github.com/jyviko/fieldcraft/issues/85)).
|
||||
The octree mesher over-refines thin walls; concave transition templates and an up-front depth
|
||||
are next. Hex meshing is the centre of gravity of the project.
|
||||
3. **Getting results in and out**: ParaView export ([#90](https://github.com/tangency-labs/fieldcraft/issues/90)),
|
||||
Gmsh import ([#91](https://github.com/tangency-labs/fieldcraft/issues/91)), Abaqus deck reading
|
||||
([#98](https://github.com/tangency-labs/fieldcraft/issues/98)), CSV and STL
|
||||
([#92](https://github.com/tangency-labs/fieldcraft/issues/92), [#93](https://github.com/tangency-labs/fieldcraft/issues/93)).
|
||||
4. **Verification benchmarks** ([#97](https://github.com/tangency-labs/fieldcraft/issues/97),
|
||||
[#106](https://github.com/tangency-labs/fieldcraft/issues/106)). An engineer with a published benchmark
|
||||
3. **Getting results in and out**: ParaView export ([#90](https://github.com/jyviko/fieldcraft/issues/90)),
|
||||
Gmsh import ([#91](https://github.com/jyviko/fieldcraft/issues/91)), Abaqus deck reading
|
||||
([#98](https://github.com/jyviko/fieldcraft/issues/98)), CSV and STL
|
||||
([#92](https://github.com/jyviko/fieldcraft/issues/92), [#93](https://github.com/jyviko/fieldcraft/issues/93)).
|
||||
4. **Verification benchmarks** ([#97](https://github.com/jyviko/fieldcraft/issues/97),
|
||||
[#106](https://github.com/jyviko/fieldcraft/issues/106)). An engineer with a published benchmark
|
||||
can add it as an oracle case without touching solver code.
|
||||
5. **Nonlinear elements and materials**: incompatible modes at finite strain
|
||||
([#82](https://github.com/tangency-labs/fieldcraft/issues/82)), kinematic hardening
|
||||
([#81](https://github.com/tangency-labs/fieldcraft/issues/81)), and the material library
|
||||
([#99](https://github.com/tangency-labs/fieldcraft/issues/99)).
|
||||
6. **The app**: typed command forms ([#112](https://github.com/tangency-labs/fieldcraft/issues/112)), XY and
|
||||
path plots ([#94](https://github.com/tangency-labs/fieldcraft/issues/94), [#95](https://github.com/tangency-labs/fieldcraft/issues/95)).
|
||||
([#82](https://github.com/jyviko/fieldcraft/issues/82)), kinematic hardening
|
||||
([#81](https://github.com/jyviko/fieldcraft/issues/81)), and the material library
|
||||
([#99](https://github.com/jyviko/fieldcraft/issues/99)).
|
||||
6. **The app**: typed command forms ([#112](https://github.com/jyviko/fieldcraft/issues/112)), XY and
|
||||
path plots ([#94](https://github.com/jyviko/fieldcraft/issues/94), [#95](https://github.com/jyviko/fieldcraft/issues/95)).
|
||||
|
||||
Bigger areas on the [roadmap](ROADMAP.md) — contact, dynamics, composites, coupled fields, wave
|
||||
propagation, turbulence — are open to anyone who wants to own one: start a thread in
|
||||
[Discussions](https://github.com/tangency-labs/fieldcraft/discussions).
|
||||
[Discussions](https://github.com/jyviko/fieldcraft/discussions).
|
||||
|
||||
## Before you start: claim an issue
|
||||
|
||||
@@ -61,53 +61,12 @@ Every change starts from an issue, and only the maintainer merges.
|
||||
|
||||
1. Pick an open issue labelled **help wanted** or **good first issue** that is not labelled
|
||||
**claimed**. If what you want to do has no issue, open one first and wait for a reply.
|
||||
2. Comment `/claim` on it. The bot assigns it to you, labels it **claimed** and replies; then it is
|
||||
yours. It refuses an issue someone else holds (naming them and when their claim lapses), an
|
||||
issue an open pull request already covers, and an issue without **help wanted** or **good
|
||||
first issue**: on those, say what you would like to do and the maintainer replies. Work on
|
||||
unassigned issues may not be accepted.
|
||||
3. Open a draft pull request early, linked with `Closes #N`. A pull request that references an
|
||||
open-for-contributors issue nobody holds (`Closes #N` in the body, `(#N)` in the title) claims
|
||||
it the same way; if someone holds it already, or an older open pull request references it,
|
||||
the bot says so on your pull request instead.
|
||||
4. An issue with no visible progress for 14 days goes back to the pool: a daily sweep frees a claim
|
||||
with no linked pull request 14 days after it was made, and one with a pull request after 14
|
||||
days without pushes. `/unclaim` releases it early (you or a maintainer).
|
||||
2. Comment that you would like to take it. The maintainer assigns it to you and labels it
|
||||
**claimed**; then it is yours. Work on unassigned issues may not be accepted.
|
||||
3. Open a draft pull request early, linked with `Closes #N`. An issue with no visible progress
|
||||
for 14 days goes back to the pool.
|
||||
|
||||
Issues labelled **in progress** are being worked on by the core team; please don't start on them.
|
||||
The bot never lets them be claimed, and never frees an issue a maintainer holds.
|
||||
|
||||
## Labels and triage
|
||||
|
||||
The triage bot labels every new issue and pull request (`.github/workflows/triage.yml`). It only
|
||||
adds labels; correct them freely and it won't put them back.
|
||||
|
||||
- **Pull requests** get `area:*` from the paths they change: `crates/mesh` → `area:mesh`,
|
||||
`crates/lbm*` → `area:cfd`, `crates/solver`, `crates/fem`, `crates/explicit` → `area:solver`,
|
||||
`crates/ui-egui` and `apps/` → `area:ui`, `crates/io`, `crates/decks` → `area:io`, `docs/` and
|
||||
top-level `*.md` → `area:docs`, `.github/`, `xtask/`, `packaging/`, `scripts/`, `tools/` →
|
||||
`area:infra`.
|
||||
- **Issues** get `bug` or `enhancement` from the form they were filed with (or a crash or
|
||||
"Feature request" title), and an `area:*` from words in the title or the command an in-app
|
||||
report names. Until it has a priority, an issue carries `needs-triage`; adding a `priority:`
|
||||
label removes it.
|
||||
- **Maintainers** comment `/triage area:mesh high S` to sort an issue or pull request: any
|
||||
existing label (case, and `-` or `_` for a space, don't matter: `in-progress`), `high` for
|
||||
`priority: high`, `S`/`M`/`L` for a size (which replaces the old one), `-label` removes one.
|
||||
Any `/triage` with a change clears `needs-triage`.
|
||||
- **Short bug reports without steps to reproduce** get `needs-info` and one comment asking for
|
||||
the steps (and the version, when it's missing). The reporter's reply, or an edit that adds the
|
||||
steps, removes the label; an issue that stays in `needs-info` for 14 days is closed, and can be
|
||||
reopened any time. Feature requests, reports filed from the app (**Help › Report a Bug…**),
|
||||
and maintainers' issues are never asked.
|
||||
- `needs-triage` is the queue: [open issues with it](https://github.com/tangency-labs/fieldcraft/issues?q=is%3Aopen+label%3Aneeds-triage).
|
||||
|
||||
## Reporting a problem or an idea
|
||||
|
||||
Use the templates under **New issue**. Show it: for anything you can see — the view, a mesh, a
|
||||
panel, a plot — add a screenshot or a short screen recording (drag it into the issue) and mark
|
||||
the problem on it. For a mesh, a section (`fieldcraft-cli snapshot … --section`) shows what the
|
||||
outside hides. A picture is often the fastest way for someone else to see what you see.
|
||||
|
||||
## Making the change
|
||||
|
||||
@@ -119,9 +78,7 @@ outside hides. A picture is often the fastest way for someone else to see what y
|
||||
3. User-visible behaviour is a command (`crates/engine/src/cmd/`) with tests, including hostile
|
||||
parameters.
|
||||
4. Meshing and solver algorithms cite the paper they come from in the module docs.
|
||||
5. A change you can see (the view, meshes, panels, results, icons) shows a picture before and after
|
||||
in the pull request.
|
||||
6. Never contribute code, text or data from GPL-family projects or commercial CAE products
|
||||
5. Never contribute code, text or data from GPL-family projects or commercial CAE products
|
||||
(see [docs/adr/0001-libraries.md](docs/adr/0001-libraries.md)).
|
||||
|
||||
By contributing you agree your work is licensed under MIT OR Apache-2.0.
|
||||
|
||||
@@ -3,12 +3,12 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.0"
|
||||
version = "0.5.7"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
authors = ["FieldCraft contributors"]
|
||||
repository = "https://github.com/tangency-labs/fieldcraft"
|
||||
repository = "https://github.com/jyviko/fieldcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# internal
|
||||
@@ -27,9 +27,6 @@ fieldcraft-testkit = { path = "crates/testkit" }
|
||||
fieldcraft-render = { path = "crates/render" }
|
||||
fieldcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
fieldcraft-mcp = { path = "crates/mcp" }
|
||||
fieldcraft-update = { path = "crates/update" }
|
||||
fieldcraft-gpu = { path = "crates/gpu" }
|
||||
fieldcraft-lbm-gpu = { path = "crates/lbm-gpu" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -37,9 +34,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
|
||||
# 3MF packages (docs/formats/tagged-mesh.md). zip is ahead of SolidCraft (still on 3), so both are built.
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
quick-xml = "0.42"
|
||||
# 3MF packages (docs/formats/tagged-mesh.md): the same versions SolidCraft uses.
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
quick-xml = "0.41"
|
||||
|
||||
# content hashes and part checksums of .fieldcraft files (the version SolidCraft uses)
|
||||
sha2 = "0.11"
|
||||
@@ -53,9 +50,6 @@ resvg = { version = "0.48", default-features = false }
|
||||
egui = "0.36"
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
egui-wgpu = "0.36"
|
||||
# the wgpu egui-wgpu uses, for the offscreen viewport (crates/gpu); backends come per target there
|
||||
wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }
|
||||
pollster = "1.0"
|
||||
# Shared Craft-family egui components (icon buttons, tabs, widget palette); the same rev as
|
||||
# VectorCraft. MIT OR Apache-2.0.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675" }
|
||||
@@ -64,13 +58,13 @@ rfd = "0.17"
|
||||
|
||||
# Geometry: SolidCraft's B-rep kernel (MIT OR Apache-2.0), pinned. Only crates/geometry uses it
|
||||
# (plan/adr/0001-libraries.md).
|
||||
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
# Runs SolidCraft command scripts (the test corpus recipes); only behind fieldcraft-geometry's
|
||||
# `scripts` feature.
|
||||
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -134,10 +128,10 @@ debug = "line-tables-only"
|
||||
# reach a dependent workspace, so FieldCraft applies the same ones from the same pinned commit;
|
||||
# keep this list and the rev in step with SolidCraft's [patch.crates-io].
|
||||
[patch.crates-io]
|
||||
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
# egui-wgpu with SolidCraft's fixes (vendor/egui-wgpu there): MSAA clamped to what the device
|
||||
# supports and 1x on OpenGL adapters, so the requested 4x never fails pipeline validation at start.
|
||||
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "b1695873f5d0031f51a8d5e7ec036fced6f000e2" }
|
||||
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
@@ -6,7 +6,7 @@ Licensed under the MIT License or the Apache License, Version 2.0, at your optio
|
||||
Third-party material
|
||||
|
||||
Software dependencies are listed in Cargo.lock; their licences are in THIRD-PARTY-LICENSES.txt
|
||||
(generated by `cargo xtask licences`, in every release package). Geometry comes from SolidCraft (https://github.com/bherbruck/solidcraft,
|
||||
(`cargo xtask licences`). Geometry comes from SolidCraft (https://github.com/bherbruck/solidcraft,
|
||||
MIT OR Apache-2.0), which builds on the truck crates (https://github.com/ricosjp/truck, Apache-2.0,
|
||||
Copyright (c) RICOS Co. Ltd.), some with SolidCraft's modifications.
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@ see the results — with a nonlinear implicit solver (large deformation, plastic
|
||||
in place. Hex meshing is the centre of gravity. Next: buckling and arc-length, contact, then
|
||||
the wider material and multiphysics library. See [ROADMAP.md](ROADMAP.md).
|
||||
**Want to help?** Pick an issue labelled
|
||||
[good first issue](https://github.com/tangency-labs/fieldcraft/labels/good%20first%20issue) or
|
||||
[help wanted](https://github.com/tangency-labs/fieldcraft/labels/help%20wanted) and read
|
||||
[good first issue](https://github.com/jyviko/fieldcraft/labels/good%20first%20issue) or
|
||||
[help wanted](https://github.com/jyviko/fieldcraft/labels/help%20wanted) and read
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||

|
||||
@@ -28,15 +28,15 @@ theory with shear 0.177 mm).
|
||||
|
||||
## Download
|
||||
|
||||
[](https://github.com/tangency-labs/fieldcraft/releases/latest)
|
||||
[](https://github.com/tangency-labs/fieldcraft/releases/latest)
|
||||
[](https://github.com/tangency-labs/fieldcraft/releases/latest)
|
||||
[](https://tangency-labs.github.io/fieldcraft/)
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://jyviko.github.io/fieldcraft/)
|
||||
|
||||
- **macOS:** open the `.dmg` and drag FieldCraft into Applications (Apple silicon and Intel).
|
||||
- **Windows:** unzip and run `fieldcraft.exe`.
|
||||
- **Linux:** the `.AppImage` (allow it to run as a program), or the `.tar.gz`.
|
||||
- **Browser:** [try it at tangency-labs.github.io/fieldcraft](https://tangency-labs.github.io/fieldcraft/), no install.
|
||||
- **Browser:** [try it at jyviko.github.io/fieldcraft](https://jyviko.github.io/fieldcraft/), no install.
|
||||
- **Command line:** `fieldcraft-cli` ships in every package; AI agents connect to it over MCP
|
||||
([docs/mcp.md](docs/mcp.md)).
|
||||
|
||||
@@ -98,27 +98,20 @@ Ready-to-solve samples: open one from **File ▸ Samples** (or the start screen)
|
||||
with `fieldcraft --sample NAME`, and press **Solve**. Each opens and solves within half a minute and is checked
|
||||
against a closed form or a reference solution ([docs/examples.md](docs/examples.md)).
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/drop-test.png" alt="Drop test" width="100%"><br><b>Drop test</b> (<code>drop-test</code>): an aluminium bracket dropped 2 m onto a tilted floor; explicit dynamics, the strike's stress waves</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/rubber-seal.png" alt="Rubber seal" width="100%"><br><b>Rubber seal</b> (<code>rubber-seal</code>): a Mooney–Rivlin gasket ring squeezed 25 %; nonlinear static, large strain</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/heated-bracket.png" alt="Heated bracket" width="100%"><br><b>Heated bracket</b> (<code>heated-bracket</code>): a clamped steel bracket heated at one end; steady heat and thermal stress</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/bracket-hex.png" alt="Hex-meshed bracket" width="100%"><br><b>Hex-meshed bracket</b> (<code>bracket-hex</code>): the bracket split into 30 cells, meshed all-hex (hex20), von Mises</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/crank-arm.png" alt="Bicycle crank arm" width="100%"><br><b>Bicycle crank arm</b> (<code>crank-arm</code>): an aluminium crank meshed structured all-hex (hex20) from a partitioned half and its mirror image, a rider's weight on the pedal; root bending within 0.3 % of M/Z</td>
|
||||
<td width="33%" valign="top"><i>No picture yet: the viewport does not draw flow results (M12).</i><br><b>Flow past a bracket</b> (<code>flow-past</code>): air past an L-bracket on the floor; lattice Boltzmann flow, the drag and the force on each face</td>
|
||||
</tr>
|
||||
</table>
|
||||
| | | |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
| **Drop test** (`drop-test`): an aluminium bracket dropped 2 m onto a tilted floor; explicit dynamics, the strike's stress waves | **Rubber seal** (`rubber-seal`): a Mooney–Rivlin gasket ring squeezed 25 %; nonlinear static, large strain | **Heated bracket** (`heated-bracket`): a clamped steel bracket heated at one end; steady heat and thermal stress |
|
||||
|  | *No picture yet: the viewport does not draw flow results (M12).* |  |
|
||||
| **Hex-meshed bracket** (`bracket-hex`): the bracket split into 30 cells, meshed all-hex (hex20), von Mises | **Flow past a bracket** (`flow-past`): air past an L-bracket on the floor; lattice Boltzmann flow, the drag and the force on each face | **Bicycle crank arm** (`crank-arm`): an aluminium crank swept all-hex (hex20), a rider's weight on the pedal; root bending within 0.3 % of M/Z |
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
cargo xtask ci # fmt, assets, layers, clippy, tests, wasm
|
||||
cargo xtask ci # fmt, assets, licences, layers, clippy, tests, wasm
|
||||
cargo xtask test --heavy # the heavy (ignored) tests and the doc tests
|
||||
cargo run -p fieldcraft-cli -- commands # every command and its parameters
|
||||
cargo run -p fieldcraft-cli -- run script.json # run a command script
|
||||
cargo run -p fieldcraft-cli -- snapshot script.json --out shot.png # draw it to a PNG, no window
|
||||
cargo run -p fieldcraft-cli -- mcp # MCP server on stdio for AI agents (docs/mcp.md)
|
||||
```
|
||||
|
||||
@@ -136,21 +129,10 @@ Rust 1.95 or later, with the `wasm32-unknown-unknown` target for `cargo xtask ci
|
||||
- [Releasing](docs/releasing.md): how a release is built, verified and published
|
||||
- [Contributing](CONTRIBUTING.md) and [agent instructions](AGENTS.md)
|
||||
|
||||
## Privacy
|
||||
|
||||
FieldCraft sends nothing until you agree. The first start asks once whether to share anonymous
|
||||
usage (which tools you use, nothing from your models); Help › Settings… changes it, and
|
||||
`FIELDCRAFT_TELEMETRY=0` turns it off. File names, paths, geometry, model contents, parameter
|
||||
values and messages are never sent: [docs/privacy.md](docs/privacy.md) lists every event and
|
||||
property. Crash reports and the log stay on your computer; Help › Report a Bug opens a GitHub issue
|
||||
you review and submit yourself, with your session or model attached only if you tick them
|
||||
([docs/crash-reports.md](docs/crash-reports.md)).
|
||||
|
||||
## License
|
||||
|
||||
Dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. Notices
|
||||
are in [NOTICE](NOTICE); third-party licences in
|
||||
THIRD-PARTY-LICENSES.txt, which every release package carries (`cargo xtask licences` writes it).
|
||||
are in [NOTICE](NOTICE); third-party licences in [THIRD-PARTY-LICENSES.txt](THIRD-PARTY-LICENSES.txt).
|
||||
|
||||
FieldCraft is an independent project, not affiliated with, sponsored or endorsed by Dassault
|
||||
Systèmes, MSC Software, Siemens or Ansys. Abaqus, Nastran, MSC Nastran, Simcenter Nastran and
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# OneCAD Simulation rebrand map (identity layer)
|
||||
|
||||
OneCAD Simulation is the OneBSpace fork of FieldCraft (a pure-Rust CAE app: FEA, meshing,
|
||||
thermal, LBM CFD, with a WASM web app at `apps/fieldcraft-web`). The rebrand is **source-level**
|
||||
for everything the user can see or click; only the compatibility layer keeps upstream names (so
|
||||
`.fieldcraft` files, crate names, storage keys and internal identifiers stay upstream-compatible,
|
||||
and every upstream sync stays a clean merge). Files tagged `// OneBSpace (OneCAD Simulation):`
|
||||
are downstream-only deltas — one tag per edited site, above or beside the change, so the whole
|
||||
fork layer can be found with `grep -rn "OneBSpace (OneCAD Simulation)"`.
|
||||
|
||||
## Rebranded in source (user-visible)
|
||||
|
||||
| Layer | Change |
|
||||
|---|---|
|
||||
| Web page | `<title>OneCAD Simulation`, description and social-card meta renamed; upstream's `tangency-labs.github.io/fieldcraft` `og:url`/`og:image`/`twitter:image` dropped; loading, no-JavaScript and could-not-start text say "OneCAD Simulation" (`apps/fieldcraft-web/index.html`) |
|
||||
| App bar | upstream's drawn fringe-cube vector mark dropped; a painted `OneCAD Simulation` wordmark (`appbar.rs::APP_NAME`) shows in **every** width variant — the compact bar keeps the name and the quick actions start after the measured wordmark (`bar_layout` gained a `name_w` argument) |
|
||||
| Help menu | Samples, navigation help, Crash Reports…, Settings… and the version label `OneCAD Simulation {VERSION}` remain; upstream's `Report a Bug…` (GitHub draft), `Check for Updates` and `Reinstall FieldCraft…` items and their handler branches are removed (`appbar.rs::help_menu`) |
|
||||
| Bug/crash reports | fully local: the Report-a-Bug form's `Open GitHub Issue` became a `Copy report` button — the draft (title, fields, session) goes to the clipboard and attachments to the local `bug-reports/` folder; nothing opens a browser, `ISSUE_URL` is never opened (`report.rs::copy_report`); crash questions/headings say "OneCAD Simulation closed unexpectedly / hit an internal error" |
|
||||
| Crash messages | the engine's unclean-exit and native-crash messages (rendered in the crash dialog and the copied report) name the fork (`engine/src/crash.rs`) |
|
||||
| Command catalogue | `diagnostics.bug_report` and `app.update.check` palette help texts describe the local draft / name the fork (`engine/src/cmd/diagnostics.rs`, `engine/src/cmd/update.rs`) |
|
||||
| Updates (desktop-only) | every status line, the notice and the install dialog say "OneCAD Simulation" (`updates.rs`); the web build has no update host, so none of this runs in the browser; "What's new"/release URLs stay desktop-only logic, rebranded text only |
|
||||
| Privacy | consent question and dialog title, Settings copy and tooltips say "OneCAD Simulation"; the upstream GitHub `PRIVACY_URL` is no longer rendered as a link nor opened — the privacy note is plain text (`privacy.rs`); the constant is kept for reference |
|
||||
| Navigation | the default mouse-mapping preset's label is "OneCAD Simulation" (its `id: "fieldcraft"` stays, preferences depend on it) |
|
||||
| Desktop window | window title / `run_native` app name "OneCAD Simulation" (`apps/fieldcraft/src/main.rs`; the `APP_ID` reverse-DNS id stays) |
|
||||
| Attachments | the bug-report session attachment is `onecadsim-session.json` (`engine/src/bug_report.rs::SESSION_FILE`); the model attachment keeps the `.fieldcraft` name |
|
||||
|
||||
## Stays upstream (compatibility & scale)
|
||||
|
||||
- **The `.fieldcraft` file-format extension** (and `model.fieldcraft` attachment naming); crate
|
||||
names and the Cargo workspace layout — untouched, so upstream syncs stay mergeable.
|
||||
- **localStorage keys** (`fieldcraft-recovery/`, `fieldcraft-prefs`) and the browser recovery
|
||||
folder layout.
|
||||
- **HTML element ids** (`fieldcraft_canvas`, `fieldcraft_loading`) and the trunk tags in
|
||||
`apps/fieldcraft-web/index.html`.
|
||||
- **Environment variable names** (`FIELDCRAFT_POSTHOG_KEY`, `FIELDCRAFT_TELEMETRY`,
|
||||
`FIELDCRAFT_CONTROL_PORT`, …). Telemetry logic is untouched: the Odoo build simply does not set
|
||||
`FIELDCRAFT_POSTHOG_KEY`, so the PostHog sender stays inert; no key or host URL is surfaced in
|
||||
the UI.
|
||||
- **Internal identifiers**: egui window/id salts (`fc_appbar`, `fc_report_bug`, …), command ids
|
||||
(`diagnostics.bug_report`), the `fieldcraft` nav-preset id, `SESSION_FILE`/`ISSUE_URL` API
|
||||
names, the `fieldcraft-cli` binary name quoted in report text.
|
||||
- Desktop-only updater internals (release URLs, package layouts) keep upstream strings —
|
||||
unreachable from the web build.
|
||||
|
||||
## Not touched here
|
||||
|
||||
`crates/ui-egui/src/files.rs` and `apps/fieldcraft-web/src/{web,main}.rs` plus `odoo/*` are owned
|
||||
by other agents in this task train; their user-visible strings are handled there.
|
||||
@@ -28,17 +28,17 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|
||||
|---|---|---|
|
||||
| M0 Foundation | Workspace, quality gates, FE model, command engine with rollback and panic guard, CLI, geometry boundary on SolidCraft | done |
|
||||
| M1 Geometry in and surface preparation | Open `.solidcraft` designs with persistent face names, assemblies placed (done); face-tagged 3MF (done); test corpus, `cargo xtask corpus` (done); exact predicates (done); quality metrics and certified validity gate (done); weld, closed/manifold/orientation and self-intersection checks, feature edges (`fieldcraft-mesh::surface`, `mesh.surface.check`, done) | in progress |
|
||||
| M2 Tet meshing and size field | Size field (global, curvature and proximity; edge seeds done: `mesh.seed.edge` on persistent design edge names (`<face>|<face>`) with a count or size, geometric bias and an exact, min or free constraint, shown as ticks and under Mesh › Seeds, honoured by the hex sweep, extrude, revolve, mapped, blocks and cells meshers through interval assignment (conflicting exact seeds named) and by the tet mesher, which divides the edge at the seed's nodes and grades its size field from them; per-face seeds to do; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in; size controls done (#435): `mesh.size.set` on faces, bodies, a box or a sphere with a growth rate (`mesh.size.growth`), saved with the model, listed by `mesh.size.list`, drawn in the viewport, honoured by the tet mesher's graded field, the structured hex meshers' and the block projection's divisions and the octree's depth); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
|
||||
| M2 Tet meshing and size field | Size field (global, per face and edge seeds, curvature and proximity; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
|
||||
| M3 First deck | Sets and surfaces bound to SolidCraft face, edge, vertex and body names, resolved after meshing; materials (isotropic and orthotropic elastic, density) with a unit-system label and consistency check; sections (solid, shell, beam profiles) assigned by set; element formulation per region mapped to each solver; BCs (fixed, displacement, symmetry); loads (force and moment on reference points, pressure, gravity); reference points with kinematic and distributing coupling; steps (linear static, frequency) with explicit per-step load and BC tables and output presets; `model.check` naming every missing or bad item; `model.*` and `mesh.tag` commands (model definition: done); writers for Abaqus input (done: `deck.write`), Nastran SOL 101/103 (done: `deck.write`) and LS-DYNA implicit (done); the `.fieldcraft` file (text definition, binary mesh, geometry references reopened on load, journal; atomic saves, autosave and recovery; undo/redo on the journal: done) | in progress |
|
||||
| M4 Own solver and first results | Element library per docs/elements.md (1D and 2D first); Linear static and modal solver (tet4/10, wedge6, hex8, hex20; sparse direct, Lanczos), verified against analytic solutions (solver: done — `fieldcraft-fem` kernels, `fieldcraft-solver` with nested dissection, sparse Cholesky and block Lanczos, `solve.static`/`solve.frequency`/`solve.probe`, patch, cantilever, Lamé, Kirsch and beam-frequency tests; reference points with kinematic and distributing couplings and moments by master–slave constraint elimination, verified by rigid motion, clamping, Saint-Venant tension, bending and tube torsion; 1D elements I: rod2/rod3 trusses, point masses, rotary inertia, springs and dashpots in both solvers and all three decks, verified by the method of joints, the three-bar truss, spring–mass, two-mass chain and torsional pendulum frequencies, and damped decay; 2D elements: plane stress, plane strain and axisymmetric tri3, tri6, quad4 (incompatible modes QM6), quad8 with two degrees of freedom per node, centrifugal loads, `mesh.planar` 2D meshes of polygons and planar faces, verified by patch tests, Kirsch, Lamé (plane strain and axisymmetric), rotating discs and cylinders, and a plane stress cantilever; deck mapping to Abaqus CPS/CPE/CAX, Nastran membranes, LS-DYNA ELFORM 12/13); shells and beams (done: quad4 MITC4 and tri3 MITC3 flat shells with a Hughes–Brezzi drilling rotation, two-node Timoshenko beams with profile properties and orientations, six degrees of freedom at shell and beam nodes shared with solids and trusses, section forces and surface stresses, verified by shell patch tests, Navier's plate, cantilever and portal-frame beams, and the Scordelis–Lo and pinched-cylinder benchmarks); results display (done: `results.*` commands, deformed shape to scale, banded contours of displacement, von Mises, principal and component stresses with a legend, mode shapes with their frequencies and animation, probing a node by clicking it, reaction force and moment sums per set, stale results marked after an edit; explicit steps: field frames by slider or animation with contours per frame, energy histories plotted) | started |
|
||||
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); partitions inside FieldCraft (done: datum planes and axes, `geometry.partition` cuts the open design by a datum plane, kept in the model and replayed when the design opens, the two faces of each cut paired by name); cells meshed each with its own method into one mesh (done: `mesh.cells` — hex where a method fits, else tet; matching interfaces merged node for node, others, such as hex next to tet, tied by dual mortar, verified by a tied hex–tet bar in tension to 1e-6); meshing half a symmetric part and mirroring it (done: `mesh.mirror` reflects hex8/hex20/tet4/tet10/wedge6 across a datum plane, right-handed, nodes on the plane merged, tags carried to the image half; a mirrored half bar equals the whole bar's mesh and bending deflection to 1e-12; samples `crank-arm` and `crank-mirror`: one datum, the half extruded in automatic blocks and mirrored, scaled Jacobian ≥ 0.37; or solving the half: `model.boundary_condition.symmetry` on a datum plane, a half bar with half the load bends as the whole to 1e-11); three-sided sweep regions mapped as triangle primitives (done: midpoint subdivision, dominance constraints in interval assignment); automatic blocks of extruded cross-sections (done: `hex::decompose` — holes separated, O-grids, cuts from concave corners and fillets chosen by block quality, kept only when no worse than the free mesh; nothing added to the model); pyramid transitions; automatic decomposition of 3D parts into sweepable and mappable regions | started |
|
||||
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing (node tools done: `mesh.node.merge` equivalences coincident nodes with sets and tags following the survivors and element collapses left out, previewed in its form; `mesh.check.duplicates` lists unmerged nodes, repeated elements, cracks and free edges and selects them; `mesh.renumber` compact, by body or in reverse Cuthill–McKee order, every reference following) and orphan-mesh import | started |
|
||||
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); sweepable cells in a conforming mesh and tet–hex transition; automatic decomposition into sweepable and mappable regions, proposed as SolidCraft splits | started |
|
||||
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing and orphan-mesh import | started |
|
||||
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar: done — `interaction.tie`, dual mortar constraints in the implicit analyses, Abaqus `*TIE` and LS-DYNA tied contact, the tie patch test); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (mortar contact pairs with Coulomb friction in nonlinear static steps: done — segment-to-segment mortar with the consistent tangent by automatic differentiation of the segmentation, augmented Lagrangian with Uzawa updates to a gap tolerance, semismooth active set with a chattering cutback, small sliding without nonlinear geometry and finite sliding with it, overclosure adjusted or refused, Coulomb friction (stick/slip return map, static and kinetic coefficients, symmetrised tangent), pressure, gap, status, shear and slip output; verified by the contact patch test, Hertz cylinder and sphere, Newton's quadratic rate and sliding blocks; the linear analyses refuse contact by name); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | started |
|
||||
| M8 Materials, explicit, shells, composites | Plasticity, hyperelasticity, damage data per solver; explicit dynamics decks (Abaqus/Explicit, LS-DYNA); midsurface shells; composite layups and material orientations, continuum shells on swept hex; hybrid (mixed u–p) hex8/hex20/tet10 for nearly incompressible materials (done); heat transfer (solids done: steady and θ-method transient conduction with flux, convection and sources, thermal strain in static steps (solids and 2D) and explicit dynamics (with plasticity), coupled temperature–displacement, `solve.heat`; deck output, 2D/shell/beam conduction planned) | started |
|
||||
| M9 Post-processing and deck readers | Results readers for public formats (Nastran OP2, LS-DYNA d3plot, Abaqus `.fil`); XY and path plots, cuts, display groups, free-body forces; deck readers that keep unknown keywords; mesh convergence studies | planned |
|
||||
| M10 Explicit dynamics | Shared element and material kernels with the implicit solver (`fem`); central-difference solver with lumped mass, stable time step, one-point hex8 with hourglass control and nodal-pressure tet4, bulk viscosity, energy accounting (X1 core: done — `fieldcraft-explicit`, `explicit_dynamic` steps with initial velocities, prescribed motion and planar rigid walls, `solve.explicit`/`solve.history`, small-strain linear elastic; bar wave, rigid-wall impact, energy balance and cantilever-period tests); large-deformation materials (X2: done — updated Lagrangian elements, Jaumann/Hughes–Winget and Green–Naghdi/Flanagan–Taylor rates, J2 bilinear/table plasticity, Johnson–Cook strength with heating and damage, erosion; materials gain `plastic`, `damage`, `erosion` with `model.material.plasticity`/`damage`; Dienes shear, rigid rotation, J2 uniaxial and Taylor-bar tests); contact (X3: done — `interaction.contact.pair`/`general`/`find`, segment-to-segment penalty contact both ways with polygon clipping (passes the contact patch test on non-matching meshes), pairs, general (all exterior faces) and self contact, bucket-grid search, deterministic on any thread count, a penalty from the masses and the stable increment that never shortens it, Coulomb friction with exponential decay by a return map, friction on rigid walls, contact energy and friction dissipation in the balance, initial penetrations adjusted or refused; Abaqus `*CONTACT PAIR`/`*CONTACT`/`*FRICTION` and LS-DYNA automatic contacts in the decks; verified by colliding bars, sliding blocks, the patch test and Hertz's sphere impact); hyperelastic materials (neo-Hookean, Mooney–Rivlin, Yeoh) on the shared material point with average nodal pressure tets, and opt-in mass scaling with the added mass reported: done; runs on hex and tet meshes | started |
|
||||
| M11 Equations of state and shells | Polynomial, ideal-gas, Mie–Grüneisen, JWL with programmed burn, tabulated; energy coupling; shock verification (Rankine–Hugoniot, Sod, Noh, Sedov); Belytschko–Lin–Tsay shells with self-contact on quad meshes | planned |
|
||||
| M12 CFD: lattice Boltzmann | D3Q19/D3Q27 on grids voxelised from the face-tagged surface; TRT, regularised and cumulant collision; interpolated walls, inlets and outlets; LES (Smagorinsky, WALE) with wall models; thermal LBM and conjugate heat transfer with the structure's thermal solver; non-Newtonian viscosity (power-law, Carreau–Yasuda, Cross, Herschel–Bulkley, Bingham) and temperature-dependent viscosity; porous media (Brinkman, Darcy–Forchheimer); multiphase and free surface (M13); validation by the lid-driven cavity, backward-facing step, cylinder wake (Strouhal) and turbulent channel; octree refinement shared with the hex mesher; wgpu backend (deterministic per device, checked against the CPU) (CPU core: done — `fieldcraft-lbm` with D3Q19 TRT and Guo forcing, halfway bounce-back and moving walls, slip and periodic faces, Zou–He velocity and pressure faces, exact voxelisation of obstacle bodies, momentum-exchange forces per face; fluid materials, fluid domains and fluid steps in the model; `model.fluid_domain.*`, `solve.fluid`; verified by Poiseuille channel and pipe, Couette, Taylor–Green decay, sphere-array Stokes drag and mass conservation; Schäfer–Turek 2D-1 as a benchmark; results in the viewport and headless pictures: velocity or pressure on a slice, the obstacles coloured by the flow beside them and streamlines seeded upstream, `results.slice`, `results.surface`, `results.streamlines`: done) | started |
|
||||
| M12 CFD: lattice Boltzmann | D3Q19/D3Q27 on grids voxelised from the face-tagged surface; TRT, regularised and cumulant collision; interpolated walls, inlets and outlets; LES (Smagorinsky, WALE) with wall models; thermal LBM and conjugate heat transfer with the structure's thermal solver; non-Newtonian viscosity (power-law, Carreau–Yasuda, Cross, Herschel–Bulkley, Bingham) and temperature-dependent viscosity; porous media (Brinkman, Darcy–Forchheimer); multiphase and free surface (M13); validation by the lid-driven cavity, backward-facing step, cylinder wake (Strouhal) and turbulent channel; octree refinement shared with the hex mesher; wgpu backend (deterministic per device, checked against the CPU) (CPU core: done — `fieldcraft-lbm` with D3Q19 TRT and Guo forcing, halfway bounce-back and moving walls, slip and periodic faces, Zou–He velocity and pressure faces, exact voxelisation of obstacle bodies, momentum-exchange forces per face; fluid materials, fluid domains and fluid steps in the model; `model.fluid_domain.*`, `solve.fluid`; verified by Poiseuille channel and pipe, Couette, Taylor–Green decay, sphere-array Stokes drag and mass conservation; Schäfer–Turek 2D-1 as a benchmark) | started |
|
||||
| M13 Fluid–structure interaction | Immersed-boundary coupling of the lattice Boltzmann fluid with the explicit or implicit structure; interface force transfer; sub-cycling; Aitken then interface quasi-Newton coupling; free-surface flow | planned |
|
||||
| M14 Blast and impact fluids | EOS-driven fluids in the explicit solver: ALE multi-material or SPH, with fluid–structure contact | planned |
|
||||
| M15 Nonlinear implicit core | Newton–Raphson with line search, automatic increments and cutbacks, convergence on force, displacement and energy; geometric nonlinearity (total and updated Lagrangian, large rotations for shells and beams, follower pressure); every `fem` material behind one interface with its consistent tangent (plasticity, damage and thermal strain from the explicit solver reused implicitly); arc-length (Riks) for snap-through; linear buckling (eigen) with preload stress stiffening, and imperfections from buckling modes; nonlinear stabilisation; restart. Verified by the elastica, Lee's frame, the snap-through arch, the hinged cylindrical shell and plastic collapse loads (solids core: done — `nonlinear_static` steps with automatic increments and cutbacks, Newton–Raphson with the consistent tangent, force, displacement and energy convergence and an optional line search; a material point interface (Kirchhoff stress and spatial tangent from F, with history) with St Venant–Kirchhoff and compressible neo-Hookean; total Lagrangian tet4, tet10, wedge6, hex8, hex20 (full and reduced), hybrid hex8/hex20/tet10 by the three-field mixed form, plane strain and axisymmetric elements; follower pressure with its symmetrised load stiffness; Cauchy stress and logarithmic strain, increment history and frames, `solve.nonlinear`; Abaqus and LS-DYNA decks; verified by the patch and objectivity tests, uniaxial stretch, the elastica and tube inflation by a follower pressure (finite-strain Cook's membrane pending its transcribed reference; J2 plasticity on the interface: Simo's exponential return map at finite strain and the radial return at small strain, both with consistent tangents and the return shared with explicit dynamics, bilinear isotropic and kinematic (small strain), tabulated and Johnson–Cook (rate-independent) hardening, hybrid elements included, load paths for cyclic loading, a tangent predictor for path-dependent materials, verified by uniaxial tension to large strain, Hill's thick cylinder (plastic zone and collapse pressure), a cantilever's collapse and the Bauschinger effect, with quadratic Newton convergence; Mooney–Rivlin and Yeoh options (decoupled, hybrid elements), verified in Treloar's three modes and by a stretched tube's inflation; thermal strain by the multiplicative split at finite strain and the additive one at small strain, with temperatures from temperature loads or the step's own conduction, verified by free and constrained expansion and a heated bar held past yield. a supernodal symmetric indefinite LDLᵀ factorization (bounded Bunch–Kaufman within supernodes, inertia) on which Newton continues through indefinite tangents, so nearly incompressible hybrid elements (ν = 0.4999) converge under prescribed displacement; linear buckling steps (linear preload, initial-stress stiffness of solids and 2D elements, block Lanczos in the K inner product, the shifted buckling transformation on LDLᵀ with an inertia count, `solve.buckle`, Abaqus `*BUCKLE`), verified by Euler columns and Bryan's plate; imperfections from buckling modes; arc-length (Riks–Crisfield, cylindrical or spherical) with limit and bifurcation points from the tangent's inertia, verified by the snap-through of a shallow arch. Next: Lee's frame and the hinged cylindrical shell (with shells), the follower pressure's full tangent (LU), incompatible modes (EAS), kinematic hardening at finite strain, shells and beams) | started |
|
||||
@@ -50,46 +50,9 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|
||||
| M21 Biomechanics and biomaterials | Soft tissue: Holzapfel–Gasser–Ogden fibre-reinforced hyperelasticity with dispersion, Fung, transversely isotropic models; biphasic and poro-hyperelastic cartilage (M19); active muscle (Hill-type); hydrogel swelling. Bone: density-dependent moduli from CT data, strain-energy-density remodelling (Huiskes, Beaupré). Growth and remodelling by kinematic growth (F = Fe·Fg). Implants and biomaterials (titanium, PEEK, UHMWPE) from the M17 library. Verified against published experiments with their tolerances | planned |
|
||||
| M22 Design studies | Parameters of the SolidCraft design driven from FieldCraft: parametric sweeps, design of experiments, response surfaces and sensitivities; topology optimisation (SIMP with filters, manufacturing constraints); size and shape optimisation; submodelling (driven boundaries from a global model); uncertainty quantification | planned |
|
||||
| M23 Wave propagation and ultrasound | Elastic, acoustic and coupled waves from the explicit solver's 1D bar today to guided and ultrasonic waves, by two methods. Finite differences first, for fast 2D (then 3D) ultrasound on regular grids: staggered-grid velocity–stress FDTD (Virieux) and the elastodynamic finite integration technique for solids, the rotated staggered grid for anisotropic media, a k-space pseudospectral scheme for weakly heterogeneous tissue and water, all on grids voxelised from the face-tagged geometry by the LBM's exact voxeliser, with heterogeneous, layered and fluid–solid media, CPML boundaries, threads and the GPU backend; staircased curved boundaries scatter spuriously, so the FD grid is checked against the finite elements on curved parts. Finite elements for curved geometry and coupling with structures: spectral elements (high-order Gauss–Lobatto–Legendre hexes with diagonal mass) on the hex meshes, and a mesh check in elements per wavelength with the dispersion error it implies; absorbing boundaries (convolutional PML, absorbing layers with increasing damping) and infinite media; tone-burst sources (Hann-windowed cycles), point, line and surface excitation, and piezoelectric transducers (M19); anisotropic media (composites, crystals) and viscoelastic, power-law-in-frequency attenuation; fluid–solid interfaces and fluid-loaded plates; ultrasound in water and tissue, nonlinear acoustics (Westervelt, KZK) for focused ultrasound. Guided waves: dispersion curves by semi-analytical finite elements (SAFE) for plates, pipes, rails and layered and anisotropic laminates — Lamb, Rayleigh, Love and SH modes — with phase and group velocities and mode shapes; mode-selective excitation. Output: A-scans and B-scans at sensors, wavefield snapshots, 2D FFT (frequency–wavenumber) for mode identification, and time–frequency diagrams of any signal — short-time Fourier spectrograms, continuous wavelet transforms (Morlet), reassigned spectrograms and smoothed pseudo Wigner–Ville — with the SAFE or Rayleigh–Lamb group-velocity curves overlaid as arrival times, and group velocities extracted from the ridges. GPU paths (M12's backend) for long runs. Verified by Lamb's problem (point load on a half-space), Rayleigh-wave speed, Rayleigh–Lamb dispersion, Love waves in a layer over a half-space, reflection and transmission at interfaces, and published guided-wave measurements | planned |
|
||||
| Continuous: verification and validation | Every capability checked against theory (closed forms), experiments (published measurements) and published benchmarks (NAFEMS, vendor benchmark and verification manuals such as Abaqus's), each case our own model in `tests/oracle/` with its cited reference and tolerance; `cargo xtask oracle` runs them and writes docs/oracle.md; once a case matches, our result is frozen as a fixture so fidelity cannot regress (docs/verification.md). Runner, fixtures and CI job: done; 62 theory cases (patch tests of every solid element, cantilevers, Lamé in 3D, plane strain and axisymmetric, Kirsch in 3D and plane stress, rotating disc and cylinder, beam frequencies, couplings, explicit waves, impact and J2 plasticity, CDT invariants), 15 published benchmarks (the MacNeal–Harder solid tests, the Scordelis–Lo roof with solids and with shells, the pinched cylinder, NAFEMS LE1 in 3D and 2D, LE2, LE3, LE5, LE7, LE10, FV32) and 8 pending cases with citations (the pinched hemisphere and twisted beam shell meshes, thermal, Cook's membrane, Taylor bar, CFD, explicit Hertz contact); `mesh.block` mapped blocks and 2D patches build their meshes, curved shell patches are written node by node | started |
|
||||
| Continuous: verification and validation | Every capability checked against theory (closed forms), experiments (published measurements) and published benchmarks (NAFEMS, vendor benchmark and verification manuals such as Abaqus's), each case our own model in `tests/oracle/` with its cited reference and tolerance; `cargo xtask oracle` runs them and writes docs/oracle.md; once a case matches, our result is frozen as a fixture so fidelity cannot regress (docs/verification.md). Runner, fixtures and CI job: done; 26 theory cases (patch tests of every solid element, cantilevers, Lamé in 3D, plane strain and axisymmetric, Kirsch in 3D and plane stress, rotating disc and cylinder, beam frequencies, couplings, explicit waves, impact and J2 plasticity, CDT invariants), 9 published benchmarks (MacNeal–Harder solid tests, Scordelis–Lo with solids, NAFEMS LE1 in 3D and 2D, LE10, FV32) and 9 pending cases with citations (shells, thermal, static plasticity, Taylor bar, CFD); `mesh.block` mapped blocks and 2D patches build their meshes | started |
|
||||
| Continuous: performance | CPU first, deterministic: results never depend on the thread count (fixed partitions, sums in a fixed order; checked by hashing results on 1, 2 and 7 threads). Supernodal left-looking Cholesky (11–15× faster than the column solver on one thread), parallel element matrices, stresses and Lanczos products, explicit element updates and LBM cell blocks on rayon threads (done — `fieldcraft-parallel`, `threads` on the solve commands, `FIELDCRAFT_THREADS`); parallel forward/back substitution and explicit tet4 assembly; GPU paths later, within a stated tolerance of the CPU | started |
|
||||
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; symbols as wireframes, one mark per constrained degree of freedom, a constant size on screen with a size setting, highlighted with their selected definition, concentrated loads drawn over the part: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done; in-app updates — a daily check of GitHub Releases, Help › Check for Updates and Reinstall, downloads verified against the release key's signature of SHA256SUMS.txt and swapped in after closing, `app.update.check`, `fieldcraft-cli update`, Reload to update in the browser, docs/updates.md: done), command schema as the public API | started |
|
||||
|
||||
## 0.6.0: the UI/UX release
|
||||
|
||||
What landed for 0.6.0 (milestone 0.6.0 on GitHub):
|
||||
|
||||
- **Browser:** status checks in one aligned column, Interactions counting ties, a selected set
|
||||
highlighted in the viewport, seeds selectable, editable and deletable, definitions shown with
|
||||
units instead of raw JSON, one highlighted item per context menu, given names shown as typed,
|
||||
and a setup checklist that does not ask for a load on a displacement-driven model or for a
|
||||
support or load on a free body in explicit dynamics (#315, #335, #336, #352, #356, #361, #366).
|
||||
- **Results:** units on every legend, summary, probe and reaction sum; legend ranges that can be
|
||||
clamped; max and min markers in the viewport; an energies plot with axes and the current frame;
|
||||
the deformed shape kept when the field changes; a sensible auto scale for large strains; setup
|
||||
symbols off over contours; heat flow through each convection and flux load; probe and reaction
|
||||
results exported to CSV (#92, #191, #319, #321, #325–#332, #362).
|
||||
- **Forms, progress and jobs:** solves and meshers run as jobs with their step, stage, count and
|
||||
elapsed time and a Cancel that interrupts every solver and mesher; the control channel and MCP
|
||||
wait for a long solve; mesher forms report what they made; typed fields for label lists, point
|
||||
lists, multi-choices and number-or-auto, JSON fields with hints, defaults shown as set; forms
|
||||
without orphan sets on Cancel; unknown parameters refused (#169, #316, #322–#324, #337, #339,
|
||||
#340, #353, #357, #367, #371).
|
||||
- **Picking and preparation:** vertices pickable, selected edges visible over the mesh, a
|
||||
reference point placed by a pick or a hole's centre, Seed Edges switching the filter to edges,
|
||||
live previews and default names for datums and partitions, readable partition cell names, the
|
||||
Partitioned Mesh form with picks and per-cell methods, a mesh marked out of date when its seeds
|
||||
or partitions change, remeshing from the current mesh's settings (#338, #341–#349, #351).
|
||||
- **UI conveniences:** File › New (`file.new`), Help › Crash Reports, the I-beam sample, every
|
||||
sample with a Start-card thumbnail and a gallery capture, node tools (merge, duplicates, free
|
||||
edges, renumber), the mesh quality panel's histograms and worst elements, Mirror Mesh and Mesh
|
||||
Block on the ribbon, Rigid Wall in Interactions, readable journal entries and status messages,
|
||||
a sample's name on its document tab, the web build naming an unknown sample (#113, #143, #144,
|
||||
#200, #234, #300, #333, #334, #348, #350, #354, #355, #359, #360, #365).
|
||||
- **Mesh soundness:** tet improvement that no longer crowds one vertex, hex20 extrudes that pass
|
||||
the validity gate where hex8 does, biased seeds carried to the opposite edge of a mapped face,
|
||||
designs with a closed internal void and face names over 256 characters meshed (#197, #257,
|
||||
#311, #364, #374).
|
||||
- **Heat:** heat transfer across ties for bonded multi-body thermal models (#358).
|
||||
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done), command schema as the public API | started |
|
||||
|
||||
## Next
|
||||
|
||||
@@ -123,20 +86,3 @@ What exists and what is missing, by area; each gap is in a milestone above.
|
||||
| Fluid dynamics | LBM D3Q19 TRT, walls, inlets/outlets, obstacle forces | Turbulence with wall models, thermal and conjugate heat transfer, non-Newtonian, porous media, multiphase, GPU (M12, M13) |
|
||||
| Wave propagation | One-dimensional elastic waves and impact in the explicit solver (bar cases in the oracle) | A 2D/3D finite-difference ultrasound solver (velocity–stress FDTD, EFIT, k-space pseudospectral) on voxelised geometry, time–frequency diagrams (spectrogram, wavelet, Wigner–Ville) with dispersion overlays, spectral elements, absorbing boundaries, tone-burst and transducer sources, attenuation, Lamb/Rayleigh/Love guided waves and SAFE dispersion curves, ultrasound in fluids and tissue, nonlinear acoustics, A/B-scans and frequency–wavenumber analysis (M23) |
|
||||
| Design | — | Parametric studies on SolidCraft parameters, optimisation, submodelling (M22) |
|
||||
|
||||
### Heated flow results (#157)
|
||||
|
||||
Temperature is available on fluid slices, obstacle surfaces and streamline colours when the
|
||||
saved frames carry it. Signed face-average wall heat follows recorded histories and the
|
||||
model's power/area units. Commands, the Results panel and headless pictures share the view;
|
||||
initial frames without recorded wall heat remain uncoloured.
|
||||
|
||||
### Flow start-up transient and gallery clip (#164)
|
||||
|
||||
`results.animate` now plays a fluid step's frames in order, the start-up transient from the
|
||||
uniform initial field to the settled flow, the way an explicit step plays its frames; the fluid Results
|
||||
panel gains an Animate control. The `flow-past` gallery sample gains a clip and a solved still of
|
||||
the air flowing past the L-bracket, regenerated by `tools/flow-clip/make.py` (the app rendered
|
||||
frame by frame over the control channel, encoded with ffmpeg). The wake forms and the drag
|
||||
settles; it does not shed (that needs a finer grid or a collision operator stable near τ⁺ = 0.5,
|
||||
#557).
|
||||
@@ -3,7 +3,7 @@
|
||||
FieldCraft is young; only `main` and the latest release get fixes.
|
||||
|
||||
Please **don't open a public issue** for a security problem. Report it privately through the
|
||||
repository's [Security tab](https://github.com/tangency-labs/fieldcraft/security/advisories/new) with
|
||||
repository's [Security tab](https://github.com/jyviko/fieldcraft/security/advisories/new) with
|
||||
what you found, how to reproduce it (a model, deck or script), the version and platform, and the
|
||||
impact you expect.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "fieldcraft-cli"
|
||||
description = "FieldCraft from the command line: list commands, run scripts, draw snapshots, serve MCP"
|
||||
description = "FieldCraft from the command line: list commands, run scripts, serve MCP"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -10,14 +10,6 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
fieldcraft-engine = { workspace = true }
|
||||
fieldcraft-lbm-gpu = { workspace = true }
|
||||
fieldcraft-gpu = { workspace = true }
|
||||
fieldcraft-render = { workspace = true }
|
||||
fieldcraft-io = { workspace = true }
|
||||
fieldcraft-mcp = { workspace = true }
|
||||
fieldcraft-update = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
png = { workspace = true }
|
||||
fieldcraft-update = { workspace = true, features = ["mock"] }
|
||||
@@ -1,80 +0,0 @@
|
||||
//! `fieldcraft-cli crashes`: the crash reports the desktop app wrote on this computer
|
||||
//! (docs/crash-reports.md): list them, show one, replay one, delete them.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use fieldcraft_engine::crash;
|
||||
use serde_json::json;
|
||||
|
||||
pub const USAGE: &str = "usage: fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]";
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let dir = crash::default_dir().ok_or("no crash folder on this system (set FIELDCRAFT_CRASH_DIR)")?;
|
||||
let id = || args.get(1).map(String::as_str).ok_or_else(|| USAGE.to_string());
|
||||
match args.first().map(String::as_str) {
|
||||
None | Some("list") => {
|
||||
let reports = crash::list(&dir);
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return print_json(&json!({ "dir": dir.to_string_lossy(), "reports": reports }));
|
||||
}
|
||||
println!("crash reports in {}", dir.display());
|
||||
if reports.is_empty() {
|
||||
println!(" (none)");
|
||||
}
|
||||
for r in reports {
|
||||
let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() };
|
||||
let cmd = r.command.map(|c| format!(" in {c}")).unwrap_or_default();
|
||||
let replay = if r.replayable { " [replayable]" } else { "" };
|
||||
println!(" {} {}{times}{cmd} v{}{replay}\n {}", r.id, r.kind, r.version, r.message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("show") => print_json(&crash::read(&dir, id()?)?),
|
||||
Some("replay") => replay(&dir, id()?),
|
||||
Some("dir") => {
|
||||
println!("{}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
Some("clear") => {
|
||||
println!("deleted {} report(s)", crash::clear(&dir, args.get(1).map(String::as_str)));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(USAGE.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_json(v: &serde_json::Value) -> Result<(), String> {
|
||||
println!("{}", serde_json::to_string_pretty(v).map_err(|e| e.to_string())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a report's commands on its model and say whether the crash happens again. Files the
|
||||
/// commands write go to a scratch folder, never over the user's files.
|
||||
fn replay(dir: &Path, id: &str) -> Result<(), String> {
|
||||
let report = crash::read(dir, id)?;
|
||||
let scratch = std::env::temp_dir().join(format!("fieldcraft-replay-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&scratch).map_err(|e| format!("{}: {e}", scratch.display()))?;
|
||||
if report["kind"] == "unclean_exit" {
|
||||
println!("this crash ended the app without a report: if this process ends abruptly, it reproduced");
|
||||
}
|
||||
println!("replaying on {}", report["model_path"].as_str().unwrap_or("a new model"));
|
||||
let r = crash::replay(&report, &scratch);
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
let r = r?;
|
||||
for (i, (cmd, outcome)) in r.steps.iter().enumerate() {
|
||||
match outcome {
|
||||
Ok(()) => println!(" {:>3}. {cmd}: ok", i + 1),
|
||||
Err(e) => println!(" {:>3}. {cmd}: {e}", i + 1),
|
||||
}
|
||||
}
|
||||
let said = |k: &str| report[k].as_str().unwrap_or_default().to_string();
|
||||
if r.reproduced {
|
||||
println!("reproduced: the same internal error ({}) at {}", said("message"), said("location"));
|
||||
} else if let Some((l, m)) = r.panics.first() {
|
||||
println!("an internal error happened, but not the reported one: {m} at {l}");
|
||||
println!("(the report says: {} at {})", said("message"), said("location"));
|
||||
} else {
|
||||
println!("did not reproduce: no internal error (fixed, or it depends on something the replay does not have)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,18 +1,11 @@
|
||||
//! fieldcraft-cli commands
|
||||
//! fieldcraft-cli run <script.json>
|
||||
//! fieldcraft-cli snapshot <script.json> --out shot.png [--view V | --camera JSON] [--size WxH] [--section x|y|z[=V]] [--field F]
|
||||
//! fieldcraft-cli features
|
||||
//! fieldcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
//! fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]
|
||||
//! fieldcraft-cli update --check | --install
|
||||
//! fieldcraft-cli --version
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod crashes;
|
||||
mod snapshot;
|
||||
mod update;
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -25,19 +18,6 @@ usage:
|
||||
fieldcraft-cli commands --json the same as JSON, each command's parameters as JSON Schema
|
||||
fieldcraft-cli run <script.json> run a script (a JSON array of {\"command\", \"params\"})
|
||||
and print the model summary
|
||||
fieldcraft-cli snapshot <script.json> --out FILE.png [--view V | --camera JSON]
|
||||
[--size WxH] [--section x|y|z[=VALUE]] [--field FIELD]
|
||||
run a script and draw the model to a PNG with no
|
||||
window: the viewport's GPU pipeline on a hardware or
|
||||
software GPU, else the CPU rasterizer (FIELDCRAFT_GPU=
|
||||
auto|hardware|software|cpu); V: iso (default), x, y, z,
|
||||
front, back, left, right, top, bottom; size 1280x800;
|
||||
--section hides the elements beyond a plane (at the
|
||||
mesh's middle, or VALUE); --field contours a nodal
|
||||
field of the solved step (results.contour);
|
||||
--camera '{\"yaw\":30,\"pitch\":20,\"target\":...,
|
||||
\"fit\":true,\"fov\":35}' aims as MCP screenshot's camera
|
||||
(default target: the model's centre of mass)
|
||||
fieldcraft-cli features print docs/features.md (every capability, ready or
|
||||
coming soon) from the capability catalogue
|
||||
fieldcraft-cli mcp [options] serve the Model Context Protocol on stdin/stdout
|
||||
@@ -48,14 +28,6 @@ usage:
|
||||
--automation-read-root DIR files may be read only inside DIR
|
||||
--automation-write-root DIR files may be written only inside DIR (with either root,
|
||||
the access a root left out is not granted)
|
||||
fieldcraft-cli crashes [list|show <id>|replay <id>|dir|clear [<id>]]
|
||||
the crash reports the desktop app wrote on this
|
||||
computer (docs/crash-reports.md): list them (--json),
|
||||
show one, replay one (does the crash happen again?),
|
||||
print their folder, delete them
|
||||
fieldcraft-cli update --check is a newer FieldCraft published? (app.update.check; JSON)
|
||||
fieldcraft-cli update --install download the latest release, verify its signature and
|
||||
checksum, and install it over this copy (docs/updates.md)
|
||||
fieldcraft-cli --version print the version
|
||||
";
|
||||
|
||||
@@ -63,8 +35,6 @@ usage:
|
||||
const MAX_SCRIPT_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// The lattice Boltzmann GPU backend, for `solve.fluid` with `backend: "gpu"` (scripts and MCP).
|
||||
fieldcraft_lbm_gpu::register();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let result = match args.first().map(String::as_str) {
|
||||
Some("commands") if args.get(1).map(String::as_str) == Some("--json") => {
|
||||
@@ -82,9 +52,6 @@ fn main() -> ExitCode {
|
||||
Ok(())
|
||||
}
|
||||
Some("mcp") => mcp(args.get(1..).unwrap_or(&[])),
|
||||
Some("crashes") => crashes::run(args.get(1..).unwrap_or(&[])),
|
||||
Some("update") => update::run(args.get(1..).unwrap_or(&[])),
|
||||
Some("snapshot") => snapshot::run(args.get(1..).unwrap_or(&[])),
|
||||
Some("run") => args.get(1).ok_or_else(|| format!("run needs a script\n\n{USAGE}")).and_then(|p| run(p)),
|
||||
Some("-V" | "--version") => {
|
||||
println!("fieldcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
@@ -153,14 +120,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
server.serve(std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| format!("mcp: {e}"))
|
||||
}
|
||||
|
||||
/// The JSON report of a picture: what drew it and what it shows (the MCP `screenshot` reply's
|
||||
/// fields).
|
||||
pub fn picture_report(r: &fieldcraft_gpu::Renderer, shown: &fieldcraft_engine::view::Shown) -> serde_json::Value {
|
||||
fieldcraft_mcp::picture_report(r, shown)
|
||||
}
|
||||
|
||||
/// The session after running the script at `path`.
|
||||
fn session_of(path: &str) -> Result<Session, String> {
|
||||
fn run(path: &str) -> Result<(), String> {
|
||||
let size = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?.len();
|
||||
if size > MAX_SCRIPT_BYTES {
|
||||
return Err(format!("{path}: larger than {} MB", MAX_SCRIPT_BYTES / (1024 * 1024)));
|
||||
@@ -169,11 +129,6 @@ fn session_of(path: &str) -> Result<Session, String> {
|
||||
let script: serde_json::Value = serde_json::from_str(&text).map_err(|e| format!("{path}: {e}"))?;
|
||||
let mut session = Session::default();
|
||||
session.run_script(&script).map_err(|e| e.to_string())?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn run(path: &str) -> Result<(), String> {
|
||||
let mut session = session_of(path)?;
|
||||
let info = session.execute("model.info", &json!({})).map_err(|e| e.to_string())?;
|
||||
println!("{}", serde_json::to_string_pretty(&info).map_err(|e| e.to_string())?);
|
||||
Ok(())
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
//! `fieldcraft-cli snapshot`: a script in, a PNG out, with no window and no display. The picture
|
||||
//! is the viewport's: the engine's scene ([`fieldcraft_engine::view::frame`]) drawn with the
|
||||
//! window's GPU pipelines ([`fieldcraft_gpu::capture`]) on a hardware GPU or a software one
|
||||
//! (lavapipe, llvmpipe, WARP), and by the CPU rasterizer as the last tier (`FIELDCRAFT_GPU`,
|
||||
//! [`fieldcraft_gpu::select`]).
|
||||
|
||||
use fieldcraft_engine::view::{self, Aim, Palette, Section, Target};
|
||||
use fieldcraft_gpu::Renderer;
|
||||
use fieldcraft_gpu::capture::{self, Capturer};
|
||||
use fieldcraft_gpu::select::Policy;
|
||||
use fieldcraft_render::{Orientation, StandardView};
|
||||
|
||||
/// The picture size when `--size` is not given.
|
||||
const DEFAULT_SIZE: (u32, u32) = (1280, 800);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Options {
|
||||
pub script: String,
|
||||
pub out: String,
|
||||
pub view: StandardView,
|
||||
/// A camera aimed as the MCP `screenshot`'s (`--camera JSON`; not with `--view`).
|
||||
pub camera: Option<Aim>,
|
||||
pub size: (u32, u32),
|
||||
/// A section through the mesh (`--section x|y|z[=VALUE]`).
|
||||
pub section: Option<Section>,
|
||||
/// A nodal field contoured on the last solved step (`--field von_mises`).
|
||||
pub field: Option<String>,
|
||||
}
|
||||
|
||||
/// A view name: a standard view, or the axis looked along (`x`: from the right, `y`: from the
|
||||
/// front, `z`: from the top).
|
||||
fn view_of(s: &str) -> Option<StandardView> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"x" => Some(StandardView::Right),
|
||||
"y" => Some(StandardView::Front),
|
||||
"z" => Some(StandardView::Top),
|
||||
other => StandardView::parse(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// `WxH`, each side 1..=the renderer's limit.
|
||||
fn size_of(s: &str) -> Option<(u32, u32)> {
|
||||
let (w, h) = s.split_once(['x', 'X'])?;
|
||||
let (w, h) = (w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?);
|
||||
let max = fieldcraft_gpu::capture::MAX_SIDE;
|
||||
((1..=max).contains(&w) && (1..=max).contains(&h) && u64::from(w) * u64::from(h) <= fieldcraft_gpu::capture::MAX_PIXELS).then_some((w, h))
|
||||
}
|
||||
|
||||
/// The options: the script, then each flag once, as `--flag value` or `--flag=value`.
|
||||
pub fn options(args: &[String]) -> Result<Options, String> {
|
||||
let (mut script, mut out, mut view, mut size, mut section, mut field, mut camera) = (None, None, None, None, None, None, None);
|
||||
let mut it = args.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
if !arg.starts_with("--") {
|
||||
if script.replace(arg.clone()).is_some() {
|
||||
return Err(format!("snapshot takes one script, not `{arg}` too"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (flag, inline) = match arg.split_once('=') {
|
||||
Some((f, v)) => (f, Some(v.to_string())),
|
||||
None => (arg.as_str(), None),
|
||||
};
|
||||
let value = inline.or_else(|| it.next().cloned()).filter(|v| !v.is_empty()).ok_or_else(|| format!("{flag} needs a value"))?;
|
||||
let twice = match flag {
|
||||
"--out" => out.replace(value).is_some(),
|
||||
"--view" => view
|
||||
.replace(
|
||||
view_of(&value).ok_or_else(|| format!("--view: unknown view `{value}` (iso, x, y, z, front, back, left, right, top, bottom)"))?,
|
||||
)
|
||||
.is_some(),
|
||||
"--size" => size
|
||||
.replace(size_of(&value).ok_or_else(|| {
|
||||
format!(
|
||||
"--size: `{value}` is not WxH with each side 1..={} and at most {} pixels",
|
||||
fieldcraft_gpu::capture::MAX_SIDE,
|
||||
fieldcraft_gpu::capture::MAX_PIXELS
|
||||
)
|
||||
})?)
|
||||
.is_some(),
|
||||
"--section" => section
|
||||
.replace(Section::parse(&value).ok_or_else(|| format!("--section: `{value}` is not x, y, z or AXIS=VALUE (x=12.5)"))?)
|
||||
.is_some(),
|
||||
"--field" => field.replace(value).is_some(),
|
||||
"--camera" => {
|
||||
let v: serde_json::Value = serde_json::from_str(&value).map_err(|e| format!("--camera: not JSON: {e}"))?;
|
||||
camera.replace(view::camera(&v).map_err(|e| format!("--camera: {e}"))?).is_some()
|
||||
}
|
||||
other => return Err(format!("snapshot: unknown option `{other}`")),
|
||||
};
|
||||
if twice {
|
||||
return Err(format!("{flag} is given twice"));
|
||||
}
|
||||
}
|
||||
if view.is_some() && camera.is_some() {
|
||||
return Err("give --view or --camera, not both".into());
|
||||
}
|
||||
Ok(Options {
|
||||
script: script.ok_or("snapshot needs a script")?,
|
||||
out: out.ok_or("snapshot needs --out FILE.png")?,
|
||||
view: view.unwrap_or(StandardView::Iso),
|
||||
camera,
|
||||
size: size.unwrap_or(DEFAULT_SIZE),
|
||||
section,
|
||||
field,
|
||||
})
|
||||
}
|
||||
|
||||
/// The PNG of the session `o` describes, drawn as `policy` says ([`capture::png`]).
|
||||
pub fn picture(o: &Options, policy: Policy) -> Result<(Vec<u8>, Renderer, view::Shown), String> {
|
||||
let mut session = crate::session_of(&o.script)?;
|
||||
if let Some(field) = &o.field {
|
||||
session.execute("results.contour", &serde_json::json!({"field": field})).map_err(|e| format!("--field: {e}"))?;
|
||||
}
|
||||
let (w, h) = o.size;
|
||||
let f = match &o.camera {
|
||||
Some(aim) => view::frame_at(&session, aim, w as usize, h as usize, &Palette::LIGHT, o.section).map_err(|e| e.to_string())?,
|
||||
None => view::frame(&session, &Orientation::of(o.view), w as usize, h as usize, &Palette::LIGHT, o.section),
|
||||
};
|
||||
let capturer = Capturer::open(policy);
|
||||
let (png, renderer) = capture::png(&capturer, policy, &f.scene, &[&f.symbols], &f.cam, w, h).map_err(|e| e.to_string())?;
|
||||
Ok((png, renderer, f.shown))
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let o = options(args)?;
|
||||
let policy = Policy::from_env().map_err(|e| e.to_string())?;
|
||||
let (png, renderer, shown) = picture(&o, policy)?;
|
||||
std::fs::write(&o.out, &png).map_err(|e| format!("{}: {e}", o.out))?;
|
||||
let mut report = crate::picture_report(&renderer, &shown);
|
||||
if let Some(r) = report.as_object_mut() {
|
||||
r.insert("out".into(), o.out.clone().into());
|
||||
r.insert("width".into(), o.size.0.into());
|
||||
r.insert("height".into(), o.size.1.into());
|
||||
match &o.camera {
|
||||
Some(aim) => r.insert("camera".into(), Aim { target: Some(aim.target.clone().unwrap_or(Target::MODEL)), ..aim.clone() }.json()),
|
||||
None => r.insert("view".into(), o.view.label().into()),
|
||||
};
|
||||
}
|
||||
println!("{report}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn opts(args: &[&str]) -> Result<Options, String> {
|
||||
options(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_are_checked() {
|
||||
let o = opts(&["s.json", "--out", "a.png"]).unwrap();
|
||||
assert_eq!(
|
||||
o,
|
||||
Options {
|
||||
script: "s.json".into(),
|
||||
out: "a.png".into(),
|
||||
view: StandardView::Iso,
|
||||
camera: None,
|
||||
size: DEFAULT_SIZE,
|
||||
section: None,
|
||||
field: None
|
||||
}
|
||||
);
|
||||
let o = opts(&["s", "--out", "o", "--section", "y=2.5", "--field", "displacement"]).unwrap();
|
||||
assert_eq!((o.section, o.field.as_deref()), (Some(Section { axis: 1, at: Some(2.5) }), Some("displacement")));
|
||||
assert_eq!(opts(&["s", "--out", "o", "--section=Z"]).unwrap().section, Some(Section { axis: 2, at: None }));
|
||||
let o = opts(&["--view=z", "s.json", "--size", "640x480", "--out=b.png"]).unwrap();
|
||||
assert_eq!((o.view, o.size), (StandardView::Top, (640, 480)));
|
||||
assert_eq!(opts(&["s", "--out", "o", "--view", "X"]).unwrap().view, StandardView::Right);
|
||||
assert_eq!(opts(&["s", "--out", "o", "--view", "front"]).unwrap().view, StandardView::Front);
|
||||
let o = opts(&["s", "--out", "o", "--camera", r#"{"yaw": 30, "pitch": 10, "target": [1, 2, 3], "fit": true}"#]).unwrap();
|
||||
assert_eq!(o.camera.and_then(|a| a.target), Some(Target::Point(fieldcraft_render::Vec3::new(1.0, 2.0, 3.0))));
|
||||
for bad in [
|
||||
vec![],
|
||||
vec!["s.json"],
|
||||
vec!["--out", "a.png"],
|
||||
vec!["s", "t", "--out", "o"],
|
||||
vec!["s", "--out"],
|
||||
vec!["s", "--out", "o", "--out", "p"],
|
||||
vec!["s", "--out", "o", "--view", "diagonal"],
|
||||
vec!["s", "--out", "o", "--size", "0x10"],
|
||||
vec!["s", "--out", "o", "--size", "10"],
|
||||
vec!["s", "--out", "o", "--size", "99999x10"],
|
||||
vec!["s", "--out", "o", "--size", "8192x8192"],
|
||||
vec!["s", "--out", "o", "--size", "-5x10"],
|
||||
vec!["s", "--out", "o", "--nope", "1"],
|
||||
vec!["s", "--out", "o", "--section", "w"],
|
||||
vec!["s", "--out", "o", "--section", "x=inf"],
|
||||
vec!["s", "--out", "o", "--section", "x=", "--field", "f"],
|
||||
vec!["s", "--out", "o", "--camera", "{yaw: 1}"],
|
||||
vec!["s", "--out", "o", "--camera", r#"{"yaw": 0}"#],
|
||||
vec!["s", "--out", "o", "--camera", r#"{"yaw": 0, "pitch": 0}"#, "--view", "x"],
|
||||
] {
|
||||
assert!(opts(&bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// PNG width, height and pixels (RGBA).
|
||||
fn decode(png: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let mut r = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
|
||||
let mut buf = vec![0; r.output_buffer_size().unwrap()];
|
||||
let info = r.next_frame(&mut buf).unwrap();
|
||||
buf.truncate(info.buffer_size());
|
||||
(info.width, info.height, buf)
|
||||
}
|
||||
|
||||
fn script(dir: &std::path::Path, name: &str, solve: bool) -> String {
|
||||
let mut steps = fieldcraft_engine::sample::cantilever();
|
||||
if solve && let Some(a) = steps.as_array_mut() {
|
||||
a.push(serde_json::json!({"command": "solve.static", "params": {}}));
|
||||
}
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, steps.to_string()).unwrap();
|
||||
path.to_string_lossy().into()
|
||||
}
|
||||
|
||||
fn opts_for(script: String) -> Options {
|
||||
Options { script, out: String::new(), view: StandardView::Iso, camera: None, size: (320, 200), section: None, field: None }
|
||||
}
|
||||
|
||||
/// The cantilever drawn headless: a PNG of the size asked for, with the model in it (pixels
|
||||
/// of the hex colour) and its element edges (dark pixels). `auto` draws on the GPU when the
|
||||
/// machine has one and on the CPU otherwise (it must be the GPU under `FIELDCRAFT_REQUIRE_GPU=1`); `cpu` always
|
||||
/// on the CPU, and both pictures show the same model. A section and a field change it.
|
||||
#[test]
|
||||
fn snapshots_the_model_and_its_mesh_headless() {
|
||||
let dir = std::env::temp_dir().join(format!("fieldcraft-snapshot-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let o = opts_for(script(&dir, "cantilever.json", false));
|
||||
for policy in [Policy::Auto, Policy::Cpu] {
|
||||
let (png, drawn, _) = picture(&o, policy).unwrap();
|
||||
let (w, h, px) = decode(&png);
|
||||
assert_eq!((w, h), (320, 200), "{drawn:?}");
|
||||
let hex = Palette::LIGHT.hex;
|
||||
let near = |p: &[u8], c: fieldcraft_render::Rgb, d: u8| p[0].abs_diff(c.0) <= d && p[1].abs_diff(c.1) <= d && p[2].abs_diff(c.2) <= d;
|
||||
// Shaded faces vary in brightness around the hex colour; the edges are near black.
|
||||
let faces = px.chunks(4).filter(|p| near(p, hex, 60) && p[2] > p[0]).count();
|
||||
let edges = px.chunks(4).filter(|p| p[0] < 90 && p[1] < 90 && p[2] < 90).count();
|
||||
assert!(faces > 500, "{drawn:?}: {faces} face pixels");
|
||||
assert!(edges > 100, "{drawn:?}: {edges} edge pixels");
|
||||
if policy == Policy::Cpu {
|
||||
assert_eq!(drawn, Renderer::Cpu { why: None });
|
||||
} else if fieldcraft_gpu::select::gpu_required() {
|
||||
assert!(matches!(drawn, Renderer::Gpu { .. }), "FIELDCRAFT_REQUIRE_GPU=1 but drawn by {drawn:?}");
|
||||
}
|
||||
}
|
||||
// A section along the beam draws half of it.
|
||||
let whole = picture(&o, Policy::Cpu).unwrap().0;
|
||||
let cut = picture(&Options { section: Some(Section { axis: 0, at: None }), ..o.clone() }, Policy::Cpu).unwrap().0;
|
||||
assert_ne!(whole, cut);
|
||||
// A field needs a solved step; on a solved one it is the contour reported.
|
||||
assert!(picture(&Options { field: Some("von_mises".into()), ..o.clone() }, Policy::Cpu).is_err());
|
||||
let solved = Options { field: Some("displacement".into()), ..opts_for(script(&dir, "solved.json", true)) };
|
||||
let (_, _, shown) = picture(&solved, Policy::Auto).unwrap();
|
||||
assert_eq!(shown.contour.map(|c| c.0).as_deref(), Some("displacement"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//! `fieldcraft-cli update --check | --install` (docs/updates.md): the same check as the app's
|
||||
//! Help › Check for Updates (`app.update.check`), and installing the latest release over this
|
||||
//! copy of the CLI's install, verified against the release key first. `FIELDCRAFT_UPDATE_HOST`
|
||||
//! points both at a local test server.
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use fieldcraft_update::install::{self, Finish};
|
||||
use fieldcraft_update::net::Client;
|
||||
use fieldcraft_update::stage::{self, Options};
|
||||
use serde_json::json;
|
||||
|
||||
pub const USAGE: &str = "usage: fieldcraft-cli update --check | --install";
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
|
||||
["--check"] => check(),
|
||||
["--install"] => install(),
|
||||
_ => Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn check() -> Result<(), String> {
|
||||
fieldcraft_engine::enable_update_checks(true);
|
||||
let report = Session::default().execute("app.update.check", &json!({})).map_err(|e| e.to_string())?;
|
||||
println!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install() -> Result<(), String> {
|
||||
let client = Client::from_env();
|
||||
let check = client.check().map_err(|e| e.to_string())?;
|
||||
if !check.newer() {
|
||||
println!("FieldCraft {} is up to date (the latest release is {}).", check.current, check.latest.version);
|
||||
return Ok(());
|
||||
}
|
||||
let here = install::here();
|
||||
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
|
||||
eprintln!("Downloading FieldCraft {} for {}…", check.latest.version, here.describe());
|
||||
let progress = |done: u64, total: u64| {
|
||||
if total > 0 && done == total {
|
||||
eprintln!("Downloaded {} MB; verifying…", total / (1024 * 1024));
|
||||
}
|
||||
};
|
||||
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
|
||||
let staged = stage::stage(&client, &check.latest, &here, &options).map_err(|e| e.to_string())?;
|
||||
match install::plan(&staged, false).map_err(|e| e.to_string())? {
|
||||
Finish::Swap(plan) => {
|
||||
stage::apply(&plan).map_err(|e| e.to_string())?;
|
||||
println!("Installed FieldCraft {} ({}). A running FieldCraft app uses it from its next start.", staged.version, here.describe());
|
||||
}
|
||||
Finish::Package { file, command } => {
|
||||
println!("Downloaded and verified {}.\nInstall it with the system's package manager:\n {command}", file.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
//! `fieldcraft-cli crashes` on a crash folder of its own (`FIELDCRAFT_CRASH_DIR`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const ID: &str = "20261014-101500-00000000deadbeef";
|
||||
|
||||
/// A replayable report: a model with two nodes and a replay that adds a third.
|
||||
fn folder() -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("fieldcraft-cli-crashes-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let r = d.join(ID);
|
||||
std::fs::create_dir_all(&r).unwrap();
|
||||
let mut s = Session::default();
|
||||
for l in 1..=2 {
|
||||
s.execute("mesh.node.add", &json!({"label": l, "xyz": [l, 0, 0]})).unwrap();
|
||||
}
|
||||
std::fs::write(r.join("model.fieldcraft"), s.file_bytes(None).unwrap()).unwrap();
|
||||
let replay = json!({"commands": [
|
||||
{"command": "mesh.node.add", "params": {"label": 3, "xyz": [3, 0, 0]}},
|
||||
{"command": "file.save", "params": {"path": d.join("overwritten.fieldcraft")}},
|
||||
]});
|
||||
std::fs::write(r.join("replay.json"), replay.to_string()).unwrap();
|
||||
let report = json!({
|
||||
"format": "fieldcraft-crash/1", "id": ID, "kind": "unclean_exit", "signature": "00000000deadbeef", "count": 2,
|
||||
"first_seen": "2026-10-14T10:15:00Z", "message": "FieldCraft ended without a clean exit while running `mesh.node.add`",
|
||||
"location": "unclean exit in mesh.node.add", "command": {"command": "mesh.node.add", "params": {}},
|
||||
"app": {"version": "9.9.9"}, "backtrace": [],
|
||||
});
|
||||
std::fs::write(r.join("report.json"), report.to_string()).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn cli(dir: &Path, args: &[&str]) -> (String, bool) {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_CRASH_DIR", dir).output().unwrap();
|
||||
(format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)), out.status.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crashes_list_show_replay_and_clear() {
|
||||
let d = folder();
|
||||
let (out, ok) = cli(&d, &["crashes"]);
|
||||
assert!(ok, "{out}");
|
||||
assert!(out.contains(ID) && out.contains("unclean_exit ×2 in mesh.node.add") && out.contains("[replayable]"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "list", "--json"]);
|
||||
assert!(ok);
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(v["reports"][0]["id"], ID);
|
||||
let (out, ok) = cli(&d, &["crashes", "show", ID]);
|
||||
assert!(ok);
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert!(v["model_path"].as_str().unwrap().ends_with("model.fieldcraft"));
|
||||
let (out, ok) = cli(&d, &["crashes", "replay", ID]);
|
||||
assert!(ok, "{out}");
|
||||
assert!(out.contains("1. mesh.node.add: ok"), "{out}");
|
||||
// A command that writes a file is refused outside the scratch folder: the replay never
|
||||
// writes over the user's files.
|
||||
assert!(out.contains("2. file.save: ") && out.contains("outside the write root"), "{out}");
|
||||
assert!(!d.join("overwritten.fieldcraft").exists());
|
||||
assert!(out.contains("did not reproduce"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "show", "../etc"]);
|
||||
assert!(!ok && out.contains("no crash report"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "dir"]);
|
||||
assert!(ok && out.trim() == d.to_string_lossy(), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "clear"]);
|
||||
assert!(ok && out.contains("deleted 1 report(s)"), "{out}");
|
||||
let (out, _) = cli(&d, &["crashes"]);
|
||||
assert!(out.contains("(none)"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "nope"]);
|
||||
assert!(!ok && out.contains("usage"), "{out}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//! `fieldcraft-cli update --check` against a local release server (FIELDCRAFT_UPDATE_HOST).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use fieldcraft_update::mock::Server;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn cli(host: &str, args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_UPDATE_HOST", host).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_check_reports_the_latest_release() {
|
||||
let server = Server::start().unwrap();
|
||||
server.release(
|
||||
"latest",
|
||||
&json!({"tag_name": "v99.0.0", "html_url": "https://github.com/tangency-labs/fieldcraft/releases/tag/v99.0.0", "assets": []}),
|
||||
);
|
||||
let out = cli(&server.url(), &["update", "--check"]);
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
let report: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(report["current"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!((report["latest"].as_str(), report["newer"].as_bool(), report["signed"].as_bool()), (Some("99.0.0"), Some(true), Some(false)));
|
||||
// A test build is not a release package: it checks but would not install.
|
||||
assert_eq!(report["asset"], Value::Null);
|
||||
assert_eq!(server.requests(), 1);
|
||||
|
||||
// The same version: not newer, and --install has nothing to do.
|
||||
server.release("latest", &json!({"tag_name": format!("v{}", env!("CARGO_PKG_VERSION")), "assets": []}));
|
||||
let out = cli(&server.url(), &["update", "--check"]);
|
||||
assert_eq!(serde_json::from_slice::<Value>(&out.stdout).unwrap()["newer"], false);
|
||||
let out = cli(&server.url(), &["update", "--install"]);
|
||||
assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("is up to date"), "{out:?}");
|
||||
|
||||
// Unreachable: an error, not a crash.
|
||||
let out = cli("http://127.0.0.1:1", &["update", "--check"]);
|
||||
assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("could not reach"), "{out:?}");
|
||||
assert!(!cli(&server.url(), &["update"]).status.success());
|
||||
}
|
||||
@@ -29,6 +29,6 @@ rfd = { workspace = true, features = ["file-handle-inner"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage", "Crypto", "Headers", "Request", "RequestInit", "RequestCache", "Response"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage"] }
|
||||
# Autosaves kept in the browser's local storage, which holds text.
|
||||
base64 = "0.23"
|
||||
base64 = "0.22"
|
||||
@@ -3,43 +3,47 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<title>OneCAD Simulation</title>
|
||||
<title>FieldCraft</title>
|
||||
<meta name="description" content="Open-source CAE modeling in Rust: mesh a part, set up the analysis and solve it, in your browser.">
|
||||
<!-- OneBSpace: upstream's social-card meta (og: / twitter:) and its og.png copy are
|
||||
stripped — no social junk in this app's bundle. -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="FieldCraft">
|
||||
<meta property="og:title" content="FieldCraft">
|
||||
<meta property="og:description" content="Open-source CAE built in Rust: structures, heat, fluids, and MCP for AI agents.">
|
||||
<meta property="og:url" content="https://jyviko.github.io/fieldcraft/">
|
||||
<meta property="og:image" content="https://jyviko.github.io/fieldcraft/og.png">
|
||||
<meta property="og:image:width" content="1280">
|
||||
<meta property="og:image:height" content="640">
|
||||
<meta property="og:image:alt" content="FieldCraft: Open-source CAE built in Rust">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="FieldCraft">
|
||||
<meta name="twitter:description" content="Open-source CAE built in Rust: structures, heat, fluids, and MCP for AI agents.">
|
||||
<meta name="twitter:image" content="https://jyviko.github.io/fieldcraft/og.png">
|
||||
<link data-trunk rel="rust" data-bin="fieldcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<link data-trunk rel="icon" type="image/svg+xml" href="../../assets/app-icon/icon-small.svg" />
|
||||
<link data-trunk rel="copy-file" href="../../assets/app-icon/icon.iconset/icon_128x128@2x.png" data-target-path="icons" />
|
||||
<link data-trunk rel="copy-file" href="../../docs/media/og.png" />
|
||||
<link rel="apple-touch-icon" href="icons/icon_128x128@2x.png">
|
||||
<!-- OneBSpace: the Odoo Documents host bridge glue (src/odoo). Copied verbatim
|
||||
(not hashed): the framework's bundleVersion ?v= on the iframe URL is the
|
||||
cache buster, like every other OneBSpace app bundle. -->
|
||||
<link data-trunk rel="copy-dir" href="src/odoo" data-target-path="odoo" />
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262c37; }
|
||||
#fieldcraft_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
|
||||
#fieldcraft_loading { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 16px; padding: 0 16px; text-align: center; color: #c3cad6; font: 14px system-ui, sans-serif; pointer-events: none; }
|
||||
/* OneBSpace: the upstream logo image is gone — a plain wordmark instead. */
|
||||
#fieldcraft_loading .wordmark { font: 600 clamp(28px, 6vmin, 52px) system-ui, sans-serif;
|
||||
letter-spacing: 0.18em; text-indent: 0.18em; color: #c3cad6; user-select: none; }
|
||||
#fieldcraft_loading img { width: 96px; height: 96px; }
|
||||
#fieldcraft_loading p { margin: 0; max-width: 32em; }
|
||||
#fieldcraft_loading.failed { pointer-events: auto; }
|
||||
#fieldcraft_loading.failed .spinner { display: none; }
|
||||
#fieldcraft_loading.failed img, #fieldcraft_loading.failed .spinner { display: none; }
|
||||
.spinner { width: 24px; height: 24px; border-radius: 50%; border: 3px solid #4a5468; border-top-color: #c3cad6; animation: spin 0.9s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="fieldcraft_canvas"></canvas>
|
||||
<div id="fieldcraft_loading" role="status">
|
||||
<span class="wordmark">OneCAD Simulation</span>
|
||||
<div id="fieldcraft_loading">
|
||||
<img src="icons/icon_128x128@2x.png" alt="">
|
||||
<div class="spinner"></div>
|
||||
<span class="sr-only">Loading OneCAD Simulation…</span>
|
||||
<!-- // OneBSpace (OneCAD Simulation): the no-JavaScript note names the fork -->
|
||||
<noscript><p>OneCAD Simulation needs JavaScript and WebAssembly.</p></noscript>
|
||||
<p>Loading FieldCraft…</p>
|
||||
<noscript><p>FieldCraft needs JavaScript and WebAssembly.</p></noscript>
|
||||
</div>
|
||||
<script>
|
||||
// The page could not load or start the app (no WebAssembly, a failed download): say so
|
||||
@@ -50,8 +54,7 @@
|
||||
if (!el || el.classList.contains("failed")) return;
|
||||
el.classList.add("failed");
|
||||
el.textContent = "";
|
||||
// // OneBSpace (OneCAD Simulation): the failure message names the fork
|
||||
["OneCAD Simulation could not start: " + why, "It needs a current browser with WebAssembly and WebGPU or WebGL2."].forEach(function (t) {
|
||||
["FieldCraft could not start: " + why, "It needs a current browser with WebAssembly and WebGPU or WebGL2."].forEach(function (t) {
|
||||
var p = document.createElement("p");
|
||||
p.textContent = t;
|
||||
el.appendChild(p);
|
||||
@@ -61,15 +64,5 @@
|
||||
addEventListener("unhandledrejection", function (e) { fail(String(e.reason && e.reason.message || e.reason)); });
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
// OneBSpace: boot the Odoo Documents bridge glue only inside a frame (the
|
||||
// wasm_app_framework shell). Standalone runs never import it.
|
||||
// odoo/index.js is src/odoo/index.ts compiled by the addon build script.
|
||||
try {
|
||||
if (window.parent !== window) {
|
||||
import("./odoo/index.js?v=20.0.1.0.0").catch((e) => console.warn("OneCAD Simulation odoo bridge:", e));
|
||||
}
|
||||
} catch (e) { /* cross-origin parent (standalone) — skip */ }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,75 +0,0 @@
|
||||
//! A new deployment of the web app: every half hour the page's own address is fetched past the browser's cache, and when it loads another build
|
||||
//! of the app than the one running (Trunk names each build's files by their content hash), the
|
||||
//! status bar offers "Reload to update" (docs/updates.md). Reloading asks first when the model
|
||||
//! has unsaved changes, as closing the page does.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
/// How often the page looks for a new deployment (seconds).
|
||||
pub const INTERVAL: f64 = 30.0 * 60.0;
|
||||
|
||||
/// Watches for a new deployment.
|
||||
pub struct Watch {
|
||||
/// The build this page runs.
|
||||
running: Option<String>,
|
||||
/// A fetch found another build.
|
||||
found: Rc<Cell<bool>>,
|
||||
/// App time of the last look.
|
||||
pub looked_at: f64,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
pub fn start() -> Watch {
|
||||
let html = web_sys::window().and_then(|w| w.document()).and_then(|d| d.document_element()).map(|e| e.outer_html()).unwrap_or_default();
|
||||
let running = crate::build_in_page(&html).map(str::to_string);
|
||||
if running.is_none() {
|
||||
log::info!("deploy: no hashed build in the page (a development server?); not watching");
|
||||
}
|
||||
Watch { running, found: Rc::default(), looked_at: 0.0 }
|
||||
}
|
||||
|
||||
/// Whether a newer deployment was found.
|
||||
pub fn found(&self) -> bool {
|
||||
self.found.get()
|
||||
}
|
||||
|
||||
/// Fetch the page again and compare its build with the running one.
|
||||
pub fn look(&self) {
|
||||
let (Some(running), Some(window)) = (self.running.clone(), web_sys::window()) else { return };
|
||||
if self.found.get() {
|
||||
return;
|
||||
}
|
||||
let url = window.location().pathname().unwrap_or_else(|_| "./".into());
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_cache(web_sys::RequestCache::NoStore);
|
||||
let promise = window.fetch_with_str_and_init(&url, &init);
|
||||
let found = self.found.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let text = async {
|
||||
let response: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise).await.ok()?.dyn_into().ok()?;
|
||||
if !response.ok() {
|
||||
return None;
|
||||
}
|
||||
wasm_bindgen_futures::JsFuture::from(response.text().ok()?).await.ok()?.as_string()
|
||||
};
|
||||
// Offline or refused: look again next time.
|
||||
if let Some(html) = text.await
|
||||
&& let Some(deployed) = crate::build_in_page(&html)
|
||||
&& deployed != running
|
||||
{
|
||||
log::info!("deploy: {deployed} is deployed (running {running})");
|
||||
found.set(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Reload the page (the new deployment loads).
|
||||
pub fn reload() {
|
||||
if let Some(w) = web_sys::window() {
|
||||
let _ = w.location().reload();
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,7 @@
|
||||
//! - files live in the page ([`fieldcraft_io::fs`] keeps them in memory): File › Open and drops
|
||||
//! read the computer's files into it; Save, Save As and Write Deck hand the written file out as
|
||||
//! a download;
|
||||
//! - autosaves for recovery and the preferences are kept in the browser's local storage
|
||||
//! ([`storage`], [`usage`]), and anonymous usage (when agreed) goes out with `fetch`;
|
||||
//! - autosaves for recovery are kept in the browser's local storage ([`storage`]);
|
||||
//! - no control channel (a page can't listen on a socket);
|
||||
//! - background jobs (meshing, solving) run on the page's one thread once the window has shown
|
||||
//! that they run.
|
||||
@@ -18,17 +17,10 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod deploy;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod storage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod usage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
// OneBSpace (OneCAD Simulation): Odoo Documents host integration
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod services_odoo;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
@@ -50,25 +42,6 @@ fn sample_in_query(query: &str) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The build of the app a page loads: the content-hashed name Trunk gives its WebAssembly
|
||||
/// (`fieldcraft-web-<hash>_bg.wasm`). A new deployment loads another one.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
fn build_in_page(html: &str) -> Option<&str> {
|
||||
const HEAD: &str = "fieldcraft-web-";
|
||||
const TAIL: &str = "_bg.wasm";
|
||||
let mut rest = html;
|
||||
while let Some(at) = rest.find(HEAD) {
|
||||
let candidate = rest.get(at..)?;
|
||||
let hash = candidate.get(HEAD.len()..)?;
|
||||
let len = hash.bytes().take_while(u8::is_ascii_alphanumeric).count();
|
||||
if len > 0 && hash.get(len..)?.starts_with(TAIL) {
|
||||
return candidate.get(..HEAD.len() + len + TAIL.len());
|
||||
}
|
||||
rest = candidate.get(HEAD.len()..)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The name a file from the computer is kept under in the page: its last path part, without
|
||||
/// characters a path would read as folders.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
@@ -91,18 +64,6 @@ mod tests {
|
||||
assert_eq!(sample_in_query("?samples=x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_running_build_is_found_in_the_page() {
|
||||
let page = r#"<link rel="modulepreload" href="/fieldcraft/fieldcraft-web-1a2b3c.js"><link rel="preload" href="/fieldcraft/fieldcraft-web-1a2b3c_bg.wasm" as="fetch">"#;
|
||||
assert_eq!(build_in_page(page), Some("fieldcraft-web-1a2b3c_bg.wasm"));
|
||||
let next = page.replace("1a2b3c", "9f8e7d");
|
||||
assert_ne!(build_in_page(page), build_in_page(&next));
|
||||
// A development page (no hash) and other text: nothing to compare.
|
||||
assert_eq!(build_in_page(r#"<script src="fieldcraft-web.js"></script>"#), None);
|
||||
assert_eq!(build_in_page("fieldcraft-web-"), None);
|
||||
assert_eq!(build_in_page(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_names_stay_in_their_folder() {
|
||||
assert_eq!(safe_name("beam.fieldcraft"), "beam.fieldcraft");
|
||||
|
||||
@@ -1,947 +0,0 @@
|
||||
// (C) OneBSpace — https://1bspace.com — a 1B Global company. Proprietary.
|
||||
// OneCAD Simulation Odoo Documents glue (ported from OneCAD).
|
||||
/**
|
||||
* OneCAD Simulation odoo/bridge.ts — the Odoo Documents bridge client + Rust facade.
|
||||
* -----------------------------------------------------------------------
|
||||
* Port of the family adapter (one-cut-pro apps/web/src/odoo/bridge.ts,
|
||||
* vanilla twin: onepixel frontend/src/odoo-host/bridge.ts) onto the
|
||||
* wasm_app_framework host protocol — authoritative implementation:
|
||||
* one-os-dev/core-components/wasm_app_framework/static/src/wasm_app_action.js
|
||||
*
|
||||
* request : {source: "one-cad-simulation", kind: "odoo-documents", id, method, payload}
|
||||
* posted on window.parent (same-origin Odoo shell iframe)
|
||||
* reply : {source: "one-cad-simulation-host", kind: "odoo-documents", id, ok,
|
||||
* result | error:{message}}
|
||||
*
|
||||
* Host methods and payload shapes (confirmed against the framework):
|
||||
* ping {} -> {user, folder, app:{root, projects?, assets?, exports?}}
|
||||
* list {} -> {documents:[{id,name,updatedAt,size}]}
|
||||
* read {recordId} -> {name, dataB64}
|
||||
* write {recordId?, name?, dataB64, folderId?} -> {id}
|
||||
* delete {recordId} -> {deleted}
|
||||
* usage {} -> {bytesUsed, documentCount}
|
||||
* folders {} -> {tree:[{id,name,parentId,system}], app:{...app, appsFilesRoot}}
|
||||
* createFolder {name, parentId?} -> {id}
|
||||
* listFolder {folderId} -> {folders:[{id,name,system}], files:[{id,name,ext,mimetype,size,updatedAt}]}
|
||||
* saveExport {name, dataB64, folderId?} -> {id} (folderId omitted -> the app's "exports" subfolder)
|
||||
* stat {recordId} -> {id, name, mimetype}
|
||||
*
|
||||
* Family laws: Documents is the ONLY storage; 60 s calls / 300 s writes;
|
||||
* one correlation id per call; air-gapped (no external fetch ever).
|
||||
* The 128 MB per-record cap is enforced HERE, on the raw bytes, before any
|
||||
* base64 conversion (the host mirrors it on base64 length * 3/4).
|
||||
*
|
||||
* RUST EVENT CONTRACT (window CustomEvents; the Rust side is built
|
||||
* separately and consumes host responses through these):
|
||||
*
|
||||
* LISTEN "onecadsim:host-request" detail {id:number, method:string,
|
||||
* (Rust -> JS) payload?:object}
|
||||
* One door for everything. Known host
|
||||
* methods (ping/list/read/write/delete/
|
||||
* usage/folders/createFolder/listFolder/
|
||||
* saveExport/stat) pass straight through
|
||||
* to the host with their own payload.
|
||||
* Orchestration methods run dialogs +
|
||||
* writes in JS and never hit the host:
|
||||
* "saveAs" {name?, dataB64?, recordId?, bytes?}
|
||||
* "open" {}
|
||||
* "export" {name?, dataB64?, bytes?}
|
||||
* "importAsset" {name?, dataB64?, bytes?}
|
||||
* Bytes may arrive as dataB64 (JSON) or a
|
||||
* Uint8Array in payload.bytes; when absent
|
||||
* the bridge asks the app to serialize
|
||||
* itself via window.onecadsim (below).
|
||||
* REQUEST QUEUE: entries are processed
|
||||
* strictly FIFO, one at a time, and each
|
||||
* id is answered exactly once.
|
||||
*
|
||||
* EMIT "onecadsim:host-response" detail {id, ok, result?, error?{message}}
|
||||
* (JS -> Rust) correlate with the request id. Timeouts
|
||||
* surface as ok:false errors (60 s calls,
|
||||
* 300 s write/read/saveExport).
|
||||
*
|
||||
* EMIT "onecadsim:host-ready" detail {host:boolean, documentId, name}
|
||||
* (JS -> Rust) fired once by the boot glue (odoo/
|
||||
* index.ts) after waitForHost() and any
|
||||
* ?document= deep-link read. Late-booting
|
||||
* Rust can read the same state sync at
|
||||
* window.onecadsimHost.{ready,host,documentId,name}.
|
||||
*
|
||||
* EMIT "onecadsim:document-opened" detail {documentId, name, dataB64}
|
||||
* (JS -> Rust) fired after the deep-link record was
|
||||
* read. The full payload stays available
|
||||
* for late listeners via
|
||||
* window.onecadsimHost.consumePendingOpen()
|
||||
* (returns the detail once, then null).
|
||||
*
|
||||
* JS -> APP window.onecadsim.request("odoo.document.bytes")
|
||||
* -> Promise<Uint8Array | ArrayBuffer | {dataB64}> — serialize
|
||||
* the current workspace (used when a save/export carries no
|
||||
* bytes). request("odoo.document.info") -> Promise<{name?}> —
|
||||
* suggested document name; failures are ignored.
|
||||
*
|
||||
* STANDALONE DEV MODE — when the app is not inside the framework iframe,
|
||||
* the facade goes inert: waitForHost() resolves immediately (host:false),
|
||||
* every host call rejects with a clear "standalone" error and host-request
|
||||
* events are answered ok:false — the app still boots, nothing hangs.
|
||||
*
|
||||
* This file is erasable-syntax-only TypeScript with ZERO dependencies: the
|
||||
* addon build compiles it to bridge.js next
|
||||
* to this file (node stripTypeScriptTypes; tsc when available).
|
||||
*/
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 60_000;
|
||||
const WRITE_TIMEOUT_MS = 300_000; // large .fieldcraft containers over the bridge
|
||||
const POLL_INTERVAL_MS = 100;
|
||||
const HOST_WAIT_MS = 20_000; // ping every 100 ms for up to 20 s
|
||||
/** Family cap (wasm_app_action.js MAX_DOCUMENT_BYTES), mirrored client-side. */
|
||||
export const MAX_DOCUMENT_BYTES = 128 * 1024 * 1024;
|
||||
|
||||
export const SOURCE_TAG = "one-cad-simulation";
|
||||
export const HOST_SOURCE_TAG = "one-cad-simulation-host";
|
||||
export const BRIDGE_KIND = "odoo-documents";
|
||||
|
||||
/** Window CustomEvent names of the Rust facade contract (see header). */
|
||||
export const EVT_HOST_REQUEST = "onecadsim:host-request";
|
||||
export const EVT_HOST_RESPONSE = "onecadsim:host-response";
|
||||
export const EVT_HOST_READY = "onecadsim:host-ready";
|
||||
export const EVT_DOCUMENT_OPENED = "onecadsim:document-opened";
|
||||
|
||||
/** window.onecadsim request names the bridge calls INTO the app. */
|
||||
export const APP_SERIALIZE_METHOD = "odoo.document.bytes";
|
||||
export const APP_INFO_METHOD = "odoo.document.info";
|
||||
|
||||
export interface OdooAppTree {
|
||||
root: number;
|
||||
projects?: number;
|
||||
assets?: number;
|
||||
exports?: number;
|
||||
appsFilesRoot?: number;
|
||||
}
|
||||
|
||||
export interface PingResult {
|
||||
user: string;
|
||||
folder: number;
|
||||
app: OdooAppTree;
|
||||
}
|
||||
|
||||
export interface FolderRow {
|
||||
id: number;
|
||||
name: string;
|
||||
parentId: number | null;
|
||||
system?: boolean;
|
||||
}
|
||||
|
||||
export interface FileRow {
|
||||
id: number;
|
||||
name: string;
|
||||
ext?: string;
|
||||
mimetype?: string;
|
||||
size: number;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface WriteResult {
|
||||
id: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface ReadResult {
|
||||
name: string;
|
||||
dataB64: string;
|
||||
}
|
||||
|
||||
export interface StatResult {
|
||||
id: number;
|
||||
name: string;
|
||||
mimetype: string;
|
||||
}
|
||||
|
||||
export interface UsageResult {
|
||||
bytesUsed: number;
|
||||
documentCount: number;
|
||||
}
|
||||
|
||||
export interface FoldersResult {
|
||||
tree: FolderRow[];
|
||||
app: OdooAppTree;
|
||||
}
|
||||
|
||||
export interface ListResult {
|
||||
documents: FileRow[];
|
||||
}
|
||||
|
||||
export interface CallOptions {
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface BindEntry {
|
||||
recordId: number;
|
||||
name: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** The document the app is currently working on (deep link / last save). */
|
||||
export interface CurrentBinding {
|
||||
documentId: number | null;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export interface ExplorerChoice {
|
||||
name?: string;
|
||||
folderId?: number;
|
||||
recordId?: number;
|
||||
recordName?: string;
|
||||
file?: File;
|
||||
}
|
||||
|
||||
export type ExplorerOpener = (opts: {
|
||||
mode: "save" | "open" | "asset" | "export";
|
||||
defaultName?: string;
|
||||
extensions?: string[];
|
||||
}) => Promise<ExplorerChoice | null>;
|
||||
|
||||
export interface HostRequestDetail {
|
||||
id: number;
|
||||
method: string;
|
||||
payload?: Record<string, unknown> | null;
|
||||
/** services_odoo.rs names the request object `params`; payload is the glue
|
||||
* spelling. runRequest accepts either. */
|
||||
params?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface HostResponseDetail {
|
||||
id: number;
|
||||
ok: boolean;
|
||||
result?: unknown;
|
||||
error?: { message: string } | null;
|
||||
}
|
||||
|
||||
export interface HostReadyDetail {
|
||||
host: boolean;
|
||||
documentId: number | null;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export interface DocumentOpenedDetail {
|
||||
documentId: number;
|
||||
name: string;
|
||||
dataB64: string;
|
||||
}
|
||||
|
||||
export interface SaveAsResult {
|
||||
id: number;
|
||||
name: string;
|
||||
folderId: number | null;
|
||||
}
|
||||
|
||||
export interface OpenResult {
|
||||
id: number;
|
||||
name: string;
|
||||
dataB64: string;
|
||||
}
|
||||
|
||||
export interface SavedResult {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Host method names accepted on "onecadsim:host-request" (pass-through). */
|
||||
const HOST_METHODS = new Set([
|
||||
"ping", "list", "read", "write", "delete", "usage",
|
||||
"folders", "createFolder", "listFolder", "saveExport", "stat",
|
||||
]);
|
||||
/** Host methods that move bulk bytes — family law says 300 s. */
|
||||
const BULK_METHODS = new Set(["read", "write", "saveExport"]);
|
||||
/** Orchestration methods served by this bridge (dialogs + writes). */
|
||||
const UI_METHODS = new Set(["saveAs", "open", "export", "importAsset"]);
|
||||
|
||||
const BIND_KEY_PREFIX = "one-cad-sim:fieldcraft:bind:";
|
||||
const OWNED_EXTENSION = ".fieldcraft";
|
||||
|
||||
/** Rust services_odoo.rs ASSET_EXTS — pick_program offers these from Documents. */
|
||||
const RUST_ASSET_EXTS = ["step", "stp", "iges", "igs", "brep", "stl", "obj", "3mf", "dxf", "gltf", "glb", "ply"];
|
||||
|
||||
/** Emulated pending paths must sanitize exactly like services_odoo.rs::sanitize. */
|
||||
function sanitizeName(name: unknown): string {
|
||||
const cleaned = String(name || "").replace(/[/\\]/g, "_").trim();
|
||||
return cleaned || "file";
|
||||
}
|
||||
|
||||
/** Pull the Uint8Array payload out of an odoo.write / odoo.import event. */
|
||||
function bytesOf(payload: Record<string, unknown>): Uint8Array | null {
|
||||
const raw = payload ? payload.bytes : undefined;
|
||||
if (!raw) return null;
|
||||
if (raw instanceof Uint8Array) return raw;
|
||||
// Cross-realm payloads (tests, odd hosts): isView works across realms.
|
||||
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(raw)) {
|
||||
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
}
|
||||
if (typeof ArrayBuffer !== "undefined" && raw instanceof ArrayBuffer) return new Uint8Array(raw);
|
||||
return normalizeBytes(raw);
|
||||
}
|
||||
|
||||
function newToken(): string {
|
||||
if (window.crypto && typeof window.crypto.randomUUID === "function") {
|
||||
return "t" + window.crypto.randomUUID().replace(/-/g, "");
|
||||
}
|
||||
return "t" + Date.now().toString(36) + Math.random().toString(36).slice(2);
|
||||
}
|
||||
|
||||
interface PendingTokenBinding {
|
||||
recordId: number | null;
|
||||
name: string;
|
||||
folderId: number | null;
|
||||
}
|
||||
|
||||
interface OnecadsimApi {
|
||||
request?: (method: string, params?: unknown) => Promise<unknown>;
|
||||
}
|
||||
|
||||
interface PendingEntry {
|
||||
resolve: (value: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
interface QueueEntry {
|
||||
id: number;
|
||||
method: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Codec + guard helpers (exported for the explorer and the app glue) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Chunked btoa so multi-megabyte CAD containers never blow the arg stack. */
|
||||
export function bytesToBase64(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
const chunk = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
const slice = bytes.subarray(i, i + chunk);
|
||||
binary += String.fromCharCode.apply(null, Array.from(slice) as unknown as number[]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function base64ToBytes(dataB64: string): Uint8Array {
|
||||
const binary = atob(dataB64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** Family 128 MB cap, enforced on RAW bytes before base64 conversion. */
|
||||
export function guardCap(bytes: Uint8Array): void {
|
||||
if (bytes.byteLength > MAX_DOCUMENT_BYTES) {
|
||||
throw new Error(
|
||||
"OneCAD Simulation odoo bridge: document exceeds the 128 MB bridge limit (" +
|
||||
bytes.byteLength + " raw bytes)",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBytes(value: unknown): Uint8Array | null {
|
||||
if (value instanceof Uint8Array) return value;
|
||||
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
||||
if (value && typeof value === "object") {
|
||||
const holder = value as { dataB64?: unknown };
|
||||
if (typeof holder.dataB64 === "string") return base64ToBytes(holder.dataB64);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function ensureExtension(name: string, extension: string): string {
|
||||
const trimmed = (name || "").trim() || "Untitled";
|
||||
const dot = trimmed.lastIndexOf(".");
|
||||
if (dot > 0) return trimmed;
|
||||
return trimmed + extension;
|
||||
}
|
||||
|
||||
function stripOwnedExtension(name: string): string {
|
||||
return (name || "").replace(/\.(fieldcraft|solidcraft)$/i, "");
|
||||
}
|
||||
|
||||
function detectInFrame(): boolean {
|
||||
try {
|
||||
return window.parent !== window;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function onecadsimApi(): OnecadsimApi | null {
|
||||
const holder = window as unknown as { onecadsim?: OnecadsimApi };
|
||||
const api = holder.onecadsim;
|
||||
return api && typeof api.request === "function" ? api : null;
|
||||
}
|
||||
|
||||
function messageOf(error: unknown): string {
|
||||
return error && typeof error === "object" && "message" in error
|
||||
? String((error as { message?: unknown }).message)
|
||||
: String(error);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* The bridge */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
class OneCadBridge {
|
||||
inFrame: boolean;
|
||||
standalone: boolean = false;
|
||||
nextId: number = 1;
|
||||
pending: Map<number, PendingEntry> = new Map();
|
||||
queue: QueueEntry[] = [];
|
||||
draining: boolean = false;
|
||||
opener: ExplorerOpener | null = null;
|
||||
binding: CurrentBinding = { documentId: null, name: null };
|
||||
pendingOpen: DocumentOpenedDetail | null = null;
|
||||
/** odoo.pickSave tokens -> binding (services_odoo.rs writes to
|
||||
* /odoo/pending/<token>/<name>; the first write creates the record and
|
||||
* every later Ctrl+S writes back in place). */
|
||||
pendingTokens = new Map<string, PendingTokenBinding>();
|
||||
|
||||
constructor() {
|
||||
this.inFrame = detectInFrame();
|
||||
window.addEventListener("message", (event) => this.onMessage(event));
|
||||
window.addEventListener(EVT_HOST_REQUEST, ((event: Event) => {
|
||||
const detail = (event as CustomEvent).detail as HostRequestDetail | undefined;
|
||||
if (!detail || typeof detail.id !== "number" || typeof detail.method !== "string") return;
|
||||
// services_odoo.rs dispatches the request object as `params`; the
|
||||
// orchestration glue historically used `payload`. Accept both.
|
||||
const raw = detail.payload !== undefined ? detail.payload : detail.params;
|
||||
this.enqueue({
|
||||
id: detail.id,
|
||||
method: detail.method,
|
||||
payload: (raw && typeof raw === "object"
|
||||
? raw
|
||||
: {}) as Record<string, unknown>,
|
||||
});
|
||||
}) as EventListener);
|
||||
}
|
||||
|
||||
/* ---------------- host plumbing ---------------- */
|
||||
|
||||
isHostAvailable(): boolean {
|
||||
return this.inFrame && !this.standalone;
|
||||
}
|
||||
|
||||
private onMessage(event: MessageEvent): void {
|
||||
const message = event.data as
|
||||
| { source?: string; kind?: string; id?: number; ok?: boolean; result?: unknown; error?: { message?: string } | null }
|
||||
| null;
|
||||
if (
|
||||
!message ||
|
||||
typeof message !== "object" ||
|
||||
message.source !== HOST_SOURCE_TAG ||
|
||||
message.kind !== BRIDGE_KIND ||
|
||||
typeof message.id !== "number"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) return;
|
||||
this.pending.delete(message.id);
|
||||
clearTimeout(pending.timer);
|
||||
if (message.ok) pending.resolve(message.result);
|
||||
else pending.reject(new Error(message.error?.message || "Odoo Documents bridge call failed"));
|
||||
}
|
||||
|
||||
/** One correlation id per call; 60 s default / 300 s for writes. */
|
||||
call<T>(method: string, payload?: Record<string, unknown>, options?: CallOptions): Promise<T> {
|
||||
if (!this.inFrame) {
|
||||
this.standalone = true;
|
||||
return Promise.reject(
|
||||
new Error(`OneCAD Simulation odoo bridge: standalone (no Odoo host) — "${method}" unavailable`),
|
||||
);
|
||||
}
|
||||
const timeoutMs = (options && options.timeoutMs) || DEFAULT_TIMEOUT_MS;
|
||||
const id = this.nextId++;
|
||||
const envelope = {
|
||||
source: SOURCE_TAG,
|
||||
kind: BRIDGE_KIND,
|
||||
id,
|
||||
method,
|
||||
payload: payload || {},
|
||||
};
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`OneCAD Simulation odoo bridge: "${method}" timed out after ${timeoutMs} ms`));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });
|
||||
// The framework shell is our parent window (same origin).
|
||||
window.parent.postMessage(envelope, window.location.origin);
|
||||
});
|
||||
}
|
||||
|
||||
/** Ping every 100 ms until the host answers (mount-order independence). */
|
||||
async waitForHost(timeoutMs: number = HOST_WAIT_MS): Promise<PingResult> {
|
||||
if (!this.inFrame) {
|
||||
this.standalone = true;
|
||||
return { user: "", folder: 0, app: { root: 0 } };
|
||||
}
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError: Error | null = null;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const pong = await this.ping();
|
||||
this.standalone = false;
|
||||
return pong;
|
||||
} catch (error) {
|
||||
lastError = error as Error;
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`OneCAD Simulation odoo bridge: host did not answer ping within ${timeoutMs} ms (${messageOf(lastError)})`,
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------- raw host calls ---------------- */
|
||||
|
||||
ping(): Promise<PingResult> {
|
||||
return this.call<PingResult>("ping");
|
||||
}
|
||||
|
||||
list(): Promise<ListResult> {
|
||||
return this.call<ListResult>("list");
|
||||
}
|
||||
|
||||
stat(recordId: number): Promise<StatResult> {
|
||||
return this.call<StatResult>("stat", { recordId });
|
||||
}
|
||||
|
||||
read(recordId: number): Promise<ReadResult> {
|
||||
return this.call<ReadResult>("read", { recordId }, { timeoutMs: WRITE_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
write(payload: { recordId?: number; name?: string; dataB64: string; folderId?: number }, timeoutMs?: number): Promise<WriteResult> {
|
||||
return this.call<WriteResult>("write", payload, { timeoutMs: timeoutMs || WRITE_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
delete(recordId: number): Promise<{ deleted: boolean }> {
|
||||
return this.call<{ deleted: boolean }>("delete", { recordId });
|
||||
}
|
||||
|
||||
usage(): Promise<UsageResult> {
|
||||
return this.call<UsageResult>("usage");
|
||||
}
|
||||
|
||||
folders(): Promise<FoldersResult> {
|
||||
return this.call<FoldersResult>("folders");
|
||||
}
|
||||
|
||||
createFolder(payload: { name: string; parentId?: number }): Promise<{ id: number }> {
|
||||
return this.call<{ id: number }>("createFolder", payload);
|
||||
}
|
||||
|
||||
listFolder(folderId: number): Promise<{ folders: FolderRow[]; files: FileRow[] }> {
|
||||
return this.call<{ folders: FolderRow[]; files: FileRow[] }>("listFolder", { folderId });
|
||||
}
|
||||
|
||||
saveExport(payload: { name: string; dataB64: string; folderId?: number }, timeoutMs?: number): Promise<WriteResult> {
|
||||
return this.call<WriteResult>("saveExport", payload, { timeoutMs: timeoutMs || WRITE_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
/* ---------------- binding cache (localStorage) ---------------- */
|
||||
|
||||
getCurrentBinding(): CurrentBinding {
|
||||
return this.binding;
|
||||
}
|
||||
|
||||
/** document name -> Odoo record id, keyed by app + document name. */
|
||||
bindLookup(name: string): BindEntry | null {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(BIND_KEY_PREFIX + stripOwnedExtension(name));
|
||||
if (!raw) return null;
|
||||
const entry = JSON.parse(raw) as BindEntry;
|
||||
return entry && typeof entry.recordId === "number" ? entry : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bindSet(name: string, recordId: number): void {
|
||||
this.binding = { documentId: recordId, name: stripOwnedExtension(name) };
|
||||
try {
|
||||
const entry: BindEntry = {
|
||||
recordId,
|
||||
name: stripOwnedExtension(name),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
window.localStorage.setItem(BIND_KEY_PREFIX + entry.name, JSON.stringify(entry));
|
||||
} catch {
|
||||
/* private mode — memory-only binding still works for this session */
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- document flows ---------------- */
|
||||
|
||||
/** Ctrl+S style write-back / create. Guard runs BEFORE base64. */
|
||||
async saveDocument(bytes: Uint8Array | ArrayBuffer, name: string, recordId?: number): Promise<WriteResult> {
|
||||
const raw = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
||||
guardCap(raw);
|
||||
const dataB64 = bytesToBase64(raw);
|
||||
const clean = ensureExtension(name, OWNED_EXTENSION);
|
||||
const result = await this.write({ recordId, name: clean, dataB64 });
|
||||
this.bindSet(result.name || clean, result.id);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Deep-link read; also refreshes the current binding. */
|
||||
async readDocument(recordId: number): Promise<ReadResult> {
|
||||
const result = await this.read(recordId);
|
||||
this.bindSet(result.name, recordId);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* ?document=<id> boot deep link. Never throws (boot must proceed);
|
||||
* on success stores pendingOpen, fires "onecadsim:document-opened" and
|
||||
* refreshes the binding so host-ready can carry the metadata.
|
||||
*/
|
||||
async openDeepLink(search?: string): Promise<boolean> {
|
||||
let params: URLSearchParams;
|
||||
try {
|
||||
params = new URLSearchParams(search === undefined ? window.location.search : search);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const rawId = params.get("document");
|
||||
if (!rawId) return false;
|
||||
const id = Number(rawId);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
console.warn("[onecadsim-odoo] ignoring malformed deep link ?document=" + rawId);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const opened = await this.readDocument(id);
|
||||
this.pendingOpen = { documentId: id, name: opened.name, dataB64: opened.dataB64 };
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<DocumentOpenedDetail>(EVT_DOCUMENT_OPENED, { detail: this.pendingOpen }),
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[onecadsim-odoo] deep-link read failed for document " + id + ":", messageOf(error));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Late-boot consumers fetch the deep-link payload once, then null. */
|
||||
consumePendingOpen(): DocumentOpenedDetail | null {
|
||||
const pending = this.pendingOpen;
|
||||
this.pendingOpen = null;
|
||||
return pending;
|
||||
}
|
||||
|
||||
setExplorerOpener(opener: ExplorerOpener): void {
|
||||
this.opener = opener;
|
||||
}
|
||||
|
||||
private async askExplorer(options: {
|
||||
mode: "save" | "open" | "asset" | "export";
|
||||
defaultName?: string;
|
||||
extensions?: string[];
|
||||
}): Promise<ExplorerChoice | null> {
|
||||
if (!this.isHostAvailable()) {
|
||||
throw new Error("OneCAD Simulation odoo bridge: standalone (no Odoo host) — explorer unavailable");
|
||||
}
|
||||
if (!this.opener) {
|
||||
throw new Error("OneCAD Simulation odoo bridge: no explorer dialog wired (setExplorerOpener)");
|
||||
}
|
||||
return this.opener(options);
|
||||
}
|
||||
|
||||
private async appSerialize(): Promise<Uint8Array> {
|
||||
const api = onecadsimApi();
|
||||
if (!api || !api.request) {
|
||||
throw new Error(
|
||||
"OneCAD Simulation odoo bridge: no document bytes given and window.onecadsim is unavailable",
|
||||
);
|
||||
}
|
||||
const out = await api.request(APP_SERIALIZE_METHOD);
|
||||
const bytes = normalizeBytes(out);
|
||||
if (!bytes) {
|
||||
throw new Error("OneCAD Simulation odoo bridge: window.onecadsim did not return document bytes");
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private async appInfo(): Promise<{ name?: string }> {
|
||||
const api = onecadsimApi();
|
||||
if (!api || !api.request) return {};
|
||||
try {
|
||||
const info = (await api.request(APP_INFO_METHOD)) as { name?: unknown } | null;
|
||||
return info && typeof info.name === "string" ? { name: info.name } : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Save-as flow: bytes -> explorer (tree + name) -> write -> bind. */
|
||||
async saveAs(options?: {
|
||||
bytes?: Uint8Array | ArrayBuffer;
|
||||
dataB64?: string;
|
||||
name?: string;
|
||||
recordId?: number;
|
||||
}): Promise<SaveAsResult | null> {
|
||||
const opts = options || {};
|
||||
let dataB64 = typeof opts.dataB64 === "string" && opts.dataB64 ? opts.dataB64 : "";
|
||||
if (!dataB64) {
|
||||
const raw = opts.bytes ? (opts.bytes instanceof Uint8Array ? opts.bytes : new Uint8Array(opts.bytes)) : await this.appSerialize();
|
||||
guardCap(raw);
|
||||
dataB64 = bytesToBase64(raw);
|
||||
}
|
||||
const info = await this.appInfo();
|
||||
const suggested = opts.name || info.name || "untitled";
|
||||
const choice = await this.askExplorer({
|
||||
mode: "save",
|
||||
defaultName: ensureExtension(suggested, OWNED_EXTENSION),
|
||||
});
|
||||
if (!choice || !choice.name) return null; // cancelled
|
||||
const name = ensureExtension(choice.name, OWNED_EXTENSION);
|
||||
const result = await this.write({
|
||||
recordId: opts.recordId,
|
||||
name,
|
||||
dataB64,
|
||||
folderId: choice.folderId,
|
||||
});
|
||||
this.bindSet(result.name || name, result.id);
|
||||
return { id: result.id, name: result.name || name, folderId: choice.folderId || null };
|
||||
}
|
||||
|
||||
/** Open flow: explorer (.fieldcraft filter) -> read 300 s. */
|
||||
async openFromDocuments(): Promise<OpenResult | null> {
|
||||
const choice = await this.askExplorer({ mode: "open", extensions: ["fieldcraft", "solidcraft"] });
|
||||
if (!choice || typeof choice.recordId !== "number") return null; // cancelled
|
||||
const opened = await this.readDocument(choice.recordId);
|
||||
return { id: choice.recordId, name: opened.name, dataB64: opened.dataB64 };
|
||||
}
|
||||
|
||||
/** Export flow: bytes -> (optional name dialog) -> saveExport -> Exports. */
|
||||
async exportTo(options?: {
|
||||
bytes?: Uint8Array | ArrayBuffer;
|
||||
dataB64?: string;
|
||||
name?: string;
|
||||
}): Promise<SavedResult | null> {
|
||||
const opts = options || {};
|
||||
let dataB64 = typeof opts.dataB64 === "string" && opts.dataB64 ? opts.dataB64 : "";
|
||||
if (!dataB64) {
|
||||
const raw = opts.bytes ? (opts.bytes instanceof Uint8Array ? opts.bytes : new Uint8Array(opts.bytes)) : await this.appSerialize();
|
||||
guardCap(raw);
|
||||
dataB64 = bytesToBase64(raw);
|
||||
}
|
||||
let name = (opts.name || "").trim();
|
||||
let folderId: number | undefined;
|
||||
if (!name) {
|
||||
const info = await this.appInfo();
|
||||
const choice = await this.askExplorer({
|
||||
mode: "export",
|
||||
defaultName: (info.name || "export") + ".step",
|
||||
});
|
||||
if (!choice || !choice.name) return null; // cancelled
|
||||
name = choice.name;
|
||||
folderId = choice.folderId;
|
||||
}
|
||||
const result = await this.saveExport({ name, dataB64, folderId });
|
||||
return { id: result.id, name: result.name || name };
|
||||
}
|
||||
|
||||
/** Import flow: file picker (or given bytes) -> write into Assets. */
|
||||
async importAsset(options?: {
|
||||
file?: File;
|
||||
bytes?: Uint8Array | ArrayBuffer;
|
||||
dataB64?: string;
|
||||
name?: string;
|
||||
}): Promise<SavedResult | null> {
|
||||
const opts = options || {};
|
||||
let dataB64 = typeof opts.dataB64 === "string" && opts.dataB64 ? opts.dataB64 : "";
|
||||
let name = (opts.name || "").trim();
|
||||
let folderId: number | undefined;
|
||||
if (!dataB64 && !opts.file && !opts.bytes) {
|
||||
const choice = await this.askExplorer({ mode: "asset" });
|
||||
if (!choice || !(choice.file instanceof File)) return null; // cancelled
|
||||
folderId = choice.folderId;
|
||||
const raw = new Uint8Array(await choice.file.arrayBuffer());
|
||||
guardCap(raw);
|
||||
dataB64 = bytesToBase64(raw);
|
||||
name = name || choice.file.name;
|
||||
} else if (!dataB64) {
|
||||
const raw = opts.bytes
|
||||
? opts.bytes instanceof Uint8Array
|
||||
? opts.bytes
|
||||
: new Uint8Array(opts.bytes)
|
||||
: new Uint8Array(await (opts.file as File).arrayBuffer());
|
||||
guardCap(raw);
|
||||
dataB64 = bytesToBase64(raw);
|
||||
name = name || (opts.file ? opts.file.name : "asset");
|
||||
}
|
||||
if (!folderId) {
|
||||
const app = (await this.ping()).app;
|
||||
folderId = app.assets || app.root;
|
||||
}
|
||||
const result = await this.write({ name: name || "asset", dataB64, folderId });
|
||||
return { id: result.id, name: result.name || name || "asset" };
|
||||
}
|
||||
|
||||
/* ---------------- Rust event queue ---------------- */
|
||||
|
||||
private enqueue(entry: QueueEntry): void {
|
||||
this.queue.push(entry);
|
||||
void this.drainQueue();
|
||||
}
|
||||
|
||||
/** Strictly FIFO, one request at a time; every id answered exactly once. */
|
||||
private async drainQueue(): Promise<void> {
|
||||
if (this.draining) return;
|
||||
this.draining = true;
|
||||
while (this.queue.length > 0) {
|
||||
const entry = this.queue.shift() as QueueEntry;
|
||||
try {
|
||||
const result = await this.runRequest(entry.method, entry.payload);
|
||||
this.respond(entry.id, true, result, null);
|
||||
} catch (error) {
|
||||
this.respond(entry.id, false, null, { message: messageOf(error) });
|
||||
}
|
||||
}
|
||||
this.draining = false;
|
||||
}
|
||||
|
||||
private respond(id: number, ok: boolean, result: unknown, error: { message: string } | null): void {
|
||||
const detail: HostResponseDetail = { id, ok, result, error };
|
||||
window.dispatchEvent(new CustomEvent<HostResponseDetail>(EVT_HOST_RESPONSE, { detail }));
|
||||
}
|
||||
|
||||
private async runRequest(method: string, payload: Record<string, unknown>): Promise<unknown> {
|
||||
if (method === "odoo.pickOpen" || method === "odoo.pickProgram") return this.pickForRust(method, payload);
|
||||
if (method === "odoo.pickSave") return this.pickSaveForRust(payload);
|
||||
if (method === "odoo.write") return this.rustWrite(payload);
|
||||
if (method === "odoo.saveExport") return this.rustSaveExport(payload);
|
||||
if (method === "odoo.import") return this.rustImport(payload);
|
||||
if (method === "saveAs") {
|
||||
return this.saveAs({
|
||||
dataB64: typeof payload.dataB64 === "string" ? payload.dataB64 : undefined,
|
||||
name: typeof payload.name === "string" ? payload.name : undefined,
|
||||
recordId: typeof payload.recordId === "number" ? payload.recordId : undefined,
|
||||
bytes: (payload.bytes instanceof Uint8Array ? payload.bytes : undefined) as Uint8Array | undefined,
|
||||
});
|
||||
}
|
||||
if (method === "open") return this.openFromDocuments();
|
||||
if (method === "export") {
|
||||
return this.exportTo({
|
||||
dataB64: typeof payload.dataB64 === "string" ? payload.dataB64 : undefined,
|
||||
name: typeof payload.name === "string" ? payload.name : undefined,
|
||||
bytes: (payload.bytes instanceof Uint8Array ? payload.bytes : undefined) as Uint8Array | undefined,
|
||||
});
|
||||
}
|
||||
if (method === "importAsset") {
|
||||
return this.importAsset({
|
||||
dataB64: typeof payload.dataB64 === "string" ? payload.dataB64 : undefined,
|
||||
name: typeof payload.name === "string" ? payload.name : undefined,
|
||||
bytes: (payload.bytes instanceof Uint8Array ? payload.bytes : undefined) as Uint8Array | undefined,
|
||||
file: payload.file instanceof File ? payload.file : undefined,
|
||||
});
|
||||
}
|
||||
if (HOST_METHODS.has(method)) {
|
||||
const timeoutMs = BULK_METHODS.has(method) ? WRITE_TIMEOUT_MS : undefined;
|
||||
return this.call<unknown>(method, payload, { timeoutMs });
|
||||
}
|
||||
throw new Error("OneCAD Simulation odoo bridge: unknown host-request method \"" + method + "\"");
|
||||
}
|
||||
/* ------- services_odoo.rs wire protocol (CustomEvent round trip) ------- */
|
||||
/** odoo.pickOpen / odoo.pickProgram -> {recordId, name, bytes} | null. */
|
||||
private async pickForRust(method: string, payload: Record<string, unknown>): Promise<unknown> {
|
||||
const requested = Array.isArray(payload.extensions) && payload.extensions.length
|
||||
? (payload.extensions as string[])
|
||||
: null;
|
||||
const extensions = requested || (method === "odoo.pickProgram" ? RUST_ASSET_EXTS : ["fieldcraft", "solidcraft"]);
|
||||
const choice = await this.askExplorer({ mode: "open", extensions });
|
||||
if (!choice || typeof choice.recordId !== "number") return null;
|
||||
const opened = await this.readDocument(choice.recordId);
|
||||
return {
|
||||
recordId: choice.recordId,
|
||||
name: opened.name || choice.recordName || "document",
|
||||
bytes: base64ToBytes(opened.dataB64),
|
||||
};
|
||||
}
|
||||
/** odoo.pickSave -> {token, name}; the token binds the later write-back. */
|
||||
private async pickSaveForRust(payload: Record<string, unknown>): Promise<unknown> {
|
||||
const design = payload.design !== false;
|
||||
const suggested = typeof payload.name === "string" && payload.name.trim() ? payload.name.trim() : "untitled";
|
||||
const choice = await this.askExplorer({
|
||||
mode: "save",
|
||||
defaultName: design ? ensureExtension(suggested, OWNED_EXTENSION) : suggested,
|
||||
});
|
||||
if (!choice || !choice.name) return null;
|
||||
const token = newToken();
|
||||
const name = sanitizeName(choice.name);
|
||||
this.pendingTokens.set(token, { recordId: null, name, folderId: choice.folderId || null });
|
||||
return { token, name };
|
||||
}
|
||||
/** odoo.write: /odoo/doc/<rid>/<name> in place, /odoo/pending/<token>/<name> first save. */
|
||||
private async rustWrite(payload: Record<string, unknown>): Promise<unknown> {
|
||||
const bytes = bytesOf(payload);
|
||||
if (!bytes) throw new Error("odoo.write: no bytes given");
|
||||
guardCap(bytes);
|
||||
const dataB64 = bytesToBase64(bytes);
|
||||
const path = typeof payload.path === "string" ? payload.path : "";
|
||||
if (path.startsWith("/odoo/pending/")) {
|
||||
const rest = path.slice("/odoo/pending/".length);
|
||||
const slash = rest.indexOf("/");
|
||||
const token = slash > 0 ? rest.slice(0, slash) : "";
|
||||
const pathName = slash > 0 ? sanitizeName(rest.slice(slash + 1)) : "document";
|
||||
const bind = token ? this.pendingTokens.get(token) : undefined;
|
||||
const name = (bind ? bind.name : "") || pathName;
|
||||
let recordId = bind ? bind.recordId : null;
|
||||
if (!recordId) {
|
||||
const remembered = this.bindLookup(name);
|
||||
recordId = remembered ? remembered.recordId : null;
|
||||
}
|
||||
const result = await this.write({ recordId, name, dataB64, folderId: bind ? bind.folderId : undefined });
|
||||
if (bind) bind.recordId = result.id;
|
||||
else if (token) this.pendingTokens.set(token, { recordId: result.id, name, folderId: null });
|
||||
this.bindSet(result.name || name, result.id);
|
||||
return { id: result.id, name: result.name || name };
|
||||
}
|
||||
if (path.startsWith("/odoo/doc/")) {
|
||||
const rest = path.slice("/odoo/doc/".length);
|
||||
const slash = rest.indexOf("/");
|
||||
const recordId = slash > 0 ? Number(rest.slice(0, slash)) : 0;
|
||||
const name = slash > 0 ? sanitizeName(rest.slice(slash + 1)) : "document";
|
||||
if (!Number.isInteger(recordId) || recordId <= 0) {
|
||||
throw new Error("odoo.write: bad record path \"" + path + "\"");
|
||||
}
|
||||
const result = await this.write({ recordId, name, dataB64 });
|
||||
this.bindSet(result.name || name, recordId);
|
||||
return { id: result.id, name: result.name || name };
|
||||
}
|
||||
throw new Error("odoo.write: unsupported path \"" + path + "\"");
|
||||
}
|
||||
/** odoo.saveExport: {name, bytes} -> Documents "Exports" folder. */
|
||||
private async rustSaveExport(payload: Record<string, unknown>): Promise<unknown> {
|
||||
const bytes = bytesOf(payload);
|
||||
if (!bytes) throw new Error("odoo.saveExport: no bytes given");
|
||||
guardCap(bytes);
|
||||
const result = await this.saveExport({ name: sanitizeName(payload.name) || "export", dataB64: bytesToBase64(bytes) });
|
||||
return { id: result.id, name: result.name };
|
||||
}
|
||||
/** odoo.import: mirror a computer import into the Documents "Assets" folder. */
|
||||
private async rustImport(payload: Record<string, unknown>): Promise<unknown> {
|
||||
const bytes = bytesOf(payload);
|
||||
if (!bytes) throw new Error("odoo.import: no bytes given");
|
||||
guardCap(bytes);
|
||||
const app = (await this.ping()).app;
|
||||
const result = await this.write({ name: payload.name || "asset", dataB64: bytesToBase64(bytes), folderId: app.assets || app.root });
|
||||
return { id: result.id, name: result.name };
|
||||
}
|
||||
}
|
||||
|
||||
/** The process-wide singleton (one bridge per app window). */
|
||||
export const bridge = new OneCadBridge();
|
||||
|
||||
/** Family export: the app glue and dialogs always share this instance. */
|
||||
export function exportForHost(): OneCadBridge {
|
||||
return bridge;
|
||||
}
|
||||
@@ -1,719 +0,0 @@
|
||||
// (C) OneBSpace — https://1bspace.com — a 1B Global company. Proprietary.
|
||||
// OneCAD Simulation Odoo Documents glue (ported from OneCAD).
|
||||
/**
|
||||
* OneCAD Simulation odoo/explorer.js — the unified Documents explorer dialogs.
|
||||
* ----------------------------------------------------------------------
|
||||
* Vanilla-JS (ES module, zero deps) port of the family gold-standard
|
||||
* explorer (one-photo src/odoo-host/explorer.js — same layout, same
|
||||
* interactions, same last-folder memory), restyled with an injected dark
|
||||
* CAD palette (no CSS imports — one <style> tag) so it reads native over
|
||||
* the egui canvas. Four dialogs, one explorer:
|
||||
*
|
||||
* save — "Save to Documents": folder tree + name input (.fieldcraft chip)
|
||||
* open — "Open from Documents": folder tree + files filtered to .fieldcraft
|
||||
* asset — "Import asset": file picker -> Assets folder (+ retarget)
|
||||
* export — "Export": name input -> Exports folder
|
||||
*
|
||||
* left — My Drive folder tree (recursive, expandable, usage footer)
|
||||
* right — breadcrumb + folder/file rows (icon, name, size)
|
||||
* footer — Cancel left, primary action right, Esc / backdrop cancels
|
||||
*
|
||||
* Everything runs through the bridge (odoo/bridge.js — compiled from
|
||||
* bridge.ts): listFolder / createFolder / folders / usage. No framework.
|
||||
*
|
||||
* @returns per mode (resolve value, null = cancelled):
|
||||
* save -> {name, folderId}
|
||||
* open -> {recordId, recordName}
|
||||
* asset -> {file, folderId, name}
|
||||
* export -> {name, folderId}
|
||||
*/
|
||||
import { bridge } from "./bridge.js?v=20.0.1.0.0";
|
||||
|
||||
const STYLE_ID = "ocs-explorer-style";
|
||||
|
||||
const MODES = {
|
||||
save: {
|
||||
heading: "Save to Documents",
|
||||
description: "Choose a folder in your Odoo drive for this .fieldcraft document.",
|
||||
action: "Save",
|
||||
prefer: "root",
|
||||
lastKey: "one-cad-sim:documents:last-folder:save",
|
||||
},
|
||||
open: {
|
||||
heading: "Open from Documents",
|
||||
description: "Browse your Odoo Documents drive and pick a .fieldcraft document.",
|
||||
action: "Open",
|
||||
prefer: "root",
|
||||
lastKey: "one-cad-sim:documents:last-folder:open",
|
||||
extensions: new Set(["fieldcraft", "solidcraft"]),
|
||||
},
|
||||
asset: {
|
||||
heading: "Import asset",
|
||||
description: "Pick a CAD asset from your computer to copy into the Assets folder.",
|
||||
action: "Import",
|
||||
prefer: "assets",
|
||||
lastKey: "one-cad-sim:documents:last-folder:asset",
|
||||
extensions: new Set([
|
||||
"step", "stp", "iges", "igs", "brep", "stl", "obj", "3mf",
|
||||
"dxf", "svg", "gltf", "glb", "ply", "urdf",
|
||||
]),
|
||||
},
|
||||
export: {
|
||||
heading: "Export",
|
||||
description: "Name the export — it lands in your Documents Exports folder.",
|
||||
action: "Export",
|
||||
prefer: "exports",
|
||||
lastKey: "one-cad-sim:documents:last-folder:export",
|
||||
},
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Small SVG icon set (lucide-style, stroke = currentColor) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
function svg(paths, size) {
|
||||
return (
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
|
||||
'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" ' +
|
||||
'style="width:' + (size || 16) + 'px;height:' + (size || 16) + 'px;flex:none">' +
|
||||
paths + "</svg>"
|
||||
);
|
||||
}
|
||||
|
||||
const ICONS = {
|
||||
folder: svg('<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>'),
|
||||
lock: svg('<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>', 11),
|
||||
chevronRight: svg('<path d="m9 18 6-6-6-6"/>', 12),
|
||||
hardDrive: svg('<line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/>'),
|
||||
file: svg('<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>'),
|
||||
cube: svg('<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/>'),
|
||||
save: svg('<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 1-1 1H7"/>'),
|
||||
folderPlus: svg('<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/><path d="M12 10v6"/><path d="M9 13h6"/>'),
|
||||
upload: svg('<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/>'),
|
||||
open: svg('<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/><path d="m2 21 5.1-5.1a2 2 0 0 1 2.8 0l1.1 1.1a2 2 0 0 0 2.8 0l4.2-4.2a2 2 0 0 1 2.8 0L22 14"/>'),
|
||||
download: svg('<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>'),
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Injected dark CAD styles (the only CSS this module ever adds) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
const STYLE_CSS = [
|
||||
":root{--ocs-bg:#1b1e24;--ocs-panel:#23272f;--ocs-panel2:#2a2f39;--ocs-hairline:#333945;",
|
||||
"--ocs-text:#e8eaed;--ocs-dim:#9aa3ad;--ocs-accent:#4f8cff;--ocs-accent-press:#3f76e0;",
|
||||
"--ocs-danger:#e5534b;--ocs-ok:#3fb26f}",
|
||||
".ocs-explorer-root{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;",
|
||||
"font:13px/1.45 'Segoe UI',system-ui,-apple-system,sans-serif;color:var(--ocs-text)}",
|
||||
".ocs-backdrop{position:absolute;inset:0;background:rgba(8,10,14,.62)}",
|
||||
".ocs-dialog{position:relative;width:min(860px,calc(100vw - 48px));height:min(560px,calc(100vh - 64px));",
|
||||
"background:var(--ocs-bg);border:1px solid var(--ocs-hairline);border-radius:10px;",
|
||||
"box-shadow:0 24px 64px rgba(0,0,0,.55);display:flex;flex-direction:column;overflow:hidden}",
|
||||
".ocs-header{padding:14px 18px 10px;border-bottom:1px solid var(--ocs-hairline);background:var(--ocs-panel)}",
|
||||
".ocs-title{font-size:15px;font-weight:600}",
|
||||
".ocs-desc{margin-top:2px;color:var(--ocs-dim);font-size:12px}",
|
||||
".ocs-desc-error{color:var(--ocs-danger)}",
|
||||
".ocs-body{flex:1;display:flex;min-height:0}",
|
||||
".ocs-aside{width:250px;flex:none;display:flex;flex-direction:column;border-right:1px solid var(--ocs-hairline);background:var(--ocs-panel)}",
|
||||
".ocs-tree-box{flex:1;overflow:auto;padding:8px 6px}",
|
||||
".ocs-tree-label{margin:2px 8px 6px;color:var(--ocs-dim);font-size:11px;text-transform:uppercase;letter-spacing:.06em}",
|
||||
".ocs-tree-error{padding:8px}",
|
||||
".ocs-tree-row{display:flex;align-items:center;gap:6px;padding:5px 8px;border-radius:6px;cursor:pointer;white-space:nowrap}",
|
||||
".ocs-tree-row:hover{background:var(--ocs-panel2)}",
|
||||
".ocs-tree-row.ocs-active{background:var(--ocs-panel2);color:#fff}",
|
||||
".ocs-tree-toggle{width:14px;height:14px;flex:none;color:var(--ocs-dim);display:inline-flex;transition:transform .12s}",
|
||||
".ocs-tree-toggle.ocs-open{transform:rotate(90deg)}",
|
||||
".ocs-tree-icon{display:inline-flex;color:var(--ocs-accent)}",
|
||||
".ocs-tree-name{overflow:hidden;text-overflow:ellipsis}",
|
||||
".ocs-usage{padding:8px 14px;border-top:1px solid var(--ocs-hairline);color:var(--ocs-dim);font-size:11px}",
|
||||
".ocs-main{flex:1;display:flex;flex-direction:column;min-width:0}",
|
||||
".ocs-crumbs{display:flex;align-items:center;gap:2px;padding:8px 12px;border-bottom:1px solid var(--ocs-hairline);overflow:hidden}",
|
||||
".ocs-crumb{display:inline-flex;align-items:center;gap:5px;background:none;border:0;color:var(--ocs-dim);",
|
||||
"font:inherit;padding:4px 7px;border-radius:6px;cursor:pointer}",
|
||||
".ocs-crumb:hover:not(:disabled){background:var(--ocs-panel2);color:var(--ocs-text)}",
|
||||
".ocs-crumb:disabled{opacity:.45;cursor:default}",
|
||||
".ocs-crumb-current{color:var(--ocs-text)}",
|
||||
".ocs-crumb-sep{display:inline-flex;color:var(--ocs-dim)}",
|
||||
".ocs-files{flex:1;overflow:auto;padding:6px 8px}",
|
||||
".ocs-file-row{display:flex;align-items:center;gap:10px;width:100%;text-align:left;background:none;border:0;",
|
||||
"color:inherit;font:inherit;padding:7px 9px;border-radius:6px;cursor:pointer}",
|
||||
".ocs-file-row:hover{background:var(--ocs-panel2)}",
|
||||
".ocs-file-row.ocs-selected{background:rgba(79,140,255,.18);outline:1px solid var(--ocs-accent)}",
|
||||
".ocs-file-icon{display:inline-flex;color:var(--ocs-dim)}",
|
||||
".ocs-file-icon.ocs-icon-owned{color:var(--ocs-accent)}",
|
||||
".ocs-file-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
|
||||
".ocs-file-size{color:var(--ocs-dim);font-size:11px;flex:none}",
|
||||
".ocs-empty{color:var(--ocs-dim);padding:18px 10px;text-align:center}",
|
||||
".ocs-savebar{border-top:1px solid var(--ocs-hairline);padding:10px 14px;background:var(--ocs-panel)}",
|
||||
".ocs-name-row{display:flex;align-items:flex-end;gap:10px}",
|
||||
".ocs-name-wrap{flex:1;min-width:0}",
|
||||
".ocs-name-label{display:block;color:var(--ocs-dim);font-size:11px;margin-bottom:4px}",
|
||||
".ocs-name-field{display:flex;align-items:center;background:var(--ocs-bg);border:1px solid var(--ocs-hairline);border-radius:6px;padding:0 8px}",
|
||||
".ocs-name-field:focus-within{border-color:var(--ocs-accent)}",
|
||||
".ocs-name-input{flex:1;min-width:0;background:none;border:0;outline:0;color:var(--ocs-text);font:inherit;padding:7px 0}",
|
||||
".ocs-suffix{color:var(--ocs-dim);font-size:12px;user-select:none}",
|
||||
".ocs-create-row{display:flex;gap:8px;margin-top:8px}",
|
||||
".ocs-newfolder-input{flex:1;background:var(--ocs-bg);border:1px solid var(--ocs-hairline);border-radius:6px;",
|
||||
"color:var(--ocs-text);font:inherit;padding:6px 9px;outline:0}",
|
||||
".ocs-newfolder-input:focus{border-color:var(--ocs-accent)}",
|
||||
".ocs-picker{display:flex;flex-direction:column;gap:8px}",
|
||||
".ocs-pick-btn{display:inline-flex;align-items:center;gap:8px}",
|
||||
".ocs-picked{color:var(--ocs-dim);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
|
||||
".ocs-footer{display:flex;justify-content:space-between;align-items:center;padding:10px 14px;",
|
||||
"border-top:1px solid var(--ocs-hairline);background:var(--ocs-panel)}",
|
||||
".ocs-btn{display:inline-flex;align-items:center;gap:6px;font:inherit;padding:7px 14px;border-radius:6px;",
|
||||
"border:1px solid var(--ocs-hairline);background:var(--ocs-panel2);color:var(--ocs-text);cursor:pointer}",
|
||||
".ocs-btn:hover:not(:disabled){border-color:var(--ocs-dim)}",
|
||||
".ocs-btn:disabled{opacity:.45;cursor:default}",
|
||||
".ocs-btn-accent{background:var(--ocs-accent);border-color:var(--ocs-accent);color:#fff}",
|
||||
".ocs-btn-accent:hover:not(:disabled){background:var(--ocs-accent-press)}",
|
||||
".ocs-btn-ghost{background:none;border-color:transparent;color:var(--ocs-dim)}",
|
||||
".ocs-btn-ghost:hover:not(:disabled){color:var(--ocs-text)}",
|
||||
".ocs-btn-icon{display:inline-flex}",
|
||||
].join("\n");
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = STYLE_CSS;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
function h(tag, attrs) {
|
||||
const el = document.createElement(tag);
|
||||
if (attrs) {
|
||||
for (const key in attrs) {
|
||||
if (!Object.prototype.hasOwnProperty.call(attrs, key)) continue;
|
||||
const value = attrs[key];
|
||||
if (key === "class") el.className = value;
|
||||
else if (key === "html") el.innerHTML = value;
|
||||
else if (key === "text") el.textContent = value;
|
||||
else if (key.slice(0, 2) === "on" && typeof value === "function")
|
||||
el.addEventListener(key.slice(2), value);
|
||||
else if (value !== null && value !== undefined) el.setAttribute(key, value);
|
||||
}
|
||||
}
|
||||
for (let i = 2; i < arguments.length; i++) {
|
||||
const child = arguments[i];
|
||||
if (child === null || child === undefined) continue;
|
||||
el.appendChild(typeof child === "string" ? document.createTextNode(child) : child);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
function formatSize(size) {
|
||||
size = Number(size) || 0;
|
||||
if (size < 1024) return size + " B";
|
||||
if (size < 1024 * 1024) return (size / 1024).toFixed(1) + " KB";
|
||||
if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + " MB";
|
||||
return (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
|
||||
}
|
||||
|
||||
function extensionOf(name) {
|
||||
const dot = name.lastIndexOf(".");
|
||||
return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
function fileIconFor(file, extensions) {
|
||||
const ext = extensionOf(file.name || "");
|
||||
if (extensions && extensions.has(ext)) {
|
||||
return '<span class="ocs-file-icon ocs-icon-owned">' + ICONS.cube + "</span>";
|
||||
}
|
||||
return '<span class="ocs-file-icon">' + ICONS.file + "</span>";
|
||||
}
|
||||
|
||||
function rememberLastFolder(folderId, key) {
|
||||
try {
|
||||
window.localStorage.setItem(key, String(folderId));
|
||||
} catch (e) {
|
||||
/* private mode — memory only */
|
||||
}
|
||||
}
|
||||
|
||||
function restoreLastFolder(key) {
|
||||
try {
|
||||
const id = Number(window.localStorage.getItem(key));
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* The explorer */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Open one Documents explorer dialog.
|
||||
*
|
||||
* @param {object} opts
|
||||
* mode "save" | "open" | "asset" | "export"
|
||||
* defaultName save/export mode: suggested file name ("part.fieldcraft")
|
||||
* extensions open/asset mode: restrict file rows to these extensions
|
||||
* @returns {Promise<{name?, folderId?, recordId?, recordName?, file?} | null>}
|
||||
* null = cancelled (Esc, backdrop, Cancel button).
|
||||
*/
|
||||
export function openDocumentsExplorer(opts) {
|
||||
opts = opts || {};
|
||||
const mode = MODES[opts.mode] ? opts.mode : "save";
|
||||
const config = MODES[mode];
|
||||
const extensions = opts.extensions && opts.extensions.length
|
||||
? new Set(opts.extensions.map((ext) => String(ext).toLowerCase().replace(/^\./, "")))
|
||||
: config.extensions || null;
|
||||
|
||||
/* Standalone dev mode: no host, no dialog — the caller treats null as
|
||||
* "nothing chosen", so the app keeps running untouched. */
|
||||
if (typeof bridge.isHostAvailable === "function" && !bridge.isHostAvailable()) {
|
||||
console.info("[onecadsim-odoo] explorer: no Odoo host (standalone) — dialog unavailable");
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
ensureStyle();
|
||||
|
||||
/* Save/export name split: stem in the field, extension as the chip. */
|
||||
const wantsName = mode === "save" || mode === "export";
|
||||
const defaultExtension = mode === "save" ? ".fieldcraft" : "";
|
||||
let defaultName = typeof opts.defaultName === "string" && opts.defaultName.trim() !== ""
|
||||
? opts.defaultName.trim()
|
||||
: mode === "save"
|
||||
? "untitled.fieldcraft"
|
||||
: "export";
|
||||
let stem = defaultName;
|
||||
let suffix = "";
|
||||
const dotIdx = defaultName.lastIndexOf(".");
|
||||
if (dotIdx > 0) {
|
||||
stem = defaultName.slice(0, dotIdx);
|
||||
suffix = defaultName.slice(dotIdx);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const settle = (result) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
document.removeEventListener("keydown", onDocKeyDown, true);
|
||||
if (root && root.parentNode) root.parentNode.removeChild(root);
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
/* ---------------- state ---------------- */
|
||||
let tree = null;
|
||||
let treeError = null;
|
||||
let appTree = {};
|
||||
let appRootId = null;
|
||||
let currentFolderId = null;
|
||||
let folderFolders = [];
|
||||
let folderFiles = [];
|
||||
let loadingFiles = false;
|
||||
let selectedFileId = null;
|
||||
let pickedFile = null;
|
||||
let createBusy = false;
|
||||
let usage = null;
|
||||
const expandedSet = new Set();
|
||||
|
||||
/* ---------------- chrome ---------------- */
|
||||
const backdrop = h("div", { class: "ocs-backdrop" });
|
||||
const dialog = h("div", { class: "ocs-dialog", role: "dialog", "aria-modal": "true" });
|
||||
const root = h("div", { class: "ocs-explorer-root" }, backdrop, dialog);
|
||||
|
||||
const descEl = h("div", { class: "ocs-desc" }, config.description);
|
||||
const header = h("div", { class: "ocs-header" },
|
||||
h("div", { class: "ocs-title" }, config.heading), descEl);
|
||||
|
||||
const treeLabel = h("p", { class: "ocs-tree-label" }, "Loading drive…");
|
||||
const treeBox = h("div", { class: "ocs-tree-box" }, treeLabel);
|
||||
const usageEl = h("div", { class: "ocs-usage", style: "display:none" });
|
||||
const aside = h("div", { class: "ocs-aside" }, treeBox, usageEl);
|
||||
|
||||
const crumbs = h("div", { class: "ocs-crumbs" });
|
||||
const fileList = h("div", { class: "ocs-files" });
|
||||
const main = h("div", { class: "ocs-main" }, crumbs, fileList);
|
||||
const body = h("div", { class: "ocs-body" }, aside, main);
|
||||
|
||||
/* name row (save + export) */
|
||||
const nameInput = h("input", {
|
||||
class: "ocs-name-input",
|
||||
id: "onecadsim-explorer-name",
|
||||
type: "text",
|
||||
value: stem,
|
||||
placeholder: mode === "save" ? "Untitled" : "export",
|
||||
spellcheck: "false",
|
||||
});
|
||||
const suffixChip = h("span", { class: "ocs-suffix" }, suffix);
|
||||
const nameField = h("div", { class: "ocs-name-field" }, nameInput, suffixChip);
|
||||
const nameRow = h("div", { class: "ocs-name-row" },
|
||||
h("div", { class: "ocs-name-wrap" },
|
||||
h("label", { class: "ocs-name-label", for: "onecadsim-explorer-name" }, "File name"),
|
||||
nameField));
|
||||
|
||||
/* new-folder row (save + export; asset keeps it too — retargeting) */
|
||||
const newNameInput = h("input", {
|
||||
class: "ocs-newfolder-input",
|
||||
type: "text",
|
||||
placeholder: "Folder name…",
|
||||
spellcheck: "false",
|
||||
});
|
||||
const createBtn = h("button", { class: "ocs-btn ocs-btn-accent", type: "button" }, "Create");
|
||||
const cancelCreateBtn = h("button", { class: "ocs-btn ocs-btn-ghost", type: "button" }, "Cancel");
|
||||
const createRow = h("div", { class: "ocs-create-row", style: "display:none" }, newNameInput, createBtn, cancelCreateBtn);
|
||||
const newFolderBtn = h("button", { class: "ocs-btn", type: "button" },
|
||||
h("span", { class: "ocs-btn-icon", html: ICONS.folderPlus }), "New folder");
|
||||
|
||||
/* asset file picker */
|
||||
const fileInput = h("input", {
|
||||
type: "file",
|
||||
style: "display:none",
|
||||
...(extensions ? { accept: Array.from(extensions).map((ext) => "." + ext).join(",") } : {}),
|
||||
});
|
||||
const pickedLabel = h("div", { class: "ocs-picked", text: "No file chosen yet." });
|
||||
const pickBtn = h("button", { class: "ocs-btn ocs-btn-accent", type: "button" },
|
||||
h("span", { class: "ocs-btn-icon", html: ICONS.upload }), "Choose file…");
|
||||
const picker = h("div", { class: "ocs-picker" }, pickBtn, pickedLabel, fileInput);
|
||||
|
||||
const savebar = h("div", { class: "ocs-savebar" });
|
||||
if (wantsName) savebar.appendChild(nameRow);
|
||||
if (mode === "asset") savebar.appendChild(picker);
|
||||
savebar.appendChild(newFolderBtn);
|
||||
savebar.appendChild(createRow);
|
||||
|
||||
/* footer */
|
||||
const cancelBtn = h("button", { class: "ocs-btn ocs-btn-ghost", type: "button" }, "Cancel");
|
||||
const actionIcon = mode === "save" ? ICONS.save : mode === "open" ? ICONS.open : mode === "asset" ? ICONS.upload : ICONS.download;
|
||||
const actionBtn = h("button", { class: "ocs-btn ocs-btn-accent", type: "button" },
|
||||
h("span", { class: "ocs-btn-icon", html: actionIcon }), config.action);
|
||||
const footer = h("div", { class: "ocs-footer" }, cancelBtn, actionBtn);
|
||||
|
||||
dialog.appendChild(header);
|
||||
dialog.appendChild(body);
|
||||
if (mode !== "open") dialog.appendChild(savebar);
|
||||
dialog.appendChild(footer);
|
||||
|
||||
const redraw = () => {
|
||||
if (mode === "save") {
|
||||
actionBtn.disabled = !nameInput.value.trim() || currentFolderId === null;
|
||||
} else if (mode === "open") {
|
||||
actionBtn.disabled = selectedFileId === null;
|
||||
} else if (mode === "asset") {
|
||||
actionBtn.disabled = !pickedFile || currentFolderId === null;
|
||||
} else {
|
||||
actionBtn.disabled = !nameInput.value.trim() || currentFolderId === null;
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------------- tree rendering ---------------- */
|
||||
function renderTree() {
|
||||
treeBox.innerHTML = "";
|
||||
if (tree === null && !treeError) {
|
||||
treeBox.appendChild(h("p", { class: "ocs-tree-label" }, "Loading drive…"));
|
||||
return;
|
||||
}
|
||||
if (treeError) {
|
||||
const retry = h("button", { class: "ocs-btn", type: "button" }, "Retry");
|
||||
retry.addEventListener("click", () => boot());
|
||||
treeBox.appendChild(h("div", { class: "ocs-tree-error" },
|
||||
h("p", { class: "ocs-tree-label" }, treeError), retry));
|
||||
return;
|
||||
}
|
||||
treeBox.appendChild(h("p", { class: "ocs-tree-label" }, "My Drive"));
|
||||
const childrenOf = new Map();
|
||||
for (const folder of tree) {
|
||||
const key = folder.parentId === null ? "root" : String(folder.parentId);
|
||||
if (!childrenOf.has(key)) childrenOf.set(key, []);
|
||||
childrenOf.get(key).push(folder);
|
||||
}
|
||||
const renderNodes = (parentId, depth) => {
|
||||
const key = parentId === null ? "root" : String(parentId);
|
||||
const children = childrenOf.get(key) || [];
|
||||
for (const folder of children) {
|
||||
const hasChildren = (childrenOf.get(String(folder.id)) || []).length > 0;
|
||||
const isOpen = expandedSet.has(folder.id);
|
||||
const row = h("div", {
|
||||
class: "ocs-tree-row" + (folder.id === currentFolderId ? " ocs-active" : ""),
|
||||
style: "padding-left:" + (8 + depth * 14) + "px",
|
||||
});
|
||||
const toggle = h("span", { class: "ocs-tree-toggle" });
|
||||
if (hasChildren) {
|
||||
toggle.innerHTML = ICONS.chevronRight;
|
||||
toggle.classList.add("ocs-has-children");
|
||||
if (isOpen) toggle.classList.add("ocs-open");
|
||||
}
|
||||
toggle.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
if (expandedSet.has(folder.id)) expandedSet.delete(folder.id);
|
||||
else expandedSet.add(folder.id);
|
||||
renderTree();
|
||||
});
|
||||
row.appendChild(toggle);
|
||||
row.appendChild(h("span", { class: "ocs-tree-icon", html: ICONS.folder }));
|
||||
row.appendChild(h("span", { class: "ocs-tree-name" }, folder.name));
|
||||
row.addEventListener("click", () => enterFolder(folder.id));
|
||||
treeBox.appendChild(row);
|
||||
if (hasChildren && isOpen) renderNodes(folder.id, depth + 1);
|
||||
}
|
||||
};
|
||||
renderNodes(null, 0);
|
||||
usageEl.style.display = usage ? "" : "none";
|
||||
if (usage) {
|
||||
usageEl.textContent = usage.documentCount + " file" + (usage.documentCount === 1 ? "" : "s") +
|
||||
" · " + formatSize(usage.bytesUsed) + " used";
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- breadcrumb ---------------- */
|
||||
function renderCrumbs() {
|
||||
crumbs.innerHTML = "";
|
||||
const driveBtn = h("button", { class: "ocs-crumb ocs-crumb-root", type: "button" });
|
||||
driveBtn.appendChild(h("span", { class: "ocs-btn-icon", html: ICONS.hardDrive }));
|
||||
driveBtn.appendChild(document.createTextNode("My Drive"));
|
||||
driveBtn.disabled = appRootId === null;
|
||||
driveBtn.addEventListener("click", () => appRootId !== null && enterFolder(appRootId));
|
||||
crumbs.appendChild(driveBtn);
|
||||
const path = [];
|
||||
let cursor = currentFolderId;
|
||||
const byId = new Map(tree ? tree.map((row) => [row.id, row]) : []);
|
||||
while (cursor !== null && byId.has(cursor)) {
|
||||
path.unshift(byId.get(cursor));
|
||||
cursor = byId.get(cursor).parentId;
|
||||
}
|
||||
for (const folder of path) {
|
||||
crumbs.appendChild(h("span", { class: "ocs-crumb-sep", html: ICONS.chevronRight }));
|
||||
const crumb = h("button", {
|
||||
class: "ocs-crumb" + (folder.id === currentFolderId ? " ocs-crumb-current" : ""),
|
||||
type: "button",
|
||||
}, folder.name);
|
||||
crumb.addEventListener("click", () => enterFolder(folder.id));
|
||||
crumbs.appendChild(crumb);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- files ---------------- */
|
||||
function renderFiles() {
|
||||
fileList.innerHTML = "";
|
||||
if (loadingFiles) {
|
||||
fileList.appendChild(h("p", { class: "ocs-empty" }, "Loading…"));
|
||||
return;
|
||||
}
|
||||
/* Desktop file-manager behavior: subfolders first (click = enter),
|
||||
* then files — open mode filtered to the requested extensions. */
|
||||
for (const folder of folderFolders) {
|
||||
const row = h("button", { class: "ocs-file-row", type: "button" });
|
||||
row.insertAdjacentHTML("beforeend", '<span class="ocs-file-icon ocs-icon-owned">' + ICONS.folder + "</span>");
|
||||
row.appendChild(h("span", { class: "ocs-file-name" }, folder.name));
|
||||
if (folder.system) {
|
||||
row.insertAdjacentHTML("beforeend",
|
||||
'<span class="ocs-file-size" title="Protected OneBSpace folder">' + ICONS.lock + "</span>");
|
||||
}
|
||||
row.appendChild(h("span", { class: "ocs-file-size" }, "Folder"));
|
||||
row.addEventListener("click", () => enterFolder(folder.id));
|
||||
fileList.appendChild(row);
|
||||
}
|
||||
const visibleFiles = extensions
|
||||
? folderFiles.filter((file) => extensions.has(extensionOf(file.name || "")))
|
||||
: folderFiles;
|
||||
if (folderFolders.length === 0 && visibleFiles.length === 0) {
|
||||
fileList.appendChild(h("p", { class: "ocs-empty" },
|
||||
mode === "save" || mode === "export" ? "This folder is empty." : "No compatible files in this folder."));
|
||||
return;
|
||||
}
|
||||
if (visibleFiles.length === 0) {
|
||||
fileList.appendChild(h("p", { class: "ocs-empty" }, "No compatible files here yet."));
|
||||
return;
|
||||
}
|
||||
for (const file of visibleFiles) {
|
||||
const row = h("button", {
|
||||
class: "ocs-file-row" + (selectedFileId === file.id ? " ocs-selected" : ""),
|
||||
type: "button",
|
||||
});
|
||||
row.insertAdjacentHTML("beforeend", fileIconFor(file, extensions));
|
||||
row.appendChild(h("span", { class: "ocs-file-name" }, file.name));
|
||||
row.appendChild(h("span", { class: "ocs-file-size" }, formatSize(file.size || 0)));
|
||||
row.addEventListener("click", () => {
|
||||
selectedFileId = file.id;
|
||||
renderFiles();
|
||||
redraw();
|
||||
});
|
||||
row.addEventListener("dblclick", () => {
|
||||
if (mode === "open") settle({ recordId: file.id, recordName: file.name });
|
||||
});
|
||||
fileList.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- actions ---------------- */
|
||||
function enterFolder(folderId) {
|
||||
currentFolderId = folderId;
|
||||
selectedFileId = null;
|
||||
rememberLastFolder(folderId, config.lastKey);
|
||||
loadFiles(folderId);
|
||||
renderTree();
|
||||
renderCrumbs();
|
||||
redraw();
|
||||
}
|
||||
|
||||
function loadFiles(folderId) {
|
||||
loadingFiles = true;
|
||||
renderFiles();
|
||||
bridge
|
||||
.listFolder(folderId)
|
||||
.then((listing) => {
|
||||
folderFiles = listing.files || [];
|
||||
folderFolders = listing.folders || [];
|
||||
loadingFiles = false;
|
||||
renderFiles();
|
||||
})
|
||||
.catch((error) => {
|
||||
folderFiles = [];
|
||||
folderFolders = [];
|
||||
loadingFiles = false;
|
||||
renderFiles();
|
||||
flashError("Could not list this folder — " + (error && error.message ? error.message : "unknown error"));
|
||||
});
|
||||
}
|
||||
|
||||
function onCreateFolder() {
|
||||
const trimmed = newNameInput.value.trim();
|
||||
if (!trimmed || currentFolderId === null || createBusy) return;
|
||||
createBusy = true;
|
||||
createBtn.disabled = true;
|
||||
bridge
|
||||
.createFolder({ name: trimmed, parentId: currentFolderId })
|
||||
.then((created) => {
|
||||
tree = (tree || []).concat([{ id: created.id, name: trimmed, parentId: currentFolderId }]);
|
||||
expandedSet.add(currentFolderId);
|
||||
expandedSet.add(created.id);
|
||||
newNameInput.value = "";
|
||||
createRow.style.display = "none";
|
||||
newFolderBtn.style.display = "";
|
||||
enterFolder(created.id);
|
||||
})
|
||||
.catch((error) => {
|
||||
flashError("Could not create folder — " + (error && error.message ? error.message : "unknown error"));
|
||||
})
|
||||
.finally(() => {
|
||||
createBusy = false;
|
||||
createBtn.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
function confirmAction() {
|
||||
if (mode === "save") {
|
||||
const name = nameInput.value.trim();
|
||||
if (!name || currentFolderId === null) return;
|
||||
settle({ name, folderId: currentFolderId });
|
||||
} else if (mode === "open") {
|
||||
const file = folderFiles.find((candidate) => candidate.id === selectedFileId);
|
||||
if (file) settle({ recordId: file.id, recordName: file.name });
|
||||
} else if (mode === "asset") {
|
||||
if (pickedFile && currentFolderId !== null) {
|
||||
settle({ file: pickedFile, folderId: currentFolderId, name: pickedFile.name });
|
||||
}
|
||||
} else {
|
||||
const name = nameInput.value.trim();
|
||||
if (!name || currentFolderId === null) return;
|
||||
settle({ name, folderId: currentFolderId });
|
||||
}
|
||||
}
|
||||
|
||||
pickBtn.addEventListener("click", () => fileInput.click());
|
||||
fileInput.addEventListener("change", () => {
|
||||
pickedFile = fileInput.files && fileInput.files[0] ? fileInput.files[0] : null;
|
||||
pickedLabel.textContent = pickedFile
|
||||
? pickedFile.name + " · " + formatSize(pickedFile.size)
|
||||
: "No file chosen yet.";
|
||||
redraw();
|
||||
});
|
||||
|
||||
newFolderBtn.addEventListener("click", () => {
|
||||
newFolderBtn.style.display = "none";
|
||||
createRow.style.display = "";
|
||||
newNameInput.focus();
|
||||
});
|
||||
cancelCreateBtn.addEventListener("click", () => {
|
||||
newNameInput.value = "";
|
||||
createRow.style.display = "none";
|
||||
newFolderBtn.style.display = "";
|
||||
});
|
||||
createBtn.addEventListener("click", onCreateFolder);
|
||||
newNameInput.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter") onCreateFolder();
|
||||
});
|
||||
nameInput.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter") confirmAction();
|
||||
});
|
||||
nameInput.addEventListener("input", redraw);
|
||||
cancelBtn.addEventListener("click", () => settle(null));
|
||||
actionBtn.addEventListener("click", confirmAction);
|
||||
backdrop.addEventListener("mousedown", () => settle(null));
|
||||
dialog.addEventListener("mousedown", (ev) => ev.stopPropagation());
|
||||
|
||||
function onDocKeyDown(ev) {
|
||||
if (ev.key !== "Escape") return;
|
||||
ev.stopPropagation();
|
||||
settle(null);
|
||||
}
|
||||
document.addEventListener("keydown", onDocKeyDown, true);
|
||||
|
||||
let errorTimer = null;
|
||||
function flashError(message) {
|
||||
descEl.textContent = message;
|
||||
descEl.classList.add("ocs-desc-error");
|
||||
if (errorTimer) clearTimeout(errorTimer);
|
||||
errorTimer = setTimeout(() => {
|
||||
descEl.textContent = config.description;
|
||||
descEl.classList.remove("ocs-desc-error");
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
/* ---------------- boot ---------------- */
|
||||
function boot() {
|
||||
tree = null;
|
||||
treeError = null;
|
||||
renderTree();
|
||||
void (async () => {
|
||||
try {
|
||||
const folders = await bridge.folders();
|
||||
tree = folders.tree || [];
|
||||
appTree = folders.app || {};
|
||||
appRootId = typeof appTree.root === "number" ? appTree.root : null;
|
||||
const preferred = typeof appTree[config.prefer] === "number"
|
||||
? appTree[config.prefer]
|
||||
: appTree.root;
|
||||
const restored = restoreLastFolder(config.lastKey);
|
||||
const known = new Set(tree.map((row) => row.id));
|
||||
const target = restored && known.has(restored) ? restored : preferred;
|
||||
currentFolderId = target;
|
||||
const byId = new Map(tree.map((row) => [row.id, row]));
|
||||
let cursor = target;
|
||||
while (cursor !== null) {
|
||||
expandedSet.add(cursor);
|
||||
cursor = byId.has(cursor) ? byId.get(cursor).parentId : null;
|
||||
}
|
||||
renderTree();
|
||||
renderCrumbs();
|
||||
loadFiles(target);
|
||||
bridge
|
||||
.usage()
|
||||
.then((info) => {
|
||||
usage = info;
|
||||
renderTree();
|
||||
})
|
||||
.catch(() => undefined);
|
||||
} catch (error) {
|
||||
treeError = error && error.message ? error.message : "Could not load the drive";
|
||||
renderTree();
|
||||
}
|
||||
redraw();
|
||||
if (wantsName) {
|
||||
window.setTimeout(() => {
|
||||
nameInput.focus();
|
||||
nameInput.select();
|
||||
}, 50);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
document.body.appendChild(root);
|
||||
boot();
|
||||
});
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
// (C) OneBSpace — https://1bspace.com — a 1B Global company. Proprietary.
|
||||
// OneCAD Simulation Odoo Documents glue (ported from OneCAD).
|
||||
/**
|
||||
* OneCAD Simulation odoo/index.ts — the boot glue (bridge <-> explorer <-> Rust app).
|
||||
* ----------------------------------------------------------------------
|
||||
* Entry module loaded by index.html ONLY inside the wasm_app_framework
|
||||
* iframe (standalone runs never import it — see the import guard there).
|
||||
* Responsibilities:
|
||||
*
|
||||
* 1. instantiate the bridge singleton and wire the explorer dialogs
|
||||
* ("saveAs" / "open" / "export" / "importAsset" host-request methods);
|
||||
* 2. BOOT GATE: waitForHost() (ping every 100 ms, up to 20 s) — then, if
|
||||
* location.search carries ?document=<id>, read that record BEFORE the
|
||||
* app is signaled ready (deep-link open, "onecadsim:document-opened");
|
||||
* 3. signal "onecadsim:host-ready" {host, documentId, name} exactly once.
|
||||
* The same state stays readable synchronously at window.onecadsimHost
|
||||
* (late-booting Rust) together with consumePendingOpen(), which hands
|
||||
* the deep-link payload {documentId, name, dataB64} over once.
|
||||
*
|
||||
* Standalone dev mode: no host frame — no waiting, no deep link, the ready
|
||||
* signal still fires with host:false so the app boots untouched.
|
||||
*
|
||||
* Build note: erasable-syntax-only TS compiled by the OneCAD addon build
|
||||
* to odoo/index.js next to bridge.js; explorer.js is a plain-JS module
|
||||
* copied verbatim. Exports nothing.
|
||||
*/
|
||||
import { exportForHost, EVT_HOST_READY } from "./bridge.js?v=20.0.1.0.0";
|
||||
// @ts-ignore — explorer.js is a sibling plain-JS ES module (copied verbatim
|
||||
// into dist; it imports the compiled bridge.js at runtime).
|
||||
import { openDocumentsExplorer } from "./explorer.js?v=20.0.1.0.0";
|
||||
import type { DocumentOpenedDetail, ExplorerOpener, HostReadyDetail } from "./bridge.js";
|
||||
|
||||
const bridge = exportForHost();
|
||||
bridge.setExplorerOpener(openDocumentsExplorer as ExplorerOpener);
|
||||
|
||||
/* Late-boot contract surface (Rust registers listeners after this module
|
||||
* has run, so it polls this synchronously-readable state on init). */
|
||||
interface OneCadHostWindow {
|
||||
onecadsimHostReady?: boolean;
|
||||
onecadsimHost?: {
|
||||
ready: boolean;
|
||||
host: boolean;
|
||||
documentId: number | null;
|
||||
name: string | null;
|
||||
consumePendingOpen: () => DocumentOpenedDetail | null;
|
||||
};
|
||||
onecadsim?: { request?: (method: string, params?: unknown) => Promise<unknown> };
|
||||
onecadsimOdoo?: {
|
||||
bootFile?: (recordId: number, name: string, bytes: Uint8Array) => string | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
const hostWindow = window as unknown as OneCadHostWindow;
|
||||
hostWindow.onecadsimHost = {
|
||||
ready: false,
|
||||
host: false,
|
||||
documentId: null,
|
||||
name: null,
|
||||
consumePendingOpen: () => bridge.consumePendingOpen(),
|
||||
};
|
||||
|
||||
/* services_odoo.rs polls window.onecadsimHostReady (a plain boolean) before
|
||||
* dispatching odoo.pickOpen / odoo.pickSave / odoo.write to this glue.
|
||||
* Set it as soon as the boot attempt finishes (host answered or not): every
|
||||
* Rust picker parks its slot behind this flag, so an unset flag wedges the
|
||||
* app's file dialogs for REQUEST_TIMEOUT (120 s) with no dialog on screen. */
|
||||
function markHostReady(): void {
|
||||
try {
|
||||
hostWindow.onecadsimHostReady = true;
|
||||
} catch (error) {
|
||||
console.warn("[onecadsim-odoo] could not set onecadsimHostReady:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/* Deep-link opener: stage the record bytes into the engine VFS via the
|
||||
* window.onecadsimOdoo.bootFile seam (installed by services_odoo.rs), then ask
|
||||
* the app to open the staged path through its control API. The wasm app API
|
||||
* appears asynchronously after boot, so poll briefly for it. */
|
||||
async function openStagedDeepLink(entry: DocumentOpenedDetail | null): Promise<void> {
|
||||
if (!entry || typeof entry.dataB64 !== "string") return;
|
||||
const deadline = Date.now() + 60000;
|
||||
while (Date.now() < deadline) {
|
||||
const api = hostWindow.onecadsim;
|
||||
const seam = hostWindow.onecadsimOdoo;
|
||||
if (api && typeof api.request === "function" && seam && typeof seam.bootFile === "function") {
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(entry.dataB64), (char) => char.charCodeAt(0));
|
||||
const path = seam.bootFile(entry.documentId, entry.name, bytes);
|
||||
if (typeof path === "string" && path) {
|
||||
await api.request("ui.file", { path });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[onecadsim-odoo] deep-link open failed:",
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
console.warn("[onecadsim-odoo] deep-link open skipped: the app API never appeared");
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
let host = false;
|
||||
if (bridge.inFrame) {
|
||||
try {
|
||||
await bridge.waitForHost();
|
||||
host = true;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[onecadsim-odoo] host did not answer in time — continuing without Odoo Documents:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.info("[onecadsim-odoo] standalone (no host frame) — Odoo Documents disabled");
|
||||
}
|
||||
|
||||
/* Unblock the Rust pickers first; the deep-link read continues in the
|
||||
* background and must never keep the file dialogs hostage. */
|
||||
markHostReady();
|
||||
let deepLink = false;
|
||||
if (host) {
|
||||
try {
|
||||
deepLink = await bridge.openDeepLink();
|
||||
} catch (error) {
|
||||
console.warn("[onecadsim-odoo] deep-link read failed:", error);
|
||||
}
|
||||
}
|
||||
const binding = bridge.getCurrentBinding();
|
||||
|
||||
const detail: HostReadyDetail = {
|
||||
host,
|
||||
documentId: binding.documentId,
|
||||
name: binding.name,
|
||||
};
|
||||
const state = hostWindow.onecadsimHost;
|
||||
if (state) {
|
||||
state.ready = true;
|
||||
state.host = host;
|
||||
state.documentId = detail.documentId;
|
||||
state.name = detail.name;
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent<HostReadyDetail>(EVT_HOST_READY, { detail }));
|
||||
if (deepLink) {
|
||||
void openStagedDeepLink(bridge.consumePendingOpen());
|
||||
}
|
||||
})();
|
||||
|
||||
export {};
|
||||
@@ -1,708 +0,0 @@
|
||||
// OneBSpace (OneCAD Simulation): Odoo Documents host integration.
|
||||
//! OneBSpace (OneCAD Simulation): Odoo Documents host integration for the wasm32 build
|
||||
//! (the `mod services_odoo;` declaration in `main.rs` carries the
|
||||
//! `#[cfg(target_arch = "wasm32")]` gate).
|
||||
//!
|
||||
//! Inside the wasm_app_framework shell every host seam of
|
||||
//! [`fieldcraft_ui_egui::Services`] is rerouted through the one-cad-simulation JS
|
||||
//! bridge instead of the browser/device. FieldCraft's pickers are *synchronous*
|
||||
//! (`Fn(&[Filter]) -> Option<String>`), so unlike the OneCAD port this module does
|
||||
//! not return futures: the closure fires the bridge request and answers `None`
|
||||
//! (the UI sees "cancelled"), and the real completion is queued here and drained
|
||||
//! once per frame by the web shell:
|
||||
//!
|
||||
//! - an *open* pick stages the record's bytes in the page filesystem at
|
||||
//! `/odoo/doc/<recordId>/<name>` and queues `ModelApp::open_path` (the same
|
||||
//! entry `web.rs::open_arrived` uses, so statuses and worker opens behave);
|
||||
//! - a *save* pick queues `file.save_as {"path": "/odoo/pending/<token>/<name>"}`;
|
||||
//! the engine write is air-gapped by [`handle_write`] and the bridge binds the
|
||||
//! pending token to the Documents record, so the model's file becomes the
|
||||
//! record and later Ctrl+S writes back in place.
|
||||
//! - writes drained from the page filesystem under `/odoo/…` (or model files
|
||||
//! anywhere else) go to the bound Documents record; every other write becomes
|
||||
//! an export into the "Exports" folder — the air gap keeps bytes off the local
|
||||
//! device ([`handle_write`]); the web shell checks the autosave/recovery folder
|
||||
//! *first*, so the localStorage recovery mirror keeps working as upstream.
|
||||
//!
|
||||
//! Everything is inert standalone: when the page is not framed by the Odoo shell
|
||||
//! ([`embedded`]) nothing is overridden and the upstream behavior is untouched.
|
||||
//!
|
||||
//! # WIRE PROTOCOL (matches the one-cad-simulation JS bridge: CustomEvents)
|
||||
//!
|
||||
//! Rust → JS: `window.dispatchEvent(new CustomEvent("onecadsim:host-request",
|
||||
//! { detail }))` with `detail = { id: number, method: string, params: object }`.
|
||||
//!
|
||||
//! JS → Rust: `window.dispatchEvent(new CustomEvent("onecadsim:host-response",
|
||||
//! { detail }))` with `detail = { id, ok: boolean, result?: any, error?: string }`.
|
||||
//!
|
||||
//! The glue must attach its `onecadsim:host-response` listener *before* the app
|
||||
//! boots (index.html loads the bridge module ahead of the wasm) and set
|
||||
//! `window.onecadsimHostReady = true` when listening; until the flag appears
|
||||
//! requests are retried every [`RETRY_MS`] for [`HOST_DEADLINE`].
|
||||
//!
|
||||
//! | method | params | result (on `ok`) |
|
||||
//! |--------------------|------------------------------------------|------------------|
|
||||
//! | `odoo.pickOpen` | `{ extensions: string[] }` | `{ recordId, name, bytes: Uint8Array }` or `{ content: <base64> }` → bytes staged at `/odoo/doc/<recordId>/<name>` |
|
||||
//! | `odoo.pickSave` | `{ name: string, design: boolean }` | `{ token, name }` → `/odoo/pending/<token>/<name>`, or `{ path: "/odoo/…" }` |
|
||||
//! | `odoo.pickProgram` | `{}` (asset pick from the "Assets" folder) | same shape as `odoo.pickOpen` |
|
||||
//! | `odoo.write` | `{ path: string, bytes: Uint8Array }` | ack only (`ok`) — Documents record write-back |
|
||||
//! | `odoo.saveExport` | `{ name: string, bytes: Uint8Array }` | ack only — lands in the "Exports" folder |
|
||||
//! | `odoo.import` | `{ name: string, bytes: Uint8Array }` | ack only — best-effort mirror into "Assets" |
|
||||
//!
|
||||
//! A `null`/absent `result` with `ok: true` means the user cancelled the
|
||||
//! explorer; nothing is queued and the UI stays as it was.
|
||||
//!
|
||||
//! For JS→Rust staging (deep links `?document=<id>`) the glue calls
|
||||
//! `window.onecadsimOdoo.bootFile(recordId, name, uint8array) -> path`, which
|
||||
//! inserts the bytes into the page filesystem at `/odoo/doc/<id>/<name>`, then
|
||||
//! asks the app to open the returned path via `window.onecadsim.request`.
|
||||
//!
|
||||
//! `window.onecadsim` is a small promise-based API the glue drives (the OneCAD
|
||||
//! fork's `api.rs` equivalent, kept minimal):
|
||||
//!
|
||||
//! - `request("ui.file", { path })` → queues the open; resolves immediately.
|
||||
//! - `request("odoo.document.bytes")` → resolves with the current model's
|
||||
//! `.fieldcraft` bytes ([`Session::file_bytes`], via the shell's frame drain).
|
||||
//! - `request("odoo.document.info")` → resolves with `{ name }` (the current
|
||||
//! model's file name, if any).
|
||||
//!
|
||||
//! # HOW TO WIRE (exact locations in this tree)
|
||||
//!
|
||||
//! 1. `apps/fieldcraft-web/src/main.rs`, module block (tagged
|
||||
//! `OneBSpace (OneCAD Simulation)`): `#[cfg(target_arch = "wasm32")] mod services_odoo;`
|
||||
//! 2. `apps/fieldcraft-web/src/web.rs`, the startup closure — immediately after
|
||||
//! the `services(inbox, ctx)` literal and before `with_services`:
|
||||
//! `let services = crate::services_odoo::install_odoo_services(services, cc.egui_ctx.clone());`
|
||||
//! 3. `apps/fieldcraft-web/src/web.rs` `Shell::logic` (tagged line):
|
||||
//! `crate::services_odoo::drain(&mut self.app);` — completes queued picks.
|
||||
//! 4. `apps/fieldcraft-web/src/web.rs` `Shell::hand_out_writes` (tagged): the
|
||||
//! `else if crate::services_odoo::handle_write(&path, &bytes) { continue; }`
|
||||
//! branch between the recovery-folder branch and the download branch.
|
||||
//! 5. `apps/fieldcraft-web/src/web.rs` `Shell::open_arrived` (tagged):
|
||||
//! `crate::services_odoo::mirror_import(&name, …)` mirrors computer imports
|
||||
//! into the Documents "Assets" folder.
|
||||
|
||||
// OneBSpace (OneCAD Simulation) — this entire file is downstream; keep it out of
|
||||
// upstream syncs (greppable tag above).
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use fieldcraft_ui_egui::{Filter, ModelApp, Services};
|
||||
use wasm_bindgen::{JsCast as _, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
/// An existing Documents record inside the emulated filesystem.
|
||||
const ODOC: &str = "/odoo/doc/";
|
||||
/// A Save-as destination chosen in the explorer, not yet written.
|
||||
const OPENDING: &str = "/odoo/pending/";
|
||||
/// Scratch area whose writes the shell swallows (never a record, never a download).
|
||||
const OTMP: &str = "/odoo/tmp/";
|
||||
/// Rust → JS request event (see the WIRE PROTOCOL block above).
|
||||
const REQUEST_EVENT: &str = "onecadsim:host-request";
|
||||
/// JS → Rust response event (see the WIRE PROTOCOL block above).
|
||||
const RESPONSE_EVENT: &str = "onecadsim:host-response";
|
||||
const PICK_OPEN: &str = "odoo.pickOpen";
|
||||
const PICK_SAVE: &str = "odoo.pickSave";
|
||||
/// Supported by the JS bridge; FieldCraft's `Services` has no program picker,
|
||||
/// so the Rust side never emits it today.
|
||||
#[allow(dead_code)]
|
||||
const PICK_PROGRAM: &str = "odoo.pickProgram";
|
||||
const WRITE: &str = "odoo.write";
|
||||
const SAVE_EXPORT: &str = "odoo.saveExport";
|
||||
const IMPORT: &str = "odoo.import";
|
||||
/// At most this many bridge requests parked at once.
|
||||
const MAX_PENDING: usize = 64;
|
||||
/// Retry cadence while `window.onecadsimHostReady` has not appeared yet.
|
||||
const RETRY_MS: i32 = 250;
|
||||
/// How long to wait for the JS bridge module to become ready per request
|
||||
/// (in retry ticks of [`RETRY_MS`]: 30 s).
|
||||
const HOST_DEADLINE_TICKS: u32 = 120;
|
||||
|
||||
/// CAE/model formats the app ingests beyond its own (mirrors the JS bridge's
|
||||
/// asset list). Imported copies land in the Documents "Assets" folder.
|
||||
const ASSET_EXTS: [&str; 12] = ["step", "stp", "iges", "igs", "brep", "stl", "obj", "3mf", "dxf", "gltf", "glb", "ply"];
|
||||
|
||||
thread_local! {
|
||||
/// Decided once: does this page run inside the Odoo shell?
|
||||
static EMBEDDED: Cell<Option<bool>> = const { Cell::new(None) };
|
||||
/// Pending picker requests, keyed by request id.
|
||||
static PENDING: RefCell<HashMap<u64, Arc<Slot>>> = RefCell::new(HashMap::new());
|
||||
/// Completions waiting for the shell's next frame ([`drain`]).
|
||||
static COMPLETED: RefCell<Vec<Completion>> = RefCell::new(Vec::new());
|
||||
/// Promise resolvers parked for `odoo.document.bytes`, keyed by request id.
|
||||
static BYTES_WAITING: RefCell<HashMap<u64, Function>> = RefCell::new(HashMap::new());
|
||||
/// Promise resolvers parked for `odoo.document.info`, keyed by request id.
|
||||
static INFO_WAITING: RefCell<HashMap<u64, Function>> = RefCell::new(HashMap::new());
|
||||
/// The request-id counter.
|
||||
static NEXT_ID: Cell<u64> = const { Cell::new(1) };
|
||||
/// The `onecadsim:host-response` listener is installed exactly once.
|
||||
static LISTENER: Cell<bool> = const { Cell::new(false) };
|
||||
/// The `window.onecadsimOdoo` boot seam is installed exactly once.
|
||||
static BOOT: Cell<bool> = const { Cell::new(false) };
|
||||
/// The `window.onecadsim` API is installed exactly once.
|
||||
static API: Cell<bool> = const { Cell::new(false) };
|
||||
/// Asset imports already mirrored this session (name, size).
|
||||
static MIRRORED: RefCell<HashSet<(String, usize)>> = RefCell::new(HashSet::new());
|
||||
}
|
||||
|
||||
/// A picker request parked in flight: the response listener removes it from
|
||||
/// [`PENDING`] and pushes the queued completion for [`drain`] (the sync
|
||||
/// `Services` design has no future to poll a slot, so the queue is the handoff).
|
||||
struct Slot {
|
||||
done: Cell<bool>,
|
||||
}
|
||||
|
||||
/// Work the shell performs on its next frame.
|
||||
enum Completion {
|
||||
/// Open the emulated path (`ModelApp::open_path`).
|
||||
Open(String),
|
||||
/// Save the model to the emulated path (`file.save_as`).
|
||||
SaveAs(String),
|
||||
/// Resolve `odoo.document.bytes` with the model's bytes.
|
||||
Bytes(u64),
|
||||
/// Resolve `odoo.document.info` with the model's file name.
|
||||
Info(u64),
|
||||
}
|
||||
|
||||
/// Is this page running inside the wasm_app_framework shell? Decided once,
|
||||
/// the family rule (one-cut-pro env.ts): framed and the same-origin parent
|
||||
/// is the Odoo web client (`/odoo` or `/web`). `?odoo-host=1` forces it on
|
||||
/// for local testing against a stub shell.
|
||||
pub fn embedded() -> bool {
|
||||
if let Some(decided) = EMBEDDED.with(Cell::get) {
|
||||
return decided;
|
||||
}
|
||||
let decided = embedded_uncached();
|
||||
EMBEDDED.with(|e| e.set(Some(decided)));
|
||||
decided
|
||||
}
|
||||
|
||||
fn embedded_uncached() -> bool {
|
||||
let Some(window) = web_sys::window() else { return false };
|
||||
let Ok(search) = window.location().search() else { return false };
|
||||
if search.contains("odoo-host=1") {
|
||||
return true;
|
||||
}
|
||||
let Ok(parent) = window.parent() else { return false };
|
||||
// Top window: standalone run, upstream behavior everywhere.
|
||||
let parent_top = parent
|
||||
.as_ref()
|
||||
.map(|p| {
|
||||
AsRef::<JsValue>::as_ref(p) == AsRef::<JsValue>::as_ref(&window)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if parent_top {
|
||||
return false;
|
||||
}
|
||||
// Same-origin shell: the parent path is readable; anything else that is
|
||||
// framed counts as embedded (the shell never cross-origins the iframe).
|
||||
let pathname = parent
|
||||
.as_ref()
|
||||
.and_then(|p| p.location().pathname().ok());
|
||||
match pathname {
|
||||
Some(path) => path.starts_with("/odoo") || path.starts_with("/web"),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the integration: the seams and the response listener always
|
||||
/// (harmless standalone), the Services overrides only inside the shell.
|
||||
/// Call once at app start, right after the `services(inbox, ctx)` literal in
|
||||
/// `web.rs` and before `with_services` (see HOW TO WIRE above).
|
||||
pub fn install_odoo_services(services: Services, ctx: egui::Context) -> Services {
|
||||
install_response_listener(ctx.clone());
|
||||
install_seams(ctx.clone());
|
||||
if !embedded() {
|
||||
return services;
|
||||
}
|
||||
log::info!("OneCAD Simulation: Odoo shell detected — pickers and writes route through the Documents bridge");
|
||||
let open_ctx = ctx.clone();
|
||||
let save_ctx = ctx;
|
||||
Services {
|
||||
// Open/Insert pickers browse Odoo Documents: fire the explorer request
|
||||
// and answer `None` (the shell completes the open on a later frame).
|
||||
pick_open: Some(Box::new(move |filters: &[Filter]| {
|
||||
let params = Object::new();
|
||||
let list = Array::new();
|
||||
for ext in filter_extensions(filters) {
|
||||
list.push(&JsValue::from_str(&ext));
|
||||
}
|
||||
let _ = Reflect::set(¶ms, &"extensions".into(), &list.into());
|
||||
pick(PICK_OPEN, params, open_ctx.clone());
|
||||
None
|
||||
})),
|
||||
// Saves ask the explorer once; the returned pending token binds the
|
||||
// model to its record (the queued `file.save_as` lands it, later
|
||||
// Ctrl+S writes back in place).
|
||||
pick_save: Some(Box::new(move |name: &str, filters: &[Filter]| {
|
||||
let params = Object::new();
|
||||
let _ = Reflect::set(¶ms, &"name".into(), &JsValue::from_str(name));
|
||||
// A model save (the owned `.fieldcraft` type) drives the owned save flow.
|
||||
let design = filters.iter().any(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case("fieldcraft")));
|
||||
let _ = Reflect::set(¶ms, &"design".into(), &JsValue::from_bool(design));
|
||||
pick(PICK_SAVE, params, save_ctx.clone());
|
||||
None
|
||||
})),
|
||||
// Air gap: no external links from the shell.
|
||||
open_url: Some(Box::new(|_: &str| Ok(()))),
|
||||
..services
|
||||
}
|
||||
}
|
||||
|
||||
/// The union of a picker filter set's extensions, lowercase, deduped, in order.
|
||||
fn filter_extensions(filters: &[Filter]) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for filter in filters {
|
||||
for ext in filter.extensions {
|
||||
let ext = ext.to_ascii_lowercase();
|
||||
if !out.iter().any(|seen| *seen == ext) {
|
||||
out.push(ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Fire a bridge request (retried until the glue is ready); the answer arrives
|
||||
/// out-of-band via `onecadsim:host-response` and completes a queued pick.
|
||||
fn pick(method: &'static str, params: Object, ctx: egui::Context) {
|
||||
if PENDING.with(|p| p.borrow().len()) >= MAX_PENDING {
|
||||
log::error!("OneCAD Simulation: too many pending bridge requests (maximum {MAX_PENDING})");
|
||||
return;
|
||||
}
|
||||
let id = next_id();
|
||||
let slot = Arc::new(Slot { done: Cell::new(false) });
|
||||
PENDING.with(|p| p.borrow_mut().insert(id, slot));
|
||||
deliver(method, id, params, 0);
|
||||
// Nudge the UI so the shell's frame drain runs promptly.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn next_id() -> u64 {
|
||||
NEXT_ID.with(|n| {
|
||||
let id = n.get();
|
||||
n.set(id + 1);
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
/// Deliver a request once `window.onecadsimHostReady` appears (the glue sets it
|
||||
/// after attaching its response listener), then cancel the slot if it never
|
||||
/// does. Answers arrive out-of-band via `onecadsim:host-response`.
|
||||
fn deliver(method: &'static str, id: u64, params: Object, tick: u32) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let slot_done = PENDING.with(|p| p.borrow().get(&id).map(|s| s.done.get()).unwrap_or(true));
|
||||
if slot_done {
|
||||
return; // answered or cancelled while we were waiting
|
||||
}
|
||||
if host_ready() && dispatch_event(method, id, ¶ms) {
|
||||
return; // the shell owns the answer now
|
||||
}
|
||||
if tick >= HOST_DEADLINE_TICKS {
|
||||
log::error!("OneCAD Simulation: the Odoo bridge never became ready; cancelling \"{method}\"");
|
||||
PENDING.with(|p| p.borrow_mut().remove(&id));
|
||||
return;
|
||||
}
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, RETRY_MS);
|
||||
});
|
||||
let _ = JsFuture::from(promise).await;
|
||||
deliver(method, id, params, tick + 1);
|
||||
});
|
||||
}
|
||||
|
||||
fn host_ready() -> bool {
|
||||
web_sys::window()
|
||||
.map(|w| Reflect::get(&w, &"onecadsimHostReady".into()).ok().and_then(|v| v.as_bool()).unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `window.dispatchEvent(new CustomEvent(method, { detail: {id, method, params} }))`.
|
||||
/// Built through `js_sys` (no extra web-sys feature gates). `false` when the
|
||||
/// event could not be created or dispatched (no shell listening).
|
||||
fn dispatch_event(method: &str, id: u64, params: &Object) -> bool {
|
||||
let Some(window) = web_sys::window() else { return false };
|
||||
let Ok(ctor) = Reflect::get(&window, &"CustomEvent".into()) else { return false };
|
||||
let Ok(ctor) = ctor.dyn_into::<js_sys::Function>() else { return false };
|
||||
let detail = Object::new();
|
||||
let _ = Reflect::set(&detail, &"id".into(), &JsValue::from(id as f64));
|
||||
let _ = Reflect::set(&detail, &"method".into(), &JsValue::from_str(method));
|
||||
let _ = Reflect::set(&detail, &"params".into(), params);
|
||||
let init = Object::new();
|
||||
let _ = Reflect::set(&init, &"detail".into(), &detail.into());
|
||||
let args = Array::of2(&JsValue::from_str(REQUEST_EVENT), &init.into());
|
||||
let Ok(event) = Reflect::construct(&ctor, &args) else { return false };
|
||||
let Ok(dispatch) = Reflect::get(&window, &"dispatchEvent".into()) else { return false };
|
||||
let Ok(dispatch) = dispatch.dyn_into::<js_sys::Function>() else { return false };
|
||||
dispatch.call1(&window, &event).is_ok()
|
||||
}
|
||||
|
||||
/// Install the `onecadsim:host-response` listener once: responses complete the
|
||||
/// parked picker slots (queued work for [`drain`]) or log write/import failures.
|
||||
fn install_response_listener(ctx: egui::Context) {
|
||||
if LISTENER.with(Cell::get) {
|
||||
return;
|
||||
}
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let listener = Closure::<dyn Fn(JsValue)>::new(move |event: JsValue| {
|
||||
let detail = Reflect::get(&event, &"detail".into()).unwrap_or(JsValue::UNDEFINED);
|
||||
let id = field_u64(&detail, "id");
|
||||
let ok = Reflect::get(&detail, &"ok".into()).ok().and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let error = field_string(&detail, "error").unwrap_or_default();
|
||||
let result = Reflect::get(&detail, &"result".into()).unwrap_or(JsValue::UNDEFINED);
|
||||
let slot = PENDING.with(|p| p.borrow_mut().remove(&id));
|
||||
match slot {
|
||||
Some(_slot) => {
|
||||
if ok {
|
||||
// OneBSpace (OneCAD Simulation): the completion goes on the
|
||||
// queue the shell's frame drain consumes ([`drain`]).
|
||||
if let Some(completion) = completion_from_result(&result) {
|
||||
COMPLETED.with(|c| c.borrow_mut().push(completion));
|
||||
}
|
||||
} else {
|
||||
log::warn!("OneCAD Simulation: the shell refused the request: {error}");
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
// Writes, exports and imports are acknowledged without a parked
|
||||
// slot; only their failures are interesting here.
|
||||
None if !ok => log::warn!("OneCAD Simulation: the shell refused a write/export/import: {error}"),
|
||||
None => {}
|
||||
}
|
||||
});
|
||||
let Ok(add) = Reflect::get(&window, &"addEventListener".into()) else { return };
|
||||
let Ok(add) = add.dyn_into::<js_sys::Function>() else { return };
|
||||
if add.call2(&window, &JsValue::from_str(RESPONSE_EVENT), &listener.into_js_value()).is_ok() {
|
||||
LISTENER.with(|l| l.set(true));
|
||||
log::info!("OneCAD Simulation: response listener installed");
|
||||
} else {
|
||||
log::warn!("OneCAD Simulation: response listener install FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a `onecadsim:host-response` result onto the queued completion the shell
|
||||
/// drains (see the WIRE PROTOCOL table above).
|
||||
fn completion_from_result(result: &JsValue) -> Option<Completion> {
|
||||
if !result.is_object() {
|
||||
return None; // the user cancelled the explorer
|
||||
}
|
||||
let name = field_string(result, "name");
|
||||
// An opened record: bytes come as a Uint8Array (preferred) or base64.
|
||||
if let Ok(bytes) = Reflect::get(result, &"bytes".into())
|
||||
&& bytes.is_instance_of::<Uint8Array>()
|
||||
{
|
||||
let Ok(bytes) = bytes.dyn_into::<Uint8Array>() else { return None };
|
||||
return stage_record(field_u64(result, "recordId"), name.as_deref(), bytes.to_vec()).map(Completion::Open);
|
||||
}
|
||||
if let Some(content) = field_string(result, "content")
|
||||
&& let Some(bytes) = base64_decode(&content)
|
||||
{
|
||||
return stage_record(field_u64(result, "recordId"), name.as_deref(), bytes).map(Completion::Open);
|
||||
}
|
||||
// A Save-as destination: the pending token names the path the engine
|
||||
// will write to (the glue binds the token to the record).
|
||||
let token = field_string(result, "token");
|
||||
if let (Some(token), Some(name)) = (token, name) {
|
||||
return Some(Completion::SaveAs(format!("{OPENDING}{token}/{}", sanitize(&name))));
|
||||
}
|
||||
// Or the glue resolved an explicit emulated path itself.
|
||||
if let Some(path) = field_string(result, "path")
|
||||
&& path.starts_with("/odoo/")
|
||||
{
|
||||
return Some(Completion::Open(path));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Stage a picked record's bytes in the page filesystem at `/odoo/doc/<id>/<name>`.
|
||||
fn stage_record(record_id: u64, name: Option<&str>, bytes: Vec<u8>) -> Option<String> {
|
||||
if record_id == 0 {
|
||||
return None;
|
||||
}
|
||||
let path = format!("{ODOC}{record_id}/{}", sanitize(name.unwrap_or("document")));
|
||||
match fieldcraft_io::fs::insert(Path::new(&path), bytes) {
|
||||
Ok(()) => Some(path),
|
||||
Err(e) => {
|
||||
log::error!("OneCAD Simulation: could not stage the document ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn field_u64(value: &JsValue, key: &str) -> u64 {
|
||||
Reflect::get(value, &key.into()).ok().and_then(|v| v.as_f64()).map(|f| f as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn field_string(value: &JsValue, key: &str) -> Option<String> {
|
||||
Reflect::get(value, &key.into()).ok().and_then(|v| v.as_string())
|
||||
}
|
||||
|
||||
/// File names only key the filesystem: keep them single-segment.
|
||||
fn sanitize(name: &str) -> String {
|
||||
let cleaned: String = name.chars().map(|c| if c == '/' || c == '\\' { '_' } else { c }).collect();
|
||||
let trimmed = cleaned.trim();
|
||||
if trimmed.is_empty() {
|
||||
"file".into()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiny base64 (standard alphabet, padding optional) decoder for bridge
|
||||
/// payloads that arrive as `content` strings instead of `Uint8Array`s.
|
||||
fn base64_decode(input: &str) -> Option<Vec<u8>> {
|
||||
fn value(byte: u8) -> Option<u32> {
|
||||
match byte {
|
||||
b'A'..=b'Z' => Some((byte - b'A') as u32),
|
||||
b'a'..=b'z' => Some((byte - b'a') as u32 + 26),
|
||||
b'0'..=b'9' => Some((byte - b'0') as u32 + 52),
|
||||
b'+' => Some(62),
|
||||
b'/' => Some(63),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let clean: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=').collect();
|
||||
let mut out = Vec::with_capacity(clean.len() * 3 / 4);
|
||||
for chunk in clean.chunks(4) {
|
||||
if chunk.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut acc: u32 = 0;
|
||||
for (i, byte) in chunk.iter().enumerate() {
|
||||
acc |= value(*byte)? << (18 - 6 * i);
|
||||
}
|
||||
out.push((acc >> 16) as u8);
|
||||
if chunk.len() > 2 {
|
||||
out.push((acc >> 8) as u8);
|
||||
}
|
||||
if chunk.len() > 3 {
|
||||
out.push(acc as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drain hook (tagged call site in `web.rs::hand_out_writes`, right after the
|
||||
/// recovery-folder branch): consume writes the shell must not turn into device
|
||||
/// downloads. `/odoo/…` writes go to the bound Documents record (or the pending
|
||||
/// token's destination on first write); model files elsewhere are write-backs
|
||||
/// by name; everything else is an export into the "Exports" folder. Returns
|
||||
/// true when the write was consumed (standalone: always false, upstream
|
||||
/// behavior untouched).
|
||||
pub fn handle_write(path: &Path, bytes: &[u8]) -> bool {
|
||||
if !embedded() {
|
||||
return false;
|
||||
}
|
||||
let path_str = path.to_string_lossy().into_owned();
|
||||
// Scratch writes (never a record): swallowed, nothing leaves the page.
|
||||
if path_str.starts_with(OTMP) {
|
||||
return true;
|
||||
}
|
||||
let params = Object::new();
|
||||
let method = if path_str.starts_with(ODOC) || path_str.starts_with(OPENDING) {
|
||||
let _ = Reflect::set(¶ms, &"path".into(), &JsValue::from_str(&path_str));
|
||||
WRITE
|
||||
} else if is_model_path(&path_str) {
|
||||
// Model files written outside the emulated tree (New model saved to the
|
||||
// page's folder): the bridge resolves the record by name or creates one.
|
||||
let _ = Reflect::set(¶ms, &"path".into(), &JsValue::from_str(&path_str));
|
||||
WRITE
|
||||
} else {
|
||||
// Decks, reports, results: an export into the "Exports" folder.
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "export".into());
|
||||
let _ = Reflect::set(¶ms, &"name".into(), &JsValue::from_str(&name));
|
||||
SAVE_EXPORT
|
||||
};
|
||||
let _ = Reflect::set(¶ms, &"bytes".into(), &Uint8Array::from(bytes).into());
|
||||
if !dispatch_event(method, next_id(), ¶ms) {
|
||||
log::error!("OneCAD Simulation: the Odoo bridge is unavailable; \"{path_str}\" stays in the page (the Documents copy was not updated)");
|
||||
}
|
||||
// Consumed either way: the air gap wins even if the bridge module is
|
||||
// gone — bytes never reach the local device from the shell (a copy
|
||||
// survives in the page filesystem and the localStorage autosave until
|
||||
// the save succeeds).
|
||||
true
|
||||
}
|
||||
|
||||
/// `.fieldcraft`/`.solidcraft`/`.3mf` are the model-ish types the shell writes
|
||||
/// back to Documents; everything else counts as an export.
|
||||
fn is_model_path(path: &str) -> bool {
|
||||
Path::new(path)
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ["fieldcraft", "solidcraft", "3mf"].iter().any(|candidate| ext.eq_ignore_ascii_case(candidate)))
|
||||
}
|
||||
|
||||
/// Mirror hook (tagged call site in `web.rs::open_arrived`): CAE assets brought
|
||||
/// in from the computer get a copy in the Documents "Assets" folder (family
|
||||
/// storage rule). Deduplicated per (name, size) this session; the JS side
|
||||
/// additionally dedupes by signature across reloads.
|
||||
pub fn mirror_import(name: &str, bytes: Option<&[u8]>) {
|
||||
if !embedded() {
|
||||
return;
|
||||
}
|
||||
let Some(bytes) = bytes else { return };
|
||||
if !is_asset_name(name) {
|
||||
return;
|
||||
}
|
||||
if !MIRRORED.with(|m| m.borrow_mut().insert((name.to_string(), bytes.len()))) {
|
||||
return;
|
||||
}
|
||||
let params = Object::new();
|
||||
let _ = Reflect::set(¶ms, &"name".into(), &JsValue::from_str(name));
|
||||
let _ = Reflect::set(¶ms, &"bytes".into(), &Uint8Array::from(bytes).into());
|
||||
if !dispatch_event(IMPORT, next_id(), ¶ms) {
|
||||
log::warn!("OneCAD Simulation: could not mirror \"{name}\" into the Assets folder (bridge not ready)");
|
||||
}
|
||||
}
|
||||
|
||||
fn is_asset_name(name: &str) -> bool {
|
||||
Path::new(name)
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ASSET_EXTS.iter().any(|candidate| ext.eq_ignore_ascii_case(candidate)))
|
||||
}
|
||||
|
||||
/// The shell's per-frame drain (tagged call site in `web.rs::Shell::logic`):
|
||||
/// completes queued picks and answers the glue's API requests.
|
||||
pub fn drain(app: &mut ModelApp) {
|
||||
let work: Vec<Completion> = COMPLETED.with(|c| std::mem::take(&mut *c.borrow_mut()));
|
||||
if !work.is_empty() {
|
||||
log::info!("OneCAD Simulation: drain {} queued item(s)", work.len());
|
||||
}
|
||||
for completion in work {
|
||||
match completion {
|
||||
Completion::Open(path) => app.open_path(&path),
|
||||
Completion::SaveAs(path) => {
|
||||
if let Err(e) = app.session.execute("file.save_as", &serde_json::json!({"path": path})) {
|
||||
log::warn!("OneCAD Simulation: the save-as to \"{path}\" failed: {e}");
|
||||
}
|
||||
}
|
||||
Completion::Bytes(id) => match app.session.file_bytes(None) {
|
||||
Ok(bytes) => complete_bytes(id, &bytes),
|
||||
Err(e) => BYTES_WAITING.with(|b| {
|
||||
if let Some(reject) = b.borrow_mut().remove(&id) {
|
||||
let _ = reject.call1(&JsValue::UNDEFINED, &JsValue::from_str(&format!("{e}")));
|
||||
}
|
||||
}),
|
||||
},
|
||||
Completion::Info(id) => {
|
||||
let name = app
|
||||
.session
|
||||
.path
|
||||
.as_deref()
|
||||
.map(|p| sanitize(p.rsplit('/').next().unwrap_or(p)))
|
||||
.filter(|n| !n.is_empty());
|
||||
complete_info(id, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn complete_bytes(id: u64, bytes: &[u8]) {
|
||||
if let Some(resolve) = BYTES_WAITING.with(|b| b.borrow_mut().remove(&id)) {
|
||||
let _ = resolve.call1(&JsValue::UNDEFINED, &Uint8Array::from(bytes).into());
|
||||
}
|
||||
}
|
||||
|
||||
fn complete_info(id: u64, name: Option<String>) {
|
||||
if let Some(resolve) = INFO_WAITING.with(|b| b.borrow_mut().remove(&id)) {
|
||||
let info = Object::new();
|
||||
let _ = Reflect::set(&info, &"name".into(), &name.as_deref().map(JsValue::from_str).unwrap_or(JsValue::NULL));
|
||||
let _ = resolve.call1(&JsValue::UNDEFINED, &info.into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the JS→Rust seams once:
|
||||
///
|
||||
/// - `window.onecadsimOdoo = { bootFile }` — the staging seam for deep links
|
||||
/// (`?document=<id>`): the glue inserts the record's bytes into the page
|
||||
/// filesystem, then opens the returned path via `window.onecadsim.request`.
|
||||
/// - `window.onecadsim = { request }` — the promise-based API the glue drives
|
||||
/// (the OneCAD fork's `api.rs` equivalent, kept minimal).
|
||||
fn install_seams(ctx: egui::Context) {
|
||||
install_boot_seam();
|
||||
install_api(ctx);
|
||||
}
|
||||
|
||||
fn install_boot_seam() {
|
||||
if BOOT.with(Cell::get) {
|
||||
return;
|
||||
}
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let boot_file = Closure::<dyn Fn(JsValue, JsValue, JsValue) -> JsValue>::new(
|
||||
|record_id: JsValue, name: JsValue, bytes: JsValue| {
|
||||
let id = record_id.as_f64().map(|f| f as u64).unwrap_or(0);
|
||||
if id == 0 {
|
||||
return JsValue::UNDEFINED;
|
||||
}
|
||||
let name = name.as_string().unwrap_or_else(|| "document".into());
|
||||
let Ok(bytes) = bytes.dyn_into::<Uint8Array>() else { return JsValue::UNDEFINED };
|
||||
match stage_record(id, Some(&name), bytes.to_vec()) {
|
||||
Some(path) => JsValue::from_str(&path),
|
||||
None => JsValue::UNDEFINED,
|
||||
}
|
||||
},
|
||||
);
|
||||
let glue = Object::new();
|
||||
let _ = Reflect::set(&glue, &"bootFile".into(), &boot_file.into_js_value());
|
||||
if Reflect::set(&window, &"onecadsimOdoo".into(), &glue).is_ok() {
|
||||
BOOT.with(|b| b.set(true));
|
||||
}
|
||||
}
|
||||
|
||||
fn install_api(ctx: egui::Context) {
|
||||
if API.with(Cell::get) {
|
||||
return;
|
||||
}
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let request = Closure::<dyn Fn(JsValue, JsValue) -> JsValue>::new(move |method: JsValue, params: JsValue| {
|
||||
let method = method.as_string().unwrap_or_default();
|
||||
let ctx = ctx.clone();
|
||||
js_sys::Promise::new(&mut move |resolve, reject| match method.as_str() {
|
||||
// Open the staged deep-link path on the shell's next frame.
|
||||
"ui.file" => {
|
||||
let path = Reflect::get(¶ms, &"path".into()).ok().and_then(|v| v.as_string());
|
||||
match path {
|
||||
Some(path) if path.starts_with("/odoo/") => {
|
||||
COMPLETED.with(|c| c.borrow_mut().push(Completion::Open(path)));
|
||||
ctx.request_repaint();
|
||||
let _ = resolve.call1(&JsValue::UNDEFINED, &JsValue::NULL);
|
||||
}
|
||||
_ => {
|
||||
let _ = reject.call1(&JsValue::UNDEFINED, &JsValue::from_str("ui.file: an /odoo/ path is required"));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The current model's bytes, resolved from the shell's frame drain.
|
||||
"odoo.document.bytes" => {
|
||||
let id = next_id();
|
||||
BYTES_WAITING.with(|b| b.borrow_mut().insert(id, resolve));
|
||||
COMPLETED.with(|c| c.borrow_mut().push(Completion::Bytes(id)));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
// The current model's file name (best effort), same drain.
|
||||
"odoo.document.info" => {
|
||||
let id = next_id();
|
||||
INFO_WAITING.with(|b| b.borrow_mut().insert(id, resolve));
|
||||
COMPLETED.with(|c| c.borrow_mut().push(Completion::Info(id)));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
other => {
|
||||
let _ = reject.call1(&JsValue::UNDEFINED, &JsValue::from_str(format!("onecadsim: unknown method \"{other}\"").as_str()));
|
||||
}
|
||||
})
|
||||
.into()
|
||||
});
|
||||
let api = Object::new();
|
||||
let _ = Reflect::set(&api, &"request".into(), &request.into_js_value());
|
||||
if Reflect::set(&window, &"onecadsim".into(), &api).is_ok() {
|
||||
API.with(|a| a.set(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
//! Anonymous usage in the browser (docs/privacy.md): the same events and the same consent as the
|
||||
//! desktop app, the choice kept in the browser's local storage with the other preferences. Queued
|
||||
//! events are posted with `fetch` every half minute and when the page is closed or left (`keepalive`, so
|
||||
//! a closing page still sends them); a failed post is dropped silently.
|
||||
//!
|
||||
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`: a build without one asks nothing
|
||||
//! and sends nothing.
|
||||
|
||||
use fieldcraft_engine::usage;
|
||||
use fieldcraft_ui_egui::files::PrefsStore;
|
||||
use fieldcraft_ui_egui::privacy::UsageHost;
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
|
||||
/// Where the preferences are kept in local storage.
|
||||
const PREFS_KEY: &str = "fieldcraft-prefs";
|
||||
/// How often queued events are sent (seconds).
|
||||
pub const INTERVAL: f64 = 30.0;
|
||||
|
||||
fn key() -> Option<&'static str> {
|
||||
KEY.map(str::trim).filter(|k| !k.is_empty())
|
||||
}
|
||||
|
||||
fn local_storage() -> Option<web_sys::Storage> {
|
||||
web_sys::window()?.local_storage().ok().flatten()
|
||||
}
|
||||
|
||||
/// The preferences in local storage (navigation, privacy).
|
||||
pub fn prefs_store() -> PrefsStore {
|
||||
PrefsStore {
|
||||
load: Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten().map(String::into_bytes)),
|
||||
save: Box::new(|bytes| {
|
||||
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
|
||||
local_storage().ok_or("browser storage is turned off")?.set_item(PREFS_KEY, text).map_err(crate::web::js_err)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the window needs to ask and record, when the build has a key.
|
||||
pub fn host() -> Option<UsageHost> {
|
||||
// The browser's clock for command durations (the plain wasm target has none).
|
||||
usage::set_clock(js_sys::Date::now);
|
||||
key().is_some().then(|| UsageHost {
|
||||
platform: "web",
|
||||
os: "web",
|
||||
arch: "wasm32",
|
||||
new_id: Box::new(|| web_sys::window()?.crypto().ok().map(|c| c.random_uuid())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Post what is queued.
|
||||
pub fn send() {
|
||||
let (Some(key), Some(window)) = (key(), web_sys::window()) else { return };
|
||||
let url = format!("{}/batch/", usage::DEFAULT_HOST);
|
||||
while let Some(batch) = usage::take_batch() {
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_method("POST");
|
||||
init.set_body(&wasm_bindgen::JsValue::from_str(&batch.body(key)));
|
||||
// The Fetch standard's `keepalive` (a closing page still sends it); web-sys has no setter.
|
||||
let _ = js_sys::Reflect::set(&init, &"keepalive".into(), &true.into());
|
||||
let headers = web_sys::Headers::new().ok();
|
||||
if let Some(h) = &headers {
|
||||
let _ = h.set("Content-Type", "application/json");
|
||||
init.set_headers(h);
|
||||
}
|
||||
let promise = window.fetch_with_str_and_init(&url, &init);
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Offline or refused: the batch is dropped.
|
||||
if let Err(e) = wasm_bindgen_futures::JsFuture::from(promise).await {
|
||||
log::debug!("usage: not sent: {}", crate::web::js_err(e));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// When the page is closed or left: the session's length, then send.
|
||||
pub fn send_when_hidden(window: &web_sys::Window) {
|
||||
let on_hide = wasm_bindgen::closure::Closure::<dyn FnMut()>::new(|| {
|
||||
usage::closing();
|
||||
send();
|
||||
});
|
||||
if let Err(e) = window.add_event_listener_with_callback("pagehide", on_hide.as_ref().unchecked_ref()) {
|
||||
log::warn!("usage: {}", crate::web::js_err(e));
|
||||
}
|
||||
on_hide.forget();
|
||||
}
|
||||
@@ -74,7 +74,6 @@ pub fn start() {
|
||||
fieldcraft_io::recovery::set_clock(|| js_sys::Date::now().max(0.0) as u64);
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
ask_before_unload(&window);
|
||||
crate::usage::send_when_hidden(&window);
|
||||
let Some(canvas) = element(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
@@ -86,14 +85,7 @@ pub fn start() {
|
||||
web_options(),
|
||||
Box::new(|cc| {
|
||||
let inbox = Inbox::default();
|
||||
let services = services(inbox.clone(), cc.egui_ctx.clone());
|
||||
// OneBSpace (OneCAD Simulation): install odoo services on wasm
|
||||
let services = crate::services_odoo::install_odoo_services(services, cc.egui_ctx.clone());
|
||||
let mut app = ModelApp::new(Session::default()).with_services(services);
|
||||
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
|
||||
if let Some(host) = crate::usage::host() {
|
||||
app = app.with_usage(host);
|
||||
}
|
||||
let mut app = ModelApp::new(Session::default()).with_services(services(inbox.clone(), cc.egui_ctx.clone()));
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
log::info!("fieldcraft-web: graphics {:?} {}, MSAA {}x", info.backend, info.name, rs.msaa_samples);
|
||||
@@ -110,8 +102,7 @@ pub fn start() {
|
||||
if recoverable > 0 {
|
||||
app.set_status(format!("{recoverable} autosaved model(s) can be recovered: File › Recover…"), false);
|
||||
}
|
||||
let deploy = crate::deploy::Watch::start();
|
||||
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false, sent_at: 0.0, deploy }))
|
||||
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -121,7 +112,7 @@ pub fn start() {
|
||||
el.remove();
|
||||
}
|
||||
}
|
||||
Err(e) => failed(&format!("OneCAD Simulation could not start: {}", js_err(e))),
|
||||
Err(e) => failed(&format!("FieldCraft could not start: {}", js_err(e))),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -146,7 +137,7 @@ fn failed(why: &str) {
|
||||
// Best effort: the console has the message too.
|
||||
let _ = el.class_list().add_1("failed");
|
||||
for line in
|
||||
[why, "OneCAD Simulation needs a browser with WebGPU or WebGL2 (a current Chrome, Edge, Firefox or Safari) and graphics acceleration turned on."]
|
||||
[why, "FieldCraft needs a browser with WebGPU or WebGL2 (a current Chrome, Edge, Firefox or Safari) and graphics acceleration turned on."]
|
||||
{
|
||||
if let Ok(p) = document.create_element("p") {
|
||||
p.set_text_content(Some(line));
|
||||
@@ -197,10 +188,6 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
pick_save: Some(Box::new(|name: &str, _: &[Filter]| Some(page_path(name)))),
|
||||
// The recent list holds the page's files, which go with the page.
|
||||
recent_path: None,
|
||||
// Preferences are kept in the browser's local storage.
|
||||
prefs: Some(crate::usage::prefs_store()),
|
||||
// egui opens links itself in the browser.
|
||||
open_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,10 +202,6 @@ struct Shell {
|
||||
autosaved_at: f64,
|
||||
/// The last autosave did not fit in the browser's storage (said once until one fits).
|
||||
storage_error: bool,
|
||||
/// App time usage events were last sent.
|
||||
sent_at: f64,
|
||||
/// Looks for a new deployment of the app.
|
||||
deploy: crate::deploy::Watch,
|
||||
}
|
||||
|
||||
impl Shell {
|
||||
@@ -230,8 +213,6 @@ impl Shell {
|
||||
let mut paths = Vec::with_capacity(batch.len());
|
||||
for (name, read) in batch {
|
||||
let path = page_path(&name);
|
||||
// OneBSpace (OneCAD Simulation): mirror computer imports into the Documents "Assets" folder
|
||||
crate::services_odoo::mirror_import(&name, read.as_deref().ok());
|
||||
match read.and_then(|bytes| fieldcraft_io::fs::insert(Path::new(&path), bytes).map_err(|e| e.to_string())) {
|
||||
Ok(()) => paths.push(path),
|
||||
Err(e) => self.app.set_status(format!("{name}: {e}"), true),
|
||||
@@ -262,9 +243,6 @@ impl Shell {
|
||||
}
|
||||
Err(e) => log::warn!("autosave: {e}"),
|
||||
}
|
||||
} // OneBSpace (OneCAD Simulation): the shell air-gaps every other write through the Documents bridge
|
||||
else if crate::services_odoo::handle_write(&path, &bytes) {
|
||||
continue;
|
||||
} else if let Err(e) = download(&path, &bytes) {
|
||||
self.app.set_status(format!("{}: the download did not start ({e})", path.display()), true);
|
||||
}
|
||||
@@ -287,23 +265,9 @@ impl Shell {
|
||||
impl eframe::App for Shell {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.open_arrived();
|
||||
// OneBSpace (OneCAD Simulation): complete Documents picks (open/save-as/serialize)
|
||||
crate::services_odoo::drain(&mut self.app);
|
||||
self.app.logic(ctx);
|
||||
self.autosave(ctx);
|
||||
if self.app.now - self.sent_at >= crate::usage::INTERVAL {
|
||||
self.sent_at = self.app.now;
|
||||
crate::usage::send();
|
||||
}
|
||||
UNSAVED.with(|u| u.set(self.app.session.is_dirty() && !self.app.session.journal.is_empty()));
|
||||
if self.app.now - self.deploy.looked_at >= crate::deploy::INTERVAL || self.app.now < self.deploy.looked_at {
|
||||
self.deploy.looked_at = self.app.now;
|
||||
self.deploy.look();
|
||||
}
|
||||
if self.deploy.found() && !self.app.reload_offered() {
|
||||
self.app.offer_reload(Box::new(crate::deploy::reload));
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::deploy::INTERVAL));
|
||||
}
|
||||
|
||||
/// Dropped files are read here (browsers read them asynchronously) and arrive through the
|
||||
|
||||
@@ -1,141 +1,24 @@
|
||||
[package]
|
||||
name = "fieldcraft"
|
||||
description = "Finite element modeling: meshing, model setup, solver decks and a linear solver"
|
||||
description = "FieldCraft desktop app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
# The workspace lints, except unsafe_code: denied, not forbidden, so that src/native_crash.rs
|
||||
# (the Windows exception filter, which has no safe API) can allow it. Keep the rest in sync with
|
||||
# [workspace.lints].
|
||||
[lints.rust]
|
||||
unsafe_code = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
type_complexity = "allow"
|
||||
neg_cmp_op_on_partial_ord = "allow"
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fieldcraft-engine = { workspace = true }
|
||||
fieldcraft-lbm-gpu = { workspace = true }
|
||||
fieldcraft-ui-egui = { workspace = true }
|
||||
fieldcraft-io = { workspace = true }
|
||||
fieldcraft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Usage analytics (docs/privacy.md): an HTTPS POST with rustls on ring, checked against the
|
||||
# operating system's certificates (no bundled root list), and a random install id.
|
||||
ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "platform-verifier"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
|
||||
getrandom = "0.4"
|
||||
|
||||
# A termination signal (SIGTERM, SIGINT) closes the window the normal way (terminate.rs).
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
signal-hook = "0.4"
|
||||
|
||||
# The exception filter and minidump of a native crash (src/native_crash.rs).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
# WriteFile's OVERLAPPED.
|
||||
"Win32_System_IO",
|
||||
"Win32_System_Kernel",
|
||||
"Win32_System_LibraryLoader",
|
||||
# MiniDumpWriteDump.
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
[build-dependencies]
|
||||
# The Windows executable's icon resource (build.rs).
|
||||
embed-resource = "3.0.12"
|
||||
|
||||
# Linux .deb and .rpm packages (cargo-deb, cargo-generate-rpm), built by packaging/linux/package.sh
|
||||
# from the release binaries it has already built and stripped; it sets the version and the file
|
||||
# names. The file list matches the tar.gz's (package.sh's staged tree; the release workflow
|
||||
# compares them).
|
||||
# The binaries link only glibc and libgcc_s. Windowing (Wayland, X11, xkbcommon), the GPU (Vulkan
|
||||
# or EGL) and the file dialogs (the XDG desktop portal) are opened at run time, so they are no ELF
|
||||
# NEEDED entries and the tools cannot find them: they are listed here.
|
||||
[package.metadata.deb]
|
||||
name = "fieldcraft"
|
||||
maintainer = "FieldCraft contributors <jyviko@users.noreply.github.com>"
|
||||
copyright = "FieldCraft contributors"
|
||||
section = "science"
|
||||
priority = "optional"
|
||||
extended-description = """\
|
||||
FieldCraft turns geometry into analysis-ready finite element models: volume \
|
||||
meshes, materials, sections, boundary conditions, loads and steps. It writes \
|
||||
Abaqus input, Nastran bulk data and LS-DYNA keyword decks, and solves linear \
|
||||
static and modal problems with its own solver. Includes fieldcraft-cli, a \
|
||||
headless command runner and MCP server."""
|
||||
depends = "$auto, libxkbcommon0, libxkbcommon-x11-0, libwayland-client0, libx11-6, libx11-xcb1, libxcb1, libxcursor1, libxi6, libvulkan1 | libegl1"
|
||||
recommends = "mesa-vulkan-drivers, libegl-mesa0, xdg-desktop-portal"
|
||||
assets = [
|
||||
["target/release/fieldcraft", "usr/bin/", "755"],
|
||||
["target/release/fieldcraft-cli", "usr/bin/", "755"],
|
||||
["../../packaging/linux/io.github.jyviko.fieldcraft.desktop", "usr/share/applications/", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_16x16.png", "usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_32x32.png", "usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_32x32@2x.png", "usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_128x128.png", "usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_256x256.png", "usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_512x512.png", "usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_512x512@2x.png", "usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../README.md", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../LICENSE-MIT", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../LICENSE-APACHE", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../NOTICE", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../THIRD-PARTY-LICENSES.txt", "usr/share/doc/fieldcraft/", "644"],
|
||||
]
|
||||
|
||||
[package.metadata.generate-rpm]
|
||||
name = "fieldcraft"
|
||||
license = "MIT OR Apache-2.0"
|
||||
url = "https://github.com/tangency-labs/fieldcraft"
|
||||
assets = [
|
||||
{ source = "target/release/fieldcraft", dest = "/usr/bin/fieldcraft", mode = "755" },
|
||||
{ source = "target/release/fieldcraft-cli", dest = "/usr/bin/fieldcraft-cli", mode = "755" },
|
||||
{ source = "../../packaging/linux/io.github.jyviko.fieldcraft.desktop", dest = "/usr/share/applications/io.github.jyviko.fieldcraft.desktop", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_16x16.png", dest = "/usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_32x32.png", dest = "/usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_32x32@2x.png", dest = "/usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_128x128.png", dest = "/usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_256x256.png", dest = "/usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_512x512@2x.png", dest = "/usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../README.md", dest = "/usr/share/doc/fieldcraft/README.md", mode = "644", doc = true },
|
||||
{ source = "../../LICENSE-MIT", dest = "/usr/share/doc/fieldcraft/LICENSE-MIT", mode = "644", doc = true },
|
||||
{ source = "../../LICENSE-APACHE", dest = "/usr/share/doc/fieldcraft/LICENSE-APACHE", mode = "644", doc = true },
|
||||
{ source = "../../NOTICE", dest = "/usr/share/doc/fieldcraft/NOTICE", mode = "644", doc = true },
|
||||
{ source = "../../THIRD-PARTY-LICENSES.txt", dest = "/usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt", mode = "644", doc = true },
|
||||
]
|
||||
# The binaries' ELF dependencies (glibc, libgcc_s) are found automatically; these are opened at run
|
||||
# time. Soname provides rather than package names, so the same requirements resolve on Fedora/RHEL
|
||||
# and openSUSE.
|
||||
require-sh = false
|
||||
|
||||
[package.metadata.generate-rpm.requires]
|
||||
"libxkbcommon.so.0()(64bit)" = "*"
|
||||
"libxkbcommon-x11.so.0()(64bit)" = "*"
|
||||
"libwayland-client.so.0()(64bit)" = "*"
|
||||
"libX11.so.6()(64bit)" = "*"
|
||||
"libX11-xcb.so.1()(64bit)" = "*"
|
||||
"libxcb.so.1()(64bit)" = "*"
|
||||
"libXcursor.so.1()(64bit)" = "*"
|
||||
"libXi.so.6()(64bit)" = "*"
|
||||
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))" = ""
|
||||
|
||||
[package.metadata.generate-rpm.recommends]
|
||||
mesa-vulkan-drivers = "*"
|
||||
xdg-desktop-portal = "*"
|
||||
@@ -115,11 +115,6 @@ fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
|
||||
}
|
||||
ctx.request_repaint();
|
||||
let mut r = rrx.recv_timeout(REPLY_TIMEOUT).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
|
||||
// A request waiting for a job (a solve, a mesher): its reply comes when the job
|
||||
// ends, however long it runs; the job always answers, even when cancelled.
|
||||
if r.get(fieldcraft_ui_egui::control::PENDING).is_some() {
|
||||
r = rrx.recv().unwrap_or_else(|_| json!({"ok": false, "error": "the job ended without a reply"}));
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
|
||||
@@ -9,17 +9,12 @@
|
||||
//! `fieldcraft_ui_egui::control` and docs/control-protocol.md.
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
// Unsafe code is denied (Cargo.toml): only the Windows exception filter allows it (native_crash.rs).
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod control_server;
|
||||
#[cfg(windows)]
|
||||
mod native_crash;
|
||||
mod terminate;
|
||||
mod update;
|
||||
mod usage;
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use fieldcraft_engine::autosave::{self, Autosaver};
|
||||
use fieldcraft_engine::{Session, crash, logfile};
|
||||
use fieldcraft_ui_egui::{Filter, ModelApp, Services};
|
||||
|
||||
const USAGE: &str =
|
||||
@@ -52,10 +47,6 @@ struct App {
|
||||
autosaver: Option<Autosaver>,
|
||||
/// App time of the last autosave check.
|
||||
autosaved_at: f64,
|
||||
/// Frames drawn so far, up to 2 (the second means the first was presented: the app is up).
|
||||
frames: u8,
|
||||
/// Sends the anonymous usage events, when this run may (docs/privacy.md).
|
||||
usage: Option<usage::Sender>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -70,14 +61,6 @@ impl App {
|
||||
|
||||
impl eframe::App for App {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
if self.frames < 2 {
|
||||
self.frames += 1;
|
||||
// A second frame right away, which means the first was presented: the app is up.
|
||||
ctx.request_repaint();
|
||||
if self.frames == 2 {
|
||||
crash::phase(crash::RUNNING);
|
||||
}
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
if self.app.now - self.autosaved_at >= AUTOSAVE_SECONDS {
|
||||
self.autosaved_at = self.app.now;
|
||||
@@ -93,16 +76,6 @@ impl eframe::App for App {
|
||||
{
|
||||
log::warn!("autosave: {e}");
|
||||
}
|
||||
self.app.usage_closing();
|
||||
if let Some(u) = self.usage.take() {
|
||||
u.finish();
|
||||
}
|
||||
// An update the user chose to install: swapped in now that the window has closed.
|
||||
if let Some(staged) = self.app.take_staged_update() {
|
||||
update::finish(&staged);
|
||||
}
|
||||
log::info!("FieldCraft closed");
|
||||
crash::end_session();
|
||||
}
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(raw);
|
||||
@@ -122,65 +95,9 @@ fn services() -> Services {
|
||||
})),
|
||||
// Beside the recovery folder in the per-user data folder.
|
||||
recent_path: fieldcraft_io::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("recent.json"))),
|
||||
prefs: fieldcraft_io::recovery::default_dir()
|
||||
.and_then(|d| d.parent().map(|p| fieldcraft_ui_egui::files::PrefsStore::file(p.join("prefs.json")))),
|
||||
open_url: Some(Box::new(open_url)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a web link in the default browser, with the system's own opener: `open` (macOS),
|
||||
/// `xdg-open` (Linux and the BSDs), `explorer` (Windows). The link is one argument, never
|
||||
/// passed through a shell. Only https links are opened.
|
||||
fn open_url(url: &str) -> Result<(), String> {
|
||||
if !url.starts_with("https://") {
|
||||
return Err(format!("not a web link: {}", url.chars().take(80).collect::<String>()));
|
||||
}
|
||||
let opener = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let mut child = std::process::Command::new(opener).arg(url).spawn().map_err(|e| format!("{opener}: {e}"))?;
|
||||
// Reaped off the window thread; its exit status says nothing (`explorer` exits with 1 even
|
||||
// when it opened the link).
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Crash reports and the log file (docs/crash-reports.md): reports of earlier runs that crashed
|
||||
/// come back, for the window to offer. Both live in the app's data folder (a temporary one in
|
||||
/// runs driven by automation); `FIELDCRAFT_CRASH_DIR` moves the crash folder.
|
||||
fn start_reporting() -> Vec<crash::Summary> {
|
||||
// First the crash reports: an unclean exit's report takes the dead run's lines from the log.
|
||||
let crashed = crash::default_dir().map(|dir| crash::install(dir, crash::Build::current())).unwrap_or_default();
|
||||
match fieldcraft_io::recovery::data_dir().map(|d| logfile::install(&d.join("logs"), log::LevelFilter::Info)) {
|
||||
Some(Ok(path)) => eprintln!("fieldcraft: log {}", path.display()),
|
||||
Some(Err(e)) => eprintln!("fieldcraft: no log file: {e}"),
|
||||
None => {}
|
||||
}
|
||||
let b = crash::Build::current();
|
||||
log::info!(
|
||||
"FieldCraft {} started ({}), crash reports in {}",
|
||||
b.version,
|
||||
b.version_line(),
|
||||
crash::default_dir().map(|d| d.display().to_string()).unwrap_or_default()
|
||||
);
|
||||
crashed
|
||||
}
|
||||
|
||||
/// egui-wgpu is about to start a step of getting the graphics device and the window's surface
|
||||
/// up: the crash journal keeps it, and the adapter once it is picked (#299).
|
||||
fn startup_step(step: &'static str, detail: &str) {
|
||||
if step == eframe::egui_wgpu::STEP_ADAPTER_CHOSEN {
|
||||
crash::set_environment(&format!("Renderer: {detail}"));
|
||||
}
|
||||
crash::phase(step);
|
||||
}
|
||||
|
||||
/// Command-line options.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Args {
|
||||
@@ -224,8 +141,6 @@ fn parse_args(args: impl IntoIterator<Item = String>, env_port: Option<String>)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// The lattice Boltzmann GPU backend, for `solve.fluid` with `backend: "gpu"`.
|
||||
fieldcraft_lbm_gpu::register();
|
||||
let args = match parse_args(std::env::args().skip(1), std::env::var("FIELDCRAFT_CONTROL_PORT").ok()) {
|
||||
Ok(Some(a)) => a,
|
||||
Ok(None) => return Ok(()),
|
||||
@@ -234,23 +149,9 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if args.control.is_some() {
|
||||
// A run driven by automation keeps its autosaves (and recent files and preferences, which
|
||||
// live beside them), its crash reports and its log in a temporary folder, never the user's.
|
||||
fieldcraft_io::recovery::use_automation_dir();
|
||||
}
|
||||
let crashed = start_reporting();
|
||||
// A crash in native code (a graphics driver) says where it happened: the exception and the
|
||||
// module on Windows, and on every system the startup step the app was in.
|
||||
#[cfg(windows)]
|
||||
native_crash::install();
|
||||
eframe::egui_wgpu::set_startup_hook(startup_step);
|
||||
crash::phase("window");
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
// OneBSpace (OneCAD Simulation): the window title names the fork (the APP_ID, which
|
||||
// the packaged .desktop entries and the bundle id match, stays upstream).
|
||||
.with_title("OneCAD Simulation")
|
||||
.with_title("FieldCraft")
|
||||
.with_app_id(APP_ID)
|
||||
.with_icon(app_icon())
|
||||
.with_inner_size([1400.0, 900.0])
|
||||
@@ -267,46 +168,16 @@ fn main() -> eframe::Result {
|
||||
..Default::default()
|
||||
};
|
||||
eframe::run_native(
|
||||
// OneBSpace (OneCAD Simulation): the app name in the window title.
|
||||
"OneCAD Simulation",
|
||||
"FieldCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
crash::phase("app setup");
|
||||
let mut session = Session::default();
|
||||
// The window's model: its commands go into the crash journal.
|
||||
session.crash_journal = crash::enabled();
|
||||
let mut app = ModelApp::new(session).with_services(services());
|
||||
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
|
||||
let usage = match usage::host(args.control.is_some()) {
|
||||
Some(host) => {
|
||||
app = app.with_usage(host);
|
||||
usage::start()
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// Updates (docs/updates.md): checked at most daily when on, installed only on a click.
|
||||
fieldcraft_engine::enable_update_checks(true);
|
||||
app = app.with_updates(update::host(cc.egui_ctx.clone(), args.control.is_some()));
|
||||
let mut app = ModelApp::new(Session::default()).with_services(services());
|
||||
app.custom_titlebar = CUSTOM_TITLEBAR;
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
log::info!("graphics {:?} {} ({}), MSAA {}x (requested {MSAA}x)", info.backend, info.name, info.driver, rs.msaa_samples);
|
||||
crash::set_environment(&format!("Renderer: {:?} {} ({}), MSAA {}x", info.backend, info.name, info.driver, rs.msaa_samples));
|
||||
crash::phase("viewport pipelines (shader compile)");
|
||||
eprintln!("fieldcraft: graphics {:?} {}, MSAA {}x (requested {MSAA}x)", info.backend, info.name, rs.msaa_samples);
|
||||
app.set_wgpu(rs, DEPTH_BITS, rs.msaa_samples, &cc.egui_ctx);
|
||||
// The graphics driver is loaded now; it may have put its own exception filter
|
||||
// in front of ours.
|
||||
#[cfg(windows)]
|
||||
native_crash::reinstall();
|
||||
}
|
||||
// `kill` or Ctrl-C closes the window as Close does: autosaved, no crash (#248).
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
if let Err(e) = terminate::watch(move || {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
ctx.request_repaint();
|
||||
}) {
|
||||
log::warn!("termination signals: {e}");
|
||||
}
|
||||
if let Some(port) = args.control {
|
||||
app = app.with_control(control_server::start(port, cc.egui_ctx.clone()));
|
||||
@@ -325,9 +196,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
Autosaver::new(&dir).map_err(|e| log::warn!("autosave unavailable: {e}")).ok()
|
||||
});
|
||||
app.announce_crashes(&crashed);
|
||||
crash::phase("first frame");
|
||||
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0, frames: 0, usage }))
|
||||
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0 }))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,290 +0,0 @@
|
||||
//! Windows: what a crash in native code leaves behind (docs/crash-reports.md, #299).
|
||||
//!
|
||||
//! A crash inside a graphics driver or another DLL (an access violation, a stack overflow) is no
|
||||
//! Rust panic: the panic hook never runs and the next start only found "an unclean exit". An
|
||||
//! unhandled-exception filter now writes, before the process goes, a small JSON file with the
|
||||
//! exception code, the faulting module and the offset into it, and a minidump, next to the run's
|
||||
//! crash journal (`fieldcraft_engine::crash::native_paths`). The next start puts both into the
|
||||
//! unclean exit's report, with the startup step the journal says the app was in. Everything that
|
||||
//! can be tested without Windows (reading the file, the report, the startup steps) lives in
|
||||
//! `fieldcraft_engine::crash` and is tested there.
|
||||
//!
|
||||
//! Installing an exception filter and asking the system which module holds an address have no
|
||||
//! safe API, hence the `unsafe_code` allowance on this module, the only one in FieldCraft (the
|
||||
//! app crate denies unsafe code instead of forbidding it for this). The filter runs on a thread
|
||||
//! that may have a broken heap or almost no stack left: it doesn't allocate, formats into a buffer
|
||||
//! on the stack, and skips the minidump after a stack overflow.
|
||||
//!
|
||||
//! Adapted from SolidCraft's `apps/solidcraft/src/native_crash.rs` (MIT OR Apache-2.0), see
|
||||
//! ATTRIBUTION.md.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, GENERIC_WRITE, HANDLE, HMODULE, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::Storage::FileSystem::{CREATE_ALWAYS, CreateFileW, FILE_ATTRIBUTE_NORMAL, WriteFile};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::{
|
||||
EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, MINIDUMP_EXCEPTION_INFORMATION, MiniDumpNormal, MiniDumpWithThreadInfo,
|
||||
MiniDumpWithUnloadedModules, MiniDumpWriteDump, SetUnhandledExceptionFilter,
|
||||
};
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId};
|
||||
|
||||
/// Where the filter writes (NUL-terminated UTF-16), set once by [`install`].
|
||||
struct Paths {
|
||||
info: Vec<u16>,
|
||||
dump: Vec<u16>,
|
||||
}
|
||||
|
||||
static PATHS: OnceLock<Paths> = OnceLock::new();
|
||||
/// The filter that was installed before ours (called after ours), as an address.
|
||||
static PREVIOUS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The filter has started writing (a second exception while it does is left alone).
|
||||
static BUSY: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
const STATUS_ACCESS_VIOLATION: u32 = 0xC000_0005;
|
||||
const STATUS_IN_PAGE_ERROR: u32 = 0xC000_0006;
|
||||
const STATUS_STACK_OVERFLOW: u32 = 0xC000_00FD;
|
||||
|
||||
/// Catch native crashes from now on (after `fieldcraft_engine::crash::install`; nothing without it).
|
||||
pub fn install() {
|
||||
let Some((info, dump)) = fieldcraft_engine::crash::native_paths() else { return };
|
||||
let wide = |p: &Path| p.as_os_str().encode_wide().chain([0]).collect::<Vec<u16>>();
|
||||
if PATHS.set(Paths { info: wide(&info), dump: wide(&dump) }).is_ok() {
|
||||
set_filter();
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the filter back on top: a DLL loaded since (a graphics driver) may have set its own,
|
||||
/// which is then called after ours.
|
||||
pub fn reinstall() {
|
||||
if PATHS.get().is_some() {
|
||||
set_filter();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_filter() {
|
||||
// SAFETY: `filter` has the signature the system calls it with and stays valid for the
|
||||
// process's life.
|
||||
let previous = unsafe { SetUnhandledExceptionFilter(Some(filter)) };
|
||||
if let Some(p) = previous
|
||||
&& p as usize != filter as *const () as usize
|
||||
{
|
||||
PREVIOUS.store(p as usize, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// The unhandled-exception filter: record, then let the previous filter (or the system) go on.
|
||||
unsafe extern "system" fn filter(pointers: *const EXCEPTION_POINTERS) -> i32 {
|
||||
if !BUSY.swap(true, Ordering::SeqCst) {
|
||||
// SAFETY: the system passes valid exception pointers for the duration of the call.
|
||||
unsafe { record(pointers) };
|
||||
}
|
||||
let previous = PREVIOUS.load(Ordering::SeqCst);
|
||||
if previous != 0 && previous != filter as *const () as usize {
|
||||
// SAFETY: the address came from `SetUnhandledExceptionFilter` as a filter of this type.
|
||||
let previous: unsafe extern "system" fn(*const EXCEPTION_POINTERS) -> i32 = unsafe { std::mem::transmute(previous) };
|
||||
// SAFETY: as for this filter.
|
||||
return unsafe { previous(pointers) };
|
||||
}
|
||||
EXCEPTION_CONTINUE_SEARCH
|
||||
}
|
||||
|
||||
/// A fixed buffer to format into without allocating (what doesn't fit is cut off).
|
||||
struct Buf {
|
||||
bytes: [u8; 2048],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Write for Buf {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
let room = self.bytes.len().saturating_sub(self.len);
|
||||
let n = s.len().min(room);
|
||||
if let (Some(to), Some(from)) = (self.bytes.get_mut(self.len..self.len + n), s.as_bytes().get(..n)) {
|
||||
to.copy_from_slice(from);
|
||||
self.len += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The usual names of the exception codes a crash shows.
|
||||
fn code_name(code: u32) -> &'static str {
|
||||
match code {
|
||||
STATUS_ACCESS_VIOLATION => "EXCEPTION_ACCESS_VIOLATION",
|
||||
STATUS_IN_PAGE_ERROR => "EXCEPTION_IN_PAGE_ERROR",
|
||||
STATUS_STACK_OVERFLOW => "EXCEPTION_STACK_OVERFLOW",
|
||||
0xC000_001D => "EXCEPTION_ILLEGAL_INSTRUCTION",
|
||||
0xC000_0094 => "EXCEPTION_INT_DIVIDE_BY_ZERO",
|
||||
0xC000_0096 => "EXCEPTION_PRIV_INSTRUCTION",
|
||||
0xC000_008C => "EXCEPTION_ARRAY_BOUNDS_EXCEEDED",
|
||||
0xC000_0374 => "STATUS_HEAP_CORRUPTION",
|
||||
0xC000_0409 => "STATUS_STACK_BUFFER_OVERRUN",
|
||||
0xC000_0602 => "STATUS_FAIL_FAST_EXCEPTION",
|
||||
0x8000_0003 => "EXCEPTION_BREAKPOINT",
|
||||
0xE06D_7363 => "C++ exception",
|
||||
_ => "exception",
|
||||
}
|
||||
}
|
||||
|
||||
/// Write what `pointers` says into the info file, then the minidump.
|
||||
unsafe fn record(pointers: *const EXCEPTION_POINTERS) {
|
||||
let Some(paths) = PATHS.get() else { return };
|
||||
if pointers.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: checked non-null; the system keeps it valid during the filter.
|
||||
let rec = unsafe { (*pointers).ExceptionRecord };
|
||||
if rec.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let rec = unsafe { &*rec };
|
||||
let code = rec.ExceptionCode as u32;
|
||||
let address = rec.ExceptionAddress as usize;
|
||||
let mut module: HMODULE = std::ptr::null_mut();
|
||||
let mut name = [0u16; 512];
|
||||
// SAFETY: FROM_ADDRESS takes the address in place of a name; UNCHANGED_REFCOUNT means no
|
||||
// handle to release; `name` is as long as we say.
|
||||
let len = unsafe {
|
||||
if GetModuleHandleExW(
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
address as *const u16,
|
||||
&mut module,
|
||||
) != 0
|
||||
{
|
||||
GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32) as usize
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
// SAFETY: no preconditions.
|
||||
let thread = unsafe { GetCurrentThreadId() };
|
||||
let mut b = Buf { bytes: [0; 2048], len: 0 };
|
||||
let _ = write!(b, "{{\"code\":\"0x{code:08X}\",\"name\":\"{}\",\"address\":\"0x{address:016X}\",\"thread\":{thread}", code_name(code));
|
||||
if len > 0 {
|
||||
let _ = write!(b, ",\"offset\":\"0x{:X}\",\"module\":\"", address.wrapping_sub(module as usize));
|
||||
for c in char::decode_utf16(name.iter().take(len).copied()) {
|
||||
let _ = match c.unwrap_or(char::REPLACEMENT_CHARACTER) {
|
||||
'"' => b.write_str("\\\""),
|
||||
'\\' => b.write_str("\\\\"),
|
||||
c if (c as u32) < 0x20 => b.write_str("?"),
|
||||
c => b.write_char(c),
|
||||
};
|
||||
}
|
||||
let _ = b.write_str("\"");
|
||||
}
|
||||
if matches!(code, STATUS_ACCESS_VIOLATION | STATUS_IN_PAGE_ERROR) && rec.NumberParameters >= 2 {
|
||||
let what = match rec.ExceptionInformation[0] {
|
||||
0 => "read of",
|
||||
1 => "write to",
|
||||
8 => "execution at",
|
||||
_ => "access to",
|
||||
};
|
||||
let _ = write!(b, ",\"detail\":\"{what} 0x{:016X}\"", rec.ExceptionInformation[1]);
|
||||
}
|
||||
let _ = b.write_str("}");
|
||||
let bytes = b.bytes.get(..b.len).unwrap_or_default();
|
||||
// SAFETY: NUL-terminated path; the handle is closed below.
|
||||
unsafe {
|
||||
let file = create(&paths.info);
|
||||
if !file.is_null() {
|
||||
let mut written = 0u32;
|
||||
WriteFile(file, bytes.as_ptr(), bytes.len() as u32, &mut written, std::ptr::null_mut());
|
||||
CloseHandle(file);
|
||||
}
|
||||
}
|
||||
// After a stack overflow there is no stack left for writing a minidump.
|
||||
if code == STATUS_STACK_OVERFLOW {
|
||||
return;
|
||||
}
|
||||
// SAFETY: as above; the exception information points at this thread's exception.
|
||||
unsafe {
|
||||
let file = create(&paths.dump);
|
||||
if !file.is_null() {
|
||||
let exception = MINIDUMP_EXCEPTION_INFORMATION { ThreadId: thread, ExceptionPointers: pointers as *mut _, ClientPointers: 0 };
|
||||
MiniDumpWriteDump(
|
||||
GetCurrentProcess(),
|
||||
GetCurrentProcessId(),
|
||||
file,
|
||||
MiniDumpNormal | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules,
|
||||
&exception,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
);
|
||||
CloseHandle(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A new file at `path` (NUL-terminated) for writing, or null.
|
||||
unsafe fn create(path: &[u16]) -> HANDLE {
|
||||
// SAFETY: the caller passes a NUL-terminated path.
|
||||
let h = unsafe { CreateFileW(path.as_ptr(), GENERIC_WRITE, 0, std::ptr::null(), CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, std::ptr::null_mut()) };
|
||||
if h == INVALID_HANDLE_VALUE { std::ptr::null_mut() } else { h }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The child half: install crash reporting and the filter, then fault in native code.
|
||||
#[test]
|
||||
fn child() {
|
||||
let Some(dir) = std::env::var_os("FIELDCRAFT_NATIVE_CRASH_CHILD") else { return };
|
||||
let build = fieldcraft_engine::crash::Build { version: "9.9.9", commit: "abc1234" };
|
||||
let fresh = fieldcraft_engine::crash::install(PathBuf::from(dir), build);
|
||||
println!("FRESH {}", serde_json::to_string(&fresh).unwrap_or_default());
|
||||
if std::env::var_os("FIELDCRAFT_NATIVE_CRASH_FAULT").is_none() {
|
||||
fieldcraft_engine::crash::end_session();
|
||||
return;
|
||||
}
|
||||
super::install();
|
||||
fieldcraft_engine::crash::phase("device creation");
|
||||
// SAFETY: none; this is the crash under test (a read of address 16, as a null struct
|
||||
// pointer's field would be).
|
||||
let v = unsafe { std::ptr::read_volatile(16 as *const u64) };
|
||||
println!("unreachable {v}");
|
||||
}
|
||||
|
||||
fn run(dir: &std::path::Path, fault: bool) -> std::process::Output {
|
||||
let mut c = std::process::Command::new(std::env::current_exe().unwrap());
|
||||
c.args(["--exact", "native_crash::tests::child", "--test-threads=1", "--nocapture"]).env("FIELDCRAFT_NATIVE_CRASH_CHILD", dir);
|
||||
if fault {
|
||||
c.env("FIELDCRAFT_NATIVE_CRASH_FAULT", "1");
|
||||
}
|
||||
c.output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_access_violation_is_reported_with_its_module_step_and_minidump() {
|
||||
let dir = std::env::temp_dir().join(format!("fieldcraft-native-crash-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let out = run(&dir, true);
|
||||
assert_eq!(out.status.code().map(|c| c as u32), Some(super::STATUS_ACCESS_VIOLATION), "{out:?}");
|
||||
let sessions: Vec<PathBuf> = std::fs::read_dir(dir.join("sessions")).unwrap().flatten().map(|e| e.path()).collect();
|
||||
let info = sessions.iter().find(|p| p.to_string_lossy().ends_with(".native.json")).expect("the filter wrote what it caught");
|
||||
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(info).unwrap()).unwrap();
|
||||
assert_eq!(v["code"], "0xC0000005", "{v}");
|
||||
assert_eq!(v["detail"], "read of 0x0000000000000010", "{v}");
|
||||
assert!(v["module"].as_str().unwrap().to_lowercase().contains("fieldcraft"), "the fault is in the test binary: {v}");
|
||||
let dump = sessions.iter().find(|p| p.extension().is_some_and(|e| e == "dmp")).expect("a minidump");
|
||||
assert_eq!(std::fs::read(dump).unwrap().get(..4), Some(&b"MDMP"[..]));
|
||||
// The next start reports it.
|
||||
let out = run(&dir, false);
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
let reports = fieldcraft_engine::crash::list(&dir);
|
||||
assert_eq!(reports.len(), 1, "{reports:?}");
|
||||
let r = fieldcraft_engine::crash::read(&dir, &reports[0].id).unwrap();
|
||||
assert!(r["message"].as_str().unwrap().contains("EXCEPTION_ACCESS_VIOLATION (0xC0000005) in fieldcraft"), "{r}");
|
||||
assert!(r["message"].as_str().unwrap().contains("during startup (device creation"), "{r}");
|
||||
assert!(r.get("minidump_path").is_some(), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
//! A request to terminate (SIGTERM, SIGINT on Unix) closes the window the normal way.
|
||||
//!
|
||||
//! Without this, `kill PID`, Ctrl-C in the terminal, a system shutdown or a test harness's timeout
|
||||
//! ended the process on the spot: no `on_exit`, so no last autosave and no clean end of the crash
|
||||
//! journal, and the next start filed an `unclean_exit` crash report for what was no crash (#248:
|
||||
//! "ended without a clean exit between commands (last: control ui.capture)" was an automation run
|
||||
//! stopped with SIGTERM after its capture). Now the first signal asks the window to close, which
|
||||
//! autosaves, ends the journal and exits as a click on Close does; the journal notes the signal,
|
||||
//! so a run that still dies while closing says why. A second signal, for a window that does not
|
||||
//! close, ends the process at once with the signal's default action.
|
||||
//!
|
||||
//! SIGHUP is left alone: `nohup fieldcraft &` ignores it on purpose so the app outlives its
|
||||
//! terminal, and a handler would override that (a safe API cannot ask whether a signal was
|
||||
//! ignored at launch).
|
||||
//!
|
||||
//! Windows has no such signals: a window there is closed through its messages, which eframe
|
||||
//! already turns into a normal close.
|
||||
|
||||
use std::io;
|
||||
|
||||
/// The signals that ask the app to terminate.
|
||||
#[cfg(unix)]
|
||||
const SIGNALS: [i32; 2] = [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT];
|
||||
|
||||
/// The signal's usual name, for the log and the crash journal.
|
||||
#[cfg(unix)]
|
||||
fn name(signal: i32) -> &'static str {
|
||||
match signal {
|
||||
signal_hook::consts::SIGTERM => "SIGTERM",
|
||||
signal_hook::consts::SIGINT => "SIGINT",
|
||||
_ => "signal",
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `close` (on a thread of its own) on the first termination signal; a second one ends the
|
||||
/// process with the signal's default action.
|
||||
#[cfg(unix)]
|
||||
pub fn watch(close: impl Fn() + Send + 'static) -> io::Result<()> {
|
||||
let mut signals = signal_hook::iterator::Signals::new(SIGNALS)?;
|
||||
std::thread::Builder::new().name("terminate".into()).spawn(move || {
|
||||
let mut asked = false;
|
||||
for signal in signals.forever() {
|
||||
if asked {
|
||||
log::warn!("{}: the window did not close; ending now", name(signal));
|
||||
if let Err(e) = signal_hook::low_level::emulate_default_handler(signal) {
|
||||
log::error!("{}: {e}", name(signal));
|
||||
std::process::exit(128 + signal);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
asked = true;
|
||||
log::info!("{}: closing", name(signal));
|
||||
fieldcraft_engine::crash::activity(&format!("terminating ({})", name(signal)));
|
||||
close();
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Nothing to watch without Unix signals.
|
||||
#[cfg(not(unix))]
|
||||
pub fn watch(_close: impl Fn() + Send + 'static) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc;
|
||||
|
||||
use fieldcraft_engine::crash;
|
||||
|
||||
/// The child half: start crash reporting as the app does, then get SIGTERM. With the watcher
|
||||
/// the "window" (here the main thread) closes the normal way; without it the process dies.
|
||||
#[test]
|
||||
fn child() {
|
||||
let Some(dir) = std::env::var_os("FIELDCRAFT_TERMINATE_CHILD") else { return };
|
||||
let build = crash::Build { version: "9.9.9", commit: "abc1234" };
|
||||
let fresh = crash::install(PathBuf::from(dir), build);
|
||||
if std::env::var_os("FIELDCRAFT_TERMINATE_NEXT").is_some() {
|
||||
// The next start: what it reports of the run before.
|
||||
println!("FRESH {}", fresh.iter().map(|s| s.message.as_str()).collect::<Vec<_>>().join(" | "));
|
||||
crash::end_session();
|
||||
return;
|
||||
}
|
||||
crash::activity("control ui.capture");
|
||||
if std::env::var_os("FIELDCRAFT_TERMINATE_WATCH").is_some() {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
super::watch(move || {
|
||||
let _ = tx.send(());
|
||||
})
|
||||
.unwrap();
|
||||
signal_hook::low_level::raise(signal_hook::consts::SIGTERM).unwrap();
|
||||
// What `on_exit` does once the window has closed.
|
||||
rx.recv().unwrap();
|
||||
crash::end_session();
|
||||
println!("CLOSED");
|
||||
return;
|
||||
}
|
||||
signal_hook::low_level::raise(signal_hook::consts::SIGTERM).unwrap();
|
||||
// Not reached: SIGTERM's default action ends the process.
|
||||
std::thread::sleep(std::time::Duration::from_secs(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigterm_closes_cleanly_and_leaves_no_crash_report() {
|
||||
let root = std::env::temp_dir().join(format!("fieldcraft-terminate-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let run = |dir: &Path, mode: &str| {
|
||||
let mut c = std::process::Command::new(std::env::current_exe().unwrap());
|
||||
c.args(["--exact", "terminate::tests::child", "--test-threads=1", "--nocapture"]).env("FIELDCRAFT_TERMINATE_CHILD", dir);
|
||||
match mode {
|
||||
"watch" => c.env("FIELDCRAFT_TERMINATE_WATCH", "1"),
|
||||
"next" => c.env("FIELDCRAFT_TERMINATE_NEXT", "1"),
|
||||
_ => &mut c,
|
||||
};
|
||||
c.output().unwrap()
|
||||
};
|
||||
// What the next start in `dir` reports of the run before.
|
||||
let reported_at_next_start = |dir: &Path| {
|
||||
let out = run(dir, "next");
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
stdout.lines().find_map(|l| l.split_once("FRESH ").map(|(_, r)| r.trim().to_string())).unwrap_or_else(|| panic!("{stdout}"))
|
||||
};
|
||||
|
||||
// Without the watcher (the bug): killed, and the journal it leaves reads as a crash.
|
||||
let unwatched = root.join("unwatched");
|
||||
let out = run(&unwatched, "kill");
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
assert_eq!(out.status.signal(), Some(signal_hook::consts::SIGTERM), "{out:?}");
|
||||
let reported = reported_at_next_start(&unwatched);
|
||||
assert!(reported.contains("ended without a clean exit") && reported.contains("control ui.capture"), "{reported}");
|
||||
|
||||
// With it: the close runs, the journal ends, and nothing is reported as a crash.
|
||||
let watched = root.join("watched");
|
||||
let out = run(&watched, "watch");
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("CLOSED"), "{out:?}");
|
||||
assert_eq!(reported_at_next_start(&watched), "");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
//! The desktop app's side of updates (docs/updates.md): it runs the window's update jobs
|
||||
//! ([`fieldcraft_ui_egui::updates`]) on background threads with [`fieldcraft_update`], and swaps
|
||||
//! a staged release in after the window has closed ([`finish`]).
|
||||
//!
|
||||
//! Automatic checks are off in runs driven by automation (`--control`) and under CI, so test
|
||||
//! and agent runs never reach GitHub on their own; `FIELDCRAFT_UPDATE_HOST` (a local test
|
||||
//! server) turns them back on. Help › Check for Updates works in every run.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc;
|
||||
|
||||
use fieldcraft_ui_egui::updates::{Event, Job, UpdateHost};
|
||||
use fieldcraft_update::install::{self, Finish, Install};
|
||||
use fieldcraft_update::net::{Client, Which};
|
||||
use fieldcraft_update::stage::{self, Options};
|
||||
use fieldcraft_update::{Release, Staged};
|
||||
|
||||
/// What the window needs for updates.
|
||||
pub fn host(ctx: egui::Context, automation: bool) -> UpdateHost {
|
||||
let here = install::here();
|
||||
log::info!("updates: {}", here.describe());
|
||||
stage::clean_stale(&here);
|
||||
let env = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
|
||||
let automatic = env(fieldcraft_update::HOST_ENV) || !(automation || env("CI"));
|
||||
let (tx, events) = mpsc::channel::<Event>();
|
||||
let unsupported = here.unsupported();
|
||||
let start = move |job: Job| {
|
||||
let (tx, ctx, here) = (tx.clone(), ctx.clone(), here.clone());
|
||||
let spawned = std::thread::Builder::new().name("fieldcraft update".into()).spawn(move || {
|
||||
let send = |e: Event| {
|
||||
let _ = tx.send(e);
|
||||
ctx.request_repaint();
|
||||
};
|
||||
let client = Client::from_env();
|
||||
match job {
|
||||
Job::Check { manual } => send(Event::Checked { manual, result: client.check().map_err(|e| e.to_string()) }),
|
||||
Job::Stage(release) => send(Event::Staged(stage_release(&client, &release, &here, &send))),
|
||||
Job::Reinstall => {
|
||||
let staged = client
|
||||
.release(&Which::Version(fieldcraft_update::current()))
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|r| stage_release(&client, &r, &here, &send));
|
||||
send(Event::Staged(staged));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("updates: no thread: {e}");
|
||||
}
|
||||
};
|
||||
UpdateHost { unsupported, automatic, start: Box::new(start), events, now: Box::new(now), open_file: Box::new(open_file) }
|
||||
}
|
||||
|
||||
/// Download, verify and stage `release`, reporting each whole percent.
|
||||
fn stage_release(client: &Client, release: &Release, here: &Install, send: &dyn Fn(Event)) -> Result<Staged, String> {
|
||||
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
|
||||
let last = Cell::new(u64::MAX);
|
||||
let progress = |done: u64, total: u64| {
|
||||
let step = done.saturating_mul(100).checked_div(total).unwrap_or(done / (1024 * 1024));
|
||||
if last.replace(step) != step {
|
||||
send(Event::Progress(done, total));
|
||||
}
|
||||
};
|
||||
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
|
||||
let staged = stage::stage(client, release, here, &options).map_err(|e| e.to_string());
|
||||
match &staged {
|
||||
Ok(s) => log::info!("updates: FieldCraft {} verified and staged at {}", s.version, s.payload.display()),
|
||||
Err(e) => log::warn!("updates: FieldCraft {} not staged: {e}", release.version),
|
||||
}
|
||||
staged
|
||||
}
|
||||
|
||||
/// Swap `staged` in and start it: the window has closed, its autosave is closed.
|
||||
pub fn finish(staged: &Staged) {
|
||||
match install::plan(staged, true) {
|
||||
Ok(Finish::Swap(plan)) => match stage::apply(&plan) {
|
||||
Ok(()) => log::info!("updates: FieldCraft {} installed ({})", staged.version, staged.install.describe()),
|
||||
Err(e) => log::error!("updates: FieldCraft {} not installed, the previous version is kept: {e}", staged.version),
|
||||
},
|
||||
Ok(Finish::Package { .. }) => {}
|
||||
Err(e) => log::error!("updates: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since the Unix epoch.
|
||||
fn now() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Open a downloaded package with the system's handler for it (Linux: the software installer).
|
||||
fn open_file(path: &Path) -> Result<(), String> {
|
||||
let opener = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let mut child = std::process::Command::new(opener).arg(path).spawn().map_err(|e| format!("{opener}: {e}"))?;
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
//! Sending the anonymous usage events (docs/privacy.md) to PostHog Cloud EU: a background
|
||||
//! thread posts the queued events ([`fieldcraft_engine::usage`]) in batches every half minute and
|
||||
//! when the window closes. A failed post (offline, a slow network) drops its batch silently;
|
||||
//! nothing waits on it but the thread.
|
||||
//!
|
||||
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`, which only the release workflow
|
||||
//! sets: local, development and fork builds have none and send nothing.
|
||||
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use fieldcraft_engine::usage;
|
||||
use fieldcraft_ui_egui::privacy::UsageHost;
|
||||
|
||||
/// The PostHog project key the release build was made with.
|
||||
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
|
||||
/// How often queued events are sent.
|
||||
const INTERVAL: Duration = Duration::from_secs(30);
|
||||
/// The longest one post may take.
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// How long closing the window waits for the last batch.
|
||||
const LAST_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
fn key() -> Option<&'static str> {
|
||||
KEY.map(str::trim).filter(|k| !k.is_empty())
|
||||
}
|
||||
|
||||
/// What the window needs to ask and record, when this run may share usage: the build has a key,
|
||||
/// `FIELDCRAFT_TELEMETRY` is not `0`, and neither CI nor `--control` automation runs it (unless
|
||||
/// `FIELDCRAFT_TELEMETRY=1`).
|
||||
pub fn host(automation: bool) -> Option<UsageHost> {
|
||||
let telemetry = std::env::var("FIELDCRAFT_TELEMETRY").ok();
|
||||
let ci = std::env::var_os("CI").is_some_and(|v| !v.is_empty());
|
||||
usage::allowed(key().is_some(), telemetry.as_deref(), automation, ci).then(|| UsageHost {
|
||||
platform: "desktop",
|
||||
os: std::env::consts::OS,
|
||||
arch: std::env::consts::ARCH,
|
||||
new_id: Box::new(new_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// A random (version 4) UUID from the operating system's random source.
|
||||
fn new_id() -> Option<String> {
|
||||
let mut b = [0u8; 16];
|
||||
getrandom::fill(&mut b).ok()?;
|
||||
b[6] = (b[6] & 0x0f) | 0x40;
|
||||
b[8] = (b[8] & 0x3f) | 0x80;
|
||||
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
|
||||
Some(format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]))
|
||||
}
|
||||
|
||||
/// The sending thread; [`Sender::finish`] sends what is left and stops it.
|
||||
pub struct Sender {
|
||||
stop: mpsc::Sender<()>,
|
||||
finished: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
/// Start the sending thread (only when the build has a key). `FIELDCRAFT_TELEMETRY_HOST`
|
||||
/// replaces PostHog's host, for checking the payload against a local listener.
|
||||
pub fn start() -> Option<Sender> {
|
||||
let key = key()?;
|
||||
let host = std::env::var("FIELDCRAFT_TELEMETRY_HOST").ok().filter(|h| !h.trim().is_empty()).unwrap_or_else(|| usage::DEFAULT_HOST.into());
|
||||
let url = format!("{}/batch/", host.trim_end_matches('/'));
|
||||
// rustls's process-wide crypto (ring); another part of the app may have installed it first.
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(TIMEOUT))
|
||||
.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build())
|
||||
.build()
|
||||
.into();
|
||||
let (stop, stopped) = mpsc::channel::<()>();
|
||||
let (done, finished) = mpsc::channel::<()>();
|
||||
let spawned = std::thread::Builder::new().name("fieldcraft usage".into()).spawn(move || {
|
||||
loop {
|
||||
let last = !matches!(stopped.recv_timeout(INTERVAL), Err(mpsc::RecvTimeoutError::Timeout));
|
||||
while let Some(batch) = usage::take_batch() {
|
||||
if let Err(e) = agent.post(&url).header("Content-Type", "application/json").send(batch.body(key)) {
|
||||
// Offline or refused: this batch is dropped, the rest waits for the next try.
|
||||
log::debug!("usage: {} event(s) not sent: {e}", batch.events.len());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if last {
|
||||
let _ = done.send(());
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
match spawned {
|
||||
Ok(_) => Some(Sender { stop, finished }),
|
||||
Err(e) => {
|
||||
log::warn!("usage: no sending thread: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sender {
|
||||
/// Send what is queued (waiting briefly) and stop.
|
||||
pub fn finish(self) {
|
||||
let _ = self.stop.send(());
|
||||
let _ = self.finished.recv_timeout(LAST_WAIT);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn install_ids_are_random_version_4_uuids() {
|
||||
let (a, b) = (super::new_id().unwrap(), super::new_id().unwrap());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 36);
|
||||
assert_eq!(a.as_bytes()[14], b'4');
|
||||
assert!(matches!(a.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), "{a}");
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>diagnostics.bug_report</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 8.5 L12 8.5 C14.209 8.5 16 10.291 16 12.5 L16 15.5 C16 17.709 14.209 19.5 12 19.5 L12 19.5 C9.791 19.5 8 17.709 8 15.5 L8 12.5 C8 10.291 9.791 8.5 12 8.5 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9.9 5.8 C9.9 4.64 10.84 3.7 12 3.7 C13.16 3.7 14.1 4.64 14.1 5.8 C14.1 6.96 13.16 7.9 12 7.9 C10.84 7.9 9.9 6.96 9.9 5.8 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 10.5 L12 18" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 11.5 L4.8 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 14.5 L4.4 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8.3 17.4 L5 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16 11.5 L19.2 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16 14.5 L19.6 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15.7 17.4 L19 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.6 KiB |
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.check</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M9 3 L16 6.5 L16 13 L9 16.5 L2 13 L2 6.5 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M2 6.5 L9 10 L16 6.5 M9 10 L9 16.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M2 6.5 L2 9.5" fill="none" stroke="#f0b44a" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.5 17 C13.5 15.067 15.067 13.5 17 13.5 C18.933 13.5 20.5 15.067 20.5 17 C20.5 18.933 18.933 20.5 17 20.5 C15.067 20.5 13.5 18.933 13.5 17 Z" fill="none" stroke="#4f9ce8" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M19.5 19.5 L22 22" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.datum.axis</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M7 17 L19 5" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M20 4 L15 5.2 M20 4 L18.8 9" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M5.5 18.5 L2.5 21.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
|
||||
<path d="M8.8 12 C8.8 10.233 10.233 8.8 12 8.8 C13.767 8.8 15.2 10.233 15.2 12 C15.2 13.767 13.767 15.2 12 15.2 C10.233 15.2 8.8 13.767 8.8 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10.6 12 C10.6 11.227 11.227 10.6 12 10.6 C12.773 10.6 13.4 11.227 13.4 12 C13.4 12.773 12.773 13.4 12 13.4 C11.227 13.4 10.6 12.773 10.6 12 Z" fill="#f0b44a"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.datum.point</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 16 L9 10 L21 10 L15 16 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 3 L12 11 M8 7 L16 7" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10.2 7 C10.2 6.006 11.006 5.2 12 5.2 C12.994 5.2 13.8 6.006 13.8 7 C13.8 7.994 12.994 8.8 12 8.8 C11.006 8.8 10.2 7.994 10.2 7 Z" fill="#f0b44a"/>
|
||||
<path d="M12 12.5 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 846 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.defeature</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L3 16 L12 20 L12 12 M12 20 L21 16 L21 8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9 8 C9 8.828 10.343 9.5 12 9.5 C13.657 9.5 15 8.828 15 8 C15 7.172 13.657 6.5 12 6.5 C10.343 6.5 9 7.172 9 8 Z" fill="#f0b44a" stroke="#f0b44a" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 11 L16.5 5" fill="none" stroke="#4f9ce8" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 886 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.face.absorb</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L3 16 L12 20 L12 12 M12 20 L21 16 L21 8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14.5 5.1 L17 6.2 L8 10.3 L5.5 9.2 Z" fill="#f0b44a" stroke="#f0b44a" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="none" stroke="#4f9ce8" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 823 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.face.split</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L3 16 L12 20 L12 12 M12 20 L21 16 L21 8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 10 L16.5 6" fill="none" stroke="#f0b44a" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M5 4.5 L9 2.5 M15 9.5 L19 7.5" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 1.5"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 845 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.faces.merge</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L3 16 L12 20 L12 12 M12 20 L21 16 L21 8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 6 L16.5 10" fill="none" stroke="#f0b44a" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
|
||||
<path d="M3 8 L12 4 L21 8 L12 12 Z" fill="none" stroke="#4f9ce8" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 844 B |
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.stitch</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 6 L10.5 6 L10.5 18 L3 18 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.5 6 L21 6 L21 18 L13.5 18 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9 8.5 L15 8.5" fill="none" stroke="#f0b44a" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9 12 L15 12" fill="none" stroke="#f0b44a" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9 15.5 L15 15.5" fill="none" stroke="#f0b44a" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 923 B |
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.block</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M4 6 L16 3 L20 15 L8 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 5 L12.33 16.33 M12 4 L16.67 17.67 M5.33 10.33 L17.33 7 M6.67 14.67 L18.67 11" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 559 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.export.stl</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 9 L9 5 L15 9 L9 13 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 9 L3 17 L9 21 L9 13 M9 21 L15 17 L15 9" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 9 L9 21 M9 13 L15 17" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15 15 L21 15 M18.19 16.53 L21 15 L18.19 13.47" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 817 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.cells</title>
|
||||
<title>mesh.hex.blocks</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
|
Before Width: | Height: | Size: 1003 B After Width: | Height: | Size: 1008 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.extrude</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M6 20 L18 20 L18 11.6 C14 9.467 10 9.467 6 11.6 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M6 17.2 L18 17.2 M6 14.4 C10 12.8 14 12.8 18 14.4 M10 20 L10 9.9 M14 20 L14 9.9" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 9.2 C9 5.333 15 5.333 21 9.2" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 6 L12 3 M10.5 4.5 L12 3 L13.5 4.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 879 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.generate</title>
|
||||
<title>mesh.hex.mapped</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
|
Before Width: | Height: | Size: 884 B After Width: | Height: | Size: 882 B |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.sweep</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 8 L12 17 L3 17 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 8 L7.5 17 M3 12.5 L12 12.5" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L8 4 L21 4 L21 13 L12 17 M12 8 L21 4" fill="none" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 13 L20 10 M18.17 12.63 L20 10 L16.8 9.88" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 825 B |
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.mirror</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 2 L12 22" fill="none" stroke="#4f9ce8" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="2 1.5"/>
|
||||
<path d="M10 5 L3 7 L3 17 L10 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 12 L10 12 M6.5 6 L6.5 18" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 5 L21 7 L21 17 L14 19 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 12 L21 12 M17.5 6 L17.5 18" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 923 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.node.move</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M5 4 L19 4 C19.552 4 20 4.448 20 5 L20 19 C20 19.552 19.552 20 19 20 L5 20 C4.448 20 4 19.552 4 19 L4 5 C4 4.448 4.448 4 5 4 Z" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 12 L20 12 M12 4 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 12 L15 9 L20 12 M12 4 L15 9 L12 20" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.2 9 C13.2 8.006 14.006 7.2 15 7.2 C15.994 7.2 16.8 8.006 16.8 9 C16.8 9.994 15.994 10.8 15 10.8 C14.006 10.8 13.2 9.994 13.2 9 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1022 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.node.relax</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 12 C3 7.029 7.029 3 12 3 C16.971 3 21 7.029 21 12 C21 16.971 16.971 21 12 21 C7.029 21 3 16.971 3 12 Z" fill="none" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="2 2"/>
|
||||
<path d="M5 12 L19 12 M12 5 L12 19" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 8 L16.5 8 M7.5 16 L16.5 16 M8 7.5 L8 16.5 M16 7.5 L16 16.5" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9.6 12 C9.6 10.675 10.675 9.6 12 9.6 C13.325 9.6 14.4 10.675 14.4 12 C14.4 13.325 13.325 14.4 12 14.4 C10.675 14.4 9.6 13.325 9.6 12 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1017 B |
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.plan</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 11.5 L12 15.5 L20 11.5 M8 9 L8 18 M16 9 L16 18" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 3 L12 5.4 M20 7 L15.2 7 M12 11 L12 8.6 M4 7 L8.8 7" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8.8 7 C8.8 7.884 10.233 8.6 12 8.6 C13.767 8.6 15.2 7.884 15.2 7 C15.2 6.116 13.767 5.4 12 5.4 C10.233 5.4 8.8 6.116 8.8 7 Z" fill="none" stroke="#f0b44a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.quality.mark</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 3 L11 3 L11 11 L3 11 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13 3 L21 3 L21 11 L13 11 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 13 L11 13 L11 21 L3 21 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13 14 L21 13 L20 21 L14 19 Z" fill="#f0b44a" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 822 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.seed.edge</title>
|
||||
<title>mesh.size.seed</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 19 C7 5 17 5 21 19" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M1.7 19 C1.7 18.282 2.282 17.7 3 17.7 C3.718 17.7 4.3 18.282 4.3 19 C4.3 19.718 3.718 20.3 3 20.3 C2.282 20.3 1.7 19.718 1.7 19 Z" fill="#4f9ce8"/>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.size.set</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 3 L21 3 L21 21 L3 21 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 3 L12 21 M3 12 L21 12" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 12 L21 12 L21 21 L12 21 Z" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16.5 12 L16.5 21 M12 16.5 L21 16.5" fill="none" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 777 B |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.transition</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 4 L21 4 L21 20 L3 20 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 4 L7.5 20 M3 9.33 L12 9.33 M3 14.67 L12 14.67" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 4 L21 9.33 L12 14.67 L21 20 M12 14.67 L21 14.67 M12 4 L21 4" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 4 L12 20" fill="none" stroke="#4f9ce8" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 816 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>results.export.vtu</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M4 3 L12 3 L16 7 L16 21 L4 21 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 3 L12 7 L16 7" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7 17 L7 14 M10 17 L10 11 M13 17 L13 13" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15 15 L21 15 M18.19 16.53 L21 15 L18.19 13.47" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 837 B |
@@ -1 +0,0 @@
|
||||
{"shapes": [{"rect": [8, 8.5, 8, 11], "radius": 4, "stroke": "line", "width": 1.6}, {"circle": [12, 5.8, 2.1], "stroke": "line", "width": 1.6}, {"line": [12, 10.5, 12, 18], "stroke": "accent", "width": 1.5}, {"line": [8, 11.5, 4.8, 9.8], "stroke": "line"}, {"line": [8, 14.5, 4.4, 14.5], "stroke": "line"}, {"line": [8.3, 17.4, 5, 19.4], "stroke": "line"}, {"line": [16, 11.5, 19.2, 9.8], "stroke": "line"}, {"line": [16, 14.5, 19.6, 14.5], "stroke": "line"}, {"line": [15.7, 17.4, 19, 19.4], "stroke": "line"}]}
|
||||
@@ -1 +0,0 @@
|
||||
{"shapes": [{"d": "M9 3 L16 6.5 L16 13 L9 16.5 L2 13 L2 6.5 Z", "fill": "soft", "stroke": "line"}, {"d": "M2 6.5 L9 10 L16 6.5 M9 10 L9 16.5", "stroke": "line"}, {"line": [2, 6.5, 2, 9.5], "stroke": "warm", "width": 2.25}, {"circle": [17, 17, 3.5], "stroke": "accent", "width": 1.75}, {"line": [19.5, 19.5, 22, 22], "stroke": "accent", "width": 2}]}
|
||||
@@ -1 +0,0 @@
|
||||
{"shapes": [{"d": "M7 17 L19 5", "stroke": "accent", "width": 2}, {"d": "M20 4 L15 5.2 M20 4 L18.8 9", "stroke": "accent", "width": 2}, {"d": "M5.5 18.5 L2.5 21.5", "stroke": "line", "dash": [1.5, 2]}, {"circle": [12, 12, 3.2], "fill": "soft", "stroke": "line", "width": 1.25}, {"circle": [12, 12, 1.4], "fill": "warm", "stroke": null}]}
|
||||
@@ -1 +0,0 @@
|
||||
{"shapes": [{"d": "M3 16 L9 10 L21 10 L15 16 Z", "fill": "soft", "stroke": "line", "width": 1.25}, {"d": "M12 3 L12 11 M8 7 L16 7", "stroke": "accent", "width": 2}, {"circle": [12, 7, 1.8], "fill": "warm", "stroke": null}, {"d": "M12 12.5 L12 20", "stroke": "line", "dash": [1.5, 2]}]}
|
||||