release: 0.1.1 — update channel, settings/UI trims, macOS + Windows x64 only
Update path - `src-tauri/src/update.rs`: manifest fetch, semver compare, optional ed25519 signature check against a key baked in at build time, then a size + SHA256 gate before an installer can run. `UpdateStatus` now reports the artifact key it resolved so the UI can name what it will install. - Settings → Updates panel shows the feed, the check/download state machine, and the local OS, architecture and release artifact for this machine. - `scripts/publish-release.sh` + `scripts/release-key.py` publish installers and a signed `shift-update.json` onto an orphan `releases` branch. Scope trims requested for this release - Settings: the Radial rings tab is gone, so ring orders are read from `settings.json` with no in-app editor for now. - Main window: the update entry in the header bar is gone; updates live in Settings → Updates only. - Release targets are macOS universal and Windows x64. ARM64 and Linux stay buildable and are no longer published; `docs/RELEASE.md` records the decision. Gates: cargo fmt --check clean, `cargo test --lib` 142 passed / 2 ignored, `pnpm check` clean, `pnpm test` 34 passed, `pnpm build` ok.main v0.1.1
parent
b96bb03bbd
commit
b732b91ea6
|
|
@ -0,0 +1,13 @@
|
|||
# The Linux image builds its own toolchain and dependency tree; copying the host
|
||||
# artefacts in would be both enormous and the wrong architecture.
|
||||
node_modules
|
||||
src-tauri/target
|
||||
src-tauri/binaries
|
||||
artifacts
|
||||
dist
|
||||
public/tesseract
|
||||
.github
|
||||
docs
|
||||
codesign0
|
||||
.git
|
||||
.DS_Store
|
||||
|
|
@ -47,3 +47,35 @@ jobs:
|
|||
- run: cargo check
|
||||
working-directory: src-tauri
|
||||
- run: pnpm tauri build --debug --no-bundle
|
||||
|
||||
# The Linux paths (grim, wf-recorder, x11grab, Poppler) are the only ones with no
|
||||
# build or test job today, so nothing in the repository has ever compiled them.
|
||||
# Ubuntu's desktop runner carries the GTK and WebKit packages Tauri needs, which a
|
||||
# macOS machine cannot provide; `scripts/linux/Dockerfile` is the same dependency set
|
||||
# for building the packages off CI.
|
||||
linux:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install Tauri system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libxdo-dev \
|
||||
libayatana-appindicator3-dev librsvg2-dev patchelf
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm check
|
||||
- run: pnpm build
|
||||
- run: cargo test --lib
|
||||
working-directory: src-tauri
|
||||
# Bundles deb and AppImage, so this is also the Linux release artifact that
|
||||
# publish-release.sh can push onto the update channel.
|
||||
- run: pnpm tauri build --debug --bundles deb,appimage
|
||||
|
|
|
|||
113
README.md
113
README.md
|
|
@ -17,11 +17,14 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
|
|||
- [Tools](#tools)
|
||||
- [Compression, naming, cancellation](#compression-naming-cancellation)
|
||||
- [Capture & annotation](#capture--annotation)
|
||||
- [Capture history library](#capture-history-library)
|
||||
- [OCR](#ocr)
|
||||
- [Send to a device](#send-to-a-device)
|
||||
- [Custom ring order](#custom-ring-order)
|
||||
- [Shortcuts](#shortcuts)
|
||||
- [Tray menu](#tray-menu)
|
||||
- [Output locations](#output-locations)
|
||||
- [Updates](#updates)
|
||||
- [External dependencies](#external-dependencies)
|
||||
- [Platform status](#platform-status)
|
||||
- [Build from source](#build-from-source)
|
||||
|
|
@ -43,7 +46,9 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
|
|||
|
||||
**Batch by default.** Select ten files, drag, and one gesture produces ten outputs. Results land next to each source with a descriptive suffix (`report (compressed).pdf`, `photo (rotated).png`) and never overwrite — a numeric suffix is appended on collision. Settings can collect every result into one folder instead.
|
||||
|
||||
**Capture is built in.** Frozen-screen area capture, full-screen capture, and area recording with a floating timer, all aimed at the monitor under the pointer rather than always the primary display. Screenshots open straight into the annotation canvas and can be pinned as always-on-top reference windows.
|
||||
**Capture is built in.** Frozen-screen area capture, full-screen capture, and area recording with a floating timer, all aimed at the monitor under the pointer rather than always the primary display. A finished capture hands you a floating result card - Copy, Pin, Send, Reveal, Edit, one click each, and it steps aside on its own - or opens the annotation canvas straight away, whichever you choose in Settings. Recording options only ever offer what your platform actually does: microphone on macOS, frame rate on the FFmpeg backends.
|
||||
|
||||
**The rings are yours to arrange.** A saved order rearranges the wedges for each file type and each ring, so the convert you use hourly sits at the top of an image's action ring rather than the bottom. (The Settings screen that edited those orders was removed, so orders are applied from `settings.json` rather than changed in the app.)
|
||||
|
||||
**OCR runs on-device.** English and Simplified Chinese, via a bundled Tesseract WASM engine with the traineddata shipped inside the app. No network access at any point in the OCR path.
|
||||
|
||||
|
|
@ -71,6 +76,8 @@ Shift lives in the menu bar (macOS) and the notification area (Windows), and it
|
|||
|
||||
**Several files at once.** Multi-select with `⌘`/`Ctrl`-click, then drag. Every file is processed. With 2+ images or 2+ PDFs selected, a **Merge** wedge appears that combines them into a single PDF.
|
||||
|
||||
**First run.** Shift shows one card with four checks: Screen Recording, whether the three output folders are writable, whether this copy owns the global shortcuts, and which optional tools are missing. Each one says what it found and offers the fix — open the privacy pane, quit the other copies — and dismissing the card changes nothing. It appears once per install — including the first launch after an upgrade, since older settings files have no such flag — and removing `setupReviewed` from `settings.json` shows it again.
|
||||
|
||||
**First run on macOS.** Grant Screen Recording for screenshots and recording, and Files & Folders access for the output locations you choose. Capture checks permission before showing the overlay, so a denial produces an actionable error rather than a black screenshot.
|
||||
|
||||
## Supported files
|
||||
|
|
@ -90,7 +97,7 @@ Recognition is by extension, against four tables in `src-tauri/src/files.rs`. Th
|
|||
|
||||
Decoding and encoding are not symmetric, and the app does not pretend otherwise:
|
||||
|
||||
- **Image decode** is native (Rust `image`) for PNG, JPEG, WebP, TIFF, BMP and GIF. HEIC/HEIF/AVIF first decode through the system codec — `sips` on macOS, ImageMagick elsewhere — and can then convert to every offered image target, including WEBP, or to PDF. The pixel tools still need a natively readable input, so convert those formats first before rotate, flip, B&W, 50% or compress.
|
||||
- **Image decode** is native (Rust `image`) for PNG, JPEG, WebP, TIFF, BMP and GIF. HEIC/HEIF/AVIF first decode through the system codec — `sips` on macOS, ImageMagick elsewhere — and can then convert to every offered image target, including WEBP, or to PDF. The pixel tools use that same decode, so rotating or halving a phone screenshot works directly; nothing here can write HEIC through the pixel path, so the result is written as PNG.
|
||||
- **Image encode** for PNG, JPG, WebP, TIFF, BMP and GIF is native. HEIC export uses `sips` on macOS and requires ImageMagick on Windows/Linux. AVIF is accepted as an input but is not offered as an export target.
|
||||
- **Media** decode and encode are whatever your FFmpeg build supports; the menu offers MP4, MOV, GIF and M4A for video, and M4A, WAV and MP3 for audio.
|
||||
- **Office** files are parsed in pure Rust (`calamine` for spreadsheets, `zip` + `quick-xml` for PPTX), so no Office installation is needed.
|
||||
|
|
@ -130,11 +137,13 @@ Anything not in this table is not offered — the ring is built from this catalo
|
|||
|
||||
The tool ring (`Option + Shift` while dragging). These are one-gesture operations, not conversions.
|
||||
|
||||
"Same type" means the output keeps the input's container, with one exception: HEIC and AVIF can be decoded here but not re-encoded, so a pixel tool run on one of them writes PNG and says so in the filename.
|
||||
|
||||
| Tool | Applies to | Output | What it does |
|
||||
| --- | --- | --- | --- |
|
||||
| Compress | image, video, audio, PDF | `.jpg`/`.png`, `.mp4`, `.m4a`, `.pdf` | Images re-encode at q68 (PNG kept when alpha); video at CRF 28; audio to 128k AAC; PDF images resampled to ≤1440 px at q60 JPEG, then objects pruned |
|
||||
| Metadata | image, PDF | same type, ` (clean)` | Rewrites the image with no EXIF; strips the PDF `/Info` and `/Metadata` entries |
|
||||
| Rotate | image, PDF | same type, ` (rotated)` | 90° clockwise, in place for the format |
|
||||
| Strip metadata | image, PDF | same type, ` (clean)` | Rewrites the image with no EXIF; strips the PDF `/Info` and `/Metadata` entries. It removes and writes a copy; it never displays what a file carries |
|
||||
| Rotate | image, PDF | same type, ` (rotated)` | 90° clockwise, in place for the format; a HEIC/AVIF input has no native encoder here, so it comes back as PNG |
|
||||
| Flip | image | same type, ` (flipped)` | Horizontal mirror |
|
||||
| B&W | image | same type, ` (bw)` | Grayscale conversion |
|
||||
| 50% | image | same type, ` (50%)` | Half width and height, Lanczos3 |
|
||||
|
|
@ -178,7 +187,11 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
|
|||
|
||||
## Capture & annotation
|
||||
|
||||
**Capture.** Area capture paints a frozen still so the pixels you select are the pixels you get; full-screen capture skips the overlay entirely. Recordings save as MOV on macOS via `screencapture -v` and MP4 elsewhere via FFmpeg, with a floating timer and stop control. Linux capture prefers `grim` and falls back to `gnome-screenshot`.
|
||||
**Capture.** Area capture paints a frozen still so the pixels you select are the pixels you get; full-screen capture skips the overlay entirely. Recordings save as MOV on macOS via `screencapture -v` and MP4 elsewhere, with a floating timer and stop control. Linux capture prefers `grim` and falls back to `gnome-screenshot`; on Wayland, recording uses `wf-recorder`, because ffmpeg's `x11grab` has no root window to grab there.
|
||||
|
||||
**Recording options are honest.** `capabilities()` in `src-tauri/src/recording.rs` reports what the backend actually implements, and the capture toolbar renders only those switches. macOS gets the microphone toggle (`screencapture -g`) and no frame-rate control, because `screencapture -v` has none; Windows and Linux get a frame-rate chip (15 / 24 / 30) that becomes ffmpeg's `-framerate`, and no microphone toggle, because no audio input is wired into the grab yet. Nothing in the UI can promise a setting the encoder would silently drop.
|
||||
|
||||
**Result card.** A finished screenshot or recording appears bottom-right as a card with **Copy**, **Pin**, **Send**, **Reveal** and **Edit**. Hovering holds it open; otherwise it steps aside on its own. Settings -> Screenshots chooses what happens at that moment - **Result card** or **Open in editor** - and the editor is the fallback whenever a card window cannot be created.
|
||||
|
||||
**Annotation.** The editor canvas works at native resolution and writes a new PNG, so the source file is never modified.
|
||||
|
||||
|
|
@ -187,6 +200,8 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
|
|||
| Rectangle, Arrow, Highlight, Text | Freehand placement, colour and weight per annotation |
|
||||
| Redact | Solid black bar, burnt into the output — not an overlay |
|
||||
| Pixelate | Real mosaic sampling of the region underneath, not a translucent fill |
|
||||
| Blur | Gaussian blur of the region, clipped to the shape you drew |
|
||||
| Stamp | Check, cross and star glyphs, placed with a tap |
|
||||
| Number | Auto-incrementing callout badges |
|
||||
| Crop | Interactive crop with an explicit apply step |
|
||||
| Add BG | Rounded-corner padding with a gradient mat, for social and deck shots |
|
||||
|
|
@ -197,6 +212,16 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
|
|||
|
||||
**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as editable text. Every editor host has Copy, Save As, Open, Reveal in Folder, OCR and Copy Text.
|
||||
|
||||
## Capture history library
|
||||
|
||||
Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. The main window's **Recent** card is that library:
|
||||
|
||||
- **Search** once the list grows past a few rows; it filters on the file name.
|
||||
- **Pin** a row to keep it through the capacity limit, a deleted file, and Clear.
|
||||
- **Remove** one row, or **Clear** the library - pinned rows stay.
|
||||
- **Drag a row out** into Finder, a mail composer or a chat window: the row carries a `file://` URL, so the receiving application gets the file rather than a path string. Plain text and Shift's own internal type travel with it for editors and for the ring.
|
||||
- Click a row to open it in the editor; the row's other buttons send, reveal, and pin it to the screen.
|
||||
|
||||
## OCR
|
||||
|
||||
Tesseract.js with the LSTM core, running as WASM inside the app. `eng` and `chi_sim` traineddata are copied into `public/tesseract` at build time by `pnpm prepare:ocr`, so recognition works with no network and no download on first run.
|
||||
|
|
@ -219,6 +244,12 @@ How it finds peers, with no server and no configuration:
|
|||
|
||||
Only the local network is involved — nothing reaches the internet. The receiver listens on all interfaces, so a macOS firewall prompt appears the first time Shift shares; allowing it enables both directions.
|
||||
|
||||
## Custom ring order
|
||||
|
||||
A saved order picks a file type, then a ring (**Actions** or **Tools**), and rearranges its wedges. **The screen that edits those orders is not in Settings any more** — the reorder tab was removed, so orders are read from `settings.json` (`wedgeOrders`) but nothing in the app currently writes them. Existing files keep working; there is no way to change them from the interface yet.
|
||||
|
||||
The catalogue, not the preset, decides what exists. `src/lib/radialOrder.ts` holds the wedge list for every kind and ring, and a saved order can only permute the ids that catalogue offers for that file: an id that has since been removed disappears from the ring, a newly added one slides into its default slot, and **Send** always stays last. A reorder takes effect on the next gesture - no restart, and no way to hide an action you suddenly need.
|
||||
|
||||
## Shortcuts
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
|
@ -242,6 +273,7 @@ The menu bar (macOS) and notification area (Windows) icon exposes the actions yo
|
|||
| Capture full screen | `Alt+Shift+4` | Grab the monitor under the pointer |
|
||||
| Record area | `Alt+Shift+3` | Start, or stop, an area recording |
|
||||
| OCR an image… | — | Pick an image and read its text locally |
|
||||
| Update available *x.y.z* | — | Only while an update is available; opens Settings → Updates |
|
||||
| Quit Shift | `Cmd/Ctrl+Q` | Exit; an in-flight recording is finalised first |
|
||||
|
||||
Tray labels follow the selected app language; native macOS permission prompts remain in English.
|
||||
|
|
@ -258,13 +290,20 @@ Settings → **Behaviour** holds two switches: **Drag rings** (master enable for
|
|||
|
||||
Each is overridable in Settings. File actions offer a *collect everything in one folder* mode in place of beside-the-source. The Settings panel lists every resolved path, checks that it is actually writable, reveals it in the file manager, and deep-links to the macOS Screen Recording and Files & Folders privacy panes when access is missing.
|
||||
|
||||
## Updates
|
||||
|
||||
The update channel is this repository: a `releases` branch holding the installers plus `shift-update.json`, which names each artifact, its size and its SHA256. The feed URL is derived from the git remote at build time - Gitea, GitHub and GitLab forms are known, and `SHIFT_UPDATE_URL` overrides it - so no update service has to be deployed anywhere.
|
||||
|
||||
Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A downloaded installer is checked twice before it can be installed: exact byte length, then a recomputed SHA256 that must match the manifest. A mismatch deletes the file and says so, so nothing half-downloaded launches. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`).
|
||||
|
||||
## External dependencies
|
||||
|
||||
Core conversion, radial menu, capture, and OCR work with nothing installed. These extend coverage:
|
||||
|
||||
| Tool | Needed for | macOS | Windows | Linux |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| FFmpeg | media convert/compress, 720p, mute, frame, mono; recording off-macOS | optional | **required** for recording | **required** |
|
||||
| FFmpeg | media convert/compress, 720p, mute, frame, mono; recording off-macOS | optional | **required** for recording | **required** (media, plus X11 recording) |
|
||||
| `wf-recorder` | area recording under Wayland | not needed | not needed | needed under Wayland |
|
||||
| Pandoc | document ↔ DOCX/RTF/HTML/TXT/MD (ODT input only) | optional | needed | needed |
|
||||
| Typst | Pandoc document-to-PDF engine | not needed (AppKit) | needed | needed |
|
||||
| Poppler `pdftoppm` | PDF → images, PDF → Word, scanned-PDF OCR | not needed (PDFKit) | needed | needed |
|
||||
|
|
@ -284,9 +323,12 @@ wedge rather than the app.
|
|||
| --- | --- | --- | --- |
|
||||
| Radial menu, editor, tray, i18n | Yes | Yes | Yes |
|
||||
| Drag-to-ring | AppKit global drag bridge | Win32 drag-state poll + native drop | none yet — main-window picker only |
|
||||
| Area / full-screen capture | `screencapture` | PowerShell | `grim` / `gnome-screenshot` |
|
||||
| Area / full-screen capture | `screencapture` | Win32 GDI `BitBlt` | `grim` / `gnome-screenshot` |
|
||||
| Monitor under cursor | Yes | Yes | `grim` output selection |
|
||||
| Area recording | `screencapture -v` | FFmpeg | planned |
|
||||
| Area recording | `screencapture -v`, audio via `-g` | FFmpeg `x11grab` | `wf-recorder` under Wayland, FFmpeg `x11grab` under X11 |
|
||||
| Recording frame-rate control | not offered (`screencapture` has none) | 15 / 24 / 30 | 15 / 24 / 30 (`-r` / `-framerate`) |
|
||||
| History library, drag a row out | Yes | Yes | Yes |
|
||||
| Git-backed updates: SHA256 gate, optional signed manifest | Yes | x64 is the published installer; an ARM machine gets it through the `windows` fallback | Checks and downloads; nothing published for Linux, so the answer is "no artifact" |
|
||||
| Image convert and edit | Yes | Yes | Yes |
|
||||
| HEIC / AVIF encode | `sips` | ImageMagick | ImageMagick |
|
||||
| PDF text, merge, split, rotate, compress | Yes | Yes | Yes |
|
||||
|
|
@ -311,7 +353,7 @@ pnpm tauri dev
|
|||
|
||||
```bash
|
||||
pnpm check # TypeScript, no emit
|
||||
pnpm test # conversion matrix and drag-target tests
|
||||
pnpm test # conversion matrix, ring catalogue and order, drag payload, drop targets
|
||||
pnpm build # tsc + vite
|
||||
cargo test --lib # Rust unit tests, from src-tauri/
|
||||
pnpm tauri build # release bundle
|
||||
|
|
@ -327,19 +369,21 @@ PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
|||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
```
|
||||
|
||||
The result is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. To produce the Windows installer and portable ZIP from macOS, run `scripts/build-windows-release.sh`; full details are in `docs/BUILD_WINDOWS.md`.
|
||||
The result is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. To produce the Windows installers and portable ZIPs — x64 and ARM64, both — from macOS, run `scripts/build-windows-release.sh`; full details are in `docs/BUILD_WINDOWS.md`.
|
||||
|
||||
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. Dev builds signed with a local certificate keep those grants stable across rebuilds; distribution needs Developer ID plus notarization.
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
React UI one webview, six views
|
||||
├─ main drop target, shortcuts, recent outputs, language, settings
|
||||
React UI one webview, eight view kinds
|
||||
├─ main drop target, shortcuts, history library, settings, first-run checks
|
||||
├─ radial transparent always-on-top ring, hit-tested by polar sector
|
||||
├─ capture frozen still + area selection
|
||||
├─ recorder floating timer and stop control
|
||||
├─ editor annotation canvas, text, video, OCR
|
||||
├─ result-* floating capture result card, one window per capture
|
||||
├─ share-* incoming transfer consent card
|
||||
└─ pin always-on-top image reference
|
||||
|
||||
Tauri command layer src-tauri/src/
|
||||
|
|
@ -347,16 +391,20 @@ Tauri command layer src-tauri/src/
|
|||
├─ pdf.rs merge, split, rotate, text, render, image→PDF, compress
|
||||
├─ office.rs PPTX and spreadsheet → Markdown, pure Rust
|
||||
├─ capture.rs full-screen capture, region crop, editor handoff
|
||||
├─ recording.rs screencapture / FFmpeg, with interrupt-based finalization
|
||||
├─ recording.rs screencapture / FFmpeg / wf-recorder, with signal-based finalization
|
||||
├─ drag_bridge.rs global drag detection, ring mode, radial positioning
|
||||
├─ settings.rs output directories, write checks, privacy deep links
|
||||
├─ settings.rs output directories, write checks, ring order, permission links,
|
||||
│ first-run flag
|
||||
├─ history.rs the shared capture/result library, pinning and capacity
|
||||
├─ result_card.rs floating post-capture card with its own auto-close fuse
|
||||
├─ update.rs manifest fetch, signature check, semver compare, SHA256 gate
|
||||
├─ share.rs LAN beacons, peer list, AirDrop-style file transfer
|
||||
└─ editor.rs editor and pin window state
|
||||
|
||||
Platform adapters
|
||||
├─ macOS AppKit drag bridge · PDFKit renderer · AppKit doc renderer · screencapture
|
||||
├─ Windows Win32 drag state · PowerShell capture · FFmpeg · Poppler
|
||||
└─ Linux grim / gnome-screenshot · FFmpeg · Poppler
|
||||
├─ Windows Win32 drag state · GDI BitBlt capture · FFmpeg · Poppler
|
||||
└─ Linux grim / gnome-screenshot · wf-recorder (Wayland) · FFmpeg · Poppler
|
||||
|
||||
OCR: Tesseract.js WASM + bundled eng/chi_sim, in-process, offline
|
||||
```
|
||||
|
|
@ -367,22 +415,27 @@ The radial hit-test is pure geometry — one polar calculation shared by native
|
|||
|
||||
```text
|
||||
src/ React UI, i18n (en/zh), Tauri API bindings
|
||||
src/lib/ pure helpers and Node tests, including the conversion matrix
|
||||
src/lib/ pure helpers and Node tests: conversion matrix, ring
|
||||
catalogue and ordering, drag payloads, drop targets
|
||||
src-tauri/src/ Rust command layer and platform adapters
|
||||
native/macos/ Swift sidecars: drag bridge, PDF renderer, doc renderer,
|
||||
compiled into src-tauri/binaries/ by pnpm mac:drag-bridge
|
||||
scripts/ OCR staging, macOS sidecars, Windows installer and release builds
|
||||
scripts/ OCR staging, macOS sidecars, Windows installer, release build,
|
||||
manifest publish and manifest signing
|
||||
public/tesseract/ WASM core + traineddata, generated, not committed
|
||||
assets/ app icon source
|
||||
src-tauri/icons/ generated app icons per platform
|
||||
docs/ Windows build guide, roadmap
|
||||
.github/workflows/ macOS and Windows CI
|
||||
docs/ Windows build guide, release/update channel, roadmap, mobile plan
|
||||
scripts/linux/ Dockerfile that builds the Linux deb/AppImage off CI
|
||||
.github/workflows/ CI definitions for macOS, Windows and Linux (see Contributing)
|
||||
FileFlipper/ separate companion project, its own repository
|
||||
```
|
||||
|
||||
## Privacy
|
||||
|
||||
Shift makes no internet requests. Files are read, converted, and written locally; OCR runs in-process against bundled models; recent outputs are a local list. Nothing is uploaded, and nothing is collected.
|
||||
Shift makes no internet requests for anything it does to your files. They are read, converted, and written locally; OCR runs in-process against bundled models; the history library is a local file. Nothing is uploaded, and nothing is collected.
|
||||
|
||||
Two paths touch the network, and neither carries file content unless you ask: the **update check** fetches a manifest over HTTPS at most once a day - and an installer only when you press the button - while **Send to a device** talks to your local network alone.
|
||||
|
||||
The one exception is opt-in by usage: **Send to a device** talks to your local network only — UDP beacons on `239.255.77.88:47888` plus a direct TCP connection between the two machines, carrying the machine name so each side can label the other. It is inert until you open that picker or another Shift sends you a file.
|
||||
|
||||
|
|
@ -391,12 +444,14 @@ The one exception is opt-in by usage: **Send to a device** talks to your local n
|
|||
- Document → PDF on Windows/Linux still needs Pandoc plus a working PDF engine; the bundled AppKit renderer is macOS-only.
|
||||
- PPTX and spreadsheet → PDF is a text and table summary, not a layout-accurate render.
|
||||
- `.doc`, `.pages`, `.ppt`, `.key` and `.numbers` are recognised but not parsed — export to DOCX/PPTX/XLSX first.
|
||||
- HEIC/HEIF/AVIF convert through the system decoder, but the pixel tools need a PNG/JPEG/WebP/TIFF/BMP/GIF input; AVIF is not yet an export target.
|
||||
- HEIC/HEIF/AVIF are read through the system decoder, so conversion and the pixel tools both accept them. Neither format can be written on this path, so a pixel tool applied to one produces a PNG; AVIF is not an export target at all.
|
||||
- PDF compression resamples embedded images to at most 1440 px as q60 JPEG. It deliberately skips anything it cannot prove it can round-trip — masks, indexed or CMYK colour, JPX/JBIG2/CCITT — so exotic scans may still resist shrinking.
|
||||
- Windows recording and media conversion require `ffmpeg` on `PATH`.
|
||||
- Windows recording and media conversion require `ffmpeg` on `PATH`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11, and neither path is exercised by the forge this repository is hosted on, so treat Linux capture as build-verified only.
|
||||
- Linux is a build target, not a shipped product: no deb or AppImage is published, so the update channel carries no `linux` key and a Linux build finds nothing to download. `scripts/linux/Dockerfile` and the `linux` job in CI remain the recipe for anyone who wants one.
|
||||
- Dragging a library row out uses the webview's file-URL drag support. It is the standard `text/uri-list` payload with a `file://` entry plus the plain path, and it needs a gesture-level check on each platform; until then, **Send**, **Reveal** and the row's own buttons are the guaranteed paths for handing a file over.
|
||||
- LAN sharing needs a network that allows peer traffic. Multicast is skipped by some guest and corporate Wi-Fi; those networks still work over the broadcast and unicast fallbacks, but two copies cannot meet across a router that isolates clients.
|
||||
- On Windows only one Shift copy per machine can hold the discovery port, so extra instances do not appear as peers.
|
||||
- Windows paths build and pass CI, but gesture-level QA needs real Windows hardware.
|
||||
- Windows and Linux paths are compile-verified here, and the forge hosting this repository runs no Actions, so nothing is ever built by CI on your behalf. Gesture-level QA needs real Windows and Linux hardware.
|
||||
- Signing identity changes on macOS may require re-approving Screen Recording and Accessibility.
|
||||
|
||||
Roadmap: `docs/ROADMAP.md`.
|
||||
|
|
@ -423,6 +478,12 @@ Next to the source file by default, with a suffix — check the recent list in t
|
|||
**❓ Which languages are supported?**
|
||||
English and Simplified Chinese, switchable in the main window's Settings. On first launch it follows the system language. The tray menu follows the selected language; native macOS permission prompts stay in English.
|
||||
|
||||
**❓ How does Shift get updates?**
|
||||
From this repository. A `releases` branch carries the installers plus a manifest with each file's SHA256; Settings → **Updates** shows the feed this build reads, checks it once a day, and downloads on request. Nothing installs until the download's byte length and recomputed SHA256 both match the manifest. `docs/RELEASE.md` documents publishing with `scripts/publish-release.sh`, and the optional ed25519 manifest signature that proves where the manifest came from rather than only that the download matches it.
|
||||
|
||||
**❓ Can I change which wedge comes first?**
|
||||
The order is honoured, but there is currently no screen to change it: Settings no longer carries the reorder tab. An order written to `wedgeOrders` in `settings.json` is still applied, and an order can only arrange the wedges a file type actually supports — it cannot add or remove actions, and **Send** always stays last.
|
||||
|
||||
**❓ Can I edit a screenshot without saving it?**
|
||||
Yes — annotation works on a canvas copy and only writes on **Save copy** or **Copy**. The source file is never modified. Use **Pin** to keep it floating on screen as a reference instead.
|
||||
|
||||
|
|
@ -431,7 +492,9 @@ Quit from the tray and delete the app. Nothing is written outside your output fo
|
|||
|
||||
## Contributing
|
||||
|
||||
Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`; adding a tool is one entry in `toolWedges` plus one match arm. Run `pnpm check`, `pnpm test`, `pnpm build` and `cargo test --lib` before pushing. CI builds debug bundles on macOS and Windows.
|
||||
Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`. Adding a tool is one id in the right list in `src/lib/radialOrder.ts`, its label, its icon in `WEDGE_ICONS`, and one match arm in `executeAction` - the ring renders the same catalogue, so it appears with no other registration. Run `pnpm check`, `pnpm test`, `pnpm build` and `cargo test --lib` before pushing.
|
||||
|
||||
`.github/workflows/ci.yml` carries macOS, Windows and Linux jobs, but **the forge hosting this repository has no Actions runner**, so those jobs are definitions rather than a live guarantee: nothing is built until a GitHub mirror, a Forgejo Actions instance, or a contributor runs them. The four commands above are what CI would run, plus `pnpm tauri build` per platform; `scripts/linux/Dockerfile` builds the Linux packages on a plain Docker host.
|
||||
|
||||
**Forks and derivative works are welcome.** You may use, modify, redistribute, and build on this code commercially, provided you keep the copyright notice and the LICENSE file.
|
||||
|
||||
|
|
|
|||
112
README.zh-CN.md
112
README.zh-CN.md
|
|
@ -17,11 +17,14 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
|
|||
- [工具](#工具)
|
||||
- [压缩、命名与取消](#压缩命名与取消)
|
||||
- [截图与标注](#截图与标注)
|
||||
- [截图历史库](#截图历史库)
|
||||
- [OCR](#ocr)
|
||||
- [发送到设备](#发送到设备)
|
||||
- [自定义圆环顺序](#自定义圆环顺序)
|
||||
- [快捷键](#快捷键)
|
||||
- [菜单栏菜单](#菜单栏菜单)
|
||||
- [输出位置](#输出位置)
|
||||
- [软件更新](#软件更新)
|
||||
- [外部依赖](#外部依赖)
|
||||
- [平台支持情况](#平台支持情况)
|
||||
- [从源码构建](#从源码构建)
|
||||
|
|
@ -43,7 +46,9 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
|
|||
|
||||
**默认批量处理。** 选中十个文件、一次拖拽,就产出十个结果。结果保存在源文件旁边并附带描述性后缀(`report (compressed).pdf`、`photo (rotated).png`),永不覆盖——重名时自动追加序号。也可在设置中改为统一收集到一个文件夹。
|
||||
|
||||
**截图能力内置。** 冻结画面的区域截图、全屏截图,以及带悬浮计时器的区域录屏;一律对准光标所在的显示器,而非固定主屏。截图完成后直接进入标注画布,并可钉成常驻置顶的参考窗口。
|
||||
**截图能力内置。** 冻结画面的区域截图、全屏截图,以及带悬浮计时器的区域录屏;一律对准光标所在的显示器,而非固定主屏。一次截图完成后会弹出一张浮动结果卡片——复制、钉住、发送、在文件夹中显示、编辑,各一键完成,稍候自行退场;也可在设置里改成直接进入标注画布。截图与录屏选项只给出当前平台真正支持的开关:macOS 提供麦克风,FFmpeg 后端提供帧率。
|
||||
|
||||
**圆环顺序由你决定。** 已保存的顺序会按文件类型、按环重新排列扇区,最常用的转换不再压在扇区环的最下面。(调整顺序的设置标签页已移除,顺序改由 `settings.json` 提供,应用内暂无修改入口。)
|
||||
|
||||
**OCR 在本机运行。** 英文与简体中文,使用随应用打包的 Tesseract WASM 引擎与语言模型。OCR 全流程不发生任何网络请求。
|
||||
|
||||
|
|
@ -71,6 +76,8 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
|
||||
**一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。
|
||||
|
||||
**首次运行。** Shift 会弹出一张检查卡片,包含四项:屏幕录制权限、三个输出目录是否可写、当前实例是否持有全局快捷键、缺少哪些可选工具。每一项都会说明查到了什么并给出修复入口——打开隐私设置、退出其他实例——直接关掉卡片不会改动任何设置。每个安装只会弹一次——升级后的首次启动也算一次,因为旧设置文件里没有这个字段;删掉 `settings.json` 里的 `setupReviewed` 就能再看一次。
|
||||
|
||||
**macOS 首次运行。** 需要授予「屏幕录制」(截图与录屏),以及你所选输出目录的「文件与文件夹」访问权限。截图前会先检查权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑截图。
|
||||
|
||||
## 支持的文件
|
||||
|
|
@ -90,7 +97,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
|
||||
解码与编码能力并不对称,应用也不会假装对称:
|
||||
|
||||
- **图片解码**由 Rust `image` 原生完成,支持 PNG、JPEG、WebP、TIFF、BMP 与 GIF。HEIC/HEIF/AVIF 先走系统解码器——macOS 用 `sips`,其他系统用 ImageMagick——随后可转换为圆环提供的任意图片格式(包括 WEBP),也可生成 PDF。像素类工具仍需要可原生读取的输入,因此旋转、翻转、黑白、50%、压缩前请先转一次。
|
||||
- **图片解码**由 Rust `image` 原生完成,支持 PNG、JPEG、WebP、TIFF、BMP 与 GIF。HEIC/HEIF/AVIF 先走系统解码器——macOS 用 `sips`,其他系统用 ImageMagick——随后可转换为圆环提供的任意图片格式(包括 WEBP),也可生成 PDF。像素类工具走同一条解码路径,因此手机截图可以直接旋转或缩小;由于这条路径无法写出 HEIC,结果会以 PNG 保存。
|
||||
- **图片编码**中的 PNG、JPG、WebP、TIFF、BMP、GIF 为原生实现。HEIC 导出在 macOS 走 `sips`,在 Windows/Linux 需要 ImageMagick。AVIF 可作为输入,但暂未提供为导出目标。
|
||||
- **音视频**的解码与编码范围取决于你的 FFmpeg 构建;菜单为视频提供 MP4、MOV、GIF、M4A,为音频提供 M4A、WAV、MP3。
|
||||
- **Office 文件**以纯 Rust 解析(表格用 `calamine`,PPTX 用 `zip` + `quick-xml`),因此无需安装 Office。
|
||||
|
|
@ -130,11 +137,13 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
|
||||
工具环(拖拽时按 `Option + Shift`)。这些是一次手势完成的操作,不属于格式转换。
|
||||
|
||||
「同类型」指输出沿用输入的文件容器,只有一个例外:HEIC 与 AVIF 在本机能读不能写,因此对它们执行像素类工具时会输出 PNG,文件名也会如实标注。
|
||||
|
||||
| 工具 | 适用对象 | 输出 | 具体行为 |
|
||||
| --- | --- | --- | --- |
|
||||
| 压缩 | 图片、视频、音频、PDF | `.jpg`/`.png`、`.mp4`、`.m4a`、`.pdf` | 图片按 q68 重编码(含透明通道则保留 PNG);视频 CRF 28;音频转 128k AAC;PDF 先把内嵌图片降采样到 ≤1440 px 的 q60 JPEG,再清理对象 |
|
||||
| 元数据 | 图片、PDF | 同类型,` (clean)` | 重写图片并去除 EXIF;移除 PDF 的 `/Info` 与 `/Metadata` |
|
||||
| 旋转 | 图片、PDF | 同类型,` (rotated)` | 顺时针 90°,按各格式的原生方式处理 |
|
||||
| 移除元数据 | 图片、PDF | 同类型,` (clean)` | 重写图片并去除 EXIF;移除 PDF 的 `/Info` 与 `/Metadata`。只负责移除并另存副本,不展示文件携带了什么 |
|
||||
| 旋转 | 图片、PDF | 同类型,` (rotated)` | 顺时针 90°,按各格式的原生方式处理;HEIC/AVIF 输入在本机没有对应编码器,因此结果转为 PNG |
|
||||
| 翻转 | 图片 | 同类型,` (flipped)` | 水平镜像 |
|
||||
| 黑白 | 图片 | 同类型,` (bw)` | 转灰度 |
|
||||
| 50% | 图片 | 同类型,` (50%)` | 宽高各减半,Lanczos3 |
|
||||
|
|
@ -178,7 +187,11 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
|
||||
## 截图与标注
|
||||
|
||||
**截图。** 区域截图会先铺一层冻结画面,你框选的像素就是最终得到的像素;全屏截图则完全跳过遮罩层。录屏在 macOS 通过 `screencapture -v` 保存为 MOV,其他系统通过 FFmpeg 保存为 MP4,配有悬浮计时器与停止按钮。Linux 截图优先使用 `grim`,回退到 `gnome-screenshot`。
|
||||
**截图。** 区域截图会先铺一层冻结画面,你框选的像素就是最终得到的像素;全屏截图则完全跳过遮罩层。录屏在 macOS 通过 `screencapture -v` 保存为 MOV,其他系统保存为 MP4,配有悬浮计时器与停止按钮。Linux 截图优先使用 `grim`,回退到 `gnome-screenshot`;Wayland 下录屏改用 `wf-recorder`,因为 ffmpeg 的 `x11grab` 在那里没有可抓取的根窗口。
|
||||
|
||||
**录屏选项是诚实的。** `src-tauri/src/recording.rs` 中的 `capabilities()` 报告当前后端真正实现的能力,截图工具条只渲染这些开关。macOS 有麦克风开关(`screencapture -g`)而没有帧率选项,因为 `screencapture -v` 根本不支持帧率;Windows 与 Linux 提供 15 / 24 / 30 三档帧率,它会成为 ffmpeg 的 `-framerate`,但没有麦克风开关,因为抓屏尚未接入音频输入。界面上不存在“按了却被编码器默默忽略”的选项。
|
||||
|
||||
**结果卡片。** 截图或录屏完成后,右下角出现一张卡片,提供**复制**、**钉住**、**发送**、**在文件夹中显示**、**编辑**。鼠标悬停时卡片停留,否则自行退场。设置 → 截图 可选择这一刻的行为是**结果卡片**还是**在编辑器中打开**;当卡片窗口无法创建时会自动回退到编辑器。
|
||||
|
||||
**标注。** 编辑器画布按原始分辨率工作,并写出新的 PNG,因此源文件永远不会被修改。
|
||||
|
||||
|
|
@ -187,6 +200,8 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
| 矩形、箭头、高亮、文字 | 自由绘制,每条标注可单独设置颜色与粗细 |
|
||||
| 打码 | 实心黑色遮挡条,直接烧入输出图像——不是覆盖层 |
|
||||
| 马赛克 | 对下方区域做真实采样降采样,不是半透明填充 |
|
||||
| 模糊 | 对区域做真正的高斯模糊,并按绘制形状裁切 |
|
||||
| 图章 | 对勾、叉、星三种矢量图章,点一下即可落下 |
|
||||
| 序号 | 自动递增的序号标记 |
|
||||
| 裁剪 | 交互式裁剪,带明确的「应用裁剪」步骤 |
|
||||
| 加背景 | 圆角留白加渐变底,适合社交配图与幻灯片插图 |
|
||||
|
|
@ -197,6 +212,16 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
|
||||
**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以可编辑文本打开。每个编辑器都提供复制、另存为、打开、在文件夹中显示、文字识别与复制文字。
|
||||
|
||||
## 截图历史库
|
||||
|
||||
每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。主窗口的「最近使用」卡片就是这个历史库:
|
||||
|
||||
- 列表超过几行后出现**搜索**框,按文件名过滤。
|
||||
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。
|
||||
- **移除**单行,或**清空**整个库——收藏项会保留。
|
||||
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径与 Shift 内部类型,供编辑器与圆环使用。
|
||||
- 单击某一行在编辑器中打开;行内其余按钮负责发送、在文件夹中显示、以及钉在屏幕上。
|
||||
|
||||
## OCR
|
||||
|
||||
界面中对应「文字识别」(图片与扫描件)和「提取文字」(含文字层的 PDF)两处按钮。
|
||||
|
|
@ -221,6 +246,12 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
|
|||
|
||||
整个过程只涉及本地网络——不会有任何数据走到互联网。接收端监听全部网卡,因此 macOS 首次分享时会弹出防火墙授权提示,允许后双向均可用。
|
||||
|
||||
## 自定义圆环顺序
|
||||
|
||||
已保存的顺序会为某种文件类型、某个环重新排列扇区。**调整顺序的界面已不在设置中**——该标签页已移除,因此顺序仍从 `settings.json` 的 `wedgeOrders` 读取并生效,但当前界面不再提供修改入口。已有的顺序照常工作,只是暂时无法在应用内更改。
|
||||
|
||||
决定“存在哪些操作”的是目录而不是预设。`src/lib/radialOrder.ts` 保存每种文件类型、每个环的扇区列表,保存的顺序只能对目录为该类型提供的 id 重新排列:日后被移除的 id 会自动从圆环消失,新增的 id 会插入默认位置,而**发送**永远排在最后。改完下一个手势即生效——不需要重启,也不可能把某个操作藏到你找不到。
|
||||
|
||||
## 快捷键
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
|
@ -244,6 +275,7 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
|
|||
| Capture full screen | `Alt+Shift+4` | 截取光标所在显示器 |
|
||||
| Record area | `Alt+Shift+3` | 开始或停止区域录屏 |
|
||||
| OCR an image… | — | 选择图片并在本机识别文字 |
|
||||
| Update available *x.y.z* | — | 仅在有可用更新时出现;打开设置 → 软件更新 |
|
||||
| Quit Shift | `Cmd/Ctrl+Q` | 退出;若有正在进行的录屏会先收尾保存 |
|
||||
|
||||
菜单项文案会跟随应用语言;macOS 系统权限弹窗仍为英文。
|
||||
|
|
@ -260,13 +292,20 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
|
|||
|
||||
三者都可在设置中修改。文件操作另外提供「统一收集到一个文件夹」模式,替代默认的就近保存。设置面板会列出所有解析后的实际路径、检测该路径是否可写、在文件管理器中显示它,并在缺少权限时直接跳转到 macOS 的「屏幕录制」与「文件与文件夹」隐私面板。
|
||||
|
||||
## 软件更新
|
||||
|
||||
更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。
|
||||
|
||||
Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。下载完成的安装包在安装前要通过两道校验:字节数完全一致,以及重新计算的 SHA256 与清单一致。任一不符即删除文件并明确报错,因此半成品永远不会被启动。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。
|
||||
|
||||
## 外部依赖
|
||||
|
||||
核心转换、环形菜单、截图与 OCR 在零外部依赖的情况下即可工作。以下工具用于扩展能力边界:
|
||||
|
||||
| 工具 | 用于 | macOS | Windows | Linux |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| FFmpeg | 音视频转换/压缩、720p、静音、截帧、单声道;非 macOS 的录屏 | 可选 | 录屏**必需** | **必需** |
|
||||
| FFmpeg | 音视频转换/压缩、720p、静音、截帧、单声道;非 macOS 的录屏 | 可选 | 录屏**必需** | **必需**(音视频与 X11 录屏) |
|
||||
| `wf-recorder` | Wayland 下的区域录屏 | 不需要 | 不需要 | Wayland 下需要 |
|
||||
| Pandoc | 文档 ↔ DOCX/RTF/HTML/TXT/MD(仅支持 ODT 输入) | 可选 | 需要 | 需要 |
|
||||
| Typst | Pandoc 文档转 PDF 引擎 | 不需要(AppKit) | 需要 | 需要 |
|
||||
| Poppler `pdftoppm` | PDF 转图片、PDF 转 Word、扫描件 OCR | 不需要(PDFKit) | 需要 | 需要 |
|
||||
|
|
@ -281,9 +320,12 @@ Shift 会在设置 →「运行组件」中显示当前机器实际找到的工
|
|||
| --- | --- | --- | --- |
|
||||
| 环形菜单、编辑器、托盘、多语言 | 支持 | 支持 | 支持 |
|
||||
| 拖拽唤起圆环 | AppKit 全局拖拽桥 | Win32 拖拽状态轮询 + 原生拖放 | 暂不支持——仅能用主窗口选择文件 |
|
||||
| 区域 / 全屏截图 | `screencapture` | PowerShell | `grim` / `gnome-screenshot` |
|
||||
| 区域 / 全屏截图 | `screencapture` | Win32 GDI `BitBlt` | `grim` / `gnome-screenshot` |
|
||||
| 跟随光标所在显示器 | 支持 | 支持 | `grim` 输出选择 |
|
||||
| 区域录屏 | `screencapture -v` | FFmpeg | 计划中 |
|
||||
| 区域录屏 | `screencapture -v`,`-g` 录麦克风 | FFmpeg `x11grab` | Wayland 用 `wf-recorder`,X11 用 FFmpeg `x11grab` |
|
||||
| 录屏帧率控制 | 不提供(`screencapture` 不支持) | 15 / 24 / 30 | 15 / 24 / 30(`-r` / `-framerate`) |
|
||||
| 截图历史库、把某一行拖出 | 支持 | 支持 | 支持 |
|
||||
| 基于 git 的更新:SHA256 校验,清单可选签名 | 支持 | 发布的是 x64 安装包;ARM 机器经由 `windows` 回退拿到同一份 | 可检查并下载;Linux 没有发布产物,因此结果是「没有对应产物」 |
|
||||
| 图片转换与编辑 | 支持 | 支持 | 支持 |
|
||||
| HEIC / AVIF 编码 | `sips` | ImageMagick | ImageMagick |
|
||||
| PDF 文字、合并、拆分、旋转、压缩 | 支持 | 支持 | 支持 |
|
||||
|
|
@ -308,7 +350,7 @@ pnpm tauri dev
|
|||
|
||||
```bash
|
||||
pnpm check # TypeScript 类型检查,不产出文件
|
||||
pnpm test # 转换矩阵与拖拽命中测试
|
||||
pnpm test # 转换矩阵、圆环目录与顺序、拖拽载荷、投放命中测试
|
||||
pnpm build # tsc + vite
|
||||
cargo test --lib # Rust 单元测试,在 src-tauri/ 目录下执行
|
||||
pnpm tauri build # 发布构建
|
||||
|
|
@ -324,19 +366,21 @@ PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
|||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
```
|
||||
|
||||
产物是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程。若要在 macOS 上同时生成 Windows 安装版与便携版,运行 `scripts/build-windows-release.sh`;完整步骤见 `docs/BUILD_WINDOWS.md`。
|
||||
产物是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程。若要在 macOS 上生成 Windows 安装版与便携版(x64 与 ARM64 两种架构都会产出),运行 `scripts/build-windows-release.sh`;完整步骤见 `docs/BUILD_WINDOWS.md`。
|
||||
|
||||
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。使用本地证书签名的开发构建,可以在反复重编译后保持这些授权稳定;对外分发则需要 Developer ID 证书与公证。
|
||||
|
||||
## 架构
|
||||
|
||||
```text
|
||||
React UI 单一 webview,六种视图
|
||||
├─ main 拖放目标、快捷键、最近输出、语言、设置
|
||||
React UI 单一 webview,八类视图
|
||||
├─ main 拖放目标、快捷键、截图历史库、设置、首次运行检查
|
||||
├─ radial 透明置顶圆环,按极角扇区命中判定
|
||||
├─ capture 冻结画面 + 区域框选
|
||||
├─ recorder 悬浮计时器与停止按钮
|
||||
├─ editor 标注画布、文本、视频、OCR
|
||||
├─ result-* 截图后的浮动结果卡片,每次截图一个窗口
|
||||
├─ share-* 收到文件时的确认卡片
|
||||
└─ pin 置顶图片参考窗
|
||||
|
||||
Tauri 命令层 src-tauri/src/
|
||||
|
|
@ -344,16 +388,19 @@ Tauri 命令层 src-tauri/src/
|
|||
├─ pdf.rs 合并、拆分、旋转、文字、渲染、图片转 PDF、压缩
|
||||
├─ office.rs PPTX 与电子表格转 Markdown,纯 Rust
|
||||
├─ capture.rs 全屏截图、区域裁剪、交给编辑器
|
||||
├─ recording.rs screencapture / FFmpeg,以中断方式收尾
|
||||
├─ recording.rs screencapture / FFmpeg / wf-recorder,以信号方式收尾
|
||||
├─ drag_bridge.rs 全局拖拽检测、圆环模式、环形菜单定位
|
||||
├─ settings.rs 输出目录、可写检测、隐私面板深链
|
||||
├─ settings.rs 输出目录、可写检测、圆环顺序、隐私面板深链、首次检查标记
|
||||
├─ history.rs 共享的截图/结果历史库、收藏与容量上限
|
||||
├─ result_card.rs 浮动结果卡片,自带自动关闭保险
|
||||
├─ update.rs 清单拉取、签名校验、semver 比较、SHA256 校验
|
||||
├─ share.rs 局域网广播、设备列表、AirDrop 式文件传输
|
||||
└─ editor.rs 编辑器与钉图窗口状态
|
||||
|
||||
平台适配器
|
||||
├─ macOS AppKit 拖拽桥 · PDFKit 渲染器 · AppKit 文档渲染器 · screencapture
|
||||
├─ Windows Win32 拖拽状态 · PowerShell 截图 · FFmpeg · Poppler
|
||||
└─ Linux grim / gnome-screenshot · FFmpeg · Poppler
|
||||
├─ Windows Win32 拖拽状态 · GDI BitBlt 截图 · FFmpeg · Poppler
|
||||
└─ Linux grim / gnome-screenshot · wf-recorder(Wayland)· FFmpeg · Poppler
|
||||
|
||||
OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线
|
||||
```
|
||||
|
|
@ -364,36 +411,41 @@ OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线
|
|||
|
||||
```text
|
||||
src/ React 界面、多语言(en/zh)、Tauri API 绑定
|
||||
src/lib/ 纯函数与 Node 测试,包括格式转换矩阵
|
||||
src/lib/ 纯函数与 Node 测试:转换矩阵、圆环目录与顺序、拖拽载荷、
|
||||
投放命中判定
|
||||
src-tauri/src/ Rust 命令层与平台适配器
|
||||
native/macos/ Swift 伴生进程:拖拽桥、PDF 渲染器、文档渲染器
|
||||
由 pnpm mac:drag-bridge 编译进 src-tauri/binaries/
|
||||
scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器与发布构建
|
||||
scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器、发布构建、
|
||||
清单发布与清单签名
|
||||
public/tesseract/ WASM 内核与语言模型,构建生成,不提交
|
||||
assets/ 应用图标源文件
|
||||
src-tauri/icons/ 各平台生成的应用图标
|
||||
docs/ Windows 构建指南、路线图
|
||||
.github/workflows/ macOS 与 Windows CI
|
||||
docs/ Windows 构建指南、发布与更新通道、路线图、移动端规划
|
||||
scripts/linux/ 在 CI 之外构建 Linux deb/AppImage 的 Dockerfile
|
||||
.github/workflows/ macOS、Windows、Linux 的 CI 定义(见「参与贡献」)
|
||||
FileFlipper/ 独立姊妹项目,拥有自己的仓库
|
||||
```
|
||||
|
||||
## 隐私
|
||||
|
||||
Shift 不发起任何互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;最近输出只是本地列表。既不上传,也不收集。
|
||||
Shift 对文件做的任何处理都不会发起互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;截图历史库只是一个本地文件。既不上传,也不收集。
|
||||
|
||||
唯一的例外取决于你是否使用:**发送到设备** 只与本地网络通信——`239.255.77.88:47888` 上的 UDP 广播,加上两台电脑之间的直连 TCP,其中携带机器名称以便双方互相标注。在你打开该面板、或有另一台 Shift 向你发送文件之前,它不会有任何动作。
|
||||
只有两条路径会接触网络,且默认都不携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单(只有你按下按钮时才下载安装包);而**发送到设备** 只与本地网络通信——`239.255.77.88:47888` 上的 UDP 广播,加上两台电脑之间的直连 TCP,其中携带机器名称以便双方互相标注。在你打开该面板、或有另一台 Shift 向你发送文件之前,它不会有任何动作。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- Windows/Linux 上的文档转 PDF 仍需 Pandoc 加上可用的 PDF 引擎;内置的 AppKit 渲染器仅限 macOS。
|
||||
- PPTX 与电子表格转 PDF 是文字与表格摘要,不是版面精确还原。
|
||||
- `.doc`、`.pages`、`.ppt`、`.key`、`.numbers` 可识别但不解析——请先导出为 DOCX/PPTX/XLSX。
|
||||
- HEIC/HEIF/AVIF 通过系统解码器转换,但像素类工具需要 PNG/JPEG/WebP/TIFF/BMP/GIF 输入;AVIF 暂未提供为导出目标。
|
||||
- HEIC/HEIF/AVIF 可由系统解码器读取,格式转换与像素类工具都能直接使用。只是这两种格式无法经由该路径写出,因此对它们执行像素类工具时会输出 PNG;AVIF 仍不提供为导出目标。
|
||||
- PDF 压缩会把内嵌图片降采样到最长边 1440 px、q60 JPEG。凡是不能确认可安全往返的内容都会原样保留——蒙版、索引色/CMYK、JPX/JBIG2/CCITT——因此部分特殊扫描件仍难以压缩。
|
||||
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。
|
||||
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`;本仓库所在的代码托管平台不会执行这些路径,因此 Linux 的截图能力只能算「可编译」而非「已验证」。
|
||||
- Linux 是「可构建」而非「已发布」:不提供 deb 或 AppImage,更新通道里也没有 `linux` 键,因此 Linux 构建检查更新时会得到「没有对应产物」。想要自己动手的人,可照 `scripts/linux/Dockerfile` 或 CI 里的 `linux` 任务来做。
|
||||
- 把历史库的某一行拖出去依赖 Webview 对 file URL 拖拽的支持。载荷使用标准的 `text/uri-list`(内含 `file://` 条目)并附带纯文本路径,仍需在每个平台上做手势级验证;在此之前,**发送**、**在文件夹中显示**以及行内按钮是交付文件的确定路径。
|
||||
- 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。
|
||||
- Windows 上每台电脑只有一个 Shift 实例能占用发现端口,因此额外实例不会出现在设备列表中。
|
||||
- Windows 代码路径可编译并通过 CI,但手势层面的验证仍需真实 Windows 设备。
|
||||
- Windows 与 Linux 代码路径在本机通过编译验证,而托管本仓库的平台并不运行 Actions,因此 CI 不会替你构建任何东西;手势层面的验证仍需真实 Windows 与 Linux 设备。
|
||||
- macOS 上签名身份变化后,可能需要重新授予「屏幕录制」与「辅助功能」权限。
|
||||
|
||||
路线图见 `docs/ROADMAP.md`。
|
||||
|
|
@ -420,6 +472,12 @@ Shift 不发起任何互联网请求。文件在本地读取、转换、写回
|
|||
**❓ 支持哪些语言?**
|
||||
英文与简体中文,可在主窗口的设置中切换;首次启动时跟随系统语言。托盘菜单会跟随所选语言;macOS 系统权限弹窗仍为英文。
|
||||
|
||||
**❓ Shift 怎么获取更新?**
|
||||
就来自本仓库。`releases` 分支保存安装包,以及记录每个文件 SHA256 的清单;设置 → **软件更新** 会显示当前构建读取的更新源,每天检查一次,并在你点击后才下载。只有下载结果的字节数与重新计算的 SHA256 同时与清单一致,才允许安装。发布流程见 `docs/RELEASE.md` 与 `scripts/publish-release.sh`。
|
||||
|
||||
**❓ 能调整扇区的先后顺序吗?**
|
||||
顺序会被照常执行,但目前没有修改它的界面:设置中已不再有该标签页。写在 `settings.json` 里 `wedgeOrders` 的顺序仍然生效;顺序只能排列这种文件真正支持的操作,不能增删,并且**发送**始终排在最后。
|
||||
|
||||
**❓ 能先标注、不保存原图吗?**
|
||||
可以。标注工作在画布副本上,只有「保存副本」或「复制」才会写盘,源文件永不被修改。也可以「钉在屏幕上」,把它作为浮动参考图。
|
||||
|
||||
|
|
@ -428,7 +486,9 @@ Shift 不发起任何互联网请求。文件在本地读取、转换、写回
|
|||
|
||||
## 参与贡献
|
||||
|
||||
新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `toolWedges` 加一项加一个 match 分支。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build` 与 `cargo test --lib`。CI 会在 macOS 与 Windows 上产出 debug 包。
|
||||
新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `src/lib/radialOrder.ts` 的对应列表中加入 id、补上文案、在 `WEDGE_ICONS` 中加入图标,再在 `executeAction` 中加一个分支——圆环渲染的就是同一份目录,因此无需别处注册即可出现。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build` 与 `cargo test --lib`。
|
||||
|
||||
`.github/workflows/ci.yml` 内含 macOS、Windows、Linux 三个任务,但**本仓库所在的托管平台没有 Actions 执行器**,因此这些任务目前只是定义、而非实时保障:只有镜像到 GitHub、接入 Forgejo Actions,或由贡献者本地执行时才会真正构建。CI 会执行的就是上面这四条命令,外加各平台的 `pnpm tauri build`;Linux 安装包可在普通 Docker 主机上用 `scripts/linux/Dockerfile` 构建。
|
||||
|
||||
**欢迎二次开发。** 你可以免费使用、修改、再发布本代码,也可用于商业项目,只需保留原版权声明与 LICENSE 文件。
|
||||
|
||||
|
|
|
|||
|
|
@ -40,14 +40,23 @@ Windows artefacts without a Windows host:
|
|||
|
||||
```bash
|
||||
brew install makensis
|
||||
scripts/build-windows-release.sh # add --skip-build to reuse the EXE
|
||||
scripts/build-windows-release.sh # both architectures
|
||||
scripts/build-windows-release.sh --arch arm64 # one of them
|
||||
scripts/build-windows-release.sh --skip-build # repackage the EXEs already built
|
||||
```
|
||||
|
||||
It writes `artifacts/Shift-Setup-<version>-win-x64.exe` (NSIS, per-user, no
|
||||
administrator rights), `artifacts/Shift-Portable-<version>-win-x64.zip` and
|
||||
refreshes `artifacts/SHA256SUMS.txt`. `scripts/windows-installer.nsi` installs
|
||||
into `%LOCALAPPDATA%\Programs\Shift`, and its uninstaller only removes what the
|
||||
installer wrote.
|
||||
For each architecture asked for it writes
|
||||
`artifacts/Shift-Setup-<version>-win-<arch>.exe` (NSIS, per-user, no administrator
|
||||
rights) and `artifacts/Shift-Portable-<version>-win-<arch>.zip`, then refreshes
|
||||
`artifacts/SHA256SUMS.txt`. Before packaging an EXE the script checks its PE machine
|
||||
field — `0x8664` for x64, `0xAA64` for ARM64 — so a binary built for the wrong target
|
||||
cannot end up in the wrong package, and each installer refuses a machine of the other
|
||||
architecture. `scripts/windows-installer.nsi` installs into
|
||||
`%LOCALAPPDATA%\Programs\Shift`, and its uninstaller only removes what the installer
|
||||
wrote.
|
||||
|
||||
The ARM64 build is cross-compiled and packaged from macOS, but it has not been run on
|
||||
Windows-on-ARM hardware, so treat it as unverified on the device.
|
||||
|
||||
## Runtime behavior
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,265 @@
|
|||
# Shift for iOS and Android
|
||||
|
||||
Planning document. It answers one question: which parts of Shift's desktop design survive
|
||||
translation to a phone, and how the two ends share ground. Decisions are recorded as
|
||||
decisions, with the reason, so a later reader knows what was considered and rejected.
|
||||
|
||||
## What Shift actually is
|
||||
|
||||
Strip the desktop chrome and Shift is four things:
|
||||
|
||||
1. A **gesture** that opens a capability menu attached to a file, not to a window.
|
||||
2. A **catalogue** of what each file type can become, matched to what is really installed
|
||||
to do the work.
|
||||
3. **Local processing** — convert, compress, redact, OCR, extract — with no upload.
|
||||
4. A **hand-off** path: the result lands next to the source, in a history library, or on
|
||||
another machine on the LAN.
|
||||
|
||||
All four translate. The desktop UI does not: a 760 px radial ring around a cursor has no
|
||||
mobile equivalent, and neither does "hold Shift while dragging in Finder".
|
||||
|
||||
## The one feature worth copying
|
||||
|
||||
**Share-drag is the feature.** Everything else on desktop is either table stakes
|
||||
(convert, crop, compress) or platform-specific (menu bar, global hotkeys). The thing users
|
||||
remember is that a capability menu appears *while you are already moving a file*, so the
|
||||
action is part of the gesture instead of a place you navigate to.
|
||||
|
||||
iOS and Android both have exactly one gesture with that shape, and it is the one users
|
||||
already perform every day:
|
||||
|
||||
| Desktop | iOS | Android |
|
||||
| --- | --- | --- |
|
||||
| Shift-drag out of the Finder row, release over a wedge | **Share sheet**, including the drag-and-drop share from Files/Photos/Safari where the picker slides out from under the finger | **Share sheet**, same shape, from any app |
|
||||
| Radial ring of wedges | The share sheet's own app list, plus a Share Extension whose UI we own | Share sheet targets, plus an Action/Share Activity we own |
|
||||
| Ring reorder in Settings | Share sheet "Edit Actions" ordering, mirrored in our Settings | Same, mirrored |
|
||||
|
||||
So the mobile pitch is not "Shift in your pocket", it is: **release a share over a Shift
|
||||
action**. Concretely: long-press an image in Files → Share → Shift → *HEIC → PNG, then
|
||||
redact*, and the file comes back where it went out from. Same mental model, native
|
||||
gesture, no invented interaction.
|
||||
|
||||
Two more mobile entry points carry the same idea cheaply:
|
||||
|
||||
- **Quick Action / home-screen shortcuts** (long-press the app icon): "Capture + convert",
|
||||
"Scan text", "Compress". The iOS Action Button and Android's app shortcuts give the
|
||||
"one gesture away" promise better than any menu.
|
||||
- **Share Extension from other apps** is the only sanctioned way in on both platforms;
|
||||
neither lets a third party overlay an arbitrary app's window the way the macOS drag
|
||||
bridge does. Do not plan a mobile equivalent of the global drag bridge — it does not
|
||||
exist, and an app that behaves like a system overlay gets rejected or uninstalled
|
||||
within a day.
|
||||
|
||||
## Ecosystem surfaces
|
||||
|
||||
"Hook into the OS ecosystem" on mobile means a short list of sanctioned doors. Each one is
|
||||
an entry point with a different activation rule, and each costs one well-scoped UI. Nothing
|
||||
here needs an account, a server, or a background service that fights the OS.
|
||||
|
||||
| Surface | iOS | Android | What it buys |
|
||||
| --- | --- | --- | --- |
|
||||
| Files in, other apps out | Share Extension (`com.apple.share-services`, activation rule on images/PDF/office types) | `ACTION_SEND` / `ACTION_SEND_MULTIPLE` intent filter | The core loop: any app's Share button reaches Shift |
|
||||
| Files as a place | File Provider extension so Shift's history library appears in the Files app sidebar | `DocumentsProvider` exposing the same library | Shift's outputs are reachable *and* openable from outside, not trapped in a sandbox |
|
||||
| Open a type | `CFBundleDocumentTypes` + UTType declarations (`public.image`, `com.adobe.pdf`, `org.openxmlformats...`) | `ACTION_VIEW` filters per MIME type | "Open with Shift" from mail, chat, and browser downloads |
|
||||
| Write a type back | `ACTION_CREATE_DOCUMENT` equivalent: iOS document-based launch + "Save on iPhone" | `ACTION_CREATE_DOCUMENT` / `ACTION_GET_CONTENT` response | Shift can be the *saving* app, so it can hand a converted file back to whatever asked |
|
||||
| One-tap entry | Home-screen Quick Actions, Action Button, App Intents (iOS 16+) so Shortcuts can call "Convert", "Redact", "Scan text" | Launcher long-press shortcuts, Quick Settings tile, Assistant/`app_functions.xml` | The "one gesture away" promise without a global hotkey, and other apps can compose Shift |
|
||||
| Hand-off out | `NSItemProvider` with a `fileURL`, plus AirDrop, Save to Photos, Copy | `ClipData` `FILE_URI` through a `FileProvider` grant, temp-read permission | The result returns where it came from, which is the desktop behaviour that matters |
|
||||
| Widgets | WidgetKit: one widget for "last capture → redact/share", one for history | Glance/App widget + notification with a Copy/Send action | Value without opening the app |
|
||||
| Cross-machine | `NSLocalNetworkUsageDescription` + `_shift._tcp` Bonjour browse/register | `ACCESS_NETWORK_STATE`, `CHANGE_WIFI_MULTICAST_STATE` lock while discovering, NSD | The LAN Send path, described in the next section |
|
||||
|
||||
Two rules keep this from sprawling. First, **every surface ships with a job list, not a
|
||||
window**: the share extension opens, does the work, and returns to the caller; the widget
|
||||
taps deep-link into the library. Second, **no surface may require a persistent background
|
||||
service**. iOS will kill one and Android's battery optimisers will throttle it, and a Shift
|
||||
that silently stopped receiving is worse than one that never claimed to.
|
||||
|
||||
### Making the two ends actually meet
|
||||
|
||||
Discovery is the part that breaks between ecosystems, so it gets explicit answers:
|
||||
|
||||
- **Same-LAN discovery.** Desktop already beacons UDP multicast to `239.255.77.88:47888`
|
||||
with broadcast and unicast fallbacks. Phones keep that as a fallback but lead with
|
||||
Bonjour/mDNS on iOS and NSD on Android, because both give a wake-up that survives
|
||||
doze and neither needs a multicast lock held hostage. The desktop registers `_shift._tcp`
|
||||
alongside the existing beacon, so a phone finds it by name instead of guessing.
|
||||
- **First contact is a pairing code, not a prompt.** A phone joining a network with five
|
||||
desktops needs to pick one. The desktop shows a short code and the phone types it (or
|
||||
scans a QR encoding host, port, and code); the desktop then pins that phone's identity
|
||||
the way SSH does. This removes the "who is `Desktop-2.local`?" problem and gives the
|
||||
consent card something to vouch for.
|
||||
- **Background receiving is asymmetric, and stays that way.** iOS gives a socket a few
|
||||
seconds of life, so a phone is a first-class sender and a *wake-to-receive* peer: a push
|
||||
or a tap opens the app, which then pulls the queued job. Desktop-to-phone therefore
|
||||
behaves like a pull: the desktop queues, the phone collects. Saying so beats shipping a
|
||||
receiver that drops files at random.
|
||||
- **No cloud relay, still.** The pairing code is what makes a *user-run* hub workable if a
|
||||
remote case ever appears — one desktop as the hub, the phone dialling it — without
|
||||
inventing a hosted service, accounts, or a retention policy.
|
||||
|
||||
## Capability map
|
||||
|
||||
Legend: **Native** = OS API, do not reimplement. **Port** = existing Shift logic moves
|
||||
with little change. **Substitute** = the desktop mechanism is unavailable, use the listed
|
||||
replacement. **Skip** = no mobile answer that fits the product.
|
||||
|
||||
| Desktop capability | Mobile | Mechanism |
|
||||
| --- | --- | --- |
|
||||
| Radial ring | Substitute | Share-sheet extension with its own ring-style picker; the wedge catalogue is shared code, the geometry is a phone-sized arc |
|
||||
| Ring catalogue + custom order | Port | `src/lib/radialOrder.ts` is pure TypeScript with no Tauri import; reuse it verbatim, persist orders in app group / `SharedPreferences` |
|
||||
| Format catalogue (`conversionFormats`) | Port | Pure TS, same table; prune per platform at build time where a codec is absent |
|
||||
| Image convert (PNG/JPG/WebP/TIFF/BMP/GIF) | Port | Keep the Rust `image` crate — it builds for `aarch64-apple-ios` and `aarch64-linux-android`; or substitute `ImageIO`/`ImageDecoder` |
|
||||
| HEIC decode/encode | Native | `ImageIO` on iOS, HEIF support in Android's decoder (API 28+); desktop's `sips`/ImageMagick has no mobile role |
|
||||
| Image pixel tools (rotate, flip, B&W, 50%, crop, compress) | Port | Same math. On desktop these now decode HEIC/AVIF through `open_for_pixels`, which shells out to `sips`/ImageMagick; that function is the one thing in the path to replace, and both mobile platforms decode those formats natively, so the mobile core needs an injected decoder rather than a subprocess |
|
||||
| Video/audio convert, compress, 720p, mute, extract audio, mono, frame | Native | `AVFoundation` on iOS, `Media3`/`MediaCodec` on Android; `mobile-ffmpeg`-style bundled FFmpeg works but costs 15–25 MB and licence review for GPL builds — decide per platform, not globally |
|
||||
| Video GIF | Native + port | Frame sampling natively, palette-quantise in Rust (desktop already caps GIF at 15 s / 12 fps / 480 px / 8 MB — keep those caps, phones care more) |
|
||||
| PDF text, split, merge, rotate | Port | `lopdf` is pure Rust; or native `PDFKit`/`PdfRenderer` for page images |
|
||||
| PDF → images | Native | `PDFKit` (iOS), `PdfRenderer` (Android) — replaces PDFKit-sidecar/Poppler |
|
||||
| PDF → DOCX | Substitute | Native page render + the existing pure-Rust DOCX packager; the macOS AppKit renderer has no mobile twin |
|
||||
| PPTX / XLSX / CSV → Markdown | Port | `calamine` + `quick-xml`, pure Rust, no platform dependency. Highest value-to-effort item on the list |
|
||||
| Document → PDF | Substitute | iOS: `UIPrintRenderer`/`UIMarkupTextPrintFormatter`; Android: `PdfRenderer`/WebView print. Neither matches the AppKit renderer's fidelity; say so in the UI |
|
||||
| Annotate: rectangle, arrow, text, highlight, number | Port | The canvas model is React/TS; a mobile build reuses it, though native `PencilKit` is better for finger/stylus |
|
||||
| Annotate: redact, pixelate, blur, stamps | Port | Same drawing primitives; redaction stays "burned in", which is the whole point |
|
||||
| Cutout (corner-sample keying) | Port | Works, but iOS `VNGeneratePersonSegmentationRequest` / Android segmenter are dramatically better — substitute where available |
|
||||
| OCR EN + ZH | Native | **Drop Tesseract WASM on mobile.** `Vision` (`VNRecognizeTextRequest`, `.enUS`+`.zh-Hans`) and ML Kit Text Recognition v2 are faster, smaller and better on-device engines. Keep Tesseract only if one shared engine matters more than quality |
|
||||
| Screen capture | Native | iOS `ReplayKit` (broadcast or one-shot, user-initiated); Android MediaProjection, plus the built-in screenshot + `MediaStore` observer |
|
||||
| Screen recording | Native | `ReplayKit` / MediaProjection; frame-rate honesty (`capabilities()`) carries straight over — mobile has the same "backend ignores this" problem |
|
||||
| Result card (Copy / Pin / Send / Reveal / Edit) | Substitute | No floating always-on-top windows. iOS: the Share-sheet extension's own completion UI + Live Activity where useful; Android: a floating service (easy) and a Quick Settings tile |
|
||||
| History library | Port | `history.rs` logic (capacity, pinning, missing files) is portable; storage becomes the app group container / scoped storage. Search + pin behave identically |
|
||||
| Drag a row out | Native | `NSItemProvider` with `fileURL` on iOS, `ClipData` `FILE_URI` + `FileProvider` on Android — same intent as `text/uri-list` with a `file://` entry |
|
||||
| Pin to screen | Substitute | Android: floating overlay window. iOS: no API — pinned images become a Widget or nothing |
|
||||
| Menu bar / tray | Substitute | iOS: Menu Bar Extra is not a thing; share sheet + Shortcuts actions. Android: Quick Settings tile, launcher icon long-press |
|
||||
| Global hotkeys | Skip | Do not request Accessibility for a keyboard shortcut. Offer App Intents (iOS 16+) / Quick Settings tile + Assistant shortcuts |
|
||||
| Launch at login | Skip | Meaningless on mobile |
|
||||
| LAN Send (SHSF beacons + TCP) | Port | UDP multicast + direct TCP work on both platforms; needs `NSLocalNetworkUsageDescription` + Bonjour on iOS (the privacy prompt is unavoidable) and `ACCESS_NETWORK_STATE`/multicast lock on Android. Background reception is unreliable on iOS, so treat mobile as a first-class *sender* and a best-effort receiver |
|
||||
| Update channel on git | Skip | Store review is the only permitted update path for executable code. Keep the SHA256 discipline for *content* (models, catalogues), not for the binary |
|
||||
| Runtime components panel | Substitute | Nothing is installable. Show "detected codecs" read-only, or drop it; do not fake a desktop panel |
|
||||
| i18n en/zh | Port | The two message tables are data; move them as-is |
|
||||
|
||||
## Architecture for two ecosystems
|
||||
|
||||
The claim that the core is portable was checked rather than assumed, against this
|
||||
repository as it stands:
|
||||
|
||||
- `cargo metadata --no-deps` reports one workspace package, `shift`. Nothing is separable
|
||||
yet, so step zero is a real refactor, not a packaging detail.
|
||||
- `src-tauri/src/pdf.rs` and `src-tauri/src/office.rs` contain **zero** references to
|
||||
`tauri::` or `AppHandle`. Their functions already take `&Path` and return
|
||||
`Result<PathBuf, String>`, which is exactly the shape a C header wraps. They move
|
||||
essentially unchanged.
|
||||
- `src-tauri/src/files.rs` is 2,761 lines with 11 `#[tauri::command]` wrappers, and 28 of
|
||||
its lines mention `tauri::` or `AppHandle`. The wrappers are thin — the workers beneath
|
||||
them already take `&Path` and an `output_dir: Option<&Path>` — but the settings lookups
|
||||
inside the command layer (`files_output_dir`, `auto_reveal`) have to become parameters,
|
||||
and the `history::record` call each command makes after a write becomes a callback.
|
||||
- The dependency closure of `image`, `lopdf`, `printpdf`, `calamine`, `quick-xml`, `zip`,
|
||||
`sha2`, `ed25519-dalek`, `base64`, `serde` and `serde_json` is 161 crates, and not one of
|
||||
them needs a C compiler: the only system-flavoured members are `libc`, `windows-sys`,
|
||||
`adler2` and `miniz_oxide`, all of which build for iOS and Android. There is no AV1 or
|
||||
HEVC encoder in the tree, which is why HEIC and video stay native on mobile.
|
||||
|
||||
So the core is genuinely the leverage: `image`, `lopdf`, `printpdf`, `calamine`,
|
||||
`quick-xml`, `zip`, `sha2` cross-compile to `aarch64-apple-ios`, `aarch64-apple-ios-sim`
|
||||
and `aarch64-linux-android`. Put the conversion pipeline, the wedge catalogue, the PDF and
|
||||
Office readers, and the SHSF protocol in a Rust static library and let both platforms call
|
||||
it; that is where most of the value is, and it is the part with no platform API in it.
|
||||
|
||||
```text
|
||||
shared/
|
||||
├─ shift-core (Rust staticlib + C header)
|
||||
│ ├─ convert / compress / pixel tools / pdf / office ← from src-tauri/src/files.rs, pdf.rs, office.rs
|
||||
│ ├─ catalogue ← from src/lib/radialOrder.ts + conversionFormats.ts (generated or mirrored)
|
||||
│ └─ shsf ← from src-tauri/src/share.rs
|
||||
├─ ios/ Swift UI + Share Extension + App Intents, links shift-core
|
||||
└─ android/ Kotlin UI + Share Activity + Tile, JNI to shift-core
|
||||
```
|
||||
|
||||
Step zero, before any UI: split the workspace into `shift-core` (the pure functions above,
|
||||
plus a decoder trait standing in for `open_for_pixels`), a `shift-ffi` staticlib over it,
|
||||
and the existing Tauri app consuming `shift-core`. The desktop then exercises the same code
|
||||
the phones ship, which is the only thing that keeps three platforms from drifting. That
|
||||
split is verifiable on desktop alone — `cargo test --lib` keeps passing while the pure
|
||||
functions move out from under the command layer.
|
||||
|
||||
Two consequences worth deciding early:
|
||||
|
||||
- **The wedge catalogue should stop being TypeScript-only.** It is currently the source of
|
||||
truth for the desktop ring. Either generate the mobile lists from it, or move it into
|
||||
`shift-core` and have the desktop read it. Do not maintain three hand-written copies.
|
||||
- **Tauri does not run on iOS/Android usefully here.** Tauri v2 can target mobile, but the
|
||||
product is a share-sheet extension, which is a small native UI, not a webview app. Plan
|
||||
a native shell around the Rust core; keep the desktop's React UI on desktop.
|
||||
|
||||
## What mobile must send to desktop
|
||||
|
||||
Cross-ecosystem hand-off is the feature that justifies a mobile app at all. The current
|
||||
`SHSF` frame is: four magic bytes `SHSF`, a big-endian `u32` header length, a JSON header
|
||||
(`fileName`, `size`, `peerName`, `transferId`, `batchId`, `batchIndex`, `batchTotal`), the
|
||||
raw file bytes, then a one-byte accept decision. Notably **there is no version field** —
|
||||
compatibility today comes from `#[serde(default)]` letting a newer reader accept an older
|
||||
header. That is enough for two desktop revisions and not enough once a phone app is out in
|
||||
the wild and cannot be force-updated.
|
||||
|
||||
Before the first mobile release, freeze the protocol:
|
||||
|
||||
```text
|
||||
"SHSF" | version:u8 = 1 | headerLen:u32 | header:JSON | payload | decision:u8
|
||||
```
|
||||
|
||||
Plus, in the header: `platform`, `appVersion`, `kind` ("file" | "job"), and for jobs
|
||||
`action` + `args`. Everything else the mobile app needs is a job it can describe:
|
||||
|
||||
1. **Phone → desktop, direct.** LAN transfer, receiver stores to its output folder, both
|
||||
histories update. This is Send with a phone as a peer. Small change: the peer beacon
|
||||
needs a `kind` so a phone does not look like a desktop, and the consent card needs to
|
||||
say "iPhone sent this".
|
||||
2. **Phone → desktop as a job.** A phone encodes 4K video or a 900-page PDF poorly. Send
|
||||
the file plus a requested action, the desktop runs it in the existing job pipeline
|
||||
(`perform_file_action` already reports progress and writes conflict-safe names), and the
|
||||
result comes back. The desktop queue already exists; the phone needs a second, smaller
|
||||
queue that only shows status.
|
||||
3. **Desktop → phone.** Symmetric; a phone receiving a file is one `URLSession`/`OkHttp`
|
||||
upload to the desktop's existing receive port.
|
||||
|
||||
Deliberately **not** part of the plan: a cloud relay. Shift's whole claim is that nothing
|
||||
leaves the machine, and a relay would need authentication, retention limits, and a privacy
|
||||
policy for a feature that works fine over the LAN. If a remote case ever demands it, the
|
||||
right shape is user-run (one desktop is the hub, the phone dials it with a pairing code),
|
||||
not a hosted service.
|
||||
|
||||
The privacy posture carries over unchanged: no telemetry, no analytics SDK, no crash
|
||||
reporter that uploads file content. On iOS that also means the local-network permission
|
||||
string and a Bonjour service type in `Info.plist` — write them before the first submission,
|
||||
because the denial is silent and the feature looks broken.
|
||||
|
||||
## Build order
|
||||
|
||||
Each step ships something usable on its own; none depends on a feature Shift lacks today.
|
||||
|
||||
0. **Extract `shift-core` on desktop.** Move the pure conversion, PDF and Office code out
|
||||
from under the Tauri command layer and add the `staticlib` target. Ships nothing new to
|
||||
users, and it is the step that can be finished and verified without an Apple developer
|
||||
account or an Android SDK: `cargo test --lib` keeps passing the whole way, and the tests
|
||||
that follow the functions prove the boundary is real.
|
||||
1. **iOS share-sheet converter for images.** `shift-core` + the ported catalogue + a
|
||||
ring-style picker. No networking, no capture, no accounts. Proves the gesture.
|
||||
2. **Android share-sheet converter.** Same core, same catalogue; the second platform is
|
||||
the test that the abstraction is real rather than iOS-shaped.
|
||||
3. **PDF and Office text extraction.** Pure-Rust ports, no platform APIs, high perceived
|
||||
value ("turn this deck into Markdown on my phone").
|
||||
4. **Native OCR (Vision / ML Kit) + annotation.** Redact first — it is the mobile-native
|
||||
killer use (screenshot → redact → share, all on device).
|
||||
5. **LAN peer + phone→desktop jobs.** Add the version byte and the `kind` field to SHSF
|
||||
here, in the same release as the first phone that speaks it.
|
||||
6. **Capture on mobile, last.** ReplayKit/MediaProjection is real work, mobile screenshots
|
||||
are already excellent, and the desktop capture loop is the least portable thing in the
|
||||
product. Do it when users ask for it rather than for parity.
|
||||
|
||||
## Open decisions
|
||||
|
||||
| Question | Leaning | Why |
|
||||
| --- | --- | --- |
|
||||
| Tauri mobile or native shell | Native shell + Rust core | Share extensions are small native UIs; a webview adds size and latency to the one interaction that must feel instant |
|
||||
| One FFmpeg binary per platform | iOS: no, Android: measure | `AVFoundation` covers most mobile media needs at zero licence risk; Android's codecs are as capable but the surface is fragmented |
|
||||
| Shared OCR engine or native | Native | Vision and ML Kit beat Tesseract WASM on speed and Chinese accuracy; a shared engine buys nothing users can see |
|
||||
| Catalogue home | `shift-core` | Desktop can read from it; phones and desktop cannot drift apart |
|
||||
| Priced app to fund it | Undecided | The desktop app is MIT and free; a paid mobile app is defensible but changes the project's centre of gravity |
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
# Releases and updates
|
||||
|
||||
Shift's update channel is this repository. There is no update server, no object
|
||||
storage, and no release service to configure: the installers and a small manifest are
|
||||
pushed to a git branch, and a running copy reads that branch over HTTPS.
|
||||
|
||||
## The channel
|
||||
|
||||
An orphan branch named `releases` holds exactly one release:
|
||||
|
||||
```text
|
||||
releases/
|
||||
├── shift-update.json
|
||||
├── shift-update.sig
|
||||
├── Shift-macOS-universal.dmg
|
||||
└── Shift-Setup-0.1.1-win-x64.exe
|
||||
```
|
||||
|
||||
`shift-update.json` names the version and, per platform, the artifact file, its size in
|
||||
bytes and its SHA256:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.1",
|
||||
"date": "2026-10-26",
|
||||
"notes": "",
|
||||
"artifacts": {
|
||||
"macos": { "file": "Shift-macOS-universal.dmg", "sha256": "57fc…", "size": 55479751 },
|
||||
"windows": { "file": "Shift-Setup-0.1.1-win-x64.exe", "sha256": "0255…", "size": 24545040 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Supported release targets
|
||||
|
||||
**Shift ships two installers: macOS (universal) and Windows x64.** That is a scope decision,
|
||||
not a code limit, and it decides what the channel may contain:
|
||||
|
||||
| Key | Shipped | Notes |
|
||||
| --- | --- | --- |
|
||||
| `macos` | yes | One universal bundle, Apple silicon and Intel |
|
||||
| `windows` | yes | x64, which is also what an ARM machine falls back to |
|
||||
| `windows-arm64` | no | Buildable — `build-windows-release.sh --arch arm64` still works — just not published |
|
||||
| `linux` | no | Build target, not a product; see below |
|
||||
|
||||
Publishing an ARM64 Windows build later needs no code change: the ladder already prefers
|
||||
`windows-arm64` and falls back to `windows`, so adding the file to `artifacts/` and
|
||||
re-publishing is enough.
|
||||
|
||||
Keys are platform, then platform and architecture where they differ. A build picks the
|
||||
first key its own architecture matches and never crosses operating systems:
|
||||
|
||||
| Running on | Keys tried, in order |
|
||||
| --- | --- |
|
||||
| macOS (Apple silicon or Intel) | `macos` |
|
||||
| Windows x64 | `windows` |
|
||||
| Windows ARM64 | `windows-arm64`, then `windows` |
|
||||
| Linux | `linux` |
|
||||
|
||||
The ARM64 fallback to `windows` is deliberate: Windows on ARM runs x64 binaries under
|
||||
emulation, so a channel that only carries x64 keeps serving ARM machines exactly as it did
|
||||
before the ARM build existed. `artifact_keys_for` and `select_artifact` in
|
||||
`src-tauri/src/update.rs` hold that ladder and are tested directly, so the rule is fixed
|
||||
by a test rather than by a comment.
|
||||
|
||||
The branch is rebuilt as a fresh root commit on every publish and force-pushed, so it
|
||||
never accumulates gigabytes of installer history while `main` stays clean.
|
||||
|
||||
## Publishing
|
||||
|
||||
```bash
|
||||
pnpm tauri build … # bundles land in artifacts/
|
||||
printf 'Fixes the ring on external displays.\n' > /tmp/notes.md
|
||||
scripts/publish-release.sh --notes /tmp/notes.md # hash, commit, push
|
||||
```
|
||||
|
||||
`scripts/publish-release.sh` hashes every file in `artifacts/`, builds the manifest,
|
||||
writes the tree with git plumbing (`update-index` → `write-tree` → `commit-tree` →
|
||||
`update-ref`, through a temporary `GIT_INDEX_FILE` so the working tree is untouched) and
|
||||
force-pushes `releases`. The manifest and the pushed bytes cannot disagree, because the
|
||||
same Python pass that walks the files produces both.
|
||||
|
||||
| Flag | Effect |
|
||||
| --- | --- |
|
||||
| `--notes FILE` | Release notes shown in the Updates panel |
|
||||
| `--key FILE` | Sign the manifest with this ed25519 key (`SHIFT_RELEASE_KEY` also works) |
|
||||
| `--dry-run` | Print the manifest and the tree that would be pushed; write nothing |
|
||||
| `--no-push` | Commit locally on `releases` but leave the remote alone |
|
||||
| `--branch NAME` | Publish to another channel instead of `releases` |
|
||||
|
||||
Recognised installers: `Shift-macOS-universal.dmg` (macOS), `Shift-Setup-<version>-win-x64.exe`
|
||||
and `Shift-Setup-<version>-win-arm64.exe` (Windows, keys `windows` and `windows-arm64`),
|
||||
`*.AppImage` / `*.deb` (Linux). Other files in `artifacts/` — the portable ZIPs,
|
||||
`SHA256SUMS.txt`, the `README-Windows-<arch>.txt` notes — travel with the branch but are
|
||||
not offered as installers. Dotfiles and an old manifest are skipped.
|
||||
|
||||
Both Windows architectures come from one command, which cross-compiles each target,
|
||||
checks the PE machine field of the binary it just built (`0x8664` for x64, `0xAA64` for
|
||||
ARM64) so a wrong `--target` cannot ship an x64 EXE inside an arm64 package, and gates the
|
||||
installer to the matching machine:
|
||||
|
||||
```bash
|
||||
scripts/build-windows-release.sh # both architectures
|
||||
scripts/build-windows-release.sh --arch arm64 # one of them
|
||||
scripts/build-windows-release.sh --skip-build # repackage existing EXEs
|
||||
```
|
||||
|
||||
## Signing the channel
|
||||
|
||||
Integrity says the download matches the manifest; authenticity says the manifest came
|
||||
from you. `scripts/release-key.py` closes that gap with one ed25519 key.
|
||||
|
||||
```bash
|
||||
scripts/release-key.py keygen ~/.config/shift-release/release.ed25519
|
||||
# -> prints the hex public key to bake into the build
|
||||
|
||||
export SHIFT_RELEASE_KEY=~/.config/shift-release/release.ed25519
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg # macOS
|
||||
scripts/build-windows-release.sh # both Windows architectures
|
||||
scripts/publish-release.sh --key "$SHIFT_RELEASE_KEY"
|
||||
```
|
||||
|
||||
Give the release build `SHIFT_UPDATE_PUBKEY` (the hex key) and it can verify the feed; give
|
||||
it `SHIFT_RELEASE_KEY` (the private key) and `build-windows-release.sh` derives the public
|
||||
key from it, so a cross-build can never be packaged with a key that does not match the
|
||||
signature `publish-release.sh --key` produces. Without either, the script prints
|
||||
`no release key: this build will report the feed as unsigned` rather than letting it pass
|
||||
for a quieter log.
|
||||
|
||||
The signature is **detached**: `shift-update.sig` holds base64 over the manifest's exact
|
||||
bytes, so verification needs no JSON canonicalisation rules and the manifest's formatting
|
||||
stays free to change. It is fetched from the directory that already holds the manifest, so
|
||||
a staging feed needs only its own manifest plus signature — a fork never configures a
|
||||
second URL.
|
||||
|
||||
| Build | Feed | Result |
|
||||
| --- | --- | --- |
|
||||
| Key baked | signature verifies | update offered, panel says the signature was verified |
|
||||
| Key baked | signature missing or wrong | check fails with that reason; nothing is offered |
|
||||
| No key | any | integrity gate only; panel says this build cannot verify a signature |
|
||||
|
||||
The key is the one secret in this design. Losing it means publishing a new app build with
|
||||
a new baked key; leaking it means an attacker can publish anything to the channel, exactly
|
||||
as leaking push access to `releases` already does today. Keep it outside the repository —
|
||||
`~/.config/shift-release/` is where the local publishing machine keeps it.
|
||||
|
||||
## Where a build looks for updates
|
||||
|
||||
`src-tauri/build.rs` derives the feed from the `origin` remote at build time:
|
||||
|
||||
| Remote | Feed URL |
|
||||
| --- | --- |
|
||||
| Gitea / Forgejo | `https://host/owner/repo/raw/branch/releases/shift-update.json` |
|
||||
| GitHub | `https://github.com/owner/repo/raw/releases/shift-update.json` |
|
||||
| GitLab | `https://gitlab.example/owner/repo/-/raw/releases/shift-update.json` |
|
||||
|
||||
Two overrides exist, and neither needs a rebuild of the frontend:
|
||||
|
||||
- `SHIFT_UPDATE_PUBKEY` at build time bakes in the release key; anything that is not 32
|
||||
bytes of hex fails the build rather than silently producing an updater that trusts the
|
||||
feed anyway. A key that parses but is not a curve point is a runtime error, never a
|
||||
quiet downgrade to "no key".
|
||||
- `SHIFT_UPDATE_URL` at build time bakes a different feed into the binary.
|
||||
- `SHIFT_UPDATE_URL` in the environment of a running copy wins over the baked value,
|
||||
which is how a fork or a staging branch is tested.
|
||||
|
||||
A source tree with no remote builds an updater that reports "no feed" rather than
|
||||
guessing at one.
|
||||
|
||||
## What the app does with it
|
||||
|
||||
1. Once a day, at startup (and on demand from Settings → **Updates**), the manifest is
|
||||
fetched with the system HTTP client — `/usr/bin/curl` on macOS and Linux,
|
||||
`Invoke-WebRequest` on Windows. The day of the last probe is stored in `settings.json`,
|
||||
so restarts cannot spend the day's check twice.
|
||||
2. Versions are compared with semver rules, prereleases included: `0.2.0-alpha` sorts
|
||||
below `0.2.0`, so a test build does not offer to downgrade itself.
|
||||
3. Download writes into a temp folder, then two gates run before anything can be
|
||||
installed: the byte length must equal the manifest's `size`, and the recomputed SHA256
|
||||
must equal the manifest's `sha256`. A mismatch deletes the file and reports the error,
|
||||
so a truncated or swapped installer never reaches the installer step.
|
||||
4. **Install** runs the verified artifact; **Discard** removes it. When an update is
|
||||
available the tray menu gains a row that opens Settings on the Updates tab.
|
||||
|
||||
Manifest `schema` is checked, and a newer schema than this build understands is refused
|
||||
instead of being parsed optimistically. Unknown platform keys are ignored, so the
|
||||
manifest can name a platform an older app has never heard of. The Updates panel always
|
||||
states which of the two properties the current feed satisfies, so an unsigned channel
|
||||
never looks signed.
|
||||
|
||||
## Trust boundary
|
||||
|
||||
Two properties, two mechanisms:
|
||||
|
||||
- **Integrity of the installer** — byte length plus recomputed SHA256 against the
|
||||
manifest. Always enforced, in every build.
|
||||
- **Authenticity of the manifest** — a detached ed25519 signature verified against a baked
|
||||
public key. Enforced in every build that was compiled with `SHIFT_UPDATE_PUBKEY`.
|
||||
|
||||
A build without a key falls back to the weaker trust it had before signing existed: the
|
||||
HTTPS connection to the forge plus whoever can push to `releases`. That is the only
|
||||
remaining gap for such a build, and the panel says so out loud. Developer ID signing plus
|
||||
notarization for the macOS package — which macOS requires for downloaded apps regardless —
|
||||
is still open and tracked in `docs/ROADMAP.md` under M5.
|
||||
|
||||
```bash
|
||||
scripts/release-key.py verify ~/.config/shift-release/release.pub \
|
||||
manifest.json manifest.sig # check a channel by hand
|
||||
```
|
||||
|
||||
## Verifying a channel by hand
|
||||
|
||||
```bash
|
||||
SHIFT_UPDATE_URL="https://host/owner/repo/raw/branch/releases/shift-update.json" \
|
||||
cargo test --lib update:: -- --ignored # from src-tauri/
|
||||
```
|
||||
|
||||
```bash
|
||||
cargo test --lib update:: -- --ignored # unsigned build: integrity only
|
||||
SHIFT_UPDATE_PUBKEY=<hex> cargo test --lib update:: -- --ignored
|
||||
```
|
||||
|
||||
The test fetches the real feed, checks the manifest signature when the build carries a
|
||||
key, then downloads the artifact for this platform and architecture and checks size and
|
||||
hash against what is on disk. A baked key that is valid but not the publisher's fails the
|
||||
test, which is the proof that the check is real and not a pass-through.
|
||||
|
||||
## State of the published channel
|
||||
|
||||
Checked against the live `releases` branch of this repository:
|
||||
|
||||
Version **0.1.1**, checked by downloading each artifact back from the raw endpoint rather
|
||||
than trusting the local copy:
|
||||
|
||||
| Key | Artifact | Verified from the remote |
|
||||
| --- | --- | --- |
|
||||
| `macos` | `Shift-macOS-universal.dmg` (55,479,751 B) | bytes downloaded, SHA256 matches the manifest |
|
||||
| `windows` | `Shift-Setup-0.1.1-win-x64.exe` (24,545,040 B) | bytes downloaded, SHA256 matches the manifest |
|
||||
| `windows-arm64` | not published | by choice — see "Supported release targets" |
|
||||
| `linux` | not published | by choice: Linux is a build target here, not a shipped product |
|
||||
|
||||
`shift-update.sig` verifies over the manifest's exact bytes against the key baked into both
|
||||
artifacts. The channel's home is derived from `origin` at build time, and this forge is
|
||||
Gitea, so the raw form is `/raw/branch/releases/`.
|
||||
|
||||
Both artifacts carry the key and the feed URL, which is what makes an in-app upgrade
|
||||
possible at all: a build whose binary predates those constants reports "this build has no
|
||||
feed" and can never see the channel, however new it is.
|
||||
|
||||
The forge runs **no Actions**, so nothing on this list was built by CI: every artifact was
|
||||
cross-compiled on one macOS host and pushed with `scripts/publish-release.sh`. Treat "pass
|
||||
CI" in the contributing guide as a definition to run locally, not a gate that already ran.
|
||||
|
||||
A Linux release would slot in under the `linux` key with no code change — `artifact_keys_for`
|
||||
already answers `linux` for that host — so publishing one is a build task, not a feature.
|
||||
179
docs/ROADMAP.md
179
docs/ROADMAP.md
|
|
@ -1,6 +1,10 @@
|
|||
# Shift Roadmap
|
||||
|
||||
## M1: Foundation
|
||||
Statuses describe this repository as it stands, not intentions. `Done` means the
|
||||
feature exists and is covered by the test suite or a verified manual run; `Partial`
|
||||
names what is still missing.
|
||||
|
||||
## M1: Foundation — done
|
||||
|
||||
- Tangerine radial menu and transition between format/tool rings.
|
||||
- Global Shift-drag bridge on macOS.
|
||||
|
|
@ -9,32 +13,165 @@
|
|||
- Shared English/Chinese UI and tray app.
|
||||
- Launch at login and a master enable switch for the drag rings, both in Settings.
|
||||
|
||||
## M2: Capture parity
|
||||
## M2: Capture parity — done
|
||||
|
||||
- Multi-display capture for the monitor under the pointer is implemented; per-display recording QA is ongoing.
|
||||
- Annotation canvas: crop, rectangle, arrow, text, highlight, black-bar redaction, pixelate/mosaic, numbering and gradient background are implemented; blur and stamps are next.
|
||||
- Pinned screenshot windows with copy and close controls are implemented.
|
||||
- Recording controls: resolution, frame rate, audio source, pause/resume.
|
||||
- Capture history library with search, pinning and drag-out.
|
||||
- Quick-access overlay after capture, matching CleanShot's floating result card.
|
||||
- Multi-display capture for the monitor under the pointer, plus per-display recording.
|
||||
- Annotation canvas: crop, rectangle, arrow, text, highlight, black-bar redaction,
|
||||
pixelate/mosaic, blur, stamps (check / cross / star), numbering and gradient background.
|
||||
- Pinned screenshot windows with copy and close controls.
|
||||
- Recording controls that only offer what the platform honours: audio plus pause/resume
|
||||
on macOS, frame rate plus pause/resume on the FFmpeg backends. `recording_capabilities`
|
||||
is the single source of truth, so a switch the backend would ignore is never shown.
|
||||
- Capture history library: Rust-owned list in the app data directory with search, pinning,
|
||||
per-row removal, clear, and drag-out of a row into Finder or another application. The drag
|
||||
payload (`text/uri-list` with a `file://` entry, plus the plain path and Shift's internal
|
||||
type) is unit-tested in `src/lib/dragOut.test.ts`; the release of that drag is the one part
|
||||
of M2 still needing a gesture-level check on each platform, and the README says so.
|
||||
- Quick-access result card after capture, matching CleanShot's floating card, with
|
||||
Copy / Pin / Send / Reveal / Edit and a "card or editor" switch in Settings.
|
||||
|
||||
## M3: File workspace
|
||||
## M3: File workspace — done
|
||||
|
||||
- PDF, image, media, DOCX and Markdown paths are implemented; DOC/DOCX/ODT/RTF/HTML/TXT to PDF is implemented on macOS through the bundled AppKit renderer; PowerPoint/Excel basic text/table PDF export is implemented, with layout-accurate export next.
|
||||
- PDF, image, media, DOCX and Markdown paths are implemented; DOC/DOCX/ODT/RTF/HTML/TXT
|
||||
to PDF is implemented on macOS through the bundled AppKit renderer; PowerPoint/Excel
|
||||
basic text/table PDF export is implemented, with layout-accurate export next.
|
||||
- Batch operations and drag-to-submenu interaction.
|
||||
- Custom radial item ordering and per-file-type presets.
|
||||
- Undo history and conflict-safe output naming.
|
||||
- Custom radial item ordering with per-file-type presets: the wedge catalogue lives in
|
||||
`src/lib/radialOrder.ts`, orders are stored per kind and ring in `settings.json`. The
|
||||
Settings tab that edited them was removed in 0.1.1, so orders now come from
|
||||
`settings.json` alone; `src/components/RadialOrderPanel.tsx` is kept for when an editor
|
||||
comes back.
|
||||
- Undo history in the annotation canvas (annotations pop first, then image-level
|
||||
operations, matching the README table) and conflict-safe output naming: `unique_output`
|
||||
appends a numeric suffix instead of overwriting. There is no undo for a completed file
|
||||
conversion — the original file is never touched, so nothing needs undoing.
|
||||
|
||||
## M4: Cross-platform parity
|
||||
## M4: Cross-platform parity — partial
|
||||
|
||||
- Windows global drag bridge using the Win32/OLE drag state is implemented.
|
||||
- Windows native capture backend without PowerShell where practical.
|
||||
- Linux Wayland and X11 capture backends.
|
||||
- Universal macOS build is implemented; Windows ARM64 build is pending.
|
||||
- Linux capture: `grim` for stills on both Wayland and X11, and `wf-recorder` for area
|
||||
recording under Wayland (ffmpeg's `x11grab` has no root window to grab there), with the
|
||||
X11 ffmpeg path unchanged.
|
||||
- Windows capture is native already: `capture_windows_screen` in `src-tauri/src/capture.rs`
|
||||
grabs the monitor under the pointer with GDI `BitBlt` + `GetDIBits`, pinning the worker
|
||||
thread to per-monitor-v2 DPI awareness so a mixed-DPI or multi-monitor desktop cannot
|
||||
shift the image out from under the overlay. PowerShell is nowhere in the capture path; it
|
||||
is used only as the HTTP client for the update download.
|
||||
- Windows ARM64: `scripts/build-windows-release.sh` builds both architectures by
|
||||
default, checks each binary's PE machine field (`0x8664` / `0xAA64`) before packaging
|
||||
it, and gates each NSIS installer to the matching machine. The update manifest gained a
|
||||
`windows-arm64` key; an ARM build tries it first and falls back to `windows`, which
|
||||
Windows on ARM runs under emulation, so a channel that predates the ARM build still
|
||||
serves it. Verified by cross-building, packaging and publishing all of that from macOS;
|
||||
running the installer on real Windows-on-ARM hardware has not happened. Since 0.1.1 the
|
||||
shipped targets are macOS and Windows x64 only, so ARM64 stays a buildable architecture
|
||||
(`--arch arm64` still works, `windows-arm64` still falls back to `windows`) that nothing
|
||||
is published for.
|
||||
- Linux is supported as a build and run target but is **not a shipped product**: no deb or
|
||||
AppImage is published, so the update channel has no `linux` key and the platform table
|
||||
reports "no artifact" rather than a failure. `scripts/linux/Dockerfile` and the `linux` CI
|
||||
job stay as the recipe for anyone who wants a package; nothing in the app blocks on them.
|
||||
|
||||
## M5: Distribution
|
||||
- HEIC/HEIF/AVIF inputs no longer stop the pixel tools. The pixel tools used to call the
|
||||
Rust decoder directly, so a phone screenshot could be converted but not rotated,
|
||||
halved, compressed or cleaned. They now share the decode path the convert wedge already
|
||||
used (`open_for_pixels` in `src-tauri/src/files.rs`), which falls back to the system
|
||||
codec, and the result is written as PNG because nothing in this path can write HEIC.
|
||||
Covered by `pixel_tools_read_system_only_image_formats`, which builds a real HEIC with
|
||||
`sips` and skips only when the machine cannot write one. Shipped: 0.1.1 is the first
|
||||
published build carrying it; the 0.1.0 installers were built before it.
|
||||
|
||||
- Signed and notarized macOS package.
|
||||
- Signed Windows installer.
|
||||
- Automatic updates with signed manifests.
|
||||
- Permission onboarding and diagnostics screen.
|
||||
## M5: Distribution — partial
|
||||
|
||||
- Update channel on git is implemented: `scripts/publish-release.sh` copies the built
|
||||
installers plus `shift-update.json` (version, size, SHA256 per platform) onto an orphan
|
||||
`releases` branch, and Shift reads that manifest from the forge's raw endpoint, downloads
|
||||
its own artifact, and refuses to install it unless the recomputed SHA256 matches. See
|
||||
`docs/RELEASE.md`.
|
||||
- Daily startup probe with a manual "check now", a progress readout, and a tray row that
|
||||
jumps to Settings → Updates.
|
||||
- Signed and notarized macOS package: pending (builds are signed with a local identity).
|
||||
- Signed Windows installer: pending.
|
||||
- Manifest signing is done. `scripts/release-key.py` mints the release key,
|
||||
`publish-release.sh --key` publishes a detached `shift-update.sig` over the manifest's
|
||||
exact bytes, and a build compiled with the key refuses a manifest that does not verify.
|
||||
Every release artifact on the channel is built with the key baked in —
|
||||
`build-windows-release.sh` derives `SHIFT_UPDATE_PUBKEY` from `SHIFT_RELEASE_KEY`, so the
|
||||
installer and the signature cannot drift apart. Verified against the published feed both
|
||||
ways: the real key passes, a valid but different key fails, and a key that is not a curve
|
||||
point is an error rather than a silent fall-back to "unsigned". What remains is custody of
|
||||
the key itself (it lives outside the repository, and losing it means shipping a new build
|
||||
with a new one) plus the code-signing items above.
|
||||
- Guided first-run checks are done: one card, four probes (Screen Recording, writable
|
||||
output folders, ownership of the global shortcuts, missing optional tools), each with the
|
||||
fix next to the finding, and dismissal changes no setting. It reuses the same commands
|
||||
Settings uses — `screen_capture_access_status`, `check_output_access`, `hotkey_status`,
|
||||
`machine_info` — so the card cannot disagree with the panels, and it reads
|
||||
`setup_reviewed` from `settings.json` so a second copy on the same account stays quiet.
|
||||
Rendered and checked in a browser for all three row states; a real first launch on each
|
||||
platform is still worth watching.
|
||||
- The Linux install step no longer ends in "Automatic updates are not wired up on this
|
||||
platform", which was a dead end for anyone who builds their own package: it now sets the
|
||||
executable bit and starts a downloaded AppImage, and hands a `.deb` to the desktop's
|
||||
package handler. That serves a self-built bundle, not this channel — Linux publishes
|
||||
nothing, so a stock Linux build still stops at "no artifact for this platform". No host
|
||||
here compiles the branch, so it was type-checked by temporarily disabling the other two
|
||||
arms; it has never run on a Linux desktop.
|
||||
- The published channel was re-verified by hand against the live `releases` branch for
|
||||
every release since: the 0.1.1 manifest's signature checks out against the baked key and
|
||||
both artifacts (`macos`, `windows`) match their published size and SHA256. The
|
||||
`windows-arm64` and `linux` keys are absent because only those two platforms are shipped.
|
||||
See "State of the published channel" in `docs/RELEASE.md`.
|
||||
|
||||
## M6: Next desktop work
|
||||
|
||||
Restricted to work this repository can do something about; hardware QA is last because no
|
||||
commit closes it. Each item states the check that closes it. Linux packaging is deliberately
|
||||
absent — the platform is supported, not shipped.
|
||||
|
||||
1. **A real CI run.** The forge (Gitea) returns 404 for `/actions/runs`, so `ci.yml` is
|
||||
never executed. Either mirror to GitHub or install Forgejo Actions. Close: one green run
|
||||
per platform whose log is linked from the release notes.
|
||||
2. **Persistent job queue with cancel and retry.** `perform_file_action` already emits
|
||||
`app://file-action-progress` with real page counts, but a batch dies with the window and
|
||||
an error aborts the rest of the batch. Close: a queued batch survives an app restart,
|
||||
one file's failure reports and continues, and each row can be cancelled.
|
||||
3. **A metadata reader.** The wedge is now labelled **Strip metadata** (*移除元数据*), which
|
||||
is what it does, so the label no longer promises a lookup; the wedge id stays `metadata`
|
||||
and `LABEL_KEYS` does the rename, so orders saved by earlier builds still resolve. What
|
||||
is still missing is the reader itself. Close: a read-only panel with dimensions, codec,
|
||||
colour space and the EXIF/XMP a file actually carries, reachable from the same ring.
|
||||
4. **AVIF export.** `sips` on this macOS reports `public.avif` as readable but not
|
||||
writable, so this needs an encoder rather than a flag; the `image` crate has no AVIF
|
||||
encoder. Close: an AVIF target in the image ring with the matrix test updated, or an
|
||||
explicit README statement that AVIF stays read-only.
|
||||
5. **Drag-out gesture QA on real Windows hardware.** These are
|
||||
the claims in the README that rest on cross-compilation rather than execution, and no
|
||||
code change closes them.
|
||||
|
||||
## Mobile
|
||||
|
||||
`docs/MOBILE.md` is the plan; this is the short version of what it concluded.
|
||||
|
||||
- The one desktop idea worth copying is not the ring, it is that a capability menu appears
|
||||
while a file is already moving. On both phones that gesture already exists and users do it
|
||||
daily: the share sheet. So the mobile product is "release a share over a Shift action",
|
||||
not "Shift in your pocket".
|
||||
- Portable, and now measured: `pdf.rs` and `office.rs` have no Tauri reference at all,
|
||||
`files.rs` needs its command wrappers peeled off, and the conversion dependency closure
|
||||
(161 crates) needs no C toolchain on iOS or Android. That is most of the product value
|
||||
with no platform API in it.
|
||||
- Substituted rather than ported: HEIC and media codecs, OCR (`Vision` / ML Kit over the
|
||||
Tesseract WASM), capture (ReplayKit / MediaProjection), and the result card, which has no
|
||||
always-on-top window to live in. Skipped: global hotkeys, launch-at-login, the update
|
||||
channel (the store is the only permitted update path), and the runtime-components panel.
|
||||
- Ecosystem surfaces are enumerated per platform in that document — share extension and
|
||||
`ACTION_SEND`, File Provider and `DocumentsProvider` so the history library appears in
|
||||
Files, document-type declarations for open-with and create-document, App Intents and
|
||||
launcher shortcuts, widgets, and the local-network permissions the LAN path needs.
|
||||
- Cross-machine work is the reason a phone app exists at all, and it needs one protocol
|
||||
change first: SHSF has no version byte today. Pairing by short code, mDNS/NSD discovery
|
||||
beside the existing beacon, and a pull model for desktop→phone because iOS will not let a
|
||||
backgrounded socket listen. Still no cloud relay.
|
||||
- Step zero is executable today and needs no phone: extract `shift-core` on desktop and keep
|
||||
`cargo test --lib` green while the pure functions move out from under the command layer.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "shift",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"prepare:ocr": "bash scripts/prepare-ocr-assets.sh",
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
#!/bin/bash
|
||||
# Build the Windows release artefacts from current source.
|
||||
#
|
||||
# scripts/build-windows-release.sh [--skip-build]
|
||||
# scripts/build-windows-release.sh [--skip-build] [--arch x64|arm64]...
|
||||
#
|
||||
# Produces an NSIS per-user installer plus a portable ZIP in artifacts/, then
|
||||
# refreshes artifacts/SHA256SUMS.txt. Cross-compiled on macOS with cargo-xwin;
|
||||
# makensis is the Homebrew formula of the same name.
|
||||
# For every architecture asked for (both by default) this produces an NSIS
|
||||
# per-user installer plus a portable ZIP in artifacts/, then refreshes
|
||||
# artifacts/SHA256SUMS.txt. Cross-compiled on macOS with cargo-xwin; makensis is
|
||||
# the Homebrew formula of the same name. publish-release.sh maps the installers
|
||||
# onto the "windows" and "windows-arm64" keys of the update manifest.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
|
|
@ -14,35 +16,90 @@ export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
|
|||
export RUSTC="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/rustc"
|
||||
|
||||
ROOT="$PWD"
|
||||
EXE=src-tauri/target/x86_64-pc-windows-msvc/release/shift.exe
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
INSTALLER="artifacts/Shift-Setup-$VERSION-win-x64.exe"
|
||||
PORTABLE="artifacts/Shift-Portable-$VERSION-win-x64.zip"
|
||||
|
||||
if [ "${1:-}" != "--skip-build" ]; then
|
||||
echo "== frontend (Windows target: chrome105) =="
|
||||
TAURI_ENV_PLATFORM=windows pnpm build
|
||||
ARCHES=""
|
||||
SKIP_BUILD=0
|
||||
usage() { echo "usage: $0 [--skip-build] [--arch x64|arm64]..." >&2 && exit 2; }
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1 ;;
|
||||
--arch)
|
||||
shift
|
||||
case "${1:-}" in
|
||||
x64|arm64) ARCHES="$ARCHES $1" ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[ -n "$ARCHES" ] || ARCHES="x64 arm64"
|
||||
|
||||
echo "== rust cross build =="
|
||||
# --features tauri/custom-protocol is mandatory: without it Tauri derives
|
||||
# cfg(dev) and every window loads build.devUrl instead of the bundled assets.
|
||||
CROSS_LOG=$(mktemp /tmp/shift-win-build.XXXXXX)
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target x86_64-pc-windows-msvc --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
# A build can only verify a signed channel if the release key is compiled in. Derive
|
||||
# it from the signing key when the caller gave us one, and never do this quietly: the
|
||||
# alternative is two installers with the same version number and different trust.
|
||||
if [ -z "${SHIFT_UPDATE_PUBKEY:-}" ] && [ -n "${SHIFT_RELEASE_KEY:-}" ]; then
|
||||
SHIFT_UPDATE_PUBKEY=$(python3 scripts/release-key.py pubkey "${SHIFT_RELEASE_KEY%.ed25519}.pub")
|
||||
export SHIFT_UPDATE_PUBKEY
|
||||
fi
|
||||
if [ -n "${SHIFT_UPDATE_PUBKEY:-}" ]; then
|
||||
echo "== release key baked in: ${SHIFT_UPDATE_PUBKEY:0:12}… =="
|
||||
else
|
||||
echo "== no release key: this build will report the feed as unsigned =="
|
||||
fi
|
||||
|
||||
test -f "$EXE"
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
echo "== frontend (Windows target: chrome105) =="
|
||||
TAURI_ENV_PLATFORM=windows pnpm build
|
||||
fi
|
||||
|
||||
echo "== verify the frontend is embedded =="
|
||||
python3 - "$EXE" <<'PY'
|
||||
# One target triple, one expected PE machine and one release-note label per
|
||||
# architecture. The PE check is what stops an x64 binary shipping inside an
|
||||
# arm64 package because a build was pointed at the wrong target.
|
||||
for ARCH in $ARCHES; do
|
||||
case "$ARCH" in
|
||||
x64) TARGET=x86_64-pc-windows-msvc; PE_MACHINE=8664; MACHINE="64 位" ;;
|
||||
arm64) TARGET=aarch64-pc-windows-msvc; PE_MACHINE=aa64; MACHINE=ARM64 ;;
|
||||
esac
|
||||
EXE="src-tauri/target/$TARGET/release/shift.exe"
|
||||
INSTALLER="artifacts/Shift-Setup-$VERSION-win-$ARCH.exe"
|
||||
PORTABLE="artifacts/Shift-Portable-$VERSION-win-$ARCH.zip"
|
||||
NOTES="artifacts/README-Windows-$ARCH.txt"
|
||||
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
echo "== rust cross build ($ARCH: $TARGET) =="
|
||||
# --features tauri/custom-protocol is mandatory: without it Tauri derives
|
||||
# cfg(dev) and every window loads build.devUrl instead of the bundled assets.
|
||||
CROSS_LOG=$(mktemp /tmp/shift-win-build.XXXXXX)
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target "$TARGET" --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
fi
|
||||
|
||||
test -f "$EXE"
|
||||
|
||||
echo "== PE machine check ($ARCH) =="
|
||||
python3 - "$EXE" "$PE_MACHINE" <<PE
|
||||
import pathlib, struct, sys
|
||||
exe = pathlib.Path(sys.argv[1]).read_bytes()
|
||||
machine = struct.unpack_from("<H", exe, struct.unpack_from("<I", exe, 0x3C)[0] + 4)[0]
|
||||
expected = int(sys.argv[2], 16)
|
||||
if machine != expected:
|
||||
sys.exit(f"{sys.argv[1]} is PE machine 0x{machine:04x}, expected 0x{expected:04x}")
|
||||
print(f"pe machine ok: 0x{machine:04x}")
|
||||
PE
|
||||
|
||||
echo "== verify the frontend is embedded =="
|
||||
python3 - "$EXE" <<PY
|
||||
import pathlib, sys
|
||||
exe = pathlib.Path(sys.argv[1]).read_bytes()
|
||||
missing = [p.name for p in pathlib.Path("dist/assets").iterdir() if p.name.encode() not in exe]
|
||||
|
|
@ -68,17 +125,18 @@ if missing:
|
|||
print(f"embedded ok: {len(exe):,} byte exe carries the current dist/assets")
|
||||
PY
|
||||
|
||||
echo "== windows notes =="
|
||||
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
|
||||
mkdir -p "$STAGE/portable/Shift-$VERSION-Windows-x64"
|
||||
python3 - "$STAGE" "$VERSION" <<'PY'
|
||||
echo "== windows notes ($ARCH) =="
|
||||
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
|
||||
mkdir -p "$STAGE/portable/Shift-$VERSION-Windows-$ARCH"
|
||||
python3 - "$STAGE" "$VERSION" "$ARCH" "$MACHINE" <<PY
|
||||
import pathlib, sys
|
||||
stage, version = pathlib.Path(sys.argv[1]), sys.argv[2]
|
||||
text = f"""Shift {version} - Windows x64
|
||||
stage = pathlib.Path(sys.argv[1])
|
||||
version, arch, machine = sys.argv[2:5]
|
||||
text = f"""Shift {version} - Windows {arch}
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11(64 位)。
|
||||
- Windows 10 或 Windows 11({machine})。
|
||||
- Microsoft Edge WebView2 Runtime。当前 Windows 10/11 通常已内置;如果 Shift
|
||||
启动后窗口空白或无法打开,请从微软官方页面安装:
|
||||
https://developer.microsoft.com/microsoft-edge/webview2/
|
||||
|
|
@ -87,7 +145,7 @@ text = f"""Shift {version} - Windows x64
|
|||
|
||||
安装
|
||||
----
|
||||
1. 运行 Shift-Setup-{version}-win-x64.exe,默认安装到
|
||||
1. 运行 Shift-Setup-{version}-win-{arch}.exe,默认安装到
|
||||
%LOCALAPPDATA%\\Programs\\Shift,并创建开始菜单与桌面快捷方式。
|
||||
2. 这是未签名构建。若 SmartScreen 显示“Windows 已保护你的电脑”,请选择
|
||||
“更多信息” > “仍要运行”。
|
||||
|
|
@ -95,7 +153,7 @@ text = f"""Shift {version} - Windows x64
|
|||
|
||||
便携版
|
||||
------
|
||||
不想安装时,解压 Shift-Portable-{version}-win-x64.zip,直接运行其中的
|
||||
不想安装时,解压 Shift-Portable-{version}-win-{arch}.zip,直接运行其中的
|
||||
shift.exe。请先完整解压,不要在压缩包的预览窗口里运行。
|
||||
|
||||
运行组件
|
||||
|
|
@ -120,49 +178,63 @@ WinGet 包映射:
|
|||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\\Shift-Setup-{version}-win-x64.exe -Algorithm SHA256
|
||||
Get-FileHash .\\Shift-Setup-{version}-win-{arch}.exe -Algorithm SHA256
|
||||
"""
|
||||
(stage / "README-Windows.txt").write_bytes(text.replace("\n", "\r\n").encode("utf-8"))
|
||||
PY
|
||||
|
||||
echo "== NSIS installer =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSHIFT_EXE="$PWD/$EXE" \
|
||||
-DLICENSE_FILE="$PWD/LICENSE" \
|
||||
-DNOTICES_FILE="$PWD/THIRD_PARTY_NOTICES.md" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$PWD/src-tauri/icons" \
|
||||
-DOUT_FILE="$PWD/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
echo "== NSIS installer ($ARCH) =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSHIFT_EXE="$PWD/$EXE" \
|
||||
-DLICENSE_FILE="$PWD/LICENSE" \
|
||||
-DNOTICES_FILE="$PWD/THIRD_PARTY_NOTICES.md" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$PWD/src-tauri/icons" \
|
||||
-DOUT_FILE="$PWD/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DARCH="$ARCH" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
|
||||
echo "== portable ZIP =="
|
||||
cp "$EXE" "$STAGE/portable/Shift-$VERSION-Windows-x64/shift.exe"
|
||||
cp LICENSE "$STAGE/portable/Shift-$VERSION-Windows-x64/LICENSE.txt"
|
||||
cp THIRD_PARTY_NOTICES.md "$STAGE/portable/Shift-$VERSION-Windows-x64/THIRD_PARTY_NOTICES.txt"
|
||||
cp "$STAGE/README-Windows.txt" "$STAGE/portable/Shift-$VERSION-Windows-x64/README-Windows.txt"
|
||||
(cd "$STAGE/portable" && zip -q -r -X -9 "$ROOT/$PORTABLE" "Shift-$VERSION-Windows-x64")
|
||||
mv "$STAGE/README-Windows.txt" "artifacts/README-Windows.txt"
|
||||
echo "== portable ZIP ($ARCH) =="
|
||||
cp "$EXE" "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/shift.exe"
|
||||
cp LICENSE "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/LICENSE.txt"
|
||||
cp THIRD_PARTY_NOTICES.md "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/THIRD_PARTY_NOTICES.txt"
|
||||
cp "$STAGE/README-Windows.txt" "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/README-Windows.txt"
|
||||
(cd "$STAGE/portable" && zip -q -r -X -9 "$ROOT/$PORTABLE" "Shift-$VERSION-Windows-$ARCH")
|
||||
mv "$STAGE/README-Windows.txt" "$NOTES"
|
||||
done
|
||||
|
||||
echo "== checksums =="
|
||||
python3 - "$INSTALLER" "$PORTABLE" <<'PY'
|
||||
python3 - "$VERSION" <<PY
|
||||
import hashlib, pathlib, sys
|
||||
version = sys.argv[1]
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
names = ["Shift-macOS-universal.dmg", "Shift-macOS-universal.zip"]
|
||||
names += [pathlib.Path(arg).name for arg in sys.argv[1:]]
|
||||
names.append("README-Windows.txt")
|
||||
lines = []
|
||||
for name in names:
|
||||
path = artifacts / name
|
||||
lines.append(f"{hashlib.sha256(path.read_bytes()).hexdigest()} {name}")
|
||||
preferred = [
|
||||
"Shift-macOS-universal.dmg",
|
||||
"Shift-macOS-universal.zip",
|
||||
f"Shift-Setup-{version}-win-x64.exe",
|
||||
f"Shift-Setup-{version}-win-arm64.exe",
|
||||
f"Shift-Portable-{version}-win-x64.zip",
|
||||
f"Shift-Portable-{version}-win-arm64.zip",
|
||||
"README-Windows-x64.txt",
|
||||
"README-Windows-arm64.txt",
|
||||
]
|
||||
names = [name for name in preferred if (artifacts / name).is_file()]
|
||||
names += sorted(
|
||||
path.name
|
||||
for path in artifacts.iterdir()
|
||||
if path.is_file()
|
||||
and path.name not in names
|
||||
and path.name != "SHA256SUMS.txt"
|
||||
and not path.name.startswith(".")
|
||||
)
|
||||
lines = [f"{hashlib.sha256((artifacts / name).read_bytes()).hexdigest()} {name}" for name in names]
|
||||
(artifacts / "SHA256SUMS.txt").write_text("".join(line + "\n" for line in lines), encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
PY
|
||||
|
||||
echo "== result =="
|
||||
ls -lh "$INSTALLER" "$PORTABLE"
|
||||
printf 'installer sha256: %s\n' "$(shasum -a 256 "$INSTALLER" | cut -d' ' -f1)"
|
||||
printf 'exe sha256: %s\n' "$(shasum -a 256 "$EXE" | cut -d' ' -f1)"
|
||||
ls -lh artifacts/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
# Linux release build for Shift, run from macOS through Docker.
|
||||
#
|
||||
# docker build -f scripts/linux/Dockerfile -t shift-linux-build .
|
||||
#
|
||||
# The base image is whatever Debian bookworm image is local; Tauri's Linux
|
||||
# bundlers (deb, AppImage) need WebKitGTK, the indicator library and pkg-config
|
||||
# in addition to a Rust and Node toolchain, none of which exist on macOS.
|
||||
ARG BASE_IMAGE=debian:bookworm-slim
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
# libxdo-dev is required by tauri's global-shortcut plugin; the indicator and
|
||||
# rsvg libraries back the tray icon and generated icons.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl xz-utils git pkg-config file \
|
||||
build-essential libssl-dev \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libxdo-dev \
|
||||
libayatana-appindicator3-dev librsvg2-dev patchelf \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# pnpm is installed through npm rather than Corepack: Corepack re-resolves pnpm over
|
||||
# the network in every fresh container, and this project's lockfile wants pnpm 8/9.
|
||||
ARG NODE_VERSION=22.14.0
|
||||
RUN arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) node_arch=$arch ;; esac \
|
||||
&& curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${node_arch}.tar.xz" \
|
||||
| tar -xJ -C /usr/local --strip-components=1 \
|
||||
&& npm install --global pnpm@9
|
||||
|
||||
ENV CARGO_HOME=/usr/local/cargo RUSTUP_HOME=/usr/local/rustup PATH=/usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
| sh -s -- -y --profile minimal --default-toolchain stable --component rustfmt
|
||||
|
||||
WORKDIR /work
|
||||
COPY . /work
|
||||
|
||||
# The Linux build has no Swift sidecars, and the frontend must exist before
|
||||
# Tauri embeds it.
|
||||
RUN pnpm install --frozen-lockfile && pnpm prepare:ocr && pnpm check && pnpm build
|
||||
|
||||
CMD ["bash", "-c", "cd src-tauri && cargo test --lib && cd .. && pnpm tauri build --bundles deb,appimage"]
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
#!/bin/bash
|
||||
# Publish the built artifacts onto the git branch that IS the update channel.
|
||||
#
|
||||
# scripts/publish-release.sh [--notes FILE] [--key FILE] [--dry-run]
|
||||
# [--no-push] [--branch NAME]
|
||||
#
|
||||
# Every installer in artifacts/ is copied onto an orphan `releases` branch together
|
||||
# with `shift-update.json`, which names each file, its size and its SHA256. A running
|
||||
# Shift reads that manifest from the forge's raw endpoint, downloads its own
|
||||
# platform's artifact and refuses to launch it unless the recomputed hash matches, so
|
||||
# this script is the only thing needed to ship a release: no release service, no
|
||||
# object storage, no credentials beyond what `git push` already uses.
|
||||
#
|
||||
# With `--key` (or SHIFT_RELEASE_KEY) the manifest is also signed, and the base64
|
||||
# ed25519 signature is pushed as `shift-update.sig`. A Shift built with the matching
|
||||
# SHIFT_UPDATE_PUBKEY refuses a manifest that does not verify, so the channel proves
|
||||
# authenticity and not just integrity. Without a key the publish still works and the
|
||||
# app falls back to trusting the feed over HTTPS, and says so in the Updates panel.
|
||||
#
|
||||
# The branch is rebuilt as a fresh root commit on every run and force-pushed, so it
|
||||
# always holds exactly one release instead of accumulating gigabytes of history.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
BRANCH="${SHIFT_RELEASE_BRANCH:-releases}"
|
||||
MANIFEST="shift-update.json"
|
||||
NOTES_FILE=""
|
||||
KEY_FILE="${SHIFT_RELEASE_KEY:-}"
|
||||
DRY_RUN=0
|
||||
NO_PUSH=0
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--notes) NOTES_FILE="$2"; shift 2 ;;
|
||||
--dry-run) DRY_RUN=1; shift ;;
|
||||
--no-push) NO_PUSH=1; shift ;;
|
||||
--branch) BRANCH="$2"; shift 2 ;;
|
||||
--key) KEY_FILE="$2"; shift 2 ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
PLAN=$(mktemp /tmp/shift-release-plan.XXXXXX)
|
||||
INDEX_FILE=$(mktemp /tmp/shift-release-index.XXXXXX)
|
||||
trap 'rm -f "$PLAN" "$INDEX_FILE"' EXIT
|
||||
|
||||
# The plan is: one JSON manifest document, then a NUL-separated list of the files
|
||||
# that back it. Keeping the hashing in Python means the manifest and the pushed
|
||||
# bytes cannot disagree.
|
||||
python3 - "$VERSION" "$MANIFEST" "$NOTES_FILE" > "$PLAN" <<'PY'
|
||||
import datetime, hashlib, json, pathlib, re, sys
|
||||
|
||||
version, manifest_name, notes_file = sys.argv[1:4]
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
if not artifacts.is_dir():
|
||||
sys.exit("artifacts/ is missing; build a release first.")
|
||||
notes = pathlib.Path(notes_file).read_text(encoding="utf-8").strip() if notes_file else ""
|
||||
|
||||
# One installer per manifest key. Extra files such as the portable archive and the
|
||||
# checksum listing still travel with the branch, they are just not installers.
|
||||
# Windows is keyed per architecture: `windows` is what an x64 machine installs and
|
||||
# what an ARM machine falls back to, `windows-arm64` is the native ARM build. The
|
||||
# x64 pattern must not match the arm64 file, or every Windows machine would be
|
||||
# served whichever installer sorted first.
|
||||
PATTERNS = [
|
||||
("macos", [r"^Shift-macOS-universal\.dmg$", r"^[Ss]hift.*\.dmg$"]),
|
||||
(
|
||||
"windows",
|
||||
[rf"^Shift-Setup-{re.escape(version)}-win-x64\.exe$", r"-win-x64\.exe$"],
|
||||
),
|
||||
(
|
||||
"windows-arm64",
|
||||
[rf"^Shift-Setup-{re.escape(version)}-win-arm64\.exe$", r"-win-arm64\.exe$"],
|
||||
),
|
||||
("linux", [r"\.AppImage$", r"\.deb$"]),
|
||||
]
|
||||
candidates = sorted(p.name for p in artifacts.iterdir() if p.is_file())
|
||||
|
||||
def digest(name):
|
||||
path = artifacts / name
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_size
|
||||
|
||||
manifest = {
|
||||
"schema": 1,
|
||||
"version": version,
|
||||
"date": datetime.date.today().isoformat(),
|
||||
"notes": notes,
|
||||
"artifacts": {},
|
||||
}
|
||||
chosen = []
|
||||
for platform, patterns in PATTERNS:
|
||||
for pattern in patterns:
|
||||
match = next((name for name in candidates if re.search(pattern, name)), None)
|
||||
if match:
|
||||
hash_value, size = digest(match)
|
||||
manifest["artifacts"][platform] = {"file": match, "sha256": hash_value, "size": size}
|
||||
chosen.append(match)
|
||||
break
|
||||
|
||||
if not manifest["artifacts"]:
|
||||
sys.exit(
|
||||
f"no installer found in artifacts/ for version {version}; "
|
||||
"expected Shift-macOS-universal.dmg and/or Shift-Setup-<version>-win-{x64,arm64}.exe"
|
||||
)
|
||||
|
||||
payload = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
|
||||
sys.stdout.write(payload)
|
||||
sys.stdout.write("\0")
|
||||
for name in candidates:
|
||||
# The manifest and its signature are regenerated each run; dotfiles are not
|
||||
# build products.
|
||||
if name in {manifest_name, "shift-update.sig"} or name.startswith("."):
|
||||
continue
|
||||
hash_value, size = digest(name)
|
||||
sys.stdout.write(f"{name}\t{hash_value}\t{size}\0")
|
||||
PY
|
||||
|
||||
MANIFEST_JSON=$(python3 -c "import sys;print(sys.stdin.read().split('\0')[0],end='')" < "$PLAN")
|
||||
echo "== manifest for $VERSION =="
|
||||
printf '%s\n' "$MANIFEST_JSON"
|
||||
|
||||
MANIFEST_PATH=$(mktemp /tmp/shift-manifest.XXXXXX)
|
||||
SIGNATURE_PATH=$(mktemp /tmp/shift-sig.XXXXXX)
|
||||
trap 'rm -f "$PLAN" "$INDEX_FILE" "$MANIFEST_PATH" "$SIGNATURE_PATH"' EXIT
|
||||
printf '%s\n' "$MANIFEST_JSON" > "$MANIFEST_PATH"
|
||||
|
||||
# The signature covers the manifest file's own bytes, which are the bytes a client
|
||||
# fetches, so verification needs no JSON canonicalisation rules.
|
||||
if [ -n "$KEY_FILE" ]; then
|
||||
python3 scripts/release-key.py sign "$KEY_FILE" "$MANIFEST_PATH" > "$SIGNATURE_PATH"
|
||||
echo "== manifest signed with $KEY_FILE =="
|
||||
fi
|
||||
|
||||
echo "== building the $BRANCH tree =="
|
||||
export GIT_INDEX_FILE=$INDEX_FILE
|
||||
git read-tree --empty
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "$MANIFEST_PATH"),$MANIFEST"
|
||||
if [ -s "$SIGNATURE_PATH" ]; then
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "$SIGNATURE_PATH"),shift-update.sig"
|
||||
fi
|
||||
while IFS=$'\t' read -r -d '' name hash_value size; do
|
||||
[ -n "$name" ] || continue
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "artifacts/$name"),$name"
|
||||
printf ' %-38s %10s B %s…\n' "$name" "$size" "${hash_value:0:16}"
|
||||
done < <(python3 -c "
|
||||
import sys
|
||||
chunks = sys.stdin.read().split('\0')
|
||||
for entry in chunks[1:]:
|
||||
if entry.strip():
|
||||
sys.stdout.write(entry + '\0')
|
||||
" < "$PLAN")
|
||||
TREE=$(git write-tree)
|
||||
COMMIT=$(git commit-tree "$TREE" -m "release $VERSION")
|
||||
unset GIT_INDEX_FILE
|
||||
|
||||
if [ "$DRY_RUN" = 1 ]; then
|
||||
echo "== dry run: $COMMIT would become $BRANCH =="
|
||||
git ls-tree -rl "$COMMIT" | while read -r mode type hash size name; do
|
||||
printf ' %12s B %s\n' "$size" "$name"
|
||||
done
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if git rev-parse --verify -q "refs/heads/$BRANCH" >/dev/null; then
|
||||
echo "== replacing $(git rev-parse --short "$BRANCH") =="
|
||||
fi
|
||||
git update-ref "refs/heads/$BRANCH" "$COMMIT"
|
||||
echo "committed $VERSION as $(git rev-parse --short "$BRANCH")"
|
||||
|
||||
if [ "$NO_PUSH" = 1 ]; then
|
||||
echo "--no-push: committed locally on $BRANCH"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "== pushing $BRANCH =="
|
||||
git push --force origin "$BRANCH"
|
||||
echo "published $VERSION"
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Ed25519 signing for the git update channel.
|
||||
|
||||
scripts/release-key.py keygen KEY_FILE # create the release key
|
||||
scripts/release-key.py pubkey KEY_FILE # hex key to bake into the build
|
||||
scripts/release-key.py sign KEY_FILE FILE # base64 signature on stdout
|
||||
scripts/release-key.py verify PUBKEY FILE SIG_FILE
|
||||
|
||||
The signed bytes are the file's exact bytes, with no re-serialisation, so what the
|
||||
app verifies is byte-identical to what was signed and the JSON layout stays free to
|
||||
change. Python is used because `cryptography` is already available at build time and
|
||||
its ed25519 is a one-call primitive; the app verifies with ed25519-dalek.
|
||||
"""
|
||||
import base64
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
||||
Ed25519PrivateKey,
|
||||
Ed25519PublicKey,
|
||||
)
|
||||
except ImportError:
|
||||
sys.exit("needs cryptography: pip install cryptography")
|
||||
|
||||
USAGE = __doc__
|
||||
|
||||
|
||||
def public_hex(path):
|
||||
key = Ed25519PublicKey.from_public_bytes(path.read_bytes())
|
||||
return key.public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
).hex()
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 2:
|
||||
sys.exit(USAGE)
|
||||
command, key_file = argv[0], pathlib.Path(argv[1])
|
||||
|
||||
if command == "keygen":
|
||||
if key_file.exists():
|
||||
sys.exit(f"{key_file} exists; refusing to overwrite a release key")
|
||||
key = Ed25519PrivateKey.generate()
|
||||
key_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
key_file.write_bytes(
|
||||
key.private_bytes(
|
||||
serialization.Encoding.Raw,
|
||||
serialization.PrivateFormat.Raw,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
)
|
||||
key_file.chmod(0o600)
|
||||
public = key_file.with_suffix(".pub")
|
||||
public.write_bytes(
|
||||
key.public_key().public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
)
|
||||
)
|
||||
print(f"key: {key_file} (keep this private, never commit it)")
|
||||
print(f"pubkey: {public}")
|
||||
print(f"build with SHIFT_UPDATE_PUBKEY={public_hex(public)}")
|
||||
return 0
|
||||
|
||||
if command == "pubkey":
|
||||
print(public_hex(key_file))
|
||||
return 0
|
||||
|
||||
if command == "sign":
|
||||
if len(argv) < 3:
|
||||
sys.exit(USAGE)
|
||||
key = Ed25519PrivateKey.from_private_bytes(key_file.read_bytes())
|
||||
signature = key.sign(pathlib.Path(argv[2]).read_bytes())
|
||||
sys.stdout.write(base64.b64encode(signature).decode() + "\n")
|
||||
return 0
|
||||
|
||||
if command == "verify":
|
||||
if len(argv) < 4:
|
||||
sys.exit(USAGE)
|
||||
signature = base64.b64decode(pathlib.Path(argv[3]).read_text().strip())
|
||||
Ed25519PublicKey.from_public_bytes(key_file.read_bytes()).verify(
|
||||
signature, pathlib.Path(argv[2]).read_bytes()
|
||||
)
|
||||
print("signature ok")
|
||||
return 0
|
||||
|
||||
sys.exit(f"unknown command: {command}\n\n{USAGE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
|
|
@ -2,7 +2,12 @@
|
|||
;
|
||||
; makensis -DSHIFT_EXE=<path> -DLICENSE_FILE=<path> -DNOTICES_FILE=<path> \
|
||||
; -DREADME_FILE=<path> -DICONS_DIR=<path> -DOUT_FILE=<path> \
|
||||
; -DVERSION=0.1.0 -DEST_SIZE_KB=<kb> scripts/windows-installer.nsi
|
||||
; -DVERSION=0.1.0 -DEST_SIZE_KB=<kb> [-DARCH=x64|arm64] \
|
||||
; scripts/windows-installer.nsi
|
||||
;
|
||||
; ARCH decides which machine the installer accepts: an x64 package refuses an ARM
|
||||
; machine and an arm64 package refuses x64, so nobody installs the wrong build and
|
||||
; finds out from a blank window. Omitting it keeps the previous x64 behaviour.
|
||||
;
|
||||
; Install scope is deliberately per-user: Shift writes only to HKCU and its own
|
||||
; folder, which is also what the portable build already does.
|
||||
|
|
@ -25,6 +30,21 @@
|
|||
!define EST_SIZE_KB "40000"
|
||||
!endif
|
||||
|
||||
!ifndef ARCH
|
||||
!define ARCH "x64"
|
||||
!endif
|
||||
|
||||
!if "${ARCH}" == "arm64"
|
||||
!define ARCH_GATE '${IsNativeARM64}'
|
||||
!define ARCH_GATE_MESSAGE "This build is for 64-bit Windows (ARM64)."
|
||||
!else
|
||||
!if "${ARCH}" != "x64"
|
||||
!error "ARCH is either x64 or arm64"
|
||||
!endif
|
||||
!define ARCH_GATE '${IsNativeAMD64}'
|
||||
!define ARCH_GATE_MESSAGE "This build is for 64-bit Windows (x64)."
|
||||
!endif
|
||||
|
||||
!define APP_NAME "Shift"
|
||||
!define APP_ID "app.nex.shift"
|
||||
!define APP_VERSION "${VERSION}"
|
||||
|
|
@ -87,11 +107,17 @@ Function .onInit
|
|||
Abort
|
||||
${EndIf}
|
||||
|
||||
${IfNot} ${IsNativeAMD64}
|
||||
MessageBox MB_OK|MB_ICONSTOP "This build is for 64-bit Windows (x64)."
|
||||
${IfNot} ${ARCH_GATE}
|
||||
MessageBox MB_OK|MB_ICONSTOP "${ARCH_GATE_MESSAGE}"
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
!if "${ARCH}" == "arm64"
|
||||
; Read the real 64-bit registry view: on ARM64 the default view is emulated,
|
||||
; and the machine-wide WebView2 key looked up after install is not in it.
|
||||
SetRegView 64
|
||||
!endif
|
||||
|
||||
; Shift keeps a tray process alive and Windows refuses to overwrite a mapped
|
||||
; EXE, so ask before closing a conversion the user may be waiting on.
|
||||
${If} ${FileExists} "$INSTDIR\shift.exe"
|
||||
|
|
|
|||
|
|
@ -317,6 +317,12 @@ version = "0.23.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
|
|
@ -848,6 +854,33 @@ version = "1.0.13"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.11.3",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
|
|
@ -930,6 +963,16 @@ dependencies = [
|
|||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
|
|
@ -1114,6 +1157,31 @@ dependencies = [
|
|||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2 0.11.1",
|
||||
"signature",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
|
|
@ -1267,6 +1335,12 @@ dependencies = [
|
|||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
|
||||
|
||||
[[package]]
|
||||
name = "field-offset"
|
||||
version = "0.3.6"
|
||||
|
|
@ -3104,6 +3178,16 @@ dependencies = [
|
|||
"futures-io",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
|
|
@ -3815,12 +3899,14 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "shift"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"calamine",
|
||||
"chrono",
|
||||
"ed25519-dalek",
|
||||
"flate2",
|
||||
"hex",
|
||||
"image",
|
||||
"libc",
|
||||
"lopdf 0.45.0",
|
||||
|
|
@ -3828,6 +3914,7 @@ dependencies = [
|
|||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-clipboard-manager",
|
||||
|
|
@ -3856,6 +3943,12 @@ dependencies = [
|
|||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
|
|
@ -3947,6 +4040,16 @@ dependencies = [
|
|||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
|
|
@ -4006,6 +4109,12 @@ version = "0.11.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "swift-rs"
|
||||
version = "1.0.9"
|
||||
|
|
@ -5974,6 +6083,12 @@ dependencies = [
|
|||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "shift"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
description = "A radial file utility with screenshot, recording and OCR."
|
||||
authors = ["Shift Contributors"]
|
||||
edition = "2021"
|
||||
|
|
@ -30,6 +30,9 @@ base64 = "0.22"
|
|||
chrono = { version = "0.4", features = ["clock"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
which = "7"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
ed25519-dalek = { version = "3.0.0", default-features = false, features = ["alloc", "fast"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = [
|
||||
|
|
|
|||
|
|
@ -1,4 +1,108 @@
|
|||
//! Build-time wiring for the git-backed update channel.
|
||||
//!
|
||||
//! The update feed is this repository itself, so the manifest URL is derived from
|
||||
//! the `origin` remote: `https://host/owner/repo/raw/branch/<release-branch>/
|
||||
//! shift-update.json`. GitHub uses `/raw/<branch>/` and GitLab `/-/raw/<branch>/`;
|
||||
//! everything else (Gitea, Forgejo) uses the Gitea form. A `SHIFT_UPDATE_URL`
|
||||
//! environment variable at build time overrides the derivation, and a source tree
|
||||
//! with no remote simply builds an app whose updater reports "no feed".
|
||||
//!
|
||||
//! The feed's *authenticity* comes from `SHIFT_UPDATE_PUBKEY`: a 64-byte hex ed25519
|
||||
//! public key baked into the binary, against which the manifest's own signature is
|
||||
//! checked. A build without it still verifies artifact integrity (size + SHA256) and
|
||||
//! falls back to trusting the HTTPS connection, which is what it does today.
|
||||
|
||||
use std::{path::Path, process::Command};
|
||||
|
||||
const RELEASE_BRANCH: &str = "releases";
|
||||
const MANIFEST: &str = "shift-update.json";
|
||||
const PUBKEY_ENV: &str = "SHIFT_UPDATE_PUBKEY";
|
||||
|
||||
fn git(args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).parent()?)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8(output.stdout).ok()?;
|
||||
let text = text.trim().to_string();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
/// `owner/repo` plus the host scheme, from either ssh or https remote forms.
|
||||
fn parse_remote(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim().trim_end_matches('/').trim_end_matches(".git");
|
||||
let (host, path) = if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.split_once('/')?
|
||||
} else if let Some(rest) = url.find("://").map(|index| &url[index + 3..]) {
|
||||
rest.split_once('/')?
|
||||
} else if let Some((host, path)) = url.split_once(':') {
|
||||
(host.strip_prefix("git@")?, path)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
(!host.is_empty() && !path.is_empty()).then(|| (format!("https://{host}"), path.to_string()))
|
||||
}
|
||||
|
||||
fn raw_directory(host: &str, path: &str) -> String {
|
||||
let domain = host.replace("https://", "");
|
||||
let segment = if domain.ends_with("github.com") {
|
||||
format!("raw/{RELEASE_BRANCH}")
|
||||
} else if domain.contains("gitlab") {
|
||||
format!("-/raw/{RELEASE_BRANCH}")
|
||||
} else {
|
||||
format!("raw/branch/{RELEASE_BRANCH}")
|
||||
};
|
||||
format!("{host}/{path}/{segment}")
|
||||
}
|
||||
|
||||
fn manifest_url() -> Option<String> {
|
||||
if let Ok(url) = std::env::var("SHIFT_UPDATE_URL") {
|
||||
if !url.trim().is_empty() {
|
||||
return Some(url.trim().to_string());
|
||||
}
|
||||
}
|
||||
let (host, path) = parse_remote(&git(&["remote", "get-url", "origin"])?)?;
|
||||
Some(format!("{}/{}", raw_directory(&host, &path), MANIFEST))
|
||||
}
|
||||
|
||||
/// The baked publish key, normalised to 64 lowercase hex characters. Anything else
|
||||
/// is a typo worth failing the build over rather than shipping an updater that
|
||||
/// silently accepts an unsigned feed.
|
||||
fn public_key() -> Result<String, String> {
|
||||
let raw = match std::env::var(PUBKEY_ENV) {
|
||||
Ok(value) => value,
|
||||
Err(_) => return Ok(String::new()),
|
||||
};
|
||||
let value: String = raw
|
||||
.trim()
|
||||
.chars()
|
||||
.filter(|character| !character.is_whitespace() && *character != ':')
|
||||
.collect::<String>()
|
||||
.to_ascii_lowercase();
|
||||
if value.len() != 64 || !value.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(format!("{PUBKEY_ENV} must be 64 hex characters (32 bytes)"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../dist");
|
||||
println!("cargo:rerun-if-env-changed=SHIFT_UPDATE_URL");
|
||||
println!("cargo:rerun-if-env-changed={PUBKEY_ENV}");
|
||||
// The remote can change between builds, so the derived URL refreshes whenever
|
||||
// git metadata moves. Cheap enough to re-check on every build.
|
||||
println!("cargo:rerun-if-changed=../.git/config");
|
||||
println!(
|
||||
"cargo:rustc-env=SHIFT_UPDATE_URL={}",
|
||||
manifest_url().unwrap_or_default()
|
||||
);
|
||||
match public_key() {
|
||||
Ok(key) => println!("cargo:rustc-env=SHIFT_UPDATE_PUBKEY={key}"),
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
tauri_build::build()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,16 @@
|
|||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Default permissions for Shift windows.",
|
||||
"windows": ["main", "radial", "capture", "recorder", "editor", "pin"],
|
||||
"windows": [
|
||||
"main",
|
||||
"radial",
|
||||
"capture",
|
||||
"recorder",
|
||||
"editor",
|
||||
"pin",
|
||||
"share-*",
|
||||
"result-*"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use crate::{
|
|||
editor,
|
||||
files::app_cache_dir,
|
||||
models::{ActionOutcome, CaptureSessionInfo, CaptureSource, NormalizedRect},
|
||||
settings, AppState,
|
||||
result_card, settings, AppState,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
|
|
@ -425,9 +425,9 @@ fn finish_capture(
|
|||
}
|
||||
}
|
||||
dismiss_capture(app);
|
||||
editor::show_editor(app, &output)?;
|
||||
let _ = app.emit(
|
||||
"app://file-result",
|
||||
hand_off(app, &output);
|
||||
crate::history::publish_result(
|
||||
app,
|
||||
ActionOutcome {
|
||||
outputs: vec![output.to_string_lossy().to_string()],
|
||||
message: "Screenshot saved.".into(),
|
||||
|
|
@ -436,6 +436,22 @@ fn finish_capture(
|
|||
Ok(output.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Route a finished capture per the Capture-after setting. The card is allowed to
|
||||
/// fail silently: a screenshot that saved is more important than an overlay that
|
||||
/// could not be built, and the file is already on disk and copied by then.
|
||||
fn hand_off(app: &AppHandle, output: &Path) {
|
||||
match settings::load(app).capture_after {
|
||||
settings::CaptureAfter::Editor => {
|
||||
let _ = editor::show_editor(app, output);
|
||||
}
|
||||
settings::CaptureAfter::Card => {
|
||||
if result_card::show(app, output).is_err() {
|
||||
let _ = editor::show_editor(app, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capture_fullscreen_core(app: &AppHandle, state: &AppState) -> Result<String, String> {
|
||||
ensure_screen_capture_access()?;
|
||||
for label in ["main", "radial", "editor"] {
|
||||
|
|
|
|||
|
|
@ -310,6 +310,30 @@ pub(crate) fn system_convert(input: &Path, output: &Path, target: &str) -> Resul
|
|||
}
|
||||
}
|
||||
|
||||
/// Open an image for the pixel tools.
|
||||
///
|
||||
/// HEIC, HEIF and AVIF are readable only through the system codec, so every pixel
|
||||
/// tool used to reject a phone screenshot that the convert wedge could read without
|
||||
/// trouble. Decoding through the same path the convert wedge already uses keeps the
|
||||
/// rejection for files no decoder can read at all.
|
||||
fn open_for_pixels(input: &Path) -> Result<DynamicImage, String> {
|
||||
if let Ok(image) = image::open(input) {
|
||||
return Ok(image);
|
||||
}
|
||||
let intermediate =
|
||||
std::env::temp_dir().join(format!("shift-decode-{}.png", uuid::Uuid::new_v4()));
|
||||
let decoded = system_convert(input, &intermediate, "png")
|
||||
.ok()
|
||||
.and_then(|()| image::open(&intermediate).ok());
|
||||
let _ = fs::remove_file(&intermediate);
|
||||
decoded.ok_or_else(|| {
|
||||
format!(
|
||||
"Could not read {}: an unsupported or corrupted image.",
|
||||
input.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_file(input: &Path, target: &str, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let (ext, format) = normalized_target(target);
|
||||
let output = unique_output_in(input, output_dir, "", ext)?;
|
||||
|
|
@ -1181,7 +1205,7 @@ fn convert_document(
|
|||
}
|
||||
|
||||
fn compress_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let has_alpha = image.color().has_alpha();
|
||||
let (ext, format) = if has_alpha {
|
||||
("png", ImageFormat::Png)
|
||||
|
|
@ -1194,7 +1218,7 @@ fn compress_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, Str
|
|||
}
|
||||
|
||||
fn strip_metadata(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let ext = extension_of(input);
|
||||
let (ext, format) = normalized_target(&ext);
|
||||
let output = unique_output_in(input, output_dir, " (clean)", ext)?;
|
||||
|
|
@ -1203,7 +1227,7 @@ fn strip_metadata(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, St
|
|||
}
|
||||
|
||||
fn resize_file(input: &Path, scale: f64, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let (width, height) = image.dimensions();
|
||||
let target_width = ((width as f64 * scale).round() as u32).max(1);
|
||||
let target_height = ((height as f64 * scale).round() as u32).max(1);
|
||||
|
|
@ -1225,7 +1249,7 @@ fn resize_file(input: &Path, scale: f64, output_dir: Option<&Path>) -> Result<Pa
|
|||
}
|
||||
|
||||
fn rotate_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let rotated = image.rotate90();
|
||||
let ext = extension_of(input);
|
||||
let (ext, format) = normalized_target(&ext);
|
||||
|
|
@ -1235,7 +1259,7 @@ fn rotate_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, Strin
|
|||
}
|
||||
|
||||
fn flip_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let flipped = image.fliph();
|
||||
let ext = extension_of(input);
|
||||
let (ext, format) = normalized_target(&ext);
|
||||
|
|
@ -1245,7 +1269,7 @@ fn flip_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String>
|
|||
}
|
||||
|
||||
fn grayscale_file(input: &Path, output_dir: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let grayscale = image.grayscale();
|
||||
let ext = extension_of(input);
|
||||
let (ext, format) = normalized_target(&ext);
|
||||
|
|
@ -1333,7 +1357,7 @@ fn crop_file(
|
|||
rect: &crate::models::NormalizedRect,
|
||||
output_dir: Option<&Path>,
|
||||
) -> Result<PathBuf, String> {
|
||||
let image = image::open(input).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let image = open_for_pixels(input)?;
|
||||
let (width, height) = image.dimensions();
|
||||
let x = (rect.x.clamp(0.0, 1.0) * width as f64).round() as u32;
|
||||
let y = (rect.y.clamp(0.0, 1.0) * height as f64).round() as u32;
|
||||
|
|
@ -1828,7 +1852,7 @@ pub fn perform_file_action(
|
|||
|
||||
match result {
|
||||
Ok(outcome) => {
|
||||
let _ = worker.emit("app://file-result", outcome.clone());
|
||||
crate::history::publish_result(&worker, outcome.clone());
|
||||
let _ = worker.emit(
|
||||
"app://file-action-finished",
|
||||
ActionResultEvent {
|
||||
|
|
@ -1921,7 +1945,12 @@ pub async fn save_image_data(
|
|||
) -> Result<String, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let output_dir = settings::files_output_dir(&app)?;
|
||||
save_image_data_in(&source, &data_url, suffix.as_deref(), output_dir.as_deref())
|
||||
let output =
|
||||
save_image_data_in(&source, &data_url, suffix.as_deref(), output_dir.as_deref())?;
|
||||
// Annotations saved from the editor are a result like any other, and this
|
||||
// path does not run through the action pipeline, so it records itself.
|
||||
crate::history::record(&app, &[output.clone()]);
|
||||
Ok(output)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
|
|
@ -2004,7 +2033,9 @@ pub async fn save_text_near(
|
|||
) -> Result<String, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let output_dir = settings::files_output_dir(&app)?;
|
||||
save_text_near_in(&source, &text, suffix.as_deref(), output_dir.as_deref())
|
||||
let output = save_text_near_in(&source, &text, suffix.as_deref(), output_dir.as_deref())?;
|
||||
crate::history::record(&app, &[output.clone()]);
|
||||
Ok(output)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
|
|
@ -2085,6 +2116,32 @@ mod tests {
|
|||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn pixel_tools_read_system_only_image_formats() {
|
||||
let dir = scratch_dir();
|
||||
let input = dir.join("sample.png");
|
||||
sample_image(&input);
|
||||
let heic = dir.join("phone.heic");
|
||||
if system_convert(&input, &heic, "heic").is_err() {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
return;
|
||||
}
|
||||
|
||||
// The pixel tools used to fail here because the Rust decoder cannot read
|
||||
// HEIC. The result is a PNG, which is what its name now says it is.
|
||||
let rotated = rotate_file(&heic, None).unwrap();
|
||||
assert_eq!(
|
||||
rotated.extension().and_then(|value| value.to_str()),
|
||||
Some("png")
|
||||
);
|
||||
assert!(image::open(&rotated).is_ok());
|
||||
let half = resize_file(&heic, 0.5, None).unwrap();
|
||||
assert!(image::open(&half).is_ok());
|
||||
assert!(image::open(&half).unwrap().width() <= 16);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_output_directory_collects_results() {
|
||||
let dir = scratch_dir();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,300 @@
|
|||
//! The library of captures and processed files, kept in one place on disk.
|
||||
//!
|
||||
//! This used to be a `localStorage` list of eight paths, which meant every window
|
||||
//! had to remember to report its own results and a cleared webview cache threw the
|
||||
//! history away. The list now lives in the app data directory, is capped at a few
|
||||
//! hundred entries, drops files that no longer exist, and is written by Rust at the
|
||||
//! moment a result is produced — so a capture recorded by the tray, a conversion
|
||||
//! from the ring and a file received over the LAN all land in the same library
|
||||
//! without any window having to opt in.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::Mutex,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
/// Entries kept before the oldest unpinned ones fall off. Large enough to be a
|
||||
/// working history, small enough that the JSON file stays trivial to read.
|
||||
const CAPACITY: usize = 300;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HistoryEntry {
|
||||
pub path: String,
|
||||
/// "image" | "video" | "text" | "file", matching the editor's own kinds.
|
||||
pub kind: String,
|
||||
/// Milliseconds since the epoch, as the webview already reports them.
|
||||
pub at: i64,
|
||||
/// Pinned entries survive both the capacity limit and a missing file.
|
||||
#[serde(default)]
|
||||
pub pinned: bool,
|
||||
}
|
||||
|
||||
impl HistoryEntry {
|
||||
fn new(path: &str) -> Self {
|
||||
Self {
|
||||
path: path.to_string(),
|
||||
kind: crate::files::editor_kind(Path::new(path)).to_string(),
|
||||
at: chrono::Utc::now().timestamp_millis(),
|
||||
pinned: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct HistoryState {
|
||||
entries: Mutex<Vec<HistoryEntry>>,
|
||||
}
|
||||
|
||||
fn history_path(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
Ok(app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map_err(|error| error.to_string())?
|
||||
.join("history.json"))
|
||||
}
|
||||
|
||||
fn read(app: &AppHandle) -> Vec<HistoryEntry> {
|
||||
history_path(app)
|
||||
.ok()
|
||||
.and_then(|path| fs::read_to_string(path).ok())
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write(app: &AppHandle, entries: &[HistoryEntry]) -> Result<(), String> {
|
||||
let path = history_path(app)?;
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
}
|
||||
let contents = serde_json::to_vec_pretty(entries).map_err(|error| error.to_string())?;
|
||||
// One write, not a rename: this file is a cache of convenience, and a torn
|
||||
// write costs a history list rather than a user document.
|
||||
fs::write(&path, contents).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Entries with deleted files dropped and the list trimmed, pinned entries kept.
|
||||
fn tidy(mut entries: Vec<HistoryEntry>) -> Vec<HistoryEntry> {
|
||||
entries.retain(|entry| entry.pinned || Path::new(&entry.path).exists());
|
||||
entries.sort_by(|left, right| right.pinned.cmp(&left.pinned).then(right.at.cmp(&left.at)));
|
||||
if entries.len() > CAPACITY {
|
||||
let pinned = entries.iter().filter(|entry| entry.pinned).count();
|
||||
// Never evict a pinned row to make room; trim from the unpinned tail only.
|
||||
entries.truncate(CAPACITY.max(pinned));
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
fn snapshot(app: &AppHandle) -> Vec<HistoryEntry> {
|
||||
let state = app.state::<HistoryState>();
|
||||
let mut guard = state
|
||||
.entries
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if guard.is_empty() {
|
||||
*guard = tidy(read(app));
|
||||
}
|
||||
guard.clone()
|
||||
}
|
||||
|
||||
fn publish(app: &AppHandle, entries: Vec<HistoryEntry>) {
|
||||
let state = app.state::<HistoryState>();
|
||||
if let Ok(mut guard) = state.entries.lock() {
|
||||
*guard = entries.clone();
|
||||
}
|
||||
let _ = app.emit("history://changed", entries);
|
||||
}
|
||||
|
||||
/// Record files that just became available. Called by the result pipeline rather
|
||||
/// than by whichever window happens to be open.
|
||||
pub fn record(app: &AppHandle, paths: &[String]) {
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut entries = snapshot(app);
|
||||
for path in paths {
|
||||
if path.trim().is_empty() || !Path::new(path).exists() {
|
||||
continue;
|
||||
}
|
||||
entries.retain(|entry| entry.path != *path);
|
||||
entries.push(HistoryEntry::new(path));
|
||||
}
|
||||
let entries = tidy(entries);
|
||||
if let Err(error) = write(app, &entries) {
|
||||
eprintln!("Could not save the capture history: {error}");
|
||||
}
|
||||
publish(app, entries);
|
||||
}
|
||||
|
||||
/// Emit a finished file action *and* record it, so the two can never drift apart.
|
||||
pub fn publish_result(app: &AppHandle, outcome: crate::models::ActionOutcome) {
|
||||
record(app, &outcome.outputs);
|
||||
let _ = app.emit("app://file-result", outcome);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn history_list(app: AppHandle) -> Result<Vec<HistoryEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || Ok(snapshot(&app)))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn history_record(
|
||||
app: AppHandle,
|
||||
paths: Vec<String>,
|
||||
) -> Result<Vec<HistoryEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
record(&app, &paths);
|
||||
Ok(snapshot(&app))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn history_set_pinned(
|
||||
app: AppHandle,
|
||||
path: String,
|
||||
pinned: bool,
|
||||
) -> Result<Vec<HistoryEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let mut entries = snapshot(&app);
|
||||
for entry in entries.iter_mut() {
|
||||
if entry.path == path {
|
||||
entry.pinned = pinned;
|
||||
}
|
||||
}
|
||||
let entries = tidy(entries);
|
||||
write(&app, &entries)?;
|
||||
publish(&app, entries.clone());
|
||||
Ok(entries)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Forget the entry without touching the file on disk.
|
||||
#[tauri::command]
|
||||
pub async fn history_remove(app: AppHandle, path: String) -> Result<Vec<HistoryEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let mut entries = snapshot(&app);
|
||||
entries.retain(|entry| entry.path != path);
|
||||
write(&app, &entries)?;
|
||||
publish(&app, entries.clone());
|
||||
Ok(entries)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn history_clear(app: AppHandle) -> Result<Vec<HistoryEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
// Pinned rows survive a clear: the button promises an empty list, not an
|
||||
// abandoned set of favourites.
|
||||
let entries: Vec<HistoryEntry> = snapshot(&app)
|
||||
.into_iter()
|
||||
.filter(|entry| entry.pinned)
|
||||
.collect();
|
||||
write(&app, &entries)?;
|
||||
publish(&app, entries.clone());
|
||||
Ok(entries)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(path: &str, at: i64, pinned: bool) -> HistoryEntry {
|
||||
HistoryEntry {
|
||||
path: path.into(),
|
||||
kind: "image".into(),
|
||||
at,
|
||||
pinned,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_kind_follows_the_editor_classification() {
|
||||
assert_eq!(HistoryEntry::new("/x/a.png").kind, "image");
|
||||
assert_eq!(HistoryEntry::new("/x/a.mov").kind, "video");
|
||||
assert_eq!(HistoryEntry::new("/x/a.md").kind, "text");
|
||||
assert_eq!(HistoryEntry::new("/x/a.bin").kind, "file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_leaves_the_list() {
|
||||
let missing = format!("/nonexistent/shift-{}.png", std::process::id());
|
||||
let tidyed = tidy(vec![entry(&missing, 2, false)]);
|
||||
assert!(tidyed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_entry_outlives_its_file() {
|
||||
let missing = format!("/nonexistent/shift-{}.png", std::process::id());
|
||||
let tidyed = tidy(vec![entry(&missing, 2, true)]);
|
||||
assert_eq!(tidyed.len(), 1);
|
||||
}
|
||||
|
||||
/// A tidy pass only keeps paths that exist, so tests point every entry at the
|
||||
/// test binary itself and vary just the timestamp.
|
||||
fn real_path() -> String {
|
||||
std::env::current_exe()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_entry_comes_first() {
|
||||
let here = real_path();
|
||||
let tidyed = tidy(vec![
|
||||
entry(&here, 1, false),
|
||||
entry(&here, 5, false),
|
||||
entry(&here, 3, false),
|
||||
]);
|
||||
let times: Vec<i64> = tidyed.iter().map(|item| item.at).collect();
|
||||
assert_eq!(times, vec![5, 3, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_entries_sort_ahead_and_are_never_trimmed() {
|
||||
let here = real_path();
|
||||
let mut entries: Vec<HistoryEntry> = (0..CAPACITY + 40)
|
||||
.map(|index| entry(&here, index as i64, false))
|
||||
.collect();
|
||||
entries.push(entry(&here, 1, true));
|
||||
let tidyed = tidy(entries);
|
||||
assert!(tidyed[0].pinned, "pinned rows sort first");
|
||||
assert!(tidyed.len() <= CAPACITY + 1);
|
||||
assert!(tidyed.iter().any(|item| item.pinned));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_library_round_trips_through_json() {
|
||||
let entries = vec![
|
||||
entry("/tmp/a.png", 10, false),
|
||||
entry("/tmp/b.mov", 20, true),
|
||||
];
|
||||
let text = serde_json::to_string(&entries).unwrap();
|
||||
let parsed: Vec<HistoryEntry> = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(parsed.len(), 2);
|
||||
assert!(parsed[1].pinned);
|
||||
assert_eq!(parsed[0].at, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_file_without_pinned_still_parses() {
|
||||
let parsed: Vec<HistoryEntry> =
|
||||
serde_json::from_str(r#"[{"path":"/tmp/a.png","kind":"image","at":5}]"#).unwrap();
|
||||
assert!(!parsed[0].pinned, "a missing field defaults to unpinned");
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ mod capture;
|
|||
mod drag_bridge;
|
||||
mod editor;
|
||||
mod files;
|
||||
mod history;
|
||||
mod hotkeys;
|
||||
mod locale;
|
||||
mod markdown;
|
||||
|
|
@ -11,9 +12,11 @@ mod office;
|
|||
mod pdf;
|
||||
mod process;
|
||||
mod recording;
|
||||
mod result_card;
|
||||
mod runtime;
|
||||
mod settings;
|
||||
mod share;
|
||||
mod update;
|
||||
|
||||
use std::{
|
||||
process::Child,
|
||||
|
|
@ -172,18 +175,20 @@ fn tray_menu(app: &AppHandle, language: &str) -> tauri::Result<Menu<tauri::Wry>>
|
|||
let ocr = MenuItem::with_id(app, "ocr", titles.ocr, true, None::<&str>)?;
|
||||
let separator = PredefinedMenuItem::separator(app)?;
|
||||
let quit = MenuItem::with_id(app, "quit", titles.quit, true, Some("CmdOrCtrl+Q"))?;
|
||||
let menu = Menu::with_items(
|
||||
app,
|
||||
&[
|
||||
&open,
|
||||
&capture,
|
||||
&fullscreen,
|
||||
&record,
|
||||
&ocr,
|
||||
&separator,
|
||||
&quit,
|
||||
],
|
||||
)?;
|
||||
let mut items: Vec<&dyn tauri::menu::IsMenuItem<tauri::Wry>> =
|
||||
vec![&open, &capture, &fullscreen, &record, &ocr];
|
||||
// A known newer release gets its own row, so the update is reachable without
|
||||
// opening a window. It disappears again once the check reports "current".
|
||||
let update = match update::tray_title(app) {
|
||||
Some(title) => Some(MenuItem::with_id(app, "update", title, true, None::<&str>)?),
|
||||
None => None,
|
||||
};
|
||||
if let Some(update) = &update {
|
||||
items.push(update);
|
||||
}
|
||||
items.push(&separator);
|
||||
items.push(&quit);
|
||||
let menu = Menu::with_items(app, &items)?;
|
||||
Ok(menu)
|
||||
}
|
||||
|
||||
|
|
@ -220,6 +225,10 @@ fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
|
|||
show_main(app);
|
||||
let _ = app.emit("app://open-ocr", ());
|
||||
}
|
||||
"update" => {
|
||||
show_main(app);
|
||||
let _ = app.emit("app://open-updates", ());
|
||||
}
|
||||
"quit" => app.exit(0),
|
||||
_ => {}
|
||||
});
|
||||
|
|
@ -364,6 +373,8 @@ pub fn run() {
|
|||
.plugin(shortcut_plugin)
|
||||
.manage(AppState::default())
|
||||
.manage(share::ShareState::default())
|
||||
.manage(history::HistoryState::default())
|
||||
.manage(update::UpdateState::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
files::inspect_files,
|
||||
files::perform_file_action,
|
||||
|
|
@ -376,6 +387,11 @@ pub fn run() {
|
|||
files::render_pdf_pages,
|
||||
files::cleanup_pdf_pages,
|
||||
files::save_text_near,
|
||||
history::history_list,
|
||||
history::history_record,
|
||||
history::history_set_pinned,
|
||||
history::history_remove,
|
||||
history::history_clear,
|
||||
settings::get_app_settings,
|
||||
settings::set_output_directory,
|
||||
settings::set_file_output_mode,
|
||||
|
|
@ -385,7 +401,17 @@ pub fn run() {
|
|||
settings::set_autostart,
|
||||
settings::check_output_access,
|
||||
settings::set_language,
|
||||
settings::set_capture_after,
|
||||
settings::set_update_check_enabled,
|
||||
settings::set_setup_reviewed,
|
||||
settings::get_wedge_orders,
|
||||
settings::set_wedge_order,
|
||||
settings::reveal_output_directory,
|
||||
update::update_check,
|
||||
update::update_status,
|
||||
update::update_download,
|
||||
update::update_install,
|
||||
update::update_clear,
|
||||
settings::open_files_permission_settings,
|
||||
runtime::machine_info,
|
||||
runtime::install_runtime_component,
|
||||
|
|
@ -397,6 +423,7 @@ pub fn run() {
|
|||
capture::capture_fullscreen,
|
||||
capture::copy_file_to,
|
||||
capture::open_screen_recording_settings,
|
||||
recording::recording_capabilities,
|
||||
recording::start_recording,
|
||||
recording::stop_recording,
|
||||
recording::recording_status,
|
||||
|
|
@ -457,6 +484,7 @@ pub fn run() {
|
|||
register_shortcuts(app.handle())?;
|
||||
drag_bridge::spawn(app.handle());
|
||||
share::spawn(app.handle());
|
||||
update::spawn_startup_check(app.handle());
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
|
|
@ -530,12 +558,15 @@ mod tests {
|
|||
("drag_bridge.rs", include_str!("drag_bridge.rs")),
|
||||
("editor.rs", include_str!("editor.rs")),
|
||||
("files.rs", include_str!("files.rs")),
|
||||
("history.rs", include_str!("history.rs")),
|
||||
("hotkeys.rs", include_str!("hotkeys.rs")),
|
||||
("pdf.rs", include_str!("pdf.rs")),
|
||||
("recording.rs", include_str!("recording.rs")),
|
||||
("result_card.rs", include_str!("result_card.rs")),
|
||||
("runtime.rs", include_str!("runtime.rs")),
|
||||
("settings.rs", include_str!("settings.rs")),
|
||||
("share.rs", include_str!("share.rs")),
|
||||
("update.rs", include_str!("update.rs")),
|
||||
];
|
||||
for (name, source) in sources {
|
||||
// Tests may spawn freely; only shipped code needs the helper.
|
||||
|
|
|
|||
|
|
@ -103,6 +103,11 @@ pub fn preferred(stored: Option<&str>) -> &'static str {
|
|||
from_setting(stored).unwrap_or_else(system_language)
|
||||
}
|
||||
|
||||
/// The tray row that advertises a newer release, e.g. "Update available 0.2.0".
|
||||
pub fn update_available(language: &str, version: &str) -> String {
|
||||
format!("{}{}", tray_titles(language).update, version)
|
||||
}
|
||||
|
||||
/// Tray titles. Kept here rather than in the webview bundle because the tray has
|
||||
/// to be right before the first window has loaded.
|
||||
pub struct TrayTitles {
|
||||
|
|
@ -111,6 +116,8 @@ pub struct TrayTitles {
|
|||
pub fullscreen: &'static str,
|
||||
pub record: &'static str,
|
||||
pub ocr: &'static str,
|
||||
/// Suffix for the update row, which the caller formats with a version number.
|
||||
pub update: &'static str,
|
||||
pub quit: &'static str,
|
||||
}
|
||||
|
||||
|
|
@ -122,6 +129,7 @@ pub fn tray_titles(language: &str) -> TrayTitles {
|
|||
fullscreen: "全屏截图",
|
||||
record: "区域录屏",
|
||||
ocr: "识别图片文字…",
|
||||
update: "发现新版本 ",
|
||||
quit: "退出 Shift",
|
||||
}
|
||||
} else {
|
||||
|
|
@ -131,6 +139,7 @@ pub fn tray_titles(language: &str) -> TrayTitles {
|
|||
fullscreen: "Capture full screen",
|
||||
record: "Record area",
|
||||
ocr: "OCR an image…",
|
||||
update: "Update available ",
|
||||
quit: "Quit Shift",
|
||||
}
|
||||
}
|
||||
|
|
@ -140,6 +149,12 @@ pub fn tray_titles(language: &str) -> TrayTitles {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_update_row_carries_the_version() {
|
||||
assert_eq!(update_available(CHINESE, "0.2.0"), "发现新版本 0.2.0");
|
||||
assert_eq!(update_available(ENGLISH, "0.2.0"), "Update available 0.2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chinese_variants_all_select_chinese() {
|
||||
for candidate in ["zh", "zh-CN", "zh-Hans", "zh_TW", " ZH-Hant "] {
|
||||
|
|
|
|||
|
|
@ -79,18 +79,36 @@ pub struct EditorInfo {
|
|||
pub kind: String,
|
||||
}
|
||||
|
||||
/// What the capture overlay asks for when a recording starts.
|
||||
///
|
||||
/// The two switches are honest: `recording_capabilities` says which of them the
|
||||
/// current platform honours, and the overlay hides the rest, so a choice the backend
|
||||
/// would ignore can never be presented as applied.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RecordingOptions {
|
||||
/// Record audio alongside video.
|
||||
pub audio: bool,
|
||||
pub fps: u32,
|
||||
/// Requested frame rate, where the backend accepts one. `None` leaves the choice
|
||||
/// to the capture tool instead of inventing a number.
|
||||
pub fps: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for RecordingOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
audio: false,
|
||||
fps: 30,
|
||||
fps: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which recording switches this platform actually implements.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecordingCapabilities {
|
||||
/// Whether audio is captured with the video.
|
||||
pub audio: bool,
|
||||
/// Whether a frame-rate request is passed to the capture tool.
|
||||
pub fps: bool,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, ChildStdin, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
|
|
@ -14,7 +14,9 @@ use tauri::{AppHandle, Emitter, LogicalPosition, Manager, State};
|
|||
|
||||
use crate::{
|
||||
capture, editor,
|
||||
models::{ActionOutcome, NormalizedRect, RecordingInfo, RecordingOptions},
|
||||
models::{
|
||||
ActionOutcome, NormalizedRect, RecordingCapabilities, RecordingInfo, RecordingOptions,
|
||||
},
|
||||
settings, AppState,
|
||||
};
|
||||
|
||||
|
|
@ -23,6 +25,9 @@ pub struct RecordingSession {
|
|||
pub stdin: Option<ChildStdin>,
|
||||
pub output: PathBuf,
|
||||
pub started_at: i64,
|
||||
/// ffmpeg quits and finalizes the file when it is asked to on stdin; a Wayland
|
||||
/// recorder has no such console, so it only finalizes on a signal.
|
||||
pub stops_with_signal: bool,
|
||||
}
|
||||
|
||||
struct Region {
|
||||
|
|
@ -32,6 +37,19 @@ struct Region {
|
|||
height: f64,
|
||||
}
|
||||
|
||||
/// Region as an X11 geometry string, which is what `wf-recorder -g` expects.
|
||||
/// Only the Linux recorder calls it; the rest of the tree keeps it alive for the test.
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
fn x11_geometry(region: &Region) -> String {
|
||||
format!(
|
||||
"{}x{}+{}+{}",
|
||||
region.width.round() as u32,
|
||||
region.height.round() as u32,
|
||||
region.x.round() as i64,
|
||||
region.y.round() as i64,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn logical_region(
|
||||
app: &AppHandle,
|
||||
|
|
@ -79,6 +97,24 @@ fn physical_region(
|
|||
})
|
||||
}
|
||||
|
||||
/// Which recording switches this build actually honours.
|
||||
///
|
||||
/// `screencapture -v` has no frame-rate option, so macOS reports audio only. The
|
||||
/// ffmpeg backends take `-framerate` but have no audio input wired up, so Windows and
|
||||
/// Linux report frame rate only. The overlay reads this and hides whatever is a lie.
|
||||
pub fn capabilities() -> RecordingCapabilities {
|
||||
#[cfg(target_os = "macos")]
|
||||
return RecordingCapabilities {
|
||||
audio: true,
|
||||
fps: false,
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
return RecordingCapabilities {
|
||||
audio: false,
|
||||
fps: true,
|
||||
};
|
||||
}
|
||||
|
||||
fn recording_directory(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
settings::recording_dir(app)
|
||||
}
|
||||
|
|
@ -96,9 +132,10 @@ fn start_process(
|
|||
state: &AppState,
|
||||
rect: &NormalizedRect,
|
||||
options: &RecordingOptions,
|
||||
) -> Result<(Child, Option<ChildStdin>, PathBuf), String> {
|
||||
) -> Result<(Child, Option<ChildStdin>, PathBuf, bool), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// `screencapture -v` picks its own frame rate; there is nothing to pass.
|
||||
let _ = options.fps;
|
||||
let region = logical_region(app, state, rect)?;
|
||||
let output = output_path(app, "mov")?;
|
||||
|
|
@ -127,57 +164,80 @@ fn start_process(
|
|||
.map_err(|error| format!("Could not start screen recording: {error}"))?;
|
||||
let mut child = child;
|
||||
let stdin = child.stdin.take();
|
||||
Ok((child, stdin, output))
|
||||
Ok((child, stdin, output, true))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
// No audio input is wired into the ffmpeg grab yet; see `capabilities`.
|
||||
let _ = options.audio;
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// Under Wayland there is no root window to grab, so ffmpeg's x11grab would
|
||||
// record a black frame. wf-recorder talks to the same wlroots/PipeWire
|
||||
// compositor grim takes stills from, and finalizes on SIGINT.
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
if let Some(recorder) = crate::files::resolve_tool("wf-recorder") {
|
||||
let geometry = x11_geometry(®ion);
|
||||
let mut wayland = crate::process::command(recorder);
|
||||
wayland.args(["-f", &output, "-g", &geometry]);
|
||||
if let Some(fps) = options.fps {
|
||||
wayland.args(["-r", &fps.to_string()]);
|
||||
}
|
||||
let child = wayland
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not start wf-recorder: {error}"))?;
|
||||
return Ok((child, None, output, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ffmpeg = crate::files::resolve_tool("ffmpeg")
|
||||
.ok_or_else(|| "Screen recording needs ffmpeg on Windows and Linux.".to_string())?;
|
||||
let region = physical_region(app, state, rect)?;
|
||||
let output = output_path(app, "mp4")?;
|
||||
let mut command = crate::process::command(ffmpeg);
|
||||
let size = format!(
|
||||
"{}x{}",
|
||||
region.width.round() as u32,
|
||||
region.height.round() as u32
|
||||
);
|
||||
// `-framerate` is an input option for both grabbers, so it is part of the
|
||||
// input argument list rather than a separate flag after `-i`.
|
||||
let framerate = options
|
||||
.fps
|
||||
.map(|fps| vec!["-framerate".to_string(), fps.to_string()])
|
||||
.unwrap_or_default();
|
||||
#[cfg(target_os = "windows")]
|
||||
command.args([
|
||||
"-y",
|
||||
"-f",
|
||||
"gdigrab",
|
||||
"-framerate",
|
||||
&options.fps.to_string(),
|
||||
"-offset_x",
|
||||
&(region.x.round() as i64).to_string(),
|
||||
"-offset_y",
|
||||
&(region.y.round() as i64).to_string(),
|
||||
"-video_size",
|
||||
&format!(
|
||||
"{}x{}",
|
||||
region.width.round() as u32,
|
||||
region.height.round() as u32
|
||||
),
|
||||
"-i",
|
||||
"desktop",
|
||||
]);
|
||||
{
|
||||
let source = region.x.round() as i64;
|
||||
let top = region.y.round() as i64;
|
||||
command.args(["-y", "-f", "gdigrab"]);
|
||||
command.args(&framerate);
|
||||
command.args([
|
||||
"-offset_x",
|
||||
&source.to_string(),
|
||||
"-offset_y",
|
||||
&top.to_string(),
|
||||
"-video_size",
|
||||
&size,
|
||||
"-i",
|
||||
"desktop",
|
||||
]);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
command.args([
|
||||
"-y",
|
||||
"-f",
|
||||
"x11grab",
|
||||
"-framerate",
|
||||
&options.fps.to_string(),
|
||||
"-video_size",
|
||||
&format!(
|
||||
"{}x{}",
|
||||
region.width.round() as u32,
|
||||
region.height.round() as u32
|
||||
),
|
||||
"-i",
|
||||
&format!(
|
||||
{
|
||||
let origin = format!(
|
||||
":0.0+{},{}",
|
||||
region.x.round() as i64,
|
||||
region.y.round() as i64
|
||||
),
|
||||
]);
|
||||
);
|
||||
command.args(["-y", "-f", "x11grab"]);
|
||||
command.args(&framerate);
|
||||
command.args(["-video_size", &size, "-i", &origin]);
|
||||
}
|
||||
command.args([
|
||||
"-c:v",
|
||||
"libx264",
|
||||
|
|
@ -194,7 +254,7 @@ fn start_process(
|
|||
.spawn()
|
||||
.map_err(|error| format!("Could not start ffmpeg: {error}"))?;
|
||||
let stdin = child.stdin.take();
|
||||
return Ok((child, stdin, output));
|
||||
return Ok((child, stdin, output, false));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -226,7 +286,7 @@ pub fn start(
|
|||
{
|
||||
return Err("A recording is already in progress.".into());
|
||||
}
|
||||
let (mut child, stdin, output) = start_process(app, state, rect, &options)?;
|
||||
let (mut child, stdin, output, stops_with_signal) = start_process(app, state, rect, &options)?;
|
||||
ensure_capture_started(&mut child, &output)?;
|
||||
let started_at = chrono::Utc::now().timestamp_millis();
|
||||
let info = RecordingInfo {
|
||||
|
|
@ -238,6 +298,7 @@ pub fn start(
|
|||
stdin,
|
||||
output: output.clone(),
|
||||
started_at,
|
||||
stops_with_signal,
|
||||
});
|
||||
capture::dismiss_capture(app);
|
||||
|
||||
|
|
@ -263,6 +324,14 @@ fn stop_process(session: &mut RecordingSession) -> Result<(), String> {
|
|||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
#[cfg(target_os = "linux")]
|
||||
if session.stops_with_signal {
|
||||
let _ = unsafe { libc::kill(session.child.id() as libc::pid_t, libc::SIGINT) };
|
||||
} else if let Some(stdin) = session.stdin.as_mut() {
|
||||
let _ = stdin.write_all(b"q\n");
|
||||
let _ = stdin.flush();
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
if let Some(stdin) = session.stdin.as_mut() {
|
||||
let _ = stdin.write_all(b"q\n");
|
||||
let _ = stdin.flush();
|
||||
|
|
@ -324,9 +393,18 @@ pub fn stop(app: &AppHandle, state: &AppState) -> Result<Option<RecordingInfo>,
|
|||
if let Some(window) = app.get_webview_window("recorder") {
|
||||
let _ = window.hide();
|
||||
}
|
||||
editor::show_recording_editor(app, &info)?;
|
||||
let _ = app.emit(
|
||||
"app://file-result",
|
||||
match crate::settings::load(app).capture_after {
|
||||
crate::settings::CaptureAfter::Editor => {
|
||||
editor::show_recording_editor(app, &info)?;
|
||||
}
|
||||
crate::settings::CaptureAfter::Card => {
|
||||
if crate::result_card::show(app, Path::new(&info.output)).is_err() {
|
||||
editor::show_recording_editor(app, &info)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::history::publish_result(
|
||||
app,
|
||||
ActionOutcome {
|
||||
outputs: vec![info.output.clone()],
|
||||
message: "Recording saved.".into(),
|
||||
|
|
@ -347,6 +425,12 @@ pub fn stop_on_exit(app: &AppHandle, state: &AppState) {
|
|||
/// Starting a recording spawns a capture process and stopping one waits for the
|
||||
/// encoder to finalize the file (up to three seconds), so neither belongs on the
|
||||
/// main thread.
|
||||
/// The recording switches the overlay is allowed to offer on this platform.
|
||||
#[tauri::command]
|
||||
pub fn recording_capabilities() -> RecordingCapabilities {
|
||||
capabilities()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn start_recording(
|
||||
app: AppHandle,
|
||||
|
|
@ -389,6 +473,17 @@ mod tests {
|
|||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn wayland_geometry_uses_the_x11_shape() {
|
||||
let region = Region {
|
||||
x: 12.6,
|
||||
y: 30.4,
|
||||
width: 800.5,
|
||||
height: 600.2,
|
||||
};
|
||||
assert_eq!(x11_geometry(®ion), "801x600+13+30");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_recording_process_cleanly() {
|
||||
let child = Command::new("sleep")
|
||||
|
|
@ -403,6 +498,7 @@ mod tests {
|
|||
stdin: None,
|
||||
output: std::env::temp_dir().join("shift-recording-test.mov"),
|
||||
started_at: 0,
|
||||
stops_with_signal: false,
|
||||
};
|
||||
let started = Instant::now();
|
||||
stop_process(&mut session).unwrap();
|
||||
|
|
@ -435,6 +531,7 @@ mod tests {
|
|||
stdin,
|
||||
output: output.clone(),
|
||||
started_at: 0,
|
||||
stops_with_signal: true,
|
||||
};
|
||||
stop_process(&mut session).unwrap();
|
||||
let metadata = fs::metadata(&output).unwrap();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,147 @@
|
|||
//! The floating card that appears the moment a capture lands.
|
||||
//!
|
||||
//! CleanShot's result card is the reason its screenshots end up in the right
|
||||
//! place: the four things a user does next, Copy, Pin, Edit and Send, are on the
|
||||
//! card and one click away, so the shot does not have to be re-found in a folder.
|
||||
//! The card is a short-lived borderless window near the corner of the display the
|
||||
//! capture came from, and it closes itself, so ignoring it costs nothing.
|
||||
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};
|
||||
|
||||
/// How long an untouched card stays up. Long enough to act, short enough that a
|
||||
/// stack of screenshots does not litter the screen.
|
||||
const LIFETIME: Duration = Duration::from_secs(8);
|
||||
const WIDTH: f64 = 392.0;
|
||||
const HEIGHT: f64 = 108.0;
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct CardInfo {
|
||||
path: String,
|
||||
name: String,
|
||||
/// "image" | "video", which decides whether a thumbnail or an icon is shown.
|
||||
kind: &'static str,
|
||||
/// Milliseconds before the card hides itself, so the countdown cannot disagree
|
||||
/// with the window's own timer.
|
||||
ttl_ms: u64,
|
||||
}
|
||||
|
||||
fn kind_of(path: &Path) -> &'static str {
|
||||
let extension = path
|
||||
.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
if matches!(
|
||||
extension.as_str(),
|
||||
"mov" | "mp4" | "m4v" | "avi" | "mkv" | "webm"
|
||||
) {
|
||||
"video"
|
||||
} else {
|
||||
"image"
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(info: &CardInfo) -> Result<String, String> {
|
||||
let bytes = serde_json::to_vec(info).map_err(|error| error.to_string())?;
|
||||
Ok(bytes
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>())
|
||||
}
|
||||
|
||||
/// Show the card for one saved capture. A failure here must never swallow the
|
||||
/// capture, so callers ignore the result.
|
||||
pub fn show(app: &AppHandle, path: &Path) -> Result<(), String> {
|
||||
let info = CardInfo {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: path
|
||||
.file_name()
|
||||
.and_then(|value| value.to_str())
|
||||
.unwrap_or("Shift")
|
||||
.to_string(),
|
||||
kind: kind_of(path),
|
||||
ttl_ms: LIFETIME.as_millis() as u64,
|
||||
};
|
||||
let label = format!("result-{}", uuid::Uuid::new_v4().simple());
|
||||
let mut builder = WebviewWindowBuilder::new(
|
||||
app,
|
||||
&label,
|
||||
WebviewUrl::App(format!("index.html?view=result-card&info={}", encode(&info)?).into()),
|
||||
)
|
||||
.title("Shift")
|
||||
.inner_size(WIDTH, HEIGHT)
|
||||
.resizable(false)
|
||||
.maximizable(false)
|
||||
.minimizable(false)
|
||||
.closable(false)
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.always_on_top(true)
|
||||
.skip_taskbar(true)
|
||||
.shadow(true)
|
||||
.visible(false)
|
||||
.focused(false);
|
||||
|
||||
// Bottom-right of the display the capture came from, clear of the menu bar.
|
||||
if let Ok(Some(monitor)) = app.primary_monitor() {
|
||||
let size = monitor.size().to_logical::<f64>(monitor.scale_factor());
|
||||
builder = builder.position(
|
||||
(size.width - WIDTH - 26.0).max(12.0),
|
||||
(size.height - HEIGHT - 26.0).max(12.0),
|
||||
);
|
||||
}
|
||||
let window = builder.build().map_err(|error| error.to_string())?;
|
||||
let _ = window.show();
|
||||
|
||||
let handle = app.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(LIFETIME);
|
||||
if let Some(window) = handle.get_webview_window(&label) {
|
||||
// Only close if the card is still up; the user may have moved on to the
|
||||
// editor, which already took the window down.
|
||||
if window.is_visible().unwrap_or(false) {
|
||||
let _ = window.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recordings_are_distinguished_from_screenshots() {
|
||||
assert_eq!(kind_of(Path::new("/x/Shift Recording.mov")), "video");
|
||||
assert_eq!(kind_of(Path::new("/x/clip.mp4")), "video");
|
||||
assert_eq!(kind_of(Path::new("/x/shot.png")), "image");
|
||||
assert_eq!(kind_of(Path::new("/x/no-extension")), "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_payload_survives_a_url_round_trip() {
|
||||
let info = CardInfo {
|
||||
path: "/Users/x/图片/Shift 截图.png".into(),
|
||||
name: "Shift 截图.png".into(),
|
||||
kind: "image",
|
||||
ttl_ms: 8000,
|
||||
};
|
||||
let encoded = encode(&info).unwrap();
|
||||
assert!(
|
||||
encoded.chars().all(|c| c.is_ascii_hexdigit()),
|
||||
"the query string must be URL-safe"
|
||||
);
|
||||
let bytes: Vec<u8> = (0..encoded.len())
|
||||
.step_by(2)
|
||||
.map(|index| u8::from_str_radix(&encoded[index..index + 2], 16).unwrap())
|
||||
.collect();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains("Shift"), "{text}");
|
||||
assert!(text.contains("截图"), "non-ascii paths must survive");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,12 @@
|
|||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::{Mutex, MutexGuard, OnceLock},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Manager};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
/// The switches only need their own value back. Rebuilding the full settings
|
||||
/// snapshot probes the login item and creates three folders, which can block on
|
||||
|
|
@ -24,6 +25,16 @@ pub struct SwitchUpdate {
|
|||
pub autostart: Option<bool>,
|
||||
}
|
||||
|
||||
/// What happens the instant a capture is saved. The card keeps the shot out of the
|
||||
/// way but one click from Copy / Pin / Edit / Send; the editor opens it directly.
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CaptureAfter {
|
||||
#[default]
|
||||
Card,
|
||||
Editor,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FileOutputMode {
|
||||
|
|
@ -48,6 +59,19 @@ pub struct AppSettings {
|
|||
pub autostart: bool,
|
||||
/// UI language, "" until the user picks one. Unset follows the system.
|
||||
pub language: String,
|
||||
/// Card or editor, chosen right after a screenshot or recording is written.
|
||||
pub capture_after: CaptureAfter,
|
||||
/// Ask the git release branch for a newer build once a day.
|
||||
pub update_check_enabled: bool,
|
||||
/// Last startup probe as a unix day, so the daily check survives restarts.
|
||||
pub last_update_check_day: i64,
|
||||
/// Custom wedge order per file kind and ring, keyed `"<kind>/<ring>"`. The ring
|
||||
/// only ever rearranges the wedges it already offers, so this map can never
|
||||
/// invent an action; see `src/lib/radialOrder.ts`.
|
||||
pub wedge_orders: HashMap<String, Vec<String>>,
|
||||
/// True once the guided first-run checks have been shown or dismissed. Stored
|
||||
/// with the other settings so a second copy on the same account does not nag.
|
||||
pub setup_reviewed: bool,
|
||||
}
|
||||
|
||||
impl Default for AppSettings {
|
||||
|
|
@ -62,6 +86,11 @@ impl Default for AppSettings {
|
|||
share_enabled: true,
|
||||
autostart: false,
|
||||
language: String::new(),
|
||||
capture_after: CaptureAfter::default(),
|
||||
update_check_enabled: true,
|
||||
last_update_check_day: 0,
|
||||
wedge_orders: HashMap::new(),
|
||||
setup_reviewed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -78,6 +107,11 @@ pub struct SettingsSnapshot {
|
|||
pub share_enabled: bool,
|
||||
pub autostart: bool,
|
||||
pub language: String,
|
||||
pub capture_after: CaptureAfter,
|
||||
pub update_check_enabled: bool,
|
||||
pub update_feed_url: String,
|
||||
pub wedge_orders: HashMap<String, Vec<String>>,
|
||||
pub setup_reviewed: bool,
|
||||
pub default_file_output_dir: String,
|
||||
pub default_screenshot_dir: String,
|
||||
pub default_recording_dir: String,
|
||||
|
|
@ -265,6 +299,11 @@ pub fn snapshot(app: &AppHandle) -> Result<SettingsSnapshot, String> {
|
|||
// Report what the OS actually has registered, not what we last wrote.
|
||||
autostart: crate::autostart::is_enabled(),
|
||||
language: settings.language.clone(),
|
||||
capture_after: settings.capture_after,
|
||||
update_check_enabled: settings.update_check_enabled,
|
||||
update_feed_url: crate::update::manifest_url(),
|
||||
wedge_orders: settings.wedge_orders.clone(),
|
||||
setup_reviewed: settings.setup_reviewed,
|
||||
default_file_output_dir: default_directory(app, "files")?
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
|
|
@ -327,6 +366,154 @@ pub fn test_output_access(app: &AppHandle) -> Result<Vec<WriteCheck>, String> {
|
|||
.collect())
|
||||
}
|
||||
|
||||
fn unix_day() -> i64 {
|
||||
chrono::Utc::now().timestamp() / 86_400
|
||||
}
|
||||
|
||||
/// File kinds and rings a saved wedge order may name. Mirrors `ORDERABLE_KINDS`
|
||||
/// and `RadialRing` in `src/lib/radialOrder.ts`; anything else is rejected so a
|
||||
/// stale or hand-edited settings.json cannot grow entries the UI never reads.
|
||||
const WEDGE_ORDER_KINDS: [&str; 8] = [
|
||||
"image",
|
||||
"video",
|
||||
"audio",
|
||||
"pdf",
|
||||
"document",
|
||||
"presentation",
|
||||
"spreadsheet",
|
||||
"other",
|
||||
];
|
||||
const WEDGE_ORDER_RINGS: [&str; 2] = ["actions", "tools"];
|
||||
|
||||
/// Whether `"<kind>/<ring>"` names a ring the reorder screen offers. The format
|
||||
/// ring is catalogue-driven rather than a fixed list, so it has no preset.
|
||||
fn is_wedge_order_key(key: &str) -> bool {
|
||||
match key.split_once('/') {
|
||||
Some((kind, ring)) => {
|
||||
WEDGE_ORDER_KINDS.contains(&kind) && WEDGE_ORDER_RINGS.contains(&ring)
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop blank and repeated ids, keeping first appearance. The ring ignores ids it
|
||||
/// does not offer, so no further validation is needed.
|
||||
fn normalize_wedge_order(order: &[String]) -> Vec<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
order
|
||||
.iter()
|
||||
.map(|id| id.trim())
|
||||
.filter(|id| !id.is_empty())
|
||||
.filter(|id| seen.insert((*id).to_string()))
|
||||
.map(|id| id.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the daily startup probe may run. The day counter is stored rather than
|
||||
/// an instant so a restart cannot spend the day's check again.
|
||||
pub fn update_check_due(app: &AppHandle, interval: std::time::Duration) -> bool {
|
||||
let settings = load(app);
|
||||
let elapsed_days = unix_day().saturating_sub(settings.last_update_check_day);
|
||||
elapsed_days >= (interval.as_secs() / 86_400).max(1) as i64
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_capture_after(
|
||||
app: AppHandle,
|
||||
after: CaptureAfter,
|
||||
) -> Result<SettingsSnapshot, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.capture_after = after;
|
||||
Ok(())
|
||||
})?;
|
||||
snapshot(&app)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Close the guided first-run flow. The checks themselves are re-runnable from
|
||||
/// Settings, so dismissing the flow loses nothing.
|
||||
#[tauri::command]
|
||||
pub async fn set_setup_reviewed(app: AppHandle, reviewed: bool) -> Result<bool, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.setup_reviewed = reviewed;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(reviewed)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_update_check_enabled(
|
||||
app: AppHandle,
|
||||
enabled: bool,
|
||||
) -> Result<SwitchState, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.update_check_enabled = enabled;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(SwitchState { enabled })
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// The saved orders on their own. The radial window reads this on startup instead
|
||||
/// of a full snapshot, which would probe the output folders on every launch.
|
||||
#[tauri::command]
|
||||
pub async fn get_wedge_orders(app: AppHandle) -> Result<HashMap<String, Vec<String>>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || Ok(load(&app).wedge_orders))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Store the wedge order for one ring of one file kind. An empty list restores the
|
||||
/// built-in order, so "reset" needs no separate flag. The radial window listens for
|
||||
/// the broadcast so a change shows up in the next gesture without a restart.
|
||||
#[tauri::command]
|
||||
pub async fn set_wedge_order(
|
||||
app: AppHandle,
|
||||
kind: String,
|
||||
ring: String,
|
||||
order: Vec<String>,
|
||||
) -> Result<SettingsSnapshot, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let key = format!("{kind}/{ring}");
|
||||
if !is_wedge_order_key(&key) {
|
||||
return Err(format!("Unknown radial ring: {key}"));
|
||||
}
|
||||
let cleaned = normalize_wedge_order(&order);
|
||||
update_settings(&app, |settings| {
|
||||
if cleaned.is_empty() {
|
||||
settings.wedge_orders.remove(&key);
|
||||
} else {
|
||||
settings.wedge_orders.insert(key, cleaned);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let orders = load(&app).wedge_orders;
|
||||
let _ = app.emit("settings://wedge-orders", orders);
|
||||
snapshot(&app)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Stamp the daily probe so the next launch waits for the interval instead of
|
||||
/// reaching the network again.
|
||||
pub fn note_update_check(app: &AppHandle) {
|
||||
let _ = update_settings(app, |settings| {
|
||||
settings.last_update_check_day = unix_day();
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
// These commands run off the main thread: every one of them touches the disk
|
||||
// (settings.json, output-directory probes) and one slow folder — a cloud-synced
|
||||
// or network volume — would otherwise freeze the whole app behind a toggle.
|
||||
|
|
@ -529,6 +716,18 @@ mod tests {
|
|||
assert!(settings.share_enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setup_review_flag_starts_unsettled() {
|
||||
// A settings file written before the guided flow existed has no field, and
|
||||
// `#[serde(default)]` means it reads as "not reviewed yet" — so the checks
|
||||
// are shown once after an upgrade rather than silently skipped.
|
||||
let older = r#"{"fileOutputMode":"alongside","autoReveal":true,"language":"en"}"#;
|
||||
let restored: AppSettings = serde_json::from_str(older).unwrap();
|
||||
assert!(!restored.setup_reviewed);
|
||||
assert!(restored.auto_reveal);
|
||||
assert!(!AppSettings::default().setup_reviewed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_mode_serializes_for_frontend() {
|
||||
assert_eq!(
|
||||
|
|
@ -559,4 +758,22 @@ mod tests {
|
|||
assert!(directory.is_dir());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wedge_orders_are_limited_to_the_rings_the_ui_offers() {
|
||||
assert!(is_wedge_order_key("image/tools"));
|
||||
assert!(is_wedge_order_key("spreadsheet/actions"));
|
||||
assert!(is_wedge_order_key("other/tools"));
|
||||
// The format ring follows the catalogue, and an unknown kind is a typo.
|
||||
assert!(!is_wedge_order_key("image/formats"));
|
||||
assert!(!is_wedge_order_key("archive/tools"));
|
||||
assert!(!is_wedge_order_key("image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wedge_orders_drop_blanks_and_duplicates_in_order() {
|
||||
let cleaned =
|
||||
normalize_wedge_order(&[" crop ".into(), "crop".into(), String::new(), "ocr".into()]);
|
||||
assert_eq!(cleaned, vec!["crop".to_string(), "ocr".to_string()]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -960,7 +960,8 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
|
|||
path: Some(path.clone()),
|
||||
},
|
||||
);
|
||||
// Reuse the existing result pipeline so received files land in "Recent".
|
||||
// Reuse the result pipeline so received files land in the history library.
|
||||
crate::history::record(app, &[path.clone()]);
|
||||
let _ = app.emit(
|
||||
"app://file-result",
|
||||
serde_json::json!({ "outputs": [path], "message": name }),
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Shift",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"identifier": "app.nex.shift",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { MainWindow } from "./components/MainWindow";
|
|||
import { PinnedImage } from "./components/PinnedImage";
|
||||
import { RadialMenu } from "./components/RadialMenu";
|
||||
import { RecorderHud } from "./components/RecorderHud";
|
||||
import { ResultCard } from "./components/ResultCard";
|
||||
import { ShareNotice } from "./components/ShareNotice";
|
||||
import type { View } from "./types";
|
||||
|
||||
|
|
@ -15,6 +16,7 @@ function resolveView(): View {
|
|||
value === "recorder" ||
|
||||
value === "editor" ||
|
||||
value === "pin" ||
|
||||
value === "result-card" ||
|
||||
value === "share-notice"
|
||||
) {
|
||||
return value;
|
||||
|
|
@ -37,6 +39,8 @@ export default function App() {
|
|||
return <Editor />;
|
||||
case "pin":
|
||||
return <PinnedImage />;
|
||||
case "result-card":
|
||||
return <ResultCard />;
|
||||
case "share-notice":
|
||||
return <ShareNotice />;
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
import { convertFileSrc, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Check, LoaderCircle, Mic, MicOff, ScanLine, Square, X } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Check, Gauge, LoaderCircle, Mic, MicOff, ScanLine, Square, X } from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { IS_MAC, normalizeSelection } from "../lib/utils";
|
||||
import type { CaptureSession } from "../types";
|
||||
import { normalizeSelection } from "../lib/utils";
|
||||
import type { CaptureSession, RecordingCapabilities } from "../types";
|
||||
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/** Choices the frame-rate chip cycles through, low to high. */
|
||||
const FRAME_RATES = [15, 24, 30];
|
||||
|
||||
export function CaptureOverlay() {
|
||||
const { t } = useI18n();
|
||||
const [session, setSession] = useState<CaptureSession | null>(null);
|
||||
|
|
@ -21,7 +24,19 @@ export function CaptureOverlay() {
|
|||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [audio, setAudio] = useState(false);
|
||||
// Which recording switches this platform actually implements. Offering a control the
|
||||
// backend ignores would promise something the file cannot deliver, so the toolbar
|
||||
// only renders what the platform reports.
|
||||
const [capabilities, setCapabilities] = useState<RecordingCapabilities>({
|
||||
audio: true,
|
||||
fps: false,
|
||||
});
|
||||
// Frame rate is only sent where the capture backend accepts one, so this is a real
|
||||
// request rather than a number that gets dropped on the floor.
|
||||
const [fps, setFps] = useState(30);
|
||||
const stageRef = useRef<HTMLDivElement>(null);
|
||||
const toolbarRef = useRef<HTMLDivElement>(null);
|
||||
const [toolbarWidth, setToolbarWidth] = useState(260);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTauri()) {
|
||||
|
|
@ -41,6 +56,7 @@ export function CaptureOverlay() {
|
|||
void api.getCaptureSession().then((next) => {
|
||||
if (next) setSession(next);
|
||||
});
|
||||
void api.recordingCapabilities().then(setCapabilities).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -94,7 +110,12 @@ export function CaptureOverlay() {
|
|||
setStatus(t("processing"));
|
||||
try {
|
||||
if (session?.mode === "recording") {
|
||||
await api.startRecording(selection.normalized, { audio, fps: 30 });
|
||||
// Only the switches this platform honours are sent, so nothing in the
|
||||
// toolbar can promise a recording option the backend would drop.
|
||||
await api.startRecording(selection.normalized, {
|
||||
audio: capabilities.audio ? audio : false,
|
||||
...(capabilities.fps ? { fps } : {}),
|
||||
});
|
||||
} else {
|
||||
await api.captureCrop(selection.normalized);
|
||||
}
|
||||
|
|
@ -114,6 +135,14 @@ export function CaptureOverlay() {
|
|||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const node = toolbarRef.current;
|
||||
if (!node) return;
|
||||
// Keep the measured width so the clamping below centres the toolbar wherever the
|
||||
// selection sits, without hard-coding how many chips the platform shows.
|
||||
setToolbarWidth((current) => (current === node.offsetWidth ? current : node.offsetWidth));
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
return <div className="capture-loading" />;
|
||||
}
|
||||
|
|
@ -136,8 +165,8 @@ export function CaptureOverlay() {
|
|||
: 0;
|
||||
const toolbarLeft = selection
|
||||
? Math.min(
|
||||
Math.max(12, selection.left + selection.width / 2 - 130),
|
||||
Math.max(12, window.innerWidth - 272),
|
||||
Math.max(12, selection.left + selection.width / 2 - toolbarWidth / 2),
|
||||
Math.max(12, window.innerWidth - toolbarWidth - 12),
|
||||
)
|
||||
: 0;
|
||||
|
||||
|
|
@ -187,6 +216,7 @@ export function CaptureOverlay() {
|
|||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref={toolbarRef}
|
||||
className="capture-toolbar"
|
||||
style={{ top: toolbarTop, left: toolbarLeft }}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
|
|
@ -194,7 +224,7 @@ export function CaptureOverlay() {
|
|||
>
|
||||
{session.mode === "recording" ? (
|
||||
<>
|
||||
{IS_MAC ? (
|
||||
{capabilities.audio ? (
|
||||
<button
|
||||
className={`capture-tool ${audio ? "is-selected" : ""}`}
|
||||
onClick={() => setAudio((value) => !value)}
|
||||
|
|
@ -203,6 +233,22 @@ export function CaptureOverlay() {
|
|||
{audio ? <Mic size={17} /> : <MicOff size={17} />}
|
||||
</button>
|
||||
) : null}
|
||||
{capabilities.fps ? (
|
||||
<button
|
||||
className="capture-tool capture-fps"
|
||||
onClick={() =>
|
||||
setFps(
|
||||
FRAME_RATES[
|
||||
(FRAME_RATES.indexOf(fps) + 1) % FRAME_RATES.length
|
||||
] ?? 30,
|
||||
)
|
||||
}
|
||||
title={t("frameRate")}
|
||||
>
|
||||
<Gauge size={15} />
|
||||
{fps}
|
||||
</button>
|
||||
) : null}
|
||||
<button className="capture-tool capture-record" onClick={() => void confirm()}>
|
||||
<Square size={14} fill="currentColor" />
|
||||
{t("startRecording")}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ import { useEffect, useRef, useState } from "react";
|
|||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { recognizeImage } from "../lib/ocr";
|
||||
import { basename, dirname, extensionOf, IS_MAC, rememberRecent } from "../lib/utils";
|
||||
import { basename, dirname, extensionOf, IS_MAC } from "../lib/utils";
|
||||
import { history } from "../lib/history";
|
||||
import type { EditorInfo } from "../types";
|
||||
import { ImageAnnotator } from "./ImageAnnotator";
|
||||
|
||||
|
|
@ -45,11 +46,9 @@ export function Editor() {
|
|||
setOcrProgress(0);
|
||||
setOcrStatus("");
|
||||
setTextContent("");
|
||||
rememberRecent({
|
||||
path: next.path,
|
||||
kind: next.kind,
|
||||
at: Date.now(),
|
||||
});
|
||||
// Anything opened for editing belongs in the library. Rust assigns the kind
|
||||
// and timestamp, so the editor does not classify the file a second time.
|
||||
void history.record([next.path]).catch(() => undefined);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -3,8 +3,11 @@ import { isTauri } from "@tauri-apps/api/core";
|
|||
import {
|
||||
ArrowUpRight,
|
||||
Check,
|
||||
CircleCheck,
|
||||
CircleX,
|
||||
Copy,
|
||||
Crop,
|
||||
Droplets,
|
||||
EyeOff,
|
||||
Grid3X3,
|
||||
Highlighter,
|
||||
|
|
@ -14,6 +17,7 @@ import {
|
|||
Save,
|
||||
Scissors,
|
||||
Square,
|
||||
Star,
|
||||
Type,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
|
|
@ -26,10 +30,15 @@ type Tool =
|
|||
| "arrow"
|
||||
| "highlight"
|
||||
| "redact"
|
||||
| "blur"
|
||||
| "pixelate"
|
||||
| "number"
|
||||
| "crop"
|
||||
| "text";
|
||||
| "text"
|
||||
| "stamp";
|
||||
|
||||
/// Stamps are vector glyphs so they stay sharp at any canvas resolution.
|
||||
export type Stamp = "check" | "cross" | "star";
|
||||
|
||||
interface Annotation {
|
||||
tool: Tool;
|
||||
|
|
@ -39,6 +48,7 @@ interface Annotation {
|
|||
y2: number;
|
||||
text?: string;
|
||||
number?: number;
|
||||
stamp?: Stamp;
|
||||
}
|
||||
|
||||
interface Point {
|
||||
|
|
@ -56,6 +66,96 @@ interface Props {
|
|||
onSaved: (path: string) => void;
|
||||
}
|
||||
|
||||
/// Soften a region by downscaling it and painting it back blurred. Unlike
|
||||
/// pixelate, which is deliberately blocky, this keeps the shapes readable while
|
||||
/// removing detail, and it is baked into the output rather than a translucent
|
||||
/// overlay, so a blurred area cannot be recovered from the saved PNG.
|
||||
export function drawBlur(
|
||||
context: CanvasRenderingContext2D,
|
||||
left: number,
|
||||
top: number,
|
||||
boxWidth: number,
|
||||
boxHeight: number,
|
||||
) {
|
||||
const source = document.createElement("canvas");
|
||||
source.width = Math.max(1, Math.round(boxWidth));
|
||||
source.height = Math.max(1, Math.round(boxHeight));
|
||||
const sourceContext = source.getContext("2d");
|
||||
if (!sourceContext) return;
|
||||
sourceContext.drawImage(context.canvas, left, top, boxWidth, boxHeight, 0, 0, source.width, source.height);
|
||||
|
||||
const factor = 10;
|
||||
const small = document.createElement("canvas");
|
||||
small.width = Math.max(1, Math.round(source.width / factor));
|
||||
small.height = Math.max(1, Math.round(source.height / factor));
|
||||
const smallContext = small.getContext("2d");
|
||||
if (!smallContext) return;
|
||||
smallContext.imageSmoothingEnabled = true;
|
||||
smallContext.drawImage(source, 0, 0, small.width, small.height);
|
||||
|
||||
context.save();
|
||||
context.beginPath();
|
||||
context.rect(left, top, boxWidth, boxHeight);
|
||||
context.clip();
|
||||
context.imageSmoothingEnabled = true;
|
||||
// The filter widens the soft edge the downscale alone leaves behind.
|
||||
context.filter = `blur(${Math.max(2, Math.round(Math.min(boxWidth, boxHeight) / 24))}px)`;
|
||||
context.drawImage(small, 0, 0, small.width, small.height, left, top, boxWidth, boxHeight);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function stampPath(context: CanvasRenderingContext2D, stamp: Stamp, radius: number) {
|
||||
context.beginPath();
|
||||
if (stamp === "check") {
|
||||
context.lineWidth = Math.max(4, radius * 0.34);
|
||||
context.moveTo(-radius * 0.46, radius * 0.04);
|
||||
context.lineTo(-radius * 0.12, radius * 0.42);
|
||||
context.lineTo(radius * 0.5, -radius * 0.4);
|
||||
context.stroke();
|
||||
return;
|
||||
}
|
||||
if (stamp === "cross") {
|
||||
context.lineWidth = Math.max(4, radius * 0.3);
|
||||
const arm = radius * 0.42;
|
||||
context.moveTo(-arm, -arm);
|
||||
context.lineTo(arm, arm);
|
||||
context.moveTo(arm, -arm);
|
||||
context.lineTo(-arm, arm);
|
||||
context.stroke();
|
||||
return;
|
||||
}
|
||||
const points = 5;
|
||||
for (let index = 0; index < points * 2; index += 1) {
|
||||
const outer = index % 2 === 0 ? radius * 0.62 : radius * 0.26;
|
||||
const angle = (Math.PI / points) * index - Math.PI / 2;
|
||||
const x = Math.cos(angle) * outer;
|
||||
const y = Math.sin(angle) * outer;
|
||||
if (index === 0) context.moveTo(x, y);
|
||||
else context.lineTo(x, y);
|
||||
}
|
||||
context.closePath();
|
||||
context.fill();
|
||||
}
|
||||
|
||||
/// A filled disc plus a glyph, centred on the tap and sized from the canvas so a
|
||||
/// stamp stays proportional on a 4K screenshot and a small crop alike.
|
||||
function drawStamp(context: CanvasRenderingContext2D, annotation: Annotation, width: number) {
|
||||
const stamp = annotation.stamp ?? "check";
|
||||
const radius = Math.max(18, Math.round(width / 22));
|
||||
context.save();
|
||||
context.translate(annotation.x1, annotation.y1);
|
||||
context.fillStyle = stamp === "cross" ? "#e0342b" : stamp === "star" ? "#f5a623" : "#1aa260";
|
||||
context.beginPath();
|
||||
context.arc(0, 0, radius, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
context.strokeStyle = "rgba(255,255,255,0.94)";
|
||||
context.fillStyle = "#fffdf9";
|
||||
context.lineCap = "round";
|
||||
context.lineJoin = "round";
|
||||
stampPath(context, stamp, radius);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function drawAnnotation(
|
||||
context: CanvasRenderingContext2D,
|
||||
annotation: Annotation,
|
||||
|
|
@ -79,6 +179,10 @@ function drawAnnotation(
|
|||
} else if (annotation.tool === "redact") {
|
||||
context.fillStyle = "#111111";
|
||||
context.fillRect(left, top, boxWidth, boxHeight);
|
||||
} else if (annotation.tool === "blur" && boxWidth > 0 && boxHeight > 0) {
|
||||
drawBlur(context, left, top, boxWidth, boxHeight);
|
||||
} else if (annotation.tool === "stamp" && annotation.stamp) {
|
||||
drawStamp(context, annotation, width);
|
||||
} else if (annotation.tool === "pixelate" && boxWidth > 0 && boxHeight > 0) {
|
||||
const sampleWidth = Math.max(1, Math.round(boxWidth / 12));
|
||||
const sampleHeight = Math.max(1, Math.round(boxHeight / 12));
|
||||
|
|
@ -166,6 +270,7 @@ export function ImageAnnotator({ path, onSaved }: Props) {
|
|||
const [busy, setBusy] = useState(false);
|
||||
const [copying, setCopying] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [stamp, setStamp] = useState<Stamp>("check");
|
||||
const [textPoint, setTextPoint] = useState<Point | null>(null);
|
||||
const [textDraft, setTextDraft] = useState("");
|
||||
const [imageHistory, setImageHistory] = useState<ImageSnapshot[]>([]);
|
||||
|
|
@ -442,11 +547,19 @@ export function ImageAnnotator({ path, onSaved }: Props) {
|
|||
{ id: "highlight" as const, icon: Highlighter, label: t("highlight") },
|
||||
{ id: "redact" as const, icon: EyeOff, label: t("redact") },
|
||||
{ id: "pixelate" as const, icon: Grid3X3, label: t("pixelate") },
|
||||
{ id: "blur" as const, icon: Droplets, label: t("blur") },
|
||||
{ id: "number" as const, icon: ListOrdered, label: t("number") },
|
||||
{ id: "stamp" as const, icon: CircleCheck, label: t("stamp") },
|
||||
{ id: "crop" as const, icon: Crop, label: t("crop") },
|
||||
{ id: "text" as const, icon: Type, label: t("textAnnotation") },
|
||||
];
|
||||
|
||||
const stamps: { id: Stamp; icon: typeof CircleCheck; label: string }[] = [
|
||||
{ id: "check", icon: CircleCheck, label: t("stampCheck") },
|
||||
{ id: "cross", icon: CircleX, label: t("stampCross") },
|
||||
{ id: "star", icon: Star, label: t("stampStar") },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="annotator-shell">
|
||||
<div className="annotator-toolbar">
|
||||
|
|
@ -462,6 +575,19 @@ export function ImageAnnotator({ path, onSaved }: Props) {
|
|||
</button>
|
||||
))}
|
||||
<span className="annotator-separator" />
|
||||
{tool === "stamp"
|
||||
? stamps.map(({ id, icon: Icon, label }) => (
|
||||
<button
|
||||
key={id}
|
||||
className={`annotator-tool annotator-stamp ${stamp === id ? "is-active" : ""}`}
|
||||
title={label}
|
||||
onClick={() => setStamp(id)}
|
||||
>
|
||||
<Icon size={15} />
|
||||
</button>
|
||||
))
|
||||
: null}
|
||||
<span className="annotator-separator" />
|
||||
{cropRect ? (
|
||||
<button className="annotator-tool is-primary" onClick={applyCrop}>
|
||||
<Check size={15} />
|
||||
|
|
@ -503,6 +629,13 @@ export function ImageAnnotator({ path, onSaved }: Props) {
|
|||
setTextDraft("");
|
||||
return;
|
||||
}
|
||||
if (tool === "stamp") {
|
||||
setAnnotations((current) => [
|
||||
...current,
|
||||
{ tool: "stamp", stamp, x1: point.x, y1: point.y, x2: point.x, y2: point.y },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
if (tool === "number") {
|
||||
setAnnotations((current) => {
|
||||
const nextNumber =
|
||||
|
|
|
|||
|
|
@ -27,31 +27,35 @@ import {
|
|||
RefreshCw,
|
||||
ScanLine,
|
||||
ScanText,
|
||||
Search,
|
||||
Send,
|
||||
Settings2,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
Sparkle,
|
||||
Star,
|
||||
Wrench,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
|
||||
import { getInitialLang, publishLang, useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { hitTestDropTarget, toWindowPoint } from "../lib/dropTargets";
|
||||
import { SetupPanel } from "./SetupPanel";
|
||||
import { SharePanel } from "./SharePanel";
|
||||
import { UpdatePanel } from "./UpdatePanel";
|
||||
import {
|
||||
basename,
|
||||
dirname,
|
||||
extensionOf,
|
||||
getRecentItems,
|
||||
getLocalRecentItems,
|
||||
IS_MAC,
|
||||
recentKind,
|
||||
rememberRecent,
|
||||
type RecentItem,
|
||||
setRecentItems,
|
||||
subscribeRecent,
|
||||
timeAgo,
|
||||
} from "../lib/utils";
|
||||
import { dragOutPayload } from "../lib/dragOut";
|
||||
import { history } from "../lib/history";
|
||||
import type {
|
||||
AppSettings,
|
||||
HotkeyStatus,
|
||||
|
|
@ -62,6 +66,7 @@ import type {
|
|||
SwitchUpdate,
|
||||
WriteCheck,
|
||||
} from "../types";
|
||||
import type { FileKind, RadialRing } from "../lib/radialOrder";
|
||||
|
||||
const FALLBACK_SETTINGS: AppSettings = {
|
||||
fileOutputMode: "alongside",
|
||||
|
|
@ -72,12 +77,19 @@ const FALLBACK_SETTINGS: AppSettings = {
|
|||
dragEnabled: true,
|
||||
shareEnabled: true,
|
||||
autostart: false,
|
||||
captureAfter: "card",
|
||||
defaultFileOutputDir: "~/Downloads/Shift",
|
||||
defaultScreenshotDir: "~/Pictures/Shift",
|
||||
defaultRecordingDir: "~/Movies/Shift",
|
||||
language: "",
|
||||
updateCheckEnabled: true,
|
||||
updateFeedUrl: "",
|
||||
wedgeOrders: {},
|
||||
setupReviewed: false,
|
||||
};
|
||||
|
||||
type SettingsTab = "system" | "runtime" | "updates";
|
||||
|
||||
const DROP_ICONS = [
|
||||
{ icon: FileType, tone: "pdf" },
|
||||
{ icon: FileText, tone: "document" },
|
||||
|
|
@ -213,8 +225,9 @@ export function MainWindow() {
|
|||
// Every switch uses this snapshot until the real settings arrive. Starting
|
||||
// empty made the first click wait for a disk read before it could change.
|
||||
const [settings, setSettings] = useState<AppSettings | null>(FALLBACK_SETTINGS);
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [settingsTab, setSettingsTab] = useState<"system" | "runtime">("system");
|
||||
const [settingsTab, setSettingsTab] = useState<SettingsTab>("system");
|
||||
const [screenAccess, setScreenAccess] = useState<boolean | null>(null);
|
||||
const [checks, setChecks] = useState<WriteCheck[] | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
|
|
@ -225,7 +238,9 @@ export function MainWindow() {
|
|||
const [runtimeInstallHelp, setRuntimeInstallHelp] = useState<
|
||||
"homebrew" | "winget" | null
|
||||
>(null);
|
||||
const [recent, setRecent] = useState<RecentItem[]>(getRecentItems);
|
||||
const [recent, setRecent] = useState<RecentItem[]>(getLocalRecentItems);
|
||||
/** Filter text for the history library, matched against the file name. */
|
||||
const [historyQuery, setHistoryQuery] = useState("");
|
||||
const [sharePaths, setSharePaths] = useState<string[] | null>(null);
|
||||
const toastTimer = useRef<number | null>(null);
|
||||
const [, setNowTick] = useState(0);
|
||||
|
|
@ -234,7 +249,24 @@ export function MainWindow() {
|
|||
const dropTargets = useRef<Partial<Record<DropAction, HTMLElement | null>>>({});
|
||||
const runtimeCheckStarted = useRef(false);
|
||||
|
||||
function flash(message: string, duration = 2600) {
|
||||
async function finishSetup() {
|
||||
setSetupOpen(false);
|
||||
try {
|
||||
await api.setSetupReviewed(true);
|
||||
} catch {
|
||||
// A failed write only means the flow may appear again next launch; the
|
||||
// checks it reported are all re-runnable from Settings.
|
||||
}
|
||||
}
|
||||
|
||||
/** Leave the guided flow and land on the panel that can install what it found. */
|
||||
function openRuntimeFromSetup() {
|
||||
void finishSetup();
|
||||
setSettingsTab("runtime");
|
||||
setSettingsOpen(true);
|
||||
}
|
||||
|
||||
async function flash(message: string, duration = 2600) {
|
||||
if (toastTimer.current) window.clearTimeout(toastTimer.current);
|
||||
setToast(message);
|
||||
toastTimer.current = window.setTimeout(() => setToast(null), duration);
|
||||
|
|
@ -489,6 +521,7 @@ export function MainWindow() {
|
|||
// The tray menu is native, so it can only show the language the backend
|
||||
// knows about. Adopt the stored choice, or hand it ours on a first run;
|
||||
// the backend only writes when the value actually changed.
|
||||
if (!loaded.setupReviewed) setSetupOpen(true);
|
||||
const stored = loaded.language;
|
||||
const effective = stored === "en" || stored === "zh" ? stored : getInitialLang();
|
||||
if (effective !== stored) publishLang(effective);
|
||||
|
|
@ -505,18 +538,9 @@ export function MainWindow() {
|
|||
.hotkeyStatus()
|
||||
.then(setHotkeys)
|
||||
.catch(() => setHotkeys(null));
|
||||
const items = getRecentItems();
|
||||
void api
|
||||
.existingFiles(items.map((item) => item.path))
|
||||
.then((existing) => {
|
||||
const keep = new Set(existing);
|
||||
const pruned = items.filter((item) => keep.has(item.path));
|
||||
if (pruned.length !== items.length) {
|
||||
setRecentItems(pruned);
|
||||
setRecent(pruned);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
// Rust prunes entries whose file is gone as it reads the library, so there is
|
||||
// no separate sweep to run here.
|
||||
void history.list().then(setRecent).catch(() => undefined);
|
||||
// Settings are loaded once when the main window starts.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
|
@ -593,17 +617,21 @@ export function MainWindow() {
|
|||
void listen("app://open-ocr", () => void chooseOcr()).then((unlisten) =>
|
||||
unlisteners.push(unlisten),
|
||||
);
|
||||
void listen("app://recent-changed", () => setRecent(getRecentItems())).then((unlisten) =>
|
||||
unlisteners.push(unlisten),
|
||||
);
|
||||
void listen<{ outputs: string[]; message: string }>("app://file-result", (event) => {
|
||||
const output = event.payload.outputs[0];
|
||||
if (!output) return;
|
||||
rememberRecent({ path: output, kind: recentKind(output), at: Date.now() });
|
||||
setRecent(getRecentItems());
|
||||
// The tray's update row lands here: open Settings on the Updates tab so the
|
||||
// download and its SHA256 are the next thing the user sees.
|
||||
void listen("app://open-updates", () => {
|
||||
setSettingsTab("updates");
|
||||
setSettingsOpen(true);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
// A capture card's Send button: this window owns the peer list, so the card
|
||||
// asks here rather than duplicating the discovery UI.
|
||||
void listen<{ paths: string[] }>("app://send-files", (event) =>
|
||||
setSharePaths(event.payload.paths),
|
||||
).then((unlisten) => unlisteners.push(unlisten));
|
||||
}
|
||||
const unsubscribeRecent = subscribeRecent(() => setRecent(getRecentItems()));
|
||||
const unsubscribeRecent = subscribeRecent(() => void history.list().then(setRecent));
|
||||
// Rust owns the library, so its broadcast is the only cross-window signal needed.
|
||||
const unsubscribeHistory = history.onChanged(setRecent);
|
||||
// Keeps the relative timestamps honest without re-reading storage constantly.
|
||||
// The same slow tick keeps relative timestamps and the hotkey-ownership
|
||||
// notice honest, so a copy that quits clears the warning without a restart.
|
||||
|
|
@ -614,6 +642,7 @@ export function MainWindow() {
|
|||
return () => {
|
||||
unlisteners.forEach((unlisten) => unlisten());
|
||||
unsubscribeRecent();
|
||||
unsubscribeHistory();
|
||||
window.clearInterval(clockTimer);
|
||||
if (toastTimer.current) window.clearTimeout(toastTimer.current);
|
||||
};
|
||||
|
|
@ -621,6 +650,14 @@ export function MainWindow() {
|
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// The library holds hundreds of rows, so the filter runs where the list is
|
||||
// rendered rather than as a second request to Rust.
|
||||
const visibleRecent = useMemo(() => {
|
||||
const needle = historyQuery.trim().toLowerCase();
|
||||
if (!needle) return recent;
|
||||
return recent.filter((item) => basename(item.path).toLowerCase().includes(needle));
|
||||
}, [recent, historyQuery]);
|
||||
|
||||
const outputLabel = (kind: WriteCheck["kind"]) =>
|
||||
kind === "screenshot" ? t("screenshots") : kind === "recording" ? t("recordings") : t("fileResults");
|
||||
const runtimeGroups = runtimeInfo
|
||||
|
|
@ -692,6 +729,13 @@ export function MainWindow() {
|
|||
</div>
|
||||
</header>
|
||||
|
||||
{setupOpen ? (
|
||||
<SetupPanel
|
||||
onDone={() => void finishSetup()}
|
||||
onOpenRuntime={openRuntimeFromSetup}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<main className="home-main">
|
||||
<section className={`home-drop ${dragging ? "is-dragging" : ""}`}>
|
||||
{screenAccess === false ? (
|
||||
|
|
@ -783,9 +827,40 @@ export function MainWindow() {
|
|||
<Clock3 size={16} />
|
||||
<h1>{t("recent")}</h1>
|
||||
<span className="home-card-count">
|
||||
{recent.length > 0 ? t("itemCount", { count: recent.length }) : t("nothingYet")}
|
||||
{recent.length > 0
|
||||
? t("itemCount", {
|
||||
count: historyQuery.trim() ? visibleRecent.length : recent.length,
|
||||
})
|
||||
: t("nothingYet")}
|
||||
</span>
|
||||
{recent.length > 0 ? (
|
||||
<button
|
||||
className="settings-link home-card-clear"
|
||||
onClick={() => void history.clear().catch(() => undefined)}
|
||||
>
|
||||
{t("clearHistory")}
|
||||
</button>
|
||||
) : null}
|
||||
</header>
|
||||
{recent.length > 3 ? (
|
||||
<label className="home-recent-search">
|
||||
<Search size={13} />
|
||||
<input
|
||||
value={historyQuery}
|
||||
placeholder={t("searchHistory")}
|
||||
onChange={(event) => setHistoryQuery(event.target.value)}
|
||||
/>
|
||||
{historyQuery ? (
|
||||
<button
|
||||
onClick={() => setHistoryQuery("")}
|
||||
title={t("clearHistory")}
|
||||
aria-label={t("clearHistory")}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
) : null}
|
||||
</label>
|
||||
) : null}
|
||||
{recent.length === 0 ? (
|
||||
<div className="home-empty">
|
||||
<span className="home-empty-glyph" aria-hidden="true">
|
||||
|
|
@ -793,13 +868,32 @@ export function MainWindow() {
|
|||
</span>
|
||||
<p>{t("recentEmpty")}</p>
|
||||
</div>
|
||||
) : visibleRecent.length === 0 ? (
|
||||
<div className="home-empty">
|
||||
<p>{t("historyNoMatches", { query: historyQuery.trim() })}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="home-recent-list">
|
||||
{recent.map((item) => (
|
||||
<div key={item.path} className="home-recent" title={item.path}>
|
||||
<ul className="home-recent-list">
|
||||
{visibleRecent.map((item) => (
|
||||
<li
|
||||
key={item.path}
|
||||
className={`home-recent ${item.pinned ? "is-pinned" : ""}`}
|
||||
title={item.path}
|
||||
draggable
|
||||
onDragStart={(event) => {
|
||||
// A row leaves Shift as the file itself: WebKit turns the file URL
|
||||
// in text/uri-list into a real file drop for Finder and friends,
|
||||
// while the plain path keeps editors and our own drop zones happy.
|
||||
event.dataTransfer.effectAllowed = "copy";
|
||||
for (const [type, value] of Object.entries(dragOutPayload(item.path))) {
|
||||
event.dataTransfer.setData(type, value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<button
|
||||
className="home-recent-main"
|
||||
onClick={() => void api.openInEditor(item.path)}
|
||||
title={t("dragOutHint")}
|
||||
>
|
||||
<RecentThumb item={item} />
|
||||
<span>
|
||||
|
|
@ -810,6 +904,15 @@ export function MainWindow() {
|
|||
</span>
|
||||
</button>
|
||||
<span className="home-recent-actions">
|
||||
<button
|
||||
title={item.pinned ? t("unpinFromRecent") : t("pinToRecent")}
|
||||
aria-pressed={item.pinned}
|
||||
onClick={() =>
|
||||
void history.setPinned(item.path, !item.pinned).catch(() => undefined)
|
||||
}
|
||||
>
|
||||
<Star size={13} />
|
||||
</button>
|
||||
<button title={t("sendTo")} onClick={() => setSharePaths([item.path])}>
|
||||
<Send size={13} />
|
||||
</button>
|
||||
|
|
@ -821,10 +924,16 @@ export function MainWindow() {
|
|||
<Pin size={13} />
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
title={t("forget")}
|
||||
onClick={() => void history.remove(item.path).catch(() => undefined)}
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</div>
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
|
|
@ -846,7 +955,13 @@ export function MainWindow() {
|
|||
<X size={17} />
|
||||
</button>
|
||||
<div className="home-settings-heading">
|
||||
<h2>{settingsTab === "system" ? t("systemSettings") : t("runtimeComponents")}</h2>
|
||||
<h2>
|
||||
{settingsTab === "system"
|
||||
? t("systemSettings")
|
||||
: settingsTab === "runtime"
|
||||
? t("runtimeComponents")
|
||||
: t("updates")}
|
||||
</h2>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
|
@ -873,10 +988,47 @@ export function MainWindow() {
|
|||
<Cpu size={14} />
|
||||
{t("runtimeComponents")}
|
||||
</button>
|
||||
<button
|
||||
id="settings-tab-updates"
|
||||
className={`home-settings-tab ${settingsTab === "updates" ? "is-active" : ""}`}
|
||||
role="tab"
|
||||
aria-selected={settingsTab === "updates"}
|
||||
aria-controls="settings-panel-updates"
|
||||
onClick={() => setSettingsTab("updates")}
|
||||
>
|
||||
<Sparkle size={14} />
|
||||
{t("updates")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="home-settings-body">
|
||||
{settingsTab === "system" ? (
|
||||
{settingsTab === "updates" ? (
|
||||
<div
|
||||
className="home-settings-panel"
|
||||
id="settings-panel-updates"
|
||||
role="tabpanel"
|
||||
aria-labelledby="settings-tab-updates"
|
||||
>
|
||||
<UpdatePanel
|
||||
feedUrl={settings?.updateFeedUrl ?? ""}
|
||||
autoCheck={settings?.updateCheckEnabled ?? true}
|
||||
onAutoCheckChange={(enabled) =>
|
||||
void applyToggle({ updateCheckEnabled: enabled }, () =>
|
||||
api.setUpdateCheckEnabled(enabled),
|
||||
)
|
||||
}
|
||||
system={
|
||||
runtimeInfo
|
||||
? {
|
||||
platform: runtimeInfo.platform,
|
||||
osVersion: runtimeInfo.osVersion,
|
||||
architecture: runtimeInfo.architecture,
|
||||
}
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : settingsTab === "system" ? (
|
||||
<div
|
||||
className="home-settings-panel"
|
||||
id="settings-panel-system"
|
||||
|
|
@ -931,6 +1083,21 @@ export function MainWindow() {
|
|||
onReveal={() => void api.revealOutputDirectory("screenshot")}
|
||||
onReset={() => void resetFolder("screenshot")}
|
||||
/>
|
||||
<div className="home-segment home-segment-after">
|
||||
<button
|
||||
className={(settings?.captureAfter ?? "card") !== "editor" ? "is-active" : ""}
|
||||
onClick={() => void applySettings(() => api.setCaptureAfter("card"))}
|
||||
>
|
||||
{t("captureAfterCard")}
|
||||
</button>
|
||||
<button
|
||||
className={settings?.captureAfter === "editor" ? "is-active" : ""}
|
||||
onClick={() => void applySettings(() => api.setCaptureAfter("editor"))}
|
||||
>
|
||||
{t("captureAfterEditor")}
|
||||
</button>
|
||||
</div>
|
||||
<p className="runtime-summary">{t("captureAfterBody")}</p>
|
||||
</section>
|
||||
|
||||
<section className="home-settings-section">
|
||||
|
|
|
|||
|
|
@ -41,8 +41,16 @@ import { useEffect, useRef, useState } from "react";
|
|||
import type { ComponentType } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { conversionFormats } from "../lib/conversionFormats";
|
||||
import {
|
||||
WEDGE_ACTION_IDS,
|
||||
defaultWedgeIds,
|
||||
orderWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
type WedgeOrders,
|
||||
} from "../lib/radialOrder";
|
||||
import { recognizeImage } from "../lib/ocr";
|
||||
import { basename, formatBytes, recentKind, rememberRecent } from "../lib/utils";
|
||||
import { basename, formatBytes } from "../lib/utils";
|
||||
import type { FileInfo, RadialContext } from "../types";
|
||||
import { useI18n } from "../i18n";
|
||||
import { SharePanel } from "./SharePanel";
|
||||
|
|
@ -112,6 +120,48 @@ function sectorAt(x: number, y: number, count: number): number | null {
|
|||
return Math.floor(offset / step);
|
||||
}
|
||||
|
||||
/**
|
||||
* Icon for every wedge the rings can show. Labels come from `wedgeLabelKey` in
|
||||
* `src/lib/radialOrder.ts`, which is where the wedge catalogue and the reorder screen
|
||||
* in Settings agree on wording.
|
||||
*/
|
||||
const WEDGE_ICONS: Record<string, IconType> = {
|
||||
addBackground: ImagePlus,
|
||||
annotate: PenLine,
|
||||
compress: Minimize2,
|
||||
convert: FileOutput,
|
||||
crop: Crop,
|
||||
cutout: Scissors,
|
||||
edit: SlidersHorizontal,
|
||||
extractAudio: Music,
|
||||
flip: FlipHorizontal,
|
||||
frame: Camera,
|
||||
grayscale: Contrast,
|
||||
hd720: Video,
|
||||
merge: Merge,
|
||||
metadata: Tags,
|
||||
mono: Volume1,
|
||||
mute: VolumeX,
|
||||
ocr: ScanText,
|
||||
open: ExternalLink,
|
||||
pdfOcr: ScanText,
|
||||
plain: FileText,
|
||||
redact: EyeOff,
|
||||
resizeHalf: Scaling,
|
||||
reveal: FolderOpen,
|
||||
rotate: RotateCw,
|
||||
send: Send,
|
||||
split: Scissors,
|
||||
text: FileText,
|
||||
};
|
||||
|
||||
// A wedge whose icon was forgotten renders the generic file glyph, which is easy to add
|
||||
// by accident and hard to notice, so name it on the console. Empty in a healthy build.
|
||||
const wedgesWithoutIcons = WEDGE_ACTION_IDS.filter((id) => !WEDGE_ICONS[id]);
|
||||
if (wedgesWithoutIcons.length > 0) {
|
||||
console.warn("radial wedges without an icon:", wedgesWithoutIcons);
|
||||
}
|
||||
|
||||
function formatIcon(format: string): IconType {
|
||||
if (format === "PDF" || format === "TXT" || format === "MD" || format === "DOCX") {
|
||||
return FileText;
|
||||
|
|
@ -149,6 +199,23 @@ function actionWedge(
|
|||
return { id, label, icon, format };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn one wedge id from the catalogue into what the ring renders. An id that names
|
||||
* one of the source's convert targets is a format wedge; everything else is an action
|
||||
* whose label and icon come from the shared wedge tables.
|
||||
*/
|
||||
function buildWedge(
|
||||
id: string,
|
||||
formats: string[],
|
||||
t: (key: string) => string,
|
||||
): Wedge {
|
||||
const target = formats.find((format) => format.toLowerCase() === id);
|
||||
if (target) {
|
||||
return actionWedge(id, target, formatIcon(target), target);
|
||||
}
|
||||
return actionWedge(id, t(wedgeLabelKey(id)), WEDGE_ICONS[id] ?? File);
|
||||
}
|
||||
|
||||
function messageOf(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.replace(/^Error:\s*/, "") || "Unknown error";
|
||||
|
|
@ -175,6 +242,8 @@ export function RadialMenu() {
|
|||
const [error, setError] = useState<string | null>(null);
|
||||
// Files waiting for a peer to be picked; the ring stays open behind the panel.
|
||||
const [sharePaths, setSharePaths] = useState<string[] | null>(null);
|
||||
// Custom wedge order per kind and ring, as saved in Settings.
|
||||
const [orders, setOrders] = useState<WedgeOrders>({});
|
||||
const sharePathsRef = useRef<string[] | null>(null);
|
||||
// True once the send panel has reported an outcome; the ring then stays open
|
||||
// just long enough to show the message.
|
||||
|
|
@ -203,116 +272,14 @@ export function RadialMenu() {
|
|||
|
||||
const kind = context?.fileInfo[0]?.kind ?? "other";
|
||||
const formats = conversionFormats(kind, context?.fileInfo[0]?.extension ?? "");
|
||||
|
||||
const actions: Wedge[] =
|
||||
kind === "image"
|
||||
? [
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("metadata", t("metadata"), Tags),
|
||||
actionWedge("edit", t("edit"), SlidersHorizontal),
|
||||
actionWedge("annotate", t("annotate"), PenLine),
|
||||
actionWedge("addBackground", t("addBackground"), ImagePlus),
|
||||
actionWedge("crop", t("crop"), Crop),
|
||||
actionWedge("redact", t("redact"), EyeOff),
|
||||
actionWedge("ocr", t("ocr"), ScanText),
|
||||
actionWedge("convert", t("convert"), FileOutput),
|
||||
...(context && context.fileInfo.length > 1
|
||||
? [actionWedge("merge", t("merge"), Merge)]
|
||||
: []),
|
||||
]
|
||||
: kind === "video" || kind === "audio"
|
||||
? [
|
||||
actionWedge("convert", t("convert"), FileOutput),
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("edit", t("edit"), SlidersHorizontal),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
]
|
||||
: kind === "pdf"
|
||||
? [
|
||||
actionWedge("convert", t("convert"), FileOutput),
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("pdfOcr", t("ocr"), ScanText),
|
||||
actionWedge("text", t("extractText"), FileText),
|
||||
actionWedge("split", t("split"), Scissors),
|
||||
actionWedge("rotate", t("rotate"), RotateCw),
|
||||
actionWedge("metadata", t("metadata"), Tags),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
...(context && context.fileInfo.length > 1
|
||||
? [actionWedge("merge", t("merge"), Merge)]
|
||||
: []),
|
||||
]
|
||||
: kind === "presentation" || kind === "spreadsheet" || kind === "document"
|
||||
? [
|
||||
...(formats.length > 0
|
||||
? [actionWedge("convert", t("convert"), FileOutput)]
|
||||
: []),
|
||||
actionWedge("edit", t("edit"), SlidersHorizontal),
|
||||
actionWedge("open", t("open"), ExternalLink),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
]
|
||||
: [
|
||||
actionWedge("open", t("open"), ExternalLink),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
];
|
||||
|
||||
const formatWedges: Wedge[] = formats.map((format) =>
|
||||
actionWedge(format.toLowerCase(), format, formatIcon(format), format),
|
||||
const multi = (context?.fileInfo.length ?? 0) > 1;
|
||||
// The catalogue decides which wedges exist, the saved order where each appears.
|
||||
const ids = defaultWedgeIds(ring, kind, formats, multi);
|
||||
const wedges = orderWedgeIds(ids, savedOrderFor(orders, kind, ring)).map((id) =>
|
||||
buildWedge(id, formats, t),
|
||||
);
|
||||
const toolWedges: Wedge[] =
|
||||
kind === "image"
|
||||
? [
|
||||
actionWedge("rotate", t("rotate"), RotateCw),
|
||||
actionWedge("flip", t("flip"), FlipHorizontal),
|
||||
actionWedge("grayscale", t("blackWhite"), Contrast),
|
||||
actionWedge("resizeHalf", t("halfSize"), Scaling),
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("metadata", t("metadata"), Tags),
|
||||
actionWedge("crop", t("crop"), Crop),
|
||||
actionWedge("cutout", t("cutout"), Scissors),
|
||||
...(context && context.fileInfo.length > 1
|
||||
? [actionWedge("merge", t("merge"), Merge)]
|
||||
: []),
|
||||
]
|
||||
: kind === "video"
|
||||
? [
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("hd720", t("hd720"), Video),
|
||||
actionWedge("mute", t("mute"), VolumeX),
|
||||
actionWedge("extractAudio", t("extractAudio"), Music),
|
||||
actionWedge("frame", t("frame"), Camera),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
]
|
||||
: kind === "audio"
|
||||
? [
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("mono", t("mono"), Volume1),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
]
|
||||
: kind === "pdf"
|
||||
? [
|
||||
actionWedge("compress", t("compress"), Minimize2),
|
||||
actionWedge("metadata", t("metadata"), Tags),
|
||||
actionWedge("rotate", t("rotate"), RotateCw),
|
||||
actionWedge("split", t("split"), Scissors),
|
||||
actionWedge("text", t("extractText"), FileText),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
...(context && context.fileInfo.length > 1
|
||||
? [actionWedge("merge", t("merge"), Merge)]
|
||||
: []),
|
||||
]
|
||||
: kind === "document"
|
||||
? [
|
||||
actionWedge("plain", t("plain"), FileText),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
]
|
||||
: [
|
||||
actionWedge("open", t("open"), ExternalLink),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
];
|
||||
// Sending works for any file, so the wedge joins every type's tool ring.
|
||||
toolWedges.push(actionWedge("send", t("sendShort"), Send));
|
||||
const wedges =
|
||||
ring === "formats" ? formatWedges : ring === "tools" ? toolWedges : actions;
|
||||
if (ring === "tools") wedges.push(actionWedge("send", t("sendShort"), Send));
|
||||
wedgesRef.current = wedges;
|
||||
const wedgeCount = Math.max(wedges.length, 1);
|
||||
const hoveredWedge = hovered !== null ? wedges[hovered] : undefined;
|
||||
|
|
@ -384,6 +351,14 @@ export function RadialMenu() {
|
|||
});
|
||||
return;
|
||||
}
|
||||
// Saved wedge orders arrive with the context and again whenever Settings edits
|
||||
// one, so a reorder takes effect on the very next gesture.
|
||||
void api.getWedgeOrders().then((next) => {
|
||||
if (!disposed) setOrders(next);
|
||||
});
|
||||
void listen<WedgeOrders>("settings://wedge-orders", (event) => {
|
||||
setOrders(event.payload);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void api.getRadialContext().then((next) => {
|
||||
if (!disposed) applyContext(next);
|
||||
});
|
||||
|
|
@ -598,9 +573,6 @@ export function RadialMenu() {
|
|||
);
|
||||
},
|
||||
);
|
||||
for (const output of outcome.outputs) {
|
||||
rememberRecent({ path: output, kind: recentKind(output), at: Date.now() });
|
||||
}
|
||||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
|
|
@ -661,7 +633,6 @@ export function RadialMenu() {
|
|||
void api.cleanupPdfPages(pages).catch(() => undefined);
|
||||
}
|
||||
const output = await api.saveTextNear(current.files[0], chunks.join("\n\n"), " (OCR)");
|
||||
rememberRecent({ path: output, kind: "text", at: Date.now() });
|
||||
await api.openInEditor(output);
|
||||
void api.hideRadial();
|
||||
} catch (error) {
|
||||
|
|
@ -694,9 +665,6 @@ export function RadialMenu() {
|
|||
current.files,
|
||||
id === "extractAudio" ? "m4a" : "txt",
|
||||
);
|
||||
for (const output of outcome.outputs) {
|
||||
rememberRecent({ path: output, kind: recentKind(output), at: Date.now() });
|
||||
}
|
||||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
|
|
@ -734,9 +702,6 @@ export function RadialMenu() {
|
|||
await waitForPaint();
|
||||
try {
|
||||
const outcome = await api.performFileAction(action, current.files);
|
||||
for (const output of outcome.outputs) {
|
||||
rememberRecent({ path: output, kind: recentKind(output), at: Date.now() });
|
||||
}
|
||||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,126 @@
|
|||
import { ArrowDown, ArrowUp, RotateCcw } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import {
|
||||
ORDERABLE_KINDS,
|
||||
hasCustomOrder,
|
||||
isOrderDirty,
|
||||
moveWedge,
|
||||
orderWedgeIds,
|
||||
presetWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
type FileKind,
|
||||
type RadialRing,
|
||||
type WedgeOrders,
|
||||
} from "../lib/radialOrder";
|
||||
|
||||
/**
|
||||
* The reorder screen for the radial rings.
|
||||
*
|
||||
* It edits one preset at a time — a file kind plus a ring — and can only rearrange the
|
||||
* wedges that ring actually offers, so a preset can never invent an action. The list is
|
||||
* always the live catalogue in a saved order; saving an empty list (Reset) hands the
|
||||
* ring back to the built-in order. Every rule the screen applies lives in
|
||||
* `src/lib/radialOrder.ts`, which keeps them testable without mounting this panel.
|
||||
*/
|
||||
export function RadialOrderPanel({
|
||||
orders,
|
||||
onApply,
|
||||
}: {
|
||||
orders: WedgeOrders;
|
||||
onApply: (kind: FileKind, ring: RadialRing, order: string[]) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [kind, setKind] = useState<FileKind>("image");
|
||||
const [ring, setRing] = useState<RadialRing>("actions");
|
||||
const [draft, setDraft] = useState<string[]>([]);
|
||||
|
||||
const catalogue = useMemo(() => presetWedgeIds(kind, ring), [ring, kind]);
|
||||
const saved = savedOrderFor(orders, kind, ring);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(orderWedgeIds(catalogue, saved));
|
||||
}, [catalogue, saved]);
|
||||
|
||||
const custom = Boolean(saved);
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="home-settings-section">
|
||||
<div className="home-section-title">{t("radialKind")}</div>
|
||||
<div className="radial-kind-grid">
|
||||
{ORDERABLE_KINDS.map((entry) => (
|
||||
<button
|
||||
key={entry}
|
||||
className={entry === kind ? "is-active" : ""}
|
||||
onClick={() => setKind(entry)}
|
||||
>
|
||||
{t(`kind_${entry}`)}
|
||||
{hasCustomOrder(orders, entry) ? <span className="radial-kind-dot" /> : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="home-segment">
|
||||
<button
|
||||
className={ring === "actions" ? "is-active" : ""}
|
||||
onClick={() => setRing("actions")}
|
||||
>
|
||||
{t("ringActions")}
|
||||
</button>
|
||||
<button className={ring === "tools" ? "is-active" : ""} onClick={() => setRing("tools")}>
|
||||
{t("ringTools")}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="home-settings-section">
|
||||
<div className="runtime-section-head">
|
||||
<div className="home-section-title">{t("radialOrder", { count: draft.length })}</div>
|
||||
<button
|
||||
className="settings-link"
|
||||
onClick={() => onApply(kind, ring, [])}
|
||||
disabled={!custom}
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
{t("reset")}
|
||||
</button>
|
||||
</div>
|
||||
<p className="runtime-summary">{t("radialOrderBody")}</p>
|
||||
<ol className="radial-order-list">
|
||||
{draft.map((id, index) => (
|
||||
<li className="radial-order-row" key={id}>
|
||||
<span className="radial-order-index">{index + 1}</span>
|
||||
<span className="radial-order-label">{t(wedgeLabelKey(id))}</span>
|
||||
<span className="radial-order-buttons">
|
||||
<button
|
||||
onClick={() => setDraft(moveWedge(draft, index, -1))}
|
||||
disabled={index === 0}
|
||||
title={t("moveUp")}
|
||||
aria-label={t("moveUp")}
|
||||
>
|
||||
<ArrowUp size={12} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDraft(moveWedge(draft, index, 1))}
|
||||
disabled={index === draft.length - 1}
|
||||
title={t("moveDown")}
|
||||
aria-label={t("moveDown")}
|
||||
>
|
||||
<ArrowDown size={12} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<button
|
||||
className="settings-wide-button radial-order-save"
|
||||
onClick={() => onApply(kind, ring, draft)}
|
||||
disabled={!isOrderDirty(draft, catalogue, saved)}
|
||||
>
|
||||
{t("radialOrderSave")}
|
||||
</button>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
import { convertFileSrc, isTauri } from "@tauri-apps/api/core";
|
||||
import { emitTo } from "@tauri-apps/api/event";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { writeImage, writeText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { Copy, FileVideo, FolderSearch, Images, Send } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { basename, decodeHexParam } from "../lib/utils";
|
||||
import type { CaptureResult } from "../types";
|
||||
|
||||
const THUMB_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "bmp", "tiff", "tif"];
|
||||
|
||||
function readInfo(): CaptureResult | null {
|
||||
const raw = decodeHexParam(new URLSearchParams(window.location.search).get("info"));
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as CaptureResult;
|
||||
return parsed.path ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The card that appears the moment a screenshot or recording is saved. It answers
|
||||
* the four things a capture raises, in the order they get asked: put it on the
|
||||
* clipboard, keep it on screen, hand it to another machine, open it. It hides
|
||||
* itself, so ignoring it is a valid answer too.
|
||||
*/
|
||||
export function ResultCard() {
|
||||
const { t } = useI18n();
|
||||
const info = readInfo();
|
||||
const ttl = info?.ttlMs ?? 8000;
|
||||
const [remaining, setRemaining] = useState(ttl);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const hold = useRef<number | null>(null);
|
||||
|
||||
const close = useCallback(() => {
|
||||
void getCurrentWindow()
|
||||
.close()
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const started = Date.now();
|
||||
const tick = window.setInterval(() => {
|
||||
const left = Math.max(0, ttl - (Date.now() - started));
|
||||
setRemaining(left);
|
||||
if (left === 0) {
|
||||
window.clearInterval(tick);
|
||||
close();
|
||||
}
|
||||
}, 100);
|
||||
return () => window.clearInterval(tick);
|
||||
}, [close, ttl]);
|
||||
|
||||
// Hovering pauses the fuse: the difference between a helper and a reflex test.
|
||||
function pause() {
|
||||
if (hold.current) window.clearTimeout(hold.current);
|
||||
}
|
||||
|
||||
function resume() {
|
||||
pause();
|
||||
hold.current = window.setTimeout(close, 2500);
|
||||
}
|
||||
|
||||
useEffect(() => () => pause(), []);
|
||||
|
||||
async function copy() {
|
||||
if (!info) return;
|
||||
try {
|
||||
if (info.kind === "image") await writeImage(info.path);
|
||||
else await writeText(info.path);
|
||||
setNote(t("copied"));
|
||||
} catch (error) {
|
||||
setNote(String(error));
|
||||
}
|
||||
}
|
||||
|
||||
async function open() {
|
||||
if (!info) return;
|
||||
await api.openInEditor(info.path);
|
||||
close();
|
||||
}
|
||||
|
||||
async function pin() {
|
||||
if (!info || info.kind !== "image") return;
|
||||
await api.pinImage(info.path);
|
||||
close();
|
||||
}
|
||||
|
||||
async function reveal() {
|
||||
if (!info) return;
|
||||
await api.revealFile(info.path);
|
||||
close();
|
||||
}
|
||||
|
||||
function send() {
|
||||
if (!info) return;
|
||||
// The main window owns the peer list, so the request goes there.
|
||||
void emitTo("main", "app://send-files", { paths: [info.path] });
|
||||
close();
|
||||
}
|
||||
|
||||
if (!info) return null;
|
||||
const extension = info.path.split(".").pop()?.toLowerCase() ?? "";
|
||||
const showThumb = info.kind === "image" && THUMB_EXTENSIONS.includes(extension) && !failed;
|
||||
const percent = ttl > 0 ? (remaining / ttl) * 100 : 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="result-card"
|
||||
onMouseEnter={pause}
|
||||
onMouseLeave={resume}
|
||||
role="status"
|
||||
aria-label={t("captureSaved")}
|
||||
>
|
||||
<div className={`result-card-thumb ${info.kind}`}>
|
||||
{showThumb ? (
|
||||
<img
|
||||
src={isTauri() ? convertFileSrc(info.path) : info.path}
|
||||
alt=""
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
) : info.kind === "video" ? (
|
||||
<FileVideo size={18} />
|
||||
) : (
|
||||
<Images size={18} />
|
||||
)}
|
||||
</div>
|
||||
<div className="result-card-copy" data-tauri-drag-region>
|
||||
<strong>{t("captureSaved")}</strong>
|
||||
<span title={info.path}>{basename(info.path)}</span>
|
||||
{note ? <em>{note}</em> : null}
|
||||
</div>
|
||||
<div className="result-card-actions">
|
||||
<button title={t("copy")} onClick={() => void copy()}>
|
||||
<Copy size={14} />
|
||||
</button>
|
||||
{info.kind === "image" ? (
|
||||
<button title={t("pin")} onClick={() => void pin()}>
|
||||
<Images size={14} />
|
||||
</button>
|
||||
) : null}
|
||||
<button title={t("sendTo")} onClick={() => void send()}>
|
||||
<Send size={14} />
|
||||
</button>
|
||||
<button title={t("revealFile")} onClick={() => void reveal()}>
|
||||
<FolderSearch size={14} />
|
||||
</button>
|
||||
<button className="result-card-open" onClick={() => void open()}>
|
||||
{t("edit")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="result-card-fuse" style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,228 @@
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
Check,
|
||||
FolderOpen,
|
||||
Keyboard,
|
||||
LoaderCircle,
|
||||
RefreshCw,
|
||||
ScanLine,
|
||||
ShieldCheck,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import type { HotkeyStatus, RuntimeInfo, WriteCheck } from "../types";
|
||||
|
||||
type State = "checking" | "ok" | "problem" | "unknown";
|
||||
|
||||
interface Row {
|
||||
id: "capture" | "folders" | "shortcuts" | "tools";
|
||||
state: State;
|
||||
detail: string;
|
||||
action?: { label: string; run: () => void };
|
||||
}
|
||||
|
||||
/**
|
||||
* Guided first-run checks. Everything here is a probe that Settings also offers, so
|
||||
* the flow reports the same truth rather than a first-run guess: it reads the OS
|
||||
* permission state, writes a probe file into each output folder, asks which copy owns
|
||||
* the global hotkeys, and lists optional tools the platform is missing. Dismissing it
|
||||
* never disables anything.
|
||||
*/
|
||||
export function SetupPanel({
|
||||
onDone,
|
||||
onOpenRuntime,
|
||||
}: {
|
||||
onDone: () => void;
|
||||
onOpenRuntime: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [rows, setRows] = useState<Row[]>([
|
||||
{ id: "capture", state: "checking", detail: "" },
|
||||
{ id: "folders", state: "checking", detail: "" },
|
||||
{ id: "shortcuts", state: "checking", detail: "" },
|
||||
{ id: "tools", state: "checking", detail: "" },
|
||||
]);
|
||||
const [checks, setChecks] = useState<WriteCheck[] | null>(null);
|
||||
|
||||
const patch = (id: Row["id"], next: Partial<Row>) =>
|
||||
setRows((current) => current.map((row) => (row.id === id ? { ...row, ...next } : row)));
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setRows((current) => current.map((row) => ({ ...row, state: "checking" as State })));
|
||||
|
||||
void api
|
||||
.screenCaptureAccessStatus()
|
||||
.then((allowed) =>
|
||||
patch(
|
||||
"capture",
|
||||
allowed
|
||||
? { state: "ok", detail: t("setupCaptureOk") }
|
||||
: {
|
||||
state: "problem",
|
||||
detail: t("screenPermissionPrompt"),
|
||||
action: {
|
||||
label: t("openScreenSettings"),
|
||||
run: () => void api.openScreenRecordingSettings(),
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
.catch(() => patch("capture", { state: "unknown", detail: t("setupCheckFailed") }));
|
||||
|
||||
void api
|
||||
.checkOutputAccess()
|
||||
.then((results) => {
|
||||
setChecks(results);
|
||||
const broken = results.filter((check) => !check.ok);
|
||||
patch(
|
||||
"folders",
|
||||
broken.length === 0
|
||||
? { state: "ok", detail: t("setupFoldersOk") }
|
||||
: { state: "problem", detail: broken.map((check) => check.message).join(" ") },
|
||||
);
|
||||
})
|
||||
.catch(() => patch("folders", { state: "unknown", detail: t("setupCheckFailed") }));
|
||||
|
||||
void api
|
||||
.hotkeyStatus()
|
||||
.then((status: HotkeyStatus) =>
|
||||
patch(
|
||||
"shortcuts",
|
||||
status.live
|
||||
? { state: "ok", detail: t("setupShortcutsOk") }
|
||||
: {
|
||||
state: "problem",
|
||||
detail: status.others.length > 0 ? t("hotkeysDead") : t("hotkeysNotLive"),
|
||||
action: {
|
||||
label: t("hotkeysFix"),
|
||||
run: () =>
|
||||
void api
|
||||
.quitOtherInstances()
|
||||
.then(() => api.reclaimHotkeys())
|
||||
.then((live) =>
|
||||
patch(
|
||||
"shortcuts",
|
||||
live.live
|
||||
? { state: "ok", detail: t("setupShortcutsOk") }
|
||||
: { state: "problem", detail: t("hotkeysNotLive") },
|
||||
),
|
||||
)
|
||||
.catch(() => patch("shortcuts", { state: "unknown", detail: t("setupCheckFailed") })),
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
.catch(() => patch("shortcuts", { state: "unknown", detail: t("setupCheckFailed") }));
|
||||
|
||||
void api
|
||||
.getRuntimeInfo()
|
||||
.then((info: RuntimeInfo) => {
|
||||
const missing = info.components.filter((component) => !component.available);
|
||||
const installable = missing.filter((component) => component.installable);
|
||||
// Anything missing is the same state; only the fix differs. A platform with
|
||||
// no installer still says what is absent rather than "not checked", which
|
||||
// would imply the probe never ran.
|
||||
patch(
|
||||
"tools",
|
||||
missing.length === 0
|
||||
? { state: "ok", detail: t("setupToolsOk") }
|
||||
: {
|
||||
state: "problem",
|
||||
detail: t("setupToolsMissing", { count: missing.length }),
|
||||
action: installable.length
|
||||
? { label: t("runtimeOpenPanel"), run: onOpenRuntime }
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
})
|
||||
.catch(() => patch("tools", { state: "unknown", detail: t("setupCheckFailed") }));
|
||||
}, [t, onDone, onOpenRuntime]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const icons = {
|
||||
capture: ScanLine,
|
||||
folders: FolderOpen,
|
||||
shortcuts: Keyboard,
|
||||
tools: ShieldCheck,
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<div className="setup-scrim" role="dialog" aria-modal="true" aria-label={t("setupTitle")}>
|
||||
<div className="setup-card">
|
||||
<header className="setup-head">
|
||||
<div>
|
||||
<h2>{t("setupTitle")}</h2>
|
||||
<p>{t("setupIntro")}</p>
|
||||
</div>
|
||||
<button className="setup-refresh" onClick={() => void refresh()}>
|
||||
<RefreshCw size={13} />
|
||||
{t("setupRecheck")}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<ul className="setup-list">
|
||||
{rows.map((row) => {
|
||||
const Icon = icons[row.id];
|
||||
return (
|
||||
<li key={row.id} className={`setup-row is-${row.state}`}>
|
||||
<span className="setup-row-icon">
|
||||
<Icon size={15} />
|
||||
</span>
|
||||
<span className="setup-row-body">
|
||||
<strong>{t(`setupRow_${row.id}`)}</strong>
|
||||
<small>
|
||||
{row.state === "checking" ? (
|
||||
<>
|
||||
<LoaderCircle size={11} className="spin" /> {t("setupChecking")}
|
||||
</>
|
||||
) : (
|
||||
row.detail
|
||||
)}
|
||||
</small>
|
||||
{row.action ? (
|
||||
<button className="settings-link" onClick={row.action.run}>
|
||||
{row.action.label}
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
<span className={`setup-state is-${row.state}`}>
|
||||
{row.state === "ok" ? (
|
||||
<Check size={14} />
|
||||
) : row.state === "problem" ? (
|
||||
<X size={14} />
|
||||
) : null}
|
||||
{t(
|
||||
row.state === "ok"
|
||||
? "setupStateOk"
|
||||
: row.state === "problem"
|
||||
? "setupStateProblem"
|
||||
: "setupStateUnknown",
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{checks ? (
|
||||
<div className="setup-paths">
|
||||
{checks.map((check) => (
|
||||
<code key={check.kind}>{check.path}</code>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<footer className="setup-foot">
|
||||
<span>{t("setupFootnote")}</span>
|
||||
<button className="runtime-install" onClick={onDone}>
|
||||
{t("setupStart")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,209 @@
|
|||
import {
|
||||
Check,
|
||||
Monitor,
|
||||
Download,
|
||||
LoaderCircle,
|
||||
PackageOpen,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Sparkle,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { useUpdateFlow } from "../lib/useUpdate";
|
||||
import { formatBytes } from "../lib/utils";
|
||||
|
||||
interface Props {
|
||||
/** Raw URL of the manifest, so the panel can name the feed it just queried. */
|
||||
feedUrl: string;
|
||||
autoCheck: boolean;
|
||||
onAutoCheckChange: (enabled: boolean) => void;
|
||||
/**
|
||||
* The host this build is running on. The panel needs it because the update
|
||||
* question is per-operating-system: which artifact the feed will serve, and
|
||||
* whether a download can be installed at all, both follow from it.
|
||||
*/
|
||||
system: UpdateSystemInfo | null;
|
||||
}
|
||||
|
||||
/** Operating-system facts, read from the same probe the Runtime tab uses. */
|
||||
export interface UpdateSystemInfo {
|
||||
platform: string;
|
||||
osVersion: string;
|
||||
architecture: string;
|
||||
}
|
||||
|
||||
/** Rust reports `std::env::consts::ARCH`; the channel names the same thing differently. */
|
||||
function architectureLabel(arch: string): string {
|
||||
if (arch === "aarch64") return "ARM64";
|
||||
if (arch === "x86_64") return "x64";
|
||||
return arch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update channel backed by the git repository itself: the release branch carries
|
||||
* the installers plus a manifest of SHA256 hashes, and this panel is the only
|
||||
* place a download can be trusted. A hash mismatch is shown as an error and the
|
||||
* file is deleted, so a half-good download can never be launched.
|
||||
*/
|
||||
export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: Props) {
|
||||
const { t } = useI18n();
|
||||
// One state machine shared with any other view of the channel, driven by the
|
||||
// events Rust already broadcasts, so two views cannot offer different actions.
|
||||
const { status, checking, downloading, installing, progress, percent, check, download, install, clear } =
|
||||
useUpdateFlow();
|
||||
|
||||
const verified = status?.state === "ready";
|
||||
// Rust reports the key it resolved; the panel only repeats it.
|
||||
const artifactKey = status?.artifactKey ?? "";
|
||||
const available = status?.state === "available" || verified;
|
||||
const failed = status?.state === "error" || status?.state === "unavailable";
|
||||
|
||||
return (
|
||||
<section className="home-settings-section">
|
||||
<div className="runtime-section-head">
|
||||
<div className="home-section-title">
|
||||
<Sparkle size={15} />
|
||||
{t("updates")}
|
||||
</div>
|
||||
<button
|
||||
className="settings-link runtime-refresh"
|
||||
onClick={() => void check()}
|
||||
disabled={checking || downloading}
|
||||
>
|
||||
<RefreshCw size={12} className={checking ? "spin" : ""} />
|
||||
{checking ? t("updateChecking") : t("updateCheckNow")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="update-feed">
|
||||
<span className="update-feed-label">{t("updateFeed")}</span>
|
||||
<code title={feedUrl}>{feedUrl || t("updateFeedNone")}</code>
|
||||
{/* Only a status backed by a manifest may claim anything about trust: an
|
||||
errored check has no manifest to have verified. */}
|
||||
{status && status.state !== "error" ? (
|
||||
<span className={`update-trust is-${status.signed ? "signed" : "unsigned"}`}>
|
||||
<ShieldCheck size={11} />
|
||||
{t(status.signed ? "updateSigned" : "updateUnsigned")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Which artifact the feed serves, and whether it can be installed at all,
|
||||
are both decided by the host. Saying it here is what makes an "no artifact
|
||||
for this platform" answer explain itself. */}
|
||||
<div className="update-system">
|
||||
<Monitor size={13} />
|
||||
<span className="update-system-label">{t("updateSystem")}</span>
|
||||
{system ? (
|
||||
<span className="update-system-host">
|
||||
<strong>{system.osVersion || system.platform}</strong>
|
||||
<small>{architectureLabel(system.architecture)}</small>
|
||||
</span>
|
||||
) : (
|
||||
<span className="update-system-pending">{t("updateSystemPending")}</span>
|
||||
)}
|
||||
{artifactKey ? (
|
||||
<span className="update-system-key">
|
||||
{t("updateSystemArtifact", { key: artifactKey })}
|
||||
</span>
|
||||
) : status && status.state === "unavailable" ? (
|
||||
<span className="update-system-key is-unknown">{t("updateSystemArtifactUnknown")}</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="update-status-row">
|
||||
<strong>{status?.currentVersion ?? "-"}</strong>
|
||||
{available && status ? (
|
||||
<span className="update-arrow">
|
||||
<span className="update-new">
|
||||
<Sparkle size={11} />
|
||||
{status.availableVersion}
|
||||
</span>
|
||||
<small>{status.date}</small>
|
||||
</span>
|
||||
) : null}
|
||||
<span className={`update-state is-${status?.state ?? "idle"}`}>
|
||||
{status
|
||||
? t(
|
||||
status.state === "ready"
|
||||
? "updateReady"
|
||||
: status.state === "available"
|
||||
? "updateAvailable"
|
||||
: status.state === "current"
|
||||
? "updateCurrent"
|
||||
: "updateUnavailable",
|
||||
)
|
||||
: t("updateIdle")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{status?.notes ? <p className="update-notes">{status.notes}</p> : null}
|
||||
|
||||
{status?.fileName ? (
|
||||
<div className="update-artifact">
|
||||
<PackageOpen size={13} />
|
||||
<span className="update-artifact-name" title={status.fileName}>
|
||||
{status.fileName}
|
||||
</span>
|
||||
<span className="update-artifact-size">{formatBytes(status.size)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{percent !== null ? (
|
||||
<div className="update-progress" role="progressbar" aria-valuenow={percent}>
|
||||
<div className="update-progress-fill" style={{ width: `${percent}%` }} />
|
||||
<span>
|
||||
{progress ? `${formatBytes(progress.downloaded)} / ${formatBytes(progress.total)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status?.sha256 ? (
|
||||
<code className="update-hash" title={status.sha256}>
|
||||
<ShieldCheck size={11} />
|
||||
SHA256 {verified ? status.sha256 : `${status.sha256.slice(0, 16)}…`}
|
||||
</code>
|
||||
) : null}
|
||||
|
||||
{status?.message && (failed || verified) ? (
|
||||
<div className={`runtime-error ${verified ? "is-ok" : ""}`}>
|
||||
<span>{verified ? t("updateVerified") : status.message}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="update-actions">
|
||||
{available && !verified ? (
|
||||
<button className="runtime-install" onClick={() => void download()} disabled={downloading}>
|
||||
{downloading ? <LoaderCircle size={12} className="spin" /> : <Download size={12} />}
|
||||
{downloading ? t("updateDownloading") : t("updateDownload")}
|
||||
</button>
|
||||
) : null}
|
||||
{verified ? (
|
||||
<button className="runtime-install" onClick={() => void install()} disabled={installing}>
|
||||
{installing ? <LoaderCircle size={12} className="spin" /> : <Check size={12} />}
|
||||
{t("updateInstall")}
|
||||
</button>
|
||||
) : null}
|
||||
{verified ? (
|
||||
<button className="settings-link" onClick={() => void clear()}>
|
||||
<X size={12} />
|
||||
{t("updateDiscard")}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label className="home-toggle-row home-toggle-divider">
|
||||
<strong>{t("updateAutoCheck")}</strong>
|
||||
<button
|
||||
className={`home-toggle ${autoCheck ? "is-on" : ""}`}
|
||||
onClick={() => onAutoCheckChange(!autoCheck)}
|
||||
aria-pressed={autoCheck}
|
||||
>
|
||||
<span />
|
||||
</button>
|
||||
</label>
|
||||
<p className="runtime-summary">{t("updateBody")}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
167
src/i18n.ts
167
src/i18n.ts
|
|
@ -31,7 +31,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
convert: "Convert",
|
||||
compress: "Compress",
|
||||
redact: "Redact",
|
||||
metadata: "Metadata",
|
||||
stripMetadata: "Strip metadata",
|
||||
edit: "Edit",
|
||||
annotate: "Annotate",
|
||||
rectangle: "Rectangle",
|
||||
|
|
@ -39,7 +39,12 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
highlight: "Highlight",
|
||||
textAnnotation: "Text",
|
||||
pixelate: "Pixelate",
|
||||
blur: "Blur",
|
||||
number: "Number",
|
||||
stamp: "Stamp",
|
||||
stampCheck: "Check",
|
||||
stampCross: "Cross",
|
||||
stampStar: "Star",
|
||||
undo: "Undo",
|
||||
saveCopy: "Save copy",
|
||||
applyCrop: "Apply crop",
|
||||
|
|
@ -81,6 +86,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
startRecording: "Start recording",
|
||||
stopRecording: "Stop recording",
|
||||
audio: "Audio",
|
||||
frameRate: "Frame rate",
|
||||
dragSelect: "Drag to select an area",
|
||||
recordingSaved: "Recording saved",
|
||||
ocrTitle: "Extract text",
|
||||
|
|
@ -159,6 +165,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
checkAccess: "Check folders",
|
||||
accessOk: "Write access confirmed.",
|
||||
runtimeComponents: "Runtime components",
|
||||
runtimeOpenPanel: "Open Runtime components",
|
||||
languageSaveFailed: "The language could not be saved. Try again.",
|
||||
runtimeRefresh: "Refresh",
|
||||
runtimeChecking: "Inspecting…",
|
||||
|
|
@ -186,11 +193,86 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
runtimeSource_bundled: "Built-in",
|
||||
runtimeSource_system: "System",
|
||||
runtimeSource_external: "External",
|
||||
updates: "Updates",
|
||||
updateCheckNow: "Check now",
|
||||
updateChecking: "Checking…",
|
||||
updateFeed: "Feed",
|
||||
updateFeedNone: "Not configured for this build",
|
||||
updateSystem: "This machine",
|
||||
updateSystemPending: "Reading operating system…",
|
||||
updateSystemArtifact: "Installs the \u201c{key}\u201d artifact",
|
||||
updateSystemArtifactUnknown: "This release names no artifact for this machine",
|
||||
updateIdle: "Not checked yet",
|
||||
updateAvailable: "Update available",
|
||||
updateCurrent: "Up to date",
|
||||
updateReady: "Downloaded and verified",
|
||||
updateUnavailable: "No artifact for this platform",
|
||||
updateDownload: "Download & verify",
|
||||
updateDownloading: "Downloading…",
|
||||
updateInstall: "Install update",
|
||||
updateDiscard: "Discard",
|
||||
updateVerified: "SHA256 matched the manifest.",
|
||||
updateSigned: "Manifest signature verified against the release key.",
|
||||
updateUnsigned: "This build cannot verify a manifest signature, so the manifest is trusted through HTTPS alone. The SHA256 gate still applies.",
|
||||
updateAutoCheck: "Check for updates daily",
|
||||
updateBody:
|
||||
"Releases come from this repository’s release branch. Every download is re-hashed and must match the manifest before it can be installed.",
|
||||
radial: "Radial rings",
|
||||
radialKind: "File type preset",
|
||||
ringActions: "Actions",
|
||||
ringTools: "Tools",
|
||||
radialOrder: "Order ({count} wedges)",
|
||||
radialOrderBody:
|
||||
"The ring only ever shows what this file type can do; this list decides where each wedge sits. Send always stays last.",
|
||||
radialOrderSave: "Save order",
|
||||
moveUp: "Move up",
|
||||
moveDown: "Move down",
|
||||
kind_image: "Images",
|
||||
kind_video: "Video",
|
||||
kind_audio: "Audio",
|
||||
kind_pdf: "PDF",
|
||||
kind_document: "Documents",
|
||||
kind_presentation: "Slides",
|
||||
kind_spreadsheet: "Spreadsheets",
|
||||
kind_other: "Other files",
|
||||
setupTitle: "Before you start",
|
||||
setupIntro: "Shift works offline and installs nothing. These are the four things that can quietly stop it working on this machine.",
|
||||
setupRecheck: "Run the checks again",
|
||||
setupChecking: "Checking…",
|
||||
setupStart: "Start using Shift",
|
||||
setupFootnote: "Rerun them any time: permissions, folders and tools are under Settings, and a shortcut problem shows on this window.",
|
||||
setupCheckFailed: "Could not read this status on this machine.",
|
||||
setupStateOk: "Ready",
|
||||
setupStateProblem: "Needs you",
|
||||
setupStateUnknown: "Not checked",
|
||||
setupRow_capture: "Screen Recording",
|
||||
setupRow_folders: "Output folders",
|
||||
setupRow_shortcuts: "Global shortcuts",
|
||||
setupRow_tools: "Optional tools",
|
||||
setupCaptureOk: "Screen capture is allowed.",
|
||||
setupFoldersOk: "All three output folders are writable.",
|
||||
setupShortcutsOk: "This copy owns the global shortcuts.",
|
||||
setupToolsOk: "Every optional tool this app uses is installed.",
|
||||
setupToolsMissing: "{count} optional tool(s) are missing. Core conversion works without them; those wedges stay empty.",
|
||||
permissions: "Permissions",
|
||||
screenPermission: "Screen Recording",
|
||||
screenPermissionPrompt:
|
||||
"Screen Recording is off. Enable it to capture screenshots and recordings.",
|
||||
filesPermission: "Files & Folders",
|
||||
captureSaved: "Capture saved",
|
||||
copied: "Copied",
|
||||
clearHistory: "Clear",
|
||||
searchHistory: "Search captures and results",
|
||||
historyNoMatches: "Nothing matches “{query}”.",
|
||||
pinToRecent: "Keep in the library",
|
||||
unpinFromRecent: "Stop keeping",
|
||||
forget: "Remove from the list",
|
||||
dragOutHint: "Click to open, or drag this row out to hand over the file",
|
||||
captureAfter: "After capture",
|
||||
captureAfterCard: "Result card",
|
||||
captureAfterEditor: "Open editor",
|
||||
captureAfterBody:
|
||||
"The card floats where the capture landed with Copy, Pin, Send and Edit on it, then fades away.",
|
||||
agoNow: "just now",
|
||||
agoMinutes: "{count}m ago",
|
||||
agoHours: "{count}h ago",
|
||||
|
|
@ -222,7 +304,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
convert: "转换",
|
||||
compress: "压缩",
|
||||
redact: "打码",
|
||||
metadata: "元数据",
|
||||
stripMetadata: "移除元数据",
|
||||
edit: "编辑",
|
||||
annotate: "标注",
|
||||
rectangle: "矩形",
|
||||
|
|
@ -230,7 +312,12 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
highlight: "高亮",
|
||||
textAnnotation: "文字",
|
||||
pixelate: "马赛克",
|
||||
blur: "模糊",
|
||||
number: "序号",
|
||||
stamp: "印章",
|
||||
stampCheck: "对勾",
|
||||
stampCross: "叉号",
|
||||
stampStar: "星标",
|
||||
undo: "撤销",
|
||||
saveCopy: "保存副本",
|
||||
applyCrop: "应用裁剪",
|
||||
|
|
@ -272,6 +359,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
startRecording: "开始录屏",
|
||||
stopRecording: "停止录屏",
|
||||
audio: "声音",
|
||||
frameRate: "帧率",
|
||||
dragSelect: "拖动框选区域",
|
||||
recordingSaved: "录屏已保存",
|
||||
ocrTitle: "提取文字",
|
||||
|
|
@ -349,6 +437,7 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
checkAccess: "检测目录",
|
||||
accessOk: "写入权限正常。",
|
||||
runtimeComponents: "运行组件",
|
||||
runtimeOpenPanel: "打开运行组件",
|
||||
languageSaveFailed: "语言设置保存失败,请重试。",
|
||||
runtimeRefresh: "重新检测",
|
||||
runtimeChecking: "检测中…",
|
||||
|
|
@ -374,10 +463,84 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
runtimeSource_bundled: "内置",
|
||||
runtimeSource_system: "系统",
|
||||
runtimeSource_external: "外部",
|
||||
updates: "软件更新",
|
||||
updateCheckNow: "立即检查",
|
||||
updateChecking: "检查中…",
|
||||
updateFeed: "更新源",
|
||||
updateFeedNone: "当前构建未配置更新源",
|
||||
updateSystem: "本机",
|
||||
updateSystemPending: "正在读取系统信息…",
|
||||
updateSystemArtifact: "将安装「{key}」产物",
|
||||
updateSystemArtifactUnknown: "本次发布没有为本机准备产物",
|
||||
updateIdle: "尚未检查",
|
||||
updateAvailable: "发现新版本",
|
||||
updateCurrent: "已是最新版本",
|
||||
updateReady: "已下载并校验",
|
||||
updateUnavailable: "该平台没有对应安装包",
|
||||
updateDownload: "下载并校验",
|
||||
updateDownloading: "下载中…",
|
||||
updateInstall: "安装更新",
|
||||
updateDiscard: "放弃",
|
||||
updateVerified: "SHA256 与清单一致。",
|
||||
updateSigned: "清单签名已用发布公钥验证通过。",
|
||||
updateUnsigned: "本构建内置的公钥无法验证清单签名,因此清单本身只依赖 HTTPS 通道的信任;SHA256 校验依然生效。",
|
||||
updateAutoCheck: "每天自动检查更新",
|
||||
updateBody:
|
||||
"更新包来自本仓库的 release 分支。下载后会重新计算 SHA256,只有与清单一致才允许安装。",
|
||||
radial: "环形菜单",
|
||||
radialKind: "文件类型预设",
|
||||
ringActions: "快捷操作",
|
||||
ringTools: "工具",
|
||||
radialOrder: "顺序({count} 项)",
|
||||
radialOrderBody: "环形菜单只显示这种文件真正支持的操作,这里决定每一项的位置。“发送”始终排在最后。",
|
||||
radialOrderSave: "保存顺序",
|
||||
moveUp: "上移",
|
||||
moveDown: "下移",
|
||||
kind_image: "图片",
|
||||
kind_video: "视频",
|
||||
kind_audio: "音频",
|
||||
kind_pdf: "PDF",
|
||||
kind_document: "文档",
|
||||
kind_presentation: "演示文稿",
|
||||
kind_spreadsheet: "表格",
|
||||
kind_other: "其他文件",
|
||||
setupTitle: "开始前先检查",
|
||||
setupIntro: "Shift 全程离线运行,也不会往系统里装任何东西。以下四项是唯一可能让它在当前电脑上悄悄失效的地方。",
|
||||
setupRecheck: "重新检查",
|
||||
setupChecking: "检查中…",
|
||||
setupStart: "开始使用 Shift",
|
||||
setupFootnote: "随时可重新检查:权限、输出目录与工具都在设置里,快捷键异常会直接显示在主窗口上。",
|
||||
setupCheckFailed: "在当前系统上无法读取该项状态。",
|
||||
setupStateOk: "已就绪",
|
||||
setupStateProblem: "需要你处理",
|
||||
setupStateUnknown: "未检查",
|
||||
setupRow_capture: "屏幕录制权限",
|
||||
setupRow_folders: "输出文件夹",
|
||||
setupRow_shortcuts: "全局快捷键",
|
||||
setupRow_tools: "可选工具",
|
||||
setupCaptureOk: "已授予屏幕录制权限。",
|
||||
setupFoldersOk: "三个输出目录均可写。",
|
||||
setupShortcutsOk: "当前实例已持有全局快捷键。",
|
||||
setupToolsOk: "本应用会用到的可选工具都已安装。",
|
||||
setupToolsMissing: "缺少 {count} 个可选工具。核心转换无需它们即可工作,只有对应的扇区会空着。",
|
||||
permissions: "系统权限",
|
||||
screenPermission: "屏幕录制",
|
||||
screenPermissionPrompt: "屏幕录制权限未开启,截图和录屏需要该权限。",
|
||||
filesPermission: "文件与文件夹",
|
||||
captureSaved: "截图已保存",
|
||||
copied: "已复制",
|
||||
clearHistory: "清空",
|
||||
searchHistory: "搜索截图与结果",
|
||||
historyNoMatches: "没有与“{query}”匹配的记录。",
|
||||
pinToRecent: "保留在库中",
|
||||
unpinFromRecent: "取消保留",
|
||||
forget: "从列表移除",
|
||||
dragOutHint: "点击打开,或把这一行拖出去即可交付文件",
|
||||
captureAfter: "截图后",
|
||||
captureAfterCard: "结果卡片",
|
||||
captureAfterEditor: "打开编辑器",
|
||||
captureAfterBody:
|
||||
"卡片悬停在屏幕角落,提供复制、钉住、发送与编辑,然后自动消失。",
|
||||
agoNow: "刚刚",
|
||||
agoMinutes: "{count} 分钟前",
|
||||
agoHours: "{count} 小时前",
|
||||
|
|
|
|||
|
|
@ -10,14 +10,18 @@ import type {
|
|||
FileOutputMode,
|
||||
NormalizedRect,
|
||||
RadialContext,
|
||||
RecordingCapabilities,
|
||||
RecordingInfo,
|
||||
RecordingOptions,
|
||||
SharePeer,
|
||||
RuntimeInfo,
|
||||
SwitchState,
|
||||
SwitchUpdate,
|
||||
UpdateProgress,
|
||||
UpdateStatus,
|
||||
WriteCheck,
|
||||
} from "../types";
|
||||
import type { FileKind, RadialRing, WedgeOrders } from "./radialOrder";
|
||||
|
||||
interface FileActionResultEvent {
|
||||
jobId: string;
|
||||
|
|
@ -77,7 +81,6 @@ export const api = {
|
|||
inspectFiles: (paths: string[]) => invoke<FileInfo[]>("inspect_files", { paths }),
|
||||
performFileAction,
|
||||
revealFile: (path: string) => invoke<void>("reveal_file", { path }),
|
||||
existingFiles: (paths: string[]) => invoke<string[]>("existing_files", { paths }),
|
||||
openFile: (path: string) => invoke<void>("open_file", { path }),
|
||||
readTextFile: (path: string) => invoke<string>("read_text_file", { path }),
|
||||
readImageData: (path: string) => invoke<string>("read_image_data", { path }),
|
||||
|
|
@ -99,6 +102,7 @@ export const api = {
|
|||
captureFullscreen: () => invoke<string>("capture_fullscreen"),
|
||||
startRecording: (rect: NormalizedRect, options?: RecordingOptions) =>
|
||||
invoke<RecordingInfo>("start_recording", { rect, options }),
|
||||
recordingCapabilities: () => invoke<RecordingCapabilities>("recording_capabilities"),
|
||||
stopRecording: () => invoke<RecordingInfo | null>("stop_recording"),
|
||||
recordingStatus: () => invoke<RecordingInfo | null>("recording_status"),
|
||||
getEditorSession: () => invoke<EditorInfo | null>("get_editor_session"),
|
||||
|
|
@ -138,6 +142,24 @@ export const api = {
|
|||
revealOutputDirectory: (kind: "screenshot" | "recording" | "files") =>
|
||||
invoke<void>("reveal_output_directory", { kind }),
|
||||
openFilesPermissionSettings: () => invoke<void>("open_files_permission_settings"),
|
||||
setCaptureAfter: (after: "card" | "editor") =>
|
||||
invoke<AppSettings>("set_capture_after", { after }),
|
||||
setUpdateCheckEnabled: (enabled: boolean) =>
|
||||
invoke<SwitchState>("set_update_check_enabled", { enabled }),
|
||||
setSetupReviewed: (reviewed: boolean) => invoke<boolean>("set_setup_reviewed", { reviewed }),
|
||||
getWedgeOrders: () => invoke<WedgeOrders>("get_wedge_orders"),
|
||||
setWedgeOrder: (kind: FileKind, ring: RadialRing, order: string[]) =>
|
||||
invoke<AppSettings>("set_wedge_order", { kind, ring, order }),
|
||||
updateCheck: () =>
|
||||
invoke<{ status: UpdateStatus; downloadReady: boolean }>("update_check"),
|
||||
updateStatus: () => invoke<UpdateStatus | null>("update_status"),
|
||||
updateDownload: () => invoke<UpdateStatus>("update_download"),
|
||||
updateInstall: () => invoke<string>("update_install"),
|
||||
updateClear: () => invoke<void>("update_clear"),
|
||||
onUpdateProgress: (handler: (progress: UpdateProgress) => void) =>
|
||||
listen<UpdateProgress>("update://progress", (event) => handler(event.payload)),
|
||||
onUpdateStatus: (handler: (status: UpdateStatus | null) => void) =>
|
||||
listen<UpdateStatus | null>("update://status", (event) => handler(event.payload)),
|
||||
getRuntimeInfo: () => invoke<RuntimeInfo>("machine_info"),
|
||||
installRuntimeComponent: (componentId: string) =>
|
||||
invoke<string>("install_runtime_component", { componentId }),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { dragOutPayload, fileUrl } from "./dragOut.ts";
|
||||
|
||||
test("unix paths become file URLs with separators kept", () => {
|
||||
assert.equal(fileUrl("/Users/me/Shift/photo.png"), "file:///Users/me/Shift/photo.png");
|
||||
});
|
||||
|
||||
test("spaces and unicode are percent-encoded", () => {
|
||||
assert.equal(
|
||||
fileUrl("/Users/me/My Shift/截图 1.png"),
|
||||
"file:///Users/me/My%20Shift/%E6%88%AA%E5%9B%BE%201.png",
|
||||
);
|
||||
});
|
||||
|
||||
test("windows paths keep their drive letter", () => {
|
||||
assert.equal(fileUrl("C:\\Users\\me\\Shift\\photo.png"), "file:///C:/Users/me/Shift/photo.png");
|
||||
assert.equal(fileUrl("C:\\Users\\me\\a b.pdf"), "file:///C:/Users/me/a%20b.pdf");
|
||||
});
|
||||
|
||||
test("repeated separators collapse", () => {
|
||||
assert.equal(fileUrl("/Users//me///x.png"), "file:///Users/me/x.png");
|
||||
});
|
||||
|
||||
test("a row is offered as uri-list, plain path and share paths", () => {
|
||||
const payload = dragOutPayload("/tmp/a.png");
|
||||
assert.deepEqual(payload, {
|
||||
"text/uri-list": "file:///tmp/a.png",
|
||||
"text/plain": "/tmp/a.png",
|
||||
"application/x-shift-share-paths": JSON.stringify(["/tmp/a.png"]),
|
||||
});
|
||||
});
|
||||
|
||||
test("unc shares are readable too", () => {
|
||||
assert.equal(fileUrl("\\\\server\\share\\a.pdf"), "file:///server/share/a.pdf");
|
||||
});
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
* Payload for dragging a library row out of Shift.
|
||||
*
|
||||
* A row is dragged as a file URL rather than as text: WebKit promotes a `file://`
|
||||
* entry in `text/uri-list` into a real file drop, so Finder, mail composers and chat
|
||||
* apps receive the file instead of a path string. Plain text still carries the path for
|
||||
* editors, and Shift's own drop zones read the internal type so a row can be dragged
|
||||
* back onto the ring.
|
||||
*/
|
||||
const SHARE_PATH_TYPE = "application/x-shift-share-paths";
|
||||
|
||||
/** Encode a path segment but leave a Windows drive colon readable. */
|
||||
function encodeSegment(segment: string): string {
|
||||
return encodeURIComponent(segment).replace(/%3A/gi, ":");
|
||||
}
|
||||
|
||||
/** `file://` URL for a local path, percent-encoded but keeping path separators. */
|
||||
export function fileUrl(path: string): string {
|
||||
const unc = path.startsWith("\\\\");
|
||||
const windows = /^[a-zA-Z]:[\\/]/.test(path) || unc;
|
||||
const segments = path.split(windows ? /[\\/]+/ : /\/+/).filter(Boolean).map(encodeSegment);
|
||||
return `file:///${segments.join("/")}`;
|
||||
}
|
||||
|
||||
/** The three flavours a receiving application can pick up, keyed by MIME type. */
|
||||
export function dragOutPayload(path: string): Record<string, string> {
|
||||
const uri = fileUrl(path);
|
||||
return {
|
||||
"text/uri-list": uri,
|
||||
"text/plain": path,
|
||||
[SHARE_PATH_TYPE]: JSON.stringify([path]),
|
||||
};
|
||||
}
|
||||
|
||||
export const SHARE_PATHS_TYPE = SHARE_PATH_TYPE;
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
announceRecentChange,
|
||||
getLocalRecentItems,
|
||||
type RecentItem,
|
||||
setLocalRecentItems,
|
||||
} from "./utils";
|
||||
|
||||
/**
|
||||
* Frontend half of the history library. Rust owns the list and writes it the
|
||||
* moment a capture, conversion or received file lands, so a window never has to
|
||||
* report its own results; this module just reads the list, applies the handful of
|
||||
* edits the UI offers, and re-renders when Rust broadcasts a change. Outside
|
||||
* Tauri the same API reads and writes the browser store so a plain webview
|
||||
* preview still shows something.
|
||||
*/
|
||||
async function request<T>(command: string, args?: Record<string, unknown>): Promise<T> {
|
||||
return invoke<T>(command, args);
|
||||
}
|
||||
|
||||
function fallback(list: RecentItem[]): RecentItem[] {
|
||||
setLocalRecentItems(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
export const history = {
|
||||
async list(): Promise<RecentItem[]> {
|
||||
if (!isTauri()) return getLocalRecentItems();
|
||||
return request<RecentItem[]>("history_list");
|
||||
},
|
||||
|
||||
/** Record paths that just became available, e.g. an editor save. */
|
||||
async record(paths: string[]): Promise<RecentItem[]> {
|
||||
const usable = paths.filter(Boolean);
|
||||
if (usable.length === 0) return this.list();
|
||||
if (!isTauri()) {
|
||||
const fresh: RecentItem[] = usable.map((path) => ({
|
||||
path,
|
||||
kind: "file",
|
||||
at: Date.now(),
|
||||
pinned: false,
|
||||
}));
|
||||
const merged = [...fresh, ...getLocalRecentItems().filter((e) => !usable.includes(e.path))];
|
||||
return fallback(merged);
|
||||
}
|
||||
return request<RecentItem[]>("history_record", { paths: usable });
|
||||
},
|
||||
|
||||
async setPinned(path: string, pinned: boolean): Promise<RecentItem[]> {
|
||||
if (!isTauri())
|
||||
return fallback(
|
||||
getLocalRecentItems().map((entry) => (entry.path === path ? { ...entry, pinned } : entry)),
|
||||
);
|
||||
return request<RecentItem[]>("history_set_pinned", { path, pinned });
|
||||
},
|
||||
|
||||
async remove(path: string): Promise<RecentItem[]> {
|
||||
if (!isTauri())
|
||||
return fallback(getLocalRecentItems().filter((entry) => entry.path !== path));
|
||||
return request<RecentItem[]>("history_remove", { path });
|
||||
},
|
||||
|
||||
async clear(): Promise<RecentItem[]> {
|
||||
if (!isTauri()) return fallback([]);
|
||||
return request<RecentItem[]>("history_clear");
|
||||
},
|
||||
|
||||
/** Rust republishes the whole list on every change, including from other windows. */
|
||||
onChanged(handler: (items: RecentItem[]) => void) {
|
||||
if (!isTauri()) {
|
||||
// The browser store only changes in this window, so a local event is enough.
|
||||
const listener = () => handler(getLocalRecentItems());
|
||||
window.addEventListener("shift:recent", listener);
|
||||
return () => window.removeEventListener("shift:recent", listener);
|
||||
}
|
||||
let disposed = false;
|
||||
let unlisten: (() => void) | undefined;
|
||||
void listen<RecentItem[]>("history://changed", (event) => {
|
||||
if (!disposed) handler(event.payload);
|
||||
}).then((stop) => {
|
||||
if (disposed) stop();
|
||||
else unlisten = stop;
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
unlisten?.();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Kept so a caller that only has a path can still announce a local change. */
|
||||
export { announceRecentChange };
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import {
|
||||
ORDERABLE_KINDS,
|
||||
WEDGE_ACTION_IDS,
|
||||
defaultWedgeIds,
|
||||
hasCustomOrder,
|
||||
isOrderDirty,
|
||||
moveWedge,
|
||||
orderWedgeIds,
|
||||
presetWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
wedgeOrderKey,
|
||||
} from "./radialOrder.ts";
|
||||
|
||||
const IMAGE_FORMATS = ["PNG", "JPG", "WEBP", "HEIC", "TIFF", "BMP", "GIF", "PDF"];
|
||||
|
||||
test("image action ring keeps its default catalogue", () => {
|
||||
assert.deepEqual(defaultWedgeIds("actions", "image", IMAGE_FORMATS), [
|
||||
"compress",
|
||||
"metadata",
|
||||
"edit",
|
||||
"annotate",
|
||||
"addBackground",
|
||||
"crop",
|
||||
"redact",
|
||||
"ocr",
|
||||
"convert",
|
||||
]);
|
||||
});
|
||||
|
||||
test("image tool ring keeps its default catalogue", () => {
|
||||
assert.deepEqual(defaultWedgeIds("tools", "image"), [
|
||||
"rotate",
|
||||
"flip",
|
||||
"grayscale",
|
||||
"resizeHalf",
|
||||
"compress",
|
||||
"metadata",
|
||||
"crop",
|
||||
"cutout",
|
||||
]);
|
||||
});
|
||||
|
||||
test("merge joins only image and pdf rings once files are selected", () => {
|
||||
assert.deepEqual(defaultWedgeIds("tools", "image", [], true).slice(-1), ["merge"]);
|
||||
assert.deepEqual(defaultWedgeIds("tools", "pdf", [], true).slice(-1), ["merge"]);
|
||||
assert.equal(defaultWedgeIds("tools", "video", [], true).includes("merge"), false);
|
||||
assert.equal(defaultWedgeIds("tools", "image", [], false).includes("merge"), false);
|
||||
assert.equal(defaultWedgeIds("actions", "image", IMAGE_FORMATS, false).includes("merge"), false);
|
||||
});
|
||||
|
||||
test("a document that cannot convert has no convert wedge", () => {
|
||||
assert.deepEqual(defaultWedgeIds("actions", "document", []), [
|
||||
"edit",
|
||||
"open",
|
||||
"reveal",
|
||||
]);
|
||||
assert.deepEqual(defaultWedgeIds("actions", "document", ["PDF"]), [
|
||||
"convert",
|
||||
"edit",
|
||||
"open",
|
||||
"reveal",
|
||||
]);
|
||||
});
|
||||
|
||||
test("the format ring is the catalogue lowercased", () => {
|
||||
assert.deepEqual(defaultWedgeIds("formats", "image", IMAGE_FORMATS), [
|
||||
"png",
|
||||
"jpg",
|
||||
"webp",
|
||||
"heic",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"gif",
|
||||
"pdf",
|
||||
]);
|
||||
});
|
||||
|
||||
test("a saved order leads and unknown ids are dropped", () => {
|
||||
const ids = ["compress", "ocr", "convert"];
|
||||
assert.deepEqual(orderWedgeIds(ids, ["convert", "stale", "ocr"]), ["convert", "ocr", "compress"]);
|
||||
});
|
||||
|
||||
test("an order missing a wedge leaves it in default relative order", () => {
|
||||
const ids = ["rotate", "flip", "crop", "newcomer"];
|
||||
assert.deepEqual(orderWedgeIds(ids, ["crop", "rotate"]), ["crop", "rotate", "flip", "newcomer"]);
|
||||
});
|
||||
|
||||
test("no saved order means the default order", () => {
|
||||
const ids = ["a", "b"];
|
||||
assert.deepEqual(orderWedgeIds(ids), ids);
|
||||
assert.deepEqual(orderWedgeIds(ids, []), ids);
|
||||
});
|
||||
|
||||
test("moving a wedge clamps at both ends", () => {
|
||||
const ids = ["a", "b", "c"];
|
||||
assert.deepEqual(moveWedge(ids, 0, -1), ids);
|
||||
assert.deepEqual(moveWedge(ids, 2, 1), ids);
|
||||
assert.deepEqual(moveWedge(ids, 1, -1), ["b", "a", "c"]);
|
||||
assert.deepEqual(moveWedge(ids, 1, 1), ["a", "c", "b"]);
|
||||
});
|
||||
|
||||
test("orders are stored per kind and ring", () => {
|
||||
assert.equal(wedgeOrderKey("image", "tools"), "image/tools");
|
||||
const orders = { "image/tools": ["crop"] };
|
||||
assert.deepEqual(savedOrderFor(orders, "image", "tools"), ["crop"]);
|
||||
assert.equal(savedOrderFor(orders, "image", "actions"), undefined);
|
||||
assert.equal(savedOrderFor(orders, "pdf", "tools"), undefined);
|
||||
assert.equal(savedOrderFor({ "image/tools": [] }, "image", "tools"), undefined);
|
||||
assert.equal(savedOrderFor(undefined, "image", "tools"), undefined);
|
||||
});
|
||||
|
||||
test("wedge labels reuse the ring's own wording", () => {
|
||||
assert.equal(wedgeLabelKey("grayscale"), "blackWhite");
|
||||
assert.equal(wedgeLabelKey("resizeHalf"), "halfSize");
|
||||
assert.equal(wedgeLabelKey("pdfOcr"), "ocr");
|
||||
assert.equal(wedgeLabelKey("text"), "extractText");
|
||||
assert.equal(wedgeLabelKey("compress"), "compress");
|
||||
// The wedge strips, so the ring says so rather than offering a lookup.
|
||||
assert.equal(wedgeLabelKey("metadata"), "stripMetadata");
|
||||
});
|
||||
|
||||
test("a kind is marked custom once any of its rings is reordered", () => {
|
||||
const orders = { "image/tools": ["crop"], "pdf/actions": ["split"] };
|
||||
assert.equal(hasCustomOrder(orders, "image"), true);
|
||||
assert.equal(hasCustomOrder(orders, "pdf"), true);
|
||||
assert.equal(hasCustomOrder(orders, "video"), false);
|
||||
assert.equal(hasCustomOrder({ "image/tools": [] }, "image"), false);
|
||||
});
|
||||
|
||||
test("saving is offered only when the draft differs from storage", () => {
|
||||
const catalogue = ["compress", "crop", "ocr"];
|
||||
assert.equal(isOrderDirty(catalogue, catalogue), false);
|
||||
assert.equal(isOrderDirty(["crop", "compress", "ocr"], catalogue), true);
|
||||
// Reordering into the same visible sequence is not a change.
|
||||
assert.equal(isOrderDirty(["crop", "compress", "ocr"], catalogue, ["crop"]), false);
|
||||
assert.equal(isOrderDirty(["crop", "compress"], catalogue, ["crop"]), true);
|
||||
});
|
||||
|
||||
test("the derived action list covers every catalogue wedge", () => {
|
||||
// Send is appended by the menu, so it is deliberately absent.
|
||||
assert.equal(WEDGE_ACTION_IDS.includes("send"), false);
|
||||
for (const kind of ORDERABLE_KINDS) {
|
||||
for (const id of defaultWedgeIds("tools", kind, [], true)) {
|
||||
assert.equal(WEDGE_ACTION_IDS.includes(id), true, `${kind}/tools ${id}`);
|
||||
}
|
||||
for (const id of defaultWedgeIds("actions", kind, ["PNG", "PDF"], true)) {
|
||||
assert.equal(WEDGE_ACTION_IDS.includes(id), true, `${kind}/actions ${id}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a preset shows the wedges the ring offers for that kind", () => {
|
||||
// Convert only appears where a typical source of the kind has targets.
|
||||
assert.equal(presetWedgeIds("image", "actions").includes("convert"), true);
|
||||
assert.equal(presetWedgeIds("image", "actions").includes("crop"), true);
|
||||
assert.equal(presetWedgeIds("video", "tools").includes("extractAudio"), true);
|
||||
assert.equal(presetWedgeIds("pdf", "tools").includes("split"), true);
|
||||
assert.equal(presetWedgeIds("document", "actions").includes("convert"), true);
|
||||
// Merge follows the multi-select rule, so the preset always shows it.
|
||||
assert.equal(presetWedgeIds("image", "tools").at(-1), "merge");
|
||||
assert.equal(presetWedgeIds("audio", "tools").includes("merge"), false);
|
||||
// Send is appended after ordering, so it never appears in the editable list.
|
||||
assert.equal(presetWedgeIds("image", "tools").includes("send"), false);
|
||||
});
|
||||
|
||||
test("every kind has a preset for both editable rings", () => {
|
||||
for (const kind of ORDERABLE_KINDS) {
|
||||
assert.ok(presetWedgeIds(kind, "actions").length > 0, kind);
|
||||
assert.ok(presetWedgeIds(kind, "tools").length > 0, kind);
|
||||
}
|
||||
});
|
||||
|
|
@ -0,0 +1,254 @@
|
|||
/**
|
||||
* The wedge catalogue for the radial rings, plus the ordering rules behind the
|
||||
* "custom radial order" setting.
|
||||
*
|
||||
* The rings used to hard-code their wedge lists inline in RadialMenu, which made a
|
||||
* user-chosen order impossible to express. Now every ring is described here as a
|
||||
* list of wedge ids for a file kind, and the menu only ever renders
|
||||
* `orderWedgeIds(defaultWedgeIds(...), savedOrder)` — so the default order is
|
||||
* whatever this module says, and a saved order can only rearrange those ids.
|
||||
* Ids the catalogue no longer offers are dropped, and new ids slide in at their
|
||||
* default position, so a saved order never hides or duplicates a wedge.
|
||||
*/
|
||||
import { conversionFormats } from "./conversionFormats.ts";
|
||||
import type { FileInfo } from "../types";
|
||||
|
||||
export type RadialRing = "actions" | "formats" | "tools";
|
||||
export type FileKind = FileInfo["kind"];
|
||||
|
||||
/** Per-kind and per-ring saved orders, keyed by `wedgeOrderKey`. */
|
||||
export type WedgeOrders = Record<string, string[]>;
|
||||
|
||||
/** Kinds that get their own preset in Settings, in display order. */
|
||||
export const ORDERABLE_KINDS: FileKind[] = [
|
||||
"image",
|
||||
"video",
|
||||
"audio",
|
||||
"pdf",
|
||||
"document",
|
||||
"presentation",
|
||||
"spreadsheet",
|
||||
"other",
|
||||
];
|
||||
|
||||
const IMAGE_ACTIONS = [
|
||||
"compress",
|
||||
"metadata",
|
||||
"edit",
|
||||
"annotate",
|
||||
"addBackground",
|
||||
"crop",
|
||||
"redact",
|
||||
"ocr",
|
||||
"convert",
|
||||
];
|
||||
const IMAGE_TOOLS = [
|
||||
"rotate",
|
||||
"flip",
|
||||
"grayscale",
|
||||
"resizeHalf",
|
||||
"compress",
|
||||
"metadata",
|
||||
"crop",
|
||||
"cutout",
|
||||
];
|
||||
const MEDIA_ACTIONS = ["convert", "compress", "edit", "reveal"];
|
||||
const VIDEO_TOOLS = ["compress", "hd720", "mute", "extractAudio", "frame", "reveal"];
|
||||
const AUDIO_TOOLS = ["compress", "mono", "reveal"];
|
||||
const PDF_ACTIONS = [
|
||||
"convert",
|
||||
"compress",
|
||||
"pdfOcr",
|
||||
"text",
|
||||
"split",
|
||||
"rotate",
|
||||
"metadata",
|
||||
"reveal",
|
||||
];
|
||||
const PDF_TOOLS = ["compress", "metadata", "rotate", "split", "text", "reveal"];
|
||||
const DOCUMENT_ACTIONS = ["convert", "edit", "open", "reveal"];
|
||||
const DOCUMENT_TOOLS = ["plain", "reveal"];
|
||||
const PLAIN_ACTIONS = ["open", "reveal"];
|
||||
const PLAIN_TOOLS = ["open", "reveal"];
|
||||
|
||||
/** Kinds whose rings gain a Merge wedge when 2+ files are selected. */
|
||||
const MERGEABLE: FileKind[] = ["image", "pdf"];
|
||||
|
||||
/**
|
||||
* Default wedge order for one ring of one file kind.
|
||||
*
|
||||
* `formats` is the format catalogue for the source (see conversionFormats); it is a
|
||||
* parameter because it depends on the source extension, which this module does not
|
||||
* know. `multi` mirrors the merge-wedge rule in the menu.
|
||||
*/
|
||||
export function defaultWedgeIds(
|
||||
ring: RadialRing,
|
||||
kind: FileKind,
|
||||
formats: string[] = [],
|
||||
multi = false,
|
||||
): string[] {
|
||||
switch (ring) {
|
||||
case "formats":
|
||||
return formats.map((format) => format.toLowerCase());
|
||||
case "tools":
|
||||
return withMerge(toolsFor(kind), kind, multi);
|
||||
case "actions":
|
||||
return withMerge(actionsFor(kind, formats.length), kind, multi);
|
||||
}
|
||||
}
|
||||
|
||||
function toolsFor(kind: FileKind): string[] {
|
||||
switch (kind) {
|
||||
case "image":
|
||||
return IMAGE_TOOLS;
|
||||
case "video":
|
||||
return VIDEO_TOOLS;
|
||||
case "audio":
|
||||
return AUDIO_TOOLS;
|
||||
case "pdf":
|
||||
return PDF_TOOLS;
|
||||
case "document":
|
||||
case "presentation":
|
||||
case "spreadsheet":
|
||||
return DOCUMENT_TOOLS;
|
||||
default:
|
||||
return PLAIN_TOOLS;
|
||||
}
|
||||
}
|
||||
|
||||
function actionsFor(kind: FileKind, formatCount: number): string[] {
|
||||
switch (kind) {
|
||||
case "image":
|
||||
return IMAGE_ACTIONS;
|
||||
case "video":
|
||||
case "audio":
|
||||
return MEDIA_ACTIONS;
|
||||
case "pdf":
|
||||
return PDF_ACTIONS;
|
||||
case "document":
|
||||
case "presentation":
|
||||
case "spreadsheet":
|
||||
// A source that cannot convert has no convert wedge to order.
|
||||
return formatCount > 0 ? DOCUMENT_ACTIONS : DOCUMENT_ACTIONS.slice(1);
|
||||
default:
|
||||
return PLAIN_ACTIONS;
|
||||
}
|
||||
}
|
||||
|
||||
function withMerge(ids: string[], kind: FileKind, multi: boolean): string[] {
|
||||
return multi && MERGEABLE.includes(kind) ? [...ids, "merge"] : ids;
|
||||
}
|
||||
|
||||
/** Send is appended by the menu after ordering, so it always sits last. */
|
||||
export const ALWAYS_LAST = "send";
|
||||
|
||||
/**
|
||||
* Every action id any catalogue mentions, derived rather than listed so a new wedge
|
||||
* cannot be added to one ring and forgotten here. The menu cross-checks this against
|
||||
* its icon table in development, which is what catches a wedge rendered with the
|
||||
* generic fallback icon.
|
||||
*/
|
||||
export const WEDGE_ACTION_IDS: string[] = Array.from(
|
||||
new Set(
|
||||
ORDERABLE_KINDS.flatMap((kind) => [
|
||||
...defaultWedgeIds("actions", kind, ["PNG", "PDF"], true),
|
||||
...defaultWedgeIds("tools", kind, [], true),
|
||||
]),
|
||||
),
|
||||
).filter((id) => id !== ALWAYS_LAST);
|
||||
|
||||
/**
|
||||
* Apply a saved order to the wedges this ring actually offers. Unknown ids are
|
||||
* ignored, missing ones keep their default slot.
|
||||
*/
|
||||
export function orderWedgeIds(ids: string[], order?: string[]): string[] {
|
||||
if (!order || order.length === 0) return [...ids];
|
||||
const leading = order.filter((id) => ids.includes(id));
|
||||
const seen = new Set(leading);
|
||||
const rest = ids.filter((id) => !seen.has(id));
|
||||
return [...leading, ...rest];
|
||||
}
|
||||
|
||||
export function wedgeOrderKey(kind: FileKind, ring: RadialRing): string {
|
||||
return `${kind}/${ring}`;
|
||||
}
|
||||
|
||||
export function savedOrderFor(
|
||||
orders: WedgeOrders | undefined,
|
||||
kind: FileKind,
|
||||
ring: RadialRing,
|
||||
): string[] | undefined {
|
||||
const value = orders?.[wedgeOrderKey(kind, ring)];
|
||||
return Array.isArray(value) && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A typical source extension per kind, so the reorder screen can show the same wedge
|
||||
* list the ring would build for that kind. The convert wedge only exists when the kind
|
||||
* has targets, and that depends on the source extension rather than the kind alone.
|
||||
*/
|
||||
const PRESET_SOURCE: Record<FileKind, string> = {
|
||||
image: "png",
|
||||
video: "mp4",
|
||||
audio: "wav",
|
||||
pdf: "pdf",
|
||||
document: "docx",
|
||||
presentation: "pptx",
|
||||
spreadsheet: "xlsx",
|
||||
other: "zip",
|
||||
};
|
||||
|
||||
/**
|
||||
* The wedge list the reorder screen shows for a preset: what the ring offers for a
|
||||
* typical source of that kind, multi-select included. Exported so the ordering rules
|
||||
* stay testable without mounting the settings panel.
|
||||
*/
|
||||
export function presetWedgeIds(kind: FileKind, ring: RadialRing): string[] {
|
||||
const formats = ring === "formats" ? [] : conversionFormats(kind, PRESET_SOURCE[kind]);
|
||||
return defaultWedgeIds(ring, kind, formats, true);
|
||||
}
|
||||
|
||||
/** Move one entry of an order list up or down; out-of-range moves are no-ops. */
|
||||
export function moveWedge(ids: string[], index: number, delta: number): string[] {
|
||||
const target = index + delta;
|
||||
if (index < 0 || index >= ids.length || target < 0 || target >= ids.length) return [...ids];
|
||||
const next = [...ids];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wedge ids whose label key differs from the id itself, so the reorder list can
|
||||
* reuse the wording the ring already uses.
|
||||
*/
|
||||
const LABEL_KEYS: Record<string, string> = {
|
||||
grayscale: "blackWhite",
|
||||
resizeHalf: "halfSize",
|
||||
pdfOcr: "ocr",
|
||||
text: "extractText",
|
||||
send: "sendShort",
|
||||
// The wedge removes metadata and writes a cleaned copy; it never shows what a file
|
||||
// carries. The id stays `metadata` so orders saved by earlier builds still resolve.
|
||||
metadata: "stripMetadata",
|
||||
};
|
||||
|
||||
export function wedgeLabelKey(id: string): string {
|
||||
return LABEL_KEYS[id] ?? id;
|
||||
}
|
||||
|
||||
/** Whether any ring of this kind carries a custom order, for the preset markers. */
|
||||
export function hasCustomOrder(orders: WedgeOrders, kind: FileKind): boolean {
|
||||
return Object.keys(orders).some(
|
||||
(key) => key.startsWith(`${kind}/`) && (orders[key]?.length ?? 0) > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a draft differs from what is stored, i.e. whether saving does anything. */
|
||||
export function isOrderDirty(
|
||||
draft: string[],
|
||||
catalogue: string[],
|
||||
saved?: string[],
|
||||
): boolean {
|
||||
const baseline = orderWedgeIds(catalogue, saved);
|
||||
return draft.length !== baseline.length || draft.some((id, index) => id !== baseline[index]);
|
||||
}
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api } from "./api";
|
||||
import type { UpdateProgress, UpdateStatus } from "../types";
|
||||
|
||||
export interface UpdateFlow {
|
||||
/** Last known result, or null when nothing has been checked this session. */
|
||||
status: UpdateStatus | null;
|
||||
checking: boolean;
|
||||
downloading: boolean;
|
||||
installing: boolean;
|
||||
progress: UpdateProgress | null;
|
||||
/** Percent of the download, or null until the first byte-aligned report. */
|
||||
percent: number | null;
|
||||
check: () => Promise<void>;
|
||||
download: () => Promise<void>;
|
||||
install: () => Promise<void>;
|
||||
clear: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The git update channel as one state machine: check the manifest, download the
|
||||
* artifact it names, refuse the install unless the recomputed SHA256 matches, then
|
||||
* hand the verified installer to the system.
|
||||
*
|
||||
* Both the main window's bar button and Settings > Updates run this hook rather than
|
||||
* keeping their own copy. Rust broadcasts `update://status` and `update://progress`,
|
||||
* so every mounted copy converges on the same state and neither can offer an action
|
||||
* the other has already finished.
|
||||
*/
|
||||
export function useUpdateFlow(): UpdateFlow {
|
||||
const [status, setStatus] = useState<UpdateStatus | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [installing, setInstalling] = useState(false);
|
||||
const [progress, setProgress] = useState<UpdateProgress | null>(null);
|
||||
const [percent, setPercent] = useState<number | null>(null);
|
||||
const mounted = useRef(true);
|
||||
// Install must refuse a status with no verified file on disk, and the callback
|
||||
// cannot read the state variable without being rebuilt on every progress tick.
|
||||
const statusRef = useRef<UpdateStatus | null>(null);
|
||||
const publish = useCallback((next: UpdateStatus | null) => {
|
||||
statusRef.current = next;
|
||||
if (mounted.current) setStatus(next);
|
||||
}, []);
|
||||
|
||||
const check = useCallback(async () => {
|
||||
if (checking) return;
|
||||
setChecking(true);
|
||||
try {
|
||||
const outcome = await api.updateCheck();
|
||||
publish(outcome.status);
|
||||
} catch {
|
||||
// A failed probe still has to be reported, and Rust holds the last result.
|
||||
publish(await api.updateStatus().catch(() => null));
|
||||
} finally {
|
||||
if (mounted.current) setChecking(false);
|
||||
}
|
||||
}, [checking, publish]);
|
||||
|
||||
const download = useCallback(async () => {
|
||||
if (downloading) return;
|
||||
setDownloading(true);
|
||||
setProgress(null);
|
||||
setPercent(null);
|
||||
try {
|
||||
const ready = await api.updateDownload();
|
||||
publish(ready);
|
||||
} catch {
|
||||
publish(await api.updateStatus().catch(() => null));
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setDownloading(false);
|
||||
setProgress(null);
|
||||
setPercent(null);
|
||||
}
|
||||
}
|
||||
}, [downloading, publish]);
|
||||
|
||||
const install = useCallback(async () => {
|
||||
if (installing || !statusRef.current?.path) return;
|
||||
setInstalling(true);
|
||||
try {
|
||||
await api.updateInstall();
|
||||
} catch (error) {
|
||||
const last = statusRef.current;
|
||||
if (last) publish({ ...last, message: String(error) });
|
||||
} finally {
|
||||
if (mounted.current) setInstalling(false);
|
||||
}
|
||||
}, [installing, publish]);
|
||||
|
||||
const clear = useCallback(async () => {
|
||||
await api.updateClear().catch(() => undefined);
|
||||
publish(null);
|
||||
}, [publish]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
// Rust keeps the last result, so a fresh window shows it without a request.
|
||||
void api
|
||||
.updateStatus()
|
||||
.then((last) => {
|
||||
if (last) publish(last);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
// Event names live in the api layer, the same one every other view uses.
|
||||
const unlisteners: (() => void)[] = [];
|
||||
void api
|
||||
.onUpdateProgress((next) => {
|
||||
if (!mounted.current) return;
|
||||
setProgress(next);
|
||||
setPercent(next.total > 0 ? Math.min(100, Math.round((next.downloaded / next.total) * 100)) : null);
|
||||
})
|
||||
.then((stop) => unlisteners.push(stop));
|
||||
void api
|
||||
.onUpdateStatus((next) => {
|
||||
statusRef.current = next;
|
||||
if (mounted.current) setStatus(next);
|
||||
})
|
||||
.then((stop) => unlisteners.push(stop));
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
unlisteners.forEach((stop) => stop());
|
||||
};
|
||||
}, [publish]);
|
||||
|
||||
return {
|
||||
status,
|
||||
checking,
|
||||
downloading,
|
||||
installing,
|
||||
progress,
|
||||
percent,
|
||||
check,
|
||||
download,
|
||||
install,
|
||||
clear,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,3 @@
|
|||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { emit } from "@tauri-apps/api/event";
|
||||
|
||||
export function basename(path: string): string {
|
||||
return path.split(/[\\/]/).pop() || path;
|
||||
}
|
||||
|
|
@ -101,34 +98,44 @@ export interface RecentItem {
|
|||
path: string;
|
||||
kind: "image" | "video" | "text" | "file";
|
||||
at: number;
|
||||
/** Pinned rows survive the capacity limit, a missing file, and Clear. */
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The history library lives in Rust, next to the other app data, and Rust writes
|
||||
* it the moment a result exists. Nothing here keeps a second copy: these helpers
|
||||
* cover the plain-webview preview, where there is no backend to ask, and let a
|
||||
* window tell its own listeners that the list moved.
|
||||
*/
|
||||
const RECENT_KEY = "shift.recent";
|
||||
const RECENT_EVENT = "shift:recent";
|
||||
|
||||
export function getRecentItems(): RecentItem[] {
|
||||
/** Browser-only stand-in for the Rust library, used when there is no backend. */
|
||||
export function getLocalRecentItems(): RecentItem[] {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(RECENT_KEY) || "[]");
|
||||
return Array.isArray(parsed) ? parsed.slice(0, 8) : [];
|
||||
return Array.isArray(parsed)
|
||||
? parsed
|
||||
.map((entry: RecentItem) => ({ ...entry, pinned: entry.pinned ?? false }))
|
||||
.slice(0, 8)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberRecent(item: RecentItem) {
|
||||
const current = getRecentItems().filter((entry) => entry.path !== item.path);
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify([item, ...current].slice(0, 8)));
|
||||
window.dispatchEvent(new Event(RECENT_EVENT));
|
||||
// Radial and editor windows record results too; tell the main window to re-read.
|
||||
if (isTauri()) void emit("app://recent-changed", item.path).catch(() => undefined);
|
||||
}
|
||||
|
||||
export function setRecentItems(items: RecentItem[]) {
|
||||
export function setLocalRecentItems(items: RecentItem[]) {
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(items.slice(0, 8)));
|
||||
announceRecentChange();
|
||||
}
|
||||
|
||||
/** Notify listeners in this window; other windows hear the Rust broadcast. */
|
||||
export function announceRecentChange() {
|
||||
window.dispatchEvent(new Event(RECENT_EVENT));
|
||||
}
|
||||
|
||||
/** Subscribe to recent-list changes from this window or any other Shift window. */
|
||||
/** Subscribe to history changes, whether they came from this window or Rust. */
|
||||
export function subscribeRecent(listener: () => void) {
|
||||
window.addEventListener(RECENT_EVENT, listener);
|
||||
window.addEventListener("storage", listener);
|
||||
|
|
|
|||
718
src/styles.css
718
src/styles.css
|
|
@ -40,6 +40,7 @@ body[data-view="radial"],
|
|||
body[data-view="capture"],
|
||||
body[data-view="recorder"],
|
||||
body[data-view="pin"],
|
||||
body[data-view="result-card"],
|
||||
body[data-view="share-notice"] {
|
||||
background: transparent;
|
||||
}
|
||||
|
|
@ -2348,6 +2349,55 @@ kbd {
|
|||
background: #fff;
|
||||
}
|
||||
|
||||
/* Host row in the Updates tab: which machine this is, and which artifact the
|
||||
feed will therefore serve. */
|
||||
.update-system {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
margin-top: 10px;
|
||||
color: #6b4f42;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.update-system-label {
|
||||
color: #9c7e6d;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.update-system-host {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.update-system-host strong {
|
||||
color: #3f2a20;
|
||||
font-weight: 660;
|
||||
}
|
||||
|
||||
.update-system-host small,
|
||||
.update-system-pending {
|
||||
color: #9c7e6d;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.update-system-key {
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
color: #12703f;
|
||||
background: rgba(26, 162, 96, 0.1);
|
||||
font-size: 10.5px;
|
||||
font-weight: 620;
|
||||
}
|
||||
|
||||
.update-system-key.is-unknown {
|
||||
color: #a3401b;
|
||||
background: rgba(242, 106, 51, 0.12);
|
||||
}
|
||||
|
||||
.home-main {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
|
|
@ -2980,13 +3030,21 @@ kbd {
|
|||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Four tabs have to share a 390 px drawer, so the strip scrolls instead of
|
||||
wrapping onto a second row. */
|
||||
.home-settings-tabs {
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 22px;
|
||||
padding: 0 20px;
|
||||
gap: 12px;
|
||||
padding: 0 16px;
|
||||
border-bottom: 1px solid rgba(91, 55, 35, 0.08);
|
||||
background: #fffaf5;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.home-settings-tabs::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.home-settings-tab {
|
||||
|
|
@ -2996,7 +3054,7 @@ kbd {
|
|||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-width: 94px;
|
||||
min-width: 76px;
|
||||
height: 43px;
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
|
|
@ -4370,3 +4428,657 @@ body[data-view="radial"] .share-backdrop {
|
|||
background: rgba(40, 25, 18, 0.16);
|
||||
backdrop-filter: none;
|
||||
}
|
||||
|
||||
/* Updates: git release branch, hash-verified download. */
|
||||
.update-feed {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
margin: 10px 0 14px;
|
||||
}
|
||||
|
||||
.update-feed-label {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: rgba(91, 55, 35, 0.55);
|
||||
}
|
||||
|
||||
.update-feed code {
|
||||
font-size: 11px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
background: rgba(240, 79, 36, 0.06);
|
||||
color: rgba(60, 34, 20, 0.8);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.update-trust {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
color: rgba(91, 55, 35, 0.62);
|
||||
}
|
||||
|
||||
.update-trust.is-signed {
|
||||
color: rgba(28, 110, 74, 0.86);
|
||||
}
|
||||
|
||||
.update-status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.update-status-row > strong {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.update-arrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: rgba(91, 55, 35, 0.62);
|
||||
}
|
||||
|
||||
.update-new {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: rgba(26, 162, 96, 0.12);
|
||||
color: #14794a;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.update-arrow small {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.update-state {
|
||||
margin-left: auto;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: rgba(91, 55, 35, 0.6);
|
||||
}
|
||||
|
||||
.update-state.is-available,
|
||||
.update-state.is-ready {
|
||||
color: #14794a;
|
||||
}
|
||||
|
||||
.update-state.is-error,
|
||||
.update-state.is-unavailable {
|
||||
color: #b4342a;
|
||||
}
|
||||
|
||||
.update-notes {
|
||||
margin: 10px 0 0;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
color: rgba(60, 34, 20, 0.74);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.update-artifact {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
margin-top: 12px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
border: 1px solid rgba(91, 55, 35, 0.1);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.update-artifact-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.update-artifact-size {
|
||||
color: rgba(91, 55, 35, 0.6);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.update-progress {
|
||||
position: relative;
|
||||
height: 22px;
|
||||
margin-top: 10px;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
background: rgba(91, 55, 35, 0.08);
|
||||
}
|
||||
|
||||
.update-progress-fill {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: linear-gradient(90deg, rgba(240, 79, 36, 0.75), rgba(26, 162, 96, 0.75));
|
||||
transition: width 0.25s ease;
|
||||
}
|
||||
|
||||
.update-progress span {
|
||||
position: relative;
|
||||
display: block;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
line-height: 22px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.update-hash {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
margin-top: 10px;
|
||||
font-size: 11px;
|
||||
color: rgba(60, 34, 20, 0.66);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.runtime-error.is-ok {
|
||||
border-color: rgba(26, 162, 96, 0.4);
|
||||
background: rgba(26, 162, 96, 0.08);
|
||||
color: #12603c;
|
||||
}
|
||||
|
||||
.update-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* Capture result card: the four things a screenshot raises, one click each. */
|
||||
.home-segment-after {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.result-card {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 46px 1fr auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: calc(100% - 2px);
|
||||
height: calc(100% - 2px);
|
||||
margin: 1px;
|
||||
padding: 12px 14px 14px;
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
background: rgba(255, 250, 245, 0.96);
|
||||
border: 1px solid rgba(91, 55, 35, 0.14);
|
||||
box-shadow: 0 18px 44px rgba(48, 26, 14, 0.24);
|
||||
color: #2b1d16;
|
||||
animation: result-card-in 0.22s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
@keyframes result-card-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(14px) scale(0.97);
|
||||
}
|
||||
}
|
||||
|
||||
.result-card-thumb {
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 11px;
|
||||
overflow: hidden;
|
||||
color: #d15f31;
|
||||
background: #ffeadc;
|
||||
}
|
||||
|
||||
.result-card-thumb.video {
|
||||
color: #c94d5c;
|
||||
background: #ffe5e9;
|
||||
}
|
||||
|
||||
.result-card-thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.result-card-copy {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.result-card-copy strong {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.result-card-copy span,
|
||||
.result-card-copy em {
|
||||
font-size: 11.5px;
|
||||
font-style: normal;
|
||||
color: rgba(91, 55, 35, 0.68);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.result-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.result-card-actions button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 0;
|
||||
border-radius: 9px;
|
||||
background: rgba(91, 55, 35, 0.06);
|
||||
color: #4a2b1b;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
transform 0.15s ease;
|
||||
}
|
||||
|
||||
.result-card-actions button:hover {
|
||||
background: #f04f24;
|
||||
color: #fffdf9;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.result-card-actions .result-card-open {
|
||||
width: auto;
|
||||
padding: 0 11px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.result-card-fuse {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, #f04f24, #ffb27a);
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
|
||||
/* History library: pinned rows, and the list is a real list now. */
|
||||
.home-recent-list {
|
||||
list-style: none;
|
||||
padding-left: 0;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.home-recent.is-pinned .home-recent-icon {
|
||||
box-shadow: inset 0 0 0 1.5px rgba(240, 79, 36, 0.55);
|
||||
}
|
||||
|
||||
.home-card-clear {
|
||||
flex: none;
|
||||
margin-left: -4px;
|
||||
}
|
||||
|
||||
.home-recent-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
flex: none;
|
||||
margin-top: 10px;
|
||||
padding: 6px 9px;
|
||||
border-radius: 10px;
|
||||
background: rgba(91, 55, 35, 0.05);
|
||||
color: rgba(91, 55, 35, 0.55);
|
||||
}
|
||||
|
||||
.home-recent-search input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #3a251b;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.home-recent-search button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: rgba(91, 55, 35, 0.1);
|
||||
color: #4a2b1b;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.home-recent-search button:hover {
|
||||
background: #f04f24;
|
||||
color: #fffdf9;
|
||||
}
|
||||
|
||||
/* Radial ring presets: reorder the wedges this file type actually offers. */
|
||||
.radial-kind-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.radial-kind-grid button {
|
||||
position: relative;
|
||||
height: 30px;
|
||||
border: 1px solid rgba(99, 61, 39, 0.1);
|
||||
border-radius: 9px;
|
||||
color: #86645a;
|
||||
background: rgba(255, 255, 255, 0.62);
|
||||
font-size: 9px;
|
||||
font-weight: 620;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.radial-kind-grid button.is-active {
|
||||
color: #4b2c1d;
|
||||
border-color: rgba(196, 91, 48, 0.36);
|
||||
background: #fff;
|
||||
box-shadow: 0 2px 7px rgba(74, 43, 27, 0.09);
|
||||
}
|
||||
|
||||
.radial-kind-dot {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 5px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #c45b30;
|
||||
}
|
||||
|
||||
.radial-order-list {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
counter-reset: wedge;
|
||||
}
|
||||
|
||||
.radial-order-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid rgba(100, 61, 39, 0.08);
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.radial-order-index {
|
||||
flex: none;
|
||||
width: 18px;
|
||||
color: #a08578;
|
||||
font-size: 9px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.radial-order-label {
|
||||
flex: 1;
|
||||
color: #43291d;
|
||||
font-size: 10.5px;
|
||||
font-weight: 620;
|
||||
}
|
||||
|
||||
.radial-order-buttons {
|
||||
display: inline-flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.radial-order-buttons button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 1px solid rgba(99, 61, 39, 0.12);
|
||||
border-radius: 7px;
|
||||
color: #7a584a;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.radial-order-buttons button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.radial-order-save {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.radial-order-save:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* Guided first-run checks: a modal card over the main window, using the same warm
|
||||
palette and type scale as the settings drawer it reports on. */
|
||||
.setup-scrim {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(48, 26, 14, 0.32);
|
||||
backdrop-filter: blur(6px);
|
||||
animation: setup-fade 220ms ease-out;
|
||||
}
|
||||
|
||||
.setup-card {
|
||||
width: min(560px, 100%);
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
padding: 20px 22px 16px;
|
||||
border: 1px solid rgba(190, 83, 42, 0.16);
|
||||
border-radius: 16px;
|
||||
background: #fffaf6;
|
||||
box-shadow: 0 26px 60px rgba(70, 32, 14, 0.24);
|
||||
animation: setup-rise 260ms cubic-bezier(0.22, 0.8, 0.3, 1);
|
||||
}
|
||||
|
||||
.setup-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.setup-head h2 {
|
||||
margin: 0;
|
||||
color: #3c2214;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.setup-head p {
|
||||
margin: 5px 0 0;
|
||||
max-width: 46ch;
|
||||
color: rgba(91, 55, 35, 0.66);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.setup-refresh {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 26px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid rgba(190, 83, 42, 0.2);
|
||||
border-radius: 8px;
|
||||
color: #a84c29;
|
||||
background: #fff1e7;
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.setup-list {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.setup-row {
|
||||
display: grid;
|
||||
grid-template-columns: 26px 1fr auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid rgba(120, 70, 40, 0.12);
|
||||
border-radius: 11px;
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
transition: border-color 160ms ease;
|
||||
}
|
||||
|
||||
.setup-row.is-problem {
|
||||
border-color: rgba(217, 79, 31, 0.32);
|
||||
background: rgba(255, 241, 232, 0.8);
|
||||
}
|
||||
|
||||
.setup-row.is-ok {
|
||||
border-color: rgba(28, 110, 74, 0.2);
|
||||
}
|
||||
|
||||
.setup-row-icon {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 8px;
|
||||
color: #a84c29;
|
||||
background: rgba(240, 79, 36, 0.09);
|
||||
}
|
||||
|
||||
.setup-row.is-ok .setup-row-icon {
|
||||
color: #1c6e4a;
|
||||
background: rgba(28, 110, 74, 0.1);
|
||||
}
|
||||
|
||||
.setup-row-body {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.setup-row-body strong {
|
||||
color: #3c2214;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.setup-row-body small {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: rgba(91, 55, 35, 0.7);
|
||||
font-size: 9.5px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.setup-row-body .settings-link {
|
||||
justify-self: start;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: #a84c29;
|
||||
font-size: 9.5px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.setup-state {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: rgba(91, 55, 35, 0.55);
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.setup-state.is-ok {
|
||||
color: #1c6e4a;
|
||||
}
|
||||
|
||||
.setup-state.is-problem {
|
||||
color: #c24615;
|
||||
}
|
||||
|
||||
.setup-paths {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.setup-paths code {
|
||||
padding: 3px 7px;
|
||||
border-radius: 7px;
|
||||
background: rgba(240, 79, 36, 0.06);
|
||||
color: rgba(60, 34, 20, 0.72);
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.setup-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid rgba(120, 70, 40, 0.1);
|
||||
}
|
||||
|
||||
.setup-foot span {
|
||||
color: rgba(91, 55, 35, 0.6);
|
||||
font-size: 9.5px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.setup-foot .runtime-install {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
@keyframes setup-fade {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes setup-rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px) scale(0.985);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
66
src/types.ts
66
src/types.ts
|
|
@ -1,4 +1,12 @@
|
|||
export type View = "main" | "radial" | "capture" | "recorder" | "editor" | "pin" | "share-notice";
|
||||
export type View =
|
||||
| "main"
|
||||
| "radial"
|
||||
| "capture"
|
||||
| "recorder"
|
||||
| "editor"
|
||||
| "pin"
|
||||
| "result-card"
|
||||
| "share-notice";
|
||||
|
||||
export interface FileInfo {
|
||||
path: string;
|
||||
|
|
@ -57,7 +65,14 @@ export interface NormalizedRect {
|
|||
|
||||
export interface RecordingOptions {
|
||||
audio: boolean;
|
||||
fps: number;
|
||||
/** Omitted when the platform's capture tool decides the frame rate itself. */
|
||||
fps?: number;
|
||||
}
|
||||
|
||||
/** Which recording switches the current platform actually honours. */
|
||||
export interface RecordingCapabilities {
|
||||
audio: boolean;
|
||||
fps: boolean;
|
||||
}
|
||||
|
||||
export type FileOutputMode = "alongside" | "custom";
|
||||
|
|
@ -73,6 +88,16 @@ export interface AppSettings {
|
|||
autostart: boolean;
|
||||
/** "" until the user picks a language; the tray follows whatever is stored. */
|
||||
language: string;
|
||||
/** Show the floating result card, or open the editor, after a capture. */
|
||||
captureAfter: "card" | "editor";
|
||||
/** Ask the git release branch for a newer build once a day. */
|
||||
updateCheckEnabled: boolean;
|
||||
/** Raw URL of the release manifest this build reads; "" when unconfigured. */
|
||||
updateFeedUrl: string;
|
||||
/** Custom wedge order per kind and ring, keyed "<kind>/<ring>". */
|
||||
wedgeOrders: Record<string, string[]>;
|
||||
/** False until the guided first-run checks have been shown or dismissed. */
|
||||
setupReviewed: boolean;
|
||||
defaultFileOutputDir: string;
|
||||
defaultScreenshotDir: string;
|
||||
defaultRecordingDir: string;
|
||||
|
|
@ -150,3 +175,40 @@ export interface ShareTransfer {
|
|||
state: "sending" | "received" | "error";
|
||||
path?: string | null;
|
||||
}
|
||||
|
||||
/** Result of the git-backed update check, mirroring `update::UpdateStatus`. */
|
||||
export interface UpdateStatus {
|
||||
state: "current" | "available" | "ready" | "unavailable" | "error";
|
||||
currentVersion: string;
|
||||
availableVersion: string;
|
||||
fileName: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
notes: string;
|
||||
date: string;
|
||||
/** Absolute path once the installer has been downloaded and hash-verified. */
|
||||
path: string | null;
|
||||
message: string;
|
||||
feedUrl: string;
|
||||
/** True when the manifest was signature-verified against a key baked into this
|
||||
* build. False means the feed is trusted through HTTPS alone. */
|
||||
signed: boolean;
|
||||
/** The manifest key this build resolved its artifact under, reported by Rust
|
||||
* rather than inferred, or "" when the release names nothing for it. */
|
||||
artifactKey: string;
|
||||
}
|
||||
|
||||
export interface UpdateProgress {
|
||||
downloaded: number;
|
||||
total: number;
|
||||
state: "downloading" | "verifying";
|
||||
}
|
||||
|
||||
/** One saved capture, handed to the result-card window. */
|
||||
export interface CaptureResult {
|
||||
path: string;
|
||||
name: string;
|
||||
kind: "image" | "video";
|
||||
/** Milliseconds before the card hides itself. */
|
||||
ttlMs: number;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
|
|
|
|||
Loading…
Reference in New Issue