mirror of
https://github.com/storytold/soundcraft.git
synced 2026-11-28 08:44:05 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a19d9f3d39 | ||
|
|
3911c7e5d3 |
@@ -1,16 +0,0 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -1,107 +0,0 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/soundcraft",
|
||||
"repository_id": 1408486424,
|
||||
"producer_workflow_id": 429730684,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "soundcraft-nightly-20261124",
|
||||
"repository": "storytold/soundcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 380135771,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_soundcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_soundcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
name: Nightly build check
|
||||
|
||||
# Builds the isolated Nightly flavor on all three platforms without secrets and checks each
|
||||
# archive as the Launcher unpacks it. The real feed build and its signing live in the shared
|
||||
# producer and release-ref signer (craft-common-actions), which call the same app scripts; this
|
||||
# workflow exists so the three packaging paths are exercised on PRs and by hand.
|
||||
#
|
||||
# macOS runners are shared with release builds: the macOS leg runs only with the `full-ci` label
|
||||
# (as ci.yml's Windows legs), never by changed paths.
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a labelled PR cancels its older run. An event that will not build gets a group of
|
||||
# its own, so it never cancels a real build.
|
||||
concurrency:
|
||||
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Nightly Linux x86_64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the desktop build dependencies
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "SOUNDCRAFT_BUILD_SHA=$sha"
|
||||
echo "SOUNDCRAFT_BUILD_DATE=$date"
|
||||
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the GUI-only Nightly tar
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: bash packaging/linux/nightly.sh --arch x86_64
|
||||
- name: Check the archive and the isolated launch protocol
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tz="$(mktemp -d)"
|
||||
archive="$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
|
||||
mkdir -p "$tz" && tar -xzf "$archive" -C "$tz"
|
||||
# Flat, allowlisted members only: the launcher, the GUI it starts, the Nightly icon and
|
||||
# the notices.
|
||||
members="$(tar -tzf "$archive" | grep -v '/$' | sort | tr '\n' ' ')"
|
||||
echo "$members"
|
||||
case "$members" in *soundcraft-cli*|*portable.txt*|*.desktop*) echo 'GUI-only tar contains a CLI, marker or desktop entry' >&2; exit 1;; esac
|
||||
test -x "$tz/soundcraft"
|
||||
test -x "$tz/soundcraft-bin"
|
||||
# The entry point is the launcher; the GUI beside it is what a launch starts with the
|
||||
# profile, so an unpacked tar is isolated too.
|
||||
head -n 1 "$tz/soundcraft" | grep -qx '#!/bin/sh' || { echo 'soundcraft is not the launcher' >&2; exit 1; }
|
||||
test -f "$tz/soundcraft-nightly.png"
|
||||
# The version query, plain and in the Launcher's form, with an empty environment (a shell
|
||||
# script needs PATH for dirname/readlink even when everything else is cleared).
|
||||
path=/usr/local/bin:/usr/bin:/bin
|
||||
home="$(mktemp -d)"; profile="$(mktemp -d)"; xdg="$(mktemp -d)"
|
||||
plain="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" XDG_DATA_HOME="$xdg/d" XDG_CACHE_HOME="$xdg/k" XDG_STATE_HOME="$xdg/s" "$tz/soundcraft" --version)"
|
||||
test "$plain" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "plain query: $plain" >&2; exit 1; }
|
||||
launcher="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$profile" --version)"
|
||||
test "$launcher" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "launcher query: $launcher" >&2; exit 1; }
|
||||
# A native package refuses a Flatpak instance with exit status 2 (the same status whether or
|
||||
# not a display exists), and no stable folder is created.
|
||||
status=0
|
||||
env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" FLATPAK_ID=ai.storyteller.soundcraft "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$(mktemp -d)/p" -- >/dev/null 2>&1 || status=$?
|
||||
test "$status" -eq 2 || { echo "a Flatpak instance must be refused with exit status 2, got $status" >&2; exit 1; }
|
||||
# Look where the configured XDG folders actually point, not at $xdg/config and $xdg/data.
|
||||
for dir in "$xdg/c" "$xdg/d" "$xdg/k" "$xdg/s"; do test ! -e "$dir/soundcraft" || { echo "stable folder created: $dir/soundcraft" >&2; exit 1; }; done
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-linux-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
windows:
|
||||
name: Nightly Windows x86_64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$inPkg = $false
|
||||
$base = $null
|
||||
foreach ($line in Get-Content Cargo.toml) {
|
||||
if ($line -match '^\s*\[') { $inPkg = ($line.Trim() -eq '[workspace.package]'); continue }
|
||||
if ($inPkg -and $line -match '^\s*version\s*=\s*"([^"]+)"') { $base = $Matches[1].Split('-')[0]; break }
|
||||
}
|
||||
if (-not $base) { throw 'could not read [workspace.package] version from Cargo.toml' }
|
||||
$sha = (git rev-parse HEAD).Trim()
|
||||
$date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd')
|
||||
$version = "$base-nightly.$($date.Replace('-','')).$env:GITHUB_RUN_NUMBER.$env:GITHUB_RUN_ATTEMPT.g$($sha.Substring(0,12))"
|
||||
"SOUNDCRAFT_BUILD_SHA=$sha" >> $env:GITHUB_ENV
|
||||
"SOUNDCRAFT_BUILD_DATE=$date" >> $env:GITHUB_ENV
|
||||
"SOUNDCRAFT_VERSION=$version" >> $env:GITHUB_ENV
|
||||
- name: Refuse signing material in the build environment
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/sign.ps1 -CheckBuildEnvironment
|
||||
- name: Build the GUI-only Nightly intermediate
|
||||
shell: pwsh
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly
|
||||
- name: Check the PE, the version and the archive payload
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$exe = Join-Path $env:RUNNER_TEMP 'nightly-targets/x86_64-pc-windows-msvc/release/soundcraft.exe'
|
||||
$bytes = [IO.File]::ReadAllBytes($exe)
|
||||
$pe = [BitConverter]::ToInt32($bytes, 0x3C)
|
||||
if ([BitConverter]::ToUInt16($bytes, $pe + 4) -ne 0x8664) { throw 'not an x86_64 executable' }
|
||||
if ([BitConverter]::ToUInt16($bytes, $pe + 0x5C) -ne 2) { throw 'not a Windows GUI subsystem executable' }
|
||||
$info = (Get-Item -LiteralPath $exe).VersionInfo
|
||||
if ($info.ProductName -ne 'SoundCraft Nightly') { throw "ProductName: $($info.ProductName)" }
|
||||
if ($info.ProductVersion -cne $env:SOUNDCRAFT_VERSION) { throw "ProductVersion: $($info.ProductVersion)" }
|
||||
$version = (& $exe --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $version -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "version query: $version" }
|
||||
$profile = Join-Path $env:RUNNER_TEMP 'nightly-profile'
|
||||
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
||||
$launcher = (& $exe --launch-profile nightly-v1 --profile-root $profile --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $launcher -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "launcher query: $launcher" }
|
||||
# A Nightly build without its profile is refused before any window (exit status 2). The
|
||||
# refusal dialog would need a desktop, so that path is covered by the Rust unit tests.
|
||||
$zip = Join-Path $env:RUNNER_TEMP "nightly-dist/soundcraft-$env:SOUNDCRAFT_VERSION-windows-x86_64-nightly.unsigned.zip"
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
|
||||
try {
|
||||
$names = @($archive.Entries | ForEach-Object { $_.FullName })
|
||||
if ('soundcraft.exe' -notin $names) { throw 'no soundcraft.exe in the archive' }
|
||||
foreach ($forbidden in @('soundcraft-cli.exe', 'portable.txt', '.desktop')) {
|
||||
if (@($names | Where-Object { $_ -like "*$forbidden*" }).Count -ne 0) { throw "archive holds $forbidden" }
|
||||
}
|
||||
} finally { $archive.Dispose() }
|
||||
- name: Fixture suites
|
||||
shell: pwsh
|
||||
run: |
|
||||
./packaging/windows/nightly-package-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-fixtures')
|
||||
./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-sign-fixtures')
|
||||
- name: Keep the unsigned intermediate
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-windows-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
macos:
|
||||
name: Nightly macOS aarch64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "SOUNDCRAFT_BUILD_SHA=$sha"
|
||||
echo "SOUNDCRAFT_BUILD_DATE=$date"
|
||||
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly bundle
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Check the archive and the bundle's version
|
||||
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-macos-aarch64-nightly.zip"
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-macos-aarch64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-macos-aarch64-nightly.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
@@ -1,45 +0,0 @@
|
||||
name: SoundCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: soundcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: soundcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -1,34 +0,0 @@
|
||||
name: SoundCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and a reviewed dispatcher with it).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: soundcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -1,20 +0,0 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -49,23 +49,3 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-synthetic-suites:
|
||||
# The macOS and Windows Nightly scripts, the flat Linux archive and its launchers, and the
|
||||
# shared caller contracts run as generated fixtures in seconds: no app build, no signing, no
|
||||
# secrets.
|
||||
name: Nightly synthetic suites (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites, the launcher tests and bash -n
|
||||
run: bash packaging/nightly-checks.sh
|
||||
|
||||
@@ -10,11 +10,3 @@ plan/
|
||||
/craft-fonts/
|
||||
plans/
|
||||
.DS_Store
|
||||
|
||||
__pycache__/
|
||||
|
||||
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
/craft-fonts
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Accessibility
|
||||
|
||||
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
|
||||
|
||||
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
|
||||
|
||||
## Supported environments and how accessibility works
|
||||
|
||||
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
|
||||
|
||||
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
|
||||
- **macOS:** NSAccessibility (VoiceOver)
|
||||
- **Linux and FreeBSD:** AT-SPI (Orca)
|
||||
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
|
||||
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
|
||||
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
|
||||
|
||||
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
|
||||
|
||||
## Known limitations and workarounds
|
||||
|
||||
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
|
||||
|
||||
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
|
||||
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
|
||||
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
|
||||
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
|
||||
|
||||
See [This application](#this-application) below for repository-specific links and details.
|
||||
|
||||
## Reporting an accessibility barrier
|
||||
|
||||
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
|
||||
|
||||
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
|
||||
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
|
||||
- **Helpful details to share (when convenient):**
|
||||
- What you were trying to do, what happened, and what you expected
|
||||
- Application version (or commit) and operating system or browser
|
||||
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
|
||||
|
||||
## How we respond
|
||||
|
||||
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
|
||||
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
|
||||
|
||||
## Note for contributors and coding agents
|
||||
|
||||
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
|
||||
|
||||
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
|
||||
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
|
||||
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
|
||||
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
|
||||
|
||||
## Ownership
|
||||
|
||||
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
|
||||
|
||||
## This application
|
||||
|
||||
**SoundCraft** (`storytold/soundcraft`) is an open-source digital audio workstation (DAW) written in pure Rust.
|
||||
|
||||
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
|
||||
- **Command-line and automation interface:** `soundcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
|
||||
- **Report an accessibility barrier:** [Open an issue in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues/new)
|
||||
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
|
||||
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
|
||||
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
|
||||
@@ -81,7 +81,6 @@ Layers, checked by `cargo xtask layers`; nothing below L6 depends on egui, efram
|
||||
- Audio formats, codecs and waveform peaks come from `craft-audio` in `storytold/craft-libs`; `soundcraft_model::FileFormat` maps them onto the session model.
|
||||
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`), each module with its own `specs()` registered in `crates/engine/src/cmd.rs`; UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Menus, shortcuts, CLI, control channel and MCP dispatch the same ids. Panels act through `engine.execute(id, params)`. Programmatic calls open no dialogs; `ui.menu.invoke` does.
|
||||
- Parity: `crates/engine/catalog/menus.txt` lists the reference menu leaves; `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): the parity report marks a leaf `headless: yes` only when the engine registry implements it (what `soundcraft-cli` and the MCP server load); the UI layer's `parity_with` extras never count. Other leaves take their `no`/`partial` value and `reach:` (`window`, `os`, `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or read `unknown`. When a command lands, drop or narrow its mark; `headless_marks_are_current` fails on one that only hides a `yes`.
|
||||
- Progress docs: `ROADMAP.md`, `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md` and the per-area `docs/*-parity.md`. Releases: `docs/releasing.md` (push to `release`; `cargo xtask version [set X.Y.Z]`). Control protocol: `docs/control-protocol.md`.
|
||||
|
||||
### Checks
|
||||
|
||||
@@ -54,8 +54,4 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts
|
||||
| `assets/app-icon/soundcraft.icns` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft.ico` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/hicolor/` | SoundCraft contributors | original, rendered from `icon.svg` (16–512 px PNGs and the scalable SVG) | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly-macos-512.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.icns` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.ico` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `docs/images/` | SoundCraft contributors | screenshots of SoundCraft rendered from the synthesised demo session | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+80
-1292
File diff suppressed because it is too large
Load Diff
+28
-35
@@ -11,9 +11,9 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/soundcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
# internal
|
||||
soundcraft-interchange = { path = "crates/interchange" }
|
||||
soundcraft-time = { path = "crates/time" }
|
||||
@@ -61,34 +61,27 @@ cpal = "0.18"
|
||||
midir = "=0.11.1"
|
||||
|
||||
# Which file paths stored in a session may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
|
||||
# Video containers and bitstreams, shared with the other craft apps.
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
# H.264 and ProRes codecs shared with the other Craft apps.
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
|
||||
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
|
||||
# types with craft-media, so both stay on one rev.
|
||||
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
|
||||
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["serde"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["decode", "lossless-encode", "peaks", "serde"] }
|
||||
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["decode", "lossless-encode", "peaks", "serde"] }
|
||||
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
# AAF property-stream framing, shared with the other craft apps.
|
||||
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["egui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
|
||||
# the framework's components draw in (craft-libs).
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
|
||||
egui = { version = "0.37" }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -131,18 +124,18 @@ debug = 0
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -88,7 +88,7 @@ where things are.
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Automation and markers.</b> Breakpoint automation for volume, pan, mute, sends and every plugin parameter, written live in Write, Touch and Latch, plus memory locations and a big counter.</td>
|
||||
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64 and ARM64), Linux (AppImage, deb, rpm, Flatpak, Arch), FreeBSD, and a WebAssembly build that runs in the browser.</td>
|
||||
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64, x86, Arm), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, and a WebAssembly build that runs in the browser.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img alt="The Video window showing a colour-bar test movie with a timecode burn-in, above a Video track with thumbnails in the Edit window" src="docs/images/video.png"></td>
|
||||
@@ -302,9 +302,7 @@ very welcome, in the issues or on Discord.
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `soundcraft-<ver>-windows-x64.msi` | `soundcraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `soundcraft-<ver>-windows-arm64.msi` | `soundcraft-<ver>-windows-arm64-portable.zip` |
|
||||
|
||||
For 32-bit Windows, [SoundCraft v0.18.0](https://github.com/storytold/soundcraft/releases/tag/v0.18.0)
|
||||
was the last release with both an x86 MSI and portable ZIP.
|
||||
| x86 (32-bit) | `soundcraft-<ver>-windows-x86.msi` | `soundcraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
Installers and executables are code-signed.
|
||||
|
||||
@@ -342,19 +340,15 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
|
||||
| Flatpak | `soundcraft-<ver>-linux-x86_64.flatpak` | `soundcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `soundcraft-<ver>-linux-x86_64.deb` | `soundcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `soundcraft-<ver>-linux-x86_64.rpm` | `soundcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Arch Linux | `soundcraft-<ver>-linux-x86_64.pkg.tar.zst` | `soundcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
|
||||
| Tarball | `soundcraft-<ver>-linux-x86_64.tar.gz` | `soundcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
|
||||
`soundcraft-<ver>-linux-riscv64.rpm`, and `soundcraft-<ver>-linux-riscv64.tar.gz`
|
||||
(glibc 2.39+, e.g. Ubuntu 24.04).
|
||||
RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc 2.39+, e.g. Ubuntu 24.04).
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
| aarch64 (ARM64) | `soundcraft-<ver>-freebsd-aarch64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
@@ -362,24 +356,6 @@ RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
|
||||
|---|---|---|
|
||||
| Static site | `soundcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
|
||||
### Nightly (ArtCraft Launcher only)
|
||||
|
||||
A separate build channel, `nightly-v1`, ships untested previews of main. It is a different app
|
||||
with a different identity, installed and updated by ArtCraft Launcher:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Package, macOS bundle and Linux identity | `ai.storyteller.soundcraft.nightly` |
|
||||
| Window app id and Windows taskbar id | `ai.storyteller.soundcraft.nightly-v1` |
|
||||
| Data (settings, autosaves, presets, logs) | the Launcher's `profiles/soundcraft` folder, never the stable one |
|
||||
| Launch | `soundcraft --launch-profile nightly-v1 --profile-root <dir> -- <files>` |
|
||||
| Version | `soundcraft --version` → `SoundCraft <x.y.z>-nightly.<date>.<run>.<attempt>.g<sha12> (nightly-v1)` |
|
||||
|
||||
It carries no updater, control server or file associations, and it refuses to start without its
|
||||
profile. Build artifacts are `soundcraft-<ver>-{windows-x86_64-nightly.zip,linux-x86_64-nightly.tar.gz,macos-aarch64-nightly.zip}`,
|
||||
made by `packaging/windows/nightly.ps1`, `packaging/linux/nightly.sh` and `packaging/macos/nightly.sh`;
|
||||
see `docs/nightly-release-preparation.md`. Nothing is enabled yet.
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
SoundCraft is one of the **Crafting Apps**: free, open-source creative tools from the
|
||||
|
||||
@@ -22,8 +22,6 @@ fn is_control_method(method: &str) -> bool {
|
||||
| "ui.move"
|
||||
| "ui.click"
|
||||
| "ui.drag"
|
||||
| "ui.scroll"
|
||||
| "ui.zoom"
|
||||
| "ui.key"
|
||||
| "ui.text"
|
||||
| "ui.screenshot"
|
||||
@@ -70,11 +68,5 @@ mod tests {
|
||||
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
|
||||
assert_eq!(app_request(method, json!({})).0, method);
|
||||
}
|
||||
for (method, params) in [
|
||||
("ui.scroll", json!({"x": 120, "y": 80, "dx": 5, "dy": -15, "unit": "line"})),
|
||||
("ui.zoom", json!({"x": 120, "y": 80, "factor": 1.5, "steps": 4})),
|
||||
] {
|
||||
assert_eq!(app_request(method, params.clone()), (method.to_string(), params));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ fn write_help() -> &'static str {
|
||||
|
||||
/// soundcraft-cli: SoundCraft without a window
|
||||
#[derive(Parser)]
|
||||
#[command(name = "soundcraft-cli", version = long_version(), propagate_version = true, arg_required_else_help = true)]
|
||||
#[command(name = "soundcraft-cli", version = long_version(), arg_required_else_help = true)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
|
||||
@@ -40,12 +40,9 @@ pub(crate) fn parity(args: &ParityArgs, out: &mut dyn Write) -> Result<(), CliEr
|
||||
for m in p["per_menu"].as_array().cloned().unwrap_or_default() {
|
||||
md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"]));
|
||||
}
|
||||
md.push_str(&format!("\n{}\n", soundcraft_engine::catalog::headless_summary_line(&p)));
|
||||
md.push_str("A leaf the engine implements is `headless: yes`: `soundcraft-cli` and the MCP server load that registry. The rest carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n");
|
||||
md.push_str("\n## Not yet implemented\n\n");
|
||||
for m in p["headless_missing"].as_array().cloned().unwrap_or_default() {
|
||||
let reach = m["reach"].as_str().map(|r| format!(", reach: {r} ({})", m["why"].as_str().unwrap_or(""))).unwrap_or_default();
|
||||
md.push_str(&format!("- {}: headless: {}{reach}\n", m["path"].as_str().unwrap_or(""), m["headless"].as_str().unwrap_or("")));
|
||||
for m in p["missing"].as_array().cloned().unwrap_or_default() {
|
||||
md.push_str(&format!("- {}\n", m.as_str().unwrap_or("")));
|
||||
}
|
||||
if let Some(path) = &args.write {
|
||||
std::fs::write(path, &md).map_err(|source| CliError::File { path: path.clone(), source })?;
|
||||
|
||||
@@ -73,11 +73,10 @@ fn at_rate(pos: u64, from: u32, to: u32) -> u64 {
|
||||
fn write_replacing(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
let name = target.file_name().map_or_else(|| "output".into(), |n| n.to_string_lossy().into_owned());
|
||||
let tmp = target.with_file_name(format!(".{name}.{}.part", std::process::id()));
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let written = (|| {
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
std::fs::rename(&tmp, target)
|
||||
})();
|
||||
if written.is_err() {
|
||||
|
||||
@@ -29,24 +29,6 @@ use info::info;
|
||||
use mcp::mcp;
|
||||
use session::{run_cmds, script};
|
||||
|
||||
/// A Launcher-only protocol argument, in either the separate or the `=` form. Everything after
|
||||
/// `--` is a file name, so it is not inspected.
|
||||
fn launcher_protocol_flag(args: &[OsString]) -> Option<&'static str> {
|
||||
for arg in args {
|
||||
if arg == "--" {
|
||||
break;
|
||||
}
|
||||
let text = arg.to_string_lossy();
|
||||
if text == "--launch-profile" || text.starts_with("--launch-profile=") {
|
||||
return Some("--launch-profile");
|
||||
}
|
||||
if text == "--profile-root" || text.starts_with("--profile-root=") {
|
||||
return Some("--profile-root");
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The command line's clap definition.
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
@@ -62,12 +44,6 @@ where
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
// The Launcher's Nightly protocol belongs to the GUI alone. Refuse it here, with a usage error,
|
||||
// before the subcommand is parsed: `soundcraft-cli` never opens a profile root or a window.
|
||||
if let Some(flag) = launcher_protocol_flag(&args) {
|
||||
let _ = writeln!(err, "soundcraft-cli: {flag} belongs to SoundCraft Nightly; this is the command-line tool");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
@@ -105,31 +81,3 @@ fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Resul
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod launcher_protocol_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_launcher_only_protocol_is_a_usage_error_not_a_file() {
|
||||
for args in [
|
||||
vec!["--launch-profile", "nightly-v1", "--profile-root", "/tmp/profile", "--", "song.scraft"],
|
||||
vec!["--launch-profile=nightly-v1"],
|
||||
vec!["--profile-root=/tmp/profile"],
|
||||
vec!["convert", "in.wav", "--launch-profile", "nightly-v1"],
|
||||
] {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = run(args.iter().map(OsString::from), &mut out, &mut err);
|
||||
assert_eq!(code, 2, "{args:?}");
|
||||
let message = String::from_utf8_lossy(&err);
|
||||
assert!(message.contains("SoundCraft Nightly"), "{args:?}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_after_the_delimiter_is_a_file_name() {
|
||||
let args: Vec<OsString> = ["convert", "--", "--launch-profile", "--profile-root=./x"].map(OsString::from).to_vec();
|
||||
assert_eq!(launcher_protocol_flag(&args), None);
|
||||
assert_eq!(launcher_protocol_flag(&[OsString::from("--profile-root"), OsString::from("/p")]), Some("--profile-root"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,6 @@ pub(crate) fn run_cmds(args: &RunArgs, out: &mut dyn Write, err: &mut dyn Write)
|
||||
pub(crate) fn script(args: &ScriptArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let path = &args.file;
|
||||
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||
let mut e = load_engine(&args.engine, err)?;
|
||||
let keep = args.keep_going;
|
||||
let mut failed = false;
|
||||
|
||||
@@ -89,19 +89,6 @@ fn version_flags_print_the_long_version_to_stdout() {
|
||||
}
|
||||
}
|
||||
|
||||
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
|
||||
/// return without running it (`mcp` and `app` would otherwise wait on something).
|
||||
#[test]
|
||||
fn every_subcommand_prints_the_version() {
|
||||
let release = format!("{} ({} {})\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
|
||||
for sub in ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins"] {
|
||||
for spelling in ["--version", "-V"] {
|
||||
let got = invoke(&[sub, spelling]);
|
||||
assert_eq!((got.code, got.stdout, got.stderr), (0, format!("soundcraft-cli-{sub} {release}"), String::new()), "{sub} {spelling}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_is_not_a_subcommand() {
|
||||
assert_usage_error(&invoke(&["version"]), "unrecognized subcommand 'version'");
|
||||
|
||||
@@ -26,15 +26,6 @@ fn invoke(dir: &Path, args: &[&str]) -> Output {
|
||||
Command::new(crate::common::soundcraft_cli_binary()).current_dir(dir).env("SOUNDCRAFT_NO_PREFS", "1").args(args).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_accepts_a_leading_utf8_bom() {
|
||||
let dir = Scratch::new();
|
||||
std::fs::write(dir.0.join("bom.txt"), "\u{feff}track.new {\"name\":\"BOM\",\"count\":1,\"format\":\"stereo\"}\n").unwrap();
|
||||
let output = invoke(&dir.0, &["script", "bom.txt"]);
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("track.new:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_going_runs_later_commands_and_finishes_but_reports_failure() {
|
||||
let dir = Scratch::new();
|
||||
|
||||
@@ -49,7 +49,6 @@ pub fn start() {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
log::info!("soundcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
|
||||
}
|
||||
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
|
||||
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
|
||||
let app = SoundApp::new(engine, Some(player), Services::default());
|
||||
@@ -225,14 +224,12 @@ impl eframe::App for WebShell {
|
||||
self.app.logic(ctx);
|
||||
// A prompt opened during this frame becomes a picker on the next one.
|
||||
self.take_path_prompt(ctx);
|
||||
self.app.close_path(ctx);
|
||||
}
|
||||
|
||||
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
|
||||
/// shell.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
|
||||
@@ -48,5 +48,3 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["NSAppl
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# The Nightly flavor's explicit taskbar identity (process_identity.rs); stable sets none.
|
||||
winsafe = { version = "0.0.29", features = ["user", "shell"] }
|
||||
|
||||
@@ -4,70 +4,26 @@
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `SOUNDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
//!
|
||||
//! `SOUNDCRAFT_BUILD_CHANNEL=nightly-v1` compiles the isolated Nightly flavor: `cfg(soundcraft_nightly_v1)`,
|
||||
//! the Nightly icon, `ProductName "SoundCraft Nightly"` and the exact feed version as
|
||||
//! `ProductVersion` (the Launcher checks that field, not FileVersion). An unset, empty or `stable`
|
||||
//! channel is the stable build; anything else is a build error.
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(soundcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("SOUNDCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=soundcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported SOUNDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_VERSION");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_OVERRIDE_VERSION");
|
||||
let built_version = if nightly {
|
||||
// The feed identity is SOUNDCRAFT_VERSION. The packaging scripts (packaging/env.sh and the
|
||||
// Linux package.sh, inherited from PhotoCraft) set the same value as
|
||||
// SOUNDCRAFT_OVERRIDE_VERSION, which is accepted as the one alias so both agree.
|
||||
let identity = std::env::var("SOUNDCRAFT_VERSION").or_else(|_| std::env::var("SOUNDCRAFT_OVERRIDE_VERSION"));
|
||||
match identity {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit SOUNDCRAFT_VERSION feed identity (SOUNDCRAFT_OVERRIDE_VERSION is accepted)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=SOUNDCRAFT_BUILT_VERSION={built_version}");
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "SoundCraft Nightly" } else { "SoundCraft" })
|
||||
.set("FileDescription", if nightly { "SoundCraft Nightly digital audio workstation" } else { "SoundCraft digital audio workstation" })
|
||||
res.set_icon("../../assets/app-icon/soundcraft.ico")
|
||||
.set("ProductName", "SoundCraft")
|
||||
.set("FileDescription", "SoundCraft digital audio workstation")
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the SoundCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "soundcraft.exe")
|
||||
.set("InternalName", "soundcraft");
|
||||
if nightly {
|
||||
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
|
||||
panic!("embedding Windows resources failed: {e}");
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
println!("cargo:warning=soundcraft.exe built without icon/version resources: {e}");
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/soundcraft-nightly.ico" } else { "../../assets/app-icon/soundcraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/soundcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/soundcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.20.1-nightly.20261124.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.20.1",
|
||||
"0.20.1-nightly",
|
||||
"0.20.1-nightly.20261124",
|
||||
"0.20.1-nightly.20261124.17.1.gABCDEF012345",
|
||||
"0.20.1-nightly.20261124.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.20.1-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.20.1-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.20.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(soundcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open SoundCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable SoundCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.20.1"), "0.20.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,8 @@ use soundcraft_ui_egui::docking;
|
||||
|
||||
/// Portable mode (#268): this file beside the executable keeps settings, autosaves, presets and
|
||||
/// logs in [`PORTABLE_DATA_DIR`] next to it instead of the user profile.
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
|
||||
/// The portable marker in `dir`, if it is a regular file (never a link or a directory).
|
||||
pub(crate) fn portable_marker(dir: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
let marker = dir.join(PORTABLE_MARKER);
|
||||
std::fs::symlink_metadata(&marker).ok().filter(|m| m.file_type().is_file()).map(|_| marker)
|
||||
}
|
||||
const PORTABLE_MARKER: &str = "portable.txt";
|
||||
const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Platform {
|
||||
@@ -38,17 +32,10 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
|
||||
Platform::Other
|
||||
};
|
||||
let exe = std::env::current_exe().ok();
|
||||
// The one place a validated Nightly profile replaces every data root: ui.json, Autosave/,
|
||||
// Presets/ and logs/ all hang off this folder, before any of them is first used.
|
||||
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent), crate::launch_profile::current().root())
|
||||
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent))
|
||||
}
|
||||
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
|
||||
// The compiled Nightly flavor cannot run without a profile (`build_flavor::require_profile`),
|
||||
// so this is the complete settings folder and never falls back to Stable data.
|
||||
if let Some(root) = nightly {
|
||||
return Some(root.to_path_buf());
|
||||
}
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
if let Some(dir) = env(crate::env::CONFIG_DIR) {
|
||||
return (!dir.is_empty()).then(|| PathBuf::from(dir));
|
||||
}
|
||||
@@ -68,26 +55,12 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, e
|
||||
}
|
||||
}
|
||||
|
||||
/// Create `dir` if needed and prove a file can be written in it. The Nightly profile validator
|
||||
/// injects this same exclusive probe.
|
||||
///
|
||||
/// The probe never replaces an existing entry: `create_new` cannot truncate one, and a name that is
|
||||
/// already taken (an interrupted run, or a file someone else made) is left untouched while the next
|
||||
/// name is tried. Only a file this call created is removed again.
|
||||
pub(crate) fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
/// Create `dir` if needed and prove a file can be written in it.
|
||||
fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
for attempt in 0..8u32 {
|
||||
let probe = dir.join(format!(".write-test-{}-{attempt}", std::process::id()));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
return std::fs::remove_file(probe);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name"))
|
||||
let probe = dir.join(format!(".write-test-{}", std::process::id()));
|
||||
std::fs::write(&probe, b"")?;
|
||||
std::fs::remove_file(probe)
|
||||
}
|
||||
|
||||
/// Read bounded settings, recovering unreadable docking metadata independently of other settings.
|
||||
@@ -183,16 +156,10 @@ mod config_tests {
|
||||
app.ui = load_ui(&path).unwrap().unwrap();
|
||||
assert_eq!(app.ui.theme, soundcraft_ui_egui::theme::ThemeMode::Light);
|
||||
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), edit);
|
||||
assert_eq!(
|
||||
app.ui.mix_docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
|
||||
egui::Rect::from_min_size(egui::pos2(140.0, 150.0), egui::vec2(280.0, 420.0))
|
||||
);
|
||||
assert_eq!(app.ui.mix_docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [140.0, 150.0, 280.0, 420.0]);
|
||||
app.ui.window = MainWindow::Edit;
|
||||
app.run("ui.dock", serde_json::json!({"operation":"open","panel":"tracks"})).unwrap();
|
||||
assert_eq!(
|
||||
app.ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
|
||||
egui::Rect::from_min_size(egui::pos2(80.0, 90.0), egui::vec2(260.0, 400.0))
|
||||
);
|
||||
assert_eq!(app.ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [80.0, 90.0, 260.0, 400.0]);
|
||||
let mut invalid_mix = app.ui.clone();
|
||||
invalid_mix.mix_docking = soundcraft_ui_egui::docking::edit_default();
|
||||
let invalid_bytes = serde_json::to_vec(&invalid_mix).unwrap();
|
||||
@@ -284,7 +251,7 @@ mod config_tests {
|
||||
}
|
||||
|
||||
fn resolve(platform: Platform, vars: &[(&str, &str)]) -> Option<PathBuf> {
|
||||
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None)
|
||||
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -297,7 +264,6 @@ mod config_tests {
|
||||
Some(OsString::from("isolated/settings"))
|
||||
},
|
||||
None,
|
||||
None,
|
||||
);
|
||||
assert_eq!(actual, Some(PathBuf::from("isolated/settings")));
|
||||
}
|
||||
@@ -313,7 +279,6 @@ mod config_tests {
|
||||
assert_eq!(name, "SOUNDCRAFT_CONFIG_DIR");
|
||||
Some(OsString::new())
|
||||
},
|
||||
None,
|
||||
None
|
||||
),
|
||||
None
|
||||
@@ -353,33 +318,7 @@ mod config_tests {
|
||||
}
|
||||
|
||||
fn resolve_with_exe(vars: &[(&str, &str)], exe: &Path) -> Option<PathBuf> {
|
||||
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_validated_nightly_profile_replaces_every_settings_root() {
|
||||
let nightly = PathBuf::from("/launcher/profiles/soundcraft");
|
||||
let vars = [("SOUNDCRAFT_CONFIG_DIR", "/custom"), ("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")];
|
||||
for platform in [Platform::Mac, Platform::Windows, Platform::Other] {
|
||||
let dir = config_dir_with(
|
||||
platform,
|
||||
|name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))),
|
||||
None,
|
||||
Some(&nightly),
|
||||
);
|
||||
assert_eq!(dir, Some(nightly.clone()), "the profile wins over the variable and the platform default");
|
||||
}
|
||||
// Even an empty override variable cannot take the Nightly settings folder away.
|
||||
let dir = config_dir_with(Platform::Other, |_| Some(OsString::new()), None, Some(&nightly));
|
||||
assert_eq!(dir, Some(nightly.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stable_channel_keeps_its_own_resolution() {
|
||||
let vars = [("XDG_CONFIG_HOME", "/xdg")];
|
||||
let dir =
|
||||
config_dir_with(Platform::Other, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None);
|
||||
assert_eq!(dir, Some(PathBuf::from("/xdg/soundcraft")));
|
||||
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -387,6 +326,6 @@ mod config_tests {
|
||||
fn config_override_preserves_non_unicode_paths() {
|
||||
use std::os::unix::ffi::OsStringExt as _;
|
||||
let value = OsString::from_vec(b"isolated/\xff".to_vec());
|
||||
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None, None), Some(PathBuf::from(value)));
|
||||
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None), Some(PathBuf::from(value)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,14 +40,6 @@ pub(crate) fn command() -> Command {
|
||||
LaunchArgs::command().mut_args(blank_env_is_unset)
|
||||
}
|
||||
|
||||
/// The command line for the selected channel. A Nightly window never inherits the stable
|
||||
/// `SOUNDCRAFT_CONTROL_PORT` variable: its control server is not started and the Launcher owns
|
||||
/// its lifecycle, so only its file list is meaningful.
|
||||
pub(crate) fn command_for_profile(nightly: bool) -> Command {
|
||||
let cmd = command();
|
||||
if nightly { cmd.mut_arg("control", |arg| arg.env(None)) } else { cmd }
|
||||
}
|
||||
|
||||
/// Parses the launch arguments (without the program name) with `cmd`, from [`command`]. macOS
|
||||
/// passes a process serial number (`-psn_…`) when an app is started from Finder on old versions:
|
||||
/// it is dropped first, unless it comes after `--`. A bad value from a variable is a usage error
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old portable/config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
// SoundCraft keeps no Documents agent folder and has no craft-settings data/cache roots: one
|
||||
// settings folder holds ui.json, Autosave/, Presets/ and logs/, and `config::writable` is the
|
||||
// app's existing exclusive write probe.
|
||||
crate::profile_root::validate(root, env, exe, crate::config::writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\soundcraft" } else { "/nightly-data/profiles/soundcraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
@@ -166,13 +166,7 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
// Control characters are written escaped: a message quoting a session file (a plugin id, a
|
||||
// path) must not start a line of its own in the log or steer the terminal.
|
||||
let mut escaped = String::with_capacity(message.len());
|
||||
for c in message.chars() {
|
||||
if c.is_control() { escaped.extend(c.escape_default()) } else { escaped.push(c) }
|
||||
}
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {escaped}\n")
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
|
||||
}
|
||||
|
||||
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
|
||||
|
||||
@@ -158,15 +158,8 @@ fn a_line_carries_time_level_thread_target_and_message() {
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "soundcraft_mix", "eq_7band: the plugin did not accept its stored state"),
|
||||
"2026-10-08T07:59:17.728Z WARN [main] soundcraft_mix: eq_7band: the plugin did not accept its stored state\n"
|
||||
);
|
||||
// A message with breaks of its own stays one record; the record still ends in exactly one newline.
|
||||
assert!(
|
||||
format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\\nb\n"),
|
||||
"a break inside the message is escaped, the final one dropped"
|
||||
);
|
||||
assert!(
|
||||
format_line("t", log::Level::Error, "w", "x", "plugin \u{1b}[2J\r\n2026 INFO forged")
|
||||
.ends_with("x: plugin \\u{1b}[2J\\r\\n2026 INFO forged\n")
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in exactly one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+24
-187
@@ -11,27 +11,20 @@
|
||||
#![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)]
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod config;
|
||||
mod control_server;
|
||||
mod env;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod graphics;
|
||||
mod launch_args;
|
||||
mod launch_profile;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod switch;
|
||||
|
||||
use env::Env;
|
||||
use soundcraft_engine::Engine;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs, os_window};
|
||||
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct App(SoundApp, Option<&'static logging::AppLogger>, Env, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
@@ -71,6 +64,8 @@ impl eframe::App for App {
|
||||
}
|
||||
if self.0.quit_requested {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
} else if ctx.input(|i| i.viewport().close_requested()) && dialogs::ask_to_save(&mut self.0, "app.quit", &serde_json::json!({})) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
soundcraft_ui_egui::fit_window_to_screen(ctx);
|
||||
let (inner, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().maximized.unwrap_or(false)));
|
||||
@@ -85,26 +80,24 @@ impl eframe::App for App {
|
||||
}
|
||||
// With the system menu bar there is no egui bar showing the window and dirty state, so the
|
||||
// title carries them; elsewhere the egui menu bar already does.
|
||||
let app_name = os_window::name_for(os_window::identity());
|
||||
let document = (self.0.engine.session().name.as_str(), self.0.engine.is_dirty());
|
||||
let title = if self.0.native_menu_bar {
|
||||
let section = if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" };
|
||||
soundcraft_ui_egui::os_title_with_section(app_name, Some(document), section)
|
||||
format!(
|
||||
"{}{} — SoundCraft — {}",
|
||||
self.0.engine.session().name,
|
||||
if self.0.engine.is_dirty() { " *" } else { "" },
|
||||
if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" }
|
||||
)
|
||||
} else {
|
||||
soundcraft_ui_egui::os_title(app_name, Some(document.0))
|
||||
format!("{} — SoundCraft", self.0.engine.session().name)
|
||||
};
|
||||
set_title(ctx, title);
|
||||
// Last: the runtime's close path, which asks about unsaved changes before the window closes.
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
|
||||
/// shell.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
soundcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.0.guarded(|app| app.ui(ui));
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
@@ -119,9 +112,6 @@ impl eframe::App for App {
|
||||
self.0.player = None;
|
||||
soundcraft_engine::shutdown_plugin_hosts();
|
||||
self.0.start_pending_update();
|
||||
// The binary's last step: on Nightly, finishing the session-health record. macOS ends the
|
||||
// process from inside AppKit's terminate, so this is that channel's only exit path.
|
||||
self.0.services.run_exit_hook();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,122 +174,30 @@ fn services() -> Services {
|
||||
d.save_file()
|
||||
})),
|
||||
pick_folder: Some(Box::new(|start: &std::path::Path| rfd::FileDialog::new().set_directory(start).pick_folder())),
|
||||
..Services::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin);
|
||||
/// elsewhere the full tile. Regenerate with `packaging/icons.sh`.
|
||||
fn app_icon() -> Option<egui::IconData> {
|
||||
let nightly = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
|
||||
#[cfg(target_os = "macos")]
|
||||
let png: &[u8] = if nightly {
|
||||
include_bytes!("../../../assets/app-icon/soundcraft-nightly-macos-512.png")
|
||||
} else {
|
||||
include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png")
|
||||
};
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let png: &[u8] = if nightly {
|
||||
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft-nightly.png")
|
||||
} else {
|
||||
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png")
|
||||
};
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png");
|
||||
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
|
||||
}
|
||||
|
||||
/// Set the immutable Windows AUMID for the Nightly flavor before any window or COM service.
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
os_window::id_for(os_window::LaunchIdentity::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Report a refused launch profile on standard error, and in a dialog on a Windows or X11/Wayland
|
||||
/// desktop session: a Nightly build started from a file manager has no console to read. macOS keeps
|
||||
/// the console line, because a modal before its event loop never appears.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("SoundCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("SoundCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("SoundCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any start-up service or side effect. `None` means
|
||||
/// this process is done: a version query already answered, or a refused profile (exit status 2).
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before the logger, updates, fonts or saved state.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window, as
|
||||
// `SoundCraft <version> (nightly-v1)` on standard output with nothing on standard error.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
// The compiled identity, so About and diagnostics report the Nightly feed version verbatim.
|
||||
soundcraft_ui_egui::set_build_version(env!("SOUNDCRAFT_BUILT_VERSION").to_owned());
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
// Nightly has no updater of its own: ArtCraft Launcher carries the next build.
|
||||
#[cfg(windows)]
|
||||
if !launch_profile::current().is_nightly()
|
||||
&& let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
if let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// First, so every start-up record (and the engine's panic hook, installed with the first
|
||||
// Engine) is captured; see `logging`.
|
||||
let logger = logging::install(env::rust_log().as_deref());
|
||||
// Help, version and usage errors print and exit here, before a window or a log file exists.
|
||||
let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit());
|
||||
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
|
||||
// After the arguments and the logger: reading resolves the settings folder, which creates it,
|
||||
// and a malformed switch is logged.
|
||||
let env = Env::read();
|
||||
@@ -328,12 +226,12 @@ fn main() -> eframe::Result {
|
||||
let prefs = load_prefs(&env).unwrap_or_default();
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_title("SoundCraft")
|
||||
.with_inner_size(sane_window_size(prefs.window_size))
|
||||
.with_maximized(prefs.window_maximized)
|
||||
.with_min_inner_size([960.0, 600.0])
|
||||
.with_drag_and_drop(true)
|
||||
.with_app_id(os_window::app_id()),
|
||||
.with_app_id("ai.storyteller.soundcraft"),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
@@ -342,77 +240,34 @@ fn main() -> eframe::Result {
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let forced_x11 = env.use_xwayland(std::env::var_os("DISPLAY").as_ref());
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let forced_x11 = false;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// Nightly session health: an owned lease plus a record removed only by a clean exit, so the
|
||||
// next start can say when the previous one did not finish. Stable and a secondary window keep
|
||||
// their existing behaviour and touch nothing. No document names or paths are collected.
|
||||
let (nightly_session, session_health_warning) =
|
||||
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("SOUNDCRAFT_BUILT_VERSION"), None) {
|
||||
Ok(state) => state,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, true)
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_callback = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The app's exit hook is the controlled return on macOS, where every quit ends the process
|
||||
// inside AppKit's terminate and `run_native` never returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
|
||||
};
|
||||
let result = eframe::run_native(
|
||||
os_window::name_for(os_window::identity()),
|
||||
eframe::run_native(
|
||||
"SoundCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
soundcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11)?;
|
||||
let player =
|
||||
if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) };
|
||||
let mut app = SoundApp::new(engine, player, services());
|
||||
// Nightly is updated by ArtCraft Launcher only, never from inside the app.
|
||||
app.set_startup_update_check(!launch_profile::current().is_nightly());
|
||||
app.set_startup_update_check(true);
|
||||
app.set_system_fonts(env.system_fonts());
|
||||
app.autosave_dir = env.config_dir.as_ref().map(|d| d.join("Autosave"));
|
||||
app.leftovers = app.autosave_dir.as_deref().map(soundcraft_engine::autosave::leftovers).unwrap_or_default();
|
||||
app.preset_dir = env.config_dir.as_ref().map(|d| d.join("Presets"));
|
||||
app.extra.ui_scale = prefs.ui_scale;
|
||||
app.ui = prefs;
|
||||
// The Nightly window has no control server: no inherited port, no stable token file.
|
||||
if let Some(port) = control_port.filter(|_| !launch_profile::current().is_nightly()) {
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
if previous_nightly_unclean || session_health_warning {
|
||||
app.ui.status = if previous_nightly_unclean {
|
||||
"The previous SoundCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.".to_owned()
|
||||
} else {
|
||||
"SoundCraft Nightly could not record session health in its private profile; abnormal-exit detection is unavailable.".to_owned()
|
||||
};
|
||||
notice_shown_in_callback.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
app.services.at_exit = Some(Box::new(finish_at_exit));
|
||||
}
|
||||
for f in &files {
|
||||
dialogs::open_path(&mut app, f);
|
||||
}
|
||||
@@ -436,11 +291,7 @@ fn main() -> eframe::Result {
|
||||
menu,
|
||||
)))
|
||||
}),
|
||||
);
|
||||
// A controlled return, even for a handled start-up error. On macOS a window that was created
|
||||
// has already finished in its exit hook, so this is then a no-op.
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
result
|
||||
)
|
||||
}
|
||||
|
||||
/// A saved window size, or the default when the prefs file holds nonsense (NaN, negative, tiny).
|
||||
@@ -465,17 +316,3 @@ mod tests {
|
||||
assert_eq!(titles("Song * — SoundCraft"), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
|
||||
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
|
||||
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
|
||||
/// still runs for a start that created no window.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through an exclusively created temporary file in the same directory.
|
||||
/// The temporary name is never reused and is opened with `create_new`, so an existing file or a
|
||||
/// link at either name is replaced rather than followed; a failure leaves `path` untouched.
|
||||
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| io::Error::other(error.to_string()))?.as_nanos();
|
||||
let name = path.file_name().ok_or_else(|| io::Error::other("Nightly session state needs a file name"))?;
|
||||
let temporary = path.with_file_name(format!(".{}.{}.{nonce}.tmp", name.to_string_lossy(), std::process::id()));
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
|
||||
let written = (|| -> io::Result<()> {
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&temporary, path)
|
||||
})();
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage,
|
||||
/// while Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
// Durable, exclusive creation: a raced destination link is replaced, never followed.
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
|
||||
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
|
||||
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("soundcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
// Renderer initialization failed before the app callback: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The CPU retry (or the next start) still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
// Without an earlier interruption, a handled failure still clears normally.
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IdentityError(String);
|
||||
|
||||
impl std::fmt::Display for IdentityError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentityError {}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::config::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The Nightly Flatpak's own app id (packaging/linux/flatpak-bundle.sh). Inside that instance the
|
||||
/// sandbox is the isolation, so it is the one Flatpak whose environment a Nightly launch accepts.
|
||||
const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.soundcraft.nightly";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("SoundCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("soundcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.soundcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/SoundCraft"),
|
||||
library.join("Caches/SoundCraft"),
|
||||
library.join("Caches/ai.storyteller.soundcraft"),
|
||||
library.join("Preferences/SoundCraft"),
|
||||
library.join("Preferences/ai.storyteller.soundcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.soundcraft.savedState"),
|
||||
home.join("Applications/SoundCraft.app"),
|
||||
PathBuf::from("/Applications/SoundCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
|
||||
/// inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a SoundCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["soundcraft.exe", "soundcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
|
||||
/// boundary tests exercise the real policy without starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if env("SOUNDCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
// The Launcher protocol is the one root the app validates. A wrapper that isolates with
|
||||
// the stable override variable instead passes the profile explicitly; the message names
|
||||
// that, because this is what a Linux nightly launcher hits when it exports the variable.
|
||||
return Err(
|
||||
"nightly-v1 cannot be combined with SOUNDCRAFT_CONFIG_DIR; pass --launch-profile nightly-v1 --profile-root <dir> -- instead".into()
|
||||
);
|
||||
}
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
|
||||
// runtime socket namespace could point another profile at the stable app's socket. The
|
||||
// Nightly Flatpak is the exception: its own app id is the sandbox, so $HOME and the XDG
|
||||
// folders in there are already this package's own.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(instance) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& instance.to_string_lossy() != NIGHTLY_FLATPAK_ID
|
||||
{
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable SoundCraft installation or its SoundCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Autosave is swept and rewritten on start and Presets are written in place: never let either
|
||||
// alias leave this private profile, including toward a Stable portable directory we cannot know.
|
||||
private_subdirectory(&chosen, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&chosen, "Presets", "presets folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&confirmed, "Presets", "presets folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("soundcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/soundcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("SoundCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/state/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("Autosave")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "Autosave must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "Autosave cannot treat all profile settings as autosaves");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let autosave = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&autosave).unwrap();
|
||||
std::os::unix::fs::symlink(&autosave, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("Autosave")).unwrap(), autosave);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/soundcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Autosave"), platform));
|
||||
assert!(overlaps(&root.join("Autosave"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("soundcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/SoundCraft Nightly.app/Contents/MacOS/SoundCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/SoundCraft",
|
||||
"Caches/SoundCraft",
|
||||
"Caches/ai.storyteller.soundcraft",
|
||||
"Preferences/SoundCraft",
|
||||
"Saved Application State/ai.storyteller.soundcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_msi_install_folders_are_fenced() {
|
||||
let mut fixture = Fixture::new();
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("soundcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not SoundCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("D/PC");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
|
||||
std::fs::write(portable.join("soundcraft.exe"), b"stable portable executable, never run").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("portable"));
|
||||
assert!(!probed.get());
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
}
|
||||
// A portable.txt that no SoundCraft executable sits beside is someone else's file.
|
||||
let unrelated = fixture.root.join("user folder");
|
||||
std::fs::create_dir_all(&unrelated).unwrap();
|
||||
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
|
||||
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.soundcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft/Presets");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
|
||||
for name in ["Presets", "logs", "settings.json"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-presets")).unwrap();
|
||||
std::fs::write(private.join("settings.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/soundcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("SOUNDCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("SOUNDCRAFT_CONFIG_DIR"));
|
||||
fixture.env.remove("SOUNDCRAFT_CONFIG_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
// The Nightly Flatpak is its own instance: the profile inside it is a sandbox-local folder.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft.nightly".into());
|
||||
let sandboxed = fixture.home().join(".var/app/ai.storyteller.soundcraft.nightly/config/soundcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &sandboxed).unwrap(), sandboxed);
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/soundcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 18 KiB |
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 49 KiB |
@@ -2,4 +2,8 @@ allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -153,9 +153,6 @@ impl RunLoop {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
#[test]
|
||||
fn timers_and_descriptors_follow_registration() {
|
||||
@@ -171,21 +168,25 @@ mod tests {
|
||||
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
|
||||
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
|
||||
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
|
||||
// A connected stream has defined read and write readiness on both Linux and BSD.
|
||||
let (stream, mut peer) = UnixStream::pair().unwrap();
|
||||
let fd = stream.as_raw_fd();
|
||||
assert!(rl.add_fd(fd, CLAP_POSIX_FD_READ));
|
||||
assert!(!rl.add_fd(fd, CLAP_POSIX_FD_READ), "registered once");
|
||||
let mut fds = [0; 2];
|
||||
// SAFETY: `fds` holds the two descriptors `pipe` writes.
|
||||
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
|
||||
assert!(rl.add_fd(fds[0], CLAP_POSIX_FD_READ));
|
||||
assert!(!rl.add_fd(fds[0], CLAP_POSIX_FD_READ), "registered once");
|
||||
assert!(!rl.add_fd(-1, CLAP_POSIX_FD_READ));
|
||||
assert!(rl.ready().is_empty(), "nothing to read");
|
||||
peer.write_all(b"x").unwrap();
|
||||
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_READ)]);
|
||||
// The unread byte is still there, so reporting read as well would be a stale interest.
|
||||
assert!(rl.modify_fd(fd, CLAP_POSIX_FD_WRITE));
|
||||
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_WRITE)]);
|
||||
assert!(rl.remove_fd(fd) && !rl.has_fd(fd));
|
||||
assert!(rl.ready().is_empty(), "no callbacks for an unregistered descriptor");
|
||||
// SAFETY: a valid one-byte buffer written to our own pipe.
|
||||
assert_eq!(unsafe { libc::write(fds[1], b"x".as_ptr().cast(), 1) }, 1);
|
||||
assert_eq!(rl.ready(), vec![(fds[0], CLAP_POSIX_FD_READ)]);
|
||||
assert!(rl.modify_fd(fds[0], CLAP_POSIX_FD_WRITE));
|
||||
assert!(rl.ready().is_empty(), "a read end never becomes writable");
|
||||
assert!(rl.remove_fd(fds[0]) && !rl.has_fd(fds[0]));
|
||||
rl.clear();
|
||||
assert!(!rl.has_timer(b));
|
||||
// SAFETY: closing the pipe we opened.
|
||||
unsafe {
|
||||
libc::close(fds[0]);
|
||||
libc::close(fds[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cfb.workspace = true
|
||||
craft-aaf.workspace = true
|
||||
proptest.workspace = true
|
||||
zip.workspace = true
|
||||
|
||||
|
||||
@@ -478,8 +478,6 @@ pub fn create_unique_folder(parent: &Path, prefix: &str) -> std::io::Result<Path
|
||||
for _ in 0..16 {
|
||||
let random = |_| std::collections::hash_map::RandomState::new().build_hasher().finish();
|
||||
let dir = parent.join(format!("{prefix}-{:016x}{:016x}", random(0), random(1)));
|
||||
// Only Unix sets a mode on the builder, so elsewhere it is never mutated.
|
||||
#[cfg_attr(not(unix), allow(unused_mut))]
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
|
||||
@@ -96,92 +96,6 @@ pub fn is_placeholder(path: &str) -> bool {
|
||||
PLACEHOLDERS.contains(&path)
|
||||
}
|
||||
|
||||
/// RFC-0052 hand marks for catalog leaves the engine registry doesn't implement:
|
||||
/// `(path, headless, reach, why)`. A path ending in ` > ` marks every leaf under it; the longest
|
||||
/// matching path wins.
|
||||
///
|
||||
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
|
||||
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
|
||||
/// command, isn't one yet). `yes` is never written here: a leaf is `yes` only when the engine registry
|
||||
/// that `soundcraft-cli` and the MCP server load implements it. UI-layer ids (`parity_with`'s
|
||||
/// `extra`) don't count. An unmarked missing leaf is `unknown`. [`headless_errors`] rejects marks
|
||||
/// that match nothing or only hide a `yes`.
|
||||
pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
|
||||
("File > Open > Project...", "no", "os", "online project service"),
|
||||
("File > Open > Sketch...", "no", "engine-gap", "sketch files could be opened by a command"),
|
||||
("File > Dashboard...", "no", "window", "the start dialog"),
|
||||
("File > Start Collaboration...", "no", "os", "online collaboration service"),
|
||||
("File > Import > ", "no", "engine-gap", "the import could be a command"),
|
||||
("File > Export > ", "no", "engine-gap", "the export could be a command"),
|
||||
("File > Sign In", "no", "os", "online account service"),
|
||||
("Edit > Automation > ", "no", "engine-gap", "automation copies could be commands"),
|
||||
("View > ", "no", "window", "shows or hides part of a desktop window"),
|
||||
("Track > Change Track Width > Show / Hide...", "no", "window", "a desktop dialog"),
|
||||
("Track > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
|
||||
("Clip > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
|
||||
("AudioSuite > ", "no", "engine-gap", "offline processing over the crates/dsp plug-ins could be commands"),
|
||||
("Options > Activate HEAT", "no", "engine-gap", "the processor could be an engine option"),
|
||||
("Setup > Machine Track Arming Profiles...", "no", "os", "external machine control hardware"),
|
||||
("Window > ", "no", "window", "opens or arranges a desktop window"),
|
||||
("Window > Collaboration > ", "no", "os", "online collaboration service"),
|
||||
("Window > Splice", "no", "os", "online sample service"),
|
||||
("Window > SoundFlow", "no", "os", "third-party automation service"),
|
||||
];
|
||||
|
||||
/// Whether a `HEADLESS` mark path covers a catalog leaf.
|
||||
fn mark_covers(mark: &str, leaf: &str) -> bool {
|
||||
mark == leaf || (mark.ends_with(" > ") && leaf.starts_with(mark))
|
||||
}
|
||||
|
||||
/// A leaf's RFC-0052 `headless:` value, `reach:` and reason: `yes` when the engine implements it,
|
||||
/// else the longest `marks` path that covers it, else `unknown`.
|
||||
pub fn headless_of<'a>(leaf: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) {
|
||||
if in_engine {
|
||||
return ("yes", None, "");
|
||||
}
|
||||
marks.iter().filter(|m| mark_covers(m.0, leaf)).max_by_key(|m| m.0.len()).map_or(("unknown", None, ""), |m| (m.1, Some(m.2), m.3))
|
||||
}
|
||||
|
||||
/// Problems with `marks` against `leaves` (`(path, in_engine)`): bad values, a mark that covers no
|
||||
/// leaf, and a mark whose leaves the engine all implements (it would only hide a `yes`).
|
||||
pub fn headless_errors(marks: &[(&str, &str, &str, &str)], leaves: &[(&str, bool)]) -> Vec<String> {
|
||||
let mut errs = Vec::new();
|
||||
for (i, (path, value, reach, _)) in marks.iter().enumerate() {
|
||||
if !matches!(*value, "no" | "partial") {
|
||||
errs.push(format!("headless mark `{path}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !matches!(*reach, "window" | "os" | "engine-gap") {
|
||||
errs.push(format!("headless mark `{path}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if marks[..i].iter().any(|m| m.0 == *path) {
|
||||
errs.push(format!("headless mark `{path}` is written twice"));
|
||||
}
|
||||
let covered: Vec<bool> = leaves.iter().filter(|l| mark_covers(path, l.0)).map(|l| l.1).collect();
|
||||
if covered.is_empty() {
|
||||
errs.push(format!("headless mark `{path}` matches no catalog leaf"));
|
||||
} else if covered.iter().all(|live| *live) {
|
||||
errs.push(format!("headless mark `{path}` is stale: the engine implements every leaf it covers"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// The RFC-0052 summary line for a [`parity_with`] report.
|
||||
pub fn headless_summary_line(p: &Value) -> String {
|
||||
let h = &p["headless"];
|
||||
let n = |v: &Value| v.as_u64().unwrap_or(0);
|
||||
format!(
|
||||
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**",
|
||||
n(&h["yes"]),
|
||||
n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]),
|
||||
n(&h["no"]["window"]),
|
||||
n(&h["no"]["os"]),
|
||||
n(&h["no"]["engine-gap"]),
|
||||
n(&h["partial"]),
|
||||
n(&h["unknown"]),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn catalog() -> Vec<&'static str> {
|
||||
MENUS.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
|
||||
}
|
||||
@@ -208,27 +122,17 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
|
||||
let mut done = 0usize;
|
||||
let mut missing = Vec::new();
|
||||
let mut per_menu: std::collections::BTreeMap<String, (usize, usize)> = Default::default();
|
||||
let mut headless: Vec<(&str, Option<&str>)> = Vec::new();
|
||||
let mut headless_missing = Vec::new();
|
||||
for e in &cat {
|
||||
let top = e.split(" > ").next().unwrap_or("").to_string();
|
||||
let slot = per_menu.entry(top).or_default();
|
||||
slot.1 += 1;
|
||||
let in_engine = implemented_by(e, &[]).is_some();
|
||||
let (value, reach, why) = headless_of(e, in_engine, HEADLESS);
|
||||
headless.push((value, reach));
|
||||
if value != "yes" {
|
||||
headless_missing.push(json!({"path": e, "headless": value, "reach": reach, "why": why}));
|
||||
}
|
||||
if in_engine || (!extra.is_empty() && implemented_by(e, extra).is_some()) {
|
||||
if implemented_by(e, extra).is_some() {
|
||||
done += 1;
|
||||
slot.0 += 1;
|
||||
} else {
|
||||
missing.push(*e);
|
||||
}
|
||||
}
|
||||
let count = |v: &str| headless.iter().filter(|h| h.0 == v).count();
|
||||
let no = |r: &str| headless.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count();
|
||||
let pct = if cat.is_empty() { 0.0 } else { done as f64 * 100.0 / cat.len() as f64 };
|
||||
json!({
|
||||
"total": cat.len(),
|
||||
@@ -236,13 +140,6 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
|
||||
"percent": (pct * 10.0).round() / 10.0,
|
||||
"per_menu": per_menu.iter().map(|(k, (d, t))| json!({"menu": k, "implemented": d, "total": t})).collect::<Vec<_>>(),
|
||||
"missing": missing,
|
||||
"headless": {
|
||||
"yes": count("yes"),
|
||||
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
|
||||
"partial": count("partial"),
|
||||
"unknown": count("unknown"),
|
||||
},
|
||||
"headless_missing": headless_missing,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -262,51 +159,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_are_current() {
|
||||
let leaves: Vec<(&str, bool)> = catalog().into_iter().map(|e| (e, implemented_by(e, &[]).is_some())).collect();
|
||||
let errs = headless_errors(HEADLESS, &leaves);
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_is_the_engine_only() {
|
||||
let p = parity_json();
|
||||
let h = &p["headless"];
|
||||
assert_eq!(h["yes"], p["implemented"], "engine-only parity: every implemented leaf is yes");
|
||||
// AudioSuite has no engine command: every leaf is marked, none reads as reachable.
|
||||
let audiosuite: Vec<&Value> = p["headless_missing"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| m["path"].as_str().is_some_and(|x| x.starts_with("AudioSuite > ")))
|
||||
.collect();
|
||||
assert!(!audiosuite.is_empty());
|
||||
assert!(audiosuite.iter().all(|m| m["headless"] == "no" && m["reach"] == "engine-gap"));
|
||||
// A UI-layer alias makes a leaf implemented for the desktop report, not headless.
|
||||
let ui = [("Window > Mix", "window.mix")];
|
||||
let with_ui = parity_with(&ui);
|
||||
assert!(with_ui["implemented"].as_u64() > p["implemented"].as_u64());
|
||||
assert_eq!(with_ui["headless"], p["headless"]);
|
||||
assert!(headless_summary_line(&p).contains(&format!("{} yes", h["yes"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_pick_the_longest_path_and_refuse_bad_ones() {
|
||||
let marks = [("W > ", "no", "window", "a"), ("W > C > ", "no", "os", "b"), ("X", "partial", "engine-gap", "c")];
|
||||
assert_eq!(headless_of("W > C > M", false, &marks), ("no", Some("os"), "b"));
|
||||
assert_eq!(headless_of("W > Mix", false, &marks), ("no", Some("window"), "a"));
|
||||
assert_eq!(headless_of("W > Mix", true, &marks).0, "yes");
|
||||
assert_eq!(headless_of("Y", false, &marks).0, "unknown");
|
||||
assert_eq!(headless_of("WX", false, &marks).0, "unknown", "a prefix mark needs the separator");
|
||||
let leaves = [("W > Mix", false), ("X", true)];
|
||||
let bad = [("W > ", "yes", "window", ""), ("W > ", "no", "desk", ""), ("X", "no", "os", ""), ("Z", "no", "os", "")];
|
||||
let errs = headless_errors(&bad, &leaves);
|
||||
for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`X` is stale", "`Z` matches no catalog leaf"] {
|
||||
assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parity_floor() {
|
||||
let p = parity_json();
|
||||
|
||||
@@ -66,7 +66,6 @@ pub use file::bounce_job;
|
||||
|
||||
pub(crate) use edit::remember_selection;
|
||||
pub use strip_silence::strip_silence_scan;
|
||||
pub use tab::tab_stop_ahead;
|
||||
|
||||
pub type Run = fn(&mut Engine, &Value) -> Result<Value>;
|
||||
/// `Err(reason)` = disabled.
|
||||
|
||||
@@ -21,23 +21,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// How many times longer than its input a process's output can be.
|
||||
fn growth(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> f64 {
|
||||
match name {
|
||||
"time_stretch" => ratio,
|
||||
"pitch_shift" => 2f64.powf(f64::from(semitones) / 12.0),
|
||||
"varispeed" => f64::from(to) / sr,
|
||||
"speed_ramp" if selection == SpeedRampSelection::Extend => 1.5,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The most frames a process can take in: these processes cut their output at MAX_OFFLINE_SAMPLES frames.
|
||||
fn frame_limit(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> usize {
|
||||
let longest = |grows: f64| (soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / grows) as usize;
|
||||
match name {
|
||||
"time_stretch" | "pitch_shift" | "varispeed" | "speed_ramp" => {
|
||||
(soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / growth(name, ratio, semitones, sr, to, selection)) as usize
|
||||
}
|
||||
"time_stretch" => longest(ratio),
|
||||
"pitch_shift" => longest(2f64.powf(f64::from(semitones) / 12.0)),
|
||||
"varispeed" => longest(f64::from(to) / sr),
|
||||
"speed_ramp" => longest(if selection == SpeedRampSelection::Extend { 1.5 } else { 1.0 }),
|
||||
_ => usize::MAX,
|
||||
}
|
||||
}
|
||||
@@ -89,33 +80,14 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let selection = if get("selection", 0.0) >= 0.5 { SpeedRampSelection::Extend } else { SpeedRampSelection::FitTo };
|
||||
let fades = get("fades", 1.0) >= 0.5;
|
||||
let most = frame_limit(&name, ratio, semitones, sr.as_f64(), to, selection);
|
||||
// Each clip once: a clip listed again would otherwise process the result of its first pass
|
||||
// (an expanding process compounding its length every time).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let ids: Vec<_> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
// Refuse before processing anything. Every result is kept as a new source for the life of
|
||||
// the command (and undo holds it), so cap the total output across clips, not just each one.
|
||||
// (pitch_shift resamples its stretched result back to the input length)
|
||||
let grows = if name == "pitch_shift" { 1.0 } else { growth(&name, ratio, semitones, sr.as_f64(), to, selection).max(1.0) };
|
||||
let mut budget = soundcraft_mix::MAX_RENDER_SAMPLES;
|
||||
for id in &ids {
|
||||
let Some((track, clip)) = e.session().find_clip(*id) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels()).max(1);
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let frames = (clip.length.max(0) as f64 * grows).ceil() as usize;
|
||||
budget = budget
|
||||
.checked_sub(frames.saturating_mul(channels))
|
||||
.ok_or_else(|| bad("audiosuite.process", "too much audio to process in one command"))?;
|
||||
}
|
||||
let mut done = 0;
|
||||
for id in ids {
|
||||
let Some((track, clip)) = e.session().find_clip(id).map(|(t, c)| (t, c.clone())) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels());
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let mut audio = soundcraft_mix::render_clips(e.session(), track, clip.range());
|
||||
// Render without the clip's own fades: re-render a copy without fades so they stay editable.
|
||||
let mut tmp = e.session().clone();
|
||||
@@ -390,40 +362,6 @@ mod tests {
|
||||
assert_eq!(e.session().tracks[0].clips().len(), 1, "one clip, not one per duplicate listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_listed_twice_is_processed_once() {
|
||||
let (mut e, id) = gained_clip();
|
||||
let out =
|
||||
e.execute("audiosuite.process", &json!({"process": "time_stretch", "params": {"ratio": 4.0}, "clips": [id.0, id.0, id.0]})).unwrap();
|
||||
assert_eq!(out["processed"], 1);
|
||||
let c = e.session().tracks[0].clips()[0].clone();
|
||||
assert!(c.length <= 64 * 4 + 64, "stretched once, not compounded: {}", c.length);
|
||||
assert_eq!(e.session().sources.len(), 2, "one new source, not one per listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_refuses_a_total_budget_across_clips() {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Tone"));
|
||||
let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.5; 64]] };
|
||||
let src = crate::io::add_source(&mut s, "tone", buf, None, FileFormat::Wav);
|
||||
// Three clips each within the per-clip limit whose results together exceed the budget.
|
||||
let len = (soundcraft_mix::MAX_RENDER_SAMPLES / 3 + 1) as i64;
|
||||
let ids: Vec<u64> = (0..3)
|
||||
.map(|k| {
|
||||
let id = s.new_clip_id();
|
||||
crate::edit::place_clip(&mut s, t, Clip::audio(id, "tone", src, 0, k * len, len));
|
||||
id.0
|
||||
})
|
||||
.collect();
|
||||
let mut e = crate::Engine::new(s);
|
||||
let before = serde_json::to_value(e.session()).unwrap();
|
||||
let out = e.execute("audiosuite.process", &json!({"process": "reverse", "clips": ids}));
|
||||
let ok = matches!(out, Err(crate::EngineError::BadParams(_, ref m)) if m.contains("too much audio"));
|
||||
assert!(ok, "three clips over budget, but got: {out:?}");
|
||||
assert_eq!(serde_json::to_value(e.session()).unwrap(), before, "refused before processing anything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_refuses_a_total_budget_across_tracks() {
|
||||
let mut e = Engine::new(Session::default());
|
||||
|
||||
@@ -301,7 +301,7 @@ const MAX_LOOPS: i64 = 1000;
|
||||
|
||||
fn loop_clips(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let ids = clip_ids_param(e, p);
|
||||
let count = i64_or(p, "count", 4).clamp(1, MAX_LOOPS);
|
||||
let count = i64_or(p, "count", 4).clamp(1, 512);
|
||||
let total = position_param(e, "clip.loop", p, "length")?;
|
||||
let fill = p.get("fill").and_then(Value::as_bool).unwrap_or(false);
|
||||
let s = e.session_mut();
|
||||
|
||||
@@ -469,13 +469,6 @@ mod tests {
|
||||
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "length": 100_100})).unwrap()["loops"], 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_count_accepts_up_to_the_documented_thousand() {
|
||||
let (mut e, t, ids) = engine_with(&[(0, 100, 0)]);
|
||||
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "count": 600})).unwrap()["loops"], 599);
|
||||
assert_eq!(e.session().track(t).unwrap().clips().len(), 600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regroup_reuses_group() {
|
||||
let (mut e, _, ids) = engine_with(&[(0, 100, 0), (500, 100, 0), (900, 100, 0)]);
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::more_util::toggle_flag;
|
||||
use crate::edit as ops;
|
||||
use crate::{Clipboard, Engine, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{Clip, ClipId, EditMode, Fade, FadeShape, Session, TrackId};
|
||||
use soundcraft_model::{ClipId, EditMode, Fade, FadeShape, Session, TrackId};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -741,9 +741,10 @@ fn trim_to_file(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
if let Some((frames, lo, hi)) = trim_limits(s, id)
|
||||
&& let Some(c) = s.find_clip_mut(id)
|
||||
{
|
||||
let (file_start, file_end) = file_span(c, frames);
|
||||
c.trim_start_to(file_start.max(lo));
|
||||
c.trim_end_to(file_end.min(hi));
|
||||
let off = c.source_offset();
|
||||
let new_start = c.start - off;
|
||||
c.trim_start_to(new_start.max(lo));
|
||||
c.trim_end_to((new_start + frames).min(hi));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
@@ -759,24 +760,15 @@ fn trim_to_fill(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
if let Some((frames, lo, hi)) = trim_limits(s, id)
|
||||
&& let Some(c) = s.find_clip_mut(id)
|
||||
{
|
||||
let (file_start, file_end) = file_span(c, frames);
|
||||
let file_start = c.start - c.source_offset();
|
||||
c.trim_start_to(r.start.max(file_start).max(lo));
|
||||
c.trim_end_to(r.end.min(file_end).min(hi));
|
||||
c.trim_end_to(r.end.min(file_start + frames).min(hi));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"trimmed": n}))
|
||||
}
|
||||
|
||||
/// Where a clip's whole source file lies on the timeline. The mixer plays `offset + rel / stretch`,
|
||||
/// so the file starts `offset * stretch` before the clip and spans `frames * stretch` samples.
|
||||
fn file_span(c: &Clip, frames: Samples) -> (Samples, Samples) {
|
||||
let stretch = if c.stretch.is_finite() && c.stretch > 0.0 { c.stretch } else { 1.0 };
|
||||
let scale = |n: Samples| if (stretch - 1.0).abs() >= 1e-9 { (n as f64 * stretch).round() as Samples } else { n };
|
||||
let start = c.start.saturating_sub(scale(c.source_offset()));
|
||||
(start, start.saturating_add(scale(frames)))
|
||||
}
|
||||
|
||||
/// How far a trim may extend an audio clip: its source length in frames, and the earliest
|
||||
/// start and latest end before it would run over the clip before or after it on the playlist
|
||||
/// (an extension never overwrites, like the trim tool). An overlap the clip already has with
|
||||
@@ -1262,33 +1254,6 @@ mod tests {
|
||||
assert_eq!(bounds(&e, t), vec![(0, 10_000, 0), (10_000, 40_000, 10_000), (40_000, 45_000, 0)]);
|
||||
}
|
||||
|
||||
/// A lone stretched clip (start 20,000, length 10,000, source offset 5,000) over the 60,000-frame source.
|
||||
fn stretched_trim_session(stretch: f64) -> (Engine, TrackId, Vec<ClipId>) {
|
||||
let (mut e, t, ids) = trim_session(&[(20_000, 10_000, 5_000)]);
|
||||
if let Some(c) = e.session_mut().find_clip_mut(ids[0]) {
|
||||
c.stretch = stretch;
|
||||
}
|
||||
(e, t, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_file_boundaries_covers_the_whole_stretched_file() {
|
||||
let (mut e, t, ids) = stretched_trim_session(2.0);
|
||||
e.execute("edit.trim_to_file_boundaries", &json!({"clips": [ids[0].0]})).unwrap();
|
||||
let (start, end, offset) = bounds(&e, t)[0];
|
||||
assert_eq!(offset, 0, "the clip starts at the file start");
|
||||
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "it plays every file frame: {start}..{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_fill_selection_stops_at_the_stretched_file() {
|
||||
let (mut e, t, ids) = stretched_trim_session(2.0);
|
||||
e.execute("edit.trim_to_fill_selection", &json!({"clips": [ids[0].0], "start": 0, "end": 500_000})).unwrap();
|
||||
let (start, end, offset) = bounds(&e, t)[0];
|
||||
assert_eq!(offset, 0);
|
||||
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "a wider selection stops at the file: {start}..{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_fill_selection_stops_at_the_neighbours() {
|
||||
let (mut e, t, ids) = trim_session(&[(0, 10_000, 0), (20_000, 10_000, 20_000), (40_000, 5_000, 0)]);
|
||||
|
||||
@@ -313,16 +313,10 @@ fn add_marker(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let at = position_param(e, "markers.add", p, "at")?;
|
||||
let st = position_param(e, "markers.add", p, "start")?;
|
||||
let en = position_param(e, "markers.add", p, "end")?;
|
||||
let kind = match p.get("kind") {
|
||||
None | Some(Value::Null) => MarkerKind::Marker,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("marker") => MarkerKind::Marker,
|
||||
Some("selection") => MarkerKind::Selection,
|
||||
Some("none") => MarkerKind::None,
|
||||
Some(other) => return Err(bad("markers.add", format!("unknown kind `{other}`"))),
|
||||
// A present non-string is neither a documented kind nor an omitted one.
|
||||
None => return Err(bad("markers.add", "kind must be a string")),
|
||||
},
|
||||
let kind = match str_param(p, "kind") {
|
||||
Some("selection") => MarkerKind::Selection,
|
||||
Some("none") => MarkerKind::None,
|
||||
_ => MarkerKind::Marker,
|
||||
};
|
||||
let (a, b) = match (at, st, en) {
|
||||
(Some(a), _, _) => (a, a),
|
||||
@@ -586,30 +580,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `markers.add` rejects an unknown or non-string `kind` instead of silently adding a plain
|
||||
/// marker; an absent or null one still means a plain marker.
|
||||
#[test]
|
||||
fn markers_add_rejects_an_unknown_kind() {
|
||||
let mut e = crate::Engine::default();
|
||||
let err = e.execute("markers.add", &json!({"name": "x", "kind": "garbage"})).unwrap_err();
|
||||
assert!(err.to_string().contains("kind"), "unexpected error: {err}");
|
||||
assert!(e.session().markers.is_empty());
|
||||
for bad in [json!(123), json!(true), json!(["marker"]), json!({"kind": "marker"}), json!(1.5)] {
|
||||
let err = e.execute("markers.add", &json!({"name": "x", "kind": bad})).unwrap_err();
|
||||
assert!(err.to_string().contains("kind"), "{bad}: unexpected error: {err}");
|
||||
assert!(e.session().markers.is_empty(), "{bad}: a marker was added");
|
||||
}
|
||||
let plain = e.execute("markers.add", &json!({"name": "Plain", "kind": null, "at": 500})).unwrap();
|
||||
assert_eq!(e.session().markers.len(), 1, "null is still an omitted kind");
|
||||
let verse = e.execute("markers.add", &json!({"name": "Verse", "kind": "marker", "at": 1000})).unwrap();
|
||||
let pre = e.execute("markers.add", &json!({"name": "Pre", "kind": "none", "at": 2000})).unwrap();
|
||||
let kind_of =
|
||||
|e: &crate::Engine, r: &serde_json::Value| e.session().markers.iter().find(|m| Some(m.id.0) == r["id"].as_u64()).map(|m| m.kind);
|
||||
assert_eq!(kind_of(&e, &plain), Some(soundcraft_model::MarkerKind::Marker));
|
||||
assert_eq!(kind_of(&e, &verse), Some(soundcraft_model::MarkerKind::Marker));
|
||||
assert_eq!(kind_of(&e, &pre), Some(soundcraft_model::MarkerKind::None));
|
||||
}
|
||||
|
||||
/// Constant replaces the tempo over [start, end) only; the tempo at the old end tick carries on after it.
|
||||
#[test]
|
||||
fn tempo_constant_is_bounded_by_its_range() {
|
||||
|
||||
@@ -52,23 +52,6 @@ fn import_audio_places_audio_offered_by_a_worker() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_audio_refuses_a_non_audio_target() {
|
||||
let dir = std::env::temp_dir().join(format!("sc-import-non-audio-target-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let wav = tone_wav(&dir, "tone.wav");
|
||||
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"kind": "instrument", "name": "Keys"})).unwrap();
|
||||
let err = e.execute("file.import_audio", &json!({"path": wav, "track": "Keys"})).unwrap_err();
|
||||
assert!(err.to_string().contains("audio track"), "{err}");
|
||||
assert_eq!(e.session().tracks.len(), 1);
|
||||
assert!(e.session().sources.is_empty());
|
||||
assert!(e.session().tracks[0].clips().is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_session_text_needs_replace_to_overwrite() {
|
||||
let dir = std::env::temp_dir().join(format!("sc-export-text-replace-{}", std::process::id()));
|
||||
|
||||
@@ -11,7 +11,7 @@ use soundcraft_model::{AutoParam, AutomationMode, INSERT_SLOTS, Insert, SEND_SLO
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("mix.volume", "Set Volume", [], None, "{tracks?, db: -144..12 | delta_db}", has_selection, volume),
|
||||
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1 (stereo: required, 0 = left, 1 = right)}", has_selection, pan),
|
||||
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1}", has_selection, pan),
|
||||
cmd!("mix.mute", "Mute", [], Some("Shift+M"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
|
||||
e,
|
||||
p,
|
||||
@@ -280,25 +280,8 @@ fn pan(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "mix.pan", p)?;
|
||||
let v = (p.get("pan").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("mix.pan", "`pan` (number) required"))? as f32)
|
||||
.clamp(-1.0, 1.0);
|
||||
// A stereo track has one panner per channel, so it must say which: moving only the left one
|
||||
// by default folded the left channel into the right. An index the track lacks is an error too.
|
||||
// `null` means no index, as with `slot`. `i64_or` rounds, so the number has to be whole already.
|
||||
let idx = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(i) => {
|
||||
let whole = i.as_f64().is_some_and(|f| f.fract() == 0.0);
|
||||
Some(usize::try_from(i64_or(p, "index", -1)).ok().filter(|n| whole && *n <= 1).ok_or_else(|| bad("mix.pan", "`index` must be 0 or 1"))?)
|
||||
}
|
||||
};
|
||||
let idx = i64_or(p, "index", 0).clamp(0, 1) as usize;
|
||||
let s = e.session_mut();
|
||||
for tr in tracks.iter().filter_map(|t| s.track(*t)) {
|
||||
match (idx, tr.mixer.pan.len()) {
|
||||
(None, 2) => return Err(bad("mix.pan", format!("`{}` is stereo: give `index` 0 (left channel) or 1 (right channel)", tr.name))),
|
||||
(Some(1), 1) => return Err(bad("mix.pan", format!("`{}` is mono: its only panner is `index` 0", tr.name))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let idx = idx.unwrap_or(0);
|
||||
for t in &tracks {
|
||||
if let Some(tr) = s.track_mut(*t)
|
||||
&& let Some(slot) = tr.mixer.pan.get_mut(idx)
|
||||
|
||||
@@ -413,38 +413,6 @@ fn clip_gain_to_volume_with_a_large_envelope_stays_fast() {
|
||||
assert!(lane.points.len() as i64 >= n);
|
||||
}
|
||||
|
||||
/// A stereo track has a panner per channel. `mix.pan` without `index` used to move only the left
|
||||
/// one, which folded the left channel into the right.
|
||||
#[test]
|
||||
fn panning_a_stereo_track_names_the_channel() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"name": "Pad", "format": "stereo"})).unwrap();
|
||||
e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap();
|
||||
let pans = |e: &Engine, name: &str| e.session().tracks.iter().find(|t| t.name == name).map(|t| t.mixer.pan.clone());
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3})).is_err());
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 1.0]), "a refused pan leaves the track alone");
|
||||
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3, "index": 1})).unwrap();
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
|
||||
// A whole number written as a float counts; a fraction is an error (1.4 used to round to 1).
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.4})).is_err());
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
|
||||
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.0})).unwrap();
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 0.9]));
|
||||
// `null` means no index, as with `slot`, so a stereo track still needs one.
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.0, "index": null})).is_err());
|
||||
// A mono track has one panner: no index needed, and any other index is an error, not a no-op.
|
||||
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.25, "index": null})).unwrap();
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.25]));
|
||||
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.5})).unwrap();
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
|
||||
for index in [json!(1), json!(2), json!(-1), json!("1"), json!(0.4)] {
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.0, "index": index})).is_err(), "index {index}");
|
||||
}
|
||||
// One stereo track without an index stops the whole command.
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox", "Pad"], "pan": 0.2})).is_err());
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
|
||||
}
|
||||
|
||||
/// Live input toggles stay outside document history in both enabled and disabled states.
|
||||
#[test]
|
||||
fn live_input_states_are_transient_and_survive_document_history() {
|
||||
|
||||
@@ -58,13 +58,6 @@ fn tab(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"selection": r}))
|
||||
}
|
||||
|
||||
/// Whether Tab has a stop after the insertion point or the selection's start. Every stop of a clip lies at or before
|
||||
/// its end, which is a stop itself.
|
||||
pub fn tab_stop_ahead(s: &Session) -> bool {
|
||||
let from = s.edit.selection.start;
|
||||
s.tracks.iter().filter(|t| s.edit.selected_tracks.contains(&t.id)).flat_map(|t| t.clips()).any(|c| c.start.max(c.end()) > from)
|
||||
}
|
||||
|
||||
/// The nearest stop after `from` (before it when `back`) on the selected tracks.
|
||||
fn stop(s: &Session, from: Samples, back: bool) -> Option<Samples> {
|
||||
let nearer = |x: Samples, best: Option<Samples>| {
|
||||
|
||||
@@ -98,16 +98,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)),
|
||||
cmd!("track.commit", "Commit...", ["Track"], Some("Alt+Shift+C"), "{tracks?}", has_selection, commit),
|
||||
cmd!("track.bounce", "Bounce...", ["Track"], Some("Cmd+Alt+Shift+B"), "{tracks?}", has_selection, commit),
|
||||
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], Some("Shift+A"), "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
|
||||
cmd!(
|
||||
"track.mute_sends",
|
||||
"All",
|
||||
["Track", "Mute Sends"],
|
||||
Some("Shift+Q"),
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| super::track_more::mute_sends_where(e, p, 0, 10)
|
||||
),
|
||||
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
|
||||
cmd!("track.mute_sends", "All", ["Track", "Mute Sends"], None, "{tracks?, mute?: bool}", has_selection, mute_sends),
|
||||
cmd!(noundo "track.set_record_to_input_only", "Set Record Tracks to Input Only", ["Track"], Some("Alt+K"), "{}", always, |e, _| {
|
||||
let s = e.runtime_session_mut();
|
||||
let mut n = 0;
|
||||
@@ -960,6 +952,20 @@ fn bypass_inserts(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"bypass": target}))
|
||||
}
|
||||
|
||||
fn mute_sends(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "track.mute_sends", p)?;
|
||||
let s = e.session_mut();
|
||||
let target = p.get("mute").and_then(Value::as_bool).unwrap_or(true);
|
||||
for t in &tracks {
|
||||
if let Some(tr) = s.track_mut(*t) {
|
||||
for snd in tr.mixer.sends.iter_mut().flatten() {
|
||||
snd.mute = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"mute": target}))
|
||||
}
|
||||
|
||||
fn create_click(e: &mut Engine, _: &Value) -> Result<Value> {
|
||||
let s = e.session_mut();
|
||||
let id = s.add_track(TrackKind::Aux, ChannelFormat::Mono, Some("Click"));
|
||||
|
||||
@@ -68,56 +68,38 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
load_preset
|
||||
),
|
||||
cmd!(
|
||||
"track.bypass_inserts_ae",
|
||||
"Inserts A-E",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+2"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |i, _| i < 5)
|
||||
),
|
||||
cmd!(
|
||||
"track.bypass_inserts_fj",
|
||||
"Inserts F-J",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+3"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |i, _| (5..10).contains(&i))
|
||||
),
|
||||
cmd!(
|
||||
"track.bypass_eq",
|
||||
"EQ",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+E"),
|
||||
"{tracks?, bypass?: bool} — EQ plug-ins only",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Eq))
|
||||
),
|
||||
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], Some("Shift+C"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Dynamics))
|
||||
cmd!("track.bypass_inserts_ae", "Inserts A-E", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |i, _| i < 5)
|
||||
}),
|
||||
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], Some("Shift+V"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Reverb))
|
||||
cmd!("track.bypass_inserts_fj", "Inserts F-J", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |i, _| (5..10).contains(&i))
|
||||
}),
|
||||
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], Some("Shift+D"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Delay))
|
||||
cmd!("track.bypass_eq", "EQ", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool} — EQ plug-ins only", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Eq))
|
||||
}),
|
||||
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Dynamics)
|
||||
)),
|
||||
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Reverb)
|
||||
)),
|
||||
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Delay)
|
||||
)),
|
||||
cmd!("track.bypass_modulation", "Modulation", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Modulation))
|
||||
}),
|
||||
cmd!(
|
||||
"track.bypass_modulation",
|
||||
"Modulation",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+W"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Modulation))
|
||||
),
|
||||
cmd!(
|
||||
"track.mute_sends_ae",
|
||||
"Sends A-E",
|
||||
["Track", "Mute Sends"],
|
||||
Some("Shift+4"),
|
||||
None,
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| mute_sends_where(e, p, 0, 5)
|
||||
@@ -126,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"track.mute_sends_fj",
|
||||
"Sends F-J",
|
||||
["Track", "Mute Sends"],
|
||||
Some("Shift+5"),
|
||||
None,
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| mute_sends_where(e, p, 5, 10)
|
||||
@@ -353,7 +335,7 @@ fn bypass_where(e: &mut Engine, p: &Value, pick: fn(usize, Option<Category>) ->
|
||||
Ok(json!({"bypass": target, "inserts": n}))
|
||||
}
|
||||
|
||||
pub(super) fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
|
||||
fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "track.mute_sends", p)?;
|
||||
let s = e.session_mut();
|
||||
let all_muted = tracks.iter().filter_map(|t| s.track(*t)).all(|tr| tr.mixer.sends.iter().skip(from).take(to - from).flatten().all(|x| x.mute));
|
||||
@@ -520,22 +502,15 @@ fn coalesce_vca(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn designate_target(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "track.designate_target_playlist";
|
||||
let tracks = tracks_required(e, id, p)?;
|
||||
let index = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => {
|
||||
let index = value.as_u64().ok_or_else(|| bad(id, "`index` must be a nonnegative integer"))?;
|
||||
Some(usize::try_from(index).map_err(|_| bad(id, "no such playlist"))?)
|
||||
}
|
||||
};
|
||||
let tracks = tracks_required(e, "track.designate_target_playlist", p)?;
|
||||
let idx = p.get("index").and_then(Value::as_u64);
|
||||
let s = e.session_mut();
|
||||
let mut out = Vec::new();
|
||||
for t in &tracks {
|
||||
let Some(tr) = s.track(*t) else { continue };
|
||||
let i = index.unwrap_or(tr.active_playlist);
|
||||
let i = idx.map_or(tr.active_playlist, |x| usize::try_from(x).unwrap_or(usize::MAX));
|
||||
if i >= tr.playlists.len() {
|
||||
return Err(bad(id, "no such playlist"));
|
||||
return Err(bad("track.designate_target_playlist", "no such playlist"));
|
||||
}
|
||||
s.edit.values.insert(format!("playlist.target.{}", t.0), i as f64);
|
||||
out.push(json!({"track": t, "target": i}));
|
||||
@@ -599,8 +574,6 @@ mod tests {
|
||||
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
e.execute("track.mute_sends_ae", &json!({})).unwrap();
|
||||
assert!(e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
e.execute("track.mute_sends", &json!({})).unwrap();
|
||||
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -753,19 +726,11 @@ mod tests {
|
||||
e.execute("track.playlist_new", &json!({})).unwrap();
|
||||
e.execute("track.designate_target_playlist", &json!({})).unwrap();
|
||||
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
|
||||
let kick = e.session().track_by_name("Kick").unwrap().id;
|
||||
for index in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] {
|
||||
assert!(e.execute("track.designate_target_playlist", &json!({"index": index})).is_err(), "{index}");
|
||||
assert_eq!(target_playlist(e.session(), kick), Some(1), "{index} must leave the target unchanged");
|
||||
}
|
||||
e.execute("track.show_target_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
|
||||
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 0);
|
||||
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
|
||||
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
|
||||
e.execute("track.designate_target_playlist", &json!({"index": null})).unwrap();
|
||||
assert_eq!(target_playlist(e.session(), kick), Some(0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,8 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
offset
|
||||
),
|
||||
cmd!(query "video.list", "Movies", [], None, "{} — lists session movies with media details, clip counts, `file_found`, and any recorded `offline` reason. \
|
||||
The top-level `online` flag reports the Video Track Online setting.", always, |e, _| {
|
||||
cmd!(query "video.list", "Movies", [], None, "{} — movies used by Video tracks (path, size, rate, codec, online file, why it is offline)", always, |e, _| {
|
||||
let s = e.session();
|
||||
let rows: Vec<Value> = s
|
||||
.videos
|
||||
|
||||
@@ -1241,10 +1241,7 @@ pub(crate) fn read_aaf_plan(_: &str, _: &str, _: Option<&str>) -> Result<Value>
|
||||
Err(EngineError::Io("AAF import needs the desktop app: its media files are read from a local folder".into()))
|
||||
}
|
||||
|
||||
// Every test here plants a link, so the module and its helper are Unix-only. `cfg(test)` stays an
|
||||
// attribute of its own: clippy allows `unwrap` in tests only under a plain `#[cfg(test)]`.
|
||||
#[cfg(test)]
|
||||
#[cfg(unix)]
|
||||
mod exclusive_tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -176,13 +176,6 @@ fn place_import(
|
||||
let file_rate = info.sample_rate;
|
||||
let s = e.session_mut();
|
||||
let session_rate = s.sample_rate.hz();
|
||||
// An explicit non-audio target cannot play the clip: refuse it before registering
|
||||
// the source, like `clip.place_source` does.
|
||||
if let Some(t) = target
|
||||
&& !s.track(t).is_some_and(|tr| tr.kind == TrackKind::Audio)
|
||||
{
|
||||
return Err(EngineError::BadParams("file.import_audio".into(), "audio files go on audio tracks".into()));
|
||||
}
|
||||
let src = add_source_audio(s, name, audio, path, FileFormat::of(info));
|
||||
if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) {
|
||||
sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate);
|
||||
|
||||
@@ -562,9 +562,7 @@ mod open_tests {
|
||||
let at = |f: &str| dir.join(f).to_string_lossy().into_owned();
|
||||
assert_eq!(got[0], (stored_path("Movies/here.mov", &session).unwrap().to_string_lossy().into_owned(), None));
|
||||
assert_eq!(got[1], (at("near.mov"), None));
|
||||
// Joined part by part, as `relink_videos` does: `join("Video Files/filed.mov")` keeps the `/`,
|
||||
// which differs from the relinked path on Windows.
|
||||
assert_eq!(got[2], (dir.join("Video Files").join("filed.mov").to_string_lossy().into_owned(), None));
|
||||
assert_eq!(got[2], (at("Video Files/filed.mov"), None));
|
||||
assert_eq!(got[3], ("Old/gone.mov".into(), Some("file not found".into())));
|
||||
assert_eq!(got[4].0, stored[4]);
|
||||
assert!(got[4].1.as_deref().is_some_and(|why| why.starts_with("not opened:")), "{:?}", got[4]);
|
||||
|
||||
@@ -437,105 +437,3 @@ fn repeated_local_mob_references_fail_before_property_expansion() {
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("duplicate local reference in mobs"), "{err}");
|
||||
}
|
||||
|
||||
/// A FilmCraft-style AAF that references one external mono PCM WAV per channel, written by the
|
||||
/// shared `craft-aaf` writer around WAVs generated here.
|
||||
struct MonoWavAaf {
|
||||
dir: PathBuf,
|
||||
}
|
||||
impl MonoWavAaf {
|
||||
fn new(wav_channels: usize) -> Self {
|
||||
use craft_aaf::model::{CClip, CItem, CKind, CTrack, Composition, Document, Source};
|
||||
use craft_aaf::time::{FrameRate, Tick};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-aaf-mono-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let frames = 96_000;
|
||||
let options = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16);
|
||||
let mut sources = Vec::new();
|
||||
let mut tracks = Vec::new();
|
||||
for (i, name) in ["Dialogue.A1.wav", "Dialogue.A2.wav"].into_iter().enumerate() {
|
||||
let audio = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.25; frames]; wav_channels] };
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, craft_audio::encode(&audio, &options).unwrap()).unwrap();
|
||||
sources.push(Source {
|
||||
key: "item:1".into(),
|
||||
name: name.into(),
|
||||
kind: CKind::Sound,
|
||||
path: Some(path.display().to_string()),
|
||||
channel: None,
|
||||
channels: 1,
|
||||
file_channels: 1,
|
||||
width: 0,
|
||||
height: 0,
|
||||
frame_rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
bits: 16,
|
||||
length: Tick::from_units(frames as i64, 48000),
|
||||
offset: Tick::ZERO,
|
||||
start_tc: None,
|
||||
tc_rate: FrameRate::FPS_25,
|
||||
embedded: None,
|
||||
markers: Vec::new(),
|
||||
nested: None,
|
||||
});
|
||||
let clip = CClip { len: Tick::from_units(25, 25), source: i, start: Tick::ZERO, gain: None, name: format!("Cut {}", i + 1) };
|
||||
tracks.push(CTrack {
|
||||
kind: CKind::Sound,
|
||||
name: format!("A{}", i + 1),
|
||||
number: i as u32 + 1,
|
||||
channels: 1,
|
||||
items: vec![CItem::Clip(clip)],
|
||||
});
|
||||
}
|
||||
let composition = Composition {
|
||||
name: "Separate mono".into(),
|
||||
aaf_mob_id: None,
|
||||
rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
start_tc: 0,
|
||||
drop: false,
|
||||
tracks,
|
||||
markers: Vec::new(),
|
||||
};
|
||||
let doc = Document { compositions: vec![composition], sources, ..Document::default() };
|
||||
let identity =
|
||||
craft_aaf::Identity { company: "Craft", product: "soundcraft tests", version: "1", platform: "test", product_id: *b"soundcraft-test." };
|
||||
let bytes =
|
||||
craft_aaf::aaf::write(&doc, &craft_aaf::aaf::WriteOptions { identity, small_sectors: false }, &mut craft_aaf::Report::default()).unwrap();
|
||||
std::fs::write(dir.join("Separate mono.aaf"), bytes).unwrap();
|
||||
Self { dir }
|
||||
}
|
||||
fn preview(&self) -> soundcraft_engine::Result<Value> {
|
||||
Engine::default().execute("file.preview_aaf", &json!({"path": self.dir.join("Separate mono.aaf"), "media_dir": self.dir}))
|
||||
}
|
||||
}
|
||||
impl Drop for MonoWavAaf {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_mono_pcm_wav_aaf_imports_one_mono_track_per_file() {
|
||||
let f = MonoWavAaf::new(1);
|
||||
let preview = f.preview().unwrap();
|
||||
let plan = &preview["plan"];
|
||||
let channels: Vec<_> = plan["sources"].as_array().unwrap().iter().map(|s| s["channels"].as_u64().unwrap()).collect();
|
||||
assert_eq!(channels, [1, 1]);
|
||||
let mut e = Engine::default();
|
||||
e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap();
|
||||
assert_eq!(e.session().tracks.len(), 2);
|
||||
assert!(e.session().tracks.iter().all(|t| t.channels() == 1 && t.clips().len() == 1));
|
||||
let sources: Vec<_> = e.session().tracks.iter().map(|t| t.clips()[0].source()).collect();
|
||||
assert_ne!(sources[0], sources[1], "each channel file is its own source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pcm_descriptor_whose_channel_count_differs_from_its_wav_is_refused() {
|
||||
let f = MonoWavAaf::new(2);
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("channel counts differ"), "{err}");
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ fn kick_trim(e: &Engine) -> f32 {
|
||||
#[test]
|
||||
fn mix_pan_rejects_a_missing_or_non_numeric_pan_and_keeps_the_pan() {
|
||||
let mut e = engine_with_kick();
|
||||
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0, "index": 0})).unwrap();
|
||||
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0})).unwrap();
|
||||
assert_eq!(kick_pan(&e)[0], -1.0);
|
||||
|
||||
for params in [json!({"tracks": ["Kick"]}), json!({"tracks": ["Kick"], "pan": "left"}), json!({"tracks": ["Kick"], "pan": null})] {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! Reads the AAF structured-storage object model directly (properties streams, strong
|
||||
//! reference vectors/sets and dictionary weak references) for a deliberately small subset:
|
||||
//! one CompositionMob whose timeline slots hold Sequences of SourceClip and Filler, resolved
|
||||
//! through MasterMobs to SourceMobs with a WAVE or PCM descriptor and one external NetworkLocator.
|
||||
//! through MasterMobs to SourceMobs with a WAVEDescriptor and one external NetworkLocator.
|
||||
//! Anything else in an audio slot aborts instead of producing a misleading montage.
|
||||
//!
|
||||
//! No filesystem access happens here: the caller passes the opened AAF and a [`MediaResolver`]
|
||||
@@ -32,7 +32,6 @@
|
||||
//! locator resolves under the AAF's folder (see `locator_path`). A file that cannot be found
|
||||
//! is reported and its edits skipped; it does not abort the import.
|
||||
use crate::{ImportClip, ImportError, ImportTrack, Media, Plan, Rational, TimecodeRate};
|
||||
use craft_aaf::aaf::linked_audio::{AudioFileDescriptor, DescriptorFieldError, DescriptorKind, DescriptorProperty};
|
||||
use craft_aaf::aaf::properties::{Properties, Property, PropertyError};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
@@ -81,6 +80,8 @@ const PID_CONTENT_ESSENCE: u16 = 0x1902;
|
||||
const PID_DEF_NAME: u16 = 0x1B02;
|
||||
const PID_ESSENCE_MOB_ID: u16 = 0x2701;
|
||||
const PID_DESCRIPTOR_LOCATORS: u16 = 0x2F01;
|
||||
const PID_FILE_SAMPLE_RATE: u16 = 0x3001;
|
||||
const PID_FILE_LENGTH: u16 = 0x3002;
|
||||
const PID_HEADER_CONTENT: u16 = 0x3B03;
|
||||
const PID_URL_STRING: u16 = 0x4001;
|
||||
const PID_MOB_ID: u16 = 0x4401;
|
||||
@@ -229,8 +230,6 @@ impl Q {
|
||||
struct Obj {
|
||||
path: String,
|
||||
class: String,
|
||||
/// The class AUID in on-disk byte order, as the shared descriptor view classifies it.
|
||||
auid: [u8; 16],
|
||||
// Cached objects are cloned along source and dictionary walks; share their property payload.
|
||||
props: Rc<HashMap<u16, (u16, Vec<u8>)>>,
|
||||
}
|
||||
@@ -270,16 +269,6 @@ impl Obj {
|
||||
fn is(&self, class: &str) -> bool {
|
||||
self.class == class
|
||||
}
|
||||
/// The shared typed view of a WAVE or PCM file descriptor (craft-libs#3180); `None` for any
|
||||
/// other class.
|
||||
fn audio_descriptor<'a>(&'a self) -> Option<AudioFileDescriptor<impl Fn(u16) -> DescriptorProperty<'a> + 'a>> {
|
||||
let kind = DescriptorKind::from_auid_le(self.auid)?;
|
||||
Some(AudioFileDescriptor::new(kind, move |pid| match self.props.get(&pid) {
|
||||
None => DescriptorProperty::Missing,
|
||||
Some((form, data)) if *form == SF_DATA => DescriptorProperty::Data(data),
|
||||
Some(_) => DescriptorProperty::OtherForm,
|
||||
}))
|
||||
}
|
||||
/// Class name for messages; unknown (extension) classes print their AUID.
|
||||
fn kind(&self) -> &str {
|
||||
CLASS_NAMES.iter().find(|(id, _)| *id == self.class).map_or(self.class.as_str(), |(_, n)| n)
|
||||
@@ -306,13 +295,6 @@ fn property_error(path: &str, e: PropertyError) -> ImportError {
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor_error(field: &str, e: DescriptorFieldError) -> ImportError {
|
||||
match e {
|
||||
DescriptorFieldError::Missing | DescriptorFieldError::Truncated => fail(format!("missing or short descriptor {field}")),
|
||||
DescriptorFieldError::OtherForm => fail(format!("descriptor {field} is not a data property")),
|
||||
}
|
||||
}
|
||||
|
||||
fn property_total(current: usize, additional: usize) -> Result<usize> {
|
||||
current.checked_add(additional).filter(|total| *total <= MAX_PROPERTY_BYTES).ok_or_else(|| fail("AAF retained property data exceeds 128 MiB"))
|
||||
}
|
||||
@@ -409,7 +391,6 @@ impl<F: Read + Seek> Store<F> {
|
||||
return Err(fail(format!("{path}: not an AAF object")));
|
||||
}
|
||||
let class = entry.clsid().to_string();
|
||||
let auid = entry.clsid().to_bytes_le();
|
||||
let props_path = if path == "/" { "/properties".to_string() } else { format!("{path}/properties") };
|
||||
let d = self.stream(&props_path)?.ok_or_else(|| fail(format!("{path}: missing properties")))?;
|
||||
if d.first() != Some(&0x4c) {
|
||||
@@ -430,7 +411,7 @@ impl<F: Read + Seek> Store<F> {
|
||||
let Property { id, form, payload } = record.map_err(|e| property_error(path, e))?;
|
||||
props.insert(id, (form, payload.to_vec()));
|
||||
}
|
||||
let object = Obj { path: path.to_string(), class, auid, props: Rc::new(props) };
|
||||
let object = Obj { path: path.to_string(), class, props: Rc::new(props) };
|
||||
self.objects.insert(path.to_string(), object.clone());
|
||||
Ok(object)
|
||||
}
|
||||
@@ -689,7 +670,7 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
}
|
||||
if mob.is(CLASS_SOURCE_MOB) {
|
||||
let desc = self.store.opt_strong(&mob, PID_SOURCE_MOB_DESCRIPTOR, "EssenceDescription")?;
|
||||
if let Some(desc) = desc.filter(|d| d.audio_descriptor().is_some()) {
|
||||
if let Some(desc) = desc.filter(|d| d.is(CLASS_WAVE_DESCRIPTOR)) {
|
||||
return self.file_source(&mob, &slot, &desc, key_urn, offset);
|
||||
}
|
||||
}
|
||||
@@ -710,20 +691,12 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
}
|
||||
|
||||
fn file_source(&mut self, mob: &Obj, slot: &Obj, desc: &Obj, key: String, offset: Q) -> Result<(String, Q)> {
|
||||
// Full interleaved WAV only: selecting one physical channel needs a channel map. Track 1
|
||||
// of a mono file is the whole file (checked once the file is probed).
|
||||
let physical = slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?;
|
||||
if !matches!(physical, None | Some(0 | 1)) {
|
||||
// Full interleaved WAV only: selecting one physical channel needs a channel map.
|
||||
if !matches!(slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?, None | Some(0)) {
|
||||
return Err(fail("Physical channel selection / split stereo unsupported"));
|
||||
}
|
||||
// Each source file is located, probed and reported once, however many edits use it.
|
||||
if let Some(source) = self.sources.iter().find(|s| s.key == key) {
|
||||
if physical == Some(1) && source.channels != 1 {
|
||||
return Err(fail("Physical channel selection / split stereo unsupported"));
|
||||
}
|
||||
return Ok((key, offset));
|
||||
}
|
||||
if self.missing.iter().any(|m| m.key == key) {
|
||||
if self.sources.iter().any(|s| s.key == key) || self.missing.iter().any(|m| m.key == key) {
|
||||
return Ok((key, offset));
|
||||
}
|
||||
let name = mob.string(PID_MOB_NAME);
|
||||
@@ -748,23 +721,12 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
if !matches!(info.channels, 1 | 2) {
|
||||
return Err(fail("Only mono/stereo PCM WAV supported"));
|
||||
}
|
||||
let fields =
|
||||
desc.audio_descriptor().ok_or_else(|| fail(format!("Unsupported referenced mob/descriptor: {}", name.clone().unwrap_or_default())))?;
|
||||
let (num, den) = fields.sample_rate().map_err(|e| descriptor_error("SampleRate", e))?;
|
||||
if Q::new(i128::from(num), i128::from(den))? != Q::int(i64::from(info.sample_rate)) {
|
||||
if desc.rational(PID_FILE_SAMPLE_RATE, "descriptor SampleRate")? != Q::int(i64::from(info.sample_rate)) {
|
||||
return Err(fail(format!("Descriptor/file sample rates differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if u64::try_from(fields.length().map_err(|e| descriptor_error("Length", e))?).ok() != Some(info.frames) {
|
||||
if u64::try_from(desc.i64(PID_FILE_LENGTH, "descriptor Length")?).ok() != Some(info.frames) {
|
||||
return Err(fail(format!("Descriptor/file lengths differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if let Some(declared) = fields.pcm_channels().map_err(|e| descriptor_error("Channels", e))?
|
||||
&& declared != u32::from(info.channels)
|
||||
{
|
||||
return Err(fail(format!("Descriptor/file channel counts differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if physical == Some(1) && info.channels != 1 {
|
||||
return Err(fail("Physical channel selection / split stereo unsupported"));
|
||||
}
|
||||
let stem = Path::new(&info.path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.sources.push(Media {
|
||||
key: key.clone(),
|
||||
|
||||
@@ -263,18 +263,12 @@ impl MixEngine {
|
||||
for s in self.strips.values_mut() {
|
||||
for p in s.plugins.iter_mut().flatten() {
|
||||
p.plugin.reset();
|
||||
if p.failed && !p.retried {
|
||||
p.failed = false;
|
||||
p.retried = true;
|
||||
}
|
||||
p.failed = false;
|
||||
}
|
||||
if let Some(i) = &mut s.instrument {
|
||||
i.plugin.all_notes_off();
|
||||
i.plugin.reset();
|
||||
if i.failed && !i.retried {
|
||||
i.failed = false;
|
||||
i.retried = true;
|
||||
}
|
||||
i.failed = false;
|
||||
}
|
||||
s.held.clear();
|
||||
s.chase = true;
|
||||
|
||||
@@ -29,10 +29,6 @@ pub(crate) struct PluginSlot {
|
||||
/// so the audio thread reuses its allocation.
|
||||
lanes: Vec<usize>,
|
||||
pub(crate) failed: bool,
|
||||
/// A failed plugin is retried once on the next reset; a second failure keeps it out for the
|
||||
/// rest of the session, so a plugin that always fails stops oscillating the track's latency
|
||||
/// (and the compensation reallocations that go with it) on every stop or seek (#919).
|
||||
pub(crate) retried: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct Strip {
|
||||
@@ -207,7 +203,7 @@ impl SlotCtx<'_> {
|
||||
let state = if third { ins.state_bytes() } else { None };
|
||||
create_instance_for(&ins.plugin, state.as_deref(), self.sr, self.mb, ch, self.offline).map(|n| n.plugin)
|
||||
}?;
|
||||
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false })
|
||||
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -628,7 +624,7 @@ mod apply_params_tests {
|
||||
fn recorder() -> (PluginSlot, Arc<Mutex<Vec<(String, f32)>>>) {
|
||||
let sets = Arc::new(Mutex::new(Vec::new()));
|
||||
let plugin = Box::new(Recorder { inner: soundcraft_dsp::create("gain").unwrap(), sets: Arc::clone(&sets) });
|
||||
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }, sets)
|
||||
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false }, sets)
|
||||
}
|
||||
|
||||
fn lane(slot: u8, param: &str, point: Option<f32>) -> AutomationLane {
|
||||
|
||||
@@ -698,31 +698,6 @@ fn an_insert_that_puts_out_nan_is_taken_out_until_the_next_reset() {
|
||||
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
|
||||
}
|
||||
|
||||
/// A plugin that fails again after its one reset retry stays failed for the session, instead of
|
||||
/// oscillating the track's latency (and its delay-line reallocations) on every stop/seek (#919).
|
||||
#[test]
|
||||
fn a_repeatedly_failing_insert_gets_only_one_reset_retry() {
|
||||
let (mut s, a) = session_with_dc(0.5, 48_000);
|
||||
let _b = add_dc_track(&mut s, 0.5, 48_000);
|
||||
s.track_mut(a).unwrap().mixer.inserts[2] = Some(Insert::new("clap:test.nan"));
|
||||
let mut eng = MixEngine::new(48_000.0, 512);
|
||||
eng.set_external_instances(true);
|
||||
let both = render_block(&mut eng, &s, 0);
|
||||
eng.adopt(nan(a, 2, 1));
|
||||
let only_b = render_block(&mut eng, &s, 512);
|
||||
assert!((only_b - both / 2.0).abs() < 1e-6, "{only_b} vs {both}");
|
||||
// While failed it passes the track's audio through, dry.
|
||||
assert_eq!(render_block(&mut eng, &s, 1024), both);
|
||||
// The first reset grants the single retry; it fails again.
|
||||
eng.reset();
|
||||
assert_eq!(render_block(&mut eng, &s, 1536), only_b);
|
||||
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
|
||||
// A later reset does not retry it again: the block stays dry and the count does not move.
|
||||
eng.reset();
|
||||
assert_eq!(render_block(&mut eng, &s, 2048), both);
|
||||
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_from_an_instrument_or_a_master_insert_is_contained() {
|
||||
let mut s = synth_session(-6.0);
|
||||
|
||||
@@ -10,11 +10,6 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
craft-ui.workspace = true
|
||||
craft-behavior.workspace = true
|
||||
craft-host.workspace = true
|
||||
craft-keymap.workspace = true
|
||||
craft-theme.workspace = true
|
||||
craft-window.workspace = true
|
||||
soundcraft-time.workspace = true
|
||||
craft-audio.workspace = true
|
||||
soundcraft-midi.workspace = true
|
||||
|
||||
@@ -114,8 +114,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"End" => "Fim",
|
||||
"Extract" => "Extrair",
|
||||
"File" => "Arquivo",
|
||||
"File path" => "Caminho do arquivo",
|
||||
"Folder path" => "Caminho da pasta",
|
||||
"Format" => "Formato",
|
||||
"Grab bag" => "Diversos",
|
||||
"Grid" => "Grade",
|
||||
@@ -220,7 +218,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Renderizações e processos do AudioSuite são concluídos antes de retornar."
|
||||
}
|
||||
"Reopen the audio devices with these settings" => "Reabrir os dispositivos de áudio com estas configurações",
|
||||
"Report a problem" => "Relatar um problema",
|
||||
"Reset" => "Redefinir",
|
||||
"Reverse the order" => "Inverter a ordem",
|
||||
"Revert" => "Reverter",
|
||||
@@ -291,7 +288,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Transpose" => "Transpor",
|
||||
"Unknown label" => "Rótulo desconhecido",
|
||||
"Update check is not supported in the web browser." => "A verificação de atualizações não é compatível com o navegador.",
|
||||
"Updated by ArtCraft Launcher." => "Atualizado pelo ArtCraft Launcher.",
|
||||
"Use" => "Usar",
|
||||
"User presets need the desktop app." => "As predefinições do usuário exigem o aplicativo para desktop.",
|
||||
"Uses the edit selection." => "Usa a seleção de edição.",
|
||||
|
||||
@@ -176,7 +176,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let current=state.compositions.iter().find(|(_,id)|*id==state.composition).map_or("Choose one…".to_string(),|(n,_)|n.clone());
|
||||
// Locked while analyzing, so a finished analysis always matches the selection.
|
||||
ui.add_enabled_ui(state.busy.is_none(),|ui|{
|
||||
egui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
|
||||
craft_ui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
|
||||
for (name,id) in &state.compositions {
|
||||
if ui.selectable_label(state.composition==*id,format!("{name} ({id})")).clicked() { state.composition=id.clone(); state.preview=None; }
|
||||
}
|
||||
|
||||
@@ -81,7 +81,6 @@ impl SoundApp {
|
||||
synthetic_batch: None,
|
||||
synthetic_pointer_active: false,
|
||||
cancel_synthetic_pointer: false,
|
||||
injected_acks: VecDeque::new(),
|
||||
cancel_synthetic_keys: false,
|
||||
cancel_synthetic_scroll: false,
|
||||
input_before_scroll: None,
|
||||
@@ -112,9 +111,6 @@ impl SoundApp {
|
||||
system_fonts: true,
|
||||
theme_applied: None,
|
||||
docking_context: None,
|
||||
docks: crate::docking::LiveDocks::default(),
|
||||
framework_dialogs: craft_ui::dialog::DialogHost::new(),
|
||||
framework_host: crate::framework::host(),
|
||||
sim: None,
|
||||
record_hint: None,
|
||||
quit_requested: false,
|
||||
@@ -155,12 +151,6 @@ impl SoundApp {
|
||||
let _language = crate::localization::enter(self.ui.language);
|
||||
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
|
||||
self.engine.set_history_limit(self.ui.undo_levels);
|
||||
// A saved state (a hand-edited `ui.json`) can hold more than the menu keeps: keep the newest
|
||||
// (the list is newest first) and have the host save the corrected list.
|
||||
if self.ui.recent_sessions.len() > crate::dialogs::recent::MAX_RECENT {
|
||||
self.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
|
||||
self.recent_changed = true;
|
||||
}
|
||||
// Fonts set now take effect next frame, so draw only from the frame after.
|
||||
if !self.fonts_ready {
|
||||
if self.fonts_installed {
|
||||
@@ -192,7 +182,7 @@ impl SoundApp {
|
||||
// Frame pacing and the transport simulation use a monotonic host clock instead.
|
||||
let dt = self.tick_dt();
|
||||
self.last_frame = Some(self.uptime);
|
||||
crate::control::expire_gestures(self, ctx);
|
||||
crate::control::expire_gestures(self);
|
||||
crate::control::drain(self, ctx);
|
||||
self.note_recent_session();
|
||||
self.apply_editor_edits();
|
||||
@@ -325,7 +315,7 @@ impl SoundApp {
|
||||
// Input preparation: remember this pass's real pointer/keyboard state, which `logic` (run
|
||||
// before `ui` in each pass and alone on hidden ticks) uses for gestures and automation.
|
||||
self.pointer_down = ctx.input(|i| i.pointer.any_down());
|
||||
self.wants_keyboard = crate::framework::widget_has_keyboard(&ctx);
|
||||
self.wants_keyboard = ctx.egui_wants_keyboard_input();
|
||||
// The integration creates this Ui before logic resolves the current frame's palette.
|
||||
ui.set_style(ctx.global_style());
|
||||
if !self.fonts_ready {
|
||||
@@ -366,11 +356,8 @@ impl SoundApp {
|
||||
dialogs::show(self, &ctx);
|
||||
aaf_import::show(self, &ctx);
|
||||
updates_ui::show(self, &ctx);
|
||||
self.run_framework_dialogs(ui);
|
||||
// The sampler's drop rects are current now, so route any captured drop in this pass.
|
||||
self.route_dropped_files();
|
||||
// A scripted key (`ui.key`) is acknowledged by the framework's idle signal, not by egui's event list.
|
||||
crate::control::injected_settled(self, &ctx);
|
||||
// The pass that actually received the injected events has already dispatched their widget
|
||||
// side effects, even when it then asks for another layout pass. `received_synthetic` was
|
||||
// captured before menus and widgets, so a widget that consumed the event from InputState
|
||||
|
||||
@@ -8,7 +8,7 @@ impl SoundApp {
|
||||
self.note_host_geometry(ctx, raw);
|
||||
// Expire before injecting: a gesture that can no longer reach a UI pass must not put one
|
||||
// last copy of its events into this pass after its request was already canceled.
|
||||
crate::control::expire_gestures(self, ctx);
|
||||
crate::control::expire_gestures(self);
|
||||
// A host that could not run a UI pass retains the input this hook mutated (eframe's
|
||||
// `pending_raw_input`, the web runner's `input.raw`) and hands it back next tick. Strip the
|
||||
// copy appended last time before appending the still-pending batch again: otherwise a
|
||||
|
||||
@@ -234,8 +234,6 @@ impl SoundApp {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// Ends recording, clears the punch state and places the recorded takes
|
||||
/// (from the recorder or the take plan when the recorder is already gone).
|
||||
fn finish_recording(&mut self) {
|
||||
self.engine.transport.recording = false;
|
||||
let midi_pass = self.end_midi_pass();
|
||||
@@ -248,21 +246,13 @@ impl SoundApp {
|
||||
// The audio input stops taking in first: waiting for the MIDI below would otherwise add
|
||||
// what the input hears meanwhile to the audio takes. No input device is open when the
|
||||
// pass was MIDI only.
|
||||
let (takes, problem) = self.recorder.as_mut().map_or_else(|| (Vec::new(), None), |r| r.finish());
|
||||
// The audio thread writes down what was played up to the stop; the clips wait for that.
|
||||
let plan = self.take_plan.take();
|
||||
self.punch = None;
|
||||
self.autosaved_rev = 0;
|
||||
// The recorder can already be gone (tests run headless): the plan still names the takes,
|
||||
// so place what it holds; with neither, there is nothing to place.
|
||||
let (takes, problem) = match (&mut self.recorder, &plan) {
|
||||
(Some(r), _) => r.finish(),
|
||||
(None, Some(plan)) => (plan.takes.iter().map(|t| (t.track, t.path.clone())).collect(), None),
|
||||
(None, None) => (Vec::new(), None),
|
||||
};
|
||||
let midi_confirmed = self.await_midi_capture(midi_pass);
|
||||
// Where the pass ended: the audio engine's own position is the freshest.
|
||||
let engine_at = self.player.as_ref().map(|p| p.position());
|
||||
let stopped_at = super::midi::pass_stop(engine_at, self.engine.transport.position);
|
||||
let plan = self.take_plan.take();
|
||||
let tracks = takes.len().max(1);
|
||||
let plan = plan.unwrap_or_else(|| soundcraft_engine::io::Recording {
|
||||
start: self.record_start,
|
||||
@@ -271,6 +261,8 @@ impl SoundApp {
|
||||
rate: 0,
|
||||
takes: Vec::new(),
|
||||
});
|
||||
self.punch = None;
|
||||
self.autosaved_rev = 0;
|
||||
let ids = soundcraft_engine::io::place_recording(&mut self.engine, &plan, takes);
|
||||
// The audio engine may have confirmed the pass while the audio takes were finished: the
|
||||
// stop position and what the user is told go by one answer.
|
||||
@@ -471,14 +463,7 @@ impl SoundApp {
|
||||
}
|
||||
TransportRequest::Record => {
|
||||
if self.engine.transport.recording {
|
||||
// Punching out ends the take; while playing, the transport keeps
|
||||
// running, like QuickPunch. `finish_recording` places the take
|
||||
// without touching playback.
|
||||
if self.is_playing() {
|
||||
self.finish_recording();
|
||||
} else {
|
||||
self.stop_play();
|
||||
}
|
||||
self.stop_play();
|
||||
} else {
|
||||
self.start_recording();
|
||||
}
|
||||
@@ -577,60 +562,4 @@ mod tests {
|
||||
assert_eq!(app.fallback_take_dir().unwrap(), a, "the same folder for the rest of the run");
|
||||
let _ = std::fs::remove_dir_all(&a);
|
||||
}
|
||||
|
||||
/// Punching out (Record pressed again mid-take) ends the take and leaves the transport
|
||||
/// running, like QuickPunch: the punch clears, the take is placed inside the punch range,
|
||||
/// and playback continues from where it was.
|
||||
#[test]
|
||||
fn punching_out_while_playing_keeps_the_transport_running() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
|
||||
app.run("track.new", json!({"count": 1, "format": "mono"})).unwrap();
|
||||
let track = app.engine.session().tracks[0].id;
|
||||
// A take already recorded over the punch range, so the punch-out has something to place.
|
||||
let take = std::env::temp_dir().join(format!("soundcraft-punch-out-take-{}.wav", std::process::id()));
|
||||
let opts = craft_audio::EncodeOptions::new(craft_audio::EncodeFormat::Wav);
|
||||
std::fs::write(
|
||||
&take,
|
||||
craft_audio::encode(&craft_audio::AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 96_000]] }, &opts).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
app.record_start = 0;
|
||||
app.punch = Some(Range { start: 48_000, end: 96_000 });
|
||||
app.take_plan = Some(soundcraft_engine::io::Recording {
|
||||
start: 0,
|
||||
pass: None,
|
||||
punch: app.punch,
|
||||
rate: 48_000,
|
||||
takes: vec![soundcraft_engine::io::Take { track, path: take.clone(), channels: 1 }],
|
||||
});
|
||||
// Punch out two seconds in: the playhead must keep its place, not restart from the top.
|
||||
app.start_play(96_000, None, None);
|
||||
app.engine.transport.recording = true;
|
||||
app.engine.transport_requests.push(TransportRequest::Record);
|
||||
app.handle_transport(1.0 / 60.0);
|
||||
assert!(!app.engine.transport.recording, "the take ends");
|
||||
assert!(app.punch.is_none(), "the punch clears");
|
||||
assert!(app.is_playing(), "playback continues after the punch-out");
|
||||
assert!(app.engine.transport.position >= 96_000, "the playhead keeps its place instead of restarting");
|
||||
let clips = app.engine.session().track(track).unwrap().clips().to_vec();
|
||||
assert_eq!(clips.len(), 1, "the take is placed");
|
||||
assert_eq!(clips[0].start, 48_000, "the take is trimmed to the punch");
|
||||
assert_eq!(clips[0].end(), 96_000, "the take covers the punch");
|
||||
let _ = std::fs::remove_file(&take);
|
||||
}
|
||||
|
||||
/// A Record press while recording but not playing (a player that died mid-take, say)
|
||||
/// still stops everything, from where it was.
|
||||
#[test]
|
||||
fn a_record_press_while_recording_but_stopped_still_stops() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
|
||||
app.start_play(96_000, None, None);
|
||||
app.engine.transport.playing = false;
|
||||
app.engine.transport.recording = true;
|
||||
app.engine.transport_requests.push(TransportRequest::Record);
|
||||
app.handle_transport(1.0 / 60.0);
|
||||
assert!(!app.engine.transport.recording);
|
||||
assert!(!app.is_playing());
|
||||
assert_eq!(app.engine.transport.position, 96_000, "the playhead stays where it stopped");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ fn slice() -> impl FnMut() -> bool {
|
||||
/// Shows how far the running bounce got, with Cancel (or Esc).
|
||||
pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let Some(job) = &app.bounce else { return };
|
||||
let mut cancel = crate::framework::escape_pressed(ctx);
|
||||
let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
egui::Modal::new(egui::Id::unique("bounce_progress")).show(ctx, |ui| {
|
||||
ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);
|
||||
ui.set_width(320.0);
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
//! One-shot completion slots for `ui.screenshot` captures.
|
||||
//!
|
||||
//! The app keeps request ids, paths, deadlines, settling and budgets in its request record
|
||||
//! (`control::PendingShot`). A slot only correlates one capture with one record, checks the image against
|
||||
//! a per-image byte bound, and wakes the owning viewport.
|
||||
//!
|
||||
//! [`CaptureSlot::new`] sends nothing: send its callback with [`egui::ViewportCommand::Screenshot`]
|
||||
//! when the capture is due. The callback holds only a weak reference to the slot, so dropping the
|
||||
//! slot releases its image and makes a late result inert. Every retry needs a
|
||||
//! fresh slot and callback.
|
||||
//!
|
||||
//! The slot holds a strong [`egui::Context`]: keep it in the app's request record, never in
|
||||
//! `Context`-owned data, which would form a cycle.
|
||||
|
||||
use std::mem::size_of;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
|
||||
|
||||
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
|
||||
|
||||
/// Why a completed screenshot was rejected and released.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CaptureError {
|
||||
/// The checked pixel count, or its byte count, overflowed `usize`.
|
||||
DimensionsOverflow { width: usize, height: usize },
|
||||
/// The pixel buffer does not match the dimensions, or the image has no area.
|
||||
MalformedImage { width: usize, height: usize, pixels: usize },
|
||||
/// The image is larger than the slot's per-image byte bound.
|
||||
ImageTooLarge { bytes: usize, max_bytes: usize },
|
||||
}
|
||||
|
||||
impl core::fmt::Display for CaptureError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::DimensionsOverflow { width, height } => {
|
||||
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
|
||||
}
|
||||
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
|
||||
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CaptureError {}
|
||||
|
||||
enum SlotState {
|
||||
Pending,
|
||||
Ready(Result<Arc<ColorImage>, CaptureError>),
|
||||
Taken,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<SlotState>,
|
||||
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
|
||||
context: Context,
|
||||
viewport: ViewportId,
|
||||
max_image_bytes: usize,
|
||||
}
|
||||
|
||||
/// The live request side of a capture. Dropping it cancels the completion and releases any
|
||||
/// retained image.
|
||||
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
|
||||
pub(crate) struct CaptureSlot {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
impl CaptureSlot {
|
||||
/// A completion slot for a capture of `viewport` and its one-shot callback. `max_image_bytes`
|
||||
/// bounds this one image; the app reserves its aggregate budget itself.
|
||||
pub(crate) fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
|
||||
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
|
||||
let weak = Arc::downgrade(&shared);
|
||||
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
|
||||
(Self { shared }, callback)
|
||||
}
|
||||
|
||||
/// The completed result, at most once; `None` while pending and after an
|
||||
/// earlier take. The request record knows which.
|
||||
pub(crate) fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
|
||||
let mut state = lock(&self.shared.state);
|
||||
if !matches!(&*state, SlotState::Ready(_)) {
|
||||
return None;
|
||||
}
|
||||
match core::mem::replace(&mut *state, SlotState::Taken) {
|
||||
SlotState::Ready(result) => Some(result),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureSlot {
|
||||
fn drop(&mut self) {
|
||||
close(&self.shared);
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for CaptureSlot {
|
||||
/// The viewport only: logging never holds or dumps screenshot contents.
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Locks the slot state, recovering from poisoning. Release the guard before calling into the
|
||||
/// context: a repaint observer may take or cancel re-entrantly.
|
||||
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
|
||||
state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Marks the slot closed; the retained image drops after the mutex is released.
|
||||
fn close(shared: &Shared) {
|
||||
let previous = {
|
||||
let mut state = lock(&shared.state);
|
||||
core::mem::replace(&mut *state, SlotState::Cancelled)
|
||||
};
|
||||
drop(previous);
|
||||
}
|
||||
|
||||
/// Checks and stores a completed image, then wakes the owning viewport, with the slot lock
|
||||
/// released. A cancelled, taken or dropped slot stores nothing and does not wake.
|
||||
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
|
||||
let Some(shared) = weak.upgrade() else { return };
|
||||
let result = checked_image(image, shared.max_image_bytes);
|
||||
let wake = {
|
||||
let mut state = lock(&shared.state);
|
||||
if matches!(&*state, SlotState::Pending) {
|
||||
*state = SlotState::Ready(result);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
if wake {
|
||||
shared.context.request_repaint_of(shared.viewport);
|
||||
}
|
||||
}
|
||||
|
||||
/// `image` when it has area, its buffer matches its size, and its byte count (checked) is within
|
||||
/// `max_image_bytes`.
|
||||
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
|
||||
let [width, height] = image.size;
|
||||
if width == 0 || height == 0 {
|
||||
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
|
||||
}
|
||||
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
|
||||
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
|
||||
if image.pixels.len() != pixels {
|
||||
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
|
||||
}
|
||||
if bytes > max_image_bytes {
|
||||
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
|
||||
}
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn image(size: [usize; 2]) -> Arc<ColorImage> {
|
||||
Arc::new(ColorImage::filled(size, Color32::RED))
|
||||
}
|
||||
|
||||
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let observed = requests.clone();
|
||||
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
|
||||
requests
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completion_wakes_its_viewport_and_is_taken_once() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::from_hash_of("window");
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
|
||||
assert!(slot.take().is_none(), "pending");
|
||||
let shot = image([2, 1]);
|
||||
callback.complete(shot.clone());
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &shot));
|
||||
assert!(slot.take().is_none(), "taken once");
|
||||
assert_eq!(*requests.lock().unwrap(), [viewport]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_slot_releases_a_late_image_without_waking() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
drop(slot);
|
||||
let late = image([2, 2]);
|
||||
let weak = Arc::downgrade(&late);
|
||||
callback.complete(late);
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(requests.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_malformed_and_overflowing_images_are_errors() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
|
||||
callback.complete(image([3, 3]));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![Color32::RED; 3] }));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { .. }))));
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//! SoundCraft's native window caption, with an explicitly selected channel name.
|
||||
|
||||
/// The OS window title beside a native menu bar, which shows neither the document nor its unsaved
|
||||
/// marker anywhere else: Stable's exact format, `"{document}{ *} — SoundCraft — {section}"`, with
|
||||
/// only the channel's name substituted, so a Nightly window never looks like a stable one.
|
||||
pub fn os_title_with_section(app_name: &str, document: Option<(&str, bool)>, section: &str) -> String {
|
||||
let Some((name, dirty)) = document else { return app_name.into() };
|
||||
format!("{name}{} \u{2014} {app_name} \u{2014} {section}", if dirty { " *" } else { "" })
|
||||
}
|
||||
|
||||
/// The OS window title without a native menu bar. The egui menu bar already shows the unsaved
|
||||
/// marker, so Stable keeps it out of the title: `"{document} — SoundCraft"`, with only the
|
||||
/// channel's name substituted.
|
||||
pub fn os_title(app_name: &str, document: Option<&str>) -> String {
|
||||
match document {
|
||||
Some(name) => format!("{name} \u{2014} {app_name}"),
|
||||
None => app_name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Stable's title is user-visible and must not change when the channel's name is substituted.
|
||||
#[test]
|
||||
fn stable_caption_is_unchanged_in_both_menu_bar_states() {
|
||||
assert_eq!(os_title("SoundCraft", None), "SoundCraft");
|
||||
assert_eq!(os_title("SoundCraft", Some("Song")), "Song \u{2014} SoundCraft");
|
||||
assert_eq!(os_title_with_section("SoundCraft", None, "Edit"), "SoundCraft");
|
||||
assert_eq!(os_title_with_section("SoundCraft", Some(("Song", false)), "Edit"), "Song \u{2014} SoundCraft \u{2014} Edit");
|
||||
// Stable marks unsaved changes between the name and the separator, never as a prefix.
|
||||
assert_eq!(os_title_with_section("SoundCraft", Some(("Song", true)), "Mix"), "Song * \u{2014} SoundCraft \u{2014} Mix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_native_caption_keeps_channel_across_document_dirty_and_menu_bar_states() {
|
||||
let channel = "SoundCraft Nightly";
|
||||
assert_eq!(os_title(channel, None), channel);
|
||||
assert_eq!(os_title(channel, Some("my session.scraft")), "my session.scraft \u{2014} SoundCraft Nightly");
|
||||
assert_eq!(
|
||||
os_title_with_section(channel, Some(("my session.scraft", false)), "Edit"),
|
||||
"my session.scraft \u{2014} SoundCraft Nightly \u{2014} Edit"
|
||||
);
|
||||
for section in ["Edit", "Mix"] {
|
||||
let shown = os_title_with_section(channel, Some(("my session.scraft", true)), section);
|
||||
assert_eq!(shown, format!("my session.scraft * \u{2014} SoundCraft Nightly \u{2014} {section}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,7 @@
|
||||
//! inspect, command or screenshot after the gesture it follows.
|
||||
|
||||
use crate::SoundApp;
|
||||
use crate::capture::CaptureSlot;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::capture::CaptureSlot;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use web_time::Instant;
|
||||
@@ -37,7 +36,7 @@ impl ControlRequest {
|
||||
}
|
||||
|
||||
/// One admitted `ui.screenshot` request. The app owns the strong completion slot; the callback the
|
||||
/// renderer receives holds only a weak reference to it (see `crate::capture`).
|
||||
/// renderer receives holds only a weak reference to it (see `craft_ui::capture`).
|
||||
pub(crate) struct PendingShot {
|
||||
token: u64,
|
||||
/// Taken once the single reply (success, timeout, cancellation or failure) was sent.
|
||||
@@ -279,32 +278,9 @@ pub(crate) struct GestureAck {
|
||||
response: Value,
|
||||
}
|
||||
|
||||
/// A `ui.key` request whose reply waits for the framework's injected input to run: the runtime owns the key's path
|
||||
/// (it takes keys such as Escape out of egui's event list), so only its own idle signal says the key was delivered.
|
||||
pub(crate) struct InjectedAck {
|
||||
deadline: Instant,
|
||||
reply: Option<Sender<Value>>,
|
||||
response: Value,
|
||||
}
|
||||
|
||||
/// True while a scripted gesture has events waiting or an applied batch still needs acknowledging.
|
||||
pub(crate) fn gesture_pending(app: &SoundApp) -> bool {
|
||||
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some() || !app.injected_acks.is_empty()
|
||||
}
|
||||
|
||||
/// Reply to every queued `ui.key` once the framework's injected input has run, asked at the end of the pass that ran
|
||||
/// the key (a pass egui repeats does not count).
|
||||
pub(crate) fn injected_settled(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if app.injected_acks.is_empty() || !WindowHost::of(ctx).injected_idle_at_pass_end() {
|
||||
return;
|
||||
}
|
||||
for mut ack in std::mem::take(&mut app.injected_acks) {
|
||||
if let Some(tx) = ack.reply.take() {
|
||||
let _ = tx.send(ack.response);
|
||||
}
|
||||
}
|
||||
// The next request queued behind this key needs a logic tick to be drained now that the barrier is gone.
|
||||
ctx.request_repaint();
|
||||
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some()
|
||||
}
|
||||
|
||||
/// Count one delivered batch against the front gesture. Batches never straddle requests (a key
|
||||
@@ -331,16 +307,8 @@ pub(crate) fn synthetic_delivered(app: &mut SoundApp, delivered: usize) {
|
||||
/// A gesture that cannot reach a UI pass (a host that never paints) must not wedge every later
|
||||
/// control request. Cancel the whole pending gesture chain: FIFO means no later request can run
|
||||
/// while an earlier undelivered click is still waiting.
|
||||
pub(crate) fn expire_gestures(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
pub(crate) fn expire_gestures(app: &mut SoundApp) {
|
||||
let now = app.clock_now();
|
||||
if app.injected_acks.iter().any(|ack| now >= ack.deadline) {
|
||||
WindowHost::of(ctx).withdraw_injected(egui::ViewportId::ROOT);
|
||||
for mut ack in std::mem::take(&mut app.injected_acks) {
|
||||
if let Some(tx) = ack.reply.take() {
|
||||
let _ = tx.send(err("synthetic input was not delivered"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !app.gesture_acks.iter().any(|ack| now >= ack.deadline) {
|
||||
return;
|
||||
}
|
||||
@@ -576,16 +544,12 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
|
||||
"ui.key" => {
|
||||
let name = p.get("key").and_then(Value::as_str).unwrap_or("");
|
||||
let Some(key) = key_from(name) else { return Some(err(format!("unknown key `{name}`"))) };
|
||||
let Some(key) = craft_keymap::Key::from_egui(key) else { return Some(err(format!("key `{name}` has no keymap key"))) };
|
||||
let mods = craft_keymap::Mods::from_egui(&mods(p), craft_keymap::egui::platform(ctx));
|
||||
// The framework's injected input carries the key through its own stages and says when it has run.
|
||||
WindowHost::of(ctx).inject_key(egui::ViewportId::ROOT, key, mods, false);
|
||||
app.injected_acks.push_back(InjectedAck {
|
||||
deadline: app.clock_now() + GESTURE_TIMEOUT,
|
||||
reply: Some(req.reply.clone()),
|
||||
response: ok(json!({})),
|
||||
});
|
||||
return None;
|
||||
let m = mods(p);
|
||||
let events = vec![
|
||||
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m },
|
||||
egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: m },
|
||||
];
|
||||
return queue_reply(app, req, events, json!({}));
|
||||
}
|
||||
"ui.text" => {
|
||||
let t = p.get("text").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
@@ -93,7 +93,6 @@ fn tmp(name: &str) -> PathBuf {
|
||||
#[test]
|
||||
fn a_screenshot_completes_once_and_writes_one_file() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let path = tmp("success");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
@@ -115,7 +114,6 @@ fn a_screenshot_completes_once_and_writes_one_file() {
|
||||
#[test]
|
||||
fn a_callback_after_the_deadline_times_out_without_writing() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let path = tmp("late");
|
||||
let reply = request(&mut a, Some(&path));
|
||||
@@ -134,7 +132,6 @@ fn a_callback_after_the_deadline_times_out_without_writing() {
|
||||
#[test]
|
||||
fn a_session_change_cancels_the_request_and_releases_its_pixels() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let path = tmp("document");
|
||||
let reply = request(&mut a, Some(&path));
|
||||
@@ -153,7 +150,6 @@ fn a_session_change_cancels_the_request_and_releases_its_pixels() {
|
||||
#[test]
|
||||
fn admission_rejects_more_than_eight_pending_requests() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
for i in 0..MAX_PENDING_SHOTS {
|
||||
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
@@ -169,7 +165,6 @@ fn admission_rejects_more_than_eight_pending_requests() {
|
||||
#[test]
|
||||
fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
let mut big = raw_input(5000.0, 5000.0, 8192);
|
||||
a.raw_input_hook(&ctx, &mut big);
|
||||
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
@@ -195,7 +190,6 @@ fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
|
||||
#[test]
|
||||
fn a_changed_window_retries_once_instead_of_writing_stale_pixels() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let path = tmp("retry");
|
||||
let reply = request(&mut a, Some(&path));
|
||||
@@ -254,7 +248,6 @@ fn a_missing_max_texture_side_uses_the_last_known_limit() {
|
||||
#[test]
|
||||
fn a_window_without_geometry_reports_no_capturable_size() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.host_geometry = Some(CaptureGeometry { points: egui::Vec2::ZERO, pixels_per_point: 1.0, max_texture_side: 8192, focused: true });
|
||||
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
let e = admit(&mut a, &ctx, &req).expect_err("no capturable size");
|
||||
@@ -266,7 +259,6 @@ fn a_window_without_geometry_reports_no_capturable_size() {
|
||||
#[test]
|
||||
fn a_document_replaced_outside_run_cancels_a_pending_capture() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let reply = request(&mut a, None);
|
||||
let out = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
|
||||
@@ -286,7 +278,6 @@ fn a_document_replaced_outside_run_cancels_a_pending_capture() {
|
||||
#[test]
|
||||
fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let kick = a.engine.session().track_by_name("Kick").expect("demo has Kick").id;
|
||||
assert!(!a.engine.session().track(kick).expect("kick").mixer.mute);
|
||||
@@ -347,7 +338,6 @@ fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
|
||||
#[test]
|
||||
fn a_capture_slot_is_bounded_by_its_own_reservation() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let (tx, rx) = channel();
|
||||
let (req, first) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
@@ -389,7 +379,6 @@ fn png_bytes_checks_its_dimensions_and_allocation() {
|
||||
#[test]
|
||||
fn control_input_queues_and_text_are_bounded() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.synthetic = (0..MAX_SYNTHETIC_EVENTS).map(|_| egui::Event::PointerMoved(egui::pos2(0.0, 0.0))).collect();
|
||||
let (req, _reply) = ControlRequest::new("ui.move", json!({"x": 1.0, "y": 2.0}));
|
||||
let v = handle(&mut a, &ctx, &req).expect("the refusal replies immediately");
|
||||
@@ -416,7 +405,6 @@ fn control_input_queues_and_text_are_bounded() {
|
||||
#[test]
|
||||
fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let path = "x".repeat(MAX_SHOT_PATH_BYTES + 1);
|
||||
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({"path": path}));
|
||||
@@ -430,11 +418,10 @@ fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
|
||||
#[test]
|
||||
fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
let (req, reply) = ControlRequest::new("ui.click", json!({"x": 10.0, "y": 10.0}));
|
||||
assert!(handle(&mut a, &ctx, &req).is_none(), "the click waits for a UI pass");
|
||||
a.advance_test_clock(Duration::from_secs(16));
|
||||
expire_gestures(&mut a, &ctx);
|
||||
expire_gestures(&mut a);
|
||||
let v = reply.try_recv().expect("the canceled gesture has exactly one reply");
|
||||
assert_eq!(v["ok"], false, "{v}");
|
||||
assert!(v["error"].as_str().unwrap_or_default().contains("not delivered"), "{v}");
|
||||
@@ -453,7 +440,6 @@ fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
|
||||
fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works() {
|
||||
for expires_after_hook in [false, true] {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
let kick = a.engine.session().track_by_name("Kick").unwrap().id;
|
||||
@@ -503,28 +489,48 @@ fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works(
|
||||
/// An expired scripted shortcut never reaches widgets or end-of-pass handling, while a simultaneous host shortcut
|
||||
/// still runs and a later script succeeds.
|
||||
#[test]
|
||||
fn a_timed_out_scripted_key_does_not_run_and_the_next_key_works() {
|
||||
fn a_timed_out_scripted_key_after_the_hook_does_not_run_and_the_next_key_works() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
|
||||
let depth = a.engine.undo_history().len();
|
||||
assert!(depth > 0, "the test needs an undoable edit");
|
||||
let applied = a.synthetic_applied_batches;
|
||||
let quickpunch = a.engine.session().edit.quickpunch;
|
||||
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
|
||||
assert!(handle(&mut a, &ctx, &req).is_none());
|
||||
assert!(gesture_pending(&a), "the key waits for the framework to run it");
|
||||
let mut raw = raw_input(800.0, 600.0, 8192);
|
||||
// A real, unrelated shortcut in the same pass must still be dispatched after the expired
|
||||
// scripted batch is removed.
|
||||
let command_shift = egui::Modifiers { command: true, shift: true, ..egui::Modifiers::NONE };
|
||||
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: command_shift });
|
||||
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: false, repeat: false, modifiers: command_shift });
|
||||
a.raw_input_hook(&ctx, &mut raw);
|
||||
assert!(a.synthetic_batch.is_some(), "the key batch waits for a UI pass");
|
||||
|
||||
// The deadline crosses before any pass ran the key.
|
||||
// The deadline crosses after the hook handed the key to egui but before logic and widgets.
|
||||
a.advance_test_clock(Duration::from_secs(16));
|
||||
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
a.logic(ui.ctx());
|
||||
a.ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let canceled = reply.try_recv().expect("one cancellation reply");
|
||||
assert_eq!(canceled["ok"], false, "{canceled}");
|
||||
assert!(!gesture_pending(&a));
|
||||
assert!(a.synthetic_batch.is_none(), "the expired batch is dropped");
|
||||
assert_eq!(a.synthetic_applied_batches, applied, "an expired batch is not delivered");
|
||||
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut");
|
||||
assert_eq!(a.engine.session().edit.quickpunch, !quickpunch, "a simultaneous host shortcut still runs");
|
||||
assert!(!a.cancel_synthetic_keys);
|
||||
assert!(
|
||||
ctx.input(|i| !i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Z, .. }))),
|
||||
"the expired key is gone from the pass, not left for widgets or end-of-pass shortcuts"
|
||||
);
|
||||
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
|
||||
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut, now or later");
|
||||
assert_eq!(a.engine.undo_history().len(), depth, "a later frame must not replay it");
|
||||
|
||||
// A fresh key after the timeout still works and runs exactly once.
|
||||
// A fresh gesture after the timeout still works and runs exactly once.
|
||||
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
|
||||
assert!(handle(&mut a, &ctx, &req).is_none());
|
||||
deliver_gestures(&mut a, &ctx);
|
||||
@@ -532,19 +538,6 @@ fn a_timed_out_scripted_key_does_not_run_and_the_next_key_works() {
|
||||
assert_eq!(a.engine.undo_history().len(), depth - 1, "a completed key still undoes exactly once");
|
||||
}
|
||||
|
||||
/// The framework takes Escape out of egui's event list; the key is still acknowledged.
|
||||
#[test]
|
||||
fn a_scripted_escape_is_acknowledged() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Escape"}));
|
||||
assert!(handle(&mut a, &ctx, &req).is_none());
|
||||
deliver_gestures(&mut a, &ctx);
|
||||
assert_eq!(reply.try_recv().expect("an acknowledgement")["ok"], true);
|
||||
}
|
||||
|
||||
/// Current timeline zoom, horizontal scroll and vertical scroll, compared before and after a gesture.
|
||||
fn view(a: &SoundApp) -> (f64, i64, f32) {
|
||||
let zoom = a.engine.session().edit.zoom;
|
||||
@@ -580,7 +573,6 @@ fn host_line_wheel(dy: f32) -> egui::Event {
|
||||
#[test]
|
||||
fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
// Make the track area overflow so a real wheel would actually move the view.
|
||||
@@ -657,7 +649,6 @@ fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing(
|
||||
#[test]
|
||||
fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_works_once() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
let at = timeline_center(&a);
|
||||
@@ -719,7 +710,6 @@ fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_work
|
||||
#[test]
|
||||
fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
|
||||
@@ -759,7 +749,6 @@ fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
|
||||
#[test]
|
||||
fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
|
||||
@@ -801,7 +790,6 @@ fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
|
||||
#[test]
|
||||
fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
|
||||
@@ -854,7 +842,6 @@ fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
|
||||
#[test]
|
||||
fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.advance_test_clock(Duration::ZERO);
|
||||
warm(&mut a, &ctx);
|
||||
let before: Vec<_> = a.engine.session().tracks.iter().map(|track| track.id).collect();
|
||||
@@ -895,7 +882,6 @@ fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
|
||||
#[test]
|
||||
fn scroll_reports_the_wheel_and_trackpad_sources_after_delivery() {
|
||||
let (mut a, ctx) = (app(), egui::Context::default());
|
||||
crate::framework::install_headless(&ctx);
|
||||
warm(&mut a, &ctx);
|
||||
let (req, reply) = ControlRequest::new("ui.scroll", json!({"x": 10.0, "y": 10.0, "dy": -30.0, "unit": "line", "steps": 2}));
|
||||
assert!(handle(&mut a, &ctx, &req).is_none(), "the reply waits for delivery");
|
||||
|
||||
@@ -221,7 +221,7 @@ fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) {
|
||||
}
|
||||
ui.separator();
|
||||
let sort = ui.label(crate::localization::text("Sort"));
|
||||
let combo = egui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
|
||||
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
|
||||
for k in SortKey::ALL {
|
||||
if ui.selectable_label(v.key == k, crate::localization::text(k.label().0)).clicked() {
|
||||
v.key = k;
|
||||
|
||||
@@ -342,8 +342,7 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
|
||||
|
||||
/// The path prompt's form; the command to run once it is confirmed.
|
||||
fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> {
|
||||
let label = if key == "dir" { crate::localization::text("Folder path") } else { crate::localization::text("File path") };
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), label);
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("Path"));
|
||||
let mut picked = None;
|
||||
// Import Audio picks several files at once; every other open dialog takes one.
|
||||
let multi = cmd == "file.import_audio" && app.services.pick_open_many.is_some();
|
||||
@@ -445,9 +444,7 @@ fn strip_silence_form(
|
||||
mode = Some("separate");
|
||||
}
|
||||
// Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked.
|
||||
// The button is its own string ("Strip Silence"), not the Channel Strip plug-in's
|
||||
// short name "Strip", so translations can give them different words (#1610).
|
||||
if buttons(ui, "Strip Silence", enter) && mode.is_none() {
|
||||
if buttons(ui, "Strip", enter) && mode.is_none() {
|
||||
mode = Some("strip");
|
||||
}
|
||||
// Enter on a focused Rename… also presses Strip, so Rename… goes first.
|
||||
@@ -515,8 +512,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// button only when no widget has the keyboard focus or a text field has it. A held Enter's repeats do not press it.
|
||||
let fresh_enter =
|
||||
|i: &egui::InputState| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }));
|
||||
let enter = !first_frame && ctx.input(fresh_enter) && (!crate::framework::widget_has_keyboard(ctx) || ctx.text_edit_focused());
|
||||
let esc = crate::framework::escape_pressed(ctx);
|
||||
let enter = !first_frame && ctx.input(fresh_enter) && (ctx.memory(|m| m.focused().is_none()) || ctx.text_edit_focused());
|
||||
let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
egui::Window::new(egui::RichText::new(crate::localization::text(&title)).font(bold(13.0)))
|
||||
.id(egui::Id::unique(&title))
|
||||
.collapsible(false)
|
||||
@@ -539,7 +536,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.label(crate::localization::text("Name"));
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
|
||||
});
|
||||
egui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
|
||||
for r in soundcraft_time::SampleRate::COMMON {
|
||||
ui.selectable_value(sample_rate, r, format!("{r} Hz"));
|
||||
}
|
||||
@@ -555,12 +552,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
Dialog::Bounce { path, format, bit_depth, normalize, dither } => {
|
||||
bounce_file_row(app, ui, path, format);
|
||||
ui.horizontal(|ui| {
|
||||
egui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
|
||||
for &f in EncodeFormat::ALL {
|
||||
ui.selectable_value(format, f, f.container().name());
|
||||
}
|
||||
});
|
||||
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
|
||||
for b in ["16", "24", "32f"] {
|
||||
ui.selectable_value(bit_depth, b.to_string(), crate::localized_format!("{b}-bit", b = b));
|
||||
}
|
||||
@@ -704,12 +701,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
Dialog::Session { frame_rate, bit_depth } => {
|
||||
egui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
|
||||
for r in soundcraft_time::FrameRate::ALL {
|
||||
ui.selectable_value(frame_rate, r.label().to_string(), crate::localization::text(r.label()));
|
||||
}
|
||||
});
|
||||
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
|
||||
for b in ["16", "24", "32f"] {
|
||||
ui.selectable_value(bit_depth, b.to_string(), crate::localization::text(b));
|
||||
}
|
||||
@@ -722,7 +719,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let s = app.engine.session();
|
||||
ui.horizontal(|ui| {
|
||||
let count_label = ui.radio_value(by, LoopBy::Count, crate::localization::text("Number of Loops"));
|
||||
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=1000)).labelled_by(count_label.id);
|
||||
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=512)).labelled_by(count_label.id);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let length_label = ui.radio_value(by, LoopBy::Length, crate::localization::text("Loop Length"));
|
||||
|
||||
@@ -183,7 +183,7 @@ impl NewTracks {
|
||||
ui.label(crate::localization::text("new"));
|
||||
let format = if has_format(&row.kind) {
|
||||
Some(
|
||||
egui::ComboBox::from_id_salt("nt_fmt")
|
||||
craft_ui::ComboBox::from_id_salt("nt_fmt")
|
||||
.width(widths.format)
|
||||
.selected_text(crate::localization::text(&row.format))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -198,7 +198,7 @@ impl NewTracks {
|
||||
ui.allocate_space(vec2(widths.format, ui.spacing().interact_size.y));
|
||||
None
|
||||
};
|
||||
let kind = egui::ComboBox::from_id_salt("nt_kind")
|
||||
let kind = craft_ui::ComboBox::from_id_salt("nt_kind")
|
||||
.width(widths.kind)
|
||||
.selected_text(crate::localization::text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label())))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -213,7 +213,7 @@ impl NewTracks {
|
||||
let timebase = if has_timebase(&row.kind) {
|
||||
ui.label(crate::localization::text("in"));
|
||||
Some(
|
||||
egui::ComboBox::from_id_salt("nt_tb")
|
||||
craft_ui::ComboBox::from_id_salt("nt_tb")
|
||||
.width(widths.timebase)
|
||||
.selected_text(crate::localization::text(if row.timebase == "ticks" { "Ticks" } else { "Samples" }))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -360,7 +360,7 @@ mod tests {
|
||||
fn harness() -> Harness<'static, SoundApp> {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
assert!(app.dialogs.open_for_command(&app.engine, "track.new"));
|
||||
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
|
||||
@@ -162,14 +162,13 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 200.0))
|
||||
.show(ctx, |ui| {
|
||||
egui::ComboBox::from_label(crate::localization::text("Curve")).selected_text(crate::localization::text(&app.ops.tempo_curve)).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
|
||||
.selected_text(crate::localization::text(&app.ops.tempo_curve))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
|
||||
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
|
||||
.accessible_name(crate::localization::text("Start tempo (BPM)"));
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
|
||||
@@ -201,21 +200,20 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 200.0))
|
||||
.show(ctx, |ui| {
|
||||
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.time_op)).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
|
||||
.selected_text(crate::localization::text(&app.ops.time_op))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["insert", "cut", "change meter", "move song start"] {
|
||||
ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
match app.ops.time_op.as_str() {
|
||||
"change meter" => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
|
||||
.accessible_name(crate::localization::text("Meter numerator"));
|
||||
ui.label(crate::localization::text("/"));
|
||||
let den = egui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
|
||||
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
|
||||
for d in [2u32, 4, 8, 16] {
|
||||
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
|
||||
}
|
||||
@@ -255,17 +253,16 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 220.0))
|
||||
.show(ctx, |ui| {
|
||||
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.midi_op)).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
|
||||
.selected_text(crate::localization::text(&app.ops.midi_op))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
|
||||
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
match app.ops.midi_op.as_str() {
|
||||
"quantize" => {
|
||||
egui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
|
||||
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
|
||||
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
|
||||
}
|
||||
|
||||
@@ -159,19 +159,4 @@ mod tests {
|
||||
let ui: crate::UiState = serde_json::from_str("{}").unwrap();
|
||||
assert!(ui.recent_sessions.is_empty());
|
||||
}
|
||||
|
||||
/// A saved state with more entries than the menu keeps (a hand-edited `ui.json`) is cut to
|
||||
/// the newest [`MAX_RECENT`] on the first frame, and a list within the limit is left alone.
|
||||
/// Cutting it tells the host to save, so the file is corrected without waiting for a clean exit.
|
||||
#[test]
|
||||
fn an_oversized_saved_list_is_capped_on_the_first_frame() {
|
||||
let paths = |count: usize| (0..count).map(|i| format!("{i}.scraft")).collect::<Vec<_>>();
|
||||
for (saved, kept) in [(1000, MAX_RECENT), (MAX_RECENT + 1, MAX_RECENT), (MAX_RECENT, MAX_RECENT), (3, 3), (0, 0)] {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
|
||||
app.ui = serde_json::from_value(json!({"recent_sessions": paths(saved)})).unwrap();
|
||||
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut SoundApp| app.logic(&ui.ctx().clone()), app);
|
||||
assert_eq!(harness.state().ui.recent_sessions, paths(kept), "{saved} saved entries");
|
||||
assert_eq!(harness.state_mut().take_recent_changed(), saved > kept, "{saved} saved entries: save only when entries were cut");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,11 +155,12 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples)
|
||||
pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
|
||||
egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
|
||||
let scale = ui.label(crate::localization::text("Time Scale"));
|
||||
let time_scale = egui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
|
||||
for f in TimeFormat::ALL {
|
||||
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
|
||||
}
|
||||
});
|
||||
let time_scale =
|
||||
craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
|
||||
for f in TimeFormat::ALL {
|
||||
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
|
||||
}
|
||||
});
|
||||
time_scale.response.labelled_by(scale.id);
|
||||
ui.end_row();
|
||||
for (i, label) in FIELDS.into_iter().enumerate() {
|
||||
|
||||
+175
-448
@@ -1,21 +1,11 @@
|
||||
//! Application panel identities and persistence around craft-ui's `DockArea`. Document contents remain owned by
|
||||
//! their existing view implementations.
|
||||
//!
|
||||
//! `UiState::docking` and `UiState::mix_docking` are the saved workspaces and the source of truth. The dock shows an
|
||||
//! `Arc` of each ([`LiveDocks`]), kept while the saved workspace is unchanged; every change the dock reports goes
|
||||
//! through [`command_for`] like a `ui.dock` command.
|
||||
//! Application panel identities and persistence around the shared docking renderer.
|
||||
//! Document contents remain owned by their existing view implementations.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::DockSide;
|
||||
use craft_behavior::dock::{
|
||||
Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, Location, Node, Permissions, SplitSize, Target,
|
||||
use craft_ui::docking::{
|
||||
Action, Column, DockArea, DockCommand, DockError, DockOperation, DockStyle, FloatSpace, Floating, Group, Layout, Location, Node, PanelLimits,
|
||||
Permissions, Placement, Side, Target, UiDock, Zone, ZoneName,
|
||||
};
|
||||
use craft_behavior::flow::Axis;
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use egui::{Rect, pos2, vec2};
|
||||
use craft_ui::layout::{SplitAxis, SplitSize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -52,41 +42,48 @@ pub const CLIPS_WIDTH: f32 = 230.0;
|
||||
pub const MIDI_HEIGHT: f32 = 320.0;
|
||||
|
||||
/// An Edit or Mix panel arrangement, saved with the UI preferences.
|
||||
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
|
||||
pub type Workspace = craft_ui::docking::Workspace<Panel>;
|
||||
|
||||
/// The height the MIDI editor's tab adds above its body in the default layout.
|
||||
const MIDI_TAB_HEIGHT: f32 = 28.0;
|
||||
const MIDI_TAB_HEIGHT: f32 = 26.0;
|
||||
|
||||
/// The document view stays docked and open, and panels open in splits beside it.
|
||||
fn permissions(panel: &Panel) -> Permissions {
|
||||
if *panel == Panel::Canvas { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
|
||||
if *panel == Panel::Canvas { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
|
||||
}
|
||||
|
||||
fn tabs(panel: Panel) -> Node<Panel> {
|
||||
Node::tabs(vec![panel], 0)
|
||||
Node::Tabs { panels: vec![panel], active: 0 }
|
||||
}
|
||||
|
||||
/// The id the Edit or Mix dock area is drawn under.
|
||||
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
|
||||
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
|
||||
/// The dock area that draws the Edit or Mix workspace.
|
||||
pub fn area_id(window: crate::MainWindow) -> egui::Id {
|
||||
egui::Id::unique(("soundcraft-docking", window == crate::MainWindow::Edit))
|
||||
}
|
||||
|
||||
/// A dock on `side` with one column holding `panel`.
|
||||
fn dock(side: DockEdge, panel: Panel, width: f32) -> Node<Panel> {
|
||||
Node::dock(side, vec![Column::new(vec![Group::new(vec![panel], 0)]).with_width(width)])
|
||||
fn area(edit: bool) -> egui::Id {
|
||||
area_id(if edit { crate::MainWindow::Edit } else { crate::MainWindow::Mix })
|
||||
}
|
||||
|
||||
const MEMORY_RECT: Rect = Rect::from_min_max(pos2(160.0, 120.0), pos2(640.0, 400.0));
|
||||
const HISTORY_RECT: Rect = Rect::from_min_max(pos2(680.0, 120.0), pos2(940.0, 420.0));
|
||||
/// A dock on `side` with one column holding `panel`.
|
||||
fn dock(side: Side, panel: Panel, width: f32) -> Node<Panel> {
|
||||
Node::Dock { side, columns: vec![Column::new(vec![Group::new(vec![panel], 0)], width)] }
|
||||
}
|
||||
|
||||
const MEMORY_RECT: [f32; 4] = [160.0, 120.0, 480.0, 280.0];
|
||||
const HISTORY_RECT: [f32; 4] = [680.0, 120.0, 260.0, 300.0];
|
||||
|
||||
/// The floating windows both windows start with. Fixed ids: the default is rebuilt every frame
|
||||
/// and must stay the same windows.
|
||||
fn default_floating() -> Vec<Floating<Panel>> {
|
||||
vec![Floating::single(1, vec![Panel::Memory], 0, MEMORY_RECT), Floating::single(2, vec![Panel::History], 0, HISTORY_RECT)]
|
||||
vec![Floating::single(vec![Panel::Memory], 0, MEMORY_RECT).with_id(1), Floating::single(vec![Panel::History], 0, HISTORY_RECT).with_id(2)]
|
||||
}
|
||||
|
||||
/// Where a panel that floats in the default layouts floats.
|
||||
fn default_float(panel: Panel) -> Option<Rect> {
|
||||
fn default_float(panel: Panel) -> Option<[f32; 4]> {
|
||||
match panel {
|
||||
Panel::Memory => Some(MEMORY_RECT),
|
||||
Panel::History => Some(HISTORY_RECT),
|
||||
@@ -95,10 +92,10 @@ fn default_float(panel: Panel) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// The dock side and column width a panel opens in when it has no recorded place.
|
||||
fn default_dock(panel: Panel) -> Option<(DockEdge, f32)> {
|
||||
fn default_dock(panel: Panel) -> Option<(Side, f32)> {
|
||||
match panel {
|
||||
Panel::Tracks => Some((DockEdge::Start, TRACKS_WIDTH)),
|
||||
Panel::Clips => Some((DockEdge::End, CLIPS_WIDTH)),
|
||||
Panel::Tracks => Some((Side::Start, TRACKS_WIDTH)),
|
||||
Panel::Clips => Some((Side::End, CLIPS_WIDTH)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -106,21 +103,30 @@ fn default_dock(panel: Panel) -> Option<(DockEdge, f32)> {
|
||||
/// The Edit window's built-in arrangement: Tracks and Groups in a full-height start dock,
|
||||
/// Clips in a full-height end dock, and the MIDI editor under the session view between them.
|
||||
pub fn edit_default() -> Workspace {
|
||||
let session = Node::split(Axis::Y, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
|
||||
let root = Node::split(
|
||||
Axis::X,
|
||||
SplitSize::FixedFirst(TRACKS_WIDTH),
|
||||
dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH),
|
||||
Node::split(Axis::X, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(DockEdge::End, Panel::Clips, CLIPS_WIDTH)),
|
||||
);
|
||||
Workspace::new(Layout::new(Some(root), default_floating()))
|
||||
let session = split(SplitAxis::Vertical, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
|
||||
Workspace::new(Layout {
|
||||
root: Some(split(
|
||||
SplitAxis::Horizontal,
|
||||
SplitSize::FixedFirst(TRACKS_WIDTH),
|
||||
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
|
||||
split(SplitAxis::Horizontal, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(Side::End, Panel::Clips, CLIPS_WIDTH)),
|
||||
)),
|
||||
floating: default_floating(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The Mix window's built-in arrangement: Tracks and Groups in a start dock beside the mixer.
|
||||
/// The timeline-only Clips and MIDI panels stay in Edit.
|
||||
pub fn mix_default() -> Workspace {
|
||||
let root = Node::split(Axis::X, SplitSize::FixedFirst(TRACKS_WIDTH), dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH), tabs(Panel::Canvas));
|
||||
Workspace::new(Layout::new(Some(root), default_floating()))
|
||||
Workspace::new(Layout {
|
||||
root: Some(split(
|
||||
SplitAxis::Horizontal,
|
||||
SplitSize::FixedFirst(TRACKS_WIDTH),
|
||||
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
|
||||
tabs(Panel::Canvas),
|
||||
)),
|
||||
floating: default_floating(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The version of the saved panel layouts, kept in [`crate::UiState::docking_version`]. Version 1
|
||||
@@ -148,7 +154,7 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
|
||||
Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) => {
|
||||
Some(if panels.len() == 1 { Ok(()) } else { Err("The document view cannot share a tab group") })
|
||||
}
|
||||
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
|
||||
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
|
||||
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Canvas)) => {
|
||||
Some(Err("The document view cannot join a dock column"))
|
||||
}
|
||||
@@ -156,24 +162,23 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a workspace against craft-behavior's rules and SoundCraft's own: saved settings cannot
|
||||
/// Check a workspace against craft-ui's rules and SoundCraft's own: saved settings cannot
|
||||
/// float, hide, collapse or share the protected document view.
|
||||
pub fn validate(workspace: &Workspace) -> Result<(), String> {
|
||||
workspace.validate().map_err(|error| error.to_string())?;
|
||||
let layout = workspace.layout();
|
||||
if !layout.contains(&Panel::Canvas) || workspace.hidden().len() > Panel::ALL.len() {
|
||||
let layout = &workspace.layout;
|
||||
if !layout.contains(&Panel::Canvas) || workspace.hidden.len() > Panel::ALL.len() {
|
||||
return Err("The panel layout must contain its document view and bounded hidden panels".into());
|
||||
}
|
||||
if layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
|
||||
return Err("The document view cannot float".into());
|
||||
}
|
||||
layout.root.as_ref().and_then(canvas_placement).unwrap_or(Err("The document view cannot float"))?;
|
||||
for (panel, location) in workspace.hidden() {
|
||||
for (panel, location) in &workspace.hidden {
|
||||
if *panel == Panel::Canvas {
|
||||
return Err("A hidden panel has an invalid or duplicate identity".into());
|
||||
}
|
||||
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, DockPlacement::Tab { .. } | DockPlacement::Split(DockSide::Center))
|
||||
{
|
||||
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center)) {
|
||||
return Err("A hidden panel cannot restore over the document view".into());
|
||||
}
|
||||
let mut probe = layout.clone();
|
||||
@@ -189,7 +194,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
|
||||
/// [`validate`] plus the Mix window's rule: Clips and MIDI stay in Edit.
|
||||
pub fn validate_mix(workspace: &Workspace) -> Result<(), String> {
|
||||
validate(workspace)?;
|
||||
if workspace.layout().contains(&Panel::Clips) || workspace.layout().contains(&Panel::Midi) {
|
||||
if workspace.layout.contains(&Panel::Clips) || workspace.layout.contains(&Panel::Midi) {
|
||||
return Err("Clips and MIDI panels belong to the Edit window".into());
|
||||
}
|
||||
Ok(())
|
||||
@@ -206,17 +211,17 @@ fn checked(workspace: &mut Workspace, change: impl FnOnce(&mut Workspace) -> Res
|
||||
}
|
||||
|
||||
fn apply(workspace: &mut Workspace, action: Action<Panel>) -> Result<(), String> {
|
||||
checked(workspace, |next| next.apply(action, false, permissions).map(drop))
|
||||
checked(workspace, |next| next.apply(action, permissions).map(drop))
|
||||
}
|
||||
|
||||
/// Whether [`Workspace::set_visible`] can actually put `panel` back at its recorded place.
|
||||
/// It follows the recorded location and the chain of hidden anchors; when none of that
|
||||
/// restores, craft-behavior falls back to an unanchored open, which chooses a dock group or
|
||||
/// right edge instead of reporting the missing anchor. Probe each chain location with the
|
||||
/// public [`Layout::restore`] on a clone, so a deleted anchor is recognized before calling in;
|
||||
/// craft-behavior still performs the restore and rewrites the chain itself.
|
||||
/// restores, craft-ui falls back to an unanchored open, which since craft-ui 650b1c0b chooses
|
||||
/// a dock group or right edge instead of reporting the missing anchor. Probe each chain
|
||||
/// location with the public [`Layout::restore`] on a clone, so a deleted anchor is recognized
|
||||
/// before calling in; craft-ui still performs the restore and rewrites the chain itself.
|
||||
fn restores(workspace: &Workspace, panel: Panel) -> bool {
|
||||
let recorded = |p: &Panel| workspace.hidden().iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
|
||||
let recorded = |p: &Panel| workspace.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
|
||||
let mut chain: Vec<Location<Panel>> = Vec::new();
|
||||
let mut seen = vec![panel];
|
||||
let mut current = panel;
|
||||
@@ -229,14 +234,13 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
|
||||
}
|
||||
// Like the chain itself, the panel's own group/column state applies to every attempt.
|
||||
let group = chain.first().and_then(|location| location.group.clone());
|
||||
// Revisit this eligibility probe when updating the pinned craft-behavior restore algorithm.
|
||||
// Revisit this eligibility probe when updating the pinned craft-ui restore algorithm.
|
||||
chain
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|location| {
|
||||
let mut location = location.clone();
|
||||
location.group = group.clone().or(location.group);
|
||||
let mut probe = workspace.layout().clone();
|
||||
let location = Location { group: group.clone().or_else(|| location.group.clone()), ..location.clone() };
|
||||
let mut probe = workspace.layout.clone();
|
||||
match probe.restore(panel, &location) {
|
||||
Err(DockError::MissingTarget) => None,
|
||||
result => Some(result.is_ok()),
|
||||
@@ -246,10 +250,10 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
|
||||
}
|
||||
|
||||
/// The first panel of the dock on `side`, when that dock is shown.
|
||||
fn dock_panel(node: &Node<Panel>, side: DockEdge) -> Option<Panel> {
|
||||
fn dock_panel(node: &Node<Panel>, side: Side) -> Option<Panel> {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => dock_panel(first, side).or_else(|| dock_panel(second, side)),
|
||||
Node::Dock { side: found, columns, .. } if *found == side => {
|
||||
Node::Dock { side: found, columns } if *found == side => {
|
||||
columns.iter().flat_map(|column| &column.groups).find_map(|group| group.panels.first().copied())
|
||||
}
|
||||
_ => None,
|
||||
@@ -260,187 +264,47 @@ fn dock_panel(node: &Node<Panel>, side: DockEdge) -> Option<Panel> {
|
||||
/// in their docks (joining the dock's first group when the dock is shown, else making the dock
|
||||
/// again), the MIDI editor under the session view and the others floating.
|
||||
fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result<(), String> {
|
||||
if workspace.layout().contains(&panel) == visible {
|
||||
if workspace.layout.contains(&panel) == visible {
|
||||
return Ok(());
|
||||
}
|
||||
checked(workspace, |next| {
|
||||
if !visible {
|
||||
return next.apply(Action::close(panel), false, permissions).map(drop);
|
||||
return next.apply(Action::Close { panel }, permissions).map(drop);
|
||||
}
|
||||
let dock = default_dock(panel);
|
||||
if let Some((side, _)) = dock
|
||||
&& let Some(anchor) = next.layout().root.as_ref().and_then(|root| dock_panel(root, side))
|
||||
&& let Some(anchor) = next.layout.root.as_ref().and_then(|root| dock_panel(root, side))
|
||||
{
|
||||
return next.set_visible(panel, true, Some(anchor), false, permissions);
|
||||
return next.set_visible(panel, true, Some(anchor), permissions);
|
||||
}
|
||||
// Without an anchor, craft-behavior would open a panel it has no record of, or whose record no
|
||||
// Without an anchor, craft-ui would open a panel it has no record of, or whose record no
|
||||
// longer restores, in some other panel's group, so the default place is applied here.
|
||||
if next.hidden().iter().any(|(hidden, _)| *hidden == panel)
|
||||
&& restores(next, panel)
|
||||
&& next.set_visible(panel, true, None, false, permissions).is_ok()
|
||||
if next.hidden.iter().any(|(hidden, _)| *hidden == panel) && restores(next, panel) && next.set_visible(panel, true, None, permissions).is_ok()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let open = Action::open(panel, None);
|
||||
let open = Action::Open { panel, anchor: None };
|
||||
let actions = match (dock, default_float(panel)) {
|
||||
(Some((side, width)), _) => vec![open, Action::move_panel(panel, Target::new_dock(side)), Action::resize_column(panel, width)],
|
||||
(None, Some(rect)) => vec![open, Action::float(panel, rect)],
|
||||
(None, None) => vec![Action::open_at(panel, Panel::Canvas, DockPlacement::Split(DockSide::Bottom))],
|
||||
(Some((side, width)), _) => vec![open, Action::MovePanel { panel, to: Target::NewDock { side } }, Action::ResizeColumn { panel, width }],
|
||||
(None, Some(rect)) => vec![open, Action::Float { panel, rect }],
|
||||
(None, None) => vec![Action::OpenAt { panel, anchor: Panel::Canvas, placement: Placement::Split(Zone::Bottom) }],
|
||||
};
|
||||
next.apply_all(actions, false, permissions)?;
|
||||
next.apply(Action::activate(panel), false, permissions).map(drop)
|
||||
next.apply_all(actions, permissions)?;
|
||||
next.apply(Action::Activate { panel }, permissions).map(drop)
|
||||
})
|
||||
}
|
||||
|
||||
/// A drop zone by name, as `ui.dock` writes it. PascalCase names also parse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum ZoneName {
|
||||
Tab,
|
||||
#[serde(alias = "Center")]
|
||||
Center,
|
||||
#[serde(alias = "Left")]
|
||||
Left,
|
||||
#[serde(alias = "Right")]
|
||||
Right,
|
||||
#[serde(alias = "Top")]
|
||||
Top,
|
||||
#[serde(alias = "Bottom")]
|
||||
Bottom,
|
||||
Above,
|
||||
Below,
|
||||
}
|
||||
|
||||
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
|
||||
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
/// A required field that may be `null`.
|
||||
fn required<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
|
||||
T::deserialize(deserializer)
|
||||
}
|
||||
|
||||
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
|
||||
/// (default `center`) and `before`, which only applies to a center move. Rects are `[x, y, width, height]`.
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
#[serde(tag = "operation", rename_all = "camelCase")]
|
||||
enum DockOperation {
|
||||
/// Show a panel at its last location and select it.
|
||||
Open {
|
||||
panel: Panel,
|
||||
},
|
||||
Close {
|
||||
panel: Panel,
|
||||
},
|
||||
Activate {
|
||||
panel: Panel,
|
||||
},
|
||||
Float {
|
||||
panel: Panel,
|
||||
rect: [f32; 4],
|
||||
},
|
||||
MoveFloating {
|
||||
panel: Panel,
|
||||
rect: [f32; 4],
|
||||
},
|
||||
Move {
|
||||
panel: Panel,
|
||||
target: Panel,
|
||||
#[serde(default)]
|
||||
zone: Option<ZoneName>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
before: Option<Option<Panel>>,
|
||||
},
|
||||
SetStackOpen {
|
||||
panel: Panel,
|
||||
open: bool,
|
||||
},
|
||||
/// `height` is required; `null` clears it.
|
||||
ResizeStack {
|
||||
panel: Panel,
|
||||
#[serde(deserialize_with = "required")]
|
||||
height: Option<f32>,
|
||||
},
|
||||
ResizeSplit {
|
||||
path: Vec<bool>,
|
||||
size: SplitSize,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `ui.dock` and `ui.dock.reset` ask of the front window's workspace, and the changes the dock reports.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum DockCommand {
|
||||
/// A raw layout action: `ui.dock` with `{action}`, or a change made in the dock.
|
||||
Layout(Action<Panel>),
|
||||
/// `ui.dock` with `{operation, …}`.
|
||||
Operation(DockOperation),
|
||||
/// `ui.dock.reset`: the built-in arrangement.
|
||||
Reset,
|
||||
}
|
||||
|
||||
/// `[x, y, width, height]` as a rect.
|
||||
fn rect_of([x, y, width, height]: [f32; 4]) -> Rect {
|
||||
Rect::from_min_size(pos2(x, y), vec2(width, height))
|
||||
}
|
||||
|
||||
/// Where a `move` puts the panel relative to `anchor`: `zone` (default `center`) and `before`,
|
||||
/// with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`].
|
||||
fn placement(
|
||||
layout: &Layout<Panel>,
|
||||
anchor: &Panel,
|
||||
zone: Option<ZoneName>,
|
||||
before: Option<Option<Panel>>,
|
||||
) -> Result<DockPlacement<Panel>, DockError> {
|
||||
let side = |side| DockPlacement::for_zone(layout, anchor, side);
|
||||
Ok(match (zone.unwrap_or(ZoneName::Center), before) {
|
||||
(ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before),
|
||||
(ZoneName::Tab, None) => DockPlacement::tab(None),
|
||||
(ZoneName::Center, None) => DockPlacement::Split(DockSide::Center),
|
||||
(_, Some(_)) => return Err(DockError::InvalidPlacement),
|
||||
(ZoneName::Left, None) => side(DockSide::Start)?,
|
||||
(ZoneName::Right, None) => side(DockSide::End)?,
|
||||
(ZoneName::Top, None) => side(DockSide::Top)?,
|
||||
(ZoneName::Bottom, None) => side(DockSide::Bottom)?,
|
||||
(ZoneName::Above, None) => DockPlacement::group(false, None),
|
||||
(ZoneName::Below, None) => DockPlacement::group(true, None),
|
||||
})
|
||||
}
|
||||
|
||||
impl DockOperation {
|
||||
/// The layout action this operation makes on `layout`. A panel that is not shown is
|
||||
/// [`DockError::MissingPanel`] for Open and Activate, which show it first ([`run`]).
|
||||
fn action(&self, layout: &Layout<Panel>) -> Result<Action<Panel>, DockError> {
|
||||
Ok(match self {
|
||||
Self::Open { panel } | Self::Activate { panel } => {
|
||||
if !layout.contains(panel) {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
Action::activate(*panel)
|
||||
}
|
||||
Self::Close { panel } => Action::close(*panel),
|
||||
Self::Float { panel, rect } => Action::float(*panel, rect_of(*rect)),
|
||||
Self::MoveFloating { panel, rect } => Action::move_floating(*panel, rect_of(*rect)),
|
||||
Self::Move { panel, target, zone, before } => Action::move_beside(*panel, *target, placement(layout, target, *zone, *before)?),
|
||||
Self::SetStackOpen { panel, open } => Action::set_stack_open(*panel, *open),
|
||||
Self::ResizeStack { panel, height } => Action::resize_stack(*panel, *height),
|
||||
Self::ResizeSplit { path, size } => Action::resize_split(path.clone(), *size),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a docking command. A hidden panel that is opened or activated comes back with
|
||||
/// Run a shared docking command. A hidden panel that is opened or activated comes back with
|
||||
/// [`set_visible`], so it gets SoundCraft's default place when it has no recorded one.
|
||||
fn run(workspace: &mut Workspace, command: &DockCommand) -> Result<(), String> {
|
||||
let action = match command {
|
||||
DockCommand::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel }) if !workspace.layout().contains(panel) => {
|
||||
return set_visible(workspace, *panel, true);
|
||||
}
|
||||
DockCommand::Operation(operation) => operation.action(workspace.layout()).map_err(|error| error.to_string())?,
|
||||
DockCommand::Layout(action) => action.clone(),
|
||||
DockCommand::Reset => return Err("Reset is applied by the window, not the layout".into()),
|
||||
};
|
||||
apply(workspace, action)
|
||||
fn run(workspace: &mut Workspace, command: &DockCommand<Panel>) -> Result<(), String> {
|
||||
if let DockCommand::Activate { panel } | DockCommand::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) =
|
||||
command
|
||||
&& !workspace.layout.contains(panel)
|
||||
{
|
||||
return set_visible(workspace, *panel, true);
|
||||
}
|
||||
// Only `window.panel.float` reads the float space, and SoundCraft does not register it.
|
||||
checked(workspace, |next| command.apply(next, false, &FloatSpace::new(egui::Rect::NOTHING), permissions).map(drop))
|
||||
}
|
||||
|
||||
fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<(), String> {
|
||||
@@ -455,13 +319,12 @@ fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<
|
||||
}
|
||||
|
||||
fn publish_visibility(app: &mut crate::SoundApp, workspace: &Workspace, edit: bool) {
|
||||
let layout = workspace.layout();
|
||||
app.ui.show_tracks_list = layout.contains(&Panel::Tracks);
|
||||
app.ui.show_memory_locations = layout.contains(&Panel::Memory);
|
||||
app.ui.show_undo_history = layout.contains(&Panel::History);
|
||||
app.ui.show_tracks_list = workspace.layout.contains(&Panel::Tracks);
|
||||
app.ui.show_memory_locations = workspace.layout.contains(&Panel::Memory);
|
||||
app.ui.show_undo_history = workspace.layout.contains(&Panel::History);
|
||||
if edit {
|
||||
app.ui.show_clip_list = layout.contains(&Panel::Clips);
|
||||
app.ui.show_midi_editor = layout.contains(&Panel::Midi);
|
||||
app.ui.show_clip_list = workspace.layout.contains(&Panel::Clips);
|
||||
app.ui.show_midi_editor = workspace.layout.contains(&Panel::Midi);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,8 +336,9 @@ fn store(app: &mut crate::SoundApp, workspace: Workspace, edit: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field.
|
||||
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation, String> {
|
||||
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field;
|
||||
/// parsed through the untagged [`UiDock`], every mistake reads "did not match any variant".
|
||||
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation<Panel>, String> {
|
||||
let name = fields.get("operation").ok_or("operation is required")?.as_str().ok_or("operation must be a string")?;
|
||||
if name != "resizeSplit" && !fields.contains_key("panel") {
|
||||
return Err("panel is required".into());
|
||||
@@ -493,48 +357,52 @@ fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation, S
|
||||
serde_json::from_value(Value::Object(fields.clone())).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// `ui.dock` and `ui.dock.reset`, applied to the front window's workspace.
|
||||
/// `ui.dock` and `ui.dock.reset`: the shared [`DockCommand`] vocabulary, applied to the
|
||||
/// front window's workspace.
|
||||
pub fn command(app: &mut crate::SoundApp, id: &str, params: &Value) -> Result<Value, String> {
|
||||
let edit = app.ui.window == crate::MainWindow::Edit;
|
||||
if !edit && ["panel", "target"].iter().any(|field| matches!(params.get(*field).and_then(Value::as_str), Some("clips" | "midi"))) {
|
||||
return Err("Clips and MIDI panels belong to the Edit window".into());
|
||||
}
|
||||
let fields = match params {
|
||||
let mut fields = match params {
|
||||
Value::Object(fields) => fields.clone(),
|
||||
Value::Null => serde_json::Map::new(),
|
||||
_ => return Err("Docking params must be an object".into()),
|
||||
};
|
||||
let command = match (id, fields.get("action")) {
|
||||
("ui.dock.reset", _) => DockCommand::Reset,
|
||||
(_, Some(action)) => DockCommand::Layout(serde_json::from_value(action.clone()).map_err(|error| error.to_string())?),
|
||||
(_, None) => DockCommand::Operation(operation(&fields)?),
|
||||
let command = if id == "ui.dock" && !fields.contains_key("action") {
|
||||
DockCommand::UiDock(UiDock::Operation(operation(&fields)?))
|
||||
} else {
|
||||
fields.insert("command".into(), json!(id));
|
||||
serde_json::from_value(Value::Object(fields)).map_err(|error| error.to_string())?
|
||||
};
|
||||
let previous = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
|
||||
let result = command_for(app, &command, edit)?;
|
||||
let next = if edit { &app.ui.docking } else { &app.ui.mix_docking };
|
||||
cancel_replaced_workspace(app, &previous, next);
|
||||
cancel_replaced_workspace(app, &previous, next, edit);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Ends a running panel drag when the workspace it started on is replaced or changed by something else
|
||||
/// than the dock.
|
||||
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace) {
|
||||
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace, edit: bool) {
|
||||
if previous != next
|
||||
&& let Some(ctx) = &app.docking_context
|
||||
{
|
||||
craft_ui::runtime::drag::cancel(ctx, craft_behavior::CancelReason::HostChanged);
|
||||
craft_ui::docking::cancel_drag::<Panel>(ctx, area(edit));
|
||||
}
|
||||
}
|
||||
|
||||
/// Restoring complete preferences/configurations uses the same ownership boundary as commands.
|
||||
pub(crate) fn cancel_replaced_state(app: &crate::SoundApp, next: &crate::UiState) {
|
||||
cancel_replaced_workspace(app, &app.ui.docking, &next.docking);
|
||||
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking);
|
||||
cancel_replaced_workspace(app, &app.ui.docking, &next.docking, true);
|
||||
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking, false);
|
||||
}
|
||||
|
||||
fn command_for(app: &mut crate::SoundApp, command: &DockCommand, edit: bool) -> Result<Value, String> {
|
||||
fn command_for(app: &mut crate::SoundApp, command: &DockCommand<Panel>, edit: bool) -> Result<Value, String> {
|
||||
let mut workspace = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
|
||||
if *command == DockCommand::Reset {
|
||||
if command.is_app_owned() {
|
||||
// Reset is the only application-owned command SoundCraft registers.
|
||||
if !matches!(command, DockCommand::ResetWorkspace {}) {
|
||||
return Err("Named panel workspaces are not supported".into());
|
||||
}
|
||||
workspace = if edit { edit_default() } else { mix_default() };
|
||||
sync(&mut workspace, app, edit)?;
|
||||
} else {
|
||||
@@ -563,189 +431,22 @@ pub(crate) fn arrange(app: &mut crate::SoundApp) -> Result<(), String> {
|
||||
validate_mix(&workspace)?;
|
||||
}
|
||||
let previous = workspace.clone();
|
||||
let floating: Vec<_> =
|
||||
workspace.layout().floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
|
||||
for (index, (panel, rect)) in floating.into_iter().enumerate() {
|
||||
let at = pos2(32.0 + index as f32 * 28.0, 80.0 + index as f32 * 28.0);
|
||||
apply(&mut workspace, Action::move_floating(panel, Rect::from_min_size(at, rect.size())))?;
|
||||
let floating: Vec<_> = workspace.layout.floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
|
||||
for (index, (panel, mut rect)) in floating.into_iter().enumerate() {
|
||||
rect[0] = 32.0 + index as f32 * 28.0;
|
||||
rect[1] = 80.0 + index as f32 * 28.0;
|
||||
apply(&mut workspace, Action::MoveFloating { panel, rect })?;
|
||||
}
|
||||
cancel_replaced_workspace(app, &previous, &workspace);
|
||||
cancel_replaced_workspace(app, &previous, &workspace, edit);
|
||||
store(app, workspace, edit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The workspaces the Edit and Mix docks show, the panels' specs and the session views' keyboard focus.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LiveDocks {
|
||||
edit: Option<Arc<Workspace>>,
|
||||
mix: Option<Arc<Workspace>>,
|
||||
specs: Tracked<DockSpecs>,
|
||||
edit_focus: ViewFocus,
|
||||
mix_focus: ViewFocus,
|
||||
}
|
||||
|
||||
impl LiveDocks {
|
||||
/// The `Arc` the dock shows for `workspace`: the last one while its arrangement is the same, so an idle pass
|
||||
/// keeps the workspace's revision and the dock reads no spec.
|
||||
fn shown(&mut self, edit: bool, workspace: &Workspace) -> Arc<Workspace> {
|
||||
let slot = if edit { &mut self.edit } else { &mut self.mix };
|
||||
if let Some(shown) = slot.as_ref().filter(|shown| ***shown == *workspace) {
|
||||
return Arc::clone(shown);
|
||||
}
|
||||
let shown = Arc::new(workspace.clone());
|
||||
*slot = Some(Arc::clone(&shown));
|
||||
shown
|
||||
}
|
||||
}
|
||||
|
||||
/// What the dock reads of the panels: their names in the interface language.
|
||||
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
|
||||
struct DockSpecs {
|
||||
/// The tab names, in [`Panel::ALL`] order.
|
||||
labels: Vec<String>,
|
||||
}
|
||||
|
||||
impl PanelSpecs<Panel> for DockSpecs {
|
||||
fn spec(&self, panel: &Panel) -> PanelSpec {
|
||||
let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
|
||||
// Every panel is SoundCraft's own egui code: the dock runs it with the window's style.
|
||||
let spec = PanelSpec::new(label).limits(panel_limits(panel)).host_body();
|
||||
if *panel == Panel::Canvas { spec.canvas() } else { spec }
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &Panel) -> Permissions {
|
||||
permissions(panel)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the panel names in the interface language, moving the specs' revision only when one changed.
|
||||
fn refresh_specs(app: &mut crate::SoundApp) {
|
||||
let labels: Vec<String> = Panel::ALL.iter().map(|panel| crate::localization::text(panel.label()).to_owned()).collect();
|
||||
if app.docks.specs.labels != labels {
|
||||
app.docks.specs.labels = labels;
|
||||
}
|
||||
}
|
||||
|
||||
/// What a session view knows of its keyboard focus from the pass that drew it last.
|
||||
#[derive(Default)]
|
||||
struct ViewFocus {
|
||||
/// That pass's number and the document the view showed (`SoundApp::doc_epoch`).
|
||||
shown: Option<(u64, u64)>,
|
||||
/// The view opened or was pressed and has yet to ask for the focus.
|
||||
wanted: bool,
|
||||
/// The view had the focus, and no other widget has taken it.
|
||||
returns: bool,
|
||||
/// An overlay ([`crate::framework::overlay_open`]) was up.
|
||||
overlay: bool,
|
||||
/// The view kept Tab.
|
||||
kept_tab: bool,
|
||||
}
|
||||
|
||||
impl LiveDocks {
|
||||
fn view_focus(&mut self, edit: bool) -> &mut ViewFocus {
|
||||
if edit { &mut self.edit_focus } else { &mut self.mix_focus }
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the session view, drawn in `rect`, the keyboard focus on a press in it, when it opens or shows another
|
||||
/// document, and when its focus went nowhere (a dialog that closed). It waits for
|
||||
/// a modal dialog, menu or popup to close. A press leaves the focus with the text field it landed on; a view that opens
|
||||
/// leaves it with any text field and with a widget of another layer. Called after the view's widgets, so that the field
|
||||
/// under a press has taken the focus already.
|
||||
fn focus_session_view(app: &mut crate::SoundApp, ui: &egui::Ui, edit: bool, rect: Rect) {
|
||||
let ctx = ui.ctx();
|
||||
let id = crate::framework::session_view_id(edit);
|
||||
let focused = ctx.memory(|memory| memory.focused());
|
||||
let pressed = ui.rect_contains_pointer(rect) && ui.input(|input| input.pointer.any_pressed());
|
||||
let overlay = crate::framework::overlay_open(app, ctx);
|
||||
let (pass, document) = (ctx.cumulative_pass_nr(), app.doc_epoch);
|
||||
let state = app.docks.view_focus(edit);
|
||||
let stayed = state.shown.is_some_and(|(last, shown)| shown == document && (last == pass || last + 1 == pass));
|
||||
state.shown = Some((pass, document));
|
||||
state.wanted |= pressed || !stayed;
|
||||
state.returns |= focused == Some(id);
|
||||
// egui keeps the focus on a widget of a closed overlay for the pass after the last one that drew it.
|
||||
if std::mem::replace(&mut state.overlay, overlay) || overlay {
|
||||
if !overlay {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let wanted = std::mem::take(&mut state.wanted);
|
||||
state.returns &= focused.is_none_or(|focused| focused == id);
|
||||
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
|
||||
let field_pressed =
|
||||
|| ctx.text_edit_focused() && focused.and_then(|field| ctx.read_response(field)).is_some_and(|field| field.is_pointer_button_down_on());
|
||||
let takes = if pressed {
|
||||
focused != Some(id) && !field_pressed()
|
||||
} else if wanted {
|
||||
focused != Some(id) && !ctx.text_edit_focused() && focused.is_none_or(|focused| layer(focused) == layer(id))
|
||||
} else {
|
||||
state.returns && focused.is_none()
|
||||
};
|
||||
if takes {
|
||||
crate::framework::focus_session_view(ctx, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock's panels over the app in one pass.
|
||||
struct Panels<'a> {
|
||||
app: &'a mut crate::SoundApp,
|
||||
edit: bool,
|
||||
}
|
||||
|
||||
impl DockPanels<Panel> for Panels<'_> {
|
||||
fn body(&mut self, panel: &Panel, ui: &mut egui::Ui, _: &mut BodyCx<'_>) {
|
||||
let app = &mut *self.app;
|
||||
match panel {
|
||||
// The session view is its group's `group_view`.
|
||||
Panel::Canvas => {}
|
||||
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
|
||||
Panel::Clips => crate::panels::clip_list(app, ui),
|
||||
Panel::Midi => {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
|
||||
minimum_body(ui, vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
|
||||
}
|
||||
Panel::Memory => crate::panels::memory_locations(app, ui),
|
||||
Panel::History => crate::panels::undo_history(app, ui),
|
||||
}
|
||||
}
|
||||
|
||||
/// The session view: the Edit window's tracks and timeline, or the mixer.
|
||||
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
|
||||
let GroupAt::Show(rect) = at else { return None };
|
||||
if !panels.contains(&Panel::Canvas) {
|
||||
return None;
|
||||
}
|
||||
let id = crate::framework::session_view_id(self.edit);
|
||||
let view = ui.interact(rect, id, egui::Sense::focusable_noninteractive());
|
||||
view.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Canvas, true, crate::localization::text(Panel::Canvas.label())));
|
||||
// The shortcuts read the root window's keys only, so a Mix window of its own leaves Tab to the focus. A press of
|
||||
// Tab is the view's to its release: the repeats of the one that reached the last stop stay here.
|
||||
let shortcuts_run = ui.ctx().viewport_id() == egui::ViewportId::ROOT;
|
||||
let held = self.app.docks.view_focus(self.edit).kept_tab && ui.input(|input| input.key_down(egui::Key::Tab));
|
||||
let keeps_tab = |app: &crate::SoundApp| shortcuts_run && (held || crate::shortcuts::tab_has_work(app));
|
||||
// Declared before the widgets drawn over it, for its place in Tab order, and again after this pass's input has
|
||||
// changed what Tab has to do.
|
||||
crate::framework::host_canvas(ui.ctx(), id, keeps_tab(self.app));
|
||||
ui.painter().rect_filled(rect, 0.0, crate::theme::Tokens::current().window_bg);
|
||||
if self.edit {
|
||||
crate::edit_window::main_area(self.app, ui);
|
||||
} else {
|
||||
crate::mix_window::content(self.app, ui);
|
||||
}
|
||||
focus_session_view(self.app, ui, self.edit, rect);
|
||||
let kept_tab = keeps_tab(self.app);
|
||||
self.app.docks.view_focus(self.edit).kept_tab = kept_tab;
|
||||
crate::framework::host_canvas(ui.ctx(), id, kept_tab);
|
||||
Some(rect.height())
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw and edit the dock layout for the requested window, falling back to the default layout if validation or panel
|
||||
/// sync fails, then publish panel visibility, store the workspace and apply the pass's layout actions.
|
||||
/// sync fails, then publish panel visibility, store the workspace and apply the frame's layout actions.
|
||||
pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWindow) {
|
||||
app.docking_context = Some(ui.ctx().clone());
|
||||
let t = crate::theme::Tokens::current();
|
||||
let edit = window == crate::MainWindow::Edit;
|
||||
let mut workspace =
|
||||
if edit { std::mem::replace(&mut app.ui.docking, edit_default()) } else { std::mem::replace(&mut app.ui.mix_docking, mix_default()) };
|
||||
@@ -755,31 +456,58 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
|
||||
workspace = if edit { edit_default() } else { mix_default() };
|
||||
let _ = sync(&mut workspace, app, edit);
|
||||
}
|
||||
cancel_replaced_workspace(app, &before_sync, &workspace);
|
||||
cancel_replaced_workspace(app, &before_sync, &workspace, edit);
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
style.min_pane = 96.0;
|
||||
style.tab_height = MIDI_TAB_HEIGHT;
|
||||
style.background = t.panel_bg;
|
||||
style.tab_background = t.panel_bg2;
|
||||
style.active_background = t.row_selected;
|
||||
style.text = t.text;
|
||||
style.inactive_text = t.text_dim;
|
||||
style.border = egui::Stroke::new(1.0, t.border);
|
||||
style.accent = t.accent;
|
||||
style.font = crate::theme::regular(11.5);
|
||||
// Free docking: a panel dropped at an empty window edge makes a dock there, and the top
|
||||
// and bottom edges take frames (`drop_edges` keeps its default).
|
||||
style.new_dock_zones = true;
|
||||
style.side_edge_zones = false;
|
||||
// The MIDI body's rect stands for a piano roll on screen (the arrow keys go to it), so only a
|
||||
// frame that draws the panel records one: open behind another tab, the old rect is gone.
|
||||
if edit {
|
||||
ui.ctx().data_mut(|data| data.remove::<egui::Rect>(egui::Id::unique("soundcraft-midi-body")));
|
||||
}
|
||||
refresh_specs(app);
|
||||
let shown = app.docks.shown(edit, &workspace);
|
||||
// The specs leave the app while its panels borrow it, and come back with their revision.
|
||||
let specs = std::mem::take(&mut app.docks.specs);
|
||||
// Floating windows stay inside the app window; a drop at an empty window edge makes a dock there, and the top and
|
||||
// bottom edges take frames (`DockConfig::default()`).
|
||||
let config = DockConfig::default().native_windows(false);
|
||||
let output = ui
|
||||
.push_id(area_id(window), |ui| {
|
||||
let mut panels = Panels { app: &mut *app, edit };
|
||||
DockArea::new("Panels", Bind::given(shown), &specs, &mut panels, config).show(ui)
|
||||
})
|
||||
.inner;
|
||||
app.docks.specs = specs;
|
||||
let output = DockArea::new(area(edit)).show_with_limits(
|
||||
ui,
|
||||
&workspace.layout,
|
||||
&style,
|
||||
|panel| crate::localization::text(panel.label()).into(),
|
||||
permissions,
|
||||
panel_limits,
|
||||
|ui, panel| match panel {
|
||||
Panel::Canvas => {
|
||||
ui.painter().rect_filled(ui.max_rect(), 0.0, t.window_bg);
|
||||
if edit {
|
||||
crate::edit_window::main_area(app, ui);
|
||||
} else {
|
||||
crate::mix_window::content(app, ui);
|
||||
}
|
||||
}
|
||||
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
|
||||
Panel::Clips => crate::panels::clip_list(app, ui),
|
||||
Panel::Midi => {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
|
||||
minimum_body(ui, egui::vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
|
||||
}
|
||||
Panel::Memory => crate::panels::memory_locations(app, ui),
|
||||
Panel::History => crate::panels::undo_history(app, ui),
|
||||
},
|
||||
);
|
||||
let _ = sync(&mut workspace, app, edit);
|
||||
publish_visibility(app, &workspace, edit);
|
||||
store(app, workspace, edit);
|
||||
for action in output.actions.into_iter().chain(output.requested) {
|
||||
if let Err(error) = command_for(app, &DockCommand::Layout(action), edit) {
|
||||
for action in output.actions {
|
||||
if let Err(error) = command_for(app, &DockCommand::Layout { action }, edit) {
|
||||
app.ui.status = crate::localized_format!("Panel move was not applied: {error}", error = error);
|
||||
}
|
||||
}
|
||||
@@ -801,15 +529,14 @@ pub(crate) fn minimum_body(ui: &mut egui::Ui, minimum: egui::Vec2, body: impl Fn
|
||||
});
|
||||
}
|
||||
|
||||
/// The panels' body limits: a minimum size and, for side panels, a maximum width.
|
||||
fn panel_limits(panel: &Panel) -> SizeLimits {
|
||||
fn panel_limits(panel: &Panel) -> PanelLimits {
|
||||
let (min, max_width) = match panel {
|
||||
Panel::Canvas => (vec2(300.0, 240.0), SizeLimits::BOUND),
|
||||
Panel::Tracks => (vec2(140.0, 120.0), 520.0),
|
||||
Panel::Clips => (vec2(180.0, 120.0), 720.0),
|
||||
Panel::Midi => (vec2(420.0, 260.0), SizeLimits::BOUND),
|
||||
Panel::Memory => (vec2(260.0, 160.0), SizeLimits::BOUND),
|
||||
Panel::History => (vec2(200.0, 160.0), 720.0),
|
||||
Panel::Canvas => (egui::vec2(300.0, 240.0), 1_000_000.0),
|
||||
Panel::Tracks => (egui::vec2(140.0, 120.0), 520.0),
|
||||
Panel::Clips => (egui::vec2(180.0, 120.0), 720.0),
|
||||
Panel::Midi => (egui::vec2(420.0, 260.0), 1_000_000.0),
|
||||
Panel::Memory => (egui::vec2(260.0, 160.0), 1_000_000.0),
|
||||
Panel::History => (egui::vec2(200.0, 160.0), 720.0),
|
||||
};
|
||||
SizeLimits::new(min, vec2(max_width, SizeLimits::BOUND))
|
||||
PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ fn harness(n: usize) -> Harness<'static, SoundApp> {
|
||||
|
||||
fn harness_with(engine: soundcraft_engine::Engine) -> Harness<'static, SoundApp> {
|
||||
let app = SoundApp::new(engine, None, crate::Services::default());
|
||||
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).with_context_setup(crate::framework::install_headless);
|
||||
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0);
|
||||
let builder = if std::env::var_os("SOUNDCRAFT_FADE_SHOTS").is_some() { builder.wgpu() } else { builder };
|
||||
let mut h = builder.build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// The app binary's exit hook runs from `on_exit`, the one exit path macOS has (its quit ends the
|
||||
/// process before `run_native` returns), and only once.
|
||||
#[test]
|
||||
fn leaving_runs_the_exit_hook_once() {
|
||||
let runs = Rc::new(Cell::new(0));
|
||||
let counted = runs.clone();
|
||||
let mut services = Services { at_exit: Some(Box::new(move || counted.set(counted.get() + 1))), ..Default::default() };
|
||||
services.run_exit_hook();
|
||||
assert_eq!(runs.get(), 1);
|
||||
services.run_exit_hook();
|
||||
assert_eq!(runs.get(), 1, "a second exit must not run the hook again");
|
||||
assert!(services.at_exit.is_none());
|
||||
}
|
||||
|
||||
/// Stable tests and the web build leave without a hook installed.
|
||||
#[test]
|
||||
fn no_hook_means_a_no_op() {
|
||||
Services::default().run_exit_hook();
|
||||
}
|
||||
@@ -135,18 +135,8 @@ pub fn definitions(system_fonts: bool) -> FontDefinitions {
|
||||
fonts
|
||||
}
|
||||
|
||||
/// Gives the context [`definitions`] through the framework runtime, which keeps its font providers and layout memory in
|
||||
/// step with them. The framework's chrome draws in three families besides the monospace one: the signature family
|
||||
/// (follows the proportional one) and the semibold family, which titles and strong text use because the stack the
|
||||
/// runtime started with has it; SoundCraft's own bold family serves as that one. A family left out draws missing-glyph
|
||||
/// boxes.
|
||||
pub fn install(ctx: &egui::Context, system_fonts: bool) {
|
||||
let mut fonts = definitions(system_fonts);
|
||||
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
let bold = fonts.families.get(&FontFamily::Name("bold".into())).cloned().unwrap_or_else(|| proportional.clone());
|
||||
fonts.families.entry(craft_ui::fonts::FontRef::signature().family()).or_insert(proportional);
|
||||
fonts.families.entry(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into())).or_insert(bold);
|
||||
craft_ui::fonts::load(ctx, fonts);
|
||||
ctx.set_fonts(definitions(system_fonts));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -185,29 +175,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every family the framework's chrome draws in has a face after `install`, with and without system fonts: the
|
||||
/// dialog title once drew boxes because the semibold family was missing.
|
||||
#[test]
|
||||
fn install_gives_every_chrome_family_a_face() {
|
||||
for system_fonts in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
install(&ctx, system_fonts);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
output.textures_delta.clear();
|
||||
let families = [
|
||||
FontFamily::Proportional,
|
||||
FontFamily::Monospace,
|
||||
craft_ui::fonts::FontRef::signature().family(),
|
||||
FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()),
|
||||
];
|
||||
for family in families {
|
||||
let font = egui::FontId::new(14.0, family.clone());
|
||||
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "Check for Updates")), "{family:?} has no Latin face (system fonts {system_fonts})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Korean names draw in every family, not as boxes; skipped when the system has no Korean font.
|
||||
#[test]
|
||||
fn every_family_draws_hangul_with_a_system_korean_font() {
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
//! The craft-ui runtime, hosted from SoundCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
|
||||
//! The desktop app calls [`install`] once, [`SoundApp::before_input`] in `raw_input_hook`, [`SoundApp::close_path`]
|
||||
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
|
||||
//! [`SoundApp::run_framework_dialogs`] runs the framework dialogs after SoundCraft's own UI.
|
||||
//!
|
||||
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of SoundCraft's own
|
||||
//! egui widgets has the keyboard. The window's Escape is read with [`escape_pressed`]; the session view is declared
|
||||
//! to the runtime with [`host_canvas`], which keeps the edit chords and the clipboard events in egui's input for
|
||||
//! SoundCraft's shortcuts, and Tab while the focused view has work for it. A focused view leaves the keyboard to the
|
||||
//! shortcuts ([`widget_has_keyboard`]).
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use craft_host::target::ShellInfo;
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_keymap::{Chord, Key, Mods, Overrides};
|
||||
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
|
||||
use craft_ui::runtime::commands::{CommandInput, CommandSet, NavCommand, QuitCommand};
|
||||
use craft_ui::runtime::env::{RootEnv, Scale};
|
||||
use craft_ui::runtime::focus::{EditSet, FocusTarget, KeepKeys, KeyUse};
|
||||
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
use craft_ui::runtime::keys::{Intent, with_window_intents};
|
||||
use craft_ui::runtime::overlay::{self, OpenFilter};
|
||||
use craft_ui::shell::embed::{self, CloseDecision};
|
||||
use craft_window::system::WindowSystem;
|
||||
|
||||
use crate::SoundApp;
|
||||
|
||||
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
|
||||
/// (Windows) and fits the window to its monitor once.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use craft_ui::shell::embed::before_ui;
|
||||
|
||||
/// The scripts of the interface languages, for the font stack.
|
||||
static SCRIPTS: I18nScripts = I18nScripts;
|
||||
|
||||
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. SoundCraft's own definitions
|
||||
/// ([`crate::fonts::install`]) replace it on the first frame, before anything is drawn.
|
||||
fn ui_fonts() -> UiFonts<'static> {
|
||||
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
|
||||
}
|
||||
|
||||
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
|
||||
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
|
||||
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
|
||||
}
|
||||
|
||||
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
|
||||
/// opens its window through XWayland. SoundCraft keeps the system's title bar on every platform.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn install(ctx: &egui::Context, forced_x11: bool) -> Result<(), String> {
|
||||
use craft_host::target::Backend;
|
||||
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
|
||||
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows))
|
||||
}
|
||||
|
||||
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
|
||||
pub fn install_headless(ctx: &egui::Context) {
|
||||
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
|
||||
log::warn!("{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Who SoundCraft is to the framework's dialogs (the update dialogs show its name and icon).
|
||||
pub(crate) fn host() -> Arc<Host> {
|
||||
Arc::new(
|
||||
Host::builder(AppInfo { id: "soundcraft", name: "SoundCraft", version: env!("CARGO_PKG_VERSION") })
|
||||
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.soundcraft.png"))
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The runtime's default keys SoundCraft's own shortcuts use: F6 and Shift+F6 move between panes by default, and F6
|
||||
/// is the Trim tool in SoundCraft; Cmd+Q (Ctrl+Q) is the runtime's Quit, and SoundCraft quits through its own
|
||||
/// `app.quit`, which keeps its recording and recovery rules. Overrides are keyed by command id, which the command set
|
||||
/// gives.
|
||||
fn command_overrides() -> Arc<Overrides> {
|
||||
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
|
||||
OVERRIDES
|
||||
.get_or_init(|| {
|
||||
let mut overrides = Overrides::new();
|
||||
overrides.insert(NavCommand::NextPane.id(), Vec::new());
|
||||
overrides.insert(NavCommand::PreviousPane.id(), Vec::new());
|
||||
overrides.insert(QuitCommand::Quit.id(), Vec::new());
|
||||
Arc::new(overrides)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
impl SoundApp {
|
||||
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
|
||||
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
|
||||
pub fn before_input(&mut self, ctx: &egui::Context) {
|
||||
embed::before_input(ctx, |output| self.frame_input(output));
|
||||
}
|
||||
|
||||
/// The root values of this frame. SoundCraft registers no commands with the runtime and lets it toggle no
|
||||
/// chrome, so the output carries nothing it acts on. The interface scale is the one SoundCraft applied last
|
||||
/// (`extra_windows`), so the runtime's zoom and SoundCraft's agree.
|
||||
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
|
||||
let mode = if crate::theme::is_light() { craft_theme::Mode::Light } else { craft_theme::Mode::Dark };
|
||||
// SoundCraft zooms with Cmd/Ctrl+scroll itself, so a smooth Ctrl+wheel stays a wheel event.
|
||||
let root = RootEnv::new().mode(mode).scale(Scale::new(self.extra.applied_scale())).ctrl_wheel_pinch(false);
|
||||
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host))
|
||||
}
|
||||
|
||||
/// The framework's part of `App::logic`, after SoundCraft's own: the root window's close path. A close the app
|
||||
/// asked for itself goes through; otherwise unsaved changes hold the window open while Save Changes asks, and
|
||||
/// its answer quits the app.
|
||||
pub fn close_path(&mut self, ctx: &egui::Context) {
|
||||
embed::logic(ctx, || {
|
||||
if self.quit_requested || !crate::dialogs::ask_to_save(self, "app.quit", &serde_json::json!({})) {
|
||||
CloseDecision::Close
|
||||
} else {
|
||||
CloseDecision::Hold
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The framework dialogs open on [`SoundApp::framework_dialogs`], once per pass after SoundCraft's own UI.
|
||||
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
|
||||
self.framework_dialogs.run(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit-mode keys (Alt+1 to Alt+4, Pro Tools' Shuffle, Slip, Spot and Grid) the session view claims, so Alt-code
|
||||
/// entry leaves them to SoundCraft's shortcuts.
|
||||
const EDIT_MODE_KEYS: [Chord; 4] =
|
||||
[Chord::new(Mods::ALT, Key::Num1), Chord::new(Mods::ALT, Key::Num2), Chord::new(Mods::ALT, Key::Num3), Chord::new(Mods::ALT, Key::Num4)];
|
||||
|
||||
/// The widget of the session view: the Edit window's tracks and timeline (`edit`) or the Mix window's strips.
|
||||
pub fn session_view_id(edit: bool) -> egui::Id {
|
||||
egui::Id::unique(("soundcraft-session-view", edit))
|
||||
}
|
||||
|
||||
/// Declares the session view `id`, drawn in this pass, as the window's document canvas. With nothing focused it is
|
||||
/// the window's key target: the edit chords, the clipboard events and the edit-mode keys stay in egui's input for
|
||||
/// SoundCraft's shortcuts, as do the arrows, Enter and the page keys. Tab and Shift+Tab stop at the view; with
|
||||
/// `keeps_tab` the focused view keeps them in egui's input, else they move on from it.
|
||||
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id, keeps_tab: bool) {
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL).with_claims(&EDIT_MODE_KEYS);
|
||||
let keys = if keeps_tab { KEYS.with_keep(KeepKeys::Tab) } else { KEYS };
|
||||
craft_ui::runtime::focus::host_canvas(ctx, id, keys);
|
||||
}
|
||||
|
||||
/// Gives the session view `id`, declared in this pass, the keyboard focus.
|
||||
pub(crate) fn focus_session_view(ctx: &egui::Context, id: egui::Id) {
|
||||
craft_ui::runtime::focus::request(ctx, FocusTarget::Id(id));
|
||||
}
|
||||
|
||||
/// Whether a widget other than the session view has the keyboard. A focused session view leaves it to SoundCraft's
|
||||
/// shortcuts, as with nothing focused.
|
||||
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
|
||||
ctx.memory(|memory| memory.focused()).is_some_and(|focused| ![true, false].map(session_view_id).contains(&focused))
|
||||
}
|
||||
|
||||
/// Whether a modal dialog, SoundCraft's, egui's or the framework's, or an egui menu or popup is up. A framework menu
|
||||
/// holds the focus in its own layer.
|
||||
pub(crate) fn overlay_open(app: &SoundApp, ctx: &egui::Context) -> bool {
|
||||
app.dialogs.open.is_some()
|
||||
|| app.ui.show_preferences
|
||||
|| app.ui.show_search
|
||||
|| egui::Popup::is_any_open(ctx)
|
||||
|| ctx.memory(|memory| memory.top_modal_layer()).is_some()
|
||||
|| overlay::any_open(ctx, OpenFilter::Modal)
|
||||
}
|
||||
|
||||
/// Whether Escape was pressed in this pass: from egui while one of SoundCraft's own widgets or popups has the
|
||||
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
|
||||
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
|
||||
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel_pending(ctx)
|
||||
}
|
||||
|
||||
/// Whether the window's cancel (an Escape while nothing has framework focus) is there and untaken.
|
||||
fn window_cancel_pending(ctx: &egui::Context) -> bool {
|
||||
let mut pending = false;
|
||||
with_window_intents(ctx, false, |intents| {
|
||||
pending = intents.untaken(&Intent::Cancel);
|
||||
false
|
||||
});
|
||||
pending
|
||||
}
|
||||
@@ -16,20 +16,17 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
|
||||
pub mod aaf_import;
|
||||
pub mod appearance;
|
||||
pub mod bounce;
|
||||
pub mod channel_titles;
|
||||
pub mod control;
|
||||
pub mod credits;
|
||||
pub mod dialogs;
|
||||
pub mod docking;
|
||||
pub mod edit_window;
|
||||
pub mod fonts;
|
||||
pub mod framework;
|
||||
pub mod icons;
|
||||
pub mod import;
|
||||
pub mod localization;
|
||||
pub mod menus;
|
||||
pub mod mix_window;
|
||||
pub mod os_window;
|
||||
pub mod palette;
|
||||
pub mod panels;
|
||||
pub mod preferences;
|
||||
@@ -63,33 +60,14 @@ pub use panels::video_window;
|
||||
pub use panels::windows;
|
||||
|
||||
mod app;
|
||||
mod capture;
|
||||
mod services;
|
||||
mod state;
|
||||
|
||||
#[cfg(test)]
|
||||
mod exit_hook_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
use app::{automation_step_due, editor_changes, editor_states_due, failed_plugin_status};
|
||||
pub use channel_titles::{os_title, os_title_with_section};
|
||||
pub use services::Services;
|
||||
pub use state::{DragSource, MainWindow};
|
||||
|
||||
/// The version line this build reports: the app binary sets the compiled identity once at start-up
|
||||
/// (a Nightly build's exact feed version), so About and diagnostics never guess it.
|
||||
static BUILD_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
|
||||
/// Record the compiled version. Later calls are ignored: the first value is the process's build.
|
||||
pub fn set_build_version(version: String) {
|
||||
let _ = BUILD_VERSION.set(version);
|
||||
}
|
||||
|
||||
/// The compiled version, or the crate's own when no binary recorded one (tests, the web build).
|
||||
pub fn build_version() -> &'static str {
|
||||
BUILD_VERSION.get().map_or(env!("CARGO_PKG_VERSION"), String::as_str)
|
||||
}
|
||||
|
||||
/// UI state (serde, so agents can read and set it).
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -380,8 +358,6 @@ pub struct SoundApp {
|
||||
synthetic_pointer_active: bool,
|
||||
/// Cancel that press before the next egui input pass, without a release click/drop.
|
||||
cancel_synthetic_pointer: bool,
|
||||
/// `ui.key` requests waiting for the framework's injected input to run.
|
||||
injected_acks: VecDeque<control::InjectedAck>,
|
||||
/// A key/text batch crossed its deadline after [`Self::raw_input_hook`] had already appended it
|
||||
/// to the pass. Do not dispatch that stale copy through shortcuts or widgets.
|
||||
cancel_synthetic_keys: bool,
|
||||
@@ -451,12 +427,6 @@ pub struct SoundApp {
|
||||
theme_applied: Option<bool>,
|
||||
/// Last panel host context, used to cancel renderer-owned gestures on explicit replacement.
|
||||
pub(crate) docking_context: Option<egui::Context>,
|
||||
/// The workspaces and panel specs the Edit and Mix docks show.
|
||||
pub(crate) docks: docking::LiveDocks,
|
||||
/// The framework dialogs (update check and prompt); they run once per pass after the app's own UI.
|
||||
pub framework_dialogs: craft_ui::dialog::DialogHost,
|
||||
/// Who SoundCraft is to the framework's components.
|
||||
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
|
||||
/// Transport simulation when there is no player (tests, offscreen renders).
|
||||
sim: Option<(Samples, Option<Samples>, Option<Range>)>,
|
||||
/// When Record last found nothing to record on, and why: the Record buttons show it for a moment.
|
||||
|
||||
@@ -512,16 +512,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Strip Silence dialog's action button and the Channel Strip plug-in's short name are
|
||||
/// different strings ("remove" vs a channel strip): the button keeps the dialog's own key,
|
||||
/// so a translation gives each its word (#1610).
|
||||
#[test]
|
||||
fn strip_button_translates_as_its_own_key() {
|
||||
let pt = Language::PortugueseBrazil;
|
||||
assert_eq!(pt.text("Strip Silence"), "Remover silêncio", "the dialog's action button");
|
||||
assert_eq!(pt.text("Strip"), "Canal", "the Channel Strip plug-in's short name keeps its own key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_localized_source_string_has_a_catalog_entry() {
|
||||
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
|
||||
|
||||
@@ -282,8 +282,7 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
if ui.add_enabled(preferences_enabled, egui::Button::new(crate::localization::text("Preferences..."))).clicked() {
|
||||
let _ = app.run("setup.preferences", json!({"value": true}));
|
||||
}
|
||||
// Nightly has no in-app updater: ArtCraft Launcher installs and updates it.
|
||||
if app.update_services_allowed() && ui.button(crate::localization::text("Check for Updates…")).clicked() {
|
||||
if ui.button(crate::localization::text("Check for Updates…")).clicked() {
|
||||
let _ = app.run("app.checkForUpdates", json!({}));
|
||||
}
|
||||
if ui.button(crate::localization::text("Session Info")).clicked() {
|
||||
@@ -648,13 +647,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
json!({"language": language.id()})
|
||||
}
|
||||
"app.checkForUpdates" | "help.checkForUpdates" => {
|
||||
// A Nightly launch has no in-app updater, so say where its updates come from instead of
|
||||
// reporting a check that will never run.
|
||||
if !app.update_services_allowed() {
|
||||
let message = "SoundCraft Nightly is updated by ArtCraft Launcher; this build has no update check".to_owned();
|
||||
app.ui.status = message.clone();
|
||||
return Some(Err(message));
|
||||
}
|
||||
crate::updates_ui::check(app);
|
||||
json!({})
|
||||
}
|
||||
@@ -866,8 +858,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
app.ui = ns;
|
||||
app.ui.undo_levels = app.ui.undo_levels.clamp(1, 64);
|
||||
app.engine.set_history_limit(app.ui.undo_levels);
|
||||
// The list is newest first, so this keeps the newest, as `recent::note` does.
|
||||
app.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
|
||||
if closed_preferences {
|
||||
app.preferences.discard_draft();
|
||||
}
|
||||
@@ -913,22 +903,6 @@ mod tests {
|
||||
assert!(!item_state(&app, "File > Save Session", Some("session.save")).0);
|
||||
}
|
||||
|
||||
/// A Nightly launch has no in-app updater: the command says where its updates come from instead
|
||||
/// of reporting a check that can never run, whichever surface (menu, palette, automation) sent it.
|
||||
#[test]
|
||||
fn a_nightly_launch_refuses_the_update_check_command() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
// Stable, the tests' launch identity, still queues the check.
|
||||
assert!(app.run("app.checkForUpdates", json!({})).is_ok());
|
||||
|
||||
app.set_update_services_for_test(false);
|
||||
let refused = app.run("app.checkForUpdates", json!({}));
|
||||
let message = refused.unwrap_err();
|
||||
assert!(message.contains("ArtCraft Launcher"), "unexpected refusal: {message}");
|
||||
assert_eq!(app.ui.status, message);
|
||||
assert!(app.run("help.checkForUpdates", json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Re-selecting Preferences through either menu keeps its modal window open.
|
||||
#[test]
|
||||
fn preferences_menu_always_opens_instead_of_toggling() {
|
||||
@@ -953,60 +927,6 @@ mod tests {
|
||||
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (64, 64));
|
||||
}
|
||||
|
||||
fn recent_paths(count: usize) -> Vec<String> {
|
||||
(0..count).map(|i| format!("{i}.scraft")).collect()
|
||||
}
|
||||
|
||||
/// `ui.set` keeps the newest `MAX_RECENT` recent sessions, in order, and answers with that list.
|
||||
#[test]
|
||||
fn ui_set_keeps_at_most_ten_recent_sessions() {
|
||||
use crate::dialogs::recent::MAX_RECENT;
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
for count in [MAX_RECENT + 1, 1000] {
|
||||
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
|
||||
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT), "{count} entries: the first ten, in order");
|
||||
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(MAX_RECENT)), "{count} entries: the answer shows the kept list");
|
||||
}
|
||||
}
|
||||
|
||||
/// A list within the limit, an empty one included, is stored as given.
|
||||
#[test]
|
||||
fn ui_set_leaves_a_recent_list_within_the_limit_alone() {
|
||||
use crate::dialogs::recent::MAX_RECENT;
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
for count in [MAX_RECENT, MAX_RECENT - 1, 1, 0] {
|
||||
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
|
||||
assert_eq!(app.ui.recent_sessions, recent_paths(count), "{count} entries");
|
||||
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(count)), "{count} entries");
|
||||
}
|
||||
}
|
||||
|
||||
/// Capping the list does not drop the other fields of the same call.
|
||||
#[test]
|
||||
fn ui_set_applies_other_fields_beside_a_capped_recent_list() {
|
||||
use crate::dialogs::recent::MAX_RECENT;
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(25), "undo_levels": 7})).unwrap();
|
||||
assert_eq!((app.ui.recent_sessions.len(), app.ui.undo_levels, app.engine.history_limit), (MAX_RECENT, 7, 7));
|
||||
assert_eq!(result["ui"]["undo_levels"], 7);
|
||||
// A call that does not name the list leaves it as it was.
|
||||
app.run("ui.set", json!({"undo_levels": 9})).unwrap();
|
||||
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT));
|
||||
}
|
||||
|
||||
/// A list that is not an array of strings is refused, however long, and nothing changes.
|
||||
#[test]
|
||||
fn ui_set_refuses_a_recent_list_of_the_wrong_type() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
app.run("ui.set", json!({"recent_sessions": recent_paths(3), "undo_levels": 7})).unwrap();
|
||||
let numbers: Vec<u32> = (0..25).collect();
|
||||
for bad in [json!("a.scraft"), json!(5), json!(null), json!({"0": "a.scraft"}), json!(["a.scraft", 5]), json!(numbers)] {
|
||||
let error = app.run("ui.set", json!({"recent_sessions": bad, "undo_levels": 20})).unwrap_err();
|
||||
assert!(error.starts_with("bad ui state"), "{bad}: {error}");
|
||||
assert_eq!((app.ui.recent_sessions.clone(), app.ui.undo_levels), (recent_paths(3), 7), "{bad} changed the state");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_view_aliases_are_allocated_once() {
|
||||
let first = ui_aliases();
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(crate) fn output_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// last frame, because egui closes them before this runs.
|
||||
let busy_id = egui::Id::unique("output_window_escape");
|
||||
let busy = ctx.data(|d| d.get_temp(busy_id)).unwrap_or(false) || app.dialogs.open.is_some() || app.ui.show_search;
|
||||
if !busy && crate::framework::escape_pressed(ctx) {
|
||||
if !busy && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.ui.output_window = None;
|
||||
}
|
||||
output_window_contents(app, ctx);
|
||||
@@ -147,7 +147,7 @@ mod tests {
|
||||
app.run("view.edit_io", json!({})).unwrap();
|
||||
app.run("track.height", json!({"tracks": ["Kick"], "height": "medium"})).unwrap();
|
||||
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
|
||||
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::{
|
||||
Align2, Rect, Route, Sense, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackId, TrackKind, Ui, db_text, fader, json, pan_knob, pan_text, pos2,
|
||||
regular, text_toggle, vec2,
|
||||
};
|
||||
use craft_ui::combo::Menu;
|
||||
|
||||
/// Draw one send slot: the route area picks a destination, while the level area opens or edits the send level.
|
||||
pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: usize, r: Rect) {
|
||||
@@ -77,7 +78,7 @@ pub(crate) fn send_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// was theirs comes from the last frame. A dialog or the search on top takes it too.
|
||||
let busy_id = egui::Id::unique("send_window_escape");
|
||||
let busy = ctx.data(|d| d.get_temp(busy_id)).unwrap_or(false) || app.dialogs.open.is_some() || app.ui.show_search;
|
||||
if !busy && crate::framework::escape_pressed(ctx) {
|
||||
if !busy && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.ui.send_window = None;
|
||||
}
|
||||
send_window_contents(app, ctx);
|
||||
@@ -333,65 +334,6 @@ fn send_level_scale(ui: &mut Ui, db: f32) {
|
||||
ui.painter().line_segment([pos2(x, r.min.y), pos2(x, line_y + 3.0)], Stroke::new(2.0, t.counter_text));
|
||||
}
|
||||
|
||||
/// The most height of the send menu's contents.
|
||||
const SEND_MENU_HEIGHT: f32 = 260.0;
|
||||
|
||||
/// A menu under `field` that opens and closes on its clicks and closes on a click outside it: `header` stays at the
|
||||
/// top, `total_rows` rows of `row_height` scroll under it (only the rows in view are laid out) and `footer` stays under
|
||||
/// the list. The menu is up to [`SEND_MENU_HEIGHT`] tall and the room on its side of the field, at least as wide as
|
||||
/// the field, and opens below the field or above it, never beside it. Returns what `rows` and `footer` returned, or
|
||||
/// `None` while the menu is closed.
|
||||
fn header_footer_menu<H, R, F>(
|
||||
ui: &Ui,
|
||||
field: &egui::Response,
|
||||
header: impl FnOnce(&mut Ui) -> H,
|
||||
row_height: f32,
|
||||
total_rows: impl FnOnce(&H) -> usize,
|
||||
rows: impl FnOnce(&mut Ui, std::ops::Range<usize>, H) -> R,
|
||||
footer: impl FnOnce(&mut Ui) -> F,
|
||||
) -> Option<(R, F)> {
|
||||
let screen = ui.ctx().content_rect();
|
||||
let room = (screen.bottom() - field.rect.bottom()).max(field.rect.top() - screen.top());
|
||||
let frame = egui::Frame::popup(ui.style()).total_margin().sum().y;
|
||||
let height = SEND_MENU_HEIGHT.min(room - frame).max(0.0);
|
||||
let flipped: &'static [egui::RectAlign] =
|
||||
if ui.ctx().global_style().right_to_left { &[egui::RectAlign::TOP_END] } else { &[egui::RectAlign::TOP_START] };
|
||||
let popup = egui::Popup::menu(field);
|
||||
let id = popup.get_id();
|
||||
let footer_id = id.with("footer-height");
|
||||
let shown = popup
|
||||
.align_alternatives(flipped)
|
||||
.max_height_from_constrain(true)
|
||||
.width(field.rect.width())
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
// egui offers the popup last pass's height; offer the full height so a list that shrank (a search with
|
||||
// no matches) grows back.
|
||||
ui.set_max_height(height.min(ui.available_height()));
|
||||
let header = header(ui);
|
||||
// The footer comes after the list; keep the room it took last pass.
|
||||
let footer_room = ui.data(|d| d.get_temp::<f32>(footer_id)).unwrap_or(0.0) + ui.spacing().item_spacing.y;
|
||||
// Labels widen a narrow menu rather than wrap early, as in egui's combo box.
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
|
||||
let total = total_rows(&header);
|
||||
let list = egui::ScrollArea::vertical()
|
||||
.max_height((ui.available_height() - footer_room).max(0.0))
|
||||
.show_rows(ui, row_height, total, |ui, range| rows(ui, range, header))
|
||||
.inner;
|
||||
let top = ui.cursor().top();
|
||||
let footer = footer(ui);
|
||||
let footer_height = ui.min_rect().bottom() - top;
|
||||
ui.data_mut(|d| d.insert_temp(footer_id, footer_height));
|
||||
(list, footer)
|
||||
})
|
||||
.map(|shown| shown.inner);
|
||||
if shown.is_some() {
|
||||
ui.ctx().accesskit_node_builder(id, |node| node.set_role(egui::accesskit::Role::ListBox));
|
||||
}
|
||||
shown
|
||||
}
|
||||
|
||||
/// What the send menu's footer was used for.
|
||||
enum SendFooter {
|
||||
NewBus,
|
||||
@@ -427,9 +369,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
};
|
||||
let target = current.as_ref().map(|(route, _)| route);
|
||||
let row_h = ui.spacing().interact_size.y;
|
||||
let shown = header_footer_menu(
|
||||
ui,
|
||||
field,
|
||||
let shown = Menu::new(ui, field).height(260.0).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show_rows_with_header_footer(
|
||||
header,
|
||||
row_h,
|
||||
|(_, visible)| visible.len(),
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
//! The app id every SoundCraft OS window carries: the main window (`main.rs`), the runtime's
|
||||
//! windows (`InstallSpec::app_id`) and the extra windows built with [`builder`], so docks show
|
||||
//! the SoundCraft icon on them and Wayland compositors' window rules can match them (Hyprland's
|
||||
//! `class:`, #6697). Without one the app id is empty.
|
||||
|
||||
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
|
||||
pub const APP_ID: &str = "ai.storyteller.soundcraft";
|
||||
|
||||
/// Immutable startup identity. The desktop selects it before any UI/runtime service is created.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LaunchIdentity {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
|
||||
|
||||
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
|
||||
let value = match identity {
|
||||
LaunchIdentity::Stable => 1,
|
||||
LaunchIdentity::NightlyV1 => 2,
|
||||
};
|
||||
IDENTITY
|
||||
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
|
||||
.map(|_| ())
|
||||
.map_err(|_| "the window launch identity was already selected".into())
|
||||
}
|
||||
|
||||
pub fn identity() -> LaunchIdentity {
|
||||
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
|
||||
}
|
||||
|
||||
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => APP_ID,
|
||||
LaunchIdentity::NightlyV1 => "ai.storyteller.soundcraft.nightly-v1",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn app_id() -> &'static str {
|
||||
id_for(identity())
|
||||
}
|
||||
|
||||
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => "SoundCraft",
|
||||
LaunchIdentity::NightlyV1 => "SoundCraft Nightly",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
|
||||
matches!(identity, LaunchIdentity::Stable)
|
||||
}
|
||||
|
||||
pub fn stable_services_allowed() -> bool {
|
||||
stable_services_for(identity())
|
||||
}
|
||||
|
||||
/// A builder for an extra OS window, carrying [`APP_ID`].
|
||||
pub fn builder() -> egui::ViewportBuilder {
|
||||
egui::ViewportBuilder::default().with_app_id(app_id())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn extra_windows_carry_the_app_id() {
|
||||
assert_eq!(super::builder().app_id.as_deref(), Some("ai.storyteller.soundcraft"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod profile_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn nightly_identity_is_distinct_and_never_enables_stable_services() {
|
||||
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
|
||||
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
|
||||
assert!(stable_services_for(LaunchIdentity::Stable));
|
||||
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
let t = Tokens::current();
|
||||
let mut run: Option<String> = None;
|
||||
let mut close = crate::framework::escape_pressed(ctx);
|
||||
let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
egui::Window::new(crate::localization::text("Search"))
|
||||
.id(egui::Id::unique("Search"))
|
||||
.collapsible(false)
|
||||
|
||||
@@ -27,13 +27,8 @@ pub(super) fn about(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
1 => crate::credits::contributors_ui(ui),
|
||||
2 => crate::credits::models_ui(ui),
|
||||
_ => {
|
||||
let channel = crate::os_window::name_for(crate::os_window::identity());
|
||||
ui.label(egui::RichText::new(channel).font(bold(22.0)));
|
||||
ui.label(crate::localized_format!("Version {}", crate::build_version()));
|
||||
if crate::os_window::identity() == crate::os_window::LaunchIdentity::NightlyV1 {
|
||||
ui.label(crate::localization::text("Updated by ArtCraft Launcher."));
|
||||
ui.hyperlink_to(crate::localization::text("Report a problem"), "https://github.com/storytold/soundcraft/issues");
|
||||
}
|
||||
ui.label(egui::RichText::new(crate::localization::text("SoundCraft")).font(bold(22.0)));
|
||||
ui.label(crate::localized_format!("Version {}", env!("CARGO_PKG_VERSION")));
|
||||
ui.label(crate::localization::text("An open-source digital audio workstation from the ArtCraft team."));
|
||||
ui.label(crate::localization::text("Dual-licensed MIT OR Apache-2.0. Made with Rust and egui."));
|
||||
ui.hyperlink_to("getartcraft.com/apps/soundcraft", "https://getartcraft.com/apps/soundcraft");
|
||||
|
||||
@@ -35,13 +35,6 @@ impl Default for ExtraState {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtraState {
|
||||
/// The interface scale applied to the context last; 1 until one is applied.
|
||||
pub(crate) fn applied_scale(&self) -> f32 {
|
||||
self.applied.map_or(1.0, |(scale, _)| scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// UI commands handled here (`window.renderer`, `window.ui_customization`, `window.config_auto_update`).
|
||||
pub fn run(app: &mut SoundApp, id: &str, p: &Value) -> Option<Value> {
|
||||
let flag = |v: &mut bool| {
|
||||
@@ -182,7 +175,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.text(crate::localization::text("Interface scale")),
|
||||
);
|
||||
let mut chosen_effects = None;
|
||||
egui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
|
||||
.selected_text(crate::localization::text(app.ui.reduce_visual_effects.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for mode in crate::preferences::ReduceVisualEffects::ALL {
|
||||
@@ -195,7 +188,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let _ = app.run("ui.reduce_visual_effects", json!({"mode": mode.id()}));
|
||||
}
|
||||
let mut selected_language = None;
|
||||
egui::ComboBox::from_label(crate::localization::text("Language"))
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Language"))
|
||||
.selected_text(crate::localization::text(language.native_name()))
|
||||
.show_ui(ui, |ui| {
|
||||
for choice in crate::localization::Language::ALL {
|
||||
@@ -208,16 +201,15 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let _ = app.run("ui.language", json!({"language": choice.id()}));
|
||||
}
|
||||
let mut chosen = None;
|
||||
egui::ComboBox::from_label(crate::localization::text("Theme")).selected_text(crate::localization::text(app.ui.theme.label())).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Theme"))
|
||||
.selected_text(crate::localization::text(app.ui.theme.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for mode in crate::theme::ThemeMode::ALL {
|
||||
if ui.selectable_label(app.ui.theme == mode, crate::localization::text(mode.label())).clicked() {
|
||||
chosen = Some(mode);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
if let Some(mode) = chosen {
|
||||
let _ = app.run("ui.theme", json!({"mode": mode.id()}));
|
||||
}
|
||||
|
||||
@@ -432,7 +432,7 @@ fn note_pointer(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId, penc
|
||||
fn note_keys(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId) {
|
||||
let Roll { sequence, roll, grid_ticks, .. } = *g;
|
||||
// Keyboard: Cmd+A select all; arrows transpose (Shift = octave) and move by the grid.
|
||||
if ui.rect_contains_pointer(roll) && !crate::framework::widget_has_keyboard(ui.ctx()) {
|
||||
if ui.rect_contains_pointer(roll) && !ui.ctx().egui_wants_keyboard_input() {
|
||||
let (all, up, down, left, right, shift) = ui.input(|i| {
|
||||
let arrows = !i.modifiers.alt && !i.modifiers.command && !i.modifiers.ctrl;
|
||||
(
|
||||
@@ -469,7 +469,7 @@ fn note_keys(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId) {
|
||||
}
|
||||
}
|
||||
if !app.midi.selected.is_empty()
|
||||
&& !crate::framework::widget_has_keyboard(ui.ctx())
|
||||
&& !ui.ctx().egui_wants_keyboard_input()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
|
||||
{
|
||||
let _ = app.run("midi.note_delete", json!({"clip": cid.0, "indices": app.midi.selected}));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user