diff --git a/.gitattributes b/.gitattributes index 6418a28b..c9c9118f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,7 @@ tests/assets/performance/**/*.3mf filter=lfs diff=lfs merge=lfs -text src-tauri/linux/*.sh text eol=lf +# Preserve the byte hashes of archived benchmark evidence on every platform. +tests/benchmark/results/cats-exact/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol +# Keep committed bytes of hashed text fixtures; CRLF checkouts change their SHA-256. +*.kfil -text +tests/assets/performance/**/*.json -text diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..c2d1ae3a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,193 @@ +name: CI + +# Fork pull requests run with a read-only token and no secrets. Keep this on pull_request, never +# pull_request_target, so PR code never runs with write access. +on: + pull_request: + branches: + - develop + - main + # Runs on the base branches also seed the npm, Playwright, and cargo caches that PRs can restore. + push: + branches: + - develop + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# Runners are pinned rather than ubuntu-latest: Playwright cannot install Chromium on Ubuntu 26.04. +jobs: + checks: + name: Lint, build, and unit tests + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Lint + run: npm run lint + + - name: Build + run: npm run build + + - name: Unit tests + run: npm test + + - name: Check that test:e2e:all runs every e2e test + run: npm run check:e2e + + e2e_suites: + name: List e2e suites + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + suites: ${{ steps.list.outputs.suites }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + # The same list test:e2e:all runs, so new suites reach CI without editing this file. + - name: List suites + id: list + run: echo "suites=$(node scripts/run-e2e-suites.mjs --list)" >> "$GITHUB_OUTPUT" + + e2e: + name: E2E (${{ matrix.suite.script }}) + needs: e2e_suites + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + suite: ${{ fromJSON(needs.e2e_suites.outputs.suites) }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + # ImageOS (for example ubuntu24) keys the browser cache by runner image, so a cache built on + # another Ubuntu release is never restored here. + - name: Read Playwright version + id: playwright + run: | + echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT" + echo "image=$ImageOS" >> "$GITHUB_OUTPUT" + + - name: Cache Playwright browsers + id: browsers + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ steps.playwright.outputs.image }}-${{ steps.playwright.outputs.version }}-chromium + + - name: Install Playwright Chromium + if: steps.browsers.outputs.cache-hit != 'true' + run: npx playwright install --with-deps chromium + + - name: Install Playwright system dependencies + if: steps.browsers.outputs.cache-hit == 'true' + run: npx playwright install-deps chromium + + - name: Run ${{ matrix.suite.script }} + env: + SUITE_SCRIPT: ${{ matrix.suite.script }} + run: npm run "$SUITE_SCRIPT" + + - name: Upload Playwright results + if: failure() + uses: actions/upload-artifact@v4 + with: + name: playwright-${{ matrix.suite.name }} + path: | + playwright-report/ + test-results/ + if-no-files-found: ignore + retention-days: 7 + + rust_tests: + name: Rust tests (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + # Each OS compiles different native code (GIO, Launch Services, ShellExecuteEx) + # and runs different tests, so one runner cannot cover the others. ubuntu-22.04 + # matches the release build and still has libwebkit2gtk-4.0-dev. + os: [ubuntu-22.04, macos-latest, windows-latest] + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Install Rust stable + uses: dtolnay/rust-toolchain@stable + + # The same packages release.yml installs to build the Linux app. + - name: Install Linux dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf zsync + + # Caches the cargo registry and src-tauri/target. Pull request runs only restore, so + # they do not each fill the repository's cache quota. + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + with: + workspaces: src-tauri -> target + save-if: ${{ github.event_name != 'pull_request' }} + + - name: cargo test + working-directory: src-tauri + run: cargo test --locked + + # One stable check to require in branch protection, however many suites the matrix has. + ci_passed: + name: CI passed + if: always() + needs: [checks, rust_tests, e2e_suites, e2e] + runs-on: ubuntu-24.04 + permissions: {} + steps: + - name: Require every CI job to pass + if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') + run: | + echo "Some CI jobs did not pass: ${{ join(needs.*.result, ', ') }}" + exit 1 diff --git a/AGENTS.md b/AGENTS.md index 370205af..4bc235e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,6 +76,18 @@ Run the focused tests when touching: For UI-only edits, lint/build is usually enough. For geometry, export, or auto-paint changes, prefer adding a small regression test over relying on screenshots. +Browser tests use Playwright. `npm run test:e2e` runs only the `@smoke` tests against the production +build. Pages such as docs, landing, privacy, terms, 404, and i18n each have their own +`playwright.*.config.ts` and `test:e2e:*` script, because they need a different server or port. Run +an area spec only through its own script; under another config it fails with a message naming the +right one. Before a change lands, run `npm run test:e2e:all`. It runs `@smoke` and then every area +suite, always on fresh servers, and fails if any suite fails or if any test is outside every suite. +The pull request workflow (`.github/workflows/ci.yml`) runs the same suites. The `@full` export +matrix in `kromacut-flow.spec.ts` is too slow for every change (its large-image cases allow 90 +minutes each), so it is excluded; run it with `test:e2e:matrix`, `test:e2e:stress`, or +`test:e2e:full` when changing the main export flow. A new e2e test must be tagged `@smoke` or +matched by an area config, and a new area config must be added to `scripts/run-e2e-suites.mjs`. + ## Changelog Guidance Update `CHANGELOG.md` under the current unreleased version for most completed changes. In general, diff --git a/CHANGELOG.md b/CHANGELOG.md index 987c4b70..cef20364 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,44 @@ All notable changes to Kromacut are documented in this file. ## Unreleased +## v4.3.0 - 2026-11-22 + +### Upgrade notes + +- **Check the first color's height when rebuilding older work.** When First Layer Height is not a multiple of Layer Height, 4.2.0 could lower the first color by one layer after resizing or Undo/Redo. 4.3.0 keeps the height you set, so a rebuilt model can have a taller first color than an earlier export. Check the color heights and the slicer preview before printing. +- **Existing profiles and palettes remain compatible.** Check new prints in your slicer as usual. + +### Added + +- **2D history shortcuts (#163)** - Ctrl/Cmd+Z undoes and Ctrl/Cmd+Shift+Z redoes image edits in 2D. The shortcuts are ignored in editable fields, dialogs, popovers, menus and open select lists, in 3D mode, while cropping, and during processing, and they follow the physical Z key on non-Latin keyboard layouts. Documented in the image adjustments guide, with Playwright regressions for keyboard behavior. +- **Auto-paint search guidance and cancellation (#103)** - Enhanced matching pauses before searching 1,024 or more distinct target colors, with guidance to quantize photos to 16–32 colors in 2D, disable repeats, or use a Fast / Compact shortcut. The advisory threshold comes from fixed-seed Balanced / Detailed measurements with repeats rather than image dimensions; deeper searches and more filaments can still be slow below it. Running filament searches now have **Cancel Auto-paint**, which terminates the worker and stays stopped until restarted or settings change; debounced requests and late worker messages cannot restart cancelled work. Changing settings invalidates previous Run/Cancel choices, including when returning to earlier values. All 12 languages include the controls, Auto-paint guide, and troubleshooting advice. Regression coverage checks the threshold, worker cancellation and restart, settings round-trips, and exact baseline final stacks and scores for existing image/profile fixtures with seed 12345. +- **Open in Slicer (desktop)** - The 3D download menu in the desktop app adds **Open in Slicer**, which builds the same 3MF as **Download 3MF** and opens it in a slicer without a Save As dialog. It first asks which app should open the model: **System default** (the system's `.3mf` app), or Bambu Studio, Orca Slicer, PrusaSlicer, and UltiMaker Cura when they are installed in their usual locations: `/Applications` or `~/Applications` on macOS; Program Files or `%LOCALAPPDATA%\Programs` on Windows, including the newest versioned Cura folder (a saved older Cura stays usable after a newer version is installed next to it, #200); and `PATH` commands or Flatpak installs on Linux. **Browse** picks any other app with the native file dialog; only app bundles, `.exe` files, or executables are accepted, and Kromacut remembers up to 16 picked apps, always keeping the saved slicer among them. With **System default**, make your slicer the default app for `.3mf` files first. **Always use this slicer** saves the choice under `kromacut:desktop-slicer`, so later clicks open the model straight away, and the menu shows the saved slicer's name when it is a specific app. When you choose a specific app, Kromacut only launches it if it was detected or picked with **Browse**, never a program named by the web view. **Choose Slicer** in the menu changes or forgets the saved slicer, and so does the **Open in Slicer** row in the desktop Settings dialog, which shows the saved choice (**Ask every time**, **System default**, or the slicer's name and path), works without an image or model, and saves a new choice without exporting or opening anything. Settings and the download menu share one saved choice, so a change in either shows up in the other straight away. Changing or forgetting the saved slicer while Open in Slicer is still checking the previous one does not let that check clear the new choice or open the model in the previous slicer, and a rebuild that finishes during the check is exported with its own head count, pause schedule, and layer heights instead of those of the build shown when **Open in Slicer** was clicked. A slicer chooser opened during the check, for example from **Settings → Change**, is also left alone: the late result does not turn that chooser's **Save** into **Open**, open the model over it, or forget the saved slicer. A saved slicer that was moved or uninstalled is forgotten and the chooser explains why. Closing the chooser returns keyboard focus to the download button or the Settings button. Each model is written to a new file in Kromacut's cache folder, so a slicer that still has an earlier copy open is never overwritten, and copies older than a day are removed on the next handoff. Flatpak slicers receive the model through Flatpak file forwarding, so their sandbox can read it. Failures to write or launch the file, including a missing default app, show a localized error that points to **Download 3MF**; Kromacut does not wait for the slicer to close. Like the rest of the download menu, **Open in Slicer** is disabled while Kromacut rebuilds the 3D preview. The browser version is unchanged. The chooser, menu, Settings row, and export guides are localized into all 12 languages. Added native tests for file naming, collisions, invalid data, cache cleanup, per-platform slicer detection, newest-version selection, a saved older Cura staying launchable after an upgrade, launchable-app validation, the detected-or-picked launch rule, picked-app storage, launch commands, and launcher failures; unit tests for the saved preference, including a slow saved-slicer check that finishes after Settings saves or forgets a slicer, a chooser opens or closes, or a new build finishes; and browser regressions for the desktop handoff, choosing, remembering, changing, browsing, and forgetting a slicer from the menu and Settings, a missing saved slicer, a found, missing, or failed check that finishes while the Settings chooser is open, the browser build without the Settings row, and focus after closing the chooser. +- **Pull request CI and `test:e2e:all`** - Pull requests into `develop` and `main`, and pushes to them, now run lint, the build, unit tests, the desktop app's Rust tests (`cargo test` on Linux, macOS, and Windows, where the test binary embeds the app's Windows manifest so it can start), and every Playwright e2e suite in parallel jobs, with cached npm packages, Chromium, and cargo builds. The other Linux jobs run on Ubuntu 24.04 rather than `ubuntu-latest` (Ubuntu 26.04), where Playwright cannot install Chromium, and the Chromium cache is keyed by runner image. One `CI passed` check summarizes the result. Fork pull requests get a read-only token and no secrets. `npm run test:e2e:all` runs the same suites locally one after another: the `@smoke` tests, then the docs, landing, privacy, terms, 404, i18n, and i18n build suites, each on a fresh server. It fails if any suite fails, if a Playwright config isn't in the suite list, or if a test isn't run by any suite; the long `@full` export matrix stays on demand. Area specs now refuse to run under the wrong Playwright config and name the script to use. Palette Proof, the Settings legal links, and the adaptive Stack Matrix round trip were not in any suite and now run with `@smoke`. +- **Multi-head printing guide** - New in-app documentation page explaining Multi-head printing: prerequisites, how layers become color runs and windows, the Head Schedule, the combination search space, Color grouping, and what Fast, Balanced, and Thorough search depth change, with four explanatory diagrams. The guide, navigation metadata, and diagrams are available in all 12 languages, with measured translated labels and reciprocal Auto-paint links. Covers routed preview colors, 3MF head assignments and M600 checkpoints, single-head fallback, and cancellation when the image changes. Regression checks require matching guide metadata and complete diagram catalogs and label bounds; browser coverage loads the guide and all four illustrations in every language. +- **Multi-head printing** - Auto-paint can analyze per-pixel filament orders across 2–8 heads in a background worker. Successful builds route every color region through its per-layer filament path and scheduled physical head; the preview shows each region’s predicted blend, corrected by the same calibration evidence as single-head builds, and can display its physical filament instead. All smoothing strengths share conforming region boundaries and closed layer geometry, with chunked generation to keep builds responsive. Multi-head 3MFs retain that geometry and physical filament colors, use the selected head count and head assignments, and insert M600 pause markers at exactly the Head Schedule’s swap checkpoints. The download menu offers only 3MF for multi-head builds, as it does for Flat Paint, because STL can't carry head routing; single-head fallback builds still offer STL. Multi-head export progress has no idle stretch reserved for unused work. The Head Schedule takes filament requirements from each region's final path on the layers that region can print, including zero-weight visible regions, so abandoned filaments and unprinted layers above a region do not cause reloads, while useful preloads and idle-head carryover are still allowed; height dithering is resolved on the preview's cropped block grid so the schedule matches the printed surfaces. Selected heads beyond the filament count remain EMPTY, and filaments are assigned to heads so the Head Schedule needs as few swaps as possible. Center/Edge priorities use the same weighted targets as normal Auto-paint; colors with zero regional weight retain printable surfaces through palette matching and finite routing groups without changing weighted centroids. Fast/Balanced/Thorough controls search effort with bounded deterministic sampling. A **Color grouping** control chooses the search targets: Layer-based merges colors sharing a printer layer; Color-based keeps hues separate within a bounded group budget while preserving every member’s original print layer. At least one group is retained per occupied layer, including visible regions with zero regional weight, so capped palettes keep every printable color assigned without changing scoring weights. Color-based can produce more printed colors, but does not guarantee lower color error. Fast fitted-optics simulation nominates a bounded shortlist; windows and final region paths are scored with the full appearance model and usage-weighted CIEDE2000 on the original grouped colors. Fully scored assignments are reused when their physical context is unchanged, avoiding repeated broad searches during reconciliation. The current order remains available during reconciliation, and calibrated preview colors and the 0.25 minimum predicted gain gate are retained. Head count, search depth, color grouping, and the mode toggle persist through fallback builds and retain edits made during analysis; Multi-head and Flat Paint are mutually exclusive. Worker errors, unusable or non-improving plans, and plans whose predicted usage-weighted mean CIEDE2000 gain over the normal stack is below 0.25 retain the normal single-head model, with a notice and its original start color and swaps. Instructions follow the built snapshot, and before the first multi-head build **Copy** gives the same build prompt the panel shows, not single-head swaps; fallback builds copy their single-head plan. Image changes cancel pending analysis and discard obsolete builds. Controls, notices, schedules, copied text, and usage guides are localized into all 12 languages. Added region/filament routing, head/extruder, pause, smoothing/topology, fallback, predicted gain, async lifecycle, worker failure, browser settings-persistence, and 3MF-only download menu regression coverage. Color-group regressions cover capped palettes crossing physical layer boundaries, and calibrated image measurements use final-stack surfaces with CIEDE2000. Added full-model shortlist, proof-anchor, weighted reconciliation, seeded corrected multi-window routing, and bounded-evaluation regressions plus reproducible measured-profile cats/Rocco benchmarks. Head Schedule regressions cover unused loads, active-layer head coverage, shared-block dithering, cropped-pixel scheduling, swap counts, copied instructions, and physical 3MF output. +- **Awards page and Snapmaker Innovation Fund winner badge** - A new Awards page shows Kromacut's Snapmaker Innovation Fund Winner medal, linked to the Snapmaker Innovation Fund page. It is available in all 12 languages, prerendered for search engines, and listed in the sitemap. The website footer and the Settings links open it; the desktop app opens it in the system browser. The website and the README each gain an Awards section near the bottom. The badges embed Snapmaker's official logo files unaltered. Pages show PNG renders of the badges so Safari and other WebKit views draw the lettering at the right weight. Added route, static-page, Settings-link, and landing browser coverage. Privacy and Terms browser tests cover all eight footer links, and the Privacy suite checks keyboard focus through Awards. + +### Changed + +- **Auto-paint scoring (#103)** - Reuse the winning CIEDE2000 error and precompute unchanged chroma, uncertainty, and segment values while preserving all target colors, arithmetic, tie breaking, and final stacks. The fixed-seed benchmark records a modest 6.1% reduction in median scoring time at 142,066 targets, with mixed results on smaller palettes; large repeated searches remain expensive. No target approximation or HD/TD storage or rounding change is involved. +- **Image decoding (#140, #141, #153)** - Imported images are decoded once: the decode that checks an import also supplies the 2D preview, image colors, and build-warning dimensions, and Stack Matrix draws the validated photo with its existing color sampling instead of decoding it again. Edits and Undo/Redo share one decoded snapshot instead of loading the same image separately for each consumer, and Manual 3D geometry, Auto-paint analysis, and Palette Proof image targets read those same pixels. Imported color-profiled images, including translucent and 8-/16-bit Display P3 files, keep their pixel values, swatches, and chosen color order through Undo/Redo, and closely spaced profiled colors stay consistent with the layers that are built and exported. Decoded bitmaps are released once their pixels are copied. While an image is still loading after Undo/Redo, Build waits for it and edits and downloads cannot use the previous image; image panels keep their size and show updating feedback. Large images show their size before color scanning finishes, and a localized checking indicator appears only when checking takes longer than 150 ms. Added browser regressions for one-decode imports, shared edit and history decodes, obsolete loads, bitmap cleanup, delayed import feedback, Display P3 import/history fidelity, chosen layer-order preservation, profiled 3D layers and watertight 3MF regions, shared Auto-paint and Palette Proof pixels without additional decodes, builds disabled during pending history loads, and EXIF-rotated Stack Matrix photos. + +### Fixed + +- **Exporting during a rebuild** - Downloading an STL or 3MF, or using **Open in Slicer**, in the moment after **Build** is clicked could export the previous build's mesh with the new build's settings. For example, a routed multi-head model rebuilt as single-head could export the old head assignments without their swap pause. The old model is no longer offered for export once a new build starts. The 3D download menu stays disabled until the build finishes, and the preview actions behind the build overlay can no longer be reached by keyboard or screen reader. Added a browser regression that holds a multi-head to single-head rebuild open and checks that the keyboard cannot reach the export controls, and that the finished export matches the new build. +- **Concurrent 2D edits (#163)** - Quantize and dedither now block competing image edits, imports and undo/redo until they finish, and stale asynchronous results (resize, crop, bake, swatch apply, imports) are discarded once the image or processing state changes. An open text draft is kept if processing produces no output. Brush, eraser and text edits not yet saved to history when processing starts are rolled back instead of staying on the canvas without an undo step, and a pending slider adjustment (from the keyboard or a just-released drag) is committed as soon as focus moves to another control instead of being refused by processing that starts on the same click. Playwright regressions cover each race. +- **Touch-up history (#153)** - Cropping right after a brush, eraser, or text touch-up keeps the visible edit instead of cropping the image from before it. Undo restores each of several rapid touch-ups even when their saves finish before the preview redraws. A touch-up that cannot be saved to history returns the preview to the latest saved edit, cancels later unsaved strokes, and lets new strokes be saved. Added browser regressions for cropping live touch-ups, batched saves, and failed saves. +- **First color height stability** - Preserve the first-layer offset when image changes recompute swatches, so valid color heights do not drift by a layer when the first-layer height is not a multiple of the normal layer height. Keep user-selected color order and heights when resizing adds or removes colors, keep the order chosen by the height reset, apply a First Layer Height change made without an image when the image returns, and keep other colors on normal layer increments. Added repeated-reconciliation, swap-plan and browser history, reset and no-image regression tests. +- **Oversized image imports** - Choosing or dropping an image beyond a conservative canvas budget now shows a localized error that names the image size and keeps the current image, undo history, and swatches. iPhone and iPad, including desktop browsing mode, use a lower pixel budget for compatibility with older Safari versions; the resize advice follows that budget. Thin panoramas beyond 32767 pixels still load when the browser supports their dimensions. Browsers with lower dimension limits are checked without allocating a full-size test canvas. Images remain importable when browser fingerprinting protection adds small amounts of canvas noise. The Loading Images and Troubleshooting guides explain recovery. Added unit coverage for dimension and area budgets, plus browser regressions for file-picker and drag-drop area rejection, iPhone/iPad limits, silent and throwing canvas failures, privacy noise on working and blank canvases, and valid panoramas. +- **Unreadable image imports** - Choosing or dropping a file that cannot be decoded as an image, including a truncated or partly damaged one, now shows a localized error in the 2D preview instead of failing silently or loading only part of the image. Truncated PNG, JPEG, and WebP files are detected from their file structure, so the macOS and Linux desktop apps, whose WebView otherwise decodes them partially, catch them too. The current image, its undo history, and its swatches are kept; previously the broken file replaced the current image in history. Image files that the platform reports without a file type are recognized by their extension. Non-image files use the same dismissible notice instead of a browser alert, and it closes when the image changes, including the next successful import, undo, edits, or removing the image. New imports are refused while quantize or dedither is running, so a finishing result cannot silently discard a newly chosen file. Stack Matrix photos go through the same check: a truncated or unreadable photo now reports that it could not be opened and keeps the photo already loaded, instead of loading only part of it. The Loading Images and Calibration Workflows guides describe this behavior. Added browser regression coverage for corrupt, truncated, and non-image files, for imports with no current image or no file type, for the notice closing after undo and redo, for drops during quantize, and for truncated and corrupt Stack Matrix photos, plus unit coverage for truncation detection and image file validation. +- **3D camera inside the model** - The 3D preview camera now stops at the model's surface instead of moving inside it, where the view went empty or clipped. Zooming in Perspective, panning in either projection, and zooming in Orthographic before switching back to Perspective all keep the camera just outside the model's bounding box, so flat prints can still be inspected up close. Close-ups also reduce an enlarged near clipping plane after an Orthographic zoom-out and projection switch, keeping nearby surfaces visible. Rebuilding a model now frames it the same way in Perspective and Orthographic view; Orthographic previously framed it about 15% tighter. The 3D guide describes the camera limits. Added framing, keep-out, orthographic-panning, near-clipping, and projection-switch regression coverage. +- **3D camera zoom when switching projections** - Returning from Orthographic to Perspective now keeps the zoom level set in Orthographic view, instead of jumping back to the distance the camera had before the switch. The camera keeps its viewing direction and target, and the visible depth range moves with it so zooming out does not clip the model or make stacked layers flicker. Rebuilding while in Orthographic view now frames the new model even after zooming. Added projection round-trip regression coverage. +- **Relief layer keyboard controls** - Arrow keys now move each Layer Preview handle by one physical print layer, including the first-layer boundary, without adding a rounding sliver at the top of taller models. Home/End and larger keyboard steps respect the selected range. Pointer positioning remains proportional to height. Added physical-boundary regression coverage and browser coverage for both handles, exact ten-layer moves, and rebuild recovery. +- **Reloading image files** - Choosing the same source image again reloads its original pixels after crop, resize, or other edits, instead of silently retaining the edited image. Added a browser regression for same-path reloads after resizing. +- **Desktop palette exports** - Save `.kpal` palettes through the native Save As dialog instead of WebView browser downloads, preserving browser downloads and surfacing write failures without changing saved palettes. Retry partial writes and treat stalled writes as failures with localized feedback; this applies to every desktop export saved through **Save As**, including images, models, profiles, and calibration files. Desktop saves write to a temporary file beside the chosen one and replace it only after the whole file is written, so a failed overwrite of an existing palette, profile, image, or model leaves the old file intact and removes the temporary file. Added cancellation, error, partial-write, overwrite-failure, and export-content regressions plus native replace/discard tests; recovery checks exclude automatic feedback dismissal. +- **Diagnostics folder (desktop)** - **Open folder** for Auto-paint diagnostics in Settings now shows its error when the system cannot open the folder, instead of counting as success as soon as the launcher started. +- **Cats Exact benchmark reproducibility** - The calibrated cats Exact benchmark from v4.2.0 passes again: an audit traced its stale replay expectation to intended prediction changes before refreshing it, and its fixture check now passes on fresh checkouts on every platform. + ## v4.2.0 - 2026-10-19 ### Upgrade notes diff --git a/README.md b/README.md index e7cfe85a..a2982769 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,10 @@ Read [AGENTS.md](AGENTS.md) for repository guidance and testing expectations. Th +## Awards + +Snapmaker Innovation Fund Winner + ## License [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). Copyright (C) 2025 vycdev. diff --git a/content/badges/innovation-fund-badge.png b/content/badges/innovation-fund-badge.png new file mode 100644 index 00000000..f5aaa295 Binary files /dev/null and b/content/badges/innovation-fund-badge.png differ diff --git a/content/badges/innovation-fund-badge.svg b/content/badges/innovation-fund-badge.svg new file mode 100644 index 00000000..eafe96bb --- /dev/null +++ b/content/badges/innovation-fund-badge.svg @@ -0,0 +1,15 @@ + +Snapmaker Innovation Fund Winner + + + + + + + + + + + +INNOVATION FUND WINNER + diff --git a/content/badges/innovation-fund-medal.png b/content/badges/innovation-fund-medal.png new file mode 100644 index 00000000..ea069691 Binary files /dev/null and b/content/badges/innovation-fund-medal.png differ diff --git a/content/badges/innovation-fund-medal.svg b/content/badges/innovation-fund-medal.svg new file mode 100644 index 00000000..87ed9eb9 --- /dev/null +++ b/content/badges/innovation-fund-medal.svg @@ -0,0 +1,18 @@ + +Snapmaker Innovation Fund Winner + + + + + + + + +INNOVATION FUND +WINNER + + + + + + diff --git a/content/badges/logo/snapmaker-icon-white.svg b/content/badges/logo/snapmaker-icon-white.svg new file mode 100644 index 00000000..d07a853b --- /dev/null +++ b/content/badges/logo/snapmaker-icon-white.svg @@ -0,0 +1,18 @@ + + + + + + + + + + \ No newline at end of file diff --git a/content/badges/logo/snapmaker-logo.svg b/content/badges/logo/snapmaker-logo.svg new file mode 100644 index 00000000..10ca7f01 --- /dev/null +++ b/content/badges/logo/snapmaker-logo.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/package-lock.json b/package-lock.json index 93c805d1..6ecf815f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kromacut", - "version": "4.2.0", + "version": "4.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kromacut", - "version": "4.2.0", + "version": "4.3.0", "license": "AGPL-3.0-only", "dependencies": { "@dnd-kit/core": "^6.3.1", diff --git a/package.json b/package.json index 597c07b7..a4dc9aac 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kromacut", "private": true, - "version": "4.2.0", + "version": "4.3.0", "license": "AGPL-3.0-only", "type": "module", "scripts": { @@ -16,10 +16,13 @@ "benchmark:calibrated-exact": "node --expose-gc --no-warnings --experimental-strip-types tests/benchmark/calibratedOptimizer.ts", "benchmark:calibrated-series": "node scripts/benchmark-calibrated-series.mjs", "benchmark:hotpaths": "node --no-warnings --experimental-strip-types tests/benchmark/performanceHotPaths.ts", + "benchmark:multi-head": "node --no-warnings --experimental-strip-types tests/benchmark/multiHeadAppearance.ts", "benchmark:meshing": "node --no-warnings --experimental-strip-types tests/benchmark/smoothMeshing.ts", "profile:calibrated": "node scripts/profile-calibrated.mjs", "profile:compare": "node scripts/compare-calibrated-profiles.mjs", "test:e2e": "playwright test --grep @smoke", + "test:e2e:all": "node scripts/run-e2e-suites.mjs", + "check:e2e": "node scripts/run-e2e-suites.mjs --check", "test:docs": "node --no-warnings --experimental-strip-types --test tests/docsContent.test.ts", "test:e2e:docs": "playwright test --config playwright.docs.config.ts", "test:e2e:not-found": "playwright test --config playwright.not-found.config.ts", diff --git a/playwright.config.ts b/playwright.config.ts index 04d165c2..a4c1d589 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,5 +1,8 @@ import { defineConfig, devices } from '@playwright/test'; +const port = Number(process.env.KROMACUT_E2E_PORT ?? 5173); +const baseURL = `http://127.0.0.1:${port}`; + export default defineConfig({ testDir: './tests/e2e', fullyParallel: false, @@ -10,7 +13,7 @@ export default defineConfig({ }, reporter: [['list'], ['html', { open: 'never' }]], use: { - baseURL: 'http://127.0.0.1:5173', + baseURL, acceptDownloads: true, actionTimeout: 30 * 1000, navigationTimeout: 60 * 1000, @@ -19,9 +22,10 @@ export default defineConfig({ video: 'off', }, webServer: { - command: 'npm run build && npm run preview -- --host 127.0.0.1 --port 5173 --strictPort', - url: 'http://127.0.0.1:5173', - reuseExistingServer: !process.env.CI, + command: `npm run build && npm run preview -- --host 127.0.0.1 --port ${port} --strictPort`, + url: baseURL, + // test:e2e:all never reuses a server, which may be serving another checkout. + reuseExistingServer: !process.env.CI && !process.env.KROMACUT_E2E_FRESH_SERVERS, timeout: 180 * 1000, }, projects: [ diff --git a/playwright.i18n.config.ts b/playwright.i18n.config.ts index 66c59837..2730ce43 100644 --- a/playwright.i18n.config.ts +++ b/playwright.i18n.config.ts @@ -14,7 +14,8 @@ export default defineConfig({ webServer: { command: 'npm run dev -- --host 127.0.0.1 --port 5192 --strictPort', url: 'http://127.0.0.1:5192', - reuseExistingServer: !process.env.CI, + // test:e2e:all never reuses a server, which may be serving another checkout. + reuseExistingServer: !process.env.CI && !process.env.KROMACUT_E2E_FRESH_SERVERS, timeout: 60000, }, projects: [ diff --git a/public/version.json b/public/version.json index 0f011c3d..41a577b1 100644 --- a/public/version.json +++ b/public/version.json @@ -1,19 +1,19 @@ { - "version": "4.2.0", - "download_url": "https://github.com/vycdev/Kromacut/releases/tag/v4.2.0", - "release_notes": "Kromacut 4.2.0 adds Smooth Meshing strengths (None, Minimal, Medium, and Aggressive), which now also work with Flat Paint, and lets the desktop app open .kfil, .kapp, and .kpal files directly. Height dithering in Auto-paint works again, Flat Paint and Layer Preview are more reliable, and Settings now links to Privacy and Terms. Saved smoothing settings carry over as Medium or None; existing profiles and palettes remain compatible. Rebuild Height dithering and Flat Paint models before printing, back up important profiles, and check new prints in your slicer.", + "version": "4.3.0", + "download_url": "https://github.com/vycdev/Kromacut/releases/tag/v4.3.0", + "release_notes": "Kromacut 4.3.0 adds Multi-head printing: Auto-paint can plan filament orders across 2–8 heads, build the matching model and Head Schedule, and export 3MF files with head assignments and M600 pause markers at swap checkpoints, explained in a new in-app guide. In the desktop app, Open in Slicer sends models straight to your slicer and can remember which one to use. Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z undo and redo 2D edits, long Auto-paint searches can be cancelled, and oversized or unreadable images now show a clear error while keeping your current image. A failed desktop save now leaves the file it was replacing intact. The 3D camera no longer moves inside the model, and a new Awards page celebrates Kromacut's Snapmaker Innovation Fund win. Existing profiles and palettes remain compatible. If your First Layer Height isn't a multiple of your Layer Height, check the first color's height when you rebuild older work. Check new prints in your slicer.", "release_notes_localized": { - "en": "Kromacut 4.2.0 adds Smooth Meshing strengths (None, Minimal, Medium, and Aggressive), which now also work with Flat Paint, and lets the desktop app open .kfil, .kapp, and .kpal files directly. Height dithering in Auto-paint works again, Flat Paint and Layer Preview are more reliable, and Settings now links to Privacy and Terms. Saved smoothing settings carry over as Medium or None; existing profiles and palettes remain compatible. Rebuild Height dithering and Flat Paint models before printing, back up important profiles, and check new prints in your slicer.", - "fr": "Kromacut 4.2.0 ajoute des niveaux de Maillage lissé (Aucun, Minimal, Moyen et Intensif), désormais compatibles avec la Peinture à plat, et permet à l’application de bureau d’ouvrir directement les fichiers .kfil, .kapp et .kpal. Le Tramage en hauteur de la Peinture automatique fonctionne de nouveau, la Peinture à plat et l’Aperçu des couches sont plus fiables, et les Paramètres renvoient désormais vers les pages Confidentialité et Conditions d’utilisation. Les réglages de lissage enregistrés deviennent Moyen ou Aucun ; les profils et palettes existants restent compatibles. Reconstruisez les modèles utilisant le Tramage en hauteur ou la Peinture à plat avant d’imprimer, sauvegardez vos profils importants et vérifiez les nouvelles impressions dans votre logiciel de découpage.", - "de": "Kromacut 4.2.0 bietet Stärkestufen für Geglättetes Netz (Keine, Minimal, Mittel und Stark), die jetzt auch mit Flat Paint funktionieren, und die Desktop-App öffnet .kfil-, .kapp- und .kpal-Dateien direkt. Höhen-Dithering in Auto-paint funktioniert wieder, Flat Paint und die Schichtvorschau arbeiten zuverlässiger, und die Einstellungen verlinken jetzt auf Datenschutz und Nutzungsbedingungen. Gespeicherte Glättungseinstellungen werden als Mittel oder Keine übernommen; bestehende Profile und Paletten bleiben kompatibel. Erstellen Sie Modelle mit Höhen-Dithering oder Flat Paint vor dem Drucken neu, sichern Sie wichtige Profile und prüfen Sie neue Drucke im Slicer.", - "it": "Kromacut 4.2.0 aggiunge i livelli di Mesh levigata (Nessuna, Minima, Media e Intensa), ora compatibili anche con Flat Paint, e consente all’app desktop di aprire direttamente i file .kfil, .kapp e .kpal. Il Dithering dell’altezza in Auto-paint funziona di nuovo, Flat Paint e l’Anteprima degli strati sono più affidabili e le Impostazioni ora rimandano a Privacy e Termini e condizioni. Le impostazioni di levigatura salvate diventano Media o Nessuna; i profili e le palette esistenti restano compatibili. Ricostruisci i modelli con Dithering dell’altezza o Flat Paint prima di stampare, esegui una copia di sicurezza dei profili importanti e verifica le nuove stampe nello slicer.", - "ro": "Kromacut 4.2.0 adaugă niveluri pentru Geometrie netezită (Fără, Minimă, Medie și Intensă), care funcționează acum și cu Flat Paint, iar aplicația desktop poate deschide direct fișierele .kfil, .kapp și .kpal. Opțiunea Dithering al înălțimii din Auto-paint funcționează din nou, Flat Paint și Previzualizarea straturilor sunt mai fiabile, iar Setările includ acum linkuri către Confidențialitate și Termeni și condiții. Setările de netezire salvate devin Medie sau Fără; profilurile și paletele existente rămân compatibile. Reconstruiește modelele cu Dithering al înălțimii sau Flat Paint înainte de imprimare, fă copii de siguranță ale profilurilor importante și verifică imprimările noi în slicer.", - "es": "Kromacut 4.2.0 añade niveles de Malla suavizada (Ninguno, Mínimo, Medio e Intenso), que ahora también funcionan con Pintura plana, y permite que la aplicación de escritorio abra directamente archivos .kfil, .kapp y .kpal. El Tramado de altura de la Pintura automática vuelve a funcionar, la Pintura plana y la Vista previa de capas son más fiables, y los Ajustes ahora enlazan a Privacidad y Términos y condiciones. Los ajustes de suavizado guardados pasan a Medio o Ninguno; los perfiles y paletas existentes siguen siendo compatibles. Reconstruye los modelos con Tramado de altura o Pintura plana antes de imprimir, haz copias de seguridad de los perfiles importantes y revisa las nuevas impresiones en tu laminador.", - "ja": "Kromacut 4.2.0では、滑らかなメッシュの強さ(なし、最小、中、強)を選べるようになり、フラット印刷でも使用できます。デスクトップアプリで.kfil、.kapp、.kpalファイルを直接開けるようになりました。自動ペイントの高さディザリングが再び機能し、フラット印刷とレイヤープレビューの信頼性が向上し、設定からプライバシーと利用規約を開けるようになりました。保存済みのスムージング設定は「中」または「なし」として引き継がれ、既存のプロファイルとパレットの互換性は維持されます。高さディザリングまたはフラット印刷を使うモデルは印刷前に再ビルドし、重要なプロファイルをバックアップして、新しい印刷データをスライサーで確認してください。", - "zh-CN": "Kromacut 4.2.0 新增平滑网格强度(无、轻度、中度、强度),现在也可用于平面打印模式;桌面应用现可直接打开 .kfil、.kapp 和 .kpal 文件。自动配色中的高度抖动已恢复正常,平面打印模式和层预览更加可靠,设置中现已提供隐私与使用条款链接。已保存的平滑设置将转换为“中度”或“无”;现有配置文件和调色板仍然兼容。使用高度抖动或平面打印模式的模型请在打印前重新生成,请备份重要配置文件,并在切片软件中检查新的打印模型。", - "hi": "Kromacut 4.2.0 में चिकनी मेशिंग के स्तर (कोई नहीं, न्यूनतम, मध्यम और तीव्र) जोड़े गए हैं, जो अब समतल प्रिंट मोड के साथ भी काम करते हैं, और डेस्कटॉप ऐप अब .kfil, .kapp और .kpal फ़ाइलें सीधे खोल सकता है। स्वचालित रंगाई में ऊँचाई डिथरिंग फिर से काम करती है, समतल प्रिंट मोड और परत पूर्वावलोकन अधिक भरोसेमंद हैं, और सेटिंग्स में अब गोपनीयता और नियम व शर्तों के लिंक हैं। सहेजी गई स्मूदिंग सेटिंग्स मध्यम या कोई नहीं के रूप में बनी रहती हैं; मौजूदा प्रोफ़ाइल और पैलेट संगत बने रहते हैं। ऊँचाई डिथरिंग या समतल प्रिंट मोड वाले मॉडल प्रिंट से पहले फिर से बनाएँ, महत्वपूर्ण प्रोफ़ाइल का बैकअप लें और नए प्रिंट को अपने स्लाइसर में जाँचें।", - "pt-PT": "O Kromacut 4.2.0 adiciona níveis de Malha suavizada (Nenhuma, Mínima, Média e Intensa), que agora também funcionam com a Pintura plana, e permite que a aplicação de computador abra diretamente ficheiros .kfil, .kapp e .kpal. O Pontilhamento em altura da Pintura automática volta a funcionar, a Pintura plana e a Pré-visualização de camadas estão mais fiáveis, e as Definições incluem agora ligações para Privacidade e Termos e condições. As definições de suavização guardadas passam a Média ou Nenhuma; os perfis e as paletas existentes continuam compatíveis. Reconstrua os modelos com Pontilhamento em altura ou Pintura plana antes de imprimir, faça cópias de segurança dos perfis importantes e verifique as novas impressões no seu programa de corte.", - "uk": "Kromacut 4.2.0 додає рівні параметра «Згладжена сітка» (Без згладжування, Мінімальне, Середнє та Інтенсивне), які тепер працюють і з Flat Paint, а настільний застосунок може безпосередньо відкривати файли .kfil, .kapp і .kpal. Дизеринг висоти в Auto-paint знову працює, Flat Paint і Перегляд шарів стали надійнішими, а в Налаштуваннях з’явилися посилання на Конфіденційність і Умови користування. Збережені налаштування згладжування переходять у Середнє або Без згладжування; наявні профілі та палітри залишаються сумісними. Перед друком перебудуйте моделі з дизерингом висоти або Flat Paint, створіть резервні копії важливих профілів і перевіряйте нові моделі для друку у слайсері.", - "bn": "Kromacut 4.2.0-তে মসৃণ মেশের স্তর (কোনোটিই নয়, ন্যূনতম, মাঝারি ও তীব্র) যোগ করা হয়েছে, যা এখন সমতল প্রিন্ট মোডেও কাজ করে, এবং ডেস্কটপ অ্যাপ এখন সরাসরি .kfil, .kapp ও .kpal ফাইল খুলতে পারে। স্বয়ংক্রিয় রং-এর উচ্চতার ডিথারিং আবার কাজ করে, সমতল প্রিন্ট মোড ও স্তরের প্রিভিউ আরও নির্ভরযোগ্য হয়েছে, এবং সেটিংসে এখন গোপনীয়তা ও নিয়ম ও শর্তাবলির লিংক রয়েছে। সংরক্ষিত মসৃণকরণ সেটিং মাঝারি বা কোনোটিই নয় হিসেবে বহাল থাকে; বিদ্যমান প্রোফাইল ও প্যালেট সামঞ্জস্যপূর্ণ থাকে। উচ্চতার ডিথারিং বা সমতল প্রিন্ট মোড ব্যবহার করা মডেল প্রিন্টের আগে আবার তৈরি করুন, গুরুত্বপূর্ণ প্রোফাইলের ব্যাকআপ নিন এবং নতুন প্রিন্টগুলো আপনার স্লাইসারে পরীক্ষা করুন।" + "en": "Kromacut 4.3.0 adds Multi-head printing: Auto-paint can plan filament orders across 2–8 heads, build the matching model and Head Schedule, and export 3MF files with head assignments and M600 pause markers at swap checkpoints, explained in a new in-app guide. In the desktop app, Open in Slicer sends models straight to your slicer and can remember which one to use. Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z undo and redo 2D edits, long Auto-paint searches can be cancelled, and oversized or unreadable images now show a clear error while keeping your current image. A failed desktop save now leaves the file it was replacing intact. The 3D camera no longer moves inside the model, and a new Awards page celebrates Kromacut's Snapmaker Innovation Fund win. Existing profiles and palettes remain compatible. If your First Layer Height isn't a multiple of your Layer Height, check the first color's height when you rebuild older work. Check new prints in your slicer.", + "fr": "Kromacut 4.3.0 ajoute l’Impression multi-têtes : la Peinture automatique peut planifier l’ordre des filaments sur 2 à 8 têtes, générer le modèle et le Planning des têtes correspondants, et exporter des fichiers 3MF avec les affectations des têtes et des marqueurs de pause M600 aux points de changement, le tout expliqué dans un nouveau guide intégré. Dans l’application de bureau, Ouvrir dans le logiciel de découpe envoie les modèles directement à votre logiciel de découpe et peut mémoriser celui à utiliser. Ctrl/Cmd+Z et Ctrl/Cmd+Maj+Z annulent et rétablissent les modifications 2D, les longues recherches de la Peinture automatique peuvent être annulées, et les images trop grandes ou illisibles affichent désormais une erreur claire tout en conservant l’image actuelle. Dans l’application de bureau, un enregistrement qui échoue laisse désormais intact le fichier qu’il devait remplacer. La caméra 3D ne pénètre plus dans le modèle, et une nouvelle page Récompenses célèbre la victoire de Kromacut au Snapmaker Innovation Fund. Les profils et palettes existants restent compatibles. Si votre Hauteur de première couche n’est pas un multiple de votre Hauteur de couche, vérifiez la hauteur de la première couleur lorsque vous reconstruisez d’anciens travaux. Vérifiez les nouvelles impressions dans votre logiciel de découpe.", + "de": "Kromacut 4.3.0 bietet Mehrkopfdruck: Auto-paint kann Filamentreihenfolgen für 2–8 Druckköpfe planen, das passende Modell samt Druckkopfplan erstellen und 3MF-Dateien mit Druckkopfzuweisungen und M600-Pausenmarkierungen an den Wechselpunkten exportieren; eine neue Anleitung in der App erklärt den Ablauf. In der Desktop-App sendet „Im Slicer öffnen“ Modelle direkt an Ihren Slicer und kann sich den gewählten Slicer merken. Strg/Cmd+Z und Strg/Cmd+Umschalt+Z machen 2D-Bearbeitungen rückgängig bzw. stellen sie wieder her, lange Auto-paint-Suchen lassen sich abbrechen, und zu große oder nicht lesbare Bilder zeigen jetzt eine klare Fehlermeldung, während das aktuelle Bild erhalten bleibt. In der Desktop-App lässt ein fehlgeschlagenes Speichern die zu ersetzende Datei jetzt unverändert. Die 3D-Kamera bewegt sich nicht mehr in das Modell hinein, und eine neue Seite „Auszeichnungen“ würdigt Kromacuts Gewinn beim Snapmaker Innovation Fund. Bestehende Profile und Paletten bleiben kompatibel. Wenn Ihre „Höhe der ersten Schicht“ kein Vielfaches der „Schichthöhe“ ist, prüfen Sie beim Neuaufbau älterer Arbeiten die Höhe der ersten Farbe. Prüfen Sie neue Drucke im Slicer.", + "it": "Kromacut 4.3.0 aggiunge la Stampa multitesta: Auto-paint può pianificare l’ordine dei filamenti su 2–8 teste, generare il modello e il Programma delle teste corrispondenti ed esportare file 3MF con le assegnazioni delle teste e i marcatori di pausa M600 ai punti di cambio, il tutto spiegato in una nuova guida nell’app. Nell’app desktop, Apri nello slicer invia i modelli direttamente al tuo slicer e può ricordare quale usare. Ctrl/Cmd+Z e Ctrl/Cmd+Maiusc+Z annullano e ripristinano le modifiche 2D, le ricerche lunghe di Auto-paint si possono annullare e le immagini troppo grandi o illeggibili ora mostrano un errore chiaro mantenendo l’immagine attuale. Nell’app desktop, un salvataggio non riuscito ora lascia intatto il file che doveva sostituire. La fotocamera 3D non entra più all’interno del modello e una nuova pagina Premi celebra la vittoria di Kromacut allo Snapmaker Innovation Fund. I profili e le palette esistenti restano compatibili. Se l’Altezza del primo strato non è un multiplo dell’Altezza dello strato, controlla l’altezza del primo colore quando ricostruisci lavori precedenti. Verifica le nuove stampe nello slicer.", + "ro": "Kromacut 4.3.0 adaugă Imprimarea cu mai multe capete: Auto-paint poate planifica ordinea filamentelor pe 2–8 capete, poate genera modelul și Programul capetelor corespunzătoare și poate exporta fișiere 3MF cu atribuirea capetelor și marcaje de pauză M600 la punctele de schimbare, totul explicat într-un ghid nou din aplicație. În aplicația desktop, Deschide în slicer trimite modelele direct în slicerul tău și poate reține ce slicer să folosească. Ctrl/Cmd+Z și Ctrl/Cmd+Shift+Z anulează și refac editările 2D, căutările lungi Auto-paint pot fi anulate, iar imaginile prea mari sau care nu pot fi citite afișează acum o eroare clară și păstrează imaginea curentă. În aplicația desktop, o salvare eșuată lasă acum intact fișierul pe care trebuia să-l înlocuiască. Camera 3D nu mai intră în interiorul modelului, iar o nouă pagină Premii marchează câștigarea Snapmaker Innovation Fund de către Kromacut. Profilurile și paletele existente rămân compatibile. Dacă Înălțimea primului strat nu este un multiplu al Înălțimii stratului, verifică înălțimea primei culori când reconstruiești lucrări mai vechi. Verifică imprimările noi în slicer.", + "es": "Kromacut 4.3.0 añade la Impresión multicabezal: la Pintura automática puede planificar el orden de los filamentos en 2–8 cabezales, generar el modelo y el Programa de cabezales correspondientes y exportar archivos 3MF con la asignación de cabezales y marcadores de pausa M600 en los puntos de cambio, todo explicado en una nueva guía de la aplicación. En la aplicación de escritorio, Abrir en el laminador envía los modelos directamente a tu laminador y puede recordar cuál usar. Ctrl/Cmd+Z y Ctrl/Cmd+Mayús+Z deshacen y rehacen las ediciones 2D, las búsquedas largas de la Pintura automática se pueden cancelar, y las imágenes demasiado grandes o ilegibles ahora muestran un error claro y conservan la imagen actual. En la aplicación de escritorio, un guardado fallido ahora deja intacto el archivo que iba a reemplazar. La cámara 3D ya no entra dentro del modelo, y una nueva página de Premios celebra que Kromacut ganó el Snapmaker Innovation Fund. Los perfiles y paletas existentes siguen siendo compatibles. Si tu Altura de la primera capa no es múltiplo de tu Altura de capa, revisa la altura del primer color al reconstruir trabajos anteriores. Revisa las nuevas impresiones en tu laminador.", + "ja": "Kromacut 4.3.0ではマルチヘッド印刷に対応しました。自動ペイントで2〜8個のヘッドにわたるフィラメントの順序を計画し、対応するモデルとヘッドスケジュールを作成して、ヘッドの割り当てと交換地点のM600一時停止マーカーを含む3MFファイルを書き出せます。使い方は新しいアプリ内ガイドで説明しています。デスクトップアプリでは「スライサーで開く」でモデルをスライサーに直接送り、使用するスライサーを記憶できます。Ctrl/Cmd+ZとCtrl/Cmd+Shift+Zで2D編集を元に戻す・やり直すことができ、時間のかかる自動ペイントの検索はキャンセルでき、大きすぎる画像や読み込めない画像は現在の画像を保ったまま分かりやすいエラーを表示するようになりました。デスクトップアプリでは、保存に失敗しても置き換え先の既存ファイルが損なわれなくなりました。3Dカメラがモデルの内部に入り込まなくなり、新しい受賞歴ページではKromacutのSnapmaker Innovation Fund受賞を紹介しています。既存のプロファイルとパレットの互換性は維持されます。「初層の高さ」が「レイヤー高さ」の倍数でない場合は、以前の作品を再構築するときに最初の色の高さを確認してください。新しい印刷データはスライサーで確認してください。", + "zh-CN": "Kromacut 4.3.0 新增多打印头打印:自动配色可为 2–8 个打印头规划耗材顺序,生成相应的模型和打印头计划,并导出包含打印头分配和换料检查点 M600 暂停标记的 3MF 文件,新的应用内指南提供了详细说明。在桌面应用中,“在切片软件中打开”可将模型直接发送到切片软件,并可记住要使用的切片软件。Ctrl/Cmd+Z 和 Ctrl/Cmd+Shift+Z 可撤销和重做 2D 编辑,耗时较长的自动配色搜索可以取消,过大或无法读取的图像现在会显示明确的错误并保留当前图像。在桌面应用中,保存失败时将不再损坏原本要替换的文件。3D 相机不再进入模型内部,新的奖项页面展示了 Kromacut 荣获 Snapmaker Innovation Fund 的成果。现有配置文件和调色板仍然兼容。如果“首层高度”不是“层高”的整数倍,重新构建旧作品时请检查第一种颜色的高度。请在切片软件中检查新的打印模型。", + "hi": "Kromacut 4.3.0 में मल्टी-हेड प्रिंटिंग जोड़ी गई है: स्वचालित रंगाई 2–8 हेड के लिए फ़िलामेंट का क्रम तय कर सकती है, उससे मेल खाता मॉडल और हेड का कार्यक्रम बना सकती है, और हेड आवंटन तथा बदलाव चेकपॉइंट पर M600 विराम मार्कर वाली 3MF फ़ाइलें निर्यात कर सकती है; एक नई इन-ऐप गाइड इसे समझाती है। डेस्कटॉप ऐप में, स्लाइसर में खोलें मॉडल को सीधे आपके स्लाइसर में भेजता है और याद रख सकता है कि कौन-सा स्लाइसर इस्तेमाल करना है। Ctrl/Cmd+Z और Ctrl/Cmd+Shift+Z से 2D संपादन पूर्ववत और फिर से किए जा सकते हैं, स्वचालित रंगाई की लंबी खोजें रद्द की जा सकती हैं, और बहुत बड़े या न पढ़े जा सकने वाले चित्र अब मौजूदा चित्र को बनाए रखते हुए स्पष्ट त्रुटि दिखाते हैं। डेस्कटॉप ऐप में, सहेजना विफल होने पर अब वह फ़ाइल सुरक्षित रहती है जिसे बदला जाना था। 3D कैमरा अब मॉडल के अंदर नहीं जाता, और नया पुरस्कार पेज Kromacut की Snapmaker Innovation Fund जीत को दर्शाता है। मौजूदा प्रोफ़ाइल और पैलेट संगत बने रहते हैं। अगर पहली परत की ऊँचाई परत की ऊँचाई का गुणज नहीं है, तो पुराने काम को दोबारा बनाते समय पहले रंग की ऊँचाई जाँचें। नए प्रिंट को अपने स्लाइसर में जाँचें।", + "pt-PT": "O Kromacut 4.3.0 adiciona a Impressão multicabeças: a Pintura automática pode planear a ordem dos filamentos em 2–8 cabeças, gerar o modelo e o Plano das cabeças correspondentes e exportar ficheiros 3MF com a atribuição das cabeças e marcadores de pausa M600 nos pontos de mudança, tudo explicado num novo guia na aplicação. Na aplicação de computador, Abrir no laminador envia os modelos diretamente para o seu laminador e pode memorizar qual utilizar. Ctrl/Cmd+Z e Ctrl/Cmd+Shift+Z anulam e refazem as edições 2D, as pesquisas longas da Pintura automática podem ser canceladas, e as imagens demasiado grandes ou ilegíveis mostram agora um erro claro e mantêm a imagem atual. Na aplicação de computador, uma gravação falhada deixa agora intacto o ficheiro que ia substituir. A câmara 3D já não entra no interior do modelo, e uma nova página de Prémios celebra a vitória do Kromacut no Snapmaker Innovation Fund. Os perfis e as paletas existentes continuam compatíveis. Se a Altura da primeira camada não for múltipla da Altura de camada, verifique a altura da primeira cor ao reconstruir trabalhos anteriores. Verifique as novas impressões no seu laminador.", + "uk": "Kromacut 4.3.0 додає Багатоголовковий друк: Auto-paint може планувати порядок філаментів для 2–8 головок, створювати відповідну модель і Розклад головок та експортувати файли 3MF із призначенням головок і маркерами паузи M600 у точках заміни, а новий посібник у застосунку пояснює, як це працює. У настільному застосунку «Відкрити в слайсері» надсилає моделі просто у ваш слайсер і може запам’ятати, який слайсер використовувати. Ctrl/Cmd+Z і Ctrl/Cmd+Shift+Z скасовують і повторюють редагування у 2D, тривалі пошуки Auto-paint можна скасувати, а завеликі чи нечитабельні зображення тепер показують зрозумілу помилку й зберігають поточне зображення. У настільному застосунку невдале збереження тепер не пошкоджує файл, який мало замінити. 3D-камера більше не заходить усередину моделі, а нова сторінка «Нагороди» розповідає про перемогу Kromacut у Snapmaker Innovation Fund. Наявні профілі та палітри залишаються сумісними. Якщо «Висота першого шару» не кратна значенню «Висота шару», під час повторної побудови старих робіт перевірте висоту першого кольору. Нові моделі для друку перевіряйте у слайсері.", + "bn": "Kromacut 4.3.0-তে মাল্টি-হেড প্রিন্টিং যোগ করা হয়েছে: স্বয়ংক্রিয় রং 2–8টি হেডে ফিলামেন্টের ক্রম পরিকল্পনা করতে, মিলিয়ে মডেল ও হেডের সময়সূচি তৈরি করতে এবং হেড বরাদ্দ ও বদলানোর চেকপয়েন্টে M600 বিরতি চিহ্নসহ 3MF ফাইল রপ্তানি করতে পারে; একটি নতুন ইন-অ্যাপ গাইড এটি ব্যাখ্যা করে। ডেস্কটপ অ্যাপে স্লাইসারে খুলুন মডেলকে সরাসরি আপনার স্লাইসারে পাঠায় এবং কোন স্লাইসার ব্যবহার করতে হবে তা মনে রাখতে পারে। Ctrl/Cmd+Z ও Ctrl/Cmd+Shift+Z দিয়ে 2D সম্পাদনা পূর্বাবস্থায় ফেরানো ও আবার করা যায়, স্বয়ংক্রিয় রং-এর দীর্ঘ অনুসন্ধান বাতিল করা যায়, এবং অতিরিক্ত বড় বা পড়া যায় না এমন ছবি এখন বর্তমান ছবি রেখে একটি স্পষ্ট ত্রুটি দেখায়। ডেস্কটপ অ্যাপে সংরক্ষণ ব্যর্থ হলে এখন যে ফাইলটি প্রতিস্থাপন করার কথা ছিল সেটি অক্ষত থাকে। 3D ক্যামেরা আর মডেলের ভেতরে ঢোকে না, এবং নতুন পুরস্কার পেজে Kromacut-এর Snapmaker Innovation Fund জয় তুলে ধরা হয়েছে। বিদ্যমান প্রোফাইল ও প্যালেট সামঞ্জস্যপূর্ণ থাকে। প্রথম স্তরের উচ্চতা যদি স্তরের উচ্চতার গুণিতক না হয়, তবে পুরোনো কাজ আবার তৈরি করার সময় প্রথম রঙের উচ্চতা পরীক্ষা করুন। নতুন প্রিন্টগুলো আপনার স্লাইসারে পরীক্ষা করুন।" } } diff --git a/scripts/build-winner-badges.mjs b/scripts/build-winner-badges.mjs new file mode 100644 index 00000000..b7159d82 --- /dev/null +++ b/scripts/build-winner-badges.mjs @@ -0,0 +1,211 @@ +// Maintenance-only generator for the Snapmaker Innovation Fund winner badges. +// Snapmaker's rules: use their official logo files unaltered, and state only +// "Snapmaker Innovation Fund Winner". Their dark wordmark goes in content/badges/logo/ +// as snapmaker-logo.(svg|png); until then a dashed placeholder marks the logo slot. An +// optional snapmaker-icon-white.(svg|png|jpg) (the white "ʃ" mark) fills the small badge's +// medal. Both badges carry their own light card, so one version suits any page background. +// Each SVG is also rendered to a 2x PNG with Playwright Chromium. WebKit (Safari, GitHub's +// iOS app, the macOS/Linux desktop webviews) ignores variable-font weights inside SVG images +// and draws the lettering at Oxanium's thinnest weight, so the README, website and app show +// the PNGs to look the same everywhere. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chromium } from '@playwright/test'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const output = path.join(root, 'content/badges'); +const logoDir = path.join(output, 'logo'); +mkdirSync(logoDir, { recursive: true }); + +const font = readFileSync(path.join(root, 'public/fonts/oxanium-v21-latin.woff2')).toString('base64'); +const fontStyle = ``; + +// Clockwise from 12 o'clock, sampled from the Kromacut K so the rim reads as the same spectrum. +const SPECTRUM = [ + '#dfd13b', + '#f0a21f', + '#ff6b1f', + '#ff2a3a', + '#ff1f85', + '#c01784', + '#5c1a93', + '#33137f', + '#0b238c', + '#0066b8', + '#009bcb', + '#00a07a', + '#4ab548', + '#bfcd35', +]; +const INK = '#121530'; +// viewBox of the official wordmark files. +const LOGO_ASPECT = 171.762 / 34; + +const hexToRgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)); +const rgbToHex = (rgb) => + `#${rgb.map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('')}`; +const mix = (a, b, t) => { + const [ra, rb] = [hexToRgb(a), hexToRgb(b)]; + return rgbToHex(ra.map((v, i) => v + (rb[i] - v) * t)); +}; +const spectrumAt = (u) => { + const x = (((u % 1) + 1) % 1) * SPECTRUM.length; + const i = Math.floor(x); + return mix(SPECTRUM[i], SPECTRUM[(i + 1) % SPECTRUM.length], x - i); +}; +const polar = (cx, cy, r, turn) => { + const a = turn * Math.PI * 2 - Math.PI / 2; + return [cx + r * Math.cos(a), cy + r * Math.sin(a)]; +}; +const pt = ([x, y]) => `${x.toFixed(2)},${y.toFixed(2)}`; + +function loadLogo(name) { + const mimes = { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg' }; + for (const [ext, mime] of Object.entries(mimes)) { + const file = path.join(logoDir, `${name}.${ext}`); + if (existsSync(file)) { + return `data:${mime};base64,${readFileSync(file).toString('base64')}`; + } + } + return null; +} + +// The logo is embedded byte-for-byte and only scaled, never redrawn or recolored. +function logoSlot(x, y, width) { + const height = width / LOGO_ASPECT; + const href = loadLogo('snapmaker-logo'); + if (href) { + return ``; + } + const stroke = '#9aa0b8'; + return `official Snapmaker logo`; +} + +function facetRing(cx, cy, rOuter, rFacet, count) { + const parts = []; + for (let i = 0; i < count; i++) { + const u0 = (i - 0.5) / count; + const u1 = (i + 0.5) / count; + const color = spectrumAt(i / count); + const a = polar(cx, cy, rOuter, u0); + const b = polar(cx, cy, rOuter, u1); + const m = polar(cx, cy, rFacet, i / count); + const base = mix(color, INK, 0.18); + const lit = mix(color, '#ffffff', 0.1); + // Same-color strokes hide the anti-aliasing seams between neighbouring facets. + parts.push(``); + parts.push(``); + } + return parts.join(''); +} + +function layerStrip(x, y, width, height, count) { + const w = width / count; + return Array.from( + { length: count }, + (_, i) => + `` + ).join(''); +} + +function medal() { + const size = 480; + const c = size / 2; + const band = { outer: 186, inner: 132, mid: 159 }; + const fontSize = 29; + const capHalf = fontSize * 0.36; + const rTop = band.mid - capHalf; + const rBottom = band.mid + capHalf; + const logoWidth = 212; + const logoHeight = logoWidth / LOGO_ASPECT; + const sparkle = (turn) => { + const [x, y] = polar(c, c, band.mid, turn); + return ``; + }; + return ` +Snapmaker Innovation Fund Winner +${fontStyle} + + + +${facetRing(c, c, 234, 206, 28)} + + + +INNOVATION FUND +WINNER + +${sparkle(0.25)}${sparkle(0.75)} + +${logoSlot(c - logoWidth / 2, c - logoHeight / 2 - 6, logoWidth)} +${layerStrip(c - 60, c + logoHeight / 2 + 12, 120, 6, 12)} + +`; +} + +// Snapmaker's mark on a dark disc when its file is present, otherwise a plain sparkle. +function medallion({ cx, cy, r }) { + const mark = loadLogo('snapmaker-icon-white'); + if (mark) { + // The official mark is already a dark disc, so it fills the centre as-is; the white + // ring is drawn over its edge rather than inside it. + const disc = r * 0.76; + return ``; + } + const disc = r * 0.66; + return ``; +} + +function ribbon() { + const width = 420; + const height = 96; + const icon = { cx: 50, cy: 46, r: 32 }; + const logoWidth = 150; + return ` +Snapmaker Innovation Fund Winner +${fontStyle} + + + + +${layerStrip(0, height - 8, width, 8, 28)} + + +${facetRing(icon.cx, icon.cy, icon.r, icon.r * 0.86, 20)} +${medallion(icon)} +${logoSlot(100, 20, logoWidth)} +INNOVATION FUND WINNER + +`; +} + +const files = { + 'innovation-fund-medal.svg': medal(), + 'innovation-fund-badge.svg': ribbon(), +}; +for (const [name, svg] of Object.entries(files)) { + writeFileSync(path.join(output, name), svg); + console.log(`wrote content/badges/${name} (${(svg.length / 1024).toFixed(1)} KB)`); +} + +const PNG_SCALE = 2; +const browser = await chromium.launch(); +try { + const page = await browser.newPage({ deviceScaleFactor: PNG_SCALE }); + for (const [name, svg] of Object.entries(files)) { + const href = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`; + await page.setContent( + `` + ); + await page.locator('#badge').evaluate((img) => img.decode()); + // Let the embedded font settle before capturing. + await page.waitForTimeout(500); + const png = await page.locator('#badge').screenshot({ omitBackground: true }); + const pngName = name.replace(/\.svg$/, '.png'); + writeFileSync(path.join(output, pngName), png); + console.log(`wrote content/badges/${pngName} (${(png.length / 1024).toFixed(1)} KB)`); + } +} finally { + await browser.close(); +} diff --git a/scripts/generate-docs-seo-pages.mjs b/scripts/generate-docs-seo-pages.mjs index 55a60963..b980dcc1 100644 --- a/scripts/generate-docs-seo-pages.mjs +++ b/scripts/generate-docs-seo-pages.mjs @@ -515,7 +515,7 @@ function writeNotFoundPage(template) { } function writeSitemap(docs) { - const urls = ['/', '/privacy', '/terms', ...docs.map((doc) => `/docs/${doc.slug}`)]; + const urls = ['/', '/privacy', '/terms', '/awards', ...docs.map((doc) => `/docs/${doc.slug}`)]; const body = urls .map((url) => ` ${siteUrl}${url === '/' ? '/' : url}`) .join('\n'); @@ -623,6 +623,75 @@ function writeLegalPage(template, kind) { writeFileSync(path.join(outputDir, 'index.html'), html); } +const SNAPMAKER_INNOVATION_FUND_URL = 'https://www.snapmaker.com/innovation-fund'; + +// Static twin of AwardsPage, so the page is crawlable and works without JavaScript. +function generateAwardsPage( + template, + catalog = JSON.parse(readFileSync(path.join(rootDir, 'src/locales/en/public.json'), 'utf8')) +) { + const logo = findBuiltAsset('logo-'); + const medal = findBuiltAsset('innovation-fund-medal-'); + const stylesheet = readdirSync(path.join(distDir, 'assets')).find( + (file) => + file.endsWith('.css') && + readFileSync(path.join(distDir, 'assets', file), 'utf8').includes('.awards-entry') + ); + if (!logo || !medal || !stylesheet) throw new Error('awards page assets are missing.'); + const { awards, landing, navigation } = catalog; + + let html = template + .replace(/]*type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>/gi, '') + .replace( + /]*rel="canonical"[^>]*>/gi, + `` + ) + .replace('', '') + .replace(/.*?<\/title>/, `<title>${escapeHtml(awards.seoTitle)}`) + .replace('', `\n`); + html = updateMeta(html, 'name', 'description', awards.description); + html = updateMeta(html, 'name', 'robots', 'index,follow'); + html = updateMeta(html, 'property', 'og:title', awards.seoTitle); + html = updateMeta(html, 'property', 'og:description', awards.description); + html = updateMeta(html, 'property', 'og:url', `${siteUrl}/awards`); + html = updateMeta(html, 'name', 'twitter:title', awards.seoTitle); + html = updateMeta(html, 'name', 'twitter:description', awards.description); + return html.replace( + /
<\/div>/, + `
+
+
+
+ Kromacut + ${escapeHtml(navigation.openApp)} +
+ + +
+
+
` + ); +} + +function writeAwardsPage(template) { + const outputDir = path.join(distDir, 'awards'); + mkdirSync(outputDir, { recursive: true }); + writeFileSync(path.join(outputDir, 'index.html'), generateAwardsPage(template)); +} + function writeRobots() { writeFileSync( path.join(distDir, 'robots.txt'), @@ -638,6 +707,7 @@ function verifyGeneratedOutput(docs) { 'docs/index.html', 'privacy/index.html', 'terms/index.html', + 'awards/index.html', 'robots.txt', 'sitemap.xml', 'site.webmanifest', @@ -676,6 +746,16 @@ function verifyGeneratedOutput(docs) { ); } + const awardsHtml = readFileSync(path.join(distDir, 'awards', 'index.html'), 'utf8'); + assertGenerated( + sitemap.includes('https://kromacut.com/awards') && + awardsHtml.includes('data-testid="awards-page"') && + awardsHtml.includes('', `${escapeHtml(catalog.navigation.home)}`); html = html.replace( - /href="\/(docs(?:\/[^"#?]*)?|privacy|terms)?([?#][^"]*)?"/g, + /href="\/(docs(?:\/[^"#?]*)?|privacy|terms|awards)?([?#][^"]*)?"/g, (_, pathname = '', suffix = '') => `href="${prefix(language, `/${pathname}`)}${suffix}"` ); return html; @@ -115,7 +116,13 @@ function write(filename, html) { writeFileSync(target, html); } -const urls = ['/', '/privacy', '/terms', ...sourceDocs.map((doc) => `/docs/${doc.slug}`)]; +const urls = [ + '/', + '/privacy', + '/terms', + '/awards', + ...sourceDocs.map((doc) => `/docs/${doc.slug}`), +]; for (const { code: language } of SUPPORTED_LANGUAGES) { if (language === 'en') continue; const dir = path.join(locales, language); @@ -200,6 +207,16 @@ for (const { code: language } of SUPPORTED_LANGUAGES) { html = localeHead(html, language, `/${kind}`, notice.seoTitle, notice.description); write(`${language}/${kind}/index.html`, html); } + write( + `${language}/awards/index.html`, + localeHead( + localizeShell(generateAwardsPage(template, catalog), language, catalog), + language, + '/awards', + catalog.awards.seoTitle, + catalog.awards.description + ) + ); const schema = JSON.stringify({ '@context': 'https://schema.org', '@type': 'SoftwareApplication', @@ -338,6 +355,16 @@ for (const { code } of SUPPORTED_LANGUAGES) { `${route}: missing image ${image}` ); } + if (route === '/awards') { + for (const text of [ + catalog.awards.title, + catalog.awards.intro, + catalog.landing.snapmakerInnovationFundWinner, + catalog.landing.aboutTheSnapmakerInnovationFund, + ]) { + assertOutput(html.includes(escapeHtml(text)), `${route}: untranslated ${text}`); + } + } if (route === '/privacy' || route === '/terms') { const kind = route.slice(1); const notice = readJson( diff --git a/scripts/run-e2e-suites.mjs b/scripts/run-e2e-suites.mjs new file mode 100644 index 00000000..486d91df --- /dev/null +++ b/scripts/run-e2e-suites.mjs @@ -0,0 +1,156 @@ +import { spawnSync } from 'node:child_process'; +import { readdirSync, readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// Every e2e suite that must pass before changes land, in run order. Area suites need their own +// server (Vite dev, Vite preview, or the Pages-style 404 server) on their own port, so each one is +// a separate Playwright run. The long @full export matrix in kromacut-flow.spec.ts is excluded; +// run it on demand with test:e2e:matrix, test:e2e:stress, or test:e2e:full. +const E2E_SUITES = [ + 'test:e2e', + 'test:e2e:docs', + 'test:e2e:landing', + 'test:e2e:privacy', + 'test:e2e:terms', + 'test:e2e:not-found', + 'test:e2e:i18n', + 'test:e2e:i18n:build', +]; +const ON_DEMAND_TAG = '@full'; + +const root = path.resolve(fileURLToPath(new URL('..', import.meta.url))); +const scripts = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).scripts; + +function suiteArgs(script) { + const command = scripts[script]; + const words = command?.trim().split(/\s+/) ?? []; + if (words[0] !== 'playwright' || words[1] !== 'test' || /[&|;<>"'`$]/.test(command)) { + throw new Error(`${script} must be a plain "playwright test ..." command`); + } + return words.slice(1); +} + +// A file-name-safe label, used for report folders and CI artifacts. +function suiteName(script) { + return script.replace(/^test:e2e:?/, '').replaceAll(':', '-') || 'smoke'; +} + +function configOf(args) { + const index = args.indexOf('--config'); + return index === -1 ? 'playwright.config.ts' : args[index + 1]; +} + +function playwright(args, options = {}) { + const cli = createRequire(import.meta.url).resolve('@playwright/test/cli'); + return spawnSync(process.execPath, [cli, ...args], { cwd: root, ...options }); +} + +function listTests(args) { + const result = playwright([...args, '--list', '--reporter=json'], { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + }); + let report; + try { + report = JSON.parse(result.stdout); + } catch { + // Reported below with stderr. + } + // The JSON reporter puts load errors, such as a spec that does not compile, in stdout. + const problems = report?.errors?.map((error) => error.message) ?? []; + if (result.status !== 0 || !report || problems.length > 0) { + const details = [...problems, result.stderr].join('\n').trim(); + throw new Error(`could not list tests for "${args.join(' ')}":\n${details}`); + } + const tests = new Map(); + const walk = (suite, titles) => { + for (const spec of suite.specs ?? []) { + const tags = spec.tags.map((tag) => `@${tag.replace(/^@/, '')}`); + tests.set([...titles, spec.title].join(' › '), tags); + } + for (const child of suite.suites ?? []) walk(child, [...titles, child.title]); + }; + for (const file of report.suites) walk(file, [file.file]); + return tests; +} + +// Fails when a Playwright config or test would be skipped by test:e2e:all. +function checkE2eCoverage() { + const errors = []; + const configs = new Set(E2E_SUITES.map((script) => configOf(suiteArgs(script)))); + for (const file of readdirSync(root)) { + if (/^playwright(\..+)?\.config\.ts$/.test(file) && !configs.has(file)) { + errors.push(`${file} is not run by any suite in scripts/run-e2e-suites.mjs`); + } + } + let all; + const covered = new Set(); + try { + for (const script of E2E_SUITES) { + for (const test of listTests(suiteArgs(script)).keys()) covered.add(test); + } + all = listTests(['test']); + } catch (error) { + return [...errors, error.message]; + } + for (const [test, tags] of all) { + if (!covered.has(test) && !tags.includes(ON_DEMAND_TAG)) { + errors.push( + `"${test}" is not run by any suite; tag it @smoke or match it in an area config` + ); + } + } + return errors; +} + +function runSuites(extraArgs) { + const failures = []; + for (const script of E2E_SUITES) { + const name = suiteName(script); + console.log(`\n=== ${script} (${scripts[script]})\n`); + const started = Date.now(); + // Keep each suite's traces and HTML report; later suites would otherwise delete them. + const result = playwright( + [...suiteArgs(script), '--output', `test-results/${name}`, ...extraArgs], + { + stdio: 'inherit', + env: { + ...process.env, + KROMACUT_E2E_FRESH_SERVERS: '1', + PLAYWRIGHT_HTML_OUTPUT_DIR: `playwright-report/${name}`, + }, + } + ); + const seconds = Math.round((Date.now() - started) / 1000); + const passed = result.status === 0; + console.log(`\n=== ${script} ${passed ? 'passed' : 'FAILED'} in ${seconds}s`); + if (!passed) failures.push(script); + } + return failures; +} + +// --list prints the suites as JSON for the CI job matrix, --check only checks coverage, and any +// other arguments are passed to every suite's Playwright run. +const args = process.argv.slice(2); +if (args[0] === '--list') { + console.log(JSON.stringify(E2E_SUITES.map((script) => ({ script, name: suiteName(script) })))); +} else { + const coverageErrors = checkE2eCoverage(); + for (const error of coverageErrors) console.error(`e2e coverage: ${error}`); + if (args[0] === '--check') { + if (coverageErrors.length === 0) { + console.log(`test:e2e:all covers every e2e test except ${ON_DEMAND_TAG}.`); + } + } else { + const failures = runSuites(args); + console.log( + failures.length === 0 + ? `\nAll ${E2E_SUITES.length} e2e suites passed.` + : `\nFailed e2e suites: ${failures.join(', ')}` + ); + if (failures.length > 0) process.exitCode = 1; + } + if (coverageErrors.length > 0) process.exitCode = 1; +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index a6214923..c8b08a91 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2126,9 +2126,12 @@ dependencies = [ [[package]] name = "kromacut" -version = "4.2.0" +version = "4.3.0" dependencies = [ + "embed-resource", + "gio", "log", + "percent-encoding", "reqwest 0.12.28", "serde", "serde_json", @@ -2139,6 +2142,7 @@ dependencies = [ "tauri-plugin-log", "tauri-plugin-single-instance", "tokio", + "windows-sys 0.61.2", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 60532f84..84476b6e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kromacut" -version = "4.2.0" +version = "4.3.0" description = "Kromacut - Multi-color lithophane 3D print generator" authors = ["vycdev"] license = "AGPL-3.0-only" @@ -16,9 +16,11 @@ crate-type = ["staticlib", "cdylib", "rlib"] [build-dependencies] tauri-build = { version = "2.6.0", features = [] } +embed-resource = "3" [dependencies] serde_json = "1.0" +percent-encoding = "2" serde = { version = "1.0", features = ["derive"] } log = "0.4" tauri = { version = "2.11.0", features = ["devtools"] } @@ -28,3 +30,12 @@ tokio = { version = "1", features = ["full"] } tauri-plugin-dialog = "2" tauri-plugin-fs = "2" tauri-plugin-single-instance = "2" + +[dev-dependencies] +tauri = { version = "2.11.0", features = ["devtools", "test"] } + +[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] +gio = "0.18" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Registry", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } diff --git a/src-tauri/build.rs b/src-tauri/build.rs index d860e1e6..c083ea5f 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,3 +1,34 @@ fn main() { - tauri_build::build() + let mut attributes = tauri_build::Attributes::new(); + // tauri-build links its Windows app manifest into binaries only, but the unit test executable + // links the same Tauri and dialog code. Without the manifest's Common Controls v6 dependency it + // fails to start with STATUS_ENTRYPOINT_NOT_FOUND. So embed the manifest ourselves, in every + // target. + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(); + if target_os == "windows" && target_env == "msvc" { + attributes = attributes + .windows_attributes(tauri_build::WindowsAttributes::new_without_app_manifest()); + embed_manifest_in_every_target(); + } + tauri_build::try_build(attributes).expect("failed to run tauri-build"); +} + +/// Writes tauri-build's default manifest into a resource script in tauri-winres' format, so the +/// app's embedded manifest bytes do not change, then links it into tests and libraries as well as +/// binaries. `windows/app-manifest.xml` is a verbatim copy of tauri-build 2.6.3's +/// `windows-app-manifest.xml`; re-diff it when upgrading tauri-build. Only `"` is escaped, the +/// one character tauri-winres escapes that the manifest contains. +fn embed_manifest_in_every_target() { + let manifest = include_str!("windows/app-manifest.xml"); + let mut script = String::from("#pragma code_page(65001)\n1 24\n{\n"); + for line in manifest.lines() { + script.push_str(&format!("\" {} \"\n", line.trim().replace('"', "\"\""))); + } + script.push_str("}\n"); + let path = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("app-manifest.rc"); + std::fs::write(&path, script).expect("failed to write the manifest resource script"); + embed_resource::compile_for_everything(&path, embed_resource::NONE) + .manifest_required() + .expect("failed to compile the manifest resource"); } diff --git a/src-tauri/src/default_app.rs b/src-tauri/src/default_app.rs new file mode 100644 index 00000000..21fb1191 --- /dev/null +++ b/src-tauri/src/default_app.rs @@ -0,0 +1,139 @@ +use std::io; +use std::path::Path; + +/// Dispatches a file or directory to its default application. Success means the OS accepted +/// the handoff, not that the application has finished using the file. Call off the UI thread. +#[cfg(target_os = "macos")] +pub fn open_with_default_app(path: &Path) -> io::Result<()> { + checked_launcher(std::process::Command::new("/usr/bin/open").arg(path)) +} + +#[cfg(target_os = "macos")] +pub(crate) fn checked_launcher(command: &mut std::process::Command) -> io::Result<()> { + // `open` exits after dispatch unless passed -W. Merely spawning it loses Launch Services + // failures such as a missing association, which are reported through its exit status. + let output = command.output()?; + if output.status.success() { + Ok(()) + } else { + Err(io::Error::other(format!( + "Default application launcher exited with {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))) + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +pub fn open_with_default_app(path: &Path) -> io::Result<()> { + use gio::prelude::FileExt; + + // GIO is already required by the Linux desktop runtime. Unlike waiting on xdg-open, + // this reports dispatch errors without potentially waiting until the slicer exits. + let uri = gio::File::for_path(path).uri(); + gio::AppInfo::launch_default_for_uri(&uri, None::<&gio::AppLaunchContext>) + .map_err(|error| io::Error::other(error.to_string())) +} + +#[cfg(target_os = "windows")] +pub fn open_with_default_app(path: &Path) -> io::Result<()> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Foundation::RPC_E_CHANGED_MODE; + use windows_sys::Win32::System::Com::{ + CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, + }; + use windows_sys::Win32::UI::Shell::{ + ShellExecuteExW, SEE_MASK_FLAG_NO_UI, SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + + let mut file: Vec = path.as_os_str().encode_wide().collect(); + if file.contains(&0) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Path contains NUL", + )); + } + file.push(0); + let mut info = SHELLEXECUTEINFOW { + cbSize: std::mem::size_of::() as u32, + fMask: SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI, + lpVerb: windows_sys::w!("open"), + lpFile: file.as_ptr(), + nShow: SW_SHOWNORMAL, + ..Default::default() + }; + + // SAFETY: COM is initialized for this worker thread. An existing apartment can be used + // without balancing its initialization; only our own successful calls are uninitialized. + let initialized = unsafe { + CoInitializeEx( + std::ptr::null(), + (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32, + ) + }; + if initialized < 0 && initialized != RPC_E_CHANGED_MODE { + return Err(io::Error::other(format!( + "Failed to initialize the application launcher: HRESULT {initialized:#x}" + ))); + } + // SAFETY: All pointers in `info` are null or valid NUL-terminated strings which outlive + // the call. NOASYNC waits for dispatch, not application exit. No process handle is kept. + let result = if unsafe { ShellExecuteExW(&mut info) } == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + }; + if initialized >= 0 { + // SAFETY: Balances the successful CoInitializeEx call on this thread. + unsafe { CoUninitialize() }; + } + result +} + +#[cfg(test)] +mod tests { + #[test] + fn native_dispatch_reports_a_missing_file() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let directory = std::env::temp_dir().join(format!( + "kromacut-launch-test-{}-{unique}", + std::process::id() + )); + std::fs::create_dir(&directory).unwrap(); + // The file is absent, so no application is launched. Windows errors are suppressed + // by SEE_MASK_FLAG_NO_UI; all platforms must return the failure to the caller. + let result = super::open_with_default_app(&directory.join("missing model.3mf")); + std::fs::remove_dir(&directory).unwrap(); + assert!(result.is_err()); + } +} + +#[cfg(all(test, target_os = "macos"))] +mod macos_tests { + use super::checked_launcher; + use std::process::Command; + + #[test] + fn launcher_reports_failure_after_a_successful_spawn() { + let error = checked_launcher( + Command::new("/bin/sh").args(["-c", "printf 'No application registered' >&2; exit 7"]), + ) + .unwrap_err(); + assert!(error.to_string().contains("7")); + assert!(error.to_string().contains("No application registered")); + } + + #[test] + fn launcher_accepts_a_successful_dispatch() { + checked_launcher(Command::new("/bin/sh").args(["-c", "exit 0"])).unwrap(); + } + + #[test] + fn launcher_reports_spawn_failure() { + assert!(checked_launcher(&mut Command::new("/dev/null/no-launcher")).is_err()); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 47202e77..08f3640a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -7,8 +7,16 @@ use std::process::Command; use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Manager, State}; +mod default_app; mod opened_files; +mod safe_save; +mod slicer_apps; +mod slicer_handoff; +use default_app::open_with_default_app; use opened_files::{enqueue_and_notify, take_opened_file, OpenedFiles}; +use safe_save::{begin_safe_file_save, discard_safe_file_save, finish_safe_file_save, SafeSaves}; +use slicer_apps::{find_slicer_app, list_slicer_apps, pick_slicer_app}; +use slicer_handoff::open_model_in_slicer; const RELEASES_URL: &str = "https://github.com/vycdev/Kromacut/releases"; @@ -147,26 +155,16 @@ fn finish_auto_paint_diagnostic( .map_err(|error| format!("Failed to close the diagnostic file: {error}")) } -fn open_directory(path: &Path) -> Result<(), String> { - #[cfg(target_os = "windows")] - let result = Command::new("explorer").arg(path).spawn(); - - #[cfg(target_os = "macos")] - let result = Command::new("open").arg(path).spawn(); - - #[cfg(all(unix, not(target_os = "macos")))] - let result = Command::new("xdg-open").arg(path).spawn(); - - result - .map(|_| ()) - .map_err(|error| format!("Failed to open the diagnostics directory: {error}")) -} - #[tauri::command] -fn open_auto_paint_diagnostics_directory(app: AppHandle) -> Result { +async fn open_auto_paint_diagnostics_directory(app: AppHandle) -> Result { let directory = auto_paint_diagnostics_directory(&app)?; - open_directory(&directory)?; - Ok(directory.to_string_lossy().into_owned()) + tauri::async_runtime::spawn_blocking(move || { + open_with_default_app(&directory) + .map_err(|error| format!("Failed to open the diagnostics directory: {error}"))?; + Ok(directory.to_string_lossy().into_owned()) + }) + .await + .map_err(|error| format!("Failed to run the directory launcher: {error}"))? } fn normalized_version(version: &str) -> &str { @@ -216,8 +214,8 @@ fn open_releases_page() -> Result<(), String> { fn legal_page_url(path: &str) -> Result { let segments: Vec<_> = path.strip_prefix('/').unwrap_or("").split('/').collect(); let supported = match segments.as_slice() { - ["privacy" | "terms"] => true, - [language, "privacy" | "terms"] => matches!( + ["privacy" | "terms" | "awards"] => true, + [language, "privacy" | "terms" | "awards"] => matches!( *language, "fr" | "de" | "it" | "ro" | "es" | "ja" | "zh-CN" | "hi" | "pt-PT" | "uk" | "bn" ), @@ -249,11 +247,17 @@ fn open_external_url(url: &str) -> Result<(), String> { .map_err(|e| format!("Failed to open web page: {}", e)) } +/// The app's config, assets and capabilities. The macro can only expand once per crate. +fn app_context() -> tauri::Context { + tauri::generate_context!() +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .manage(DiagnosticWriterState::default()) .manage(OpenedFiles::default()) + .manage(SafeSaves::default()) .plugin(tauri_plugin_single_instance::init(|app, args, cwd| { enqueue_and_notify( app, @@ -269,10 +273,17 @@ pub fn run() { open_releases_page, open_legal_page, take_opened_file, + begin_safe_file_save, + finish_safe_file_save, + discard_safe_file_save, begin_auto_paint_diagnostic, append_auto_paint_diagnostic, finish_auto_paint_diagnostic, - open_auto_paint_diagnostics_directory + open_auto_paint_diagnostics_directory, + open_model_in_slicer, + list_slicer_apps, + find_slicer_app, + pick_slicer_app ]) .setup(|app| { #[cfg(any(target_os = "windows", target_os = "linux"))] @@ -289,7 +300,7 @@ pub fn run() { } Ok(()) }) - .build(tauri::generate_context!()) + .build(app_context()) .expect("error while building tauri application") .run(|_app, _event| { #[cfg(target_os = "macos")] @@ -315,7 +326,7 @@ mod tests { for language in [ "", "fr", "de", "it", "ro", "es", "ja", "zh-CN", "hi", "pt-PT", "uk", "bn", ] { - for page in ["privacy", "terms"] { + for page in ["privacy", "terms", "awards"] { let path = if language.is_empty() { format!("/{page}") } else { @@ -337,6 +348,8 @@ mod tests { "/privacy&calc", "privacy", "/terms/", + "/awards/", + "/xx/awards", ] { assert!(super::legal_page_url(path).is_err(), "{path}"); } diff --git a/src-tauri/src/safe_save.rs b/src-tauri/src/safe_save.rs new file mode 100644 index 00000000..cfcffab4 --- /dev/null +++ b/src-tauri/src/safe_save.rs @@ -0,0 +1,429 @@ +//! Replaces a Save As destination only after its new contents are fully written. +//! +//! The webview streams the file into a temporary sibling through the fs plugin, then asks for +//! the sibling to be renamed over the destination. A failed or abandoned save removes the +//! sibling, so an existing file keeps its old contents. + +use std::collections::HashMap; +use std::fs::{remove_file, rename, OpenOptions}; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; +use tauri::{AppHandle, Manager, Runtime, State}; +use tauri_plugin_fs::FsExt; + +/// Temporary file paths handed to the webview, mapped to the destination each one replaces. +#[derive(Default)] +pub struct SafeSaves { + pending: Mutex>, +} + +fn create_temp_sibling(destination: &Path) -> Result { + let directory = destination + .parent() + .ok_or_else(|| "The save destination has no parent folder".to_string())?; + // Renaming can replace a read-only file that opening it for writing would refuse. + let replacing = match OpenOptions::new().write(true).open(destination) { + Ok(_) => true, + Err(error) if error.kind() == ErrorKind::NotFound => false, + Err(error) => return Err(format!("Failed to open the file for writing: {error}")), + }; + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + // Keep a replaced file's new contents private until the commit copies its mode. + #[cfg(unix)] + if replacing { + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + } + #[cfg(not(unix))] + let _ = replacing; + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis()) + .unwrap_or_default(); + for collision in 0..1_000_u16 { + let path = directory.join(format!(".kromacut-save-{stamp}-{collision}.tmp")); + match options.open(&path) { + Ok(_) => return Ok(path), + Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, + Err(error) => return Err(format!("Failed to create a temporary save file: {error}")), + } + } + Err("Could not allocate a unique temporary save file name".to_string()) +} + +fn discard_temp(temp: &Path) { + if let Err(error) = remove_file(temp) { + if error.kind() != ErrorKind::NotFound { + log::warn!("Failed to remove temporary save file {temp:?}: {error}"); + } + } +} + +fn commit_temp(temp: &Path, destination: &Path) -> Result<(), String> { + let result = (|| { + OpenOptions::new() + .write(true) + .open(temp) + .and_then(|file| file.sync_all()) + .map_err(|error| format!("Failed to flush the saved file: {error}"))?; + // Keep an existing file's Unix mode instead of the umask default. + // Best effort: some mounts (such as SMB shares) reject chmod but still accept the file. + #[cfg(unix)] + if let Ok(metadata) = std::fs::metadata(destination) { + if let Err(error) = std::fs::set_permissions(temp, metadata.permissions()) { + log::warn!("Failed to copy file permissions to {destination:?}: {error}"); + } + } + rename(temp, destination).map_err(|error| format!("Failed to replace the file: {error}")) + })(); + if result.is_err() { + discard_temp(temp); + } + result +} + +/// Whether the path is in the app's local data folder, which holds the webview data that the fs +/// plugin denies the webview by default. +fn is_in_app_local_data(app: &AppHandle, path: &Path) -> bool { + // Canonicalize the deepest folder that exists, so both sides compare in the same form even + // when one is missing (on Windows, canonical paths gain a `\\?\` prefix). + let canonical = |path: &Path| { + path.ancestors() + .find_map(|ancestor| { + let rest = path.strip_prefix(ancestor).ok()?; + Some(std::fs::canonicalize(ancestor).ok()?.join(rest)) + }) + .unwrap_or_else(|| path.to_path_buf()) + }; + match (app.path().app_local_data_dir(), path.parent()) { + (Ok(data), Some(directory)) => canonical(directory).starts_with(canonical(&data)), + _ => false, + } +} + +// Async commands run off the main thread, so flushing a large export does not freeze the UI. +#[tauri::command(async)] +pub fn begin_safe_file_save( + path: PathBuf, + app: AppHandle, + state: State<'_, SafeSaves>, +) -> Result { + // Replace the file a symlink points to, not the link, and check that same file below. + let path = match path.symlink_metadata() { + Ok(metadata) if metadata.file_type().is_symlink() => std::fs::canonicalize(&path) + .map_err(|error| format!("Failed to resolve the save destination: {error}"))?, + _ => path, + }; + let scope = app.fs_scope(); + if !scope.is_allowed(&path) { + return Err("The save destination was not chosen in a Save dialog".to_string()); + } + if is_in_app_local_data(&app, &path) { + return Err("Files cannot be saved in the app's data folder".to_string()); + } + let temp = create_temp_sibling(&path)?; + if let Err(error) = scope.allow_file(&temp) { + discard_temp(&temp); + return Err(format!("Failed to allow the temporary save file: {error}")); + } + let mut pending = state + .pending + .lock() + .map_err(|_| "Safe save lock was poisoned".to_string())?; + pending.insert(temp.clone(), path); + Ok(temp.to_string_lossy().into_owned()) +} + +fn take_pending( + app: &AppHandle, + state: &SafeSaves, + temp: &Path, +) -> Result, String> { + let destination = state + .pending + .lock() + .map_err(|_| "Safe save lock was poisoned".to_string())? + .remove(temp); + if destination.is_some() { + let _ = app.fs_scope().forbid_file(temp); + } + Ok(destination) +} + +#[tauri::command(async)] +pub fn finish_safe_file_save( + temp_path: PathBuf, + app: AppHandle, + state: State<'_, SafeSaves>, +) -> Result<(), String> { + let destination = take_pending(&app, &state, &temp_path)? + .ok_or_else(|| "Unknown or finished temporary save file".to_string())?; + commit_temp(&temp_path, &destination) +} + +#[tauri::command(async)] +pub fn discard_safe_file_save( + temp_path: PathBuf, + app: AppHandle, + state: State<'_, SafeSaves>, +) -> Result<(), String> { + if take_pending(&app, &state, &temp_path)?.is_some() { + discard_temp(&temp_path); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{commit_temp, create_temp_sibling, discard_temp}; + use std::fs::{create_dir_all, read, read_dir, remove_dir_all, write}; + use std::path::PathBuf; + + fn test_directory(name: &str) -> PathBuf { + let folder = format!("kromacut-safe-save-{name}-{}", std::process::id()); + let directory = std::env::temp_dir().join(folder); + let _ = remove_dir_all(&directory); + create_dir_all(&directory).unwrap(); + directory + } + + fn entries(directory: &PathBuf) -> Vec { + let mut names: Vec<_> = read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + } + + #[test] + fn commit_replaces_an_existing_file_with_the_complete_temp_contents() { + let directory = test_directory("commit"); + let destination = directory.join("palette.kpal"); + write(&destination, b"old palette").unwrap(); + let temp = create_temp_sibling(&destination).unwrap(); + assert_eq!(temp.parent(), destination.parent()); + write(&temp, b"new palette").unwrap(); + + commit_temp(&temp, &destination).unwrap(); + + assert_eq!(read(&destination).unwrap(), b"new palette"); + assert_eq!(entries(&directory), ["palette.kpal"]); + remove_dir_all(directory).unwrap(); + } + + #[test] + fn discarding_a_partial_temp_file_keeps_the_original_file() { + let directory = test_directory("discard"); + let destination = directory.join("palette.kpal"); + write(&destination, b"old palette").unwrap(); + let temp = create_temp_sibling(&destination).unwrap(); + write(&temp, b"new pal").unwrap(); + + discard_temp(&temp); + + assert_eq!(read(&destination).unwrap(), b"old palette"); + assert_eq!(entries(&directory), ["palette.kpal"]); + remove_dir_all(directory).unwrap(); + } + + #[test] + fn failed_commit_removes_the_temp_file() { + let directory = test_directory("failed-commit"); + let temp = create_temp_sibling(&directory.join("palette.kpal")).unwrap(); + write(&temp, b"new palette").unwrap(); + // A directory cannot be replaced by a file, so the rename fails on every platform. + let blocked = directory.join("blocked"); + create_dir_all(blocked.join("child")).unwrap(); + + assert!(commit_temp(&temp, &blocked).is_err()); + + assert_eq!(entries(&directory), ["blocked"]); + remove_dir_all(directory).unwrap(); + } + + #[cfg(unix)] + #[test] + fn read_only_files_are_not_replaced() { + use std::os::unix::fs::PermissionsExt; + let directory = test_directory("read-only"); + let destination = directory.join("palette.kpal"); + write(&destination, b"old palette").unwrap(); + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o444)).unwrap(); + + assert!(create_temp_sibling(&destination).is_err()); + + assert_eq!(read(&destination).unwrap(), b"old palette"); + assert_eq!(entries(&directory), ["palette.kpal"]); + remove_dir_all(directory).unwrap(); + } + + #[cfg(unix)] + #[test] + fn commit_keeps_the_existing_file_mode() { + use std::os::unix::fs::PermissionsExt; + let directory = test_directory("mode"); + let destination = directory.join("palette.kpal"); + write(&destination, b"old palette").unwrap(); + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o640)).unwrap(); + let temp = create_temp_sibling(&destination).unwrap(); + let mode = |path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&temp), 0o600); + write(&temp, b"new palette").unwrap(); + + commit_temp(&temp, &destination).unwrap(); + + assert_eq!(mode(&destination), 0o640); + remove_dir_all(directory).unwrap(); + } + + fn invoke( + webview: &tauri::WebviewWindow, + cmd: &str, + args: serde_json::Value, + ) -> Result { + let url = if cfg!(windows) { + "http://tauri.localhost" + } else { + "tauri://localhost" + }; + tauri::test::get_ipc_response( + webview, + tauri::webview::InvokeRequest { + cmd: cmd.into(), + callback: tauri::ipc::CallbackFn(0), + error: tauri::ipc::CallbackFn(1), + url: url.parse().unwrap(), + body: tauri::ipc::InvokeBody::Json(args), + headers: Default::default(), + invoke_key: tauri::test::INVOKE_KEY.to_string(), + }, + ) + .map(|body| body.deserialize().unwrap()) + } + + /// Runs the webview's save sequence against the app's real fs plugin scope and capabilities. + #[test] + fn webview_saves_replace_only_dialog_chosen_files_through_the_fs_plugin() { + use super::{begin_safe_file_save, discard_safe_file_save, finish_safe_file_save}; + use serde_json::json; + use tauri::Manager; + use tauri_plugin_fs::FsExt; + + let directory = test_directory("ipc"); + let destination = directory.join("palette.kpal"); + let unchosen = directory.join("other.kpal"); + write(&destination, b"old palette").unwrap(); + write(&unchosen, b"other palette").unwrap(); + let app = tauri::test::mock_builder() + .plugin(tauri_plugin_fs::init()) + .manage(super::SafeSaves::default()) + .invoke_handler(tauri::generate_handler![ + begin_safe_file_save, + finish_safe_file_save, + discard_safe_file_save + ]) + .build(crate::app_context()) + .unwrap(); + let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap(); + // The Save dialog allows exactly the chosen file. + app.fs_scope().allow_file(&destination).unwrap(); + + assert!(invoke( + &webview, + "begin_safe_file_save", + json!({ "path": unchosen }) + ) + .is_err()); + + let save = |path: &PathBuf, data: &[u8]| -> Result<(), serde_json::Value> { + let temp = invoke(&webview, "begin_safe_file_save", json!({ "path": path }))?; + let options = json!({ "read": false, "write": true, "create": true, "truncate": true }); + let rid = invoke( + &webview, + "plugin:fs|open", + json!({ "path": temp, "options": options }), + )?; + let written = invoke( + &webview, + "plugin:fs|write", + json!({ "rid": rid, "data": data }), + ); + invoke(&webview, "plugin:resources|close", json!({ "rid": rid }))?; + if written.is_err() || data.is_empty() { + invoke( + &webview, + "discard_safe_file_save", + json!({ "tempPath": temp }), + )?; + return Err(json!("abandoned")); + } + invoke( + &webview, + "finish_safe_file_save", + json!({ "tempPath": temp }), + )?; + // A finished temp file can no longer be written by the webview. + let reopened = invoke( + &webview, + "plugin:fs|open", + json!({ "path": temp, "options": options }), + ); + assert!(reopened.is_err(), "{reopened:?}"); + Ok(()) + }; + + assert!(save(&destination, b"").is_err()); + assert_eq!(read(&destination).unwrap(), b"old palette"); + assert_eq!(entries(&directory), ["other.kpal", "palette.kpal"]); + + save(&destination, b"new palette").unwrap(); + assert_eq!(read(&destination).unwrap(), b"new palette"); + assert_eq!(read(&unchosen).unwrap(), b"other palette"); + assert_eq!(entries(&directory), ["other.kpal", "palette.kpal"]); + + // Absolute and relative links to the chosen file update that file and stay links. + #[cfg(unix)] + { + let elsewhere = test_directory("ipc-link"); + let link = elsewhere.join("link.kpal"); + std::os::unix::fs::symlink(&destination, &link).unwrap(); + let relative = elsewhere.join("relative.kpal"); + let folder = directory.file_name().unwrap(); + std::os::unix::fs::symlink( + PathBuf::from("..").join(folder).join("palette.kpal"), + &relative, + ) + .unwrap(); + for (path, data) in [(&link, "linked palette"), (&relative, "relative palette")] { + let data = data.as_bytes(); + save(path, data).unwrap(); + assert!(path.symlink_metadata().unwrap().file_type().is_symlink()); + assert_eq!(read(&destination).unwrap(), data); + } + assert_eq!(entries(&elsewhere), ["link.kpal", "relative.kpal"]); + remove_dir_all(elsewhere).unwrap(); + } + + // The fs plugin denies the webview data folder, even for a dialog-chosen file. + let data_file = app + .path() + .app_local_data_dir() + .unwrap() + .join("kromacut-safe-save-test/palette.kpal"); + app.fs_scope().allow_file(&data_file).unwrap(); + assert_eq!( + invoke( + &webview, + "begin_safe_file_save", + json!({ "path": data_file }) + ), + Err(json!("Files cannot be saved in the app's data folder")) + ); + remove_dir_all(directory).unwrap(); + } +} diff --git a/src-tauri/src/slicer_apps.rs b/src-tauri/src/slicer_apps.rs new file mode 100644 index 00000000..79451baa --- /dev/null +++ b/src-tauri/src/slicer_apps.rs @@ -0,0 +1,955 @@ +use serde::Serialize; +use std::ffi::OsStr; +use std::fs::create_dir_all; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Command; +use tauri::{AppHandle, Manager}; +use tauri_plugin_dialog::DialogExt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + MacOs, + Windows, + Linux, +} + +#[cfg(target_os = "macos")] +const PLATFORM: Platform = Platform::MacOs; +#[cfg(target_os = "windows")] +const PLATFORM: Platform = Platform::Windows; +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +const PLATFORM: Platform = Platform::Linux; + +/// A slicer the user can open models with: an app bundle on macOS, an `.exe` on Windows and an +/// executable (including Flatpak's exported launchers) on Linux. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct SlicerApp { + name: String, + path: String, +} + +enum WindowsFolder { + /// A folder path below a programs directory. + Fixed(&'static [&'static str]), + /// Folders named ` `; the highest installed version wins. + Versioned(&'static str), +} + +struct WindowsInstall { + folder: WindowsFolder, + executable: &'static str, +} + +/// The usual install locations of the slicers Kromacut detects. Anything else can be picked +/// with Browse, so these only need to cover the official installers and packages. +struct Preset { + name: &'static str, + macos_bundles: &'static [&'static str], + windows_installs: &'static [WindowsInstall], + linux_commands: &'static [&'static str], + flatpak_ids: &'static [&'static str], +} + +const PRESETS: &[Preset] = &[ + Preset { + name: "Bambu Studio", + macos_bundles: &["BambuStudio.app"], + windows_installs: &[WindowsInstall { + folder: WindowsFolder::Fixed(&["Bambu Studio"]), + executable: "bambu-studio.exe", + }], + linux_commands: &["bambu-studio"], + flatpak_ids: &["com.bambulab.BambuStudio"], + }, + Preset { + name: "Orca Slicer", + macos_bundles: &["OrcaSlicer.app"], + windows_installs: &[WindowsInstall { + folder: WindowsFolder::Fixed(&["OrcaSlicer"]), + executable: "orca-slicer.exe", + }], + linux_commands: &["orca-slicer"], + flatpak_ids: &[ + "com.orcaslicer.OrcaSlicer", + "io.github.softfever.OrcaSlicer", + ], + }, + Preset { + name: "PrusaSlicer", + macos_bundles: &["PrusaSlicer.app"], + windows_installs: &[WindowsInstall { + folder: WindowsFolder::Fixed(&["Prusa3D", "PrusaSlicer"]), + executable: "prusa-slicer.exe", + }], + linux_commands: &["prusa-slicer"], + flatpak_ids: &["com.prusa3d.PrusaSlicer"], + }, + Preset { + name: "UltiMaker Cura", + macos_bundles: &["UltiMaker Cura.app"], + // Windows file names ignore case, so this also finds the older "Ultimaker Cura" folders. + windows_installs: &[WindowsInstall { + folder: WindowsFolder::Versioned("UltiMaker Cura"), + executable: "UltiMaker-Cura.exe", + }], + linux_commands: &["cura"], + flatpak_ids: &["com.ultimaker.cura"], + }, +]; + +/// Flatpak installs a launcher named after the app ID here, in each installation directory. +const FLATPAK_EXPORTS: &str = "flatpak/exports/bin"; + +/// Directories searched for presets on each platform. +#[derive(Default)] +struct SearchRoots { + macos_applications: Vec, + windows_programs: Vec, + linux_path: Vec, + flatpak_exports: Vec, +} + +fn push_unique(paths: &mut Vec, path: PathBuf) { + if path.is_absolute() && !paths.contains(&path) { + paths.push(path); + } +} + +impl SearchRoots { + fn from_env() -> Self { + let env_path = |name: &str| std::env::var_os(name).map(PathBuf::from); + let home = env_path("HOME"); + let mut roots = Self::default(); + match PLATFORM { + Platform::MacOs => { + push_unique(&mut roots.macos_applications, "/Applications".into()); + if let Some(home) = &home { + push_unique(&mut roots.macos_applications, home.join("Applications")); + } + } + Platform::Windows => { + // ProgramW6432 is the 64-bit Program Files even for a 32-bit process. + for name in ["ProgramW6432", "ProgramFiles"] { + if let Some(path) = env_path(name) { + push_unique(&mut roots.windows_programs, path); + } + } + if let Some(local) = env_path("LOCALAPPDATA") { + push_unique(&mut roots.windows_programs, local.join("Programs")); + } + } + Platform::Linux => { + if let Some(path) = std::env::var_os("PATH") { + for directory in std::env::split_paths(&path) { + push_unique(&mut roots.linux_path, directory); + } + } + let data_home = env_path("XDG_DATA_HOME") + .filter(|path| path.is_absolute()) + .or_else(|| home.map(|home| home.join(".local").join("share"))); + if let Some(data_home) = data_home { + push_unique(&mut roots.flatpak_exports, data_home.join(FLATPAK_EXPORTS)); + } + push_unique( + &mut roots.flatpak_exports, + Path::new("/var/lib").join(FLATPAK_EXPORTS), + ); + } + } + roots + } +} + +fn has_extension(path: &Path, extension: &str) -> bool { + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|actual| actual.eq_ignore_ascii_case(extension)) +} + +#[cfg(unix)] +fn is_executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + path.metadata() + .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn is_executable_file(path: &Path) -> bool { + path.is_file() +} + +/// Whether `path` is something Kromacut can launch with a model on `platform`. +fn is_launchable(platform: Platform, path: &Path) -> bool { + path.is_absolute() + && match platform { + Platform::MacOs => has_extension(path, "app") && path.is_dir(), + Platform::Windows => has_extension(path, "exe") && path.is_file(), + Platform::Linux => is_executable_file(path), + } +} + +fn version_key(version: &str) -> Vec { + version + .split(|c: char| !c.is_ascii_digit()) + .filter_map(|part| part.parse().ok()) + .collect() +} + +/// Every ` ` folder in `programs` containing `executable`, with its version. +fn versioned_installs(programs: &Path, prefix: &str, executable: &str) -> Vec<(Vec, PathBuf)> { + let prefix = format!("{} ", prefix.to_ascii_lowercase()); + let Ok(entries) = std::fs::read_dir(programs) else { + return Vec::new(); + }; + entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let version = name.to_ascii_lowercase().strip_prefix(&prefix)?.to_string(); + let key = version_key(&version); + let path = entry.path().join(executable); + (!key.is_empty() && is_launchable(Platform::Windows, &path)).then_some((key, path)) + }) + .collect() +} + +/// The newest ` ` folder in `programs` containing `executable`. +fn newest_versioned_install(programs: &Path, prefix: &str, executable: &str) -> Option { + versioned_installs(programs, prefix, executable) + .into_iter() + .max_by(|(a, _), (b, _)| a.cmp(b)) + .map(|(_, path)| path) +} + +/// Whether `path` is any installed version of a preset that installs each version into its own +/// folder. Detection lists only the newest, but a slicer saved before an upgrade still works. +fn is_versioned_preset_install(platform: Platform, roots: &SearchRoots, path: &Path) -> bool { + platform == Platform::Windows + && roots.windows_programs.iter().any(|programs| { + PRESETS + .iter() + .flat_map(|preset| preset.windows_installs) + .any(|install| match install.folder { + WindowsFolder::Fixed(_) => false, + WindowsFolder::Versioned(prefix) => { + versioned_installs(programs, prefix, install.executable) + .iter() + .any(|(_, found)| found == path) + } + }) + }) +} + +fn find_preset(platform: Platform, preset: &Preset, roots: &SearchRoots) -> Option { + let candidates: Vec = match platform { + Platform::MacOs => roots + .macos_applications + .iter() + .flat_map(|root| preset.macos_bundles.iter().map(|bundle| root.join(bundle))) + .collect(), + Platform::Windows => { + return roots.windows_programs.iter().find_map(|programs| { + preset + .windows_installs + .iter() + .find_map(|install| match install.folder { + WindowsFolder::Fixed(folders) => { + let path = folders + .iter() + .fold(programs.clone(), |path, folder| path.join(folder)) + .join(install.executable); + is_launchable(platform, &path).then_some(path) + } + WindowsFolder::Versioned(prefix) => { + newest_versioned_install(programs, prefix, install.executable) + } + }) + }); + } + Platform::Linux => roots + .linux_path + .iter() + .flat_map(|root| preset.linux_commands.iter().map(|name| root.join(name))) + .chain( + roots + .flatpak_exports + .iter() + .flat_map(|root| preset.flatpak_ids.iter().map(|id| root.join(id))), + ) + .collect(), + }; + candidates + .into_iter() + .find(|path| is_launchable(platform, path)) +} + +fn detect_slicer_apps(platform: Platform, roots: &SearchRoots) -> Vec { + PRESETS + .iter() + .filter_map(|preset| { + let path = find_preset(platform, preset, roots)?; + Some(SlicerApp { + name: preset.name.to_string(), + path: path.to_string_lossy().into_owned(), + }) + }) + .collect() +} + +/// Names a launchable app after the preset it belongs to, or after its file name. +fn describe_slicer_app(platform: Platform, path: &Path) -> Option { + if !is_launchable(platform, path) { + return None; + } + let file_name = path.file_name()?.to_string_lossy(); + let preset = PRESETS.iter().find(|preset| match platform { + Platform::MacOs => preset + .macos_bundles + .iter() + .any(|bundle| bundle.eq_ignore_ascii_case(&file_name)), + Platform::Windows => preset + .windows_installs + .iter() + .any(|install| install.executable.eq_ignore_ascii_case(&file_name)), + Platform::Linux => preset + .linux_commands + .iter() + .chain(preset.flatpak_ids) + .any(|name| *name == file_name), + }); + let name = match preset { + Some(preset) => preset.name.to_string(), + None if platform == Platform::Linux => file_name.into_owned(), + None => path.file_stem()?.to_string_lossy().into_owned(), + }; + Some(SlicerApp { + name, + path: path.to_string_lossy().into_owned(), + }) +} + +/// The Flatpak app ID when `app` is one of Flatpak's exported launchers. +fn flatpak_app_id(app: &Path) -> Option<&str> { + app.parent()? + .ends_with(FLATPAK_EXPORTS) + .then(|| app.file_name()?.to_str()) + .flatten() +} + +fn launch_command(platform: Platform, app: &Path, model: &Path) -> Command { + if platform == Platform::MacOs { + let mut command = Command::new("/usr/bin/open"); + command.arg("-a").arg(app).arg(model); + return command; + } + if platform == Platform::Linux { + if let Some(id) = flatpak_app_id(app) { + // The exported launcher does not forward files, so the sandboxed slicer could not + // read Kromacut's cache. File forwarding grants it this one file. + let mut command = Command::new("flatpak"); + command + .args(["run", "--file-forwarding", id, "@@"]) + .arg(model) + .arg("@@"); + return command; + } + } + let mut command = Command::new(app); + command.arg(model); + if let Some(directory) = app.parent() { + command.current_dir(directory); + } + command +} + +/// Slicers picked with Browse are remembered here, in the app config directory. +const PICKED_APPS_FILE: &str = "picked-slicers.json"; +const MAX_PICKED_APPS: usize = 16; + +pub fn picked_apps_file(app: &AppHandle) -> Result { + app.path() + .app_config_dir() + .map(|directory| directory.join(PICKED_APPS_FILE)) + .map_err(|error| format!("Failed to resolve the app config directory: {error}")) +} + +/// A missing or unreadable file only means nothing was picked yet. +fn read_picked_apps(file: &Path) -> Vec { + std::fs::read(file) + .ok() + .and_then(|data| serde_json::from_slice(&data).ok()) + .unwrap_or_default() +} + +/// Adds `path` as the newest picked app and drops the oldest ones beyond the cap. `keep` is the +/// slicer saved for Open in Slicer: it is never dropped, or it could no longer be launched. +fn remember_picked_app(file: &Path, path: &str, keep: Option<&str>) -> Result<(), String> { + let mut picked = read_picked_apps(file); + picked.retain(|known| known != path); + picked.push(path.to_string()); + while picked.len() > MAX_PICKED_APPS { + let Some(oldest) = picked.iter().position(|known| Some(known.as_str()) != keep) else { + break; + }; + picked.remove(oldest); + } + if let Some(directory) = file.parent() { + create_dir_all(directory) + .map_err(|error| format!("Failed to create the app config directory: {error}"))?; + } + let data = serde_json::to_vec(&picked) + .map_err(|error| format!("Failed to encode the picked slicers: {error}"))?; + std::fs::write(file, data).map_err(|error| format!("Failed to remember the slicer: {error}")) +} + +/// Models are only opened with a detected preset or an app the user picked in the native +/// dialog, so the webview can never ask Kromacut to run an arbitrary program. +fn find_known_slicer_app( + platform: Platform, + roots: &SearchRoots, + picked_apps: &Path, + path: &Path, +) -> Option { + let known = detect_slicer_apps(platform, roots) + .into_iter() + .map(|app| app.path) + .chain(read_picked_apps(picked_apps)) + .any(|known| Path::new(&known) == path) + || is_versioned_preset_install(platform, roots, path); + if known { + describe_slicer_app(platform, path) + } else { + None + } +} + +/// Opens `model` with the slicer at `app`, which must be a detected or picked slicer. Like the +/// default-app handoff, success means the slicer was started, not that it has loaded the file. +/// Call off the UI thread. +pub fn open_with_slicer_app(app: &Path, model: &Path, picked_apps: &Path) -> io::Result<()> { + if find_known_slicer_app(PLATFORM, &SearchRoots::from_env(), picked_apps, app).is_none() { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("No detected or picked slicer at {}", app.display()), + )); + } + let mut command = launch_command(PLATFORM, app, model); + + #[cfg(target_os = "macos")] + return crate::default_app::checked_launcher(&mut command); + + #[cfg(not(target_os = "macos"))] + { + let mut child = command.spawn()?; + // The slicer keeps running after the handoff; reap it when it exits. + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) + } +} + +/// Slicers from the presets that are installed in their usual locations. +#[tauri::command] +pub async fn list_slicer_apps() -> Result, String> { + tauri::async_runtime::spawn_blocking(|| detect_slicer_apps(PLATFORM, &SearchRoots::from_env())) + .await + .map_err(|error| format!("Failed to look for slicers: {error}")) +} + +/// The detected or picked slicer at `path`, or `None` when it no longer exists, cannot be +/// launched, or was never detected or picked. +#[tauri::command] +pub async fn find_slicer_app(app: AppHandle, path: String) -> Result, String> { + let picked_apps = picked_apps_file(&app)?; + tauri::async_runtime::spawn_blocking(move || { + find_known_slicer_app( + PLATFORM, + &SearchRoots::from_env(), + &picked_apps, + Path::new(&path), + ) + }) + .await + .map_err(|error| format!("Failed to check the slicer: {error}")) +} + +/// Lets the user pick a slicer that is not in the presets. `None` means the dialog was +/// cancelled; picking something that cannot be launched is an error. `keep` is the path of the +/// saved slicer, which stays launchable however many other apps are picked. +#[tauri::command] +pub async fn pick_slicer_app( + app: AppHandle, + title: String, + filter_name: String, + keep: Option, +) -> Result, String> { + let picked_apps = picked_apps_file(&app)?; + let mut dialog = app.dialog().file().set_title(title); + match PLATFORM { + Platform::MacOs => { + dialog = dialog + .add_filter(filter_name, &["app"]) + .set_directory("/Applications"); + } + Platform::Windows => dialog = dialog.add_filter(filter_name, &["exe"]), + Platform::Linux => {} + } + tauri::async_runtime::spawn_blocking(move || { + let Some(picked) = dialog.blocking_pick_file() else { + return Ok(None); + }; + let path = picked + .into_path() + .map_err(|error| format!("Unsupported slicer location: {error}"))?; + let slicer = describe_slicer_app(PLATFORM, &path) + .ok_or_else(|| format!("Not a launchable app: {}", path.display()))?; + remember_picked_app(&picked_apps, &slicer.path, keep.as_deref())?; + Ok(Some(slicer)) + }) + .await + .map_err(|error| format!("Failed to run the slicer picker: {error}"))? +} + +#[cfg(test)] +mod tests { + use super::{ + describe_slicer_app, detect_slicer_apps, find_known_slicer_app, flatpak_app_id, + is_launchable, launch_command, read_picked_apps, remember_picked_app, Platform, + SearchRoots, SlicerApp, MAX_PICKED_APPS, + }; + use std::fs::{create_dir_all, remove_dir_all, write}; + use std::path::{Path, PathBuf}; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn test_directory(name: &str) -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let directory = + std::env::temp_dir().join(format!("kromacut-{name}-{}-{nanos}", std::process::id())); + create_dir_all(&directory).unwrap(); + directory + } + + fn touch(path: &Path) { + create_dir_all(path.parent().unwrap()).unwrap(); + write(path, b"").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + fn app(name: &str, path: &Path) -> SlicerApp { + SlicerApp { + name: name.to_string(), + path: path.to_string_lossy().into_owned(), + } + } + + fn args(command: &std::process::Command) -> Vec { + command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn detects_installed_macos_bundles_only() { + let root = test_directory("slicers-macos"); + let system = root.join("Applications"); + let user = root.join("home").join("Applications"); + create_dir_all(system.join("OrcaSlicer.app")).unwrap(); + create_dir_all(user.join("UltiMaker Cura.app")).unwrap(); + create_dir_all(user.join("OrcaSlicer.app")).unwrap(); + // A file with a bundle name is not an app. + touch(&system.join("PrusaSlicer.app")); + let roots = SearchRoots { + macos_applications: vec![system.clone(), user.clone()], + ..SearchRoots::default() + }; + + assert_eq!( + detect_slicer_apps(Platform::MacOs, &roots), + vec![ + app("Orca Slicer", &system.join("OrcaSlicer.app")), + app("UltiMaker Cura", &user.join("UltiMaker Cura.app")), + ] + ); + remove_dir_all(root).unwrap(); + } + + #[test] + fn detects_windows_installs_and_the_newest_cura() { + let root = test_directory("slicers-windows"); + let programs = root.join("Program Files"); + let local = root.join("Local").join("Programs"); + touch(&programs.join("Bambu Studio").join("bambu-studio.exe")); + touch( + &programs + .join("Prusa3D") + .join("PrusaSlicer") + .join("prusa-slicer.exe"), + ); + touch(&local.join("OrcaSlicer").join("orca-slicer.exe")); + for version in ["5.9.1", "5.10.0", "5.2.1"] { + touch( + &programs + .join(format!("UltiMaker Cura {version}")) + .join("UltiMaker-Cura.exe"), + ); + } + // A folder without its executable, or without a version, is not an install. + create_dir_all(programs.join("UltiMaker Cura 5.11.0")).unwrap(); + touch(&programs.join("UltiMaker Cura").join("UltiMaker-Cura.exe")); + let roots = SearchRoots { + windows_programs: vec![programs.clone(), local.clone()], + ..SearchRoots::default() + }; + + assert_eq!( + detect_slicer_apps(Platform::Windows, &roots), + vec![ + app( + "Bambu Studio", + &programs.join("Bambu Studio").join("bambu-studio.exe") + ), + app( + "Orca Slicer", + &local.join("OrcaSlicer").join("orca-slicer.exe") + ), + app( + "PrusaSlicer", + &programs + .join("Prusa3D") + .join("PrusaSlicer") + .join("prusa-slicer.exe") + ), + app( + "UltiMaker Cura", + &programs + .join("UltiMaker Cura 5.10.0") + .join("UltiMaker-Cura.exe") + ), + ] + ); + remove_dir_all(root).unwrap(); + } + + #[test] + fn detects_cura_folders_from_before_the_ultimaker_rename() { + let root = test_directory("slicers-windows-legacy"); + // Cura 5.2 and older install to "Ultimaker Cura ". + let exe = root.join("Ultimaker Cura 5.2.1").join("UltiMaker-Cura.exe"); + touch(&exe); + let roots = SearchRoots { + windows_programs: vec![root.clone()], + ..SearchRoots::default() + }; + + assert_eq!( + detect_slicer_apps(Platform::Windows, &roots), + vec![app("UltiMaker Cura", &exe)] + ); + remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn detects_linux_commands_before_flatpaks() { + use super::FLATPAK_EXPORTS; + + let root = test_directory("slicers-linux"); + let bin = root.join("bin"); + let user_flatpak = root.join("home").join(FLATPAK_EXPORTS); + let system_flatpak = root.join("var").join(FLATPAK_EXPORTS); + touch(&bin.join("prusa-slicer")); + touch(&system_flatpak.join("com.prusa3d.PrusaSlicer")); + touch(&system_flatpak.join("com.bambulab.BambuStudio")); + touch(&user_flatpak.join("com.orcaslicer.OrcaSlicer")); + // Not executable, so not launchable. + write(bin.join("cura"), b"").unwrap(); + let roots = SearchRoots { + linux_path: vec![bin.clone()], + flatpak_exports: vec![user_flatpak.clone(), system_flatpak.clone()], + ..SearchRoots::default() + }; + + assert_eq!( + detect_slicer_apps(Platform::Linux, &roots), + vec![ + app( + "Bambu Studio", + &system_flatpak.join("com.bambulab.BambuStudio") + ), + app( + "Orca Slicer", + &user_flatpak.join("com.orcaslicer.OrcaSlicer") + ), + app("PrusaSlicer", &bin.join("prusa-slicer")), + ] + ); + remove_dir_all(root).unwrap(); + } + + #[test] + fn describes_picked_apps_by_preset_or_file_name() { + let root = test_directory("slicers-describe"); + let bundle = root.join("PrusaSlicer.app"); + let custom_bundle = root.join("Creality Print.app"); + create_dir_all(&bundle).unwrap(); + create_dir_all(&custom_bundle).unwrap(); + let exe = root.join("ORCA-SLICER.EXE"); + let custom_exe = root.join("CrealityPrint.exe"); + let appimage = root.join("PrusaSlicer-2.9.0.AppImage"); + for path in [&exe, &custom_exe, &appimage] { + touch(path); + } + + assert_eq!( + describe_slicer_app(Platform::MacOs, &bundle), + Some(app("PrusaSlicer", &bundle)) + ); + assert_eq!( + describe_slicer_app(Platform::MacOs, &custom_bundle), + Some(app("Creality Print", &custom_bundle)) + ); + assert_eq!( + describe_slicer_app(Platform::Windows, &exe), + Some(app("Orca Slicer", &exe)) + ); + assert_eq!( + describe_slicer_app(Platform::Windows, &custom_exe), + Some(app("CrealityPrint", &custom_exe)) + ); + #[cfg(unix)] + assert_eq!( + describe_slicer_app(Platform::Linux, &appimage), + Some(app("PrusaSlicer-2.9.0.AppImage", &appimage)) + ); + remove_dir_all(root).unwrap(); + } + + #[test] + fn rejects_paths_that_cannot_be_launched() { + let root = test_directory("slicers-reject"); + let bundle = root.join("OrcaSlicer.app"); + create_dir_all(&bundle).unwrap(); + let exe = root.join("orca-slicer.exe"); + let model = root.join("model.3mf"); + touch(&exe); + touch(&model); + + for (platform, path) in [ + (Platform::MacOs, exe.clone()), + (Platform::MacOs, root.join("Missing.app")), + (Platform::MacOs, PathBuf::from("OrcaSlicer.app")), + (Platform::Windows, bundle.clone()), + (Platform::Windows, model.clone()), + (Platform::Windows, root.join("missing.exe")), + (Platform::Linux, bundle.clone()), + (Platform::Linux, root.join("missing")), + ] { + assert!(!is_launchable(platform, &path), "{platform:?} {path:?}"); + assert_eq!(describe_slicer_app(platform, &path), None); + } + // Off Unix hosts there is no executable bit, so a plain file passes the Linux check. + #[cfg(unix)] + { + let plain = root.join("notes.txt"); + write(&plain, b"").unwrap(); + assert!(!is_launchable(Platform::Linux, &plain)); + assert_eq!(describe_slicer_app(Platform::Linux, &plain), None); + } + remove_dir_all(root).unwrap(); + } + + #[test] + fn launches_each_kind_of_app_with_the_model() { + let model = Path::new("/cache/slicer-handoff/model.3mf"); + + let bundle = Path::new("/Applications/OrcaSlicer.app"); + let open = launch_command(Platform::MacOs, bundle, model); + assert_eq!(open.get_program(), "/usr/bin/open"); + assert_eq!( + args(&open), + [ + "-a", + "/Applications/OrcaSlicer.app", + "/cache/slicer-handoff/model.3mf" + ] + ); + + let flatpak = Path::new("/var/lib/flatpak/exports/bin/com.prusa3d.PrusaSlicer"); + assert_eq!(flatpak_app_id(flatpak), Some("com.prusa3d.PrusaSlicer")); + let run = launch_command(Platform::Linux, flatpak, model); + assert_eq!(run.get_program(), "flatpak"); + assert_eq!( + args(&run), + [ + "run", + "--file-forwarding", + "com.prusa3d.PrusaSlicer", + "@@", + "/cache/slicer-handoff/model.3mf", + "@@" + ] + ); + + let binary = Path::new("/opt/slicers/PrusaSlicer.AppImage"); + assert_eq!(flatpak_app_id(binary), None); + let direct = launch_command(Platform::Linux, binary, model); + assert_eq!(direct.get_program(), binary.as_os_str()); + assert_eq!(args(&direct), ["/cache/slicer-handoff/model.3mf"]); + assert_eq!(direct.get_current_dir(), Some(Path::new("/opt/slicers"))); + + // Flatpak launchers are only special on Linux. + let windows = launch_command(Platform::Windows, flatpak, model); + assert_eq!(windows.get_program(), flatpak.as_os_str()); + } + + #[test] + fn only_detected_or_picked_apps_can_open_models() { + let root = test_directory("slicers-known"); + let programs = root.join("Program Files"); + let orca = programs.join("OrcaSlicer").join("orca-slicer.exe"); + let picked = root.join("Tools").join("CrealityPrint.exe"); + let other = root.join("Tools").join("calc.exe"); + for path in [&orca, &picked, &other] { + touch(path); + } + let roots = SearchRoots { + windows_programs: vec![programs.clone()], + ..SearchRoots::default() + }; + let picked_apps = root.join("config").join("picked-slicers.json"); + let find = + |path: &Path| find_known_slicer_app(Platform::Windows, &roots, &picked_apps, path); + + assert_eq!(find(&orca), Some(app("Orca Slicer", &orca))); + assert_eq!(find(&picked), None); + remember_picked_app(&picked_apps, &picked.to_string_lossy(), None).unwrap(); + assert_eq!(find(&picked), Some(app("CrealityPrint", &picked))); + assert_eq!(find(&other), None); + assert_eq!(find(&root.join("Tools").join("missing.exe")), None); + + // A picked app that was uninstalled can no longer be launched. + std::fs::remove_file(&picked).unwrap(); + assert_eq!(find(&picked), None); + remove_dir_all(root).unwrap(); + } + + #[test] + fn a_saved_cura_stays_launchable_after_a_newer_one_is_installed() { + let root = test_directory("slicers-cura-upgrade"); + let programs = root.join("Program Files"); + let cura = |version: &str| { + programs + .join(format!("UltiMaker Cura {version}")) + .join("UltiMaker-Cura.exe") + }; + let (older, newer) = (cura("5.7.2"), cura("5.8.0")); + touch(&older); + touch(&newer); + // Same executable name, but not in a versioned Cura folder under a programs directory. + let elsewhere = root + .join("Tools") + .join("UltiMaker Cura 5.7.2") + .join("UltiMaker-Cura.exe"); + let unversioned = programs.join("UltiMaker Cura").join("UltiMaker-Cura.exe"); + let nested = programs + .join("UltiMaker Cura 5.7.2") + .join("bin") + .join("UltiMaker-Cura.exe"); + let other = programs.join("UltiMaker Cura 5.7.2").join("calc.exe"); + for path in [&elsewhere, &unversioned, &nested, &other] { + touch(path); + } + let roots = SearchRoots { + windows_programs: vec![programs.clone()], + ..SearchRoots::default() + }; + let picked_apps = root.join("config").join("picked-slicers.json"); + let find = + |path: &Path| find_known_slicer_app(Platform::Windows, &roots, &picked_apps, path); + + assert_eq!( + detect_slicer_apps(Platform::Windows, &roots), + vec![app("UltiMaker Cura", &newer)] + ); + assert_eq!(find(&older), Some(app("UltiMaker Cura", &older))); + assert_eq!(find(&newer), Some(app("UltiMaker Cura", &newer))); + for path in [&elsewhere, &unversioned, &nested, &other] { + assert_eq!(find(path), None, "{path:?}"); + } + // Versioned folders only count on Windows. + assert_eq!( + find_known_slicer_app(Platform::Linux, &roots, &picked_apps, &older), + None + ); + + // Uninstalling the older version forgets it. + remove_dir_all(older.parent().unwrap()).unwrap(); + assert_eq!(find(&older), None); + remove_dir_all(root).unwrap(); + } + + #[test] + fn picked_apps_are_deduplicated_and_capped() { + let root = test_directory("slicers-picked"); + let file = root.join("picked-slicers.json"); + assert!(read_picked_apps(&file).is_empty()); + write(&file, b"not json").unwrap(); + assert!(read_picked_apps(&file).is_empty()); + + remember_picked_app(&file, "/opt/a", None).unwrap(); + remember_picked_app(&file, "/opt/b", None).unwrap(); + remember_picked_app(&file, "/opt/a", None).unwrap(); + assert_eq!(read_picked_apps(&file), ["/opt/b", "/opt/a"]); + + for index in 0..MAX_PICKED_APPS { + remember_picked_app(&file, &format!("/opt/app-{index}"), None).unwrap(); + } + let picked = read_picked_apps(&file); + assert_eq!(picked.len(), MAX_PICKED_APPS); + assert_eq!(picked.first().map(String::as_str), Some("/opt/app-0")); + assert_eq!( + picked.last().map(String::as_str), + Some(format!("/opt/app-{}", MAX_PICKED_APPS - 1).as_str()) + ); + remove_dir_all(root).unwrap(); + } + + #[test] + fn the_saved_slicer_outlives_later_picks() { + let root = test_directory("slicers-saved"); + let file = root.join("picked-slicers.json"); + let saved = "/opt/saved"; + remember_picked_app(&file, saved, None).unwrap(); + + // The saved slicer is the oldest pick, yet the apps picked after it are dropped instead. + for index in 0..=MAX_PICKED_APPS { + remember_picked_app(&file, &format!("/opt/app-{index}"), Some(saved)).unwrap(); + } + let picked = read_picked_apps(&file); + assert_eq!(picked.len(), MAX_PICKED_APPS); + assert_eq!(picked.first().map(String::as_str), Some(saved)); + assert_eq!(picked[1], "/opt/app-2"); + assert_eq!( + picked.last().map(String::as_str), + Some(format!("/opt/app-{MAX_PICKED_APPS}").as_str()) + ); + + // Once something else is saved, the old choice ages out like any other pick. + remember_picked_app(&file, "/opt/newest", Some("/opt/app-2")).unwrap(); + let picked = read_picked_apps(&file); + assert_eq!(picked.len(), MAX_PICKED_APPS); + assert!(!picked.iter().any(|known| known == saved)); + assert_eq!(picked.first().map(String::as_str), Some("/opt/app-2")); + remove_dir_all(root).unwrap(); + } +} diff --git a/src-tauri/src/slicer_handoff.rs b/src-tauri/src/slicer_handoff.rs new file mode 100644 index 00000000..8d0e17f6 --- /dev/null +++ b/src-tauri/src/slicer_handoff.rs @@ -0,0 +1,270 @@ +use percent_encoding::percent_decode_str; +use std::fs::{create_dir_all, read_dir, remove_file, File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; +use tauri::ipc::{InvokeBody, Request}; +use tauri::{AppHandle, Manager}; + +/// Header carrying the suggested file name; the request body is the raw 3MF archive. +const FILE_NAME_HEADER: &str = "x-kromacut-file-name"; +/// Optional header carrying the percent-encoded path of the slicer to open the model with. +/// Without it, the system's default 3MF application opens the model. +const SLICER_APP_HEADER: &str = "x-kromacut-slicer-app"; +/// Handoff copies older than this are removed the next time a model is opened. Slicers import +/// the 3MF when it opens, so a day leaves ample time without letting the cache grow. +const STALE_AFTER: Duration = Duration::from_secs(24 * 60 * 60); +const MAX_FILE_NAME_CHARS: usize = 128; +const ZIP_SIGNATURE: &[u8] = b"PK\x03\x04"; + +fn handoff_directory(app: &AppHandle) -> Result { + let directory = app + .path() + .app_cache_dir() + .map_err(|error| format!("Failed to resolve the app cache directory: {error}"))? + .join("slicer-handoff"); + create_dir_all(&directory) + .map_err(|error| format!("Failed to create the slicer handoff directory: {error}"))?; + Ok(directory) +} + +/// Accepts only a plain `.3mf` file name, so the handoff can never leave its directory or hand +/// the operating system something other than a 3MF to open. +fn handoff_stem(file_name: &str) -> Result<&str, String> { + let stem = file_name + .strip_suffix(".3mf") + .ok_or_else(|| "The model file name must end in .3mf".to_string())?; + let valid = !stem.is_empty() + && file_name.len() <= MAX_FILE_NAME_CHARS + && !stem.starts_with('.') + && stem + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); + if valid { + Ok(stem) + } else { + Err(format!("Unsupported model file name: {file_name}")) + } +} + +/// Creates a new file rather than overwriting one a slicer may still have open. +fn create_handoff_file(directory: &Path, stem: &str) -> Result<(PathBuf, File), String> { + for collision in 0..1_000_u16 { + let name = if collision == 0 { + format!("{stem}.3mf") + } else { + format!("{stem}-{collision}.3mf") + }; + let path = directory.join(name); + match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(file) => return Ok((path, file)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(format!("Failed to create the model file: {error}")), + } + } + + Err("Could not allocate a unique model file name".to_string()) +} + +/// Best effort: a file that is still locked or already gone is simply left for next time. +fn remove_stale_handoff_files(directory: &Path, now: SystemTime) { + let Ok(entries) = read_dir(directory) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|extension| extension.to_str()) != Some("3mf") { + continue; + } + let stale = entry + .metadata() + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()) + .is_some_and(|age| age >= STALE_AFTER); + if stale { + let _ = remove_file(path); + } + } +} + +fn write_handoff_file(directory: &Path, file_name: &str, model: &[u8]) -> Result { + if !model.starts_with(ZIP_SIGNATURE) { + return Err("The model data is not a 3MF archive".to_string()); + } + let stem = handoff_stem(file_name)?; + remove_stale_handoff_files(directory, SystemTime::now()); + let (path, mut file) = create_handoff_file(directory, stem)?; + if let Err(error) = file.write_all(model).and_then(|_| file.sync_all()) { + drop(file); + let _ = remove_file(&path); + return Err(format!("Failed to write the model file: {error}")); + } + Ok(path) +} + +/// Header values are ASCII, so the slicer path travels percent-encoded. +fn slicer_app_path(header: &str) -> Result { + percent_decode_str(header) + .decode_utf8() + .map(|path| PathBuf::from(path.as_ref())) + .map_err(|_| "The slicer path is not valid UTF-8".to_string()) +} + +/// Writes the exported 3MF into Kromacut's cache and opens it with the chosen slicer, or with +/// the system's default 3MF application when none was chosen. Returns the path that was opened. +#[tauri::command] +pub async fn open_model_in_slicer(app: AppHandle, request: Request<'_>) -> Result { + let InvokeBody::Raw(model) = request.body() else { + return Err("Expected the 3MF archive as raw bytes".to_string()); + }; + let header = |name: &str| { + request + .headers() + .get(name) + .map(|value| value.to_str().map_err(|_| format!("Invalid {name} header"))) + .transpose() + }; + let file_name = + header(FILE_NAME_HEADER)?.ok_or_else(|| "Missing the model file name".to_string())?; + let slicer = header(SLICER_APP_HEADER)? + .map(slicer_app_path) + .transpose()?; + let picked_apps = crate::slicer_apps::picked_apps_file(&app)?; + let path = write_handoff_file(&handoff_directory(&app)?, file_name, model)?; + tauri::async_runtime::spawn_blocking(move || { + match slicer { + Some(slicer) => crate::slicer_apps::open_with_slicer_app(&slicer, &path, &picked_apps) + .map_err(|error| format!("Failed to open the model in the chosen slicer: {error}")), + None => crate::open_with_default_app(&path).map_err(|error| { + format!("Failed to open the model in the default 3MF app: {error}") + }), + }?; + Ok(path.to_string_lossy().into_owned()) + }) + .await + .map_err(|error| format!("Failed to run the model launcher: {error}"))? +} + +#[cfg(test)] +mod tests { + use super::{ + handoff_stem, remove_stale_handoff_files, slicer_app_path, write_handoff_file, STALE_AFTER, + }; + use std::fs::{create_dir_all, read, remove_dir_all, File}; + use std::path::PathBuf; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + const MODEL: &[u8] = b"PK\x03\x04model"; + + fn test_directory(name: &str) -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let directory = + std::env::temp_dir().join(format!("kromacut-{name}-{}-{nanos}", std::process::id())); + create_dir_all(&directory).unwrap(); + directory + } + + #[test] + fn handoff_accepts_only_plain_3mf_file_names() { + assert_eq!( + handoff_stem("kromacut-2026-11-13.3mf"), + Ok("kromacut-2026-11-13") + ); + assert_eq!(handoff_stem("my_model.v2.3mf"), Ok("my_model.v2")); + for name in [ + "", + ".3mf", + "..3mf", + "model.stl", + "model.3MF", + "model.3mf.exe", + "../model.3mf", + "..\\model.3mf", + "/tmp/model.3mf", + "C:model.3mf", + "nested/model.3mf", + "model name.3mf", + "modèle.3mf", + "model&calc.3mf", + ".hidden.3mf", + ] { + assert!(handoff_stem(name).is_err(), "{name}"); + } + let longest = format!("{}.3mf", "a".repeat(124)); + assert!(handoff_stem(&longest).is_ok()); + assert!(handoff_stem(&format!("a{longest}")).is_err()); + } + + #[test] + fn slicer_paths_are_percent_decoded() { + assert_eq!( + slicer_app_path("%2FApplications%2FOrcaSlicer.app"), + Ok(PathBuf::from("/Applications/OrcaSlicer.app")) + ); + assert_eq!( + slicer_app_path("C%3A%5CProgram%20Files%5CBambu%20Studio%5Cbambu-studio.exe"), + Ok(PathBuf::from( + "C:\\Program Files\\Bambu Studio\\bambu-studio.exe" + )) + ); + assert_eq!( + slicer_app_path("%2Fhome%2Fjos%C3%A9%2FPrusaSlicer.AppImage"), + Ok(PathBuf::from("/home/josé/PrusaSlicer.AppImage")) + ); + assert!(slicer_app_path("%FF").is_err()); + } + + #[test] + fn handoff_writes_new_files_without_replacing_open_ones() { + let directory = test_directory("slicer-handoff-write"); + let first = write_handoff_file(&directory, "kromacut-2026-11-13.3mf", MODEL).unwrap(); + let second = + write_handoff_file(&directory, "kromacut-2026-11-13.3mf", b"PK\x03\x04next").unwrap(); + + assert_eq!(first, directory.join("kromacut-2026-11-13.3mf")); + assert_eq!(second, directory.join("kromacut-2026-11-13-1.3mf")); + assert_eq!(read(&first).unwrap(), MODEL); + assert_eq!(read(&second).unwrap(), b"PK\x03\x04next"); + remove_dir_all(directory).unwrap(); + } + + #[test] + fn handoff_rejects_data_that_is_not_a_3mf_archive() { + let directory = test_directory("slicer-handoff-invalid"); + for model in [&b""[..], b"PK", b"#!/bin/sh\n", b"solid stl\n"] { + assert!(write_handoff_file(&directory, "model.3mf", model).is_err()); + } + assert!(write_handoff_file(&directory, "../model.3mf", MODEL).is_err()); + assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 0); + remove_dir_all(directory).unwrap(); + } + + #[test] + fn handoff_removes_only_stale_3mf_files() { + let directory = test_directory("slicer-handoff-prune"); + let now = SystemTime::now(); + let stale = now - STALE_AFTER - Duration::from_secs(1); + let recent = now - STALE_AFTER + Duration::from_secs(60); + for (name, modified) in [ + ("old.3mf", stale), + ("recent.3mf", recent), + ("old.txt", stale), + ] { + File::create(directory.join(name)) + .unwrap() + .set_modified(modified) + .unwrap(); + } + + remove_stale_handoff_files(&directory, now); + + assert!(!directory.join("old.3mf").exists()); + assert!(directory.join("recent.3mf").exists()); + assert!(directory.join("old.txt").exists()); + remove_dir_all(directory).unwrap(); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c045ff79..59f369ee 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Kromacut", - "version": "4.2.0", + "version": "4.3.0", "identifier": "com.kromacut.lithophane", "build": { "frontendDist": "../dist", diff --git a/src-tauri/windows/app-manifest.xml b/src-tauri/windows/app-manifest.xml new file mode 100644 index 00000000..2d510ed3 --- /dev/null +++ b/src-tauri/windows/app-manifest.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/src/App.tsx b/src/App.tsx index b0e36e18..4e9064c4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -21,11 +21,14 @@ import AdjustmentsPanel from './components/AdjustmentsPanel'; import DeditherPanel from './components/DeditherPanel'; import ImageResizePanel from './components/ImageResizePanel'; import { ADJUSTMENT_DEFAULTS } from './lib/applyAdjustments'; -import { calculateImageResizeDimensions } from './lib/imageResize'; import SLIDER_DEFS from './components/sliderDefs'; import { useSwatches } from './hooks/useSwatches'; import type { SwatchEntry } from './hooks/useSwatches'; import { useImageHistory } from './hooks/useImageHistory'; +import { useImageEditingActions } from './hooks/useImageEditingActions'; +import { useImageHistoryShortcuts } from './hooks/useImageHistoryShortcuts'; +import { useImageCanvas } from './hooks/useImageCanvas'; +import { useImageImport, type ImageImportError } from './hooks/useImageImport'; import { useQuantize } from './hooks/useQuantize'; import Header from './components/Header'; import ModeTabs from './components/ModeTabs'; @@ -33,6 +36,7 @@ import PreviewActions from './components/PreviewActions'; import { useDropzone } from './hooks/useDropzone'; import { exportObjectToStlBlob } from './lib/exportStl'; import { exportObjectTo3MFBlob } from './lib/export3mf'; +import { getMultiHeadRoutingPlan, multiHeadExportOptions } from './lib/multiHeadBuild'; import { useAppHandlers, type ExportProgressStep } from './hooks/useAppHandlers'; import { useProcessingState } from './hooks/useProcessingState'; import { useBuildWarning } from './hooks/useBuildWarning'; @@ -47,7 +51,9 @@ import ResizableSplitter from './components/ResizableSplitter'; import { ControlsPanel } from './components/ControlsPanel'; import { usePaletteManager } from './hooks/usePaletteManager'; import { useDesktopFileOpen } from './hooks/useDesktopFileOpen'; +import { useSlicerChoice } from './hooks/useSlicerChoice'; import { DesktopFileDialog } from './components/DesktopFileDialog'; +import { SlicerChooserDialog } from './components/SlicerChooserDialog'; import { UpdateChecker } from './components/UpdateChecker'; import ProgressOverlay from './components/ProgressOverlay'; import DocsPage from './components/docs/DocsPage'; @@ -81,6 +87,8 @@ import { AlertDialogAction, AlertDialogCancel, } from './components/ui/alert-dialog'; +import { Button } from './components/ui/button'; +import { Loader, X } from 'lucide-react'; // ...existing imports const AUTOPAINT_STORAGE_KEY = 'kromacut.autopaint.v1'; @@ -124,6 +132,10 @@ type AutoPaintPersisted = Pick< | 'omitAtRiskPixels' | 'flatPaint' | 'flatPaintFaceUp' + | 'multiHeadMode' + | 'multiHeadCount' + | 'multiHeadSearchDepth' + | 'multiHeadColorMode' >; // Schema v2: filament `td` values store frontlit hiding distances. State @@ -204,6 +216,10 @@ const loadAutoPaintPersisted = (): AutoPaintPersisted | null => { omitAtRiskPixels: parsed.omitAtRiskPixels === true, flatPaint: parsed.flatPaint ?? false, flatPaintFaceUp: parsed.flatPaintFaceUp === true, + multiHeadMode: parsed.multiHeadMode ?? false, + multiHeadCount: parsed.multiHeadCount ?? 4, + multiHeadSearchDepth: parsed.multiHeadSearchDepth ?? 'balanced', + multiHeadColorMode: parsed.multiHeadColorMode ?? 'luminance', }; } catch { return null; @@ -296,16 +312,27 @@ function App(): React.ReactElement | null { const pal = allPalettes.find((p) => p.id === selectedPalette); if (pal && pal.size > 0) setFinalColors(pal.size); }, [allPalettes, selectedPalette]); - const { imageSrc, setImage, clearCurrent, undo, redo, canUndo, canRedo } = useImageHistory( - logo, - undefined + const { + importFile, + isImporting, + importError: imageImportError, + dismissImportError, + cancelPendingImport, + } = useImageImport(); + const { imageSrc, setImage, clearCurrent, undo, redo, canUndo, canRedo, past, future } = + useImageHistory(logo, cancelPendingImport); + const { imageCanvas, imageCanvasLoading, prepareImageCanvas } = useImageCanvas( + imageSrc, + past, + future ); const { swatches, swatchesLoading, imageDimensions, invalidate, immediateOverride } = - useSwatches(imageSrc); + useSwatches(imageCanvas, imageCanvasLoading); // adjustments managed locally inside AdjustmentsPanel now // initial selectedPalette derived from initial weight above const inputRef = useRef(null); const canvasPreviewRef = useRef(null); + const downloadMenuButtonRef = useRef(null); const [showCheckerboard, setShowCheckerboard] = useState(false); const [isCropMode, setIsCropMode] = useState(false); const [hasValidCropSelection, setHasValidCropSelection] = useState(false); @@ -314,23 +341,21 @@ function App(): React.ReactElement | null { const [touchUpColor, setTouchUpColor] = useState('#000000'); const [touchUpBrushSize, setTouchUpBrushSize] = useState(4); const [touchUpTextSize, setTouchUpTextSize] = useState(24); + const processing = useProcessingState(); const { isQuantizing, - setIsQuantizing, isDedithering, - setIsDedithering, processingLabel, - setProcessingLabel, processingProgress, setProcessingProgress, processingIndeterminate, setProcessingIndeterminate, - } = useProcessingState(); + } = processing; const [processingStep, setProcessingStep] = useState({ stepIndex: 1, stepCount: 1, }); - const { applyQuantize } = useQuantize({ + const { applyQuantize: quantize } = useQuantize({ algorithm, weight, finalColors, @@ -456,7 +481,7 @@ function App(): React.ReactElement | null { // 3D printing shared state const { threeDState, - setThreeDState, + handleThreeDSettingsChange, threeDBuildSignal, builtThreeDState, builtFlatPaint, @@ -466,10 +491,19 @@ function App(): React.ReactElement | null { confirmBuild, cancelBuild, markBuildStarted, - } = useBuildWarning({ imageSrc, initialState: autopaintHydrated }); + } = useBuildWarning({ imageSrc, imageCanvas, initialState: autopaintHydrated }); + const [isThreeDBuilding, setIsThreeDBuilding] = useState(false); + // The build overlays cover the preview actions, but not from keyboard or screen readers. + const threeDBuildBusy = isBuildStarting || isThreeDBuilding; const builtModelState = builtThreeDState ?? threeDState; const builtModelAutoPaint = builtModelState.paintMode === 'autopaint'; const builtModelValid = !builtModelAutoPaint || builtModelState.autoPaintResult !== undefined; + const builtMultiHeadPlan = useMemo( + () => getMultiHeadRoutingPlan(builtModelState), + [builtModelState] + ); + // Both models are built from parts that only 3MF keeps apart. + const builtModelStlUnavailable = builtFlatPaint || builtMultiHeadPlan !== undefined; const prevModeRef = useRef(mode); @@ -493,6 +527,10 @@ function App(): React.ReactElement | null { omitAtRiskPixels: threeDState.omitAtRiskPixels, flatPaint: threeDState.flatPaint, flatPaintFaceUp: threeDState.flatPaintFaceUp, + multiHeadMode: threeDState.multiHeadMode, + multiHeadCount: threeDState.multiHeadCount, + multiHeadSearchDepth: threeDState.multiHeadSearchDepth, + multiHeadColorMode: threeDState.multiHeadColorMode, }); }, [ threeDState.filaments, @@ -513,6 +551,10 @@ function App(): React.ReactElement | null { threeDState.omitAtRiskPixels, threeDState.flatPaint, threeDState.flatPaintFaceUp, + threeDState.multiHeadMode, + threeDState.multiHeadCount, + threeDState.multiHeadSearchDepth, + threeDState.multiHeadColorMode, ]); // No auto-build on tab switch — the user must click "Build 3D Model" / "Apply Changes". @@ -564,77 +606,52 @@ function App(): React.ReactElement | null { } }; - const handleFiles = (file?: File) => { - if (!file) return; - if (!file.type.startsWith('image/')) { - alert(t('app.uploadImage')); - return; - } - setTouchUpTool(null); - const url = URL.createObjectURL(file); - invalidate(); - setImage(url, true); - }; - - // removed unused handlers (inline handlers used instead) - - const clear = () => { - setTouchUpTool(null); - clearCurrent(); - if (inputRef.current) inputRef.current.value = ''; - }; - - const resizeCurrentImage = async (percent: number) => { - if (!canvasPreviewRef.current || !imageSrc) return; - - let sourceUrl: string | null = null; - try { - const sourceBlob = await canvasPreviewRef.current.exportImageBlob(); - if (!sourceBlob) return; - - sourceUrl = URL.createObjectURL(sourceBlob); - const imageUrl = sourceUrl; - const img = await new Promise((resolve) => { - const image = new Image(); - image.onload = () => resolve(image); - image.onerror = () => resolve(null); - image.src = imageUrl; - }); - - if (!img) return; - - const target = calculateImageResizeDimensions( - img.naturalWidth, - img.naturalHeight, - percent - ); - - if (target.width >= img.naturalWidth && target.height >= img.naturalHeight) return; - - const canvas = document.createElement('canvas'); - canvas.width = target.width; - canvas.height = target.height; - const ctx = canvas.getContext('2d'); - if (!ctx) return; - - ctx.imageSmoothingEnabled = true; - ctx.imageSmoothingQuality = 'high'; - ctx.drawImage(img, 0, 0, target.width, target.height); - - const resizedBlob = await new Promise((resolve) => - canvas.toBlob((blob) => resolve(blob), 'image/png') - ); - if (!resizedBlob) return; + const processingActive = isQuantizing || isDedithering; + const imageActions = useImageEditingActions({ + imageSrc, + imageCanvasLoading, + canvasPreviewRef, + inputRef, + importFile, + cancelPendingImport, + prepareImageCanvas, + invalidate, + setImage, + clearCurrent, + resetTouchUp: () => setTouchUpTool(null), + setAdjustments, + resetAdjustmentsPanel: () => setAdjustmentsEpoch((epoch) => epoch + 1), + exitCrop: () => setIsCropMode(false), + processing, + setProcessingStep, + quantize, + }); + const { handleFiles, applyQuantize } = imageActions; + useImageHistoryShortcuts({ + undo, + redo, + canUndo, + canRedo, + disabled: mode !== '2d' || docsOpen || isCropMode || processingActive, + beginEdit: imageActions.beginEdit, + }); - const url = URL.createObjectURL(resizedBlob); - invalidate(); - setImage(url, true); - } catch (error) { - console.warn('Image resize failed', error); - alert(t('app.resizeFailed')); - } finally { - if (sourceUrl) URL.revokeObjectURL(sourceUrl); + const imageImportErrorMessage = (error: ImageImportError) => { + if (error.kind === 'notImage') return t('app.uploadImage'); + if (error.kind === 'tooLarge') { + const values = { + name: error.name, + width: error.width, + height: error.height, + maxSize: `${error.maxSquareSide}×${error.maxSquareSide}`, + }; + return error.keptImage + ? t('app.imageTooLarge', values) + : t('app.imageTooLargeNoImage', values); } + return error.keptImage + ? t('app.imageDecodeFailed', { name: error.name }) + : t('app.imageDecodeFailedNoImage', { name: error.name }); }; // splitter & layout management preserved below @@ -654,43 +671,70 @@ function App(): React.ReactElement | null { ); const handleTouchUpToolChange = (nextTool: TouchUpTool | null) => { - if (!imageSrc) return; + if (!imageSrc || !imageActions.beginEdit()) return; setTouchUpTool(nextTool); }; - const dropzone = useDropzone({ enabled: mode === '2d', onFile: handleFiles }); - const { onExportImage, onExportStl, onExport3MF, onSwatchApply, onSwatchDelete } = - useAppHandlers({ - canvasPreviewRef, - imageSrc, - invalidate, - setImage, - setExportingSTL, - setExportProgress, - setExportStep, - exportingSTL, - exportObjectToStlBlob, - exportObjectTo3MFBlob: (obj, onProgress, onZipProgress) => - exportObjectTo3MFBlob(obj, { - layerHeight: builtModelState.layerHeight, - firstLayerHeight: builtModelState.slicerFirstLayerHeight, - smoothMeshingStrength: builtModelState.smoothMeshingStrength, - layerFilamentColors: builtModelAutoPaint - ? builtModelState.autoPaintFilamentSwatches?.map((s) => s.hex) - : undefined, - onProgress, - onZipProgress, - }), - applyQuantize, - swatches, - }); - - const processingActive = mode === '2d' && (isQuantizing || isDedithering); + // Quantize and dedither commit their result through image history, which cancels a + // pending import, so refuse new imports until they finish rather than drop one silently. + const dropzone = useDropzone({ + enabled: mode === '2d' && !processingActive, + onFile: handleFiles, + }); + const { + onExportImage, + onExportStl, + onExport3MF, + onOpenInSlicer, + onSwatchApply, + onSwatchDelete, + } = useAppHandlers({ + beginEdit: imageActions.beginEdit, + canvasPreviewRef, + imageSrc, + invalidate, + setImage, + setExportingSTL, + setExportProgress, + setExportStep, + exportingSTL, + threeDBuildBusy, + stlUnavailable: builtModelStlUnavailable, + exportObjectToStlBlob, + exportObjectTo3MFBlob: (obj, onProgress, onZipProgress) => + exportObjectTo3MFBlob(obj, { + ...multiHeadExportOptions(builtMultiHeadPlan), + layerHeight: builtModelState.layerHeight, + firstLayerHeight: builtModelState.slicerFirstLayerHeight, + smoothMeshingStrength: builtModelState.smoothMeshingStrength, + layerFilamentColors: builtModelAutoPaint + ? builtModelState.autoPaintFilamentSwatches?.map((s) => s.hex) + : undefined, + onProgress, + onZipProgress, + }), + applyQuantize, + swatches, + }); + const slicerChoice = useSlicerChoice(onOpenInSlicer); return ( <>
-
+
{docsOpen && (
@@ -710,20 +754,29 @@ function App(): React.ReactElement | null { ref={inputRef} type="file" accept="image/*" + disabled={processingActive} data-testid="image-file-input" onChange={(e) => { - if (e.target.files && e.target.files[0]) - handleFiles(e.target.files[0]); + const file = e.currentTarget.files?.[0]; + // Allow choosing this same source again after + // cropping, resizing, or other image edits. + e.currentTarget.value = ''; + if (file) void handleFiles(file); }} className="hidden-file-input" /> {/* file input stays here (hidden); uploader buttons moved to preview actions */} -
+
{ + if (!imageActions.beginEdit()) return; setTouchUpTool(null); setAdjustments(vals); // schedule a redraw @@ -731,50 +784,28 @@ function App(): React.ReactElement | null { canvasPreviewRef.current?.redraw() ); }} - onBake={async (vals) => { - if (!canvasPreviewRef.current) return; - try { - const blob = - await canvasPreviewRef.current.exportAdjustedImageBlob?.( - vals - ); - if (!blob) return; - const url = URL.createObjectURL(blob); - invalidate(); - setImage(url, true); - // After baking, reset adjustments state to defaults - setAdjustments(ADJUSTMENT_DEFAULTS); - setAdjustmentsEpoch((e) => e + 1); - } catch (e) { - console.warn('Bake adjustments failed', e); - } - }} + onBake={imageActions.bakeAdjustments} /> { invalidate(); setImage(url, true); }} - onWorkingChange={(working) => { - setIsDedithering(working); - if (working) { - setProcessingLabel('Dedithering...'); - setProcessingStep({ - stepIndex: 1, - stepCount: 1, - label: 'Dedithering pass 1', - stepProgress: 0, - }); - setProcessingProgress(0); - setProcessingIndeterminate(false); - } - }} + onWorkingChange={ + imageActions.onDeditherWorkingChange + } onStepChange={setProcessingStep} onProgress={(value) => { setProcessingProgress(clampProgress(value)); @@ -795,30 +826,13 @@ function App(): React.ReactElement | null { }} algorithm={algorithm} setAlgorithm={setAlgorithm} - onApply={async () => { - if (isQuantizing) return; - setIsQuantizing(true); - setProcessingLabel('Quantizing...'); - setProcessingStep({ - stepIndex: 1, - stepCount: 5, - label: 'Loading image data', - stepProgress: 0, - }); - setProcessingProgress(0); - setProcessingIndeterminate(false); - await new Promise((r) => - requestAnimationFrame(r) - ); - try { - await applyQuantize(canvasPreviewRef); - } finally { - setIsQuantizing(false); - setProcessingProgress(1); - setProcessingIndeterminate(false); - } - }} - disabled={!imageSrc || isCropMode} + onApply={() => applyQuantize(canvasPreviewRef)} + disabled={ + !imageSrc || + isCropMode || + processingActive || + imageCanvasLoading + } applying={isQuantizing} weightDisabled={algorithm === 'none'} selectedPalette={selectedPalette} @@ -853,7 +867,7 @@ function App(): React.ReactElement | null { onSwatchDelete={onSwatchDelete} onSwatchApply={onSwatchApply} /> -
+ )} {mode === '3d' && !hasMountedThreeDControls && ( @@ -867,13 +881,14 @@ function App(): React.ReactElement | null { active={mode === '3d'} swatches={swatches} imageSrc={imageSrc} + imageCanvas={imageCanvas} imageDimensions={imageDimensions} builtState={builtThreeDState} builtFlatPaint={builtFlatPaint} onChange={handleThreeDStateChange} onSettingsChange={(partial) => { autoPaintWorkingStateInitializedRef.current = true; - setThreeDState((prev) => ({ ...prev, ...partial })); + handleThreeDSettingsChange(partial); }} persisted={threeDState} hasAutoPaintWorkingState={ @@ -901,6 +916,8 @@ function App(): React.ReactElement | null {
{ - const url = URL.createObjectURL(blob); - invalidate(); - setImage(url, true); - return url; - }} + onTouchUpCommit={imageActions.commitTouchUp} onTouchUpPickColor={(hex) => { setTouchUpColor(hex); setTouchUpTool('brush'); }} onTouchUpExit={() => setTouchUpTool(null)} /> + {isImporting && ( +
+ + {t('app.checkingImage')} +
+ )} + {imageImportError && ( +
+
+

+ {t('app.imageImportFailed')} +

+

+ {imageImportErrorMessage(imageImportError)} +

+
+ +
+ )} {processingActive && ( {isBuildStarting && ( @@ -1037,39 +1103,50 @@ function App(): React.ReactElement | null { )} { + if (imageActions.beginEdit()) undo(); + }} + onRedo={() => { + if (imageActions.beginEdit()) redo(); + }} onEnterCrop={() => { - if (!imageSrc) return; + if (!imageSrc || !imageActions.beginEdit()) return; setTouchUpTool(null); setIsCropMode(true); }} - onSaveCrop={async () => { - if (!canvasPreviewRef.current) return; - const blob = - await canvasPreviewRef.current.exportCroppedImage(); - if (!blob) return; - const url = URL.createObjectURL(blob); - invalidate(); - setImage(url, true); - setIsCropMode(false); - }} + onSaveCrop={imageActions.saveCrop} onCancelCrop={() => setIsCropMode(false)} onToggleCheckerboard={() => setShowCheckerboard((s) => !s)} onPickFile={() => inputRef.current?.click()} - onClear={clear} + pickFileDisabled={processingActive} + onClear={imageActions.clearImage} onExportImage={onExportImage} onExportStl={onExportStl} onExport3MF={onExport3MF} - flatPaintModel={builtFlatPaint} - modelExportDisabled={!builtModelValid} + onOpenInSlicer={ + isTauri() ? slicerChoice.onOpenInSlicer : undefined + } + savedSlicerName={ + slicerChoice.preference?.kind === 'app' + ? slicerChoice.preference.app.name + : undefined + } + onChooseSlicer={ + slicerChoice.preference + ? slicerChoice.onChooseSlicer + : undefined + } + downloadMenuButtonRef={downloadMenuButtonRef} + stlUnavailable={builtModelStlUnavailable} + modelExportDisabled={!builtModelValid || threeDBuildBusy} + inert={mode === '3d' && threeDBuildBusy} isOrtho={isOrtho} previewRenderMode={previewRenderMode} onPreviewRenderModeChange={(next) => { @@ -1133,6 +1210,16 @@ function App(): React.ReactElement | null { + {slicerChoice.chooser && ( + + )} {/* Update checker for Tauri desktop app */} {desktopFile && diff --git a/src/assets/diagrams/01_window_run_diagram.svg b/src/assets/diagrams/01_window_run_diagram.svg new file mode 100644 index 00000000..6744c69d --- /dev/null +++ b/src/assets/diagrams/01_window_run_diagram.svg @@ -0,0 +1,74 @@ + +Color runs and windows +Example selected windows span three consecutive filament runs. Runs outside windows retain their planned filament and remain in the head schedule. + + +Color runs and windows +Example windows selected from a printable stack +N = 3 run positions; heads are scheduled separately + +stack height ↑ + + +Run 8 + + +Run 7 + + +Run 6 + + +Run 5 + + +Run 4 + + +Run 3 + + +Run 2 + + +Run 1 + + + + + +Window 2 + + + + + +Window 1 + + + + +outside windows + +How it works +Run: +Consecutive layers using one filament. +Thickness follows the printable Auto-paint result. +Window (N = 3 runs): +Selected windows do not overlap. +Pause only when a head needs reloading. +Each region can use a different filament order. +Inside a selected window: +Orders are compared by predicted color. +Run positions are mapped to physical heads. +The Head Schedule lists required reloads. +Outside selected windows: +Runs keep their planned filament. +Their head loads are included in the schedule. + + + + +Stripes represent individual layers (schematic). +Kromacut + \ No newline at end of file diff --git a/src/assets/diagrams/02_nozzle_swap_schedule.svg b/src/assets/diagrams/02_nozzle_swap_schedule.svg new file mode 100644 index 00000000..1772c937 --- /dev/null +++ b/src/assets/diagrams/02_nozzle_swap_schedule.svg @@ -0,0 +1,119 @@ + +Head reload schedule +Three heads change loads across three windows. Four head reloads occur at two pause checkpoints; unchanged filaments stay loaded. Initial loading is excluded from the counts. + + +Head reload schedule +Retain unchanged loads; reload only marked heads +Start / Window 1 +Window 2 +Window 3 +(+ outside runs) +Head 1 +Head 2 +Head 3 + +#C0392B + +#2980B9 + +#27AE60 + +#8E44AD + +#16A085 + +#27AE60 + +#8E44AD + +#2980B9 + +#D35400 + +reload + +reload + + +reload + +reload + + + + +→ Print progression (low to high) + + + +Start / Window 1 + + + +Window 2 + + + +Window 3 (+ outside runs) + +Red +1 + +reload + +Blue +2 + +reload + +Green +3 + +reload + +Purple +4 + +reload + +Teal +5 + +reload + +Green +6 + +reload + +Purple +7 + +reload + +Blue +8 + +reload + +Orange +9 +Multi-head: + + + + +2 pauses · 4 reloads +Single-head: + + + + + + + + +8 reloads +Kromacut + \ No newline at end of file diff --git a/src/assets/diagrams/03_beer_lambert_blending.svg b/src/assets/diagrams/03_beer_lambert_blending.svg new file mode 100644 index 00000000..f3f6d3f6 --- /dev/null +++ b/src/assets/diagrams/03_beer_lambert_blending.svg @@ -0,0 +1,53 @@ + +Layer order changes color +Two orders of the same three filaments give different illustrative blends over opaque backing. + + +Layer order changes color +Same filaments, different layer order +Side bars and swatches are schematic, not measured colors. + +Outer face — toward viewer + + + + + + +1 + + + +2 + + + +3 + + + + +1 + + + +2 + + + +3 + + +Opaque backing + +Different layer order + +Illustrative blend +A: blue / red / green + +Illustrative blend +B: red / blue / green + + +Kromacut + \ No newline at end of file diff --git a/src/assets/diagrams/05_combo_search_space.svg b/src/assets/diagrams/05_combo_search_space.svg new file mode 100644 index 00000000..df5895c4 --- /dev/null +++ b/src/assets/diagrams/05_combo_search_space.svg @@ -0,0 +1,182 @@ + +Window combination search space +Three filaments across three run positions allow 27 orders with repeats. A table shows how the K^N search space grows. + + +Window combination search space +Tested orders compete by predicted ΔE; large spaces are sampled. + +K = 3, N = 3: 27 orders + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +best → + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Position 1 +Position 2 +Position 3 +Each cell is an order; repeats are allowed. + +Combination count = K^N +K=2 +K=3 +K=4 +K=5 +K=6 +N=2 + +4 + +9 + +16 + +25 + +36 +N=3 + +8 + +27 + +64 + +125 + +216 +N=4 + +16 + +81 + +256 + +625 + +1,296 +N=5 + +32 + +243 + +1,024 + +3,125 + +7,776 + +Example (K = 3, N = 3) +More filaments or positions increase the search space. +Search depth limits work in large spaces. +Kromacut + \ No newline at end of file diff --git a/src/assets/diagrams/layout.json b/src/assets/diagrams/layout.json index 104b06bc..8e57effc 100644 --- a/src/assets/diagrams/layout.json +++ b/src/assets/diagrams/layout.json @@ -1952,5 +1952,633 @@ "fontSize": 18, "fontWeight": 400 } + }, + "01_window_run_diagram": { + "title": { + "width": 740, + "fontSize": 18, + "fontWeight": 700 + }, + "subtitle": { + "width": 740, + "fontSize": 11, + "fontWeight": 400 + }, + "windowSize": { + "width": 740, + "fontSize": 11, + "fontWeight": 700 + }, + "height": { + "width": 330, + "fontSize": 11, + "fontWeight": 400 + }, + "run8": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run7": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run6": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run5": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run4": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run3": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run2": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "run1": { + "width": 80, + "fontSize": 11, + "fontWeight": 700 + }, + "window2": { + "width": 96, + "fontSize": 13, + "fontWeight": 700 + }, + "window1": { + "width": 96, + "fontSize": 13, + "fontWeight": 700 + }, + "outsideShort": { + "width": 96, + "fontSize": 12, + "fontWeight": 400 + }, + "how": { + "width": 740, + "fontSize": 14, + "fontWeight": 700 + }, + "run": { + "width": 398, + "fontSize": 12, + "fontWeight": 700 + }, + "runDefinition": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "runHeight": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "window": { + "width": 398, + "fontSize": 12, + "fontWeight": 700 + }, + "windowSelection": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "windowPauses": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "windowOrders": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "inside": { + "width": 398, + "fontSize": 12, + "fontWeight": 700 + }, + "match": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "mapping": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "schedule": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "outside": { + "width": 398, + "fontSize": 12, + "fontWeight": 700 + }, + "keep": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "loads": { + "width": 382, + "fontSize": 11, + "fontWeight": 400 + }, + "stripe": { + "width": 350, + "fontSize": 10, + "fontWeight": 400 + }, + "credit": { + "width": 740, + "fontSize": 10, + "fontWeight": 400 + } + }, + "02_nozzle_swap_schedule": { + "title": { + "width": 760, + "fontSize": 18, + "fontWeight": 700 + }, + "subtitle": { + "width": 760, + "fontSize": 11, + "fontWeight": 400 + }, + "start": { + "width": 176, + "fontSize": 9, + "fontWeight": 400 + }, + "window2": { + "width": 176, + "fontSize": 9, + "fontWeight": 400 + }, + "window3": { + "width": 208, + "fontSize": 11, + "fontWeight": 400 + }, + "outsideRuns": { + "width": 208, + "fontSize": 11, + "fontWeight": 400 + }, + "head1": { + "width": 88, + "fontSize": 12, + "fontWeight": 400 + }, + "head2": { + "width": 88, + "fontSize": 12, + "fontWeight": 400 + }, + "head3": { + "width": 88, + "fontSize": 12, + "fontWeight": 400 + }, + "valueC0392B": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "value2980B9": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "value27AE60": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "value8E44AD": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "value16A085": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "valueD35400": { + "width": 760, + "fontSize": 10, + "fontWeight": 700 + }, + "reload": { + "width": 50, + "fontSize": 8, + "fontWeight": 400 + }, + "progression": { + "width": 760, + "fontSize": 11, + "fontWeight": 400 + }, + "phase3": { + "width": 176, + "fontSize": 9, + "fontWeight": 400 + }, + "red": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber1": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "blue": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber2": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "green": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber3": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "purple": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber4": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "teal": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber5": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "runNumber6": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "runNumber7": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "runNumber8": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "orange": { + "width": 36, + "fontSize": 8, + "fontWeight": 700 + }, + "runNumber9": { + "width": 46, + "fontSize": 8, + "fontWeight": 400 + }, + "multi": { + "width": 105, + "fontSize": 10, + "fontWeight": 400 + }, + "multiCount": { + "width": 340, + "fontSize": 10, + "fontWeight": 700 + }, + "single": { + "width": 105, + "fontSize": 10, + "fontWeight": 400 + }, + "singleCount": { + "width": 250, + "fontSize": 10, + "fontWeight": 700 + }, + "credit": { + "width": 760, + "fontSize": 10, + "fontWeight": 400 + } + }, + "03_beer_lambert_blending": { + "title": { + "width": 880, + "fontSize": 17, + "fontWeight": 700 + }, + "subtitle": { + "width": 880, + "fontSize": 10, + "fontWeight": 400 + }, + "bars": { + "width": 880, + "fontSize": 10, + "fontWeight": 400 + }, + "outer": { + "width": 300, + "fontSize": 9, + "fontWeight": 400 + }, + "positionNumber1": { + "width": 40, + "fontSize": 10, + "fontWeight": 700 + }, + "positionNumber2": { + "width": 40, + "fontSize": 10, + "fontWeight": 700 + }, + "positionNumber3": { + "width": 40, + "fontSize": 10, + "fontWeight": 700 + }, + "backing": { + "width": 880, + "fontSize": 9, + "fontWeight": 400 + }, + "changes": { + "width": 300, + "fontSize": 9, + "fontWeight": 400 + }, + "blend": { + "width": 178, + "fontSize": 9, + "fontWeight": 400 + }, + "orderA": { + "width": 300, + "fontSize": 9, + "fontWeight": 400 + }, + "orderB": { + "width": 300, + "fontSize": 9, + "fontWeight": 400 + }, + "credit": { + "width": 880, + "fontSize": 10, + "fontWeight": 400 + } + }, + "05_combo_search_space": { + "title": { + "width": 880, + "fontSize": 18, + "fontWeight": 700 + }, + "subtitle": { + "width": 880, + "fontSize": 11, + "fontWeight": 400 + }, + "all": { + "width": 400, + "fontSize": 13, + "fontWeight": 700 + }, + "best": { + "width": 52, + "fontSize": 9, + "fontWeight": 700 + }, + "position1": { + "width": 84, + "fontSize": 10, + "fontWeight": 400 + }, + "position2": { + "width": 84, + "fontSize": 10, + "fontWeight": 400 + }, + "position3": { + "width": 84, + "fontSize": 10, + "fontWeight": 400 + }, + "cell": { + "width": 400, + "fontSize": 9, + "fontWeight": 400 + }, + "count": { + "width": 408, + "fontSize": 13, + "fontWeight": 700 + }, + "valueK2": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "valueK3": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "valueK4": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "valueK5": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "valueK6": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "valueN2": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "value4": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value9": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value16": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value25": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value36": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "valueN3": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "value8": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value27": { + "width": 54, + "fontSize": 12, + "fontWeight": 700 + }, + "value64": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value125": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value216": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "valueN4": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "value81": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value256": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value625": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value1296": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "valueN5": { + "width": 54, + "fontSize": 11, + "fontWeight": 700 + }, + "value32": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value243": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value1024": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value3125": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "value7776": { + "width": 54, + "fontSize": 11, + "fontWeight": 400 + }, + "example": { + "width": 190, + "fontSize": 10, + "fontWeight": 400 + }, + "growth": { + "width": 408, + "fontSize": 10, + "fontWeight": 400 + }, + "limit": { + "width": 408, + "fontSize": 10, + "fontWeight": 400 + }, + "credit": { + "width": 880, + "fontSize": 10, + "fontWeight": 400 + } } } diff --git a/src/components/AdjustmentsPanel.tsx b/src/components/AdjustmentsPanel.tsx index eaf8827c..07dcefad 100644 --- a/src/components/AdjustmentsPanel.tsx +++ b/src/components/AdjustmentsPanel.tsx @@ -7,6 +7,7 @@ import { Check, RotateCcw } from 'lucide-react'; import type { SliderDef } from '@/components/sliderDefs'; interface Props { + disabled?: boolean; defs: SliderDef[]; initial?: Record; /** Called when user finishes a slider drag (pointer up). */ @@ -17,7 +18,7 @@ interface Props { // Memoize to avoid parent re-render noise when props are stable export const AdjustmentsPanel: React.FC = React.memo( - ({ defs, initial, onCommit, onBake }) => { + ({ defs, initial, onCommit, onBake, disabled = false }) => { const { t } = useTranslation('workspace'); // Local state only; parent not updated per-drag const [values, setValues] = useState>(() => { @@ -38,6 +39,8 @@ export const AdjustmentsPanel: React.FC = React.memo( const draggingRef = useRef(false); const scheduleSet = useCallback((k: string, v: number) => { + // Keep the ref current before React renders, so an early blur commits this value. + if (valuesRef.current[k] !== v) valuesRef.current = { ...valuesRef.current, [k]: v }; setValues((prev) => { if (prev[k] === v) return prev; // no change return { ...prev, [k]: v }; @@ -67,9 +70,27 @@ export const AdjustmentsPanel: React.FC = React.memo( draggingRef.current = false; // Defer flush to next frame so final value state is applied if (frameRef.current) cancelAnimationFrame(frameRef.current); - frameRef.current = requestAnimationFrame(() => flush()); + frameRef.current = requestAnimationFrame(() => { + frameRef.current = null; + flush(); + }); }, [flush]); + const cancelPendingFlush = useCallback(() => { + if (frameRef.current) cancelAnimationFrame(frameRef.current); + frameRef.current = null; + }, []); + + // The latest value is in valuesRef when focus leaves, so commit now (including a drag + // whose deferred flush is still pending): focusing another control such as + // Dedither can start processing before the next frame. + const handleBlur = useCallback(() => { + if (!draggingRef.current && frameRef.current === null) return; + draggingRef.current = false; + cancelPendingFlush(); + flush(); + }, [cancelPendingFlush, flush]); + // Attach a global pointerup listener only while dragging (simple approach) useEffect(() => { const up = () => handlePointerUp(); @@ -84,10 +105,11 @@ export const AdjustmentsPanel: React.FC = React.memo( return { ...prev, [key]: defaultVal }; }); draggingRef.current = false; + cancelPendingFlush(); dirtyRef.current = true; onCommit?.({ ...valuesRef.current, [key]: defaultVal }); }, - [onCommit] + [cancelPendingFlush, onCommit] ); const handleResetAll = useCallback(() => { @@ -98,8 +120,9 @@ export const AdjustmentsPanel: React.FC = React.memo( setValues(defaults); dirtyRef.current = true; draggingRef.current = false; + cancelPendingFlush(); onCommit?.(defaults); - }, [defs, onCommit]); + }, [cancelPendingFlush, defs, onCommit]); const allDefault = defs.every((d) => values[d.key] === d.default); @@ -175,6 +198,7 @@ export const AdjustmentsPanel: React.FC = React.memo(
= React.memo( draggingRef.current = true; }} onPointerUp={() => handlePointerUp()} - onBlur={() => handlePointerUp()} + onBlur={handleBlur} />
); diff --git a/src/components/AutoPaintTab.tsx b/src/components/AutoPaintTab.tsx index b6b6ae72..33680a97 100644 --- a/src/components/AutoPaintTab.tsx +++ b/src/components/AutoPaintTab.tsx @@ -55,6 +55,7 @@ import { import { TEMPLATE_PROFILES, isTemplateProfileId } from '../data/supplierFilaments'; import { getConfidenceLabel, getConfidenceColor } from '../lib/calibration'; import { getExactBaseOrderCount } from '../lib/optimizer'; +import { MAX_MULTI_HEAD_HEADS } from '../lib/multiHeadAnalysisColorFirst'; import { useNextBestColorWorker } from '../hooks/useNextBestColorWorker'; import type { PrintableFeatureSimulation } from '../lib/printableFeatures.ts'; import PrintableFeaturePreview from './PrintableFeaturePreview'; @@ -398,7 +399,7 @@ interface AutoPaintTabProps { // Image colors filteredCount: number; imageSwatches: Array<{ hex: string; count?: number }>; - paletteProofImageSrc: string | null; + paletteProofImageCanvas: HTMLCanvasElement | null; // Enhanced matching options enhancedColorMatch: boolean; @@ -431,6 +432,18 @@ interface AutoPaintTabProps { setOptimizerSeed: (v: number | undefined) => void; regionWeightingMode: 'uniform' | 'center' | 'edge'; setRegionWeightingMode: (v: 'uniform' | 'center' | 'edge') => void; + + // Multi-head mode + multiHeadMode: boolean; + setMultiHeadMode: (v: boolean) => void; + multiHeadCount: number; + setMultiHeadCount: (v: number) => void; + multiHeadSearchDepth: 'fast' | 'balanced' | 'thorough'; + setMultiHeadSearchDepth: (v: 'fast' | 'balanced' | 'thorough') => void; + multiHeadColorMode: 'luminance' | 'color'; + setMultiHeadColorMode: (v: 'luminance' | 'color') => void; + /** Set after a build that fell back from Multi-head mode to a single-head model. */ + multiHeadNotice?: string; } export default function AutoPaintTab({ @@ -483,7 +496,7 @@ export default function AutoPaintTab({ firstLayerHeight, filteredCount, imageSwatches, - paletteProofImageSrc, + paletteProofImageCanvas, enhancedColorMatch, setEnhancedColorMatch, preserveSeparation, @@ -510,6 +523,15 @@ export default function AutoPaintTab({ setOptimizerSeed, regionWeightingMode, setRegionWeightingMode, + multiHeadMode, + setMultiHeadMode, + multiHeadCount, + setMultiHeadCount, + multiHeadSearchDepth, + setMultiHeadSearchDepth, + multiHeadColorMode, + setMultiHeadColorMode, + multiHeadNotice, }: AutoPaintTabProps) { const { t, i18n } = useTranslation('printing'); const activeProfile = React.useMemo( @@ -1425,6 +1447,118 @@ export default function AutoPaintTab({
)} + {/* Multi-head mode */} + {filaments.length > 0 && ( +
+
+
+
+ +

+ {t('multiHead.description', { heads: multiHeadCount })} +

+
+ +
+ {multiHeadNotice && ( +
+ {multiHeadNotice} +
+ )} + {multiHeadMode && ( +
+

+ {t('multiHead.incompatibleWithFlatPaint')} +

+
+ + { + const v = parseInt(e.target.value, 10); + if (v >= 2) { + setMultiHeadCount(Math.min(v, MAX_MULTI_HEAD_HEADS)); + } + }} + /> +
+
+ + +
+

+ {t('multiHead.searchHelp')} +

+
+ + +
+

+ {t('multiHead.colorGroupingHelp')} +

+
+ )} +
+ )} + {/* Auto-paint transition zones preview */} {autoPaintResult && autoPaintResult.transitionZones.length > 0 && ( <> @@ -1875,7 +2009,7 @@ export default function AutoPaintTab({ layerHeight={calibrationLayerHeight} firstLayerHeight={firstLayerHeight} paletteProofSnapshot={autoPaintResult?.finalStack} - paletteProofImageSrc={paletteProofImageSrc} + paletteProofImageCanvas={paletteProofImageCanvas} paletteProofProfile={activeProfile} paletteProofProfileDirty={isDirty} onRegisterPaletteProof={handleRegisterPaletteProof} diff --git a/src/components/AwardsPage.tsx b/src/components/AwardsPage.tsx new file mode 100644 index 00000000..cc7d1c33 --- /dev/null +++ b/src/components/AwardsPage.tsx @@ -0,0 +1,93 @@ +import { useTranslation } from 'react-i18next'; +import { useEffect } from 'react'; +import logo from '@/assets/logo.png'; +import innovationFundMedal from '../../content/badges/innovation-fund-medal.png'; +import { applyAwardsSeo } from '@/lib/seo'; +import { applyThemeMode, getStoredThemeMode, subscribeToSystemTheme } from '@/lib/theme'; +import LanguageSetting from './LanguageSetting'; +import { publicPath } from '@/lib/routes'; +import './privacy-page.css'; + +// Each award shows its approved artwork unaltered and only the wording its organizer allows. +const awards = [ + { + id: 'snapmaker-innovation-fund', + image: innovationFundMedal, + nameKey: 'landing.snapmakerInnovationFundWinner', + href: 'https://www.snapmaker.com/innovation-fund', + linkKey: 'landing.aboutTheSnapmakerInnovationFund', + }, +] as const; + +export default function AwardsPage() { + const { t, i18n } = useTranslation('public'); + + useEffect(() => { + applyAwardsSeo(); + const syncTheme = () => applyThemeMode(getStoredThemeMode()); + syncTheme(); + const unsubscribe = subscribeToSystemTheme(() => { + if (getStoredThemeMode() === 'system') syncTheme(); + }); + window.addEventListener('storage', syncTheme); + return () => { + unsubscribe(); + window.removeEventListener('storage', syncTheme); + }; + }, [i18n.resolvedLanguage]); + + return ( +
+
+
+ + + Kromacut + + + {t('navigation.openApp')} + +
+
+

{t('awards.eyebrow')}

+

{t('awards.title')}

+

{t('awards.intro')}

+ {awards.map((award) => ( +
+ +
+

{t(award.nameKey)}

+

+ + {t(award.linkKey)} + +

+
+
+ ))} +
+ + +
+
+ ); +} diff --git a/src/components/CanvasPreview.tsx b/src/components/CanvasPreview.tsx index 7496757a..47d1d508 100644 --- a/src/components/CanvasPreview.tsx +++ b/src/components/CanvasPreview.tsx @@ -2,6 +2,7 @@ import { useTranslation } from 'react-i18next'; import React, { useEffect, useImperativeHandle, + useLayoutEffect, useRef, useState, forwardRef, @@ -38,12 +39,15 @@ export interface CanvasPreviewHandle { interface Props { imageSrc: string | null; + imageCanvas: HTMLCanvasElement | null; isCropMode?: boolean; showCheckerboard?: boolean; adjustments?: Record; onCropSelectionChange?: (hasValid: boolean) => void; /** Active 2D touch-up tool; while set, left-drag edits instead of panning. */ touchUpTool?: TouchUpTool | null; + /** Temporarily pause tool input without leaving the tool or baking a text draft. */ + touchUpDisabled?: boolean; touchUpColor?: string; touchUpBrushSize?: number; touchUpTextSize?: number; @@ -85,11 +89,13 @@ const CanvasPreview = forwardRef( ( { imageSrc, + imageCanvas, isCropMode, showCheckerboard, adjustments, onCropSelectionChange, touchUpTool, + touchUpDisabled = false, touchUpColor, touchUpBrushSize, touchUpTextSize, @@ -102,10 +108,14 @@ const CanvasPreview = forwardRef( const { t } = useTranslation('workspace'); const canvasRef = useRef(null); const previewContainerRef = useRef(null); - const imgRef = useRef(null); + // Immutable committed pixels; the original canvas below is an editable copy. + const committedCanvasRef = useRef(null); const zoomRef = useRef(1); const [zoomState, setZoomState] = useState(1); - const [imageLoaded, setImageLoaded] = useState(false); + // Track identity so every newly loaded source schedules its own render, + // even if the previous source was already loaded. + const [loadedCanvas, setLoadedCanvas] = useState(null); + const imageLoaded = loadedCanvas !== null; const offsetRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 }); const panningRef = useRef(false); const panStartXRef = useRef(0); @@ -134,14 +144,22 @@ const CanvasPreview = forwardRef( const processedCanvasRef = useRef(null); const lastAdjSigRef = useRef(''); const mountedRef = useRef(true); - const imageLoadGenerationRef = useRef(0); const activeTouchStrokeRef = useRef(null); // Object URLs of our own pending commits. When one of them arrives back // as imageSrc, the live canvases already hold exactly those pixels and // are kept as-is — drawing never blocks on the round trip. const selfCommitSrcsRef = useRef>(new Set()); - // Bumped only when the image is replaced from outside the touch-up - // tools (undo, quantize, crop, …); invalidates in-flight commits. + const selfCommitSrcRef = useRef(null); + // A successful touch-up can reach history before its shared canvas + // loads. Retain its existing snapshot only for that interval, so a + // later failed save can restore the actual last committed pixels. + const touchUpSnapshotRef = useRef<{ src: string; canvas: HTMLCanvasElement } | null>(null); + const releaseTouchUpSnapshot = useCallback(() => { + const snapshot = touchUpSnapshotRef.current; + touchUpSnapshotRef.current = null; + if (snapshot) snapshot.canvas.width = snapshot.canvas.height = 1; + }, []); + // External replacements or a failed save invalidate in-flight commits. const externalImageGenerationRef = useRef(0); const touchUpCommitChainRef = useRef>(Promise.resolve()); const onTouchUpCommitRef = useRef(onTouchUpCommit); @@ -175,14 +193,12 @@ const CanvasPreview = forwardRef( ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, cw, ch); - const img = imgRef.current; + const img = committedCanvasRef.current; if (!img) return; - // Prefer the live offscreen canvas dimensions: while a committed - // touch-up edit's image is still loading, the original canvas is - // the source of truth and keeps the preview from blanking out. + // Touch-up edits can be ahead of the committed snapshot. const original = originalCanvasRef.current; - const iw = original?.width || img.naturalWidth; - const ih = original?.height || img.naturalHeight; + const iw = original?.width || img.width; + const ih = original?.height || img.height; if (!iw || !ih) return; const baseScale = Math.min(cw / iw, ch / ih); @@ -212,23 +228,18 @@ const CanvasPreview = forwardRef( // Recompute processed canvas only if signature changed or missing. if (sig !== lastAdjSigRef.current) { try { - const baseSource: HTMLCanvasElement | HTMLImageElement = original ?? img; - const iw2 = - baseSource instanceof HTMLImageElement ? baseSource.naturalWidth : iw; - const ih2 = - baseSource instanceof HTMLImageElement ? baseSource.naturalHeight : ih; let srcCtx: CanvasRenderingContext2D | null = null; if (original) { srcCtx = original.getContext('2d'); } else { // lazily build original if missing originalCanvasRef.current = document.createElement('canvas'); - originalCanvasRef.current.width = iw2; - originalCanvasRef.current.height = ih2; + originalCanvasRef.current.width = iw; + originalCanvasRef.current.height = ih; const octx = originalCanvasRef.current.getContext('2d'); if (octx) { octx.imageSmoothingEnabled = false; - octx.drawImage(img, 0, 0, iw2, ih2); + octx.drawImage(img, 0, 0, iw, ih); srcCtx = octx; } } @@ -273,6 +284,9 @@ const CanvasPreview = forwardRef( } }, [adjustments, adjustmentsSig, hasAdjustments]); + const drawToCanvasRef = useRef(drawToCanvas); + drawToCanvasRef.current = drawToCanvas; + const drawRafRef = useRef(null); const requestDraw = useCallback(() => { if (drawRafRef.current !== null) return; @@ -287,15 +301,15 @@ const CanvasPreview = forwardRef( const computeImageLayout = () => { const container = previewContainerRef.current; - const img = imgRef.current; + const img = committedCanvasRef.current; if (!container || !img) return null; const cw = container.clientWidth; const ch = container.clientHeight; // Same fallback as drawToCanvas: the offscreen canvas keeps layout // (and tool coordinates) stable while a committed edit reloads. const original = originalCanvasRef.current; - const iw = original?.width || img.naturalWidth; - const ih = original?.height || img.naturalHeight; + const iw = original?.width || img.width; + const ih = original?.height || img.height; if (!iw || !ih) return null; const baseScale = Math.min(cw / iw, ch / ih); const dw = iw * baseScale; @@ -306,24 +320,41 @@ const CanvasPreview = forwardRef( }; useEffect(() => { - const loadGeneration = ++imageLoadGenerationRef.current; // Our own commits come back with canvases already holding exactly // these pixels; keep the canvases (and any in-progress stroke) // untouched so drawing stays continuous across history commits. - const isSelfCommit = !!imageSrc && selfCommitSrcsRef.current.delete(imageSrc); - if (!isSelfCommit) { + selfCommitSrcRef.current = + imageSrc && selfCommitSrcsRef.current.has(imageSrc) ? imageSrc : null; + if (selfCommitSrcRef.current) { + // React may batch several successful commits into one render. + // Earlier URLs are history entries now, not pending self-commits; + // retaining their markers would make Undo skip restoring pixels. + for (const src of selfCommitSrcsRef.current) { + selfCommitSrcsRef.current.delete(src); + if (src === imageSrc) break; + } + } + if (!selfCommitSrcRef.current) { + releaseTouchUpSnapshot(); selfCommitSrcsRef.current.clear(); externalImageGenerationRef.current += 1; activeTouchStrokeRef.current = null; // A text draft's coordinates belong to the replaced image. if (textDraftRef.current) setTextDraft(null); } + }, [imageSrc, releaseTouchUpSnapshot]); + + useEffect(() => { + // Keep the live preview while the next history entry is loading. + // Adjustment changes only redraw; they never reload source pixels. + if (imageSrc && !imageCanvas) return; + const isSelfCommit = !!imageSrc && selfCommitSrcRef.current === imageSrc; if (!imageSrc) { - imgRef.current = null; + committedCanvasRef.current = null; originalCanvasRef.current = null; processedCanvasRef.current = null; - setImageLoaded(false); + setLoadedCanvas(null); const canvas = canvasRef.current; if (canvas) { const ctx = canvas.getContext('2d'); @@ -334,13 +365,13 @@ const CanvasPreview = forwardRef( return; } - // Capture visible center image coordinates so we can preserve the + // Capture the relative image position at the view center so we can preserve the // user's view when the underlying image is replaced (e.g. after // baking, dedithering, or cropping). If there's no previous layout // available we'll fall back to the existing offset. const container = previewContainerRef.current; let prevCenterImageCoord: { x: number; y: number } | null = null; - if (!isSelfCommit && container && imgRef.current) { + if (!isSelfCommit && container && committedCanvasRef.current) { const rect = container.getBoundingClientRect(); const cx = rect.width / 2; const cy = rect.height / 2; @@ -349,83 +380,56 @@ const CanvasPreview = forwardRef( const prevScale = prevLayout.baseScale * (zoomRef.current || 1); const imgX = (cx - (offsetRef.current.x + prevLayout.dx)) / prevScale; const imgY = (cy - (offsetRef.current.y + prevLayout.dy)) / prevScale; - prevCenterImageCoord = { x: imgX, y: imgY }; + prevCenterImageCoord = { x: imgX / prevLayout.iw, y: imgY / prevLayout.ih }; } } - const img = new Image(); - imgRef.current = img; - if (!isSelfCommit) setImageLoaded(false); // Reset loading state - img.onload = () => { - if ( - !mountedRef.current || - loadGeneration !== imageLoadGenerationRef.current || - imgRef.current !== img - ) { - return; - } - if (isSelfCommit) { - // The img element only feeds the export helpers here; the - // offscreen canvases already show exactly these pixels. - setImageLoaded(true); - drawToCanvas(); - return; - } - // preserve current zoom (don't reset) and try to restore the - // same image coordinate under the container center so the view - // doesn't jump when swapping the image source. - const iw = img.naturalWidth; - const ih = img.naturalHeight; - if (iw && ih) { - setImageLoaded(true); // Image is now loaded - originalCanvasRef.current = document.createElement('canvas'); - originalCanvasRef.current.width = iw; - originalCanvasRef.current.height = ih; - const octx = originalCanvasRef.current.getContext('2d'); - if (octx) { - octx.imageSmoothingEnabled = false; - octx.drawImage(img, 0, 0, iw, ih); - } - processedCanvasRef.current = null; // invalidate processed - lastAdjSigRef.current = ''; + const img = imageCanvas!; + committedCanvasRef.current = img; + if (touchUpSnapshotRef.current?.src === imageSrc) releaseTouchUpSnapshot(); + if (isSelfCommit) { + // The live canvases may already include another stroke. + setLoadedCanvas(img); + drawToCanvasRef.current(); + return; + } + // preserve current zoom (don't reset) and try to restore the + // same image coordinate under the container center so the view + // doesn't jump when swapping the image source. + const iw = img.width; + const ih = img.height; + if (iw && ih) { + setLoadedCanvas(img); + originalCanvasRef.current = document.createElement('canvas'); + originalCanvasRef.current.width = iw; + originalCanvasRef.current.height = ih; + const octx = originalCanvasRef.current.getContext('2d'); + if (octx) { + octx.imageSmoothingEnabled = false; + octx.drawImage(img, 0, 0, iw, ih); } + processedCanvasRef.current = null; // invalidate processed + lastAdjSigRef.current = ''; + } - // restore view center if we computed it earlier - if (prevCenterImageCoord && container) { - const rect = container.getBoundingClientRect(); - const cx = rect.width / 2; - const cy = rect.height / 2; - const newLayout = computeImageLayout(); - if (newLayout) { - const newScale = newLayout.baseScale * (zoomRef.current || 1); - const newOffsetX = cx - newLayout.dx - prevCenterImageCoord.x * newScale; - const newOffsetY = cy - newLayout.dy - prevCenterImageCoord.y * newScale; - offsetRef.current = { x: newOffsetX, y: newOffsetY }; - } + // restore view center if we computed it earlier + if (prevCenterImageCoord && container) { + const rect = container.getBoundingClientRect(); + const cx = rect.width / 2; + const cy = rect.height / 2; + const newLayout = computeImageLayout(); + if (newLayout) { + const newScale = newLayout.baseScale * (zoomRef.current || 1); + const newOffsetX = + cx - newLayout.dx - prevCenterImageCoord.x * newLayout.iw * newScale; + const newOffsetY = + cy - newLayout.dy - prevCenterImageCoord.y * newLayout.ih * newScale; + offsetRef.current = { x: newOffsetX, y: newOffsetY }; } + } - drawToCanvas(); - }; - img.onerror = () => { - if ( - !mountedRef.current || - loadGeneration !== imageLoadGenerationRef.current || - imgRef.current !== img - ) { - return; - } - setImageLoaded(false); - }; - img.src = imageSrc; - return () => { - img.onload = null; - img.onerror = null; - if (imageLoadGenerationRef.current === loadGeneration) { - imageLoadGenerationRef.current += 1; - } - if (imgRef.current === img) imgRef.current = null; - }; - }, [imageSrc, drawToCanvas]); + drawToCanvasRef.current(); + }, [imageSrc, imageCanvas, releaseTouchUpSnapshot]); // initialize selection when entering crop mode useEffect(() => { @@ -461,7 +465,7 @@ const CanvasPreview = forwardRef( // update hasValidCropSelection when selection changes useEffect(() => { - const img = imgRef.current; + const img = committedCanvasRef.current; const sel = selectionRef.current; if (!img || !sel) { setHasValidCropSelection(false); @@ -489,10 +493,10 @@ const CanvasPreview = forwardRef( const cw = container.clientWidth; const ch = container.clientHeight; - const img = imgRef.current; + const img = committedCanvasRef.current; if (!img) return; - const iw = img.naturalWidth; - const ih = img.naturalHeight; + const iw = img.width; + const ih = img.height; if (!iw || !ih) return; const baseScale = Math.min(cw / iw, ch / ih); @@ -519,7 +523,22 @@ const CanvasPreview = forwardRef( // === 2D touch-up tools === - const touchUpActive = !!touchUpTool && !isCropMode && imageLoaded; + // A pending external history entry still shows the previous preview. + // Only our own commits may use those live pixels before their shared + // snapshot loads: they were already applied to the original canvas. + const hasCurrentImagePixels = () => + !!imageSrc && + !!originalCanvasRef.current && + ((!!imageCanvas && committedCanvasRef.current === imageCanvas) || + selfCommitSrcRef.current === imageSrc || + selfCommitSrcsRef.current.has(imageSrc)); + + const touchUpActive = + !!touchUpTool && + !touchUpDisabled && + !isCropMode && + imageLoaded && + hasCurrentImagePixels(); const showBrushOutline = touchUpActive && (touchUpTool === 'brush' || touchUpTool === 'eraser'); const brushOutlineRef = useRef(null); @@ -540,7 +559,7 @@ const CanvasPreview = forwardRef( const TEXT_DRAFT_LINE_HEIGHT = 1.25; useEffect(() => { - if (!touchUpTool) return; + if (!touchUpTool || touchUpDisabled) return; const onKey = (e: KeyboardEvent) => { if (e.key !== 'Escape') return; // First Escape discards an open text draft, second exits the tool. @@ -552,7 +571,17 @@ const CanvasPreview = forwardRef( }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); - }, [touchUpTool]); + }, [touchUpTool, touchUpDisabled]); + + // Processing refuses every touch-up that is not in history yet, so drop + // them before it reads the canvas (and stop a stroke still in progress). + const pendingTouchUpCommitsRef = useRef(0); + const rollbackUnsavedTouchUpsRef = useRef<() => void>(() => {}); + useLayoutEffect(() => { + if (!touchUpDisabled) return; + if (!activeTouchStrokeRef.current && pendingTouchUpCommitsRef.current === 0) return; + rollbackUnsavedTouchUpsRef.current(); + }, [touchUpDisabled]); // Leaving the text tool (or entering crop) commits whatever was typed // instead of silently dropping it. @@ -638,6 +667,24 @@ const CanvasPreview = forwardRef( requestDraw(); }; + // Roll back all unsaved strokes, including the active one and snapshots + // still queued for history, to the last successful history entry. + const rollbackUnsavedTouchUps = () => { + externalImageGenerationRef.current += 1; + activeTouchStrokeRef.current = null; + const img = touchUpSnapshotRef.current?.canvas ?? committedCanvasRef.current; + const liveOriginal = originalCanvasRef.current; + const octx = liveOriginal?.getContext('2d'); + if (img && liveOriginal && octx) { + octx.clearRect(0, 0, liveOriginal.width, liveOriginal.height); + octx.imageSmoothingEnabled = false; + octx.drawImage(img, 0, 0); + } + invalidateProcessedCache(); + requestDraw(); + }; + rollbackUnsavedTouchUpsRef.current = rollbackUnsavedTouchUps; + // Commits are serialized so rapid strokes land in history in order. // Drawing never waits on a commit: the offscreen canvases stay the // source of truth, and the imageSrc round trip is absorbed by the @@ -656,40 +703,52 @@ const CanvasPreview = forwardRef( snapshotContext.imageSmoothingEnabled = false; snapshotContext.drawImage(original, 0, 0); const externalGeneration = externalImageGenerationRef.current; + pendingTouchUpCommitsRef.current += 1; touchUpCommitChainRef.current = touchUpCommitChainRef.current.then(async () => { - if (!mountedRef.current) return; - // The image was replaced from outside (undo, quantize, …) - // after this edit was made — the edit is gone by design. - if (externalImageGenerationRef.current !== externalGeneration) return; + try { + if (!mountedRef.current) return; + // The image was replaced from outside (undo, quantize, …) + // after this edit was made — the edit is gone by design. + if (externalImageGenerationRef.current !== externalGeneration) return; - const blob = await new Promise((resolve) => - snapshot.toBlob((result) => resolve(result), 'image/png') - ); - if ( - !mountedRef.current || - externalImageGenerationRef.current !== externalGeneration - ) { - return; - } - if (blob) { - const url = commitCallback(blob); - if (typeof url === 'string') selfCommitSrcsRef.current.add(url); - } else { - // Encoding failed — restore the canvases from the last - // committed image so the preview matches the history. - const img = imgRef.current; - const liveOriginal = originalCanvasRef.current; - const octx = liveOriginal?.getContext('2d'); - if (img && liveOriginal && octx) { - octx.clearRect(0, 0, liveOriginal.width, liveOriginal.height); - octx.imageSmoothingEnabled = false; - octx.drawImage(img, 0, 0); + let blob: Blob | null; + try { + blob = await new Promise((resolve) => + snapshot.toBlob((result) => resolve(result), 'image/png') + ); + } catch { + // Browsers can throw instead of invoking the callback + // with null. Both failures must leave the queue usable. + blob = null; + } + if ( + !mountedRef.current || + externalImageGenerationRef.current !== externalGeneration + ) { + return; + } + // The owner may refuse the edit (processing started meanwhile); + // a refused edit must not stay on the canvas outside history. + const url = blob ? commitCallback(blob) : undefined; + if (typeof url === 'string') { + selfCommitSrcsRef.current.add(url); + releaseTouchUpSnapshot(); + touchUpSnapshotRef.current = { src: url, canvas: snapshot }; + // One recompute per commit keeps the adjusted preview exact + // without paying for it on every pointer move. + invalidateProcessedCache(); + requestDraw(); + } else { + rollbackUnsavedTouchUps(); + } + } finally { + pendingTouchUpCommitsRef.current -= 1; + // The retained successful snapshot has one explicit owner; + // cancelled and failed snapshots can release their pixels now. + if (touchUpSnapshotRef.current?.canvas !== snapshot) { + snapshot.width = snapshot.height = 1; } } - // One recompute per commit keeps the adjusted preview exact - // without paying for it on every pointer move. - invalidateProcessedCache(); - requestDraw(); }); }; @@ -1146,7 +1205,7 @@ const CanvasPreview = forwardRef( mountedRef.current = true; return () => { mountedRef.current = false; - imageLoadGenerationRef.current += 1; + releaseTouchUpSnapshot(); externalImageGenerationRef.current += 1; activeTouchStrokeRef.current = null; originalCanvasRef.current = null; @@ -1162,7 +1221,7 @@ const CanvasPreview = forwardRef( selectionRafRef.current = null; } }; - }, []); + }, [releaseTouchUpSnapshot]); useImperativeHandle(ref, () => ({ redraw: () => drawToCanvas(), @@ -1176,7 +1235,8 @@ const CanvasPreview = forwardRef( }); }, exportCroppedImage: async (): Promise => { - const img = imgRef.current; + if (!hasCurrentImagePixels()) return null; + const img = originalCanvasRef.current; const sel = selectionRef.current; if (!img || !sel) return null; const layout = computeImageLayout(); @@ -1191,8 +1251,8 @@ const CanvasPreview = forwardRef( const sw = sel.w / scale; const sh = sel.h / scale; - const iw = img.naturalWidth; - const ih = img.naturalHeight; + const iw = img.width; + const ih = img.height; // clamp and integerize const sxClamped = Math.max(0, Math.min(iw, sx)); @@ -1221,12 +1281,11 @@ const CanvasPreview = forwardRef( return hasValidCropSelection; }, exportImageBlob: async (): Promise => { - if (!imageLoaded) return null; - const source = originalCanvasRef.current ?? imgRef.current; + if (!hasCurrentImagePixels()) return null; + const source = originalCanvasRef.current ?? committedCanvasRef.current; if (!source) return null; - const iw = source instanceof HTMLCanvasElement ? source.width : source.naturalWidth; - const ih = - source instanceof HTMLCanvasElement ? source.height : source.naturalHeight; + const iw = source.width; + const ih = source.height; if (!iw || !ih) return null; const outCanvas = document.createElement('canvas'); outCanvas.width = iw; @@ -1245,10 +1304,11 @@ const CanvasPreview = forwardRef( exportAdjustedImageBlob: async ( adjustmentsOverride?: Record ): Promise => { - const img = imgRef.current; + if (!hasCurrentImagePixels()) return null; + const img = committedCanvasRef.current; if (!img) return null; - const iw = img.naturalWidth; - const ih = img.naturalHeight; + const iw = img.width; + const ih = img.height; if (!iw || !ih) return null; const canvas = document.createElement('canvas'); canvas.width = iw; @@ -1398,15 +1458,15 @@ const CanvasPreview = forwardRef(
) : null} {/* small HUD showing image size and crop size (when active) */} - {imageLoaded && imgRef.current ? ( + {imageLoaded && committedCanvasRef.current ? (
{(() => { - const img = imgRef.current!; - const iw = originalCanvasRef.current?.width || img.naturalWidth; - const ih = originalCanvasRef.current?.height || img.naturalHeight; + const img = committedCanvasRef.current!; + const iw = originalCanvasRef.current?.width || img.width; + const ih = originalCanvasRef.current?.height || img.height; let text = t('canvasPreview.imageDimensions', { width: iw, height: ih, diff --git a/src/components/DeditherPanel.tsx b/src/components/DeditherPanel.tsx index f7665ebe..71454b26 100644 --- a/src/components/DeditherPanel.tsx +++ b/src/components/DeditherPanel.tsx @@ -7,8 +7,10 @@ import { CollapsibleCard, DirtyDot } from '@/components/CollapsibleCard'; import { RotateCcw, Check, Loader } from 'lucide-react'; import type { CanvasPreviewHandle } from './CanvasPreview'; import { deditherRowProgress } from '../lib/progress'; +import { decodeImage } from '../lib/decodeImage'; interface Props { + beginEdit: () => (() => boolean) | null; canvasRef: React.RefObject; onApplyResult: (blobUrl: string) => void; onWorkingChange?: (working: boolean) => void; @@ -22,6 +24,7 @@ interface Props { } export const DeditherPanel: React.FC = ({ + beginEdit, canvasRef, onApplyResult, onWorkingChange, @@ -37,6 +40,8 @@ export const DeditherPanel: React.FC = ({ const handleApply = useCallback(async () => { if (!canvasRef.current) return; + const isCurrent = beginEdit(); + if (!isCurrent) return; const totalPasses = Math.max(1, Math.min(10, Math.round(passes))); setWorking(true); onWorkingChange?.(true); @@ -48,17 +53,15 @@ export const DeditherPanel: React.FC = ({ }); onProgress?.(0.01); await new Promise((r) => requestAnimationFrame(r)); + let sourceUrl: string | null = null; try { + if (!isCurrent() || !canvasRef.current) return; // prefer adjusted image if available const blob = await canvasRef.current.exportAdjustedImageBlob?.(); - if (!blob) return; - const img = await new Promise((res) => { - const i = new Image(); - i.onload = () => res(i); - i.onerror = () => res(null); - i.src = URL.createObjectURL(blob); - }); - if (!img) return; + if (!blob || !isCurrent()) return; + sourceUrl = URL.createObjectURL(blob); + const img = await decodeImage(sourceUrl); + if (!img || !isCurrent()) return; onProgress?.(0.06); const w = img.naturalWidth; @@ -167,6 +170,7 @@ export const DeditherPanel: React.FC = ({ } if (performance.now() - lastYield > YIELD_MS) { await new Promise((r) => requestAnimationFrame(r)); + if (!isCurrent()) return; lastYield = performance.now(); } processedRows++; @@ -200,17 +204,27 @@ export const DeditherPanel: React.FC = ({ const outBlob = await new Promise((res) => c.toBlob((b) => res(b), 'image/png') ); - if (!outBlob) return; + if (!outBlob || !isCurrent()) return; onProgress?.(1); const url = URL.createObjectURL(outBlob); onApplyResult(url); } catch (err) { - console.warn('Dedither failed', err); + if (isCurrent()) console.warn('Dedither failed', err); } finally { + if (sourceUrl) URL.revokeObjectURL(sourceUrl); setWorking(false); onWorkingChange?.(false); } - }, [canvasRef, weight, passes, onApplyResult, onWorkingChange, onProgress, onStepChange]); + }, [ + beginEdit, + canvasRef, + weight, + passes, + onApplyResult, + onWorkingChange, + onProgress, + onStepChange, + ]); const allDefault = weight === DEFAULT_WEIGHT && passes === DEFAULT_PASSES; diff --git a/src/components/FilamentCalibrationDialog.tsx b/src/components/FilamentCalibrationDialog.tsx index 91a1886e..5053caf2 100644 --- a/src/components/FilamentCalibrationDialog.tsx +++ b/src/components/FilamentCalibrationDialog.tsx @@ -95,7 +95,7 @@ interface FilamentCalibrationDialogProps { layerHeight: number; firstLayerHeight: number; paletteProofSnapshot?: FinalPrintableStackSnapshot; - paletteProofImageSrc?: string | null; + paletteProofImageCanvas?: HTMLCanvasElement | null; paletteProofProfile?: AutoPaintProfile; paletteProofProfileDirty?: boolean; onRegisterPaletteProof?: ( @@ -213,7 +213,7 @@ export function FilamentCalibrationDialog({ layerHeight, firstLayerHeight, paletteProofSnapshot, - paletteProofImageSrc, + paletteProofImageCanvas, paletteProofProfile, paletteProofProfileDirty, onRegisterPaletteProof, @@ -1482,7 +1482,7 @@ export function FilamentCalibrationDialog({ void; + /** Forgets the saved slicer, so Open in Slicer asks again. */ + onForget: () => void; +} interface Props { docsOpen: boolean; onBackToApp: () => void; onOpenDocs: () => void; + /** Desktop only: the slicer Open in Slicer uses without asking. */ + slicer?: SlicerSetting; } const appVersion = __APP_VERSION__; @@ -72,9 +83,10 @@ type UpdateCheckStatus = 'idle' | 'checking' | 'available' | 'current' | 'error' const legalLinks = [ { path: '/privacy', labelKey: 'public:navigation.privacy' }, { path: '/terms', labelKey: 'public:navigation.terms' }, + { path: '/awards', labelKey: 'public:navigation.awards' }, ] as const; -export const Header: React.FC = ({ docsOpen, onBackToApp, onOpenDocs }) => { +export const Header: React.FC = ({ docsOpen, onBackToApp, onOpenDocs, slicer }) => { const { t, i18n } = useTranslation('common'); const [themeMode, setThemeMode] = React.useState(() => getStoredThemeMode()); const [settingsOpen, setSettingsOpen] = React.useState(false); @@ -94,10 +106,13 @@ export const Header: React.FC = ({ docsOpen, onBackToApp, onOpenDocs }) = const settingsTitleId = React.useId(); const updateStartupSwitchId = React.useId(); const multiPlateSwitchId = React.useId(); + const slicerTitleId = React.useId(); + const slicerCurrentId = React.useId(); const diagnosticsSwitchId = React.useId(); const isDesktopApp = isDesktopUpdateSupported(); const settingsButtonRef = React.useRef(null); const settingsDialogRef = React.useRef(null); + const slicerChangeRef = React.useRef(null); React.useEffect(() => { if (!settingsOpen) return; @@ -523,6 +538,88 @@ export const Header: React.FC = ({ docsOpen, onBackToApp, onOpenDocs }) =
+ {slicer && ( +
+
+
+ {t('settings.slicer')} +
+

+ {t('settings.slicerDescription')} +

+
+ +
+
+
+ {slicer.preference === null + ? t('settings.slicerAskEveryTime') + : slicer.preference.kind === 'system' + ? t('workspace:slicerChooser.systemDefault') + : slicer.preference.app.name} +
+ {slicer.preference?.kind === 'app' && ( +
+ {slicer.preference.app.path} +
+ )} +
+
+ + {slicer.preference && ( + + )} +
+
+
+ )} + {isDesktopApp && (
diff --git a/src/components/LandingPage.tsx b/src/components/LandingPage.tsx index b0061d65..d771879a 100644 --- a/src/components/LandingPage.tsx +++ b/src/components/LandingPage.tsx @@ -1,6 +1,8 @@ import { Trans, useTranslation } from 'react-i18next'; import { ArrowRight, + ArrowUpRight, + Award, BookOpen, Check, ChevronDown, @@ -38,6 +40,7 @@ import batmangaFinished from '../../content/community/batmanga-finished.jpg'; import narutoKromacutPreview from '../../content/community/naruto-kromacut-preview.png'; import narutoSlicerPreview from '../../content/community/naruto-slicer-preview.png'; import narutoFinished from '../../content/community/naruto-finished.jpg'; +import innovationFundMedal from '../../content/badges/innovation-fund-medal.png'; import redditIcon from '../assets/reddit.svg'; import { APP_PATH, docsPath, publicPath } from '@/lib/routes'; import LanguageSetting from './LanguageSetting'; @@ -60,6 +63,7 @@ const links = { discord: 'https://discord.gg/nU63sFMcnX', reddit: 'https://www.reddit.com/r/kromacut/', patreon: 'https://www.patreon.com/cw/vycdev', + snapmakerInnovationFund: 'https://www.snapmaker.com/innovation-fund', }; const workflow = [ @@ -917,6 +921,44 @@ export default function LandingPage() {
+
+
+ +
+

+ {t('navigation.awards')} +

+

+ {t('landing.snapmakerInnovationFundWinner')} +

+ + {t('landing.aboutTheSnapmakerInnovationFund')} + +
+
+
+
@@ -1014,6 +1056,14 @@ export default function LandingPage() { data-testid="landing-footer-utility" className="flex flex-wrap items-center gap-x-6 gap-y-3 lg:justify-end" > + + { - let cancelled = false; setLoadError(null); setSelectionMessage(null); sourcePixelsRef.current = null; setImageSize({ width: 0, height: 0 }); - const image = new Image(); - image.onload = () => { - if (cancelled) return; - const size = paletteProofTargetImageSize(image.naturalWidth, image.naturalHeight); + try { + const size = paletteProofTargetImageSize(imageCanvas.width, imageCanvas.height); const samplingCanvas = document.createElement('canvas'); samplingCanvas.width = size.width; samplingCanvas.height = size.height; @@ -114,23 +111,13 @@ export default function PaletteProofImageTargetPicker({ } context.imageSmoothingEnabled = false; context.clearRect(0, 0, size.width, size.height); - context.drawImage(image, 0, 0, size.width, size.height); - try { - sourcePixelsRef.current = context.getImageData(0, 0, size.width, size.height); - setImageSize(size); - } catch { - setLoadError('Could not read the processed image colors.'); - } - }; - image.onerror = () => { - if (!cancelled) setLoadError('Could not load the processed image.'); - }; - image.src = imageSrc; - - return () => { - cancelled = true; - }; - }, [imageSrc]); + context.drawImage(imageCanvas, 0, 0, size.width, size.height); + sourcePixelsRef.current = context.getImageData(0, 0, size.width, size.height); + setImageSize(size); + } catch { + setLoadError('Could not read the processed image colors.'); + } + }, [imageCanvas]); useEffect(() => { const canvas = canvasRef.current; diff --git a/src/components/PaletteProofPanel.tsx b/src/components/PaletteProofPanel.tsx index 5a36fbd9..1755b3cf 100644 --- a/src/components/PaletteProofPanel.tsx +++ b/src/components/PaletteProofPanel.tsx @@ -58,7 +58,7 @@ import type { FinalPrintableStackSnapshot } from '../types/appearance'; interface PaletteProofPanelProps { snapshot?: FinalPrintableStackSnapshot; - imageSrc?: string | null; + imageCanvas?: HTMLCanvasElement | null; profile?: AutoPaintProfile; profileDirty?: boolean; embedded?: boolean; @@ -130,7 +130,7 @@ function proofTimestamp(record: PaletteProofRecord): string { export default function PaletteProofPanel({ snapshot, - imageSrc, + imageCanvas, profile, profileDirty = false, embedded = false, @@ -508,13 +508,13 @@ export default function PaletteProofPanel({ (column) => column.targetMappingId ), }); - setIsSelectingTargets(Boolean(imageSrc)); + setIsSelectingTargets(Boolean(imageCanvas)); }; if ( isSelectingTargets && snapshot && - imageSrc && + imageCanvas && !selectedRecord && proofGeneration.mode !== 'continue' && targetCountOptions.length > 0 @@ -613,7 +613,7 @@ export default function PaletteProofPanel({ setIsSelectingTargets(true)} > {t('proof.chooseFromImage')} diff --git a/src/components/PreviewActions.tsx b/src/components/PreviewActions.tsx index 719db29d..e1adae10 100644 --- a/src/components/PreviewActions.tsx +++ b/src/components/PreviewActions.tsx @@ -14,6 +14,8 @@ import { X, Loader, Download, + ExternalLink, + SlidersHorizontal, Grid3x3, Upload, Trash2, @@ -49,14 +51,26 @@ export interface PreviewActionsProps { onCancelCrop: () => void; onToggleCheckerboard: () => void; onPickFile: () => void; + /** Image imports are refused while quantize or dedither is running. */ + pickFileDisabled?: boolean; onClear: () => void; onExportImage: () => Promise; onExportStl: () => Promise; onExport3MF: () => Promise; - /** The currently built model is a Flat Paint slab — STL export is useless for it */ - flatPaintModel?: boolean; - /** No valid model exists for the selected 3D mode/settings. */ + /** Desktop only: export a 3MF and open it in the chosen slicer, asking first if none is saved. */ + onOpenInSlicer?: () => Promise; + /** Name of the saved slicer that Open in Slicer uses without asking. */ + savedSlicerName?: string; + /** Desktop only, once a slicer is saved: change or forget it. */ + onChooseSlicer?: () => void; + /** Receives the download menu button, so the slicer chooser can return focus to it. */ + downloadMenuButtonRef?: React.Ref; + /** The built model is a Flat Paint slab or a multi-head build, so STL can't represent it. */ + stlUnavailable?: boolean; + /** No valid model exists for the selected 3D mode/settings, or a build is running. */ modelExportDisabled?: boolean; + /** Covered by a build overlay: keep keyboard and screen-reader users out as well. */ + inert?: boolean; isOrtho?: boolean; onToggleCamera?: () => void; previewRenderMode?: PreviewRenderMode; @@ -94,12 +108,18 @@ export const PreviewActions: React.FC = ({ onCancelCrop, onToggleCheckerboard, onPickFile, + pickFileDisabled = false, onClear, onExportImage, onExportStl, onExport3MF, - flatPaintModel = false, + onOpenInSlicer, + savedSlicerName, + onChooseSlicer, + downloadMenuButtonRef, + stlUnavailable = false, modelExportDisabled = false, + inert = false, isOrtho = false, onToggleCamera, previewRenderMode = 'shaded', @@ -202,7 +222,7 @@ export const PreviewActions: React.FC = ({ }; return ( -
+
{mode === '3d' && onPreviewRenderModeChange && ( @@ -411,6 +431,7 @@ export const PreviewActions: React.FC = ({ - - {/* Flat Paint slabs carry their colors as per-filament 3MF - objects; a single-geometry STL of the slab is useless */} - {!flatPaintModel && ( + + {/* Flat Paint slabs and multi-head builds need 3MF: one STL + can't carry their per-filament objects or head routing */} + {!stlUnavailable && ( + {onOpenInSlicer && ( + + )} + {onOpenInSlicer && onChooseSlicer && ( + + )} )} @@ -476,6 +529,7 @@ export const PreviewActions: React.FC = ({ title={t('previewActions.chooseFile')} aria-label={t('previewActions.chooseFile')} onClick={onPickFile} + disabled={pickFileDisabled} className="bg-primary hover:bg-primary/80 text-primary-foreground disabled:opacity-50 disabled:cursor-not-allowed" > diff --git a/src/components/PrintInstructions.tsx b/src/components/PrintInstructions.tsx index b572c35f..9fb6d540 100644 --- a/src/components/PrintInstructions.tsx +++ b/src/components/PrintInstructions.tsx @@ -1,10 +1,12 @@ import { Trans, useTranslation } from 'react-i18next'; import { CollapsibleCard, DirtyDot } from '@/components/CollapsibleCard'; -import type { SwapEntry } from '../hooks/useSwapPlan'; +import type { SwapEntry, MultiHeadScheduleEvent } from '../hooks/useSwapPlan'; import type { SmoothMeshingStrength } from '../types'; interface PrintInstructionsProps { swapPlan: SwapEntry[]; + multiHeadPlan?: MultiHeadScheduleEvent[] | null; + multiHeadMode?: boolean; layerHeight: number; slicerFirstLayerHeight: number; copied: boolean; @@ -20,6 +22,8 @@ interface PrintInstructionsProps { export default function PrintInstructions({ swapPlan, + multiHeadPlan, + multiHeadMode = false, layerHeight, slicerFirstLayerHeight, copied, @@ -55,7 +59,6 @@ export default function PrintInstructions({ onClick={onCopy} title={t('printInstructions.copyPrintInstructionsToClipboard')} aria-pressed={copied} - disabled={tooManyColors} className={`px-3 py-1.5 rounded-md text-sm font-medium transition-all duration-200 ${ copied ? 'bg-green-600 text-white' @@ -67,6 +70,11 @@ export default function PrintInstructions({ } >
+ {tooManyColors && ( +
+ {t('multiHead.largePrintWarning', { layers: colorCount })} +
+ )} {/* Recommended Settings */}
@@ -169,9 +177,21 @@ export default function PrintInstructions({ )}
+ ) : multiHeadPlan ? ( + + ) : multiHeadMode ? ( +
+ , + }} + /> +
) : ( + /* Single-head */ <> - {/* Start Color */}
{t('printInstructions.startWithColor')} @@ -197,13 +217,9 @@ export default function PrintInstructions({ ); })() ) : ( -
- — -
+
—
)}
- - {/* Color Swap Plan */}
{t('printInstructions.colorSwapPlan')} @@ -290,3 +306,89 @@ export default function PrintInstructions({ ); } + +// --------------------------------------------------------------------------- +// HeadSchedule — multi-head load / swap schedule in layer order +// --------------------------------------------------------------------------- + +function HeadSchedule({ events }: { events: MultiHeadScheduleEvent[] }) { + const { t } = useTranslation('printing'); + if (events.length === 0) { + return ( +
+ {t('multiHead.noAssignments')} +
+ ); + } + + return ( +
+
{t('multiHead.schedule')}
+
+ {events.filter(evt => evt.isPrePrint || evt.swapCount > 0).map((evt, evtIdx) => { + return ( +
+ {/* Event header */} +
+ + ), + }} + /> +
+ + {/* Nozzle rows — all heads shown; changed ones highlighted */} +
+ {evt.nozzles.map((n) => ( +
+ + {t('multiHead.head', { head: n.nozzle })} + + + + {n.empty ? t('multiHead.empty') : n.filamentName} + +
+ ))} +
+
+ ); + })} +
+
+ ); +} diff --git a/src/components/SlicerChooserDialog.tsx b/src/components/SlicerChooserDialog.tsx new file mode 100644 index 00000000..26008657 --- /dev/null +++ b/src/components/SlicerChooserDialog.tsx @@ -0,0 +1,244 @@ +import { useEffect, useId, useRef, useState, type RefObject } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Check, FolderOpen } from 'lucide-react'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from './ui/alert-dialog'; +import { Button } from './ui/button'; +import { Switch } from './ui/switch'; +import { listSlicerApps, pickSlicerApp, type SlicerApp } from '../lib/desktopSlicer'; +import type { SlicerPreference } from '../lib/slicerPreference'; + +interface Props { + preference: SlicerPreference | null; + missingSlicerName: string | null; + /** Opened from Settings: confirming saves the selected slicer instead of opening a model. */ + saveOnly?: boolean; + /** Gets focus on close when the element that opened the chooser is gone, such as a menu item. */ + fallbackFocusRef?: RefObject; + onConfirm: (slicer: SlicerApp | null, remember: boolean) => void; + onCancel: () => void; +} + +const SYSTEM_DEFAULT = ''; + +/** + * Desktop only: asks which slicer opens the model, and whether to stop asking. With `saveOnly` + * it picks the slicer Open in Slicer uses from now on. + */ +export function SlicerChooserDialog({ + preference, + missingSlicerName, + saveOnly = false, + fallbackFocusRef, + onConfirm, + onCancel, +}: Props) { + const { t } = useTranslation('workspace'); + const groupName = useId(); + const rememberId = useId(); + const savedApp = preference?.kind === 'app' ? preference.app : null; + const [apps, setApps] = useState(null); + const [browsed, setBrowsed] = useState(savedApp ? [savedApp] : []); + const [selectedPath, setSelectedPath] = useState(savedApp?.path ?? SYSTEM_DEFAULT); + const [remember, setRemember] = useState(preference !== null); + const [browsing, setBrowsing] = useState(false); + const [browseFailed, setBrowseFailed] = useState(false); + // The chooser has no trigger, so closing it would leave focus on the page body. + const openerRef = useRef(null); + + useEffect(() => { + let cancelled = false; + listSlicerApps() + .catch((err) => { + console.warn('Looking for installed slicers failed', err); + return []; + }) + .then((detected) => { + if (!cancelled) setApps(detected); + }); + return () => { + cancelled = true; + }; + }, []); + + // Detected slicers first, then saved or browsed ones that are not among them. + const options = [ + ...(apps ?? []), + ...browsed.filter((app) => !apps?.some((detected) => detected.path === app.path)), + ]; + const selected = options.find((app) => app.path === selectedPath) ?? null; + + const browse = async () => { + setBrowsing(true); + setBrowseFailed(false); + try { + const app = await pickSlicerApp( + t('slicerChooser.browseTitle'), + t('slicerChooser.browseFilter'), + savedApp?.path + ); + if (!app) return; + setBrowsed((current) => + current.some((known) => known.path === app.path) ? current : [...current, app] + ); + setSelectedPath(app.path); + } catch (err) { + console.warn('Choosing a slicer failed', err); + setBrowseFailed(true); + } finally { + setBrowsing(false); + } + }; + + const option = (value: string, label: string, detail: string, testId: string) => { + const checked = selectedPath === value; + return ( + + ); + }; + + return ( + { + if (!open) onCancel(); + }} + > + { + openerRef.current = document.activeElement as HTMLElement | null; + }} + onCloseAutoFocus={(event) => { + const opener = openerRef.current; + const target = + opener?.isConnected && opener !== document.body + ? opener + : fallbackFocusRef?.current; + if (!target?.isConnected) return; + event.preventDefault(); + target.focus(); + }} + > + + {t('slicerChooser.title')} + + {missingSlicerName + ? t('slicerChooser.missing', { name: missingSlicerName }) + : saveOnly + ? t('slicerChooser.saveDescription') + : t('slicerChooser.description')} + + + +
+
+ {option( + SYSTEM_DEFAULT, + t('slicerChooser.systemDefault'), + t('slicerChooser.systemDefaultHint'), + 'slicer-option-system' + )} + {options.map((app) => + option(app.path, app.name, app.path, 'slicer-option') + )} +
+ {apps === null ? ( +

+ {t('slicerChooser.searching')} +

+ ) : ( + apps.length === 0 && ( +

+ {t('slicerChooser.noneFound')} +

+ ) + )} + + {browseFailed && ( +

+ {t('slicerChooser.notAnApp')} +

+ )} + {!saveOnly && ( +
+ + +
+ )} +
+ + + + {t('slicerChooser.cancel')} + + { + event.preventDefault(); + onConfirm(selected, saveOnly || remember); + }} + > + {saveOnly ? t('slicerChooser.save') : t('slicerChooser.open')} + + +
+
+ ); +} diff --git a/src/components/StackMatrixCalibrationPanel.tsx b/src/components/StackMatrixCalibrationPanel.tsx index 6907b4c1..c3db5b99 100644 --- a/src/components/StackMatrixCalibrationPanel.tsx +++ b/src/components/StackMatrixCalibrationPanel.tsx @@ -1,6 +1,7 @@ import { useTranslation } from 'react-i18next'; import { i18n, translate } from '@/lib/i18n'; import { translateRuntimeMessage } from '@/lib/runtimeMessages'; +import { isImageFile, validateImageFile } from '@/lib/imageFile'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { AlertTriangle, @@ -133,13 +134,6 @@ const CORNER_MARKER_LAYOUT = [ ] as const; let nextMatrixWorkerRequestId = 1; -function isImageFile(file: Pick): boolean { - return ( - file.type.startsWith('image/') || - (!file.type && /\.(avif|bmp|gif|heic|heif|jpe?g|png|webp)$/i.test(file.name)) - ); -} - function filamentLabel(filament: Filament): string { return filament.name || filament.brand || filament.color; } @@ -698,8 +692,10 @@ export default function StackMatrixCalibrationPanel({ ); const handlePhotoFile = useCallback( - (file: File | undefined) => { + async (file: File | undefined) => { if (!file || !activeRecord) return; + // Checked before taking a load generation, so a non-image does not + // cancel a photo that is still loading. if (!isImageFile(file)) { setError('Drop an image file for the Stack Matrix photo'); return; @@ -707,31 +703,41 @@ export default function StackMatrixCalibrationPanel({ const loadGeneration = ++photoLoadGenerationRef.current; const photoProfileId = profileId; const recordId = activeRecord.id; - const url = URL.createObjectURL(file); - const image = new Image(); - image.onload = () => { - const activeOwner = activePhotoOwnerRef.current; - if ( - loadGeneration !== photoLoadGenerationRef.current || - activeOwner.profileId !== photoProfileId || - activeOwner.recordId !== recordId - ) { - URL.revokeObjectURL(url); - return; + const result = await validateImageFile(file); + const activeOwner = activePhotoOwnerRef.current; + if ( + loadGeneration !== photoLoadGenerationRef.current || + activeOwner.profileId !== photoProfileId || + activeOwner.recordId !== recordId + ) { + if (result.ok) { + result.image.close(); + URL.revokeObjectURL(result.url); } - const scale = Math.min(1, 1200 / Math.max(image.naturalWidth, image.naturalHeight)); - const width = Math.max(1, Math.round(image.naturalWidth * scale)); - const height = Math.max(1, Math.round(image.naturalHeight * scale)); + return; + } + // A truncated photo would otherwise load with only the rows that decoded. + if (!result.ok) { + setError('Could not open that photo'); + return; + } + const { image, url } = result; + try { + const scale = Math.min(1, 1200 / Math.max(image.width, image.height)); + const width = Math.max(1, Math.round(image.width * scale)); + const height = Math.max(1, Math.round(image.height * scale)); const scratch = document.createElement('canvas'); scratch.width = width; scratch.height = height; const context = scratch.getContext('2d', { willReadFrequently: true }); if (!context) { setError('This browser could not read the Stack Matrix photo'); - URL.revokeObjectURL(url); return; } - context.drawImage(image, 0, 0, width, height); + // At the default quality, a large bitmap downscales more coarsely than + // an did, which shifts the measured cell colors. + context.imageSmoothingQuality = 'medium'; + context.drawImage(image.source, 0, 0, width, height); const pixels = context.getImageData(0, 0, width, height).data; const loadedPhoto = { sourceCanvas: scratch, @@ -747,20 +753,10 @@ export default function StackMatrixCalibrationPanel({ detectPhotoAlignment(loadedPhoto); setMeasuredColors([]); setError(null); + } finally { + image.close(); URL.revokeObjectURL(url); - }; - image.onerror = () => { - const activeOwner = activePhotoOwnerRef.current; - if ( - loadGeneration === photoLoadGenerationRef.current && - activeOwner.profileId === photoProfileId && - activeOwner.recordId === recordId - ) { - setError('Could not open that photo'); - } - URL.revokeObjectURL(url); - }; - image.src = url; + } }, [activeRecord, detectPhotoAlignment, profileId] ); @@ -831,7 +827,7 @@ export default function StackMatrixCalibrationPanel({ setError('Drop an image file for the Stack Matrix photo'); return; } - handlePhotoFile(file); + void handlePhotoFile(file); }; const drawPhotoOverlay = useCallback( @@ -1601,9 +1597,10 @@ export default function StackMatrixCalibrationPanel({ ref={fileInputRef} type="file" accept="image/*" + data-testid="matrix-photo-input" className="hidden" onChange={(event) => { - handlePhotoFile(event.target.files?.[0]); + void handlePhotoFile(event.target.files?.[0]); event.currentTarget.value = ''; }} /> @@ -1711,6 +1708,7 @@ export default function StackMatrixCalibrationPanel({ >