Merge main into fix/apprun-preserve-custom-launcher-2905
Resolve the packaging/linux/AppRun conflict by keeping both sides: main's early `--cli` / `photocraft-cli` ARGV0 dispatch runs first, then this branch's valid_baseline() check for the desktop-integration launcher. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@@ -0,0 +1,6 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
reviews:
|
||||
auto_review:
|
||||
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
|
||||
ignore_usernames:
|
||||
- "dependabot[bot]"
|
||||
@@ -1,3 +1,7 @@
|
||||
# Refuse to run under a nextest older than the fixed release: GHSA-vc25-qg58-w57c is fixed in
|
||||
# 0.9.150, and CI installs exactly that version (an older nextest exits 92 REQUIRED_VERSION_NOT_MET).
|
||||
nextest-version = "0.9.150"
|
||||
|
||||
# cargo-nextest (https://nexte.st): runs every test in its own process, in parallel across test
|
||||
# binaries. CI runs it with the `ci` profile below (#6117); locally it is optional and `cargo test`
|
||||
# keeps working (#2204).
|
||||
@@ -15,10 +19,29 @@ gpu = { max-threads = 4 }
|
||||
filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))'
|
||||
test-group = 'gpu'
|
||||
|
||||
# CI (`--profile ci`, .github/workflows/ci.yml). Stops at the first failure so a red PR frees its
|
||||
# runner, fails a test that hangs instead of letting it hold the runner, and repeats every failure
|
||||
# at the end of the log. The default profile's GPU override still applies.
|
||||
# CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run
|
||||
# instead of exposing one regression per rebuild. A hanging test still terminates, and every
|
||||
# failure is repeated at the end of the log. The default profile's GPU override still applies.
|
||||
[profile.ci]
|
||||
fail-fast = true
|
||||
fail-fast = false
|
||||
slow-timeout = { period = "60s", terminate-after = 10 }
|
||||
failure-output = "immediate-final"
|
||||
|
||||
# Keep phase timings for the remaining expensive Windows GPU regressions visible. This does
|
||||
# not relax their timeout, isolate failures differently or remove any test cases.
|
||||
# Page eviction and budget borrowing redraw multi-effect documents. On the Windows
|
||||
# CPU-backed adapter it uses all GPU slots, avoiding oversubscription without skipping work.
|
||||
[[profile.ci.overrides]]
|
||||
platform = 'cfg(target_os = "windows")'
|
||||
filter = 'package(photocraft-gpu) & test(/pages_are_evicted_under_the_budget|layer_pages_that_just_miss_borrow_the_effect_map_share/)'
|
||||
threads-required = 4
|
||||
success-output = "immediate"
|
||||
|
||||
[[profile.ci.overrides]]
|
||||
platform = 'cfg(target_os = "windows")'
|
||||
filter = 'package(photocraft-gpu) & test(/documents_larger_than_the_texture_limit|layer_effects_update_incrementally|pages_are_evicted_under_the_budget|the_focused_view_stays_resident_after_a_full_refresh/)'
|
||||
success-output = "immediate"
|
||||
# These multi-page effect regressions saturate the Windows software GPU. Reserve two
|
||||
# scheduling slots so four independent devices do not compete for the same CPU renderer.
|
||||
# All cases and the 60-second warning remain unchanged.
|
||||
threads-required = 2
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Maintain Rust / Cargo dependencies
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
# Consolidate updates into a single PR rather than one PR per crate
|
||||
groups:
|
||||
cargo-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "chore(deps)"
|
||||
|
||||
# Maintain GitHub Actions workflows
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "ci(deps)"
|
||||
@@ -1,12 +1,40 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request. The Linux gate runs through the
|
||||
# suite's shared gate workflow in craft-common-actions (`cargo xtask ci`); the Windows legs, the
|
||||
# test variant and the corpus, web and fuzz jobs are PhotoCraft's own.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
# `labeled` so that adding `full-ci` to an open PR starts a run with Windows in it.
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
full_sweep:
|
||||
description: "Run every testkit sweep case (runtime comparison and integration validation)"
|
||||
type: boolean
|
||||
default: false
|
||||
color_range:
|
||||
description: "Compare cropped Color Range on 24 MP (Linux, exact outputs)"
|
||||
type: boolean
|
||||
default: false
|
||||
selection_combining:
|
||||
description: "Compare direct GRAY8 selection combining on 36 MP (Linux, exact outputs)"
|
||||
type: boolean
|
||||
default: false
|
||||
brush_tip:
|
||||
description: "Compare cached round-tip rasterization on 24 MP"
|
||||
type: boolean
|
||||
default: false
|
||||
brush_tip_base:
|
||||
description: "Baseline commit for the round-tip comparison"
|
||||
type: string
|
||||
default: "main"
|
||||
selection_morphology:
|
||||
description: "Compare selection morphology on 36 MP (Linux, exact outputs)"
|
||||
type: boolean
|
||||
default: false
|
||||
fuzz:
|
||||
description: "Run the fuzz job"
|
||||
type: boolean
|
||||
@@ -14,59 +42,89 @@ on:
|
||||
fuzz_seconds:
|
||||
description: "Seconds per fuzz target"
|
||||
default: "600"
|
||||
dry_mixer:
|
||||
description: "Compare the live Mixer Brush against the origin/main merge base on 24 MP (Linux)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
# The token is only used to check out the code: no job writes to the repository.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
PHOTOCRAFT_FULL_SWEEP: ${{ inputs.full_sweep && '1' || '0' }}
|
||||
# No test or fuzz run may print a page: the engine refuses to spool, and if something ever
|
||||
# bypasses that, lp fails loudly on a printer that does not exist.
|
||||
PHOTOCRAFT_NO_PRINT: "1"
|
||||
LPDEST: photocraft-no-such-printer
|
||||
# Debug and test builds keep line tables (file:line in panic backtraces) but drop the rest of the
|
||||
# debug info: faster codegen and links, and a smaller target dir (the Linux test job ran out of
|
||||
# disk with full debug info). The Windows test legs drop debuginfo entirely (see the test job).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
|
||||
# A newer push to a PR branch cancels its older run. Runs on main are never cancelled: a merge
|
||||
# that lands while main's run is in progress waits for it, so every main state that gets a run is
|
||||
# checked to the end. (Cancelling here left main unverified whenever merges came close together.)
|
||||
# A newer push to a PR branch cancels its older run. Every push to main gets a run of its own that
|
||||
# is never cancelled, so each state of main is checked to the end. Adding any label but `full-ci`
|
||||
# gets a group of its own, so it neither runs anything nor cancels a run.
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# Which OSes the test job runs on. main, manual runs and PRs labelled `full-ci` get Linux and
|
||||
# Windows. Other PRs get Linux, plus Windows when they touch code whose behaviour differs by
|
||||
# platform: the app shell, UI, text and fonts, GPU, pen input, build scripts or the lockfile.
|
||||
# macOS is tested only by release.yml.
|
||||
# Whether the Windows legs and the web build run. main, manual runs and PRs labelled `full-ci`
|
||||
# get both. Other PRs get Windows when they touch code whose behaviour differs by platform: the
|
||||
# app shell, UI, text and fonts, GPU, pen input, native saves, build scripts or the lockfile.
|
||||
# Format changes must exercise the Windows-only publication barriers (#8034). macOS is tested
|
||||
# only by release.yml.
|
||||
platforms:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
timeout-minutes: 10
|
||||
name: select platforms
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
legs: ${{ steps.pick.outputs.legs }}
|
||||
windows: ${{ steps.pick.outputs.windows }}
|
||||
web: ${{ steps.pick.outputs.web }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
- id: pick
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
BASE: ${{ github.event.pull_request.base.sha }}
|
||||
FULL: ${{ contains(github.event.pull_request.labels.*.name, 'full-ci') }}
|
||||
run: |
|
||||
# No macOS on PRs or main: the org's 5 macOS slots are kept for release builds, and
|
||||
# release.yml builds and tests macOS (a failing release is fixed and rebuilt).
|
||||
# Windows tests run as two legs in parallel: the unit tests and the integration tests. As
|
||||
# one job they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting
|
||||
# the integration tests over a third runner (nextest --partition) saved ~2 min of wall
|
||||
# time but cost ~7 runner-minutes and one more Windows slot per PR.
|
||||
linux='{"os":"ubuntu-latest","part":"all"}'
|
||||
win() { printf '{"os":"windows-latest","part":"%s"}' "$1"; }
|
||||
all="[$linux,$(win unit),$(win integration)]"
|
||||
if [ "$EVENT" != pull_request ] || [ "$FULL" = true ]; then
|
||||
echo "legs=$all" >> "$GITHUB_OUTPUT"
|
||||
echo "windows=true" >> "$GITHUB_OUTPUT"
|
||||
echo "web=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
@@ -78,67 +136,101 @@ jobs:
|
||||
else
|
||||
echo "web=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif)/|Cargo\.lock$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
|
||||
echo "legs=$all" >> "$GITHUB_OUTPUT"
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
|
||||
echo "windows=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "legs=[$linux]" >> "$GITHUB_OUTPUT"
|
||||
echo "windows=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
test:
|
||||
timeout-minutes: 100
|
||||
name: test (${{ matrix.os }}${{ matrix.part != 'all' && format(', {0}', matrix.part) || '' }})
|
||||
# The Linux gate. Its rust-cache entry is the one `test (without heif)` restores.
|
||||
gate:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# egui/winit/rfd.
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
# The tests build with the optional craft-fonts input (crates/text/build.rs), so the
|
||||
# Japanese font tests that skip without it run. Same commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# Cargo.toml's dev profile already keeps line tables only.
|
||||
dev-debug: ""
|
||||
env: |
|
||||
PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }}
|
||||
PHOTOCRAFT_NO_PRINT=1
|
||||
LPDEST=photocraft-no-such-printer
|
||||
timeout-minutes: 100
|
||||
# fmt, clippy, layers, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
|
||||
# `--locked --features heif`, then the missing-translations report (xtask/src/main.rs).
|
||||
command: cargo xtask ci
|
||||
|
||||
# Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job
|
||||
# they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration
|
||||
# tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7
|
||||
# runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache,
|
||||
# which needs its own action step.
|
||||
windows:
|
||||
needs: platforms
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: needs.platforms.outputs.windows == 'true'
|
||||
timeout-minutes: 100
|
||||
name: test (windows-latest, ${{ matrix.part }})
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.platforms.outputs.legs) }}
|
||||
part: [unit, integration]
|
||||
env:
|
||||
# No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes.
|
||||
# A panic still names its file and line; only backtrace frames lose theirs (Linux keeps
|
||||
# line-tables-only, so a backtrace with lines is one OS away).
|
||||
CARGO_PROFILE_DEV_DEBUG: ${{ startsWith(matrix.os, 'windows') && '0' || 'line-tables-only' }}
|
||||
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||
# The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels
|
||||
# with kittest's strict `MissingGlyphPolicy::Panic`. A hosted Windows image has no
|
||||
# guaranteed Japanese or Simplified Chinese system font, and egui 0.37 panics on a
|
||||
# missing glyph; the app's lazy system fallback runs after layout, too late for the
|
||||
# first headless frame. Use the same pinned central fonts as Linux and release, so every
|
||||
# language is drawn by a real embedded face rather than skipping. Same commit as the gate
|
||||
# above and release.yml.
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Unused toolchains in the image (Android SDK, .NET, GHC, CodeQL) are deleted in the
|
||||
# background: the space is free before the craft-fonts build needs it, and nothing waits.
|
||||
- name: Install Linux system dependencies (egui/winit/rfd)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
nohup sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \
|
||||
/opt/hostedtoolcache/CodeQL </dev/null >/dev/null 2>&1 &
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \
|
||||
libgl1-mesa-dev libgtk-3-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
persist-credentials: false
|
||||
|
||||
# Only main saves caches; PRs restore main's. Every PR used to save its own set (up to
|
||||
# 3.8 GB), usable by that PR only, so the repo's 10 GB cache budget kept evicting main's.
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
path: craft-fonts
|
||||
persist-credentials: false
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
components: clippy
|
||||
|
||||
# Only main saves caches; PRs restore main's, so the repo's 10 GB cache budget keeps main's.
|
||||
# A failing test still saves: the cache holds compiled dependencies, not test results.
|
||||
# The Windows legs share one key (same dependencies); the integration leg saves it,
|
||||
# because it also runs Clippy and so leaves Clippy's dependency metadata in it.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
# Both legs share one key (same dependencies); the integration leg saves it, because it also
|
||||
# runs Clippy and so leaves Clippy's dependency metadata in it.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && (matrix.part == 'all' || matrix.part == 'integration') }}
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }}
|
||||
cache-on-failure: true
|
||||
|
||||
# sccache caches the workspace crates' compiled libraries, which rust-cache leaves out:
|
||||
# warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read
|
||||
# main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688).
|
||||
# Test executables can't be cached, so a PR still links its tests.
|
||||
- name: Install sccache (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
- name: Install sccache
|
||||
uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: v0.18.0
|
||||
|
||||
- name: Use sccache (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
- name: Use sccache
|
||||
env:
|
||||
MAIN: ${{ github.ref == 'refs/heads/main' }}
|
||||
run: |
|
||||
@@ -147,139 +239,80 @@ jobs:
|
||||
if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi
|
||||
shell: bash
|
||||
|
||||
- name: Format
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
# Keep formatting, strict Clippy, layering and scorecard checks ahead of tests.
|
||||
- name: Clippy
|
||||
if: matrix.part == 'all' || matrix.part == 'integration'
|
||||
if: matrix.part == 'integration'
|
||||
run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings
|
||||
|
||||
- name: Dependency layering
|
||||
if: matrix.part == 'all' || matrix.part == 'integration'
|
||||
if: matrix.part == 'integration'
|
||||
run: cargo xtask layers
|
||||
|
||||
# docs/scorecard.md must match its sources (checklists, budgets, baseline, corpus floors,
|
||||
# prefs audit). Static: it reads committed files only, no benchmarks run here.
|
||||
- name: Scorecard up to date
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo xtask scorecard --check
|
||||
|
||||
# nextest runs the test binaries in parallel (cargo test runs them one at a time), with the
|
||||
# GPU tests capped by the `gpu` group in .config/nextest.toml (#2204).
|
||||
- uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22
|
||||
- uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
with:
|
||||
tool: cargo-nextest@0.9.146
|
||||
tool: cargo-nextest@0.9.150
|
||||
|
||||
# `--features heif`: official builds open HEIC photos via the optional photocraft-heif crate.
|
||||
# `--lib --bins --tests` leaves out the examples, which cargo test would build and link but
|
||||
# never run (Clippy's `--all-targets` still checks they compile). nextest skips doctests, so
|
||||
# they get their own step.
|
||||
#
|
||||
# On Windows the unit leg runs `--lib --bins` and the integration leg `--test '*'` (every
|
||||
# The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every
|
||||
# integration-test target); the feature selection stays the same, so both legs share the
|
||||
# dependency cache. The `ci` profile fails fast and terminates hung tests
|
||||
# (.config/nextest.toml); assertion failures are not retried.
|
||||
# dependency cache.
|
||||
- name: Test
|
||||
env:
|
||||
PART: ${{ matrix.part }}
|
||||
run: |
|
||||
case "$PART" in
|
||||
unit) targets=(--lib --bins) ;;
|
||||
integration) targets=(--test '*') ;;
|
||||
*) targets=(--lib --bins --tests) ;;
|
||||
*) targets=(--test '*') ;;
|
||||
esac
|
||||
cargo nextest run --profile ci --workspace --locked --features heif "${targets[@]}"
|
||||
shell: bash
|
||||
|
||||
- name: Doctests
|
||||
if: matrix.part == 'all' || matrix.part == 'unit'
|
||||
if: matrix.part == 'unit'
|
||||
run: cargo test --workspace --locked --features heif --doc
|
||||
|
||||
# The Windows tests used to be one job named `test (windows-latest)`; they're now legs named
|
||||
# `test (windows-latest, unit)` and `test (windows-latest, integration)`. This job keeps the old
|
||||
# name reporting, so a required status check on it (none today) would keep working. It fails
|
||||
# unless the whole test matrix and both Linux variants passed. `needs` reports one result
|
||||
# for all matrix legs; when a PR runs no Windows legs it still checks every Linux result.
|
||||
windows-gate:
|
||||
timeout-minutes: 5
|
||||
name: test (windows-latest)
|
||||
needs: [platforms, test, test-variants]
|
||||
if: ${{ !cancelled() }}
|
||||
runs-on: ubuntu-latest
|
||||
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error
|
||||
# for distributors who leave it out. Runs beside the gate and restores the gate's dependency
|
||||
# cache without saving one: the dependencies are the same, and the 10 GB cache budget is tight
|
||||
# (#2688).
|
||||
test-without-heif:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
timeout-minutes: 60
|
||||
name: test (without heif)
|
||||
# The gate's runner: its cache entry is keyed on the OS.
|
||||
runs-on: ubuntu-24.04
|
||||
env:
|
||||
# The gate sets these; rust-cache hashes CARGO_* and RUST* variables into its key.
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_RETRY: 10
|
||||
steps:
|
||||
- env:
|
||||
PLATFORMS: ${{ needs.platforms.result }}
|
||||
TEST: ${{ needs.test.result }}
|
||||
VARIANTS: ${{ needs.test-variants.result }}
|
||||
run: |
|
||||
echo "platforms: $PLATFORMS, test: $TEST, variants: $VARIANTS"
|
||||
[ "$PLATFORMS" = success ] && [ "$TEST" = success ] && [ "$VARIANTS" = success ]
|
||||
|
||||
# The two other builds of the Linux tests, in parallel with the test job instead of after it (they
|
||||
# added ~10 min to its critical path). Each restores the test job's cache (`shared-key: test` is
|
||||
# that job's key) and saves none: the dependencies are the same, and the 10 GB cache budget is
|
||||
# tight (#2688).
|
||||
test-variants:
|
||||
timeout-minutes: 100
|
||||
name: test (${{ matrix.variant }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
variant: [without heif, with craft-fonts]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Linux system dependencies (egui/winit/rfd)
|
||||
run: |
|
||||
nohup sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \
|
||||
/opt/hostedtoolcache/CodeQL </dev/null >/dev/null 2>&1 &
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \
|
||||
libgl1-mesa-dev libgtk-3-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
shared-key: test
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
|
||||
# gate.yml keys its cache `<cache-version>-rust-<hash of Cargo.toml>-gate`.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
prefix-key: v1-rust
|
||||
shared-key: ${{ hashFiles('Cargo.toml') }}-gate
|
||||
save-if: false
|
||||
|
||||
- uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22
|
||||
- uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
with:
|
||||
tool: cargo-nextest@0.9.146
|
||||
tool: cargo-nextest@0.9.150
|
||||
|
||||
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build"
|
||||
# error for distributors who leave it out.
|
||||
- name: Test without heif
|
||||
if: matrix.variant == 'without heif'
|
||||
run: cargo nextest run -p photocraft-heif -p photocraft-codecs -p photocraft-io --locked --profile ci
|
||||
|
||||
# The tests built with the optional craft-fonts input (crates/text/build.rs), so the Japanese
|
||||
# font tests that skip without it run. Keep the test job's exact `--workspace --features heif
|
||||
# --lib --bins --tests`, so the restored dependencies match and only the workspace rebuilds.
|
||||
# Filter execution to the three crates that read the optional font input (#6127).
|
||||
- name: Check out craft-fonts
|
||||
if: matrix.variant == 'with craft-fonts'
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
|
||||
- name: Test with craft-fonts
|
||||
if: matrix.variant == 'with craft-fonts'
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
run: >-
|
||||
cargo nextest run --profile ci --workspace --locked --features heif --lib --bins --tests
|
||||
-E 'package(photocraft-text) | package(photocraft-io) | package(photocraft-ui-egui)'
|
||||
|
||||
corpus:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
timeout-minutes: 30
|
||||
# Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are
|
||||
# pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache
|
||||
@@ -295,15 +328,17 @@ jobs:
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: corpus
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
- name: Restore test corpora
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: corpus/
|
||||
key: corpus-${{ hashFiles('xtask/src/corpus_pins.rs', 'xtask/*.sha256') }}
|
||||
@@ -312,23 +347,6 @@ jobs:
|
||||
- name: Corpus tests
|
||||
run: cargo xtask test-corpus
|
||||
|
||||
wasm:
|
||||
timeout-minutes: 30
|
||||
name: wasm32 check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: wasm32
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
- name: Check wasm-safe crates
|
||||
run: cargo xtask wasm
|
||||
|
||||
web:
|
||||
timeout-minutes: 60
|
||||
name: web build and wasm size gate
|
||||
@@ -340,18 +358,20 @@ jobs:
|
||||
# Match release.yml so PR results reflect what would actually ship.
|
||||
TRUNK_VERSION: 0.21.14
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: ci-web
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
- name: Install trunk
|
||||
run: |
|
||||
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
|
||||
curl --proto '=https' -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
|
||||
| tar -xz -C "$HOME/.cargo/bin" trunk
|
||||
trunk --version
|
||||
# package.sh runs Trunk's release builds, validates relative URLs, cuts the wasm into
|
||||
@@ -398,6 +418,7 @@ jobs:
|
||||
- { crate: psd, name: metadata }
|
||||
- { crate: psd, name: tagged }
|
||||
- { crate: psd, name: resources }
|
||||
- { crate: psd, name: asl }
|
||||
- { crate: codecs, name: decode_any }
|
||||
- { crate: codecs, name: decode_png }
|
||||
- { crate: codecs, name: decode_jpeg }
|
||||
@@ -408,19 +429,237 @@ jobs:
|
||||
- { crate: affinity, name: import_preview, args: "--features io" }
|
||||
- { crate: format, name: load }
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # nightly
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: crates/${{ matrix.target.crate }}/fuzz
|
||||
- name: Install cargo-fuzz
|
||||
run: cargo install cargo-fuzz --locked
|
||||
- name: Fuzz
|
||||
working-directory: crates/${{ matrix.target.crate }}
|
||||
run: cargo fuzz run ${{ matrix.target.name }} ${{ matrix.target.args }} -- -max_total_time=${{ inputs.fuzz_seconds }}
|
||||
env:
|
||||
FUZZ_SECONDS: ${{ inputs.fuzz_seconds }}
|
||||
run: cargo fuzz run ${{ matrix.target.name }} ${{ matrix.target.args }} -- -max_total_time="$FUZZ_SECONDS"
|
||||
- name: Upload crash artifacts
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: fuzz-${{ matrix.target.crate }}-${{ matrix.target.name }}
|
||||
path: crates/${{ matrix.target.crate }}/fuzz/artifacts
|
||||
|
||||
color-range-performance:
|
||||
if: inputs.color_range == true
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: color-range-perf
|
||||
- name: Compare exact outputs and release timings on 24 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo test --release -p photocraft-engine --lib color_range_release_comparison -- --ignored --nocapture | tee color-range-perf.txt
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: color-range-performance
|
||||
path: color-range-perf.txt
|
||||
|
||||
selection-morphology:
|
||||
if: inputs.selection_morphology == true
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: selection-morphology-perf
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo run --release -p photocraft-algo --example bench_selection_morphology | tee selection-morphology-perf.txt
|
||||
- name: Compare cropped command reads and writeback on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo test --release -p photocraft-engine --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: selection-morphology-performance
|
||||
path: selection-morphology-perf.txt
|
||||
|
||||
selection-morphology-quick-perf:
|
||||
if: inputs.selection_morphology == true || inputs.color_range == true || inputs.selection_combining == true || inputs.brush_tip == true || inputs.dry_mixer == true
|
||||
name: quick performance suite
|
||||
# Match perf-nightly.yml: Linux llvmpipe lacks the float render targets needed by
|
||||
# bevel_bench, so its required GPU rows cannot be measured there.
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: perf-release
|
||||
- name: Quick performance suite
|
||||
run: cargo xtask perf --quick
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: selection-morphology-quick-perf
|
||||
path: |
|
||||
target/perf/*.json
|
||||
target/perf/summary.md
|
||||
|
||||
selection-combining:
|
||||
if: inputs.selection_combining == true
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: selection-combining-perf
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo test --release -p photocraft-algo --lib gray8_combining_release_comparison -- --ignored --nocapture | tee selection-combining-perf.txt
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: selection-combining-performance
|
||||
path: selection-combining-perf.txt
|
||||
|
||||
brush-tip:
|
||||
if: inputs.brush_tip == true
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
path: after
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.brush_tip_base }}
|
||||
path: before
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: |
|
||||
before -> target
|
||||
after -> target
|
||||
key: brush-tip-release
|
||||
- name: Build the same benchmark against both versions
|
||||
run: |
|
||||
cp after/crates/paint/examples/big_dab_bench.rs before/crates/paint/examples/big_dab_bench.rs
|
||||
cargo build --release --locked --manifest-path before/Cargo.toml -p photocraft-paint --example big_dab_bench
|
||||
cargo build --release --locked --manifest-path after/Cargo.toml -p photocraft-paint --example big_dab_bench
|
||||
- name: Compare round and transformed tips on 24 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
for size in 200 2000; do
|
||||
for angle in 0 0.7; do
|
||||
for version in before after; do
|
||||
echo "$version: size=$size angle=$angle" | tee -a brush-tip.txt
|
||||
"$version/target/release/examples/big_dab_bench" "$size" 0.37 "$angle" | tee -a brush-tip.txt
|
||||
done
|
||||
done
|
||||
done
|
||||
- uses: actions/upload-artifact@v7
|
||||
if: always()
|
||||
with:
|
||||
name: brush-tip-performance
|
||||
path: brush-tip.txt
|
||||
dry-mixer:
|
||||
if: inputs.dry_mixer == true
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Pin baseline to the merge base with origin/main
|
||||
id: baseline
|
||||
run: |
|
||||
git remote add upstream https://github.com/storytold/photocraft.git
|
||||
git fetch --no-tags upstream main
|
||||
base=$(git merge-base HEAD upstream/main)
|
||||
echo "sha=$base" >> "$GITHUB_OUTPUT"
|
||||
git worktree add --detach "$RUNNER_TEMP/photocraft-baseline" "$base"
|
||||
mkdir -p "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples"
|
||||
cp crates/engine/examples/bench_dry_mixer.rs "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples/bench_dry_mixer.rs"
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- name: Benchmark baseline and candidate on this runner
|
||||
run: |
|
||||
set -o pipefail
|
||||
echo "baseline=${{ steps.baseline.outputs.sha }}" | tee dry-mixer-perf.txt
|
||||
echo "candidate=${GITHUB_SHA}" | tee -a dry-mixer-perf.txt
|
||||
CARGO_TARGET_DIR="$RUNNER_TEMP/target-baseline" cargo run --release --manifest-path "$RUNNER_TEMP/photocraft-baseline/Cargo.toml" -p photocraft-engine --example bench_dry_mixer | tee baseline-mixer.txt
|
||||
CARGO_TARGET_DIR="$RUNNER_TEMP/target-candidate" cargo run --release -p photocraft-engine --example bench_dry_mixer | tee candidate-mixer.txt
|
||||
cat baseline-mixer.txt candidate-mixer.txt >> dry-mixer-perf.txt
|
||||
python3 - <<'PY'
|
||||
import re
|
||||
def fingerprints(path):
|
||||
rows = open(path).readlines()
|
||||
result = {}
|
||||
for row in rows:
|
||||
match = re.search(r'wet=\s*(\d+)% sample_all=\s*(\w+)\s+size=\s*(\d+).*blake3=(\w+)', row)
|
||||
if match:
|
||||
result[match.group(1, 2, 3)] = match.group(4)
|
||||
return result
|
||||
before, after = fingerprints('baseline-mixer.txt'), fingerprints('candidate-mixer.txt')
|
||||
assert len(before) == 12 and before == after, 'baseline/candidate mixer output or state differs'
|
||||
PY
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: dry-mixer-performance
|
||||
path: dry-mixer-perf.txt
|
||||
|
||||
@@ -31,8 +31,8 @@ jobs:
|
||||
name: mdBook build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@v7
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- name: Install mdBook
|
||||
run: cargo install mdbook --version 0.4.52 --locked
|
||||
- name: Build documentation
|
||||
|
||||
@@ -9,6 +9,8 @@ name: FreeBSD
|
||||
# or dependency change: a drifted dependency still shows up within a day. PRs that change the
|
||||
# FreeBSD packaging itself still run it.
|
||||
on:
|
||||
push:
|
||||
branches: [release]
|
||||
schedule:
|
||||
- cron: "17 2 * * *"
|
||||
pull_request:
|
||||
@@ -30,7 +32,9 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
cargo-build-extra-args: "--features heif"
|
||||
custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-ui-egui && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --lib && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --test '*' -- --test-threads=1"
|
||||
# The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at
|
||||
# once, so photocraft-gpu's tests run one at a time, like ui-egui's integration tests.
|
||||
custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-ui-egui --exclude photocraft-gpu && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-gpu --locked -- --test-threads=1 && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --lib && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --test '*' -- --test-threads=1"
|
||||
run-package-check: true
|
||||
|
||||
@@ -18,16 +18,6 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
eval:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
|
||||
- name: nix flake check --no-build
|
||||
run: |
|
||||
if [ -f flake.nix ]; then
|
||||
nix flake check --no-build --all-systems
|
||||
else
|
||||
echo "No flake.nix present in this repository; skipping check."
|
||||
fi
|
||||
nix:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
|
||||
|
||||
@@ -29,3 +29,27 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: bash packaging/linux/verified-download-test.sh
|
||||
|
||||
windows-install-policy:
|
||||
timeout-minutes: 10
|
||||
name: Windows installation policy (no app build)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the pinned packaging toolchain
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix'
|
||||
dotnet tool install --tool-path $tools wix --version 5.0.2
|
||||
if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' }
|
||||
$tools >> $env:GITHUB_PATH
|
||||
$policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json
|
||||
foreach ($extension in @($policy.extensions)) {
|
||||
& (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2"
|
||||
if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." }
|
||||
}
|
||||
- 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')
|
||||
|
||||
@@ -4,10 +4,13 @@ name: Perf (nightly)
|
||||
# Metal), every night and on demand. It never runs on pull requests, so it can't block one.
|
||||
# It fails when an enforced budget in perf/budgets.toml breaks or a scenario's p50 regresses
|
||||
# more than 15 % against perf/baseline.json from the same machine class (other classes are
|
||||
# never compared). The table goes to the job summary; results.json is uploaded as an artifact.
|
||||
# never compared; a baseline built from several runs is judged against its highest p50). The
|
||||
# table goes to the job summary; results.json is uploaded as the `perf-results` artifact.
|
||||
#
|
||||
# To give this runner class its own baseline: run it by hand with "update_baseline", download
|
||||
# the `perf-baseline` artifact and commit it as perf/baseline.json in a PR.
|
||||
# To give this runner class its own baseline: download the `perf-results` artifact of the last
|
||||
# five or more nightly runs (`gh run download <run id> -n perf-results -D runs/<run id>`), run
|
||||
# `cargo xtask perf --update-baseline --from runs/<id>/results.json ... --allow-contended` (this
|
||||
# runner is never idle) and commit perf/baseline.json and docs/scorecard.md in a PR.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
@@ -40,13 +43,13 @@ jobs:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: perf-release
|
||||
|
||||
@@ -58,7 +61,8 @@ jobs:
|
||||
run: |
|
||||
args=()
|
||||
if [ "$QUICK" = "true" ]; then args+=(--quick); fi
|
||||
if [ "$UPDATE" = "true" ]; then args+=(--update-baseline); fi
|
||||
# This runner is never idle: a baseline from it is recorded labelled as contended.
|
||||
if [ "$UPDATE" = "true" ]; then args+=(--update-baseline --allow-contended); fi
|
||||
cargo xtask perf "${args[@]}"
|
||||
|
||||
- name: Job summary
|
||||
@@ -72,7 +76,7 @@ jobs:
|
||||
|
||||
- name: Upload results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: perf-results
|
||||
path: |
|
||||
@@ -83,7 +87,7 @@ jobs:
|
||||
|
||||
- name: Upload baseline
|
||||
if: always() && inputs.update_baseline
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: perf-baseline
|
||||
path: perf/baseline.json
|
||||
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
with:
|
||||
app-name: photocraft
|
||||
app-title: PhotoCraft
|
||||
craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
version: ${{ inputs.version }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
# Track shared CI improvements on main.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
timeout-minutes: 120
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
@@ -7,6 +7,8 @@ name: Windows ARM64
|
||||
# Nightly on main (dependency and runner-image drift shows up within a day), and on PRs that
|
||||
# change the Windows packaging itself.
|
||||
on:
|
||||
push:
|
||||
branches: [release]
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/windows-arm64.yml
|
||||
@@ -29,3 +31,5 @@ jobs:
|
||||
with:
|
||||
app-name: photocraft
|
||||
app-dir: PhotoCraft
|
||||
install-relative-path: Programs/ArtCraft/PhotoCraft
|
||||
install-scope: perUser
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
*~
|
||||
plan/
|
||||
/plan/
|
||||
/target
|
||||
target/
|
||||
/dist
|
||||
|
||||
@@ -19,7 +19,7 @@ PhotoCraft is an open-source, native, Photoshop-comparable image editor written
|
||||
| `docs/parity-checklist.md` | Generated list of every Photoshop menu item, live or missing |
|
||||
| `docs/scorecard.md` | Generated scorecard: performance budgets and numbers, corpus floors, per-area checklists (tools, files, UI, type, automation, reliability, distribution), settings that do nothing |
|
||||
| `crates/<name>/README.md` (where present) | Public API of that crate |
|
||||
| [photocraft-corpus](https://github.com/storytold/photocraft-corpus) + `docs/development.md` › Test corpora | Real-file test oracles (our Photoshop-authored PSDs); with psd-tools, ag-psd and PngSuite fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs` |
|
||||
| [photocraft-corpus](https://github.com/storytold/photocraft-corpus) + `docs/development.md` › Test corpora | Real-file test oracles (our Photoshop-authored PSDs and GIMP-authored XCFs); with psd-tools, ag-psd and PngSuite fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs` |
|
||||
|
||||
## 2. Workspace map
|
||||
|
||||
@@ -27,7 +27,7 @@ PhotoCraft is an open-source, native, Photoshop-comparable image editor written
|
||||
crates/
|
||||
geom cms color raster L0 foundation (geometry, ICC colour management, pixel formats + blend math, COW tiles)
|
||||
psd codecs L0 standalone format crates (no workspace deps; publishable)
|
||||
tablet L0 standalone pen tablet input (macOS AppKit, X11 XInput2); the one isolated unsafe crate
|
||||
tablet L0 standalone pen tablet input (macOS AppKit, X11 XInput2, Windows barrel button); the one isolated unsafe crate
|
||||
doc L1 document model (layers, masks, adjustments, effects, smart objects: pure data)
|
||||
ops paint algo text vector L2 history, brush engine, imaging algorithms, type engine, paths/shapes
|
||||
compose gpu format L3 CPU compositor (the oracle), wgpu compositor, .pcraft native format
|
||||
@@ -52,13 +52,13 @@ xtask/ cargo xtask layers | wasm | ci | stats | corpus | t
|
||||
People trust PhotoCraft with their work, and a crash loses it. A malformed file, a bad command or MCP param, a corrupt settings file, an odd keystroke or a full disk must produce an error the user or agent can act on, never a panic. Don't ship a feature by adding a panic path; fix a crash before building on top of it. The shared standard is `../craftrules/standards/never-crash.md`.
|
||||
|
||||
- **Non-test code never panics.** No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Return the crate's error type and propagate with `?`; use `ok_or(..)?`, `let .. else { return Err(..) }`, `if let`, or `unwrap_or*` where a fallback is truly correct (never one that silently corrupts a document). Unfinished features return an "unsupported" error. The only exception is a provably infallible literal: `#[allow(clippy::expect_used)]` plus `.expect("why it can't fail")`.
|
||||
- **No `unsafe`.** The workspace sets `unsafe_code = "forbid"`. The one exception is the isolated helper crate `photocraft-tablet` (`crates/tablet`): winit drops pen tablet data, and reading it on macOS needs an AppKit event monitor (Objective-C interop). Only its `src/macos.rs` allows `unsafe` (`unsafe_code = "deny"` crate-wide, every block has a `SAFETY:` comment, tested against real `NSEvent`s); its X11 path and all mapping code are safe. Don't add `unsafe` anywhere else.
|
||||
- **No `unsafe`.** The workspace sets `unsafe_code = "forbid"`. The one exception is the isolated helper crate `photocraft-tablet` (`crates/tablet`): winit drops pen tablet data, and reading it on macOS needs an AppKit event monitor (Objective-C interop) and on Windows a pointer message hook (`GetPointerPenInfo`). Only its `src/macos.rs` and `src/windows.rs` allow `unsafe` (`unsafe_code = "deny"` crate-wide, every block has a `SAFETY:` comment, tested against real `NSEvent`s and pointer messages); its X11 path and all mapping code are safe. Don't add `unsafe` anywhere else.
|
||||
- **Input-derived numbers are hostile.** Use `get()` rather than `[i]`/`[a..b]` for indices from files, params, selections or arithmetic on them; slice strings only at char boundaries; use `checked_*`/`saturating_*` for lengths, offsets and counts; guard division by zero and NaN/inf casts; cap allocations sized by input.
|
||||
- **Bound recursion** with depth limits or seen-sets (documents can be deep or cyclic).
|
||||
- **Don't cascade.** Handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)`) and treat thread joins as `Result`s.
|
||||
- **Last-resort guard.** The app shell must catch an escaped panic around command dispatch and file import/export, reports it as an error and keeps the document. It's a safety net, not a licence to panic. Keep `panic = "unwind"`.
|
||||
- **Prove it.** Every crash fix comes with a small synthetic regression test that panicked before the fix.
|
||||
- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic`/indexing in tests only. Clean crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it.
|
||||
- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic` in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`.
|
||||
|
||||
1. **Everything is a command.** New user-visible behaviour = a command in the engine (`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path, shortcut, params doc, `enabled` and `run`, plus tests. The UI, CLI, control channel and MCP all dispatch commands by id. Use the **exact id from `crates/ui-egui/src/menu_catalog.rs`** and the menu item goes live automatically. Only pure view/window state (zoom, panels, screen mode) belongs to the shell (`menus.rs` `UI_COMMANDS`).
|
||||
2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `photocraft-cms` (`Transform`, `transform::cached`). Test at several depths.
|
||||
@@ -70,6 +70,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
|
||||
8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log.
|
||||
|
||||
9. **Never panic on input** (see *Never crash* above). A command's `run` closure and anything it calls must return `Err`, never panic, for *any* params or document state: validate params, check bounds before indexing or dividing, and reject absurd sizes before allocating. The `panic_hunt` integration test fuzzes every command with adversarial params and must stay green.
|
||||
10. **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
|
||||
## 4. Picking work
|
||||
|
||||
@@ -107,7 +108,7 @@ cargo xtask test-corpus # if you touched psd, io, codecs, compose, gpu, text
|
||||
|
||||
While iterating, run less and keep the full commands above as the final gate: `cargo test -p <crate> --lib --tests` skips the examples and doctests plain `cargo test` builds every time (ui-egui has 11 examples), and `cargo test -p <crate> --test <file>` runs one integration-test file. `cargo nextest run` runs tests in parallel across binaries; see `docs/development.md` › Faster test loops.
|
||||
|
||||
**Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora.
|
||||
**Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop- and GIMP-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora.
|
||||
|
||||
Commands must **never panic** on bad input (Rule 9): every `run` closure and the code it calls returns `Err`, not a panic, for any params or document state. New commands come with a graceful-failure test (empty/out-of-range/wrong-type params → `Err`, not a crash).
|
||||
|
||||
@@ -157,3 +158,8 @@ If the field has a PSD equivalent, map it in `crates/io` too, and keep unknown P
|
||||
GitHub profiles). Never hand-edit `contributors.json`.
|
||||
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
|
||||
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
|
||||
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
@@ -23,26 +23,39 @@ next to them.
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | Czech UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | Russian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Swedish UI translations | @kler, @davvarn and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish UI translations | @Janiz-zzz, @metuuu and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/da.tsv` | Danish UI translations | @pechnikov2026-star and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål UI translations | @nikolainyegaard, @Bolla76 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
|
||||
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (114 files; `star-filled.svg` is `star.svg` with a solid fill, `rotate-ccw.svg` is `rotate-cw.svg` mirrored) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/type-mask.svg`, `assets/icons/type-mask-vertical.svg` | Horizontal and Vertical Type Mask tool glyphs: a T drawn as marching ants (the vertical one beside a downward arrow), on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/text-warp.svg` | Create Warped Text glyph (Type tool options bar): a T above a bowed arc, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/align-edge-*.svg`, `assets/icons/distribute-*.svg` | Move tool options-bar glyphs: Align (six edges/centres) and Distribute (edges, centres, spacing), a guide line or edge lines with bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/ellipse-dashed.svg` | Elliptical Marquee tool glyph: a dashed horizontal ellipse, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/gradient.svg` | Gradient tool glyph: a rounded rectangle filled with a left-to-right linear ramp, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush` plus a dashed selection arc around the bristles | Lucide Icons and Contributors; arc by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush`, scaled to 70%, inside a dashed upright rounded "C" selection | Lucide Icons and Contributors; selection by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/pen-freeform.svg`, `assets/icons/pen-curvature.svg` | Freeform Pen and Curvature Pen tool glyphs: Lucide `pen-tool` scaled down, plus a freehand squiggle or a curve through two points | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
@@ -57,6 +70,7 @@ next to them.
|
||||
| `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | <https://ethanschoonover.com/solarized/> | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) |
|
||||
| `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, <https://invent.kde.org/plasma/breeze> (its colour schemes are LGPL-2.0-or-later) | Original work |
|
||||
| `crates/ui-egui/src/theme.rs` (Soft Dark and Soft Light themes) | Original colour values and radii for two low-contrast themes on PhotoCraft's Studio layout; no third-party palette, file or code is used | PhotoCraft contributors | Original | Original work |
|
||||
| `crates/algo/data/libfacedetection.bin` (face detection weights, read by `crates/algo/src/faces.rs`, whose network code is a port of the library's) | libfacedetection CNN (YuNet design) weights and inference code, weights converted to half precision | Shiqi Yu | [ShiqiYu/libfacedetection](https://github.com/ShiqiYu/libfacedetection) (`src/facedetectcnn-data.cpp`, `facedetectcnn.cpp`, `facedetectcnn-model.cpp`) | BSD-3-Clause, [`LICENSE-libfacedetection.txt`](crates/algo/data/LICENSE-libfacedetection.txt) |
|
||||
|
||||
### Optional build input: craft-fonts (not files in this repo)
|
||||
|
||||
@@ -82,6 +96,8 @@ The other built-in ICC profiles and the generated LUT looks are produced by code
|
||||
| `docs/brand/` (all files) | ArtCraft name, wordmark and mark | ArtCraft Team | getartcraft.com | Not open source; trademarks of the ArtCraft Team, [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) |
|
||||
| `docs/images/photocraft-*.jpg` | PhotoCraft screenshots | PhotoCraft contributors (UI) | Rendered offscreen with the `snapshot` example | MIT OR Apache-2.0 (UI); the artwork in each is public domain, listed below |
|
||||
| `docs/images/preferences-apply-*.png` | Preferences before and after adding Apply (no artwork) | PhotoCraft contributors | PhotoCraft control-channel capture and offscreen `snapshot` example | MIT OR Apache-2.0 |
|
||||
| `docs/images/gradient-overlay-method-*.png` | Gradient Overlay Method selector, before and after (synthetic gradient) | @oRE-o | Rendered offscreen with the `snapshot` example; no external artwork | MIT OR Apache-2.0 |
|
||||
| `docs/images/cpu-pixel-alignment/*.png` | CPU canvas pixel alignment, before and after #8321 | PhotoCraft contributors | Original synthetic noise rendered with the offscreen `snapshot` example; see the adjacent README | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` |
|
||||
|
||||
Artwork shown in the screenshots (all public domain, via Wikimedia Commons; details in
|
||||
[`docs/images/SOURCES.md`](docs/images/SOURCES.md)):
|
||||
@@ -107,12 +123,14 @@ next to the files:
|
||||
|
||||
| Path (fetched) | Title | Author | Source | License |
|
||||
|---|---|---|---|---|
|
||||
| `corpus/photoshop/` (256 PSDs) | Photoshop oracle corpus: smart filters, layer-style effects, type, adjustments in every mode and depth | PhotoCraft contributors (authored with Adobe Photoshop 2026 by a script) | [https://github.com/storytold/photocraft-corpus](https://github.com/storytold/photocraft-corpus) (`photoshop/`, with its generator and README) | MIT OR Apache-2.0 |
|
||||
| `corpus/photoshop/` (258 PSDs) | Photoshop oracle corpus: smart filters, layer-style effects, type, adjustments in every mode and depth | PhotoCraft contributors (authored with Adobe Photoshop 2026 by a script) | [https://github.com/storytold/photocraft-corpus](https://github.com/storytold/photocraft-corpus) (`photoshop/`, with its generator and README) | MIT OR Apache-2.0 |
|
||||
| `corpus/gimp/` (28 files, 251 KB) | GIMP XCF oracles: 40×30 procedural layers written by GIMP 3.2.6 through the corpus generator `tools/gimp-xcf/xcf_fixtures.py`, each with GIMP's merged rendering as a PNG | PhotoCraft contributors (authored with GIMP 3.2.6 by a script) | [https://github.com/storytold/photocraft-corpus](https://github.com/storytold/photocraft-corpus) (`gimp/`, with its generator and README) | MIT OR Apache-2.0 |
|
||||
| `corpus/psd-tools/` (309 files) | psd-tools test set | Kota Yamaguchi and contributors | [psd-tools `tests/psd_files`](https://github.com/psd-tools/psd-tools/tree/main/tests/psd_files) | MIT, Copyright (c) 2019 Kota Yamaguchi |
|
||||
| `corpus/psd/` (170 files) | Small selection of the psd-tools and ag-psd test files | Kota Yamaguchi; Agamnentzar | psd-tools (above) and [ag-psd `test/`](https://github.com/Agamnentzar/ag-psd/tree/master/test) | MIT (both) |
|
||||
| `corpus/heif/` (9 files, 0.1 MB) | HEIC/HEIF test files: `heic-rs/` checkerboards, RGB strips and a grid-tiled photo with EXIF and XMP (synthetic pixels encoded by macOS `sips`, each `.ref.png` Apple's decode); `pillow-heif/` the 10-bit RGBA `RGBA_10__29x100.heif` and its source `RGBA_16__29x100.png` | Thomas Braun (heic-rs); Pillow-Heif contributors | [heic-rs `tests/fixtures`](https://github.com/tbraun96/heic-rs/tree/main/tests/fixtures), [pillow-heif `tests/images`](https://github.com/bigcat88/pillow_heif/tree/master/tests/images) | MIT OR Apache-2.0 (heic-rs); BSD-3-Clause (pillow-heif) |
|
||||
| `corpus/exr/` (5 files, 2.3 MB) | The deep OpenEXR test images `11`, `42`, `64`, `multivariate` and `objectid.deep.exr` | Contributors to the OpenEXR Project | [openexr `src/test/bin/test_images`](https://github.com/AcademySoftwareFoundation/openexr/tree/main/src/test/bin/test_images) | BSD-3-Clause |
|
||||
| `corpus/affinity/` (60 files) | Public Affinity documents and PNG references: `vector-art/` (9 documents), `afdesignload/` (9), `jac21/` (2), `asset-store-template/` (1), and `affinity-samples/` (18 CC0 documents plus exported references) | samuel-etver; Nick Beeuwsaert; Jeremy Cantu; DAIKI (eviltwo); satoshoe-dev | [vector-art `simple/`](https://github.com/samuel-etver/vector-art/tree/255f8add3c8f0740196e22bd59502b811b532f0b/simple), [AFDesignLoad `testDesigns/`](https://github.com/NickBeeuwsaert/AFDesignLoad/tree/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns), [Jac21/Branding `Logos/JC/DesignerFiles/Affinity`](https://github.com/Jac21/Branding/tree/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity), [AssetStoreTemplate `AssetStoreTemplate/`](https://github.com/eviltwo/AssetStoreTemplate/tree/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate), [affinity-samples](https://github.com/satoshoe-dev/affinity-samples/tree/96aca6bd86bbe7a677f1cf0630bd832d23943be8) | CC0-1.0 (vector-art and affinity-samples); MIT, Copyright (c) 2015 Nick Beeuwsaert; MIT, Copyright (c) 2018 Jeremy Cantu; MIT, Copyright (c) 2024 DAIKI |
|
||||
| `corpus/atn/` (16 files, 0.9 MB) | Photoshop Actions sets, one folder per repository: `sbaril/` (Frequency Separation, Firefly, Dimension, Harmonize, Photo, Quick Object Extraction, Generative Upscale), `bjango/` (Bjango Actions, Adjustment Actions, Scale Actions), `bkwld/` (Save layers for web), `atntools/` (test.atn), `trimmer/` (Trimmer), `alpha-utility/` (AlphaUtilityAdditions), `gif-creator/` (BannerActions) | Stéphane Baril; Bjango and Marc Edwards; BKWLD; Maurits Rijk; damsmcfly; UCLA Game Lab; overbyte | [sbaril/Photoshop-Scripts](https://github.com/sbaril/Photoshop-Scripts), [bjango/Bjango-Actions](https://github.com/bjango/Bjango-Actions), [BKWLD/photoshop-actions](https://github.com/BKWLD/photoshop-actions), [mrijk/atntools](https://github.com/mrijk/atntools), [damsmcfly/photoshop-cleaner-trimmer](https://github.com/damsmcfly/photoshop-cleaner-trimmer), [uclagamelab/AlphaUtilityAdditions](https://github.com/uclagamelab/AlphaUtilityAdditions), [overbyte/photoshop-gif-creator-script](https://github.com/overbyte/photoshop-gif-creator-script), pinned in [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | MIT (sbaril, BKWLD, atntools, gif-creator), BSD (bjango, per `Help/License.md`), BSD-2-Clause (alpha-utility), Unlicense (trimmer); each licence file sits next to its files |
|
||||
| `corpus/pngsuite/` | PngSuite | Willem van Schaik | <http://www.schaik.com/pngsuite/> | Public domain |
|
||||
| `corpus/pixls/` (11 files) | Real camera raws, one per decode path: Canon PowerShot SX50 HS (CR2 and its DNG conversion), Nikon D3 uncompressed NEF and Z6 paired 12/14-bit lossy and packed NEFs, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2, Olympus E-1 GRBG ORF, plus the E-5 packed ORF as the documented known-unsupported case. Per file (each CC0, per its database entry): [IMG_4059.CR2](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/IMG_4059.CR2), [CRW_4061.DNG](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/CRW_4061.DNG), [JD1_8203.NEF](https://raw.pixls.us/data/Nikon/D3/JD1_8203.NEF), [DSC00009.ARW](https://raw.pixls.us/data/Sony/DSC-RX0/DSC00009.ARW), [P1000475.RW2](https://raw.pixls.us/data/Panasonic/DC-G9/P1000475.RW2), [E_1__C106743_gredos.ORF](https://raw.pixls.us/data/Olympus/E-1/E_1__C106743_gredos.ORF), [_7061961_copy.ORF](https://raw.pixls.us/data/Olympus/E-5/_7061961_copy.ORF), [DSC_0750.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0750.NEF), [DSC_0751.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0751.NEF), [DSC_0753.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0753.NEF), [DSC_0754.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0754.NEF) | The photographers of the pixls.us raw samples database | [raw.pixls.us](https://raw.pixls.us) `data/`, fetched per [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | CC0 / public domain, per file as linked |
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.0"
|
||||
version = "0.17.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
# internal
|
||||
photocraft-geom = { path = "crates/geom" }
|
||||
photocraft-color = { path = "crates/color" }
|
||||
@@ -36,47 +36,66 @@ photocraft-engine = { path = "crates/engine" }
|
||||
photocraft-ui-egui = { path = "crates/ui-egui" }
|
||||
photocraft-testkit = { path = "crates/testkit" }
|
||||
photocraft-tablet = { path = "crates/tablet" }
|
||||
photocraft-ipp = { path = "crates/ipp" }
|
||||
|
||||
# external
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3d37da389a3618ab9b76109da11416e9ca4ea719" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
arc-swap = "1"
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
|
||||
image = { version = "0.25", default-features = false }
|
||||
# Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg.
|
||||
zune-core = "0.5"
|
||||
zune-jpeg = "0.5"
|
||||
proptest = "1"
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
# Without `default_fonts`, which embeds egui's fonts uncompressed: ui-egui ships them deflated
|
||||
# (egui_fonts.rs; the web build's size gate).
|
||||
egui = { version = "0.36", default-features = false }
|
||||
egui_kittest = "0.36"
|
||||
egui = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
rustc-hash = "2.1.3"
|
||||
criterion = { version = "0.8", default-features = false }
|
||||
getrandom = "0.3"
|
||||
# Monotonic clock on native and wasm (screenshot deadlines: a wall clock can jump).
|
||||
web-time = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
too_many_arguments = "deny"
|
||||
wildcard_imports = "deny"
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
|
||||
# Dependencies carry no debug info: their frames in a backtrace lose file:line, and the target dir
|
||||
# and link times shrink. The test profile inherits both settings.
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
debug = false
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
# Line tables keep file:line in panic backtraces but drop variable info, which roughly halves link
|
||||
# time and PDB size for the ~260 test binaries (#2204). CI sets the same through
|
||||
# CARGO_PROFILE_DEV_DEBUG (and no debuginfo at all for the Windows tests). To inspect locals in a
|
||||
# debugger, build with CARGO_PROFILE_DEV_DEBUG=true.
|
||||
# time and PDB size for the test binaries (#2204). CI's Windows legs build with no debuginfo at all
|
||||
# (CARGO_PROFILE_DEV_DEBUG=0). To inspect locals in a debugger, build with
|
||||
# CARGO_PROFILE_DEV_DEBUG=true.
|
||||
debug = "line-tables-only"
|
||||
|
||||
# Test builds compile ui-egui without optimization: its library and unit tests were the biggest
|
||||
@@ -136,6 +155,14 @@ opt-level = "z"
|
||||
[profile.wasm-release.package.naga]
|
||||
opt-level = "z"
|
||||
|
||||
# The browser UI toolkit favors size to stay within the WebAssembly upload budget.
|
||||
[profile.wasm-release.package.egui]
|
||||
opt-level = "z"
|
||||
[profile.wasm-release.package.epaint]
|
||||
opt-level = "z"
|
||||
[profile.wasm-release.package.eframe]
|
||||
opt-level = "z"
|
||||
|
||||
# Pixel processing keeps its speed-oriented optimization level, with two exceptions.
|
||||
# Colour-management transforms are built once and cached (`transform::cached`), so "z" costs
|
||||
# little runtime. The browser app composites per frame on the GPU (`crates/gpu`, WebGPU/WebGL2),
|
||||
@@ -157,3 +184,20 @@ opt-level = "z"
|
||||
[profile.wasm-release.package.photocraft-paint]
|
||||
opt-level = 3
|
||||
|
||||
# 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 = "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" }
|
||||
|
||||
@@ -25,8 +25,8 @@ RUN set -eu; \
|
||||
asset="trunk-${arch}-unknown-linux-musl.tar.gz"; \
|
||||
url="https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}"; \
|
||||
cd /tmp; \
|
||||
curl -fsSL --retry 3 -A Photocraft-dev "$url/$asset" -o "$asset"; \
|
||||
curl -fsSL --retry 3 -A Photocraft-dev "$url/$asset.sha256" -o "$asset.sha256"; \
|
||||
curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "$url/$asset" -o "$asset"; \
|
||||
curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "$url/$asset.sha256" -o "$asset.sha256"; \
|
||||
printf '%s %s\n' "$(cat "$asset.sha256")" "$asset" | sha256sum -c -; \
|
||||
tar -xzf "$asset" -C /usr/local/bin trunk; \
|
||||
rm "$asset" "$asset.sha256"; \
|
||||
|
||||
@@ -16,8 +16,26 @@ Inter font (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/
|
||||
JetBrains Mono font (assets/fonts/JetBrainsMono-Regular.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt.
|
||||
Lucide icons (assets/icons/*.svg, except slice-knife.svg) — ISC; icons derived from Feather also MIT. See assets/icons/LICENSE-lucide.txt.
|
||||
SCOWL English word list (assets/dict/en_US-scowl-50.txt.gz) — SCOWL license. See assets/dict/LICENSE-SCOWL.txt.
|
||||
libfacedetection face detection weights and network (crates/algo/data/libfacedetection.bin, crates/algo/src/faces/cnn.rs) — BSD-3-Clause, Copyright (c) 2015-2019, Shiqi Yu, all rights reserved. See crates/algo/data/LICENSE-libfacedetection.txt.
|
||||
|
||||
Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed in
|
||||
https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDPGothic, Shippori Mincho and
|
||||
BIZ UDMincho; not the web build), under the SIL Open Font License 1.1. Their licence texts
|
||||
ship with the package as OFL-<family>.txt.
|
||||
|
||||
The egui-icons font subset is embedded from epaint_default_fonts by crates/ui-egui/build.rs
|
||||
and registered in the native and web fallback stacks by crates/ui-egui/src/egui_fonts.rs.
|
||||
It is a subset of emoji-icon-font by John Slegers; the same upstream MIT license applies.
|
||||
Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
|
||||
Original: https://github.com/jslegers/emoji-icon-font
|
||||
The following notice is reproduced verbatim from emoji-icon-font-mit-license.txt:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png" width="128" height="128" alt="PhotoCraft icon: an engraved nine-tailed fox on a blue tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">PhotoCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
@@ -20,6 +24,9 @@
|
||||
<img alt="macOS · Windows · Linux · FreeBSD · Web" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-native-2f7bf5?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-3a3a3a?style=flat-square">
|
||||
<img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-d69e2e?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_photocraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/photocraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -178,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🧰 67 tools</h4>
|
||||
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
<h4>🧰 68 tools</h4>
|
||||
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🖌️ A real brush engine</h4>
|
||||
@@ -199,7 +206,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🗂️ Formats</h4>
|
||||
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, <a href="docs/kra.md">Krita .kra (read, with paint layers, groups, blend modes and transparency masks)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and FITS (astronomy images: 8/16-bit and 32-bit float, gray or RGB, header kept), and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
|
||||
PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, <a href="docs/ora.md">OpenRaster (read and write, with layers, groups and blend modes, for Krita, MyPaint and GIMP)</a>, <a href="docs/xcf.md">GIMP XCF (read, with layers, groups, masks, blend modes, channels and the selection)</a>, <a href="docs/kra.md">Krita .kra (read, with paint layers, groups, blend modes and transparency masks)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and FITS (astronomy images: 8/16-bit and 32-bit float, gray or RGB, header kept), and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🪄 The everyday essentials</h4>
|
||||
@@ -214,7 +221,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
|
||||
PhotoCraft's PSD support is a standalone crate written from Adobe's public specification and tested against a corpus of real-world files.
|
||||
|
||||
- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/corpus.rs`).
|
||||
- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/it/corpus.rs`).
|
||||
- **Pixels that match:** a composite oracle compares our render with Photoshop's own merged image, covering gradient interpolation (Classic, Perceptual and Linear), layer effects, shape strokes, clipping and fill opacity.
|
||||
- **Large documents:** PSB, 16 and 32-bit files, and CMYK and Lab documents open natively.
|
||||
|
||||
@@ -275,8 +282,12 @@ flatpak install --user photocraft-<version>-linux-x86_64.flatpak # or -linux-a
|
||||
flatpak run ai.storyteller.photocraft
|
||||
```
|
||||
|
||||
The Flatpak prints through the host's CUPS socket (File › Print talks IPP to it directly, no `lp` needed); without CUPS, or without a printer, File › Print opens the system print dialog through the print portal. See [printing](docs/printing.md).
|
||||
|
||||
The AppImage needs no install: the first run registers its launcher icon and menu entry in `~/.local/share` so the dock shows PhotoCraft's icon on Wayland. Set `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` to skip that, and see [`docs/releasing.md`](docs/releasing.md) › Linux to undo it.
|
||||
|
||||
To use the bundled CLI, run `./photocraft-<version>-linux-x86_64.AppImage --cli --help`, or `--cli mcp` to start the MCP server on stdio. CLI launches skip desktop integration. A symlink named `photocraft-cli` also selects the CLI; see [`docs/development.md`](docs/development.md#headless-cli).
|
||||
|
||||
On a Wayland session, files dropped on the window don't open yet: winit 0.30, the windowing library under egui, has no Wayland drag and drop (#386). Use File › Open, or copy the image in your file manager and paste it with Ctrl+V. To drag and drop, start PhotoCraft under XWayland: `WAYLAND_DISPLAY= photocraft`, `WAYLAND_DISPLAY= ./photocraft-<version>-linux-x86_64.AppImage`, or `flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft`. On Wayland, PhotoCraft shows the command for your install in a notice until you dismiss it. Preferences › Performance › Linux display server = X11 does the same on every launch. With a fractional display scale (125%, 150%, 175%) an XWayland window is drawn at a lower resolution and enlarged by the compositor, so the interface is blurred there; native Wayland stays sharp (#1072).
|
||||
|
||||
On macOS, the command-line tool comes as `photocraft-cli-<version>-macos-universal.zip`. The binary is signed with the same Developer ID as the app and notarized by Apple. A bare binary can't carry a stapled notarization ticket the way the DMG does, so the first time you run it macOS checks the notarization online. You can confirm it yourself:
|
||||
@@ -300,6 +311,19 @@ Maintainers: [`docs/releasing.md`](docs/releasing.md) explains how releases are
|
||||
> [!IMPORTANT]
|
||||
> **Status:** PhotoCraft is in early alpha, and we want to be straight about where it stands: much of Photoshop's feature surface exists in some form, but **it is not yet a Photoshop replacement for daily professional work**. The biggest gaps are AI/generative features, 15 missing tools, depth in typography and pro workflows, and plug-in compatibility. Every Photoshop menu item is wired to a command ([`docs/parity-checklist.md`](docs/parity-checklist.md)), but that measures wiring, not behaviour. The honest, dimension-by-dimension picture and where we're going next are in the [roadmap](ROADMAP.md) and [parity assessment](docs/target-app-parity.md). Expect rough edges, and please file issues (include your OS, document size, layer count and a screenshot). You can also tell us what broke on [Discord](https://discord.gg/artcraft).
|
||||
|
||||
## Community packages
|
||||
|
||||
These installers are maintained by community members, not by the PhotoCraft team.
|
||||
|
||||
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the Linux release as `media-gfx/photocraft-bin`:
|
||||
|
||||
```sh
|
||||
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
|
||||
emaint sync -r snakebyte
|
||||
echo 'media-gfx/photocraft-bin ~amd64' >> /etc/portage/package.accept_keywords/photocraft
|
||||
emerge --ask media-gfx/photocraft-bin
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Developer, architecture, automation, format, and security documentation is maintained in the [PhotoCraft documentation book](book/).
|
||||
@@ -321,7 +345,7 @@ sha256-verified. Fetch them with `cargo xtask corpus --all` and run the tests wi
|
||||
|
||||
**New to PhotoCraft?** Download it from the [PhotoCraft page on getartcraft.com](https://getartcraft.com/apps/photocraft). That's the easiest way to install it.
|
||||
|
||||
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/photocraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/photocraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/photocraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/photocraft/releases) have earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
### Windows
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~30 points (ready for real work ~45% → ~75%, with reliable PSD) and ~1,100–1,800 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (Object Finder retains large enclosed foregrounds (#6548); Russian catalog covers every dynamic label; previously minor: oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
PhotoCraft's one-page summary of how close it is to Adobe Photoshop 2026 (27.11.0, measured from
|
||||
the installed app on 2026-10-10) at version 0.6.0. Detail: [target-app parity](docs/target-app-parity.md)
|
||||
@@ -104,7 +104,7 @@ because engine messages are still English. Detail: [localization-parity](docs/lo
|
||||
| Korean | `ko` | 100% | partial |
|
||||
| Vietnamese | `vi` | 0% | none |
|
||||
|
||||
Also shipped: Traditional Chinese, Russian, Ukrainian, Czech, Polish, Greek, Dutch, Italian (8).
|
||||
Also shipped: Traditional Chinese, Russian (every dynamic label, [notes](docs/localization-ru.md)), Ukrainian, Czech, Polish, Greek, Dutch, Italian (8).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -122,6 +122,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
| Date | Entry |
|
||||
|---|---|
|
||||
| 2026-10-17 | Object Finder classifies background by boundary coverage, retaining large enclosed foregrounds and rejecting surrounding backdrop (#6548); learned segmentation remains open (#2788) |
|
||||
| 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized to the craftrules standard (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. |
|
||||
| 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus |
|
||||
| 2026-10-08 | 0.5.0. Affinity import; Magnetic Lasso, Pattern Stamp, Mixer Brush, Pencil, Patch, Vertical Type on the toolbar |
|
||||
@@ -135,7 +136,9 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) |
|
||||
| 2026-10-17 | minor | Object Finder retains large enclosed foregrounds (#6548) |
|
||||
| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/it/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) |
|
||||
| 2026-10-15 | minor | Russian catalog covers every dynamic UI label the other catalogs translate |
|
||||
| 2026-10-11 | minor | Toolbox count 56 of 68 (12 missing) with the Convert Point tool (#3204) |
|
||||
| 2026-10-10 | minor | Readiness by audience with hours per tier |
|
||||
| 2026-10-10 | minor | Mainstream-practitioner and essentials-user numbers added |
|
||||
|
||||
@@ -28,9 +28,19 @@ photocraft-engine = { workspace = true }
|
||||
photocraft-io = { workspace = true }
|
||||
photocraft-format = { path = "../../crates/format" }
|
||||
photocraft-codecs = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Synthetic camera raws (#7789).
|
||||
photocraft-raw = { workspace = true, features = ["testgen"] }
|
||||
# Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in
|
||||
# the binary.
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for photocraft-cli.exe; build.rs only uses it when targeting Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
@@ -12,6 +12,14 @@ fn main() -> std::io::Result<()> {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return Ok(());
|
||||
}
|
||||
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which
|
||||
// stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe
|
||||
// from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use;
|
||||
// the print command checks for it first and reports an error instead.
|
||||
if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
|
||||
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll");
|
||||
println!("cargo:rustc-link-arg-bins=delayimp.lib");
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
// FileVersion / ProductVersion strings and the numeric FILEVERSION / PRODUCTVERSION are left
|
||||
// to `WindowsResource::new`, which reads the Cargo package version. A pre-release such as
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Writes photocraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `photocraft-cli.1` and one per subcommand, such as
|
||||
//! `photocraft-cli-convert.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p photocraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = photocraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "photocraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`photocraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(photocraft_cli::command(), dir)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Why an actions file can't be played.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ActionsError {
|
||||
#[error("actions JSON: {0}")]
|
||||
Json(#[source] serde_json::Error),
|
||||
/// The steps don't parse ([`photocraft_engine::automate_cmds::parse_action`]).
|
||||
#[error(transparent)]
|
||||
Steps(#[from] photocraft_engine::EngineError),
|
||||
#[error("--action picks an action from an Actions set ({{\"actions\": [{{\"name\", \"steps\"}}…]}}), but this file holds one action's steps")]
|
||||
NotASet,
|
||||
#[error("Actions set: {0}")]
|
||||
Set(#[source] serde_json::Error),
|
||||
#[error("no action named `{name}` in the set (it holds {})", quoted(names))]
|
||||
NoSuchAction { name: String, names: Vec<String> },
|
||||
#[error("the Actions set holds {} actions: pick one with --action <name> ({})", names.len(), quoted(names))]
|
||||
PickOne { names: Vec<String> },
|
||||
#[error("{}: {source}", path.display())]
|
||||
Read { path: PathBuf, source: std::io::Error },
|
||||
#[error("{}: {source}", path.display())]
|
||||
Utf8 { path: PathBuf, source: std::string::FromUtf8Error },
|
||||
/// A Photoshop Actions file that doesn't import ([`photocraft_engine::atn_cmds::import`]).
|
||||
#[error("{}: {message}", path.display())]
|
||||
Atn { path: PathBuf, message: String },
|
||||
#[error("no action named `{name}` in the set `{set}` (it holds {})", quoted(names))]
|
||||
NoSuchAtnAction { name: String, set: String, names: Vec<String> },
|
||||
#[error("{}: the set holds no actions", path.display())]
|
||||
EmptyAtn { path: PathBuf },
|
||||
#[error("the set `{set}` holds {} actions: pick one with --action <name> ({})", names.len(), quoted(names))]
|
||||
PickOneAtn { set: String, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// `` `a`, `b` ``: the action names an error lists.
|
||||
fn quoted(names: &[String]) -> String {
|
||||
names.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
fn names(actions: &[Action]) -> Vec<String> {
|
||||
actions.iter().map(|a| a.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Parse an actions file: the steps of a recorded action or a droplet (`[id, params]` pairs,
|
||||
/// `{"command": id, "params": {…}}` objects or bare ids; `"id"` is accepted for `"command"`), as a
|
||||
/// list or wrapped in `{"actions": […]}`, `{"steps": […]}` or a droplet (#489).
|
||||
pub fn parse_actions(text: &str) -> Result<Vec<(String, Value)>, ActionsError> {
|
||||
let v: Value = serde_json::from_str(text).map_err(ActionsError::Json)?;
|
||||
steps_of(&v)
|
||||
}
|
||||
|
||||
fn steps_of(v: &Value) -> Result<Steps, ActionsError> {
|
||||
Ok(photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(v), "batch --actions")?)
|
||||
}
|
||||
|
||||
/// Engine commands to run in order: `(id, params)`.
|
||||
pub type Steps = Vec<(String, Value)>;
|
||||
|
||||
/// The steps `batch` plays on each file, and the actions they can call. An Actions set (the
|
||||
/// Actions panel's `actions.json`: `{"actions": [{"name", "steps"}…]}`, or the bare list) plays
|
||||
/// the action `name` picks (optional when the set holds one) with the whole set loaded, as
|
||||
/// Photoshop's Batch does; anything else is one action's steps ([`parse_actions`]) (#2786).
|
||||
pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>), ActionsError> {
|
||||
let v: Value = serde_json::from_str(text).map_err(ActionsError::Json)?;
|
||||
let list = v.get("actions").unwrap_or(&v);
|
||||
let is_set = list.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|x| x.get("name").is_some_and(Value::is_string)));
|
||||
if !is_set {
|
||||
if name.is_some() {
|
||||
return Err(ActionsError::NotASet);
|
||||
}
|
||||
return Ok((steps_of(&v)?, Vec::new()));
|
||||
}
|
||||
let set: Vec<Action> = serde_json::from_value(list.clone()).map_err(ActionsError::Set)?;
|
||||
let action = match (name, set.as_slice()) {
|
||||
(Some(n), _) => set.iter().find(|a| a.name == n).ok_or_else(|| ActionsError::NoSuchAction { name: n.to_owned(), names: names(&set) })?,
|
||||
(None, [only]) => only,
|
||||
(None, _) => return Err(ActionsError::PickOne { names: names(&set) }),
|
||||
};
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, set))
|
||||
}
|
||||
|
||||
/// [`load_actions`] for a file on disk: a Photoshop Actions file (`.atn`, by extension or by
|
||||
/// its version word) is converted first; the played action's steps with no PhotoCraft
|
||||
/// equivalent come back as warnings (they fail at playback, as in Photoshop when a step can't run).
|
||||
pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec<Action>, Vec<String>), ActionsError> {
|
||||
let bytes = std::fs::read(path).map_err(|source| ActionsError::Read { path: path.to_path_buf(), source })?;
|
||||
let is_atn = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || bytes.starts_with(&[0, 0, 0, 16]);
|
||||
if !is_atn {
|
||||
let text = String::from_utf8(bytes).map_err(|source| ActionsError::Utf8 { path: path.to_path_buf(), source })?;
|
||||
let (steps, set) = load_actions(&text, name)?;
|
||||
return Ok((steps, set, Vec::new()));
|
||||
}
|
||||
let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?;
|
||||
let action = match (name, imp.actions.as_slice()) {
|
||||
(Some(n), _) => imp.actions.iter().find(|a| a.name == n).ok_or_else(|| ActionsError::NoSuchAtnAction {
|
||||
name: n.to_owned(),
|
||||
set: imp.set.clone(),
|
||||
names: names(&imp.actions),
|
||||
})?,
|
||||
(None, [only]) => only,
|
||||
(None, []) => return Err(ActionsError::EmptyAtn { path: path.to_path_buf() }),
|
||||
(None, _) => return Err(ActionsError::PickOneAtn { set: imp.set.clone(), names: names(&imp.actions) }),
|
||||
};
|
||||
let warnings = imp
|
||||
.unsupported
|
||||
.iter()
|
||||
.filter(|u| u.action == action.name)
|
||||
.map(|u| format!("`{}` step {}: Photoshop's \"{}\" ({}) has no PhotoCraft equivalent yet", u.action, u.step + 1, u.name, u.event))
|
||||
.chain(imp.warnings.iter().cloned())
|
||||
.collect();
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, imp.actions, warnings))
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! The command line, as clap types. Values are parsed into their types here, so a bad one is a
|
||||
//! usage error naming its flag (exit 2) and the handlers never see it (#7071). A flag a
|
||||
//! subcommand doesn't take is a usage error too, so a typo such as `--fromat` can't be silently
|
||||
//! ignored (#423), and so is a repeated one: `--quality 80 --quality 60` is more likely a mistake
|
||||
//! than a choice. A value starting with `-` is written `--out=-image.png` (or `./-image.png`), so a
|
||||
//! value flag never takes the next flag as its value; negative numbers are kept where they mean
|
||||
//! something.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::error::ErrorKind;
|
||||
use clap::parser::ValueSource;
|
||||
use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
|
||||
use photocraft_automation::args::{AutomationArgs, ControlArgs, blank_env_is_unset, conflict, control_port, name_env_vars};
|
||||
use photocraft_codecs::{JpegFormat, TiffCompression};
|
||||
use photocraft_io::{DdsCompression, DpxBits, TgaBits};
|
||||
use serde_json::Value;
|
||||
|
||||
/// photocraft-cli: headless PhotoCraft
|
||||
#[derive(Parser)]
|
||||
#[command(name = "photocraft-cli", version = photocraft_engine::build_info::long_version_static(), arg_required_else_help = true)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub(crate) enum Command {
|
||||
Convert(ConvertArgs),
|
||||
Info(InfoArgs),
|
||||
Run(RunArgs),
|
||||
Batch(BatchArgs),
|
||||
Droplet(DropletArgs),
|
||||
Commands(CommandsArgs),
|
||||
Mcp(McpArgs),
|
||||
Serve(ServeArgs),
|
||||
}
|
||||
|
||||
// How an image is written: shared by `convert`, `run` and `batch`.
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ExportArgs {
|
||||
/// Output format, overriding the output's extension (png, jpg, tif, webp, …)
|
||||
#[arg(long, value_name = "EXT")]
|
||||
pub(crate) format: Option<String>,
|
||||
/// JPEG or WebP quality, 1-100. A WebP written with a quality is lossy, without one lossless
|
||||
// allow_negative_numbers makes `--quality -1` an out-of-range value rather than an unexpected argument.
|
||||
#[arg(long, value_name = "1-100", value_parser = clap::value_parser!(u8).range(1..=100), allow_negative_numbers = true)]
|
||||
pub(crate) quality: Option<u8>,
|
||||
/// Keep the layers in TIFF output (Photoshop layer data); TIFF output is flat without it
|
||||
#[arg(long)]
|
||||
pub(crate) tiff_layers: bool,
|
||||
/// Compress TIFF output: none (the default), lzw or zip
|
||||
#[arg(long, value_name = "none|lzw|zip", value_parser = tiff_compression)]
|
||||
pub(crate) tiff_compression: Option<TiffCompression>,
|
||||
/// A TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its
|
||||
/// alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24
|
||||
#[arg(long, value_name = "24|32", value_parser = tga_bits)]
|
||||
pub(crate) tga_bits: Option<TgaBits>,
|
||||
/// A DPX's bits per sample. Without it: 8 for an 8-bit document, else 16
|
||||
#[arg(long, value_name = "8|10|12|16", value_parser = dpx_bits)]
|
||||
pub(crate) dpx_bits: Option<DpxBits>,
|
||||
/// A DDS texture's compression: none (uncompressed, the default), bc1 (DXT1: alpha on or
|
||||
/// off), bc2 (DXT3) or bc3 (DXT5)
|
||||
#[arg(long, value_name = "none|bc1|bc2|bc3", value_parser = dds_compression)]
|
||||
pub(crate) dds_compression: Option<DdsCompression>,
|
||||
/// Also write a DDS texture's full mip chain
|
||||
#[arg(long)]
|
||||
pub(crate) dds_mipmaps: bool,
|
||||
/// A JPEG's scans, as JPEG Options picks them: baseline (the default), optimized (Huffman
|
||||
/// tables fitted to the image; RGB is written 4:2:0 and keeps the standard tables, so only Gray
|
||||
/// and CMYK shrink) or progressive
|
||||
#[arg(long, value_name = "baseline|optimized|progressive", value_parser = jpeg_format)]
|
||||
pub(crate) jpeg_format: Option<JpegFormat>,
|
||||
}
|
||||
|
||||
/// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …)
|
||||
///
|
||||
/// An <OUT> that is the <IN> file is refused, as the result would replace the original;
|
||||
/// --in-place allows it.
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The file to read
|
||||
#[arg(value_name = "IN")]
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension picks the format unless --format is given
|
||||
#[arg(value_name = "OUT")]
|
||||
pub(crate) output: PathBuf,
|
||||
/// Allow an <OUT> that is the <IN> file, replacing the original
|
||||
#[arg(long)]
|
||||
pub(crate) in_place: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
}
|
||||
|
||||
/// Print the document as JSON (size, mode, depth, layer tree)
|
||||
#[derive(Args)]
|
||||
pub(crate) struct InfoArgs {
|
||||
pub(crate) file: PathBuf,
|
||||
/// One line of JSON instead of pretty-printed
|
||||
#[arg(long)]
|
||||
pub(crate) compact: bool,
|
||||
}
|
||||
|
||||
/// Open a file (or start a new document), run engine commands in order, save the result
|
||||
///
|
||||
/// Prints each command's JSON result. Give exactly one of <FILE> or --new, and at least one --cmd
|
||||
/// or --out. An --out that is the <FILE> is refused, as the result would replace the original;
|
||||
/// --in-place allows it.
|
||||
#[derive(Args)]
|
||||
#[command(group(ArgGroup::new("source").args(["file", "new"]).required(true)))]
|
||||
#[command(group(ArgGroup::new("work").args(["cmd", "out"]).required(true).multiple(true)))]
|
||||
pub(crate) struct RunArgs {
|
||||
/// The document to open
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from a new document with these JSON parameters instead of opening a file
|
||||
#[arg(long, value_name = "JSON", value_parser = json)]
|
||||
pub(crate) new: Option<Value>,
|
||||
/// An engine command to run; repeat for several, run in order
|
||||
#[arg(long, value_name = "ID", action = ArgAction::Append)]
|
||||
pub(crate) cmd: Vec<String>,
|
||||
/// JSON parameters for the --cmd before it (default {})
|
||||
#[arg(long, value_name = "JSON", action = ArgAction::Append, value_parser = json)]
|
||||
pub(crate) params: Vec<Value>,
|
||||
/// Save the result to this file
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) out: Option<PathBuf>,
|
||||
/// Allow an --out that is the <FILE>, replacing the original
|
||||
#[arg(long)]
|
||||
pub(crate) in_place: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
/// `--cmd` and `--params` values in command-line order, set by [`parse`].
|
||||
#[arg(skip)]
|
||||
pub(crate) steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// One `--cmd` or `--params` of `run`, in command-line order.
|
||||
pub(crate) enum Step {
|
||||
Cmd(String),
|
||||
Params(Value),
|
||||
}
|
||||
|
||||
/// Apply an action list to every image in a directory
|
||||
///
|
||||
/// A Photoshop Actions file (.atn) is a set: its action --action names plays, as below. JSON steps
|
||||
/// are [id, params] pairs, {"command": id, "params": {…}} objects or bare ids, as a recorded
|
||||
/// action or droplet stores them (a list, or wrapped in {"actions": …}, {"steps": …} or a
|
||||
/// droplet). An Actions set (the Actions panel's actions.json, {"actions": [{"name", "steps"}…]})
|
||||
/// plays the action --action names (needed when the set holds more than one) with the whole set
|
||||
/// loaded, so its steps can play other actions of the set.
|
||||
#[derive(Args)]
|
||||
pub(crate) struct BatchArgs {
|
||||
/// The action list: actions.json, a droplet, or a Photoshop Actions file (.atn)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) actions: PathBuf,
|
||||
/// Which action of an Actions set to play
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) action: Option<String>,
|
||||
/// The folder of images to process
|
||||
#[arg(long = "in", value_name = "DIR")]
|
||||
pub(crate) in_dir: PathBuf,
|
||||
/// The folder to write the results to, as <stem>.<ext>
|
||||
#[arg(long, value_name = "DIR")]
|
||||
pub(crate) out: PathBuf,
|
||||
/// An --out folder that is the --in folder is refused, as the results would replace the
|
||||
/// originals; --in-place allows it
|
||||
#[arg(long)]
|
||||
pub(crate) in_place: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
}
|
||||
|
||||
/// Run a droplet (File › Automate › Create Droplet) on images and folders
|
||||
#[derive(Args)]
|
||||
pub(crate) struct DropletArgs {
|
||||
/// The droplet to run
|
||||
#[arg(value_name = "FILE.pcdroplet")]
|
||||
pub(crate) file: String,
|
||||
/// Images and folders to run it on
|
||||
#[arg(value_name = "FILE-OR-DIR", required = true)]
|
||||
pub(crate) inputs: Vec<String>,
|
||||
/// The folder to write the results to
|
||||
#[arg(long, value_name = "DIR")]
|
||||
pub(crate) out: Option<String>,
|
||||
}
|
||||
|
||||
/// List the engine command registry
|
||||
#[derive(Args)]
|
||||
pub(crate) struct CommandsArgs {
|
||||
/// Print the entries as JSON
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
/// Only the commands matching this text
|
||||
#[arg(long, value_name = "TEXT", allow_negative_numbers = true)]
|
||||
pub(crate) filter: Option<String>,
|
||||
}
|
||||
|
||||
/// Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`)
|
||||
///
|
||||
/// Headless: each automation root grants that direction of file access; an omitted root denies it.
|
||||
/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop
|
||||
/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT).
|
||||
#[derive(Args)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means
|
||||
/// 127.0.0.1:<PORT>
|
||||
#[arg(long, value_name = "127.0.0.1:PORT", env = "PHOTOCRAFT_CONTROL_PORT", value_parser = bridge)]
|
||||
pub(crate) bridge: Option<Bridge>,
|
||||
/// `--bridge` came from PHOTOCRAFT_CONTROL_PORT, set by [`parse`].
|
||||
#[arg(skip)]
|
||||
pub(crate) bridge_from_env: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) control: ControlArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
}
|
||||
|
||||
/// Keep one headless session open and answer JSON lines on stdio, or on 127.0.0.1:<PORT>
|
||||
///
|
||||
/// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute,
|
||||
/// jobs.list/cancel, engine.commands,
|
||||
/// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close,
|
||||
/// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require
|
||||
/// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token.
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ServeArgs {
|
||||
/// Listen on 127.0.0.1:<PORT> instead of stdio
|
||||
#[arg(long, value_name = "PORT", env = "PHOTOCRAFT_CONTROL_PORT", value_parser = control_port)]
|
||||
pub(crate) port: Option<u16>,
|
||||
/// `--port` came from PHOTOCRAFT_CONTROL_PORT, set by [`parse`].
|
||||
#[arg(skip)]
|
||||
pub(crate) port_from_env: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) control: ControlArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
}
|
||||
|
||||
/// Why a value was refused: clap prints it after the flag and its value (exit 2).
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ValueError {
|
||||
#[error("expected 24 or 32")]
|
||||
TgaBits,
|
||||
#[error("expected 8, 10, 12 or 16")]
|
||||
DpxBits,
|
||||
#[error("expected none, bc1, bc2 or bc3")]
|
||||
DdsCompression,
|
||||
#[error("expected none, lzw or zip")]
|
||||
TiffCompression,
|
||||
#[error("expected baseline, optimized or progressive")]
|
||||
JpegFormat,
|
||||
/// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused.
|
||||
#[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:<PORT>)")]
|
||||
Bridge,
|
||||
}
|
||||
|
||||
/// Why `parse` refuses `mcp` or `serve` options clap accepted: clap prints it as a usage error
|
||||
/// (exit 2).
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ServerOptionError {
|
||||
/// PHOTOCRAFT_CONTROL_PORT holds a port, as for the desktop app's --control: only the flag
|
||||
/// takes host:port.
|
||||
#[error("invalid value '{0}' for 'PHOTOCRAFT_CONTROL_PORT': {bridge}", bridge = ValueError::Bridge)]
|
||||
BridgeVar(String),
|
||||
/// With --bridge the roots are the desktop process's to set: accepting them here promises
|
||||
/// authority the bridge can't give (#8035).
|
||||
#[error("configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode")]
|
||||
BridgeRoots,
|
||||
/// A token flag without the bridge or port that reads it would be ignored (#8035).
|
||||
#[error("{flag} requires {transport}")]
|
||||
NeedsTransport { flag: &'static str, transport: &'static str },
|
||||
}
|
||||
|
||||
impl ServerOptionError {
|
||||
fn into_clap(self, cmd: &mut clap::Command) -> clap::Error {
|
||||
let kind = match self {
|
||||
Self::BridgeVar(_) => ErrorKind::ValueValidation,
|
||||
Self::BridgeRoots => ErrorKind::ArgumentConflict,
|
||||
Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument,
|
||||
};
|
||||
cmd.error(kind, self)
|
||||
}
|
||||
}
|
||||
|
||||
fn tga_bits(s: &str) -> Result<TgaBits, ValueError> {
|
||||
s.parse().ok().and_then(TgaBits::from_bits).ok_or(ValueError::TgaBits)
|
||||
}
|
||||
|
||||
fn dpx_bits(s: &str) -> Result<DpxBits, ValueError> {
|
||||
s.parse().ok().and_then(DpxBits::from_bits).ok_or(ValueError::DpxBits)
|
||||
}
|
||||
|
||||
fn dds_compression(s: &str) -> Result<DdsCompression, ValueError> {
|
||||
DdsCompression::from_name(s).ok_or(ValueError::DdsCompression)
|
||||
}
|
||||
|
||||
fn tiff_compression(s: &str) -> Result<TiffCompression, ValueError> {
|
||||
match s {
|
||||
"none" => Ok(TiffCompression::None),
|
||||
"lzw" => Ok(TiffCompression::Lzw),
|
||||
"zip" => Ok(TiffCompression::Deflate),
|
||||
_ => Err(ValueError::TiffCompression),
|
||||
}
|
||||
}
|
||||
|
||||
fn jpeg_format(s: &str) -> Result<JpegFormat, ValueError> {
|
||||
JpegFormat::parse(s).ok_or(ValueError::JpegFormat)
|
||||
}
|
||||
|
||||
/// Where `mcp --bridge` connects. Shown as the address: `127.0.0.1:<PORT>` for a port.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Bridge {
|
||||
/// A bare port: the app on 127.0.0.1.
|
||||
Port(u16),
|
||||
/// `host:port`, as given. Whether the host is loopback is the bridge's to say.
|
||||
Addr(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for Bridge {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Bridge::Port(port) => SocketAddr::from((Ipv4Addr::LOCALHOST, *port)).fmt(f),
|
||||
Bridge::Addr(addr) => f.write_str(addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp --bridge`, or PHOTOCRAFT_CONTROL_PORT, which holds a port.
|
||||
fn bridge(s: &str) -> Result<Bridge, ValueError> {
|
||||
match control_port(s) {
|
||||
Ok(port) => Ok(Bridge::Port(port)),
|
||||
Err(_) if s.contains(':') => Ok(Bridge::Addr(s.to_owned())),
|
||||
Err(_) => Err(ValueError::Bridge),
|
||||
}
|
||||
}
|
||||
|
||||
/// `--new` and `--params`: bad JSON is a usage error, before any work. Whether the value is an
|
||||
/// object is the command's to say.
|
||||
fn json(s: &str) -> Result<Value, serde_json::Error> {
|
||||
serde_json::from_str(s)
|
||||
}
|
||||
|
||||
/// `--cmd` and `--params` values back in command-line order: clap keeps each flag's values apart,
|
||||
/// their indices say how they interleave.
|
||||
fn steps(m: &ArgMatches) -> Vec<Step> {
|
||||
let mut steps: Vec<(usize, Step)> = Vec::new();
|
||||
if let (Some(at), Ok(Some(ids))) = (m.indices_of("cmd"), m.try_get_many::<String>("cmd")) {
|
||||
steps.extend(at.zip(ids).map(|(i, id)| (i, Step::Cmd(id.clone()))));
|
||||
}
|
||||
if let (Some(at), Ok(Some(params))) = (m.indices_of("params"), m.try_get_many::<Value>("params")) {
|
||||
steps.extend(at.zip(params).map(|(i, p)| (i, Step::Params(p.clone()))));
|
||||
}
|
||||
steps.sort_by_key(|s| s.0);
|
||||
steps.into_iter().map(|(_, s)| s).collect()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the binary name). clap reads them as `OsString`s: a path need not
|
||||
/// be valid Unicode (#1108), text must. A flag left out falls back to its environment variable,
|
||||
/// unless that is empty, and a bad value from one is a usage error naming the variable (#2491). A
|
||||
/// bare `--help` or `-h` is help even after a mistake on the same line (`--out --help`, `mcp
|
||||
/// stray.psd --help`): clap reports the mistake first.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset));
|
||||
let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned());
|
||||
let matches = match cmd.try_get_matches_from_mut(argv) {
|
||||
Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => {
|
||||
let help = [OsString::from("photocraft-cli"), args.first().cloned().unwrap_or_default(), OsString::from("--help")];
|
||||
return Err(cmd.try_get_matches_from_mut(help).err().unwrap_or(e));
|
||||
}
|
||||
matches => matches.map_err(|e| name_env_vars(e, &cmd, args))?,
|
||||
};
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
let from_env = |m: &ArgMatches, id: &str| m.value_source(id) == Some(ValueSource::EnvVariable);
|
||||
match (&mut cli.command, matches.subcommand()) {
|
||||
(Command::Run(r), Some((_, m))) => r.steps = steps(m),
|
||||
(Command::Mcp(a), Some((name, m))) => {
|
||||
a.bridge_from_env = from_env(m, "bridge");
|
||||
if a.bridge_from_env
|
||||
&& let Some(Bridge::Addr(v)) = &a.bridge
|
||||
{
|
||||
return Err(ServerOptionError::BridgeVar(v.clone()).into_clap(&mut cmd));
|
||||
}
|
||||
if let Some(sub) = cmd.find_subcommand_mut(name) {
|
||||
// Only the bridge reads a token, so a stale exported pair doesn't stop a headless
|
||||
// run.
|
||||
if a.bridge.is_some() {
|
||||
conflict(sub, m, "control_token", "control_token_file")?;
|
||||
}
|
||||
// The roots are the headless engine's: the variable switching to the bridge would
|
||||
// drop them, and the error names it.
|
||||
if a.bridge_from_env {
|
||||
conflict(sub, m, "automation_read_root", "bridge")?;
|
||||
conflict(sub, m, "automation_write_root", "bridge")?;
|
||||
}
|
||||
if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) {
|
||||
return Err(ServerOptionError::BridgeRoots.into_clap(sub));
|
||||
}
|
||||
check_server(sub, m, a.bridge.is_some(), "--bridge")?;
|
||||
}
|
||||
}
|
||||
(Command::Serve(a), Some((name, m))) => {
|
||||
a.port_from_env = from_env(m, "port");
|
||||
if let Some(sub) = cmd.find_subcommand_mut(name) {
|
||||
// Only the TCP server reads a token, so a stale exported pair doesn't stop stdio.
|
||||
if a.port.is_some() {
|
||||
conflict(sub, m, "control_token", "control_token_file")?;
|
||||
}
|
||||
check_server(sub, m, a.port.is_some(), "--port")?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// Refuse a token flag without the bridge or port that reads it (as a flag or its variable). A
|
||||
/// token variable alone may be a stale export, so it isn't refused.
|
||||
fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &'static str) -> Result<(), clap::Error> {
|
||||
for (id, flag) in [("control_token", "--control-token"), ("control_token_file", "--control-token-file")] {
|
||||
if m.value_source(id) == Some(ValueSource::CommandLine) && !has_transport {
|
||||
return Err(ServerOptionError::NeedsTransport { flag, transport }.into_clap(sub));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use std::io::Write;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use photocraft_automation::{Headless, PhotocraftMcp, security};
|
||||
|
||||
use crate::{
|
||||
Result,
|
||||
args::{CommandsArgs, McpArgs, ServeArgs},
|
||||
output::{JsonStyle, print_json},
|
||||
};
|
||||
|
||||
pub(crate) fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result {
|
||||
let h = Headless::new();
|
||||
let list = h.command_list();
|
||||
let needle = a.filter.as_deref().map(str::to_lowercase);
|
||||
let items: Vec<&Value> = list
|
||||
.as_array()
|
||||
.map(|v| v.iter().collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|c| needle.as_ref().is_none_or(|n| photocraft_engine::commands::list_entry_matches(c, n)))
|
||||
.collect();
|
||||
if a.json {
|
||||
return print_json(out, &Value::Array(items.into_iter().cloned().collect()), JsonStyle::Pretty);
|
||||
}
|
||||
for c in items {
|
||||
let menu = c["menu"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" > ")).unwrap_or_default();
|
||||
writeln!(out, "{:<44} {:<32} {}", c["id"].as_str().unwrap_or(""), c["label"].as_str().unwrap_or(""), menu)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let h = Arc::new(Mutex::new(Headless::with_workspace(a.automation.workspace()?)));
|
||||
match a.port {
|
||||
Some(port) => {
|
||||
if a.port_from_env {
|
||||
// Name the mode switch: an exported variable changes what this command does, and
|
||||
// unsetting it (or setting it empty) is the way back to stdio.
|
||||
let _ = writeln!(err, "photocraft-cli: PHOTOCRAFT_CONTROL_PORT={port} is set; serving on TCP instead of stdio (unset it to serve stdio)");
|
||||
}
|
||||
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)).to_string();
|
||||
let (supplied, token_file) = (a.control.control_token.as_deref(), a.control.control_token_file.as_deref());
|
||||
let token = security::server_token(supplied, token_file)?;
|
||||
if let Some(path) = token_file {
|
||||
let _ = writeln!(err, "photocraft-cli control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
let _ = writeln!(err, "photocraft-cli control token: {token}");
|
||||
}
|
||||
photocraft_automation::rpc::serve_tcp(&addr, h, token, |local| {
|
||||
let _ = writeln!(err, "photocraft-cli serving on {local}");
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
let stdin = std::io::stdin();
|
||||
Ok(photocraft_automation::rpc::serve_lines(&h, stdin.lock(), std::io::stdout())?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
|
||||
let server = match &a.bridge {
|
||||
Some(addr) => {
|
||||
if a.bridge_from_env {
|
||||
// Name the mode switch, as `serve` does: the way back to headless is to unset it.
|
||||
let _ = writeln!(
|
||||
err,
|
||||
"photocraft-cli: PHOTOCRAFT_CONTROL_PORT is set; bridging to the app on {addr} instead of a headless engine (unset it to run headless)"
|
||||
);
|
||||
}
|
||||
let token = security::client_token(a.control.control_token.as_deref(), a.control.control_token_file.as_deref())?;
|
||||
PhotocraftMcp::bridge(&addr.to_string(), &token)?
|
||||
}
|
||||
None => PhotocraftMcp::headless_with_workspace(a.automation.workspace()?),
|
||||
};
|
||||
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
||||
Ok(rt.block_on(server.serve_stdio())?)
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_automation::Headless;
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
use photocraft_io::ExportOptions;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{
|
||||
CliError, Result,
|
||||
actions::load_actions_file,
|
||||
args::{BatchArgs, DropletArgs},
|
||||
output::warn_all,
|
||||
};
|
||||
|
||||
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
|
||||
/// trailing separator, through a symbolic link).
|
||||
fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
|
||||
}
|
||||
|
||||
pub(crate) fn is_input(p: &Path) -> bool {
|
||||
let known = |e: &str| {
|
||||
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub")
|
||||
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
|
||||
};
|
||||
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
/// Drops the Save and view steps the desktop records from `action` (Batch saves each result
|
||||
/// itself, #3143), keeping its unchecked and dialog flags on the steps that remain (#6860).
|
||||
fn strip_shell_steps(action: &mut Action) {
|
||||
use photocraft_engine::actions_cmds::{shell_save_command, shell_view_command};
|
||||
let (mut steps, mut disabled, mut dialogs) = (Vec::new(), std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
|
||||
for (i, (id, p)) in std::mem::take(&mut action.steps).into_iter().enumerate() {
|
||||
if shell_save_command(&id) || shell_view_command(&id) {
|
||||
continue;
|
||||
}
|
||||
if action.disabled.contains(&i) {
|
||||
disabled.insert(steps.len());
|
||||
}
|
||||
if action.dialogs.contains(&i) {
|
||||
dialogs.insert(steps.len());
|
||||
}
|
||||
steps.push((id, p));
|
||||
}
|
||||
(action.steps, action.disabled, action.dialogs) = (steps, disabled, dialogs);
|
||||
}
|
||||
|
||||
pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let (in_dir, out_dir) = (a.in_dir.as_path(), a.out.as_path());
|
||||
let (actions, mut set, warnings) = load_actions_file(&a.actions, a.action.as_deref())?;
|
||||
set.iter_mut().for_each(strip_shell_steps);
|
||||
warn_all(err, &warnings);
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
|
||||
// replace the originals (#492).
|
||||
if !a.in_place && same_dir(in_dir, out_dir) {
|
||||
return Err(CliError::OutIsIn(out_dir.to_path_buf()));
|
||||
}
|
||||
std::fs::create_dir_all(out_dir)?;
|
||||
let mut inputs: Vec<PathBuf> = std::fs::read_dir(in_dir)
|
||||
.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| is_input(p))
|
||||
.collect();
|
||||
inputs.sort();
|
||||
let (mut ok, mut failed) = (0, 0);
|
||||
let mut written = photocraft_engine::file_cmds::OutputClaims::default();
|
||||
// `--format .jpg` names outputs `<stem>.jpg`, as `--format jpg` does (#490).
|
||||
let format = a.export.format.as_deref().map(|f| f.strip_prefix('.').unwrap_or(f));
|
||||
for input in &inputs {
|
||||
let ext = format.map(str::to_owned).or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into());
|
||||
let stem = input.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let target = out_dir.join(format!("{stem}.{ext}"));
|
||||
let target_text = target.to_string_lossy();
|
||||
let r = (|| -> Result<Vec<String>> {
|
||||
written.check(&target_text).map_err(CliError::OutputClaimed)?;
|
||||
let mut h = Headless::trusted_local();
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
h.session.actions.list = set.clone();
|
||||
h.open(input)?;
|
||||
for (id, p) in &actions {
|
||||
if photocraft_engine::actions_cmds::shell_view_command(id)
|
||||
|| photocraft_engine::actions_cmds::shell_save_command(id)
|
||||
|| photocraft_engine::actions_cmds::noop_step(&h.session, id, p)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let r = h.command_run(id, p.clone()).map_err(|source| CliError::Command { id: id.clone(), source })?;
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(message) = photocraft_engine::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(CliError::NestedFailure { id: id.clone(), message });
|
||||
}
|
||||
}
|
||||
let r = h.save(None, Some(&target), Some(&ext), &opts)?;
|
||||
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
|
||||
})();
|
||||
match r {
|
||||
Ok(ws) => {
|
||||
ok += 1;
|
||||
written.record(&target_text, &input.to_string_lossy());
|
||||
let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());
|
||||
warn_all(err, &ws);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
let _ = writeln!(err, "FAIL {}: {e}", input.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "{ok} succeeded, {failed} failed");
|
||||
if failed > 0 { Err(CliError::FilesFailed(failed)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub(crate) fn droplet(a: &DropletArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let (file, inputs) = (&a.file, &a.inputs);
|
||||
let mut p = json!({"droplet": file, "input": inputs});
|
||||
if let Some(o) = &a.out {
|
||||
p["output"] = json!(o);
|
||||
}
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
let r = s.execute("file.automate.runDroplet", p)?;
|
||||
for f in r["files"].as_array().into_iter().flatten() {
|
||||
let _ = writeln!(out, "ok {}", f.as_str().unwrap_or_default());
|
||||
}
|
||||
let errors = r["errors"].as_array().cloned().unwrap_or_default();
|
||||
for e in &errors {
|
||||
let _ = writeln!(err, "FAIL {}: {}", e["file"].as_str().unwrap_or_default(), e["error"].as_str().unwrap_or_default());
|
||||
}
|
||||
if errors.is_empty() { Ok(()) } else { Err(CliError::FilesFailed(errors.len())) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod batch_action_set_tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Invoke, invoke};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A batched action that plays another action of its set finds it in every file's session; a
|
||||
/// failure inside the called action fails the file, and a self-call stops instead of looping.
|
||||
#[test]
|
||||
fn batch_plays_an_action_that_calls_another_action_of_its_set() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
for name in ["a", "b"] {
|
||||
let Invoke { code, stderr, .. } = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("in/{name}.png"))]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
}
|
||||
let set = json!({"version": 1, "actions": [
|
||||
{"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}]]},
|
||||
{"name": "Rotate", "steps": [["image.imageRotation.90cw", {}]]},
|
||||
{"name": "Calls bad", "steps": [["actions.play", {"action": "Bad"}]]},
|
||||
{"name": "Bad", "steps": [["layer.delete", {"layer": 999_999}]]},
|
||||
{"name": "Loop", "steps": [["actions.play", {"action": "Loop"}]]},
|
||||
]});
|
||||
std::fs::write(dir.join("actions.json"), set.to_string()).unwrap();
|
||||
let batch = |action: &str| invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]);
|
||||
|
||||
let Invoke { code, stdout, stderr } = batch("Outer");
|
||||
assert_eq!(code, 0, "{stdout}{stderr}");
|
||||
for name in ["a", "b"] {
|
||||
let Invoke { code, stdout: info, stderr } = invoke(&["info", &path(&format!("Outer/{name}.png")), "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "rotated by the called action");
|
||||
}
|
||||
for action in ["Calls bad", "Loop"] {
|
||||
let Invoke { code, stdout, stderr } = batch(action);
|
||||
assert_ne!(code, 0, "{stdout}");
|
||||
assert_eq!(stderr.matches("FAIL").count(), 2, "{stderr}");
|
||||
assert!(!dir.join(action).join("a.png").exists(), "a file whose called action failed is not saved");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Save and view steps recorded inside a batched action set are skipped, also in a called
|
||||
/// action, and unchecked steps stay unchecked once they are gone (#6860).
|
||||
#[test]
|
||||
fn batch_skips_save_and_view_steps_inside_an_action_set() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-save-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
let Invoke { code, stderr, .. } = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path("in/a.png")]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let set = json!({"version": 1, "actions": [
|
||||
{"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}], ["file.saveAs", {}]]},
|
||||
{"name": "Rotate", "steps": [
|
||||
["file.save", {}],
|
||||
["image.imageRotation.90cw", {}],
|
||||
["view.fitOnScreen", {}],
|
||||
["image.imageRotation.90cw", {}],
|
||||
["file.saveAs", {}],
|
||||
], "disabled": [3], "dialogs": [1]},
|
||||
]});
|
||||
std::fs::write(dir.join("actions.json"), set.to_string()).unwrap();
|
||||
for action in ["Outer", "Rotate"] {
|
||||
let Invoke { code, stdout, stderr } =
|
||||
invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]);
|
||||
assert_eq!(code, 0, "{stdout}{stderr}");
|
||||
let Invoke { code, stdout: info, stderr } = invoke(&["info", &path(&format!("{action}/a.png")), "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "{action}: rotated once, the unchecked step skipped");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use photocraft_automation::{Headless, files};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use photocraft_engine::type_extra_cmds::missing_font_warnings;
|
||||
use photocraft_io::ExportOptions;
|
||||
|
||||
use crate::{
|
||||
CliError, Result,
|
||||
args::{ConvertArgs, InfoArgs, RunArgs, Step},
|
||||
output::{JsonStyle, print_json, warn_all},
|
||||
};
|
||||
|
||||
/// An output that is the input file itself, however it is spelt (relative, with `./`, through a
|
||||
/// hard or symbolic link), would replace the original, and a lossy re-encode can't be undone: it
|
||||
/// is refused unless `--in-place` asks for it, as `batch` refuses an `--out` that is its `--in`
|
||||
/// folder (#7437). The paths are compared when the command starts and the save opens `output`
|
||||
/// again later, so another process swapping in a link meanwhile goes unnoticed: this guards
|
||||
/// against mistakes, it is not a security boundary.
|
||||
fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Result {
|
||||
if !in_place && photocraft_engine::file_cmds::same_file(input, output) {
|
||||
return Err(CliError::OutIsInput(output.to_path_buf()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let (input, output) = (&a.input, &a.output);
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
refuse_overwriting_input(a.in_place, input, output)?;
|
||||
let mut o = files::open(input)?;
|
||||
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
|
||||
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
|
||||
warn_all(err, &o.warnings);
|
||||
warn_all(err, &missing_font_warnings(&o.document));
|
||||
let ws = files::save(&o.document, output, a.export.format.as_deref(), &opts, None)?;
|
||||
warn_all(err, &ws);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result {
|
||||
let file = &a.file;
|
||||
let mut h = Headless::trusted_local();
|
||||
let opened = h.open(file)?;
|
||||
let mut doc = h.inspect(None)?;
|
||||
let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default();
|
||||
if let Some(st) = h.session.active() {
|
||||
warnings.extend(missing_font_warnings(&st.doc).into_iter().map(Value::String));
|
||||
}
|
||||
doc["warnings"] = Value::Array(warnings);
|
||||
doc["file"] = json!(file.to_string_lossy());
|
||||
// Drop per-session noise.
|
||||
if let Value::Object(m) = &mut doc {
|
||||
for k in ["history", "canUndo", "canRedo", "revision"] {
|
||||
m.remove(k);
|
||||
}
|
||||
}
|
||||
print_json(out, &doc, if a.compact { JsonStyle::Compact } else { JsonStyle::Pretty })
|
||||
}
|
||||
|
||||
/// `(id, params)` pairs from repeated `--cmd`/`--params` flags.
|
||||
fn command_list(a: &RunArgs) -> Result<Vec<(String, Value)>> {
|
||||
let mut cmds: Vec<(String, Value)> = Vec::new();
|
||||
for step in &a.steps {
|
||||
match step {
|
||||
Step::Cmd(id) => cmds.push((id.clone(), json!({}))),
|
||||
Step::Params(p) => cmds.last_mut().ok_or(CliError::ParamsBeforeCmd)?.1 = p.clone(),
|
||||
}
|
||||
}
|
||||
Ok(cmds)
|
||||
}
|
||||
|
||||
pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
let mut h = Headless::trusted_local();
|
||||
// Opening, running commands and exporting can all notice the same missing font:
|
||||
// one `run` invocation reports each warning line at most once.
|
||||
let mut reported_fonts = std::collections::HashSet::<String>::new();
|
||||
// clap's `source` group gives exactly one of the two, and its `work` group a --cmd or --out.
|
||||
if let Some(new) = &a.new {
|
||||
h.command_run("file.new", new.clone()).map_err(CliError::New)?;
|
||||
} else if let Some(file) = &a.file {
|
||||
// Refused before the file is read or any command runs.
|
||||
if let Some(out) = &a.out {
|
||||
refuse_overwriting_input(a.in_place, file, out)?;
|
||||
}
|
||||
let o = h.open(file)?;
|
||||
let ws: Vec<String> = serde_json::from_value(o["warnings"].clone()).unwrap_or_default();
|
||||
warn_all(err, &ws);
|
||||
reported_fonts.extend(ws);
|
||||
}
|
||||
let cmds = command_list(a)?;
|
||||
for (id, params) in cmds {
|
||||
// A step that is a silent no-op in action playback (Deselect with nothing selected, an Arrange that cannot move the layer) is one in a script too (#8802).
|
||||
if photocraft_engine::actions_cmds::noop_step(&h.session, &id, ¶ms) {
|
||||
print_json(out, &json!({"command": id, "result": null}), JsonStyle::Compact)?;
|
||||
continue;
|
||||
}
|
||||
let r = h.command_run(&id, params).map_err(|source| CliError::Command { id: id.clone(), source })?;
|
||||
if let Some(message) = photocraft_engine::actions_cmds::nested_failure(&id, &r) {
|
||||
return Err(CliError::NestedFailure { id, message });
|
||||
}
|
||||
let new_warnings: Vec<String> =
|
||||
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &new_warnings);
|
||||
let mut result = json!({"command": id, "result": r});
|
||||
if !new_warnings.is_empty() {
|
||||
result["warnings"] = json!(new_warnings);
|
||||
}
|
||||
print_json(out, &result, JsonStyle::Compact)?;
|
||||
}
|
||||
// A `run` with only `--out` still reports missing fonts before exporting.
|
||||
let remaining: Vec<String> =
|
||||
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &remaining);
|
||||
if let Some(o) = a.out.as_deref() {
|
||||
let r = h.save(None, Some(o), a.export.format.as_deref(), &opts)?;
|
||||
let ws: Vec<String> = serde_json::from_value(r["warnings"].clone()).unwrap_or_default();
|
||||
let ws: Vec<String> = ws.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &ws);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod missing_font_warning_tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
batch::is_input,
|
||||
test_support::{Invoke, invoke},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn missing_typeface_is_reported_by_run_info_and_convert() {
|
||||
let family = "DefinitelyMissingPhotoCraftTypeface1251";
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-font-warnings-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let native = folder.join("missing.pcraft");
|
||||
let png = folder.join("missing.png");
|
||||
let native_str = native.to_string_lossy().to_string();
|
||||
let png_str = png.to_string_lossy().to_string();
|
||||
let params = json!({"x": 6, "y": 38, "text": "Missing font warning", "font": family, "size": 20}).to_string();
|
||||
|
||||
let Invoke { code, stdout, stderr } = invoke(&[
|
||||
"run",
|
||||
"--new",
|
||||
r#"{"width":256,"height":96,"background":"white"}"#,
|
||||
"--cmd",
|
||||
"type.create",
|
||||
"--params",
|
||||
¶ms,
|
||||
"--cmd",
|
||||
"type.resolveMissingFonts",
|
||||
"--out",
|
||||
&native_str,
|
||||
]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert_eq!(stderr.matches(family).count(), 1, "multi-command runs should not repeat the same missing font warning");
|
||||
let commands: Vec<Value> = stdout.lines().map(|s| serde_json::from_str(s).unwrap()).collect();
|
||||
assert_eq!(commands.len(), 2, "{stdout}");
|
||||
assert!(commands[0]["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains(family))));
|
||||
assert!(commands[1].get("warnings").is_none(), "only newly detected missing fonts are reported");
|
||||
|
||||
let Invoke { code, stdout, stderr } = invoke(&["info", &native_str, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert!(info["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains(family))));
|
||||
assert!(stderr.is_empty(), "info puts warnings in JSON, not stderr");
|
||||
|
||||
let Invoke { code, stderr, .. } = invoke(&["convert", &native_str, &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(stderr.contains(&format!("warning: font '{family}'")), "{stderr}");
|
||||
assert!(png.is_file());
|
||||
|
||||
// Even with no commands, run --out checks the opened document before export.
|
||||
let Invoke { code, stdout, stderr } = invoke(&["run", &native_str, "--out", &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(stdout.is_empty());
|
||||
assert_eq!(stderr.matches(family).count(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_reads_and_writes_openraster() {
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-ora-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let path = |name: &str| folder.join(name).to_string_lossy().to_string();
|
||||
let (native, ora, png) = (path("layers.pcraft"), path("layers.ora"), path("back.png"));
|
||||
let Invoke { code, stderr, .. } = invoke(&["run", "--new", r#"{"width":16,"height":12}"#, "--cmd", "layer.new.layer", "--out", &native]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let Invoke { code, stderr, .. } = invoke(&["convert", &native, &ora]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let Invoke { code, stdout, stderr } = invoke(&["info", &ora, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert_eq!(info["layers"].as_array().map(Vec::len), Some(2), "{info}");
|
||||
let Invoke { code, stderr, .. } = invoke(&["convert", &ora, &png]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(is_input(std::path::Path::new(&ora)));
|
||||
// Krita documents are batch inputs too (import-only).
|
||||
for name in ["sketch.kra", "old.KRZ"] {
|
||||
std::fs::write(folder.join(name), b"").unwrap();
|
||||
assert!(is_input(&folder.join(name)), "{name}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_type_layers_do_not_produce_missing_font_warnings() {
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-no-font-warning-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let native = folder.join("blank.pcraft");
|
||||
let png = folder.join("blank.png");
|
||||
let native_str = native.to_string_lossy().to_string();
|
||||
let png_str = png.to_string_lossy().to_string();
|
||||
let Invoke { code, stderr, .. } = invoke(&["run", "--new", r#"{"width":16,"height":16}"#, "--out", &native_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(!stderr.contains("font '"), "{stderr}");
|
||||
let Invoke { code, stdout, stderr } = invoke(&["info", &native_str, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert!(info["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap_or_default().contains("font '")));
|
||||
let Invoke { code, stderr, .. } = invoke(&["convert", &native_str, &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(!stderr.contains("font '"), "{stderr}");
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use photocraft_automation::AutomationError;
|
||||
|
||||
use crate::actions::ActionsError;
|
||||
|
||||
/// Why a subcommand failed: printed as `error: {e}`, exit 1.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum CliError {
|
||||
#[error(transparent)]
|
||||
Automation(#[from] AutomationError),
|
||||
#[error(transparent)]
|
||||
Engine(#[from] photocraft_engine::EngineError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
Actions(#[from] ActionsError),
|
||||
#[error("{}: {source}", path.display())]
|
||||
ReadDir { path: PathBuf, source: std::io::Error },
|
||||
#[error("--params must follow a --cmd")]
|
||||
ParamsBeforeCmd,
|
||||
#[error("--new: {0}")]
|
||||
New(#[source] AutomationError),
|
||||
#[error("`{id}`: {source}")]
|
||||
Command { id: String, source: AutomationError },
|
||||
/// A step inside an action the command played failed ([`photocraft_engine::actions_cmds::nested_failure`]).
|
||||
#[error("`{id}`: {message}")]
|
||||
NestedFailure { id: String, message: String },
|
||||
#[error("{} is the input file, so the result would replace the original: choose another output, or pass --in-place to overwrite it", .0.display())]
|
||||
OutIsInput(PathBuf),
|
||||
#[error("--out {} is the --in folder, so the results would replace the originals: choose another --out folder, or pass --in-place to overwrite them", .0.display())]
|
||||
OutIsIn(PathBuf),
|
||||
/// Another input already wrote this output ([`photocraft_engine::file_cmds::OutputClaims::check`]).
|
||||
#[error("{0}")]
|
||||
OutputClaimed(String),
|
||||
#[error("{0} file(s) failed")]
|
||||
FilesFailed(usize),
|
||||
}
|
||||
|
||||
pub(crate) type Result<T = (), E = CliError> = std::result::Result<T, E>;
|
||||
@@ -3,197 +3,63 @@
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_automation::{AuthorizedWorkspace, Headless, PhotocraftMcp, files, security};
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
use photocraft_io::ExportOptions;
|
||||
use serde_json::{Value, json};
|
||||
use clap::CommandFactory;
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
photocraft-cli: headless PhotoCraft
|
||||
mod actions;
|
||||
mod args;
|
||||
mod automation;
|
||||
mod batch;
|
||||
mod document;
|
||||
mod error;
|
||||
mod output;
|
||||
|
||||
USAGE:
|
||||
photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).
|
||||
TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).
|
||||
--quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless.
|
||||
--tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as
|
||||
its alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24.
|
||||
--dpx-bits sets a DPX's bits per sample. Without it: 8 for an 8-bit document, else 16.
|
||||
photocraft-cli info <file> [--compact]
|
||||
Print the document as JSON (size, mode, depth, layer tree).
|
||||
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Open a file, run engine commands in order, save the result. Each --params
|
||||
applies to the preceding --cmd. Prints each command's JSON result.
|
||||
photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a
|
||||
set: its action --action names plays, as below. JSON steps are [id, params] pairs,
|
||||
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
|
||||
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions
|
||||
panel's actions.json, {\"actions\": [{\"name\", \"steps\"}…]}) plays the action --action names (needed
|
||||
when the set holds more than one) with the whole set loaded, so its steps can play other actions
|
||||
of the set. An --out folder that is the --in folder is refused, as the results would replace
|
||||
the originals; --in-place allows it.
|
||||
photocraft-cli droplet <file.pcdroplet> <file-or-dir>… [--out <dir>]
|
||||
Run a droplet (File › Automate › Create Droplet) on images and folders.
|
||||
photocraft-cli commands [--json] [--filter <text>]
|
||||
List the engine command registry.
|
||||
photocraft-cli mcp [--bridge <127.0.0.1:port>] [--control-token <64-hex> | --control-token-file <path>]
|
||||
[--automation-read-root <dir>] [--automation-write-root <dir>]
|
||||
Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`).
|
||||
photocraft-cli serve [--port <port>] [--control-token <64-hex> | --control-token-file <path>]
|
||||
[--automation-read-root <dir>] [--automation-write-root <dir>]
|
||||
Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio,
|
||||
or on 127.0.0.1:<port>. Methods: engine.execute, jobs.list/cancel, engine.commands,
|
||||
doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, session.list, batch, methods
|
||||
(docs/control-protocol.md#headless-server).
|
||||
pub use actions::{ActionsError, Steps, load_actions, load_actions_file, parse_actions};
|
||||
use args::{Command, parse};
|
||||
use automation::{commands, mcp, serve};
|
||||
use batch::{batch, droplet};
|
||||
use document::{convert, info, run_cmds};
|
||||
pub(crate) use error::{CliError, Result};
|
||||
|
||||
photocraft-cli <subcommand> --help (or -h) prints this text. A flag the subcommand doesn't take is
|
||||
an error.
|
||||
";
|
||||
|
||||
struct Args {
|
||||
positional: Vec<String>,
|
||||
flags: Vec<(String, Option<String>)>,
|
||||
/// The command line's clap definition, for generating shell completions and man pages
|
||||
/// (`examples/man-and-completions.rs`).
|
||||
pub fn command() -> clap::Command {
|
||||
args::Cli::command()
|
||||
}
|
||||
|
||||
/// A subcommand: the flags it reads (taking a value, or given bare) and what it runs. A flag
|
||||
/// outside these is a usage error, so a typo such as `--fromat` can't be silently ignored (#423).
|
||||
struct Subcommand {
|
||||
name: &'static str,
|
||||
values: &'static [&'static str],
|
||||
bare: &'static [&'static str],
|
||||
run: fn(&Args, &mut dyn Write, &mut dyn Write) -> R,
|
||||
}
|
||||
|
||||
const SUBCOMMANDS: &[Subcommand] = &[
|
||||
Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--tiff-layers"], run: convert },
|
||||
Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },
|
||||
Subcommand {
|
||||
name: "run",
|
||||
values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"],
|
||||
bare: &["--tiff-layers"],
|
||||
run: run_cmds,
|
||||
},
|
||||
Subcommand {
|
||||
name: "batch",
|
||||
values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"],
|
||||
bare: &["--in-place", "--tiff-layers"],
|
||||
run: batch,
|
||||
},
|
||||
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
|
||||
Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) },
|
||||
Subcommand {
|
||||
name: "mcp",
|
||||
values: &["--bridge", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"],
|
||||
bare: &[],
|
||||
run: |a, _, _| mcp(a),
|
||||
},
|
||||
Subcommand {
|
||||
name: "serve",
|
||||
values: &["--port", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"],
|
||||
bare: &[],
|
||||
run: |a, _, err| serve(a, err),
|
||||
},
|
||||
];
|
||||
|
||||
/// The subcommand's arguments, or `None` when they ask for help (`--help` or `-h`).
|
||||
fn parse(sub: &Subcommand, args: &[String]) -> Result<Option<Args>, String> {
|
||||
let mut a = Args { positional: Vec::new(), flags: Vec::new() };
|
||||
let unknown = |flag: &str| format!("unknown flag {flag} for {}", sub.name);
|
||||
let mut i = 0;
|
||||
while let Some(s) = args.get(i) {
|
||||
if s == "--help" || s == "-h" {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some((k, v)) = s.split_once('=').filter(|(k, _)| k.starts_with("--")) {
|
||||
if sub.bare.contains(&k) {
|
||||
return Err(format!("{k} takes no value"));
|
||||
}
|
||||
if !sub.values.contains(&k) {
|
||||
return Err(unknown(k));
|
||||
}
|
||||
a.flags.push((k.to_owned(), Some(v.to_owned())));
|
||||
} else if sub.values.contains(&s.as_str()) {
|
||||
let v = args.get(i + 1).ok_or_else(|| format!("{s} needs a value"))?;
|
||||
a.flags.push((s.clone(), Some(v.clone())));
|
||||
i += 1;
|
||||
} else if sub.bare.contains(&s.as_str()) {
|
||||
a.flags.push((s.clone(), None));
|
||||
} else if s.starts_with("--") {
|
||||
return Err(unknown(s));
|
||||
} else {
|
||||
a.positional.push(s.clone());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(Some(a))
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn get(&self, k: &str) -> Option<&str> {
|
||||
self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref())
|
||||
}
|
||||
fn has(&self, k: &str) -> bool {
|
||||
self.flags.iter().any(|(f, _)| f == k)
|
||||
}
|
||||
}
|
||||
|
||||
type R = Result<(), String>;
|
||||
|
||||
/// [`run`] on the raw process arguments. An argument that is not valid Unicode is a usage error
|
||||
/// naming its position and a lossy rendering (exit 2), never a panic: `std::env::args()` aborts
|
||||
/// the process on one (issue #1108).
|
||||
pub fn run_os(args: &[std::ffi::OsString], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
|
||||
let mut strings = Vec::with_capacity(args.len());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
match a.clone().into_string() {
|
||||
Ok(s) => strings.push(s),
|
||||
Err(raw) => {
|
||||
let _ = writeln!(err, "error: argument {} is not valid Unicode: `{}`\n\n{USAGE}", i + 1, raw.to_string_lossy());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
run(&strings, out, err)
|
||||
}
|
||||
|
||||
/// Run the CLI. Returns the process exit code (0 ok, 1 failure, 2 usage).
|
||||
pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
|
||||
let Some(cmd) = args.first() else {
|
||||
let _ = write!(err, "{USAGE}");
|
||||
return 2;
|
||||
};
|
||||
match cmd.as_str() {
|
||||
"-h" | "--help" | "help" => {
|
||||
let _ = write!(out, "{USAGE}");
|
||||
return 0;
|
||||
}
|
||||
"--version" | "version" => {
|
||||
let _ = writeln!(out, "photocraft-cli {}", photocraft_engine::build_info::long_version());
|
||||
return 0;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(sub) = SUBCOMMANDS.iter().find(|s| s.name == cmd) else {
|
||||
let _ = writeln!(err, "error: unknown command `{cmd}`\n\n{USAGE}");
|
||||
return 2;
|
||||
};
|
||||
let parsed = match parse(sub, &args[1..]) {
|
||||
Ok(Some(p)) => p,
|
||||
// `<subcommand> --help`: usage, without reading inputs or starting a server.
|
||||
Ok(None) => {
|
||||
let _ = write!(out, "{USAGE}");
|
||||
return 0;
|
||||
}
|
||||
/// Run the CLI on its arguments (without the program name). Returns the process exit code (0 ok,
|
||||
/// 1 failure, 2 usage). clap reads the arguments as they are: a path that is not valid Unicode (a
|
||||
/// Latin-1 file name on Linux) is taken, and one where text is expected is a usage error (exit 2).
|
||||
/// Never a panic, as `std::env::args()` aborts on one (issue #1108).
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
// Help and `--version` (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too,
|
||||
// for `out`, exit 0: the subcommand never runs.
|
||||
let cli = match parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let _ = writeln!(err, "error: {e}\n\n{USAGE}");
|
||||
return 2;
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
match (sub.run)(&parsed, out, err) {
|
||||
let result = match &cli.command {
|
||||
Command::Convert(a) => convert(a, out, err),
|
||||
Command::Info(a) => info(a, out),
|
||||
Command::Run(a) => run_cmds(a, out, err),
|
||||
Command::Batch(a) => batch(a, out, err),
|
||||
Command::Droplet(a) => droplet(a, out, err),
|
||||
Command::Commands(a) => commands(a, out),
|
||||
Command::Mcp(a) => mcp(a, err),
|
||||
Command::Serve(a) => serve(a, err),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
let _ = writeln!(err, "error: {e}");
|
||||
@@ -202,553 +68,18 @@ pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn export_opts(a: &Args) -> Result<ExportOptions, String> {
|
||||
// TIFF output is flat unless asked: scripted conversions keep predictable sizes.
|
||||
let mut o = ExportOptions { tiff_layers: a.has("--tiff-layers"), ..Default::default() };
|
||||
if let Some(q) = a.get("--quality") {
|
||||
let q = q.parse().ok().filter(|q| (1..=100).contains(q)).ok_or_else(|| format!("bad --quality `{q}`: expected a whole number from 1 to 100"))?;
|
||||
o.encode.jpeg_quality = q;
|
||||
// Asking for a quality asks for a lossy WebP; the default WebP stays lossless.
|
||||
o.encode.webp_quality = q;
|
||||
o.encode.webp_lossless = false;
|
||||
}
|
||||
if let Some(b) = a.get("--tga-bits") {
|
||||
o.tga_bits = Some(b.parse().ok().and_then(photocraft_io::TgaBits::from_bits).ok_or_else(|| format!("bad --tga-bits `{b}`: expected 24 or 32"))?);
|
||||
}
|
||||
if let Some(b) = a.get("--dpx-bits") {
|
||||
o.encode.dpx_bits =
|
||||
Some(b.parse().ok().and_then(photocraft_io::DpxBits::from_bits).ok_or_else(|| format!("bad --dpx-bits `{b}`: expected 8, 10, 12 or 16"))?);
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
fn warn_all(err: &mut dyn Write, ws: &[String]) {
|
||||
for w in ws {
|
||||
let _ = writeln!(err, "warning: {w}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine knows which type families aren't installed. Warn before an export
|
||||
/// uses a fallback face rather than silently changing the appearance of the text.
|
||||
fn missing_font_warnings(fonts: Vec<String>) -> Vec<String> {
|
||||
fonts.into_iter().map(|font| format!("font '{font}' is not installed; text may render using a fallback face")).collect()
|
||||
}
|
||||
|
||||
fn automation_workspace(args: &Args) -> Result<AuthorizedWorkspace, String> {
|
||||
AuthorizedWorkspace::new(args.get("--automation-read-root").map(Path::new), args.get("--automation-write-root").map(Path::new))
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let [input, output] = a.positional.as_slice() else {
|
||||
return Err("convert needs <in> <out>".into());
|
||||
};
|
||||
let opts = export_opts(a)?;
|
||||
let o = files::open(Path::new(input)).map_err(|e| e.to_string())?;
|
||||
warn_all(err, &o.warnings);
|
||||
warn_all(err, &photocraft_engine::type_extra_cmds::missing_font_warnings(&o.document));
|
||||
let ws = files::save(&o.document, Path::new(output), a.get("--format"), &opts, None).map_err(|e| e.to_string())?;
|
||||
warn_all(err, &ws);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_json(out: &mut dyn Write, v: &Value, compact: bool) -> R {
|
||||
let s = if compact { serde_json::to_string(v) } else { serde_json::to_string_pretty(v) }.map_err(|e| e.to_string())?;
|
||||
writeln!(out, "{s}").map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn info(a: &Args, out: &mut dyn Write) -> R {
|
||||
let [file] = a.positional.as_slice() else {
|
||||
return Err("info needs <file>".into());
|
||||
};
|
||||
let mut h = Headless::trusted_local();
|
||||
let opened = h.open(Path::new(file)).map_err(|e| e.to_string())?;
|
||||
let mut doc = h.inspect(None).map_err(|e| e.to_string())?;
|
||||
let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default();
|
||||
if let Some(st) = h.session.active() {
|
||||
warnings.extend(missing_font_warnings(photocraft_engine::type_extra_cmds::missing_fonts(&st.doc)).into_iter().map(Value::String));
|
||||
}
|
||||
doc["warnings"] = Value::Array(warnings);
|
||||
doc["file"] = json!(file);
|
||||
// Drop per-session noise.
|
||||
if let Value::Object(m) = &mut doc {
|
||||
for k in ["history", "canUndo", "canRedo", "revision"] {
|
||||
m.remove(k);
|
||||
}
|
||||
}
|
||||
print_json(out, &doc, a.has("--compact"))
|
||||
}
|
||||
|
||||
/// `(id, params)` pairs from repeated `--cmd`/`--params` flags.
|
||||
fn command_list(a: &Args) -> Result<Vec<(String, Value)>, String> {
|
||||
let mut cmds: Vec<(String, Value)> = Vec::new();
|
||||
for (k, v) in &a.flags {
|
||||
match (k.as_str(), v) {
|
||||
("--cmd", Some(id)) => cmds.push((id.clone(), json!({}))),
|
||||
("--params", Some(p)) => {
|
||||
let last = cmds.last_mut().ok_or("--params must follow a --cmd")?;
|
||||
last.1 = serde_json::from_str(p).map_err(|e| format!("bad --params JSON for `{}`: {e}", last.0))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(cmds)
|
||||
}
|
||||
|
||||
fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let opts = export_opts(a)?;
|
||||
let mut h = Headless::trusted_local();
|
||||
// Opening, running commands and exporting can all notice the same missing font:
|
||||
// one `run` invocation reports each warning line at most once.
|
||||
let mut reported_fonts = std::collections::HashSet::<String>::new();
|
||||
match (a.positional.as_slice(), a.get("--new")) {
|
||||
([file], None) => {
|
||||
let o = h.open(Path::new(file)).map_err(|e| e.to_string())?;
|
||||
let ws: Vec<String> = serde_json::from_value(o["warnings"].clone()).unwrap_or_default();
|
||||
reported_fonts.extend(ws.iter().cloned());
|
||||
warn_all(err, &ws);
|
||||
reported_fonts.extend(ws);
|
||||
}
|
||||
([], Some(new)) => {
|
||||
let p: Value = serde_json::from_str(new).map_err(|e| format!("bad --new JSON: {e}"))?;
|
||||
h.command_run("file.new", p).map_err(|e| format!("--new: {e}"))?;
|
||||
}
|
||||
_ => return Err("run needs exactly one of <file> or --new <json>".into()),
|
||||
}
|
||||
let cmds = command_list(a)?;
|
||||
if cmds.is_empty() && a.get("--out").is_none() {
|
||||
return Err("run needs at least one --cmd (or --out)".into());
|
||||
}
|
||||
for (id, params) in cmds {
|
||||
let r = h.command_run(&id, params).map_err(|e| format!("`{id}`: {e}"))?;
|
||||
if let Some(e) = photocraft_engine::actions_cmds::nested_failure(&id, &r) {
|
||||
return Err(format!("`{id}`: {e}"));
|
||||
}
|
||||
let new_warnings: Vec<String> = h
|
||||
.session
|
||||
.active()
|
||||
.map(|st| missing_font_warnings(photocraft_engine::type_extra_cmds::missing_fonts(&st.doc)))
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|w| reported_fonts.insert(w.clone()))
|
||||
.collect();
|
||||
warn_all(err, &new_warnings);
|
||||
let mut result = json!({"command": id, "result": r});
|
||||
if !new_warnings.is_empty() {
|
||||
result["warnings"] = json!(new_warnings);
|
||||
}
|
||||
print_json(out, &result, true)?;
|
||||
}
|
||||
// A `run` with only `--out` still reports missing fonts before exporting.
|
||||
let remaining: Vec<String> = h
|
||||
.session
|
||||
.active()
|
||||
.map(|st| missing_font_warnings(photocraft_engine::type_extra_cmds::missing_fonts(&st.doc)))
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|w| reported_fonts.insert(w.clone()))
|
||||
.collect();
|
||||
warn_all(err, &remaining);
|
||||
if let Some(o) = a.get("--out") {
|
||||
let r = h.save(None, Some(Path::new(o)), a.get("--format"), &opts).map_err(|e| e.to_string())?;
|
||||
let ws: Vec<String> = serde_json::from_value(r["warnings"].clone()).unwrap_or_default();
|
||||
let ws: Vec<String> = ws.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &ws);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse an actions file: the steps of a recorded action or a droplet (`[id, params]` pairs,
|
||||
/// `{"command": id, "params": {…}}` objects or bare ids; `"id"` is accepted for `"command"`), as a
|
||||
/// list or wrapped in `{"actions": […]}`, `{"steps": […]}` or a droplet (#489).
|
||||
pub fn parse_actions(text: &str) -> Result<Vec<(String, Value)>, String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
|
||||
steps_of(&v)
|
||||
}
|
||||
|
||||
fn steps_of(v: &Value) -> Result<Steps, String> {
|
||||
photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(v), "batch --actions").map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Engine commands to run in order: `(id, params)`.
|
||||
pub type Steps = Vec<(String, Value)>;
|
||||
|
||||
/// The steps `batch` plays on each file, and the actions they can call. An Actions set (the
|
||||
/// Actions panel's `actions.json`: `{"actions": [{"name", "steps"}…]}`, or the bare list) plays
|
||||
/// the action `name` picks (optional when the set holds one) with the whole set loaded, as
|
||||
/// Photoshop's Batch does; anything else is one action's steps ([`parse_actions`]) (#2786).
|
||||
pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>), String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
|
||||
let list = v.get("actions").unwrap_or(&v);
|
||||
let is_set = list.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|x| x.get("name").is_some_and(Value::is_string)));
|
||||
if !is_set {
|
||||
if name.is_some() {
|
||||
return Err("--action picks an action from an Actions set ({\"actions\": [{\"name\", \"steps\"}…]}), but this file holds one action's steps".into());
|
||||
}
|
||||
return Ok((steps_of(&v)?, Vec::new()));
|
||||
}
|
||||
let set: Vec<Action> = serde_json::from_value(list.clone()).map_err(|e| format!("Actions set: {e}"))?;
|
||||
let names = || set.iter().map(|a| format!("`{}`", a.name)).collect::<Vec<_>>().join(", ");
|
||||
let action = match (name, set.as_slice()) {
|
||||
(Some(n), _) => set.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set (it holds {})", names()))?,
|
||||
(None, [only]) => only,
|
||||
(None, _) => return Err(format!("the Actions set holds {} actions: pick one with --action <name> ({})", set.len(), names())),
|
||||
};
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, set))
|
||||
}
|
||||
|
||||
/// [`load_actions`] for a file on disk: a Photoshop Actions file (`.atn`, by extension or by
|
||||
/// its version word) is converted first; the played action's steps with no PhotoCraft
|
||||
/// equivalent come back as warnings (they fail at playback, as in Photoshop when a step can't run).
|
||||
pub fn load_actions_file(path: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>, Vec<String>), String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let is_atn = Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || bytes.starts_with(&[0, 0, 0, 16]);
|
||||
if !is_atn {
|
||||
let text = String::from_utf8(bytes).map_err(|e| format!("{path}: {e}"))?;
|
||||
let (steps, set) = load_actions(&text, name)?;
|
||||
return Ok((steps, set, Vec::new()));
|
||||
}
|
||||
let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|e| format!("{path}: {e}"))?;
|
||||
let names = || imp.actions.iter().map(|a| format!("`{}`", a.name)).collect::<Vec<_>>().join(", ");
|
||||
let action = match (name, imp.actions.as_slice()) {
|
||||
(Some(n), _) => {
|
||||
imp.actions.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set `{}` (it holds {})", imp.set, names()))?
|
||||
}
|
||||
(None, [only]) => only,
|
||||
(None, []) => return Err(format!("{path}: the set holds no actions")),
|
||||
(None, _) => return Err(format!("the set `{}` holds {} actions: pick one with --action <name> ({})", imp.set, imp.actions.len(), names())),
|
||||
};
|
||||
let warnings = imp
|
||||
.unsupported
|
||||
.iter()
|
||||
.filter(|u| u.action == action.name)
|
||||
.map(|u| format!("`{}` step {}: Photoshop's \"{}\" ({}) has no PhotoCraft equivalent yet", u.action, u.step + 1, u.name, u.event))
|
||||
.chain(imp.warnings.iter().cloned())
|
||||
.collect();
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, imp.actions, warnings))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
|
||||
/// trailing separator, through a symbolic link).
|
||||
fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
|
||||
}
|
||||
|
||||
fn is_input(p: &Path) -> bool {
|
||||
let known = |e: &str| {
|
||||
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub")
|
||||
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
|
||||
};
|
||||
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let actions_path = a.get("--actions").ok_or("batch needs --actions <file>")?;
|
||||
let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in <dir>")?);
|
||||
let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out <dir>")?);
|
||||
let (actions, set, warnings) = load_actions_file(actions_path, a.get("--action"))?;
|
||||
for w in &warnings {
|
||||
let _ = writeln!(err, "warning: {w}");
|
||||
}
|
||||
let opts = export_opts(a)?;
|
||||
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
|
||||
// replace the originals (#492).
|
||||
if !a.has("--in-place") && same_dir(&in_dir, &out_dir) {
|
||||
return Err(format!(
|
||||
"--out {} is the --in folder, so the results would replace the originals: choose another --out folder, or pass --in-place to overwrite them",
|
||||
out_dir.display()
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?;
|
||||
let mut inputs: Vec<PathBuf> =
|
||||
std::fs::read_dir(&in_dir).map_err(|e| format!("{}: {e}", in_dir.display()))?.flatten().map(|e| e.path()).filter(|p| is_input(p)).collect();
|
||||
inputs.sort();
|
||||
let (mut ok, mut failed) = (0, 0);
|
||||
let mut written = photocraft_engine::file_cmds::OutputClaims::default();
|
||||
// `--format .jpg` names outputs `<stem>.jpg`, as `--format jpg` does (#490).
|
||||
let format = a.get("--format").map(|f| f.strip_prefix('.').unwrap_or(f));
|
||||
for input in &inputs {
|
||||
let ext = format.map(str::to_owned).or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into());
|
||||
let stem = input.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let target = out_dir.join(format!("{stem}.{ext}"));
|
||||
let target_text = target.to_string_lossy();
|
||||
let r = (|| -> Result<Vec<String>, String> {
|
||||
written.check(&target_text)?;
|
||||
let mut h = Headless::trusted_local();
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
h.session.actions.list = set.clone();
|
||||
h.open(input).map_err(|e| e.to_string())?;
|
||||
for (id, p) in &actions {
|
||||
if photocraft_engine::actions_cmds::shell_view_command(id) || photocraft_engine::actions_cmds::shell_save_command(id) {
|
||||
continue;
|
||||
}
|
||||
let r = h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(e) = photocraft_engine::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(format!("`{id}`: {e}"));
|
||||
}
|
||||
}
|
||||
let r = h.save(None, Some(&target), Some(&ext), &opts).map_err(|e| e.to_string())?;
|
||||
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
|
||||
})();
|
||||
match r {
|
||||
Ok(ws) => {
|
||||
ok += 1;
|
||||
written.record(&target_text, &input.to_string_lossy());
|
||||
let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());
|
||||
warn_all(err, &ws);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
let _ = writeln!(err, "FAIL {}: {e}", input.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "{ok} succeeded, {failed} failed");
|
||||
if failed > 0 { Err(format!("{failed} file(s) failed")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn droplet(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let (file, inputs) = a.positional.split_first().ok_or("droplet needs <file.pcdroplet> and inputs")?;
|
||||
if inputs.is_empty() {
|
||||
return Err("droplet needs at least one input file or folder".into());
|
||||
}
|
||||
let mut p = json!({"droplet": file, "input": inputs});
|
||||
if let Some(o) = a.get("--out") {
|
||||
p["output"] = json!(o);
|
||||
}
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
let r = s.execute("file.automate.runDroplet", p).map_err(|e| e.to_string())?;
|
||||
for f in r["files"].as_array().into_iter().flatten() {
|
||||
let _ = writeln!(out, "ok {}", f.as_str().unwrap_or_default());
|
||||
}
|
||||
let errors = r["errors"].as_array().cloned().unwrap_or_default();
|
||||
for e in &errors {
|
||||
let _ = writeln!(err, "FAIL {}: {}", e["file"].as_str().unwrap_or_default(), e["error"].as_str().unwrap_or_default());
|
||||
}
|
||||
if errors.is_empty() { Ok(()) } else { Err(format!("{} file(s) failed", errors.len())) }
|
||||
}
|
||||
|
||||
fn commands(a: &Args, out: &mut dyn Write) -> R {
|
||||
let h = Headless::new();
|
||||
let list = h.command_list();
|
||||
let needle = a.get("--filter").map(str::to_lowercase);
|
||||
let items: Vec<&Value> = list
|
||||
.as_array()
|
||||
.map(|v| v.iter().collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|c| needle.as_ref().is_none_or(|n| photocraft_engine::commands::list_entry_matches(c, n)))
|
||||
.collect();
|
||||
if a.has("--json") {
|
||||
return print_json(out, &Value::Array(items.into_iter().cloned().collect()), false);
|
||||
}
|
||||
for c in items {
|
||||
let menu = c["menu"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" > ")).unwrap_or_default();
|
||||
writeln!(out, "{:<44} {:<32} {}", c["id"].as_str().unwrap_or(""), c["label"].as_str().unwrap_or(""), menu).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serve(a: &Args, err: &mut dyn Write) -> R {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let h = Arc::new(Mutex::new(Headless::with_workspace(automation_workspace(a)?)));
|
||||
match a.get("--port") {
|
||||
Some(port) => {
|
||||
let port: u16 = port.parse().map_err(|_| format!("bad --port `{port}`"))?;
|
||||
let addr = format!("127.0.0.1:{port}");
|
||||
let (supplied, token_file) = security::token_inputs(a.get("--control-token").map(str::to_owned), a.get("--control-token-file").map(PathBuf::from));
|
||||
let token = security::server_token(supplied.as_deref(), token_file.as_deref()).map_err(|e| e.to_string())?;
|
||||
if let Some(path) = &token_file {
|
||||
let _ = writeln!(err, "photocraft-cli control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
let _ = writeln!(err, "photocraft-cli control token: {token}");
|
||||
}
|
||||
photocraft_automation::rpc::serve_tcp(&addr, h, token, |local| {
|
||||
let _ = writeln!(err, "photocraft-cli serving on {local}");
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
None => {
|
||||
let stdin = std::io::stdin();
|
||||
photocraft_automation::rpc::serve_lines(&h, stdin.lock(), std::io::stdout()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: &Args) -> R {
|
||||
let server = match a.get("--bridge") {
|
||||
Some(addr) => {
|
||||
let (supplied, token_file) = security::token_inputs(a.get("--control-token").map(str::to_owned), a.get("--control-token-file").map(PathBuf::from));
|
||||
let token = security::client_token(supplied.as_deref(), token_file.as_deref()).map_err(|e| e.to_string())?;
|
||||
PhotocraftMcp::bridge(addr, &token).map_err(|e| e.to_string())?
|
||||
}
|
||||
None => PhotocraftMcp::headless_with_workspace(automation_workspace(a)?),
|
||||
};
|
||||
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| e.to_string())?;
|
||||
rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod missing_font_warning_tests {
|
||||
use super::*;
|
||||
|
||||
fn invoke(args: &[&str]) -> (i32, String, String) {
|
||||
let mut output = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
|
||||
let code = run(&args, &mut output, &mut errors);
|
||||
(code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap())
|
||||
pub(crate) mod test_support {
|
||||
/// What [`crate::run`] returned and wrote.
|
||||
pub(crate) struct Invoke {
|
||||
pub(crate) code: i32,
|
||||
pub(crate) stdout: String,
|
||||
pub(crate) stderr: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_typeface_is_reported_by_run_info_and_convert() {
|
||||
let family = "DefinitelyMissingPhotoCraftTypeface1251";
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-font-warnings-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let native = folder.join("missing.pcraft");
|
||||
let png = folder.join("missing.png");
|
||||
let native_str = native.to_string_lossy().to_string();
|
||||
let png_str = png.to_string_lossy().to_string();
|
||||
let params = json!({"x": 6, "y": 38, "text": "Missing font warning", "font": family, "size": 20}).to_string();
|
||||
|
||||
let (code, stdout, stderr) = invoke(&[
|
||||
"run",
|
||||
"--new",
|
||||
r#"{"width":256,"height":96,"background":"white"}"#,
|
||||
"--cmd",
|
||||
"type.create",
|
||||
"--params",
|
||||
¶ms,
|
||||
"--cmd",
|
||||
"type.resolveMissingFonts",
|
||||
"--out",
|
||||
&native_str,
|
||||
]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert_eq!(stderr.matches(family).count(), 1, "multi-command runs should not repeat the same missing font warning");
|
||||
let commands: Vec<Value> = stdout.lines().map(|s| serde_json::from_str(s).unwrap()).collect();
|
||||
assert_eq!(commands.len(), 2, "{stdout}");
|
||||
assert!(commands[0]["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains(family))));
|
||||
assert!(commands[1].get("warnings").is_none(), "only newly detected missing fonts are reported");
|
||||
|
||||
let (code, stdout, stderr) = invoke(&["info", &native_str, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert!(info["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains(family))));
|
||||
assert!(stderr.is_empty(), "info puts warnings in JSON, not stderr");
|
||||
|
||||
let (code, _, stderr) = invoke(&["convert", &native_str, &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(stderr.contains(&format!("warning: font '{family}'")), "{stderr}");
|
||||
assert!(png.is_file());
|
||||
|
||||
// Even with no commands, run --out checks the opened document before export.
|
||||
let (code, stdout, stderr) = invoke(&["run", &native_str, "--out", &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(stdout.is_empty());
|
||||
assert_eq!(stderr.matches(family).count(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_reads_and_writes_openraster() {
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-ora-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let path = |name: &str| folder.join(name).to_string_lossy().to_string();
|
||||
let (native, ora, png) = (path("layers.pcraft"), path("layers.ora"), path("back.png"));
|
||||
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":16,"height":12}"#, "--cmd", "layer.new.layer", "--out", &native]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let (code, _, stderr) = invoke(&["convert", &native, &ora]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let (code, stdout, stderr) = invoke(&["info", &ora, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert_eq!(info["layers"].as_array().map(Vec::len), Some(2), "{info}");
|
||||
let (code, _, stderr) = invoke(&["convert", &ora, &png]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(is_input(std::path::Path::new(&ora)));
|
||||
// Krita documents are batch inputs too (import-only).
|
||||
for name in ["sketch.kra", "old.KRZ"] {
|
||||
std::fs::write(folder.join(name), b"").unwrap();
|
||||
assert!(is_input(&folder.join(name)), "{name}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_type_layers_do_not_produce_missing_font_warnings() {
|
||||
let folder = std::env::temp_dir().join(format!("photocraft-cli-no-font-warning-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let native = folder.join("blank.pcraft");
|
||||
let png = folder.join("blank.png");
|
||||
let native_str = native.to_string_lossy().to_string();
|
||||
let png_str = png.to_string_lossy().to_string();
|
||||
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":16,"height":16}"#, "--out", &native_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(!stderr.contains("font '"), "{stderr}");
|
||||
let (code, stdout, stderr) = invoke(&["info", &native_str, "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&stdout).unwrap();
|
||||
assert!(info["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap_or_default().contains("font '")));
|
||||
let (code, _, stderr) = invoke(&["convert", &native_str, &png_str]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert!(!stderr.contains("font '"), "{stderr}");
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod batch_action_set_tests {
|
||||
use super::*;
|
||||
|
||||
fn invoke(args: &[&str]) -> (i32, String, String) {
|
||||
let (mut output, mut errors) = (Vec::new(), Vec::new());
|
||||
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
|
||||
let code = run(&args, &mut output, &mut errors);
|
||||
(code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap())
|
||||
}
|
||||
|
||||
/// A batched action that plays another action of its set finds it in every file's session; a
|
||||
/// failure inside the called action fails the file, and a self-call stops instead of looping.
|
||||
#[test]
|
||||
fn batch_plays_an_action_that_calls_another_action_of_its_set() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
for name in ["a", "b"] {
|
||||
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("in/{name}.png"))]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
}
|
||||
let set = json!({"version": 1, "actions": [
|
||||
{"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}]]},
|
||||
{"name": "Rotate", "steps": [["image.imageRotation.90cw", {}]]},
|
||||
{"name": "Calls bad", "steps": [["actions.play", {"action": "Bad"}]]},
|
||||
{"name": "Bad", "steps": [["layer.delete", {"layer": 999_999}]]},
|
||||
{"name": "Loop", "steps": [["actions.play", {"action": "Loop"}]]},
|
||||
]});
|
||||
std::fs::write(dir.join("actions.json"), set.to_string()).unwrap();
|
||||
let batch = |action: &str| invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]);
|
||||
|
||||
let (code, stdout, stderr) = batch("Outer");
|
||||
assert_eq!(code, 0, "{stdout}{stderr}");
|
||||
for name in ["a", "b"] {
|
||||
let (code, info, stderr) = invoke(&["info", &path(&format!("Outer/{name}.png")), "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "rotated by the called action");
|
||||
}
|
||||
for action in ["Calls bad", "Loop"] {
|
||||
let (code, stdout, stderr) = batch(action);
|
||||
assert_ne!(code, 0, "{stdout}");
|
||||
assert_eq!(stderr.matches("FAIL").count(), 2, "{stderr}");
|
||||
assert!(!dir.join(action).join("a.png").exists(), "a file whose called action failed is not saved");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
pub(crate) fn invoke(args: &[&str]) -> Invoke {
|
||||
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
|
||||
let code = crate::run(args, &mut stdout, &mut stderr);
|
||||
Invoke { code, stdout: String::from_utf8(stdout).unwrap(), stderr: String::from_utf8(stderr).unwrap() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
fn main() {
|
||||
// `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must be a
|
||||
// usage error, not a panic before anything is printed (issue #1108).
|
||||
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
let code = photocraft_cli::run_os(&args, &mut std::io::stdout(), &mut std::io::stderr());
|
||||
// `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap,
|
||||
// not panic before anything is printed (issue #1108).
|
||||
let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr());
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use photocraft_io::ExportOptions;
|
||||
use serde_json::Value;
|
||||
use std::io::Write;
|
||||
|
||||
use crate::{Result, args::ExportArgs};
|
||||
|
||||
/// The `--format` family's options. A bad value never gets here: clap refused it.
|
||||
impl From<&ExportArgs> for ExportOptions {
|
||||
fn from(a: &ExportArgs) -> Self {
|
||||
// TIFF output is flat unless asked: scripted conversions keep predictable sizes.
|
||||
let mut o = ExportOptions { tiff_layers: a.tiff_layers, tga_bits: a.tga_bits, ..Default::default() };
|
||||
if let Some(q) = a.quality {
|
||||
o.encode.jpeg_quality = q;
|
||||
// Asking for a quality asks for a lossy WebP; the default WebP stays lossless.
|
||||
o.encode.webp_quality = q;
|
||||
o.encode.webp_lossless = false;
|
||||
}
|
||||
o.encode.dpx_bits = a.dpx_bits;
|
||||
if let Some(c) = a.tiff_compression {
|
||||
o.encode.tiff_compression = c;
|
||||
}
|
||||
if let Some(f) = a.jpeg_format {
|
||||
o.encode.jpeg_format = f;
|
||||
}
|
||||
if let Some(c) = a.dds_compression {
|
||||
o.encode.dds.compression = c;
|
||||
}
|
||||
o.encode.dds.mipmaps = a.dds_mipmaps;
|
||||
o
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn warn_all(err: &mut dyn Write, ws: &[String]) {
|
||||
for w in ws {
|
||||
let _ = writeln!(err, "warning: {w}");
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`print_json`] lays the JSON out.
|
||||
pub(crate) enum JsonStyle {
|
||||
Pretty,
|
||||
Compact,
|
||||
}
|
||||
|
||||
pub(crate) fn print_json(out: &mut dyn Write, v: &Value, style: JsonStyle) -> Result {
|
||||
let s = match style {
|
||||
JsonStyle::Pretty => serde_json::to_string_pretty(v),
|
||||
JsonStyle::Compact => serde_json::to_string(v),
|
||||
}?;
|
||||
Ok(writeln!(out, "{s}")?)
|
||||
}
|
||||
@@ -1,755 +0,0 @@
|
||||
//! Process-level tests of the `photocraft-cli` binary.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn bin() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_photocraft-cli"))
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pc-cli-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn write_png(path: &Path, w: u32, h: u32, seed: u8) {
|
||||
let data: Vec<u8> = (0..w * h * 4).map(|i| (i as u8).wrapping_mul(seed).wrapping_add(seed)).collect();
|
||||
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, data).unwrap();
|
||||
std::fs::write(path, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
fn ok(cmd: &mut Command) -> (String, String) {
|
||||
let o = cmd.output().unwrap();
|
||||
let (out, err) = (String::from_utf8_lossy(&o.stdout).into_owned(), String::from_utf8_lossy(&o.stderr).into_owned());
|
||||
assert!(o.status.success(), "exit {:?}\nstdout: {out}\nstderr: {err}", o.status);
|
||||
(out, err)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_and_unknown_command() {
|
||||
let o = bin().output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("USAGE"));
|
||||
let o = bin().arg("frobnicate").output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
let (out, _) = ok(bin().arg("--help"));
|
||||
assert!(out.contains("convert"));
|
||||
let (out, _) = ok(bin().arg("--version"));
|
||||
assert!(out.starts_with("photocraft-cli "));
|
||||
}
|
||||
|
||||
/// #423: `<subcommand> --help` and `-h` print usage and return at once (no inputs read, no files
|
||||
/// written, no server started), whatever else is on the line.
|
||||
#[test]
|
||||
fn every_subcommand_answers_help() {
|
||||
let d = tmp("help");
|
||||
for sub in ["convert", "info", "run", "batch", "droplet", "commands", "mcp", "serve"] {
|
||||
for help in ["--help", "-h"] {
|
||||
let o = bin().current_dir(&d).arg(sub).arg(help).arg("--out").arg("x.png").stdin(Stdio::null()).output().unwrap();
|
||||
let out = String::from_utf8_lossy(&o.stdout);
|
||||
assert_eq!(o.status.code(), Some(0), "{sub} {help}: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out.contains("USAGE") && out.contains("photocraft-cli batch"), "{sub} {help}: {out}");
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "help wrote nothing");
|
||||
}
|
||||
|
||||
/// #423: a flag the subcommand doesn't take is a usage error naming it, before any work.
|
||||
#[test]
|
||||
fn unknown_flags_are_usage_errors() {
|
||||
let d = tmp("flags");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
let actions = d.join("actions.json");
|
||||
std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap();
|
||||
let out_dir = d.join("out");
|
||||
let fails = |cmd: &mut Command, flag: &str| {
|
||||
let o = cmd.output().unwrap();
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert_eq!(o.status.code(), Some(2), "{err}");
|
||||
assert!(err.contains(&format!("unknown flag {flag}")), "{err}");
|
||||
};
|
||||
for typo in [&["--fromat", "jpg"][..], &["--fromat=jpg"][..]] {
|
||||
fails(bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out_dir).args(typo), "--fromat");
|
||||
assert!(!out_dir.exists(), "nothing written");
|
||||
}
|
||||
let x = d.join("x.png");
|
||||
fails(bin().arg("run").arg(input.join("a.png")).args(["--cmd", "image.adjustments.invert", "--param", "{}", "--out"]).arg(&x), "--param");
|
||||
assert!(!x.exists());
|
||||
// A flag one subcommand takes is still unknown to another; a bare flag takes no value.
|
||||
fails(bin().args(["info", "--json"]).arg(input.join("a.png")), "--json");
|
||||
let o = bin().args(["commands", "--json=yes"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("--json takes no value"));
|
||||
// Every flag still works in both forms.
|
||||
let (out, _) = ok(bin().args(["commands", "--json", "--filter=gaussian"]));
|
||||
assert!(out.contains("filter.blur.gaussianBlur"), "{out}");
|
||||
// The Elliptical Marquee is a `select.rect` option, found by its keywords (#5060).
|
||||
for needle in ["ellipse", "marquee"] {
|
||||
let (out, _) = ok(bin().args(["commands", "--filter", needle]));
|
||||
assert!(out.contains("select.rect"), "{needle}: {out}");
|
||||
}
|
||||
ok(bin().args(["batch", "--actions"]).arg(&actions).arg(format!("--in={}", input.display())).arg("--out").arg(&out_dir).args([
|
||||
"--format=jpg",
|
||||
"--quality",
|
||||
"80",
|
||||
]));
|
||||
assert!(out_dir.join("a.jpg").exists());
|
||||
let (out, _) = ok(bin().arg("info").arg(input.join("a.png")).arg("--compact"));
|
||||
assert!(!out.trim().contains('\n'), "compact JSON is one line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_png_pcraft_png_is_lossless() {
|
||||
let d = tmp("convert");
|
||||
let (a, b, c) = (d.join("a.png"), d.join("b.pcraft"), d.join("c.png"));
|
||||
write_png(&a, 37, 23, 7);
|
||||
ok(bin().args(["convert"]).arg(&a).arg(&b));
|
||||
assert!(photocraft_format::is_pcraft(&std::fs::read(&b).unwrap()));
|
||||
ok(bin().args(["convert"]).arg(&b).arg(&c));
|
||||
let x = photocraft_codecs::decode(&std::fs::read(&a).unwrap()).unwrap();
|
||||
let y = photocraft_codecs::decode(&std::fs::read(&c).unwrap()).unwrap();
|
||||
assert_eq!(x.to_rgba8(), y.to_rgba8());
|
||||
// Format override and lossy warning path.
|
||||
ok(bin().args(["convert"]).arg(&a).arg(d.join("out.bin")).args(["--format", "jpg", "--quality", "60"]));
|
||||
assert!(photocraft_codecs::detect(&std::fs::read(d.join("out.bin")).unwrap()) == Some(photocraft_codecs::Format::Jpeg));
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_errors() {
|
||||
let d = tmp("converr");
|
||||
let o = bin().args(["convert", "/missing/in.png"]).arg(d.join("x.png")).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let o = bin().args(["convert", "only-one"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_prints_layer_tree_json() {
|
||||
let d = tmp("info");
|
||||
let a = d.join("a.png");
|
||||
write_png(&a, 10, 6, 3);
|
||||
let (out, _) = ok(bin().arg("info").arg(&a));
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(v["width"], 10);
|
||||
assert_eq!(v["height"], 6);
|
||||
// An RGBA PNG opens as a normal "Layer 0", not the locked Background (as in Photoshop).
|
||||
assert_eq!(v["layers"][0]["name"], "Layer 0");
|
||||
assert!(v.get("history").is_none());
|
||||
let (out, _) = ok(bin().arg("info").arg(&a).arg("--compact"));
|
||||
assert_eq!(out.trim().lines().count(), 1);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
/// #518, #523: a truncated JPEG and an animated GIF open, but `info` lists why the image is
|
||||
/// incomplete and `convert` prints it on stderr (and still succeeds); complete files stay quiet.
|
||||
#[test]
|
||||
fn info_and_convert_report_decode_warnings() {
|
||||
let d = tmp("decode-warnings");
|
||||
let noise: Vec<u8> = (0..64 * 48 * 3).map(|i: u32| (i.wrapping_mul(7919) % 251) as u8).collect();
|
||||
let img = photocraft_codecs::Image::from_u8(64, 48, photocraft_codecs::ChannelLayout::Rgb, noise).unwrap();
|
||||
let jpeg = photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).unwrap();
|
||||
// Three 1x1 frames.
|
||||
let mut gif = b"GIF89a\x01\0\x01\0\x80\0\0\0\0\0\xFF\xFF\xFF".to_vec();
|
||||
for _ in 0..3 {
|
||||
gif.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");
|
||||
}
|
||||
gif.push(0x3B);
|
||||
let cases = [
|
||||
("whole.jpg", &jpeg[..], None),
|
||||
("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing")),
|
||||
("anim.gif", &gif[..], Some("only the first of 3 frames was imported")),
|
||||
];
|
||||
for (name, bytes, warning) in cases {
|
||||
let file = d.join(name);
|
||||
std::fs::write(&file, bytes).unwrap();
|
||||
let (out, _) = ok(bin().arg("info").arg(&file).arg("--compact"));
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(v["warnings"], json!(warning.into_iter().collect::<Vec<_>>()), "{name}");
|
||||
let (_, err) = ok(bin().arg("convert").arg(&file).arg(d.join(format!("{name}.png"))));
|
||||
assert_eq!(err.trim(), warning.map(|w| format!("warning: {w}")).unwrap_or_default(), "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_commands_and_save() {
|
||||
let d = tmp("run");
|
||||
let out_pc = d.join("r.pcraft");
|
||||
let (out, _) = ok(bin()
|
||||
.args(["run", "--new", r#"{"width":40,"height":30,"name":"Run"}"#])
|
||||
.args(["--cmd", "layer.new.layer", "--params", r#"{"name":"Ink"}"#])
|
||||
.args(["--cmd", "paint.stroke", "--params", r##"{"points":[[2,2,1],[30,20,1]],"size":5,"color":"#00ff00"}"##])
|
||||
.args(["--cmd", "document.inspect"])
|
||||
.arg("--out")
|
||||
.arg(&out_pc));
|
||||
let lines: Vec<Value> = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert_eq!(lines[2]["command"], "document.inspect");
|
||||
assert_eq!(lines[2]["result"]["name"], "Run");
|
||||
let (info, _) = ok(bin().arg("info").arg(&out_pc));
|
||||
let v: Value = serde_json::from_str(&info).unwrap();
|
||||
// Saving a native document gives the reopened bundle its output filename.
|
||||
assert_eq!(v["name"], "r.pcraft");
|
||||
let names: Vec<&str> = v["layers"].as_array().unwrap().iter().filter_map(|l| l["name"].as_str()).collect();
|
||||
assert_eq!(names, ["Ink", "Background"]);
|
||||
// Continue from the saved file and export PNG.
|
||||
let png = d.join("r.png");
|
||||
ok(bin().arg("run").arg(&out_pc).args(["--cmd", "layer.new.layer"]).arg("--out").arg(&png));
|
||||
assert_eq!(photocraft_codecs::decode(&std::fs::read(&png).unwrap()).unwrap().dimensions(), (40, 30));
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_stops_after_failed_action_without_exporting() {
|
||||
let d = tmp("run-failed-action");
|
||||
let out = d.join("result.png");
|
||||
let result = bin()
|
||||
.args(["run", "--new", r#"{"width":8,"height":8}"#])
|
||||
.args(["--cmd", "layer.new.layer"])
|
||||
.args(["--cmd", "actions.record", "--params", r#"{"name":"Delete"}"#])
|
||||
.args(["--cmd", "layer.delete", "--cmd", "actions.stop"])
|
||||
// The recorded deletion succeeded with two layers; replay cannot delete the last one.
|
||||
.args(["--cmd", "actions.play", "--params", r#"{"action":"Delete"}"#])
|
||||
.args(["--cmd", "document.inspect", "--out"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
let error = String::from_utf8_lossy(&result.stderr);
|
||||
assert_eq!(result.status.code(), Some(1), "stdout: {}\nstderr: {error}", String::from_utf8_lossy(&result.stdout));
|
||||
assert!(error.contains("actions.play") && error.contains("Delete") && error.contains("step 1"), "{error}");
|
||||
let rows: Vec<Value> = String::from_utf8_lossy(&result.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert!(rows.iter().all(|row| row["command"] != "document.inspect"), "later commands must not run");
|
||||
assert!(!out.exists(), "a failed action must not export a partial result");
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_continues_after_successful_action_and_exports() {
|
||||
let d = tmp("run-successful-action");
|
||||
let out = d.join("result.png");
|
||||
let (stdout, _) = ok(bin()
|
||||
.args(["run", "--new", r#"{"width":8,"height":8}"#])
|
||||
.args(["--cmd", "actions.record", "--params", r#"{"name":"Add"}"#])
|
||||
.args(["--cmd", "layer.new.layer", "--cmd", "actions.stop"])
|
||||
.args(["--cmd", "actions.play", "--params", r#"{"action":"Add"}"#])
|
||||
.args(["--cmd", "document.inspect", "--out"])
|
||||
.arg(&out));
|
||||
let rows: Vec<Value> = stdout.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
let playback = rows.iter().find(|row| row["command"] == "actions.play").unwrap();
|
||||
assert_eq!(playback["result"]["ran"], 1);
|
||||
assert!(playback["result"].get("failed").is_none());
|
||||
assert!(rows.iter().any(|row| row["command"] == "document.inspect"));
|
||||
assert!(out.is_file());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_errors() {
|
||||
let o = bin().args(["run", "--new", "{}", "--cmd", "no.such"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown command"));
|
||||
let o = bin().args(["run", "--new", "{}", "--params", "{}"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let o = bin().args(["run", "--new", "{", "--cmd", "x"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
// Params must be a JSON object, for `--new` and for each `--params`.
|
||||
let o = bin().args(["run", "--new", "[3]", "--cmd", "layer.new.layer"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let e = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(e.contains("--new") && e.contains("must be a JSON object"), "{e}");
|
||||
let o = bin().args(["run", "--new", "{}", "--cmd", "layer.new.layer", "--params", "\"x\""]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let e = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(e.contains("layer.new.layer") && e.contains("must be a JSON object"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_invalid_filter_parameters_without_exporting() {
|
||||
let d = tmp("invalid-filter-params");
|
||||
let out = d.join("result.png");
|
||||
for (params, key) in [(r#"{"radius":"big"}"#, "radius"), (r#"{"radus":3}"#, "radus"), (r#"{"radius":5000}"#, "radius"), (r#"{"radius":-4}"#, "radius")] {
|
||||
let result = bin()
|
||||
.args(["run", "--new", r#"{"width":8,"height":8}"#, "--cmd", "filter.blur.gaussianBlur", "--params", params, "--out"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(result.status.code(), Some(1));
|
||||
let error = String::from_utf8_lossy(&result.stderr);
|
||||
assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_applies_actions_to_directory() {
|
||||
let d = tmp("batch");
|
||||
let (inp, outp) = (d.join("in"), d.join("out"));
|
||||
std::fs::create_dir_all(&inp).unwrap();
|
||||
write_png(&inp.join("one.png"), 12, 8, 1);
|
||||
write_png(&inp.join("two.png"), 9, 9, 2);
|
||||
std::fs::write(inp.join("notes.txt"), "ignored").unwrap();
|
||||
let actions = d.join("actions.json");
|
||||
std::fs::write(&actions, json!([{"command": "layer.new.layer", "params": {"name": "Batch"}}]).to_string()).unwrap();
|
||||
let (out, _) = ok(bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&inp).arg("--out").arg(&outp).args(["--format", "pcraft"]));
|
||||
assert!(out.contains("2 succeeded, 0 failed"), "{out}");
|
||||
for n in ["one", "two"] {
|
||||
let (info, _) = ok(bin().arg("info").arg(outp.join(format!("{n}.pcraft"))));
|
||||
let v: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!(v["layers"][0]["name"], "Batch");
|
||||
}
|
||||
// A failing action reports and exits 1.
|
||||
std::fs::write(&actions, r#"{"actions":[{"id":"no.such.command"}]}"#).unwrap();
|
||||
let o = bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&inp).arg("--out").arg(&outp).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("FAIL"));
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_skips_recorded_view_and_save_steps() {
|
||||
let d = tmp("batch-shell-steps");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
let source = input.join("a.png");
|
||||
write_png(&source, 12, 8, 3);
|
||||
let original = std::fs::read(&source).unwrap();
|
||||
let recorded_save = d.join("recorded-save.psd");
|
||||
let mut cases = Vec::new();
|
||||
for (name, id) in [("zoom-in", "view.zoomIn"), ("zoom-out", "view.zoomOut"), ("fit", "view.fitOnScreen"), ("actual-pixels", "view.actualPixels")] {
|
||||
cases.push((name, json!([[id, {}], ["image.imageRotation.90cw", {}]]).to_string()));
|
||||
}
|
||||
cases.push(("save", json!([["file.save", {}], ["image.imageRotation.90cw", {}]]).to_string()));
|
||||
cases.push(("save-as", json!([["file.saveAs", {"path": recorded_save.to_string_lossy()}], ["image.imageRotation.90cw", {}]]).to_string()));
|
||||
|
||||
for (name, actions) in cases {
|
||||
let o = batch_with(&d, &input, name, &actions, &[]);
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
|
||||
assert!(o.status.success(), "{name}: {stdout}\n{stderr}");
|
||||
assert!(stdout.contains("1 succeeded, 0 failed"), "{name}: {stdout}");
|
||||
let output = d.join(name).join("a.png");
|
||||
let (info, _) = ok(bin().arg("info").arg(&output));
|
||||
let info: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(8), Some(12)), "{name}: {info}");
|
||||
assert_eq!(std::fs::read(&source).unwrap(), original, "{name} changed its input");
|
||||
assert!(!recorded_save.exists(), "{name} wrote the recorded Save As path");
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_actions_formats() {
|
||||
let a = photocraft_cli::parse_actions(r#"[{"command":"a","params":{"x":1}},{"id":"b"}]"#).unwrap();
|
||||
assert_eq!(a, vec![("a".to_string(), json!({"x":1})), ("b".to_string(), json!({}))]);
|
||||
assert!(photocraft_cli::parse_actions(r#"{"actions":[{"command":"c"}]}"#).unwrap().len() == 1);
|
||||
assert!(photocraft_cli::parse_actions(r#"[{"params":{}}]"#).is_err());
|
||||
assert!(photocraft_cli::parse_actions("7").is_err());
|
||||
// #489: the step shapes a recorded action and a droplet store, bare or wrapped.
|
||||
let want = vec![("a".to_string(), json!({"x":1})), ("b".to_string(), json!({}))];
|
||||
for text in [
|
||||
r#"[["a",{"x":1}],["b"]]"#,
|
||||
r#"[["a",{"x":1}],"b"]"#,
|
||||
r#"{"steps":[["a",{"x":1}],["b",{}]]}"#,
|
||||
r#"{"photocraftDroplet":1,"action":{"steps":[["a",{"x":1}],{"command":"b"}]}}"#,
|
||||
r#"{"actions":[["a",{"x":1}],["b",{}]]}"#,
|
||||
] {
|
||||
assert_eq!(photocraft_cli::parse_actions(text).unwrap(), want, "{text}");
|
||||
}
|
||||
for text in ["[42]", "[[]]", "[[7,{}]]", r#"{"name":"x"}"#] {
|
||||
assert!(photocraft_cli::parse_actions(text).is_err(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `batch` on `input` with `actions` (saved as `<name>.json`), writing to the folder `<d>/<name>`.
|
||||
fn batch_with(d: &Path, input: &Path, name: &str, actions: &str, extra: &[&str]) -> std::process::Output {
|
||||
let file = d.join(format!("{name}.json"));
|
||||
std::fs::write(&file, actions).unwrap();
|
||||
bin().args(["batch", "--actions"]).arg(&file).arg("--in").arg(input).arg("--out").arg(d.join(name)).args(extra).output().unwrap()
|
||||
}
|
||||
|
||||
/// #489: `batch --actions` takes `[id, params]` steps and a droplet's steps, with the same results
|
||||
/// as the object form; a malformed step fails before anything is written.
|
||||
#[test]
|
||||
fn batch_accepts_recorded_action_steps() {
|
||||
let d = tmp("batch-steps");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
write_png(&input.join("b.png"), 6, 5, 9);
|
||||
let shapes = [
|
||||
("objects", r#"[{"command":"image.adjustments.invert"}]"#),
|
||||
("pairs", r#"[["image.adjustments.invert",{}]]"#),
|
||||
("ids", r#"["image.adjustments.invert"]"#),
|
||||
("droplet", r#"{"photocraftDroplet":1,"action":{"steps":[["image.adjustments.invert",{}]]}}"#),
|
||||
];
|
||||
for (name, actions) in shapes {
|
||||
let o = batch_with(&d, &input, name, actions, &[]);
|
||||
assert!(o.status.success(), "{name}: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(String::from_utf8_lossy(&o.stdout).contains("2 succeeded, 0 failed"), "{name}");
|
||||
for f in ["a.png", "b.png"] {
|
||||
assert_eq!(std::fs::read(d.join(name).join(f)).unwrap(), std::fs::read(d.join("objects").join(f)).unwrap(), "{name}/{f}");
|
||||
}
|
||||
}
|
||||
let o = batch_with(&d, &input, "bad", "[42]", &[]);
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(!d.join("bad").exists(), "nothing written");
|
||||
}
|
||||
|
||||
/// #490: a leading dot on `--format` doesn't double the dot in output names.
|
||||
#[test]
|
||||
fn batch_format_with_leading_dot() {
|
||||
let d = tmp("batch-dot");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
write_png(&input.join("b.png"), 6, 5, 9);
|
||||
let invert = r#"[{"command":"image.adjustments.invert"}]"#;
|
||||
for (name, format) in [("dot", ".jpg"), ("plain", "jpg")] {
|
||||
let o = batch_with(&d, &input, name, invert, &["--format", format]);
|
||||
assert!(o.status.success(), "{format}: {}", String::from_utf8_lossy(&o.stderr));
|
||||
let mut names: Vec<String> = std::fs::read_dir(d.join(name)).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["a.jpg", "b.jpg"], "{format}");
|
||||
assert_eq!(photocraft_codecs::detect(&std::fs::read(d.join(name).join("a.jpg")).unwrap()), Some(photocraft_codecs::Format::Jpeg));
|
||||
}
|
||||
}
|
||||
|
||||
/// #491: `--quality` outside 1-100 is an error for every subcommand, whatever the number's size,
|
||||
/// and nothing is written.
|
||||
#[test]
|
||||
fn quality_outside_1_to_100_is_refused() {
|
||||
let d = tmp("quality");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
let a = input.join("a.png");
|
||||
write_png(&a, 8, 4, 3);
|
||||
let invert = r#"[{"command":"image.adjustments.invert"}]"#;
|
||||
for q in ["0", "101", "255", "256", "1000", "-1", "abc", "50.5", ""] {
|
||||
let out = d.join("q.jpg");
|
||||
let (mut convert, mut run) = (bin(), bin());
|
||||
convert.arg("convert").arg(&a).arg(&out).args(["--quality", q]);
|
||||
run.arg("run").arg(&a).args(["--cmd", "image.adjustments.invert", "--out"]).arg(&out).args(["--quality", q]);
|
||||
for cmd in [&mut convert, &mut run] {
|
||||
let o = cmd.output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1), "--quality {q}");
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --quality `{q}`: expected a whole number from 1 to 100")), "--quality {q}");
|
||||
assert!(!out.exists(), "--quality {q} wrote a file");
|
||||
}
|
||||
let o = batch_with(&d, &input, "qb", invert, &["--format", "jpg", "--quality", q]);
|
||||
assert_eq!(o.status.code(), Some(1), "batch --quality {q}");
|
||||
assert!(!d.join("qb").exists(), "batch --quality {q} wrote a folder");
|
||||
}
|
||||
// The documented range still encodes, lower quality making a smaller file.
|
||||
let sizes: Vec<usize> = ["1", "50", "100"]
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let out = d.join(format!("q{q}.jpg"));
|
||||
ok(bin().arg("convert").arg(&a).arg(&out).args(["--quality", q]));
|
||||
std::fs::read(out).unwrap().len()
|
||||
})
|
||||
.collect();
|
||||
assert!(sizes[0] <= sizes[1] && sizes[1] <= sizes[2], "{sizes:?}");
|
||||
}
|
||||
|
||||
/// DPX converts both ways, `info` reports its size, mode and depth, and `--dpx-bits` picks the
|
||||
/// bits per sample (byte 803 of the header); anything but 8, 10, 12 or 16 is refused (#1049).
|
||||
#[test]
|
||||
fn dpx_converts_both_ways_with_the_bits_asked_for() {
|
||||
let d = tmp("dpx");
|
||||
let a = d.join("a.png");
|
||||
write_png(&a, 8, 4, 3);
|
||||
for (bits, want) in [(None, 8), (Some("10"), 10), (Some("12"), 12), (Some("16"), 16)] {
|
||||
let out = d.join("a.dpx");
|
||||
let mut convert = bin();
|
||||
convert.arg("convert").arg(&a).arg(&out);
|
||||
if let Some(b) = bits {
|
||||
convert.args(["--dpx-bits", b]);
|
||||
}
|
||||
ok(&mut convert);
|
||||
let bytes = std::fs::read(&out).unwrap();
|
||||
assert_eq!((&bytes[..4], bytes[803]), (&b"SDPX"[..], want), "--dpx-bits {bits:?}");
|
||||
}
|
||||
let (info, _) = ok(bin().arg("info").arg(d.join("a.dpx")).arg("--compact"));
|
||||
let v: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((v["width"].as_u64(), v["height"].as_u64()), (Some(8), Some(4)), "{v}");
|
||||
assert!(info.contains("16") && info.to_lowercase().contains("rgb"), "{info}");
|
||||
let back = d.join("back.png");
|
||||
ok(bin().arg("convert").arg(d.join("a.dpx")).arg(&back));
|
||||
assert!(back.exists());
|
||||
for bad in ["24", "0", "abc"] {
|
||||
let out = d.join("bad.dpx");
|
||||
let o = bin().arg("convert").arg(&a).arg(&out).args(["--dpx-bits", bad]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1), "--dpx-bits {bad}");
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --dpx-bits `{bad}`: expected 8, 10, 12 or 16")), "--dpx-bits {bad}");
|
||||
assert!(!out.exists(), "--dpx-bits {bad} wrote a file");
|
||||
}
|
||||
}
|
||||
|
||||
/// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is
|
||||
/// refused and nothing is written.
|
||||
#[test]
|
||||
fn tga_bits_choose_the_targa_depth() {
|
||||
let d = tmp("tga-bits");
|
||||
let a = d.join("a.png");
|
||||
write_png(&a, 8, 4, 3);
|
||||
for (bits, want) in [(None, 32), (Some("24"), 24), (Some("32"), 32)] {
|
||||
let out = d.join("a.tga");
|
||||
let mut convert = bin();
|
||||
convert.arg("convert").arg(&a).arg(&out);
|
||||
if let Some(b) = bits {
|
||||
convert.args(["--tga-bits", b]);
|
||||
}
|
||||
ok(&mut convert);
|
||||
assert_eq!(std::fs::read(&out).unwrap()[16], want, "--tga-bits {bits:?}");
|
||||
}
|
||||
for bad in ["16", "0", "abc", ""] {
|
||||
let out = d.join("bad.tga");
|
||||
let o = bin().arg("convert").arg(&a).arg(&out).args(["--tga-bits", bad]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(1), "--tga-bits {bad}");
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --tga-bits `{bad}`: expected 24 or 32")), "--tga-bits {bad}");
|
||||
assert!(!out.exists(), "--tga-bits {bad} wrote a file");
|
||||
}
|
||||
}
|
||||
|
||||
/// #492: an `--out` folder that is the `--in` folder, however it is spelt, is refused before
|
||||
/// anything is written, unless `--in-place` asks for it.
|
||||
#[test]
|
||||
fn batch_refuses_to_write_over_its_inputs() {
|
||||
let d = tmp("batch-in-place");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
let img = photocraft_codecs::Image::from_u8(8, 4, photocraft_codecs::ChannelLayout::Rgb, vec![90; 96]).unwrap();
|
||||
std::fs::write(input.join("a.tif"), photocraft_codecs::encode(&img, photocraft_codecs::Format::Tiff, &Default::default()).unwrap()).unwrap();
|
||||
let actions = d.join("actions.json");
|
||||
std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap();
|
||||
let snapshot = || {
|
||||
let mut files: Vec<(PathBuf, Vec<u8>)> =
|
||||
std::fs::read_dir(&input).unwrap().map(|e| e.unwrap().path()).map(|p| (p.clone(), std::fs::read(p).unwrap())).collect();
|
||||
files.sort();
|
||||
files
|
||||
};
|
||||
let before = snapshot();
|
||||
let batch = |out: &Path, extra: &[&str]| {
|
||||
bin().current_dir(&d).args(["batch", "--actions"]).arg(&actions).args(["--in", "in", "--out"]).arg(out).args(extra).output().unwrap()
|
||||
};
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&input, d.join("link")).unwrap();
|
||||
let link = cfg!(unix).then(|| PathBuf::from("link"));
|
||||
for out in [PathBuf::from("in"), PathBuf::from("./in/"), input.clone(), input.join(".")].iter().chain(&link) {
|
||||
for extra in [&[][..], &["--format", "tif"][..]] {
|
||||
let o = batch(out, extra);
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert_eq!(o.status.code(), Some(1), "--out {} {extra:?}: {err}", out.display());
|
||||
assert!(err.contains("is the --in folder") && err.contains("--in-place"), "{err}");
|
||||
assert_eq!(snapshot(), before, "--out {} {extra:?} changed the originals", out.display());
|
||||
}
|
||||
}
|
||||
// A separate folder runs as before, leaving the originals alone.
|
||||
let (out, _) = ok(bin().current_dir(&d).args(["batch", "--actions"]).arg(&actions).args(["--in", "in", "--out", "out"]));
|
||||
assert!(out.contains("2 succeeded, 0 failed"), "{out}");
|
||||
assert_eq!(snapshot(), before);
|
||||
// `--in-place` opts in: each result replaces its original.
|
||||
let o = batch(Path::new("in"), &["--in-place"]);
|
||||
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
let after = snapshot();
|
||||
assert_eq!(after.len(), 2);
|
||||
assert!(after.iter().zip(&before).all(|(a, b)| a.0 == b.0 && a.1 != b.1), "both inputs replaced");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_listing() {
|
||||
let (out, _) = ok(bin().arg("commands"));
|
||||
assert!(out.contains("file.new"));
|
||||
let (out, _) = ok(bin().args(["commands", "--json", "--filter", "layer.new"]));
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert!(
|
||||
v.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|c| { c["id"].as_str().unwrap().contains("layer.new") || c["label"].as_str().unwrap().to_lowercase().contains("layer.new") })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_process_run_matches_binary() {
|
||||
let mut out = Vec::new();
|
||||
let mut err = Vec::new();
|
||||
let code = photocraft_cli::run(&["commands".into(), "--filter".into(), "file.new".into()], &mut out, &mut err);
|
||||
assert_eq!(code, 0);
|
||||
assert!(String::from_utf8(out).unwrap().contains("file.new"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_stdio_handshake_and_tool_call() {
|
||||
let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let mut stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut send = |v: Value| {
|
||||
writeln!(stdin, "{v}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
};
|
||||
let mut recv = |id: u64| -> Value {
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed");
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
if v["id"] == id {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
};
|
||||
send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
|
||||
"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}));
|
||||
let init = recv(1);
|
||||
assert_eq!(init["result"]["serverInfo"]["name"], "photocraft", "{init}");
|
||||
send(json!({"jsonrpc":"2.0","method":"notifications/initialized"}));
|
||||
send(json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
|
||||
let tools = recv(2);
|
||||
let names: Vec<&str> = tools["result"]["tools"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
|
||||
assert!(names.contains(&"command_run") && names.contains(&"doc_render_preview"), "{names:?}");
|
||||
send(json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"doc_new","arguments":{"width":8,"height":8}}}));
|
||||
let r = recv(3);
|
||||
assert_ne!(r["result"]["isError"], true, "{r}");
|
||||
send(json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"doc_render_preview","arguments":{}}}));
|
||||
let r = recv(4);
|
||||
assert_eq!(r["result"]["content"][0]["type"], "image", "{r}");
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// `--format` mapping two inputs to one name fails the second instead of overwriting the first (#420).
|
||||
#[test]
|
||||
fn batch_fails_inputs_that_share_an_output_name() {
|
||||
let d = tmp("batch-collide");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
// Same stem in other formats; `A.tif` differs only in case.
|
||||
let img = photocraft_codecs::Image::from_u8(8, 4, photocraft_codecs::ChannelLayout::Rgb, vec![90; 96]).unwrap();
|
||||
for (name, format) in [("a.bmp", photocraft_codecs::Format::Bmp), ("A.tif", photocraft_codecs::Format::Tiff)] {
|
||||
std::fs::write(input.join(name), photocraft_codecs::encode(&img, format, &Default::default()).unwrap()).unwrap();
|
||||
}
|
||||
let actions = d.join("actions.json");
|
||||
std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap();
|
||||
let out_dir = d.join("out");
|
||||
let o = bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out_dir).args(["--format", "png"]).output().unwrap();
|
||||
let (out, err) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
|
||||
assert!(
|
||||
!o.status.success(),
|
||||
"a lost result must fail the run
|
||||
{out}
|
||||
{err}"
|
||||
);
|
||||
assert!(out.contains("1 succeeded, 2 failed"), "{out}");
|
||||
assert_eq!(err.matches("not written").count(), 2, "{err}");
|
||||
assert_eq!(std::fs::read_dir(&out_dir).unwrap().count(), 1);
|
||||
// Keeping each file's format, every input gets its own output.
|
||||
let out_dir = d.join("same");
|
||||
let (out, _) = ok(bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out_dir));
|
||||
assert!(out.contains("3 succeeded, 0 failed"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn droplet_runs_an_action_on_files() {
|
||||
let d = tmp("droplet");
|
||||
write_png(&d.join("a.png"), 8, 4, 3);
|
||||
write_png(&d.join("b.png"), 6, 2, 5);
|
||||
let droplet = d.join("rot.pcdroplet");
|
||||
std::fs::write(
|
||||
&droplet,
|
||||
json!({"photocraftDroplet": 1, "name": "rot", "action": {"steps": [["image.imageRotation.90cw", {}]]}, "options": {"format": "png"}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let out_dir = d.join("out");
|
||||
let (out, _) = ok(bin().arg("droplet").arg(&droplet).arg(d.join("a.png")).arg(d.join("b.png")).arg("--out").arg(&out_dir));
|
||||
assert_eq!(out.lines().filter(|l| l.starts_with("ok")).count(), 2, "{out}");
|
||||
let img = photocraft_codecs::decode(&std::fs::read(out_dir.join("a.png")).unwrap()).unwrap();
|
||||
assert_eq!(img.dimensions(), (4, 8));
|
||||
let o = bin().arg("droplet").arg(d.join("a.png")).arg(d.join("b.png")).output().unwrap();
|
||||
assert!(!o.status.success(), "not a droplet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiff_output_is_flat_unless_tiff_layers_is_given() {
|
||||
let d = tmp("tiff-layers");
|
||||
let layer_count = |path: &std::path::Path| -> usize {
|
||||
let (info, _) = ok(bin().arg("info").arg(path));
|
||||
let v: Value = serde_json::from_str(&info).unwrap();
|
||||
v["layers"].as_array().unwrap().len()
|
||||
};
|
||||
for (name, flag, layers) in [("flat.tif", None, 1), ("layered.tif", Some("--tiff-layers"), 2)] {
|
||||
let out = d.join(name);
|
||||
let mut cmd = bin();
|
||||
cmd.args(["run", "--new", r#"{"width":16,"height":16}"#]).args(["--cmd", "layer.new.layer", "--params", r#"{"name":"Ink"}"#]);
|
||||
if let Some(flag) = flag {
|
||||
cmd.arg(flag);
|
||||
}
|
||||
ok(cmd.arg("--out").arg(&out));
|
||||
assert_eq!(layer_count(&out), layers, "{name}");
|
||||
}
|
||||
// convert honours the same flag.
|
||||
let src = d.join("layered.tif");
|
||||
let flat = d.join("converted.tif");
|
||||
ok(bin().arg("convert").arg(&src).arg(&flat));
|
||||
assert_eq!(layer_count(&flat), 1);
|
||||
let kept = d.join("kept.tif");
|
||||
ok(bin().arg("convert").arg(&src).arg(&kept).arg("--tiff-layers"));
|
||||
assert_eq!(layer_count(&kept), 2);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
/// Issue #1108: a non-Unicode argument (a Latin-1 file name on Linux) used to panic in
|
||||
/// `std::env::args()` before anything was printed. It is a usage error naming the argument.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_non_unicode_argument_is_a_usage_error_not_a_panic() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let name = std::ffi::OsStr::from_bytes(b"caf\xe9.png");
|
||||
for args in [vec![std::ffi::OsStr::new("info"), name], vec![std::ffi::OsStr::new("convert"), name, std::ffi::OsStr::new("out.png")]] {
|
||||
let o = bin().args(&args).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert_eq!(o.status.code(), Some(2), "{err}");
|
||||
assert!(err.contains("argument 2 is not valid Unicode") && err.contains("caf\u{fffd}.png"), "{err}");
|
||||
assert!(!err.contains("panicked"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `batch --actions set.atn`: a Photoshop Actions file plays like an Actions set, and its steps
|
||||
/// PhotoCraft can't play are warned about up front.
|
||||
#[test]
|
||||
fn batch_plays_a_photoshop_actions_file() {
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
let d = tmp("atn");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
let invert = Action::new("Negative", vec![("image.adjustments.invert".into(), json!({})), ("select.all".into(), json!({}))]);
|
||||
let odd = Action::new("Odd", vec![(photocraft_engine::atn_cmds::PHOTOSHOP_STEP.into(), json!({"event": "syntheticFill", "name": "Generative Fill"}))]);
|
||||
let (bytes, skipped) = photocraft_engine::atn_cmds::export("Set", &[&invert, &odd], &[], false).unwrap();
|
||||
assert!(skipped.is_empty());
|
||||
let atn = d.join("Set.atn");
|
||||
std::fs::write(&atn, bytes).unwrap();
|
||||
let out_dir = d.join("out");
|
||||
// Two actions: the set needs --action.
|
||||
let o = bin().args(["batch", "--actions"]).arg(&atn).arg("--in").arg(&input).arg("--out").arg(&out_dir).output().unwrap();
|
||||
assert!(!o.status.success());
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("--action"), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
let (_, err) = ok(bin().args(["batch", "--actions"]).arg(&atn).args(["--action", "Negative", "--in"]).arg(&input).arg("--out").arg(&out_dir));
|
||||
assert!(out_dir.join("a.png").exists());
|
||||
assert!(!err.contains("warning"), "{err}");
|
||||
// The unsupported step is warned about, and fails the file as Photoshop would stop on it.
|
||||
let o = bin().args(["batch", "--actions"]).arg(&atn).args(["--action", "Odd", "--in"]).arg(&input).arg("--out").arg(d.join("out2")).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(err.contains("Generative Fill"), "{err}");
|
||||
assert!(!o.status.success());
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod cli;
|
||||
mod man_and_completions;
|
||||
mod orientation;
|
||||
|
||||
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
|
||||
fn binary() -> std::ffi::OsString {
|
||||
std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into())
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
photocraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut photocraft_cli::command(), "photocraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = photocraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example's two `generate_to` calls, repeated here, write the five completion files under the
|
||||
/// names `packaging/linux/package.sh` and `packaging/freebsd/package.sh` install, `photocraft-cli.1`
|
||||
/// and a page per subcommand, and no pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("pc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut cmd = photocraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "photocraft-cli", &dir).unwrap();
|
||||
}
|
||||
clap_mangen::generate_to(photocraft_cli::command(), &dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["photocraft-cli.bash", "_photocraft-cli", "photocraft-cli.fish", "photocraft-cli.elv", "_photocraft-cli.ps1"];
|
||||
let subcommands = ["convert", "info", "run", "batch", "droplet", "commands", "mcp", "serve"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("photocraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("photocraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima
|
||||
use serde_json::Value;
|
||||
|
||||
fn bin() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_photocraft-cli"))
|
||||
Command::new(crate::binary())
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
@@ -125,7 +125,8 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() {
|
||||
let (a, b) = (d.join("a.pcraft"), d.join("b.pcraft"));
|
||||
ok(bin().arg("convert").arg(&jpg).arg(&a));
|
||||
ok(bin().arg("convert").arg(&a).arg(&b));
|
||||
// Everything but the file's own path and saved document name must match.
|
||||
// Everything but the file's own path and saved document name (which the first snapshot is
|
||||
// named after) must match.
|
||||
let info = |p: &Path| {
|
||||
let mut v = serde_json::from_str::<Value>(&ok(bin().arg("info").arg(p))).unwrap();
|
||||
v.as_object_mut().unwrap().remove("file");
|
||||
@@ -136,8 +137,12 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() {
|
||||
assert_eq!((ia["width"].as_u64(), ia["height"].as_u64()), (Some(16), Some(32)));
|
||||
assert_eq!(ia["name"], "a.pcraft");
|
||||
assert_eq!(ib["name"], "b.pcraft");
|
||||
ia.as_object_mut().unwrap().remove("name");
|
||||
ib.as_object_mut().unwrap().remove("name");
|
||||
assert_eq!(ia["snapshots"][0]["name"], "a.pcraft");
|
||||
assert_eq!(ib["snapshots"][0]["name"], "b.pcraft");
|
||||
for v in [&mut ia, &mut ib] {
|
||||
v.as_object_mut().unwrap().remove("name");
|
||||
v["snapshots"][0].as_object_mut().unwrap().remove("name");
|
||||
}
|
||||
assert_eq!(ia, ib);
|
||||
let (pa, pb) = (d.join("a.png"), d.join("b.png"));
|
||||
ok(bin().arg("convert").arg(&a).arg(&pa));
|
||||
@@ -21,4 +21,4 @@ flate2 = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Node", "Request", "RequestInit", "RequestCache", "Response", "ResponseInit", "Headers", "ReadableStream", "WritableStream", "TransformStream", "TransformStreamDefaultController", "Transformer", "StreamPipeOptions", "ReadableWritablePair", "console"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Node", "Request", "RequestInit", "RequestCache", "Response", "ResponseInit", "Headers", "ReadableStream", "ReadableStreamDefaultReader", "WritableStream", "WritableStreamDefaultWriter", "TransformStream", "TransformStreamDefaultController", "Transformer", "StreamPipeOptions", "ReadableWritablePair", "console"] }
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
//! one part, however large the app grows.
|
||||
//!
|
||||
//! The browser inflates the parts (`DecompressionStream`: Safari 16.4, Firefox 113, Chrome 80).
|
||||
//! In one that can't, this module inflates them itself, a little slower.
|
||||
//! In one that can't, this module inflates them itself, a little slower. Some servers recognise
|
||||
//! the gzip in a part and send it with `Content-Encoding: gzip` (Apache's `mod_mime_magic`
|
||||
//! labels it `x-gzip`), so the browser has inflated it already: the joined download is then
|
||||
//! taken as it is, by its first bytes.
|
||||
//!
|
||||
//! A download that fails is tried again, the later tries past the browser's cache (a bad copy
|
||||
//! there would otherwise fail forever). When every try fails the page says so and offers a reload.
|
||||
@@ -36,6 +39,34 @@ fn parts(list: &str) -> Option<Vec<String>> {
|
||||
(!parts.is_empty() && parts.iter().all(plain)).then_some(parts)
|
||||
}
|
||||
|
||||
/// What the joined parts hold, told by their first bytes.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Payload {
|
||||
/// The gzip packaging made, still to be inflated.
|
||||
Gzip,
|
||||
/// The app's WebAssembly: the server sent the gzip with a `Content-Encoding` the browser
|
||||
/// already undid.
|
||||
Wasm,
|
||||
}
|
||||
|
||||
/// Enough leading bytes to tell the payloads apart.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
const HEAD: usize = 4;
|
||||
|
||||
/// What a download starting with `head` (at least `HEAD` bytes, or all there were) holds, or
|
||||
/// `None` when it is neither, such as a web page or nothing at all.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn payload(head: &[u8]) -> Option<Payload> {
|
||||
if head.starts_with(&[0x1f, 0x8b]) {
|
||||
Some(Payload::Gzip)
|
||||
} else if head.starts_with(b"\0asm") {
|
||||
Some(Payload::Wasm)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Gzip inflated a chunk at a time, for browsers that can't do it themselves.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
struct Inflater(flate2::write::GzDecoder<Vec<u8>>);
|
||||
@@ -69,11 +100,11 @@ mod boot {
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
||||
use web_sys::{
|
||||
Headers, ReadableStream, ReadableWritablePair, RequestCache, RequestInit, Response, ResponseInit, StreamPipeOptions, TransformStream,
|
||||
TransformStreamDefaultController, Transformer, WritableStream,
|
||||
Headers, ReadableStream, ReadableStreamDefaultReader, ReadableWritablePair, RequestCache, RequestInit, Response, ResponseInit, StreamPipeOptions,
|
||||
TransformStream, TransformStreamDefaultController, Transformer, WritableStream, WritableStreamDefaultWriter,
|
||||
};
|
||||
|
||||
use super::Inflater;
|
||||
use super::{HEAD, Inflater, Payload};
|
||||
|
||||
/// Where packaging puts the app, next to this module's own files.
|
||||
const PARTS: &str = "./app/parts.txt";
|
||||
@@ -172,11 +203,71 @@ mod boot {
|
||||
Ok(compressed.pipe_through(&pair))
|
||||
}
|
||||
|
||||
/// The next chunk `reader` gives, or `None` at the end of the stream.
|
||||
async fn read(reader: &ReadableStreamDefaultReader) -> Result<Option<js_sys::Uint8Array>, JsValue> {
|
||||
let result = JsFuture::from(reader.read()).await?;
|
||||
if js_sys::Reflect::get(&result, &JsValue::from_str("done"))?.is_truthy() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(js_sys::Reflect::get(&result, &JsValue::from_str("value"))?.dyn_into()?))
|
||||
}
|
||||
|
||||
/// Writes `chunk` into `writer`. When nothing will read it any more (the app's loader gave up
|
||||
/// on its stream), the download from `reader` is cancelled too, so it doesn't stay pending.
|
||||
async fn write(chunk: &js_sys::Uint8Array, reader: &ReadableStreamDefaultReader, writer: &WritableStreamDefaultWriter) -> Result<(), JsValue> {
|
||||
if let Err(e) = JsFuture::from(writer.write_with_chunk(chunk)).await {
|
||||
let _ = reader.cancel_with_reason(&e);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the `held` chunks, then the rest of `reader`'s stream, into `writer`, then closes it.
|
||||
async fn pass_on(held: Vec<js_sys::Uint8Array>, reader: &ReadableStreamDefaultReader, writer: &WritableStreamDefaultWriter) -> Result<(), JsValue> {
|
||||
for chunk in &held {
|
||||
write(chunk, reader, writer).await?;
|
||||
}
|
||||
while let Some(chunk) = read(reader).await? {
|
||||
write(&chunk, reader, writer).await?;
|
||||
}
|
||||
JsFuture::from(writer.close()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's WebAssembly from the `joined` parts: inflated, unless its first bytes show the
|
||||
/// browser has already done that.
|
||||
async fn unpacked(joined: &ReadableStream) -> Result<ReadableStream, JsValue> {
|
||||
let reader: ReadableStreamDefaultReader = joined.get_reader().unchecked_into();
|
||||
let (mut head, mut held) = (Vec::with_capacity(HEAD), Vec::new());
|
||||
while head.len() < HEAD {
|
||||
let Some(chunk) = read(&reader).await? else { break };
|
||||
let wanted = u32::try_from(HEAD - head.len()).unwrap_or(u32::MAX).min(chunk.length());
|
||||
head.extend(chunk.subarray(0, wanted).to_vec());
|
||||
held.push(chunk);
|
||||
}
|
||||
let Some(payload) = super::payload(&head) else {
|
||||
let e = JsValue::from_str("the download is not PhotoCraft's WebAssembly");
|
||||
// Stops the rest of the download, which nothing will read.
|
||||
let _ = reader.cancel_with_reason(&e);
|
||||
return Err(e);
|
||||
};
|
||||
let rest = TransformStream::new()?;
|
||||
let writer = rest.writable().get_writer()?;
|
||||
spawn_local(async move {
|
||||
if let Err(e) = pass_on(held, &reader, &writer).await {
|
||||
let _ = writer.abort_with_reason(&e);
|
||||
}
|
||||
});
|
||||
match payload {
|
||||
Payload::Gzip => inflated(&rest.readable()),
|
||||
Payload::Wasm => Ok(rest.readable()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(fresh: bool) -> Result<(), JsValue> {
|
||||
let list = JsFuture::from(fetch(PARTS, fresh).await?.text()?).await?.as_string().unwrap_or_default();
|
||||
let parts = super::parts(&list).ok_or_else(|| JsValue::from_str("app/parts.txt is not a parts list"))?;
|
||||
let joined = TransformStream::new()?;
|
||||
let wasm = inflated(&joined.readable())?;
|
||||
// Why the download stopped: the app's loader only reports that its stream broke.
|
||||
let cause = Rc::new(RefCell::new(None));
|
||||
let failed = cause.clone();
|
||||
@@ -187,6 +278,10 @@ mod boot {
|
||||
failed.replace(Some(e));
|
||||
}
|
||||
});
|
||||
let wasm = match unpacked(&joined.readable()).await {
|
||||
Ok(wasm) => wasm,
|
||||
Err(e) => return Err(cause.take().unwrap_or(e)),
|
||||
};
|
||||
let headers = Headers::new()?;
|
||||
headers.set("Content-Type", "application/wasm")?;
|
||||
let init = ResponseInit::new();
|
||||
@@ -258,7 +353,7 @@ fn main() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Inflater, MARKER, parts};
|
||||
use super::{HEAD, Inflater, MARKER, Payload, parts, payload};
|
||||
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut z = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
@@ -317,6 +412,22 @@ mod tests {
|
||||
assert!(run(b"").is_err(), "nothing at all");
|
||||
}
|
||||
|
||||
/// A server that recognises the gzip (Apache's `mod_mime_magic`) sends it with
|
||||
/// `Content-Encoding: x-gzip`, and the browser inflates it on the way (#7639). The joined parts
|
||||
/// are then the app's WebAssembly, which must start as it is, not be inflated a second time.
|
||||
#[test]
|
||||
fn the_first_bytes_tell_gzip_from_wasm_the_browser_already_inflated() {
|
||||
let mut wasm = b"\0asm\x01\0\0\0".to_vec();
|
||||
wasm.extend(sample());
|
||||
let packed = gzip(&wasm);
|
||||
assert_eq!(payload(&packed[..HEAD]), Some(Payload::Gzip), "as packaged");
|
||||
assert_eq!(payload(&wasm[..HEAD]), Some(Payload::Wasm), "inflated by the browser");
|
||||
assert_eq!(payload(&packed[..2]), Some(Payload::Gzip), "a download shorter than HEAD");
|
||||
assert_eq!(payload(b"<!DOCTYPE html>"), None, "a web page");
|
||||
assert_eq!(payload(b"\0as"), None, "a cut-off wasm header");
|
||||
assert_eq!(payload(b""), None, "nothing at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parts_list_gives_its_names_in_order() {
|
||||
let list = format!("{MARKER}\nphotocraft-web-0123abcd.part-aa\r\n\n photocraft-web-0123abcd.part-ab \n");
|
||||
|
||||
@@ -29,12 +29,12 @@ log = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit"] }
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "clipboard"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "DomRect", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "RequestMode", "Navigator"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
//!
|
||||
//! Differences from the desktop app:
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker; bytes arrive asynchronously through
|
||||
//! `Services::inbox`;
|
||||
//! - file pickers return browser file contents asynchronously through `Services::file_dialog`;
|
||||
//! this includes File → Open and commands such as Place Embedded;
|
||||
//! - saving/exporting triggers a browser download;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox.
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through `Services::inbox`.
|
||||
//!
|
||||
//! URL query flags: `?cpu` forces the CPU canvas path (same as `PHOTOCRAFT_CPU_CANVAS=1`);
|
||||
//! `?webgl` forces the WebGL2 backend instead of WebGPU.
|
||||
|
||||
@@ -9,8 +9,8 @@ use photocraft_engine::{
|
||||
};
|
||||
|
||||
pub type Batch = BTreeMap<String, Option<Arc<[u8]>>>;
|
||||
/// Three sampled images per preset (tip, dual tip, texture), plus group/index/action records.
|
||||
pub const MAX_RECORDS: usize = MAX_GROUPS + MAX_PRESETS_PER_GROUP * 3 + 2;
|
||||
/// Three sampled images per preset (tip, dual tip, texture), plus group/index/action/pattern records.
|
||||
pub const MAX_RECORDS: usize = MAX_GROUPS + MAX_PRESETS_PER_GROUP * 3 + 3;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
@@ -45,6 +45,7 @@ pub fn record_limit(name: &str) -> Result<u64, String> {
|
||||
match name {
|
||||
INDEX_FILE => Ok(MAX_INDEX_BYTES),
|
||||
ACTIONS_FILE => Ok(MAX_ACTIONS_BYTES),
|
||||
PATTERNS_FILE => Ok(MAX_PATTERNS_BYTES),
|
||||
_ if name.starts_with("tips/") && leaf.ends_with(".pctip") => Ok(MAX_TIP_BYTES),
|
||||
_ if !name.contains('/') && name.ends_with(".pcbrushes") => Ok(MAX_GROUP_BYTES),
|
||||
_ => Err("unknown preset record type".into()),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
|
||||
use photocraft_doc::Document;
|
||||
@@ -15,11 +17,12 @@ use wasm_bindgen::JsCast as _;
|
||||
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
|
||||
|
||||
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
|
||||
/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
|
||||
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl) and swatches (.aco, .act, .ase), which go to the preset libraries.
|
||||
const OPEN_EXTS: &[&str] = &[
|
||||
"pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr",
|
||||
"pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef",
|
||||
"orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub",
|
||||
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico",
|
||||
"qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", "iff", "lbm", "ilbm", "heic",
|
||||
"heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", "ase", "af",
|
||||
"afdesign", "afphoto", "afpub",
|
||||
];
|
||||
const SVG_EXTS: &[&str] = &["svg", "svgz"];
|
||||
const CANVAS_ID: &str = "photocraft_canvas";
|
||||
@@ -77,13 +80,16 @@ pub fn start() {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
PhotocraftApp::install_type_reset_hooks(&cc.egui_ctx);
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro);
|
||||
let inbox: Inbox = Arc::default();
|
||||
let place_inbox: Inbox = Arc::default();
|
||||
let served: Served = Arc::default();
|
||||
load_font_manifest(served.clone(), cc.egui_ctx.clone());
|
||||
let (session, warnings) = crate::preset_bridge::session(presets.clone());
|
||||
preset_warnings.extend(warnings);
|
||||
let mut app = PhotocraftApp::new(session, services(inbox.clone()));
|
||||
let drag = listen_drag(&pen_target);
|
||||
let mut app = PhotocraftApp::new(session, services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag)));
|
||||
if !preset_warnings.is_empty() {
|
||||
photocraft_ui_egui::notices::post(&mut app, i18n::t("Some brush presets could not be loaded"), preset_warnings, true, None);
|
||||
}
|
||||
@@ -97,7 +103,7 @@ pub fn start() {
|
||||
}
|
||||
let unsaved = Arc::new(AtomicBool::new(false));
|
||||
guard_unload(unsaved.clone());
|
||||
Ok(Box::new(WebShell { app, inbox, unsaved, served, database, presets }))
|
||||
Ok(Box::new(WebShell { app, inbox, place_inbox, unsaved, served, database, presets, ui_language: "" }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -140,6 +146,38 @@ fn listen_pen(target: &web_sys::HtmlCanvasElement, feed: photocraft_ui_egui::sty
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer in a drag over the page, in CSS pixels relative to the viewport (`clientX`,
|
||||
/// `clientY`): the last `dragover` or `drop` event's.
|
||||
type DragPos = Rc<Cell<Option<(f32, f32)>>>;
|
||||
|
||||
/// Follows files dragged over the canvas. eframe's drop events carry no pointer position and the
|
||||
/// page gets no pointer events during a drag, so this is where a drop lands: on the document's
|
||||
/// canvas it places the files, elsewhere it opens them (#5749).
|
||||
fn listen_drag(target: &web_sys::HtmlCanvasElement) -> DragPos {
|
||||
use wasm_bindgen::closure::Closure;
|
||||
let pos = DragPos::default();
|
||||
for kind in ["dragover", "drop"] {
|
||||
let pos = pos.clone();
|
||||
// A DragEvent is a MouseEvent: only its client position is read.
|
||||
let cb = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |e: web_sys::MouseEvent| pos.set(Some((e.client_x() as f32, e.client_y() as f32))));
|
||||
if target.add_event_listener_with_callback(kind, cb.as_ref().unchecked_ref()).is_ok() {
|
||||
cb.forget();
|
||||
}
|
||||
}
|
||||
pos
|
||||
}
|
||||
|
||||
/// `Services::cursor_pos` for the web: the last drag position in egui points, mapped as eframe
|
||||
/// maps pointer events (relative to the canvas, divided by the zoom factor).
|
||||
fn drag_pos_service(canvas: web_sys::HtmlCanvasElement, pos: DragPos) -> photocraft_ui_egui::CursorPosFn {
|
||||
Box::new(move |ctx: &egui::Context| {
|
||||
let (x, y) = pos.get()?;
|
||||
let rect = canvas.get_bounding_client_rect();
|
||||
let zoom = ctx.zoom_factor();
|
||||
(zoom.is_finite() && zoom > 0.0).then(|| egui::pos2((x - rect.left() as f32) / zoom, (y - rect.top() as f32) / zoom))
|
||||
})
|
||||
}
|
||||
|
||||
/// Closing or reloading the tab while a document has unsaved changes asks first, as closing the
|
||||
/// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is
|
||||
/// refreshed every frame by [`WebShell`].
|
||||
@@ -181,12 +219,15 @@ fn load_font_manifest(served: Served, ctx: egui::Context) {
|
||||
files.entry(f.family.clone()).or_default().push((f.file.clone(), f.integrity.clone()));
|
||||
}
|
||||
log::info!("photocraft-web: {} served font families", files.len());
|
||||
served.lock().unwrap_or_else(|e| e.into_inner()).files = files;
|
||||
served.lock().unwrap_or_else(PoisonError::into_inner).files = files;
|
||||
// The families for the font menus, and the script fallbacks (the manifest's `scripts`).
|
||||
served_fonts::add_fonts(&fonts);
|
||||
// Fetch now the fallbacks of the scripts the browser's languages use (an Arabic reader gets
|
||||
// the Arabic font before typing); the rest is fetched when text or a font menu needs it.
|
||||
served_fonts::request_for_languages(browser_languages().iter().map(String::as_str));
|
||||
// Also the interface language's: `serve_fonts` asked for it once already, maybe before
|
||||
// this manifest arrived, when no fallback was registered yet.
|
||||
let ui_language = photocraft_ui_egui::i18n::current().code();
|
||||
served_fonts::request_for_languages(browser_languages().iter().map(String::as_str).chain([ui_language]));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
@@ -196,20 +237,21 @@ fn browser_languages() -> Vec<String> {
|
||||
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|l| l.as_string()).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// GET `url` (relative to the page) and read the whole body. With `integrity` (a Subresource
|
||||
/// Integrity value), the browser rejects a body whose hash differs.
|
||||
/// GET `url` (a relative path on the same origin) and read the whole body. With `integrity` (a
|
||||
/// Subresource Integrity value), the browser rejects a body whose hash differs.
|
||||
async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result<Vec<u8>, String> {
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
if !served_fonts::is_relative_path(url) {
|
||||
return Err("url must be a relative path".into());
|
||||
}
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let request = match integrity {
|
||||
Some(sri) => {
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_integrity(sri);
|
||||
window.fetch_with_str_and_init(url, &init)
|
||||
}
|
||||
None => window.fetch_with_str(url),
|
||||
};
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_mode(web_sys::RequestMode::SameOrigin);
|
||||
if let Some(sri) = integrity {
|
||||
init.set_integrity(sri);
|
||||
}
|
||||
let request = window.fetch_with_str_and_init(url, &init);
|
||||
let resp: web_sys::Response = JsFuture::from(request).await.map_err(js)?.dyn_into().map_err(|_| "not a Response")?;
|
||||
if !resp.ok() {
|
||||
return Err(format!("HTTP {}", resp.status()));
|
||||
@@ -219,15 +261,20 @@ async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result<Vec<u8>, Stri
|
||||
}
|
||||
|
||||
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously,
|
||||
/// so the app's own drop path can't handle them) and feed them through the inbox.
|
||||
/// so the app's own drop path can't handle them) and feed them through the inboxes.
|
||||
struct WebShell {
|
||||
app: PhotocraftApp,
|
||||
/// Dropped files to open as documents.
|
||||
inbox: Inbox,
|
||||
/// Dropped files to place on the active document's canvas.
|
||||
place_inbox: Inbox,
|
||||
/// Read by the `beforeunload` listener ([`guard_unload`]).
|
||||
unsaved: Arc<AtomicBool>,
|
||||
served: Served,
|
||||
database: Option<web_sys::IdbDatabase>,
|
||||
presets: crate::preset_bridge::Bridge,
|
||||
/// The interface language whose served script font was last asked for.
|
||||
ui_language: &'static str,
|
||||
}
|
||||
|
||||
impl WebShell {
|
||||
@@ -252,9 +299,15 @@ impl WebShell {
|
||||
/// Fetches the served families asked for (picked in a font menu, or needed by a layout) and
|
||||
/// installs the files that arrived.
|
||||
fn serve_fonts(&mut self, ctx: &egui::Context) {
|
||||
// The interface language's script font draws its labels (Arabic, Japanese…).
|
||||
let ui_language = photocraft_ui_egui::i18n::current().code();
|
||||
if ui_language != self.ui_language {
|
||||
self.ui_language = ui_language;
|
||||
served_fonts::request_for_languages([ui_language]);
|
||||
}
|
||||
let requested = served_fonts::take_requests();
|
||||
let (fetch, arrived) = {
|
||||
let mut s = self.served.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = self.served.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut fetch = Vec::new();
|
||||
for family in requested {
|
||||
if let Some(files) = s.files.get(&family).cloned()
|
||||
@@ -271,37 +324,57 @@ impl WebShell {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match fetch_bytes(&file, integrity.as_deref()).await {
|
||||
Ok(bytes) => {
|
||||
served.lock().unwrap_or_else(|e| e.into_inner()).arrived.push((family, bytes));
|
||||
served.lock().unwrap_or_else(PoisonError::into_inner).arrived.push((family, bytes));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(e) => log::error!("couldn't fetch served font {file}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
served_fonts::install(&mut self.app, arrived);
|
||||
served_fonts::install(&mut self.app, ctx, arrived);
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
// A tap reaches eframe as Pointer Events and Touch Events: keep one press per tap, or the
|
||||
// twin press closes the menu the first one opened (#2095).
|
||||
photocraft_ui_egui::touch_twins::drop_twins(ctx, raw_input);
|
||||
// The browser build has no TCP control server, so `inject_synthetic` finds an empty
|
||||
// queue, but the clipboard key mapping (`Event::PasteImage`), legacy pinch, pen-hold and
|
||||
// titlebar normalization live in the app hook and must run here too.
|
||||
eframe::App::raw_input_hook(&mut self.app, ctx, raw_input);
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
for f in dropped {
|
||||
let inbox = self.inbox.clone();
|
||||
if !dropped.is_empty() {
|
||||
let names: Vec<String> =
|
||||
dropped.iter().map(|f| f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into())).collect();
|
||||
// Decided now, where the drop landed: on the document's canvas the files are placed
|
||||
// as layers (as on the desktop), elsewhere opened.
|
||||
let places = self.app.dropped_on_canvas(ctx, &names);
|
||||
let files: Vec<_> = dropped.into_iter().zip(names).zip(places).collect();
|
||||
let (inbox, place_inbox) = (self.inbox.clone(), self.place_inbox.clone());
|
||||
let ctx = ctx.clone();
|
||||
// One after another, so they open or place in the order they were dropped.
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
|
||||
ctx.request_repaint();
|
||||
for ((f, name), place) in files {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
let queue = if place { &place_inbox } else { &inbox };
|
||||
queue.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
self.serve_fonts(ctx);
|
||||
self.app.logic(ctx, frame);
|
||||
self.app.logic_frame(ctx, frame);
|
||||
self.save_presets(ctx);
|
||||
self.app.finish_type_reset_logic(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
@@ -328,16 +401,17 @@ impl eframe::App for WebShell {
|
||||
});
|
||||
});
|
||||
}
|
||||
self.app.ui(ui, frame);
|
||||
self.app.ui_frame(ui, frame);
|
||||
self.save_presets(ui.ctx());
|
||||
self.app.finish_type_reset_pass(ui.ctx());
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: Inbox) -> Services {
|
||||
fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {
|
||||
Services {
|
||||
screen_pick: screen_color_service(),
|
||||
import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| {
|
||||
photocraft_io::import_with_svg_group_depth(name, bytes, max_svg_group_depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
|
||||
import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| {
|
||||
photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
|
||||
})),
|
||||
export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {
|
||||
photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
|
||||
@@ -379,11 +453,15 @@ fn services(inbox: Inbox) -> Services {
|
||||
}
|
||||
})),
|
||||
write: Some(Box::new(|path: &str, bytes: &[u8]| download(path, bytes))),
|
||||
// A download may be cancelled and never reports back: it doesn't save the document.
|
||||
write_unconfirmed: true,
|
||||
encode_png: Some(Box::new(|w, h, rgba| {
|
||||
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
|
||||
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
|
||||
})),
|
||||
inbox: Some(inbox),
|
||||
place_inbox: Some(place_inbox),
|
||||
cursor_pos: Some(cursor_pos),
|
||||
// Preferences live in the browser's localStorage.
|
||||
load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())),
|
||||
save_prefs: Some(Box::new(|text: &str| local_storage().ok_or("no localStorage")?.set_item(PREFS_KEY, text).map_err(|e| format!("{e:?}")))),
|
||||
|
||||
@@ -29,17 +29,23 @@ photocraft-automation = { workspace = true }
|
||||
photocraft-ui-egui = { workspace = true }
|
||||
# Pen tablet pressure/tilt on macOS and X11 (the workspace's one isolated unsafe helper crate).
|
||||
photocraft-tablet = { workspace = true }
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence"] }
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence", "clipboard"] }
|
||||
egui = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { version = "3.6", features = ["wayland-data-control"] }
|
||||
arboard = { version = "3.7", features = ["wayland-data-control"] }
|
||||
open = "5"
|
||||
# Reads the saved window layout (eframe persistence) to drop values that would abort startup.
|
||||
ron = "0.12"
|
||||
# Background release checks; HTTPS with Rust TLS, no async runtime.
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Safe CoreGraphics bindings, compatible with the existing macOS 11 deployment target.
|
||||
@@ -50,14 +56,15 @@ core-graphics2 = { version = "=0.6.1", default-features = false, features = ["di
|
||||
# safe API. Pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
# Safe AppKit calls only: turn off AppKit's title bar dragging (mac_window.rs) and find where the
|
||||
# pointer is when files are dropped (cursor.rs; winit 0.30 drops carry no position). Already in
|
||||
# pointer is when files are dropped (cursor.rs; winit 0.30 drops carry no position), and play the
|
||||
# system alert sound for Beep When Done (services.rs, NSBeep). Already in
|
||||
# Cargo.lock (winit, photocraft-tablet); pinned exactly to the same versions.
|
||||
objc2 = "=0.6.4"
|
||||
objc2 = "=0.6.5"
|
||||
objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator", "NSGeometry"] }
|
||||
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSResponder", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSGraphics", "NSResponder", "NSView", "NSWindow"] }
|
||||
# The macOS menu bar (mac_menu.rs): a standalone native menu crate (from the tauri-apps org, but
|
||||
# not Tauri: no webview, no JS), AppKit menus behind a safe API (no GTK with default features off). Pinned exactly: review the diff before bumping.
|
||||
muda = { version = "=0.21.1", default-features = false }
|
||||
muda = { version = "=0.21.2", default-features = false }
|
||||
# Quit with `terminate:` from the main queue, outside winit's event handler (mac_window.rs).
|
||||
# Already in Cargo.lock (winit, objc2-app-kit); pinned exactly to the same version.
|
||||
dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] }
|
||||
@@ -65,6 +72,8 @@ dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] }
|
||||
# Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
photocraft-cms = { workspace = true }
|
||||
# The print portal's PDF: a private (0600) temporary file, removed when the dialog is done.
|
||||
tempfile = "3"
|
||||
x11rb = { version = "=0.13.2", default-features = false, features = ["image", "randr", "xkb"] }
|
||||
# Clipboard images in types other than PNG on Wayland (`services.rs`, #2546): arboard asks for
|
||||
# image/png only. Already in Cargo.lock (arboard's wayland-data-control); pinned exactly.
|
||||
|
||||
@@ -11,6 +11,14 @@ fn main() {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which
|
||||
// stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe
|
||||
// from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use;
|
||||
// the print command checks for it first and reports an error instead.
|
||||
if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
|
||||
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll");
|
||||
println!("cargo:rustc-link-arg-bins=delayimp.lib");
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/photocraft.ico")
|
||||
.set("ProductName", "PhotoCraft")
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
//! folder can't be written (read-only medium, Program Files), the app warns and falls back.
|
||||
//! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows
|
||||
//! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`.
|
||||
//!
|
||||
//! One exception: the platform convention keeps crash-recovery autosaves out of what is synced
|
||||
//! with the settings: the Windows roaming profile and the Linux config folder ([`recovery_dir`]).
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -60,6 +63,396 @@ pub fn config_dir() -> Option<PathBuf> {
|
||||
current().dir.clone()
|
||||
}
|
||||
|
||||
/// The crash-recovery folder's name.
|
||||
const RECOVERY: &str = "Recovery";
|
||||
|
||||
/// Where crash-recovery autosaves live, with any left in the settings directory by an earlier
|
||||
/// version moved there first ([`adopt_legacy_recovery`]). Call it once, at startup.
|
||||
pub fn recovery_dir() -> Option<PathBuf> {
|
||||
let data = current();
|
||||
let dir = resolve_recovery(data, |k| std::env::var_os(k))?;
|
||||
Some(match data.dir.as_ref().map(|d| d.join(RECOVERY)) {
|
||||
Some(legacy) => adopt_legacy_recovery(&legacy, &dir),
|
||||
None => dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// The recovery folder for `data`. Autosaves hold whole documents and are rewritten every few
|
||||
/// minutes, so with the platform convention they stay out of what is synced with the settings:
|
||||
/// - Windows (#5648): the machine-local `%LOCALAPPDATA%\Photocraft\Recovery`; the roaming
|
||||
/// `%APPDATA%` may be synced at sign-in and sign-out or capped by policy.
|
||||
/// - Linux and other XDG systems (#6612): `$XDG_STATE_HOME/photocraft/Recovery`, by default
|
||||
/// `~/.local/state/photocraft/Recovery`, where the XDG Base Directory spec puts state that
|
||||
/// should outlive a restart but isn't configuration; dotfile managers and config sync often copy
|
||||
/// `~/.config` whole. As the spec asks, a relative `XDG_STATE_HOME` is ignored.
|
||||
/// - macOS: `~/Library/Application Support/Photocraft/Recovery` as before. Apple's guidelines put
|
||||
/// app-created data that can't be regenerated there; `~/Library/Caches` may be purged by the
|
||||
/// system.
|
||||
///
|
||||
/// They are never in a temp or cache folder, which cleanup tools may empty before a crashed
|
||||
/// document is recovered. The override and portable folders keep everything in one place.
|
||||
pub fn resolve_recovery(data: &DataDir, env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
if data.mode == Mode::Platform {
|
||||
if cfg!(windows) {
|
||||
if let Some(local) = env("LOCALAPPDATA").filter(|l| !l.is_empty()) {
|
||||
return Some(PathBuf::from(local).join("Photocraft").join(RECOVERY));
|
||||
}
|
||||
} else if !cfg!(target_os = "macos") {
|
||||
let state = env("XDG_STATE_HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|s| s.is_absolute())
|
||||
.or_else(|| env("HOME").filter(|h| !h.is_empty()).map(|h| PathBuf::from(h).join(".local").join("state")));
|
||||
if let Some(state) = state {
|
||||
return Some(state.join("photocraft").join(RECOVERY));
|
||||
}
|
||||
}
|
||||
}
|
||||
data.dir.as_ref().map(|d| d.join(RECOVERY))
|
||||
}
|
||||
|
||||
/// The lock file, beside the recovery folder, that keeps two PhotoCraft processes starting at
|
||||
/// once (`--new-instance`, control launches) from moving the same autosaves.
|
||||
const MIGRATION_LOCK: &str = "recovery-migration.lock";
|
||||
|
||||
/// How long a launch waits for another one's move before going ahead without moving anything.
|
||||
const MIGRATION_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Suffix of a copy staged for publishing ([`stage_copy`]): disposable, the original still exists.
|
||||
const STAGED: &str = ".moving";
|
||||
|
||||
/// Suffix of an original set aside while it is copied to another volume ([`move_across`]): it
|
||||
/// may be the only copy, so it is put back, never thrown away, if the move doesn't finish.
|
||||
const HELD: &str = ".held";
|
||||
|
||||
/// Move autosaves from `legacy` (the recovery folder of versions before #5648) into `dir`, so a
|
||||
/// crash just before an update is still offered for recovery. Returns the folder this process
|
||||
/// uses for its recovery store. That is `legacy` only when `dir` doesn't exist and no process can
|
||||
/// be moving autosaves (the move failed, or its lock can't be made), so nothing deletes what is
|
||||
/// written there. A launch that finds another one moving uses `dir`, which the move never
|
||||
/// replaces or removes. See [`adopt_locked`] for how they move.
|
||||
pub fn adopt_legacy_recovery(legacy: &Path, dir: &Path) -> PathBuf {
|
||||
adopt_legacy_recovery_waiting(legacy, dir, MIGRATION_WAIT)
|
||||
}
|
||||
|
||||
/// [`adopt_legacy_recovery`], waiting up to `wait` for another process's move.
|
||||
fn adopt_legacy_recovery_waiting(legacy: &Path, dir: &Path, wait: std::time::Duration) -> PathBuf {
|
||||
let held_aside = || legacy.parent().is_some_and(|p| !side_entries(p, legacy, HELD).is_empty());
|
||||
if legacy == dir || (!legacy.is_dir() && !held_aside()) {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
// An empty old folder has nothing to move (`remove_dir` only removes an empty one).
|
||||
if !held_aside() && std::fs::remove_dir(legacy).is_ok() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let unmoved = || if dir.exists() || !legacy.is_dir() { dir.to_path_buf() } else { legacy.to_path_buf() };
|
||||
let Some(parent) = dir.parent() else { return unmoved() };
|
||||
let lock =
|
||||
std::fs::create_dir_all(parent).and_then(|()| std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(parent.join(MIGRATION_LOCK)));
|
||||
let Ok(lock) = lock else {
|
||||
// No lock file means no other process can be moving: the old folder is safe to use.
|
||||
log::warn!("couldn't open the recovery move lock in {}; autosaves stay where they are", parent.display());
|
||||
return unmoved();
|
||||
};
|
||||
let deadline = std::time::Instant::now() + wait;
|
||||
loop {
|
||||
match lock.try_lock() {
|
||||
Ok(()) => break,
|
||||
Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(50)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {
|
||||
// Another process is moving and may yet remove the old folder: never write there.
|
||||
log::info!("another PhotoCraft is moving crash-recovery autosaves; using {}", dir.display());
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
Err(std::fs::TryLockError::Error(e)) => {
|
||||
// Locking fails for every process here alike, so none can be moving.
|
||||
log::warn!("couldn't lock {}: {e}; autosaves stay where they are", parent.join(MIGRATION_LOCK).display());
|
||||
return unmoved();
|
||||
}
|
||||
}
|
||||
}
|
||||
// The lock file stays (removing it would race a process about to lock it); the OS releases
|
||||
// the lock when `lock` is dropped or the process ends.
|
||||
let used = adopt_locked(legacy, dir);
|
||||
if used == legacy {
|
||||
// This process writes its autosaves to the old folder: it keeps the lock for as long as it
|
||||
// runs, so no other launch moves (and removes) the folder under it.
|
||||
KEPT_LOCKS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(lock);
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// Migration locks of the old folders this process uses (see [`adopt_legacy_recovery`]), kept
|
||||
/// until it ends.
|
||||
static KEPT_LOCKS: std::sync::Mutex<Vec<std::fs::File>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// The move itself, under the migration lock. First, what a process that ended mid-move left is
|
||||
/// tidied: originals it set aside are put back, copies it staged are removed. An empty `legacy`
|
||||
/// is then just removed. Otherwise the whole folder moves if `dir` doesn't exist yet; when both
|
||||
/// exist, each autosave (`<key>.pcraft` bundle and `<key>.json` sidecar, see
|
||||
/// `photocraft_format::autosave`) moves as a whole, bundle first, unless `dir` already has either
|
||||
/// part, and one that stays is left in `legacy` untouched. Every move is a [`move_path`].
|
||||
fn adopt_locked(legacy: &Path, dir: &Path) -> PathBuf {
|
||||
if let Some(parent) = legacy.parent() {
|
||||
for held in side_entries(parent, legacy, HELD) {
|
||||
put_back(&held, legacy);
|
||||
}
|
||||
}
|
||||
// Autosave parts held aside inside the old folder by a per-autosave move.
|
||||
let held_parts: Vec<(PathBuf, String)> = std::fs::read_dir(legacy)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().to_str().and_then(|n| side_of(n, HELD)).map(|orig| (e.path(), orig.to_owned())))
|
||||
.collect();
|
||||
for (held, original) in held_parts {
|
||||
put_back(&held, &legacy.join(original));
|
||||
}
|
||||
for folder in [dir.parent(), Some(dir)].into_iter().flatten() {
|
||||
remove_stale_staging(folder);
|
||||
}
|
||||
// Another process may have finished the move while this one waited.
|
||||
if !legacy.is_dir() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
if std::fs::remove_dir(legacy).is_ok() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
if !dir.exists() {
|
||||
// The common case: the whole folder moves at once.
|
||||
return match move_path(legacy, dir) {
|
||||
Ok(()) => {
|
||||
log::info!("moved crash-recovery autosaves from {} to {}", legacy.display(), dir.display());
|
||||
dir.to_path_buf()
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("couldn't move crash-recovery autosaves from {} to {} ({e}); using the old folder", legacy.display(), dir.display());
|
||||
if legacy.is_dir() { legacy.to_path_buf() } else { dir.to_path_buf() }
|
||||
}
|
||||
};
|
||||
}
|
||||
move_entries(legacy, dir);
|
||||
// Only an emptied folder goes; anything that couldn't move stays for a later launch.
|
||||
let _ = std::fs::remove_dir(legacy);
|
||||
dir.to_path_buf()
|
||||
}
|
||||
|
||||
/// Move each autosave of `from` into `to` (both folders): bundle first, then sidecar, skipped if
|
||||
/// `to` has either part. Temp files of an interrupted write (`photocraft_format::atomic`) go
|
||||
/// along too, for the recovery store's startup sweep there.
|
||||
fn move_entries(from: &Path, to: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(from) else { return };
|
||||
let names: Vec<String> = entries.flatten().filter_map(|e| e.file_name().to_str().map(str::to_owned)).collect();
|
||||
let keys: std::collections::BTreeSet<&str> = names.iter().filter_map(|n| n.strip_suffix(".pcraft").or_else(|| n.strip_suffix(".json"))).collect();
|
||||
for key in keys {
|
||||
let parts = [format!("{key}.pcraft"), format!("{key}.json")];
|
||||
if parts.iter().any(|p| std::fs::symlink_metadata(to.join(p)).is_ok()) {
|
||||
continue;
|
||||
}
|
||||
// A bundle that moves without its sidecar is still listed (`list_recovery` reads a
|
||||
// committed bundle's manifest); a sidecar must never move without its bundle.
|
||||
for part in &parts {
|
||||
let src = from.join(part);
|
||||
if std::fs::symlink_metadata(&src).is_ok()
|
||||
&& let Err(e) = move_path(&src, &to.join(part))
|
||||
{
|
||||
log::warn!("couldn't move {} to {}: {e}", src.display(), to.display());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in names.iter().filter(|n| n.ends_with(".pcsave.tmp")) {
|
||||
let _ = move_path(&from.join(name), &to.join(name));
|
||||
}
|
||||
}
|
||||
|
||||
/// How deep [`copy_tree`] follows folders: an autosave bundle is a few levels deep.
|
||||
const MAX_COPY_DEPTH: u32 = 16;
|
||||
|
||||
fn already_exists(path: &Path) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::AlreadyExists, format!("{} already exists", path.display()))
|
||||
}
|
||||
|
||||
/// A path beside `of`, named `.<name>.<pid>-<n><suffix>`, that no other call uses.
|
||||
fn side_path(of: &Path, suffix: &str) -> std::io::Result<PathBuf> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let parent = of.parent().ok_or_else(|| std::io::Error::other(format!("{} has no parent folder", of.display())))?;
|
||||
let name = of.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Ok(parent.join(format!(".{name}.{}-{}{suffix}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))))
|
||||
}
|
||||
|
||||
/// The name `side` was made from, if it is a [`side_path`] name with `suffix`.
|
||||
fn side_of<'a>(side: &'a str, suffix: &str) -> Option<&'a str> {
|
||||
let rest = side.strip_prefix('.')?.strip_suffix(suffix)?;
|
||||
let (name, ids) = rest.rsplit_once('.')?;
|
||||
let (pid, n) = ids.split_once('-')?;
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
(!name.is_empty() && digits(pid) && digits(n)).then_some(name)
|
||||
}
|
||||
|
||||
/// The side paths with `suffix` in `folder` made from `of`.
|
||||
fn side_entries(folder: &Path, of: &Path, suffix: &str) -> Vec<PathBuf> {
|
||||
let Some(name) = of.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
|
||||
std::fs::read_dir(folder)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_str().and_then(|n| side_of(n, suffix)) == Some(name))
|
||||
.map(|e| e.path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Move the file or folder `from` to `to` without ever replacing anything at `to`. On one volume
|
||||
/// a folder is renamed (Windows refuses an existing target; elsewhere only an empty folder could
|
||||
/// be replaced) and a file is hard-linked, which fails on an existing target, and then unlinked
|
||||
/// at `from`. Otherwise (another volume, e.g. a roaming profile redirected to a network share
|
||||
/// while `%LOCALAPPDATA%` stays local) it is copied ([`move_across`]).
|
||||
fn move_path(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if std::fs::symlink_metadata(to).is_ok() {
|
||||
return Err(already_exists(to));
|
||||
}
|
||||
let meta = std::fs::symlink_metadata(from)?;
|
||||
let moved = if meta.is_dir() { std::fs::rename(from, to) } else { std::fs::hard_link(from, to).and_then(|()| std::fs::remove_file(from)) };
|
||||
match moved {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::DirectoryNotEmpty) => Err(e),
|
||||
Err(_) => move_across(from, to),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `from` to `to` by copying. `from` is first renamed aside on its own volume
|
||||
/// (`.<name>.<pid>-<n>.held`, [`hold`]), so a process still writing to the old path (another
|
||||
/// launch that couldn't take the lock, an older PhotoCraft) starts a new `from` there instead of
|
||||
/// adding to what is copied, and nothing it writes is removed. The held original is copied to a
|
||||
/// staged path ([`stage_copy`]), published without replacing anything ([`publish`]), and only
|
||||
/// then removed. If the copy or publish fails, the held original is put back ([`put_back`]).
|
||||
fn move_across(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let held = hold(from)?;
|
||||
match stage_copy(&held, to).and_then(|staged| publish(&staged, to)) {
|
||||
Ok(()) => {
|
||||
let removed = if std::fs::symlink_metadata(&held)?.is_dir() { std::fs::remove_dir_all(&held) } else { std::fs::remove_file(&held) };
|
||||
if let Err(e) = removed {
|
||||
log::warn!("copied {} to {} but couldn't remove {}: {e}", from.display(), to.display(), held.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
put_back(&held, from);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename `from` aside on its own volume (see [`move_across`]); returns where it is now.
|
||||
fn hold(from: &Path) -> std::io::Result<PathBuf> {
|
||||
let held = side_path(from, HELD)?;
|
||||
std::fs::rename(from, &held)?;
|
||||
Ok(held)
|
||||
}
|
||||
|
||||
/// Return the held original `held` to `original`. If `original` has been made again meanwhile (a
|
||||
/// writer that kept using the old path), the held folder's entries move into it without replacing
|
||||
/// anything ([`move_entries`]); whatever can't move stays held, logged, and is tried again under
|
||||
/// the next move's lock ([`adopt_locked`] puts back what a process that ended mid-move held).
|
||||
/// Nothing held is ever removed with data in it.
|
||||
fn put_back(held: &Path, original: &Path) {
|
||||
if std::fs::symlink_metadata(original).is_err() && std::fs::rename(held, original).is_ok() {
|
||||
return;
|
||||
}
|
||||
if held.is_dir() && original.is_dir() {
|
||||
move_entries(held, original);
|
||||
if std::fs::remove_dir(held).is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
log::warn!("{} is kept aside: {} exists", held.display(), original.display());
|
||||
}
|
||||
|
||||
/// Copy `from` to a staging path beside `to` that this call creates exclusively, so nothing
|
||||
/// another process made is ever written to or cleaned up. On failure the staged copy is removed.
|
||||
fn stage_copy(from: &Path, to: &Path) -> std::io::Result<PathBuf> {
|
||||
let staged = side_path(to, STAGED)?;
|
||||
let is_dir = std::fs::symlink_metadata(from)?.is_dir();
|
||||
let copied = if is_dir { copy_tree(from, &staged, 0) } else { copy_file(from, &staged) };
|
||||
if let Err(e) = copied {
|
||||
// `copy_tree` and `copy_file` create `staged` exclusively, and everything under a
|
||||
// fresh folder is new: `AlreadyExists` means `staged` was someone else's to keep.
|
||||
if e.kind() != std::io::ErrorKind::AlreadyExists {
|
||||
let _ = if is_dir { std::fs::remove_dir_all(&staged) } else { std::fs::remove_file(&staged) };
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// Remove copies a process left staged in `folder` when it ended mid-move: disposable, since the
|
||||
/// original is still in place or held aside. Called only under the migration lock, which every
|
||||
/// staging happens under. Links are never followed.
|
||||
fn remove_stale_staging(folder: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(folder) else { return };
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_name().to_str().is_none_or(|n| side_of(n, STAGED).is_none()) {
|
||||
continue;
|
||||
}
|
||||
let removed = match entry.file_type() {
|
||||
Ok(t) if t.is_dir() => std::fs::remove_dir_all(entry.path()),
|
||||
Ok(t) if t.is_file() => std::fs::remove_file(entry.path()),
|
||||
_ => continue,
|
||||
};
|
||||
if let Err(e) = removed {
|
||||
log::warn!("couldn't remove the stale staged copy {}: {e}", entry.path().display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the staged copy its final name `to` without replacing anything there (see [`move_path`]
|
||||
/// for the folder and file cases). On failure the staged copy is removed and `to` is untouched.
|
||||
fn publish(staged: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let is_dir = std::fs::symlink_metadata(staged)?.is_dir();
|
||||
let published = if std::fs::symlink_metadata(to).is_ok() {
|
||||
Err(already_exists(to))
|
||||
} else if is_dir {
|
||||
std::fs::rename(staged, to)
|
||||
} else {
|
||||
std::fs::hard_link(staged, to).and_then(|()| std::fs::remove_file(staged))
|
||||
};
|
||||
if published.is_err() {
|
||||
let _ = if is_dir { std::fs::remove_dir_all(staged) } else { std::fs::remove_file(staged) };
|
||||
}
|
||||
published
|
||||
}
|
||||
|
||||
/// Copy the folder `from` to the new folder `to` (created here; an existing `to` is an error):
|
||||
/// plain files and folders only (a link or other special file is refused), at most
|
||||
/// [`MAX_COPY_DEPTH`] levels.
|
||||
fn copy_tree(from: &Path, to: &Path, depth: u32) -> std::io::Result<()> {
|
||||
if depth > MAX_COPY_DEPTH {
|
||||
return Err(std::io::Error::other(format!("{} is nested too deep", from.display())));
|
||||
}
|
||||
std::fs::create_dir(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let target = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &target, depth.saturating_add(1))?;
|
||||
} else {
|
||||
copy_file(&entry.path(), &target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy one plain file (a link or other special file is refused) to the new file `to` (an
|
||||
/// existing `to` is an error), flushed to disk.
|
||||
fn copy_file(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if !std::fs::symlink_metadata(from)?.file_type().is_file() {
|
||||
return Err(std::io::Error::other(format!("{} is not a plain file", from.display())));
|
||||
}
|
||||
let mut src = std::fs::File::open(from)?;
|
||||
let mut dst = std::fs::OpenOptions::new().write(true).create_new(true).open(to)?;
|
||||
std::io::copy(&mut src, &mut dst)?;
|
||||
dst.sync_all()
|
||||
}
|
||||
|
||||
/// Resolve the data directory from the environment (`env`) and the executable's folder.
|
||||
pub fn resolve(env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> DataDir {
|
||||
if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) {
|
||||
@@ -109,126 +502,4 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let m: HashMap<String, OsString> = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect();
|
||||
move |k| m.get(k).cloned()
|
||||
}
|
||||
|
||||
/// A fake user folder that every platform's convention resolves under.
|
||||
fn fake_home(root: &Path) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let home = root.join("home");
|
||||
let appdata = root.join("appdata");
|
||||
env_of(&[("HOME", &home), ("APPDATA", &appdata)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_marker_uses_the_platform_dir() {
|
||||
let root = temp("platform");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
let env = fake_home(&root);
|
||||
let d = resolve(&env, Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
assert_eq!(Some(dir.clone()), platform_dir(&env));
|
||||
assert!(!dir.starts_with(&exe));
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker");
|
||||
// The convention per platform.
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(dir, root.join("home/Library/Application Support/Photocraft"));
|
||||
} else if cfg!(windows) {
|
||||
assert_eq!(dir, root.join("appdata").join("Photocraft"));
|
||||
} else {
|
||||
assert_eq!(dir, root.join("home/.config/photocraft"));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_marker_keeps_everything_beside_the_exe() {
|
||||
for marker in PORTABLE_MARKERS {
|
||||
let root = temp("portable");
|
||||
let exe = root.join("PhotoCraft");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join(marker), b"").unwrap();
|
||||
let d = resolve(fake_home(&root), Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Portable, "{marker}");
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
assert_eq!(dir, exe.join(PORTABLE_DATA_DIR));
|
||||
assert!(dir.is_dir(), "the data folder is created");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed");
|
||||
// Every derived path sits under the exe dir.
|
||||
for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] {
|
||||
assert!(dir.join(sub).starts_with(&exe));
|
||||
}
|
||||
assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_folder_is_not_a_marker() {
|
||||
let root = temp("dir-marker");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(exe.join("portable.txt")).unwrap();
|
||||
assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritable_portable_folder_falls_back_with_a_warning() {
|
||||
let root = temp("unwritable");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
// A file where the data folder should go: it can't be created, on every platform.
|
||||
std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap();
|
||||
let env = fake_home(&root);
|
||||
let d = resolve(&env, Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert_eq!(d.dir, platform_dir(&env));
|
||||
let w = d.warning.unwrap();
|
||||
assert!(w.contains("portable") && w.contains("isn't writable"), "{w}");
|
||||
// No user folder at all: still no panic, just no directory.
|
||||
let d = resolve(|_| None, Some(&exe));
|
||||
assert!(d.dir.is_none() && d.warning.is_some());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_wins_over_portable() {
|
||||
let root = temp("override");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
let custom = root.join("custom");
|
||||
let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe));
|
||||
assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom)));
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_exe_dir_or_env_never_panics() {
|
||||
let d = resolve(|_| None, None);
|
||||
assert_eq!((d.mode, d.dir), (Mode::Platform, None));
|
||||
let empty = PathBuf::new();
|
||||
let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None);
|
||||
assert_eq!(d.dir, None, "empty variables are ignored");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let m: HashMap<String, OsString> = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect();
|
||||
move |k| m.get(k).cloned()
|
||||
}
|
||||
|
||||
/// A fake user folder that every platform's convention resolves under.
|
||||
fn fake_home(root: &Path) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let home = root.join("home");
|
||||
let appdata = root.join("appdata");
|
||||
env_of(&[("HOME", &home), ("APPDATA", &appdata)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_marker_uses_the_platform_dir() {
|
||||
let root = temp("platform");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
let env = fake_home(&root);
|
||||
let d = resolve(&env, Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
assert_eq!(Some(dir.clone()), platform_dir(&env));
|
||||
assert!(!dir.starts_with(&exe));
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker");
|
||||
// The convention per platform.
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(dir, root.join("home/Library/Application Support/Photocraft"));
|
||||
} else if cfg!(windows) {
|
||||
assert_eq!(dir, root.join("appdata").join("Photocraft"));
|
||||
} else {
|
||||
assert_eq!(dir, root.join("home/.config/photocraft"));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_marker_keeps_everything_beside_the_exe() {
|
||||
for marker in PORTABLE_MARKERS {
|
||||
let root = temp("portable");
|
||||
let exe = root.join("PhotoCraft");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join(marker), b"").unwrap();
|
||||
let d = resolve(fake_home(&root), Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Portable, "{marker}");
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
assert_eq!(dir, exe.join(PORTABLE_DATA_DIR));
|
||||
assert!(dir.is_dir(), "the data folder is created");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed");
|
||||
// Every derived path sits under the exe dir.
|
||||
for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] {
|
||||
assert!(dir.join(sub).starts_with(&exe));
|
||||
}
|
||||
assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_folder_is_not_a_marker() {
|
||||
let root = temp("dir-marker");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(exe.join("portable.txt")).unwrap();
|
||||
assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritable_portable_folder_falls_back_with_a_warning() {
|
||||
let root = temp("unwritable");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
// A file where the data folder should go: it can't be created, on every platform.
|
||||
std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap();
|
||||
let env = fake_home(&root);
|
||||
let d = resolve(&env, Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert_eq!(d.dir, platform_dir(&env));
|
||||
let w = d.warning.unwrap();
|
||||
assert!(w.contains("portable") && w.contains("isn't writable"), "{w}");
|
||||
// No user folder at all: still no panic, just no directory.
|
||||
let d = resolve(|_| None, Some(&exe));
|
||||
assert!(d.dir.is_none() && d.warning.is_some());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_wins_over_portable() {
|
||||
let root = temp("override");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
let custom = root.join("custom");
|
||||
let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe));
|
||||
assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom)));
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming
|
||||
/// profile; an override or portable folder keeps them inside itself.
|
||||
#[test]
|
||||
fn autosaves_stay_out_of_the_roaming_profile() {
|
||||
let root = temp("recovery-local");
|
||||
let settings = root.join("appdata").join("Photocraft");
|
||||
let local = root.join("local");
|
||||
let env = env_of(&[("LOCALAPPDATA", &local)]);
|
||||
let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None };
|
||||
let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") };
|
||||
assert_eq!(resolve_recovery(&platform, &env), Some(expected));
|
||||
for mode in [Mode::Override, Mode::Portable] {
|
||||
let d = DataDir { dir: Some(settings.clone()), mode, warning: None };
|
||||
assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}");
|
||||
}
|
||||
// No (or an empty) LOCALAPPDATA: beside the settings, as before.
|
||||
let empty = PathBuf::new();
|
||||
assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery")));
|
||||
assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery")));
|
||||
let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None };
|
||||
assert_eq!(resolve_recovery(&nowhere, |_| None), None);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default
|
||||
/// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows
|
||||
/// and macOS don't read it, and an override or portable folder keeps them inside itself.
|
||||
#[test]
|
||||
fn autosaves_go_to_the_xdg_state_folder() {
|
||||
let root = temp("recovery-xdg");
|
||||
let settings = root.join("home").join(".config").join("photocraft");
|
||||
let home = root.join("home");
|
||||
let state = root.join("state");
|
||||
let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None };
|
||||
let xdg = !cfg!(windows) && !cfg!(target_os = "macos");
|
||||
let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") });
|
||||
assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery")));
|
||||
let default = home.join(".local").join("state").join("photocraft").join("Recovery");
|
||||
assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone()));
|
||||
let relative = PathBuf::from("relative/state");
|
||||
assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone()));
|
||||
let empty = PathBuf::new();
|
||||
assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default));
|
||||
// No home at all: beside the settings, as before.
|
||||
assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery")));
|
||||
for mode in [Mode::Override, Mode::Portable] {
|
||||
let d = DataDir { dir: Some(settings.clone()), mode, warning: None };
|
||||
assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// An autosave bundle and its sidecar, as `format::Autosaver` writes them.
|
||||
fn autosave(dir: &Path, key: &str) {
|
||||
std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap();
|
||||
std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap();
|
||||
std::fs::write(dir.join(format!("{key}.json")), key).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosaves_from_the_old_folder_move_to_the_new_one() {
|
||||
let root = temp("recovery-move");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
let dir = root.join("local").join("Photocraft").join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir);
|
||||
assert!(!legacy.exists(), "the old folder is gone");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a");
|
||||
assert!(dir.join("a.json").is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosaves_merge_into_an_existing_folder_without_overwriting() {
|
||||
let root = temp("recovery-merge");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
let dir = root.join("local").join("Recovery");
|
||||
autosave(&legacy, "old");
|
||||
autosave(&legacy, "both");
|
||||
// A temp file of an interrupted write moves along, for the recovery store's sweep.
|
||||
let temp_file = ".old.json.4294967294-0.pcsave.tmp";
|
||||
std::fs::write(legacy.join(temp_file), b"partial").unwrap();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("both.json"), "newer").unwrap();
|
||||
assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir);
|
||||
assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists());
|
||||
assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten");
|
||||
assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split");
|
||||
assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosaves_that_cannot_move_keep_being_used_where_they_are() {
|
||||
let root = temp("recovery-stuck");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
// A file where the new folder's parent should be: nothing can be created there.
|
||||
std::fs::write(root.join("blocked"), b"in the way").unwrap();
|
||||
let dir = root.join("blocked").join("Recovery");
|
||||
assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy);
|
||||
assert!(legacy.join("a.json").is_file(), "nothing lost");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_old_folder_is_removed_even_where_it_cannot_move() {
|
||||
let root = temp("recovery-empty");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
std::fs::create_dir_all(&legacy).unwrap();
|
||||
std::fs::write(root.join("blocked"), b"in the way").unwrap();
|
||||
let dir = root.join("blocked").join("Recovery");
|
||||
assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed");
|
||||
assert!(!legacy.exists(), "the empty old folder is gone");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Where a rename can't cross volumes (a roaming profile on a network share), an autosave
|
||||
/// is copied whole, nested folders included, and only then removed.
|
||||
#[test]
|
||||
fn a_move_across_volumes_copies_then_removes() {
|
||||
let root = temp("recovery-copy");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap();
|
||||
std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap();
|
||||
let dir = root.join("local").join("Recovery");
|
||||
std::fs::create_dir_all(root.join("local")).unwrap();
|
||||
move_across(&legacy, &dir).unwrap();
|
||||
assert!(!legacy.exists(), "the original is removed after the copy");
|
||||
assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a");
|
||||
assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a");
|
||||
// One file on its own, as the per-autosave moves do.
|
||||
move_across(&dir.join("a.json"), &root.join("a.json")).unwrap();
|
||||
assert!(!dir.join("a.json").exists() && root.join("a.json").is_file());
|
||||
assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() {
|
||||
let root = temp("recovery-copy-fail");
|
||||
let legacy = root.join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
// Deeper than any bundle: the copy gives up part way.
|
||||
let mut deep = legacy.join("a.pcraft");
|
||||
for _ in 0..=MAX_COPY_DEPTH {
|
||||
deep = deep.join("d");
|
||||
}
|
||||
std::fs::create_dir_all(&deep).unwrap();
|
||||
let dir = root.join("Local");
|
||||
assert!(move_across(&legacy, &dir).is_err());
|
||||
assert!(!dir.exists(), "nothing is published");
|
||||
assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside");
|
||||
assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place");
|
||||
// A target that already exists is never copied into or removed.
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("keep"), b"mine").unwrap();
|
||||
assert!(move_across(&legacy.join("a.json"), &dir).is_err());
|
||||
assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine");
|
||||
assert!(legacy.join("a.json").is_file());
|
||||
assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Staged (`.moving`) and held (`.held`) side paths left in `dir`.
|
||||
fn side_leftovers(dir: &Path) -> usize {
|
||||
std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some()))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The target appears after the copy is staged (another process got there first): publishing
|
||||
/// fails, that process's target keeps its contents, the staged copy is removed and the
|
||||
/// original is left as it was. Folder and file alike.
|
||||
#[test]
|
||||
fn a_target_that_appears_while_copying_is_never_replaced_or_removed() {
|
||||
let root = temp("recovery-race");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
let local = root.join("local");
|
||||
std::fs::create_dir_all(&local).unwrap();
|
||||
// A whole folder.
|
||||
let dir = local.join("Recovery");
|
||||
let staged = stage_copy(&legacy, &dir).unwrap();
|
||||
autosave(&dir, "theirs");
|
||||
let e = publish(&staged, &dir).unwrap_err();
|
||||
assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact");
|
||||
assert!(!dir.join("a.json").exists(), "nothing was copied into it");
|
||||
assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed");
|
||||
assert!(legacy.join("a.json").is_file(), "the original is untouched");
|
||||
// One file.
|
||||
let to = dir.join("a.json");
|
||||
let staged = stage_copy(&legacy.join("a.json"), &to).unwrap();
|
||||
std::fs::write(&to, "theirs").unwrap();
|
||||
assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs");
|
||||
assert!(!staged.exists() && legacy.join("a.json").is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A process holds the lock and is copying the old folder (held aside, copy staged) when a
|
||||
/// second launch gives up waiting. The second launch must get the new folder, never the old
|
||||
/// one, and what it writes there survives the first one finishing: the publish refuses the
|
||||
/// now-existing folder and the original is put back, so both autosaves stay (#6412 review).
|
||||
#[test]
|
||||
fn a_launch_that_times_out_never_writes_where_a_move_removes() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let root = temp("recovery-timeout");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "old");
|
||||
let local = root.join("local");
|
||||
std::fs::create_dir_all(&local).unwrap();
|
||||
let dir = local.join("Recovery");
|
||||
// First process: takes the lock, sets the original aside and stages its copy, then pauses.
|
||||
let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap();
|
||||
first.lock().unwrap();
|
||||
let held = hold(&legacy).unwrap();
|
||||
let staged = stage_copy(&held, &dir).unwrap();
|
||||
// Second launch: times out and writes a newer autosave where it was told to.
|
||||
let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO);
|
||||
assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder");
|
||||
autosave(&chosen, "new");
|
||||
// First process resumes: publish, and on failure put the original back (as `move_across`).
|
||||
assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists);
|
||||
put_back(&held, &legacy);
|
||||
drop(first);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives");
|
||||
assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place");
|
||||
assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0);
|
||||
// The next launch merges them.
|
||||
assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir);
|
||||
assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A writer that still uses the old path while it is being copied (an older PhotoCraft)
|
||||
/// starts a new folder there; the move removes only the original it held aside.
|
||||
#[test]
|
||||
fn a_write_to_the_old_path_during_a_copy_is_not_removed() {
|
||||
let root = temp("recovery-old-writer");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "old");
|
||||
let local = root.join("local");
|
||||
std::fs::create_dir_all(&local).unwrap();
|
||||
let dir = local.join("Recovery");
|
||||
let held = hold(&legacy).unwrap();
|
||||
let staged = stage_copy(&held, &dir).unwrap();
|
||||
autosave(&legacy, "new");
|
||||
publish(&staged, &dir).unwrap();
|
||||
std::fs::remove_dir_all(&held).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old");
|
||||
assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// What a process killed mid-move left is tidied at the next move: a held original is put
|
||||
/// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and
|
||||
/// look-alike names are not touched.
|
||||
#[test]
|
||||
fn a_killed_move_is_tidied_next_time() {
|
||||
let root = temp("recovery-stale");
|
||||
let roaming = root.join("roaming");
|
||||
let legacy = roaming.join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
let held = hold(&legacy).unwrap();
|
||||
assert!(!legacy.exists() && held.is_dir());
|
||||
let local = root.join("local");
|
||||
let dir = local.join("Recovery");
|
||||
let stale = local.join(".Recovery.4294967294-3.moving");
|
||||
autosave(&stale, "half");
|
||||
let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")];
|
||||
for k in &kept {
|
||||
std::fs::write(k, b"x").unwrap();
|
||||
}
|
||||
assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved");
|
||||
assert!(!stale.exists(), "the stale staged copy is gone");
|
||||
assert_eq!(side_leftovers(&roaming), 0);
|
||||
assert!(kept.iter().all(|k| k.is_file()), "only side names are touched");
|
||||
assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json"));
|
||||
assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none());
|
||||
assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// While another process holds the move lock, a launch moves nothing and uses the new folder;
|
||||
/// once the lock is released, the move happens.
|
||||
#[test]
|
||||
fn a_move_waits_for_another_process_holding_the_lock() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let root = temp("recovery-lock");
|
||||
let legacy = root.join("roaming").join("Recovery");
|
||||
autosave(&legacy, "a");
|
||||
let dir = root.join("local").join("Recovery");
|
||||
std::fs::create_dir_all(root.join("local")).unwrap();
|
||||
let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap();
|
||||
held.lock().unwrap();
|
||||
assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir);
|
||||
assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock");
|
||||
drop(held);
|
||||
assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir);
|
||||
assert!(dir.join("a.json").is_file() && !legacy.exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_old_folder_or_the_same_folder_changes_nothing() {
|
||||
let root = temp("recovery-noop");
|
||||
let dir = root.join("Recovery");
|
||||
assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir);
|
||||
assert!(!dir.exists(), "nothing is created up front");
|
||||
autosave(&dir, "a");
|
||||
assert_eq!(adopt_legacy_recovery(&dir, &dir), dir);
|
||||
assert!(dir.join("a.json").is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_exe_dir_or_env_never_panics() {
|
||||
let d = resolve(|_| None, None);
|
||||
assert_eq!((d.mode, d.dir), (Mode::Platform, None));
|
||||
let empty = PathBuf::new();
|
||||
let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None);
|
||||
assert_eq!(d.dir, None, "empty variables are ignored");
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
//! be stamped on the shortcut, or the taskbar would stop matching the two.
|
||||
|
||||
/// Window, taskbar and (when running unbundled) Dock icon. macOS gets the padded 1024 px render
|
||||
/// on Apple's icon grid; elsewhere the tighter 256 px hicolor render reads better at small sizes.
|
||||
/// on Apple's icon grid; elsewhere the 256 px hicolor render of the full tile.
|
||||
pub fn window_icon() -> egui::IconData {
|
||||
match eframe::icon_data::from_png_bytes(PNG) {
|
||||
Ok(icon) => icon,
|
||||
@@ -34,6 +34,13 @@ pub fn sets_runtime_icon(exe: Option<&std::path::Path>) -> bool {
|
||||
!(cfg!(target_os = "macos") && exe.is_some_and(in_app_bundle))
|
||||
}
|
||||
|
||||
/// Value for [`egui::ViewportBuilder::with_icon`]: [`window_icon`] when [`sets_runtime_icon`]
|
||||
/// is true; otherwise [`egui::IconData::default`] so eframe does not substitute its own icon
|
||||
/// on the Dock after the window opens (#7253).
|
||||
pub fn viewport_icon(exe: Option<&std::path::Path>) -> egui::IconData {
|
||||
if sets_runtime_icon(exe) { window_icon() } else { egui::IconData::default() }
|
||||
}
|
||||
|
||||
/// Whether `exe` is an app bundle's executable: `…/Name.app/Contents/MacOS/binary`.
|
||||
fn in_app_bundle(exe: &std::path::Path) -> bool {
|
||||
let name = |p: Option<&std::path::Path>| p.and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned());
|
||||
@@ -80,6 +87,19 @@ mod tests {
|
||||
assert_eq!(sets_runtime_icon(Some(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft"))), !cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
/// #7253: omitting `with_icon` made eframe paint its default glyph on the Dock once the window loaded.
|
||||
#[test]
|
||||
fn viewport_icon_blocks_eframe_default_when_runtime_icon_is_skipped() {
|
||||
use std::path::Path;
|
||||
let bundled = Some(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft"));
|
||||
if sets_runtime_icon(bundled) {
|
||||
let icon = viewport_icon(bundled);
|
||||
assert!(icon.width >= 256 && icon.width == icon.height);
|
||||
} else {
|
||||
assert_eq!(viewport_icon(bundled), egui::IconData::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_icon_decodes() {
|
||||
let icon = window_icon();
|
||||
@@ -88,6 +108,16 @@ mod tests {
|
||||
assert!(icon.rgba.chunks(4).any(|p| p[3] > 0), "the icon isn't blank");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_and_linux_icons_keep_the_round_corners() {
|
||||
// rx=112 of 512 leaves (10, 10) of a 256 px render transparent; the old crop filled it (#4478).
|
||||
let png = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png");
|
||||
let icon = eframe::icon_data::from_png_bytes(png).unwrap();
|
||||
assert_eq!(icon.width, 256);
|
||||
assert_eq!(icon.rgba[(10 * 256 + 10) * 4 + 3], 0, "corner is transparent");
|
||||
assert_eq!(icon.rgba[(128 * 256 + 2) * 4 + 3], 255, "the tile is full bleed");
|
||||
}
|
||||
|
||||
/// The `.ico` build.rs embeds: every size Windows asks for, each a valid PNG or BMP image.
|
||||
#[test]
|
||||
fn exe_icon_has_every_shell_size() {
|
||||
|
||||
@@ -16,16 +16,11 @@ use photocraft_ui_egui::ControlRequest;
|
||||
use photocraft_ui_egui::control::REPLY_DEADLINE;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
/// Start serving a listener already bound during startup, before a window is opened.
|
||||
pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
return rx;
|
||||
}
|
||||
};
|
||||
eprintln!("photocraft: control server listening on 127.0.0.1:{port}");
|
||||
let port = listener.local_addr().map_or(0, |a| a.port());
|
||||
eprintln!("photocraft: control server listening on {}", listening_addr(&listener, port));
|
||||
std::thread::spawn(move || {
|
||||
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
|
||||
let token = Arc::new(token);
|
||||
@@ -47,6 +42,16 @@ pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver<ControlRe
|
||||
rx
|
||||
}
|
||||
|
||||
/// The address `listener` is bound to: with `--control 0` the OS picks the port, and a client
|
||||
/// needs that one, not the requested 0 (#6427). Falls back to the requested port if the OS
|
||||
/// can't report it.
|
||||
fn listening_addr(listener: &TcpListener, requested_port: u16) -> String {
|
||||
match listener.local_addr() {
|
||||
Ok(addr) => addr.to_string(),
|
||||
Err(_) => format!("127.0.0.1:{requested_port}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
|
||||
serve_with_auth_deadline(stream, token, tx, ctx, AUTH_DEADLINE);
|
||||
}
|
||||
@@ -131,6 +136,41 @@ mod tests {
|
||||
use super::*;
|
||||
use std::io::BufRead;
|
||||
|
||||
/// #6427: with port 0 the log names the port the OS bound, which a client can connect to.
|
||||
#[test]
|
||||
fn port_zero_logs_the_bound_port() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let bound = listener.local_addr().unwrap();
|
||||
assert_ne!(bound.port(), 0);
|
||||
let logged = listening_addr(&listener, 0);
|
||||
assert_eq!(logged, format!("127.0.0.1:{}", bound.port()));
|
||||
TcpStream::connect(&logged).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prebound_listener_authenticates_and_dispatches_requests() {
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let requests = start(listener, TOKEN.into(), egui::Context::default());
|
||||
let mut stream = TcpStream::connect(address).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut replies = BufReader::new(stream.try_clone().unwrap());
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
|
||||
let mut line = String::new();
|
||||
replies.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true);
|
||||
writeln!(stream, "{}", json!({"id": 2, "method": "test.bound"})).unwrap();
|
||||
let request = requests.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(request.method, "test.bound");
|
||||
request.reply.send(json!({"ok": true, "result": "served"})).unwrap();
|
||||
line.clear();
|
||||
replies.read_line(&mut line).unwrap();
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(reply["id"], 2);
|
||||
assert_eq!(reply["result"], "served");
|
||||
}
|
||||
|
||||
/// #4965: a connection that keeps sending without authenticating is closed at the deadline
|
||||
/// (releasing its connection permit), and nothing it sent is dispatched.
|
||||
#[test]
|
||||
|
||||
@@ -70,25 +70,61 @@ pub fn start() {
|
||||
|
||||
/// Whether the portal's `FileChooser` interface is on the session bus: `Some(false)` only when the
|
||||
/// bus or the interface is definitely absent, `None` for anything inconclusive (a slow reply).
|
||||
///
|
||||
/// Asks the portal object to introspect itself rather than reading the interface's `version`
|
||||
/// property: xdg-desktop-portal exports `FileChooser` only when a backend offers it, and without
|
||||
/// one a property read fails with `InvalidArgs` ("No such interface"), an error the old check
|
||||
/// didn't count as absent (#5739). The interface list answers the question directly.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn file_chooser_portal() -> Option<bool> {
|
||||
let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) else {
|
||||
return Some(false);
|
||||
};
|
||||
let proxy = zbus::blocking::proxy::Builder::<zbus::blocking::Proxy<'_>>::new(&conn)
|
||||
.destination("org.freedesktop.portal.Desktop")
|
||||
.and_then(|b| b.path("/org/freedesktop/portal/desktop"))
|
||||
.and_then(|b| b.interface("org.freedesktop.portal.FileChooser"))
|
||||
.and_then(|b| b.cache_properties(zbus::proxy::CacheProperties::No).build())
|
||||
.ok()?;
|
||||
match proxy.get_property::<u32>("version") {
|
||||
Ok(_) => Some(true),
|
||||
Err(zbus::Error::MethodError(name, _, _)) => {
|
||||
let name = name.as_str();
|
||||
let absent = ["ServiceUnknown", "UnknownObject", "UnknownInterface", "UnknownProperty"].iter().any(|n| name.ends_with(n));
|
||||
absent.then_some(false)
|
||||
}
|
||||
Err(_) => None,
|
||||
let reply = conn.call_method(
|
||||
Some("org.freedesktop.portal.Desktop"),
|
||||
"/org/freedesktop/portal/desktop",
|
||||
Some("org.freedesktop.DBus.Introspectable"),
|
||||
"Introspect",
|
||||
&(),
|
||||
);
|
||||
match reply {
|
||||
Ok(message) => match message.body().deserialize::<String>() {
|
||||
Ok(xml) => Some(interface_listed(&xml)),
|
||||
Err(_) => None,
|
||||
},
|
||||
Err(e) => classify_error(&e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether introspection XML lists the portal's `FileChooser` interface (not a longer name such as
|
||||
/// `FileChooser2`).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn interface_listed(xml: &str) -> bool {
|
||||
["\"", "'"].iter().any(|quote| xml.contains(&format!("<interface name={quote}org.freedesktop.portal.FileChooser{quote}")))
|
||||
}
|
||||
|
||||
/// What a failed call says about the interface: `Some(false)` when the D-Bus error means the
|
||||
/// service, object or interface isn't there, `None` for anything else (a timeout, a dropped
|
||||
/// connection, an unknown error), which counts as present.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn classify_error(e: &zbus::Error) -> Option<bool> {
|
||||
use zbus::fdo::Error as Fdo;
|
||||
// Names a bus daemon or portal answers with when the thing asked about is absent.
|
||||
const ABSENT: [&str; 7] = ["ServiceUnknown", "NameHasNoOwner", "UnknownObject", "UnknownInterface", "UnknownMethod", "UnknownProperty", "InvalidArgs"];
|
||||
match e {
|
||||
zbus::Error::FDO(fdo) => matches!(
|
||||
**fdo,
|
||||
Fdo::ServiceUnknown(_)
|
||||
| Fdo::NameHasNoOwner(_)
|
||||
| Fdo::UnknownObject(_)
|
||||
| Fdo::UnknownInterface(_)
|
||||
| Fdo::UnknownMethod(_)
|
||||
| Fdo::UnknownProperty(_)
|
||||
| Fdo::InvalidArgs(_)
|
||||
)
|
||||
.then_some(false),
|
||||
zbus::Error::MethodError(name, _, _) => ABSENT.iter().any(|n| name.as_str().ends_with(n)).then_some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,4 +162,69 @@ mod tests {
|
||||
assert!(!on_path("kdialog", &path));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod portal {
|
||||
use super::super::*;
|
||||
|
||||
const WITH_FILE_CHOOSER: &str = r#"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/introspect.dtd">
|
||||
<node>
|
||||
<interface name="org.freedesktop.DBus.Peer"/>
|
||||
<interface name="org.freedesktop.portal.Settings"><property name="version" type="u" access="read"/></interface>
|
||||
<interface name="org.freedesktop.portal.FileChooser">
|
||||
<method name="OpenFile"/>
|
||||
</interface>
|
||||
</node>"#;
|
||||
const WITHOUT_FILE_CHOOSER: &str = r#"<node>
|
||||
<interface name="org.freedesktop.DBus.Peer"/>
|
||||
<interface name="org.freedesktop.portal.Settings"/>
|
||||
</node>"#;
|
||||
|
||||
fn method_error(name: &'static str) -> zbus::Error {
|
||||
let call = zbus::message::Message::method_call("/a", "M").unwrap().build(&()).unwrap();
|
||||
let reply = zbus::message::Message::error(&call.header(), name).unwrap().build(&"detail").unwrap();
|
||||
zbus::Error::MethodError(name.try_into().unwrap(), Some("detail".into()), reply)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_interface_list_says_whether_a_file_chooser_is_offered() {
|
||||
assert!(interface_listed(WITH_FILE_CHOOSER));
|
||||
assert!(interface_listed("<interface name='org.freedesktop.portal.FileChooser'>"), "single quotes");
|
||||
assert!(!interface_listed(WITHOUT_FILE_CHOOSER), "portal without a backend");
|
||||
assert!(!interface_listed(r#"<interface name="org.freedesktop.portal.FileChooser2">"#), "longer name");
|
||||
assert!(!interface_listed(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dbus_errors_for_a_missing_interface_mean_absent() {
|
||||
// zbus's fdo proxies hand D-Bus errors back as `Error::FDO`, a plain method call as
|
||||
// `MethodError`; both forms count. The portal answers `InvalidArgs` ("No such interface")
|
||||
// when no backend offers the interface (#5739).
|
||||
for e in [
|
||||
zbus::fdo::Error::InvalidArgs("No such interface".into()),
|
||||
zbus::fdo::Error::UnknownInterface("x".into()),
|
||||
zbus::fdo::Error::ServiceUnknown("x".into()),
|
||||
zbus::fdo::Error::NameHasNoOwner("x".into()),
|
||||
zbus::fdo::Error::UnknownObject("x".into()),
|
||||
] {
|
||||
let desc = format!("{e:?}");
|
||||
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(e))), Some(false), "{desc}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_error_names_still_count_as_absent() {
|
||||
for name in ["org.freedesktop.DBus.Error.ServiceUnknown", "org.freedesktop.DBus.Error.InvalidArgs", "org.freedesktop.DBus.Error.UnknownMethod"] {
|
||||
assert_eq!(classify_error(&method_error(name)), Some(false), "{name}");
|
||||
}
|
||||
assert_eq!(classify_error(&method_error("org.freedesktop.DBus.Error.AccessDenied")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inconclusive_errors_are_not_absent() {
|
||||
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::NoReply("slow".into())))), None);
|
||||
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::Failed("x".into())))), None);
|
||||
assert_eq!(classify_error(&zbus::Error::InputOutput(std::sync::Arc::new(std::io::Error::other("gone")))), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@
|
||||
//! - macOS: Metal → CPU
|
||||
//!
|
||||
//! The choice that worked is remembered in `performance.gpuBackend` (Preferences › Performance,
|
||||
//! where it can be reset). With `auto`, Intel adapters on Windows use DX12. `WGPU_BACKEND` still
|
||||
//! overrides everything, and `--safe-gpu` forces the CPU path for one launch.
|
||||
//! where it can be reset). With `auto`, Intel and Qualcomm (Windows on ARM) adapters on Windows
|
||||
//! use DX12, and when DXGI lists an Intel adapter the instance leaves Vulkan out, so the first
|
||||
//! start doesn't load the Intel Vulkan driver either. `WGPU_BACKEND` still overrides everything,
|
||||
//! and `--safe-gpu` forces the CPU path for one launch.
|
||||
//!
|
||||
//! "CPU" composites on the CPU and draws the window with a software adapter where the platform
|
||||
//! has one (WARP on Windows, llvmpipe over GL elsewhere). On Linux a GL adapter that can't present
|
||||
@@ -33,6 +35,10 @@ use serde_json::{Value, json};
|
||||
pub const MARKER_FILE: &str = "gpu-starting.json";
|
||||
/// PCI vendor id of Intel.
|
||||
pub const INTEL: u32 = 0x8086;
|
||||
/// Qualcomm's vendor id as its Vulkan driver reports it.
|
||||
pub const QUALCOMM: u32 = 0x5143;
|
||||
/// Qualcomm's vendor id as DXGI (DX12) reports it: "QCOM".
|
||||
pub const QUALCOMM_DXGI: u32 = 0x4D4F_4351;
|
||||
/// Largest marker read (a marker is a few hundred bytes).
|
||||
const MARKER_MAX: u64 = 64 << 10;
|
||||
|
||||
@@ -204,6 +210,28 @@ pub fn backends(plan: &Plan, os: Os) -> Option<wgpu::Backends> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Instance backends for `auto` on Windows (no `WGPU_BACKEND`) when `dx12_vendors`, the PCI vendor
|
||||
/// ids of the DX12 adapters, includes Intel: DX12, with GL as the last resort (see [`rank`]). An
|
||||
/// instance with Vulkan loads the Intel Vulkan driver before the adapter selector runs, and #4's
|
||||
/// crash is in that driver. `dx12_vendors` is called only for that plan; `None` keeps [`backends`]'
|
||||
/// choice.
|
||||
pub fn windows_auto_backends(plan: &Plan, os: Os, dx12_vendors: impl FnOnce() -> Vec<u32>) -> Option<wgpu::Backends> {
|
||||
let auto = plan.env.is_none() && plan.backend == GpuBackend::Auto && os == Os::Windows;
|
||||
(auto && dx12_vendors().contains(&INTEL)).then_some(wgpu::Backends::DX12 | wgpu::Backends::GL)
|
||||
}
|
||||
|
||||
/// The PCI vendor ids of the DX12 adapters, from a DX12-only instance (DXGI, no Vulkan driver)
|
||||
/// with `desc`'s flags and backend options (the shader compiler from [`dx12_compiler`]).
|
||||
fn dx12_vendors(desc: &wgpu::InstanceDescriptor) -> Vec<u32> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::DX12,
|
||||
flags: desc.flags,
|
||||
backend_options: desc.backend_options.clone(),
|
||||
..wgpu::InstanceDescriptor::new_without_display_handle()
|
||||
});
|
||||
crate::services::block_on(instance.enumerate_adapters(wgpu::Backends::DX12)).iter().map(|a| a.get_info().vendor).collect()
|
||||
}
|
||||
|
||||
/// The DX12 shader compiler (#712). wgpu's default loads `dxcompiler.dll` by name, and the
|
||||
/// Windows DLL search falls through to the current directory and `PATH`, so another program's DXC
|
||||
/// build (a browser's, an SDK's) got loaded and failed device creation or crashed the first shader
|
||||
@@ -220,6 +248,18 @@ pub fn dx12_compiler(env: Option<&str>, exe_dir: Option<&Path>) -> wgpu::Dx12Com
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU makers whose Windows Vulkan driver `auto` avoids, so DX12 comes first: Intel's
|
||||
/// (`igvk64.dll` crashed while the device was created, #4) and Qualcomm's Adreno driver on
|
||||
/// Windows on ARM (it lost the device mid-session and the window went with it; DX12 on the same
|
||||
/// machine didn't, #7537). The name is for System Info.
|
||||
fn dx12_first_on_windows(vendor: u32) -> Option<&'static str> {
|
||||
match vendor {
|
||||
INTEL => Some("Intel"),
|
||||
QUALCOMM | QUALCOMM_DXGI => Some("Qualcomm"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What adapter selection needs to know about an adapter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Candidate {
|
||||
@@ -228,13 +268,16 @@ pub struct Candidate {
|
||||
pub backend: wgpu::Backend,
|
||||
/// Can present to the window.
|
||||
pub surface_ok: bool,
|
||||
/// Its name matches the adapter the user asked for ([`adapter_matches`]).
|
||||
pub wanted: bool,
|
||||
}
|
||||
|
||||
/// Rank of an adapter (lower is better): high-performance device types first (egui's power
|
||||
/// preference) or software adapters first for `cpu`; then backends, with DX12 before Vulkan for
|
||||
/// Intel on Windows. For `cpu`, any GL adapter comes before Vulkan, which is only the fallback
|
||||
/// for presenting the window (see [`backends`]). On Windows GL comes after every other adapter,
|
||||
/// WARP included: GL there (VMware's SVGA3D, GL-only old GPUs) drew a black window (#5191, #1788).
|
||||
/// Intel and Qualcomm on Windows ([`dx12_first_on_windows`]). For `cpu`, any GL adapter comes
|
||||
/// before Vulkan, which is only the fallback for presenting the window (see [`backends`]). On
|
||||
/// Windows GL comes after every other adapter, WARP included: GL there (VMware's SVGA3D, GL-only
|
||||
/// old GPUs) drew a black window (#5191, #1788).
|
||||
fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8, u8) {
|
||||
let fallback = u8::from((backend == GpuBackend::Cpu && a.backend == wgpu::Backend::Vulkan) || (os == Os::Windows && a.backend == wgpu::Backend::Gl));
|
||||
let ty = match a.device_type {
|
||||
@@ -250,7 +293,7 @@ fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8, u8) {
|
||||
_ => ty,
|
||||
};
|
||||
let be = match a.backend {
|
||||
wgpu::Backend::Dx12 if os == Os::Windows && a.vendor == INTEL => 0,
|
||||
wgpu::Backend::Dx12 if os == Os::Windows && dx12_first_on_windows(a.vendor).is_some() => 0,
|
||||
wgpu::Backend::Vulkan | wgpu::Backend::Metal => 1,
|
||||
wgpu::Backend::Dx12 => 2,
|
||||
wgpu::Backend::Gl => 3,
|
||||
@@ -259,19 +302,62 @@ fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8, u8) {
|
||||
(fallback, ty, be)
|
||||
}
|
||||
|
||||
/// The adapter to use among `adapters` (`None` when there is none).
|
||||
/// The adapter to use among `adapters` (`None` when there is none). Adapters the user asked for
|
||||
/// win over the rest when any of them can present; otherwise the ranking decides (see
|
||||
/// [`wanted_missed`]).
|
||||
pub fn pick(adapters: &[Candidate], backend: GpuBackend, os: Os) -> Option<usize> {
|
||||
adapters.iter().enumerate().filter(|(_, a)| a.surface_ok).min_by_key(|(i, a)| (rank(a, backend, os), *i)).map(|(i, _)| i)
|
||||
let usable = |a: &&Candidate| a.surface_ok;
|
||||
let any_wanted = adapters.iter().filter(usable).any(|a| a.wanted);
|
||||
adapters.iter().enumerate().filter(|(_, a)| a.surface_ok && (a.wanted || !any_wanted)).min_by_key(|(i, a)| (rank(a, backend, os), *i)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Whether picking `chosen` applied the Intel-on-Windows DX12 default (a Vulkan adapter of the
|
||||
/// same vendor was available).
|
||||
pub fn intel_dx12_applied(adapters: &[Candidate], chosen: usize, os: Os) -> bool {
|
||||
let Some(c) = adapters.get(chosen) else { return false };
|
||||
os == Os::Windows
|
||||
&& c.vendor == INTEL
|
||||
&& c.backend == wgpu::Backend::Dx12
|
||||
&& adapters.iter().any(|a| a.vendor == INTEL && a.backend == wgpu::Backend::Vulkan)
|
||||
/// Whether an adapter called `name` is the one the user asked for: `wanted` is a case-insensitive
|
||||
/// piece of its name ("nvidia"), or several words that each appear in it ("arc a370m" finds
|
||||
/// "Intel(R) Arc(tm) A370M Graphics"). An empty `wanted` matches nothing.
|
||||
pub fn adapter_matches(name: &str, wanted: &str) -> bool {
|
||||
photocraft_engine::prefs::gpu_adapter_matches(name, wanted)
|
||||
}
|
||||
|
||||
/// The user asked for an adapter and none of `adapters` that can present is it.
|
||||
pub fn wanted_missed(adapters: &[Candidate], wanted: Option<&str>) -> bool {
|
||||
wanted.is_some() && !adapters.iter().any(|a| a.surface_ok && a.wanted)
|
||||
}
|
||||
|
||||
/// Choosing an adapter is Linux-only for now: Windows has its own Intel/DX12 selection and macOS a
|
||||
/// single Metal path, and neither is tested with a requested adapter.
|
||||
pub const ADAPTER_CHOICE: bool = cfg!(target_os = "linux");
|
||||
|
||||
/// The adapter request that applies to this launch: none off Linux (`linux`), and none in CPU mode,
|
||||
/// which wants a software adapter whatever the preference says.
|
||||
pub fn applicable_adapter(wanted: Option<String>, backend: GpuBackend, linux: bool) -> Option<String> {
|
||||
wanted.filter(|_| linux && backend != GpuBackend::Cpu)
|
||||
}
|
||||
|
||||
/// Whether `PHOTOCRAFT_GPU_ADAPTER` makes this launch its own process: only when startup will act
|
||||
/// on it (a non-empty value, on Linux, outside CPU mode). Otherwise it changes nothing, and the
|
||||
/// launch may still be forwarded to the running window.
|
||||
pub fn adapter_override_is_process_specific(env: Option<&str>, mode: RenderingMode, linux: bool) -> bool {
|
||||
env.is_some_and(|v| !v.trim().is_empty()) && linux && mode != RenderingMode::Cpu
|
||||
}
|
||||
|
||||
/// The adapter to ask for: `PHOTOCRAFT_GPU_ADAPTER` when set (for one launch), else
|
||||
/// `performance.gpuAdapter`; `None` is automatic.
|
||||
pub fn wanted_adapter(env: Option<&str>, pref: &str) -> Option<String> {
|
||||
[env.unwrap_or(""), pref].iter().map(|s| s.trim()).find(|s| !s.is_empty()).map(|s| s.chars().take(256).collect())
|
||||
}
|
||||
|
||||
/// The maker's name when picking `chosen` applied the Windows DX12 default of
|
||||
/// [`dx12_first_on_windows`]: a Vulkan adapter of the same maker was available, or, for Intel,
|
||||
/// `vulkan_left_out` ([`windows_auto_backends`] left Vulkan out of the instance).
|
||||
pub fn dx12_default_applied(adapters: &[Candidate], chosen: usize, os: Os, vulkan_left_out: bool) -> Option<&'static str> {
|
||||
let c = adapters.get(chosen)?;
|
||||
if os != Os::Windows || c.backend != wgpu::Backend::Dx12 {
|
||||
return None;
|
||||
}
|
||||
let maker = dx12_first_on_windows(c.vendor)?;
|
||||
let applied =
|
||||
(vulkan_left_out && c.vendor == INTEL) || adapters.iter().any(|a| a.backend == wgpu::Backend::Vulkan && dx12_first_on_windows(a.vendor) == Some(maker));
|
||||
applied.then_some(maker)
|
||||
}
|
||||
|
||||
/// wgpu compiles indirect-call validation shaders inside `request_device`; Metal's compiler
|
||||
@@ -283,9 +369,9 @@ fn skips_indirect_validation(os: Os, intel: bool) -> bool {
|
||||
}
|
||||
|
||||
/// Configure eframe's wgpu setup for `plan`: instance backends, the DX12 shader compiler, adapter
|
||||
/// selection (Intel on Windows, software adapters for `cpu`) and the marker update once the
|
||||
/// adapter is chosen. `note` receives a remark for System Info (e.g. the Intel default).
|
||||
pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, sentinel: SharedSentinel, note: Arc<Mutex<Option<String>>>) {
|
||||
/// selection (Intel and Qualcomm on Windows, software adapters for `cpu`) and the marker update
|
||||
/// once the adapter is chosen. `note` receives a remark for System Info (e.g. the DX12 default).
|
||||
pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, wanted: Option<String>, sentinel: SharedSentinel, note: Arc<Mutex<Option<String>>>) {
|
||||
if let egui_wgpu::WgpuSetup::CreateNew(create) = setup {
|
||||
if let Some(b) = backends(plan, os) {
|
||||
create.instance_descriptor.backends = b;
|
||||
@@ -298,7 +384,13 @@ pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, sentinel
|
||||
let env = std::env::var("WGPU_DX12_COMPILER").ok();
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = dx12_compiler(env.as_deref(), exe.as_deref().and_then(Path::parent));
|
||||
}
|
||||
let select = plan.env.is_none() && (plan.backend == GpuBackend::Cpu || (plan.backend == GpuBackend::Auto && os == Os::Windows));
|
||||
let without_vulkan = windows_auto_backends(plan, os, || dx12_vendors(&create.instance_descriptor));
|
||||
if let Some(b) = without_vulkan {
|
||||
create.instance_descriptor.backends = b;
|
||||
}
|
||||
let vulkan_left_out = without_vulkan.is_some();
|
||||
let wanted = applicable_adapter(wanted, plan.backend, ADAPTER_CHOICE);
|
||||
let select = wanted.is_some() || (plan.env.is_none() && (plan.backend == GpuBackend::Cpu || (plan.backend == GpuBackend::Auto && os == Os::Windows)));
|
||||
if select {
|
||||
let backend = plan.backend;
|
||||
create.native_adapter_selector = Some(Arc::new(move |adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>| {
|
||||
@@ -311,17 +403,24 @@ pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, sentinel
|
||||
device_type: i.device_type,
|
||||
backend: i.backend,
|
||||
surface_ok: surface.is_none_or(|s| a.is_surface_supported(s)),
|
||||
wanted: wanted.as_deref().is_some_and(|w| adapter_matches(&i.name, w)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let i = pick(&cands, backend, os).ok_or_else(|| "no graphics adapter found".to_string())?;
|
||||
if let Some(w) = wanted.as_deref().filter(|_| wanted_missed(&cands, wanted.as_deref())) {
|
||||
*note.lock().unwrap_or_else(PoisonError::into_inner) =
|
||||
Some(format!("No graphics adapter named \"{w}\" can draw the window; using the automatic choice"));
|
||||
}
|
||||
if backend == GpuBackend::Cpu && cands.get(i).is_some_and(|c| c.device_type != wgpu::DeviceType::Cpu) {
|
||||
*note.lock().unwrap_or_else(PoisonError::into_inner) =
|
||||
Some("CPU image rendering; no software graphics adapter is available, so the window uses hardware graphics".into());
|
||||
}
|
||||
if backend == GpuBackend::Auto && intel_dx12_applied(&cands, i, os) {
|
||||
if backend == GpuBackend::Auto
|
||||
&& let Some(maker) = dx12_default_applied(&cands, i, os, vulkan_left_out)
|
||||
{
|
||||
*note.lock().unwrap_or_else(PoisonError::into_inner) =
|
||||
Some("Intel graphics on Windows: using DirectX 12 (the Intel Vulkan driver is known to crash)".into());
|
||||
Some(format!("{maker} graphics on Windows: using DirectX 12 (the {maker} Vulkan driver is known to crash)"));
|
||||
}
|
||||
adapters.get(i).cloned().ok_or_else(|| "no graphics adapter found".to_string())
|
||||
}));
|
||||
@@ -443,6 +542,13 @@ pub fn read_display_server(path: Option<&Path>) -> photocraft_engine::prefs::Lin
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Preferences › Performance › Graphics Adapter (`performance.gpuAdapter`), read before the window
|
||||
/// opens; empty (automatic) when the file or value is missing.
|
||||
pub fn read_gpu_adapter(path: Option<&Path>) -> String {
|
||||
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
|
||||
v.get("performance").and_then(|p| p.get("gpuAdapter")).and_then(Value::as_str).unwrap_or("").chars().take(256).collect()
|
||||
}
|
||||
|
||||
/// Preferences › Performance › Low-Latency Drawing (`performance.lowLatencyDrawing`, off unless
|
||||
/// turned on), read before the window opens: it picks the surface's present mode.
|
||||
pub fn read_low_latency(path: Option<&Path>) -> bool {
|
||||
@@ -463,470 +569,4 @@ pub fn read_rendering_prefs(path: Option<&Path>) -> (GpuBackend, RenderingMode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use GpuBackend::*;
|
||||
|
||||
fn crashed(backend: &str, adapter_backend: &str) -> Marker {
|
||||
Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("preferences.json");
|
||||
let read = |json: &str| {
|
||||
std::fs::write(&file, json).unwrap();
|
||||
read_low_latency(Some(&file))
|
||||
};
|
||||
assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#));
|
||||
assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#));
|
||||
assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)");
|
||||
assert!(!read("not json"));
|
||||
assert!(!read_low_latency(None), "no settings file: the default (off)");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_server_preference_is_read_before_the_window_opens() {
|
||||
use photocraft_engine::prefs::LinuxDisplayServer;
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("preferences.json");
|
||||
let read = |json: &str| {
|
||||
std::fs::write(&file, json).unwrap();
|
||||
read_display_server(Some(&file))
|
||||
};
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11);
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto);
|
||||
// Unknown values, other types, broken JSON and a missing file all start as Auto.
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read("{not json"), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read_display_server(None), LinuxDisplayServer::Auto);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_policy_ignores_hardware_backend_override() {
|
||||
let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows);
|
||||
assert_eq!(p.backend, Cpu);
|
||||
assert!(p.env.is_none());
|
||||
assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu);
|
||||
let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows);
|
||||
assert_eq!(p.backend, Cpu);
|
||||
assert!(p.env.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_marker_uses_the_preference() {
|
||||
for os in [Os::Windows, Os::Mac, Os::Other] {
|
||||
let p = plan(Auto, None, None, false, os);
|
||||
assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false });
|
||||
}
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12);
|
||||
assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl);
|
||||
// A backend the platform lacks is `auto`.
|
||||
assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto);
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto);
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crash_moves_down_each_chain_and_is_remembered() {
|
||||
// Windows: Vulkan → DX12 → CPU.
|
||||
let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows);
|
||||
assert_eq!((p.backend, p.remember), (Dx12, true));
|
||||
assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}");
|
||||
assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu);
|
||||
// Crashed before the adapter was chosen (enumeration): from `auto`.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12);
|
||||
// `auto` that had already picked DX12 (the Intel default) goes to the CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu);
|
||||
// Linux: Vulkan → GL → CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl);
|
||||
assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu);
|
||||
// macOS: Metal → CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu);
|
||||
// The CPU path stays there, and isn't "remembered" again.
|
||||
let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows);
|
||||
assert_eq!((p.backend, p.remember), (Cpu, false));
|
||||
// An unreadable marker still counts as a crash.
|
||||
assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_override_beats_everything() {
|
||||
let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows);
|
||||
assert_eq!(p.env.as_deref(), Some("vulkan"));
|
||||
assert_eq!(p.backend, Auto);
|
||||
assert!(!p.remember);
|
||||
assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself");
|
||||
// A crash under the override doesn't count against `auto` later.
|
||||
let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows);
|
||||
assert_eq!(p.backend, Auto);
|
||||
// Empty means unset.
|
||||
assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None);
|
||||
// --safe-gpu with the override: CPU canvas, the override's backends.
|
||||
assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu);
|
||||
}
|
||||
|
||||
/// #3483: A temporary CPU recovery must not change the next launch.
|
||||
#[test]
|
||||
fn cpu_recovery_requires_explicit_confirmation_to_persist() {
|
||||
let gl_crash = crashed("gl", "gl");
|
||||
let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other);
|
||||
assert_eq!((cpu.backend, cpu.remember), (Cpu, true));
|
||||
assert_eq!(backend_to_remember(&cpu), None);
|
||||
|
||||
let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other);
|
||||
assert_eq!(safe.backend, Cpu);
|
||||
assert_eq!(backend_to_remember(&safe), None);
|
||||
// An unconfirmed fallback leaves the original automatic selection intact.
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto);
|
||||
// A working hardware fallback can still be remembered.
|
||||
let vk_crash = crashed("auto", "vulkan");
|
||||
let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other);
|
||||
assert_eq!(backend_to_remember(&gl), Some(Gl));
|
||||
// CPU explicitly selected in preferences still works.
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_gpu_forces_the_cpu_for_one_launch() {
|
||||
let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other);
|
||||
assert_eq!((p.backend, p.remember), (Cpu, false));
|
||||
assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12));
|
||||
assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN));
|
||||
assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL));
|
||||
}
|
||||
|
||||
fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate {
|
||||
Candidate { vendor, device_type, backend, surface_ok: true }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intel_on_windows_defaults_to_dx12() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)];
|
||||
let i = pick(&intel, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(intel[i].backend, B::Dx12);
|
||||
assert!(intel_dx12_applied(&intel, i, Os::Windows));
|
||||
// Elsewhere (and for other vendors) Vulkan stays first.
|
||||
assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan);
|
||||
let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)];
|
||||
let i = pick(&nv, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(nv[i].backend, B::Vulkan);
|
||||
assert!(!intel_dx12_applied(&nv, i, Os::Windows));
|
||||
// Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan.
|
||||
let hybrid = [intel[0], intel[1], nv[1]];
|
||||
assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2));
|
||||
// Adapters that can't present lose to ones that can.
|
||||
let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]];
|
||||
only[0].surface_ok = false;
|
||||
assert_eq!(pick(&only, Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[], Auto, Os::Windows), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_prefers_software_adapters() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)];
|
||||
assert_eq!(pick(&a, Cpu, Os::Windows), Some(1));
|
||||
// No software adapter: still something.
|
||||
assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0));
|
||||
}
|
||||
|
||||
/// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode
|
||||
/// found no adapter and never started. GL still wins whenever it can present.
|
||||
#[test]
|
||||
fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
const NVIDIA: u32 = 0x10de;
|
||||
let llvmpipe = cand(0x10005, T::Cpu, B::Gl);
|
||||
let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl);
|
||||
let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan);
|
||||
let lavapipe = cand(0x10005, T::Cpu, B::Vulkan);
|
||||
// GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan.
|
||||
assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2));
|
||||
assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2));
|
||||
// GL can't present: Vulkan for the window, software first.
|
||||
let mut gl = nvidia_gl;
|
||||
gl.surface_ok = false;
|
||||
assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2));
|
||||
assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1));
|
||||
// Other backends rank as before.
|
||||
assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1));
|
||||
}
|
||||
|
||||
/// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12).
|
||||
/// GL drew a black window; WARP works. GL stays the last resort.
|
||||
#[test]
|
||||
fn windows_auto_prefers_warp_over_gl() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let svga_gl = cand(0x15ad, T::Other, B::Gl);
|
||||
let warp = cand(0x1414, T::Cpu, B::Dx12);
|
||||
assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0));
|
||||
// Elsewhere GL keeps its rank.
|
||||
assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_must_present_even_when_none_support_the_surface() {
|
||||
let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12);
|
||||
a.surface_ok = false;
|
||||
assert_eq!(pick(&[a], Auto, Os::Windows), None);
|
||||
assert_eq!(pick(&[a], Cpu, Os::Windows), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_policy_overrides_legacy_cpu_backend() {
|
||||
assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto);
|
||||
assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu);
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_round_trip_and_lenient_parse() {
|
||||
let m = Marker {
|
||||
backend: "auto".into(),
|
||||
adapter: "A \"quoted\" GPU".into(),
|
||||
adapter_backend: "vulkan".into(),
|
||||
driver: "1.2".into(),
|
||||
version: "0.1".into(),
|
||||
};
|
||||
assert_eq!(Marker::parse(&m.to_json()), m);
|
||||
assert_eq!(Marker::parse(""), Marker::default());
|
||||
assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto));
|
||||
assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto));
|
||||
assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None);
|
||||
let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000));
|
||||
assert_eq!(Marker::parse(&long).adapter.len(), 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() {
|
||||
// GPU backends move down the chain on the next start.
|
||||
assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other));
|
||||
assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other));
|
||||
assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows));
|
||||
assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac));
|
||||
// The CPU path is the end of every chain, including the `--safe-gpu` retry.
|
||||
for os in [Os::Windows, Os::Mac, Os::Other] {
|
||||
assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os));
|
||||
assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os));
|
||||
}
|
||||
// `WGPU_BACKEND` is the user's choice; no plan reads its marker.
|
||||
assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other));
|
||||
}
|
||||
|
||||
/// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every
|
||||
/// later start was planned on CPU and failed the same way until the marker was deleted by hand.
|
||||
#[test]
|
||||
fn a_failed_cpu_start_does_not_pin_later_starts() {
|
||||
let dir = temp_dir("cpu-error");
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
let failed = plan(Auto, None, None, true, Os::Other);
|
||||
s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap();
|
||||
// eframe returned an error: what `main` does with the marker.
|
||||
if keep_marker_after_error(&failed, Os::Other) {
|
||||
drop(s);
|
||||
} else {
|
||||
s.finish();
|
||||
}
|
||||
let (prev, _s) = begin_when_unlocked(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
/// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns
|
||||
/// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child
|
||||
/// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test
|
||||
/// drops its sentinel.
|
||||
fn begin_when_unlocked(dir: &Path) -> (Previous, Option<Sentinel>) {
|
||||
let (mut prev, mut s) = Sentinel::begin(dir);
|
||||
for _ in 0..50 {
|
||||
if prev != Previous::Busy {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
(prev, s) = Sentinel::begin(dir);
|
||||
}
|
||||
(prev, s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sentinel_detects_a_crash_and_clears_on_success() {
|
||||
let dir = temp_dir("cycle");
|
||||
// First launch: nothing left behind.
|
||||
let (prev, s) = Sentinel::begin(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap();
|
||||
s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
// While it is starting, a second instance sees it busy, not crashed.
|
||||
let (busy, none) = Sentinel::begin(&dir);
|
||||
assert_eq!(busy, Previous::Busy);
|
||||
assert!(none.is_none());
|
||||
// The process dies in the driver: the lock goes, the marker stays.
|
||||
drop(s);
|
||||
let (prev, s) = begin_when_unlocked(&dir);
|
||||
let m = prev.crashed().cloned().expect("crash detected");
|
||||
assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan)));
|
||||
// This start succeeds: the next one finds nothing.
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap();
|
||||
s.finish();
|
||||
assert!(!dir.join(MARKER_FILE).exists());
|
||||
let (prev, _s) = Sentinel::begin(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn begin_when_unlocked_waits_for_a_briefly_held_lock() {
|
||||
let dir = temp_dir("shared-lock");
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
// After the start dies, a second handle on the marker holds the lock for 50 ms, as a
|
||||
// spawned child's copy of the descriptor does until the child calls exec.
|
||||
let held = File::open(dir.join(MARKER_FILE)).unwrap();
|
||||
drop(s);
|
||||
held.lock().unwrap();
|
||||
assert_eq!(Sentinel::begin(&dir).0, Previous::Busy);
|
||||
let release = std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
held.unlock().unwrap();
|
||||
});
|
||||
let (prev, s) = begin_when_unlocked(&dir);
|
||||
release.join().unwrap();
|
||||
assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan"));
|
||||
s.expect("sentinel").finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returned_non_graphics_errors_do_not_trigger_backend_recovery() {
|
||||
let cases = [
|
||||
("success", Ok(()), false),
|
||||
("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false),
|
||||
("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true),
|
||||
];
|
||||
for (name, result, keep) in cases {
|
||||
let dir = temp_dir(name);
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
if keep_marker_after_run(&result) {
|
||||
drop(s);
|
||||
} else {
|
||||
s.finish();
|
||||
}
|
||||
let (previous, s) = begin_when_unlocked(&dir);
|
||||
assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}");
|
||||
if !keep {
|
||||
assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan);
|
||||
}
|
||||
s.expect("sentinel").finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritable_config_dir_is_not_fatal() {
|
||||
let dir = temp_dir("file");
|
||||
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
|
||||
std::fs::write(&dir, b"not a directory").unwrap();
|
||||
let (prev, s) = Sentinel::begin(&dir.join("sub"));
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
assert!(s.is_none());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefs_are_read_leniently() {
|
||||
let dir = temp_dir("prefs");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let p = dir.join("preferences.json");
|
||||
assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto));
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu));
|
||||
std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu));
|
||||
std::fs::write(&p, "{not json").unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH).
|
||||
#[test]
|
||||
fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() {
|
||||
use wgpu::Dx12Compiler as C;
|
||||
let dir = temp_dir("dxc");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
assert!(matches!(dx12_compiler(None, None), C::Fxc));
|
||||
assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc));
|
||||
std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap();
|
||||
let expected = dir.join("dxcompiler.dll");
|
||||
assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected));
|
||||
// An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored.
|
||||
assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll"));
|
||||
assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path).
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
let plan = plan(Auto, None, None, false, Os::Windows);
|
||||
configure(&mut setup, &plan, Os::Windows, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
if std::env::var_os("WGPU_DX12_COMPILER").is_none() {
|
||||
let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler {
|
||||
C::Fxc => true,
|
||||
C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(),
|
||||
C::StaticDxc | C::Auto => false,
|
||||
};
|
||||
assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intel_macs_skip_the_indirect_validation_shaders() {
|
||||
// Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107).
|
||||
assert!(skips_indirect_validation(Os::Mac, true));
|
||||
// Apple silicon, Windows and Linux keep wgpu's validation.
|
||||
for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] {
|
||||
assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}");
|
||||
}
|
||||
for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] {
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") };
|
||||
let before = before.instance_descriptor.flags;
|
||||
configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched");
|
||||
}
|
||||
if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
|
||||
}
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,595 @@
|
||||
use super::*;
|
||||
use GpuBackend::*;
|
||||
|
||||
fn crashed(backend: &str, adapter_backend: &str) -> Marker {
|
||||
Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("preferences.json");
|
||||
let read = |json: &str| {
|
||||
std::fs::write(&file, json).unwrap();
|
||||
read_low_latency(Some(&file))
|
||||
};
|
||||
assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#));
|
||||
assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#));
|
||||
assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)");
|
||||
assert!(!read("not json"));
|
||||
assert!(!read_low_latency(None), "no settings file: the default (off)");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_server_preference_is_read_before_the_window_opens() {
|
||||
use photocraft_engine::prefs::LinuxDisplayServer;
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("preferences.json");
|
||||
let read = |json: &str| {
|
||||
std::fs::write(&file, json).unwrap();
|
||||
read_display_server(Some(&file))
|
||||
};
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11);
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto);
|
||||
// Unknown values, other types, broken JSON and a missing file all start as Auto.
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read("{not json"), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto);
|
||||
assert_eq!(read_display_server(None), LinuxDisplayServer::Auto);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_policy_ignores_hardware_backend_override() {
|
||||
let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows);
|
||||
assert_eq!(p.backend, Cpu);
|
||||
assert!(p.env.is_none());
|
||||
assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu);
|
||||
let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows);
|
||||
assert_eq!(p.backend, Cpu);
|
||||
assert!(p.env.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_marker_uses_the_preference() {
|
||||
for os in [Os::Windows, Os::Mac, Os::Other] {
|
||||
let p = plan(Auto, None, None, false, os);
|
||||
assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false });
|
||||
}
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12);
|
||||
assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl);
|
||||
// A backend the platform lacks is `auto`.
|
||||
assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto);
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto);
|
||||
assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crash_moves_down_each_chain_and_is_remembered() {
|
||||
// Windows: Vulkan → DX12 → CPU.
|
||||
let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows);
|
||||
assert_eq!((p.backend, p.remember), (Dx12, true));
|
||||
assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}");
|
||||
assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu);
|
||||
// Crashed before the adapter was chosen (enumeration): from `auto`.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12);
|
||||
// `auto` that had already picked DX12 (the Intel default) goes to the CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu);
|
||||
// Linux: Vulkan → GL → CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl);
|
||||
assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu);
|
||||
// macOS: Metal → CPU.
|
||||
assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu);
|
||||
// The CPU path stays there, and isn't "remembered" again.
|
||||
let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows);
|
||||
assert_eq!((p.backend, p.remember), (Cpu, false));
|
||||
// An unreadable marker still counts as a crash.
|
||||
assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_override_beats_everything() {
|
||||
let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows);
|
||||
assert_eq!(p.env.as_deref(), Some("vulkan"));
|
||||
assert_eq!(p.backend, Auto);
|
||||
assert!(!p.remember);
|
||||
assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself");
|
||||
// A crash under the override doesn't count against `auto` later.
|
||||
let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows);
|
||||
assert_eq!(p.backend, Auto);
|
||||
// Empty means unset.
|
||||
assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None);
|
||||
// --safe-gpu with the override: CPU canvas, the override's backends.
|
||||
assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu);
|
||||
}
|
||||
|
||||
/// #3483: A temporary CPU recovery must not change the next launch.
|
||||
#[test]
|
||||
fn cpu_recovery_requires_explicit_confirmation_to_persist() {
|
||||
let gl_crash = crashed("gl", "gl");
|
||||
let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other);
|
||||
assert_eq!((cpu.backend, cpu.remember), (Cpu, true));
|
||||
assert_eq!(backend_to_remember(&cpu), None);
|
||||
|
||||
let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other);
|
||||
assert_eq!(safe.backend, Cpu);
|
||||
assert_eq!(backend_to_remember(&safe), None);
|
||||
// An unconfirmed fallback leaves the original automatic selection intact.
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto);
|
||||
// A working hardware fallback can still be remembered.
|
||||
let vk_crash = crashed("auto", "vulkan");
|
||||
let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other);
|
||||
assert_eq!(backend_to_remember(&gl), Some(Gl));
|
||||
// CPU explicitly selected in preferences still works.
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_gpu_forces_the_cpu_for_one_launch() {
|
||||
let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other);
|
||||
assert_eq!((p.backend, p.remember), (Cpu, false));
|
||||
assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12));
|
||||
assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN));
|
||||
assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL));
|
||||
}
|
||||
|
||||
fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate {
|
||||
Candidate { vendor, device_type, backend, surface_ok: true, wanted: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requested_adapter_beats_the_automatic_ranking() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
// The order Vulkan lists this machine's GPUs in: iGPU, dGPU, eGPU.
|
||||
let mut a = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::DiscreteGpu, B::Vulkan), cand(0x10de, T::DiscreteGpu, B::Vulkan)];
|
||||
assert_eq!(pick(&a, Auto, Os::Other), Some(1), "automatic takes the first discrete adapter, the Arc");
|
||||
a[2].wanted = true;
|
||||
assert_eq!(pick(&a, Auto, Os::Other), Some(2));
|
||||
a[2].wanted = false;
|
||||
a[0].wanted = true;
|
||||
assert_eq!(pick(&a, Auto, Os::Other), Some(0), "even the iGPU, when asked for");
|
||||
// A wanted adapter that can't present is skipped, not an error.
|
||||
a[0].surface_ok = false;
|
||||
assert_eq!(pick(&a, Auto, Os::Other), Some(1));
|
||||
assert!(wanted_missed(&a, Some("iris")));
|
||||
assert!(!wanted_missed(&a, None));
|
||||
a[0].surface_ok = true;
|
||||
assert!(!wanted_missed(&a, Some("iris")));
|
||||
// Among several wanted ones (same GPU on Vulkan and GL) the usual ranking decides.
|
||||
let mut gl = [cand(0x10de, T::DiscreteGpu, B::Gl), cand(0x10de, T::DiscreteGpu, B::Vulkan)];
|
||||
gl.iter_mut().for_each(|c| c.wanted = true);
|
||||
assert_eq!(pick(&gl, Auto, Os::Other), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adapter_request_applies_on_linux_outside_cpu_mode() {
|
||||
let w = || Some("nvidia".to_string());
|
||||
assert_eq!(applicable_adapter(w(), Auto, true), w());
|
||||
assert_eq!(applicable_adapter(w(), Vulkan, true), w());
|
||||
assert_eq!(applicable_adapter(w(), Cpu, true), None);
|
||||
assert_eq!(applicable_adapter(w(), Auto, false), None, "Windows and macOS keep their own selection");
|
||||
assert_eq!(applicable_adapter(None, Auto, true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adapter_override_keeps_its_own_process_only_when_it_applies() {
|
||||
let on = |env, mode, linux| adapter_override_is_process_specific(env, mode, linux);
|
||||
assert!(on(Some("nvidia"), RenderingMode::Auto, true));
|
||||
assert!(on(Some("nvidia"), RenderingMode::Gpu, true));
|
||||
assert!(!on(Some("nvidia"), RenderingMode::Cpu, true), "ignored in CPU mode");
|
||||
assert!(!on(Some("nvidia"), RenderingMode::Auto, false), "ignored off Linux");
|
||||
assert!(!on(Some(" "), RenderingMode::Auto, true));
|
||||
assert!(!on(None, RenderingMode::Auto, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_names_match_loosely_and_the_environment_wins() {
|
||||
assert!(adapter_matches("NVIDIA GeForce RTX 5060 Ti", "nvidia"));
|
||||
assert!(adapter_matches("Intel(R) Arc(tm) A370M Graphics (DG2)", " ARC A370M "));
|
||||
assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics (ADL GT2)", "arc"));
|
||||
assert!(!adapter_matches("anything", ""));
|
||||
assert!(!adapter_matches("anything", " "));
|
||||
assert_eq!(wanted_adapter(None, ""), None);
|
||||
assert_eq!(wanted_adapter(Some(" "), "iris"), Some("iris".into()));
|
||||
assert_eq!(wanted_adapter(Some("nvidia"), "iris"), Some("nvidia".into()));
|
||||
assert_eq!(wanted_adapter(Some(&"x".repeat(1000)), "").map(|w| w.len()), Some(256));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_adapter_is_read_before_the_window_opens() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("preferences.json");
|
||||
let read = |json: &str| {
|
||||
std::fs::write(&file, json).unwrap();
|
||||
read_gpu_adapter(Some(&file))
|
||||
};
|
||||
assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia");
|
||||
assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), "");
|
||||
assert_eq!(read(r#"{"performance":{}}"#), "");
|
||||
assert_eq!(read("not json"), "");
|
||||
assert_eq!(read_gpu_adapter(None), "");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intel_on_windows_defaults_to_dx12() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)];
|
||||
let i = pick(&intel, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(intel[i].backend, B::Dx12);
|
||||
assert_eq!(dx12_default_applied(&intel, i, Os::Windows, false), Some("Intel"));
|
||||
// Elsewhere (and for other vendors) Vulkan stays first.
|
||||
assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan);
|
||||
let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)];
|
||||
let i = pick(&nv, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(nv[i].backend, B::Vulkan);
|
||||
assert_eq!(dx12_default_applied(&nv, i, Os::Windows, false), None);
|
||||
// Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan.
|
||||
let hybrid = [intel[0], intel[1], nv[1]];
|
||||
assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2));
|
||||
// Adapters that can't present lose to ones that can.
|
||||
let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]];
|
||||
only[0].surface_ok = false;
|
||||
assert_eq!(pick(&only, Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[], Auto, Os::Windows), None);
|
||||
}
|
||||
|
||||
/// #7537: on Windows on ARM the Adreno Vulkan driver lost the device mid-session and took the
|
||||
/// window with it; DX12 on the same machine didn't. DXGI and Vulkan report different vendor ids.
|
||||
#[test]
|
||||
fn qualcomm_on_windows_defaults_to_dx12() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let adreno = [cand(QUALCOMM, T::IntegratedGpu, B::Vulkan), cand(QUALCOMM_DXGI, T::IntegratedGpu, B::Dx12)];
|
||||
let i = pick(&adreno, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(adreno[i].backend, B::Dx12);
|
||||
assert_eq!(dx12_default_applied(&adreno, i, Os::Windows, false), Some("Qualcomm"));
|
||||
// Only Vulkan offered: still Vulkan, and no note.
|
||||
assert_eq!(pick(&adreno[..1], Auto, Os::Windows), Some(0));
|
||||
assert_eq!(dx12_default_applied(&adreno, 0, Os::Windows, false), None);
|
||||
// An Intel Vulkan adapter doesn't make a Qualcomm DX12 pick "the default".
|
||||
let mixed = [cand(INTEL, T::IntegratedGpu, B::Vulkan), adreno[1]];
|
||||
assert_eq!(dx12_default_applied(&mixed, 1, Os::Windows, false), None);
|
||||
// Vulkan left out of the instance (an Intel adapter was listed) speaks only for Intel.
|
||||
assert_eq!(dx12_default_applied(&adreno[1..], 0, Os::Windows, true), None);
|
||||
// Elsewhere Vulkan stays first.
|
||||
assert_eq!(adreno[pick(&adreno, Auto, Os::Other).unwrap()].backend, B::Vulkan);
|
||||
}
|
||||
|
||||
/// #4: an instance with Vulkan loads the Intel Vulkan driver, which crashed at startup, before
|
||||
/// the selector picks Intel's DX12 adapter. With an Intel adapter in the DX12 list, `auto` on
|
||||
/// Windows creates the instance without Vulkan.
|
||||
#[test]
|
||||
fn auto_on_windows_with_an_intel_adapter_leaves_vulkan_out_of_the_instance() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
const NVIDIA: u32 = 0x10de;
|
||||
const AMD: u32 = 0x1002;
|
||||
const WARP: u32 = 0x1414;
|
||||
let auto = plan(Auto, None, None, false, Os::Windows);
|
||||
let dx12_gl = Some(wgpu::Backends::DX12 | wgpu::Backends::GL);
|
||||
assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![INTEL, WARP]), dx12_gl);
|
||||
// Intel iGPU + discrete GPU: the discrete GPU is then used on DX12.
|
||||
assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, INTEL, WARP]), dx12_gl);
|
||||
// No Intel adapter: egui's default backends, Vulkan included.
|
||||
assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, WARP]), None);
|
||||
assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![AMD]), None);
|
||||
assert_eq!(windows_auto_backends(&auto, Os::Windows, Vec::new), None);
|
||||
// `WGPU_BACKEND`, `--safe-gpu`, a chosen backend, a crash fallback and other platforms
|
||||
// don't list the DX12 adapters at all.
|
||||
let not_listed = || -> Vec<u32> { panic!("DX12 adapters listed") };
|
||||
for (p, os) in [
|
||||
(plan(Auto, None, Some("vulkan"), false, Os::Windows), Os::Windows),
|
||||
(plan(Auto, None, None, true, Os::Windows), Os::Windows),
|
||||
(plan(Vulkan, None, None, false, Os::Windows), Os::Windows),
|
||||
(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows), Os::Windows),
|
||||
(plan(Auto, None, None, false, Os::Other), Os::Other),
|
||||
(plan(Auto, None, None, false, Os::Mac), Os::Mac),
|
||||
] {
|
||||
assert_eq!(windows_auto_backends(&p, os, not_listed), None, "{p:?}");
|
||||
}
|
||||
// Without Vulkan adapters to compare with, System Info still names the Intel default.
|
||||
let listed = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(WARP, T::Cpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)];
|
||||
let i = pick(&listed, Auto, Os::Windows).unwrap();
|
||||
assert_eq!(i, 0);
|
||||
assert_eq!(dx12_default_applied(&listed, i, Os::Windows, true), Some("Intel"));
|
||||
assert_eq!(dx12_default_applied(&listed, i, Os::Windows, false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_prefers_software_adapters() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)];
|
||||
assert_eq!(pick(&a, Cpu, Os::Windows), Some(1));
|
||||
// No software adapter: still something.
|
||||
assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0));
|
||||
}
|
||||
|
||||
/// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode
|
||||
/// found no adapter and never started. GL still wins whenever it can present.
|
||||
#[test]
|
||||
fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
const NVIDIA: u32 = 0x10de;
|
||||
let llvmpipe = cand(0x10005, T::Cpu, B::Gl);
|
||||
let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl);
|
||||
let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan);
|
||||
let lavapipe = cand(0x10005, T::Cpu, B::Vulkan);
|
||||
// GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan.
|
||||
assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2));
|
||||
assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2));
|
||||
// GL can't present: Vulkan for the window, software first.
|
||||
let mut gl = nvidia_gl;
|
||||
gl.surface_ok = false;
|
||||
assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2));
|
||||
assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1));
|
||||
// Other backends rank as before.
|
||||
assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1));
|
||||
}
|
||||
|
||||
/// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12).
|
||||
/// GL drew a black window; WARP works. GL stays the last resort.
|
||||
#[test]
|
||||
fn windows_auto_prefers_warp_over_gl() {
|
||||
use wgpu::{Backend as B, DeviceType as T};
|
||||
let svga_gl = cand(0x15ad, T::Other, B::Gl);
|
||||
let warp = cand(0x1414, T::Cpu, B::Dx12);
|
||||
assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1));
|
||||
assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0));
|
||||
// Elsewhere GL keeps its rank.
|
||||
assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_must_present_even_when_none_support_the_surface() {
|
||||
let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12);
|
||||
a.surface_ok = false;
|
||||
assert_eq!(pick(&[a], Auto, Os::Windows), None);
|
||||
assert_eq!(pick(&[a], Cpu, Os::Windows), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_policy_overrides_legacy_cpu_backend() {
|
||||
assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto);
|
||||
assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu);
|
||||
assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_round_trip_and_lenient_parse() {
|
||||
let m =
|
||||
Marker { backend: "auto".into(), adapter: "A \"quoted\" GPU".into(), adapter_backend: "vulkan".into(), driver: "1.2".into(), version: "0.1".into() };
|
||||
assert_eq!(Marker::parse(&m.to_json()), m);
|
||||
assert_eq!(Marker::parse(""), Marker::default());
|
||||
assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto));
|
||||
assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto));
|
||||
assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None);
|
||||
let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000));
|
||||
assert_eq!(Marker::parse(&long).adapter.len(), 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() {
|
||||
// GPU backends move down the chain on the next start.
|
||||
assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other));
|
||||
assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other));
|
||||
assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows));
|
||||
assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac));
|
||||
// The CPU path is the end of every chain, including the `--safe-gpu` retry.
|
||||
for os in [Os::Windows, Os::Mac, Os::Other] {
|
||||
assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os));
|
||||
assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os));
|
||||
}
|
||||
// `WGPU_BACKEND` is the user's choice; no plan reads its marker.
|
||||
assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other));
|
||||
}
|
||||
|
||||
/// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every
|
||||
/// later start was planned on CPU and failed the same way until the marker was deleted by hand.
|
||||
#[test]
|
||||
fn a_failed_cpu_start_does_not_pin_later_starts() {
|
||||
let dir = temp_dir("cpu-error");
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
let failed = plan(Auto, None, None, true, Os::Other);
|
||||
s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap();
|
||||
// eframe returned an error: what `main` does with the marker.
|
||||
if keep_marker_after_error(&failed, Os::Other) {
|
||||
drop(s);
|
||||
} else {
|
||||
s.finish();
|
||||
}
|
||||
let (prev, _s) = begin_when_unlocked(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
/// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns
|
||||
/// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child
|
||||
/// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test
|
||||
/// drops its sentinel.
|
||||
fn begin_when_unlocked(dir: &Path) -> (Previous, Option<Sentinel>) {
|
||||
let (mut prev, mut s) = Sentinel::begin(dir);
|
||||
for _ in 0..50 {
|
||||
if prev != Previous::Busy {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
(prev, s) = Sentinel::begin(dir);
|
||||
}
|
||||
(prev, s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sentinel_detects_a_crash_and_clears_on_success() {
|
||||
let dir = temp_dir("cycle");
|
||||
// First launch: nothing left behind.
|
||||
let (prev, s) = Sentinel::begin(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap();
|
||||
s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
// While it is starting, a second instance sees it busy, not crashed.
|
||||
let (busy, none) = Sentinel::begin(&dir);
|
||||
assert_eq!(busy, Previous::Busy);
|
||||
assert!(none.is_none());
|
||||
// The process dies in the driver: the lock goes, the marker stays.
|
||||
drop(s);
|
||||
let (prev, s) = begin_when_unlocked(&dir);
|
||||
let m = prev.crashed().cloned().expect("crash detected");
|
||||
assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan)));
|
||||
// This start succeeds: the next one finds nothing.
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap();
|
||||
s.finish();
|
||||
assert!(!dir.join(MARKER_FILE).exists());
|
||||
let (prev, _s) = Sentinel::begin(&dir);
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn begin_when_unlocked_waits_for_a_briefly_held_lock() {
|
||||
let dir = temp_dir("shared-lock");
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
// After the start dies, a second handle on the marker holds the lock for 50 ms, as a
|
||||
// spawned child's copy of the descriptor does until the child calls exec.
|
||||
let held = File::open(dir.join(MARKER_FILE)).unwrap();
|
||||
drop(s);
|
||||
held.lock().unwrap();
|
||||
assert_eq!(Sentinel::begin(&dir).0, Previous::Busy);
|
||||
let release = std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
held.unlock().unwrap();
|
||||
});
|
||||
let (prev, s) = begin_when_unlocked(&dir);
|
||||
release.join().unwrap();
|
||||
assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan"));
|
||||
s.expect("sentinel").finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returned_non_graphics_errors_do_not_trigger_backend_recovery() {
|
||||
let cases = [
|
||||
("success", Ok(()), false),
|
||||
("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false),
|
||||
("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true),
|
||||
];
|
||||
for (name, result, keep) in cases {
|
||||
let dir = temp_dir(name);
|
||||
let (_, s) = Sentinel::begin(&dir);
|
||||
let mut s = s.expect("sentinel");
|
||||
s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap();
|
||||
if keep_marker_after_run(&result) {
|
||||
drop(s);
|
||||
} else {
|
||||
s.finish();
|
||||
}
|
||||
let (previous, s) = begin_when_unlocked(&dir);
|
||||
assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}");
|
||||
if !keep {
|
||||
assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan);
|
||||
}
|
||||
s.expect("sentinel").finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritable_config_dir_is_not_fatal() {
|
||||
let dir = temp_dir("file");
|
||||
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
|
||||
std::fs::write(&dir, b"not a directory").unwrap();
|
||||
let (prev, s) = Sentinel::begin(&dir.join("sub"));
|
||||
assert_eq!(prev, Previous::Clean);
|
||||
assert!(s.is_none());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefs_are_read_leniently() {
|
||||
let dir = temp_dir("prefs");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let p = dir.join("preferences.json");
|
||||
assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto));
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu));
|
||||
std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu));
|
||||
std::fs::write(&p, "{not json").unwrap();
|
||||
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH).
|
||||
#[test]
|
||||
fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() {
|
||||
use wgpu::Dx12Compiler as C;
|
||||
let dir = temp_dir("dxc");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
assert!(matches!(dx12_compiler(None, None), C::Fxc));
|
||||
assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc));
|
||||
std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap();
|
||||
let expected = dir.join("dxcompiler.dll");
|
||||
assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected));
|
||||
// An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored.
|
||||
assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll"));
|
||||
assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path).
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
let plan = plan(Auto, None, None, false, Os::Windows);
|
||||
configure(&mut setup, &plan, Os::Windows, None, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
if std::env::var_os("WGPU_DX12_COMPILER").is_none() {
|
||||
let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler {
|
||||
C::Fxc => true,
|
||||
C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(),
|
||||
C::StaticDxc | C::Auto => false,
|
||||
};
|
||||
assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intel_macs_skip_the_indirect_validation_shaders() {
|
||||
// Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107).
|
||||
assert!(skips_indirect_validation(Os::Mac, true));
|
||||
// Apple silicon, Windows and Linux keep wgpu's validation.
|
||||
for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] {
|
||||
assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}");
|
||||
}
|
||||
for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] {
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") };
|
||||
let before = before.instance_descriptor.flags;
|
||||
configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, None, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched");
|
||||
}
|
||||
if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
|
||||
let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
|
||||
configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, None, Arc::new(Mutex::new(None)), Arc::default());
|
||||
let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") };
|
||||
assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The desktop app's command line, as clap types (#7071): `photocraft --help` comes from these doc
|
||||
//! comments, so the help and the parser can't disagree. Anything they don't declare is a usage
|
||||
//! error naming it (exit status 2), so a typo such as `--safegpu` doesn't open the window and then
|
||||
//! fail to open the flag as a file (#6431); so is a flag without its value, rather than a silent
|
||||
//! fall back to a generated token or to no root (#6429), a repeated flag, and a bad
|
||||
//! `--present-mode` or `--frame-latency`. A value never starts with `-` (write `--opt=-value`),
|
||||
//! except for negative numbers, and a file whose name starts with `-` goes after `--`.
|
||||
//!
|
||||
//! The control and automation flags are `photocraft-automation`'s, shared with `photocraft-cli`.
|
||||
//! Only the desktop app reads the automation roots from `PHOTOCRAFT_AUTOMATION_*_ROOT` (#1551).
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::builder::FalseyValueParser;
|
||||
use clap::parser::ValueSource;
|
||||
use clap::{Command, CommandFactory, FromArgMatches, Parser};
|
||||
use eframe::wgpu::PresentMode;
|
||||
use photocraft_automation::args::{AutomationArgs, ControlArgs, blank_env_is_unset, conflict, control_port, name_env_vars};
|
||||
|
||||
use crate::presentation;
|
||||
|
||||
/// Opens PhotoCraft with the given files
|
||||
#[derive(Parser)]
|
||||
#[command(name = "photocraft", version = photocraft_engine::build_info::long_version_static(), after_help = ENVIRONMENT)]
|
||||
pub(crate) struct LaunchArgs {
|
||||
/// Files to open. On Windows and Linux they open as new tabs in the PhotoCraft already running.
|
||||
/// Put `--` before a name that starts with `-`
|
||||
pub(crate) files: Vec<PathBuf>,
|
||||
/// Start with the CPU renderer for this launch (after a graphics driver crash)
|
||||
#[arg(long)]
|
||||
pub(crate) safe_gpu: bool,
|
||||
/// macOS: keep the menus inside the window instead of the menu bar (the variable: 0, false, no
|
||||
/// or off is off; empty is unset)
|
||||
#[arg(long, env = "PHOTOCRAFT_IN_WINDOW_MENUS", value_parser = FalseyValueParser::new())]
|
||||
pub(crate) in_window_menus: bool,
|
||||
/// Windows and Linux: start a separate PhotoCraft instead of opening the files in the one
|
||||
/// already running
|
||||
#[arg(long)]
|
||||
pub(crate) new_instance: bool,
|
||||
/// How frames reach the display: fifo, autovsync or novsync (also immediate or mailbox).
|
||||
/// Without it, PHOTOCRAFT_PRESENT_MODE
|
||||
#[arg(long, value_name = "MODE", value_parser = present_mode)]
|
||||
pub(crate) present_mode: Option<PresentMode>,
|
||||
/// Frames queued for the display, 1 to 3. Without it, PHOTOCRAFT_FRAME_LATENCY
|
||||
// allow_negative_numbers makes `--frame-latency -1` a bad value rather than an unexpected argument.
|
||||
#[arg(long, value_name = "1-3", value_parser = frame_latency, allow_negative_numbers = true)]
|
||||
pub(crate) frame_latency: Option<u32>,
|
||||
/// Time each brush stroke's frames: stderr prints a summary per stroke, a CSV file path also
|
||||
/// records every frame. Without it, PHOTOCRAFT_STROKE_TRACE
|
||||
#[arg(long, value_name = "stderr|FILE.csv")]
|
||||
pub(crate) stroke_trace: Option<String>,
|
||||
/// Start the localhost JSON-lines control server on this port
|
||||
#[arg(long, value_name = "PORT", env = "PHOTOCRAFT_CONTROL_PORT", value_parser = control_port, allow_negative_numbers = true)]
|
||||
pub(crate) control: Option<u16>,
|
||||
#[command(flatten)]
|
||||
pub(crate) auth: ControlArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
/// The per-process options given on the command line, set by [`parse`].
|
||||
#[arg(skip)]
|
||||
pub(crate) launch_options: Vec<PerProcess>,
|
||||
}
|
||||
|
||||
/// The variables that aren't a flag's fallback, for the end of `--help`.
|
||||
const ENVIRONMENT: &str = "\
|
||||
Environment: PHOTOCRAFT_NEW_INSTANCE (anything but 0 or empty: as --new-instance), PHOTOCRAFT_CONFIG_DIR (the settings folder)";
|
||||
|
||||
/// An option that applies only to the process it's given to: a launch with any of them keeps its
|
||||
/// own process instead of handing its files to the running one (`single_instance`). Shown as the
|
||||
/// flag, or the variable.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum PerProcess {
|
||||
AutomationReadRoot,
|
||||
AutomationWriteRoot,
|
||||
SafeGpu,
|
||||
InWindowMenus,
|
||||
PresentMode,
|
||||
FrameLatency,
|
||||
StrokeTrace,
|
||||
/// PHOTOCRAFT_GPU_ADAPTER, when startup will act on it (`gpu_startup`). Not a flag.
|
||||
GpuAdapterEnv,
|
||||
}
|
||||
|
||||
impl PerProcess {
|
||||
/// The flags, in the order a log line lists them. A flag's variable asks for the same thing, so
|
||||
/// it counts too (#7242); the variables that aren't a flag's fallback are counted by
|
||||
/// `single_instance::env_launch_options`.
|
||||
pub(crate) const FLAGS: [PerProcess; 7] =
|
||||
[Self::AutomationReadRoot, Self::AutomationWriteRoot, Self::SafeGpu, Self::InWindowMenus, Self::PresentMode, Self::FrameLatency, Self::StrokeTrace];
|
||||
|
||||
/// The flag's clap argument id.
|
||||
fn id(self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Self::AutomationReadRoot => "automation_read_root",
|
||||
Self::AutomationWriteRoot => "automation_write_root",
|
||||
Self::SafeGpu => "safe_gpu",
|
||||
Self::InWindowMenus => "in_window_menus",
|
||||
Self::PresentMode => "present_mode",
|
||||
Self::FrameLatency => "frame_latency",
|
||||
Self::StrokeTrace => "stroke_trace",
|
||||
Self::GpuAdapterEnv => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PerProcess {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::AutomationReadRoot => "--automation-read-root",
|
||||
Self::AutomationWriteRoot => "--automation-write-root",
|
||||
Self::SafeGpu => "--safe-gpu",
|
||||
Self::InWindowMenus => "--in-window-menus",
|
||||
Self::PresentMode => "--present-mode",
|
||||
Self::FrameLatency => "--frame-latency",
|
||||
Self::StrokeTrace => "--stroke-trace",
|
||||
Self::GpuAdapterEnv => "PHOTOCRAFT_GPU_ADAPTER",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The files to open, as [`LaunchArgs::file_names`] sorts them.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct FileNames {
|
||||
pub(crate) openable: Vec<String>,
|
||||
/// Names that are not valid Unicode, shown lossily: reported, not opened.
|
||||
pub(crate) unreadable: Vec<String>,
|
||||
}
|
||||
|
||||
impl LaunchArgs {
|
||||
/// The files to open, and those whose names are not valid Unicode (#1108): a file manager can
|
||||
/// hand over a Latin-1 name on Linux. Those are reported in a notice once the app is up.
|
||||
pub(crate) fn file_names(&self) -> FileNames {
|
||||
let mut names = FileNames { openable: Vec::new(), unreadable: Vec::new() };
|
||||
for f in &self.files {
|
||||
match f.to_str() {
|
||||
Some(s) => names.openable.push(s.to_owned()),
|
||||
None => names.unreadable.push(f.to_string_lossy().into_owned()),
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
}
|
||||
|
||||
/// The command line, with the desktop app's variables for the automation roots. An empty or blank
|
||||
/// variable counts as unset.
|
||||
pub(crate) fn command() -> Command {
|
||||
LaunchArgs::command()
|
||||
.mut_arg("automation_read_root", |a| a.env("PHOTOCRAFT_AUTOMATION_READ_ROOT"))
|
||||
.mut_arg("automation_write_root", |a| a.env("PHOTOCRAFT_AUTOMATION_WRITE_ROOT"))
|
||||
.mut_args(blank_env_is_unset)
|
||||
}
|
||||
|
||||
/// Parse the launch arguments (without the binary name) with `cmd`, from [`command`]. Old macOS
|
||||
/// passes a process serial number (`-psn_…`) when launched from Finder: it is dropped first, unless
|
||||
/// it comes after `--`. A bad value from a variable is a usage error naming the variable.
|
||||
pub(crate) fn parse(mut cmd: Command, args: impl IntoIterator<Item = OsString>) -> Result<LaunchArgs, clap::Error> {
|
||||
let mut options = true;
|
||||
let args: Vec<OsString> = args
|
||||
.into_iter()
|
||||
.filter(|a| {
|
||||
options &= a != "--";
|
||||
!(options && a.to_str().is_some_and(|s| s.starts_with("-psn_")))
|
||||
})
|
||||
.collect();
|
||||
let argv = std::iter::once(OsString::from("photocraft")).chain(args.iter().cloned());
|
||||
let matches = cmd.try_get_matches_from_mut(argv).map_err(|e| name_env_vars(e, &cmd, &args))?;
|
||||
let mut launch = LaunchArgs::from_arg_matches(&matches)?;
|
||||
// Only the control server reads a token, so a stale exported pair doesn't stop a launch.
|
||||
if launch.control.is_some() {
|
||||
conflict(&mut cmd, &matches, "control_token", "control_token_file")?;
|
||||
}
|
||||
// `PHOTOCRAFT_IN_WINDOW_MENUS=0` (or off, false, no) is a variable that turns the menus off.
|
||||
let menus = launch.in_window_menus;
|
||||
let given = |p: &PerProcess| match p.id().and_then(|id| matches.value_source(id)) {
|
||||
Some(ValueSource::CommandLine) => true,
|
||||
Some(ValueSource::EnvVariable) => *p != PerProcess::InWindowMenus || menus,
|
||||
_ => false,
|
||||
};
|
||||
launch.launch_options = PerProcess::FLAGS.into_iter().filter(given).collect();
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Why a value was refused: clap prints it after the flag and its value (exit 2).
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ValueError {
|
||||
#[error("expected fifo, autovsync or novsync (or immediate, mailbox)")]
|
||||
PresentMode,
|
||||
#[error("expected 1, 2 or 3")]
|
||||
FrameLatency,
|
||||
}
|
||||
|
||||
fn present_mode(s: &str) -> Result<PresentMode, ValueError> {
|
||||
presentation::present_mode(s).ok_or(ValueError::PresentMode)
|
||||
}
|
||||
|
||||
fn frame_latency(s: &str) -> Result<u32, ValueError> {
|
||||
presentation::frame_latency(s).ok_or(ValueError::FrameLatency)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::error::ErrorKind;
|
||||
|
||||
/// Parse without the variables, so one exported where the tests run can't change them (the
|
||||
/// process tests in `tests/command_line_usage.rs` cover the variables).
|
||||
fn parse_args(args: &[&str]) -> Result<LaunchArgs, clap::Error> {
|
||||
parse(command().mut_args(|a| a.env(None::<&str>)), args.iter().map(OsString::from))
|
||||
}
|
||||
|
||||
fn usage_error(args: &[&str]) -> String {
|
||||
let Err(e) = parse_args(args) else { panic!("{args:?} parsed") };
|
||||
assert_eq!(e.exit_code(), 2, "{args:?}: {e}");
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_port_rejects_unparseable_values_naming_them() {
|
||||
// Out of range, negative and empty values fail, naming the value (#701); a following
|
||||
// flag is never taken as the value.
|
||||
assert!(usage_error(&["--control", "78787"]).contains("invalid value '78787' for '--control <PORT>'"));
|
||||
assert!(usage_error(&["--control", "-1"]).contains("invalid value '-1'"));
|
||||
assert!(usage_error(&["--control="]).contains("invalid value '' for '--control <PORT>'"));
|
||||
assert!(usage_error(&["--control", "--safe-gpu"]).contains("a value is required for '--control <PORT>'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_without_a_value_are_usage_errors() {
|
||||
// #6429: a missing value fails the launch, rather than falling back to a generated token
|
||||
// or to no root. The tuning flags too, now (#7071).
|
||||
for flag in [
|
||||
"--control",
|
||||
"--control-token",
|
||||
"--control-token-file",
|
||||
"--automation-read-root",
|
||||
"--automation-write-root",
|
||||
"--present-mode",
|
||||
"--frame-latency",
|
||||
"--stroke-trace",
|
||||
] {
|
||||
let err = usage_error(&[flag]);
|
||||
assert!(err.contains(&format!("a value is required for '{flag} <")), "{flag}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_tuning_values_and_repeats_are_usage_errors() {
|
||||
assert!(usage_error(&["--present-mode", "fast"]).contains("expected fifo, autovsync or novsync"));
|
||||
for latency in ["0", "4", "-1", "one"] {
|
||||
let err = usage_error(&["--frame-latency", latency]);
|
||||
assert!(err.contains(&format!("invalid value '{latency}' for '--frame-latency <1-3>'")), "{err}");
|
||||
}
|
||||
assert!(usage_error(&["--safe-gpu", "--safe-gpu"]).contains("cannot be used multiple times"));
|
||||
assert!(usage_error(&["--control", "1", "--control", "2"]).contains("cannot be used multiple times"));
|
||||
// A token and a token file are either/or for the control server, and ignored without it.
|
||||
let pair = ["--control-token", "abcd", "--control-token-file", "/tmp/token"];
|
||||
assert!(usage_error(&[&["--control", "1"][..], &pair[..]].concat()).contains("cannot be used with"));
|
||||
assert!(parse_args(&pair).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_are_parsed_and_per_process_options_recorded() {
|
||||
let parsed = parse_args(&[
|
||||
"--stroke-trace",
|
||||
"stderr",
|
||||
"--control",
|
||||
"50494",
|
||||
"--control-token",
|
||||
"abcd",
|
||||
"--automation-read-root",
|
||||
"/r",
|
||||
"--automation-write-root",
|
||||
"/w",
|
||||
"--safe-gpu",
|
||||
"--in-window-menus",
|
||||
"--new-instance",
|
||||
"--present-mode",
|
||||
"Mailbox",
|
||||
"--frame-latency",
|
||||
"1",
|
||||
"photo.psd",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(parsed.control, Some(50494));
|
||||
assert_eq!(parsed.auth.control_token.as_deref(), Some("abcd"));
|
||||
assert_eq!(parsed.auth.control_token_file, None);
|
||||
assert_eq!(parsed.automation.automation_read_root.as_deref(), Some(std::path::Path::new("/r")));
|
||||
assert_eq!(parsed.automation.automation_write_root.as_deref(), Some(std::path::Path::new("/w")));
|
||||
assert!(parsed.safe_gpu && parsed.in_window_menus && parsed.new_instance);
|
||||
assert_eq!(parsed.present_mode, Some(PresentMode::AutoNoVsync));
|
||||
assert_eq!(parsed.frame_latency, Some(1));
|
||||
assert_eq!(parsed.stroke_trace.as_deref(), Some("stderr"));
|
||||
// In a fixed order: `single_instance` only lists them in a log line.
|
||||
assert_eq!(parsed.launch_options, PerProcess::FLAGS);
|
||||
assert_eq!(parsed.file_names(), FileNames { openable: vec!["photo.psd".to_string()], unreadable: vec![] });
|
||||
|
||||
let parsed = parse_args(&["--control-token-file", "/tmp/token", "--new-instance"]).unwrap();
|
||||
assert_eq!(parsed.auth.control_token_file.as_deref(), Some(std::path::Path::new("/tmp/token")));
|
||||
assert!(parsed.launch_options.is_empty() && !parsed.in_window_menus, "{:?}", parsed.launch_options);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_stops_parsing() {
|
||||
let e = parse_args(&["--version", "--control"]).err().unwrap();
|
||||
assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayVersion, 0));
|
||||
assert_eq!(e.to_string(), format!("photocraft {}\n", photocraft_engine::build_info::long_version()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_stops_parsing_and_double_dash_ends_options() {
|
||||
let e = parse_args(&["-h", "--safegpu", "--control"]).err().unwrap();
|
||||
assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayHelp, 0));
|
||||
|
||||
assert!(usage_error(&["--safegpu", "--", "--help"]).contains("unexpected argument '--safegpu'"));
|
||||
let parsed = parse_args(&["a.psd", "--", "--help", "-x"]).unwrap();
|
||||
assert_eq!(parsed.file_names().openable, ["a.psd", "--help", "-x"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finder_process_serial_number_is_dropped() {
|
||||
let parsed = parse_args(&["-psn_0_12345", "a.psd"]).unwrap();
|
||||
assert_eq!(parsed.file_names().openable, ["a.psd"]);
|
||||
let parsed = parse_args(&["--", "-psn_x.psd"]).unwrap();
|
||||
assert_eq!(parsed.file_names().openable, ["-psn_x.psd"]);
|
||||
}
|
||||
|
||||
/// #1108: a name that isn't valid Unicode is reported, not opened; a token must be text.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_unicode_file_names_are_reported_and_tokens_rejected() {
|
||||
use std::os::unix::ffi::OsStringExt as _;
|
||||
let latin1 = OsString::from_vec(b"caf\xe9.psd".to_vec());
|
||||
let parsed = parse(command().mut_args(|a| a.env(None::<&str>)), [latin1.clone()]).unwrap();
|
||||
assert_eq!(parsed.file_names(), FileNames { openable: vec![], unreadable: vec!["caf\u{fffd}.psd".to_string()] });
|
||||
let e = parse(command().mut_args(|a| a.env(None::<&str>)), [OsString::from("--control-token"), latin1]).err().unwrap();
|
||||
assert_eq!((e.kind(), e.exit_code()), (ErrorKind::InvalidUtf8, 2));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
//! lost device, the crash guard's panic report) vanished. A launch from a desktop menu has no
|
||||
//! terminal, so the file is what a bug report can attach: `<settings dir>/logs/photocraft.log`
|
||||
//! (see `app_dirs`). Each start moves the previous log to `photocraft.1.log` (and that one to
|
||||
//! `.2`), so the log of a run that crashed survives the next launch.
|
||||
//! `.2`), so the log of a run that crashed survives the next launch. A start while another
|
||||
//! instance is still running leaves that instance's log alone and writes `photocraft-<pid>.log`
|
||||
//! (see [`rotate`]).
|
||||
//!
|
||||
//! Levels: `info` for PhotoCraft's own crates, `warn` for everything else (wgpu and naga are
|
||||
//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`,
|
||||
@@ -15,7 +17,7 @@
|
||||
//! written once the file is attached. Writing never panics: a file that can't be created or
|
||||
//! written leaves standard error as the only sink.
|
||||
|
||||
use std::fs::File;
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
@@ -89,37 +91,112 @@ fn matches(name: &str, target: &str) -> bool {
|
||||
}
|
||||
|
||||
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
|
||||
/// A clock far past chrono's year range still converts (the calendar repeats every 400 years), so
|
||||
/// logging never panics and never silently resets to the epoch for a convertible instant.
|
||||
pub fn timestamp(t: SystemTime) -> String {
|
||||
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
let secs = since.as_secs();
|
||||
let (days, rem) = (secs / 86_400, secs % 86_400);
|
||||
let (y, m, d) = civil_from_days(days);
|
||||
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
|
||||
// Pre-1970 is clamped to the epoch by `unwrap_or_default` above. `as_secs` is `u64`; a value
|
||||
// past `i64::MAX` seconds saturates rather than falling back to the epoch.
|
||||
let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX);
|
||||
let (y, t) = utc_parts(secs, since.subsec_nanos());
|
||||
// `{:04}` rather than `%Y`, which writes a `+` before years past 9999.
|
||||
format!("{y:04}-{}", t.format("%m-%dT%H:%M:%S%.3fZ"))
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
|
||||
/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch).
|
||||
fn civil_from_days(days: u64) -> (u64, u64, u64) {
|
||||
let z = days + 719_468;
|
||||
let era = z / 146_097;
|
||||
let doe = z % 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + u64::from(m <= 2);
|
||||
(y, m, d)
|
||||
/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into
|
||||
/// chrono's range by whole 400-year cycles). The calendar repeats every 400 years (146_097 days),
|
||||
/// so month, day and time of day come from chrono and only the year is carried, which keeps every
|
||||
/// `i64` exact. Replaces the old hand-rolled `civil_from_days`; chrono is the only calendar logic.
|
||||
fn utc_parts(secs: i64, nanos: u32) -> (i64, chrono::NaiveDateTime) {
|
||||
use chrono::Datelike;
|
||||
let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
|
||||
// `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
|
||||
let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
|
||||
let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999)));
|
||||
match (date, time) {
|
||||
(Some(d), Some(t)) => {
|
||||
let y = i128::from(d.year()) + i128::from(cycles) * 400;
|
||||
(i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.and_time(t))
|
||||
}
|
||||
_ => (1970, chrono::NaiveDateTime::default()), // unreachable
|
||||
}
|
||||
}
|
||||
|
||||
fn numbered(dir: &Path, n: usize) -> PathBuf {
|
||||
if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("photocraft.{n}.log")) }
|
||||
}
|
||||
|
||||
/// Shift the previous logs up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest dropped)
|
||||
/// and create a fresh, empty log file in `dir` (created if missing).
|
||||
pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
/// Held by the instance that writes [`LOG_FILE`], from its start until it exits. A separate lock
|
||||
/// file rather than a lock on the log itself: Windows locks are mandatory, and a locked log could
|
||||
/// not be opened for a bug report while the app runs.
|
||||
pub const OWNER_LOCK: &str = "photocraft.lock";
|
||||
/// Held while one start rotates and prunes the logs, so two starts at once can't interleave.
|
||||
pub const ROTATE_LOCK: &str = "rotate.lock";
|
||||
|
||||
/// The log of an instance started while another one was writing [`LOG_FILE`].
|
||||
fn instance_log(dir: &Path, pid: u32) -> PathBuf {
|
||||
dir.join(format!("photocraft-{pid}.log"))
|
||||
}
|
||||
|
||||
/// The lock file that marks [`instance_log`] as in use.
|
||||
fn instance_lock(dir: &Path, pid: u32) -> PathBuf {
|
||||
dir.join(format!("photocraft-{pid}.lock"))
|
||||
}
|
||||
|
||||
/// The process id in an [`instance_log`] file name.
|
||||
fn instance_pid(name: &str) -> Option<u32> {
|
||||
let digits = name.strip_prefix("photocraft-")?.strip_suffix(".log")?;
|
||||
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
fn open_lock(path: &Path) -> std::io::Result<File> {
|
||||
OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)
|
||||
}
|
||||
|
||||
/// Take `file`'s lock without waiting: `Ok(true)` holds it, `Ok(false)` when another process holds it.
|
||||
fn try_hold(file: &File) -> std::io::Result<bool> {
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(true),
|
||||
Err(TryLockError::WouldBlock) => Ok(false),
|
||||
Err(TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a fresh, empty log file in `dir` (created if missing).
|
||||
///
|
||||
/// Normally the previous logs shift up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest
|
||||
/// dropped). While another instance is still writing [`LOG_FILE`] (it holds [`OWNER_LOCK`]), the
|
||||
/// chain is left alone and this start writes `photocraft-<pid>.log` instead: rotating would move
|
||||
/// that instance's live log away and, a few launches later, delete it (#6432). Such side-by-side
|
||||
/// logs are pruned to the newest [`KEEP`] once their instances have exited. On a file system
|
||||
/// without locks every start rotates, as before.
|
||||
pub fn rotate(dir: &Path) -> std::io::Result<LogFile> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// Waits only for another start's few file operations; without locking support, go on.
|
||||
let guard = open_lock(&dir.join(ROTATE_LOCK)).ok().filter(|g| g.lock().is_ok());
|
||||
let log = rotate_locked(dir);
|
||||
drop(guard);
|
||||
log
|
||||
}
|
||||
|
||||
fn rotate_locked(dir: &Path) -> std::io::Result<LogFile> {
|
||||
prune_instance_logs(dir);
|
||||
let owner = open_lock(&dir.join(OWNER_LOCK))?;
|
||||
let state = try_hold(&owner);
|
||||
if let Ok(false) = state {
|
||||
let pid = std::process::id();
|
||||
let lock = open_lock(&instance_lock(dir, pid))?;
|
||||
let held = try_hold(&lock).unwrap_or(false);
|
||||
let path = instance_log(dir, pid);
|
||||
let file = File::create(&path)?;
|
||||
return Ok(LogFile { path, file, owner: held.then_some(lock) });
|
||||
}
|
||||
// This start holds the owner lock (or the file system has no locks).
|
||||
let held = state.unwrap_or(false);
|
||||
for n in (1..=KEEP).rev() {
|
||||
match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
@@ -128,7 +205,40 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
}
|
||||
let path = numbered(dir, 0);
|
||||
let file = File::create(&path)?;
|
||||
Ok((path, file))
|
||||
Ok(LogFile { path, file, owner: held.then_some(owner) })
|
||||
}
|
||||
|
||||
/// Remove the side-by-side logs of instances that have exited, all but the newest [`KEEP`].
|
||||
/// A log whose lock file is held belongs to a running instance and is never touched. Failures
|
||||
/// are ignored: pruning only saves disk space.
|
||||
fn prune_instance_logs(dir: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut finished: Vec<(SystemTime, u32)> = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let Some(pid) = entry.file_name().to_str().and_then(instance_pid) else { continue };
|
||||
// A missing lock file means nobody holds it; an unknown lock state counts as running.
|
||||
let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) {
|
||||
Ok(lock) => !try_hold(&lock).unwrap_or(false),
|
||||
Err(_) => false,
|
||||
};
|
||||
if !running {
|
||||
let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
finished.push((modified, pid));
|
||||
}
|
||||
}
|
||||
finished.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for &(_, pid) in finished.iter().skip(KEEP) {
|
||||
let _ = std::fs::remove_file(instance_log(dir, pid));
|
||||
let _ = std::fs::remove_file(instance_lock(dir, pid));
|
||||
}
|
||||
}
|
||||
|
||||
/// A log file opened by [`rotate`].
|
||||
pub struct LogFile {
|
||||
pub path: PathBuf,
|
||||
pub file: File,
|
||||
/// The held lock that marks `path` as in use; `None` where locking isn't supported.
|
||||
owner: Option<File>,
|
||||
}
|
||||
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
@@ -205,19 +315,31 @@ pub struct AppLogger {
|
||||
filter: Filter,
|
||||
stderr: bool,
|
||||
sink: Mutex<Sink>,
|
||||
/// The file [`AppLogger::attach_dir`] opened, so a failure can tell the user what to attach.
|
||||
path: Mutex<Option<PathBuf>>,
|
||||
/// The lock that marks the attached log file as in use (see [`rotate`]); held until exit.
|
||||
owner: Mutex<Option<File>>,
|
||||
}
|
||||
|
||||
impl AppLogger {
|
||||
pub fn new(filter: Filter, stderr: bool) -> AppLogger {
|
||||
AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) }
|
||||
AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)), path: Mutex::new(None), owner: Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// Rotate the logs in `dir` and send records to the fresh file; returns its path.
|
||||
pub fn attach_dir(&self, dir: &Path) -> Result<PathBuf, String> {
|
||||
let (path, file) = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let LogFile { path, file, owner } = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file);
|
||||
*self.path.lock().unwrap_or_else(PoisonError::into_inner) = Some(path.clone());
|
||||
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// The log file records are written to, once [`AppLogger::attach_dir`] opened one: `None` when
|
||||
/// the file could not be created (standard error is the only sink, see [`install`]).
|
||||
pub fn path(&self) -> Option<PathBuf> {
|
||||
self.path.lock().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for AppLogger {
|
||||
@@ -266,6 +388,21 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
/// The startup-failure dialog names the log file, so the logger has to remember it (#7643).
|
||||
/// A start that couldn't create one keeps `None` and the dialog leaves the line out.
|
||||
#[test]
|
||||
fn path_names_the_attached_log_file() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let dir = temp_dir("path");
|
||||
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
assert_eq!(logger.path(), None, "nothing is written before a file is attached");
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(logger.path(), Some(path));
|
||||
drop(logger);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_filter_shows_photocraft_info_and_other_crates_warnings() {
|
||||
let f = Filter::parse(DEFAULT_FILTER);
|
||||
@@ -312,13 +449,28 @@ mod tests {
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// Past chrono's year range still converts via the 400-year cycle (the old code did too,
|
||||
// through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
|
||||
// SystemTime can't hold this instant, so it is only checked where it exists.
|
||||
// `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
// 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
|
||||
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let dir = temp_dir("rotate");
|
||||
for run in 1..=4 {
|
||||
let (path, _file) = rotate(&dir).expect("rotate");
|
||||
let LogFile { path, file: _file, owner: _owner } = rotate(&dir).expect("rotate");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(std::fs::read_to_string(&path).expect("read"), "");
|
||||
std::fs::write(&path, format!("run {run}")).expect("write");
|
||||
@@ -330,6 +482,66 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #6432: a second launch moved the running instance's live log to `.1.log`, a third to
|
||||
/// `.2.log`, and a fourth deleted it.
|
||||
#[test]
|
||||
fn a_second_start_leaves_the_running_instance_log_alone() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let dir = temp_dir("second");
|
||||
let mut first = rotate(&dir).expect("first start");
|
||||
assert_eq!(first.path, dir.join(LOG_FILE));
|
||||
first.file.write_all(b"first, before\n").expect("write");
|
||||
for _ in 0..KEEP + 1 {
|
||||
let second = rotate(&dir).expect("second start");
|
||||
assert_eq!(second.path, instance_log(&dir, std::process::id()));
|
||||
assert_eq!(read(&second.path), "");
|
||||
}
|
||||
first.file.write_all(b"first, after\n").expect("write");
|
||||
assert_eq!(read(&dir.join(LOG_FILE)), "first, before\nfirst, after\n");
|
||||
assert!(!dir.join("photocraft.1.log").exists(), "the running instance's log was rotated");
|
||||
// Once the first instance is gone, the next start rotates as before.
|
||||
drop(first);
|
||||
let third = rotate(&dir).expect("third start");
|
||||
assert_eq!(third.path, dir.join(LOG_FILE));
|
||||
assert_eq!(read(&dir.join("photocraft.1.log")), "first, before\nfirst, after\n");
|
||||
drop(third);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_logs_are_pruned_only_when_no_one_holds_them() {
|
||||
let _spawns = crate::no_child_spawns();
|
||||
let dir = temp_dir("prune");
|
||||
let first = rotate(&dir).expect("first start");
|
||||
// Earlier side-by-side runs that have exited, oldest first; the oldest has no lock file
|
||||
// (as if its lock file had been removed), the others an unlocked one.
|
||||
let now = SystemTime::now();
|
||||
for (age, pid) in [(400u64, 1u32), (300, 2), (200, 3), (100, 4)] {
|
||||
let path = instance_log(&dir, pid);
|
||||
std::fs::write(&path, format!("run {pid}")).expect("write");
|
||||
File::options().write(true).open(&path).expect("open").set_modified(now - Duration::from_secs(age)).expect("mtime");
|
||||
if pid != 1 {
|
||||
std::fs::write(instance_lock(&dir, pid), "").expect("lock file");
|
||||
}
|
||||
}
|
||||
// One older still running: its log is never removed, however old.
|
||||
let live = instance_log(&dir, 5);
|
||||
std::fs::write(&live, "live").expect("write");
|
||||
File::options().write(true).open(&live).expect("open").set_modified(now - Duration::from_secs(900)).expect("mtime");
|
||||
let held = File::create(instance_lock(&dir, 5)).expect("lock file");
|
||||
held.try_lock().expect("hold");
|
||||
|
||||
let second = rotate(&dir).expect("second start");
|
||||
assert_eq!(second.path, instance_log(&dir, std::process::id()));
|
||||
// The newest KEEP finished ones stay, the rest go with their lock files.
|
||||
assert!(instance_log(&dir, 4).exists() && instance_log(&dir, 3).exists());
|
||||
assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists());
|
||||
assert!(!instance_lock(&dir, 2).exists());
|
||||
assert_eq!(read(&live), "live");
|
||||
drop((first, second, held));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
|
||||
let dir = temp_dir("blocked");
|
||||
@@ -355,7 +567,7 @@ mod tests {
|
||||
#[test]
|
||||
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
|
||||
let dir = temp_dir("pending");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let LogFile { path, file, .. } = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early 1\n");
|
||||
sink.write("early 2\n");
|
||||
@@ -368,7 +580,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
|
||||
let dir = temp_dir("bounded");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let LogFile { path, file, .. } = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING + 5 {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
@@ -384,7 +596,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_file_stops_at_its_size_cap_with_one_note() {
|
||||
let dir = temp_dir("cap");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let LogFile { path, file, .. } = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(100);
|
||||
sink.attach(file);
|
||||
for i in 0..50 {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! PhotoCraft desktop app.
|
||||
//!
|
||||
//! Usage: `photocraft [--control <port>] [--control-token <64-hex> |
|
||||
//! --control-token-file <path>] [--automation-read-root <dir>]
|
||||
//! [--automation-write-root <dir>] [--safe-gpu] [--in-window-menus] [--present-mode <mode>]
|
||||
//! [--frame-latency <n>] [--stroke-trace <stderr|file.csv>] [--new-instance] [files…]`
|
||||
//! Usage: `photocraft [options] [--] [files…]`; `photocraft --help` lists the options, which are
|
||||
//! declared, with what makes a usage error (exit status 2), in `launch_args`.
|
||||
//!
|
||||
//! On Windows and Linux a launch hands its files to the PhotoCraft that is already running (new
|
||||
//! tabs in its window) and exits; `--new-instance` starts a separate copy instead, as does any
|
||||
@@ -26,7 +24,8 @@
|
||||
//! `{"id":1,"ok":true,"result":…}`. See `photocraft_ui_egui::control` for the methods.
|
||||
|
||||
// Release builds on Windows are GUI-subsystem apps, so launching from the Start Menu or Explorer
|
||||
// doesn't open a console window. (`--version` output then only shows when redirected.)
|
||||
// doesn't open a console window. (`--help`, `--version` and usage errors then only show when
|
||||
// redirected.)
|
||||
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -44,6 +43,7 @@ mod file_dialog_probe;
|
||||
mod gpu_startup;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod icon_theme;
|
||||
mod launch_args;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_menu;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -58,15 +58,19 @@ mod photoshop_settings;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod portal_save;
|
||||
mod presentation;
|
||||
// The print portal needs the session bus (zbus, Linux only); its pure helpers are tested everywhere.
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod print_portal;
|
||||
mod screen_color;
|
||||
mod services;
|
||||
// macOS gets one instance from LaunchServices (open-documents Apple events).
|
||||
#[cfg(any(not(target_os = "macos"), test))]
|
||||
mod single_instance;
|
||||
// Windows gets pen pressure from winit (WM_POINTER); the web runner has its own listener.
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", test))]
|
||||
mod startup_report;
|
||||
// Tablet support (macOS AppKit monitor, Linux X11/Wayland, Windows barrel button).
|
||||
mod tablet;
|
||||
mod ui_state;
|
||||
mod updates;
|
||||
mod window_frame;
|
||||
|
||||
use photocraft_engine::Session;
|
||||
@@ -89,15 +93,60 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool {
|
||||
CUSTOM_TITLEBAR && !prefs.interface.system_title_bar
|
||||
}
|
||||
|
||||
/// Preferences › Integrations, read before the window opens the way [`custom_titlebar`] is:
|
||||
/// whether agents may drive this launch at all, and the port to listen on when no `--control`
|
||||
/// was given (0 = only with `--control`). A missing or unreadable file keeps the defaults.
|
||||
///
|
||||
/// The section is read on its own, and when it doesn't read as a whole each value on its own,
|
||||
/// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or
|
||||
/// in the other field, must not turn Allow Agent Control back on while the dialog shows it off.
|
||||
fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::prefs::Integrations {
|
||||
use serde_json::Value;
|
||||
let mut out = photocraft_engine::prefs::Preferences::default().integrations;
|
||||
let file: Option<Value> = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
|
||||
let Some(section) = file.as_ref().and_then(|v| v.get("integrations")) else {
|
||||
return out;
|
||||
};
|
||||
if let Ok(whole) = serde_json::from_value(section.clone()) {
|
||||
return whole;
|
||||
}
|
||||
if let Some(allow) = section.get("allowAgentControl").and_then(Value::as_bool) {
|
||||
out.allow_agent_control = allow;
|
||||
}
|
||||
if let Some(port) = section.get("controlPort").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()) {
|
||||
out.control_port = port;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The control port this launch listens on, and the warning to print when a request was refused.
|
||||
/// `--control` (or `PHOTOCRAFT_CONTROL_PORT`) wins over the preference; Allow Agent Control off
|
||||
/// refuses both, and says so rather than ignoring the flag silently. A preferred port outside
|
||||
/// 1..=65535 is refused the same way.
|
||||
fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrations) -> (Option<u16>, Option<String>) {
|
||||
if !prefs.allow_agent_control {
|
||||
let warning = cli.map(|p| format!("photocraft: Preferences › Integrations › Allow Agent Control is off: not listening on port {p}\n"));
|
||||
return (None, warning);
|
||||
}
|
||||
if let Some(port) = cli {
|
||||
return (Some(port), None);
|
||||
}
|
||||
match prefs.control_port {
|
||||
0 => (None, None),
|
||||
p => match u16::try_from(p).ok().filter(|p| *p != 0) {
|
||||
Some(port) => (Some(port), None),
|
||||
None => (None, Some(format!("photocraft: Preferences › Integrations › Control Port {p} is not a usable port: not listening\n"))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame
|
||||
/// when it still doesn't fit, `work_area::fit_window`), centred on the main monitor. Without
|
||||
/// `centered`, Windows cascades each new window from the top-left corner, so it opened at a
|
||||
/// different offset every launch (#419). A later launch restores the saved position instead
|
||||
/// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves.
|
||||
fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
let viewport = egui::ViewportBuilder::default();
|
||||
// Not inside a macOS app bundle: its Dock icon is the bundle's .icns (`app_icon`, #5849).
|
||||
let viewport = if app_icon::sets_runtime_icon(std::env::current_exe().ok().as_deref()) { viewport.with_icon(app_icon::window_icon()) } else { viewport };
|
||||
let viewport = egui::ViewportBuilder::default().with_icon(app_icon::viewport_icon(std::env::current_exe().ok().as_deref()));
|
||||
eframe::NativeOptions {
|
||||
viewport: viewport
|
||||
.with_app_id(APP_ID)
|
||||
@@ -110,6 +159,9 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false),
|
||||
centered: true,
|
||||
// PhotoCraft owns its fallback fonts (`cjk_fonts`, craft-fonts): eframe's system-font
|
||||
// provider would compete with it and make glyph choice machine-dependent (#8512).
|
||||
system_font_fallback: false,
|
||||
// eframe saves native window geometry and egui panel/window sizes on exit.
|
||||
// Keep that state beside preferences, including config overrides and portable mode.
|
||||
persistence_path: services::config_dir().map(|dir| dir.join("ui.ron")),
|
||||
@@ -142,150 +194,9 @@ fn at_least_min_size(mut builder: egui::ViewportBuilder) -> egui::ViewportBuilde
|
||||
builder
|
||||
}
|
||||
|
||||
/// Parse a `--control` / `PHOTOCRAFT_CONTROL_PORT` value. An unparseable port is an error that
|
||||
/// names the value (issue #701): silently running with no control server leaves a launcher or
|
||||
/// agent unable to tell a typo from a successful grant.
|
||||
fn parse_control_port(value: &str, source: &str) -> Result<u16, String> {
|
||||
value.trim().parse().map_err(|_| format!("{source}: `{value}` is not a valid port (expected a number from 0 to 65535)"))
|
||||
}
|
||||
|
||||
/// Process exit status for the collected `--control` / `PHOTOCRAFT_CONTROL_PORT` errors: `None`
|
||||
/// when there are none, else 2 (a command-line usage error), never 0.
|
||||
fn control_args_exit_code(errors: &[String]) -> Option<i32> {
|
||||
if errors.is_empty() { None } else { Some(2) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod control_port_tests {
|
||||
use super::{control_args_exit_code, parse_control_port};
|
||||
|
||||
#[test]
|
||||
fn control_port_errors_exit_non_zero() {
|
||||
assert_eq!(control_args_exit_code(&[]), None);
|
||||
let errors = vec![parse_control_port("nope", "--control").unwrap_err()];
|
||||
assert_eq!(control_args_exit_code(&errors), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_port_accepts_valid_numbers() {
|
||||
assert_eq!(parse_control_port("50494", "--control"), Ok(50494));
|
||||
assert_eq!(parse_control_port(" 8080 ", "--control"), Ok(8080));
|
||||
assert_eq!(parse_control_port("0", "PHOTOCRAFT_CONTROL_PORT"), Ok(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_port_rejects_unparseable_values_naming_them() {
|
||||
// Out of range, a following flag eaten as the value, and an empty value all fail,
|
||||
// naming the offending value in the message.
|
||||
let err = parse_control_port("78787", "--control").unwrap_err();
|
||||
assert!(err.contains("78787"), "{err}");
|
||||
assert!(parse_control_port("--safe-gpu", "--control").is_err());
|
||||
assert!(parse_control_port("", "--control").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
crash_guard::install_hook();
|
||||
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
|
||||
photocraft_ui_egui::type_tool::warm_fonts();
|
||||
let mut control_port: Option<u16> = None;
|
||||
let mut control_arg_errors: Vec<String> = Vec::new();
|
||||
if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
|
||||
match parse_control_port(&value, "PHOTOCRAFT_CONTROL_PORT") {
|
||||
Ok(port) => control_port = Some(port),
|
||||
Err(error) => control_arg_errors.push(error),
|
||||
}
|
||||
}
|
||||
let mut control_token = None;
|
||||
let mut control_token_file = None;
|
||||
let mut automation_read_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from);
|
||||
let mut automation_write_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from);
|
||||
let mut files = Vec::new();
|
||||
// Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1
|
||||
// file name on Linux, and `std::env::args()` would panic before any window opened. Paths are
|
||||
// reported in a notice once the app is up; a control token is a usage error like a bad port.
|
||||
let mut unreadable_paths: Vec<String> = Vec::new();
|
||||
let mut safe_gpu = false;
|
||||
let mut new_instance = false;
|
||||
// Options that apply only to the process they're given to; a launch with any keeps its own.
|
||||
let mut launch_options: Vec<&'static str> = Vec::new();
|
||||
let (mut present_mode_arg, mut frame_latency_arg, mut stroke_trace_arg): (Option<String>, Option<String>, Option<String>) = (None, None, None);
|
||||
let mut in_window_menus = std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.to_str() {
|
||||
Some("--control") => match args.next() {
|
||||
Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") {
|
||||
Ok(port) => control_port = Some(port),
|
||||
Err(error) => control_arg_errors.push(error),
|
||||
},
|
||||
None => control_arg_errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
|
||||
},
|
||||
Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) {
|
||||
Some(Ok(token)) => control_token = Some(token),
|
||||
Some(Err(raw)) => control_arg_errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
|
||||
None => control_token = None,
|
||||
},
|
||||
Some("--control-token-file") => control_token_file = args.next().map(std::path::PathBuf::from),
|
||||
Some("--automation-read-root") => {
|
||||
launch_options.push("--automation-read-root");
|
||||
automation_read_root = args.next().map(std::path::PathBuf::from);
|
||||
}
|
||||
Some("--automation-write-root") => {
|
||||
launch_options.push("--automation-write-root");
|
||||
automation_write_root = args.next().map(std::path::PathBuf::from);
|
||||
}
|
||||
Some("--safe-gpu") => {
|
||||
launch_options.push("--safe-gpu");
|
||||
safe_gpu = true;
|
||||
}
|
||||
Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => {
|
||||
launch_options.push(match flag {
|
||||
"--present-mode" => "--present-mode",
|
||||
"--frame-latency" => "--frame-latency",
|
||||
_ => "--stroke-trace",
|
||||
});
|
||||
let flag = flag.to_string();
|
||||
match args.next().map(std::ffi::OsString::into_string) {
|
||||
Some(Ok(v)) => match flag.as_str() {
|
||||
"--present-mode" => present_mode_arg = Some(v),
|
||||
"--frame-latency" => frame_latency_arg = Some(v),
|
||||
_ => stroke_trace_arg = Some(v),
|
||||
},
|
||||
// A bad value is reported and ignored; it never fails the launch.
|
||||
_ => eprintln!("photocraft: {flag}: missing or unreadable value; ignored"),
|
||||
}
|
||||
}
|
||||
Some("--in-window-menus") => {
|
||||
launch_options.push("--in-window-menus");
|
||||
in_window_menus = true;
|
||||
}
|
||||
Some("--new-instance") => new_instance = true,
|
||||
Some("--version") => {
|
||||
println!("photocraft {}", photocraft_engine::build_info::long_version());
|
||||
return Ok(());
|
||||
}
|
||||
// Old macOS passes a process serial number when launched from Finder.
|
||||
Some(s) if s.starts_with("-psn_") => {}
|
||||
Some(s) => files.push(s.to_owned()),
|
||||
None => unreadable_paths.push(a.to_string_lossy().into_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed control port must not silently drop the control server (issue #701): name the
|
||||
// bad value and fail the launch, like `photocraft-cli serve --port` does for the same typo.
|
||||
// Exit status 2 is the usual command-line usage error, so a launcher sees the failure.
|
||||
if let Some(code) = control_args_exit_code(&control_arg_errors) {
|
||||
for error in &control_arg_errors {
|
||||
eprintln!("photocraft: {error}");
|
||||
}
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
// The log file lives under the settings directory; opened after the arguments, so `--version`
|
||||
// and usage errors leave no file behind. Records logged until now are written to it first.
|
||||
/// Attach the log file under the settings directory. Called after the arguments are parsed, so
|
||||
/// `--version` and usage errors leave no file behind. Records logged until now are written first.
|
||||
fn attach_log_file(logger: Option<&'static logging::AppLogger>) {
|
||||
if let (Some(logger), Some(dir)) = (logger, services::config_dir()) {
|
||||
match logger.attach_dir(&dir.join("logs")) {
|
||||
Ok(path) => log::info!("PhotoCraft {}, log file {}", photocraft_engine::build_info::long_version(), path.display()),
|
||||
@@ -293,59 +204,64 @@ fn main() -> eframe::Result {
|
||||
Err(e) => log::warn!("no log file: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One PhotoCraft per user (#3708): files opened from Explorer or a file manager while it runs
|
||||
// become tabs in its window. Only with the per-user settings folder (a portable copy's may be
|
||||
// shared between users), and not for automation, `--new-instance` or per-process options.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let single_instance = {
|
||||
let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok();
|
||||
let context = single_instance::LaunchContext {
|
||||
per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform,
|
||||
new_instance_flag: new_instance,
|
||||
new_instance_env: new_instance_env.as_deref(),
|
||||
control: control_port.is_some(),
|
||||
unreadable_paths: !unreadable_paths.is_empty(),
|
||||
launch_options: &launch_options,
|
||||
};
|
||||
match (single_instance::skip_reason(&context), services::config_dir()) {
|
||||
(Some(reason), _) => {
|
||||
log::info!("running as a separate PhotoCraft: {reason}");
|
||||
None
|
||||
}
|
||||
(None, None) => None,
|
||||
(None, Some(dir)) => {
|
||||
let paths: Vec<String> = files.iter().map(|f| single_instance::absolute(f)).collect();
|
||||
match single_instance::claim(&dir, &paths) {
|
||||
single_instance::Launch::Forwarded => {
|
||||
log::info!("handed {} file(s) to the running PhotoCraft", paths.len());
|
||||
return Ok(());
|
||||
}
|
||||
single_instance::Launch::Primary(primary) => Some(primary),
|
||||
single_instance::Launch::Standalone(reason) => {
|
||||
log::warn!("starting a separate PhotoCraft: {reason}");
|
||||
None
|
||||
}
|
||||
/// One PhotoCraft per user (#3708). Only with the per-user settings folder (a portable copy's may
|
||||
/// be shared between users), and not for automation, `--new-instance` or per-process options.
|
||||
/// `Break` when the files were handed to the running PhotoCraft and this launch is done.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn claim_single_instance(
|
||||
files: &[String],
|
||||
new_instance: bool,
|
||||
control: bool,
|
||||
unreadable_paths: bool,
|
||||
mut launch_options: Vec<launch_args::PerProcess>,
|
||||
) -> std::ops::ControlFlow<(), Option<single_instance::Primary>> {
|
||||
use std::ops::ControlFlow::{Break, Continue};
|
||||
let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok();
|
||||
// A variable documented as the equivalent of a per-launch flag counts as that flag: a
|
||||
// launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it
|
||||
// keeps its own process instead of handing its files over and being ignored.
|
||||
launch_options.extend_from_slice(&single_instance::env_launch_options());
|
||||
let context = single_instance::LaunchContext {
|
||||
per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform,
|
||||
new_instance_flag: new_instance,
|
||||
new_instance_env: new_instance_env.as_deref(),
|
||||
control,
|
||||
unreadable_paths,
|
||||
launch_options: &launch_options,
|
||||
};
|
||||
match (single_instance::skip_reason(&context), services::config_dir()) {
|
||||
(Some(reason), _) => {
|
||||
log::info!("running as a separate PhotoCraft: {reason}");
|
||||
Continue(None)
|
||||
}
|
||||
(None, None) => Continue(None),
|
||||
(None, Some(dir)) => {
|
||||
let paths: Vec<String> = files.iter().map(|f| single_instance::absolute(f)).collect();
|
||||
match single_instance::claim(&dir, &paths) {
|
||||
single_instance::Launch::Forwarded => {
|
||||
log::info!("handed {} file(s) to the running PhotoCraft", paths.len());
|
||||
Break(())
|
||||
}
|
||||
single_instance::Launch::Primary(primary) => Continue(Some(primary)),
|
||||
single_instance::Launch::Standalone(reason) => {
|
||||
log::warn!("starting a separate PhotoCraft: {reason}");
|
||||
Continue(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Lives until the event loop returns, then `shutdown` lets the next launch become the primary.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let single_instance = &single_instance;
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = (new_instance, &launch_options);
|
||||
}
|
||||
}
|
||||
|
||||
// The display server to open the window on: Xwayland for a pen on Wayland, which gives this
|
||||
// app no pen input (#639).
|
||||
#[cfg(target_os = "linux")]
|
||||
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
|
||||
#[cfg(target_os = "linux")]
|
||||
/// The display server to open the window on: Xwayland for a pen on Wayland, which gives this app
|
||||
/// no pen input (#639). Exits with the package to install when its libraries are missing.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_display_session() -> linux_libs::DisplaySession {
|
||||
let session = tablet::display_session();
|
||||
// Preferences › Performance › Linux display server = X11: Xwayland on a Wayland session too,
|
||||
// where native file drops work (winit 0.30 has none on Wayland, #386). Only when Xwayland can
|
||||
// run the window ($DISPLAY set, X11 libraries installed); otherwise the session's own.
|
||||
#[cfg(target_os = "linux")]
|
||||
let session = if session == linux_libs::DisplaySession::Wayland
|
||||
&& gpu_startup::read_display_server(services::prefs_file().as_deref()) == photocraft_engine::prefs::LinuxDisplayServer::X11
|
||||
&& std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty())
|
||||
@@ -356,42 +272,135 @@ fn main() -> eframe::Result {
|
||||
} else {
|
||||
session
|
||||
};
|
||||
|
||||
// winit and wgpu dlopen the windowing and GPU libraries, and some of those crates panic when
|
||||
// one is missing (issue #201). Name the package to install and exit instead.
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Err(message) = linux_libs::preflight(session) {
|
||||
eprint!("{message}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
session
|
||||
}
|
||||
|
||||
let control = if let Some(port) = control_port {
|
||||
let (supplied, token_file) = photocraft_automation::security::token_inputs(control_token, control_token_file);
|
||||
let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) {
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: cannot configure control authentication: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if let Some(path) = token_file {
|
||||
eprintln!("photocraft: control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
eprintln!("photocraft: control token: {token}");
|
||||
} else {
|
||||
eprintln!("photocraft: using supplied control token");
|
||||
/// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration).
|
||||
fn control_setup(
|
||||
cli_port: Option<u16>,
|
||||
auth: photocraft_automation::args::ControlArgs,
|
||||
automation: &photocraft_automation::args::AutomationArgs,
|
||||
) -> Option<(std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace)> {
|
||||
let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref()));
|
||||
if let Some(warning) = &warning {
|
||||
eprint!("{warning}");
|
||||
}
|
||||
let port = port?;
|
||||
let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let workspace = match photocraft_automation::AuthorizedWorkspace::new(automation_read_root.as_deref(), automation_write_root.as_deref()) {
|
||||
Ok(workspace) => workspace,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: cannot configure automation workspace: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
Some((port, token, workspace))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (supplied, token_file) = (auth.control_token, auth.control_token_file);
|
||||
let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) {
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: cannot configure control authentication: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if let Some(path) = token_file {
|
||||
eprintln!("photocraft: control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
eprintln!("photocraft: control token: {token}");
|
||||
} else {
|
||||
eprintln!("photocraft: using supplied control token");
|
||||
}
|
||||
let workspace = match automation.workspace() {
|
||||
Ok(workspace) => workspace,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: cannot configure automation workspace: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
Some((listener, token, workspace))
|
||||
}
|
||||
|
||||
/// Record this start's backend in the GPU startup marker, if the marker is locked.
|
||||
fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup::Plan) {
|
||||
if let Some(s) = sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_mut() {
|
||||
let backend = match &plan.env {
|
||||
Some(v) => format!("env:{v}"),
|
||||
None => plan.backend.name().to_string(),
|
||||
};
|
||||
let marker = gpu_startup::Marker { backend, version: photocraft_engine::build_info::long_version().to_string(), ..Default::default() };
|
||||
if let Err(e) = s.write(marker) {
|
||||
log::warn!("GPU startup marker: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
crash_guard::install_hook();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if let Err(e) = done {
|
||||
eprintln!("PhotoCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
|
||||
photocraft_ui_egui::type_tool::warm_fonts();
|
||||
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown
|
||||
// option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT: issues #701, #6429, #6431)
|
||||
// names the argument on standard error and exits 2, so a launcher sees the failure. Neither
|
||||
// panics when the stream is closed or a pipe (`photocraft --help | head -1`).
|
||||
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
|
||||
let launch_args::FileNames { openable: files, unreadable: unreadable_paths } = launch.file_names();
|
||||
let launch_args::LaunchArgs {
|
||||
files: _,
|
||||
safe_gpu,
|
||||
in_window_menus,
|
||||
new_instance,
|
||||
present_mode,
|
||||
frame_latency,
|
||||
stroke_trace,
|
||||
control: control_port,
|
||||
auth,
|
||||
automation,
|
||||
mut launch_options,
|
||||
} = launch;
|
||||
|
||||
attach_log_file(logger);
|
||||
|
||||
// An adapter named in the environment is chosen at startup, which a forwarded launch never reaches.
|
||||
let rendering_mode = gpu_startup::read_rendering_prefs(services::prefs_file().as_deref()).1;
|
||||
if gpu_startup::adapter_override_is_process_specific(std::env::var("PHOTOCRAFT_GPU_ADAPTER").ok().as_deref(), rendering_mode, gpu_startup::ADAPTER_CHOICE) {
|
||||
launch_options.push(launch_args::PerProcess::GpuAdapterEnv);
|
||||
}
|
||||
// One PhotoCraft per user (#3708): files opened from Explorer or a file manager while it runs
|
||||
// become tabs in its window. Lives until the event loop returns, then `shutdown` lets the next
|
||||
// launch become the primary.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let single_instance = match claim_single_instance(&files, new_instance, control_port.is_some(), !unreadable_paths.is_empty(), launch_options) {
|
||||
std::ops::ControlFlow::Break(()) => return Ok(()),
|
||||
std::ops::ControlFlow::Continue(primary) => primary,
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let single_instance = &single_instance;
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = (new_instance, &launch_options);
|
||||
|
||||
// Bind and authenticate the authorized control listener before display/GPU initialization.
|
||||
let control = control_setup(control_port, auth, &automation);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
|
||||
#[cfg(target_os = "linux")]
|
||||
let session = linux_display_session();
|
||||
|
||||
// Finder / Dock / Open With deliver files as Apple events, not arguments; catch the one that
|
||||
// launched us as well as later ones. Lives until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -405,6 +414,11 @@ fn main() -> eframe::Result {
|
||||
let tablet_monitor = std::cell::OnceCell::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
let tablet_monitor = &tablet_monitor;
|
||||
// The Windows pointer message hook; dropping it unhooks when the event loop returns.
|
||||
#[cfg(target_os = "windows")]
|
||||
let tablet_monitor_win = std::cell::OnceCell::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
let tablet_monitor_win = &tablet_monitor_win;
|
||||
|
||||
// Read the displays' ICC profiles while the window opens (colour-managed canvas; `None`
|
||||
// where the platform has no reader).
|
||||
@@ -444,26 +458,19 @@ fn main() -> eframe::Result {
|
||||
log::warn!("the previous start didn't finish (GPU backend {}, adapter {:?}); {}", m.backend, m.adapter, plan.reason.as_deref().unwrap_or(""));
|
||||
}
|
||||
let sentinel: gpu_startup::SharedSentinel = std::sync::Arc::new(std::sync::Mutex::new(sentinel));
|
||||
if let Some(s) = sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_mut() {
|
||||
let backend = match &plan.env {
|
||||
Some(v) => format!("env:{v}"),
|
||||
None => plan.backend.name().to_string(),
|
||||
};
|
||||
let marker = gpu_startup::Marker { backend, version: photocraft_engine::build_info::long_version().to_string(), ..Default::default() };
|
||||
if let Err(e) = s.write(marker) {
|
||||
log::warn!("GPU startup marker: {e}");
|
||||
}
|
||||
}
|
||||
write_start_marker(&sentinel, &plan);
|
||||
let gpu_note: std::sync::Arc<std::sync::Mutex<Option<String>>> = Default::default();
|
||||
// The adapter's real texture limits (egui asks for 8192 px), so big documents stay on the GPU.
|
||||
gpu_startup::configure(&mut options.wgpu_options.wgpu_setup, &plan, os, sentinel.clone(), gpu_note.clone());
|
||||
let wanted_adapter =
|
||||
gpu_startup::wanted_adapter(std::env::var("PHOTOCRAFT_GPU_ADAPTER").ok().as_deref(), &gpu_startup::read_gpu_adapter(services::prefs_file().as_deref()));
|
||||
gpu_startup::configure(&mut options.wgpu_options.wgpu_setup, &plan, os, wanted_adapter, sentinel.clone(), gpu_note.clone());
|
||||
// Preferences › Performance › Low-Latency Drawing (#1343): without vsync a stroke shows about
|
||||
// 50 ms sooner; wgpu picks Immediate, else Mailbox, else Fifo by what the driver offers.
|
||||
if gpu_startup::read_low_latency(services::prefs_file().as_deref()) {
|
||||
options.wgpu_options.surface.present_mode = eframe::wgpu::PresentMode::AutoNoVsync;
|
||||
}
|
||||
// Testers' present mode and frame latency overrides (#1343), after the preference.
|
||||
let present = presentation::Overrides::from_args_or_env(present_mode_arg.as_deref(), frame_latency_arg.as_deref());
|
||||
let present = presentation::Overrides::from_args_or_env(present_mode, frame_latency);
|
||||
options.wgpu_options.surface = present.apply(options.wgpu_options.surface);
|
||||
let present_desc = presentation::describe(&options.wgpu_options.surface, &present);
|
||||
// Without vsync, frames are capped at 240 fps (#4472) so repaint loops don't spin flat out.
|
||||
@@ -476,6 +483,10 @@ fn main() -> eframe::Result {
|
||||
log::info!("GPU startup: {:?} ({sentinel_ms:.2} ms)", plan);
|
||||
let retry_cpu = !safe_gpu && plan.backend != photocraft_engine::prefs::GpuBackend::Cpu;
|
||||
let keep_marker = gpu_startup::keep_marker_after_error(&plan, os);
|
||||
// For the failure dialog below: the plan itself moves into the window closure. With
|
||||
// `WGPU_BACKEND` set (`plan.env`) wgpu picks the backend, so name that rather than `auto`.
|
||||
let started_renderer = plan.env.clone().unwrap_or_else(|| plan.backend.name().to_string());
|
||||
let started_note = plan.reason.clone();
|
||||
let app_created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let created_in_callback = app_created.clone();
|
||||
let started_sentinel = sentinel.clone();
|
||||
@@ -499,7 +510,16 @@ fn main() -> eframe::Result {
|
||||
services::xwayland_command(var("FLATPAK_ID").as_deref(), var("APPIMAGE").as_deref(), std::env::var_os("DISPLAY").is_some());
|
||||
}
|
||||
}
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
#[cfg(target_os = "linux")]
|
||||
let session = {
|
||||
let mut session = Session::new();
|
||||
session.print_spooler = print_portal::spooler();
|
||||
session
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let session = Session::new();
|
||||
PhotocraftApp::install_type_reset_hooks(&cc.egui_ctx);
|
||||
let mut app = PhotocraftApp::new(session, services);
|
||||
app.min_frame_ms = uncapped.then_some(1000.0 / 240.0);
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
app.custom_titlebar = custom_titlebar;
|
||||
@@ -533,7 +553,7 @@ fn main() -> eframe::Result {
|
||||
let info = &mut app.perf.gpu_info;
|
||||
info.preference = pref.name().to_string();
|
||||
info.present = present_desc.clone();
|
||||
if let Some(v) = &stroke_trace_arg {
|
||||
if let Some(v) = &stroke_trace {
|
||||
app.stroke_trace.set(v);
|
||||
}
|
||||
info.selected = if plan.env.is_some() { "env".into() } else { plan.backend.name().to_string() };
|
||||
@@ -544,9 +564,19 @@ fn main() -> eframe::Result {
|
||||
info.canvas = "cpu".into();
|
||||
if let Some(rs) = cc.wgpu_render_state.clone() {
|
||||
app.perf.gpu_info.set_adapter(&rs.adapter.get_info());
|
||||
app.perf.gpu_info.set_available(&rs.available_adapters);
|
||||
// Every egui texture uploads through this adapter, whichever canvas draws:
|
||||
// Iris Xe on DX12 shows stale memory in all-zero texels (texel_guard.rs).
|
||||
photocraft_ui_egui::texel_guard::install(&cc.egui_ctx, &rs.adapter.get_info());
|
||||
let software_window = rs.adapter.get_info().device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software_window && mode != photocraft_engine::prefs::RenderingMode::Cpu {
|
||||
app.perf.gpu_info.fallback = Some("No compatible hardware graphics adapter; using software graphics.".into());
|
||||
// Keep an earlier note, such as a requested adapter that couldn't be used.
|
||||
let software = "No compatible hardware graphics adapter; using software graphics.";
|
||||
let fallback = &mut app.perf.gpu_info.fallback;
|
||||
*fallback = Some(match fallback.take() {
|
||||
Some(earlier) => format!("{earlier}. {software}"),
|
||||
None => software.into(),
|
||||
});
|
||||
}
|
||||
if !software_window
|
||||
&& plan.backend != photocraft_engine::prefs::GpuBackend::Cpu
|
||||
@@ -555,8 +585,9 @@ fn main() -> eframe::Result {
|
||||
{
|
||||
app.set_wgpu(rs);
|
||||
} else {
|
||||
// The window still draws with wgpu: record its errors instead of panicking.
|
||||
let _ = photocraft_ui_egui::gpu_canvas::DeviceHealth::watch(&rs.device);
|
||||
// The window still draws with wgpu: record its errors instead of panicking,
|
||||
// and notice when the device is lost (#3438).
|
||||
app.watch_window_device(&rs.device);
|
||||
}
|
||||
}
|
||||
let fallback_reason = std::env::var("PHOTOCRAFT_GPU_STARTUP_FAILURE").ok().or_else(|| {
|
||||
@@ -582,8 +613,8 @@ fn main() -> eframe::Result {
|
||||
log::warn!("couldn't remember GPU backend {}: {e}", b.name());
|
||||
}
|
||||
});
|
||||
if let Some((port, token, _)) = control {
|
||||
let rx = control_server::start(port, token, cc.egui_ctx.clone());
|
||||
if let Some((listener, token, _)) = control {
|
||||
let rx = control_server::start(listener, token, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -623,8 +654,13 @@ fn main() -> eframe::Result {
|
||||
if let Some(monitor) = tablet::install_macos(&app.stylus.feed) {
|
||||
let _ = tablet_monitor.set(monitor);
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Some(monitor) = tablet::install_windows() {
|
||||
let _ = tablet_monitor_win.set(monitor);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
tablet::spawn_x11(&app.stylus.feed, display);
|
||||
app.services.right_button_down = tablet::right_button_service();
|
||||
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
|
||||
app.open_paths(&files);
|
||||
if !unreadable_paths.is_empty() {
|
||||
@@ -675,9 +711,10 @@ fn main() -> eframe::Result {
|
||||
s.finish();
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
// `--safe-gpu` first: after a `--`, it would be a file name.
|
||||
let launched = std::process::Command::new(exe)
|
||||
.args(std::env::args_os().skip(1))
|
||||
.arg("--safe-gpu")
|
||||
.args(std::env::args_os().skip(1))
|
||||
.env_remove("WGPU_BACKEND")
|
||||
.env("PHOTOCRAFT_GPU_STARTUP_FAILURE", &reason)
|
||||
.spawn();
|
||||
@@ -687,9 +724,32 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A launch that fails before a window exists leaves nothing on screen, and a desktop launch
|
||||
// has no console for the `Err` above: log it, then say why in a native dialog with the log
|
||||
// file to attach (#7643). A terminal or automation launch can read standard error or the
|
||||
// exit status instead, so it keeps the silent exit.
|
||||
if let Err(error) = &result {
|
||||
log::error!("PhotoCraft could not start: {error}");
|
||||
if startup_report::needs_dialog(control_port.is_some()) {
|
||||
startup_report::show(&error.to_string(), &started_renderer, started_note.as_deref(), logger.and_then(logging::AppLogger::path).as_deref());
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Tests that spawn child processes hold this for reading, tests that check who holds a file lock
|
||||
/// for writing ([`no_child_spawns`]): until its `exec`, a child holds a copy of every open file,
|
||||
/// `flock`s included, so a spawn in another test could keep a lock this process just dropped held
|
||||
/// for a moment.
|
||||
#[cfg(test)]
|
||||
pub(crate) static CHILD_SPAWNS: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that checks who holds a file lock: no other test spawns a child meanwhile.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> {
|
||||
CHILD_SPAWNS.write().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -726,10 +786,101 @@ mod tests {
|
||||
egui::Panel::right("dock").default_size(290.0).show(ui, |ui| ui.set_min_width(ui.available_width()));
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let panel = egui::containers::panel::PanelState::load(&restored, egui::Id::new("dock")).unwrap();
|
||||
let panel = egui::containers::panel::PanelState::load(&restored, photocraft_ui_egui::panels::panel_state_id(&restored, "dock")).unwrap();
|
||||
assert_eq!(panel.size().x, 410.0);
|
||||
}
|
||||
|
||||
/// A 0.36 `ui.ron` saved panel widths under `Id::new("dock")`; the first 0.37 launch copies
|
||||
/// them to the parent-scoped key, leaves the old one for a rollback, and a later resize
|
||||
/// survives two more restarts.
|
||||
#[test]
|
||||
fn saved_036_panel_widths_migrate_and_survive_two_restarts() {
|
||||
#[derive(Default)]
|
||||
struct Storage(std::collections::BTreeMap<String, String>);
|
||||
impl eframe::Storage for Storage {
|
||||
fn get_string(&self, key: &str) -> Option<String> {
|
||||
self.0.get(key).cloned()
|
||||
}
|
||||
fn set_string(&mut self, key: &str, value: String) {
|
||||
self.0.insert(key.into(), value);
|
||||
}
|
||||
fn remove_string(&mut self, key: &str) {
|
||||
self.0.remove(key);
|
||||
}
|
||||
fn flush(&mut self) {}
|
||||
}
|
||||
let state = |width: f32| egui::containers::panel::PanelState { outer_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 600.0)) };
|
||||
let input = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() };
|
||||
let draw = |ctx: &egui::Context| {
|
||||
let mut output = ctx.run_ui(input(), |ui| {
|
||||
egui::Panel::right("dock").default_size(290.0).show(ui, |ui| ui.set_min_width(ui.available_width()));
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
};
|
||||
let save = |ctx: &egui::Context| {
|
||||
let mut storage = Storage::default();
|
||||
ctx.memory(|memory| eframe::set_value(&mut storage, "egui", memory));
|
||||
storage
|
||||
};
|
||||
let restore = |storage: &Storage| {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.memory_mut(|memory| *memory = eframe::get_value(storage, "egui").expect("the saved memory"));
|
||||
ctx
|
||||
};
|
||||
|
||||
// The real 0.14/0.15 shape: the panel state under the old key inside the egui memory.
|
||||
let ctx = egui::Context::default();
|
||||
ctx.data_mut(|d| d.insert_persisted(egui::Id::unique("dock"), state(410.0)));
|
||||
let storage = save(&ctx);
|
||||
|
||||
let first = restore(&storage);
|
||||
photocraft_ui_egui::panels::migrate_panel_state(&first);
|
||||
draw(&first);
|
||||
let key = photocraft_ui_egui::panels::panel_state_id(&first, "dock");
|
||||
assert_eq!(egui::containers::panel::PanelState::load(&first, key).map(|p| p.size().x), Some(410.0));
|
||||
assert!(egui::containers::panel::PanelState::load(&first, egui::Id::unique("dock")).is_some(), "the 0.36 key is kept");
|
||||
// Resize in 0.37: the new key wins from now on.
|
||||
first.data_mut(|d| d.insert_persisted(key, state(500.0)));
|
||||
let storage = save(&first);
|
||||
|
||||
for restart in 0..2 {
|
||||
let next = restore(&storage);
|
||||
photocraft_ui_egui::panels::migrate_panel_state(&next);
|
||||
draw(&next);
|
||||
let key = photocraft_ui_egui::panels::panel_state_id(&next, "dock");
|
||||
let width = egui::containers::panel::PanelState::load(&next, key).map(|p| p.size().x).unwrap_or_default();
|
||||
assert!((width - 500.0).abs() < 0.5, "restart {restart}: the old 410 key must not win (got {width})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Schema-probe `ui.ron` shapes *reconstructed* from the documented 0.14/0.15/0.37 layouts,
|
||||
/// not recorded machine saves: 0.14 and 0.15 both store the flat window entry, which the
|
||||
/// first 0.37 launch rewrites; a 0.37 file is left alone. Keeping all three probes makes a
|
||||
/// future change to any migration rule fail here first. They do not prove eframe's real
|
||||
/// `Memory`/`PanelState` deserialization.
|
||||
#[test]
|
||||
fn the_ui_ron_schema_probe_fixtures_migrate() {
|
||||
for (name, fixture) in [("0.14", include_str!("../tests/fixtures/ui-0.14.ron")), ("0.15", include_str!("../tests/fixtures/ui-0.15.ron"))] {
|
||||
let text = super::ui_state::migrate_for_test(fixture).unwrap_or_else(|e| panic!("{name}: {e}")).unwrap_or_else(|| panic!("{name}: not rewritten"));
|
||||
assert!(text.contains("normal_geometry"), "{name}: the flat window entry is gone: {text}");
|
||||
assert!(!super::ui_state::saved_position_for_test(fixture), "{name}: a flat entry is not what 0.37 restores");
|
||||
}
|
||||
let old = include_str!("../tests/fixtures/ui-0.14.ron");
|
||||
assert!(super::ui_state::migrate_for_test(old).expect("migratable").expect("rewritten").contains("x:1100.0"), "the 0.14 size is preserved");
|
||||
let current = include_str!("../tests/fixtures/ui-0.15.ron");
|
||||
assert!(
|
||||
super::ui_state::migrate_for_test(current).expect("migratable").expect("rewritten").contains("maximized:true"),
|
||||
"0.15 maximized state survives"
|
||||
);
|
||||
// Already 0.37-shaped: no rewrite, and (with no saved position) the window centres.
|
||||
let current = include_str!("../tests/fixtures/ui-0.37.ron");
|
||||
assert_eq!(super::ui_state::migrate_for_test(current), Ok(None));
|
||||
assert!(!super::ui_state::saved_position_for_test(current));
|
||||
// And a 0.37 file with a restorable outer position is a saved position.
|
||||
let with_position = current.replace("outer_position_pixels:None", "outer_position_pixels:Some((x:2048.0,y:1228.0))");
|
||||
assert!(super::ui_state::saved_position_for_test(&with_position));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_opens_centred_at_its_default_size() {
|
||||
let o = super::native_options(super::CUSTOM_TITLEBAR);
|
||||
@@ -798,6 +949,91 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integrations_preferences_decide_the_control_port() {
|
||||
use photocraft_engine::prefs::Integrations;
|
||||
let off = Integrations { allow_agent_control: false, control_port: 0 };
|
||||
let on = Integrations { allow_agent_control: true, control_port: 0 };
|
||||
let preferred = Integrations { allow_agent_control: true, control_port: 7878 };
|
||||
|
||||
// Nothing asked for, nothing listening.
|
||||
assert_eq!(super::control_port_for(None, &on), (None, None));
|
||||
// --control wins over the preference.
|
||||
assert_eq!(super::control_port_for(Some(9000), &preferred), (Some(9000), None));
|
||||
// The preference opens the port when --control is absent.
|
||||
assert_eq!(super::control_port_for(None, &preferred), (Some(7878), None));
|
||||
|
||||
// Allow Agent Control off refuses both, and says so when --control asked for one
|
||||
// rather than ignoring the flag.
|
||||
assert_eq!(super::control_port_for(None, &off), (None, None));
|
||||
let (port, warning) = super::control_port_for(Some(9000), &off);
|
||||
assert_eq!(port, None);
|
||||
assert!(warning.is_some_and(|w| w.contains("Allow Agent Control") && w.contains("9000")), "the refusal names the port");
|
||||
let off_with_port = Integrations { allow_agent_control: false, control_port: 7878 };
|
||||
assert_eq!(super::control_port_for(None, &off_with_port), (None, None), "off beats a preferred port");
|
||||
|
||||
// A port a hand-edited file could hold, outside 1..=65535, is refused and named.
|
||||
let huge = Integrations { allow_agent_control: true, control_port: 70_000 };
|
||||
let (port, warning) = super::control_port_for(None, &huge);
|
||||
assert_eq!(port, None);
|
||||
assert!(warning.is_some_and(|w| w.contains("70000")), "the refusal names the value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integrations_fall_back_to_the_defaults_without_a_readable_file() {
|
||||
let dir = std::env::temp_dir().join(format!("pc-integrations-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("prefs.json");
|
||||
let default = photocraft_engine::prefs::Integrations::default();
|
||||
|
||||
assert_eq!(super::integrations(None), default, "no preferences file");
|
||||
std::fs::write(&file, "not json").unwrap();
|
||||
assert_eq!(super::integrations(Some(&file)), default, "an unreadable file");
|
||||
std::fs::write(&file, r#"{"integrations":{"allowAgentControl":false,"controlPort":7878}}"#).unwrap();
|
||||
let read = super::integrations(Some(&file));
|
||||
assert!(!read.allow_agent_control);
|
||||
assert_eq!(read.control_port, 7878);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The app loads preferences leniently (#6611): one wrong-typed value resets only itself. So
|
||||
/// a bad value elsewhere, or in the port, must not turn Allow Agent Control back on.
|
||||
#[test]
|
||||
fn a_bad_value_elsewhere_keeps_agent_control_off() {
|
||||
let dir = std::env::temp_dir().join(format!("pc-integrations-lenient-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("prefs.json");
|
||||
// What the Preferences dialog shows for the same file.
|
||||
let shown = |text: &str| {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.load_prefs_json(text).unwrap();
|
||||
session.prefs().integrations.clone()
|
||||
};
|
||||
let read = |text: &str| {
|
||||
std::fs::write(&file, text).unwrap();
|
||||
let read = super::integrations(Some(&file));
|
||||
assert_eq!(read, shown(text), "{text}");
|
||||
read
|
||||
};
|
||||
|
||||
let r = read(r#"{"interface":{"enableAnimations":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
|
||||
assert!(!r.allow_agent_control, "a bad value in another section");
|
||||
assert_eq!(r.control_port, 7878);
|
||||
let r = read(r#"{"integrations":{"allowAgentControl":false,"controlPort":"x"}}"#);
|
||||
assert!(!r.allow_agent_control, "a bad port");
|
||||
assert_eq!(r.control_port, 0, "the bad port alone takes its default");
|
||||
// A bad Allow Agent Control alone takes its default.
|
||||
let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#);
|
||||
assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878 });
|
||||
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#);
|
||||
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#);
|
||||
read(r#"{"integrations":"off"}"#);
|
||||
// serde reads a struct from a list too; the app does.
|
||||
assert!(!read(r#"{"integrations":[false]}"#).allow_agent_control, "a list");
|
||||
assert_eq!(read(r#"{"integrations":[false,7878]}"#).control_port, 7878);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// X11 startup notification and docks match a window to its launcher by `StartupWMClass`,
|
||||
/// so it has to be the class the window carries: the app id, on Wayland and X11 alike.
|
||||
#[test]
|
||||
|
||||
@@ -495,6 +495,7 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_hung_helper_is_stopped_and_big_replies_dont_block() {
|
||||
let _spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let t0 = std::time::Instant::now();
|
||||
let e = run_helper(std::process::Command::new("sleep").arg("30"), std::time::Duration::from_millis(300)).unwrap_err();
|
||||
assert!(e.contains("took longer than"), "{e}");
|
||||
|
||||
@@ -156,6 +156,18 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// Which file type's extensions belong on the name the dialog returned: the one it reported, or,
|
||||
/// when the dialog offered only one type, that one. It reports no pick then, and the name it was
|
||||
/// given is the stem (`services::dialog_file_name`), so a bare `Swatches` has to come back as
|
||||
/// `Swatches.aco`. `None` when the answer names no type this dialog offered.
|
||||
fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
|
||||
match picked {
|
||||
Some(i) if i < filters.len() => Some(i),
|
||||
None if filters.len() == 1 => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Save As on Linux: the portal's dialog, with the name given the extension of the file type
|
||||
/// picked. When that changes the name to one that already exists, the dialog opens again under
|
||||
/// the new name, so the portal asks before replacing it (it asked only about the typed name).
|
||||
@@ -163,10 +175,10 @@ pub fn save_as(conn: &zbus::blocking::Connection, mut req: SaveRequest) -> Resul
|
||||
loop {
|
||||
let Some(saved) = save_file(conn, &req)? else { return Ok(None) };
|
||||
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|(l, _)| l == label));
|
||||
// With one type offered there is nothing to pick, and a typed extension is the user's.
|
||||
let exts: &[String] = match picked {
|
||||
Some(i) if req.filters.len() > 1 => &req.filters[i].1,
|
||||
_ => &[],
|
||||
// A typed extension is the user's own: `with_chosen_type` keeps one it recognises.
|
||||
let exts: &[String] = match chosen_type(&req.filters, picked) {
|
||||
Some(i) => &req.filters[i].1,
|
||||
None => &[],
|
||||
};
|
||||
let path = crate::services::with_chosen_type(&saved.path, req.suggested.as_deref(), exts);
|
||||
if path == saved.path || !path.exists() {
|
||||
|
||||
@@ -36,17 +36,22 @@ fn mock_portal(script: Script) -> Option<(zbus::blocking::Connection, Seen, std:
|
||||
/// once the user is done with it (here after 300 ms).
|
||||
fn mock_portal_with(script: Script, own_paths: bool) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
|
||||
use std::io::BufRead;
|
||||
let spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut daemon =
|
||||
std::process::Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(std::process::Stdio::piped()).spawn().ok()?;
|
||||
drop(spawns);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
|
||||
let address = address.trim().to_string();
|
||||
let server = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap();
|
||||
let seen: Seen = Arc::default();
|
||||
let log = seen.clone();
|
||||
// A stream only gets the messages that arrive after it exists: made in the thread, it could
|
||||
// miss a `SaveFile` sent before the thread got going, and the call would wait forever.
|
||||
let messages = zbus::blocking::MessageIterator::from(&server);
|
||||
std::thread::spawn(move || {
|
||||
let mut script = script.into_iter();
|
||||
for msg in zbus::blocking::MessageIterator::from(&server) {
|
||||
for msg in messages {
|
||||
let Ok(msg) = msg else { break };
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("SaveFile") {
|
||||
@@ -230,3 +235,33 @@ fn a_single_file_type_keeps_the_typed_extension() {
|
||||
assert_eq!(save_as(&conn, req).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/Swatches.ase")));
|
||||
daemon.kill().ok();
|
||||
}
|
||||
|
||||
/// The same single type, with the name left as the dialog shows it: the bare stem comes back, and
|
||||
/// that one type gives it its extension instead of a file named `Swatches` being written.
|
||||
#[test]
|
||||
fn a_single_file_type_gives_the_bare_name_its_extension() {
|
||||
let typed: &'static str = "file:///tmp/photocraft-none/Swatches";
|
||||
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "Color Swatches")))]) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let req = SaveRequest { filters: vec![("Color Swatches".into(), vec!["aco".into()])], ..request("Swatches.aco") };
|
||||
assert_eq!(save_as(&conn, req).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/Swatches.aco")));
|
||||
daemon.kill().ok();
|
||||
}
|
||||
|
||||
/// Which type's extensions the returned name gets. The portal cases above need a `dbus-daemon`,
|
||||
/// so the rule itself is checked here too, which needs none.
|
||||
#[test]
|
||||
fn the_type_that_gives_the_extension_is_the_one_picked() {
|
||||
let one: Vec<Filter> = vec![("Color Swatches".into(), vec!["aco".into()])];
|
||||
// One type offered: the dialog reports no pick, and it was given the stem.
|
||||
assert_eq!(chosen_type(&one, None), Some(0));
|
||||
assert_eq!(chosen_type(&one, Some(0)), Some(0));
|
||||
let many: Vec<Filter> = request("test").filters;
|
||||
assert_eq!(chosen_type(&many, Some(1)), Some(1));
|
||||
// Several types and no pick: nothing to add, as before.
|
||||
assert_eq!(chosen_type(&many, None), None);
|
||||
// An answer naming a type this dialog never offered is not a pick either.
|
||||
assert_eq!(chosen_type(&many, Some(99)), None);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//! latency without a rebuild (#1343): `PHOTOCRAFT_PRESENT_MODE` (`fifo`, `autovsync`, or `novsync`,
|
||||
//! also spelled `immediate`, `mailbox` or `autonovsync`: no vsync, wgpu's Immediate → Mailbox → Fifo
|
||||
//! by what the driver offers) and `PHOTOCRAFT_FRAME_LATENCY` (`1` to `3`, frames the swap chain may
|
||||
//! queue). Unset, the platform default applies. A value that isn't one of these is ignored with a
|
||||
//! warning in the log, never a failed start; a mode the driver may not offer is never requested.
|
||||
//! queue). Unset, the platform default applies. A variable's value that isn't one of these is ignored
|
||||
//! with a warning in the log, never a failed start; the `--present-mode` and `--frame-latency` flags
|
||||
//! take the same values, and a bad one is a usage error (#7071). A mode the driver may not offer is
|
||||
//! never requested.
|
||||
//! The result is logged at start and shown in the stroke trace.
|
||||
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
@@ -16,45 +18,54 @@ pub struct Overrides {
|
||||
pub latency: Option<u32>,
|
||||
}
|
||||
|
||||
/// A `--present-mode` / `PHOTOCRAFT_PRESENT_MODE` value, or `None` when it isn't one.
|
||||
pub fn present_mode(v: &str) -> Option<PresentMode> {
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
// Only modes every surface takes: wgpu crashes on an explicit Immediate, Mailbox or
|
||||
// FifoRelaxed the driver doesn't offer (X11/NVIDIA has no Mailbox, #1343). Without
|
||||
// vsync, wgpu picks Immediate, else Mailbox, else Fifo.
|
||||
"fifo" | "vsync" => Some(PresentMode::Fifo),
|
||||
"autovsync" => Some(PresentMode::AutoVsync),
|
||||
"novsync" | "immediate" | "mailbox" | "autonovsync" => Some(PresentMode::AutoNoVsync),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `--frame-latency` / `PHOTOCRAFT_FRAME_LATENCY` value (1 to 3), or `None` when it isn't one.
|
||||
pub fn frame_latency(v: &str) -> Option<u32> {
|
||||
v.trim().parse().ok().filter(|n| (1..=3).contains(n))
|
||||
}
|
||||
|
||||
/// Parse the two variables' values. Returns the overrides and a warning per rejected value.
|
||||
pub fn parse(mode: Option<&str>, latency: Option<&str>) -> (Overrides, Vec<String>) {
|
||||
let mut warnings = Vec::new();
|
||||
let mode = mode.map(str::trim).filter(|v| !v.is_empty()).and_then(|v| {
|
||||
let m = match v.to_ascii_lowercase().as_str() {
|
||||
// Only modes every surface takes: wgpu crashes on an explicit Immediate, Mailbox or
|
||||
// FifoRelaxed the driver doesn't offer (X11/NVIDIA has no Mailbox, #1343). Without
|
||||
// vsync, wgpu picks Immediate, else Mailbox, else Fifo.
|
||||
"fifo" | "vsync" => PresentMode::Fifo,
|
||||
"autovsync" => PresentMode::AutoVsync,
|
||||
"novsync" | "immediate" | "mailbox" | "autonovsync" => PresentMode::AutoNoVsync,
|
||||
_ => {
|
||||
warnings.push(format!("PHOTOCRAFT_PRESENT_MODE={v:?} isn't fifo, autovsync or novsync (immediate, mailbox); ignored"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(m)
|
||||
});
|
||||
let latency = latency.map(str::trim).filter(|v| !v.is_empty()).and_then(|v| match v.parse::<u32>() {
|
||||
Ok(n @ 1..=3) => Some(n),
|
||||
_ => {
|
||||
warnings.push(format!("PHOTOCRAFT_FRAME_LATENCY={v:?} isn't 1, 2 or 3; ignored"));
|
||||
None
|
||||
let m = present_mode(v);
|
||||
if m.is_none() {
|
||||
warnings.push(format!("PHOTOCRAFT_PRESENT_MODE={v:?} isn't fifo, autovsync or novsync (immediate, mailbox); ignored"));
|
||||
}
|
||||
m
|
||||
});
|
||||
let latency = latency.map(str::trim).filter(|v| !v.is_empty()).and_then(|v| {
|
||||
let n = frame_latency(v);
|
||||
if n.is_none() {
|
||||
warnings.push(format!("PHOTOCRAFT_FRAME_LATENCY={v:?} isn't 1, 2 or 3; ignored"));
|
||||
}
|
||||
n
|
||||
});
|
||||
(Overrides { mode, latency }, warnings)
|
||||
}
|
||||
|
||||
impl Overrides {
|
||||
/// `--present-mode` / `--frame-latency` when given, else `PHOTOCRAFT_PRESENT_MODE` /
|
||||
/// `PHOTOCRAFT_FRAME_LATENCY`; rejected values are logged.
|
||||
pub fn from_args_or_env(mode: Option<&str>, latency: Option<&str>) -> Self {
|
||||
let env_mode = std::env::var("PHOTOCRAFT_PRESENT_MODE").ok();
|
||||
let env_latency = std::env::var("PHOTOCRAFT_FRAME_LATENCY").ok();
|
||||
let (o, warnings) = parse(mode.or(env_mode.as_deref()), latency.or(env_latency.as_deref()));
|
||||
/// `--present-mode` / `--frame-latency` when given (checked by the command line), else
|
||||
/// `PHOTOCRAFT_PRESENT_MODE` / `PHOTOCRAFT_FRAME_LATENCY`, whose rejected values are logged.
|
||||
pub fn from_args_or_env(mode: Option<PresentMode>, latency: Option<u32>) -> Self {
|
||||
let env = |given: bool, name: &str| if given { None } else { std::env::var(name).ok() };
|
||||
let (o, warnings) = parse(env(mode.is_some(), "PHOTOCRAFT_PRESENT_MODE").as_deref(), env(latency.is_some(), "PHOTOCRAFT_FRAME_LATENCY").as_deref());
|
||||
for w in warnings {
|
||||
log::warn!("{w}");
|
||||
}
|
||||
o
|
||||
Self { mode: mode.or(o.mode), latency: latency.or(o.latency) }
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied.
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Printing through the XDG Print portal (`org.freedesktop.portal.Print`): the system print
|
||||
//! dialog, which a sandboxed app can reach without a CUPS socket. The engine prints over IPP
|
||||
//! when it can reach a print server (`photocraft-ipp`); this is its fallback when it cannot, and
|
||||
//! the only route with `PHOTOCRAFT_PRINT_PORTAL=1` (`0` disables it). `PreparePrint` shows the
|
||||
//! dialog seeded with the job's copies and paper; `Print` hands it the PDF. Both answer through a
|
||||
//! `Request` object's `Response` signal, which this module waits for on its own thread so the
|
||||
//! window keeps painting while the dialog is open; the outcome goes to the log.
|
||||
//! https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Print.html
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use photocraft_engine::print_cmds::{PrintJob, Spooler};
|
||||
|
||||
/// The spooler to install on the session, unless `PHOTOCRAFT_PRINT_PORTAL=0`. The portal itself
|
||||
/// is looked up per job, so a missing one costs nothing at start-up.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn spooler() -> Option<Spooler> {
|
||||
let setting = std::env::var("PHOTOCRAFT_PRINT_PORTAL").ok();
|
||||
if setting.as_deref() == Some("0") {
|
||||
return None;
|
||||
}
|
||||
Some(Spooler { name: "portal", preferred: setting.as_deref() == Some("1"), run: std::sync::Arc::new(print) })
|
||||
}
|
||||
|
||||
/// Opens the system print dialog for the job and returns as soon as it is up.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn print(job: &PrintJob) -> Result<String, String> {
|
||||
let conn = zbus::blocking::connection::Builder::session()
|
||||
.and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build())
|
||||
.map_err(|e| format!("no session bus for the print portal ({e}); print to PDF instead"))?;
|
||||
let proxy = portal(&conn)?;
|
||||
let version: u32 = proxy.get_property("version").map_err(|e| format!("no print portal on this desktop ({e}); print to PDF instead"))?;
|
||||
// The document goes to a private temporary file (0600, created atomically by `tempfile`),
|
||||
// not a guessable name in a shared /tmp. The guard owns the file: it lives on the portal
|
||||
// thread until the dialog is done, and a failure to start that thread drops it here.
|
||||
let mut file = tempfile::Builder::new().prefix("photocraft-print-").suffix(".pdf").tempfile().map_err(|e| format!("cannot create the print file: {e}"))?;
|
||||
std::io::Write::write_all(&mut file, &job.pdf).map_err(|e| format!("cannot write the print file: {e}"))?;
|
||||
let (title, settings, page_setup) = (job.title.clone(), settings(job), page_setup(job));
|
||||
std::thread::Builder::new()
|
||||
.name("print-portal".into())
|
||||
.spawn(move || {
|
||||
let outcome = dialog(&conn, &title, &settings, &page_setup, file.path());
|
||||
drop(file);
|
||||
match outcome {
|
||||
Ok(what) => log::info!("print portal (v{version}): {what}"),
|
||||
Err(e) => log::warn!("print portal (v{version}): {e}"),
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("cannot start the print thread: {e}"))?;
|
||||
Ok("the system print dialog".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn portal(conn: &zbus::blocking::Connection) -> Result<zbus::blocking::Proxy<'static>, String> {
|
||||
zbus::blocking::Proxy::new(conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Print")
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// `PreparePrint` then `Print`, each waited for on its request's `Response` signal.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn dialog(
|
||||
conn: &zbus::blocking::Connection,
|
||||
title: &str,
|
||||
settings: &[(&'static str, Seed)],
|
||||
page_setup: &[(&'static str, Seed)],
|
||||
pdf: &std::path::Path,
|
||||
) -> Result<String, String> {
|
||||
use std::collections::HashMap;
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
type Dict<'a> = HashMap<&'a str, Value<'a>>;
|
||||
fn as_dict(pairs: &[(&'static str, Seed)]) -> Dict<'static> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let value = match v {
|
||||
Seed::Text(t) => Value::from(t.clone()),
|
||||
Seed::Mm(mm) => Value::from(*mm),
|
||||
};
|
||||
(*k, value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let proxy = portal(conn)?;
|
||||
let sender = conn.unique_name().map(|n| n.as_str().to_string()).ok_or("the bus connection has no name")?;
|
||||
let wait = |token: &str| -> Result<zbus::blocking::proxy::SignalIterator<'static>, String> {
|
||||
let path = request_path(&sender, token);
|
||||
let request = zbus::blocking::Proxy::new(conn, "org.freedesktop.portal.Desktop", path, "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
|
||||
request.receive_signal("Response").map_err(|e| e.to_string())
|
||||
};
|
||||
let response = |mut signals: zbus::blocking::proxy::SignalIterator<'static>| -> Result<HashMap<String, OwnedValue>, String> {
|
||||
let message = signals.next().ok_or("the print portal went away")?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = message.body().deserialize().map_err(|e| format!("odd portal reply: {e}"))?;
|
||||
match code {
|
||||
0 => Ok(results),
|
||||
1 => Err("cancelled in the print dialog".into()),
|
||||
_ => Err("the print dialog failed".into()),
|
||||
}
|
||||
};
|
||||
|
||||
let token = format!("photocraft_prepare_{}", nonce());
|
||||
let signals = wait(&token)?;
|
||||
let mut options: Dict<'_> = HashMap::new();
|
||||
options.insert("handle_token", Value::from(token.as_str()));
|
||||
let _: OwnedObjectPath =
|
||||
proxy.call("PreparePrint", &("", title, as_dict(settings), as_dict(page_setup), options)).map_err(|e| format!("PreparePrint failed: {e}"))?;
|
||||
let results = response(signals)?;
|
||||
let prepared = results.get("token").and_then(|v| u32::try_from(v.clone()).ok()).ok_or("the print dialog gave no token")?;
|
||||
|
||||
let file = std::fs::File::open(pdf).map_err(|e| format!("cannot reopen the print file: {e}"))?;
|
||||
let token = format!("photocraft_print_{}", nonce());
|
||||
let signals = wait(&token)?;
|
||||
let mut options: Dict<'_> = HashMap::new();
|
||||
options.insert("handle_token", Value::from(token.as_str()));
|
||||
options.insert("token", Value::from(prepared));
|
||||
let fd = zbus::zvariant::Fd::from(std::os::fd::AsFd::as_fd(&file));
|
||||
let _: OwnedObjectPath = proxy.call("Print", &("", title, fd, options)).map_err(|e| format!("Print failed: {e}"))?;
|
||||
response(signals)?;
|
||||
Ok("printed through the system print dialog".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn nonce() -> u64 {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0);
|
||||
t ^ N.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The request object the portal answers on: the sender's unique name without its colon and
|
||||
/// with dots as underscores, then the handle token.
|
||||
fn request_path(unique_name: &str, token: &str) -> String {
|
||||
format!("/org/freedesktop/portal/desktop/request/{}/{token}", unique_name.trim_start_matches(':').replace('.', "_"))
|
||||
}
|
||||
|
||||
/// A value seeded into the dialog: GtkPrintSettings are strings; a GtkPageSetup's sizes are
|
||||
/// doubles in millimetres (`gtk_paper_size_new_from_gvariant` ignores anything else).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
enum Seed {
|
||||
Text(String),
|
||||
Mm(f64),
|
||||
}
|
||||
|
||||
fn text(s: &str) -> Seed {
|
||||
Seed::Text(s.to_string())
|
||||
}
|
||||
|
||||
/// The standard paper sizes, as (PWG name, PPD name, width mm, height mm), portrait. GTK's
|
||||
/// print settings take the PWG name; its page setup finds the size by the PPD name.
|
||||
const PAPERS: [(&str, &str, f64, f64); 8] = [
|
||||
("na_letter", "Letter", 215.9, 279.4),
|
||||
("na_legal", "Legal", 215.9, 355.6),
|
||||
("na_ledger", "Ledger", 279.4, 431.8),
|
||||
("iso_a3", "A3", 297.0, 420.0),
|
||||
("iso_a4", "A4", 210.0, 297.0),
|
||||
("iso_a5", "A5", 148.0, 210.0),
|
||||
("na_index-4x6", "4x6", 101.6, 152.4),
|
||||
("na_5x7", "5x7", 127.0, 177.8),
|
||||
];
|
||||
|
||||
const MM_PER_PT: f64 = 25.4 / 72.0;
|
||||
|
||||
type Paper = (&'static str, &'static str, f64, f64);
|
||||
|
||||
/// The job's paper: its row in `PAPERS` when it is a standard size, and the portrait size in
|
||||
/// millimetres.
|
||||
fn paper(paper_pt: (f64, f64)) -> (Option<&'static Paper>, f64, f64) {
|
||||
let (w, h) = (paper_pt.0.min(paper_pt.1) * MM_PER_PT, paper_pt.0.max(paper_pt.1) * MM_PER_PT);
|
||||
let row = PAPERS.iter().find(|(_, _, pw, ph)| (pw - w).abs() < 1.0 && (ph - h).abs() < 1.0);
|
||||
(row, w, h)
|
||||
}
|
||||
|
||||
fn orientation(landscape: bool) -> Seed {
|
||||
text(if landscape { "landscape" } else { "portrait" })
|
||||
}
|
||||
|
||||
/// `PreparePrint`'s settings (GtkPrintSettings keys, string values).
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
fn settings_for(copies: u32, paper_pt: (f64, f64), landscape: bool) -> Vec<(&'static str, Seed)> {
|
||||
let (row, w, h) = paper(paper_pt);
|
||||
let mut v = vec![("n-copies", text(&copies.to_string())), ("orientation", orientation(landscape))];
|
||||
match row {
|
||||
Some((pwg, _, _, _)) => v.push(("paper-format", text(pwg))),
|
||||
None => v.extend([("paper-width", text(&format!("{w:.2}"))), ("paper-height", text(&format!("{h:.2}")))]),
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `PreparePrint`'s page setup (GtkPageSetup keys): the size in millimetres, found by its PPD
|
||||
/// name when it has one, else a custom size named by its dimensions.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
fn page_setup_for(paper_pt: (f64, f64), landscape: bool) -> Vec<(&'static str, Seed)> {
|
||||
let (row, w, h) = paper(paper_pt);
|
||||
let mut v = vec![("Orientation", orientation(landscape)), ("Width", Seed::Mm(w)), ("Height", Seed::Mm(h))];
|
||||
match row {
|
||||
Some((_, ppd, _, _)) => v.push(("PPDName", text(ppd))),
|
||||
None => v.push(("Name", text(&format!("custom_{w:.0}x{h:.0}mm")))),
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn settings(job: &PrintJob) -> Vec<(&'static str, Seed)> {
|
||||
settings_for(job.copies, job.paper, job.landscape)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn page_setup(job: &PrintJob) -> Vec<(&'static str, Seed)> {
|
||||
page_setup_for(job.paper, job.landscape)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_path_follows_the_portal_rule() {
|
||||
assert_eq!(request_path(":1.42", "photocraft_prepare_7"), "/org/freedesktop/portal/desktop/request/1_42/photocraft_prepare_7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_papers_get_their_pwg_and_ppd_names_and_custom_ones_their_size() {
|
||||
// A4 landscape as the engine lays it out: width > height, still A4.
|
||||
let s = settings_for(2, (841.89, 595.28), true);
|
||||
assert_eq!(s, vec![("n-copies", text("2")), ("orientation", text("landscape")), ("paper-format", text("iso_a4"))]);
|
||||
let p = page_setup_for((841.89, 595.28), true);
|
||||
assert_eq!(p[0], ("Orientation", text("landscape")));
|
||||
let Seed::Mm(w) = p[1].1 else { panic!("width is millimetres") };
|
||||
let Seed::Mm(h) = p[2].1 else { panic!("height is millimetres") };
|
||||
assert!((w - 210.0).abs() < 0.01 && (h - 297.0).abs() < 0.01, "{w} x {h}");
|
||||
assert_eq!(p[3], ("PPDName", text("A4")));
|
||||
assert_eq!(settings_for(1, (612.0, 792.0), false)[2], ("paper-format", text("na_letter")));
|
||||
assert_eq!(page_setup_for((612.0, 792.0), false)[3], ("PPDName", text("Letter")));
|
||||
assert_eq!(settings_for(1, (288.0, 432.0), false)[2], ("paper-format", text("na_index-4x6")));
|
||||
// 100 x 200 mm is nobody's standard.
|
||||
let custom = settings_for(1, (283.46, 566.93), false);
|
||||
assert_eq!(&custom[2..], &[("paper-width", text("100.00")), ("paper-height", text("200.00"))]);
|
||||
assert_eq!(page_setup_for((283.46, 566.93), false)[3], ("Name", text("custom_100x200mm")));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
//! Desktop colour capture starts only on an explicit UI request. No snapshots are written to
|
||||
//! disk, transmitted or retained after a pick. Wayland delegates to its permission portal.
|
||||
use photocraft_ui_egui::screen_picker::{Capture, MAX_PIXELS, Pending, ScreenImage, Service};
|
||||
use photocraft_ui_egui::screen_picker::{Capture, Pending, Service};
|
||||
// Only the platform capture backends (and the tests) build images and check sizes.
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
|
||||
use photocraft_ui_egui::screen_picker::MAX_PIXELS;
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
|
||||
use photocraft_ui_egui::screen_picker::ScreenImage;
|
||||
|
||||
pub fn service(cc: &eframe::CreationContext<'_>, wayland: bool) -> Option<Service> {
|
||||
if !cfg!(any(target_os = "linux", target_os = "macos", target_os = "windows")) {
|
||||
@@ -34,6 +39,7 @@ pub fn service(cc: &eframe::CreationContext<'_>, wayland: bool) -> Option<Servic
|
||||
}))
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
#[cfg_attr(not(any(target_os = "linux", target_os = "macos", target_os = "windows", test)), allow(dead_code))]
|
||||
struct Placement {
|
||||
index: usize,
|
||||
x: i32,
|
||||
@@ -41,9 +47,11 @@ struct Placement {
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
|
||||
fn find_monitor(placements: &[Placement], x: i32, y: i32, w: u32, h: u32) -> Option<usize> {
|
||||
placements.iter().find(|p| p.x == x && p.y == y && p.width == w && p.height == h).map(|p| p.index)
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
|
||||
fn count(width: usize, height: usize) -> Result<usize, String> {
|
||||
width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_PIXELS).ok_or_else(|| "Screen capture exceeds the 64 MP memory budget".into())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use photocraft_color::Color;
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::Size;
|
||||
use photocraft_format::{Autosaver, RecoveryEntry, SaveOptions, list_recovery};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
|
||||
@@ -0,0 +1,888 @@
|
||||
use super::*;
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_format::list_recovery;
|
||||
use photocraft_ui_egui::{PhotocraftApp, prefs_ui};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily
|
||||
/// (Open would fail with "No such file", Save would write a second, renamed file).
|
||||
#[test]
|
||||
fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() {
|
||||
#[cfg(unix)]
|
||||
let bad = {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png"))
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let bad = {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
let mut wide: Vec<u16> = "img".encode_utf16().collect();
|
||||
wide.push(0xD800);
|
||||
wide.extend(".png".encode_utf16());
|
||||
std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide))
|
||||
};
|
||||
let good = std::env::temp_dir().join("ok.png");
|
||||
let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo);
|
||||
assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name")));
|
||||
assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap()));
|
||||
let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths);
|
||||
assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again")));
|
||||
}
|
||||
|
||||
/// #6121: the file type picked in the save dialog gives the name its extension where the
|
||||
/// dialog left the one it opened with, and only there.
|
||||
#[test]
|
||||
fn the_picked_file_type_gives_the_name_its_extension() {
|
||||
let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"]));
|
||||
let opened = Some("Untitled-1.psd");
|
||||
let cases = [
|
||||
// PNG picked, the name as the dialog opened (or renamed, its extension kept).
|
||||
("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"),
|
||||
("/pics/art.psd", opened, &png, "/pics/art.png"),
|
||||
("/pics/ART.PSD", opened, &png, "/pics/ART.png"),
|
||||
// No extension: the type's. One PhotoCraft doesn't save is part of the name.
|
||||
("/pics/art", opened, &png, "/pics/art.png"),
|
||||
("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"),
|
||||
// Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says
|
||||
// (the PSD type untouched, or PNG picked and .jpg typed).
|
||||
("/pics/art.png", opened, &psd, "/pics/art.png"),
|
||||
("/pics/art.jpg", opened, &png, "/pics/art.jpg"),
|
||||
("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"),
|
||||
// Already the type's: kept, including its other extensions.
|
||||
("/pics/art.png", opened, &png, "/pics/art.png"),
|
||||
("/pics/art.PNG", opened, &png, "/pics/art.PNG"),
|
||||
("/pics/big.psb", opened, &psd, "/pics/big.psb"),
|
||||
// The dialog opened on a .pcraft: that is the extension the type replaces.
|
||||
("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"),
|
||||
("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"),
|
||||
];
|
||||
for (typed, opened, chosen, want) in cases {
|
||||
assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})");
|
||||
}
|
||||
// No type picked: the name as typed.
|
||||
assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd"));
|
||||
}
|
||||
|
||||
/// Regression using the real clipboard on an isolated Windows CI runner.
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
#[ignore = "requires exclusive use of the Windows clipboard"]
|
||||
fn busy_native_clipboard_preserves_copied_shape() {
|
||||
for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] {
|
||||
let mut native = native(None);
|
||||
let services =
|
||||
Services { clipboard_set_image: native.clipboard_set_image.take(), clipboard_get_image: native.clipboard_get_image.take(), ..Default::default() };
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
app.run("file.new", json!({"width": 80, "height": 60})).unwrap();
|
||||
app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap();
|
||||
app.run("edit.copy", json!({})).unwrap();
|
||||
assert!(app.session.clipboard.as_ref().unwrap().layers.is_some());
|
||||
assert!(app.services.clipboard_get_image.as_mut().unwrap()().unwrap().is_some(), "native export succeeded");
|
||||
app.run("file.new", json!({"width": 80, "height": 60})).unwrap();
|
||||
|
||||
// Another thread holds the OS clipboard open beyond arboard's bounded retry window.
|
||||
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel();
|
||||
let holder = std::thread::spawn(move || {
|
||||
// A non-null window distinguishes this owner from arboard's null-window opens.
|
||||
let guard = winsafe::HWND::GetDesktopWindow().OpenClipboard().unwrap();
|
||||
ready_tx.send(()).unwrap();
|
||||
release_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
|
||||
drop(guard);
|
||||
});
|
||||
ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
|
||||
let contention = arboard::Clipboard::new().unwrap().get_image().err();
|
||||
let first = app.run(id, json!({}));
|
||||
release_tx.send(()).unwrap();
|
||||
holder.join().unwrap();
|
||||
assert!(matches!(contention, Some(arboard::Error::ClipboardOccupied)), "diagnostic must actually occupy the clipboard: {contention:?}");
|
||||
eprintln!("paste while clipboard occupied: {first:?}");
|
||||
assert!(first.is_err(), "report contention rather than a successful no-op");
|
||||
assert!(
|
||||
app.session.clipboard.as_ref().is_some_and(|clip| clip.layers.is_some()),
|
||||
"a temporary OS read failure must not discard the copied editable shape"
|
||||
);
|
||||
app.run(id, json!({})).unwrap();
|
||||
let state = app.session.active().unwrap();
|
||||
assert!(
|
||||
matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_)),
|
||||
"retry keeps the shape editable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn open_filters_cover_uppercase_and_mixed_case_extensions() {
|
||||
// Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`.
|
||||
fn matches(glob: &str, text: &str) -> bool {
|
||||
let mut text = text.chars();
|
||||
let mut glob = glob.chars();
|
||||
while let Some(g) = glob.next() {
|
||||
let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() };
|
||||
if !text.next().is_some_and(|t| class.contains(t)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
text.next().is_none()
|
||||
}
|
||||
assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]);
|
||||
let globs = open_filter_extensions(OPEN_EXTS);
|
||||
assert_eq!(globs.len(), OPEN_EXTS.len());
|
||||
for (ext, glob) in OPEN_EXTS.iter().zip(&globs) {
|
||||
// Every casing: lower, UPPER, and alternating both ways (JpG, jPg).
|
||||
let alternating = |upper_first: bool| -> String {
|
||||
ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect()
|
||||
};
|
||||
for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] {
|
||||
assert!(matches(glob, &name), "{glob} should match .{name}");
|
||||
}
|
||||
assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}");
|
||||
}
|
||||
assert!(!globs.iter().any(|glob| matches(glob, "txt")));
|
||||
let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default();
|
||||
assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS));
|
||||
let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default();
|
||||
assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"]));
|
||||
assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD")));
|
||||
assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz")));
|
||||
}
|
||||
|
||||
/// #6337: after All Formats, every format File › Open reads has its own filter, and no filter
|
||||
/// offers an extension All Formats doesn't.
|
||||
#[test]
|
||||
fn every_open_format_has_its_own_filter() {
|
||||
let filters = open_filters();
|
||||
assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first");
|
||||
let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect();
|
||||
let total = named.len();
|
||||
named.sort_unstable();
|
||||
named.dedup();
|
||||
assert_eq!(named.len(), total, "an extension is listed under two filters");
|
||||
let mut all = OPEN_EXTS.to_vec();
|
||||
all.sort_unstable();
|
||||
assert_eq!(named, all, "the named filters cover All Formats exactly");
|
||||
let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect();
|
||||
for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] {
|
||||
assert!(names.contains(&name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
#[test]
|
||||
fn open_filters_keep_literal_extensions_on_windows_and_macos() {
|
||||
assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS);
|
||||
assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]);
|
||||
assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()]));
|
||||
assert_eq!(
|
||||
open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts),
|
||||
Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_services_provide_update_transport() {
|
||||
assert!(native(None).check_updates.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xwayland_command_matches_how_photocraft_was_installed() {
|
||||
// Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do.
|
||||
let flatpak = xwayland_command(Some("ai.storyteller.photocraft"), None, false);
|
||||
assert_eq!(flatpak.as_deref(), Some("flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft"));
|
||||
// AppImage: its own path, quoted for the shell (spaces, quotes).
|
||||
let appimage = xwayland_command(None, Some("/home/me/My Apps/it's.AppImage"), true);
|
||||
assert_eq!(appimage.as_deref(), Some(r"WAYLAND_DISPLAY= '/home/me/My Apps/it'\''s.AppImage'"));
|
||||
let bare = xwayland_command(None, Some("/opt/photocraft-0.3.0-linux-x86_64.AppImage"), true);
|
||||
assert_eq!(bare.as_deref(), Some("WAYLAND_DISPLAY= /opt/photocraft-0.3.0-linux-x86_64.AppImage"));
|
||||
// deb, rpm, AUR, tarball: the binary on the PATH.
|
||||
assert_eq!(xwayland_command(None, None, true).as_deref(), Some("WAYLAND_DISPLAY= photocraft"));
|
||||
assert_eq!(xwayland_command(Some(""), Some(""), true).as_deref(), Some("WAYLAND_DISPLAY= photocraft"));
|
||||
// No X server (XWayland disabled): nothing to suggest.
|
||||
assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None);
|
||||
}
|
||||
|
||||
/// Tests every native save dialog and records the suggested file name. Each name's file type must come first
|
||||
/// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`).
|
||||
#[test]
|
||||
fn every_save_dialog_leads_with_its_own_extension() {
|
||||
let asked: Rc<RefCell<Vec<String>>> = Rc::default();
|
||||
let log = asked.clone();
|
||||
// Record each save dialog's suggested name and cancel it, as the user would.
|
||||
let services = Services {
|
||||
file_dialog: Some(Box::new(move |request, _parent, reply| {
|
||||
if let FileDialogRequest::Save { suggested } = request {
|
||||
log.borrow_mut().push(suggested);
|
||||
}
|
||||
reply.send(None);
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
let ctx = egui::Context::default();
|
||||
// Dialogs are shown on the next frame: poll once so each is answered before the next asks.
|
||||
let invoke = |app: &mut PhotocraftApp, id: &str| {
|
||||
let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({}));
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
r
|
||||
};
|
||||
let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| {
|
||||
let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap();
|
||||
for (k, v) in fields.as_object().unwrap() {
|
||||
app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone());
|
||||
}
|
||||
let _ = photocraft_ui_egui::dialogs::confirm(app, d);
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
};
|
||||
new_doc(&mut app, "#ff0000");
|
||||
// Save As, Save a Copy.
|
||||
// Files in a format Save As can't write, like .dng, should suggest .psd instead.
|
||||
let _ = invoke(&mut app, "file.saveAs");
|
||||
for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] {
|
||||
app.session.active_mut().unwrap().path = Some(name.into());
|
||||
let _ = invoke(&mut app, "file.saveAs");
|
||||
}
|
||||
let _ = invoke(&mut app, "file.saveACopy");
|
||||
// Export As, Quick Export, Save for Web (with and without slices).
|
||||
for format in ["png", "jpg", "webp", "tif", "tga"] {
|
||||
dialog(&mut app, "file.export.exportAs", json!({"format": format}));
|
||||
}
|
||||
for format in ["png", "jpg", "gif", "webp"] {
|
||||
app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap();
|
||||
let _ = invoke(&mut app, "file.export.quickExportAsPng");
|
||||
}
|
||||
for format in ["gif", "png8", "png24", "jpeg", "webp", "wbmp"] {
|
||||
dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format}));
|
||||
}
|
||||
app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap();
|
||||
dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true}));
|
||||
// Measurement Log, Export/Import Presets.
|
||||
app.run("image.analysis.recordMeasurements", json!({})).unwrap();
|
||||
let _ = invoke(&mut app, "measurementLog.export");
|
||||
dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"}));
|
||||
let asked = asked.borrow();
|
||||
let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect();
|
||||
// The extension each save above should suggest, in order.
|
||||
let want = [
|
||||
"psd", // Save As untitled
|
||||
"pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng
|
||||
"psd", // Save a Copy
|
||||
"png jpg webp tif tga", // Export As
|
||||
"png jpg gif webp", // Quick Export
|
||||
"gif png png jpg webp wbmp html", // Save for Web: gif png8 png24 jpeg webp wbmp, then with slices
|
||||
"csv pcpresets", // Measurement Log, Export Presets
|
||||
]
|
||||
.join(" ");
|
||||
assert_eq!(exts, want.split(' ').collect::<Vec<_>>());
|
||||
for (name, ext) in asked.iter().zip(exts) {
|
||||
// The first type's first extension is the one Windows adds to the bare name.
|
||||
assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]);
|
||||
}
|
||||
assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default");
|
||||
}
|
||||
|
||||
/// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357).
|
||||
#[test]
|
||||
fn save_as_offers_only_writable_formats_including_ico() {
|
||||
// Layered formats, and PDF, are written by `photocraft-io`, not a codec.
|
||||
let layered = ["psd", "psb", "pcraft", "ora", "pdf"];
|
||||
for (name, exts) in SAVE_FILTERS {
|
||||
for ext in exts.iter().filter(|e| !layered.contains(e)) {
|
||||
let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format"));
|
||||
assert!(format.caps().write, "{name}: .{ext} can't be written");
|
||||
}
|
||||
}
|
||||
for ext in ["ico", "gif", "bmp", "dds", "pnm", "hdr", "dib", "jpeg", "tiff"] {
|
||||
assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered");
|
||||
}
|
||||
// The codec writes P5/P6/P7/PF from the image, never from the name, so Netpbm offers only the
|
||||
// neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data.
|
||||
let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts);
|
||||
assert_eq!(netpbm, Some(vec!["pnm".to_string()]));
|
||||
// The suggested name itself becomes .pnm, as macOS and rfd keep it (CodeRabbit on #9775).
|
||||
assert_eq!(netpbm_as_pnm("scans/image.pgm"), Path::new("scans/image.pnm").to_string_lossy());
|
||||
assert_eq!(netpbm_as_pnm("image.PFM"), "image.pnm");
|
||||
assert_eq!(netpbm_as_pnm("image.png"), "image.png");
|
||||
assert_eq!(netpbm_as_pnm("Untitled-1"), "Untitled-1");
|
||||
// Also when Save As starts from a subtype's name: no filter offers that subtype again.
|
||||
for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] {
|
||||
let filters = save_filters(name);
|
||||
assert_eq!(filters[0], ("Netpbm".to_string(), vec!["pnm".to_string()]), "{name}");
|
||||
let subtype = name.rsplit('.').next().unwrap_or_default();
|
||||
assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered");
|
||||
}
|
||||
// File Open lists readable Save As formats in their own type. Export-only formats must
|
||||
// stay absent from both Open filters rather than advertising an unavailable decoder.
|
||||
for (name, exts) in SAVE_FILTERS {
|
||||
for ext in exts.iter().filter(|e| **e != "pdf") {
|
||||
if photocraft_codecs::from_extension(ext).is_some_and(|format| !format.caps().read) {
|
||||
assert!(!OPEN_EXTS.contains(ext), "{name}: export-only .{ext} must not appear in All Formats");
|
||||
assert!(!OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: export-only .{ext} must not appear in an Open type");
|
||||
continue;
|
||||
}
|
||||
assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}");
|
||||
assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}");
|
||||
}
|
||||
}
|
||||
assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type");
|
||||
// What Save As writes there: an icon up to 256×256, and a clear error past that.
|
||||
let doc = |side: u32| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": side, "height": side})).unwrap();
|
||||
s.active().unwrap().doc.clone()
|
||||
};
|
||||
let opts = export_options(&photocraft_ui_egui::ExportSettings::default());
|
||||
let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap();
|
||||
assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header");
|
||||
// And what the Netpbm and Radiance rows write.
|
||||
let pnm = photocraft_io::export(&doc(4), "x.pnm", &opts).unwrap();
|
||||
assert_eq!(pnm.bytes[..2], *b"P6", "an RGB document saves as a binary pixmap");
|
||||
let hdr = photocraft_io::export(&doc(4), "x.hdr", &opts).unwrap();
|
||||
assert!(hdr.bytes.starts_with(b"#?RADIANCE"), "a Radiance header");
|
||||
let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string();
|
||||
assert!(err.contains("256"), "{err}");
|
||||
}
|
||||
|
||||
/// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to
|
||||
/// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked
|
||||
/// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's.
|
||||
#[test]
|
||||
fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() {
|
||||
for (suggested, name, first) in [
|
||||
("/pics/image.psd", "image", "psd"),
|
||||
("/pics/image.psb", "image", "psb"),
|
||||
("/pics/image.pcraft", "image", "pcraft"),
|
||||
("/pics/sky.fit", "sky", "fit"),
|
||||
("cat.jpeg", "cat", "jpeg"),
|
||||
("swatches.aco", "swatches", "aco"),
|
||||
] {
|
||||
assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}");
|
||||
assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}");
|
||||
// Elsewhere the dialogs keep the whole name (see `dialog_file_name`).
|
||||
let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned();
|
||||
assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}");
|
||||
}
|
||||
// Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no
|
||||
// extension, and a dotfile.
|
||||
for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] {
|
||||
assert_eq!(dialog_file_name(name, true).as_deref(), Some(name));
|
||||
}
|
||||
assert_eq!(dialog_file_name("", true), None);
|
||||
}
|
||||
|
||||
/// A name in another letter case reaches the same file where the file system ignores case
|
||||
/// (Windows, and macOS by default), and only there. Two files with the same contents are two.
|
||||
#[test]
|
||||
fn same_file_follows_the_file_system() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-same-file-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (cat, dog, upper) = (dir.join("CAT.psd"), dir.join("dog.psd"), dir.join("CAT.PSD"));
|
||||
std::fs::write(&cat, b"same").unwrap();
|
||||
std::fs::write(&dog, b"same").unwrap();
|
||||
assert!(same_file(&cat, &cat));
|
||||
assert!(!same_file(&cat, &dog));
|
||||
assert_eq!(same_file(&upper, &cat), upper.exists(), "the same file only where letter case is ignored");
|
||||
assert!(!same_file(&dir.join("missing.psd"), &cat));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A hard link is another entry in the folder, though it reaches the same file: a save to it
|
||||
/// replaces that entry and leaves the other name on the old file. Another spelling of a name,
|
||||
/// where letter case is ignored, is the same entry.
|
||||
#[test]
|
||||
fn a_hard_link_is_another_entry() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-same-entry-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("other")).unwrap();
|
||||
let (cat, bare, upper, other) = (dir.join("CAT.psd"), dir.join("CAT"), dir.join("CAT.PSD"), dir.join("other").join("CAT.psd"));
|
||||
std::fs::write(&cat, b"cat").unwrap();
|
||||
std::fs::hard_link(&cat, &bare).unwrap();
|
||||
std::fs::hard_link(&cat, &other).unwrap();
|
||||
// Where both names reach one file (one inode on Unix), the folder still lists both.
|
||||
let one_file = |_: &Path, _: &Path| true;
|
||||
assert!(!same_entry(&bare, &cat, one_file));
|
||||
assert!(!same_entry(&bare, &cat, same_file));
|
||||
assert!(!same_entry(&other, &cat, same_file), "another folder");
|
||||
assert!(same_entry(&cat, &cat, one_file));
|
||||
assert!(same_entry(&cat, &cat, same_file));
|
||||
if upper.exists() {
|
||||
assert!(same_entry(&upper, &cat, same_file), "one entry where letter case is ignored");
|
||||
} else {
|
||||
std::fs::hard_link(&cat, &upper).unwrap();
|
||||
assert!(!same_entry(&upper, &cat, same_file), "two entries where letter case tells names apart");
|
||||
}
|
||||
assert!(!same_entry(&dir.join("missing.psd"), &cat, same_file));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_on_waits_for_a_wake_from_another_thread() {
|
||||
let (tx, rx) = std::sync::mpsc::channel::<std::task::Waker>();
|
||||
let mut woken = false;
|
||||
let ready = std::future::poll_fn(move |cx| {
|
||||
if woken {
|
||||
return std::task::Poll::Ready(7);
|
||||
}
|
||||
woken = true;
|
||||
let _ = tx.send(cx.waker().clone());
|
||||
std::task::Poll::Pending
|
||||
});
|
||||
let waker = std::thread::spawn(move || rx.recv().unwrap().wake());
|
||||
assert_eq!(block_on(ready), 7);
|
||||
waker.join().unwrap();
|
||||
}
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
|
||||
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
|
||||
|
||||
/// One app launch with crash recovery in `dir` (dropping it is the crash: background writes
|
||||
/// already queued finish, nothing else runs).
|
||||
fn launch(dir: &Path) -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf())));
|
||||
let ctx = egui::Context::default();
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while app.session.has_jobs() && std::time::Instant::now() < deadline {
|
||||
photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
assert!(!app.session.has_jobs(), "recovery finished");
|
||||
app
|
||||
}
|
||||
|
||||
/// The first pixel of each open document, and whether it's unsaved.
|
||||
fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> {
|
||||
app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect()
|
||||
}
|
||||
|
||||
fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize {
|
||||
open_docs(app).iter().position(|(c, _)| *c == color).unwrap()
|
||||
}
|
||||
|
||||
fn new_doc(app: &mut PhotocraftApp, color: &str) {
|
||||
app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
|
||||
app.run("edit.fill", json!({"color": color})).unwrap();
|
||||
}
|
||||
|
||||
fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
prefs_ui::autosave_now(app);
|
||||
prefs_ui::tick(app, ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let ctx = egui::Context::default();
|
||||
// Launch 1: two unsaved documents are autosaved, then the app crashes.
|
||||
{
|
||||
let mut app = launch(&dir);
|
||||
new_doc(&mut app, "#ff0000");
|
||||
new_doc(&mut app, "#0000ff");
|
||||
autosave(&mut app, &ctx);
|
||||
}
|
||||
assert_eq!(list_recovery(&dir).len(), 2);
|
||||
// Launch 2 recovers both and crashes again before its first autosave (#444).
|
||||
{
|
||||
let mut app = launch(&dir);
|
||||
let mut docs = open_docs(&app);
|
||||
docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]));
|
||||
assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved");
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
}
|
||||
assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk");
|
||||
// Launch 3 has both again; autosaving unchanged documents adds nothing, a new document
|
||||
// (whose id may repeat one from an earlier launch) gets an entry of its own.
|
||||
{
|
||||
let mut app = launch(&dir);
|
||||
assert_eq!(app.session.documents().len(), 2);
|
||||
autosave(&mut app, &ctx);
|
||||
new_doc(&mut app, "#00ff00");
|
||||
autosave(&mut app, &ctx);
|
||||
}
|
||||
assert_eq!(list_recovery(&dir).len(), 3);
|
||||
// Launch 4: closing and saving recovered documents removes their entries, no duplicates.
|
||||
let mut app = launch(&dir);
|
||||
assert_eq!(app.session.documents().len(), 3);
|
||||
let red = index_of(&app, RED);
|
||||
app.run("file.close", json!({"document": red})).unwrap();
|
||||
// Saving marks the revision saved (the file write itself is the save service's job).
|
||||
assert!(app.session.set_active(index_of(&app, BLUE)));
|
||||
let st = app.session.active_mut().unwrap();
|
||||
st.saved_revision = st.revision;
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
let left = list_recovery(&dir);
|
||||
assert_eq!(left.len(), 1);
|
||||
assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN));
|
||||
let green = index_of(&app, GREEN);
|
||||
app.run("file.close", json!({"document": green})).unwrap();
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
assert!(list_recovery(&dir).is_empty());
|
||||
drop(app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_background_autosave_is_reported_and_retried_without_another_edit() {
|
||||
let dir = temp("autosave-retry");
|
||||
let recovery = dir.join("Recovery");
|
||||
// A regular file prevents creation of the recovery bundle directory.
|
||||
std::fs::write(&recovery, b"blocked").unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = launch(&recovery);
|
||||
new_doc(&mut app, "#ff0000");
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0");
|
||||
autosave(&mut app, &ctx);
|
||||
|
||||
let mut failed = false;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while std::time::Instant::now() < deadline {
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
if app.ui.status.starts_with("Autosave failed:") {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(failed, "background write failures must reach the UI");
|
||||
assert!(app.ui.status_error);
|
||||
assert!(list_recovery(&recovery).is_empty());
|
||||
|
||||
// No edit occurs: retrying this very same revision must still work.
|
||||
std::fs::remove_file(&recovery).unwrap();
|
||||
std::fs::create_dir(&recovery).unwrap();
|
||||
autosave(&mut app, &ctx);
|
||||
// The worker commits the bundle's manifest before it publishes the sidecar, and
|
||||
// `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so
|
||||
// the first non-empty listing can come from the middle of the write. Wait for the write
|
||||
// to finish: the entry then carries the sidecar's revision.
|
||||
let mut recovered = Vec::new();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while std::time::Instant::now() < deadline {
|
||||
prefs_ui::tick(&mut app, &ctx);
|
||||
recovered = list_recovery(&recovery);
|
||||
if recovered.iter().any(|e| e.info.revision == revision) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!(recovered.len(), 1, "unchanged revision should retry after failure");
|
||||
assert_eq!(recovered[0].info.revision, revision);
|
||||
let restored = photocraft_format::recover(&recovered[0]).unwrap();
|
||||
assert_eq!(photocraft_compose::flatten(&restored).px.first().copied(), Some(RED));
|
||||
drop(app);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("photocraft-services-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn red_png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap();
|
||||
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A 1×1 uncompressed 32-bit TGA (TGA has no magic number).
|
||||
fn tga_1x1() -> Vec<u8> {
|
||||
let mut b = vec![0u8, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 32, 8];
|
||||
b.extend_from_slice(&[0, 0, 255, 255]); // BGRA red
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_image_file_pastes_its_pixels() {
|
||||
let dir = temp("png");
|
||||
let png = dir.join("red.png");
|
||||
std::fs::write(&png, red_png(3, 2)).unwrap();
|
||||
let (w, h, px) = image_from_files(&[png]).unwrap();
|
||||
assert_eq!((w, h), (3, 2));
|
||||
assert_eq!(px, [255u8, 0, 0, 255].repeat(6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_from_a_uri_list_is_ignored() {
|
||||
// arboard splits text/uri-list on LF, so GNOME Files' CRLF list leaves a '\r' behind.
|
||||
let dir = temp("crlf");
|
||||
let png = dir.join("red image.png");
|
||||
std::fs::write(&png, red_png(2, 2)).unwrap();
|
||||
let with_cr = PathBuf::from(format!("{}\r", png.display()));
|
||||
assert_eq!(image_from_files(&[with_cr]).map(|(w, h, _)| (w, h)), Some((2, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_images_are_skipped_for_the_first_image() {
|
||||
let dir = temp("mixed");
|
||||
let (txt, png) = (dir.join("notes.txt"), dir.join("red.png"));
|
||||
std::fs::write(&txt, b"not an image").unwrap();
|
||||
std::fs::write(&png, red_png(4, 1)).unwrap();
|
||||
let missing = dir.join("gone.png");
|
||||
assert_eq!(image_from_files(&[missing.clone(), txt.clone(), dir.clone(), png]).map(|(w, h, _)| (w, h)), Some((4, 1)));
|
||||
assert!(image_from_files(&[missing, txt, dir]).is_none());
|
||||
assert!(image_from_files(&[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_image_is_skipped_not_a_panic() {
|
||||
let dir = temp("damaged");
|
||||
let bad = dir.join("cut.png");
|
||||
std::fs::write(&bad, &red_png(8, 8)[..20]).unwrap();
|
||||
assert!(image_from_files(&[bad]).is_none());
|
||||
}
|
||||
|
||||
fn encoded(format: photocraft_codecs::Format, w: u32, h: u32) -> Vec<u8> {
|
||||
let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap();
|
||||
photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_png_clipboard_images_paste() {
|
||||
// #2546: a screenshot tool that offers only image/bmp or image/jpeg pasted nothing.
|
||||
let bmp = encoded(photocraft_codecs::Format::Bmp, 3, 2);
|
||||
let offers = vec!["text/plain".to_string(), "image/bmp".to_string()];
|
||||
let mut asked = Vec::new();
|
||||
let got = image_from_offers(&offers, |mime| {
|
||||
asked.push(mime.to_string());
|
||||
Some(bmp.clone())
|
||||
});
|
||||
assert_eq!(got, Some((3, 2, [255u8, 0, 0, 255].repeat(6))));
|
||||
assert_eq!(asked, ["image/bmp"], "text offers are never fetched");
|
||||
|
||||
let jpeg = encoded(photocraft_codecs::Format::Jpeg, 16, 8);
|
||||
let offers = vec!["image/jpeg".to_string()];
|
||||
assert_eq!(image_from_offers(&offers, |_| Some(jpeg.clone())).map(|(w, h, _)| (w, h)), Some((16, 8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undecodable_clipboard_offers_fall_through_to_the_next() {
|
||||
let bmp = encoded(photocraft_codecs::Format::Bmp, 2, 2);
|
||||
let cut = encoded(photocraft_codecs::Format::Png, 8, 8)[..20].to_vec();
|
||||
let offers: Vec<String> = ["image/webp", "image/png", "image/x-tga", "image/bmp"].map(String::from).to_vec();
|
||||
let got = image_from_offers(&offers, |mime| match mime {
|
||||
"image/webp" => None,
|
||||
"image/png" => Some(cut.clone()),
|
||||
"image/x-tga" => Some(b"not an image".to_vec()),
|
||||
_ => Some(bmp.clone()),
|
||||
});
|
||||
assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2)));
|
||||
assert!(image_from_offers(&offers[..3], |_| Some(cut.clone())).is_none());
|
||||
assert!(image_from_offers(&[], |_| Some(bmp.clone())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_tga_is_trusted_only_by_its_type() {
|
||||
assert_eq!(image_from_offers(&["image/x-tga".to_string()], |_| Some(tga_1x1())), Some((1, 1, vec![255, 0, 0, 255])));
|
||||
assert!(image_from_offers(&["image/x-unknown".to_string()], |_| Some(tga_1x1())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tga_is_trusted_only_with_its_extension() {
|
||||
let dir = temp("tga");
|
||||
let (tga, bin) = (dir.join("red.tga"), dir.join("red.bin"));
|
||||
std::fs::write(&tga, tga_1x1()).unwrap();
|
||||
std::fs::write(&bin, tga_1x1()).unwrap();
|
||||
assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255])));
|
||||
assert!(image_from_files(&[bin]).is_none());
|
||||
}
|
||||
|
||||
/// A 121 × 81 white rectangle with a 1-unit black stroke, written as markup the way a vector
|
||||
/// app's Copy puts it on the clipboard as text.
|
||||
const COPIED_RECTANGLE: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="121" height="81" viewBox="0 0 121 81">
|
||||
<g><path d="M0.5 0.5 L120.5 0.5 L120.5 80.5 L0.5 80.5 Z" fill="#ffffff" stroke="#000000"/></g>
|
||||
</svg>
|
||||
"##;
|
||||
|
||||
/// A 40 × 20 drawing whose left half is a red square; the right half has no art.
|
||||
const HALF_RED: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="20" height="20" fill="#ff0000"/></svg>"##;
|
||||
|
||||
/// The clipboard as `clipboard_image` reads it when it holds only `text`.
|
||||
fn from_text(text: &str) -> Option<(u32, u32, Vec<u8>)> {
|
||||
clipboard_image(&mut (), |_| Ok(None), |_| Ok(None), |_| Ok(Some(text.to_string()))).expect("no read fails")
|
||||
}
|
||||
|
||||
fn pixel(img: &(u32, u32, Vec<u8>), x: u32, y: u32) -> [u8; 4] {
|
||||
let at = ((y * img.0 + x) * 4) as usize;
|
||||
img.2[at..at + 4].try_into().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_markup_copied_as_text_pastes_its_pixels() {
|
||||
let img = from_text(COPIED_RECTANGLE).expect("the drawing's pixels");
|
||||
assert_eq!((img.0, img.1, img.2.len()), (121, 81, 121 * 81 * 4), "one pixel per SVG unit");
|
||||
assert_eq!(pixel(&img, 60, 40), [255, 255, 255, 255], "the white fill");
|
||||
for (x, y) in [(0, 40), (120, 40), (60, 0), (60, 80)] {
|
||||
let [r, g, b, a] = pixel(&img, x, y);
|
||||
assert!(a == 255 && r < 8 && g < 8 && b < 8, "the black stroke at {x},{y}: {:?}", [r, g, b, a]);
|
||||
}
|
||||
let img = from_text(HALF_RED).expect("the drawing's pixels");
|
||||
assert_eq!((img.0, img.1), (40, 20));
|
||||
assert_eq!(pixel(&img, 5, 10), [255, 0, 0, 255]);
|
||||
assert_eq!(pixel(&img, 30, 10), [0, 0, 0, 0], "transparent where there is no art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_is_not_a_drawing_pastes_nothing() {
|
||||
for text in ["", "hello", "<p>not a drawing</p>", "<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"] {
|
||||
assert!(from_text(text).is_none(), "{text:?}");
|
||||
}
|
||||
// Markup that doesn't parse, and markup past the read limit, paste nothing either.
|
||||
assert!(from_text("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect").is_none());
|
||||
assert!(from_text("<svg width=\"8\" height=\"8\"><g></svg>").is_none());
|
||||
let mut huge = String::from("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\">");
|
||||
huge.push_str(&" ".repeat(usize::try_from(MAX_CLIPBOARD_SVG_BYTES).unwrap()));
|
||||
huge.push_str("</svg>");
|
||||
assert!(from_text(&huge).is_none(), "markup past the limit isn't parsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_clipboard_text_accepts_a_long_xml_preamble() {
|
||||
let padding = "x".repeat(8192);
|
||||
for prefix in [format!("<!--{padding}-->"), format!("<?xml version=\"1.0\"?>\n<!--{padding}-->"), format!("<?drawing {padding}?>")] {
|
||||
let text = format!("{prefix}{HALF_RED}");
|
||||
let img = from_text(&text).expect("SVG after the XML preamble");
|
||||
assert_eq!((img.0, img.1), (40, 20));
|
||||
assert_eq!(pixel(&img, 5, 10), [255, 0, 0, 255]);
|
||||
assert_eq!(pixel(&img, 30, 10), [0, 0, 0, 0]);
|
||||
}
|
||||
assert!(from_text(&format!("<!--{padding}<svg/>--><not-svg/>")).is_none());
|
||||
assert!(from_text(&format!("<!--{padding}--><svg><g></svg>")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawing_past_the_pixel_limit_pastes_scaled_down() {
|
||||
let wide = r##"<svg xmlns="http://www.w3.org/2000/svg" width="20000" height="10000"><rect width="20000" height="10000" fill="#0000ff"/></svg>"##;
|
||||
let img = from_text(wide).expect("scaled down, not dropped");
|
||||
let pixels = u64::from(img.0) * u64::from(img.1);
|
||||
assert!(pixels <= 24_000_000 && pixels > 12_000_000, "{} × {}", img.0, img.1);
|
||||
assert!(img.0.abs_diff(img.1 * 2) <= 2, "the proportions are kept: {} × {}", img.0, img.1);
|
||||
assert_eq!(pixel(&img, img.0 / 2, img.1 / 2), [0, 0, 255, 255]);
|
||||
}
|
||||
|
||||
/// Copied files and an image come before SVG text, which is read only when neither is there.
|
||||
#[test]
|
||||
fn copied_files_and_images_come_before_svg_text() {
|
||||
let dir = temp("svg-order");
|
||||
let png = dir.join("red.png");
|
||||
std::fs::write(&png, red_png(3, 2)).unwrap();
|
||||
let blue = (2, 2, [0u8, 0, 255, 255].repeat(4));
|
||||
let mut text_read = false;
|
||||
let svg_text = |read: &mut bool| {
|
||||
*read = true;
|
||||
Ok(Some(COPIED_RECTANGLE.to_string()))
|
||||
};
|
||||
let got = clipboard_image(&mut text_read, |_| Ok(Some(vec![png.clone()])), |_| Ok(Some(blue.clone())), svg_text);
|
||||
assert_eq!(got.unwrap().map(|(w, h, _)| (w, h)), Some((3, 2)), "the copied file");
|
||||
let got = clipboard_image(&mut text_read, |_| Ok(None), |_| Ok(Some(blue.clone())), svg_text);
|
||||
assert_eq!(got.unwrap().map(|(w, h, _)| (w, h)), Some((2, 2)), "the image, not the SVG text");
|
||||
assert!(!text_read, "the text isn't read while there is a file or an image");
|
||||
// A copied file that isn't an image (an .svg) falls through to the image, then the text.
|
||||
let svg = dir.join("drawing.svg");
|
||||
std::fs::write(&svg, COPIED_RECTANGLE).unwrap();
|
||||
let got = clipboard_image(&mut (), |_| Ok(Some(vec![svg.clone()])), |_| Ok(None), |_| Ok(Some(COPIED_RECTANGLE.to_string())));
|
||||
assert_eq!(got.unwrap().map(|(w, h, _)| (w, h)), Some((121, 81)));
|
||||
}
|
||||
|
||||
/// A failed read, such as one of a busy clipboard, is the paste's error: the reads after it,
|
||||
/// the SVG text included, don't run.
|
||||
#[test]
|
||||
fn a_failed_clipboard_read_is_an_error_and_the_text_is_not_read() {
|
||||
fn busy<T>() -> Result<T, String> {
|
||||
Err("the clipboard is busy".to_string())
|
||||
}
|
||||
let mut text_read = false;
|
||||
let svg_text = |read: &mut bool| {
|
||||
*read = true;
|
||||
Ok(Some(COPIED_RECTANGLE.to_string()))
|
||||
};
|
||||
let got = clipboard_image(&mut text_read, |_| busy(), |_| Ok(None), svg_text);
|
||||
assert_eq!(got, Err("the clipboard is busy".to_string()), "the file list's error");
|
||||
let got = clipboard_image(&mut text_read, |_| Ok(None), |_| busy(), svg_text);
|
||||
assert_eq!(got, Err("the clipboard is busy".to_string()), "the image's error");
|
||||
assert!(!text_read, "the text isn't read after a failed read");
|
||||
let got = clipboard_image(&mut (), |_| Ok(None), |_| Ok(None), |_| busy());
|
||||
assert_eq!(got, Err("the clipboard is busy".to_string()), "the text's error");
|
||||
}
|
||||
|
||||
/// Only a clipboard with nothing in the format asked for reads as nothing to paste. A read
|
||||
/// that fails in any other way, such as a broken pipe on Wayland, is the paste's error, for
|
||||
/// the copied files and the text alike. Text that isn't UTF-8 reads as no SVG markup.
|
||||
#[test]
|
||||
fn only_missing_content_reads_as_nothing_to_paste() {
|
||||
use arboard::Error;
|
||||
let failures = || [Error::ClipboardOccupied, Error::ClipboardNotSupported, Error::Unknown { description: "broken pipe".to_string() }];
|
||||
assert_eq!(clipboard_read(Ok::<_, Error>(vec![PathBuf::from("a.png")])), Ok(Some(vec![PathBuf::from("a.png")])));
|
||||
assert_eq!(clipboard_read::<Vec<PathBuf>>(Err(Error::ContentNotAvailable)), Ok(None));
|
||||
for error in failures().into_iter().chain([Error::ConversionFailure]) {
|
||||
let message = error.to_string();
|
||||
assert_eq!(clipboard_read::<Vec<PathBuf>>(Err(error)), Err(message.clone()), "{message}");
|
||||
}
|
||||
assert_eq!(clipboard_text(Ok("words".to_string())), Ok(Some("words".to_string())));
|
||||
assert_eq!(clipboard_text(Err(Error::ContentNotAvailable)), Ok(None));
|
||||
assert_eq!(clipboard_text(Err(Error::ConversionFailure)), Ok(None), "text that isn't UTF-8");
|
||||
for error in failures() {
|
||||
let message = error.to_string();
|
||||
assert_eq!(clipboard_text(Err(error)), Err(message.clone()), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the
|
||||
/// drawing's art; other text is still a quiet "nothing to paste".
|
||||
#[test]
|
||||
fn paste_turns_svg_text_on_the_clipboard_into_a_layer() {
|
||||
let text: Rc<RefCell<String>> = Rc::new(RefCell::new(HALF_RED.to_string()));
|
||||
let clip = text.clone();
|
||||
let services = Services {
|
||||
clipboard_get_image: Some(Box::new(move || clipboard_image(&mut (), |_| Ok(None), |_| Ok(None), |_| Ok(Some(clip.borrow().clone()))))),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
let ctx = egui::Context::default();
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let layers = app.session.active().unwrap().doc.layers.len();
|
||||
let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap();
|
||||
assert_ne!(r["pasted"], json!(false), "{r}");
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.layers.len(), layers + 1);
|
||||
let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
|
||||
let bounds = surface.content_bounds();
|
||||
assert_eq!((bounds.width(), bounds.height()), (20, 20), "the red half; the transparent half adds nothing");
|
||||
*text.borrow_mut() = "just words".to_string();
|
||||
let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap();
|
||||
assert_eq!(r["pasted"], json!(false));
|
||||
assert_eq!(app.ui.status, "Nothing to paste: the clipboard holds no image");
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1);
|
||||
}
|
||||
|
||||
/// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is
|
||||
/// the paste's error in the status bar, not a crash: the document stays and the next paste
|
||||
/// works. The same for a panic while writing it.
|
||||
#[test]
|
||||
fn a_panicking_clipboard_read_is_reported_not_a_crash() {
|
||||
let panics = Rc::new(Cell::new(true));
|
||||
let p = panics.clone();
|
||||
let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) });
|
||||
let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() });
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
let layers = app.session.active().unwrap().doc.layers.len();
|
||||
|
||||
let error = app.run("edit.paste", json!({})).unwrap_err();
|
||||
assert!(error.contains("Paste failed"), "{error}");
|
||||
assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status);
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged");
|
||||
|
||||
panics.set(false);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works");
|
||||
|
||||
let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug"));
|
||||
assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed"));
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
//! copy of the program.
|
||||
//!
|
||||
//! The first launch takes an exclusive OS lock on `instance.lock` in the settings directory (the OS
|
||||
//! drops it when the process ends, crash included), listens on a loopback port and writes the port
|
||||
//! plus a fresh 256-bit token to `instance.json`. A later launch that finds the lock taken sends its
|
||||
//! drops it when the process ends, crash included), listens on a loopback port (inside a Flatpak
|
||||
//! sandbox, on a Unix socket: see [`transport`]) and writes where it listens plus a fresh 256-bit
|
||||
//! token to `instance.json`. A later launch that finds the lock taken sends its
|
||||
//! paths there; the primary queues them for the UI as [`OsEvent::Open`], which opens each one and
|
||||
//! brings the window forward. Explorer starts one process per file when several are opened at once;
|
||||
//! the lock decides the race, so they all end up as tabs in one window.
|
||||
@@ -26,7 +27,11 @@
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::Path;
|
||||
#[cfg(unix)]
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{SyncSender, sync_channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
@@ -36,8 +41,13 @@ use photocraft_automation::security::{LineRead, generate_token, read_bounded_lin
|
||||
use photocraft_ui_egui::{OsEvent, OsEventsFn};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::launch_args::PerProcess;
|
||||
|
||||
const LOCK_FILE: &str = "instance.lock";
|
||||
const INFO_FILE: &str = "instance.json";
|
||||
/// The Unix socket a sandboxed primary listens on, in the app's runtime directory.
|
||||
#[cfg(unix)]
|
||||
const SOCKET_FILE: &str = "instance.sock";
|
||||
/// More paths than this in one request is not a file manager.
|
||||
const MAX_PATHS: usize = 4096;
|
||||
/// Launches served at once; a stalled client holds only its own slot, never the next launch.
|
||||
@@ -59,6 +69,45 @@ pub struct Timing {
|
||||
/// Generous enough for a primary that is still opening its window.
|
||||
pub const TIMING: Timing = Timing { handoff: Duration::from_secs(10), ack: Duration::from_secs(8), request: Duration::from_secs(5) };
|
||||
|
||||
/// How the primary listens for later launches.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Transport {
|
||||
/// A loopback port (the default): private to the machine, reachable by every process on it.
|
||||
Loopback,
|
||||
/// A Unix socket at this path. Inside a Flatpak sandbox a loopback port is not enough: each
|
||||
/// `flatpak run` has its own network namespace, so the second sandbox's `127.0.0.1` never
|
||||
/// reaches the first (#1540). `$XDG_RUNTIME_DIR/app/<app id>/` is the same directory in every
|
||||
/// sandbox of the app, and the user's alone (0700).
|
||||
#[cfg(unix)]
|
||||
Socket(PathBuf),
|
||||
}
|
||||
|
||||
/// The transport for this process: a Unix socket when running inside a Flatpak (`FLATPAK_ID` is
|
||||
/// set and `XDG_RUNTIME_DIR` names the runtime directory), else a loopback port.
|
||||
pub fn transport() -> Transport {
|
||||
#[cfg(unix)]
|
||||
if let Some(path) = sandbox_socket(std::env::var_os("FLATPAK_ID").as_deref(), std::env::var_os("XDG_RUNTIME_DIR").as_deref()) {
|
||||
return Transport::Socket(path);
|
||||
}
|
||||
Transport::Loopback
|
||||
}
|
||||
|
||||
/// `$XDG_RUNTIME_DIR/app/<FLATPAK_ID>/instance.sock`, when both are set.
|
||||
#[cfg(unix)]
|
||||
fn sandbox_socket(flatpak_id: Option<&std::ffi::OsStr>, runtime_dir: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
|
||||
let id = flatpak_id.filter(|v| !v.is_empty())?;
|
||||
let dir = runtime_dir.filter(|v| !v.is_empty())?;
|
||||
Some(Path::new(dir).join("app").join(id).join(SOCKET_FILE))
|
||||
}
|
||||
|
||||
/// Where the running primary listens, as `instance.json` records it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Endpoint {
|
||||
Port(u16),
|
||||
#[cfg(unix)]
|
||||
Socket(PathBuf),
|
||||
}
|
||||
|
||||
/// Outcome of [`claim`].
|
||||
pub enum Launch {
|
||||
/// This process is the running instance; keep [`Primary`] alive and attach it to the app.
|
||||
@@ -82,8 +131,54 @@ pub struct LaunchContext<'a> {
|
||||
pub control: bool,
|
||||
/// Paths that aren't valid Unicode: this launch reports them.
|
||||
pub unreadable_paths: bool,
|
||||
/// Options that only apply to the process they're given to (`--safe-gpu`, …).
|
||||
pub launch_options: &'a [&'static str],
|
||||
/// Options that only apply to the process they're given to (`--safe-gpu`, …), including the
|
||||
/// ones this launch's environment sets (see [`env_launch_options`]).
|
||||
pub launch_options: &'a [PerProcess],
|
||||
}
|
||||
|
||||
/// Variables documented as the equivalent of a per-launch flag, each with the option it stands for
|
||||
/// (`PHOTOCRAFT_PRESENT_MODE` is `--present-mode`) and the rule that says whether its value asks for
|
||||
/// that option at all. Setting one asks for the same thing as giving the flag, so it belongs to this
|
||||
/// process alone. These are read where they take effect, not by the command line; the variables
|
||||
/// that are a flag's fallback (`PHOTOCRAFT_IN_WINDOW_MENUS`, the automation roots) are counted by
|
||||
/// [`crate::launch_args::parse`], as clap reads them.
|
||||
const ENV_LAUNCH_OPTIONS: [(&str, PerProcess, ValueRule); 3] = [
|
||||
("PHOTOCRAFT_PRESENT_MODE", PerProcess::PresentMode, present_mode_is_on),
|
||||
("PHOTOCRAFT_FRAME_LATENCY", PerProcess::FrameLatency, frame_latency_is_on),
|
||||
("PHOTOCRAFT_STROKE_TRACE", PerProcess::StrokeTrace, stroke_trace_is_on),
|
||||
];
|
||||
|
||||
/// Whether a variable's value asks this launch for its own option. Each rule matches how that
|
||||
/// variable is read where it takes effect, so a value ignored there keeps no process here either.
|
||||
type ValueRule = fn(&str) -> bool;
|
||||
|
||||
/// A value `presentation::parse` accepts, handed over as written: it trims, treats empty as unset and
|
||||
/// warns and ignores anything it does not recognise, so an unrecognised `PHOTOCRAFT_PRESENT_MODE`
|
||||
/// changes nothing there and so needs no process of its own here.
|
||||
fn present_mode_is_on(value: &str) -> bool {
|
||||
crate::presentation::parse(Some(value), None).0.mode.is_some()
|
||||
}
|
||||
|
||||
/// [`present_mode_is_on`] for `PHOTOCRAFT_FRAME_LATENCY`, which takes `1` to `3`.
|
||||
fn frame_latency_is_on(value: &str) -> bool {
|
||||
crate::presentation::parse(None, Some(value)).0.latency.is_some()
|
||||
}
|
||||
|
||||
/// Anything except `""`, `0`, `off` and `false`, which is how `StrokeTrace::from_value` reads it: the
|
||||
/// rest is a stderr summary or a CSV path. It trims, so `" 0 "` is off there and off here.
|
||||
fn stroke_trace_is_on(value: &str) -> bool {
|
||||
!matches!(value.trim(), "" | "0" | "off" | "false")
|
||||
}
|
||||
|
||||
/// The per-process options this launch's environment sets. A launch that sets only variables would
|
||||
/// otherwise hand its files to the running instance, which never sees the override, and exit.
|
||||
pub fn env_launch_options() -> Vec<PerProcess> {
|
||||
env_launch_options_from(|name| std::env::var_os(name))
|
||||
}
|
||||
|
||||
/// [`env_launch_options`] with the reader given, so the rule is testable without the environment.
|
||||
fn env_launch_options_from(get: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<PerProcess> {
|
||||
ENV_LAUNCH_OPTIONS.iter().filter(|(name, _, is_on)| get(name).is_some_and(|v| is_on(&v.to_string_lossy()))).map(|(_, option, _)| *option).collect()
|
||||
}
|
||||
|
||||
/// Why this launch runs as its own instance, or `None` to take part in single-instance.
|
||||
@@ -101,7 +196,8 @@ pub fn skip_reason(c: &LaunchContext) -> Option<String> {
|
||||
return Some("some paths aren't valid Unicode".into());
|
||||
}
|
||||
if !c.launch_options.is_empty() {
|
||||
return Some(format!("{} only applies to a new process", c.launch_options.join(", ")));
|
||||
let options: Vec<String> = c.launch_options.iter().map(ToString::to_string).collect();
|
||||
return Some(format!("{} only applies to a new process", options.join(", ")));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -110,6 +206,10 @@ pub fn skip_reason(c: &LaunchContext) -> Option<String> {
|
||||
pub struct Primary {
|
||||
lock: Mutex<Option<File>>,
|
||||
shared: Arc<Shared>,
|
||||
/// The socket file to remove on the first shutdown (a Unix socket transport only); taken
|
||||
/// then, so the second call (`Drop`) can't remove the socket the next primary has bound.
|
||||
#[cfg(unix)]
|
||||
socket: Mutex<Option<PathBuf>>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
@@ -151,6 +251,10 @@ impl Primary {
|
||||
self.shared.closed.store(true, Ordering::Release);
|
||||
// Dropping the senders refuses every connection still waiting for the UI.
|
||||
self.shared.inbox.lock().unwrap_or_else(PoisonError::into_inner).pending.clear();
|
||||
#[cfg(unix)]
|
||||
if let Some(path) = self.socket.lock().unwrap_or_else(PoisonError::into_inner).take() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
drop(self.lock.lock().unwrap_or_else(PoisonError::into_inner).take());
|
||||
}
|
||||
}
|
||||
@@ -211,9 +315,15 @@ pub fn claim(dir: &Path, paths: &[String]) -> Launch {
|
||||
claim_with(dir, paths, TIMING)
|
||||
}
|
||||
|
||||
/// [`claim`] with explicit timeouts. Until `timing.handoff` runs out, each round tries the lock
|
||||
/// (free once a quitting or crashed primary is gone) and then the running primary.
|
||||
/// [`claim`] with explicit timeouts, over the transport this process would use ([`transport`]).
|
||||
pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {
|
||||
claim_in(dir, paths, timing, &transport())
|
||||
}
|
||||
|
||||
/// [`claim`] over `transport`. Until `timing.handoff` runs out, each round tries the lock (free
|
||||
/// once a quitting or crashed primary is gone) and then the running primary, wherever
|
||||
/// `instance.json` says it listens.
|
||||
pub fn claim_in(dir: &Path, paths: &[String], timing: Timing, transport: &Transport) -> Launch {
|
||||
if let Err(e) = std::fs::create_dir_all(dir) {
|
||||
return Launch::Standalone(format!("{}: {e}", dir.display()));
|
||||
}
|
||||
@@ -227,7 +337,7 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {
|
||||
loop {
|
||||
match lock.try_lock() {
|
||||
Ok(()) => {
|
||||
return match serve(dir, lock, timing) {
|
||||
return match serve(dir, lock, timing, transport) {
|
||||
Ok(primary) => Launch::Primary(primary),
|
||||
Err(e) => Launch::Standalone(e),
|
||||
};
|
||||
@@ -235,8 +345,8 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
Err(std::fs::TryLockError::Error(e)) => return Launch::Standalone(format!("{}: {e}", lock_path.display())),
|
||||
}
|
||||
if let Some((port, token)) = read_info(dir) {
|
||||
match send(port, &token, paths, deadline) {
|
||||
if let Some((endpoint, token)) = read_info(dir) {
|
||||
match send(&endpoint, &token, paths, deadline) {
|
||||
Ok(()) => return Launch::Forwarded,
|
||||
Err(e) => last = e,
|
||||
}
|
||||
@@ -248,11 +358,15 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|e| format!("loopback listener: {e}"))?;
|
||||
let port = listener.local_addr().map_err(|e| format!("loopback listener: {e}"))?.port();
|
||||
fn serve(dir: &Path, lock: File, timing: Timing, transport: &Transport) -> Result<Primary, String> {
|
||||
let (listener, endpoint) = Listener::bind(transport)?;
|
||||
let token = generate_token().map_err(|e| e.to_string())?;
|
||||
write_info(dir, port, &token)?;
|
||||
write_info(dir, &endpoint, &token)?;
|
||||
#[cfg(unix)]
|
||||
let socket = match &endpoint {
|
||||
Endpoint::Socket(path) => Some(path.clone()),
|
||||
Endpoint::Port(_) => None,
|
||||
};
|
||||
let shared = Arc::new(Shared { inbox: Mutex::default(), closed: AtomicBool::new(false) });
|
||||
let listening = Arc::clone(&shared);
|
||||
let spawned = std::thread::Builder::new().name("single-instance".into()).spawn(move || {
|
||||
@@ -260,7 +374,7 @@ fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {
|
||||
let clients = Arc::new(AtomicUsize::new(0));
|
||||
loop {
|
||||
let stream = match listener.accept() {
|
||||
Ok((stream, _)) => stream,
|
||||
Ok(stream) => stream,
|
||||
// Back off instead of spinning when accept keeps failing (e.g. out of descriptors).
|
||||
Err(_) => {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
@@ -288,11 +402,117 @@ fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {
|
||||
}
|
||||
});
|
||||
spawned.map_err(|e| format!("single-instance listener thread: {e}"))?;
|
||||
Ok(Primary { lock: Mutex::new(Some(lock)), shared })
|
||||
Ok(Primary {
|
||||
lock: Mutex::new(Some(lock)),
|
||||
shared,
|
||||
#[cfg(unix)]
|
||||
socket: Mutex::new(socket),
|
||||
})
|
||||
}
|
||||
|
||||
/// The primary's listener on either transport.
|
||||
enum Listener {
|
||||
Tcp(TcpListener),
|
||||
#[cfg(unix)]
|
||||
Unix(UnixListener),
|
||||
}
|
||||
|
||||
impl Listener {
|
||||
fn bind(transport: &Transport) -> Result<(Listener, Endpoint), String> {
|
||||
match transport {
|
||||
Transport::Loopback => {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|e| format!("loopback listener: {e}"))?;
|
||||
let port = listener.local_addr().map_err(|e| format!("loopback listener: {e}"))?.port();
|
||||
Ok((Listener::Tcp(listener), Endpoint::Port(port)))
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Transport::Socket(path) => {
|
||||
let at = |e: std::io::Error| format!("{}: {e}", path.display());
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(at)?;
|
||||
}
|
||||
// This process holds the lock, so a file already there is a crashed primary's.
|
||||
let _ = std::fs::remove_file(path);
|
||||
let listener = UnixListener::bind(path).map_err(at)?;
|
||||
// The runtime directory is the user's alone already; keep the socket so too.
|
||||
std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o600)).map_err(at)?;
|
||||
Ok((Listener::Unix(listener), Endpoint::Socket(path.clone())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn accept(&self) -> std::io::Result<Stream> {
|
||||
match self {
|
||||
Listener::Tcp(l) => l.accept().map(|(s, _)| Stream::Tcp(s)),
|
||||
#[cfg(unix)]
|
||||
Listener::Unix(l) => l.accept().map(|(s, _)| Stream::Unix(s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One connection, on either transport.
|
||||
enum Stream {
|
||||
Tcp(TcpStream),
|
||||
#[cfg(unix)]
|
||||
Unix(UnixStream),
|
||||
}
|
||||
|
||||
impl Stream {
|
||||
/// Connect to the primary; `timeout` bounds the loopback connect (a Unix connect is immediate).
|
||||
fn connect(endpoint: &Endpoint, timeout: Duration) -> std::io::Result<Stream> {
|
||||
match endpoint {
|
||||
Endpoint::Port(port) => TcpStream::connect_timeout(&SocketAddr::from((Ipv4Addr::LOCALHOST, *port)), timeout).map(Stream::Tcp),
|
||||
#[cfg(unix)]
|
||||
Endpoint::Socket(path) => UnixStream::connect(path).map(Stream::Unix),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_read_timeout(&self, dur: Option<Duration>) -> std::io::Result<()> {
|
||||
match self {
|
||||
Stream::Tcp(s) => s.set_read_timeout(dur),
|
||||
#[cfg(unix)]
|
||||
Stream::Unix(s) => s.set_read_timeout(dur),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_write_timeout(&self, dur: Option<Duration>) -> std::io::Result<()> {
|
||||
match self {
|
||||
Stream::Tcp(s) => s.set_write_timeout(dur),
|
||||
#[cfg(unix)]
|
||||
Stream::Unix(s) => s.set_write_timeout(dur),
|
||||
}
|
||||
}
|
||||
|
||||
/// One read through a shared reference (both socket types read through `&self`).
|
||||
fn read_once(&self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
match self {
|
||||
Stream::Tcp(s) => (&*s).read(buf),
|
||||
#[cfg(unix)]
|
||||
Stream::Unix(s) => (&*s).read(buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Stream {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
match self {
|
||||
Stream::Tcp(s) => s.write(buf),
|
||||
#[cfg(unix)]
|
||||
Stream::Unix(s) => s.write(buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
match self {
|
||||
Stream::Tcp(s) => s.flush(),
|
||||
#[cfg(unix)]
|
||||
Stream::Unix(s) => s.flush(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one request, hand its paths to the UI and answer `ok` only if the UI took them.
|
||||
fn serve_client(stream: TcpStream, token: &str, shared: &Shared, timing: Timing) {
|
||||
fn serve_client(stream: Stream, token: &str, shared: &Shared, timing: Timing) {
|
||||
let taken = match read_request(&stream, timing.request) {
|
||||
Some(line) => match parse_request(&line, token) {
|
||||
Some((paths, wait)) => shared.hand_over(paths, wait.min(timing.ack)),
|
||||
@@ -308,7 +528,7 @@ fn serve_client(stream: TcpStream, token: &str, shared: &Shared, timing: Timing)
|
||||
|
||||
/// A reader that fails once `until` passes, however slowly the bytes trickle in.
|
||||
struct Deadline<'a> {
|
||||
stream: &'a TcpStream,
|
||||
stream: &'a Stream,
|
||||
until: Instant,
|
||||
}
|
||||
|
||||
@@ -317,25 +537,30 @@ impl Read for Deadline<'_> {
|
||||
let left = self.until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero());
|
||||
let left = left.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "request deadline passed"))?;
|
||||
self.stream.set_read_timeout(Some(left))?;
|
||||
let mut stream = self.stream;
|
||||
stream.read(buf)
|
||||
self.stream.read_once(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// The request line, if it arrives complete within `total`.
|
||||
fn read_request(stream: &TcpStream, total: Duration) -> Option<String> {
|
||||
fn read_request(stream: &Stream, total: Duration) -> Option<String> {
|
||||
let mut reader = BufReader::new(Deadline { stream, until: Instant::now() + total });
|
||||
let mut line = String::new();
|
||||
matches!(read_bounded_line(&mut reader, &mut line), Ok(LineRead::Line)).then_some(line)
|
||||
}
|
||||
|
||||
/// Port and token, written to a temporary file and renamed so a reader never sees half of it.
|
||||
/// Endpoint and token, written to a temporary file and renamed so a reader never sees half of it.
|
||||
/// On Unix the file is the user's alone (0600): another local user who read the token could make
|
||||
/// this app open any path. (Windows keeps the per-user ACL of the settings folder.)
|
||||
fn write_info(dir: &Path, port: u16, token: &str) -> Result<(), String> {
|
||||
fn write_info(dir: &Path, endpoint: &Endpoint, token: &str) -> Result<(), String> {
|
||||
let path = dir.join(INFO_FILE);
|
||||
let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id()));
|
||||
let body = json!({"port": port, "token": token, "pid": std::process::id()}).to_string();
|
||||
let mut body = json!({"token": token, "pid": std::process::id()});
|
||||
match endpoint {
|
||||
Endpoint::Port(port) => body["port"] = json!(port),
|
||||
#[cfg(unix)]
|
||||
Endpoint::Socket(socket) => body["socket"] = json!(socket.to_string_lossy()),
|
||||
}
|
||||
let body = body.to_string();
|
||||
// A leftover from a crash could carry wider permissions; the mode applies only on create.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let mut options = OpenOptions::new();
|
||||
@@ -349,10 +574,15 @@ fn write_info(dir: &Path, port: u16, token: &str) -> Result<(), String> {
|
||||
})
|
||||
}
|
||||
|
||||
fn read_info(dir: &Path) -> Option<(u16, String)> {
|
||||
fn read_info(dir: &Path) -> Option<(Endpoint, String)> {
|
||||
let v: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).ok()?).ok()?;
|
||||
let token = v.get("token")?.as_str()?.to_string();
|
||||
#[cfg(unix)]
|
||||
if let Some(socket) = v.get("socket").and_then(Value::as_str) {
|
||||
return Some((Endpoint::Socket(PathBuf::from(socket)), token));
|
||||
}
|
||||
let port = u16::try_from(v.get("port")?.as_u64()?).ok()?;
|
||||
Some((port, v.get("token")?.as_str()?.to_string()))
|
||||
Some((Endpoint::Port(port), token))
|
||||
}
|
||||
|
||||
/// `{"token":…,"open":[…],"wait_ms":…}`: the paths, and how long the sender will wait for the UI.
|
||||
@@ -370,11 +600,10 @@ fn parse_request(line: &str, token: &str) -> Option<(Vec<String>, Duration)> {
|
||||
Some((paths, wait))
|
||||
}
|
||||
|
||||
/// Offer `paths` to the primary on `port`; `Ok` once its UI has taken them.
|
||||
fn send(port: u16, token: &str, paths: &[String], deadline: Instant) -> Result<(), String> {
|
||||
/// Offer `paths` to the primary at `endpoint`; `Ok` once its UI has taken them.
|
||||
fn send(endpoint: &Endpoint, token: &str, paths: &[String], deadline: Instant) -> Result<(), String> {
|
||||
let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or("out of time")?;
|
||||
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||||
let mut stream = TcpStream::connect_timeout(&addr, left).map_err(|e| e.to_string())?;
|
||||
let mut stream = Stream::connect(endpoint, left).map_err(|e| e.to_string())?;
|
||||
// The primary must answer before our deadline, so it waits a little less than we do.
|
||||
let wait_ms = u64::try_from(left.saturating_sub(REPLY_MARGIN).as_millis()).unwrap_or(u64::MAX);
|
||||
let request = json!({"token": token, "open": paths, "wait_ms": wait_ms});
|
||||
@@ -398,251 +627,4 @@ pub fn absolute(path: &str) -> String {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) };
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Launch with `paths` on another thread (it blocks until the primary's UI takes them).
|
||||
fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle<Launch> {
|
||||
let (dir, paths): (PathBuf, Vec<String>) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect());
|
||||
std::thread::spawn(move || claim_with(&dir, &paths, timing))
|
||||
}
|
||||
|
||||
/// Play the UI: drain until `n` events arrived (or 5 s passed).
|
||||
fn drain(ui: &mut OsEventsFn, n: usize) -> Vec<OsEvent> {
|
||||
let mut got = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while got.len() < n && Instant::now() < deadline {
|
||||
got.extend(ui());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
fn primary(dir: &Path) -> Primary {
|
||||
match claim_with(dir, &[], FAST) {
|
||||
Launch::Primary(p) => p,
|
||||
_ => panic!("first launch should be primary"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_launch_hands_its_paths_to_the_first() {
|
||||
let dir = temp_dir("handoff");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let paths = ["C:\\art\\one.psd", "/home/a/two é.png"];
|
||||
let second = launch(&dir, &paths, TIMING);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]);
|
||||
assert!(matches!(second.join().unwrap(), Launch::Forwarded));
|
||||
// A plain second start (no files) just brings the window forward.
|
||||
let third = launch(&dir, &[], TIMING);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]);
|
||||
assert!(matches!(third.join().unwrap(), Launch::Forwarded));
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_launches_all_land_in_one_instance() {
|
||||
let dir = temp_dir("race");
|
||||
let (tx, rx) = channel();
|
||||
for i in 0..6 {
|
||||
let (dir, tx) = (dir.clone(), tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(claim(&dir, &[format!("file{i}.psd")]));
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new());
|
||||
let mut ui: Option<OsEventsFn> = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while primaries.len() + forwarded < 6 && Instant::now() < deadline {
|
||||
while let Ok(launch) = rx.try_recv() {
|
||||
match launch {
|
||||
Launch::Primary(p) => primaries.push(p),
|
||||
Launch::Forwarded => forwarded += 1,
|
||||
Launch::Standalone(reason) => panic!("standalone: {reason}"),
|
||||
}
|
||||
}
|
||||
if ui.is_none()
|
||||
&& let Some(p) = primaries.first()
|
||||
{
|
||||
ui = Some(p.connect(&egui::Context::default()));
|
||||
}
|
||||
if let Some(ui) = ui.as_mut() {
|
||||
events.extend(ui());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5));
|
||||
drop(primaries);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crashed_instance_leaves_nothing_in_the_way() {
|
||||
let dir = temp_dir("stale");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// instance.json from a process that is gone; the lock is free.
|
||||
std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap();
|
||||
let primary = primary(&dir);
|
||||
assert!(read_info(&dir).is_some_and(|(port, _)| port != 1));
|
||||
drop(primary);
|
||||
// Released with the handle, as on process exit.
|
||||
assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary
|
||||
/// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes
|
||||
/// the lock over and opens the file itself.
|
||||
#[test]
|
||||
fn a_launch_waiting_on_a_closing_instance_takes_over() {
|
||||
let dir = temp_dir("closing");
|
||||
let primary = primary(&dir);
|
||||
// The UI never drains (it is shutting down, or never came up).
|
||||
let waiting = launch(&dir, &["a.psd"], FAST);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
primary.shutdown();
|
||||
assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary");
|
||||
// After shutdown new connections are refused too.
|
||||
let (port, token) = read_info(&dir).unwrap();
|
||||
drop(primary);
|
||||
let short = Instant::now() + Duration::from_millis(300);
|
||||
assert!(send(port, &token, &["b.psd".into()], short).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't
|
||||
/// acknowledge them, and doesn't keep them queued to open later as well.
|
||||
#[test]
|
||||
fn a_hung_instance_never_swallows_a_file() {
|
||||
let dir = temp_dir("hung-ui");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let started = Instant::now();
|
||||
assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_)));
|
||||
assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed());
|
||||
assert!(ui().is_empty(), "withdrawn, not opened later");
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_without_the_token_or_malformed_are_rejected() {
|
||||
let token = generate_token().unwrap();
|
||||
let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token);
|
||||
assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250))));
|
||||
let wrong = generate_token().unwrap();
|
||||
assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None);
|
||||
for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] {
|
||||
assert_eq!(parse_request(bad, &token), None, "{bad:?}");
|
||||
}
|
||||
let many: Vec<String> = (0..=MAX_PATHS).map(|i| i.to_string()).collect();
|
||||
assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_client_does_not_hold_up_the_next_launch() {
|
||||
let dir = temp_dir("stalled");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let (port, _) = read_info(&dir).unwrap();
|
||||
// Connects and never sends a line (each would otherwise hold the listener).
|
||||
let stalled: Vec<TcpStream> = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect();
|
||||
let started = Instant::now();
|
||||
let next = launch(&dir, &["b.psd"], FAST);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]);
|
||||
assert!(matches!(next.join().unwrap(), Launch::Forwarded));
|
||||
assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed());
|
||||
drop(stalled);
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A client that trickles a byte at a time can't keep its slot past the request deadline.
|
||||
#[test]
|
||||
fn a_trickling_client_is_cut_off_at_the_request_deadline() {
|
||||
let dir = temp_dir("trickle");
|
||||
let primary = primary(&dir);
|
||||
let (port, _) = read_info(&dir).unwrap();
|
||||
let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();
|
||||
let started = Instant::now();
|
||||
let mut cut_off = false;
|
||||
while started.elapsed() < FAST.request * 4 {
|
||||
if slow.write_all(b"{").is_err() {
|
||||
cut_off = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
assert!(cut_off, "still connected after {:?}", started.elapsed());
|
||||
assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed());
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_token_file_is_private_to_the_user() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir("mode");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A wide leftover temporary file from a crashed start doesn't widen the new one.
|
||||
let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, "{}").unwrap();
|
||||
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
write_info(&dir, 1, &generate_token().unwrap()).unwrap();
|
||||
let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreachable_instance_falls_back_to_a_standalone_launch() {
|
||||
let dir = temp_dir("unreachable");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// Someone holds the lock but nothing listens on the advertised port.
|
||||
let held = File::create(dir.join(LOCK_FILE)).unwrap();
|
||||
held.lock().unwrap();
|
||||
let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port();
|
||||
write_info(&dir, closed, &generate_token().unwrap()).unwrap();
|
||||
assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_)));
|
||||
drop(held);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 2 and the smaller points: who takes part in single-instance.
|
||||
#[test]
|
||||
fn only_per_user_launches_without_process_options_take_part() {
|
||||
let base = LaunchContext {
|
||||
per_user_settings: true,
|
||||
new_instance_flag: false,
|
||||
new_instance_env: None,
|
||||
control: false,
|
||||
unreadable_paths: false,
|
||||
launch_options: &[],
|
||||
};
|
||||
assert_eq!(skip_reason(&base), None);
|
||||
// A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users.
|
||||
assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some());
|
||||
assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None);
|
||||
assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None);
|
||||
assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some());
|
||||
let reason = skip_reason(&LaunchContext { launch_options: &["--safe-gpu"], ..base });
|
||||
assert!(reason.is_some_and(|r| r.contains("--safe-gpu")));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) };
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Launch with `paths` on another thread (it blocks until the primary's UI takes them).
|
||||
fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle<Launch> {
|
||||
let (dir, paths): (PathBuf, Vec<String>) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect());
|
||||
std::thread::spawn(move || claim_with(&dir, &paths, timing))
|
||||
}
|
||||
|
||||
/// Play the UI: drain until `n` events arrived (or 5 s passed).
|
||||
fn drain(ui: &mut OsEventsFn, n: usize) -> Vec<OsEvent> {
|
||||
let mut got = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while got.len() < n && Instant::now() < deadline {
|
||||
got.extend(ui());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
fn primary(dir: &Path) -> Primary {
|
||||
match claim_with(dir, &[], FAST) {
|
||||
Launch::Primary(p) => p,
|
||||
_ => panic!("first launch should be primary"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104).
|
||||
#[cfg(unix)]
|
||||
fn short_socket_path(tag: &str) -> PathBuf {
|
||||
std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE)
|
||||
}
|
||||
|
||||
/// The loopback port the primary under `dir` listens on.
|
||||
fn port_of(dir: &Path) -> u16 {
|
||||
match read_info(dir).unwrap().0 {
|
||||
Endpoint::Port(port) => port,
|
||||
#[cfg(unix)]
|
||||
Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_launch_hands_its_paths_to_the_first() {
|
||||
let dir = temp_dir("handoff");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let paths = ["C:\\art\\one.psd", "/home/a/two é.png"];
|
||||
let second = launch(&dir, &paths, TIMING);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]);
|
||||
assert!(matches!(second.join().unwrap(), Launch::Forwarded));
|
||||
// A plain second start (no files) just brings the window forward.
|
||||
let third = launch(&dir, &[], TIMING);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]);
|
||||
assert!(matches!(third.join().unwrap(), Launch::Forwarded));
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_launches_all_land_in_one_instance() {
|
||||
let dir = temp_dir("race");
|
||||
let (tx, rx) = channel();
|
||||
for i in 0..6 {
|
||||
let (dir, tx) = (dir.clone(), tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(claim(&dir, &[format!("file{i}.psd")]));
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new());
|
||||
let mut ui: Option<OsEventsFn> = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while primaries.len() + forwarded < 6 && Instant::now() < deadline {
|
||||
while let Ok(launch) = rx.try_recv() {
|
||||
match launch {
|
||||
Launch::Primary(p) => primaries.push(p),
|
||||
Launch::Forwarded => forwarded += 1,
|
||||
Launch::Standalone(reason) => panic!("standalone: {reason}"),
|
||||
}
|
||||
}
|
||||
if ui.is_none()
|
||||
&& let Some(p) = primaries.first()
|
||||
{
|
||||
ui = Some(p.connect(&egui::Context::default()));
|
||||
}
|
||||
if let Some(ui) = ui.as_mut() {
|
||||
events.extend(ui());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5));
|
||||
drop(primaries);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crashed_instance_leaves_nothing_in_the_way() {
|
||||
let dir = temp_dir("stale");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// instance.json from a process that is gone; the lock is free.
|
||||
std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap();
|
||||
let primary = primary(&dir);
|
||||
assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1)));
|
||||
drop(primary);
|
||||
// Released with the handle, as on process exit.
|
||||
assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary
|
||||
/// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes
|
||||
/// the lock over and opens the file itself.
|
||||
#[test]
|
||||
fn a_launch_waiting_on_a_closing_instance_takes_over() {
|
||||
let dir = temp_dir("closing");
|
||||
let primary = primary(&dir);
|
||||
// The UI never drains (it is shutting down, or never came up).
|
||||
let waiting = launch(&dir, &["a.psd"], FAST);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
primary.shutdown();
|
||||
assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary");
|
||||
// After shutdown new connections are refused too.
|
||||
let (endpoint, token) = read_info(&dir).unwrap();
|
||||
drop(primary);
|
||||
let short = Instant::now() + Duration::from_millis(300);
|
||||
assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't
|
||||
/// acknowledge them, and doesn't keep them queued to open later as well.
|
||||
#[test]
|
||||
fn a_hung_instance_never_swallows_a_file() {
|
||||
let dir = temp_dir("hung-ui");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let started = Instant::now();
|
||||
assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_)));
|
||||
assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed());
|
||||
assert!(ui().is_empty(), "withdrawn, not opened later");
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_without_the_token_or_malformed_are_rejected() {
|
||||
let token = generate_token().unwrap();
|
||||
let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token);
|
||||
assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250))));
|
||||
let wrong = generate_token().unwrap();
|
||||
assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None);
|
||||
for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] {
|
||||
assert_eq!(parse_request(bad, &token), None, "{bad:?}");
|
||||
}
|
||||
let many: Vec<String> = (0..=MAX_PATHS).map(|i| i.to_string()).collect();
|
||||
assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_client_does_not_hold_up_the_next_launch() {
|
||||
let dir = temp_dir("stalled");
|
||||
let primary = primary(&dir);
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let port = port_of(&dir);
|
||||
// Connects and never sends a line (each would otherwise hold the listener).
|
||||
let stalled: Vec<TcpStream> = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect();
|
||||
let started = Instant::now();
|
||||
let next = launch(&dir, &["b.psd"], FAST);
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]);
|
||||
assert!(matches!(next.join().unwrap(), Launch::Forwarded));
|
||||
assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed());
|
||||
drop(stalled);
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A client that trickles a byte at a time can't keep its slot past the request deadline.
|
||||
#[test]
|
||||
fn a_trickling_client_is_cut_off_at_the_request_deadline() {
|
||||
let dir = temp_dir("trickle");
|
||||
let primary = primary(&dir);
|
||||
let port = port_of(&dir);
|
||||
let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();
|
||||
let started = Instant::now();
|
||||
let mut cut_off = false;
|
||||
while started.elapsed() < FAST.request * 4 {
|
||||
if slow.write_all(b"{").is_err() {
|
||||
cut_off = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
assert!(cut_off, "still connected after {:?}", started.elapsed());
|
||||
assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed());
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_token_file_is_private_to_the_user() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir("mode");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A wide leftover temporary file from a crashed start doesn't widen the new one.
|
||||
let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, "{}").unwrap();
|
||||
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap();
|
||||
let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreachable_instance_falls_back_to_a_standalone_launch() {
|
||||
let dir = temp_dir("unreachable");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// Someone holds the lock but nothing listens on the advertised port.
|
||||
let held = File::create(dir.join(LOCK_FILE)).unwrap();
|
||||
held.lock().unwrap();
|
||||
let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port();
|
||||
write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap();
|
||||
assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_)));
|
||||
drop(held);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Review of #3755, point 2 and the smaller points: who takes part in single-instance.
|
||||
#[test]
|
||||
fn only_per_user_launches_without_process_options_take_part() {
|
||||
let base = LaunchContext {
|
||||
per_user_settings: true,
|
||||
new_instance_flag: false,
|
||||
new_instance_env: None,
|
||||
control: false,
|
||||
unreadable_paths: false,
|
||||
launch_options: &[],
|
||||
};
|
||||
assert_eq!(skip_reason(&base), None);
|
||||
// A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users.
|
||||
assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some());
|
||||
assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None);
|
||||
assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None);
|
||||
assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some());
|
||||
assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some());
|
||||
let reason = skip_reason(&LaunchContext { launch_options: &[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], ..base });
|
||||
assert_eq!(reason.as_deref(), Some("--safe-gpu, PHOTOCRAFT_GPU_ADAPTER only applies to a new process"));
|
||||
}
|
||||
|
||||
/// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime
|
||||
/// directory, which every sandbox of the app shares, with the same lock, token and reply.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir("socket");
|
||||
// Short: a Unix socket path is limited to about 100 bytes (macOS: 104).
|
||||
let socket = short_socket_path("a");
|
||||
let transport = Transport::Socket(socket.clone());
|
||||
let primary = match claim_in(&dir, &[], FAST, &transport) {
|
||||
Launch::Primary(p) => p,
|
||||
_ => panic!("first launch should be primary"),
|
||||
};
|
||||
assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap();
|
||||
assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap()));
|
||||
assert!(info.get("port").is_none());
|
||||
let mut ui = primary.connect(&egui::Context::default());
|
||||
let paths = ["/home/a/one.psd".to_string()];
|
||||
let (d, p, t) = (dir.clone(), paths.clone(), transport.clone());
|
||||
let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t));
|
||||
assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]);
|
||||
assert!(matches!(second.join().unwrap(), Launch::Forwarded));
|
||||
// The token still gates the socket.
|
||||
let (endpoint, _) = read_info(&dir).unwrap();
|
||||
assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err());
|
||||
primary.shutdown();
|
||||
assert!(!socket.exists(), "shutdown removes the socket file");
|
||||
// The next primary binds the same path; the old one's drop (a second shutdown) must leave it.
|
||||
let next = match claim_in(&dir, &[], FAST, &transport) {
|
||||
Launch::Primary(p) => p,
|
||||
_ => panic!("the lock is free again"),
|
||||
};
|
||||
drop(primary);
|
||||
assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket");
|
||||
drop(next);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() {
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
let dir = temp_dir("stale-socket");
|
||||
let socket = short_socket_path("b");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(socket.parent().unwrap()).unwrap();
|
||||
std::fs::write(&socket, b"not a socket").unwrap();
|
||||
write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap();
|
||||
let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) {
|
||||
Launch::Primary(p) => p,
|
||||
Launch::Forwarded => panic!("nothing was listening"),
|
||||
Launch::Standalone(e) => panic!("{e}"),
|
||||
};
|
||||
assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());
|
||||
drop(primary);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(socket.parent().unwrap());
|
||||
}
|
||||
|
||||
/// The socket transport is chosen only inside a Flatpak with a runtime directory.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() {
|
||||
use std::ffi::OsStr;
|
||||
let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000"));
|
||||
assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock")));
|
||||
assert_eq!(sandbox_socket(None, Some(run)), None);
|
||||
assert_eq!(sandbox_socket(Some(id), None), None);
|
||||
assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None);
|
||||
assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None);
|
||||
}
|
||||
|
||||
/// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch
|
||||
/// that sets only variables has per-process options, so it keeps its own process rather than
|
||||
/// handing its files to the running instance, which never sees the override.
|
||||
#[test]
|
||||
fn an_environment_override_counts_as_a_process_option() {
|
||||
let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into()));
|
||||
assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec![PerProcess::PresentMode]);
|
||||
assert_eq!(with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_FRAME_LATENCY", "2")]), vec![PerProcess::FrameLatency, PerProcess::StrokeTrace]);
|
||||
// Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way
|
||||
// it is read where it takes effect, not by one rule shared across all three.
|
||||
assert!(with(&[]).is_empty());
|
||||
assert!(with(&[("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty());
|
||||
// The trace is off at `off` and `false` as well, and a value the presentation parser rejects
|
||||
// is ignored there, so neither keeps a process of its own here.
|
||||
assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty());
|
||||
// The trace and the two presentation values are trimmed where they take effect.
|
||||
assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec![PerProcess::PresentMode, PerProcess::StrokeTrace]);
|
||||
// The menus and the automation roots are flags' fallbacks: `launch_args::parse` counts them.
|
||||
assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "1"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]).is_empty());
|
||||
let base = LaunchContext {
|
||||
per_user_settings: true,
|
||||
new_instance_flag: false,
|
||||
new_instance_env: None,
|
||||
control: false,
|
||||
unreadable_paths: false,
|
||||
launch_options: &[],
|
||||
};
|
||||
let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base });
|
||||
assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}");
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Telling the user why a launch failed when there is no window to say it in (#7643).
|
||||
//!
|
||||
//! A desktop launch has no console — release builds are GUI-subsystem apps on Windows — so the
|
||||
//! `Err` that ends `main` used to vanish and PhotoCraft "just closed". This shows one native
|
||||
//! dialog with the error, the renderer that was tried and the log file to attach. The text is
|
||||
//! English diagnostics, like Help › System Info, so a bug report reads the same in every language.
|
||||
//!
|
||||
//! Terminal and automation launches keep the old behaviour: they can read standard error or the
|
||||
//! exit status, and a modal dialog would leave a script waiting.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
use std::path::Path;
|
||||
|
||||
/// Whether a failed launch needs the dialog: no terminal under standard error, no control client
|
||||
/// (an agent launch reads the exit status instead of clicking OK), and a screen to put it on.
|
||||
pub fn dialog_wanted(stderr_is_terminal: bool, automation: bool, display: bool) -> bool {
|
||||
!stderr_is_terminal && !automation && display
|
||||
}
|
||||
|
||||
/// Whether this launch asks for the dialog (see [`dialog_wanted`]).
|
||||
pub fn needs_dialog(automation: bool) -> bool {
|
||||
dialog_wanted(std::io::stderr().is_terminal(), automation, has_display())
|
||||
}
|
||||
|
||||
/// Whether there is a screen for a dialog: always on Windows and macOS; on Linux a headless box
|
||||
/// (a CI runner, an SSH session — `startup_without_display` removes both variables) has none.
|
||||
fn has_display() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
["DISPLAY", "WAYLAND_DISPLAY"].iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog's text: the error, the renderer that was tried and why it wasn't the preference,
|
||||
/// the version and, when one was opened, the log file.
|
||||
pub fn text(error: &str, renderer: &str, note: Option<&str>, version: &str, log: Option<&Path>) -> String {
|
||||
let mut text = format!("PhotoCraft could not start.\n\n{error}\n\nRenderer: {renderer}");
|
||||
if let Some(note) = note {
|
||||
text.push_str(&format!("\nStartup: {note}"));
|
||||
}
|
||||
text.push_str(&format!("\nVersion: {version}"));
|
||||
if let Some(path) = log {
|
||||
text.push_str(&format!("\nLog file: {}", path.display()));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Show [`text`] in a native error dialog. Called after the event loop returned, so nothing is
|
||||
/// repainting and the launch was about to fail anyway.
|
||||
pub fn show(error: &str, renderer: &str, note: Option<&str>, log: Option<&Path>) {
|
||||
let version = photocraft_engine::build_info::long_version();
|
||||
let body = text(error, renderer, note, &version, log);
|
||||
log::info!("showing the startup-failure dialog");
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_title(photocraft_ui_egui::i18n::t("PhotoCraft could not start"))
|
||||
.set_description(body)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_desktop_launch_asks_the_user_and_a_script_does_not() {
|
||||
assert!(dialog_wanted(false, false, true), "no console: the error would vanish");
|
||||
assert!(!dialog_wanted(true, false, true), "a terminal shows the error itself");
|
||||
assert!(!dialog_wanted(false, true, true), "an automation client reads the exit status");
|
||||
assert!(!dialog_wanted(false, false, false), "a headless launch has no screen for a dialog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_names_the_error_renderer_version_and_log() {
|
||||
let log = Path::new("/home/me/.config/photocraft/logs/photocraft.log");
|
||||
let body = text("no adapter for Vulkan", "dx12", None, "0.15.1 (abc1234)", Some(log));
|
||||
for part in [
|
||||
"could not start",
|
||||
"no adapter for Vulkan",
|
||||
"Renderer: dx12",
|
||||
"Version: 0.15.1 (abc1234)",
|
||||
"Log file: /home/me/.config/photocraft/logs/photocraft.log",
|
||||
] {
|
||||
assert!(body.contains(part), "{part:?} missing from {body:?}");
|
||||
}
|
||||
assert!(!body.contains("Startup:"), "no fallback to explain: {body:?}");
|
||||
// A start whose log file could not be created says so by leaving the line out.
|
||||
assert!(!text("boom", "cpu", None, "0.15.1", None).contains("Log file:"));
|
||||
}
|
||||
|
||||
/// A crash fallback is the confusing case: the app picks a renderer the user never chose, so
|
||||
/// the dialog has to say why as well as which.
|
||||
#[test]
|
||||
fn a_fallback_that_was_not_the_preference_is_explained() {
|
||||
let note = "the previous start didn't finish on vulkan; using dx12";
|
||||
let body = text("device lost", "dx12", Some(note), "0.15.1", None);
|
||||
assert!(body.contains(&format!("Renderer: dx12\nStartup: {note}\n")), "{body:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Pen tablet pressure, tilt, rotation and eraser end on macOS and Linux X11 (issue #79).
|
||||
//! Pen tablet pressure, tilt, rotation and eraser end on macOS and Linux X11 (issue #79), and
|
||||
//! barrel button on Windows (#5905).
|
||||
//!
|
||||
//! winit 0.30 drops tablet data on both, so `photocraft-tablet` reads it beside winit (an AppKit
|
||||
//! local event monitor; XInput2 raw events on a second X connection) and this module writes each
|
||||
//! sample into the UI's [`StylusFeed`], where the canvas reads it exactly like the web runner's
|
||||
//! Pointer Events and automation's simulated pen. Windows needs nothing here: winit forwards
|
||||
//! `WM_POINTER` pressure as touch force.
|
||||
//! winit 0.30 drops tablet data on both macOS and X11, so `photocraft-tablet` reads it beside winit
|
||||
//! (an AppKit local event monitor; XInput2 raw events on a second X connection) and this module writes
|
||||
//! each sample into the UI's [`StylusFeed`], where the canvas reads it exactly like the web runner's
|
||||
//! Pointer Events and automation's simulated pen. On Windows, winit forwards `WM_POINTER` pressure
|
||||
//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`); `photocraft-tablet` recovers the barrel
|
||||
//! button through a thread-local message hook beside winit.
|
||||
//!
|
||||
//! Wayland compositors give a pen only to clients that bind the tablet protocol
|
||||
//! (`zwp_tablet_v2`), which winit 0.30 doesn't (and binding it on winit's connection needs
|
||||
@@ -19,15 +21,36 @@ use photocraft_tablet::Sample;
|
||||
use photocraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
|
||||
/// A tablet sample as the UI's pen sample.
|
||||
#[allow(dead_code)]
|
||||
pub fn pen_sample(s: Sample) -> PenSample {
|
||||
PenSample { pressure: s.pressure, tilt_x: s.tilt_x, tilt_y: s.tilt_y, rotation: s.rotation, eraser: s.eraser }.sanitized()
|
||||
}
|
||||
|
||||
/// Writes tablet samples into `feed` (`None` = a mouse).
|
||||
#[allow(dead_code)]
|
||||
pub fn sink(feed: StylusFeed) -> impl Fn(Option<Sample>) + Send + 'static {
|
||||
move |s| feed.set(s.map(pen_sample))
|
||||
}
|
||||
|
||||
/// Install the Windows pointer message hook (main thread; keep the result until the event loop
|
||||
/// returns). On failure this logs why: the pen barrel button is then missed.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn install_windows() -> Option<photocraft_tablet::windows::Monitor> {
|
||||
photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok()
|
||||
}
|
||||
|
||||
/// Stylus barrel button down check (Windows). The right mouse button is left to egui, which
|
||||
/// reports the logical secondary button (swapped buttons included) for the app's own window only.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
|
||||
Some(Box::new(photocraft_tablet::windows::is_barrel_button_down))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Install the AppKit tablet monitor (main thread, once winit created the shared application:
|
||||
/// from eframe's app creation, not before the event loop). Keep the result until the event loop
|
||||
/// returns. On failure this logs why: pens then paint like a mouse.
|
||||
|
||||
@@ -6,16 +6,32 @@
|
||||
//! hand-edited file would then crash every launch. [`sanitize`] runs first and removes a file
|
||||
//! holding such values (the window and panels open at their defaults; nothing else is lost).
|
||||
//! A file that isn't RON at all is left alone: eframe already ignores it.
|
||||
//!
|
||||
//! egui 0.37 also replaced the flat `WindowSettings` (`inner_position_pixels`,
|
||||
//! `inner_size_points: Option<Vec2>`, …) with `normal_geometry: { outer_position_pixels,
|
||||
//! scale_factor, inner_size_points }`. eframe reads the file before any application code, so an
|
||||
//! old value cannot be interpreted lazily: [`sanitize`] rewrites it before eframe loads it and
|
||||
//! keeps a one-time `ui.ron.pre-0.37` backup. The old panel keys in the egui memory part are
|
||||
//! untouched (`panels::panel_state_id` migrates them additively), but this window rewrite is
|
||||
//! one-way: after it, a 0.36 build ignores the window entry and opens at its default geometry.
|
||||
//! Restoring the backup is the documented rollback.
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::HashMap, path::Path};
|
||||
|
||||
/// Window positions, sizes and panel rects beyond this many points or pixels are corrupt.
|
||||
const MAX_COORD: f64 = 1.0e6;
|
||||
/// egui's zoom factor is the UI scale over the display scale (75% on a 2× display is 0.375,
|
||||
/// 300% on a 1× display is 3).
|
||||
const ZOOM: std::ops::RangeInclusive<f64> = 0.1..=10.0;
|
||||
/// The size [`crate::native_options`] opens a window with when an old save has no usable size.
|
||||
const DEFAULT_SIZE: f32 = 1440.0;
|
||||
const DEFAULT_HEIGHT: f32 = 900.0;
|
||||
/// Kept beside `ui.ron` before the one-way 0.36 → 0.37 window rewrite.
|
||||
const BACKUP_SUFFIX: &str = "pre-0.37";
|
||||
|
||||
/// Remove `path` if it holds state that would crash startup. Never fails: errors are logged.
|
||||
/// Remove `path` if it holds state that would crash startup, and migrate an old window entry to
|
||||
/// the 0.37 schema before eframe reads it. Never fails: errors are logged and leave the file
|
||||
/// alone (eframe then ignores what it cannot read).
|
||||
pub fn sanitize(path: Option<&Path>) {
|
||||
let Some(path) = path else { return };
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
@@ -24,30 +40,72 @@ pub fn sanitize(path: Option<&Path>) {
|
||||
if let Err(e) = std::fs::remove_file(path) {
|
||||
log::warn!("could not remove {}: {e}", path.display());
|
||||
}
|
||||
return;
|
||||
}
|
||||
match migrate_window(text) {
|
||||
Ok(Some(text)) => write_migrated(path, &text),
|
||||
Ok(None) => {}
|
||||
Err(why) => log::warn!("not rewriting the saved window geometry in {}: {why}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` holds a window position from an earlier session, which eframe restores. Then
|
||||
/// `NativeOptions::centered` must be off: eframe applies it after restoring the saved geometry,
|
||||
/// Write the migrated file, keeping a one-time backup. A failed backup aborts the rewrite: the
|
||||
/// pre-0.37 window geometry is the documented rollback, so never destroy the only copy.
|
||||
fn write_migrated(path: &Path, text: &str) {
|
||||
let backup = backup_path(path);
|
||||
if !backup.exists()
|
||||
&& let Err(e) = std::fs::copy(path, &backup)
|
||||
{
|
||||
log::warn!("could not back up {} to {}: {e}; leaving it unchanged", path.display(), backup.display());
|
||||
return;
|
||||
}
|
||||
if let Err(e) = std::fs::write(path, text) {
|
||||
log::warn!("could not write the migrated window layout to {}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
fn backup_path(path: &Path) -> std::path::PathBuf {
|
||||
let mut name = path.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_else(|| "ui.ron".into());
|
||||
name.push(format!(".{BACKUP_SUFFIX}"));
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Whether `path` holds a window position that eframe restores, which means
|
||||
/// `NativeOptions::centered` must be off: eframe applies `centered` after the restored geometry,
|
||||
/// so it moved the window back to the centre of the main monitor on every launch (#4826).
|
||||
///
|
||||
/// Only the 0.37 `normal_geometry.outer_position_pixels` counts: `egui_winit::WindowGeometry`
|
||||
/// sets it and `initialize_viewport_builder` applies it. A 0.36 flat entry is not restored by
|
||||
/// 0.37 (`sanitize` rewrites it first), and its macOS `inner_position_pixels` was never an outer
|
||||
/// position.
|
||||
pub fn has_saved_position(path: Option<&Path>) -> bool {
|
||||
let Some(text) = path.and_then(|p| std::fs::read_to_string(p).ok()) else { return false };
|
||||
saved_position(&text)
|
||||
}
|
||||
|
||||
fn saved_position(text: &str) -> bool {
|
||||
let Ok(kv) = ron::from_str::<std::collections::HashMap<String, String>>(text) else { return false };
|
||||
let Ok(kv) = ron::from_str::<HashMap<String, String>>(text) else { return false };
|
||||
let Some(window) = kv.get("window").and_then(|w| ron::from_str::<ron::Value>(w).ok()) else { return false };
|
||||
// eframe restores the inner position on macOS and the outer position elsewhere
|
||||
// (`egui_winit::WindowSettings::initialize_viewport_builder`).
|
||||
let key = if cfg!(target_os = "macos") { "inner_position_pixels" } else { "outer_position_pixels" };
|
||||
matches!(field(&window, key), Some(ron::Value::Option(Some(_))))
|
||||
let Some(geometry) = field(&window, "normal_geometry") else { return false };
|
||||
matches!(field(geometry, "outer_position_pixels"), Some(ron::Value::Option(Some(_))))
|
||||
}
|
||||
|
||||
/// The 0.36 → 0.37 rewrite of one `ui.ron` text, for the recorded 0.14/0.15 fixtures.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn migrate_for_test(text: &str) -> Result<Option<String>, String> {
|
||||
migrate_window(text.to_owned())
|
||||
}
|
||||
|
||||
/// [`saved_position`] for the recorded fixtures.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn saved_position_for_test(text: &str) -> bool {
|
||||
saved_position(text)
|
||||
}
|
||||
|
||||
/// `Err` names the first value that would crash startup.
|
||||
fn check(text: &str) -> Result<(), String> {
|
||||
// eframe stores a map of key → RON string; a file that doesn't parse is ignored by eframe.
|
||||
let Ok(kv) = ron::from_str::<std::collections::HashMap<String, String>>(text) else { return Ok(()) };
|
||||
let Ok(kv) = ron::from_str::<HashMap<String, String>>(text) else { return Ok(()) };
|
||||
for (key, value) in &kv {
|
||||
// eframe also skips an entry that doesn't parse.
|
||||
let Ok(v) = ron::from_str::<ron::Value>(value) else { continue };
|
||||
@@ -60,6 +118,108 @@ fn check(text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Some(new_text)` when `text` is an old-schema file that should be rewritten; `None` when it
|
||||
/// is already 0.37-shaped or holds no window entry; `Err` when the old window entry is unusable
|
||||
/// and must be left untouched.
|
||||
fn migrate_window(text: String) -> Result<Option<String>, String> {
|
||||
let Ok(mut kv) = ron::from_str::<HashMap<String, String>>(&text) else { return Ok(None) };
|
||||
let Some(value) = kv.get("window").cloned() else { return Ok(None) };
|
||||
let Ok(window) = ron::from_str::<ron::Value>(&value) else { return Ok(None) };
|
||||
if field(&window, "normal_geometry").is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
if field(&window, "inner_size_points").is_none() && field(&window, "inner_position_pixels").is_none() && field(&window, "outer_position_pixels").is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let migrated = migrate_window_value(&window)?;
|
||||
kv.insert("window".into(), migrated);
|
||||
ron::to_string(&kv).map(Some).map_err(|e| format!("cannot write the new window entry: {e}"))
|
||||
}
|
||||
|
||||
/// The RON payload eframe 0.37 deserializes as `egui_winit::WindowSettings`.
|
||||
///
|
||||
/// The field order and names mirror `WindowGeometry`; the types are local because
|
||||
/// `egui_winit::WindowGeometry` keeps its fields private.
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
struct PointV37 {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
impl PointV37 {
|
||||
fn sane(self) -> Option<Self> {
|
||||
let ok = |v: f32| v.is_finite() && (v.abs() as f64) <= MAX_COORD;
|
||||
(ok(self.x) && ok(self.y)).then_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
struct GeometryV37 {
|
||||
outer_position_pixels: Option<PointV37>,
|
||||
scale_factor: f32,
|
||||
inner_size_points: PointV37,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
struct WindowV37 {
|
||||
normal_geometry: GeometryV37,
|
||||
fullscreen: bool,
|
||||
maximized: bool,
|
||||
}
|
||||
|
||||
fn migrate_window_value(window: &ron::Value) -> Result<String, String> {
|
||||
let size = old_size(window)?;
|
||||
// The old macOS entry stored an inner (not outer) position in logical points and Linux saved
|
||||
// no scale factor, so a faithful restore is only possible for the Windows physical outer
|
||||
// position. Everywhere else the window opens centred with its saved size.
|
||||
let position = if cfg!(target_os = "windows") { old_position(window, "outer_position_pixels") } else { None };
|
||||
let window = WindowV37 {
|
||||
normal_geometry: GeometryV37 {
|
||||
outer_position_pixels: position,
|
||||
// Physical pixels of the old Windows position: 0.37 divides by zoom × scale.
|
||||
scale_factor: 1.0,
|
||||
inner_size_points: size,
|
||||
},
|
||||
fullscreen: old_bool(window, "fullscreen"),
|
||||
maximized: old_bool(window, "maximized"),
|
||||
};
|
||||
ron::to_string(&window).map_err(|e| format!("cannot serialize the new window entry: {e}"))
|
||||
}
|
||||
|
||||
fn old_size(window: &ron::Value) -> Result<PointV37, String> {
|
||||
let value = field(window, "inner_size_points");
|
||||
let Some(ron::Value::Option(Some(size))) = value else {
|
||||
// A missing size is the app's own opening size, not corrupt data.
|
||||
return Ok(PointV37 { x: DEFAULT_SIZE, y: DEFAULT_HEIGHT });
|
||||
};
|
||||
let point = point_value(size).ok_or_else(|| "inner_size_points is not a finite (x, y) point".to_string())?;
|
||||
let point = point.sane().ok_or_else(|| "inner_size_points is not finite or is absurdly large".to_string())?;
|
||||
if point.x < 1.0 || point.y < 1.0 {
|
||||
return Err("inner_size_points has a zero or negative side".into());
|
||||
}
|
||||
Ok(point)
|
||||
}
|
||||
|
||||
/// One dimension of an old `Option<Pos2>` field, rejecting corrupt values rather than guessing.
|
||||
fn old_position(window: &ron::Value, key: &str) -> Option<PointV37> {
|
||||
match field(window, key) {
|
||||
Some(ron::Value::Option(Some(p))) => point_value(p).and_then(PointV37::sane),
|
||||
// `None`, missing, and malformed all mean "no position"; corrupt positions elsewhere are
|
||||
// caught by `check`, which removes a file with non-finite values before this runs.
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn old_bool(window: &ron::Value, key: &str) -> bool {
|
||||
matches!(field(window, key), Some(ron::Value::Bool(true)))
|
||||
}
|
||||
|
||||
fn point_value(v: &ron::Value) -> Option<PointV37> {
|
||||
let x = field(v, "x").and_then(as_f32)?;
|
||||
let y = field(v, "y").and_then(as_f32)?;
|
||||
Some(PointV37 { x, y })
|
||||
}
|
||||
|
||||
/// Every float finite and within [`MAX_COORD`]; depth-limited (the file is untrusted).
|
||||
fn floats_sane(v: &ron::Value, depth: usize) -> Result<(), String> {
|
||||
if depth > 64 {
|
||||
@@ -86,6 +246,13 @@ fn as_f64(v: &ron::Value) -> Option<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
fn as_f32(v: &ron::Value) -> Option<f32> {
|
||||
as_f64(v).and_then(|f| {
|
||||
let f = f as f32;
|
||||
f.is_finite().then_some(f)
|
||||
})
|
||||
}
|
||||
|
||||
fn field<'a>(v: &'a ron::Value, name: &str) -> Option<&'a ron::Value> {
|
||||
match v {
|
||||
ron::Value::Map(m) => m.get(&ron::Value::String(name.into())),
|
||||
@@ -95,7 +262,8 @@ fn field<'a>(v: &'a ron::Value, name: &str) -> Option<&'a ron::Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{check, saved_position};
|
||||
use super::{DEFAULT_HEIGHT, DEFAULT_SIZE, WindowV37, backup_path, check, migrate_window, saved_position};
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
fn file(window: &str, zoom: &str) -> String {
|
||||
let egui = format!("(options:(zoom_factor:{zoom},max_passes:2),data:([(18446744073709551615,(ron:\"(x:1.0)\"))]))");
|
||||
@@ -103,6 +271,17 @@ mod tests {
|
||||
}
|
||||
|
||||
const WINDOW: &str = "(inner_position_pixels:Some((x:616.0,y:430.0)),fullscreen:false,inner_size_points:Some((x:1100.0,y:760.0)))";
|
||||
const WINDOW_WITH_OUTER: &str = "(inner_position_pixels:Some((x:2048.0,y:1265.0)),outer_position_pixels:Some((x:2048.0,y:1228.0)),fullscreen:false,maximized:false,inner_size_points:Some((x:880.0,y:480.0)))";
|
||||
|
||||
/// Read the window payload back as eframe 0.37 would.
|
||||
fn window_of(text: &str) -> WindowV37 {
|
||||
let kv: HashMap<String, String> = ron::from_str(text).expect("the migrated file is a RON map");
|
||||
ron::from_str(kv.get("window").expect("a window entry")).expect("0.37 WindowSettings shape")
|
||||
}
|
||||
|
||||
fn migrated(window: &str) -> String {
|
||||
migrate_window(file(window, "1.0")).expect("migratable").expect("rewritten")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_layout_is_kept() {
|
||||
@@ -122,13 +301,83 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_size_and_maximized_state_survive() {
|
||||
let text = migrated(WINDOW_WITH_OUTER);
|
||||
let window = window_of(&text);
|
||||
assert_eq!(window.normal_geometry.inner_size_points.x, 880.0);
|
||||
assert_eq!(window.normal_geometry.inner_size_points.y, 480.0);
|
||||
assert!(!window.fullscreen);
|
||||
assert!(!window.maximized);
|
||||
let maximized = migrated(&WINDOW.replace("fullscreen:false", "fullscreen:true,maximized:true"));
|
||||
assert!(window_of(&maximized).fullscreen && window_of(&maximized).maximized);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_size_uses_the_default_opening_size() {
|
||||
// A window entry with a position but no size migrates and keeps the app's opening size.
|
||||
let window = window_of(&migrated("(inner_position_pixels:Some((x:616.0,y:430.0)),fullscreen:false,maximized:false)"));
|
||||
assert_eq!(window.normal_geometry.inner_size_points.x, DEFAULT_SIZE);
|
||||
assert_eq!(window.normal_geometry.inner_size_points.y, DEFAULT_HEIGHT);
|
||||
// A window entry with no geometry fields at all is left alone: it is not a 0.36 window.
|
||||
assert_eq!(migrate_window(file("(fullscreen:false,maximized:false)", "1.0")), Ok(None));
|
||||
// So is a file with no window-like fields at all.
|
||||
assert_eq!(migrate_window(file("(something:1)", "1.0")), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_old_position_is_kept_only_on_windows() {
|
||||
let text = migrated(WINDOW_WITH_OUTER);
|
||||
let pos = window_of(&text).normal_geometry.outer_position_pixels;
|
||||
if cfg!(target_os = "windows") {
|
||||
let pos = pos.expect("the Windows physical outer position survives");
|
||||
assert_eq!((pos.x, pos.y), (2048.0, 1228.0));
|
||||
assert_eq!(window_of(&text).normal_geometry.scale_factor, 1.0);
|
||||
} else {
|
||||
assert!(pos.is_none(), "an old macOS/Linux position is not a restorable outer position");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_old_size_is_not_rewritten() {
|
||||
let bad = WINDOW.replace("(x:1100.0,y:760.0)", "(x:1100.0,y:0.0)");
|
||||
assert!(migrate_window(file(&bad, "1.0")).is_err());
|
||||
let huge = WINDOW.replace("(x:1100.0,y:760.0)", "(x:1100.0,y:9000000.0)");
|
||||
assert!(migrate_window(file(&huge, "1.0")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_migrated_file_is_left_alone() {
|
||||
let text = migrated(WINDOW);
|
||||
assert_eq!(migrate_window(text), Ok(None));
|
||||
// A 0.36 build accepts the entry, but its missing flat geometry defaults to None.
|
||||
// It cannot recover position or size from the nested 0.37 geometry.
|
||||
let kv: HashMap<String, String> = ron::from_str(&migrated(WINDOW)).unwrap();
|
||||
let old: OldWindow = ron::from_str(kv.get("window").unwrap()).unwrap();
|
||||
assert!(old.inner_position_pixels.is_none() && old.outer_position_pixels.is_none());
|
||||
assert!(old.inner_size_points.is_none(), "documented rollback loss of saved geometry");
|
||||
// Restoring the original backup restores both the old position and size.
|
||||
let restored: OldWindow = ron::from_str(WINDOW).unwrap();
|
||||
let position = restored.inner_position_pixels.unwrap();
|
||||
let size = restored.inner_size_points.unwrap();
|
||||
assert_eq!((position.x, position.y), (616.0, 430.0));
|
||||
assert_eq!((size.x, size.y), (1100.0, 760.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_window_position_is_detected() {
|
||||
// #4826: the position from the report (Linux Mint, window moved to the third monitor).
|
||||
let window = "(inner_position_pixels:Some((x:2048.0,y:1265.0)),outer_position_pixels:Some((x:2048.0,y:1228.0)),fullscreen:false,maximized:false,inner_size_points:Some((x:880.0,y:480.0)))";
|
||||
assert!(saved_position(&file(window, "1.0")));
|
||||
let no_position = "(inner_position_pixels:None,outer_position_pixels:None,fullscreen:false,maximized:false,inner_size_points:Some((x:880.0,y:480.0)))";
|
||||
// A 0.36 flat entry is not what eframe 0.37 restores (it would open at the OS default);
|
||||
// `sanitize` rewrites it before eframe runs, and the migrated nested value is detected.
|
||||
assert!(!saved_position(&file(WINDOW_WITH_OUTER, "1.0")), "an unmigrated flat entry is not a restorable position");
|
||||
// An old macOS inner position is not an outer position either.
|
||||
assert!(!saved_position(&file(WINDOW, "1.0")));
|
||||
let no_position =
|
||||
"(normal_geometry:(outer_position_pixels:None,scale_factor:1.0,inner_size_points:(x:880.0,y:480.0)),fullscreen:false,maximized:false)";
|
||||
assert!(!saved_position(&file(no_position, "1.0")));
|
||||
// The migrated nested geometry is what a 0.37 save holds (on Windows only, from the
|
||||
// migration; a later 0.37 save on macOS/Linux has one too and eframe restores it).
|
||||
let text = migrated(WINDOW_WITH_OUTER);
|
||||
assert_eq!(saved_position(&text), cfg!(target_os = "windows"));
|
||||
assert!(!saved_position(&format!("{{\"egui\":{:?}}}", "()")), "no window entry");
|
||||
for text in ["", "not ron {{{", "{\"window\":\"(((\"}"] {
|
||||
assert!(!saved_position(text), "{text:?}");
|
||||
@@ -148,7 +397,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_removes_only_a_bad_file() {
|
||||
fn sanitize_removes_only_a_bad_file_and_migrates_a_good_one() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-ui-state-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let good = dir.join("good.ron");
|
||||
@@ -159,7 +408,58 @@ mod tests {
|
||||
super::sanitize(Some(&bad));
|
||||
super::sanitize(Some(&dir.join("missing.ron")));
|
||||
super::sanitize(None);
|
||||
assert!(good.exists() && !bad.exists());
|
||||
assert!(!bad.exists());
|
||||
assert!(good.exists());
|
||||
// Migrated in place, with the one-time pre-0.37 backup beside it.
|
||||
let text = std::fs::read_to_string(&good).unwrap();
|
||||
assert!(window_of(&text).normal_geometry.inner_size_points.x == 1100.0);
|
||||
let backup = backup_path(&good);
|
||||
assert!(backup.exists(), "the pre-0.37 layout is kept for rollback");
|
||||
assert_eq!(std::fs::read_to_string(&backup).unwrap(), file(WINDOW, "1.0"));
|
||||
// A second run leaves both untouched.
|
||||
super::sanitize(Some(&good));
|
||||
assert_eq!(std::fs::read_to_string(&good).unwrap(), text);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backup_is_not_overwritten_by_a_later_migration() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-ui-state-backup-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ui.ron");
|
||||
std::fs::write(&path, file(WINDOW, "1.0")).unwrap();
|
||||
super::sanitize(Some(&path));
|
||||
let backup = backup_path(&path);
|
||||
let original = std::fs::read_to_string(&backup).unwrap();
|
||||
// Pretend a 0.36 run wrote its old schema again; the backup must stay the first one.
|
||||
std::fs::write(&path, file(&WINDOW.replace("1100.0", "1111.0"), "1.0")).unwrap();
|
||||
super::sanitize(Some(&path));
|
||||
assert_eq!(std::fs::read_to_string(&backup).unwrap(), original);
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("1111"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The 0.36 flat schema, kept to prove the new nested value is a one-way migration.
|
||||
#[derive(Default, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
#[allow(dead_code)]
|
||||
struct OldWindow {
|
||||
inner_position_pixels: Option<Point>,
|
||||
outer_position_pixels: Option<Point>,
|
||||
fullscreen: bool,
|
||||
maximized: bool,
|
||||
inner_size_points: Option<Point>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct Point {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backup_path_sits_beside_ui_ron() {
|
||||
assert_eq!(backup_path(&PathBuf::from("/tmp/x/ui.ron")), PathBuf::from("/tmp/x/ui.ron.pre-0.37"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Release checks through `craft-update`, the library every Craft App shares. Only public release
|
||||
//! metadata is requested.
|
||||
|
||||
use photocraft_engine::updates_cmds::{CheckFn, CheckResult, Release};
|
||||
|
||||
pub fn service() -> CheckFn {
|
||||
Box::new(|| {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("update check".into())
|
||||
.spawn(move || {
|
||||
let result = check();
|
||||
if let Err(e) = &result {
|
||||
log::warn!("Update check: {e}");
|
||||
}
|
||||
let _ = tx.send(result);
|
||||
})
|
||||
.map_err(|e| format!("Could not start update check: {e}"))?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
fn check() -> CheckResult {
|
||||
let http = craft_update::Http::new("PhotoCraft/Update")?;
|
||||
let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?;
|
||||
Ok(found.map(|release| Release { version: release.tag.trim_start_matches(['v', 'V']).to_string(), url: release.html_url }))
|
||||
}
|
||||
@@ -20,6 +20,11 @@
|
||||
//! the work area plus its own frame, clear of the taskbar. winit pins the client area to the work
|
||||
//! area either way (`WM_NCCALCSIZE`), so the app's pixels do not move.
|
||||
//!
|
||||
//! An auto-hidden taskbar reserves no work area, so that trim leaves the maximize covering the
|
||||
//! whole monitor, and the shell, taking it for a full-screen app, no longer reveals the taskbar
|
||||
//! when the pointer reaches its edge (#4845). On each edge with an auto-hidden taskbar the guard
|
||||
//! instead stops the window one pixel short of the monitor, as other custom-frame apps do.
|
||||
//!
|
||||
//! The Windows calls go through safe `winsafe` wrappers; the workspace forbids `unsafe`, and
|
||||
//! winsafe can't wrap a raw handle without it, so the window is found by its handle instead.
|
||||
|
||||
@@ -29,7 +34,20 @@ pub use platform::service;
|
||||
mod platform {
|
||||
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
|
||||
use photocraft_ui_egui::WindowFrameFn;
|
||||
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
|
||||
use winsafe::prelude::Handle;
|
||||
use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co};
|
||||
|
||||
/// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive.
|
||||
type Rect = (i32, i32, i32, i32);
|
||||
|
||||
/// A monitor edge.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Edge {
|
||||
Left,
|
||||
Top,
|
||||
Right,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
/// A guard that keeps the window borderless each frame, or `None` when the app uses the
|
||||
/// system title bar (the window is decorated) or its handle can't be found.
|
||||
@@ -99,8 +117,11 @@ mod platform {
|
||||
return;
|
||||
};
|
||||
let (m, w) = (mi.rcMonitor, mi.rcWork);
|
||||
let Some((left, top, right, bottom)) =
|
||||
clamped_rect((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom))
|
||||
let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom));
|
||||
// The taskbars (a couple of `FindWindowEx` calls) are only looked up while the window
|
||||
// covers the whole monitor, which a trimmed maximize no longer does.
|
||||
let Some((left, top, right, bottom)) = clamped_rect(rect, monitor, work)
|
||||
.or_else(|| covers(rect, monitor).then(|| short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -153,6 +174,69 @@ mod platform {
|
||||
(corrected != rect).then_some(corrected)
|
||||
}
|
||||
|
||||
/// Whether `rect` reaches every edge of `monitor`: what the shell takes for a full-screen app.
|
||||
fn covers(rect: Rect, monitor: Rect) -> bool {
|
||||
rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3
|
||||
}
|
||||
|
||||
/// The edges of `monitor` that have a taskbar (the primary `Shell_TrayWnd` or a secondary
|
||||
/// monitor's `Shell_SecondaryTrayWnd`), shown or hidden.
|
||||
fn taskbar_edges(monitor: Rect) -> Vec<Edge> {
|
||||
let mut edges = Vec::new();
|
||||
for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] {
|
||||
let mut after: Option<HWND> = None;
|
||||
// One taskbar per monitor; the bound only guards against a misbehaving shell.
|
||||
for _ in 0..64 {
|
||||
let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else {
|
||||
break;
|
||||
};
|
||||
if let Ok(r) = tray.GetWindowRect() {
|
||||
edges.extend(taskbar_edge((r.left, r.top, r.right, r.bottom), monitor));
|
||||
}
|
||||
after = Some(tray);
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
/// The edge of `monitor` a taskbar with rect `taskbar` sits on: the one nearest its centre,
|
||||
/// or `None` when it is on another monitor. An auto-hidden taskbar is parked mostly past its
|
||||
/// edge with a sliver left on screen, so its centre may lie outside the monitor.
|
||||
fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3));
|
||||
let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3));
|
||||
if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb {
|
||||
return None;
|
||||
}
|
||||
// Doubled centre and distances, so nothing rounds.
|
||||
let (cx, cy) = (tl + tr, tt + tb);
|
||||
[(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)]
|
||||
.into_iter()
|
||||
.min_by_key(|&(_, distance)| distance)
|
||||
.map(|(edge, _)| edge)
|
||||
}
|
||||
|
||||
/// A maximize covering its monitor, trimmed to stop one pixel short of each edge where a
|
||||
/// taskbar reserves no work area (it auto-hides), so the shell still reveals it there.
|
||||
/// `None` when there is nothing to trim.
|
||||
fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option<Rect> {
|
||||
if !covers(rect, monitor) {
|
||||
return None;
|
||||
}
|
||||
let (mut l, mut t, mut r, mut b) = rect;
|
||||
for edge in taskbars {
|
||||
match edge {
|
||||
Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?,
|
||||
Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?,
|
||||
Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?,
|
||||
Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let trimmed = (l, t, r, b);
|
||||
(l < r && t < b && trimmed != rect).then_some(trimmed)
|
||||
}
|
||||
|
||||
/// `style` without the OS title bar and frame (`WS_CAPTION`, which already includes
|
||||
/// `WS_BORDER`). The sizing border (`WS_THICKFRAME`) stays, so edge resizing and Aero snap
|
||||
/// keep working, as they did with winit 0.27's undecorated windows.
|
||||
@@ -162,7 +246,7 @@ mod platform {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{borderless, clamped_rect};
|
||||
use super::{Edge, borderless, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
use winsafe::co;
|
||||
|
||||
#[test]
|
||||
@@ -221,6 +305,35 @@ mod platform {
|
||||
assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "dragged");
|
||||
assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "half-screen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_leaves_a_pixel_strip_on_an_auto_hidden_taskbar_edge() {
|
||||
// #4845: an auto-hidden taskbar reserves no work area.
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
let rect = (-8, -8, 1928, 1088);
|
||||
for (edge, expected) in
|
||||
[(Edge::Bottom, (-8, -8, 1928, 1079)), (Edge::Top, (-8, 1, 1928, 1088)), (Edge::Left, (1, -8, 1928, 1088)), (Edge::Right, (-8, -8, 1919, 1088))]
|
||||
{
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected));
|
||||
assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed");
|
||||
}
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar");
|
||||
// A taskbar that reserves its work area is the clamp's job.
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None);
|
||||
assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taskbar_sits_on_the_monitor_edge_nearest_its_centre() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown");
|
||||
assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden");
|
||||
assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top));
|
||||
assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left));
|
||||
assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right));
|
||||
assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor");
|
||||
assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
//! `--control` setup failures must exit non-zero (#1816): a launcher that sees
|
||||
//! status 0 believes the control server is running when it is not.
|
||||
//!
|
||||
//! These tests run the real binary as a subprocess and assert the exit code,
|
||||
//! covering both failure paths in `main.rs`: control authentication and the
|
||||
//! automation workspace.
|
||||
|
||||
/// A syntactically valid 64-hex-char token, so the workspace test reaches the
|
||||
/// workspace check instead of failing on token validation first.
|
||||
const VALID_TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// Run `photocraft` with the given arguments in an isolated config dir and
|
||||
/// return the exit status and stderr. Each call gets its own config dir (tests run in
|
||||
/// parallel), and no display variables, so a regression fails fast instead of opening a window.
|
||||
fn run_photocraft(args: &[&str]) -> (std::process::ExitStatus, String) {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
|
||||
.args(args)
|
||||
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
|
||||
// Isolate from the host environment so the test is reproducible.
|
||||
.env_remove("PHOTOCRAFT_CONTROL_PORT")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.output()
|
||||
.expect("failed to run photocraft binary");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
(output.status, String::from_utf8_lossy(&output.stderr).into_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_control_token_exits_with_status_2() {
|
||||
// `validate_token` rejects a token that is not exactly 64 hex characters.
|
||||
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", "invalid"]);
|
||||
assert_eq!(status.code(), Some(2), "invalid control token must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure control authentication"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_token_and_token_file_exits_with_status_2() {
|
||||
// `server_token` rejects the combination of a supplied token and a token file.
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-token-file-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let token_file = dir.join("token.txt");
|
||||
std::fs::write(&token_file, VALID_TOKEN).unwrap();
|
||||
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--control-token-file", token_file.to_str().unwrap()]);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert_eq!(status.code(), Some(2), "token + token file must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure control authentication"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_automation_read_root_exits_with_status_2() {
|
||||
// `AuthorizedWorkspace::new` fails when the read root does not exist.
|
||||
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-read-root", "/nonexistent/photocraft-test-path"]);
|
||||
assert_eq!(status.code(), Some(2), "missing read root must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_automation_write_root_exits_with_status_2() {
|
||||
// `AuthorizedWorkspace::new` fails when the write root does not exist.
|
||||
let (status, stderr) = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-write-root", "/nonexistent/photocraft-test-path"]);
|
||||
assert_eq!(status.code(), Some(2), "missing write root must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
These files are **schema probes**, not recorded machine saves.
|
||||
|
||||
`ui-0.14.ron`, `ui-0.15.ron` and `ui-0.37.ron` are minimal payloads reconstructed from the
|
||||
documented eframe/egui layouts. They exercise `apps/photocraft/src/ui_state.rs` (the flat
|
||||
window entry versus the nested `normal_geometry` entry) only. They do not prove that eframe
|
||||
and egui deserialize a real `Memory` or `PanelState`; a captured 0.14/0.15/0.37 `ui.ron`
|
||||
would be needed for that, with the machine-specific data reviewed first.
|
||||
@@ -0,0 +1 @@
|
||||
{"window":"(inner_position_pixels:Some((x:616.0,y:430.0)),outer_position_pixels:None,fullscreen:false,maximized:false,inner_size_points:Some((x:1100.0,y:760.0)))","egui":"()"}
|
||||
@@ -0,0 +1 @@
|
||||
{"window":"(inner_position_pixels:None,outer_position_pixels:Some((x:2048.0,y:1228.0)),fullscreen:false,maximized:true,inner_size_points:Some((x:1440.0,y:900.0)))","egui":"()"}
|
||||
@@ -0,0 +1 @@
|
||||
{"window":"(normal_geometry:(outer_position_pixels:None,scale_factor:2.0,inner_size_points:(x:1440.0,y:900.0)),fullscreen:false,maximized:false)","egui":"()"}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! `photocraft --help` and unknown options must not open the window (#6431): before the fix,
|
||||
//! any argument the loop didn't know was taken as a file, so `--help` or a typo such as
|
||||
//! `--safegpu` launched the GUI and logged "Couldn't open --help".
|
||||
//!
|
||||
//! These run the real binary, and every case must exit before the window opens: Windows and
|
||||
//! macOS runners have a desktop, so a launch that gets that far hangs until the test times out.
|
||||
//! Cases whose arguments are valid add a usage error before them: `--control-token` with
|
||||
//! `--control-token-file` is only checked once every argument is read (and only with `--control`),
|
||||
//! so stderr shows how the other arguments were taken.
|
||||
|
||||
/// The variables the command line reads: a test that wants one sets it.
|
||||
const VARS: [&str; 6] = [
|
||||
"PHOTOCRAFT_CONTROL_PORT",
|
||||
"PHOTOCRAFT_CONTROL_TOKEN",
|
||||
"PHOTOCRAFT_CONTROL_TOKEN_FILE",
|
||||
"PHOTOCRAFT_AUTOMATION_READ_ROOT",
|
||||
"PHOTOCRAFT_AUTOMATION_WRITE_ROOT",
|
||||
"PHOTOCRAFT_IN_WINDOW_MENUS",
|
||||
];
|
||||
|
||||
/// A usage error found only after every argument is read.
|
||||
const LATE_ERROR: [&str; 6] = ["--control", "0", "--control-token", "abcd", "--control-token-file", "token"];
|
||||
|
||||
/// How a run of `photocraft` ended.
|
||||
struct Run {
|
||||
status: std::process::ExitStatus,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// Run `photocraft` with `args` and `vars` in an isolated config dir.
|
||||
fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-usage-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut cmd = std::process::Command::new(crate::binary());
|
||||
for var in VARS {
|
||||
cmd.env_remove(var);
|
||||
}
|
||||
let output = cmd
|
||||
.args(args)
|
||||
.envs(vars.iter().copied())
|
||||
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.output()
|
||||
.expect("failed to run photocraft binary");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
Run { status: output.status, stdout: String::from_utf8_lossy(&output.stdout).into_owned(), stderr: String::from_utf8_lossy(&output.stderr).into_owned() }
|
||||
}
|
||||
|
||||
fn run_photocraft(args: &[&str]) -> Run {
|
||||
run_with(args, &[])
|
||||
}
|
||||
|
||||
/// [`LATE_ERROR`] then `args`: exit 2, and the stderr.
|
||||
fn late_error(args: &[&str], vars: &[(&str, &str)]) -> String {
|
||||
let Run { status, stdout, stderr } = run_with(&[&LATE_ERROR[..], args].concat(), vars);
|
||||
assert_eq!(status.code(), Some(2), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("cannot be used with"), "{args:?}: {stderr}");
|
||||
assert!(stdout.is_empty(), "{args:?}: {stdout}");
|
||||
stderr
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_and_exits_0() {
|
||||
for flag in ["--help", "-h"] {
|
||||
let Run { status, stdout, stderr } = run_photocraft(&[flag]);
|
||||
assert_eq!(status.code(), Some(0), "{flag} must exit 0, stderr: {stderr}");
|
||||
assert!(stdout.contains("Usage: photocraft"), "{flag} stdout: {stdout}");
|
||||
for option in ["--safe-gpu", "--new-instance", "--control <PORT>", "--version", "`--`", "PHOTOCRAFT_AUTOMATION_READ_ROOT", "PHOTOCRAFT_NEW_INSTANCE"] {
|
||||
assert!(stdout.contains(option), "{flag} usage must list {option}: {stdout}");
|
||||
}
|
||||
assert!(!stderr.contains("Couldn't open"), "{flag} was taken as a file: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_wins_over_later_arguments() {
|
||||
let Run { status, stdout, .. } = run_photocraft(&["--help", "picture.psd", "--safegpu"]);
|
||||
assert_eq!(status.code(), Some(0));
|
||||
assert!(stdout.contains("Usage: photocraft"), "stdout: {stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_prints_the_long_version() {
|
||||
let Run { status, stdout, .. } = run_photocraft(&["--version", "--safegpu"]);
|
||||
assert_eq!(status.code(), Some(0));
|
||||
assert_eq!(stdout, format!("photocraft {}\n", photocraft_engine::build_info::long_version()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_exit_2_naming_them() {
|
||||
for (args, named) in [
|
||||
(&["--safegpu"][..], "unexpected argument '--safegpu'"),
|
||||
(&["-x"][..], "unexpected argument '-x'"),
|
||||
(&["--help=yes"][..], "unexpected value 'yes' for '--help'"),
|
||||
// An unknown flag after a bad value is reported first: clap drops the pending value's error.
|
||||
(&["--control", "nope", "--safegpu"][..], "unexpected argument '--safegpu'"),
|
||||
(&["--control", "nope"][..], "invalid value 'nope' for '--control <PORT>'"),
|
||||
] {
|
||||
let Run { status, stdout, stderr } = run_photocraft(args);
|
||||
assert_eq!(status.code(), Some(2), "{args:?} must be a usage error, stderr: {stderr}");
|
||||
assert!(stderr.contains(named), "stderr: {stderr}");
|
||||
assert!(stderr.contains("--help"), "stderr should point at --help: {stderr}");
|
||||
assert!(stdout.is_empty(), "stdout: {stdout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arguments_after_double_dash_are_files() {
|
||||
// `--` ends the options: `--help` and `-x` after it are file names, so neither prints usage
|
||||
// nor is an unknown option; only the late error is reported.
|
||||
let stderr = late_error(&["--", "--help", "-x"], &[]);
|
||||
assert!(!stderr.contains("unexpected"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_process_serial_number_is_still_ignored() {
|
||||
// Old macOS passes `-psn_<n>` when launching from Finder; it is neither a file nor an error.
|
||||
let stderr = late_error(&["-psn_0_12345"], &[]);
|
||||
assert!(!stderr.contains("unexpected"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instance_is_a_known_option() {
|
||||
let stderr = late_error(&["--new-instance"], &[]);
|
||||
assert!(!stderr.contains("unexpected"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
/// The variables stand in for their flags: a flag wins, an empty variable counts as unset, a bad
|
||||
/// value is a usage error naming the variable, and a flag without its value is still an error
|
||||
/// when its variable is set (#6429).
|
||||
#[test]
|
||||
fn variables_are_the_flags_fallbacks() {
|
||||
let Run { status, stderr, .. } = run_with(&[], &[("PHOTOCRAFT_CONTROL_PORT", "nope")]);
|
||||
assert_eq!(status.code(), Some(2), "stderr: {stderr}");
|
||||
assert!(stderr.contains("invalid value 'nope' for 'PHOTOCRAFT_CONTROL_PORT'"), "stderr: {stderr}");
|
||||
// With the flag (in LATE_ERROR), the variable is never read.
|
||||
let stderr = late_error(&[], &[("PHOTOCRAFT_CONTROL_PORT", "nope")]);
|
||||
assert!(!stderr.contains("PHOTOCRAFT_CONTROL_PORT"), "stderr: {stderr}");
|
||||
// The variable turns the control server on as the flag does, so the token pair is checked.
|
||||
let Run { status, stderr, .. } = run_with(&LATE_ERROR[2..], &[("PHOTOCRAFT_CONTROL_PORT", "0")]);
|
||||
assert_eq!(status.code(), Some(2), "stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot be used with"), "stderr: {stderr}");
|
||||
let Run { status, stderr, .. } = run_with(&["--automation-read-root"], &[("PHOTOCRAFT_AUTOMATION_READ_ROOT", "/env/read")]);
|
||||
assert_eq!(status.code(), Some(2), "stderr: {stderr}");
|
||||
assert!(stderr.contains("a value is required for '--automation-read-root <DIR>'"), "stderr: {stderr}");
|
||||
// The other half of the token pair from a variable is the same either/or error, naming it
|
||||
// but never showing the token.
|
||||
let token = "a".repeat(64);
|
||||
let Run { status, stderr, .. } = run_with(&["--control", "0", "--control-token-file", "token"], &[("PHOTOCRAFT_CONTROL_TOKEN", token.as_str())]);
|
||||
assert_eq!(status.code(), Some(2), "stderr: {stderr}");
|
||||
assert!(stderr.contains("PHOTOCRAFT_CONTROL_TOKEN") && stderr.contains("cannot be used with") && !stderr.contains(&token), "stderr: {stderr}");
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! `--control` setup failures must exit non-zero (#1816): a launcher that sees
|
||||
//! status 0 believes the control server is running when it is not.
|
||||
//!
|
||||
//! These tests run the real binary as a subprocess and assert the exit code,
|
||||
//! covering control authentication, the automation workspace and listener binding.
|
||||
|
||||
/// A syntactically valid 64-hex-char token, so the workspace test reaches the
|
||||
/// workspace check instead of failing on token validation first.
|
||||
const VALID_TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// How a run of `photocraft` ended.
|
||||
struct Run {
|
||||
status: std::process::ExitStatus,
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// Run `photocraft` with the given arguments in an isolated config dir and
|
||||
/// return how it ended. Each call gets its own config dir (tests run in
|
||||
/// parallel), and no display variables, so a regression fails fast instead of opening a window.
|
||||
fn run_photocraft(args: &[&str]) -> Run {
|
||||
run_with(args, &[])
|
||||
}
|
||||
|
||||
/// [`run_photocraft`], with `vars` set.
|
||||
fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut child = std::process::Command::new(crate::binary())
|
||||
.args(args)
|
||||
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
|
||||
// Isolate from the host environment so the test is reproducible.
|
||||
.env_remove("PHOTOCRAFT_CONTROL_PORT")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.envs(vars.iter().copied())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("failed to run photocraft binary");
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
};
|
||||
let output = child.wait_with_output().unwrap();
|
||||
let gpu_started = dir.join("gpu-starting.json").exists();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(!timed_out, "PhotoCraft did not exit: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(!gpu_started, "control setup errors must exit before GPU startup");
|
||||
Run { status: output.status, stderr: String::from_utf8_lossy(&output.stderr).into_owned() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_occupied_control_port_exits_with_status_2() {
|
||||
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = held.local_addr().unwrap().port().to_string();
|
||||
let Run { status, stderr } = run_photocraft(&["--control", &port, "--control-token", VALID_TOKEN]);
|
||||
assert_eq!(status.code(), Some(2), "occupied control port must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains(&format!("failed to bind 127.0.0.1:{port}")), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_control_token_exits_with_status_2() {
|
||||
// `validate_token` rejects a token that is not exactly 64 hex characters.
|
||||
let Run { status, stderr } = run_photocraft(&["--control", "0", "--control-token", "invalid"]);
|
||||
assert_eq!(status.code(), Some(2), "invalid control token must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure control authentication"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_token_and_token_file_exits_with_status_2() {
|
||||
// The command line rejects a supplied token together with a token file (#7071), before
|
||||
// `server_token` would.
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-token-file-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let token_file = dir.join("token.txt");
|
||||
std::fs::write(&token_file, VALID_TOKEN).unwrap();
|
||||
let Run { status, stderr } = run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--control-token-file", token_file.to_str().unwrap()]);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert_eq!(status.code(), Some(2), "token + token file must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot be used with"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_automation_read_root_exits_with_status_2() {
|
||||
// `AuthorizedWorkspace::new` fails when the read root does not exist.
|
||||
let Run { status, stderr } =
|
||||
run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-read-root", "/nonexistent/photocraft-test-path"]);
|
||||
assert_eq!(status.code(), Some(2), "missing read root must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_automation_write_root_exits_with_status_2() {
|
||||
// `AuthorizedWorkspace::new` fails when the write root does not exist.
|
||||
let Run { status, stderr } =
|
||||
run_photocraft(&["--control", "0", "--control-token", VALID_TOKEN, "--automation-write-root", "/nonexistent/photocraft-test-path"]);
|
||||
assert_eq!(status.code(), Some(2), "missing write root must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_roots_come_from_the_environment_too() {
|
||||
for var in ["PHOTOCRAFT_AUTOMATION_READ_ROOT", "PHOTOCRAFT_AUTOMATION_WRITE_ROOT"] {
|
||||
let Run { status, stderr } = run_with(&["--control", "0", "--control-token", VALID_TOKEN], &[(var, "/nonexistent/photocraft-test-path")]);
|
||||
assert_eq!(status.code(), Some(2), "{var}: missing root must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "{var}: stderr: {stderr}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod command_line_usage;
|
||||
mod control_exit_code;
|
||||
mod startup_without_display;
|
||||
|
||||
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
|
||||
fn binary() -> std::ffi::OsString {
|
||||
std::env::var_os("NEXTEST_BIN_EXE_photocraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft").into())
|
||||
}
|
||||
@@ -30,7 +30,7 @@ fn missing_display_preserves_existing_gpu_crash_evidence() {
|
||||
}
|
||||
|
||||
fn launch_without_display(dir: &std::path::Path) -> String {
|
||||
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
|
||||
let output = std::process::Command::new(crate::binary())
|
||||
.env("PHOTOCRAFT_CONFIG_DIR", dir)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
@@ -17,8 +17,8 @@ Exactly three colours:
|
||||
## Geometry
|
||||
|
||||
A 512-unit tile (`viewBox="0 0 512 512"`), rounded square with `rx=112`, no border. The macOS
|
||||
renders pad it onto Apple's 824/1024 icon grid; the Windows and Linux renders crop 22 units off
|
||||
each side so the figure reads at 16–48 px.
|
||||
renders pad it onto Apple's 824/1024 icon grid; the Windows and Linux renders use the whole tile,
|
||||
as the other Crafting Apps do.
|
||||
|
||||
## Provenance
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 784 B After Width: | Height: | Size: 812 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 168 KiB After Width: | Height: | Size: 154 KiB |
|
Before Width: | Height: | Size: 6.2 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 90 KiB |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M3 20h18" />
|
||||
<rect x="5" y="4" width="5" height="12" rx="1" />
|
||||
<rect x="14" y="9" width="5" height="7" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 416 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M12 3v18" />
|
||||
<rect x="5" y="5" width="14" height="5" rx="1" />
|
||||
<rect x="8" y="14" width="8" height="5" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 416 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M4 3v18" />
|
||||
<rect x="8" y="5" width="12" height="5" rx="1" />
|
||||
<rect x="8" y="14" width="7" height="5" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 415 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M20 3v18" />
|
||||
<rect x="4" y="5" width="12" height="5" rx="1" />
|
||||
<rect x="9" y="14" width="7" height="5" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 416 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M3 4h18" />
|
||||
<rect x="5" y="8" width="5" height="12" rx="1" />
|
||||
<rect x="14" y="8" width="5" height="7" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 415 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M3 12h18" />
|
||||
<rect x="5" y="5" width="5" height="14" rx="1" />
|
||||
<rect x="14" y="8" width="5" height="8" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 416 B |
@@ -0,0 +1,19 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M4 7h16" />
|
||||
<rect x="7" y="2" width="10" height="3" rx="1" />
|
||||
<path d="M4 14h16" />
|
||||
<rect x="7" y="9" width="10" height="3" rx="1" />
|
||||
<path d="M4 21h16" />
|
||||
<rect x="7" y="16" width="10" height="3" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 516 B |
@@ -0,0 +1,22 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<rect x="2" y="6" width="4" height="12" rx="1" />
|
||||
<path d="M4 2v2" />
|
||||
<path d="M4 20v2" />
|
||||
<rect x="10" y="6" width="4" height="12" rx="1" />
|
||||
<path d="M12 2v2" />
|
||||
<path d="M12 20v2" />
|
||||
<rect x="18" y="6" width="4" height="12" rx="1" />
|
||||
<path d="M20 2v2" />
|
||||
<path d="M20 20v2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 585 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
|
||||
<path d="M3 4v16" />
|
||||
<path d="M21 4v16" />
|
||||
<rect x="9" y="7" width="6" height="10" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 387 B |