AI media harness for planning, generating, and editing locally
TypeScript
Add Linux desktop build and packaging
Bitti49f3833e3f62
diff --git a/package.cmd b/package.cmdindex 2876d0a..a8e21f5 100644--- a/package.cmd+++ b/package.cmd@@ -58,6 +58,7 @@ set "OUTPUT_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-portable"set "WORKER_ZIP=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker.zip"set "WORKER_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker"set "LINUX_WORKER_NAME=Slopus-%APP_VERSION%-linux-x64-worker.tar.gz"+set "LINUX_APP_STEM=Slopus-%APP_VERSION%-linux-x64"echo.echo [1/5] Installing locked frontend dependencies...@@ -119,6 +120,7 @@ if errorlevel 1 goto :failpowershell.exe -NoProfile -NonInteractive -Command "$ErrorActionPreference='Stop'; Compress-Archive -Path (Join-Path $env:OUTPUT_DIR '*') -DestinationPath $env:OUTPUT_ZIP -CompressionLevel Optimal -Force" || goto :failcall :package_worker || goto :failcall :package_linux_worker || goto :fail+call :package_linux_app || goto :failecho.echo Package complete.@@ -127,6 +129,9 @@ echo %OUTPUT_DIR%\echo %WORKER_ZIP%echo %WORKER_DIR%\if exist "%ARTIFACTS_DIR%\%LINUX_WORKER_NAME%" echo %ARTIFACTS_DIR%\%LINUX_WORKER_NAME%+if exist "%ARTIFACTS_DIR%\%LINUX_APP_STEM%.deb" echo %ARTIFACTS_DIR%\%LINUX_APP_STEM%.deb+if exist "%ARTIFACTS_DIR%\%LINUX_APP_STEM%.rpm" echo %ARTIFACTS_DIR%\%LINUX_APP_STEM%.rpm+if exist "%ARTIFACTS_DIR%\%LINUX_APP_STEM%.AppImage" echo %ARTIFACTS_DIR%\%LINUX_APP_STEM%.AppImageecho.echo The unpacked folder beside the zip is this build - run it straight fromecho there. It is rebuilt from scratch on every package run.@@ -176,6 +181,17 @@ wsl.exe --cd "%ROOT_DIR%" -e bash scripts/package-linux-worker.sh "%APP_VERSION%echo Linux: %LINUX_WORKER_NAME%exit /b 0+:package_linux_app+rem The Linux desktop app, built in WSL around the frontend in dist\ and+rem packed unsigned as .deb, .rpm and AppImage. See scripts\package-linux-app.sh.+where.exe wsl.exe >nul 2>nul || (+ echo Linux app: skipped - WSL was not found. Releases require it.+ exit /b 0+)+wsl.exe --cd "%ROOT_DIR%" -e bash scripts/package-linux-app.sh "%APP_VERSION%" artifacts || exit /b 1+echo Linux app: %LINUX_APP_STEM%.deb, .rpm and .AppImage+exit /b 0+:write_readme> "%~1" echo Slopus %APP_VERSION% ^(windows-%PACKAGE_ARCH%, portable^)>>"%~1" echo.diff --git a/release.cmd b/release.cmdindex 914f7b7..dd791c4 100644--- a/release.cmd+++ b/release.cmd@@ -81,6 +81,8 @@ set "OUTPUT_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-portable"set "WORKER_ZIP=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker.zip"set "WORKER_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker"set "LINUX_WORKER_NAME=Slopus-%APP_VERSION%-linux-x64-worker.tar.gz"+set "LINUX_APP_STEM=Slopus-%APP_VERSION%-linux-x64"+set "OUTPUT_APPIMAGE=%ARTIFACTS_DIR%\%LINUX_APP_STEM%.AppImage"echo.echo [1/6] Installing locked frontend dependencies...@@ -144,6 +146,9 @@ if defined MSI_SRC (echo MSI: not produced - skipping.)+rem The manifest offers the signed AppImage to Linux installs, so build it first.+call :package_linux_app || goto :fail+node scripts\updater-manifest.mjs || goto :failrem Portable layout: the executable plus the generation runtime beside it. The@@ -184,6 +189,10 @@ echo %OUTPUT_DIR%\echo %WORKER_ZIP%echo %WORKER_DIR%\if exist "%ARTIFACTS_DIR%\%LINUX_WORKER_NAME%" echo %ARTIFACTS_DIR%\%LINUX_WORKER_NAME%+echo %ARTIFACTS_DIR%\%LINUX_APP_STEM%.deb+echo %ARTIFACTS_DIR%\%LINUX_APP_STEM%.rpm+echo %OUTPUT_APPIMAGE%+echo %OUTPUT_APPIMAGE%.sigecho.echo The unpacked folder beside the zip is this build - run it straight fromecho there. It is rebuilt from scratch on every package run.@@ -252,6 +261,24 @@ wsl.exe --cd "%ROOT_DIR%" -e bash scripts/package-linux-worker.sh "%APP_VERSION%echo Linux: %LINUX_WORKER_NAME%exit /b 0+:package_linux_app+rem The Linux desktop app is built inside WSL around the frontend that the+rem Windows build just wrote to dist\, as .deb, .rpm and a signed AppImage.+rem WSLENV hands the signing key to WSL. See scripts\package-linux-app.sh.+where.exe wsl.exe >nul 2>nul || (+ echo ERROR: WSL was not found. Releases include the Linux app, which is built in WSL.+ echo Install WSL with Ubuntu and Rust, then retry.+ exit /b 1+)+if defined WSLENV (+ set "WSLENV=%WSLENV%:TAURI_SIGNING_PRIVATE_KEY:TAURI_SIGNING_PRIVATE_KEY_PASSWORD"+) else (+ set "WSLENV=TAURI_SIGNING_PRIVATE_KEY:TAURI_SIGNING_PRIVATE_KEY_PASSWORD"+)+wsl.exe --cd "%ROOT_DIR%" -e bash scripts/package-linux-app.sh "%APP_VERSION%" artifacts || exit /b 1+echo Linux app: %LINUX_APP_STEM%.deb, .rpm and .AppImage+exit /b 0+:write_readme> "%~1" echo Slopus %APP_VERSION% ^(windows-%PACKAGE_ARCH%, portable^)>>"%~1" echo.diff --git a/scripts/package-linux-app.sh b/scripts/package-linux-app.shnew file mode 100644index 0000000..ab0b926--- /dev/null+++ b/scripts/package-linux-app.sh@@ -0,0 +1,119 @@+#!/usr/bin/env bash+# Builds the Linux desktop app and its packages: .deb, .rpm and AppImage.+#+# bash scripts/package-linux-app.sh <version> <artifacts-dir>+#+# Runs on x86_64 Linux, including WSL, where package.cmd and release.cmd call+# it after their Windows build. The frontend in dist/ is platform independent,+# so it is reused rather than rebuilt (WSL usually has no Linux Node.js); the+# Tauri CLI comes from cargo. Cargo builds on the Linux filesystem, as in+# package-linux-worker.sh.+#+# With TAURI_SIGNING_PRIVATE_KEY set (a key, a Linux path or a Windows path)+# the AppImage is signed for the updater and its .sig is written beside it.+# Without one the packages are built unsigned and the AppImage cannot be+# offered as an update.+set -euo pipefail++if (($# != 2)); then+ printf 'Usage: bash %s <version> <artifacts-dir>\n' "$0" >&2+ exit 2+fi+version=$1+artifacts=$2+root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)+fail() { printf 'package-linux-app: %s\n' "$*" >&2; exit 1; }++if [[ $(uname -s) != Linux || $(uname -m) != x86_64 ]]; then+ printf 'package-linux-app: run on x86_64 Linux (including WSL).\n' >&2+ exit 2+fi+# rustup installs into ~/.cargo; a non-login WSL shell has not sourced it.+if ! command -v cargo >/dev/null && [[ -f $HOME/.cargo/env ]]; then+ # shellcheck source=/dev/null+ source "$HOME/.cargo/env"+fi+command -v cargo >/dev/null || fail 'cargo was not found. Install Rust in this Linux environment:+ curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal'++# Tauri's Linux build libraries, and the tools the bundler shells out to.+missing=()+for module in webkit2gtk-4.1 gtk+-3.0 librsvg-2.0 ayatana-appindicator3-0.1; do+ pkg-config --exists "$module" 2>/dev/null || missing+=("$module")+done+for tool in file patchelf; do+ command -v "$tool" >/dev/null || missing+=("$tool")+done+if ((${#missing[@]})); then+ fail "missing build dependencies: ${missing[*]}. On Ubuntu or Debian install them with:+ sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev build-essential file patchelf"+fi++runtime="$root/lib/slopfab/libslopfab.so"+if [[ $(head -c 4 "$runtime" 2>/dev/null | od -An -c | tr -d ' ') != '177ELF' ]]; then+ fail "$runtime is missing or a Git LFS pointer. Run git lfs pull."+fi++cargo_version=$(sed -n '/^\[workspace.package\]/,/^\[/s/^version *= *"\(.*\)"/\1/p' "$root/src-tauri/Cargo.toml")+[[ $cargo_version == "$version" ]] || fail "version $version does not match src-tauri/Cargo.toml ($cargo_version)."++# The Windows build ran `npm run build` moments ago; refuse a missing frontend+# rather than embed an old one silently.+[[ -f $root/dist/index.html ]] || fail 'dist/ has no built frontend. Run npm run build first (package.cmd does).'+asset=$(find "$root/dist/assets" -maxdepth 1 -name '*.js' -printf '%f\n' 2>/dev/null | head -n 1)+[[ -n $asset ]] || fail 'dist/assets has no JavaScript bundle.'++# The same CLI version as package-lock.json, installed once per version.+cli_version=$(sed -n '/"node_modules\/@tauri-apps\/cli": {/,/}/s/.*"version": "\(.*\)".*/\1/p' "$root/package-lock.json" | head -n 1)+[[ -n $cli_version ]] || fail 'could not read the @tauri-apps/cli version from package-lock.json.'+tools="$HOME/.cache/slopus/tauri-cli-$cli_version"+if [[ ! -x $tools/bin/cargo-tauri ]]; then+ printf 'package-linux-app: installing tauri-cli %s (once)...\n' "$cli_version"+ cargo install tauri-cli --version "=$cli_version" --locked --root "$tools"+fi++config='{"build":{"beforeBuildCommand":""}}'+if [[ -n ${TAURI_SIGNING_PRIVATE_KEY:-} ]]; then+ # release.cmd passes the Windows path of the key file through WSLENV.+ if [[ $TAURI_SIGNING_PRIVATE_KEY =~ ^[A-Za-z]:[\\/] ]] && command -v wslpath >/dev/null; then+ TAURI_SIGNING_PRIVATE_KEY=$(wslpath -u "$TAURI_SIGNING_PRIVATE_KEY")+ export TAURI_SIGNING_PRIVATE_KEY+ fi+ signed=1+else+ config='{"build":{"beforeBuildCommand":""},"bundle":{"createUpdaterArtifacts":false}}'+ signed=0+fi++target_dir=${SLOPUS_LINUX_TARGET_DIR:-"$HOME/.cache/slopus/linux-app-target"}+bundle="$target_dir/release/bundle"+rm -rf -- "$bundle"+(+ cd -- "$root"+ # The AppImage tools are themselves AppImages; WSL has no FUSE to mount them.+ CARGO_TARGET_DIR=$target_dir APPIMAGE_EXTRACT_AND_RUN=1 NO_STRIP=true \+ "$tools/bin/cargo-tauri" build --ci --bundles deb,rpm,appimage --config "$config"+)++binary="$target_dir/release/slopus"+grep -qF -- "${asset%.js}" "$binary" \+ || fail "the executable does not contain the built frontend ($asset). It would load the dev server."++pick() { find "$bundle/$1" -maxdepth 1 -type f -name "$2" -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -n 1 | cut -d' ' -f2-; }+deb=$(pick deb '*.deb')+rpm=$(pick rpm '*.rpm')+appimage=$(pick appimage '*.AppImage')+[[ -n $deb && -n $rpm && -n $appimage ]] || fail "expected a .deb, .rpm and AppImage under $bundle."++stem="Slopus-$version-linux-x64"+mkdir -p -- "$artifacts"+rm -f -- "$artifacts/$stem".{deb,rpm,AppImage,AppImage.sig}+cp -- "$deb" "$artifacts/$stem.deb"+cp -- "$rpm" "$artifacts/$stem.rpm"+cp -- "$appimage" "$artifacts/$stem.AppImage"+chmod 0755 "$artifacts/$stem.AppImage"+if ((signed)); then+ [[ -s $appimage.sig ]] || fail "the AppImage was not signed: $appimage.sig is missing."+ cp -- "$appimage.sig" "$artifacts/$stem.AppImage.sig"+fi+printf 'package-linux-app: wrote %s.{deb,rpm,AppImage}%s\n' "$artifacts/$stem" "$( ((signed)) && printf ' and the AppImage signature')"diff --git a/scripts/publish-release.mjs b/scripts/publish-release.mjsindex 634ae42..e5cd4e6 100644--- a/scripts/publish-release.mjs+++ b/scripts/publish-release.mjs@@ -44,10 +44,12 @@ export function releaseFiles(root, version) {const target = generic[0][0];const arch = { 'windows-x86_64': 'x64', 'windows-aarch64': 'arm64', 'windows-i686': 'x86' }[target];const stem = `Slopus-${version}-windows-${arch}`;+ const linuxStem = `Slopus-${version}-linux-x64`;+ const linuxTargets = ['linux-x86_64', 'linux-x86_64-appimage'];const names = new Set();for (const [key, entry] of platforms) {- if (![target, `${target}-nsis`, `${target}-msi`].includes(key)) throw new Error(`Unexpected updater target: ${key}`);- const name = key.endsWith('-msi') ? `${stem}.msi` : `${stem}-setup.exe`;+ if (![target, `${target}-nsis`, `${target}-msi`, ...linuxTargets].includes(key)) throw new Error(`Unexpected updater target: ${key}`);+ const name = linuxTargets.includes(key) ? `${linuxStem}.AppImage` : key.endsWith('-msi') ? `${stem}.msi` : `${stem}-setup.exe`;const expected = `https://github.com/${repository}/releases/download/v${version}/${encodeURIComponent(name)}`;if (entry.url !== expected) throw new Error(`Updater URL does not match this release: ${key}`);const signature = readFileSync(resolve(directory, `${name}.sig`), 'utf8').trim();@@ -56,8 +58,11 @@ export function releaseFiles(root, version) {names.add(name);}if (!manifest.platforms[`${target}-nsis`]) throw new Error('Missing NSIS updater target.');+ if (!manifest.platforms['linux-x86_64']) throw new Error('Missing Linux AppImage updater target.');names.add(`${stem}-portable.zip`);names.add(`${stem}-worker.zip`);+ names.add(`${linuxStem}.deb`);+ names.add(`${linuxStem}.rpm`);names.add(`Slopus-${version}-linux-x64-worker.tar.gz`);// Upload the manifest last. Only this explicit list can become release assets.names.add('latest.json');diff --git a/scripts/publish-release.test.mjs b/scripts/publish-release.test.mjsindex e97bfc5..376de7e 100644--- a/scripts/publish-release.test.mjs+++ b/scripts/publish-release.test.mjs@@ -26,17 +26,20 @@ function fixture() {}));const setupPath = join(root, 'artifacts/Slopus-0.2.0-windows-x64-setup.exe');const msiPath = join(root, 'artifacts/Slopus-0.2.0-windows-x64.msi');- for (const path of [setupPath, msiPath]) {+ const appImagePath = join(root, 'artifacts/Slopus-0.2.0-linux-x64.AppImage');+ for (const path of [setupPath, msiPath, appImagePath]) {writeFileSync(path, 'installer');writeFileSync(`${path}.sig`, 'signature\n');}writeFileSync(join(root, 'artifacts/Slopus-0.2.0-windows-x64-portable.zip'), 'zip');writeFileSync(join(root, 'artifacts/Slopus-0.2.0-windows-x64-worker.zip'), 'zip');writeFileSync(join(root, 'artifacts/Slopus-0.2.0-linux-x64-worker.tar.gz'), 'tar');+ writeFileSync(join(root, 'artifacts/Slopus-0.2.0-linux-x64.deb'), 'deb');+ writeFileSync(join(root, 'artifacts/Slopus-0.2.0-linux-x64.rpm'), 'rpm');// Unrelated artifacts and secrets must never be included by a wildcard upload.writeFileSync(join(root, 'artifacts/private.key'), 'secret');writeFileSync(join(root, 'artifacts/Slopus-0.1.0-windows-x64-setup.exe'), 'old');- const manifest = createManifest({ version: '0.2.0', arch: 'x64', setupPath, msiPath, notes: 'First line\nSecond line `literal` $(literal)' });+ const manifest = createManifest({ version: '0.2.0', arch: 'x64', setupPath, msiPath, appImagePath, notes: 'First line\nSecond line `literal` $(literal)' });const manifestPath = join(root, 'artifacts/latest.json');writeFileSync(manifestPath, JSON.stringify(manifest));const state = { releases: [], uploaded: [], dirty: false, sha: 'head', failUpload: false, failManifest: false, corrupt: false, private: false };@@ -124,6 +127,18 @@ it('rejects missing artifacts', () => {expect(() => releaseFiles(root, '0.2.0')).toThrow('empty');});+it('publishes the Linux packages and requires the AppImage updater target', () => {+ const { root, manifest, manifestPath } = fixture();+ const names = releaseFiles(root, '0.2.0').files.map(({ name }) => name);+ expect(names).toEqual(expect.arrayContaining([+ 'Slopus-0.2.0-linux-x64.AppImage', 'Slopus-0.2.0-linux-x64.deb', 'Slopus-0.2.0-linux-x64.rpm',+ ]));+ delete manifest.platforms['linux-x86_64'];+ delete manifest.platforms['linux-x86_64-appimage'];+ writeFileSync(manifestPath, JSON.stringify(manifest));+ expect(() => releaseFiles(root, '0.2.0')).toThrow('Linux AppImage');+});+it.each(['dirty', 'tag', 'private', 'published'])('blocks %s releases before mutation', (failure) => {const { root, run, state } = fixture();if (failure === 'dirty') state.dirty = true;diff --git a/scripts/updater-manifest.mjs b/scripts/updater-manifest.mjsindex 34134a0..d037719 100644--- a/scripts/updater-manifest.mjs+++ b/scripts/updater-manifest.mjs@@ -15,7 +15,7 @@ export function releaseVersion(root) {return version;}-export function createManifest({ version, arch, setupPath, msiPath, notes = '', repository = 'bitti-ai/slopus', date = new Date() }) {+export function createManifest({ version, arch, setupPath, msiPath, appImagePath, notes = '', repository = 'bitti-ai/slopus', date = new Date() }) {const targetArch = { x64: 'x86_64', arm64: 'aarch64', x86: 'i686' }[arch];if (!targetArch) throw new Error(`Unsupported release architecture: ${arch}`);if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) throw new Error('Invalid release version.');@@ -30,6 +30,12 @@ export function createManifest({ version, arch, setupPath, msiPath, notes = '',const setup = artifact(setupPath);const platforms = { [`windows-${targetArch}`]: setup, [`windows-${targetArch}-nsis`]: setup };if (msiPath) platforms[`windows-${targetArch}-msi`] = artifact(msiPath);+ // The Linux updater replaces an AppImage; .deb and .rpm installs update through the releases page.+ if (appImagePath) {+ const appImage = artifact(appImagePath);+ platforms['linux-x86_64'] = appImage;+ platforms['linux-x86_64-appimage'] = appImage;+ }return { version, notes, pub_date: date.toISOString(), platforms };}@@ -40,9 +46,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]if (process.argv.includes('--check')) {console.log(`Updater release configuration is ready for ${version}.`);} else {- const { PACKAGE_ARCH: arch, OUTPUT_SETUP: setupPath, OUTPUT_MSI: outputMsi, MSI_SRC: msiSource, ARTIFACTS_DIR: outputDir, UPDATE_NOTES_FILE: notesFile } = process.env;+ const { PACKAGE_ARCH: arch, OUTPUT_SETUP: setupPath, OUTPUT_MSI: outputMsi, MSI_SRC: msiSource, OUTPUT_APPIMAGE: appImagePath, ARTIFACTS_DIR: outputDir, UPDATE_NOTES_FILE: notesFile } = process.env;if (!arch || !setupPath || !outputDir) throw new Error('Run this script through release.cmd.');- const manifest = createManifest({ version, arch, setupPath, msiPath: msiSource ? outputMsi : undefined, notes: notesFile ? readFileSync(notesFile, 'utf8') : '' });+ const manifest = createManifest({ version, arch, setupPath, msiPath: msiSource ? outputMsi : undefined, appImagePath: appImagePath || undefined, notes: notesFile ? readFileSync(notesFile, 'utf8') : '' });const outputPath = resolve(outputDir, 'latest.json');writeFileSync(outputPath, JSON.stringify(manifest, null, 2) + '\n');console.log(`Updater manifest: ${outputPath}`);diff --git a/scripts/updater-manifest.test.mjs b/scripts/updater-manifest.test.mjsindex 6a50131..1165e22 100644--- a/scripts/updater-manifest.test.mjs+++ b/scripts/updater-manifest.test.mjs@@ -38,6 +38,19 @@ describe('GitHub updater manifest', () => {writeFileSync(msiPath + '.sig', 'signed msi');expect(createManifest({ ...input, msiPath }).platforms['windows-x86_64-msi'].signature).toBe('signed msi');});+ it('offers the signed AppImage to Linux installs', () => {+ const input = fixture();+ const appImagePath = join(dirname(input.setupPath), 'Slopus-0.2.0-linux-x64.AppImage');+ writeFileSync(appImagePath, 'appimage fixture');+ writeFileSync(appImagePath + '.sig', 'signed appimage\n');+ const { platforms } = createManifest({ ...input, appImagePath });+ expect(platforms['linux-x86_64']).toEqual({+ signature: 'signed appimage', url: 'https://github.com/bitti-ai/slopus/releases/download/v0.2.0/Slopus-0.2.0-linux-x64.AppImage',+ });+ expect(platforms['linux-x86_64-appimage']).toEqual(platforms['linux-x86_64']);+ writeFileSync(appImagePath + '.sig', '');+ expect(() => createManifest({ ...input, appImagePath })).toThrow('Empty signature');+ });it('fails instead of publishing an unsigned installer or unknown architecture', () => {const input = fixture();writeFileSync(input.setupPath + '.sig', '');diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 0f79019..cf8d7f2 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -3435,6 +3435,7 @@ dependencies = ["tempfile","tiny_http","tokio",+ "webkit2gtk","webview2-com","windows","windows-sys 0.59.0",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 1be59e2..8134a1a 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -64,6 +64,11 @@ windows = { version = "0.61", features = [] }windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_UI_Shell"] }+[target.'cfg(target_os = "linux")'.dependencies]+# Must stay on wry's major: with_webview hands back its WebKitGTK view. Turns+# on WebCodecs and WebGPU, which WebKitGTK ships behind feature flags.+webkit2gtk = { version = "2.0", features = ["v2_40"] }+[dev-dependencies]tempfile = "3"tiny_http = "0.12"diff --git a/src-tauri/build.rs b/src-tauri/build.rsindex 6c69426..4eb651b 100644--- a/src-tauri/build.rs+++ b/src-tauri/build.rs@@ -2,6 +2,7 @@ fn main() {// Recompile the executable's Windows resource when packaged icons change.println!("cargo:rerun-if-changed=icons");println!("cargo:rerun-if-changed=../lib/slopfab/slopfab.dll");+ println!("cargo:rerun-if-changed=../lib/slopfab/libslopfab.so");validate_slopfab_runtime();tauri_build::build()}@@ -9,14 +10,19 @@ fn main() {fn validate_slopfab_runtime() {use std::{fs::File, io::Read, path::Path};- // Fail before packaging an LFS pointer in place of the runtime DLL.- let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../lib/slopfab/slopfab.dll");- let mut header = [0_u8; 2];+ // Each platform bundles its own runtime (tauri.windows.conf.json and+ // tauri.linux.conf.json); fail before packaging an LFS pointer in its place.+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();+ let (name, magic): (&str, &[u8]) = match os.as_str() {+ "windows" => ("slopfab.dll", b"MZ"),+ "linux" => ("libslopfab.so", b"\x7fELF"),+ _ => return,+ };+ assert_eq!(arch, "x86_64", "The vendored SlopFab runtime currently supports x86_64 only.");+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../lib/slopfab").join(name);+ let mut header = vec![0_u8; magic.len()];File::open(path).and_then(|mut file| file.read_exact(&mut header))- .unwrap_or_else(|error| panic!("Missing SlopFab runtime slopfab.dll: {error}. Run git lfs pull."));- assert_eq!(&header, b"MZ", "Invalid SlopFab runtime slopfab.dll; it may be a Git LFS pointer. Run git lfs pull.");- if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {- assert_eq!(std::env::var("CARGO_CFG_TARGET_ARCH").as_deref(), Ok("x86_64"),- "The vendored SlopFab runtime currently supports Windows x64 only.");- }+ .unwrap_or_else(|error| panic!("Missing SlopFab runtime {name}: {error}. Run git lfs pull."));+ assert_eq!(header, magic, "Invalid SlopFab runtime {name}; it may be a Git LFS pointer. Run git lfs pull.");}diff --git a/src-tauri/core/src/slopfab/mod.rs b/src-tauri/core/src/slopfab/mod.rsindex d552693..1f9c388 100644--- a/src-tauri/core/src/slopfab/mod.rs+++ b/src-tauri/core/src/slopfab/mod.rs@@ -35,7 +35,8 @@ const DLL_FILE_NAME: &str = "slopfab.dll";#[cfg(not(windows))]const DLL_FILE_NAME: &str = "libslopfab.so";/// Tauri stages the repository's runtime resources in development and release-/// builds. Installers and portable folders use the same relative layout.+/// builds. Windows installers, portable folders and the worker keep it beside+/// the executable; Linux packages keep it in Tauri's resource folder.pub fn default_dll_path() -> PathBuf {let executable = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("Slopus.exe"));let directory = executable.parent().unwrap_or_else(|| Path::new("."));@@ -46,7 +47,18 @@ pub fn default_dll_path() -> PathBuf {} else {directory};- directory.join(DLL_FILE_NAME)+ runtime_beside(directory)+}++/// The runtime beside the executable, else in a Linux package's resources.+fn runtime_beside(directory: &Path) -> PathBuf {+ let beside = directory.join(DLL_FILE_NAME);+ if cfg!(windows) || beside.is_file() {+ return beside;+ }+ // .deb, .rpm and AppImage: /usr/bin/slopus with /usr/lib/Slopus/.+ let packaged = directory.join("../lib/Slopus").join(DLL_FILE_NAME);+ if packaged.is_file() { packaged } else { beside }}const EXPECTED_CAPI_MAJOR: u32 = 1;const NOT_READY: i32 = -7;diff --git a/src-tauri/core/src/slopfab/tests.rs b/src-tauri/core/src/slopfab/tests.rsindex f2e2178..a69235a 100644--- a/src-tauri/core/src/slopfab/tests.rs+++ b/src-tauri/core/src/slopfab/tests.rs@@ -1127,3 +1127,18 @@ fn generation_seed_accepts_random_and_non_negative_values() {assert_eq!(generation_seed(482_091).unwrap(), 482_091);assert!(generation_seed(-2).is_err());}++#[test]+#[cfg(not(windows))]+fn linux_packages_find_the_runtime_in_the_resource_folder() {+ let temp = tempfile::tempdir().unwrap();+ let bin = temp.path().join("usr/bin");+ let resources = temp.path().join("usr/lib/Slopus");+ std::fs::create_dir_all(&bin).unwrap();+ std::fs::create_dir_all(&resources).unwrap();+ assert_eq!(super::runtime_beside(&bin), bin.join(super::DLL_FILE_NAME));+ std::fs::write(resources.join(super::DLL_FILE_NAME), b"\x7fELF").unwrap();+ assert_eq!(super::runtime_beside(&bin), bin.join("../lib/Slopus").join(super::DLL_FILE_NAME));+ std::fs::write(bin.join(super::DLL_FILE_NAME), b"\x7fELF").unwrap();+ assert_eq!(super::runtime_beside(&bin), bin.join(super::DLL_FILE_NAME));+}diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rsindex b47a7f3..81ef717 100644--- a/src-tauri/src/app.rs+++ b/src-tauri/src/app.rs@@ -8,6 +8,11 @@ use std::io;#[tauri::command]fn app_updater_mode() -> Result<&'static str, String> {if cfg!(debug_assertions) { return Ok("disabled"); }+ /* On Linux the updater replaces only an AppImage (whose runtime sets+ APPIMAGE); .deb and .rpm installs belong to the package manager. */+ if cfg!(target_os = "linux") {+ return Ok(if std::env::var_os("APPIMAGE").is_some() { "installed" } else { "portable" });+ }let exe = std::env::current_exe().map_err(|error| error.to_string())?;let directory = exe.parent().ok_or("Could not locate the application folder.")?;Ok(if directory.join("slopus-portable").exists() { "portable" } else { "installed" })@@ -75,6 +80,8 @@ pub fn run() {let window = builder.build()?;native_shell::round_corners(&window);native_shell::disable_browser_behaviour(&window);+ #[cfg(target_os = "linux")]+ crate::linux_webview::configure(&window);native_shell::watch_accent(app.handle());match diagnostics::initialize(app.handle()) {Ok(info) => diagnostics::info(@@ -105,8 +112,8 @@ pub fn run() {.manage(ExitGuard::default()).manage(native_shell::Backdrop::default()).manage(native_shell::SystemAccent::default())- .on_menu_event(|_app, event| {- native_shell::handle_menu_event(event.id().as_ref());+ .on_menu_event(|app, event| {+ native_shell::handle_menu_event(app, event.id().as_ref());}).on_window_event(|window, event| {use tauri::Manager as _;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 90f3258..802a6dd 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -8,6 +8,8 @@ mod diagnostics;mod export;mod external_links;mod generation;+#[cfg(target_os = "linux")]+mod linux_webview;mod media;mod native_shell;mod project;diff --git a/src-tauri/src/linux_webview.rs b/src-tauri/src/linux_webview.rsnew file mode 100644index 0000000..5ed40ff--- /dev/null+++ b/src-tauri/src/linux_webview.rs@@ -0,0 +1,151 @@+/* ── WebKitGTK, the Linux webview ────────────────────────────────────────────+WebView2 ships WebCodecs and WebGPU switched on; WebKitGTK ships them behind+runtime feature flags. The media pipeline (AGENTS.md) needs both, so they are+switched on here, together with GPU compositing and WebGL.++The feature API (webkit_settings_get_all_features and friends) arrived in+WebKitGTK 2.42, after the newest version the webkit2gtk crate binds. It is+looked up at run time instead of linked, so an older WebKitGTK still starts the+app, just without the flags; diagnostics then records which ones were missing.+-------------------------------------------------------------------------- */++use std::ffi::{c_char, c_int, c_void, CStr};+use tauri::Runtime;+use webkit2gtk::{glib::translate::ToGlibPtr as _, HardwareAccelerationPolicy, SettingsExt as _, WebViewExt as _};++/// WebKit preference keys (UnifiedWebPreferences.yaml) the page relies on.+pub(crate) const REQUIRED_FEATURES: &[&str] = &[+ "WebCodecsVideoEnabled",+ "WebCodecsAudioEnabled",+ "WebCodecsAV1Enabled",+ "WebGPUEnabled",+];++type GetAllFeatures = unsafe extern "C" fn() -> *mut c_void;+type ListLength = unsafe extern "C" fn(*mut c_void) -> usize;+type ListGet = unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void;+type ListUnref = unsafe extern "C" fn(*mut c_void);+type FeatureIdentifier = unsafe extern "C" fn(*mut c_void) -> *const c_char;+type GetFeatureEnabled = unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int;+type SetFeatureEnabled = unsafe extern "C" fn(*mut c_void, *mut c_void, c_int);++/// Which of REQUIRED_FEATURES a settings object could turn on.+#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct FeatureReport {+ pub(crate) enabled: Vec<&'static str>,+ pub(crate) missing: Vec<&'static str>,+ /// A flag was off until now, so a page already loaded does not have it.+ pub(crate) changed: bool,+}++/// The features from REQUIRED_FEATURES that `available` offers, and the rest.+pub(crate) fn match_features<'a>(available: impl IntoIterator<Item = &'a str>) -> FeatureReport {+ let available: Vec<&str> = available.into_iter().collect();+ let (enabled, missing) = REQUIRED_FEATURES.iter().partition(|name| available.contains(name));+ FeatureReport { enabled, missing, changed: false }+}++/// Switches on the flags in REQUIRED_FEATURES that this WebKitGTK knows.+fn enable_features(settings: &webkit2gtk::Settings) -> Result<FeatureReport, String> {+ // SAFETY: symbols are looked up in libraries this process already loaded+ // (wry links WebKitGTK), with the signatures documented for 2.42+. The+ // list is owned by us and unreferenced once; features are borrowed from it.+ unsafe {+ let process = libloading::os::unix::Library::this();+ let symbol = |name: &[u8]| process.get::<*mut c_void>(name).map(|symbol| *symbol);+ let missing = |error: libloading::Error| format!("WebKitGTK 2.42 or later is required for WebCodecs and WebGPU: {error}");+ let get_all: GetAllFeatures = std::mem::transmute(symbol(b"webkit_settings_get_all_features\0").map_err(missing)?);+ let length: ListLength = std::mem::transmute(symbol(b"webkit_feature_list_get_length\0").map_err(missing)?);+ let get: ListGet = std::mem::transmute(symbol(b"webkit_feature_list_get\0").map_err(missing)?);+ let unref: ListUnref = std::mem::transmute(symbol(b"webkit_feature_list_unref\0").map_err(missing)?);+ let identifier: FeatureIdentifier = std::mem::transmute(symbol(b"webkit_feature_get_identifier\0").map_err(missing)?);+ let get_enabled: GetFeatureEnabled = std::mem::transmute(symbol(b"webkit_settings_get_feature_enabled\0").map_err(missing)?);+ let set_enabled: SetFeatureEnabled = std::mem::transmute(symbol(b"webkit_settings_set_feature_enabled\0").map_err(missing)?);++ let settings_ptr: *mut c_void = settings.to_glib_none().0.cast();+ let list = get_all();+ if list.is_null() {+ return Err("WebKitGTK returned no feature list.".into());+ }+ let mut available = Vec::new();+ let mut changed = false;+ for index in 0..length(list) {+ let feature = get(list, index);+ if feature.is_null() {+ continue;+ }+ let name = identifier(feature);+ if name.is_null() {+ continue;+ }+ let name = CStr::from_ptr(name).to_string_lossy();+ if let Some(required) = REQUIRED_FEATURES.iter().find(|required| **required == name) {+ if get_enabled(settings_ptr, feature) == 0 {+ set_enabled(settings_ptr, feature, 1);+ changed = true;+ }+ available.push(*required);+ }+ }+ unref(list);+ Ok(FeatureReport { changed, ..match_features(available) })+ }+}++/// Media and GPU settings for the main webview, plus the browser behaviour+/// native_shell.rs turns off on Windows. Logs what could not be enabled.+pub(crate) fn configure<R: Runtime>(window: &tauri::WebviewWindow<R>) {+ let _ = window.with_webview(|webview| {+ let view = webview.inner();+ let Some(settings) = view.settings() else { return };+ settings.set_hardware_acceleration_policy(HardwareAccelerationPolicy::Always);+ settings.set_enable_webgl(true);+ settings.set_enable_media(true);+ settings.set_media_playback_requires_user_gesture(false);+ // DevTools only in debug builds, as with WebView2.+ settings.set_enable_developer_extras(cfg!(debug_assertions));+ let report = enable_features(&settings);+ view.set_settings(&settings);+ /* The first navigation started when the window was built, and+ WebKit decides navigator.gpu and the codec classes when a page's+ global object is created. Load the page again so it has them;+ the window is still empty this early in startup. */+ if report.as_ref().is_ok_and(|report| report.changed) {+ view.reload();+ }+ match report {+ Ok(report) if report.missing.is_empty() => crate::diagnostics::info(+ "app",+ "webview",+ "WebKitGTK media and GPU features enabled.",+ serde_json::json!({ "enabled": report.enabled }),+ ),+ Ok(report) => crate::diagnostics::warn(+ "app",+ "webview",+ "This WebKitGTK lacks some media or GPU features. Update WebKitGTK for video decoding, export and effects.",+ serde_json::json!({ "enabled": report.enabled, "missing": report.missing }),+ ),+ Err(error) => crate::diagnostics::warn("app", "webview", &error, serde_json::json!({})),+ }+ });+}++/// Runs a text menu item (Cut, Copy, Paste, Select all) in the focused field.+/// WebKit's own editing commands keep undo history and input events intact,+/// which is what replaying the keys achieves on Windows.+pub(crate) fn execute_editing_command<R: Runtime>(window: &tauri::WebviewWindow<R>, command: &'static str) {+ let _ = window.with_webview(move |webview| webview.inner().execute_editing_command(command));+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reports_which_required_features_this_webkit_offers() {+ let report = match_features(["WebGPUEnabled", "WebCodecsVideoEnabled", "SomethingElse"]);+ assert_eq!(report.enabled, ["WebCodecsVideoEnabled", "WebGPUEnabled"]);+ assert_eq!(report.missing, ["WebCodecsAudioEnabled", "WebCodecsAV1Enabled"]);+ }+}diff --git a/src-tauri/src/native_shell.rs b/src-tauri/src/native_shell.rsindex 559d5e9..9e2b793 100644--- a/src-tauri/src/native_shell.rs+++ b/src-tauri/src/native_shell.rs@@ -311,17 +311,34 @@ pub(crate) fn show_text_context_menu(.map_err(|error| format!("Could not show the text menu: {error}"))}+/// The text menu's items: the Ctrl shortcut Windows replays, and the editing+/// command WebKitGTK runs for the same item.+fn text_menu_item(id: &str) -> Option<(u8, &'static str)> {+ match id {+ MENU_CUT => Some((b'X', "Cut")),+ MENU_COPY => Some((b'C', "Copy")),+ MENU_PASTE => Some((b'V', "Paste")),+ MENU_SELECT_ALL => Some((b'A', "SelectAll")),+ _ => None,+ }+}+/// Routes a click on one of the text menu's items. Returns false for any other/// menu, so the caller can keep one global handler.-pub(crate) fn handle_menu_event(id: &str) -> bool {- let key = match id {- MENU_CUT => b'X',- MENU_COPY => b'C',- MENU_PASTE => b'V',- MENU_SELECT_ALL => b'A',- _ => return false,- };- send_ctrl_shortcut(key);+pub(crate) fn handle_menu_event<R: Runtime>(app: &AppHandle<R>, id: &str) -> bool {+ let Some((key, command)) = text_menu_item(id) else { return false };+ #[cfg(target_os = "linux")]+ {+ let _ = key;+ if let Some(window) = app.get_webview_window("main") {+ crate::linux_webview::execute_editing_command(&window, command);+ }+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = (app, command);+ send_ctrl_shortcut(key);+ }true}@@ -352,7 +369,7 @@ fn send_ctrl_shortcut(key: u8) {unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };}-#[cfg(not(windows))]+#[cfg(not(any(windows, target_os = "linux")))]fn send_ctrl_shortcut(_key: u8) {}/* ── Files ────────────────────────────────────────────────────────────────── */@@ -379,13 +396,52 @@ pub(crate) fn reveal_in_explorer(path: String) -> Result<(), String> {.spawn().map_err(|error| format!("Could not reveal the file: {error}"))?;#[cfg(all(unix, not(target_os = "macos")))]- std::process::Command::new("xdg-open")- .arg(path.parent().unwrap_or(&path))- .spawn()- .map_err(|error| format!("Could not open the folder: {error}"))?;+ {+ /* Files, Dolphin and most other file managers implement the+ FileManager1 interface and select the item; xdg-open can only open+ the folder around it. */+ let selected = std::process::Command::new("dbus-send")+ .args([+ "--session",+ "--print-reply",+ "--reply-timeout=5000",+ "--dest=org.freedesktop.FileManager1",+ "--type=method_call",+ "/org/freedesktop/FileManager1",+ "org.freedesktop.FileManager1.ShowItems",+ ])+ .arg(format!("array:string:{}", file_uri(&path)))+ .arg("string:")+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .is_ok_and(|status| status.success());+ if !selected {+ std::process::Command::new("xdg-open")+ .arg(path.parent().unwrap_or(&path))+ .spawn()+ .map_err(|error| format!("Could not open the folder: {error}"))?;+ }+ }Ok(())}+/// A `file://` URI for an absolute path, percent-encoding everything but+/// unreserved characters and separators. dbus-send splits arrays on commas,+/// so those are encoded too.+#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]+pub(crate) fn file_uri(path: &std::path::Path) -> String {+ let mut uri = String::from("file://");+ for byte in path.to_string_lossy().bytes() {+ if byte.is_ascii_alphanumeric() || b"/-_.~".contains(&byte) {+ uri.push(char::from(byte));+ } else {+ uri.push_str(&format!("%{byte:02X}"));+ }+ }+ uri+}+#[derive(Debug, Deserialize)]pub(crate) struct FileFilter {pub(crate) name: String,@@ -441,6 +497,14 @@ mod tests {assert_eq!(first_launch_size(1000, 1000, 0.0, (100.0, 100.0)), (800.0, 800.0));}+ #[test]+ fn file_uris_encode_spaces_commas_and_unicode() {+ assert_eq!(+ file_uri(std::path::Path::new("/home/me/My Videos/a,b ä.mp4")),+ "file:///home/me/My%20Videos/a%2Cb%20%C3%A4.mp4"+ );+ }+#[test]fn colours_are_lowercase_hash_hex() {assert_eq!(hex(0x00, 0x78, 0xd4), "#0078d4");@@ -449,7 +513,8 @@ mod tests {#[test]fn only_the_text_menu_ids_are_claimed() {- assert!(!handle_menu_event("something-else"));+ assert!(text_menu_item("something-else").is_none());+ assert_eq!(text_menu_item(MENU_SELECT_ALL), Some((b'A', "SelectAll")));}#[test]diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 065f1c3..69c0175 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -32,9 +32,6 @@},"bundle": {"active": true,- "resources": {- "../lib/slopfab/slopfab.dll": "slopfab.dll"- },"targets": "all","icon": ["icons/32x32.png",diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.jsonnew file mode 100644index 0000000..1a7da7d--- /dev/null+++ b/src-tauri/tauri.linux.conf.json@@ -0,0 +1,31 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "bundle": {+ "targets": ["deb", "rpm", "appimage"],+ "category": "Video",+ "resources": {+ "../lib/slopfab/libslopfab.so": "libslopfab.so"+ },+ "linux": {+ "appimage": {+ "bundleMediaFramework": true+ },+ "deb": {+ "section": "video",+ "depends": [+ "gstreamer1.0-plugins-base",+ "gstreamer1.0-plugins-good",+ "gstreamer1.0-plugins-bad"+ ],+ "recommends": ["gstreamer1.0-libav"]+ },+ "rpm": {+ "depends": [+ "gstreamer1-plugins-base",+ "gstreamer1-plugins-good",+ "gstreamer1-plugins-bad-free"+ ]+ }+ }+ }+}diff --git a/src-tauri/tauri.windows.conf.json b/src-tauri/tauri.windows.conf.jsonnew file mode 100644index 0000000..e5450dd--- /dev/null+++ b/src-tauri/tauri.windows.conf.json@@ -0,0 +1,8 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "bundle": {+ "resources": {+ "../lib/slopfab/slopfab.dll": "slopfab.dll"+ }+ }+}diff --git a/src/components/ProjectCard.tsx b/src/components/ProjectCard.tsxindex d1ee61b..33a5901 100644--- a/src/components/ProjectCard.tsx+++ b/src/components/ProjectCard.tsx@@ -2,6 +2,7 @@ import { Delete16, Film32, FolderOpen16, Image32, More16, OpenExternal16 } fromimport { forwardRef, type KeyboardEvent, type MouseEvent, type Ref } from "react";import { resolutionLabel, visibleClipAt } from "../lib/export";import type { ProjectRecord } from "../lib/project";+import { fileManagerName } from "../lib/platform";import { MediaThumbnail } from "./workspace/MediaThumbnail";import { useContextMenu, type MenuEntry } from "./ui";@@ -79,7 +80,7 @@ export const ProjectCard = forwardRef(function ProjectCard(const items: MenuEntry[] = [{ id: "open", label: "Open", icon: <OpenExternal16 />, onSelect: () => onOpen(project) },- ...(onReveal ? [{ id: "reveal", label: "Show in File Explorer", icon: <FolderOpen16 />, onSelect: () => onReveal(project) }] : []),+ ...(onReveal ? [{ id: "reveal", label: `Show in ${fileManagerName()}`, icon: <FolderOpen16 />, onSelect: () => onReveal(project) }] : []),...(onDelete ? [{ separator: true } as const, { id: "delete", label: "Delete project…", icon: <Delete16 />, onSelect: () => onDelete(project) }] : []),];const openMenu = (event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => {diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 2e1c7a3..2203885 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -31,6 +31,7 @@ import {import { MAX_GENERATION_STEPS } from "../lib/project";import { availableReferenceIconGenerators, loadReferenceIconAutomation, loadReferenceIconGeneratorId, referenceIconGenerator, saveReferenceIconAutomation, saveReferenceIconGeneratorId, subscribeReferenceIconAutomation } from "../lib/referenceIconSettings";import { applyTheme, loadTheme, saveTheme, type ThemeChoice } from "../lib/theme";+import { runtimeLocationHint } from "../lib/platform";import {ComboBox, ContextMenu, InfoBadge, InfoBar, NavItem, NavPane, ProgressBar, SettingsCard, SettingsExpander, SettingsGroup, SettingsRow,TextField, ToggleSwitch, type InfoBarSeverity,@@ -695,7 +696,7 @@ const engineHeadline = (status: SlopfabStatus | null, desktop: boolean) => {const engineDetail = (status: SlopfabStatus | null, desktop: boolean, missing: number) => {if (!desktop) return "Only the desktop app can check paths and render.";if (!status) return "Looking for the engine and model files.";- if (status.state === "runtimeMissing") return `${status.detail} slopfab.dll should be next to Slopus.exe.`;+ if (status.state === "runtimeMissing") return `${status.detail} ${runtimeLocationHint()}`;if (status.state === "ready") return "All required model files found.";if (missing > 0) return `${status.detail} ${missing === 1 ? "1 path" : `${missing} paths`} still to set.`;return status.detail;diff --git a/src/components/TitleBar.tsx b/src/components/TitleBar.tsxindex 2cc246d..21cac0b 100644--- a/src/components/TitleBar.tsx+++ b/src/components/TitleBar.tsx@@ -3,6 +3,7 @@ import icon from "../../marketing/icon.png";import {closeWindow, minimizeWindow, onMaximizedChange, onWindowFocusChange, toggleMaximizeWindow,} from "../lib/nativeShell";+import { hostPlatform } from "../lib/platform";/* The window's title bar. The window is frameless (tauri.conf.json`decorations: false`), so this row IS the caption: it drags the window,@@ -46,6 +47,26 @@ const GLYPH = {close: "",} as const;+/* Other desktops have neither font: the same four shapes drawn as 10px+ hairlines, so the buttons look alike everywhere. */+const SVG_GLYPH: Record<keyof typeof GLYPH, ReactNode> = {+ minimize: <path d="M0 5.5h10" />,+ maximize: <rect x="0.5" y="0.5" width="9" height="9" />,+ restore: <><rect x="0.5" y="2.5" width="7" height="7" /><path d="M2.5 2.5V0.5h7v7h-2" /></>,+ close: <path d="M0.5 0.5l9 9M9.5 0.5l-9 9" />,+};++const fontGlyphs = hostPlatform() === "windows";++function CaptionGlyph({ kind }: { kind: keyof typeof GLYPH }) {+ if (fontGlyphs) return <span aria-hidden="true">{GLYPH[kind]}</span>;+ return (+ <svg aria-hidden="true" viewBox="0 0 10 10" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="1">+ {SVG_GLYPH[kind]}+ </svg>+ );+}+/** Follows the native maximized state. False outside Tauri. */export function useWindowMaximized(): boolean {const [maximized, setMaximized] = useState(false);@@ -93,7 +114,7 @@ export function TitleBar({Alt+Space, Win+Up/Down and Alt+F4. */}<div className="titlebar__captions" role="group" aria-label="Window controls"><button type="button" className="titlebar__caption" tabIndex={-1} aria-label="Minimize" data-tooltip="Minimize" onClick={run(minimizeWindow)}>- <span aria-hidden="true">{GLYPH.minimize}</span>+ <CaptionGlyph kind="minimize" /></button><buttontype="button"@@ -103,10 +124,10 @@ export function TitleBar({data-tooltip={maximized ? "Restore Down" : "Maximize"}onClick={run(toggleMaximizeWindow)}>- <span aria-hidden="true">{maximized ? GLYPH.restore : GLYPH.maximize}</span>+ <CaptionGlyph kind={maximized ? "restore" : "maximize"} /></button><button type="button" className="titlebar__caption titlebar__caption--close" tabIndex={-1} aria-label="Close" data-tooltip="Close" onClick={run(closeWindow)}>- <span aria-hidden="true">{GLYPH.close}</span>+ <CaptionGlyph kind="close" /></button></div></header>diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsxindex a42840e..9f7289c 100644--- a/src/components/workspace/ReferencesView.tsx+++ b/src/components/workspace/ReferencesView.tsx@@ -23,6 +23,7 @@ import { CLOTHING_SETTING_GROUPS, LOCATION_SETTING_GROUPS } from "../../lib/expaimport { isTauri } from "../../lib/persistence";import { useShortcut } from "../../lib/commands";import { revealInExplorer } from "../../lib/nativeShell";+import { fileManagerName } from "../../lib/platform";import { ReferenceImage } from "./ReferenceImage";import { PresetIcon } from "./PresetIcon";import { ReferenceIconGenerationDialog } from "../ReferenceIconGenerationDialog";@@ -395,7 +396,7 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,return [{ id: "rename", label: "Rename", icon: <Rename16 />, shortcut: "F2", disabled: many, onSelect: () => rename(reference.id) },{ id: "add-file", label: "Add file…", icon: <ImageAdd16 />, disabled: many || Boolean(reference.refmods?.length) || importingFiles, onSelect: () => { selectOnly(reference.id); void addFiles(reference.id); } },- { id: "reveal", label: "Show in File Explorer", icon: <FolderOpen16 />, disabled: many || !file || !isTauri(), onSelect: () => { if (file) void revealInExplorer(file).catch((reason) => setImportError(String(reason))); } },+ { id: "reveal", label: `Show in ${fileManagerName()}`, icon: <FolderOpen16 />, disabled: many || !file || !isTauri(), onSelect: () => { if (file) void revealInExplorer(file).catch((reason) => setImportError(String(reason))); } },{ separator: true },...(users.length? users.map((job): MenuEntry => ({ id: `open-${job.id}`, label: `Open ${job.title}`, icon: <OpenExternal16 />, disabled: !onOpenGenerator, onSelect: () => onOpenGenerator?.(job.id) }))diff --git a/src/lib/platform.test.ts b/src/lib/platform.test.tsnew file mode 100644index 0000000..caeb1f9--- /dev/null+++ b/src/lib/platform.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { fileManagerName, hostPlatform, runtimeLocationHint } from "./platform";++const WEBVIEW2 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0";+const WEBKITGTK = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";++describe("hostPlatform", () => {+ it("tells WebView2 from WebKitGTK", () => {+ expect(hostPlatform(WEBVIEW2)).toBe("windows");+ expect(hostPlatform(WEBKITGTK)).toBe("linux");+ expect(hostPlatform("")).toBe("windows");+ });++ it("names the file manager and runtime for each platform", () => {+ expect(fileManagerName("windows")).toBe("File Explorer");+ expect(fileManagerName("linux")).toBe("Files");+ expect(runtimeLocationHint("windows")).toBe("slopfab.dll should be next to Slopus.exe.");+ expect(runtimeLocationHint("linux")).toContain("libslopfab.so");+ });+});diff --git a/src/lib/platform.ts b/src/lib/platform.tsnew file mode 100644index 0000000..04dd5dc--- /dev/null+++ b/src/lib/platform.ts@@ -0,0 +1,24 @@+/* The desktop the app runs on, for the few words and glyphs that differ.+ WebView2 reports "Windows NT"; WebKitGTK reports "X11; Linux". jsdom and an+ unknown engine count as Windows, the platform the UI is drawn after. */++export type HostPlatform = "windows" | "linux" | "macos";++export function hostPlatform(userAgent: string = globalThis.navigator?.userAgent ?? ""): HostPlatform {+ if (/Windows NT/i.test(userAgent)) return "windows";+ if (/Macintosh|Mac OS X/i.test(userAgent)) return "macos";+ if (/Linux|X11|CrOS/i.test(userAgent)) return "linux";+ return "windows";+}++/** The file manager's name, for "Show in …" menu items. */+export function fileManagerName(platform: HostPlatform = hostPlatform()): string {+ return platform === "windows" ? "File Explorer" : platform === "macos" ? "Finder" : "Files";+}++/** Where the SlopFab runtime belongs, for a "runtime missing" status. */+export function runtimeLocationHint(platform: HostPlatform = hostPlatform()): string {+ return platform === "windows"+ ? "slopfab.dll should be next to Slopus.exe."+ : "libslopfab.so should be in /usr/lib/Slopus or next to the slopus executable.";+}