Compare commits

..

No commits in common. "releases" and "main" have entirely different histories.

190 changed files with 45451 additions and 73 deletions

13
.dockerignore 100644
View File

@ -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

95
.github/workflows/ci.yml vendored 100644
View File

@ -0,0 +1,95 @@
name: CI
on:
push:
pull_request:
jobs:
macos:
runs-on: macos-latest
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
with:
targets: aarch64-apple-darwin,x86_64-apple-darwin
components: rustfmt, clippy
- run: pnpm install --frozen-lockfile
- run: pnpm mac:drag-bridge
- run: pnpm check
- run: pnpm test
- run: pnpm build
- run: cargo fmt --check
working-directory: src-tauri
- run: cargo test --lib
working-directory: src-tauri
- run: cargo clippy --all-targets -- -D warnings
working-directory: src-tauri
- run: pnpm tauri build --target universal-apple-darwin --debug --bundles app
env:
RUSTUP_TOOLCHAIN: stable
windows:
runs-on: windows-latest
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
with:
components: rustfmt
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test
- run: pnpm build
- run: cargo fmt --check
working-directory: src-tauri
- run: cargo test --lib
working-directory: src-tauri
- run: pnpm tauri build --debug --no-bundle
# Linux compiles and runs the same TypeScript/Rust tests. Runtime capture still
# needs a real Wayland/X11 desktop; `scripts/linux/Dockerfile` carries the same
# dependency set for building the packages outside this workflow.
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
with:
components: rustfmt
- 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 test
- run: pnpm build
- run: cargo fmt --check
working-directory: src-tauri
- 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

13
.gitignore vendored 100644
View File

@ -0,0 +1,13 @@
node_modules/
dist/
src-tauri/target/
src-tauri/gen/
artifacts/
FileFlipper/
.DS_Store
scripts/windows-debug/
/codesign*
*.dSYM/
.env
.env.*
!.env.example

141
CONTRIBUTING.md 100644
View File

@ -0,0 +1,141 @@
# Contributing to Shift
Shift is a Tauri 2 desktop application: React/TypeScript renderers talk to a Rust
command layer, with native macOS, Windows and Linux adapters underneath. Changes
should stay local to the behaviour being fixed; the regression ledger in
[`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) records paths that must
not be simplified back into earlier failures.
## Prerequisites
- Node.js 22 (the CI baseline) and pnpm 8 or newer. The repository has no
`packageManager` pin, so use an installed pnpm rather than assuming Corepack
selects one.
- Current stable Rust and Cargo; the CI workflow tracks the stable channel.
- macOS: macOS 13 or newer and the Xcode Command Line Tools for the Swift
sidecars.
- Windows: Visual Studio Build Tools with the Desktop development with C++
workload, WebView2, and the Tauri prerequisites. See
[`docs/BUILD_WINDOWS.md`](docs/BUILD_WINDOWS.md).
- Linux: the GTK/WebKit/AppIndicator packages listed in
[`.github/workflows/ci.yml`](.github/workflows/ci.yml), plus `grim`,
`gnome-screenshot`, `wf-recorder` and FFmpeg for the optional capture paths.
## Local setup
```bash
pnpm install
pnpm prepare:ocr
pnpm mac:drag-bridge # macOS only
pnpm tauri dev
```
`pnpm prepare:ocr` refreshes the tracked Tesseract WASM and language assets
under `public/tesseract/`. They are committed so a clean checkout can build and
run OCR offline. Do not delete or replace them with remote downloads.
## Required checks
Run the checks from the repository root unless a command says otherwise:
```bash
pnpm check
pnpm test
pnpm build
cd src-tauri
cargo fmt --check
cargo test --lib
cargo clippy --all-targets -- -D warnings
cd ..
git diff --check
```
The two network-dependent Rust tests are ignored by default:
- `share::tests::two_copies_on_one_machine_discover_each_other` binds the shared
discovery port.
- `update::tests::the_configured_feed_parses_and_downloads` reaches the update
feed.
Run the first explicitly when working on discovery, and the second only with a
feed you are willing to download from:
```bash
cd src-tauri
cargo test share:: -- --ignored --nocapture
SHIFT_UPDATE_URL="<manifest-url>" cargo test --lib update:: -- --ignored
```
## What CI covers
[`.github/workflows/ci.yml`](.github/workflows/ci.yml) defines macOS, Windows and
Linux jobs. They run type checks, TypeScript tests, Rust formatting and Rust
unit tests; macOS also runs Clippy and a universal app build. Nothing in this
repository proves that the current hosting forge has a runner configured.
Link an actual run before describing CI as passing.
## Change rules
- Keep the source file untouched. Every operation writes a new result through
the collision-safe naming helpers.
- Where the interface maps a backend failure, use a stable code such as
`errTextTooLarge` or `share-timeout`; user wording belongs in `src/i18n.ts`.
Add both English and Simplified Chinese. Raw third-party diagnostics may pass
through unchanged.
- Use `messageFrom()` for unknown errors and `tLive()` for listeners that are
registered once and must follow later language changes.
- Preserve protocol compatibility. LAN beacons and transfer headers may gain
defaulted fields, but existing field meanings must not change. Update
manifests are `schema: 1`; reject unsupported schemas instead of guessing.
- Treat downloaded installers and LAN input as untrusted. Do not interpolate
paths into shell or batch text, and do not trust a declared file size without
enforcing it while copying.
- Resource limits belong at the point where bytes are read or decoded, not only
in the UI. The editor currently caps text at 8 MiB, image files at 64 MiB and
decoded images at 40 megapixels; document any new unbounded path or add a
limit.
- Do not edit generated output in `dist/`, `src-tauri/target/`, `artifacts/`, or
generated icons. Change the source and the build script that produces them.
## Documentation changes
User-visible behaviour changes require matching updates in both
[`README.md`](README.md) and [`README.zh-CN.md`](README.zh-CN.md). Architecture
changes belong in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md); observable
behaviour and limits belong in [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md);
trust-boundary changes belong in [`docs/SECURITY.md`](docs/SECURITY.md).
If a change alters discovery, conversion dependencies, update handoff or macOS
packaging, append the reason, evidence and any commit reference to
`docs/ENGINEERING-NOTES.md` rather than leaving the next contributor to
rediscover it.
## Manual checks
Unit tests cannot prove gesture handling, OS permissions, installer behaviour or
cross-machine discovery. Before a release, complete the relevant matrix:
- macOS: first launch, Screen Recording and Files & Folders permissions, area
and full-screen capture, editor save and copy, drag-to-ring, LAN receive.
- Windows: installer, firewall prompt, drag-to-ring threshold, WebView2 file
drag paths, recording with FFmpeg, LAN receive.
- Linux: build package, `grim` / `gnome-screenshot`, Wayland `wf-recorder`,
X11 FFmpeg fallback, Poppler-dependent paths.
- Updates: install the previous release and run the in-app handoff once on each
shipped platform. On Windows this requires real Windows hardware.
Record which checks were run and which were not. Do not replace an unavailable
hardware check with a compile result.
## Release work
The release process, signing key handling and channel verification are in
[`docs/RELEASE.md`](docs/RELEASE.md). A release key must never enter the
repository, logs or issue attachments. Use `scripts/release-key.py` with the key
outside the working tree.
Do not commit generated artifacts or publish a `releases` branch unless the
task explicitly asks for it.

3
LICENSE 100644
View File

@ -0,0 +1,3 @@
MIT License
Copyright (c) 2026 Shift Contributors

View File

@ -1,45 +0,0 @@
Shift 0.1.14 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。当前 Windows 10/11 通常已内置;如果 Shift
启动后窗口空白或无法打开,请从微软官方页面安装:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。只有在“运行组件”里安装外部工具时,
Windows 才可能弹出 UAC 确认。
安装
----
1. 运行 Shift-Setup-0.1.14-win-x64.exe,默认安装到
%LOCALAPPDATA%\Programs\Shift,并创建开始菜单与桌面快捷方式。
2. 这是未签名构建。若 SmartScreen 显示“Windows 已保护你的电脑”,请选择
“更多信息” > “仍要运行”。
3. 卸载请在“设置 > 应用”中移除 Shift,无需手动删除文件。
4. 首次启动若 Windows 安全中心询问网络访问,请允许 Shift 访问“专用网络”。
如果之前拒绝过,请到“Windows 安全中心 > 防火墙和网络保护 > 允许应用通过
防火墙”,勾选 Shift 的专用网络权限;否则“发送到设备”无法接收其它终端的信标。
运行组件
--------
打开 Shift 主窗口,进入“设置” > “运行组件”:
- 首次进入该页会自动检测,之后只在你点击“重新检测”时重新扫描;
扫描范围包括 PATH、WinGet、Chocolatey、Scoop 与常见安装目录。
- 页面显示本机实际使用的组件、版本、路径与来源。
- 缺失组件旁有“安装”,通过 Microsoft WinGet 安装,界面不会阻塞,
完成后自动重新检测。
WinGet 包映射:
- Pandoc: JohnMacFarlane.Pandoc
- Typst: Typst.Typst
- FFmpeg: Gyan.FFmpeg
- Poppler: oschwartz10612.Poppler
- ImageMagick: ImageMagick.ImageMagick
如果没有 WinGet,界面会给出微软官方安装说明入口。Shift 不会从第三方站点
下载运行库,也不会卸载或覆盖你已有的工具。
校验
----
PowerShell:
Get-FileHash .\Shift-Setup-0.1.14-win-x64.exe -Algorithm SHA256

527
README.md 100644
View File

@ -0,0 +1,527 @@
# Shift
**A radial file workspace for macOS and Windows. Drag a file, release over a wedge, and the conversion happens on your machine.** Linux is a source-build target, not a shipped release.
**Language:** English · [简体中文](README.zh-CN.md)
Shift puts file conversion, screenshot, screen recording, annotation, and bilingual OCR behind one radial menu that appears wherever you drop a file. No uploads, no account, no cloud round-trip — every byte is processed locally.
Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour live behind per-platform adapters, so the radial menu, editor, and format catalogue are shared wherever the platform provides the underlying gesture.
---
- [What it does](#what-it-does)
- [Quick start](#quick-start)
- [Supported files](#supported-files)
- [Conversions](#conversions)
- [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)
- [Architecture](#architecture)
- [Documentation](#documentation)
- [Repository layout](#repository-layout)
- [Privacy](#privacy)
- [Known limitations](#known-limitations)
- [FAQ](#faq)
- [Contributing](#contributing)
- [License](#license)
---
## What it does
**The radial menu is the whole interface.** Hold `Shift` and drag a file in Finder (or `Shift + Alt` on Windows) and a ring opens under the cursor. Release over a format to convert, or add `Option`/`Alt` to switch to the tool ring. In the main window the same rings open from a file you drop on one of the three buttons, or pick through `Convert files` / `File tools`.
**Everything is type-aware.** The ring only offers what the selected file can actually become, and never repeats the source format — an image can target PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF except its current format, a PPTX offers PDF and Markdown, and a `.key` or `.pages` file offers no conversion wedges at all instead of failing later. The centre shows a glass preview with the file's dimensions and size; a multi-file selection renders a stacked icon deck.
**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. A finished capture hands you a floating result card - Copy, Pin, Send, Reveal, Edit, one click each, and it steps aside on its own. 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.
**Files can hop to another machine.** Every running Shift announces itself on the local network, so the recent list can hand a file to another computer the way AirDrop does — tap a device name, watch the progress bar, and the file lands in Shift's output folder on the other side.
## Quick start
Shift lives in the menu bar (macOS) and the notification area (Windows), and it also has a normal window. There is no required window to keep open — the rings work from anywhere.
**Convert a file (Shift).**
1. Find the file in Finder or File Explorer.
2. Press and hold on it and start dragging, keeping the mouse button down.
3. While dragging, hold `Shift`. The ring appears around the pointer.
4. Drag toward the format you want — the wedge fills in and grows, and its name shows in the centre — then release. You only have to head in its direction; precision is not required.
5. The status pill reports `Saved N files.` and the result sits next to the original.
> 💡 You can press `Shift` after the drag begins. Once the ring is up you may let go of `Shift`; it stays until you release the mouse.
> 💡 Changed your mind? Release back near the centre (inside the 92 px inner radius) and nothing happens.
> 💡 Near a screen edge the ring slides back on screen; the whole 760 px ring is clamped inside the monitor under the pointer.
**Use a tool (`Option + Shift`, or `Alt + Shift` on Windows).** Same gesture, and the wedges become tools for that file type instead of formats. While the ring is open, keep `Shift` held and press or release `Option`/`Alt` to flip between the format ring and the tool ring.
**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. A button that cannot serve the file you are dragging is **switched off for the length of the gesture**, and the cursor turns into a prohibition sign over it - **OCR** for anything that is not an image, **Convert files** for a format with nothing to convert it into. A switched-off button takes no hover feedback at all, and releasing on it does nothing, silently: no empty ring, no handover to another ring, no message. **File tools** never switches off, because its ring ends in Open, Reveal and Send. The same rule, and the same look, decide a drop in every case - whichever platform you are on, and whether the file came from the file manager or from the Recent list.
**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
Recognition is by extension, against four tables in `src-tauri/src/files.rs`. The `kind` drives the centre icon and which wedges appear. Bold extensions are the ones that actually convert; the rest are recognised and get Open, Reveal, or an export-first message.
| Kind | Extensions |
| --- | --- |
| `image` | **`png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif` `heic` `heif` `avif`** |
| `video` | **`mp4` `mov` `m4v` `avi` `mkv` `webm`** |
| `audio` | **`mp3` `wav` `m4a` `aiff` `aif` `caf` `flac` `ogg`** |
| `pdf` | **`pdf`** |
| `document` | **`docx` `rtf` `odt` `txt` `md` `html` `htm`** `doc` `pages` |
| `presentation` | **`pptx`** `ppt` `key` |
| `spreadsheet` | **`xlsx` `xls` `xlsb` `ods` `csv` `tsv`** `numbers` |
| `other` | anything unrecognised — Open and Reveal only |
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 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.
- **Recognised but not converted:** `.doc`, `.pages`, `.ppt`, `.key` and `.numbers` get their proper icon plus Edit, Open and Reveal, but no format wedges. Export them to DOCX, PPTX or XLSX first.
## Conversions
The format ring for a given file type. Every target below is wired in `src-tauri/src/files.rs`; the source's own format is filtered out at runtime.
| Source | Ring targets (source format excluded) | Engine | Notes |
| --- | --- | --- | --- |
| Image | `PNG` `JPG` `WEBP` `TIFF` `BMP` `GIF` | Rust `image` | Lossless path when the codec allows it |
| Image | `HEIC` | `sips` / ImageMagick | macOS native; other OS need `magick` |
| Image | `PDF` | `printpdf` | One page per image, sized at 300 dpi |
| Video | `MP4` `MOV` | FFmpeg | `libx264`, falling back to `h264_videotoolbox` then `mpeg4` |
| Video | `GIF` | FFmpeg | First 15 s only, 12 fps, 480 px wide, 8 MB ceiling — capped so a long recording cannot produce a 100 MB GIF |
| Video | `M4A` | FFmpeg | Audio track only, 192k AAC |
| Audio | `M4A` `WAV` `MP3` | FFmpeg | MP3 falls back to `lame` if FFmpeg lacks `libmp3lame` |
| PDF | `TXT` `MD` | `lopdf` | Text-layer extraction; errors clearly when a PDF is scanned |
| PDF | `DOCX` | Page rendering + native DOCX packaging | PDFKit on macOS, Poppler on Windows/Linux; preserves images, diagrams and page layout without Microsoft Word |
| PDF | `RTF` | `lopdf` + Pandoc | Text layer becomes the document body; needs Pandoc |
| PDF | `HEIC` | PDFKit / Poppler + `sips` | Pages render as PNG then transcode; needs a system HEIC codec |
| PDF | `PNG` `JPG` `TIFF` | PDFKit / Poppler | One file per page into a `… pages` folder |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit renderer (macOS) · Pandoc elsewhere | macOS path needs no LaTeX or wkhtmltopdf. A DOCX with pictures goes through Pandoc → HTML first, because the AppKit reader drops images |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` | Pandoc | The source format is omitted; Markdown writes as GFM. HTML is a self-contained file with embedded images |
| Presentation `.pptx` | `MD` `PDF` | Pure Rust + Pandoc | Per-slide headings, bullet text and **tables as real Markdown tables**; PDF is a text summary, not a layout render |
| Spreadsheet | `MD` `PDF` | `calamine` / Rust | One Markdown table per sheet; `csv`/`tsv` parsed directly |
Anything not in this table is not offered — the ring is built from this catalogue at runtime, so a wedge you can click is a wedge that works. If a dependency is missing, the wedge names it instead of failing silently.
**Page progress follows one rule.** Conversions that can enumerate real pages report the same `Converting page N/M…` event. Image-only DOCX→PDF and image-bearing PDF→DOCX use that path. One-shot Word→PDF layout and text-only PDF→DOCX cannot expose a reliable page count, so they show `Processing…` rather than a fabricated percentage.
> Note: the conversion ring never repeats the source format. For example, a DOCX offers no DOCX target, avoiding a needless full rewrite that can lose layout.
> Scanned/image-only PDFs have no text layer, so `TXT`/`MD` return a clear error — use **OCR** on those, which renders each page first.
## Tools
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 |
| 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 |
| Crop | image | `.png`, ` (cropped)` | Radial crop opens the editor for an interactive selection |
| Cutout | image | — | Opens the editor, which keys out the sampled background colour |
| Merge | 2+ images | `.pdf`, ` (images)` | One page per image, in selection order |
| Merge | 2+ PDFs | `.pdf`, ` (merged)` | Concatenates in selection order |
| Split | PDF | `Page 001.pdf` … | One PDF per page in a `… pages` folder |
| Extract text | PDF | `.txt` | Text layer only; use OCR for scans |
| 720p | video | `.mp4`, ` (720p)` | Scales to 720p height, keeps aspect |
| Mute | video | same type, ` (muted)` | Drops the audio track, video stream copied without re-encode |
| Frame | video | `.png`, ` (frame)` | First frame as a still |
| Extract audio | video | `.m4a` | 192k AAC |
| Mono | audio | `.m4a`, ` (mono)` | Downmix to single-channel 128k AAC |
| Plain | document | `.txt` | Plain-text dump via Pandoc |
| OCR | image, PDF | `.txt`, ` (OCR)` | See [OCR](#ocr) |
| Edit / Annotate / Redact / Add BG | image | — | Opens the image editor; choose the annotation tool from its toolbar |
| Open · Reveal | any file | — | Hands off to the system default app or file manager |
## Compression, naming, cancellation
**What Compress actually does.**
| Input | Behaviour |
| --- | --- |
| Image | Re-encoded at quality 68. Images with transparency are written as PNG, everything else as JPG |
| PDF | Embedded images above 1440 px are resampled to q60 JPEG, then objects are pruned, renumbered and saved compressed. If the result is not smaller, nothing is written |
| Video | Re-encoded at CRF 28 / 2M target, AAC 96k audio, into MP4 |
| Audio | To 128k AAC M4A |
**Output naming — nothing is ever overwritten.** Results land next to the source with a descriptive suffix, and a collision appends ` 2`, ` 3`, … rather than replacing anything.
```text
report (compressed).pdf photo (rotated).png slide (bw).png
report (clean).pdf photo (50%).png report (merged).pdf
```
PDF→image and PDF split write into a new `Name pages` folder containing `Page 001.png`, `Page 002.png`, … A second run makes `Name pages 2`, also never overwriting.
**Cancel a gesture.** Release near the centre of the ring, or outside the ring entirely, and no action runs.
## 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, 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. The editor is the fallback whenever a card window cannot be created, so a capture is never left with no way to act on it.
**Annotation.** The editor canvas works at native resolution and writes a new PNG, so the source file is never modified.
| Tool | Behaviour |
| --- | --- |
| Rectangle, Arrow, Highlight, Text | Freehand placement; each tool has a fixed colour and line width |
| 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 |
| Cutout | Samples the four corners, averages the background, keys it out to transparency |
| Undo | Pops annotations first, then image-level operations |
| Save copy / Copy | New file with a suffix, or straight to the clipboard |
| Pin | Floats the image as an always-on-top window with enlarge, copy and close |
**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as read-only text previews. Copy, Save As, Open and Reveal are available for every kind. OCR, Copy Text and Pin appear for images only; text is not edited in place. The editor refuses text over 8 MB and images over 64 MB or 40 megapixels, and reports the limit instead of loading them.
## 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. Because it sits outside the bundle, **it survives an update and a reinstall**; the first launch after upgrading also adopts whatever the 0.1 webview had kept in its own store, so a list built before that change is not lost either. The main window's **Recent** card is that library:
- **Search** once the list grows past a few rows; it filters on the file name.
- **Favorite** a row to keep it through the capacity limit, a deleted file, and Clear. A favourited row carries a star on its thumbnail, so the list can be read without hovering it.
- **Remove** one row, or **Clear** the library - favorite 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. The plain-text path travels with it for editors.
- **Drag a row onto Convert files, File tools or OCR** to run just that action on a file you already used — the same gesture, inverted. Like any drop it has to land on a button; releasing it back over the list runs nothing.
- 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.
- **Images** — one pass, live progress, text goes to the editor or the clipboard.
- **Scanned PDFs** — pages are rendered to images first, then OCR'd sequentially with per-page progress, and the results are written to a ` (OCR)` text file with `--- Page N ---` separators.
- **Text PDFs** — use Extract Text instead; it reads the embedded layer directly and is far faster.
## Send to a device
Shift keeps a live list of the other Shift copies on your network and uses it for an AirDrop-style transfer. Hover any row in **Recent** and press the send button, or open a file's **Tools** ring and release over **Send** — either way a picker opens with one card per device, and clicking a card starts the transfer. The Tools ring offers Send for every file type, and selecting several files sends them as one batch.
Nothing lands without consent: the receiving machine shows a small card naming the sender and the file, with **Accept** and **Decline** and a countdown. Declining, closing the card, or letting it expire stops the transfer before a single file byte moves. An accepted batch is asked once, then the remaining files of that batch follow on their own. Accepted files are written to Shift's output folder, appear in that machine's Recent list, and a note names the sender. Whether Finder (or Explorer) also comes forward is decided by the same **Show results in Finder** switch that governs finished conversions, and a batch reveals once rather than once per file. Names that already exist get ` 2`, ` 3` appended, and a partial transfer never leaves a half-written file behind.
How it finds peers, with no server and no configuration:
- Every copy sends a small UDP beacon every two seconds to multicast group `239.255.77.88:47888`, a directed broadcast to every active IPv4 subnet, and a unicast subnet sweep that still finds peers when both multicast and broadcast are filtered. Every regular beacon gets a unicast answer, so a peer stays visible instead of flashing once and expiring. Beacons carry the machine name, OS, and the ephemeral TCP port that will receive files.
- A beacon that has not been repeated for fifteen seconds drops the device from the list, so switching networks clears stale entries by itself while older peers have time to answer again.
- File bytes move over a direct TCP connection: a `SHSF` handshake, a JSON header, the payload, then a one-byte acknowledgement, so a sender only reports success once the receiver has the whole file on disk.
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 |
| --- | --- | --- |
| Capture area | `⌥⇧2` | `Alt+Shift+2` |
| Record area | `⌥⇧3` | `Alt+Shift+3` |
| Capture full screen | `⌥⇧4` | `Alt+Shift+4` |
| Format ring while dragging | hold `⇧` | hold `Shift` |
| Tool ring while dragging | `⌥⇧` | `Alt+Shift` |
The three capture shortcuts are registered globally. The drag rings are modifier-driven: begin dragging with the modifier already held and the ring appears under the cursor without Shift needing focus.
## Tray menu
The menu bar (macOS) and notification area (Windows) icon exposes the actions you would otherwise reach through the window:
| Item | Shortcut | Meaning |
| --- | --- | --- |
| Open Shift | — | Show the main window |
| Capture area | `Alt+Shift+2` | Start an area screenshot |
| Capture full screen | `Alt+Shift+4` | Grab the monitor under the pointer |
| Record area | `Alt+Shift+3` | Start, or stop, an area recording |
| OCR | — | 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.
Settings → **Behaviour** holds two switches: **Drag rings** (master enable for the Shift-drag gesture) and **Launch at login**.
## Output locations
| Result | Default |
| --- | --- |
| Screenshots | `~/Pictures/Shift` |
| Recordings | `~/Movies/Shift` |
| File actions | beside the source file |
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
A new macOS machine installs **`Shift-0.1.13-macOS-universal.dmg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer. Double-click the image, drag `Shift.app` to /Applications, then allow the first launch once (right-click → Open, or 允许 in System Settings → Privacy & Security). In-app updates download the same image without a browser, so they never prompt. Details in `docs/RELEASE.md`.
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 release that has been found is announced at the top of the main window - **Shift x.y.z is available**, with one button that opens Settings -> Updates - and it stays announced across restarts, including the restart that follows an update, because the notice is remembered on disk rather than held in memory. Since the probe itself runs at most once a day, a notice that only lived in RAM would be visible on the morning it was discovered and invisible every launch after. A downloaded installer must match the manifest's exact byte length and recomputed SHA256, and both checks run again immediately before the handoff that installs it. A mismatch deletes the file and reports the error, so a truncated or replaced installer never launches. **Discard** removes the downloaded installer as well as the status. 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`).
**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The helper receives its paths as process arguments or environment variables, never by splicing them into the shell or batch script; the Windows launcher also keeps the outer quote layer `cmd.exe /C` otherwise strips from a path containing spaces. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update.
## 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** (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 |
| ImageMagick `magick` | HEIC/HEIF/AVIF input plus HEIC output | not needed (`sips`) | needed | needed |
| LAME | MP3 encode when FFmpeg lacks `libmp3lame` | rare | rare | rare |
Settings -> **Runtime components** shows the tools found on the current machine,
their versions and paths, and what each one unlocks on this platform. A row that reads
as missing also says how to fix it: anything installable carries an **Install** button
(Pandoc and FFmpeg on macOS through Homebrew; Pandoc, FFmpeg, Poppler, ImageMagick and
Typst on Windows through WinGet), and a row with no button is either built in or simply
not used on that platform. When more than one row is missing, the panel header adds
**Install all**, which sends the missing rows as one request: the installs run one after
another because the package managers hold a single lock, and a package that answers two
rows — Poppler, which serves both PDF rows on Windows — is installed once. Tools are also
found on `PATH` and their
standard install locations at call time, so a missing dependency degrades one
wedge rather than the app.
## Platform status
| Capability | macOS | Windows | Linux |
| --- | --- | --- | --- |
| 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` | Win32 GDI `BitBlt` | `grim` / `gnome-screenshot` |
| Monitor under cursor | Yes | Yes | `grim` output selection |
| 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 and back onto a button | 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 |
| PDF → images | PDFKit sidecar (+ `sips` for HEIC) | Poppler (+ ImageMagick for HEIC) | Poppler (+ ImageMagick for HEIC) |
| PDF → Word | Built-in page renderer | Poppler required | Poppler required |
| Scanned-PDF OCR | Yes | Poppler required | Poppler required |
| Document → PDF | bundled AppKit renderer | Pandoc + a PDF engine | Pandoc + a PDF engine |
| PPTX / XLSX / ODS → Markdown | Yes (pure Rust) | Yes | Yes |
| Local EN + ZH OCR | Yes | Yes | Yes |
## Build from source
Requires Node.js 20+, pnpm 8+, Rust 1.90+, and macOS 13+ with Xcode Command Line Tools for the native macOS sidecars.
```bash
pnpm install
pnpm mac:drag-bridge # macOS only — AppKit drag, PDFKit and document renderers
pnpm tauri dev
```
`pnpm mac:drag-bridge` compiles `native/macos/*.swift` into per-architecture and universal sidecars under `src-tauri/binaries`. Windows and Linux skip it entirely.
```bash
pnpm check # TypeScript, no emit
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
```
Versioned release builds:
```bash
rustup target add aarch64-apple-darwin x86_64-apple-darwin
pnpm mac:release
scripts/build-windows-release.sh
```
The release pipeline deliberately emits exactly two installers: `Shift-0.1.13-macOS-universal.dmg` and `Shift-Setup-0.1.13-win-x64.exe`. The macOS app is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. Windows ARM64 uses the x64 installer through the update manifest's compatibility fallback. Full details are in `docs/BUILD_WINDOWS.md` and `docs/RELEASE.md`.
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio, and Local Network for **Send to a device**. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. A denied Local Network grant is quieter: Shift still sends its beacons and still answers anyone who addresses it directly, but it receives no group traffic, so the device list simply stays empty. Ad-hoc signed builds get a new code identity on every rebuild and macOS keys these grants to that identity, so an upgrade can ask again; distribution with Developer ID keeps them stable.
## Architecture
```text
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/
├─ files.rs inspect, convert, compress, metadata, rotate, crop, media
├─ 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 / wf-recorder, with signal-based finalization
├─ drag_bridge.rs global drag detection, ring mode, radial positioning
├─ 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 · 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
```
The radial hit-test is pure geometry — one polar calculation shared by native pointer events, webview hover, and the Windows drop payload — so ring behaviour does not drift between platforms.
## Documentation
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — process/window model, module boundaries, event and data flows.
- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) — product behaviour, output naming, platform differences and acceptance criteria.
- [`docs/SECURITY.md`](docs/SECURITY.md) — trust boundaries, update integrity, LAN-transfer limits and residual risks.
- [`CONTRIBUTING.md`](CONTRIBUTING.md) — development setup, test gates and release checks.
- [`docs/README.md`](docs/README.md) — index of every technical and release document.
- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) — regression ledger for paths that must not be simplified back into earlier failures.
- [`docs/RELEASE.md`](docs/RELEASE.md) — release channel, signing and update handoff.
- [`docs/ROADMAP.md`](docs/ROADMAP.md) and [`docs/MOBILE.md`](docs/MOBILE.md) — future work and the mobile plan.
## Repository layout
```text
src/ React UI, i18n (en/zh), Tauri API bindings
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, release build,
manifest publish and manifest signing
public/tesseract/ WASM core + traineddata; refreshed by pnpm prepare:ocr and
tracked so a clean checkout builds and runs OCR offline
assets/ app icon source
src-tauri/icons/ generated app icons per platform
docs/ architecture, behaviour specification, security model, release
guide, engineering ledger, roadmap and mobile plan
scripts/linux/ Dockerfile that builds Linux deb/AppImage packages
.github/workflows/ CI definitions for macOS, Windows and Linux (see Contributing)
```
## Privacy
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 explicitly start that feature. The **update check** fetches a manifest over HTTPS at most once a day; it downloads an installer only when you press the button. **Send to a device** uses UDP beacons on `239.255.77.88:47888` and a direct TCP connection only to the machine you choose (or from another Shift that offers you a file). Discovery is silent while sharing is disabled, and a transfer begins only after the receiver accepts. LAN traffic is not authenticated or encrypted; [`docs/SECURITY.md`](docs/SECURITY.md) describes that boundary.
## Known limitations
- 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 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`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11. Those runtime paths are not exercised by the macOS development host, so treat Linux capture as build-verified until checked on real hardware.
- 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. Dropping a row back onto Shift is checked: one gesture reports through the DOM, the native webview drop, or both, and the `landed` flag in `MainWindow.tsx` lets only the first through — the invariants are in `docs/ENGINEERING-NOTES.md`.
- 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. The discovery invariants, permission checks and regression matrix are in `docs/ENGINEERING-NOTES.md`.
- On Windows only one Shift copy per machine can hold the discovery port, so extra instances do not appear as peers.
- Windows and Linux paths are compile-verified here and covered by the repository's CI definition where a runner is available; gesture-level QA still needs real Windows and Linux hardware.
- Signing identity changes on macOS may require re-approving Screen Recording and Accessibility.
- LAN sharing has no authentication or encryption. An accepted transfer proves only that you accepted an offer, not who sent it; use the feature on trusted networks.
- Office ZIP/XML parsing and PDF rendering still lack one shared resource quota across every codec and external renderer. Editor previews are bounded, but unusually large or adversarial documents should be treated as untrusted input.
Roadmap: `docs/ROADMAP.md`.
## FAQ
**❓ I hold Shift while dragging and no ring appears.**
Start the drag first — mouse button held, file moving past the drag threshold — and hold `Shift` during it. Pressing `Shift` with a file merely selected does nothing. On Windows the ring needs `Shift` held at the moment the drag crosses the system threshold; add `Alt` at that moment for tools.
**❓ It says this file type has no formats.**
Unrecognised extensions get Open and Reveal only, and legacy Apple/Office formats (`.doc`, `.pages`, `.ppt`, `.key`, `.numbers`) intentionally offer no conversion. Export them to DOCX, PPTX or XLSX first.
**❓ Can I make it run at login, or toggle it off?**
Yes, both, in Settings → **Behaviour**. **Drag rings** is the master switch for the Shift-drag gesture: off means no ring ever appears, while the tray, window and shortcuts keep working. **Launch at login** registers a LaunchAgent on macOS, a `HKCU\...\Run` entry on Windows, or an autostart `.desktop` file on Linux, and is reversible from the same toggle.
The login item is registered for the current user only and points at the executable inside the app bundle, so macOS keeps the same Screen Recording identity across launches. Move the app and re-toggle it once.
**❓ Are my files uploaded?**
No. There is no upload path in the code and no network call in the conversion or OCR paths; the Tesseract models ship inside the app. Nothing is collected, and there is no account.
**❓ Where did my output go?**
Next to the source file by default, with a suffix — check the recent list in the main window first, since clicking an entry opens the result. Settings lists every resolved output path and can reveal it.
**❓ 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.
**❓ How do I uninstall?**
Quit from the tray and delete the app. Nothing is written outside your output folders and the app's own config/cache directories.
## 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 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. The full pre-push sequence is `pnpm check`, `pnpm test`, `pnpm build`, `cargo fmt --check`, `cargo test --lib`, `cargo clippy --all-targets -- -D warnings` and `git diff --check`; [`CONTRIBUTING.md`](CONTRIBUTING.md) has the platform setup and manual matrix.
`.github/workflows/ci.yml` defines macOS, Windows and Linux jobs. The workflow runs type checks, TypeScript tests, Rust formatting and tests on every job, plus Clippy and a universal macOS app build. Whether the current forge executes it depends on whether that forge has a runner configured; a local run remains the release gate, and no CI result should be inferred without a linked log. Full setup and the pre-push checklist are in [`CONTRIBUTING.md`](CONTRIBUTING.md).
**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.
## License
Released under the **MIT License** — see [LICENSE](LICENSE) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
The app builds against Tauri (MIT / Apache-2.0), React (MIT), Lucide (ISC), and Tesseract.js with its English and Simplified Chinese models (Apache-2.0).

516
README.zh-CN.md 100644
View File

@ -0,0 +1,516 @@
# Shift
**面向 macOS 与 Windows 的环形文件工作台。拖住文件,松开在某个扇区上,转换就在你自己的机器上完成。** Linux 是可从源码构建的目标,不是已发布产品。
**语言:** [English](README.md) · **简体中文**
Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部收进一个环形菜单,它出现在你放下文件的地方。不上传、不注册、不经云端中转——每一个字节都在本地处理。
基于 Tauri 2、Rust、React 与 TypeScript 构建。原生截屏与拖拽行为封装在各平台适配器之后,因此只要平台提供对应手势,环形菜单、编辑器与格式目录就保持一致。
---
- [能力概览](#能力概览)
- [快速上手](#快速上手)
- [支持的文件](#支持的文件)
- [格式转换](#格式转换)
- [工具](#工具)
- [压缩、命名与取消](#压缩命名与取消)
- [截图与标注](#截图与标注)
- [截图历史库](#截图历史库)
- [OCR](#ocr)
- [发送到设备](#发送到设备)
- [自定义圆环顺序](#自定义圆环顺序)
- [快捷键](#快捷键)
- [菜单栏菜单](#菜单栏菜单)
- [输出位置](#输出位置)
- [软件更新](#软件更新)
- [外部依赖](#外部依赖)
- [平台支持情况](#平台支持情况)
- [从源码构建](#从源码构建)
- [架构](#架构)
- [技术文档](#技术文档)
- [仓库结构](#仓库结构)
- [隐私](#隐私)
- [已知限制](#已知限制)
- [常见问题](#常见问题)
- [参与贡献](#参与贡献)
- [许可证](#许可证)
---
## 能力概览
**环形菜单就是全部交互。** 在访达中按住 `Shift` 拖动文件(Windows 为 `Shift + Alt`),圆环会出现在光标下方。松开在某个格式上即完成转换;再加上 `Option`/`Alt` 可切换到工具环。在主窗口里,把文件拖到三个按钮之一也会弹出同一个圆环,或者用「文件转换」「文件工具」先挑文件再弹环。
**一切按类型驱动。** 圆环只列出所选文件真正能变成的格式,并且不会重复显示文件自身的格式——图片可在 PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF 之间转换,但当前格式不会出现目标;PPTX 给出 PDF 与 Markdown,而 `.key`、`.pages` 文件不会给出任何转换扇区,而不是等你点击后才失败。中心是毛玻璃预览,显示尺寸与体积;多选文件会渲染成一叠层叠图标。
**默认批量处理。** 选中十个文件、一次拖拽,就产出十个结果。结果保存在源文件旁边并附带描述性后缀(`report (compressed).pdf`、`photo (rotated).png`),永不覆盖——重名时自动追加序号。也可在设置中改为统一收集到一个文件夹。
**截图能力内置。** 冻结画面的区域截图、全屏截图,以及带悬浮计时器的区域录屏;一律对准光标所在的显示器,而非固定主屏。一次截图完成后会弹出一张浮动结果卡片——复制、钉住、发送、在文件夹中显示、编辑,各一键完成,稍候自行退场。截图与录屏选项只给出当前平台真正支持的开关:macOS 提供麦克风,FFmpeg 后端提供帧率。
**圆环顺序由你决定。** 已保存的顺序会按文件类型、按环重新排列扇区,最常用的转换不再压在扇区环的最下面。(调整顺序的设置标签页已移除,顺序改由 `settings.json` 提供,应用内暂无修改入口。)
**OCR 在本机运行。** 英文与简体中文,使用随应用打包的 Tesseract WASM 引擎与语言模型。OCR 全流程不发生任何网络请求。
**文件可以送到另一台电脑。** 每个运行中的 Shift 都会在局域网里广播自己的存在,因此「最近使用」列表可以像 AirDrop 那样把文件交给另一台电脑——点一下设备名,看着进度条走完,文件就出现在对方电脑的 Shift 输出文件夹里。
## 快速上手
Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普通窗口。无需一直开着某个窗口——圆环在任何地方都能唤起。
**转换文件(Shift)**
1. 在访达或资源管理器中找到文件。
2. 按住鼠标左键把文件拖起来(不要松开)。
3. 拖动过程中按住 `Shift`,圆环会出现在光标周围。
4. 朝想要的格式方向拖动——该扇区会高亮放大,中心显示它的名称——然后松开鼠标。只需朝那个方向即可,不必精确对准。
5. 状态提示会显示「已保存 N 个文件」,结果就在原文件旁边。
> 💡 `Shift` 可以在开始拖动之后再按。圆环出现后就可以松开 `Shift`,它会一直保持到你松开鼠标。
> 💡 改变主意了?把鼠标移回中心(内圈 92 px 之内)再松开,什么都不会发生。
> 💡 靠近屏幕边缘时圆环会自动移回屏幕内;整个 760 px 的圆环会被约束在光标所在显示器范围内。
**使用工具(`Option + Shift`,Windows 为 `Alt + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Alt`,即可在格式环与工具环之间来回切换。
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。**处理不了的按钮会在这次拖拽期间被直接禁用,光标同时变成禁止符号**:不是图片的文件会禁用「文字识别」,没有任何可转换目标的格式会禁用「文件转换」。被禁用的按钮没有任何 hover 反馈,松手时什么都不执行、安静地不做,既不会弹出一个空圆环,也不会转交给别的圆环,也不会弹提示。「文件工具」永远不会被禁用,因为它的环里总有打开、在文件夹中显示与发送。同一条规则、同一种观感,在所有平台上、无论文件来自访达/资源管理器还是「最近使用」,判定结果都一致。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。
**一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。
**首次运行。** Shift 会弹出一张检查卡片,包含四项:屏幕录制权限、三个输出目录是否可写、当前实例是否持有全局快捷键、缺少哪些可选工具。每一项都会说明查到了什么并给出修复入口——打开隐私设置、退出其他实例——直接关掉卡片不会改动任何设置。每个安装只会弹一次——升级后的首次启动也算一次,因为旧设置文件里没有这个字段;删掉 `settings.json` 里的 `setupReviewed` 就能再看一次。
**macOS 首次运行。** 需要授予「屏幕录制」(截图与录屏),以及你所选输出目录的「文件与文件夹」访问权限。截图前会先检查权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑截图。
## 支持的文件
按扩展名识别,对应 `src-tauri/src/files.rs` 中的四张表。`kind` 决定中心图标以及会出现哪些扇区。**加粗**的扩展名是可以真正转换的;其余的只是能被识别,仅提供打开、在文件夹中显示,或提示你先去导出。
| 类型 | 扩展名 |
| --- | --- |
| `image` | **`png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif` `heic` `heif` `avif`** |
| `video` | **`mp4` `mov` `m4v` `avi` `mkv` `webm`** |
| `audio` | **`mp3` `wav` `m4a` `aiff` `aif` `caf` `flac` `ogg`** |
| `pdf` | **`pdf`** |
| `document` | **`docx` `rtf` `odt` `txt` `md` `html` `htm`** `doc` `pages` |
| `presentation` | **`pptx`** `ppt` `key` |
| `spreadsheet` | **`xlsx` `xls` `xlsb` `ods` `csv` `tsv`** `numbers` |
| `other` | 未识别的类型——仅提供打开与在文件夹中显示 |
解码与编码能力并不对称,应用也不会假装对称:
- **图片解码**由 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。
- **可识别但不转换:** `.doc`、`.pages`、`.ppt`、`.key`、`.numbers` 会显示各自类型的图标,并提供编辑、打开、在文件夹中显示,但没有格式扇区。请先导出为 DOCX、PPTX 或 XLSX。
## 格式转换
以下是各文件类型在格式环中的选项。每一条转换路径都实现在 `src-tauri/src/files.rs`;文件自身的格式会在运行时自动排除。
| 源类型 | 圆环目标(不含源格式) | 引擎 | 说明 |
| --- | --- | --- | --- |
| 图片 | `PNG` `JPG` `WEBP` `TIFF` `BMP` `GIF` | Rust `image` | 编码器允许时走无损路径 |
| 图片 | `HEIC` | `sips` / ImageMagick | macOS 原生;其他系统需要 `magick` |
| 图片 | `PDF` | `printpdf` | 每张图一页,按 300 dpi 定尺寸 |
| 视频 | `MP4` `MOV` | FFmpeg | 优先 `libx264`,依次回退 `h264_videotoolbox`、`mpeg4` |
| 视频 | `GIF` | FFmpeg | 仅取前 15 秒、12 fps、宽 480 px、8 MB——设有上限,避免长时间录屏产出上百 MB 的 GIF |
| 视频 | `M4A` | FFmpeg | 仅保留音频轨,192k AAC |
| 音频 | `M4A` `WAV` `MP3` | FFmpeg | 若 FFmpeg 缺少 `libmp3lame`,MP3 回退到 `lame` |
| PDF | `TXT` `MD` | `lopdf` | 抽取文字层;扫描件会明确报错并引导使用文字识别 |
| PDF | `DOCX` | 页面渲染 + 原生 DOCX 封装 | macOS 用 PDFKit,Windows/Linux 用 Poppler;保留图片、图表和页面版式,不依赖 Microsoft Word |
| PDF | `RTF` | `lopdf` + Pandoc | 以文字层作为正文;需要 Pandoc |
| PDF | `HEIC` | PDFKit / Poppler + `sips` | 先渲染为 PNG 再转码;需要系统 HEIC 编码器 |
| PDF | `PNG` `JPG` `TIFF` | PDFKit / Poppler | 每页一个文件,输出到 `… pages` 文件夹 |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit 渲染器(macOS)· 其他系统 Pandoc | macOS 路径不需要 LaTeX 或 wkhtmltopdf。带图片的 DOCX 会先经 Pandoc 转成 HTML,因为 AppKit 读取器会丢弃图片 |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` | Pandoc | 自动省略源格式;Markdown 以 GFM 写出。HTML 为图片内嵌的独立单文件 |
| 演示文稿 `.pptx` | `MD` `PDF` | 纯 Rust + Pandoc | 按页生成标题、要点文字,**表格会输出为真正的 Markdown 表格**;PDF 仍是文字摘要版,非版面还原 |
| 电子表格 | `MD` `PDF` | `calamine` / 纯 Rust | 每个工作表一张 Markdown 表;`csv`/`tsv` 直接解析 |
表中没有的转换不会出现在界面上——圆环在运行时按这份目录生成,因此看得见的扇区就是能用的扇区。若缺少依赖,扇区会直接告诉你需要安装什么,而不是静默失败。
**页码进度遵循统一规则。** 能真实逐页处理的转换统一显示「正在转换第 N/M 页…」;当前包括图片型 DOCX→PDF 与带图 PDF→DOCX。一次性排版的文本 DOCX→PDF、以及纯文字 PDF→DOCX 无法可靠获得页数,因此显示「处理中…」,不会伪造页码。
> 说明:转换环不会重复列出文件自身的格式。例如 DOCX 不会出现 DOCX,避免无意义的整篇重写和版式损失。
> 扫描件/纯图片 PDF 没有文字层,选 `TXT`/`MD` 会返回明确报错——请改用「文字识别」,它会先把每页渲染成图片。
## 工具
工具环(拖拽时按 `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°,按各格式的原生方式处理;HEIC/AVIF 输入在本机没有对应编码器,因此结果转为 PNG |
| 翻转 | 图片 | 同类型,` (flipped)` | 水平镜像 |
| 黑白 | 图片 | 同类型,` (bw)` | 转灰度 |
| 50% | 图片 | 同类型,` (50%)` | 宽高各减半,Lanczos3 |
| 裁剪 | 图片 | `.png`,` (cropped)` | 环形菜单中的裁剪会打开编辑器进行交互式框选 |
| 抠图 | 图片 | — | 打开编辑器,按采样到的背景色抠除背景 |
| 合并 | 2 张以上图片 | `.pdf`,` (images)` | 每图一页,按选中顺序排列 |
| 合并 | 2 个以上 PDF | `.pdf`,` (merged)` | 按选中顺序拼接 |
| 拆分 | PDF | `Page 001.pdf` … | 每页一个 PDF,输出到 `… pages` 文件夹 |
| 提取文字 | PDF | `.txt` | 仅文字层;扫描件请用「文字识别」 |
| 720p | 视频 | `.mp4`,` (720p)` | 缩放到 720p 高度,保持宽高比 |
| 静音 | 视频 | 同类型,` (muted)` | 去掉音轨,视频流直接复制、不重编码 |
| 截帧 | 视频 | `.png`,` (frame)` | 取首帧导出为静帧 |
| 提取音频 | 视频 | `.m4a` | 192k AAC |
| 单声道 | 音频 | `.m4a`,` (mono)` | 下混为单声道 128k AAC |
| 纯文本 | 文档 | `.txt` | 通过 Pandoc 导出纯文本 |
| 文字识别 | 图片、PDF | `.txt`,` (OCR)` | 见 [OCR](#ocr) |
| 编辑 / 标注 / 打码 / 加背景 | 图片 | — | 打开图片编辑器,在工具栏中自行选择标注工具 |
| 打开 · 在文件夹中显示 | 任意文件 | — | 交由系统默认应用或文件管理器 |
## 压缩、命名与取消
**「压缩」具体做了什么。**
| 输入 | 行为 |
| --- | --- |
| 图片 | 按画质 68 重新编码。含透明通道的图片写出 PNG,其余写出 JPG |
| PDF | 超过 1440 px 的内嵌图片先降采样为 q60 JPEG,再清理、重编号对象并压缩保存。若结果没有更小则不写出文件 |
| 视频 | 以 CRF 28 / 目标码率 2M 重编码,AAC 96k 音频,输出 MP4 |
| 音频 | 转为 128k AAC 的 M4A |
**输出命名——永不覆盖任何文件。** 结果保存在源文件旁边并附带描述性后缀;重名时追加 ` 2`、` 3`……而不是替换原文件。
```text
report (compressed).pdf photo (rotated).png slide (bw).png
report (clean).pdf photo (50%).png report (merged).pdf
```
PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001.png`、`Page 002.png`……再执行一次会生成 `名称 pages 2`,同样不会覆盖。
**取消手势。** 在圆环中心附近、或圆环范围之外松开鼠标,不会执行任何操作。
## 截图与标注
**截图。** 区域截图会先铺一层冻结画面,你框选的像素就是最终得到的像素;全屏截图则完全跳过遮罩层。录屏在 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,因此源文件永远不会被修改。
| 工具 | 行为 |
| --- | --- |
| 矩形、箭头、高亮、文字 | 自由绘制;每种工具使用固定配色与线宽 |
| 打码 | 实心黑色遮挡条,直接烧入输出图像——不是覆盖层 |
| 马赛克 | 对下方区域做真实采样降采样,不是半透明填充 |
| 模糊 | 对区域做真正的高斯模糊,并按绘制形状裁切 |
| 图章 | 对勾、叉、星三种矢量图章,点一下即可落下 |
| 序号 | 自动递增的序号标记 |
| 裁剪 | 交互式裁剪,带明确的「应用裁剪」步骤 |
| 加背景 | 圆角留白加渐变底,适合社交配图与幻灯片插图 |
| 抠图 | 采样四角、求平均背景色,并将其抠为透明 |
| 撤销 | 先回退标注,再回退图像级操作 |
| 保存副本 / 复制 | 另存为带后缀的新文件,或直接写入剪贴板 |
| 钉在屏幕上 | 将图片浮为置顶窗口,带放大、复制与关闭按钮 |
**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以**只读文本预览**打开。所有类型都提供复制、另存为、打开与在文件夹中显示;文字识别、复制文字与钉图只出现在图片编辑器中。文本不会在应用内就地编辑。文本超过 8 MB,或图片超过 64 MB / 4000 万像素时,编辑器会报告上限而不是加载。
## 截图历史库
每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。这份文件在应用包之外,**升级与重装都不会清空它**;升级后的首次启动还会接管 0.1 版本留在 Webview 自己的存储里的旧记录,因此那条改动之前积累的列表也不会丢。主窗口的「最近使用」卡片就是这个历史库:
- 列表超过几行后出现**搜索**框,按文件名过滤。
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。收藏的行会在缩略图角上带一颗星,不用悬停就能看出哪些是收藏的。
- **移除**单行,或**清空**整个库——收藏项会保留。
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径,供编辑器使用。
- **把某一行拖到「文件转换 / 文件工具 / 文字识别」上**,就直接对这份用过的文件执行该操作——同一种手势反过来用。和所有拖放一样,它必须落在按钮上,拖回列表不会执行任何操作。
- 单击某一行在编辑器中打开;行内其余按钮负责发送、在文件夹中显示、以及钉在屏幕上。
## OCR
界面中对应「文字识别」(图片与扫描件)和「提取文字」(含文字层的 PDF)两处按钮。
使用 Tesseract.js 的 LSTM 内核,以 WASM 形式在应用内运行。`eng` 与 `chi_sim` 语言模型在构建时由 `pnpm prepare:ocr` 复制到 `public/tesseract`,因此识别无需联网,首次运行也不会下载任何东西。
- **图片**——单次识别,实时显示进度,结果可进入编辑器或剪贴板。
- **扫描版 PDF**——先把各页渲染成图片,再逐页识别并显示每页进度,结果写入 ` (OCR)` 文本文件,页与页之间用 `--- Page N ---` 分隔。
- **含文字层的 PDF**——请改用「提取文字」,它直接读取内嵌文字层,速度远快于 OCR。
## 发送到设备
Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 AirDrop 式传输。把鼠标移到「最近使用」的任意一行点击发送按钮,或打开文件的「文件工具」环并松开在「发送」扇区上——两种入口都会弹出每台设备一张卡片的设备选择面板,点击卡片即刻开始传输。工具环对每一种文件类型都提供「发送」,选中多个文件时按一批一起发送。
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。是否顺带把访达(或资源管理器)带到前台,由「完成后在访达中显示」这个开关决定,与转换完成时的行为一致;一批文件只在最后一个落地时显示一次。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
无需服务器、无需配置,发现机制如下:
- 每个实例每两秒向组播组 `239.255.77.88:47888` 发送一次小型 UDP 广播,并额外向每个已启用的 IPv4 子网发送定向广播;如果路由器同时丢弃组播与广播,还会通过单播扫描同一网段。每个普通信标都会得到一次单播回应,因此设备不会只闪现一次后过期。广播内容包含机器名、操作系统,以及用于接收文件的动态 TCP 端口。
- 十五秒内没有再次收到广播,设备就会从列表移除;这既能在切换网络后清掉过期条目,也给旧版本的再次回应留出时间。
- 文件字节通过直连 TCP 传输:`SHSF` 握手、JSON 头、文件内容,最后一字节确认;只有接收方已完整落盘,发送方才会报告成功。
整个过程只涉及本地网络——不会有任何数据走到互联网。接收端监听全部网卡,因此 macOS 首次分享时会弹出防火墙授权提示,允许后双向均可用。
## 自定义圆环顺序
已保存的顺序会为某种文件类型、某个环重新排列扇区。**调整顺序的界面已不在设置中**——该标签页已移除,因此顺序仍从 `settings.json` 的 `wedgeOrders` 读取并生效,但当前界面不再提供修改入口。已有的顺序照常工作,只是暂时无法在应用内更改。
决定“存在哪些操作”的是目录而不是预设。`src/lib/radialOrder.ts` 保存每种文件类型、每个环的扇区列表,保存的顺序只能对目录为该类型提供的 id 重新排列:日后被移除的 id 会自动从圆环消失,新增的 id 会插入默认位置,而**发送**永远排在最后。改完下一个手势即生效——不需要重启,也不可能把某个操作藏到你找不到。
## 快捷键
| 操作 | macOS | Windows / Linux |
| --- | --- | --- |
| 区域截图 | `⌥⇧2` | `Alt+Shift+2` |
| 区域录屏 | `⌥⇧3` | `Alt+Shift+3` |
| 全屏截图 | `⌥⇧4` | `Alt+Shift+4` |
| 拖拽时显示格式环 | 按住 `⇧` | 按住 `Shift` |
| 拖拽时显示工具环 | `⌥⇧` | `Alt+Shift` |
三个截图快捷键注册为全局快捷键。拖拽圆环由修饰键驱动:在开始拖动之前就按住修饰键,圆环会直接出现在光标处,无需先让 Shift 获得焦点。
## 菜单栏菜单
菜单栏(macOS)与通知区域(Windows)图标提供这些快捷入口:
| 菜单项 | 快捷键 | 作用 |
| --- | --- | --- |
| Open Shift | — | 显示主窗口 |
| Capture area | `Alt+Shift+2` | 开始区域截图 |
| Capture full screen | `Alt+Shift+4` | 截取光标所在显示器 |
| Record area | `Alt+Shift+3` | 开始或停止区域录屏 |
| OCR | — | 选择图片并在本机识别文字 |
| Update available *x.y.z* | — | 仅在有可用更新时出现;打开设置 → 软件更新 |
| Quit Shift | `Cmd/Ctrl+Q` | 退出;若有正在进行的录屏会先收尾保存 |
菜单项文案会跟随应用语言;macOS 系统权限弹窗仍为英文。
设置面板的「行为」区有两个开关:**拖拽圆环**(Shift 拖拽手势的总开关)与**开机时启动**。
## 输出位置
| 结果 | 默认位置 |
| --- | --- |
| 截图 | `~/Pictures/Shift` |
| 录屏 | `~/Movies/Shift` |
| 文件操作 | 源文件所在文件夹 |
三者都可在设置中修改。文件操作另外提供「统一收集到一个文件夹」模式,替代默认的就近保存。设置面板会列出所有解析后的实际路径、检测该路径是否可写、在文件管理器中显示它,并在缺少权限时直接跳转到 macOS 的「屏幕录制」与「文件与文件夹」隐私面板。
## 软件更新
新的 macOS 机器请安装 **`Shift-0.1.13-macOS-universal.dmg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者。双击挂载镜像,把 `Shift.app` 拖进「应用程序」,然后允许首次启动一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。软件内升级自己下载的是同一个镜像、不经浏览器,因此不会弹窗。详见 `docs/RELEASE.md`。
更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。
Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。发现的版本会显示在主窗口顶部——「Shift x.y.z 可以升级了」,旁边一个按钮直接跳到设置 → 软件更新——并且**跨启动保留**,包括升级装完之后的那一次启动:提示是记在磁盘上的,不是只存在内存里。探测本身一天最多跑一次,所以只活在内存里的话,新版本只在被发现的问题当天出现,之后每次启动都再也看不到。下载完成的安装包必须与清单的体积和重新计算的 SHA256 一致,而且这两项会在交接给安装脚本前**再次校验**。任一不符即删除文件并明确报错,因此半成品或被替换的安装包永远不会启动。点击「丢弃」会同时删除已下载的安装包和状态。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。
**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。辅助脚本通过进程参数或环境变量接收路径,路径不会被拼接进 shell 或批处理脚本文本;Windows 启动器还保留了一层外层引号,否则 `cmd.exe /C` 会把含空格路径的首尾引号剥掉。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。
## 外部依赖
核心转换、环形菜单、截图与 OCR 在零外部依赖的情况下即可工作。以下工具用于扩展能力边界:
| 工具 | 用于 | macOS | Windows | Linux |
| --- | --- | --- | --- | --- |
| 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) | 需要 | 需要 |
| ImageMagick `magick` | HEIC/HEIF/AVIF 输入与 HEIC 输出 | 不需要(`sips`) | 需要 | 需要 |
| LAME | 当 FFmpeg 缺少 `libmp3lame` 时的 MP3 编码 | 少见 | 少见 | 少见 |
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,以及它们在本平台各自负责什么。显示为缺失的行同时给出出口:能装的都带**安装**按钮(macOS 通过 Homebrew 安装 Pandoc 与 FFmpeg;Windows 通过 WinGet 安装 Pandoc、FFmpeg、Poppler、ImageMagick 与 Typst),没有按钮的行说明该能力是内置的,或在本平台根本不会用到。缺失不止一项时,面板标题栏还会给出**一键安装 N 个组件**,把所有缺失项作为一个请求提交:安装依次执行(包管理器同一时刻只允许一个安装),而一个包能回答多行时只装一次(Windows 上 Poppler 同时服务两行 PDF)。安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
## 平台支持情况
| 能力 | macOS | Windows | Linux |
| --- | --- | --- | --- |
| 环形菜单、编辑器、托盘、多语言 | 支持 | 支持 | 支持 |
| 拖拽唤起圆环 | AppKit 全局拖拽桥 | Win32 拖拽状态轮询 + 原生拖放 | 暂不支持——仅能用主窗口选择文件 |
| 区域 / 全屏截图 | `screencapture` | Win32 GDI `BitBlt` | `grim` / `gnome-screenshot` |
| 跟随光标所在显示器 | 支持 | 支持 | `grim` 输出选择 |
| 区域录屏 | `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 文字、合并、拆分、旋转、压缩 | 支持 | 支持 | 支持 |
| PDF 转图片 | PDFKit 伴生进程(HEIC 需 `sips`) | Poppler(HEIC 需 ImageMagick) | Poppler(HEIC 需 ImageMagick) |
| PDF 转 Word | 内置页面渲染器 | 需 Poppler | 需 Poppler |
| 扫描件文字识别 | 支持 | 需 Poppler | 需 Poppler |
| 文档转 PDF | 内置 AppKit 渲染器 | Pandoc + PDF 引擎 | Pandoc + PDF 引擎 |
| PPTX / XLSX / ODS 转 Markdown | 支持(纯 Rust) | 支持 | 支持 |
| 本地中英文字识别 | 支持 | 支持 | 支持 |
## 从源码构建
需要 Node.js 20+、pnpm 8+、Rust 1.90+;构建 macOS 原生伴生进程还需 macOS 13+ 与 Xcode 命令行工具。
```bash
pnpm install
pnpm mac:drag-bridge # 仅 macOS —— AppKit 拖拽桥、PDFKit 与文档渲染器
pnpm tauri dev
```
`pnpm mac:drag-bridge` 会把 `native/macos/*.swift` 编译为 `src-tauri/binaries` 下的分架构与通用(universal)伴生进程。Windows 与 Linux 完全跳过这一步。
```bash
pnpm check # TypeScript 类型检查,不产出文件
pnpm test # 转换矩阵、圆环目录与顺序、拖拽载荷、投放命中测试
pnpm build # tsc + vite
cargo test --lib # Rust 单元测试,在 src-tauri/ 目录下执行
pnpm tauri build # 发布构建
```
带版本号的正式构建:
```bash
rustup target add aarch64-apple-darwin x86_64-apple-darwin
pnpm mac:release
scripts/build-windows-release.sh
```
发布链只产出两个安装包:`Shift-0.1.13-macOS-universal.dmg` 与 `Shift-Setup-0.1.13-win-x64.exe`。macOS 是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程;Windows ARM64 通过更新清单的兼容回退使用 x64 安装包。完整步骤见 `docs/BUILD_WINDOWS.md` 与 `docs/RELEASE.md`。
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」,「发送到设备」需要「本地网络」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。「本地网络」被拒绝时比较安静:Shift 仍会发出广播、也能回应主动找它的实例,但收不到组播,设备列表于是始终为空。ad-hoc 签名每次重新构建都会得到新的代码身份,而 macOS 正是按这个身份记录上述授权,所以升级后可能重新询问;改用 Developer ID 签名即可保持稳定。
## 架构
```text
React UI 单一 webview,八类视图
├─ main 拖放目标、快捷键、截图历史库、设置、首次运行检查
├─ radial 透明置顶圆环,按极角扇区命中判定
├─ capture 冻结画面 + 区域框选
├─ recorder 悬浮计时器与停止按钮
├─ editor 标注画布、文本、视频、OCR
├─ result-* 截图后的浮动结果卡片,每次截图一个窗口
├─ share-* 收到文件时的确认卡片
└─ pin 置顶图片参考窗
Tauri 命令层 src-tauri/src/
├─ files.rs 检视、转换、压缩、元数据、旋转、裁剪、音视频
├─ pdf.rs 合并、拆分、旋转、文字、渲染、图片转 PDF、压缩
├─ office.rs PPTX 与电子表格转 Markdown,纯 Rust
├─ capture.rs 全屏截图、区域裁剪、交给编辑器
├─ recording.rs screencapture / FFmpeg / wf-recorder,以信号方式收尾
├─ drag_bridge.rs 全局拖拽检测、圆环模式、环形菜单定位
├─ settings.rs 输出目录、可写检测、圆环顺序、隐私面板深链、首次检查标记
├─ history.rs 共享的截图/结果历史库、收藏与容量上限
├─ result_card.rs 浮动结果卡片,自带自动关闭保险
├─ update.rs 清单拉取、签名校验、semver 比较、SHA256 校验
├─ share.rs 局域网广播、设备列表、AirDrop 式文件传输
└─ editor.rs 编辑器与钉图窗口状态
平台适配器
├─ macOS AppKit 拖拽桥 · PDFKit 渲染器 · AppKit 文档渲染器 · screencapture
├─ Windows Win32 拖拽状态 · GDI BitBlt 截图 · FFmpeg · Poppler
└─ Linux grim / gnome-screenshot · wf-recorder(Wayland)· FFmpeg · Poppler
OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线
```
环形菜单的命中判定是纯几何计算——同一套极角运算同时服务于原生指针事件、webview 悬停与 Windows 的拖放数据,因此圆环行为不会在各平台之间产生偏差。
## 技术文档
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) —— 进程/窗口模型、模块边界、事件与数据流。
- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) —— 产品行为规范、输出命名、平台差异与验收标准。
- [`docs/SECURITY.md`](docs/SECURITY.md) —— 信任边界、更新完整性、局域网传输限制与剩余风险。
- [`CONTRIBUTING.md`](CONTRIBUTING.md) —— 开发环境、测试门禁与发布前检查。
- [`docs/README.md`](docs/README.md) —— 全部技术与发布文档的索引。
- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) —— 不允许退回到旧故障的工程回归台账。
- [`docs/RELEASE.md`](docs/RELEASE.md) —— 发布通道、签名与更新交接。
- [`docs/ROADMAP.md`](docs/ROADMAP.md) 与 [`docs/MOBILE.md`](docs/MOBILE.md) —— 后续计划与移动端方案。
## 仓库结构
```text
src/ React 界面、多语言(en/zh)、Tauri API 绑定
src/lib/ 纯函数与 Node 测试:转换矩阵、圆环目录与顺序、拖拽载荷、
投放命中判定
src-tauri/src/ Rust 命令层与平台适配器
native/macos/ Swift 伴生进程:拖拽桥、PDF 渲染器、文档渲染器
由 pnpm mac:drag-bridge 编译进 src-tauri/binaries/
scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器、发布构建、
清单发布与清单签名
public/tesseract/ WASM 内核与语言模型;由 pnpm prepare:ocr 刷新,
已纳入仓库以保证干净检出可离线构建并离线 OCR
assets/ 应用图标源文件
src-tauri/icons/ 各平台生成的应用图标
docs/ 架构、行为规范、安全模型、发布指南、工程回归台账、路线图与移动端规划
scripts/linux/ 构建 Linux deb/AppImage 的 Dockerfile
.github/workflows/ macOS、Windows、Linux 的 CI 定义(见「参与贡献」)
```
## 隐私
Shift 对文件做的任何处理都不会发起互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;截图历史库只是一个本地文件。既不上传,也不收集。
只有两条路径会接触网络,且只有你主动使用时才会携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单,只有你按下按钮时才下载安装包;**发送到设备**只在本地网络使用 `239.255.77.88:47888` 上的 UDP 信标和你所选设备之间的直连 TCP(或有另一台 Shift 主动向你发送文件)。分享关闭时发现不会启动,传输必须经接收方确认后才开始。局域网流量没有身份认证,也没有加密;该边界详见 [`docs/SECURITY.md`](docs/SECURITY.md)。
## 已知限制
- Windows/Linux 上的文档转 PDF 仍需 Pandoc 加上可用的 PDF 引擎;内置的 AppKit 渲染器仅限 macOS。
- PPTX 与电子表格转 PDF 是文字与表格摘要,不是版面精确还原。
- `.doc`、`.pages`、`.ppt`、`.key`、`.numbers` 可识别但不解析——请先导出为 DOCX/PPTX/XLSX。
- HEIC/HEIF/AVIF 可由系统解码器读取,格式转换与像素类工具都能直接使用。只是这两种格式无法经由该路径写出,因此对它们执行像素类工具时会输出 PNG;AVIF 仍不提供为导出目标。
- PDF 压缩会把内嵌图片降采样到最长边 1440 px、q60 JPEG。凡是不能确认可安全往返的内容都会原样保留——蒙版、索引色/CMYK、JPX/JBIG2/CCITT——因此部分特殊扫描件仍难以压缩。
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`。这些运行路径尚未在 macOS 开发机上实际验证,因此 Linux 截图能力在真机确认前只能算「可编译」。
- Linux 是「可构建」而非「已发布」:不提供 deb 或 AppImage,更新通道里也没有 `linux` 键,因此 Linux 构建检查更新时会得到「没有对应产物」。想要自己动手的人,可照 `scripts/linux/Dockerfile` 或 CI 里的 `linux` 任务来做。
- 把历史库的某一行拖出去依赖 Webview 对 file URL 拖拽的支持。载荷使用标准的 `text/uri-list`(内含 `file://` 条目)并附带纯文本路径,仍需在每个平台上做手势级验证;在此之前,**发送**、**在文件夹中显示**以及行内按钮是交付文件的确定路径。
- 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。发现机制的不可回退约束、权限排查与回归矩阵见 `docs/ENGINEERING-NOTES.md`。
- Windows 上每台电脑只有一个 Shift 实例能占用发现端口,因此额外实例不会出现在设备列表中。
- Windows 与 Linux 代码路径在本机通过编译验证,并在有执行器的托管平台上由仓库内的 CI 定义覆盖;手势层面的验证仍需真实 Windows 与 Linux 设备。
- macOS 上签名身份变化后,可能需要重新授予「屏幕录制」与「辅助功能」权限。
- 局域网分享没有认证与加密。接受一次传输只能证明你同意了这次请求,不能证明发送者身份;请只在可信网络使用。
- Office ZIP/XML 解析与 PDF 渲染尚未在所有编解码器和外部渲染器之间共享同一份资源配额。编辑器预览已有上限,但异常巨大或恶意的文档仍应按不可信输入处理。
路线图见 `docs/ROADMAP.md`。
## 常见问题
**❓ 按住 Shift 拖文件,圆环没出现。**
一定要先开始拖动——按住鼠标并把文件拖过拖动阈值——在拖动过程中按住 `Shift`。只选中文件再按 `Shift` 是没有反应的。Windows 需要在拖拽越过系统阈值的那一刻按住 `Shift`;同一时刻再按 `Alt` 则进入工具环。
**❓ 提示这类文件没有可用格式。**
未识别的扩展名仅提供打开与在文件夹中显示;旧版 Apple/Office 格式(`.doc`、`.pages`、`.ppt`、`.key`、`.numbers`)刻意不提供转换。请先导出为 DOCX、PPTX 或 XLSX。
**❓ 能开机自启吗?能一键停用吗?**
都可以,位置在设置面板的「行为」区。**拖拽圆环**是 Shift 拖拽手势的总开关:关闭后不会再出现任何圆环,而托盘、主窗口与快捷键照常可用。**开机时启动**会在 macOS 写入 LaunchAgent、Windows 写入 `HKCU\...\Run`、Linux 写入 autostart `.desktop`,同一开关即可撤销。
登录项只对当前用户生效,并指向 .app 包本身,因此 macOS 的屏幕录制授权身份在多次启动间保持一致。若移动了应用位置,请重新切换一次该开关。
**❓ 我的文件会被上传吗?**
不会。代码里不存在上传路径,转换与 OCR 流程也不发起任何网络请求;Tesseract 模型随应用一起打包。不收集数据,也没有账号体系。
**❓ 输出文件去哪儿了?**
默认在源文件旁边,带描述性后缀。可先看主窗口的最近列表,点击条目即可打开结果;设置面板会列出全部实际输出路径并可在文件管理器中显示。
**❓ 支持哪些语言?**
英文与简体中文,可在主窗口的设置中切换;首次启动时跟随系统语言。托盘菜单会跟随所选语言;macOS 系统权限弹窗仍为英文。
**❓ Shift 怎么获取更新?**
就来自本仓库。`releases` 分支保存安装包,以及记录每个文件 SHA256 的清单;设置 → **软件更新** 会显示当前构建读取的更新源,每天检查一次,并在你点击后才下载。只有下载结果的字节数与重新计算的 SHA256 同时与清单一致,才允许安装。发布流程见 `docs/RELEASE.md` 与 `scripts/publish-release.sh`。
**❓ 能调整扇区的先后顺序吗?**
顺序会被照常执行,但目前没有修改它的界面:设置中已不再有该标签页。写在 `settings.json` 里 `wedgeOrders` 的顺序仍然生效;顺序只能排列这种文件真正支持的操作,不能增删,并且**发送**始终排在最后。
**❓ 能先标注、不保存原图吗?**
可以。标注工作在画布副本上,只有「保存副本」或「复制」才会写盘,源文件永不被修改。也可以「钉在屏幕上」,把它作为浮动参考图。
**❓ 怎么卸载?**
从托盘退出,然后删除应用即可。除你指定的输出目录和应用自身的配置/缓存目录外,不会写入其他位置。
## 参与贡献
新增一种格式 = 在 `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 fmt --check`、`cargo test --lib`、`cargo clippy --all-targets -- -D warnings` 与 `git diff --check`;平台环境与手工验收矩阵见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
`.github/workflows/ci.yml` 定义了 macOS、Windows、Linux 三个任务。每个任务都会运行类型检查、TypeScript 测试、Rust 格式检查与单元测试;macOS 任务还运行 Clippy 和通用应用构建。当前托管平台是否真正执行这些任务,取决于它是否配置了执行器;本地运行仍是发布门禁,没有链接到实际日志时不得声称 CI 已通过。完整环境与推送前检查见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
**欢迎二次开发。** 你可以免费使用、修改、再发布本代码,也可用于商业项目,只需保留原版权声明与 LICENSE 文件。
## 许可证
以 **MIT 许可证**发布——见 [LICENSE](LICENSE) 与 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
本应用构建使用了 Tauri(MIT / Apache-2.0)、React(MIT)、Lucide(ISC),以及 Tesseract.js 与其英文、简体中文模型(Apache-2.0)。

View File

@ -1,4 +0,0 @@
aa65404a92c98339f9b9e1335f260f8da25434f84767c8935d61194ebd8dd122 Shift-0.1.14-macOS-universal.dmg
a8bcc8b885f37414d831557c744ce48a0e87cd0329da91bdbeaf7e5461e9013c Shift-Setup-0.1.14-win-x64.exe
6877c5f674b89bf7ee72f9e43f2c8fdcbdcdef93e6e3ebcb72dce9568114ae95 README-Windows-x64.txt
ad084fa6f005ca917dd9ef106bdb29171e125f440d92f1206270873476d01f1e README-macOS-universal.txt

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,12 @@
# Third-party notices
Shift includes or builds against the following open-source components:
- Tauri: MIT or Apache-2.0.
- React: MIT.
- Lucide icons: ISC.
- Tesseract.js: Apache-2.0.
- tesseract.js-core: Apache-2.0.
- tessdata_fast English and Simplified Chinese models: Apache-2.0.
See each package's license file under `node_modules` or its upstream repository for the complete text.

View File

@ -1,4 +1,4 @@
Shift 0.1.14 - macOS 通用(universal) Shift 0.1.13 - macOS 通用(universal)
本文件说明 macOS 安装包是怎么打出来的、在其它机器上会遇到什么,以及如何自己校验。 本文件说明 macOS 安装包是怎么打出来的、在其它机器上会遇到什么,以及如何自己校验。
完整细节见仓库 docs/RELEASE.md 的「macOS packaging」和 docs/ENGINEERING-NOTES.md 完整细节见仓库 docs/RELEASE.md 的「macOS packaging」和 docs/ENGINEERING-NOTES.md
@ -8,7 +8,7 @@ Shift 0.1.14 - macOS 通用(universal)
关于这个安装包 关于这个安装包
-------------- --------------
Shift 的 macOS 产物只有一个:Shift-0.1.14-macOS-universal.dmg,通用二进制,Apple silicon 与 Shift 的 macOS 产物只有一个:Shift-0.1.13-macOS-universal.dmg,通用二进制,Apple silicon 与
Intel 都能用。它既是新机器的首次安装方式,也是软件内升级的载体(更新清单里的 macos Intel 都能用。它既是新机器的首次安装方式,也是软件内升级的载体(更新清单里的 macos
键指向它)。清单的键必须是 .dmg,因为软件内升级的交接脚本要用 hdiutil 挂载镜像再 键指向它)。清单的键必须是 .dmg,因为软件内升级的交接脚本要用 hdiutil 挂载镜像再
取出应用包;早期曾随包发布的 .pkg 在验证过 DMG 可用后就撤掉了,不为它多维护一份 取出应用包;早期曾随包发布的 .pkg 在验证过 DMG 可用后就撤掉了,不为它多维护一份
@ -23,7 +23,7 @@ Intel 都能用。它既是新机器的首次安装方式,也是软件内升
---------------- ----------------
新机器首次安装 新机器首次安装
1. 下载并双击 Shift-0.1.14-macOS-universal.dmg 挂载镜像。 1. 下载并双击 Shift-0.1.13-macOS-universal.dmg 挂载镜像。
2. 把 Shift.app 拖进「应用程序」(或任何你有权限的位置)。 2. 把 Shift.app 拖进「应用程序」(或任何你有权限的位置)。
3. 首次启动会被拦:「无法打开,因为来自身份不明的开发者」。点取消,然后 3. 首次启动会被拦:「无法打开,因为来自身份不明的开发者」。点取消,然后
右键 Shift.app → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。 右键 Shift.app → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。
@ -70,7 +70,7 @@ macOS 权限
pnpm tauri build --target universal-apple-darwin --bundles app,dmg pnpm tauri build --target universal-apple-darwin --bundles app,dmg
`pnpm mac:release` 会构建、校验并复制为 artifacts/Shift-0.1.14-macOS-universal.dmg。 `pnpm mac:release` 会构建、校验并复制为 artifacts/Shift-0.1.13-macOS-universal.dmg。
发布流程(清单、签名、推送)见仓库 docs/RELEASE.md。 发布流程(清单、签名、推送)见仓库 docs/RELEASE.md。
若希望更新通道能校验来源,构建时把 ed25519 公钥编进去(发布流程见仓库 若希望更新通道能校验来源,构建时把 ed25519 公钥编进去(发布流程见仓库
@ -96,7 +96,7 @@ docs/RELEASE.md 的「Signing the channel」):
镜像完整性: 镜像完整性:
hdiutil verify Shift-0.1.14-macOS-universal.dmg hdiutil verify Shift-0.1.13-macOS-universal.dmg
校验后仍打不开的话,请确认不是在压缩包预览窗口里运行的,并按上面的「新机器首次安装」 校验后仍打不开的话,请确认不是在压缩包预览窗口里运行的,并按上面的「新机器首次安装」
处理首次允许:右键 → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。 处理首次允许:右键 → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。

13
assets/icon.svg 100644
View File

@ -0,0 +1,13 @@
<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="102" y="102" width="820" height="820" rx="182.58" fill="#FF6B35"/>
<g fill="#FFF4EA">
<path d="M526.79 186.34 A326.00 326.00 0 0 1 786.64 336.36 L663.77 414.94 A180.16 180.16 0 0 0 520.17 332.03 Z"/>
<path d="M801.43 361.97 A326.00 326.00 0 0 1 801.43 662.03 L671.95 594.91 A180.16 180.16 0 0 0 671.95 429.09 Z"/>
<path d="M786.64 687.64 A326.00 326.00 0 0 1 526.79 837.66 L520.17 691.97 A180.16 180.16 0 0 0 663.77 609.06 Z"/>
<path d="M497.21 837.66 A326.00 326.00 0 0 1 237.36 687.64 L360.23 609.06 A180.16 180.16 0 0 0 503.83 691.97 Z"/>
<path d="M222.57 662.03 A326.00 326.00 0 0 1 222.57 361.97 L352.05 429.09 A180.16 180.16 0 0 0 352.05 594.91 Z"/>
<path d="M237.36 336.36 A326.00 326.00 0 0 1 497.21 186.34 L503.83 332.03 A180.16 180.16 0 0 0 360.23 414.94 Z"/>
</g>
<circle cx="512" cy="512" r="108.09" fill="#FFF4EA"/>
<path d="M445.08 512H578.92M512 445.08V578.92" stroke="#FF6B35" stroke-width="24.02"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1,223 @@
# Architecture
Shift is a single locally running desktop process. There is no application
backend, account service or cloud database. Rust owns native work, durable
state and process boundaries; React owns presentation and transient interaction
state.
This document describes the current shape. Behavioural requirements live in
[`SPECIFICATION.md`](SPECIFICATION.md), security boundaries in
[`SECURITY.md`](SECURITY.md), and historical failure constraints in
[`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md).
## Process and window model
The Tauri process hosts one webview asset bundle. `src/App.tsx` selects one of
eight view kinds from the `view` query parameter:
| View | Window label | Responsibility |
| --- | --- | --- |
| `main` | `main` | File picker, drop targets, recent library, settings, first-run checks |
| `radial` | `radial` | Transparent always-on-top format/tool ring |
| `capture` | `capture` | Frozen-screen overlay and area selection |
| `recorder` | `recorder` | Recording timer and stop control |
| `editor` | `editor` | Image annotation, video player, read-only text preview, OCR |
| `result-card` | `result-*` | Post-capture actions; one window per capture |
| `share-notice` | `share-*` | Incoming-transfer consent card |
| `pin` | `pin` | Always-on-top image reference |
Closing the main, editor, radial or pin window hides it rather than exiting the
app. Tray and global-shortcut actions can bring these surfaces back. A second
instance is routed to the existing copy by `tauri-plugin-single-instance`; only
one process owns the global shortcuts and, on Windows, the shared discovery
port.
## State ownership
Rust-owned runtime state is registered as managed Tauri state:
- `AppState`: capture session, recording child, editor session, radial drag
context, native drag bridge process and capture-window restoration list.
- `ShareState`: local beacon, bounded peer table, pending consent offers,
accepted batch windows and the discovery enabled flag.
- `HistoryState`: the in-memory recent-file list, persisted to
`app_data_dir/history.json`.
- `UpdateState`: last update status and whether the last signature check
passed.
Settings are persisted as one JSON read-modify-write document at
`app_config_dir/settings.json`. Writes use a process-wide mutex and an atomic
replace (temporary file then rename). History is a convenience cache: its write
is a single replace and a corrupt or missing file falls back to an empty list.
Frontend state is not authoritative for file output, history, downloads or
editing results. A renderer can be hidden and recreated; durable state remains
in Rust or on disk.
## Module boundaries
| Module | Owns |
| --- | --- |
| `files.rs` | Extension classification, previews, conversion/tool catalogue execution, collision-safe output names, editor data commands, external process helpers |
| `pdf.rs` | PDF merge/split/rotate/text/render/compress and PDF-to-DOCX packaging |
| `office.rs` | DOCX image-page extraction, PPTX text/tables and spreadsheet parsing |
| `markdown.rs` | Bundled Markdown-to-HTML fallback |
| `capture.rs` | Screen permission checks, monitor selection, screenshot capture, crop and result handoff |
| `recording.rs` | `screencapture`, FFmpeg and `wf-recorder` backends, stop/finalization |
| `drag_bridge.rs` | Native drag detection, ring mode and radial context |
| `editor.rs` | Editor session and pinned-image window state |
| `history.rs` | Recent-file merge, capacity, pinning, persistence and events |
| `settings.rs` | Settings schema, output directories, write checks, app language |
| `share.rs` | LAN discovery, peer table, SHSF transfer protocol and consent |
| `update.rs` | Manifest fetch/parse/signature, download, integrity gate and installer handoff |
| `result_card.rs` | Post-capture card lifecycle and auto-close |
| `runtime.rs` | External component detection and installation instructions |
| `process.rs` | Spawn helper that suppresses console windows on Windows |
`pdf.rs`, `office.rs` and `markdown.rs` deliberately have no Tauri window
management. They operate on paths and values so they can be tested without a
live app handle.
## Core data flows
### File action
1. A drag, picker or recent row chooses one action and one or more source paths.
2. `RadialMenu.tsx` calls `perform_file_action` with a generated `jobId`.
3. Rust runs `files::perform_action` off the UI thread.
4. Progress may arrive as `app://file-action-progress`; completion arrives as
`app://file-action-finished` with either an `ActionOutcome` or an error code.
5. New paths are recorded in `history.json`, broadcast on `history://changed`
and announced through `app://file-result`.
6. The UI reveals results only if the auto-reveal setting is enabled.
Source files are opened read-only. Every output goes through `unique_output` or
`unique_output_in`, which append ` 2`, ` 3`, ... instead of replacing an
existing file.
### Capture and recording
1. `start_capture` checks screen-capture permission and selects the monitor
under the pointer.
2. The screen is captured to a temporary file, Shift's own windows are hidden,
and the `capture` overlay is shown with the frozen frame.
3. A crop is written through the same collision-safe naming path as any other
result. Full-screen capture skips the overlay.
4. A result card window is created; if it cannot be created, the editor opens
instead so the capture still has an action surface.
5. Recording is a separate child process. Stopping it finalizes the file,
restores hidden windows and hands the recording to the editor/card flow.
### Editor
Images are read by Rust and returned as a data URL so the canvas can export
without cross-origin taint. Annotation happens in the renderer; saving returns
the composed PNG to Rust, which decodes it, checks limits and writes a new file.
Text files are read by Rust and shown in a read-only `<pre>`. Videos are loaded
through the asset protocol and played by the webview.
The editor does not write back to the source. `Copy` and `Save As` remain
separate operations.
### OCR
Image OCR runs in the renderer through Tesseract.js/WASM. The worker, core and
English/Simplified Chinese models are local files under `public/tesseract/`.
PDF OCR is a Rust-to-renderer loop: Rust renders each PDF page into a cache
folder, the renderer recognizes page images, then Rust writes the combined text
result and the cache folder is cleaned up.
No OCR path uploads a file or downloads a model at runtime.
### LAN sharing
One long-lived UDP discovery thread sends multicast, directed broadcast,
limited broadcast and a bounded unicast sweep. Peers are kept in a table capped
at 256 entries and expire after 15 seconds without a beacon. The table emits
`share://peers` only when its visible signature changes.
Transfers use a direct TCP connection to the port advertised in the beacon:
```text
"SHSF" | 4-byte big-endian header length | JSON header | 0/1 decision | body | ack
```
The receiver writes to a temporary `.shift-part` file and renames only after the
exact declared byte count has arrived. The sender copies exactly the header's
declared size, so a source file that grows cannot bleed bytes into the ack.
Inbound offers prompt once; later files in the same accepted batch use a
two-minute trust window.
The protocol has no authentication or encryption. Consent prevents automatic
writing, not sender impersonation. See [`SECURITY.md`](SECURITY.md).
### Updates
1. The manifest URL is derived at build time from the git remote, or overridden
with `SHIFT_UPDATE_URL`.
2. The manifest is fetched, capped at 256 KiB, parsed as `schema: 1`, and each
named artifact must be a safe basename with a nonzero size and SHA256.
3. If a public key is baked in, the detached `shift-update.sig` must verify over
the manifest's exact bytes.
4. The artifact is downloaded to the temp update directory, then its exact size
and SHA256 are checked.
5. Before installing, both checks run again; a failure deletes the artifact.
6. macOS and Windows hand the installer to a detached helper only after Shift
exits. Paths are process arguments, never interpolated script text.
## Events
Events are grouped by owner and are not a replacement for durable state.
| Event | Producer | Purpose |
| --- | --- | --- |
| `app://error` | Rust | User-visible native failure |
| `app://file-action-progress` | `files.rs` | Job-specific progress |
| `app://file-action-finished` | `files.rs` | Success or error for one job |
| `app://file-result` | history/capture/share | New result is available |
| `capture://ready` | capture | Overlay session data |
| `editor://open` | editor | New editor session |
| `pin://show` | editor | Pinned image payload |
| `history://changed` | history | Shared recent list changed |
| `radial://*` | drag bridge | Drag context, mode, drop and dismissal |
| `recording://started` | recording | Recording session data |
| `share://peers` | share | Visible peer list changed |
| `share://transfer` | share | Sending/received/error transfer state |
| `update://progress` | update | Download state |
| `update://status` | update | Verified update or error state |
## Platform adapters
| Concern | macOS | Windows | Linux |
| --- | --- | --- | --- |
| Drag detection | AppKit drag bridge sidecar | Win32 drag-state poll plus native drop | No global drag bridge; main-window picker only |
| Capture | `screencapture` | GDI `BitBlt` / `GetDIBits` | `grim`, fallback `gnome-screenshot` |
| Recording | `screencapture -v` | FFmpeg/X11 | `wf-recorder` on Wayland, FFmpeg on X11 |
| Document/PDF rendering | AppKit/PDFKit Swift sidecars | Poppler/Pandoc | Poppler/Pandoc |
| LAN discovery interface list | `getifaddrs` | `GetAdaptersAddresses` | `getifaddrs` |
All external processes go through `process::command`, which hides console
windows on Windows. A source-check test rejects bare `Command::new` in shipped
code.
## Invariants
- A conversion or tool never overwrites its source or an existing output.
- A visible wedge exists only because the format catalogue lists it and the
backend has a handler.
- Failures the interface maps have stable backend codes; raw third-party
diagnostics may pass through unchanged.
- A transfer or update is not considered complete until all declared bytes are
present and any required hash matches.
- A helper process receives untrusted paths as arguments, never as executable
script text.
- Resource limits are enforced before unbounded allocation where a path can
receive large local input.
## Related documents
- [`SPECIFICATION.md`](SPECIFICATION.md): observable behaviour and acceptance.
- [`SECURITY.md`](SECURITY.md): threat model and residual risk.
- [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md): regression constraints.
- [`RELEASE.md`](RELEASE.md): update channel and handoff.

View File

@ -0,0 +1,136 @@
# Windows build
## Requirements
- Windows 10/11 x64
- Visual Studio Build Tools with the Desktop development with C++ workload
- WebView2 Runtime (included with current Windows releases)
- Node.js 20+ and pnpm 8+
- Rust stable through rustup
- FFmpeg on `PATH` for screen recording and media conversion
- Pandoc and a Pandoc PDF engine (Typst is recommended) for document conversion
- Poppler (`pdftoppm`) on `PATH` for PDF-to-image and PDF-to-Word rendering
- ImageMagick (`magick`) if HEIC/AVIF export is required
These tools are optional at install time. Settings -> **Runtime components**
detects them on the current machine and shows their version and resolved path.
Missing Pandoc, Typst, FFmpeg, Poppler and ImageMagick components have an
**Install** button that runs WinGet without blocking the UI, then checks again
automatically. This is the same flow as the Homebrew-backed runtime installer
on macOS.
## Build
```powershell
pnpm install
pnpm check
pnpm build
cd src-tauri
cargo check
cd ..
pnpm tauri build
```
The installer is written below `src-tauri\target\release\bundle`.
## Release packages from macOS
`scripts/build-windows-release.sh` cross-compiles the EXE and produces the
Windows x64 installer without a Windows host:
```bash
brew install makensis
scripts/build-windows-release.sh
scripts/build-windows-release.sh --skip-build
```
It writes `artifacts/Shift-Setup-<version>-win-x64.exe` (NSIS, per-user, no
administrator rights), then refreshes `artifacts/SHA256SUMS.txt`. Before packaging
the EXE the script checks its PE machine field (`0x8664`) and the installer refuses
a non-x64 machine. `scripts/windows-installer.nsi` installs into
`%LOCALAPPDATA%\Programs\Shift`, and its uninstaller only removes what the installer
wrote. Windows ARM64 uses this x64 package through the update manifest's `windows`
fallback; no ARM64 or portable package is produced.
## Runtime behavior
- Hold `Shift` while starting a file drag, then move past the Windows drag threshold. Shift places a transparent radial window under the pointer and receives the native OLE drop.
- Hold `Alt + Shift` for the tool ring.
- Global shortcuts use `Alt + Shift + 2`, `Alt + Shift + 3`, and `Alt + Shift + 4`.
- The first screen capture uses the same local-only processing paths as macOS; no cloud service is involved.
- Revealing a result uses `SHOpenFolderAndSelectItems`, so an Explorer window
already showing that folder is reused. `explorer /select,…` opens a fresh
window for every conversion and is not used.
## Cross-compile check from macOS
The Windows-specific Rust code can be type-checked from macOS:
```bash
rustup target add x86_64-pc-windows-msvc
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:/opt/homebrew/opt/llvm/bin:$PATH" \
RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin \
cargo check --target x86_64-pc-windows-msvc
```
Prepending the rustup toolchain is required: a Homebrew `cargo` earlier on
`PATH` ignores `RUSTUP_TOOLCHAIN` and cannot find the Windows standard library.
This proves `cfg(windows)` code compiles. Interactive drag/drop and FFmpeg
recording still need a real Windows host for runtime QA.
## Cross-build a Windows EXE from macOS
```bash
cargo install cargo-xwin --locked
cd src-tauri
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin \
cargo xwin build --target x86_64-pc-windows-msvc --release --features tauri/custom-protocol
```
`--features tauri/custom-protocol` is not optional. Tauri derives `cfg(dev)` from the
absence of that feature, and a dev binary points every window at `build.devUrl`
(`http://localhost:1420`) instead of the bundled assets, so it opens a blank window on
any machine that is not running the Vite dev server. The release script verifies that
the current `dist/assets/*` files and UI strings are embedded before it creates the
installer.
The executable is written to `src-tauri/target/x86_64-pc-windows-msvc/release/shift.exe`.
It needs the Microsoft WebView2 Runtime on the target machine. FFmpeg, Poppler and Pandoc remain optional external tools for recording, PDF rendering, PDF-to-Word and document conversion.
## Runtime components
The Windows build uses these WinGet package IDs:
| Component | Package |
| --- | --- |
| Pandoc | `JohnMacFarlane.Pandoc` |
| FFmpeg | `Gyan.FFmpeg` |
| Poppler `pdftoppm` | `oschwartz10612.Poppler` |
| ImageMagick `magick` | `ImageMagick.ImageMagick` |
| Typst PDF engine | `Typst.Typst` |
WinGet runs with:
```text
install --id <package> --exact --silent --accept-package-agreements --accept-source-agreements
```
Some packages may show a Windows UAC prompt. If WinGet is missing, the
component panel links to Microsoft's official setup guide instead of downloading
an executable from a third-party source.
Shift checks the normal `PATH`, WinGet Links and Packages directories, the
standard Pandoc/FFmpeg/ImageMagick install locations, Chocolatey and Scoop
locations. This lets tools installed while Shift is running become available
after a refresh without restarting the app.
Build the frontend for the right engine first, otherwise Vite emits Safari 13 output:
```bash
TAURI_ENV_PLATFORM=windows pnpm build
```
Interactive drag/drop, installer shortcuts and recording still need a manual pass on
a real Windows machine. The release script itself can run unattended; it does not
replace that runtime QA.

View File

@ -0,0 +1,882 @@
# Shift 工程回归台账
本文件记录 0.1.2 到 0.1.13 之间已经踩过、并且不应再次引入的工程问题,重点覆盖:
- Drop / 局域网设备发现
- DOCX、Markdown 与图片转换
- 设置面板与「运行组件」的显示口径,以及 Windows 上的一键安装组件
- macOS DMG 打包及在其它机器上的安装
它记录的是实现约束、故障原因和回归方法,不是用户手册。修改相关代码或打包配置前,
先读对应章节;发布后如果得到新的有效结论,也把结论补回这里,并附上提交号。
## 版本线索
| 版本 | 本台账相关的已确认事实 |
| --- | --- |
| 0.1.2 | 当时的 Drop 在两台机器上实测可用;软件内安装升级和重启链路也已打通。 |
| 0.1.3 | 最近文件列表迁到应用数据目录,升级后不再随安装包替换而消失。 |
| 0.1.4 | 修复带图 DOCX→PDF、带相对图片 Markdown→DOCX/RTF 的丢图问题。 |
| 0.1.5 | macOS 改为 ad-hoc 签名并只发布通用 DMG,同时增加本地网络用途声明;但升级后出现 Drop 设备列表为空/只短暂闪现的回归。 |
| 0.1.6 | 增加按网卡定向广播,改善过滤组播的网络,但用户实测仍只能短暂看到设备。 |
| 0.1.7 | 增加单播扫描、普通信标回应、15 秒过期和 Windows 错误处理;用户实测 Mac 与 Windows 终端的 Drop 发现恢复正常。 |
| 0.1.8 | 最近文件改为收藏并移除拖回主操作按钮的交互;Windows 增加单实例保护;macOS DOCX→PDF 改用 Quick Look 源,保留页眉、页脚与装订版式。 |
| 0.1.9 | 重新支持把「最近使用」拖回三个主操作按钮,并且**按钮是唯一落点**——松开在面板其他位置不执行任何操作(见「『最近使用』拖回主面板的三个按钮」);设置面板字号统一到 `--text-*` 阶梯;取消「截图后」行为选项,固定为结果卡片;修复 macOS「运行组件」把 AppKit 文档渲染器报成 Pandoc 缺失且没有安装入口的回归。 |
| 0.1.10 | 拖放反馈收束到按钮:面板自身不再做拖拽动画,松开在非按钮处彻底静默(去掉 0.1.9 的提示浮层);「文字识别」对非图片直接拒绝,不再退回格式环;托盘「识别图片文字…」改为「文字识别」。 |
| 0.1.11 | Windows 实测「最近使用」拖到三个按钮全部完不成:页内文件拖拽在 WebView2 上 DOM 与原生两条投递路径都可能不上报,改由 `dragEnd` 兜底;开始拖动时先让闲置圆环让开,它无边框且始终置顶,正压在按钮上(两节都在「『最近使用』拖回主面板的三个按钮」里)。三个按钮的可用性判定收进 `src/lib/dropCapabilities.ts`,两种语言、两条投递路径共用一条"能处理就处理,不能处理就禁止"的规则。同一节里另有两处:内部拖拽被原生 `enter` 报成"没有文件"、从而三个按钮全部点亮(`dragPathsKnown()` 改为合并),以及禁止态定为**按钮禁用+光标禁止符号**——光标原本由 wry 固定回报 Copy、页面改不动,现在由 `src-tauri/src/drop_cursor.rs` 在运行时接管那两条回报方法,把页面的判定翻译成原生拖放的拒绝(同一节也记了这条路上"被拒绝的手势没有收尾事件"这个坑)。局域网接收的文件从此也受「完成后在访达中显示」控制,一批只在最后一个落地时显示一次;「运行组件」缺失多项时可以一次装完。 |
| 0.1.13 | Windows 实测「运行组件」一键安装失败:`winget` 把“已经装过”报成非零退出码,界面就照着说安装失败(见「Windows 一键安装运行组件」)。同一节还记了 `--source` 未钉住导致的静默挂死、机器级组件必须提权、以及装完之后进程内 PATH 仍是旧值这三处。另有三处与系统资源相关的约束:托盘改用自绘的黑白模板图(`scripts/build-icons.py` 重建,应用图标同一份几何,`icon_as_template` 只在 macOS 生效);钉图窗口的放大尺寸与位置必须按 work area 与 DPI 换算后夹取,见「钉图窗口的放大与还原」;闲置时的取样节奏——伴生进程 `native/macos/drag-bridge.swift` 无按压时 10Hz、Windows 手势监视 `monitor_pause` 在圆环关闭时 250ms、发现线程静默时 1.6s——都要在“关掉了就别一直占 CPU”和“还听得见、还能过期”之间取平衡。另有两条:主面板顶部的升级提示与托盘那一行共用同一份状态,而这份状态必须落到磁盘上,否则探测一天只跑一次,用户在探测当天之后就再也看不到提示——包括升级重启后的那一次启动;落盘的提示在恢复时要重新判定它是否还算数,见「升级提示跨启动存活」。Windows 应用内更新随后实测失败:`cmd.exe /C` 从带空格的 `%TEMP%\Shift Updates` 路径上剥掉了首尾引号,辅助脚本从未启动;静默安装还会被没人能点的 WebView2 提示框永久卡住。现在脚本路径经环境变量传入并保留外层引号,静默模式不弹 WebView2 提示,安装器在 `taskkill` 后也会等进程真正释放 EXE。 |
历史提交可以这样定位:
```bash
git show --stat 35cca59 # 0.1.6:定向广播
git show --stat 708bb5b # 0.1.7:Drop 完整修复
git show --stat 19602b7 # 带图 DOCX→PDF
git show --stat 9950607 # Markdown 相对图片
git show --stat 42d6424 # macOS 改回 ad-hoc 签名
git show --stat 58949be # 撤回 pkg,只保留 DMG
```
## Drop / 局域网设备发现
### 0.1.7 的发现链路
实现位于 `src-tauri/src/share.rs`。当前链路不是单独依赖组播,而是四层回退:
1. 每个运行中的 Shift 启动一个常驻 UDP 发现线程,绑定共享端口
`47888`。
2. 常规信标每 2 秒发往组播组 `239.255.77.88:47888`,同时发往每个活动
IPv4 网卡的定向广播地址和受限广播地址。
3. 打开 Drop 设备面板时,`share_refresh` 只设置
`ShareState.refresh_requested` 原子标记,让常驻线程立刻广播并扫描;它不会再创建
第二个同端口 socket。
4. 单播扫描覆盖本机所在网段,每 30 秒一次;大网段被限制在包含本机的 `/24`
内,最多约 253 个地址,避免全网段泛洪。
5. 收到普通信标后,新版本总是回一个带 `reply: true` 的单播信标。回复信标不会再次
触发回复,避免两台新版本无限互答。
6. 已知设备每 2 秒还会收到一次定向单播,因此即使对端自己的组播和广播都被过滤,
只要先通过扫描建立联系,设备就能持续可见。
7. 15 秒没有再次收到设备信标才从列表移除。旧版本自己的过期时间是 9 秒,2 秒刷新
周期必须在旧版本清除本机后仍来得及再次回应。
8. 文件传输使用信标中携带的动态 TCP 端口和 `SHSF` 握手;UDP 源端口不是传输端口。
### 不能随意改掉的约束
| 约束 | 原因 |
| --- | --- |
| `share_refresh` 必须复用常驻发现线程 | Windows 不能可靠地二次绑定 `47888`;Unix 上第二个 socket 可能抢走回复。0.1.7 之前的“只闪一下”就是这条链路失效的表现。 |
| 保留 `reply` 标记和 `#[serde(default)]` | 新版本必须能被旧版本解析,也必须能解析旧版本的省略字段;没有该标记,双方会无限互答。 |
| 普通信标每次都回复 | 只在“首次发现”时回复会让过滤组播的网络里的设备闪一次后消失。 |
| `PEER_TIMEOUT` 保持大于旧版 9 秒过期时间加刷新周期 | 0.1.7 使用 15 秒。缩短会重新制造旧版与新版本交替上线时列表闪烁的问题。 |
| 同时保留组播、定向广播、受限广播和单播扫描 | 不同路由器、访客 Wi-Fi 和企业网络会分别过滤其中一种;只改回其中一条路径会导致特定网络回归。 |
| 发现线程忽略 Windows 的 `ConnectionReset` / `ConnectionAborted` | 扫描关闭端口会产生排队的 ICMP 失败,这不是发现线程应退出的错误。 |
| 每 30 秒重建 socket,但不要退出线程 | 电脑休眠、切换 Wi-Fi 或网络接口变化后,需要重新加入组播;线程退出则再也不会恢复发现。 |
| `src-tauri/Info.plist` 保留 `NSLocalNetworkUsageDescription` | macOS 没有用途说明时无法正确发起本地网络访问授权。 |
| 发现端口和协议字段保持兼容 | 频道中同时可能有旧版本;新增字段必须可缺省,不能直接改掉现有 beacon 语义。 |
### 权限与网络排查
设备列表为空时,先按以下顺序排查,不要直接改发现算法:
1. **macOS 本地网络权限**:系统设置 → 隐私与安全性 → 本地网络,确认当前安装的
`Shift.app` 已打开。ad-hoc 构建每次签名哈希可能变化,因此升级后可能出现新的
Shift 条目,旧条目仍保留。
2. **Windows 防火墙**:首次运行时应允许 Shift 访问“专用网络”。公共网络配置下,
Windows 防火墙通常会阻止入站信标和文件接收。
3. **客户端隔离**:访客 Wi-Fi 或企业网络若开启 AP/client isolation,两台设备即使
在同一子网也无法直接收发 UDP/TCP。这是网络策略限制,不是端口扫描能绕过的。
4. **VPN 和多网卡**:确认两台机器使用的是同一个实际可互通网段;VPN 可能把默认路由
和接口顺序带偏。当前扫描只覆盖活动 IPv4 网卡。
5. **Windows 单实例限制**:Windows 上每台机器只有一个 Shift 进程能绑定发现端口;
验证多机发现时不要在同一台 Windows 上同时运行多个安装副本。
6. **ad-hoc 签名变化**:macOS 的本地网络授权绑定签名身份。无法解释的“升级前可见、
升级后不可见”应先检查权限条目,再检查代码。
正常发现时日志中会出现:
```text
Shift share: found <machine> on <ip>
```
### 回归测试
自动测试在 `src-tauri/src/share.rs` 和 `src-tauri/Cargo.toml`:
```bash
cd src-tauri
cargo test --lib share::
```
重点用例:
- `subnet_scan_skips_this_host_and_broadcast`
- `subnet_scan_bounds_a_large_network_to_this_twenty_four`
- `reply_beacons_are_distinguished_from_regular_ones`
- `peer_timeout_covers_a_legacy_peers_reply_cycle`
- `two_copies_on_one_machine_discover_each_other`(默认 ignored,会绑定共享发现端口)
需要排查真实 socket 和当前网络时运行:
```bash
cd src-tauri
cargo test share:: -- --ignored --nocapture
```
每次修改发现、签名或打包配置后,仍要完成真机矩阵:
| 场景 | 验收标准 |
| --- | --- |
| macOS ↔ macOS | 打开 Drop 后数秒内出现对端,等待 15 秒以上仍不消失。 |
| macOS ↔ Windows x64 | Windows 允许专用网络防火墙后,双方都能发现对方。 |
| 升级后 | 旧版本升级到新版本,不需要重启路由器,设备列表能恢复。 |
| 切换 Wi-Fi / 休眠唤醒 | 30 秒内重新发现;不得要求退出应用。 |
| 权限拒绝再允许 | macOS 本地网络或 Windows 防火墙从拒绝改为允许后,重新打开面板可发现。 |
0.1.7 的用户验收环境是 Mac 与 Windows 各一台,升级后 Drop 设备发现正常。该结论
覆盖真实跨系统发现;CI workflow 能验证协议单元测试,但没有双机网络夹具,因此发布前
仍需重复上面的手工矩阵。
## DOCX、Markdown 与图片转换
### 当前转换路径
| 输入 → 输出 | 当前实现 | 关键点 |
| --- | --- | --- |
| 纯图片 DOCX → PDF | `office::document_page_images` 按文档顺序抽取页面图片,再由 `pdf::images_to_pdf_with_progress` 生成 PDF | 保留页数和原始图片内容;这是扫描件路径,不经过 AppKit 文本排版。 |
| 普通 DOCX → PDF | 先用 `/usr/bin/qlmanage -p` 生成系统的 Quick Look `Preview.html`,再由 `native/macos/doc-render.swift` 用 WebKit 渲染并按 A4 切片 | AppKit 的 OOXML 读取器只保留正文;把 Quick Look HTML 再转成 attributed string 还会重排表格并制造空白页。`qlmanage` 有 30 秒超时,且必须确认 `Preview.html` 存在。 |
| Quick Look 不可用且含图 DOCX → PDF | 用 Pandoc `docx → html5`,通过 `--extract-media` 抽取图片到临时目录,再交给 `doc-render` | 保留图片的降级路径;Quick Look 失败或超时后才进入。 |
| Markdown → PDF | 先由 Pandoc(可用时)或内置 `markdown::to_html` 转成 HTML,再交给 WebKit 渲染器;HTML 的 base URL 指向 Markdown 源目录 | 相对图片路径依赖源目录,不能用临时 HTML 所在目录。 |
| Markdown → DOCX / RTF | Pandoc,并传 `--resource-path <源目录>` | Pandoc 的工作目录不是文档目录;缺少该参数会把相对图片替换成 alt 文本。 |
| Markdown → HTML | Pandoc,并传 `--resource-path <源目录>` 和 `--self-contained` | 输出必须是可单独移动的单文件,不能引用从未生成的 `media/` 目录。 |
| 含图 DOCX → HTML | Pandoc 加 `--self-contained` | 图片以内嵌 data URI 写入 HTML。 |
| 任意含宽图的文档 → PDF | HTML 在 WebKit 测量前把超宽 `<img>` 等比缩到页面宽度;非 HTML 文档仍由 `fitAttachments` 调整 attachment bounds | 不重采样像素,只修正排版请求的尺寸,避免截图被裁成碎片。 |
### 不能随意改掉的约束
1. **普通 DOCX 不能直接交给 AppKit OOXML 读取器。** 它只保留正文,页眉页脚会消失;
含图文档还会返回只有文字、没有附件的 attributed string。必须先走 Quick Look,
失败后才允许回退。
2. **HTML 必须交给 WebKit,不能再转成 NSAttributedString。** 后者会重新排版 Quick
Look 的定位内容,把原本同页的页脚推到新页,并把 7 页内容拉成 9 页。
3. **纯图片 DOCX 的页面抽取要排在通用渲染之前。** 它决定扫描件的真实页数和页面顺序。
4. **DOCX→HTML 后必须把 `--extract-media` 的临时目录作为 HTML base directory。**
Pandoc 会把图片写成相对路径;base 指向源 DOCX 目录会找不到已抽取媒体。
5. **Markdown→PDF 的 HTML base URL 始终是源 Markdown 目录。** 即使 HTML 写在临时目录,
也不能改用临时目录。
6. **Pandoc 转 DOCX/RTF/HTML 必须保留 `--resource-path`。** 这是相对图片丢失问题的
根因修复,不应为了简化命令删掉。
7. **HTML 输出必须保留 `--self-contained`。** 否则用户拿到的是一个引用不存在媒体目录
的 HTML 文件。
8. **宽图适配在 `doc-render.swift` 中完成。** HTML 必须在测量前缩放宽图;非 HTML
文档的 AppKit `<img>` 单元格不会服从 CSS width,仍需调整 attachment bounds。
9. **无 Pandoc 时保留 macOS 的降级路径。** 带图 DOCX 会退回旧的文本渲染,而不是让
整个转换直接失败;修改时要明确产品选择,不能无意打破降级。
10. **Swift 渲染器改动后重新运行 `pnpm mac:drag-bridge`。** 只改源码不重编伴生进程,
打出的 DMG 不会包含修复。
11. **Quick Look 临时目录必须在所有成功和失败路径清理。** 输出先写到临时目录,确认
PDF 有效后再改名;不能把半成品留在用户的输出目录。
### 回归测试
自动测试集中在 `src-tauri/src/files.rs`:
- `renders_image_only_docx_pages_to_pdf`
- `keeps_pictures_when_rendering_a_text_docx_to_pdf`
- `fits_a_wide_picture_onto_the_page`
- `keeps_docx_headers_and_footers_when_converting_to_pdf`
- `image_bearing_docx_to_html_embeds_images`
- `keeps_markdown_images_when_converting_to_word`
## 升级后的单实例
Windows 安装器重启应用时可能留下旧进程,再启动新进程就会有两个托盘实例和两套窗口。
`tauri-plugin-single-instance` 必须在 `tauri::Builder` 中**最先注册**:第二个进程在
其余插件和窗口初始化前就把参数交给第一实例并退出,第一实例收到回调后显示主窗口。
macOS 的 `hotkeys::acquire_instance` 文件锁仍保留为热键所有权的额外保护,不能因为加入
单实例插件而删除;但它不是 Windows 的解决方案,非 Unix 分支本身不会持有跨进程锁。
其中 `keeps_markdown_images_when_converting_to_word` 覆盖 DOCX 和 RTF;
`image_bearing_docx_to_html_embeds_images` 检查 HTML 中的图片是 data URI 而不是
`media/` 引用。很多用例在缺少 Pandoc 时跳过,因此本机安装 Pandoc 后才能得到完整结果。
历史验收样例:
- `平台技术方案(带图测试专用).docx`
- `智飞空地一体化低空应用平台技术方案.md`
这两个样例是手工验收材料,当前没有提交到仓库,不能声称 CI 会自动重跑。每次改动转换
路径时,应重新用它们检查标题、表格、正文顺序、相对路径图片和宽图是否同时保留。
### 当前边界
- 自动化覆盖的是本地文件和相对路径图片。没有单独的 HTTP/HTTPS 图片下载、缓存、重试
与离线回退实现,因此不要声称任意远程图片 URL 都已有自动回归保障。
- 含图 DOCX 依赖 Pandoc;没有 Pandoc 时会退回旧文本路径,这是兼容性降级,不等于
图片仍被保留。
- AppKit 渲染器只在 macOS 构建中可用;Windows/Linux 的文档→PDF 仍走各自的 Pandoc
与 PDF 引擎路径。
## macOS DMG 打包与跨机器安装
### 当前发布方案
Shift 的 macOS 产物只有:
```text
Shift-<版本>-macOS-universal.dmg
```
它是 Apple silicon 与 Intel 通用的应用包,同时用于首次安装和软件内升级。更新清单的
`macos` 键必须指向这个 DMG,因为软件内升级脚本会用 `hdiutil` 挂载它再取出应用。
不再发布 `.pkg`;旧的 `scripts/macos-pkg.sh` 已从仓库删除,任何 `.pkg` 都不能进入
正式发布目录或更新清单。
当前签名配置是:
```json
"macOS": {
"signingIdentity": "-",
"hardenedRuntime": false
}
```
`"-"` 表示 ad-hoc 签名。项目没有 Apple Developer ID,也不做 notarization,因此新机器
第一次打开仍需在 Gatekeeper 中授权一次。
### 为什么不能用本地自签名证书
历史上曾使用构建机钥匙串中的 `Shift Local Signing` 证书。它在构建机上看起来完全
正常:`codesign` 验证通过,`spctl` 也可能接受,因为证书只存在于那台机器。换到其它
Mac 后,证书无法链到受信任根,下载的应用会被系统报告为“已损坏”或恶意软件,而且只
提供“移到废纸篓”,没有允许运行的入口。
因此:
- **不要重新启用 `Shift Local Signing` 或任何只存在于构建机的证书。**
- **不要清空 `signingIdentity` 让它自动选择钥匙串身份。** Tauri 可能挑到本机证书,
重新产生同样的跨机器故障。
- 保持 ad-hoc,直到项目真正具备 `Developer ID Application` 证书和 notarization。
### 首次安装与软件内升级
| 场景 | 预期行为 |
| --- | --- |
| 其它 Mac 首次下载 DMG | 双击挂载,拖 `Shift.app` 到 `/Applications`。首次启动会提示“身份不明的开发者”;右键 → 打开,或在系统设置 → 隐私与安全性中允许一次。 |
| 软件内升级 | 下载 DMG、校验字节数与 SHA256,退出应用后由 helper 挂载、复制、移除 quarantine、替换并重启;不经过浏览器,因此不应出现 Gatekeeper 提示。 |
| 构建机本地运行 | 能打开不代表发布包合格;必须从 DMG 转移到另一台机器验证,构建机结论不能替代跨机器验收。 |
### 每次 macOS 发布前的硬性检查
1. 运行 `pnpm mac:drag-bridge`,确保拖拽、PDF 与文档渲染三个 Swift 伴生进程都已重新
编译为 universal。
2. 构建 `pnpm tauri build --target universal-apple-darwin --bundles app,dmg`。
3. 对应用执行 `codesign --verify --deep --strict`,并确认
`codesign -dv --verbose=2` 显示 `Signature=adhoc`,而不是本地证书名称。
4. 对 DMG 执行 `hdiutil verify`;对发布目录执行 `shasum -a 256 -c SHA256SUMS.txt`。
5. 确认 `artifacts/` 和 `shift-update.json` 都没有 `.pkg`,`macos` 键指向 DMG。
6. **把 DMG 转移到另一台 Mac 验证。** 最好使用没有安装过 Shift 的机器,并通过浏览器从
发布源下载最终文件,让 quarantine 标记符合真实用户路径。若用 USB 或 AirDrop 转移,
应确认隔离属性仍存在,否则 Gatekeeper 这一项没有被验证。完成拖入 `/Applications`、
首次右键打开、启动应用,并检查版本号。
7. 在同一台机器打开 Drop,确认本地网络授权正常、能看到另一台 Shift 终端。签名和打包
改动最容易同时影响应用启动与局域网权限。
8. 如果验证的是升级包,再从旧版本执行一次软件内升级并确认无需 Gatekeeper 提示。
第 6 步是发布闸门。只在一台机器上生成、签名和打开 DMG 不足以证明“其它机器可安装”。
0.1.7 的 DMG 已在其它机器验证可用;后续每次更换签名方式或打包容器时都要重做。
### 已知边界
- ad-hoc 构建每次的签名哈希可能变化,macOS 的“屏幕录制”和“本地网络”授权也可能重置。
这是当前没有 Developer ID 的代价,不是 Drop 代码回归。
- Developer ID + notarization 才能消除首次安装提示,并让权限在升级间稳定。当前项目没有
该证书,不能把“已公证”写入发布说明。
- 发布前不能只看构建机上的 `spctl` 结果;跨机器安装行为和系统提示类型才是有效证据。
## 截图、录制与圆环的键盘焦点
### 症状与真实原因
区域截图、区域录制时按 `ESC` 无法取消,拖动文件后出现的圆环按 `ESC` 也无反应。前端确实
监听了 `keydown`,但事件根本没有到达页面。
在运行中的 Shift 上用 `lldb` 取证可以看到:
```text
keyWindow = <TaoWindow "Shift Capture"> isKeyWindow = YES
firstResponder = <TaoView> ← 页面在 contentView 的 subview 里,不在这里
contentView = <TaoView> subviews = [<WryWebView>]
```
窗口是 key window,但 AppKit 的键盘事件投递给的是窗口的 first responder,而 first
responder 停在 tao 自己的 `TaoView` 上,所以页面收不到任何按键。链路上有两个成因:
- `WebviewWindow::set_focus()` 只做 `makeKeyAndOrderFront` 加激活应用
(tao `platform_impl/macos/window.rs` 的 `set_focus`),不会动 first responder。
- wry 在创建 webview 时调用过一次 `makeFirstResponder(webview)`,但之后每次
`set_simple_fullscreen` 都会经 `toggle_style_mask` 再调
`makeFirstResponder(ns_view)`(tao `util/mod.rs`)把它抢回去;窗口重新显示同样会丢。
因此**只要窗口被显示过一次,就必须再显式把键盘交给页面**。等价验证:在真实进程里执行
`makeFirstResponder(WryWebView)` 之后,同一个 `ESC` 立刻被页面收到。
### 不能随意改掉的约束
| 约束 | 原因 |
| --- | --- |
| 显示 overlay / 圆环后必须调用 `crate::focus_page` | 只有 `Webview::set_focus`(`makeFirstResponder`)能让页面收到 `ESC`/`Enter`;`WebviewWindow::set_focus` 不够。 |
| 采集前记住哪些 Shift 窗口是可见的,结束时按名单恢复 | 之前无条件 `show` 主窗口:面板开着会被截图吃掉,面板本来关着又会被凭空打开。 |
| 录制期间不能恢复面板,`recording::stop` 才恢复 | 恢复出来的窗口会出现在被录制的区域里。 |
| `restore_windows` 用 recorder HUD 判断是否在录制,不能去锁 `state.recording` | `recording::stop` 全程持有该 Mutex,从这条路再锁一次会自死锁。 |
| 已有 overlay 或正在录制时,新一轮采集不得覆盖待恢复名单 | 否则后一次(面板不可见)会把“面板开着”的记录擦掉。 |
### 回归测试
`src-tauri/src/lib.rs` 中的源码断言守住调用点:
```bash
cd src-tauri
cargo test --lib capture
```
键盘投递本身只能实测,最小矩阵(每步都要看窗口是否真的消失/回来):
1. 面板开着 → `Alt+Shift+2` → 直接按 `ESC` → overlay 消失且面板回来。
2. 面板开着 → `Alt+Shift+3` → 直接按 `ESC` → 同上。
3. 面板关着 → `Alt+Shift+2` → `ESC` → 不要凭空出现面板。
4. 面板开着 → 选区录制 → 录制中面板保持隐藏 → 停止后面板回来,`.mov` 有效。
5. 录制中再截一张图 → `ESC` 只关 overlay,录制与 HUD 不受影响。
6. 圆环(拖文件到面板,或「文件转换」选文件后)→ `ESC` 收起圆环。
7. `Enter` 仍能确认选区并保存截图。
## 「运行组件」的显示口径
### 0.1.9 的 macOS 回归
macOS 的设置 → 运行组件里,文档转 PDF 那一行显示 **“Pandoc PDF pipeline / 缺失”**,
而且**没有安装按钮**。两件事都是同一个错误造成的。
`document_pdf_component()` 原本在 `if let Some(renderer) = files::doc_render_bridge()`
里 `return` 掉内置的 AppKit 渲染器;`df35111`(准备 0.1.8)把 `return` 改成了裸表达式,
于是构造出的组件被丢弃、继续往下走到 Pandoc 分支。后果是:
- 名字变成 `Pandoc PDF pipeline`,可用条件变成 `pandoc.is_some() && pdf_engine.is_some()`;
macOS 这条链路根本不需要 LaTeX/Typst 引擎(pandoc 只负责把带图 DOCX 转成 HTML 交给
渲染器),所以只要机器上没装 xelatex/typst 之类就永远显示缺失。
- 面板对 `external` 且缺失的行只给安装按钮,而 `install_target("document-pdf")` 在
macOS 没有条目(只有 `pandoc`、`media`),于是既报缺失又无处可装。
**修法不是补一个安装入口,而是恢复「macOS 由内置渲染器作答」这件事。** 现在两个平台各自
拥有独立的 `document_pdf_component()`(`#[cfg(target_os = "macos")]` /
`#[cfg(not(target_os = "macos"))]`),与同文件里 `pdf_page_component`、
`image_backend_component` 的写法一致:在 macOS 上想再次落到 Pandoc 分支会变成编译错误,
而不再是一次静默的行为回归。
### 不能随意改掉的约束
| 约束 | 原因 |
| --- | --- |
| macOS 的 `document-pdf` 必须是 `source = "bundled"` 且以 `doc_render_bridge()` 为准 | 这条转换在 macOS 上就是 Quick Look / AppKit 渲染器;改成 external 会重新引入"缺失但装不了"。 |
| 带图 DOCX 仍需要 Pandoc,但那是 `pandoc` 那一行的职责 | `pandoc` 行有自己的安装目标(`brew install pandoc`);不要把依赖合并进 `document-pdf`。 |
| `external` + 缺失的行必须有安装目标 | 否则面板等于告诉用户坏了、却不给出口,就是本次回归的表现。 |
### 回归测试
`src-tauri/src/runtime.rs` 的 `tests` 模块:
```bash
cd src-tauri
cargo test --lib runtime
```
- `macos_document_pdf_is_the_bundled_renderer_not_a_pandoc_pipeline`:钉住 macOS 的
`source` 与 `name`。
- `a_missing_component_always_offers_a_way_forward`:任何标记为缺失的行都必须要么可安装、
要么本来就不是 external。
## 「运行组件」可以一次装多个缺失项
面板原先一次只能装一个组件:`runtimeInstalling` 是一个 `string | null`,`install` 命令
只接受一个 `component_id`,任何一个按钮在忙时就把整片按钮全部禁用。缺失 Pandoc 与 FFmpeg
时用户要点两次、等两轮重新检测。
现在前端把缺失且可安装的组件收成一个列表,标题栏在**缺失不止一项**时给出「一键安装
N 个组件」,行内的单个安装按钮保持原样,两种入口调用同一个 `install_runtime_components`。
| 约束 | 原因 |
| --- | --- |
| 后端逐个串行安装,不能并发 | `brew` 与 `winget` 同一时刻只允许一个安装,并发只会互相锁住并报错。 |
| 同一个 `package_id` 只装一次 | Windows 上 `pdf-render` 与 `pdf-to-word` 都指向 Poppler,按行安装会重复下载同一个包。 |
| 只有“包管理器本身坏了”才中止整批 | 没装 brew / winget、没有源、网络不通、winget 不回应:剩下的行只会把同一个错误重复 N 遍、各等一次超时。但**单个包**的失败(用户关掉 UAC、某一个安装程序自己拒绝)必须继续往下装,否则「一键安装 N 个组件」会因为一个组件被拒绝而放弃其余四个。判定收在 `ends_the_batch()`,有测试钉住。 |
| 无论成功失败都 `refreshRuntime()` | 中止的批次里先前的安装可能已经落盘,面板必须重新检测才能显示真实状态,不能相信这一个回复。 |
| 安装结果的名字由界面措辞 | `install_runtime_components` 返回 `()`:按既有约定,后端只报代号,`runtimeInstallComplete` / `runtimeInstallManyComplete` 两种数量由界面选择。 |
## Windows 一键安装运行组件
### 0.1.13 之前实测必然失败
用户在 Windows 机器上点「一键安装组件」报失败。原先的实现是一条
`winget install --id X --exact --silent --accept-package-agreements --accept-source-agreements`,
非零就报错,然后用 `resolve_tool()` 验证二进制在不在。四个独立原因都藏在这十行里:
1. **`winget` 把"已经装过"报成非零退出码。** `0x8A15002B`(PACKAGE_ALREADY_INSTALLED)与
`0x8A150016`(没有可升级版本)都是成功语义,但 `ExitStatus::success()` 一律当真失败。
机器上已经有 Pandoc 的用户,越"没问题"越必然看到"安装失败"。
2. **不钉 `--source`。** 同时挂了 msstore 源的机器上,未钉源的 `winget` 可能停在一条
`--silent` 永远不会回答的源协议上;表现就是"卡住不动",最后由 15 分钟超时收成失败。
3. **机器级组件必然要提权。** Poppler / FFmpeg / ImageMagick / Typst 默认装到
Program Files,需要管理员;Shift 自身是免管理员的 GUI 进程,`--silent` 拿不到 UAC 就
直接失败。原先没有任何提权路径。
4. **装完之后再验证也找不到。** 进程只持有启动时的环境块:`winget` 写进注册表的
`%LOCALAPPDATA%\Microsoft\WinGet\Links` 不会回流到运行中的 Shift,`which` 于是仍按旧
PATH 回答,`winget-install-missing-binary` 把一次真正成功的安装报成失败。
### 不能随意改掉的约束
| 约束 | 原因 |
| --- | --- |
| 退出码先判,代码表认不出来时才看 `winget` 的措辞 | 退出码是精确信号;措辞只用来分家两件码里分不开的事(用户关掉了 UAC、源没有接受协议)。反过来让措辞压过码,一句无用的日志就能把成功改成重试。 |
| 只按完整码匹配,不按低 16 位 | Win32 的 `0x8007_xxxx` 与 WinGet 的 `0x8A15_xxxx` 会撞低 16 位;只看尾巴会把普通的访问被拒读成"需要提权"。 |
| 每条命令都带 `--source winget` | 去掉它就会在挂了 msstore 的机器上静默挂死到超时——而那看起来就是"安装失败"。 |
| 阶梯:不指定 scope → `--scope user` → 提权 `--scope machine` | 第一档就是历来发出去的那条命令,默认装到用户目录的包行为完全不变;`--scope user` 是"不弹 UAC 也能装机器级包"的出口,且 WinGet 在选安装器阶段就会拒绝不支持的 scope,所以这一档只花一次握手而不是整包下载;UAC 是最后一招,因为一个本该是开关的操作弹出授权框,正是"看起来坏了"的来源。 |
| 提权走 `powershell Start-Process -Verb RunAs -Wait -PassThru` | 无控制台的 GUI 进程自己弹不出 UAC;提权后的 `winget` 写在自己的控制台里,但**宿主** shell 的输出仍在我们手上,而"用户取消"只在这里以文字出现(1223 只是旁证)。 |
| 成功与否最终由磁盘上有没有那个可执行文件决定 | 装完先 `refresh_process_path()` + `reset_tool_cache()` 再找。`RegGetValueW` 不加 `RRF_NOEXPAND`,注册表里的 `REG_EXPAND_SZ` 会像系统构造进程环境那样展开。找不到才说"没装上",并且说成"重启 Shift 后重新检测",而不是"安装失败"。 |
| 单个包失败不许放弃整批 | 见上一节;判定在 `ends_the_batch()`。 |
`src-tauri/src/process.rs` 里 `output_hidden_with_timeout()` 是这套逻辑唯一的输出通道:
它同时保留 `CREATE_NO_WINDOW`(GUI 进程不闪控制台)与持续排空管道(否则子进程写满管道会
一直堵到超时)。超时消息统一含 `TIMEOUT_MARKER`,调用方据此区分"没回答"与"回答不要"。
### 回归测试
```bash
cd src-tauri
cargo test --lib runtime
```
- `an_already_installed_package_is_not_a_failure`:钉住原因 1,也就是这次实测失败的主因。
- `exit_codes_are_separated_by_who_can_fix_them`:谁能修就分给谁,并钉住低 16 位撞车。
- `every_winget_attempt_pins_the_community_source`:三档命令都必须带 `--source winget`。
- `the_ladder_escalates_scope_only_when_it_must`:未提权的两档都不许要求 machine scope。
- `the_installer_own_words_break_a_tie` / `a_closed_prompt_reads_as_a_refusal`:措辞只在码
认不出来时生效,且"网络断了"不能被读成"用户说了不要"。
- `only_a_broken_package_manager_ends_the_batch`:整批中止的判定。
## 钉图窗口的放大与还原
钉图窗口原先只有「复制」和「关闭」,用户要的「放大」按钮并不存在——不是坏了,是没有。
现在一颗按钮管两个方向:放大到屏幕,或退回钉住时的大小。
| 约束 | 原因 |
| --- | --- |
| 尺寸按 work area,不按整块屏幕 | `monitor.size()` 含菜单栏与 Dock。按整屏算出来的钉图会有一部分永远压在菜单栏底下,而无边框窗口拖不回自己身上。 |
| 逻辑像素给 `set_size`,物理像素给 `set_position` | 两者单位不同。混用后在 2x 屏上放大就是两倍大、位置偏一半——这台机器上验得出来,在 1x 外接屏上看不出来,所以由 `PinArea::logical_size()` 显式换算并命名。 |
| 先 `set_size` 再 `set_position` | 混合 DPI 的桌面上,改尺寸可能把窗口挪到另一块屏,此时窗口自己的 scale factor 已经变了;顺序反过来位置就按旧的 scale 算。 |
| 放大幅度封顶 3 倍 | 预览最长边本来就是 1040 px(`PIN_PREVIEW_EDGE`)。再往上只是把锯齿摊开,用户看到的是糊成一片的马赛克,不是更大的字。 |
| 放大以窗口中心为锚点,并夹在 work area 内 | 以左上角为锚点读起来像"窗口被搬走了";不夹取的话,贴着屏幕右缘钉住的图一放大就整张跑到屏幕外。 |
| 每次重新钉都回到小图 | 窗口是复用而不是重建(`PIN_ENLARGED` 是唯一的记录)。否则上一次放到最大的用户,接下来每一张钉图都糊满全屏。 |
| 读不到显示器就答小图,不猜 | `pin_window_size(.., None, true)` 走的是小图那一支。按一块幻影屏幕算出来的尺寸,是把图放到用户够不着的地方。 |
按钮的文案(放大 / 恢复原大小)跟的是页面自己那份 `enlarged`,而真实尺寸只有 Rust 知道;
`zoom_pin` 把翻转后的状态返回给页面,两边才不会各说各话。
### 回归测试
```bash
cd src-tauri && cargo test --lib editor
```
`a_fresh_pin_never_exceeds_its_own_picture_or_520_px`、`enlarging_fills_the_screen_but_stays_inside_it`、
`a_small_picture_is_not_blown_up_to_the_ceiling`、`an_enlarged_pin_grows_from_its_centre`、
`a_pin_against_a_screen_edge_grows_inward_not_off_screen`。后两条钉的是"从中心放大"和
"贴边时向内长",因为它们在 1x 的单屏开发机上看起来永远是对的。
## 闲置时的取样节奏
Shift 绝大部分时间是停在菜单栏里没人碰的。这一节的每条节奏都是从实测里挑出来的,
目的是把"关掉了就别一直占 CPU"和"还听得见、还能过期"同时满足。
### 实测的 A/B
在装有 0.1.11 的机器上,两个版本各自空转 60 秒,按进程分别读 `ps -o time=`:
| 进程(60 秒空转) | 0.1.11 | 0.1.13 | 变化 |
| --- | --- | --- | --- |
| `drag-bridge` 伴生进程 | 140 ms | 40 ms | **−71%** |
| `shift` 主进程 | 100 ms | 60 ms | −40% |
| 合计 | 240 ms | 100 ms | **−58%** |
只有伴生进程那一行可以直接归因:它没有窗口,所以不受"主窗口有没有开着"影响,
而其余三处改动都发生在那两个数字里。主进程那一行不能当成"发现线程省了 40%"来读——
同一个构建重复测量的摆动就有 ±40ms,和差值同量级。发布前若要再引用一次,
请重新测,不要抄这张表。
| 位置 | 节奏 | 原因 |
| --- | --- | --- |
| `native/macos/drag-bridge.swift` | 无按压 10Hz,按住切 30Hz | 伴生进程是**另一个被跟踪的进程**,原先永远 30Hz,而且每跳都分配一个 CGEvent 去读一个没人要的鼠标位置。它是这一节里唯一能被干净归因的改动:伴生进程没有窗口,所以它的 CPU 与「主窗口是否开着」无关。`NSTimer` 不能改自己的间隔,所以是换掉计时器而不是调它。 |
| `src-tauri/src/drag_bridge.rs` `monitor_pause`(Windows) | 圆环开着 33ms,关了 250ms | 圆环开着时必须 33ms:这条循环要靠观察到"按下"才能从按下点量起拖拽阈值,放慢不是"晚一点发现",而是**根本记不住按下**,于是快速拖动的用户从此开不了环。只有关掉圆环时才敢放慢,那时要等的只有开关本身。 |
| `src-tauri/src/share.rs` 发现线程 | 信标 2s / 扫段 30s 不动;静默时收包等待 400ms→1.6s,无 peer 时账目检查 600ms→2.4s | **关掉 ShiftDrop 不等于变聋**:字段注释写的是"不主动播报",`recv_from` 从来不受 `enabled` 约束,所以一台关掉的机器仍然听得见、仍然能被别人选来发送;`expire()` 也必须继续跑,否则一小时前的 peer 会永远挂在列表里冒充在线。所以省的是唤醒次数,不是探测能力。播报与扫段的频率一点没动,peer 被发现的速度因此不变。 |
| `src/components/MainWindow.tsx` 30 秒时钟 | 页面可见才跑 | 主窗口一生大部分时间是隐藏的;隐藏的页面里每 30 秒重绘一次没人看的列表,正是 nex_squid `useSystemSnapshot` 用 `visibilitychange` 停掉的那类开销。空列表连 `setNowTick` 都省了——重新计时的是不存在的行。 |
| 最近列表缩略图 | `IntersectionObserver` 只保留在视线内的图片 | `loading="lazy"` 只**推迟**解码,从不**释放**。在 WKWebView 里用 250 张真实截图量过:静止时 13 张解码,滚到底单调涨到 136 张再也不降;观察者接管后同样的滚动稳定在约 20 张。root 必须是列表本身而不是视口——行的裁剪来自列表的 `overflow-y`。 |
托盘图标也在这一节,因为它省的是同一个东西:`src-tauri/icons/tray-template.png` 是
`scripts/build-icons.py` 画的纯 alpha 黑白标记(中性灰只在 Windows 上当底色用,
macOS 完全忽略颜色),`icon_as_template(cfg!(target_os = "macos"))` 只在 macOS 生效——
Windows 没有可以请求的着色。**别把它换回 `app.default_window_icon()`**:那是彩色转盘,
`tray-icon` 会把它按 18pt 高等比缩放,在菜单栏里就是一团色块,这正是"系统图标该是
黑白"这条反馈的来由。
## 升级提示跨启动存活
主面板顶部要显示升级信息,点一下跳到「设置 → 软件更新」。界面这一半很直接:
`useUpdateFlow` 在 MainWindow 里再挂一份,它只**读** Rust 记着的状态并订阅
`update://status`,不会自己发探测请求,所以两处视图不会各自查网络,也不会给出
对方已经做完的动作。
难的是另一半:探测**一天只允许跑一次**(`update_check_due` 看 `last_update_check_day`),
而原先 `UpdateState` 是纯内存的。两者一叠,"发现新版本"只会在真正跑探测的那一天出现,
之后就再也见不到——**尤其是升级装完、应用重启的那一次启动**,恰恰是用户最该看到的时候。
实测就是这么撞上的:第一次启动看不到横幅,把时间戳改老才出现。
| 约束 | 原因 |
| --- | --- |
| 提示要落盘,存在 `app_data_dir/update-notice.json` | 和 `history.json` 同一目录、同样在安装包之外,因此升级和重装都还在。只有 `available`/`ready` 值得留;其他结果一律**删掉**文件,于是一次失败的检查不会把旧结论留在面板上冒充新闻。 |
| 恢复时重新判定它还算不算数 | 版本已经不领先就整条丢掉——用户已经装上那个版本了,留着就是横幅 forever 地推荐他正在跑的版本;这也是清理的唯一时机,`revive_notice` 返回 `None` 时顺手删文件。 |
| `ready` 只有在安装包文件真在磁盘上才保留 | "已下载并校验"承诺的是临时目录里的一个文件,系统完全可以在 Shift 关着的时候清掉它。文件没了就降级成 `available`:这句话仍然为真,只是要重新下载一次。 |
| 恢复发生在 `setup_tray` **之前** | 托盘那一行(`update::tray_title`)读的是同一份状态。放在后面,横幅回来了而托盘行没有,两个入口自相矛盾。 |
| 关掉"每天检查更新"就不恢复 | 这个开关的语义是"别告诉我"。留着提示等于用磁盘缓存绕过用户刚刚做的决定。 |
| 用户点"忽略"要连磁盘那份一起删 | 否则"忽略"只有效到下次启动,横幅天天回来。 |
### 回归测试
```bash
cd src-tauri && cargo test --lib update::
```
`a_notice_for_a_release_still_ahead_survives_the_launch`(并且钉住恢复出来的
`current_version` 必须是**现在**在跑的版本,不是当初问的那个)、
`an_installed_release_stops_being_announced`、
`a_ready_notice_without_its_installer_downgrades_rather_than_lying`。
## 所有图标共用一份几何
同一句反馈的后半段是"应用图标要和当前的单色图标保持一致设计"。这句话的重点在**设计**,
不在**单色**:托盘那张必须是黑白的,因为它由系统着色;应用图标该是彩色的,因为 Dock
瓦片背后没有任何东西给它着色。真正让两张图标成为同一个作品的,是几何和填充规则,不是
颜色。
第一次改错了方向:为了“和单色标记一致”,把应用图标做成**深咖啡底 + 暖色图**,
等于把橙底白图整个翻转。深浅两种桌面都验过、对比度也算过,所以不是没检查,而是检查错了
对象——一致性有两条轴(几何 / 明暗关系),当时只对齐了几何那条,而用户认得的是“橙色底”。
所以两者由 `scripts/build-icons.py` 里的同一组常数画出来
(`OUTER`/`INNER`/`HUB`/`GAP`/`PLUS_ARM`/`PLUS_BAR`),只有背后允许出现的东西不同。
| 约束 | 原因 |
| --- | --- |
| 一致性来自几何与**平涂**,不来自配色 | 六块扇形、同样的扇区间隙角、同样的内外环与 hub 半径、加号同样是从 hub 里**挖**出来的负空间,以及同样一律平涂。旧图标之所以像另一个产品,不是因为它有颜色,而是因为它是一整块橙紫渐变底 + 径向高光 + 投影 + 六块扇形各配一种奶油色——那是另一套视觉语言。 |
| **橙底白图**,只有两色,且不得出现渐变/高光/投影/逐扇形配色 | 这条就是反馈最初的原话:“我之前是橙底、白线的风格”。底色 `#FF6B35` 取自本项目自己的母版,图色 `#FFF4EA` 取自界面的面板奶油色;加号是挖出来的洞、透出底色,而不是第三色。这样应用图标与托盘标记是**同一张图**,只是各自换了底色。 |
| 环形几何只在 `scripts/build-icons.py` 定义一次 | 托盘那张 PNG 是用它逐字节重绘出来的(改完脚本跑一遍,产物与仓库里的文件 `cmp` 相同)。几何分两处写就会漂移,而漂移只在 16px 下看得出来。 |
| SVG 母版里的瓦片是**内缩**的(820/1024) | `tauri icon` 只会等比缩放母版,**不会**加边距。母版画成满幅,产出的 `icon.png` 就是满幅方块,而仓库里原有的整组图标是 410/512=0.801 的圆角瓦片。 |
| 轮盘直径取瓦片的 0.795 | 被替换的那版母版是 r=326 画在 820 的瓦片里(0.795)。照抄这个比例,新图标在 Dock 里的视觉重量和旧的一致,不会突然变大。 |
| 加号用瓦片的颜色画,不真的打穿成透明 | 在 Dock 上两种做法看起来完全一样;但 `tauri icon` 合成 iOS/Android 图层时,真的洞会被平台背景填掉。 |
| 用 `--tauri` 重生成整组,而不是手搓 | 实测 `tauri icon` 产出的 `icon.icns` 条目(ic07…ic14 + is32/il32/s8mk/l8mk)与 `icon.ico` 尺寸梯(16/24/32/48/64/256)跟仓库里已有的**完全一致**,且它不会碰 `tray-template.png`。 |
验收看 16px:16px 时轮盘只有约 10px,六条扇区间隙约 0.46px、加号约 0.38px,都已经是
亚像素——被替换的那版在 16px 的加号也只有 0.72px,所以这不是退步,而是这套几何在小尺寸
下的固有结果。真正必须在 16px 还读得出来的是**外环的扇形分割**和瓦片轮廓,深浅两种桌面
下都验过。换成两色之后,不存在“某个颜色要到某个尺寸才出现”的问题了。
`public/shift-icon.png` 是 `icon.png` 的副本,不是另一张图:它在主窗口与编辑器标题栏里以
26 CSS px 显示(Retina 上 52 设备 px),那个尺寸下渐变版的中心已经糊成一团,而平涂版的
扇形分割和 hub 还分得开。
## 「最近使用」拖回主面板的三个按钮
0.1.8 曾经把这条交互关掉:一行拖出去是文件,拖回来却什么都不是,用户只能重新选一次文件。
现在拖到「文件转换 / 文件工具 / 文字识别」上就执行该按钮的动作。
**按钮是唯一的落点,也是唯一会响应拖放的东西。** 这条规则分两步收紧:
- 0.1.9 去掉了"落在面板空白处就打开操作环"的兜底,改成不执行操作、弹一条提示。
- 0.1.10 连提示也去掉:既然不执行任何操作,解释"为什么没执行"的浮层只是在用户没有松手的位置
制造动静,落在面板其他位置现在是彻底静默。
「文字识别」的拒绝方式在同一步收紧里改成了**事前可见**:0.1.10 用提示说明"这个格式识别不了",
但那仍是让用户先做错、再由浮层告知。现在拖拽一开始就按携带的文件判定,识别不了的按钮直接进入
不可用态,松手时什么都不发生,也不再有任何提示。
**不可用态写成"禁用 + 光标禁止符号",不额外画一层符号。** 拒绝要落在光标上:鼠标底下那个
复制角标本来就是 AppKit 对"这个落点要不要这个文件"的回答,能服务就画 +,不能服务就画禁止,
用户不需要先学会读按钮的配色。0.1.11 中途曾把拒绝画成按钮上层的禁止符号,理由是**页内拖拽改得动
`dropEffect`,外部文件却改不动光标**:外部文件走原生拖放通道,而 **macOS 下 wry 的
`draggingEntered:` / `draggingUpdated:` 固定回报 `NSDragOperation::Copy`**
(`wry/src/wkwebview/drag_drop.rs`,它甚至会把 super 返回的 `None` 改写成 `Copy`)。
现在的结论是:这条路能接管,于是拒绝交还给光标,按钮只保留 `disabled` 与配色弱化,不再叠一层符号。
**`src-tauri/src/drop_cursor.rs` 只改"回答",不改"投递"。** 页面是唯一知道"拖的是什么、
指针停在哪个按钮上"的东西,所以它把判定用 `set_drop_refusal` 命令交下来;原生侧在运行时替换 wry
那个私有类的两条回报方法(类名由 `wry::wkwebview::class::wry_web_view::WryWebView` 前缀扫描得到,
因为真名带 crate 版本,写死会在升级时静默失效),拒绝时把 `Copy` 收窄成 `NSDragOperationNone`。
**两次都必须先调用 wry 自己的实现再改它的返回值**:那次调用正是 `over` / `dragover` 的投递入口,
拒绝分支若直接 `return`,页面就再也收不到指针移动,一次拒绝会粘到整次手势结束——从不能服务的按钮
拖到能服务的按钮也不会亮。Windows 不需要这套:OLE 每次移动都会来问本进程,回报跟随页面设的
`dropEffect`,光标本来就会是禁止。
**被拒绝的手势没有收尾事件,所以盯鼠标松开。** 落点回报 `None` 时 AppKit 既不发
`performDragOperation:` 也不发 `draggingExited:`,按钮会一直停在禁用态、面板看起来卡住了。
`drop_cursor.rs` 因此在拒绝生效期间起一个线程轮询 `CGEventSourceButtonState`,松手时向主窗口
发 `drop://cancelled`,页面用它收起 `dragging` / `dropAction` / `dragPaths`。
**每次手势只报一次判定,起点必须是"欢迎"。** `draggingEntered:` 会把判定复位成不拒绝——文件还
没认全就拒绝会废掉一次本来能用的拖拽。而页面是在 `enter` 之后才回答的,所以 `useEffect` 的依赖里
必须带上一个"第几次拖拽"的计数器(`dragSession`),否则状态没变化的第二次拖拽不会重新上报,
上一次留下的判定会一直生效。
**按钮变暗用自身配色,不用全应用的 `opacity: var(--dimmed)`。** 不用 `opacity` 最早是为了
保住画在按钮之上的禁止符号——符号不能跟着被调淡。符号换成光标之后这条理由已经不在了,配色
没有再动:整颗按钮调淡会和"还在加载"混在一起,而改用 `color` / `background` 弱化读起来就是
"这颗关掉了"。留着它也省下一次已经验收过的观感改动。
**`is-drop-unavailable` 必须 `pointer-events: none`。** 落点由坐标命中(`actionAtPoint`)而不是
由"哪个元素回答了事件"决定;禁用按钮若仍占住命中区,`disabled` 后的按钮不再回应拖拽事件,
手势会停在最后一个应答过的按钮上。把它让开,命中判定与视觉状态才可能一致,顺带让 hover 反馈
彻底无从发生。
`dragPaths` 是判定唯一依据:原生路径在 `enter` 拿到 `paths`,内部路径在 `dragstart` 写入这一行
——`over` 事件不带路径,`dataTransfer` 在 `dragover` 里也读不到,所以两条路都必须在开始时登记。
### 内部拖拽会被原生 `enter` 报成"没有文件"
0.1.11 实测最隐蔽的一个 bug:把「最近使用」的一行拖到按钮上,**三个按钮全部点亮为可处理**,
松手却什么都不做——正是用户描述的"反馈为可处理文件,但又不给出操作"。原因是 macOS 上一次内部
拖拽会被**两条通道同时上报**,而原生 `enter` 的载荷里没有文件名:wry 的 `collect_paths` 只读
`NSFilenamesPboardType`,页内拖拽携带的是 `text/uri-list`,于是回报 `paths: []`。这个空数组把
`dragstart` 已经登记的 `[行路径]` 覆盖掉,而 `actionCanServe` 按既定规则必须把"文件未知"当作
不禁止,三个按钮就全成了候选落点。
修法是合并而不是覆盖:`dragPathsKnown(known, reported)`(`src/lib/dropCapabilities.ts`)——
报告非空时以报告为准,报告为空时保留已知的那一份。**不能反过来"信任最新一条"**:两条通道谁先到
因平台与 WebView 版本而异,覆盖语义必然在其中一种顺序下失效。也**不能把空数组直接判成"全禁用"**:
那是 0.1.10 之前 Windows 拖拽整片灰掉的成因(见下条 `actionCanServe`)。
外部拖入和内部拖拽始终遵循同一条规则,`dropFiles` 因此接受 `DropAction | null`,`null` 直接
原样返回——它不是"未知动作",而是"没有动作",两条投递路径共用这一个判断。
同理,拖拽反馈只加在按钮上:进行中三个按钮同时点亮为候选落点(原生拖拽用 `dragging`,内部
拖拽用 `rowDragging`),而 `.home-drop` 面板本身不再缩放、变色或换描边——`is-dragging` 类、
对应的两条 CSS 规则、以及随之失效的 `transition` 都已删除,标题也不再改文案。从外部拖入和从
列表拖起现在是同一种观感,之前只有外部拖入会让整块面板动起来。实现上有一条约束容易在重构时
丢掉:
**一次内部拖拽可能被报告两次。** 历史行使用 `dragOutPayload`,也就是 `text/uri-list` 里的
`file://` 加纯文本路径,因此它对外就是一个文件拖拽。同一次手势有两种投递路径:
- DOM:`onDragOver` / `onDrop`(挂在 `.home` 根节点,用 `clientX/clientY` 命中按钮);
- 原生:`getCurrentWebview().onDragDropEvent` 的 `drop`(坐标要先经 `toWindowPoint` 换算)。
哪个先、是否都会到,取决于 WebView 版本与平台,所以两条路都必须武装,再由
`recentDrag.current = { path, landed }` 的 `landed` 标记只放行第一个。去掉这个标记,
圆环会被打开两次;只保留 DOM,Windows 的原生投递会让拖拽失效。
另外两条约束:
| 约束 | 原因 |
| --- | --- |
| `onDragEnd` 不能立即清空 `recentDrag`,要延迟 500 ms | 部分引擎在按钮抬起之后才发出原生 `drop`,提前清空会让这一次手势变成"落回面板的空拖拽"。 |
| 两条投递路径都必须把"没命中按钮"当作同一种结果处理 | 内部拖拽与外部拖入的语义必须一致;只在 DOM 路径静默、原生路径仍兜底开环或弹提示,就会出现同一个动作两种结果。 |
| 点亮候选按钮的开关有两个来源 | 外部拖拽靠原生 `enter` 设置的 `dragging`,内部拖拽原生事件不一定到,必须另有 `rowDragging`,否则从列表拖起时按钮毫无反应。 |
| 面板不要用 `is-dragging` 自己做拖放反馈 | 内部拖拽拿不到原生事件,只有外部拖拽会点亮面板,两种拖法观感不同;把反馈收在按钮上,两条路径共用同一套 `has-drop-target`。 |
| 三个按钮共用 `src/lib/dropCapabilities.ts` 一条规则 | 判定原先只写在「文字识别」上,另外两个按钮照旧执行,于是"能处理就处理、不能处理就禁止"在同一个面板里有两种口径。视觉状态(`spent()`)、`dropFiles` 的实际执行、`aimedAction` 的点亮,三处必须问同一个函数,否则会出现"看着能按、按下去什么都不做"或者反过来。 |
| 「处理不了」不接受兜底,也不解释拒绝 | 按钮说做什么就做什么:既不能转交别的圆环,也不能弹一条"为什么不行"——那等于让用户先做错再被纠正。按钮禁用加光标禁止符号就是全部答复。 |
| 拒绝交给光标,按钮侧不再叠符号;为此必须接管原生回报 | 光标上的复制角标本来就是"这个落点要不要文件"的答复,两条投递路径都能改到它,观感天然一致;代价是 macOS 要在 `drop_cursor.rs` 里改掉 wry 固定回报的 `NSDragOperation::Copy`。页内拖拽仍走 `dropEffectFor()`,Chromium 会照它画禁止光标。 |
| 禁用按钮要 `pointer-events: none` | 落点靠坐标命中,不靠元素应答;禁用后按钮若仍占命中区,拖拽事件不再回到它身上,`dropAction` 会停在上一个应答的按钮上。 |
| 内部拖拽的原生 `enter` 不带文件名,要合并不要覆盖 | `collect_paths` 只读文件列表,页内拖拽带的是 `text/uri-list`,于是回报空数组;直接写入会把 `dragstart` 登记的行路径冲掉,三个按钮全点亮、松手又静默。`dragPathsKnown()` 保留已知的那一份。 |
| `actionCanServe` 在"文件未知"时必须返回 true | Windows 的拖拽在载荷可读之前可能报告 0 个文件;按空列表判定会把三个按钮全部禁掉,一次本来能用的手势就废了。只有"知道文件、且知道处理不了"才禁止。 |
| 「文件工具」永不禁止 | 它的环以打开 / 在文件夹中显示 / 发送收尾,任何存在的文件都能执行;把"其他"类型判成处理不了会让面板出现三个灰按钮。 |
| 拖出的行落在窗口之外时不能命中按钮 | `dragend` 的坐标也要经过 `actionAtPoint`,而命中判定四周有 `SLACK_X/SLACK_Y` 余量;不先判窗口边界,拖去资源管理器的一行会被当成落在按钮上。 |
| 拖拽结束时三处都要清空 `dragPaths` | 原生 `leave`、原生 `drop`、行的 `dragEnd` 都要清;`landRecentRow` 也清一次,因为部分引擎在落点已确定后才补 `dragEnd`,只靠它会让按钮在下一笔拖拽前一直显示为不可用。 |
### Windows:一次内部拖拽可能一次都不报告
0.1.10 用户实测:Windows 上把「最近使用」的行拖到三个按钮,**每一个都完不成**。台账
里"只保留 DOM,Windows 的原生投递会让拖拽失效"写反了方向——在 Windows 上两条路都可能不到:
1. **DOM 路径**:历史行是 `draggable` 的文件式拖拽,WebView2 在自己的窗口上注册了 OLE
`IDropTarget`(`wry/src/webview2/drag_drop.rs`),页面内的 drop 被它接管。
2. **原生路径**:那个 `IDropTarget::DragEnter` 只读 `CF_HDROP`;页内拖拽不带这个格式,
于是 `enter_is_valid` 保持 false,`DragOver` / `Drop` / `DragLeave` 一律不上报。
两条都静默,松手就没有任何事件,于是"什么都会发生"被用户读成"拒绝"。修法是让 `dragend`
成为兜底:它总会上报,且带 `clientX/clientY`,足够命中按钮;`landed` 标记保证它只在两条
投递路径都没到过的时候执行一次。
**0.1.11 第一次修错了方向。** 那版把兜底写在 `dragEnd` 里立刻执行,而 macOS 的原生
`drop` 是在按钮抬起**之后**才到的:兜底先用 `dragend` 自己的坐标判定(Chromium 在这里报
的是 (0, 0),不是松手位置),把 `landed` 置真,随后真正的那次 drop 被当作"这一笔已经完了"
丢掉——结果从"偶尔不响应"变成"三个按钮全部无反馈"。现在兜底满足两条:
| 约束 | 原因 |
| --- | --- |
| 兜底必须延迟到真正 drop 之后(260 ms),且只由 `landed` 决定谁执行 | 谁先谁是正确答案因引擎而异;macOS 是 drop 在后,页内拖拽在 Chromium 是只有 `dragend`。 |
| 兜底只在**命中按钮**时才落地 | 没命中时它给不出任何 0.1.10 给不了的东西,却可能抢在真正的 drop 之前把这一笔标记完成,把它吃掉。 |
| `dragend` 坐标为 (0, 0) 时改用在途最后一次 `dragover` 的位置 | (0, 0) 是"没报告"而不是"在左上角松手";Chromium 就是这样。 |
| 不要改成"记住离开窗口时就丢掉该位置" | Chromium 在 `dragenter` / `dragleave` 上把 `relatedTarget` 固定为 null,按它清位会让 Windows 的兜底永远拿不到落点——又回到不响应。剩下的误判只剩"从按钮上拖出去"这一种路径,代价远小于什么都不做。 |
### 拖动时的图像是文件,不是那一行
不加 `setDragImage` 时,引擎拍的是指针下的元素本身:缩略图 + 文件名 + 时间 + 目录 + 五个悬停
按钮,看上去像在拖整个列表。`src/lib/dragImage.ts` 造一个和圆环拖拽示意同款的"一个文件 +
名字"的图(图片行复用列表里已经解码好的缩略图,其他行显示扩展名)。它挂在 body 外、屏幕外,
250 ms 后自删:两个引擎拍照的时机不同帧,删早了就拍不到。
### Windows:闲置的圆环会压在按钮上
圆环窗口无边框、`always_on_top`,用完不关就停在原地等点击,而它可能正压在面板的按钮上。
开始拖动一行时先调用 `stand_down_radial` 让它让开;`radial_dragging` 为真说明这次圆环属于
一个正在进行的 Shift 拖拽手势,那时不能收——结束手势的松手才有权处置它。
注意不要把它改成"圆环在 `enter` 时自行让开":往打开的圆环上直接放文件、由落点扇区执行该
动作,是 Windows 现有的一条可用路径,被闲置判定挡掉就是功能倒退。
### 回归测试
`src/lib/dropTargets.test.ts` 覆盖命中区域与坐标换算,`src/lib/dropCapabilities.test.ts`
覆盖"谁能服务这次拖拽"这条规则(含类型表与后端一致、PDF 不落到 OCR、载荷未知时不禁止);
拖拽本身用浏览器实测(Chromium 与 WKWebView 两条路径都要走一遍):
1. 「最近使用」某行 → 拖到「文件转换」→ 只弹出一个格式环,且文件是这一行。
2. 同一行 → 拖到「文件工具」→ 只弹出工具环。
3. 图片行 → 拖到「文字识别」→ 按钮正常点亮,光标带 +,打开编辑器并自动开始识别;非图片行 → 「文字识别」拖拽全程为禁用态、**光标为禁止符号**、不会点亮,**hover 完全无反馈**,松手后不打开编辑器、不开环、**不出现任何提示**,另外两个按钮仍可正常落点。**同一条非图片行还要从访达再拖一次**:两条通道的光标观感必须一致(这是 0.1.11 的主要回归点)。
3b. `.key` / `.zip` 这类没有可转换目标的行 → 「文件转换」同样全程禁用+光标禁止、松手不执行;「文件工具」始终可用并正常弹出工具环。
3c. **Windows 必须单独跑一遍 1–3**:这一平台两条投递路径都可能不上报,兜底只在 `dragEnd` 里,macOS 通过不代表 Windows 通过。
3d. 先用「文件转换」弹出一个圆环、再拖一行到按钮上 → 圆环不能吃掉这次拖放(Windows 尤其要看这一条)。
3e. 拒绝之后把文件拖到**能服务的按钮**上 → 光标必须重新变成 +、按钮重新点亮、松手正常执行。原生侧一旦在拒绝时提前返回而跳过 wry 的实现,页面就收不到指针移动,整段手势都会停在拒绝上。
3f. 连续拖两次同一批文件 → 第二次不能残留第一次的判定(`dragSession` 就是为了让每次手势都重新上报一次)。
4. 同一行 → 拖到面板空白处 / 标题栏 / 列表本身 → 不开环、不执行、**不出现任何提示浮层**。
5. 从访达拖文件到面板空白处 → 同样不执行、不提示;拖到任一按钮 → 执行该按钮的动作。
6. 行拖出到访达/聊天窗口 → 仍是文件本体,没有被 Shift 自己吃掉。
7. 两种拖法各拖一次 → 面板(`.home-drop`)在拖拽全程不缩放、不变色,标题文案不变;只有三个按钮在拖拽开始时同时亮起虚线候选态、松开后熄灭。
8. 松手之后(无论落在哪里)→ 按钮立刻恢复正常亮度,下一次拖拽不会残留不可用态。
## 「完成后在访达中显示」管到的两条落地路径
`auto_reveal` 这个开关原本只有转换完成时会读:`perform_file_action` 结束前判断一次,
弹出第一个输出。局域网收到的文件走的是 `share.rs::receive_file`,它自己 `emit`
`app://file-result` 并写入历史,从来不经过那条判断,所以「接收完就弹一个访达窗口」
不受任何设置控制。
现在两条落地路径共用同一条规则:**文件落地之后是否把文件管理器带到前台,由
`settings::auto_reveal` 决定**。批量接收沿用批处理的既有语义——一批只在最后一个文件
落地时显示一次(`reveals_on_landing`),而不是每个文件弹一次窗口,与一次转换十个文件
只弹一个输出的行为对齐。
| 约束 | 原因 |
| --- | --- |
| 接收路径必须读 `auto_reveal`,不能自己决定弹窗 | 同一件事有两种行为,用户只能理解为开关坏了;转换那侧已经是这个口径。 |
| 一批文件只按最后一个文件显示一次 | 显示的是文件管理器窗口,十个文件弹十次等于抢占前台十次。 |
| 批内序号必须在 `emit_transfer` 之前读 | 那条事件会把 `header.peer_name` 移出,之后再借用就是编译错误;先算成一个 `bool` 才能既保住顺序又保住借用检查。 |
| 缺字段的旧版本信标必须仍然显示 | `batch_index` / `batch_total` 都取默认 0 时,`index + 1 >= total` 成立,`saturating_add` 防的是 0 - 1 下溢。 |
### 回归测试
`cargo test --lib share` 的 `only_the_last_file_of_a_batch_reveals`:钉住单文件、批次中间、
批次末尾与旧版本信标四种头部的判定。
## 提示语由界面措辞,后端只报代号
同一件事在两个地方各说一遍,就一定会说成两样。0.1.10 之前正是这样:`perform_action` 直接返回
`"Saved 1 file."` 这类英文句子,界面在中文环境里也就照原样显示,而同一个环里别的结果用的是
`t("saved")`;写目录被拒的提示同样由 Rust 拼成英文长句,macOS 首次运行必然看到它。
现在约定只有一条:**后端说"是哪件事",界面说"这句话怎么说"。**
- 结果:`ActionOutcome.message` 只能是 `outcome*` 代号,由 `src/lib/feedback.ts` 的
`outcomeMessage()` 措辞;数量取自 `outputs.length`,不再把数字写进句子再让人解析。
- 失败:`Err("…")` 用 `err*` 或 `share-*` / `homebrew-*` 这类既有小写代号;显示前统一走
`t(messageFrom(error))`。`translate()` 查不到 key 时原样返回,所以第三方库抛出的原始句子
(`ffmpeg exited with status 137`)仍会照实显示,不会被压成一句无信息的话。
- 措辞查不到就不要显示代号:`outcomeMessage()` 对未知 `outcome*` 回落到 `saved`。
`src/lib/feedback.test.ts` 会扫过 `src-tauri/src/*.rs`,要求每一个 `err*` / `outcome*` 代号在
两种语言里都有措辞,且 `outcome*` 必须被 `feedback.ts` 认识。新增代号时不必改测试——它会自己发现漏掉的
那一个;删掉一个还在用的代号同样会红。
另一条容易踩的约束:**一次性注册的监听器不要闭包捕获 `t`。** 挂载时注册的回调拿到的是首帧的 `t`,
之后切换语言,它弹出的消息仍是启动时的语言;`app://error` 与两条落点失败的回调因此用
`tLive()`(按当前存储的语言即时翻译),而不是 `t`。
反馈的时长收在 `FEEDBACK` 一处(`done` / `hint` / `notice` / `error` / `running` / `hold`),
`hold` 专用于进度会持续刷新、中途不能过期的长任务;`src/lib/utils.ts` 的 `messageFrom()` 是
把 unknown 变成文案的唯一途径。不可用控件统一用 `--dimmed` 与 `cursor: default`,
`:hover` 一律带 `:not(:disabled)`。
## 更新、分享与读取边界
2026-11 的全面评审补了一组不应被简化掉的约束。它们共同处理的是同一类问题:
**一个被声明为“已校验”的对象,在真正使用前仍可能变化,或声明值本身可能不可信。**
### 更新链路
| 约束 | 原因 |
| --- | --- |
| 清单里的文件名必须直接位于发布目录 | 路径分隔符、`..`、空格和 shell 元字符不能进入下载路径或交接参数;发布脚本产出的文件名只含 ASCII 字母、数字、`.`、`-`、`_` |
| 清单下载后限制 256 KiB | 清单是小型 JSON;损坏或被替换的 feed 不应无限占用内存 |
| 下载后校验是普通文件、精确字节数和 SHA256 | 只比较哈希仍会接受声明尺寸与实际尺寸不一致的输入 |
| 安装前再次执行同一组校验 | 下载文件位于可写的临时目录,下载完成到用户点击安装之间存在 TOCTOU 窗口;失败时必须删除文件 |
| macOS/Windows 辅助脚本使用固定脚本常量,路径经进程参数或环境变量传入 | 文件夹名不能改变 helper 的脚本文本;Windows 启动器必须保留 `cmd.exe /C` 的外层引号,否则含空格路径会被静默截断 |
| `Discard` 删除实际下载物 | 只清状态会留下可被误用的旧安装包 |
回归测试:`artifact_names_stay_inside_the_release_directory`、
`an_installer_changed_after_download_is_refused`,以及两个 handoff 脚本的参数化
检查。真实 Windows 交接仍需在 Windows 机器上验收。
### 分享链路
| 约束 | 原因 |
| --- | --- |
| peer 表最多 256 项,满时先清理过期项 | 未认证信标可伪造无限 id;可见列表不能无限增长 |
| 发送端按 header 声明大小精确复制 | 源文件在 metadata 之后变长时,多出的字节会被接收端误当成 ack |
| 源文件比声明短时立即失败 | 不允许用半截文件换取成功状态;接收端删除 `.shift-part` |
| 只有用户已接受后的接收失败才弹错误 | 任意 TCP 扫描或坏握手不应产生用户可见的 toast |
| 接收错误事件带文件名与 peer 名 | 失败要可定位,而不是只有一句泛化提示 |
回归测试:`the_peer_table_stops_accepting_new_ids_at_its_limit`、
`bytes_after_the_declared_size_never_cross_the_wire`、
`a_source_that_shrinks_is_refused_without_a_partial_file`。
分享协议本身仍无认证、无加密;这里修的是拒绝自动落盘、路径安全、字节边界和可见
失败,不是身份认证。安全边界见 `docs/SECURITY.md`。
### 编辑器读取
| 数据 | 上限 | 测试 |
| --- | --- | --- |
| 文本预览 | 8 MiB | `editor_reads_are_bounded_before_they_allocate` |
| 图片文件 | 64 MiB | 同上 |
| 图片像素 | 4000 万 | 与钉图上限一致 |
| 编辑后 data URL | 128 MiB | 解码前检查 |
文本与图片在 Rust 读盘前检查路径是否为普通文件并执行上限;UI 只负责把返回的
`errNotAFile` / `errTextTooLarge` / `errImageTooLarge` / `errEditDataTooLarge`
翻译成文案。不要在只读预览里静默吞掉读取错误。
## 修改这些路径时的统一回归命令
```bash
git diff --check
cd src-tauri
cargo fmt --check
cargo test --lib
cargo clippy --all-targets -- -D warnings
cd ..
pnpm check
pnpm test
pnpm build
```
发布构建还需额外完成本文对应章节的手工矩阵。任何一次修改如果改变了发现协议、转换
依赖链或 macOS 签名方式,都应在本文件补一条带日期的结论和提交号。

265
docs/MOBILE.md 100644
View File

@ -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 order (desktop reads `settings.json`; no editor UI in 0.1.11) | Share sheet "Edit Actions" ordering, mirrored in a mobile Settings surface | 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 |

28
docs/README.md 100644
View File

@ -0,0 +1,28 @@
# Shift documentation
Start with the user guide, then choose the engineering document that matches the
work.
| Document | Audience | Contents |
| --- | --- | --- |
| [`../README.md`](../README.md) / [`../README.zh-CN.md`](../README.zh-CN.md) | Users | Features, formats, shortcuts, privacy, known limitations |
| [`ARCHITECTURE.md`](ARCHITECTURE.md) | Contributors | Process/window model, module ownership, events, data flows |
| [`SPECIFICATION.md`](SPECIFICATION.md) | Product and QA | Observable behaviour, naming, limits, acceptance criteria |
| [`SECURITY.md`](SECURITY.md) | Security reviewers and maintainers | Trust boundaries, update and LAN risk, residual gaps |
| [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md) | Contributors | Regression ledger and non-negotiable implementation constraints |
| [`RELEASE.md`](RELEASE.md) | Release maintainers | Channel layout, signing, update handoff and verification |
| [`BUILD_WINDOWS.md`](BUILD_WINDOWS.md) | Builders | Windows prerequisites, cross-build and installer notes |
| [`ROADMAP.md`](ROADMAP.md) | Contributors | Completed milestones and next desktop work |
| [`MOBILE.md`](MOBILE.md) | Product planning | Mobile feasibility and architecture plan |
| [`../CONTRIBUTING.md`](../CONTRIBUTING.md) | Contributors | Setup, checks, change rules and manual matrix |
## Source of truth
- Current code and tests define implemented behavior.
- The conversion/tool tables in `README` describe the user-visible catalogue;
the runtime catalogue lives in `src/lib/conversionFormats.ts` and
`src/lib/radialOrder.ts`.
- Platform/runtime limitations must be stated as unverified when no real
hardware run exists.
- Do not claim a CI run without linking its log.

406
docs/RELEASE.md 100644
View File

@ -0,0 +1,406 @@
# 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-0.1.13-macOS-universal.dmg
└── Shift-Setup-0.1.13-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.13",
"date": "2026-10-26",
"notes": "",
"artifacts": {
"macos": { "file": "Shift-0.1.13-macOS-universal.dmg", "sha256": "…", "size": 0 },
"windows": { "file": "Shift-Setup-0.1.13-win-x64.exe", "sha256": "…", "size": 0 }
}
}
```
Artifact names are restricted to ASCII letters, digits, `.`, `-` and `_`; path
separators, `..`, spaces and shell metacharacters are rejected. The app also
refuses a manifest over 256 KiB. These checks keep malformed manifest data out
of download paths and out of the native handoff arguments.
## 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, shipped as a DMG. Verified on a fresh machine by dragging it to /Applications — see "macOS packaging" |
| `windows` | yes | x64, which is also what an ARM machine falls back to |
| `windows-arm64` | no | Runtime compatibility only: Windows on ARM installs the x64 package through `windows` |
| `linux` | no | Build target, not a product; see below |
The incident history, failure signatures and non-negotiable implementation constraints
behind the current Drop, conversion and macOS packaging behaviour are recorded in
[`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md). Read the relevant section before changing
those paths; this release guide defines the channel, while the engineering ledger explains
why the current shape must not be simplified back into an earlier failure.
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.
## macOS packaging
Shift builds are **ad-hoc signed** (`signingIdentity: "-"` in `tauri.conf.json`) and are
**not notarized** — notarization needs an Apple Developer ID account, which this project
does not have. Gatekeeper therefore cannot vouch for any Shift build, and what a fresh
machine says depends on how the binary is signed:
| Signing | What a fresh machine says |
| --- | --- |
| Ad-hoc (`Signature=adhoc`) — **current** | "cannot be opened because it is from an unidentified developer", and the box offers a way through: Cancel, then right-click → 打开, or 允许 in 系统设置 → 隐私与安全性 |
| Self-signed certificate | "cannot be opened because it is damaged" / reported as malware, with **only 移至废纸篓** — no override, no pane entry to approve |
| Developer ID + notarized | Opens on double-click, no prompt |
The middle row is what a release shipped with, and it is a trap because it looks healthy
locally: `codesign` reports `valid on disk` and `satisfies its Designated Requirement`, and
`spctl` accepts it on the build host. The certificate ("Shift Local Signing") is self-issued,
`CA:FALSE`, and present in only that one Mac's keychain, so on any other machine it cannot
chain to a trusted root — and an unchainable signature on a quarantined download is a hard
refusal rather than a prompt.
One correction worth keeping, because the obvious story is wrong: every DMG this channel has
ever published carries that same `Authority=Shift Local Signing`, including the earliest 0.1.0
ones, because Tauri picks a keychain identity itself when `signingIdentity` is unset. So
"older builds were ad-hoc" is **not** why one machine accepted them — a machine that had been
shown the app before may already trust the certificate, and Gatekeeper's own heuristics have
changed across macOS versions. What is verified is the direction of the fix: an ad-hoc binary
is reported as an unidentified developer with a way through, which is the behaviour this
project wants, and no release is worse off for losing a certificate no other Mac can check.
Reusing that identity again would mean installing it **and trusting it** on every machine,
which is not something to ask of a user.
So: ad-hoc, and one container. The channel ships **`Shift-<version>-macOS-universal.dmg`** and nothing
else on macOS — the earlier `.pkg` companion was dropped after the DMG was verified to work
on a fresh machine, and one file per platform is less to keep straight.
| Situation | What happens |
| --- | --- |
| A machine installing Shift for the first time | Double-click the DMG, drag `Shift.app` to /Applications. The app keeps the browser's quarantine flag, so the **first launch** needs the one approval above: right-click → 打开, or 允许 in 系统设置 → 隐私与安全性. Every launch after that is normal. |
| An installed Shift updating itself | `update_install`'s handoff downloads the DMG, mounts it with `hdiutil`, copies the bundle out and drops the quarantine flag. Shift's own downloader sets no quarantine flag (`curl` sets none, and the handoff strips it anyway), so **in-app updates never prompt**. |
The `macos` manifest key is a DMG for the same reason: the in-app handoff mounts the image,
so pointing the key at a package would break every in-app update. That was the one real
constraint the container had to satisfy, and a DMG satisfies it.
The retired `.pkg` packaging script has been removed. The DMG is the only macOS
container in the release pipeline.
### macOS release gate
Every macOS release must pass all of these before it goes into `artifacts/`:
1. Run `pnpm mac:release`. It rebuilds the universal Swift sidecars, builds the app
and DMG, verifies both, and copies the result to the versioned release name.
2. Run `codesign --verify --deep --strict` on `Shift.app`, and confirm
`codesign -dv --verbose=2` reports `Signature=adhoc`. A local certificate name here is
a release blocker, not a stronger signature.
3. Run `hdiutil verify artifacts/Shift-<version>-macOS-universal.dmg` and verify `SHA256SUMS.txt` after copying
the final artifact into `artifacts/`.
4. Confirm the release contains no `.pkg`, and that the manifest's `macos` entry points at
the DMG. The in-app helper mounts that exact container with `hdiutil`.
5. Transfer the DMG to a different Mac, preferably one that has never installed Shift.
Download the final artifact through a browser from the release feed when possible so the
quarantine flag matches the real user path; if a USB or AirDrop transfer is used, confirm
the quarantine attribute is present, otherwise Gatekeeper was not exercised. Drag
`Shift.app` to `/Applications`, approve the first launch once, and verify the version.
6. On that same machine, open Drop and confirm another Shift peer appears and stays in the
list. A packaging or signing change can invalidate Local Network approval even when the
app itself starts correctly.
7. For an update release, install the previous version on that machine and run the in-app
update once. It must restart on the new version without a Gatekeeper prompt.
The build host opening its own DMG proves neither cross-machine installation nor the
quarantine behaviour. Step 5 is the hard release gate. The full incident record and the
manual Drop matrix are in [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md).
Closing this for good means an Apple Developer ID: `Developer ID Application` +
`notarytool` + `stapler staple`. Then the DMG opens on double-click with no pane to visit,
and the privacy grants keyed to that identity — Screen Recording, and Local Network, which
is what device discovery needs — stop resetting between builds. That reset is not
theoretical: a 0.1.4 user found the device list empty after upgrading, with nothing in the
UI to say why.
## Publishing
```bash
pnpm mac:release
scripts/build-windows-release.sh
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 are exactly `Shift-<version>-macOS-universal.dmg` (macOS) and
`Shift-Setup-<version>-win-x64.exe` (Windows). Publishing fails if either is missing,
or if any other `.dmg`, `.exe`, `.msi`, `.pkg`, `.zip`, AppImage or deb remains in
`artifacts/`. `SHA256SUMS.txt`, the two platform notes and `README-macOS-universal.txt`
travel with the branch as supporting files, never as installers. Dotfiles and an old
manifest are skipped.
`README-macOS-universal.txt` is tracked in the repository as well as pushed to the channel,
so the scheme is documented where a contributor reads it and not only next to a build
product. Every claim in it was checked against the shipped artifacts: the bundle inside the
published DMG is `Signature=adhoc`, and `shasum -a 256 -c SHA256SUMS.txt` passes on the
published set.
The Windows command cross-compiles one target, checks the PE machine field (`0x8664`)
and gates the installer to x64:
```bash
scripts/build-windows-release.sh
scripts/build-windows-release.sh --skip-build
```
## 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 mac:release # macOS universal DMG
scripts/build-windows-release.sh # Windows x64 installer
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 both release scripts derive the public key from
it, so a 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.
`scripts/release-key.py` treats a file ending in `.pub` as an ed25519 public
key and every other path as the 32-byte private key. `keygen` writes the private
key (`release.ed25519`, mode 0600) and its public companion (`release.pub`). Keep
the private key out of CI logs and do not rename the public file to a non-`.pub`
name when using `pubkey`.
## 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: the byte length must equal the
manifest's `size`, and the recomputed SHA256 must equal the manifest's `sha256`. Both
checks run again immediately before the handoff. A mismatch deletes the file and
reports the error, so a truncated or swapped installer never reaches the installer
step.
4. **Install & relaunch** applies the verified artifact and restarts Shift on it, as
described in the next section; **Discard** removes the downloaded artifact as well as
the update status. When an update is available the tray menu gains a row that opens
Settings on the Updates tab.
Manifest `schema` is checked; this build accepts exactly `1` and refuses anything else
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.
## Applying an update
Neither operating system lets a running program replace its own executable, so the work
belongs to a helper that outlives the app. `update_install` writes a script into the
download folder, starts it detached, and exits about half a second later; the script waits
for that pid to disappear and only then touches the installed copy.
| Platform | What the helper does |
| --- | --- |
| macOS | Mounts the downloaded `.dmg`, `ditto`s the new bundle next to the old one, swaps them with two `mv` calls, removes the quarantine flag, detaches the image, and `open`s the result |
| Windows | Waits for `shift.exe` to leave the process table, runs the installer with `/S`, then starts the `shift.exe` the installer wrote |
| Linux, and a macOS binary run outside a bundle | Nothing is replaced; the artifact is opened instead, and the panel says so |
Both scripts are written so a failure cannot end with Shift simply closed: every macOS
failure path still `open`s the bundle it had, and the swap is `move aside, move in`, so a
copy that fails halfway leaves the previous version where it was. The scripts themselves
are fixed constants; the pid, installer, bundle and log paths arrive through process
arguments or environment variables, never interpolated into shell or batch source. The
Windows launcher also keeps the outer quote layer that `cmd.exe /C` would otherwise strip
from a script path containing spaces. Before the handoff starts, macOS
writes a probe file next to the bundle — a root-owned copy in `/Applications` is reported
as "open the downloaded installer yourself" rather than quietly quitting on an update
that could not be applied.
The Windows installer is the same one a user runs by hand, so the update path cannot drift
from the manual one. Because the silent install comes from Shift itself, `${Silent}` skips
the interactive "Shift is running, close it?" box and the WebView2 warning: the app
already told the user it is about to restart, and a box nobody can answer would abort or
hang the update.
This is not a delta update and not a signature check on the running binary: the same
SHA256 gate that guards a manual install is the only integrity gate, and the manifest
signature rules in "Signing the channel" apply unchanged.
Replacing the bundle gives it a new code-signing hash, and macOS keys permissions such as
Screen Recording to that hash. A release signed with the same identity as the copy it
replaces normally keeps its approvals; a locally signed build, where every build has its
own identity, can ask again after an update. That is the same consequence a manual
reinstall has, and it is why the notarized-build item in the roadmap is worth closing.
## 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
This section is a historical audit of the published channel at the time it was
performed. It is not a claim that the current `releases` branch still contains
this version or that CI produced it. Re-run the verification below before using
these numbers in release notes.
Version **0.1.7**, 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,585,331 B) | bytes downloaded, SHA256 matches the manifest |
| `windows` | `Shift-Setup-0.1.7-win-x64.exe` (24,514,334 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 |
The retired `Shift-macOS-universal.pkg` left the branch with this publish: the branch is
rebuilt from `artifacts/` on every run, so dropping it from the build was enough. macOS now
ships the one container ("macOS packaging").
`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 workflow defines separate macOS, Windows and Linux jobs, but this audit did
not record a linked CI run. Treat the local commands in `CONTRIBUTING.md` as the
release gate unless a green run is attached to the release.
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.

211
docs/ROADMAP.md 100644
View File

@ -0,0 +1,211 @@
# Shift Roadmap
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.
- Area screenshot, area recording, local EN/ZH OCR.
- Image conversion and basic file operations.
- 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 — done
- 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 — 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.
- Batch operations and drag-to-submenu interaction.
- 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; the retired editor was removed in 0.1.8 and only the read path is
retained for compatibility with existing user settings.
- 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 — partial
- Windows global drag bridge using the Win32/OLE drag state is implemented.
- 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.
- LAN Drop discovery is working again in 0.1.7: the shared discovery socket now combines
multicast, per-interface directed broadcast, limited broadcast and a bounded `/24`
unicast sweep; ordinary beacons receive one marked reply, and peer expiry is long enough
for older copies to answer. The user-observed acceptance run covered one Mac and one
Windows x64 machine after an upgrade. Unit tests cover the scan bounds, timeout and reply
semantics, but the live two-host check is manual because the repository has no
second-machine fixture. Client-isolated Wi-Fi remains outside the app's
control, and Windows still permits only one listener per machine. The exact invariants
and manual matrix are in `docs/ENGINEERING-NOTES.md`.
- Windows ARM64: the release pipeline ships only the x64 NSIS installer, checks its
PE machine field (`0x8664`), and gates the installer to x64. An ARM machine tries the
optional `windows-arm64` manifest key first and falls back to `windows`, which Windows
on ARM runs through emulation. Verified by cross-building, packaging and publishing
from macOS; running the installer on real Windows-on-ARM hardware has not happened.
Since 0.1.1 the shipped installers are macOS universal and Windows x64 only.
- 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.
- 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.
## 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.
- Installing happens inside the app: after the SHA256 gate, macOS replaces its own bundle
from the downloaded disk image and Windows runs the same NSIS installer with `/S`, each
from a detached helper that waits for this process to exit and then opens the new copy.
macOS was exercised end to end — a 0.1.1 bundle swapped by the published 0.1.2 image,
`codesign --verify --deep --strict` clean afterwards — including the failure path, where
a busy image left the old copy running instead of leaving Shift closed. The Windows
script is cross-built and its `${Silent}` gate compiles, but the restart itself needs
real hardware. See "Applying an update" in `docs/RELEASE.md`.
- An update no longer costs the user the Recent list. That library lives in the app data
directory rather than in the bundle, and since the move out of the webview's own storage
it had no bridge from the old store: `history_import` adopts those rows on the first
launch after an upgrade, re-deriving each entry's kind from the file rather than trusting
the older store's guess, then the legacy key is dropped so a later upgrade cannot
resurrect rows the user has since removed.
- Signed and notarized macOS package: pending. Builds are **ad-hoc** signed, deliberately:
signing with a locally created certificate made every other machine refuse the app as
*damaged / malware* with no override, because that certificate cannot chain to a trusted
root anywhere else, while an ad-hoc binary gets the softer "unidentified developer" box
the user can approve. The channel ships one macOS container, the DMG: it was verified on a
fresh machine (drag to /Applications, one approval on first launch), so the `.pkg` that
once accompanied it was dropped rather than kept as a second thing to maintain. The `macos`
manifest key has to stay a DMG anyway, because the in-app handoff mounts it with `hdiutil`;
see "macOS packaging" in `docs/RELEASE.md` and the packaging incident record in
`docs/ENGINEERING-NOTES.md`. The release gate deliberately requires installation from the
transferred DMG on a different Mac; opening the build host's own image is not evidence.
A Developer ID plus notarization removes the prompt entirely and would also stop Screen
Recording and Local Network approval from resetting between builds — both are keyed to the
signing identity, so an ad-hoc rebuild loses them, and a lost Local Network grant empties
the device list with no message anywhere in the UI.
- 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 is re-verified by hand against the live `releases` branch with
every release: the 0.1.2 manifest's signature checks out against the baked key and both
artifacts (`macos`, `windows`) match their published size and SHA256 after being
downloaded back. 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 verified CI run.** `ci.yml` defines macOS, Windows and Linux jobs, but no linked
run in this repository proves that the current hosting forge executes them. Either
configure a runner or run the workflow on a mirror. 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.

193
docs/SECURITY.md 100644
View File

@ -0,0 +1,193 @@
# Security model
Shift is a local desktop utility that opens files the user chooses, invokes
native renderers and external tools, listens for local-network transfers, and
installs signed or hash-verified updates. This document states what is
protected, how, and what remains outside the current guarantee.
It is a design document, not a promise that every path has received an
independent audit.
## Assets
- The user's source files and output folders.
- The integrity of the installed application and its update channel.
- The user's consent before another machine writes a file.
- Local data such as `settings.json` and `history.json`.
- Release-signing and manifest-signing secrets.
## Threat model
Relevant adversaries include:
- a malicious or malformed image, document, PDF or media file;
- a machine on the same LAN that sends beacons, opens transfer sockets or
impersonates another Shift;
- a compromised update feed, release branch or HTTP endpoint;
- an attacker who can modify files in the user's temp or config directories;
- a compromised renderer or injected content in the bundled webview.
The model does not assume the local operating-system account is already
compromised. An attacker with the user's account can generally read and modify
the same files Shift can.
## Local file access and webview
Shift's own React bundle calls Tauri commands with paths selected by the user or
returned by Shift. There is no user-authored HTML or remote page loaded into the
main window. External files are treated as data, not executable content.
The Tauri configuration currently sets `csp: null` and gives the asset protocol
scope `**`. That is intentionally broad because the editor and previews need
local files and the canvas needs same-origin image data. If renderer-content
injection is ever found, those settings increase the impact: the injected script
could call available commands or read local assets. Hardening this would require
a tested CSP/asset-scope reduction and a full editor, OCR-worker and clipboard
smoke test; until then, treat the webview bundle as part of the trusted computing
base.
The app does not ship a remote-content loader, analytics SDK or advertising
component.
## Untrusted files and resource exhaustion
File extensions decide the conversion catalogue, but not trust. Document and
media parsers receive attacker-controlled bytes.
Implemented bounds:
- editor text preview: 8 MiB before reading;
- editor image input: 64 MiB before reading, plus a 40-megapixel decode limit
where the decoder can report dimensions before full decode;
- editor data URL: 128 MiB, with a second decoded-size and pixel check;
- pinned-image preview: 40 megapixels;
- update manifest: 256 KiB after download;
- update artifact: exact declared size and SHA256, rechecked before install;
- LAN peer table: 256 entries;
- LAN transfer: the receiver reads exactly the header-declared byte count and
removes a partial temp file on failure;
- GIF conversion: time, frame-rate, width and byte ceiling;
- PDF page extraction: per-page extracted-text limit and bounded render edge.
Not yet uniformly bounded:
- Office ZIP entries and XML can still expand under decoder defaults; there is
no one shared decompressed-size quota across DOCX/PPTX/XLSX paths.
- PDF rendering and compression rely partly on external renderers (PDFKit,
Poppler, ImageMagick, FFmpeg) with their own limits.
- CSV/TSV and some Office paths read whole files or sheets into memory.
- LAN transfers have no maximum file size or free-space preflight. The receiver
sees the declared size before accepting, but a malicious peer can still
occupy disk after consent.
- A manifest download is size-checked after it has been written, not while it is
streaming.
Do not open adversarial documents in production until these paths have explicit
quotas and tests. Report a reproducible resource-exhaustion case rather than
assuming the editor limits cover every converter.
## Update trust boundary
The update channel is a git branch containing `shift-update.json`, optional
`shift-update.sig`, and installer files. Builds derive the feed URL from the git
remote or from `SHIFT_UPDATE_URL`.
Controls:
- manifest `schema` must be exactly the supported version (currently 1);
- artifact filenames must be safe ASCII basenames;
- artifact size must be nonzero and SHA256 must be valid hex;
- the manifest is capped at 256 KiB;
- a build compiled with `SHIFT_UPDATE_PUBKEY` requires a detached ed25519
signature over the manifest's exact bytes;
- the installer is checked for exact byte length and SHA256 after download;
- both checks run again immediately before installing;
- the installer must be a regular file, not a symlink;
- macOS and Windows handoff scripts receive paths as process arguments or
environment variables, never interpolated shell/batch text;
- `Discard` deletes the downloaded artifact, not just the UI state.
Residual risk:
- An **unsigned** build trusts the HTTPS origin plus anyone able to write the
release branch or its raw endpoint. SHA256 proves the file matches the
manifest, not that the manifest is authentic.
- A signed build trusts the baked public key and the custody of its private key.
Leaking the key allows publishing a malicious manifest and installer.
- The update artifacts are ad-hoc signed and not notarized on macOS. Gatekeeper
cannot independently vouch for the publisher; the in-app hash/signature path
is the relevant check.
- Windows installer signing is not currently performed.
- The download directory is under the system temp directory. Re-verification
detects replacement before install, but local temp-directory manipulation is
still a same-account threat.
- Windows runs the handoff through `cmd.exe`; argument passing is covered by
source-level checks, but every legal character in a user-profile path still
needs real Windows validation.
## LAN sharing
Discovery uses UDP multicast/broadcast/unicast on `239.255.77.88:47888`.
Transfers use a direct TCP connection advertised by the beacon.
The SHSF protocol is **not authenticated, not encrypted and not confidential**.
Anyone on the reachable network can:
- observe beacon metadata such as machine name and platform;
- send a forged offer with an arbitrary sender name and transfer id;
- attempt connections to the receiver's TCP port.
The consent card prevents an unsolicited transfer from being written
automatically. It does **not** prove that the named sender is the real owner of
that machine. Accept files only from people and networks you trust. The batch
window means later files from the same unauthenticated batch id are accepted for
120 seconds without another prompt.
Implemented limits:
- peer table capped at 256, with stale entries removed first;
- transfer header capped at 64 KiB;
- part files are removed after failure;
- sender copies exactly the declared size, so extra source bytes cannot be
mistaken for the acknowledgement;
- receiver reports a transfer error after an accepted transfer fails.
No protocol-level authentication, encryption, rate limiting or maximum transfer
size is implemented. Firewall or OS network policy is the outer boundary.
## External processes and secrets
External tools are invoked with argument arrays through `process::command`,
which also hides console windows on Windows. Paths are not passed through a
shell except where a documented system command requires one; those call sites
must be reviewed individually.
The release private key (`.ed25519`) must remain outside the repository and
outside build artifacts. `SHIFT_RELEASE_KEY` is for the packaging host only;
`SHIFT_UPDATE_PUBKEY` is the public value intended to be baked into builds.
Never paste a private key into an issue, log or CI variable that is visible to
untrusted jobs.
## Platform permissions
- macOS Screen Recording enables capture.
- macOS Files & Folders enables selected output directories.
- macOS Microphone enables recording with audio.
- macOS Local Network enables multicast discovery.
- Windows Firewall must allow private-network traffic for discovery/receive.
Ad-hoc macOS signing can change the code identity on rebuild, causing
permissions to reset. A Developer ID identity would stabilize them but is not
currently part of the release pipeline.
## Reporting
Report a vulnerability privately through the repository host's available
private security channel. Include the affected version, platform, minimal
reproduction, expected/actual behavior and whether a file, LAN peer or update
feed is required. Do not attach a stolen signing key or a working exploit to a
public issue.
If no private channel is configured, contact the maintainers first and share
only enough detail to establish a private transfer method.

View File

@ -0,0 +1,281 @@
# Shift 产品行为规范
本文定义 Shift 0.1.11 可观察到的产品行为与验收口径。实现结构见
[`ARCHITECTURE.md`](ARCHITECTURE.md),安全边界见 [`SECURITY.md`](SECURITY.md)。
若本文与代码冲突,以代码和自动化测试为准,并应同步修正本文。
## 1. 范围
Shift 是一个本地桌面文件工作台,提供:
- 类型感知的格式转换与文件工具;
- 区域/全屏截图与区域录屏;
- 图片标注、只读文本预览、视频播放;
- 英文与简体中文 OCR;
- 局域网设备发现与文件发送;
- 基于 git 通道的应用内更新。
不包含:账号、云端存储、遥测、文件上传、局域网中继、文本就地编辑、
Linux 官方安装包、macOS 公证。
## 2. 产品不变量
1. **源文件只读。** 转换、压缩、旋转、裁剪、标注和 OCR 都写出新文件。
2. **永不覆盖。** 所有输出使用唯一文件名;同名时追加 ` 2`、` 3`……
3. **本地处理。** 转换与 OCR 不发起网络请求;只有更新检查和用户主动发起的
局域网传输会使用网络。
4. **界面只展示可执行操作。** 格式目录决定扇区;后端没有处理器的动作不得出现。
5. **失败必须可见。** 用户操作失败时,界面显示可读文案;不允许静默停在空状态。
6. **已映射错误本地化。** 界面需要稳定识别后端失败时,Rust 返回 `err*` /
`share-*` 等代号,由 `src/i18n.ts` 映射为中英文;原始第三方诊断可以原样透传。
7. **能力如实申报。** 录屏、OCR、转换和平台权限只显示当前后端真正支持的选项。
## 3. 文件识别
识别以扩展名、而非 MIME 或文件内容为准,扩展名不区分大小写。
| 类型 `kind` | 扩展名 |
| --- | --- |
| `image` | `png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif` `heic` `heif` `avif` |
| `video` | `mp4` `mov` `m4v` `avi` `mkv` `webm` |
| `audio` | `mp3` `wav` `m4a` `aiff` `aif` `caf` `flac` `ogg` |
| `pdf` | `pdf` |
| `document` | `docx` `doc` `rtf` `odt` `txt` `md` `html` `htm` `pages` |
| `presentation` | `pptx` `ppt` `key` |
| `spreadsheet` | `xlsx` `xls` `xlsb` `ods` `csv` `tsv` `numbers` |
| `other` | 其他扩展名 |
被识别但当前不解析:`.doc`、`.pages`、`.ppt`、`.key`、`.numbers`。这些文件
只提供编辑/打开/显示,不提供格式扇区。
## 4. 输出命名与位置
### 4.1 普通结果
默认写到源文件同目录:
```text
<stem><suffix>.<ext>
<stem><suffix> 2.<ext>
<stem><suffix> 3.<ext>
```
示例:`report (compressed).pdf`、`photo (rotated) 2.png`。
设置选择「统一收集到一个文件夹」时,结果写入该目录,但唯一命名规则不变。
### 4.2 页面文件夹
PDF 转图片和 PDF 拆分写出:
```text
<stem> pages/Page 001.png
<stem> pages/Page 002.png
<stem> pages 2/Page 001.png
```
页号至少三位;已存在的页面文件夹不会被复用。
### 4.3 截图与录屏
- 截图:`Shift-YYYYMMDD-HHMMSS.png`。同一秒内的第二张为
`Shift-YYYYMMDD-HHMMSS 2.png`。
- 录屏:由当前后端决定扩展名,写入录屏输出目录;唯一命名规则相同。
- 共享接收:写入文件输出目录;冲突时使用 `<stem> 2.<ext>`。
## 5. 转换与工具
### 5.1 格式转换
可见目标必须同时满足:
- 文件类型支持该目标;
- 目标不等于源格式;
- 后端存在处理器。
当前转换目标与引擎以 README 的「Conversions / 格式转换」表为准。缺少外部
依赖时,动作返回可操作错误,说明缺少哪个工具;界面不得提前展示一个明知
不会工作的扇区。
### 5.2 工具
工具包含压缩、移除元数据、旋转、翻转、黑白、50%、裁剪、抠图、合并、拆分、
提取文字、720p、静音、截帧、提取音频、单声道、纯文本和 OCR。
批量规则:
- 2 张以上图片可选择合并为 PDF;
- 2 个以上 PDF 可选择合并为一个 PDF;
- 其他工具逐文件执行。
### 5.3 取消与失败
- 在圆环中心或环外松手不执行动作。
- 一个批次中的失败必须报告;不得把失败结果计入成功数量。
- 转换成功后的结果写入历史库。
## 6. 截图与录屏
### 6.1 截图
1. 截图前检查屏幕录制权限;拒绝时返回可操作错误,不打开黑色遮罩。
2. 区域截图为光标所在显示器的冻结画面。
3. 全屏截图直接抓取光标所在显示器,不显示遮罩。
4. 取消截图恢复先前隐藏的 Shift 窗口。
5. 截图成功后显示结果卡片;卡片创建失败时打开编辑器。
### 6.2 录屏
- macOS:`screencapture -v`,可带麦克风。
- Windows/Linux:FFmpeg 系后端,可选择 15/24/30 fps。
- Wayland:区域录屏使用 `wf-recorder`;X11 使用 FFmpeg `x11grab`。
- 界面只显示后端实现的选项;停止后必须完成文件收尾。
## 7. 编辑器
### 7.1 图片
- 以原始像素尺寸加载到画布。
- 标注工具:矩形、箭头、高亮、打码、马赛克、模糊、序号、图章、裁剪、文字。
- 每种工具使用固定颜色和线宽;不提供逐条标注的样式面板。
- 保存和复制都在画布副本上合成;源文件不变。
- 图片编辑器提供 OCR、复制文字、钉图和保存副本。
- 环形菜单的「编辑 / 标注 / 打码 / 加背景」只负责打开图片编辑器;当前不会
预选具体工具,用户需在编辑器工具栏中选择。
### 7.2 文本
- `txt` `md` `csv` `tsv` `html` `htm` 以只读 `<pre>` 预览。
- 不提供就地编辑;可复制、另存为、打开或显示源文件。
- 文本读取失败时显示错误状态,不留空白预览。
### 7.3 视频与其他文件
- 视频使用 webview 播放器。
- 其他可识别文件显示文件图标和打开入口。
### 7.4 编辑器资源上限
| 数据 | 上限 | 超限行为 |
| --- | --- | --- |
| 非普通文件路径 | — | `errNotAFile` |
| 文本预览 | 8 MiB | `errTextTooLarge` |
| 图片文件 | 64 MiB | `errImageTooLarge` |
| 图片像素 | 40,000,000 | `errImageTooLarge` |
| 编辑后 data URL | 128 MiB | `errEditDataTooLarge` |
| OCR 结果写文本 | 8 MiB | `errTextTooLarge` |
列表预览在图片超限时省略缩略图,但文件本身仍可被识别和操作。
## 8. 历史库
- 由 Rust 写入 `app_data_dir/history.json`。
- 容量上限 300 条;置顶条目不因容量或清理被移除。
- 不存在的未置顶文件在整理时被丢弃。
- 截图、转换结果和收到的文件都进入同一历史库。
- 新条目通过 `history://changed` 与 `app://file-result` 广播。
- 清除历史不删除磁盘上的文件。
## 9. OCR
- 图片:单张识别,实时显示进度,结果可复制或写入编辑器。
- PDF:逐页渲染后识别,合并文本写出 `(OCR).txt`;临时页面目录随后删除。
- 语言:英文与简体中文,使用本地 Tesseract WASM 和模型。
- OCR 过程中不得下载语言包。
## 10. 局域网发送
### 10.1 发现
- UDP 组播:`239.255.77.88:47888`。
- 另外使用定向广播、受限广播和受限 `/24` 单播扫描。
- 信标包含实例 id、机器名、平台和 TCP 接收端口。
- 15 秒未刷新即过期。
- 可见 peer 上限 256;达到上限时先清理过期 peer,仍满则拒绝新 id。
### 10.2 传输
1. 发送端先写 `SHSF`、头部长度和 JSON 头。
2. 接收端弹出确认卡片,默认 45 秒超时。
3. 用户拒绝、关闭卡片或超时:不传文件字节。
4. 用户接受:先回 1 字节同意,再传输正文。
5. 接收端只写临时 `.shift-part`,按头部声明字节数收齐后原子重命名。
6. 发送端只发送声明大小;源文件变短则失败,源文件变长不会多发送。
7. 接收端完整落盘后才回确认;发送端看到确认才报告成功。
多文件批次使用同一批 id,一次确认后在 120 秒窗口内自动接收同批文件。
### 10.3 用户反馈
- 接收成功显示发送者与文件名。
- 接收过程中断显示 `shareReceiveFailed`,不再静默。
- 旧版本缺失批次字段时按单文件处理。
## 11. 更新
### 11.1 清单
- `schema` 必须为 1;缺失、0 或更高版本均拒绝。
- 版本使用 semver,预发布版本低于同号正式版。
- 文件不得包含路径分隔符,只允许 ASCII 字母、数字、`.`、`-`、`_`。
- `size` 必须大于 0;SHA256 必须为 64 位十六进制。
- 清单响应上限 256 KiB。
### 11.2 下载与安装
1. 下载到临时更新目录。
2. 校验文件是普通文件、字节数精确一致、SHA256 匹配。
3. 安装前再次运行相同校验;失败删除安装包。
4. 只有状态为 `ready` 才允许安装。
5. macOS 挂载 DMG 并替换 `.app`;Windows 运行同一 NSIS 安装器。
6. 辅助脚本等待当前进程退出,路径通过进程参数传递。
7. 失败时尽量重新打开旧版本,不留下“应用已退出且未安装”的状态。
8. 丢弃下载会删除实际安装包并清空更新状态。
## 12. 错误与国际化
- 界面需要稳定识别的后端失败以代号返回;新增代号必须同时提供 `en` 与 `zh`。
无法稳定映射的第三方诊断原样显示。
- `translate()` 查不到 key 时原样显示,保留第三方工具诊断信息。
- 单次注册的监听器使用 `tLive()`,避免切换语言后仍显示旧语言。
- 不可用控件使用 disabled 状态和视觉禁用态,不伪装成可点击。
## 13. 平台能力
| 能力 | macOS | Windows | Linux |
| --- | --- | --- | --- |
| 发布安装包 | 通用 DMG | x64 NSIS | 无 |
| 全局拖拽唤起圆环 | AppKit 桥 | Win32 轮询 + 原生拖放 | 无;仅主窗口选择 |
| 截图/录屏 | 原生 | GDI + FFmpeg | `grim` / `wf-recorder` / FFmpeg |
| 文档渲染 | AppKit/PDFKit | Pandoc + Poppler | Pandoc + Poppler |
| 局域网分享 | 支持 | 支持(单实例监听) | 支持 |
| 更新 | 支持 | 支持 | 能检查,但通道无产物 |
Linux 是构建目标,不是已发布产品。
## 14. 验收标准
功能改动至少满足:
```bash
pnpm check
pnpm test
pnpm build
cd src-tauri
cargo fmt --check
cargo test --lib
cargo clippy --all-targets -- -D warnings
cd ..
git diff --check
```
涉及以下行为时还需手工验收:
- 跨机器发现与接收:两台真实设备,允许本地网络/防火墙;
- 截图/录屏权限:macOS 屏幕录制、麦克风、本地网络;
- Windows 拖拽与安装器:真实 Windows,不以交叉编译代替;
- 更新:安装上一版本,执行一次应用内升级;
- Linux 截图/录屏:Wayland 与 X11 各一次。
若某项无法执行,应明确记录“未验证”,不得根据编译通过推断运行时通过。

13
index.html 100644
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f4a261" />
<title>Shift</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,457 @@
import AppKit
import Foundation
import PDFKit
import Vision
import WebKit
func fail(_ message: String) -> Never {
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
exit(1)
}
func hasTextLayer(_ page: PDFPage) -> Bool {
let characters = (page.string ?? "").filter { !$0.isWhitespace }
return characters.count >= 20
}
/// Renders a PDF page on a white background, matching FileFlipper's PDFKit path.
func renderPage(_ page: PDFPage, scale: CGFloat) -> CGImage? {
let box = page.bounds(for: .mediaBox)
let sideways = page.rotation % 180 != 0
let width = Int(((sideways ? box.height : box.width) * scale).rounded())
let height = Int(((sideways ? box.width : box.height) * scale).rounded())
guard width > 0, height > 0,
let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
return nil
}
context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
context.interpolationQuality = .high
context.scaleBy(x: scale, y: scale)
page.draw(with: .mediaBox, to: context)
return context.makeImage()
}
/// Uses Vision, the system's on-device Live Text engine, for scanned pages.
func recognizeText(_ page: PDFPage) -> String {
guard let image = renderPage(page, scale: 3) else { return "" }
let request = VNRecognizeTextRequest()
request.recognitionLevel = .accurate
request.usesLanguageCorrection = true
request.automaticallyDetectsLanguage = true
let preferred = [
"zh-Hans", "zh-Hant", "en-US", "ja-JP", "ko-KR",
"fr-FR", "de-DE", "es-ES", "it-IT", "pt-BR", "ru-RU",
]
let supported = (try? request.supportedRecognitionLanguages()) ?? []
let languages = preferred.filter { supported.contains($0) }
if !languages.isEmpty {
request.recognitionLanguages = languages
}
do {
try VNImageRequestHandler(cgImage: image).perform([request])
} catch {
return ""
}
let pieces = (request.results ?? []).compactMap { observation -> (CGRect, String)? in
guard let text = observation.topCandidates(1).first?.string else { return nil }
return (observation.boundingBox, text)
}
let sorted = pieces.sorted { $0.0.midY > $1.0.midY }
var rows: [[(CGRect, String)]] = []
for piece in sorted {
if let last = rows.last?.first,
abs(last.0.midY - piece.0.midY) < min(last.0.height, piece.0.height) / 2 {
rows[rows.count - 1].append(piece)
} else {
rows.append([piece])
}
}
return rows.map { row in
row.sorted { $0.0.minX < $1.0.minX }.map { $0.1 }.joined(separator: " ")
}.joined(separator: "\n")
}
/// PDF -> editable DOCX through PDFKit and Cocoa's native OOXML writer.
func writeWordDocument(from pdf: URL, to output: URL) throws {
guard let document = PDFDocument(url: pdf) else {
throw NSError(domain: "Shift", code: 1, userInfo: [
NSLocalizedDescriptionKey: "Could not open PDF: \(pdf.path)",
])
}
if document.isLocked {
throw NSError(domain: "Shift", code: 2, userInfo: [
NSLocalizedDescriptionKey: "This PDF is password protected.",
])
}
let combined = NSMutableAttributedString()
for index in 0..<document.pageCount {
guard let page = document.page(at: index) else { continue }
let pageText: NSAttributedString
if hasTextLayer(page), let attributed = page.attributedString {
pageText = attributed
} else {
pageText = NSAttributedString(
string: recognizeText(page),
attributes: [.font: NSFont.systemFont(ofSize: 12)]
)
}
guard pageText.length > 0 else { continue }
if combined.length > 0 {
combined.append(NSAttributedString(string: "\n\u{0C}"))
}
combined.append(pageText)
}
guard combined.length > 0 else {
throw NSError(domain: "Shift", code: 3, userInfo: [
NSLocalizedDescriptionKey: "No text could be read from this PDF.",
])
}
let data = try combined.data(
from: NSRange(location: 0, length: combined.length),
documentAttributes: [.documentType: NSAttributedString.DocumentType.officeOpenXML]
)
try data.write(to: output, options: .atomic)
}
guard (3...5).contains(CommandLine.arguments.count) else {
fail("usage: doc-render <input> <output> [html-base-dir] [--webkit]")
}
let input = URL(fileURLWithPath: CommandLine.arguments[1])
let output = URL(fileURLWithPath: CommandLine.arguments[2])
let app = NSApplication.shared
app.setActivationPolicy(.prohibited)
if output.pathExtension.lowercased() == "docx" {
guard input.pathExtension.lowercased() == "pdf" else {
fail("PDF-to-Word input must be a PDF")
}
do {
try writeWordDocument(from: input, to: output)
exit(0)
} catch {
fail(error.localizedDescription)
}
}
let extensionName = input.pathExtension.lowercased()
var documentType: NSAttributedString.DocumentType?
switch extensionName {
case "docx":
documentType = .officeOpenXML
case "doc":
documentType = .docFormat
case "odt":
documentType = .openDocument
case "rtf":
documentType = .rtf
case "rtfd":
documentType = .rtfd
case "html", "htm":
documentType = .html
case "txt", "md", "markdown":
documentType = .plain
default:
documentType = nil
}
var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [:]
if let documentType {
options[.documentType] = documentType
}
if documentType == .html {
let baseDirectory = CommandLine.arguments.count == 4
? URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
: CommandLine.arguments.count == 5
? URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
: input.deletingLastPathComponent()
options[.baseURL] = baseDirectory
}
if documentType == .html,
CommandLine.arguments.count == 5,
CommandLine.arguments[4] == "--webkit" {
let baseDirectory = URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
let renderer = HTMLRenderer(input: input, output: output, baseDirectory: baseDirectory)
renderer.run()
app.run()
exit(0)
}
let data: Data
do {
data = try Data(contentsOf: input)
} catch {
fail("could not read input: \(error.localizedDescription)")
}
let attributed: NSAttributedString
do {
attributed = try NSAttributedString(data: data, options: options, documentAttributes: nil)
} catch {
fail("could not parse document: \(error.localizedDescription)")
}
/// Fits every picture into the width of the printed page.
///
/// The layout sizes an attachment from the density header inside the file —
/// 72 dpi is assumed when the file carries none — and the cell AppKit builds
/// for an `<img>` honours neither `bounds` nor a CSS width, so a 1600 px
/// screenshot saved at 96 dpi asks for 1200 points and prints as a cropped
/// fragment of itself. A plain `NSTextAttachment` does honour `bounds`, and the
/// print operation then scales it onto the page along with the text. Aspect
/// ratio is kept and nothing is resampled: only the size the layout asks for
/// changes.
func fitAttachments(
_ source: NSAttributedString,
to containerWidth: CGFloat
) -> NSMutableAttributedString {
let mutable = NSMutableAttributedString(attributedString: source)
let wanted = max(1, containerWidth)
mutable.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: mutable.length),
options: []
) { value, range, _ in
guard let old = value as? NSTextAttachment,
let contents = old.fileWrapper?.regularFileContents,
let image = NSImage(data: contents),
image.size.width > wanted else { return }
let scale = wanted / image.size.width
let replacement = NSTextAttachment()
replacement.image = image
replacement.bounds = NSRect(
x: 0,
y: 0,
width: (image.size.width * scale).rounded(),
height: (image.size.height * scale).rounded()
)
mutable.addAttribute(.attachment, value: replacement, range: range)
}
return mutable
}
/// Writes the tall PDF WebKit produces from the page as A4-sized slices.
///
/// `createPDF` keeps the HTML layout as one continuous page. Printing the web
/// view directly can loop indefinitely on documents with positioned elements,
/// so draw the single page into clipped A4 pages instead.
func writePaginatedPDF(_ data: Data, to output: URL) {
let pageSize = CGSize(width: 595.2, height: 841.8)
guard let provider = CGDataProvider(data: data as CFData),
let document = CGPDFDocument(provider),
let source = document.page(at: 1) else {
fail("could not read the rendered web page")
}
let sourceBounds = source.getBoxRect(.mediaBox)
let height = max(1, sourceBounds.height)
let pageCount = max(1, Int(ceil(height / pageSize.height)))
var mediaBox = CGRect(origin: .zero, size: pageSize)
guard let context = CGContext(output as CFURL, mediaBox: &mediaBox, nil) else {
fail("could not create the PDF")
}
for index in 0..<pageCount {
context.beginPDFPage(nil)
context.saveGState()
context.clip(to: mediaBox)
let offset = max(0, height - CGFloat(index + 1) * pageSize.height)
let remaining = max(0, height - CGFloat(index) * pageSize.height)
// Full slices move up through the tall page. The final short slice is
// top-aligned so the trailing whitespace sits below the content.
let translationY = remaining < pageSize.height
? pageSize.height - remaining
: -offset
context.translateBy(x: 0, y: translationY)
context.drawPDFPage(source)
context.restoreGState()
context.endPDFPage()
}
context.closePDF()
}
/// Renders HTML with WebKit instead of flattening it into an attributed
/// string. Quick Look supplies Word page furniture and positioned tables as
/// HTML; AppKit's text conversion reflows that content, which changes the page
/// count and can move a footer onto a page of its own.
final class HTMLRenderer: NSObject, WKNavigationDelegate {
private let input: URL
private let baseDirectory: URL
private let output: URL
private let webView: WKWebView
private var finished = false
init(input: URL, output: URL, baseDirectory: URL) {
self.input = input
self.output = output
self.baseDirectory = baseDirectory
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
self.webView = WKWebView(
frame: NSRect(x: 0, y: 0, width: 595.2, height: 841.8),
configuration: configuration
)
super.init()
webView.navigationDelegate = self
}
func run() {
webView.loadFileURL(input, allowingReadAccessTo: baseDirectory)
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
guard !self.finished else { return }
self.finished = true
fail("could not render HTML before the 30 second deadline")
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard !finished else { return }
webView.evaluateJavaScript(
"""
(() => {
const pageWidth = document.documentElement.clientWidth;
for (const image of document.images) {
if (image.getBoundingClientRect().width > pageWidth) {
image.style.width = `${pageWidth}px`;
image.style.height = "auto";
image.style.maxWidth = "100%";
}
}
let contentBottom = 0;
const range = document.createRange();
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT
);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (!node.textContent.trim()) continue;
range.selectNodeContents(node);
const rect = range.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
contentBottom = Math.max(
contentBottom,
rect.bottom + window.scrollY
);
}
}
for (const element of document.querySelectorAll(
"img, svg, canvas, table, hr"
)) {
const rect = element.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
contentBottom = Math.max(
contentBottom,
rect.bottom + window.scrollY
);
}
}
return {
width: document.documentElement.scrollWidth,
height: Math.max(1, Math.ceil(contentBottom))
};
})()
"""
) { value, error in
guard !self.finished else { return }
self.finished = true
guard error == nil,
let size = value as? [String: Any],
let width = (size["width"] as? NSNumber)?.doubleValue,
let height = (size["height"] as? NSNumber)?.doubleValue,
width > 0,
height > 0 else {
fail("could not measure the rendered HTML")
}
let configuration = WKPDFConfiguration()
configuration.rect = CGRect(x: 0, y: 0, width: width, height: height)
webView.createPDF(configuration: configuration) { result in
switch result {
case .success(let data):
writePaginatedPDF(data, to: self.output)
NSApp.terminate(nil)
case .failure(let error):
fail("could not print HTML: \(error.localizedDescription)")
}
}
}
}
func webView(
_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error
) {
guard !finished else { return }
finished = true
fail("could not load HTML: \(error.localizedDescription)")
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
guard !finished else { return }
finished = true
fail("could not load HTML: \(error.localizedDescription)")
}
}
let printInfo = NSPrintInfo.shared.copy() as! NSPrintInfo
printInfo.paperSize = NSSize(width: 595.2, height: 841.8)
printInfo.topMargin = 42
printInfo.bottomMargin = 42
printInfo.leftMargin = 48
printInfo.rightMargin = 48
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .automatic
printInfo.isHorizontallyCentered = false
printInfo.isVerticallyCentered = false
printInfo.jobDisposition = .save
printInfo.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output
let printable = printInfo.imageablePageBounds
let fitted = fitAttachments(attributed, to: printable.width)
let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: printable.width, height: 1))
textView.isEditable = false
textView.isSelectable = false
textView.drawsBackground = false
textView.textContainerInset = .zero
textView.textContainer?.lineFragmentPadding = 0
textView.textContainer?.widthTracksTextView = true
textView.textContainer?.containerSize = NSSize(
width: printable.width,
height: .greatestFiniteMagnitude
)
textView.textStorage?.setAttributedString(fitted)
guard let layoutManager = textView.layoutManager,
let textContainer = textView.textContainer else {
fail("could not create text layout")
}
layoutManager.ensureLayout(for: textContainer)
let used = layoutManager.usedRect(for: textContainer)
let height = max(1, ceil(used.height))
textView.frame = NSRect(x: 0, y: 0, width: printable.width, height: height)
let operation = NSPrintOperation(view: textView, printInfo: printInfo)
operation.showsPrintPanel = false
operation.showsProgressPanel = false
if !operation.run() {
fail("could not render PDF")
}
guard FileManager.default.fileExists(atPath: output.path) else {
fail("PDF was not created")
}

View File

@ -0,0 +1,145 @@
import AppKit
import Foundation
// Idle, this process has one job: notice the moment the mouse goes down. It used to do
// that 30 times a second, and every tick allocated a CGEvent to read a cursor position
// nothing needs while no button is held. Measured A/B against the 0.1.11 binary on the
// 2026-11 idle review: 20ms of CPU per 6s idle (~0.3%, and 30 wakeups a second,
// forever) against 0ms for the same window now, while 12s of holding the button costs
// 30ms either way. So the gesture is sampled exactly as finely as it ever was and an
// idle Shift stops touching the CPU at all.
//
// 10 Hz while idle delays only the discovery that the button went down. The ring still
// cannot appear until Finder has published the dragged files on the drag pasteboard,
// which needs the drag threshold crossed first, and a press is what moves this timer to
// 30 Hz - so the arming path is unchanged in every respect a user can feel.
let idleInterval = 1.0 / 10.0
let gestureInterval = 1.0 / 30.0
struct Payload: Encodable {
let type: String
let x: Double?
let y: Double?
let files: [String]?
let tools: Bool?
}
func emit(_ payload: Payload) {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(payload),
let line = String(data: data, encoding: .utf8) else { return }
print(line)
fflush(stdout)
}
func cursorLocation() -> NSPoint {
if let event = CGEvent(source: nil) {
return event.location
}
return NSEvent.mouseLocation
}
let dragPasteboard = NSPasteboard(name: .drag)
var mouseWasDown = false
var pickerShown = false
var cancelled = false
var toolsMode = false
var missingDragFiles = 0
var changeCountAtMouseDown = dragPasteboard.changeCount
var lastX = Double.nan
var lastY = Double.nan
func draggedFileURLs() -> [String] {
let objects = dragPasteboard.readObjects(
forClasses: [NSURL.self],
options: [.urlReadingFileURLsOnly: true]
)
return (objects as? [URL])?.map(\.path) ?? []
}
func tick() {
if getppid() == 1 {
exit(0)
}
let mouseDown = NSEvent.pressedMouseButtons & 1 != 0
// Reading the cursor costs a CGEvent allocation, and nothing downstream wants a
// position unless a press is in progress or has just ended. An idle tick is then
// one read of `pressedMouseButtons` and a couple of integer tests.
let pressEnded = mouseWasDown && !mouseDown
let point = mouseDown || pressEnded ? cursorLocation() : NSPoint(x: 0, y: 0)
if !mouseDown {
changeCountAtMouseDown = dragPasteboard.changeCount
cancelled = false
missingDragFiles = 0
}
if pressEnded && pickerShown {
pickerShown = false
emit(Payload(type: "end", x: point.x, y: point.y, files: nil, tools: nil))
}
mouseWasDown = mouseDown
guard mouseDown else { return }
let flags = NSEvent.modifierFlags.intersection(.deviceIndependentFlagsMask)
let shift = flags.contains(.shift)
let option = flags.contains(.option)
if !pickerShown {
guard !cancelled else { return }
guard shift, dragPasteboard.changeCount != changeCountAtMouseDown else { return }
let files = draggedFileURLs()
guard !files.isEmpty else { return }
pickerShown = true
toolsMode = option
lastX = point.x
lastY = point.y
emit(Payload(type: "show", x: point.x, y: point.y, files: files, tools: option))
return
}
if shift && option != toolsMode {
toolsMode = option
emit(Payload(type: "mode", x: point.x, y: point.y, files: nil, tools: option))
}
// Some Finder versions also tear down the pasteboard during cancellation.
// Keep this as a fallback for drag sessions that disappear without a key event.
if draggedFileURLs().isEmpty {
missingDragFiles += 1
if missingDragFiles >= 6 {
pickerShown = false
cancelled = true
emit(Payload(type: "cancel", x: point.x, y: point.y, files: nil, tools: nil))
}
return
}
missingDragFiles = 0
if abs(point.x - lastX) > 0.5 || abs(point.y - lastY) > 0.5 {
lastX = point.x
lastY = point.y
emit(Payload(type: "move", x: point.x, y: point.y, files: nil, tools: nil))
}
}
var timer: Timer?
var timerIsGesture = false
func reschedule(gesture: Bool) {
guard gesture != timerIsGesture || timer == nil else { return }
timerIsGesture = gesture
timer?.invalidate()
let next = Timer(timeInterval: gesture ? gestureInterval : idleInterval, repeats: true) { _ in
let down = NSEvent.pressedMouseButtons & 1 != 0
tick()
// A press changes the pace on the next tick; the timer is replaced rather
// than retuned because NSTimer cannot change its own interval.
if down != timerIsGesture { reschedule(gesture: down) }
}
timer = next
RunLoop.main.add(next, forMode: .common)
}
reschedule(gesture: NSEvent.pressedMouseButtons & 1 != 0)
RunLoop.main.run()

View File

@ -0,0 +1,66 @@
import AppKit
import Foundation
import PDFKit
func fail(_ message: String) -> Never {
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
exit(1)
}
guard CommandLine.arguments.count == 4 else {
fail("usage: pdf-render <input.pdf> <output-dir> <png|jpg|tiff>")
}
let input = URL(fileURLWithPath: CommandLine.arguments[1])
let outputDirectory = URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true)
let extensionName = CommandLine.arguments[3].lowercased()
let fileType: NSBitmapImageRep.FileType
switch extensionName {
case "png": fileType = .png
case "jpg", "jpeg": fileType = .jpeg
case "tif", "tiff": fileType = .tiff
default: fail("unsupported image format: \(extensionName)")
}
try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
guard let document = PDFDocument(url: input) else {
fail("could not open PDF: \(input.path)")
}
for index in 0..<document.pageCount {
guard let page = document.page(at: index) else { continue }
let bounds = page.bounds(for: .mediaBox)
// Render into an explicit pixel buffer. NSImage.lockFocus() follows the
// Mac's Retina backing scale, which doubled both dimensions and made
// image-heavy PDF-to-Word conversions needlessly slow.
let scale = min(2.0, 1800.0 / max(bounds.width, bounds.height, 1.0))
let width = max(1, Int((bounds.width * scale).rounded()))
let height = max(1, Int((bounds.height * scale).rounded()))
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
fail("could not create page canvas")
}
context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
context.scaleBy(x: CGFloat(width) / bounds.width, y: CGFloat(height) / bounds.height)
page.draw(with: .mediaBox, to: context)
guard let image = context.makeImage(),
let data = NSBitmapImageRep(cgImage: image).representation(
using: fileType,
properties: [:]
) else {
fail("could not render page \(index + 1)")
}
let output = outputDirectory.appendingPathComponent(
String(format: "Page %03d.%@", index + 1, extensionName == "jpeg" ? "jpg" : extensionName)
)
try data.write(to: output)
}

40
package.json 100644
View File

@ -0,0 +1,40 @@
{
"name": "shift",
"private": true,
"version": "0.1.13",
"type": "module",
"scripts": {
"prepare:ocr": "bash scripts/prepare-ocr-assets.sh",
"predev": "pnpm prepare:ocr",
"prebuild": "pnpm prepare:ocr",
"dev": "vite --port 1420 --strictPort",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri",
"check": "tsc --noEmit",
"test": "node --experimental-strip-types --test src/lib/*.test.ts",
"mac:drag-bridge": "bash scripts/build-macos-drag-bridge.sh",
"mac:release": "bash scripts/build-macos-release.sh"
},
"dependencies": {
"@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-clipboard-manager": "^2.5.0",
"@tauri-apps/plugin-dialog": "^2.8.3",
"@tauri-apps/plugin-global-shortcut": "^2.4.1",
"@tauri-apps/plugin-opener": "^2.7.2",
"@tesseract.js-data/chi_sim": "^1.0.0",
"@tesseract.js-data/eng": "^1.0.0",
"lucide-react": "^0.468.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"tesseract.js": "^7.0.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.12.3",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@vitejs/plugin-react": "^4.4.0",
"typescript": "~5.8.3",
"vite": "^6.3.0"
}
}

1335
pnpm-lock.yaml 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="sky" x1="64" y1="32" x2="462" y2="488" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFCF8A"/>
<stop offset="0.52" stop-color="#FF8A4C"/>
<stop offset="1" stop-color="#D56FD7"/>
</linearGradient>
<radialGradient id="fruit" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(194 202) rotate(52) scale(156)">
<stop stop-color="#FFA73D"/>
<stop offset="0.7" stop-color="#FF6B1A"/>
<stop offset="1" stop-color="#C93C0D"/>
</radialGradient>
<filter id="soft" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#71250B" flood-opacity="0.24"/>
</filter>
</defs>
<rect width="512" height="512" rx="112" fill="url(#sky)"/>
<path d="M382 56C352 124 338 180 342 246C346 310 376 366 424 414" stroke="#7D4A25" stroke-width="20" stroke-linecap="round"/>
<path d="M376 146C322 118 292 150 280 188" stroke="#7D4A25" stroke-width="13" stroke-linecap="round"/>
<path d="M363 213C312 190 281 217 273 253" stroke="#7D4A25" stroke-width="12" stroke-linecap="round"/>
<path d="M403 280C356 257 326 282 318 318" stroke="#7D4A25" stroke-width="12" stroke-linecap="round"/>
<path d="M358 120C324 84 278 88 255 107C283 122 316 131 358 120Z" fill="#41743B"/>
<path d="M344 176C311 143 273 151 255 172C286 184 311 188 344 176Z" fill="#4E8444"/>
<path d="M384 243C349 214 315 222 299 242C326 252 351 254 384 243Z" fill="#3E7038"/>
<g filter="url(#soft)">
<circle cx="177" cy="190" r="75" fill="url(#fruit)"/>
<circle cx="307" cy="184" r="67" fill="url(#fruit)"/>
<circle cx="235" cy="314" r="78" fill="url(#fruit)"/>
<circle cx="354" cy="310" r="61" fill="url(#fruit)"/>
<circle cx="140" cy="315" r="57" fill="url(#fruit)"/>
</g>
<circle cx="150" cy="163" r="18" fill="#FFD28E" fill-opacity="0.65"/>
<circle cx="284" cy="158" r="15" fill="#FFD28E" fill-opacity="0.6"/>
<circle cx="210" cy="288" r="18" fill="#FFD28E" fill-opacity="0.58"/>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

3
public/tesseract/worker.min.js vendored 100644

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,245 @@
#!/usr/bin/env python3
"""Draw every Shift icon from one mark.
scripts/build-icons.py # tray PNG + assets/icon.svg
scripts/build-icons.py --tauri # ... then the full platform set
Both icons are the same drawing — a six-wedge ring around a hub with a plus
punched out of it, which is the radial ring the app itself paints — and they
differ only in what is allowed to be on screen behind it. The shell tints the
tray mark, so that file carries no colour at all: its only real channel is
alpha, because macOS renders a *template* image black or white to match the
menu bar and the Windows notification area simply shrinks whatever it is
given. At 16-18 px the old colour wheel was a blob, which is what "use a
black/white system icon" was about. The app icon is the same mark with its
colour turned on, because a Dock tile is not tinted by anything and needs a
ground of its own; it is flat and warm, and deliberately not a second
gradient, since the layered rainbow treatment is what made the two icons look
like they belonged to different products.
The geometry lives once, in the constants below. The tray file is rasterised
here; the app icon is written as an SVG master that `tauri icon` turns into
the .icns / .ico / Windows tiles / android / ios set, which is worth using
over hand-rolling: its icon.icns and icon.ico carry the same size ladders the
repository already ships, verified against the committed files.
Only Pillow is needed for the default run.
"""
import argparse
import math
import pathlib
import subprocess
import sys
from PIL import Image, ImageDraw
# --- the mark, in units where the wedge ring's outer radius is 38 -----------
# These are the numbers the ring is specified in, not a size: each consumer
# scales them. Changing GAP or PLUS_BAR changes both icons together, which is
# the whole point of this file.
OUTER = 38.0 # wedge ring, outer radius
INNER = 21.0 # wedge ring, inner radius
HUB = 12.6 # solid centre disc the plus is cut out of
GAP = 5.2 # degrees of air between wedges
PLUS_ARM = 7.8 # half-length of the cross cut out of the hub
PLUS_BAR = 2.8 # half-thickness of that cross
WHEEL = 2 * OUTER # the mark's own diameter in these units
# --- tray ------------------------------------------------------------------
TRAY_EDGE = 88 # tray-icon renders the image 18 pt tall, so this is > 4x
TRAY_SS = 4 # supersample on top of TRAY_EDGE for smooth wedge edges
TRAY_TINT = (128, 128, 128) # unread by macOS; only a base for Windows
# --- app icon --------------------------------------------------------------
MASTER = 1024 # the master canvas `tauri icon` downsamples from
TILE = 820 # tile edge; the committed icon.png is 410 of 512, i.e. 0.801
TILE_CORNER = TILE * 228 / 1024 # same 0.222 corner ratio as the committed set
WHEEL_R = 326 # wheel radius in master units
# The app icon is the tray mark with its colour turned on: one warm ground, one
# cream mark, and the plus left as a hole in the mark so the ground shows through
# it. That is the same figure/ground relationship the tray file has, which is what
# "consistent design" meant in the request — the tray must be untinted because the
# shell colours it, and a Dock tile needs a ground of its own.
TILE_INK = "#FF6B35" # the orange this project's own master already carried
MARK_INK = "#FFF4EA" # the cream every panel in the app is drawn on
ROOT = pathlib.Path(__file__).resolve().parent.parent
def ring_segment(center, radius_out, radius_in, start, stop):
"""Corners of a filled annular sector, outer arc forward then inner back."""
steps = max(2, int(stop - start) + 1)
arc = lambda radius, index: (
center + radius * math.cos(math.radians(start + (stop - start) * index / steps)),
center + radius * math.sin(math.radians(start + (stop - start) * index / steps)),
)
points = [arc(radius_out, i) for i in range(steps + 1)]
points += [arc(radius_in, i) for i in range(steps, -1, -1)]
return points
def punch_cross(draw, center, scale):
"""Clear the plus out of whatever has been drawn, leaving the ground to show."""
width = int(PLUS_BAR * scale)
draw.line(
[center - PLUS_ARM * scale, center, center + PLUS_ARM * scale, center],
fill=0,
width=width,
)
draw.line(
[center, center - PLUS_ARM * scale, center, center + PLUS_ARM * scale],
fill=0,
width=width,
)
def render_tray_mask():
"""The mark as an alpha mask at TRAY_EDGE, drawn at TRAY_SS for one smooth pass."""
canvas = TRAY_EDGE * TRAY_SS
center = canvas / 2
mask = Image.new("L", (canvas, canvas), 0)
draw = ImageDraw.Draw(mask)
for wedge in range(6):
start = -90 + wedge * 60 + GAP / 2
stop = -90 + (wedge + 1) * 60 - GAP / 2
draw.polygon(
ring_segment(center, OUTER * TRAY_SS, INNER * TRAY_SS, start, stop), fill=255
)
hub = HUB * TRAY_SS
draw.ellipse([center - hub, center - hub, center + hub, center + hub], fill=255)
punch_cross(draw, center, TRAY_SS)
return mask.resize((TRAY_EDGE, TRAY_EDGE), Image.LANCZOS)
def _shown(path: pathlib.Path) -> str:
# Repo-relative when it is inside the repo; `--tray-out` may point anywhere.
path = path.resolve()
try:
return str(path.relative_to(ROOT))
except ValueError:
return str(path)
def build_tray(path: pathlib.Path) -> None:
icon = Image.new("RGBA", (TRAY_EDGE, TRAY_EDGE), TRAY_TINT + (0,))
icon.putalpha(render_tray_mask())
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(_png_bytes(icon))
print(f"wrote {_shown(path)} ({TRAY_EDGE}x{TRAY_EDGE}, alpha-only monochrome mark)")
def _png_bytes(image: Image.Image) -> bytes:
import io
buffer = io.BytesIO()
image.save(buffer, format="PNG")
return buffer.getvalue()
def build_master_svg() -> str:
"""The app icon: the tray mark, with its colour turned on.
What makes the two icons the same drawing is the geometry and the rule
about how it is filled — six wedges, the same angular gaps, the same ring
and hub radii, the plus punched out of the hub as negative space, and flat
solid fills throughout. Colour is not the thing they have to agree about,
and the tray is the one that cannot have any: macOS tints a template image
and the Windows notification area just shrinks what it is given. A Dock
tile sits on the user's wallpaper with nothing behind it, so it needs a
ground of its own and gets to be warm.
Two flat colours and nothing else. No gradient, no drop shadow, no radial
shine and no per-wedge pastel tint: that layered treatment is a different
visual language, and it is what made the old rainbow tile and the crisp
mark read as two unrelated products. The hues are the app's own rather than
invented for the icon — `#FF6B35` is the orange this project's master
already carried and `#FFF4EA` is the cream its panels are drawn on — and
the plus stays a hole rather than a second colour, so the mark sits on the
ground exactly the way it sits on the menu bar.
The plus is drawn in the tile's own colour instead of cut through to
transparency: on a Dock tile the two read identically, and a real hole
would be filled in by the platform wherever `tauri icon` composes the iOS
and Android layers.
The wheel is sized to 652 of the 820 tile because that is the ratio the
icon this replaces was drawn at (r=326 in an 820 tile), so the new mark
holds the same optical weight in the Dock rather than arriving larger.
"""
scale = WHEEL_R / OUTER
center = MASTER / 2
offset = (MASTER - TILE) / 2
bar = PLUS_BAR * scale
arm = PLUS_ARM * scale
wedges = []
for wedge in range(6):
start = -90 + wedge * 60 + GAP / 2
stop = -90 + (wedge + 1) * 60 - GAP / 2
outer_start = _point(center, OUTER * scale, start)
outer_end = _point(center, OUTER * scale, stop)
inner_start = _point(center, INNER * scale, stop)
inner_end = _point(center, INNER * scale, start)
wedges.append(
f' <path d="M{outer_start} A{OUTER * scale:.2f} {OUTER * scale:.2f} 0 0 1 '
f'{outer_end} L{inner_start} A{INNER * scale:.2f} {INNER * scale:.2f} 0 0 0 '
f'{inner_end} Z"/>'
)
return (
f'<svg width="{MASTER}" height="{MASTER}" viewBox="0 0 {MASTER} {MASTER}" '
'fill="none" xmlns="http://www.w3.org/2000/svg">\n'
f" <rect x=\"{offset:.0f}\" y=\"{offset:.0f}\" width=\"{TILE}\" height=\"{TILE}\" "
f'rx="{TILE_CORNER:.2f}" fill="{TILE_INK}"/>\n'
f' <g fill="{MARK_INK}">\n' + "\n".join(wedges) + "\n </g>\n"
f' <circle cx="{center:.0f}" cy="{center:.0f}" r="{HUB * scale:.2f}" fill="{MARK_INK}"/>\n'
f' <path d="M{center - arm:.2f} {center:.0f}H{center + arm:.2f}'
f'M{center:.0f} {center - arm:.2f}V{center + arm:.2f}" '
f'stroke="{TILE_INK}" stroke-width="{bar:.2f}"/>\n'
"</svg>\n"
)
def _point(center, radius, angle):
return (
f"{center + radius * math.cos(math.radians(angle)):.2f} "
f"{center + radius * math.sin(math.radians(angle)):.2f}"
)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--tray-out",
type=pathlib.Path,
default=ROOT / "src-tauri" / "icons" / "tray-template.png",
)
parser.add_argument("--master-out", type=pathlib.Path, default=ROOT / "assets" / "icon.svg")
parser.add_argument(
"--tauri",
action="store_true",
help="also run `tauri icon` on the master to regenerate the platform set",
)
args = parser.parse_args()
build_tray(args.tray_out)
args.master_out.parent.mkdir(parents=True, exist_ok=True)
args.master_out.write_text(build_master_svg(), encoding="utf-8")
print(f"wrote {_shown(args.master_out)} (flat two-colour master)")
if args.tauri:
# Full-bleed would be wrong: `tauri icon` scales the master rather than
# padding it, so the tile has to sit inside the canvas the way it does
# in the committed set. That is why the rect above is inset.
subprocess.run(
["pnpm", "tauri", "icon", str(args.master_out)], check=True, cwd=ROOT
)
# The brand mark in the window title bars is the same file at 26 px, so
# it is a copy of the icon rather than a second drawing to keep in step.
brand = ROOT / "public" / "shift-icon.png"
brand.write_bytes((ROOT / "src-tauri" / "icons" / "icon.png").read_bytes())
print(f"wrote {_shown(brand)} (same mark, shown at 26 px in the title bar)")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
root_dir="$(cd "$(dirname "$0")/.." && pwd)"
host_triple="$(rustc -vV | awk '/^host:/ { print $2 }')"
out_dir="$root_dir/src-tauri/binaries"
out_file="$out_dir/drag-bridge-$host_triple"
pdf_out_file="$out_dir/pdf-render-$host_triple"
doc_out_file="$out_dir/doc-render-$host_triple"
tmp_dir="$(mktemp -d)"
trap 'find "$tmp_dir" -type f -delete; rmdir "$tmp_dir"' EXIT
mkdir -p "$out_dir"
for arch in arm64 x86_64; do
swiftc \
-O \
-target "$arch-apple-macosx13.0" \
-framework AppKit \
"$root_dir/native/macos/drag-bridge.swift" \
-o "$tmp_dir/drag-bridge-$arch"
swiftc \
-O \
-target "$arch-apple-macosx13.0" \
-framework AppKit \
-framework PDFKit \
"$root_dir/native/macos/pdf-render.swift" \
-o "$tmp_dir/pdf-render-$arch"
swiftc \
-O \
-target "$arch-apple-macosx13.0" \
-framework AppKit \
-framework PDFKit \
-framework Vision \
-framework WebKit \
"$root_dir/native/macos/doc-render.swift" \
-o "$tmp_dir/doc-render-$arch"
done
lipo -create \
"$tmp_dir/drag-bridge-arm64" \
"$tmp_dir/drag-bridge-x86_64" \
-output "$out_dir/drag-bridge-universal-apple-darwin"
lipo -create \
"$tmp_dir/pdf-render-arm64" \
"$tmp_dir/pdf-render-x86_64" \
-output "$out_dir/pdf-render-universal-apple-darwin"
lipo -create \
"$tmp_dir/doc-render-arm64" \
"$tmp_dir/doc-render-x86_64" \
-output "$out_dir/doc-render-universal-apple-darwin"
cp "$tmp_dir/drag-bridge-arm64" "$out_dir/drag-bridge-aarch64-apple-darwin"
cp "$tmp_dir/pdf-render-arm64" "$out_dir/pdf-render-aarch64-apple-darwin"
cp "$tmp_dir/doc-render-arm64" "$out_dir/doc-render-aarch64-apple-darwin"
cp "$tmp_dir/drag-bridge-x86_64" "$out_dir/drag-bridge-x86_64-apple-darwin"
cp "$tmp_dir/pdf-render-x86_64" "$out_dir/pdf-render-x86_64-apple-darwin"
cp "$tmp_dir/doc-render-x86_64" "$out_dir/doc-render-x86_64-apple-darwin"
if [[ "$host_triple" == "aarch64-apple-darwin" ]]; then
cp "$tmp_dir/drag-bridge-arm64" "$out_file"
cp "$tmp_dir/pdf-render-arm64" "$pdf_out_file"
cp "$tmp_dir/doc-render-arm64" "$doc_out_file"
else
cp "$tmp_dir/drag-bridge-x86_64" "$out_file"
cp "$tmp_dir/pdf-render-x86_64" "$pdf_out_file"
cp "$tmp_dir/doc-render-x86_64" "$doc_out_file"
fi
chmod +x "$out_file" "$pdf_out_file" \
"$doc_out_file" \
"$out_dir/drag-bridge-aarch64-apple-darwin" \
"$out_dir/pdf-render-aarch64-apple-darwin" \
"$out_dir/doc-render-aarch64-apple-darwin" \
"$out_dir/drag-bridge-x86_64-apple-darwin" \
"$out_dir/pdf-render-x86_64-apple-darwin" \
"$out_dir/doc-render-x86_64-apple-darwin" \
"$out_dir/drag-bridge-universal-apple-darwin" \
"$out_dir/pdf-render-universal-apple-darwin" \
"$out_dir/doc-render-universal-apple-darwin"
echo "Built $out_file"
echo "Built $pdf_out_file"
echo "Built $doc_out_file"
echo "Built universal macOS sidecars"

View File

@ -0,0 +1,59 @@
#!/bin/bash
# Build the universal macOS DMG and copy it to the versioned release name.
#
# scripts/build-macos-release.sh [--skip-build]
#
# Produces artifacts/Shift-<version>-macOS-universal.dmg.
set -euo pipefail
cd "$(dirname "$0")/.."
# The Homebrew `cargo` on this host uses the non-rustup "system" toolchain, which
# cannot build the second slice of a universal binary.
export PATH="$HOME/.cargo/bin:$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
# Keep the same trust anchor in both platform builds when the release key is
# available. A keyless build still installs updates, but cannot verify the
# manifest signature.
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
SKIP_BUILD=0
usage() { echo "usage: $0 [--skip-build]" >&2 && exit 2; }
while [ $# -gt 0 ]; do
case "$1" in
--skip-build) SKIP_BUILD=1 ;;
*) usage ;;
esac
shift
done
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
BUNDLE_DIR="src-tauri/target/universal-apple-darwin/release/bundle"
APP="$BUNDLE_DIR/macos/Shift.app"
OUTPUT="artifacts/Shift-$VERSION-macOS-universal.dmg"
if [ "$SKIP_BUILD" != "1" ]; then
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
pnpm mac:drag-bridge
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
fi
test -d "$APP"
DMG=$(find "$BUNDLE_DIR/dmg" -maxdepth 1 -type f -name '*.dmg' -print -quit)
test -n "$DMG"
codesign --verify --deep --strict "$APP"
hdiutil verify "$DMG" >/dev/null
mkdir -p artifacts
cp -f "$DMG" "$OUTPUT"
hdiutil verify "$OUTPUT" >/dev/null
echo "== macOS release =="
ls -lh "$OUTPUT"

View File

@ -0,0 +1,201 @@
#!/bin/bash
# Build the Windows x64 release installer from current source.
#
# scripts/build-windows-release.sh [--skip-build]
#
# Produces artifacts/Shift-Setup-<version>-win-x64.exe and refreshes
# artifacts/SHA256SUMS.txt. Cross-compiled on macOS with cargo-xwin; makensis is
# the Homebrew formula of the same name. Windows ARM64 runs this x64 package
# through the update manifest's normal `windows` fallback.
set -euo pipefail
cd "$(dirname "$0")/.."
export PATH="$HOME/.cargo/bin:$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:/opt/homebrew/opt/llvm/bin:$PATH"
export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
export RUSTC="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/rustc"
ROOT="$PWD"
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
SKIP_BUILD=0
usage() { echo "usage: $0 [--skip-build]" >&2 && exit 2; }
while [ $# -gt 0 ]; do
case "$1" in
--skip-build) SKIP_BUILD=1 ;;
*) usage ;;
esac
shift
done
# 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
if [ "$SKIP_BUILD" != "1" ]; then
echo "== frontend (Windows target: chrome105) =="
TAURI_ENV_PLATFORM=windows pnpm build
fi
ARCH=x64
TARGET=x86_64-pc-windows-msvc
PE_MACHINE=8664
EXE="src-tauri/target/$TARGET/release/shift.exe"
INSTALLER="artifacts/Shift-Setup-$VERSION-win-x64.exe"
NOTES="artifacts/README-Windows-x64.txt"
if [ "$SKIP_BUILD" != "1" ]; then
echo "== rust cross build ($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 (x64) =="
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]
for extra in ("index.html", "view=radial"):
if extra.encode() not in exe:
missing.append(extra)
# The runtime hint is rendered by the webview, so it must be present in the
# asset bundle even though the PE itself does not keep readable UTF-8 strings.
asset_text = "".join(
path.read_text(encoding="utf-8") for path in pathlib.Path("dist/assets").iterdir()
)
required = [
"以下是本机安装组件的情况,未安装的组件请点击安装。",
"正在转换第 {done}/{total} 页…",
"正在生成文档…",
]
missing.extend(text for text in required if text not in asset_text)
old = "以下结果来自当前这台机器"
if old in asset_text:
sys.exit(f"stale frontend copy is still embedded: {old}")
if missing:
sys.exit(f"frontend not embedded, missing: {missing}")
print(f"embedded ok: {len(exe):,} byte exe carries the current dist/assets")
PY
echo "== windows notes (x64) =="
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
python3 - "$STAGE" "$VERSION" <<PY
import pathlib, sys
stage = pathlib.Path(sys.argv[1])
version = sys.argv[2]
text = f"""Shift {version} - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。当前 Windows 10/11 通常已内置;如果 Shift
启动后窗口空白或无法打开,请从微软官方页面安装:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。只有在“运行组件”里安装外部工具时,
Windows 才可能弹出 UAC 确认。
安装
----
1. 运行 Shift-Setup-{version}-win-x64.exe,默认安装到
%LOCALAPPDATA%\\Programs\\Shift,并创建开始菜单与桌面快捷方式。
2. 这是未签名构建。若 SmartScreen 显示“Windows 已保护你的电脑”,请选择
“更多信息” > “仍要运行”。
3. 卸载请在“设置 > 应用”中移除 Shift,无需手动删除文件。
4. 首次启动若 Windows 安全中心询问网络访问,请允许 Shift 访问“专用网络”。
如果之前拒绝过,请到“Windows 安全中心 > 防火墙和网络保护 > 允许应用通过
防火墙”,勾选 Shift 的专用网络权限;否则“发送到设备”无法接收其它终端的信标。
运行组件
--------
打开 Shift 主窗口,进入“设置” > “运行组件”:
- 首次进入该页会自动检测,之后只在你点击“重新检测”时重新扫描;
扫描范围包括 PATH、WinGet、Chocolatey、Scoop 与常见安装目录。
- 页面显示本机实际使用的组件、版本、路径与来源。
- 缺失组件旁有“安装”,通过 Microsoft WinGet 安装,界面不会阻塞,
完成后自动重新检测。
WinGet 包映射:
- Pandoc: JohnMacFarlane.Pandoc
- Typst: Typst.Typst
- FFmpeg: Gyan.FFmpeg
- Poppler: oschwartz10612.Poppler
- ImageMagick: ImageMagick.ImageMagick
如果没有 WinGet,界面会给出微软官方安装说明入口。Shift 不会从第三方站点
下载运行库,也不会卸载或覆盖你已有的工具。
校验
----
PowerShell:
Get-FileHash .\\Shift-Setup-{version}-win-x64.exe -Algorithm SHA256
"""
(stage / "README-Windows.txt").write_bytes(text.replace("\n", "\r\n").encode("utf-8"))
PY
echo "== NSIS installer (x64) =="
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
mv "$STAGE/README-Windows.txt" "$NOTES"
rm -rf "$STAGE"
echo "== checksums =="
python3 - "$VERSION" <<PY
import hashlib, pathlib, sys
version = sys.argv[1]
artifacts = pathlib.Path("artifacts")
preferred = [
f"Shift-{version}-macOS-universal.dmg",
f"Shift-Setup-{version}-win-x64.exe",
"README-Windows-x64.txt",
"README-macOS-universal.txt",
]
names = [name for name in preferred if (artifacts / name).is_file()]
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 artifacts/

View File

@ -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"]

View File

@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
root_dir="$(cd "$(dirname "$0")/.." && pwd)"
target="$root_dir/public/tesseract"
core_source="$root_dir/node_modules/.pnpm/tesseract.js-core@7.0.0/node_modules/tesseract.js-core"
mkdir -p "$target/lang" "$target/core"
cp "$root_dir/node_modules/tesseract.js/dist/worker.min.js" "$target/worker.min.js"
cp "$core_source"/tesseract-core*.wasm.js "$target/core/"
cp "$core_source"/tesseract-core*.wasm "$target/core/"
cp -L "$root_dir/node_modules/@tesseract.js-data/eng/4.0.0_best_int/eng.traineddata.gz" "$target/lang/"
cp -L "$root_dir/node_modules/@tesseract.js-data/chi_sim/4.0.0_best_int/chi_sim.traineddata.gz" "$target/lang/"

View File

@ -0,0 +1,195 @@
#!/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]
#
# The two release installers in artifacts/ are 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|--key|--branch)
if [ "$#" -lt 2 ] || [ -z "${2:-}" ]; then
echo "$1 needs a value" >&2
exit 2
fi
case "$1" in
--notes) NOTES_FILE="$2" ;;
--key) KEY_FILE="$2" ;;
--branch) BRANCH="$2" ;;
esac
shift 2
;;
--dry-run) DRY_RUN=1; shift ;;
--no-push) NO_PUSH=1; shift ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
[ -n "$BRANCH" ] || { echo "--branch cannot be empty" >&2; exit 2; }
[ -z "$NOTES_FILE" ] || [ -f "$NOTES_FILE" ] || {
echo "notes file not found: $NOTES_FILE" >&2
exit 2
}
[ -z "$KEY_FILE" ] || [ -f "$KEY_FILE" ] || {
echo "release key not found: $KEY_FILE" >&2
exit 2
}
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 ""
# The channel intentionally has exactly two installers. Versioned, exact names keep
# a stale DMG or an old architecture from slipping into a new release. Supporting
# files such as the checksums and readmes still travel with the branch.
PATTERNS = [
("macos", rf"^Shift-{re.escape(version)}-macOS-universal\.dmg$"),
("windows", rf"^Shift-Setup-{re.escape(version)}-win-x64\.exe$"),
]
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, pattern in PATTERNS:
match = next((name for name in candidates if re.search(pattern, name)), None)
if not match:
sys.exit(
f"missing installer for {platform} at version {version}; expected "
f"Shift-{version}-macOS-universal.dmg and "
f"Shift-Setup-{version}-win-x64.exe"
)
hash_value, size = digest(match)
manifest["artifacts"][platform] = {"file": match, "sha256": hash_value, "size": size}
chosen.append(match)
unexpected = [
name
for name in candidates
if re.search(r"\.(dmg|exe|msi|pkg|zip|AppImage|deb)$", name, re.IGNORECASE)
and name not in chosen
]
if unexpected:
sys.exit(
"only the two versioned installers may be published; remove: "
+ ", ".join(unexpected)
)
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"

View File

@ -0,0 +1,104 @@
#!/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):
"""Hex of the public half of a key file, whichever half was handed over.
A raw ed25519 private key is 32 bytes and so is its public half, so the two
cannot be told apart by content. Baking the private bytes as if they were a
public key produces a key no signature ever verifies against, and the build
accepts it without complaint, so the mistake only surfaces on a user's
machine as "this build cannot verify the manifest". Anything not named
``*.pub`` is therefore read as the private key it came from and expanded.
"""
if path.suffix == ".pub":
key = Ed25519PublicKey.from_public_bytes(path.read_bytes())
else:
key = Ed25519PrivateKey.from_private_bytes(path.read_bytes()).public_key()
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:]))

View File

@ -0,0 +1,205 @@
; Shift - Windows installer (NSIS 3, per-user, no administrator rights).
;
; makensis -DSHIFT_EXE=<path> -DLICENSE_FILE=<path> -DNOTICES_FILE=<path> \
; -DREADME_FILE=<path> -DICONS_DIR=<path> -DOUT_FILE=<path> \
; -DVERSION=0.1.8 -DEST_SIZE_KB=<kb> \
; scripts/windows-installer.nsi
;
; The installer accepts native x64 Windows only. Windows on ARM is served by the
; same x64 build through its compatibility layer and the update manifest fallback.
;
; Install scope is deliberately per-user: Shift writes only to HKCU and its own folder.
!include "MUI2.nsh"
!include "LogicLib.nsh"
!include "WinVer.nsh"
!include "x64.nsh"
!ifndef VERSION
!error "VERSION is required (for example -DVERSION=0.1.0)"
!endif
!ifndef SHIFT_EXE
!error "SHIFT_EXE is required"
!endif
!ifndef OUT_FILE
!define OUT_FILE "Shift-Setup.exe"
!endif
!ifndef EST_SIZE_KB
!define EST_SIZE_KB "40000"
!endif
!define APP_NAME "Shift"
!define APP_ID "app.nex.shift"
!define APP_VERSION "${VERSION}"
!define PUBLISHER "Shift Contributors"
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APP_ID}"
!define WEBVIEW_KEY "SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
Unicode true
Name "${APP_NAME}"
OutFile "${OUT_FILE}"
InstallDir "$LOCALAPPDATA\Programs\${APP_NAME}"
InstallDirRegKey HKCU "Software\${APP_NAME}" "InstallDirectory"
RequestExecutionLevel user
SetCompressor /SOLID lzma
!define /date BUILD_YEAR "%Y"
VIProductVersion "${APP_VERSION}.0"
VIAddVersionKey ProductName "${APP_NAME}"
VIAddVersionKey ProductVersion "${APP_VERSION}"
VIAddVersionKey CompanyName "${PUBLISHER}"
VIAddVersionKey LegalCopyright "Copyright ${BUILD_YEAR} ${PUBLISHER}"
VIAddVersionKey FileDescription "${APP_NAME} installer"
VIAddVersionKey FileVersion "${APP_VERSION}.0"
VIAddVersionKey OriginalFilename "Shift-Setup-${VERSION}-win-x64.exe"
!define MUI_ICON "${ICONS_DIR}\icon.ico"
!define MUI_UNICON "${ICONS_DIR}\icon.ico"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_RUN "$INSTDIR\shift.exe"
!define MUI_FINISHPAGE_RUN_TEXT "$(run_shift)"
!define MUI_FINISHPAGE_SHOWREADME
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(read_me)"
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION show_readme
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "SimpChinese"
LangString run_shift 1033 "Launch Shift when the installer closes."
LangString run_shift 2052 "安装完成后启动 Shift。"
LangString read_me 1033 "Open the Windows notes."
LangString read_me 2052 "打开 Windows 使用说明。"
LangString close_shift 1033 "${APP_NAME} is running and has to close before it can be updated.$\r$\n$\r$\nClick OK to close it now, or Cancel to leave things as they are."
LangString close_shift 2052 "${APP_NAME} 正在运行,需要先退出才能更新。$\r$\n$\r$\n点击“确定”立即退出,点击“取消”保持现状。"
LangString webview_missing 1033 "${APP_NAME} draws its windows with Microsoft Edge WebView2, which this installer did not find.$\r$\n$\r$\nIf Shift opens a blank window or does not start, install the WebView2 Evergreen Runtime from Microsoft and launch Shift again.$\r$\n$\r$\nhttps://developer.microsoft.com/microsoft-edge/webview2/"
LangString webview_missing 2052 "${APP_NAME} 的界面依赖 Microsoft Edge WebView2,安装程序没有检测到它。$\r$\n$\r$\n如果 Shift 启动后窗口空白或无法打开,请从微软官网安装 WebView2 Evergreen Runtime,然后重新启动 Shift。$\r$\n$\r$\nhttps://developer.microsoft.com/microsoft-edge/webview2/"
Var ReadmePath
Function .onInit
${IfNot} ${AtLeastWin10}
MessageBox MB_OK|MB_ICONSTOP "${APP_NAME} needs Windows 10 or later."
Abort
${EndIf}
${IfNot} ${IsNativeAMD64}
MessageBox MB_OK|MB_ICONSTOP "This build is for 64-bit Windows (x64)."
Abort
${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.
; A silent install comes from Shift itself, which has already said it is about to
; restart, and nobody is there to answer a box: go straight to the taskkill.
${If} ${FileExists} "$INSTDIR\shift.exe"
FindWindow $0 "" "${APP_NAME}"
${If} $0 != 0
${IfNot} ${Silent}
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(close_shift)" IDOK +2
Abort
${EndIf}
${EndIf}
${EndIf}
nsExec::Exec 'taskkill /IM shift.exe /F'
Pop $0
; taskkill returns once termination is requested; give Windows a moment to
; release the mapped EXE before File tries to overwrite it.
Sleep 800
FunctionEnd
Function un.onInit
nsExec::Exec 'taskkill /IM shift.exe /F'
Pop $0
Sleep 800
FunctionEnd
Section "Install"
SetOutPath "$INSTDIR"
File "${SHIFT_EXE}"
!ifdef LICENSE_FILE
File /oname=LICENSE.txt "${LICENSE_FILE}"
!endif
!ifdef NOTICES_FILE
File /oname=THIRD_PARTY_NOTICES.txt "${NOTICES_FILE}"
!endif
!ifdef README_FILE
File /oname=README-Windows.txt "${README_FILE}"
!endif
WriteUninstaller "$INSTDIR\Uninstall.exe"
StrCpy $ReadmePath "$INSTDIR\README-Windows.txt"
WriteRegStr HKCU "Software\${APP_NAME}" "InstallDirectory" "$INSTDIR"
CreateDirectory "$SMPROGRAMS\${APP_NAME}"
CreateShortCut "$SMPROGRAMS\${APP_NAME}\${APP_NAME}.lnk" "$INSTDIR\shift.exe"
CreateShortCut "$SMPROGRAMS\${APP_NAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
CreateShortCut "$DESKTOP\${APP_NAME}.lnk" "$INSTDIR\shift.exe"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${APP_NAME}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${APP_VERSION}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\shift.exe"
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "EstimatedSize" ${EST_SIZE_KB}
SectionEnd
Section "PostInstall"
; The runtime is machine-wide and normally already present on Windows 10/11,
; so a missing one is a warning rather than a reason to refuse the install.
ClearErrors
ReadRegStr $0 HKLM "${WEBVIEW_KEY}" "pv"
${If} $0 == ""
ReadRegStr $0 HKCU "${WEBVIEW_KEY}" "pv"
${EndIf}
${If} $0 == ""
; A silent install is driven by Shift's updater and has nobody to dismiss a
; dialog. The missing runtime is still worth saying out loud on a manual
; install, but a box here would hold the update open forever.
${IfNot} ${Silent}
MessageBox MB_OK|MB_ICONINFORMATION "$(webview_missing)"
${EndIf}
${EndIf}
SectionEnd
Function show_readme
${If} ${FileExists} "$ReadmePath"
Exec 'notepad.exe "$ReadmePath"'
${EndIf}
FunctionEnd
Section "Uninstall"
nsExec::Exec 'taskkill /IM shift.exe /F'
Pop $0
Delete "$INSTDIR\shift.exe"
Delete "$INSTDIR\LICENSE.txt"
Delete "$INSTDIR\THIRD_PARTY_NOTICES.txt"
Delete "$INSTDIR\README-Windows.txt"
Delete "$INSTDIR\Uninstall.exe"
RMDir "$INSTDIR"
Delete "$SMPROGRAMS\${APP_NAME}\${APP_NAME}.lnk"
Delete "$SMPROGRAMS\${APP_NAME}\Uninstall.lnk"
RMDir "$SMPROGRAMS\${APP_NAME}"
Delete "$DESKTOP\${APP_NAME}.lnk"
; Only the keys the installer owns. User preferences and the login item are
; managed by Shift itself and stay untouched.
DeleteRegKey HKCU "${UNINSTALL_KEY}"
DeleteRegValue HKCU "Software\${APP_NAME}" "InstallDirectory"
DeleteRegKey /ifempty HKCU "Software\${APP_NAME}"
SectionEnd

View File

@ -1,18 +0,0 @@
{
"schema": 1,
"version": "0.1.14",
"date": "2026-11-20",
"notes": "Windows 应用内升级修复。\n\n- Windows 交接改成与 Squid 相同的单参数启动:pid、安装包与日志路径写进脚本,`cmd.exe /D /C <脚本路径>` 只接收一个带引号的参数,不再使用 `/S` 或 `raw_arg`。含空格的 `%TEMP%\\Shift Updates` 不会再被拆成额外参数。\n- 0.1.11、0.1.12 及首个 0.1.13 包中的客户端仍带有旧的升级交接 bug,无法在应用内安装任何新版本,需要手动安装一次重发版 0.1.13 或本次 0.1.14。\n- 已安装重发版 0.1.13 的机器可以直接在应用内升级到 0.1.14,用来验证死锁已经解开。\n- 0.1.13 的图标、钉图放大、收藏标记、升级提示与资源占用改进保持不变。",
"artifacts": {
"macos": {
"file": "Shift-0.1.14-macOS-universal.dmg",
"sha256": "aa65404a92c98339f9b9e1335f260f8da25434f84767c8935d61194ebd8dd122",
"size": 54938807
},
"windows": {
"file": "Shift-Setup-0.1.14-win-x64.exe",
"sha256": "a8bcc8b885f37414d831557c744ce48a0e87cd0329da91bdbeaf7e5461e9013c",
"size": 24509319
}
}
}

View File

@ -1 +0,0 @@
HOKyr0EZHUdS5WalLzg9Q+dWwpNqyiChFlJrYfLg8y5f/RJmvq/Xe54tstV4uHjrO6Gfjd+uUt3T5dvFTZBJBw==

6235
src-tauri/Cargo.lock generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,75 @@
[package]
name = "shift"
version = "0.1.13"
description = "A radial file utility with screenshot, recording and OCR."
authors = ["Shift Contributors"]
edition = "2021"
[lib]
name = "shift_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private-api", "protocol-asset", "unstable"] }
tauri-plugin-clipboard-manager = "2"
tauri-plugin-dialog = "2"
tauri-plugin-global-shortcut = "2"
tauri-plugin-opener = "2"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
image = { version = "0.25.8", default-features = false, features = ["png", "jpeg", "webp", "tiff", "bmp", "gif"] }
lopdf = { version = "0.45", default-features = false }
printpdf = { version = "0.12.8", default-features = false, features = ["images", "png", "jpeg", "webp", "tiff", "bmp", "gif"] }
calamine = "0.36.1"
quick-xml = "0.42"
zip = { version = "8.6", default-features = false, features = ["deflate"] }
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 = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_System_Console",
"Win32_System_Com",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_System_WindowsProgramming",
"Win32_Globalization",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
] }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
flate2 = "1"
[profile.dev]
debug = 1
[profile.dev.package."*"]
debug = false

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSScreenCaptureUsageDescription</key>
<string>Shift captures the area you select for screenshots and screen recordings.</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Shift looks for other Shift copies on the same network so you can send files between them.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Shift can include microphone audio in screen recordings when you enable it.</string>
<key>NSDesktopFolderUsageDescription</key>
<string>Shift saves processed files to the folder you choose, including folders on your Desktop.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>Shift saves processed files to the folder you choose, including folders in Documents.</string>
<key>NSDownloadsFolderUsageDescription</key>
<string>Shift saves processed files to the folder you choose, including Downloads.</string>
<key>NSRemovableVolumesUsageDescription</key>
<string>Shift can process and save files on removable volumes you select.</string>
<key>NSNetworkVolumesUsageDescription</key>
<string>Shift can process and save files on network volumes you select.</string>
</dict>
</plist>

View File

@ -0,0 +1 @@

108
src-tauri/build.rs 100644
View File

@ -0,0 +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()
}

View File

@ -0,0 +1,34 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Default permissions for Shift windows.",
"windows": [
"main",
"radial",
"capture",
"recorder",
"editor",
"pin",
"share-*",
"result-*"
],
"permissions": [
"core:default",
"core:window:allow-show",
"core:window:allow-hide",
"core:window:allow-close",
"core:window:allow-set-position",
"core:window:allow-set-size",
"core:window:allow-set-focus",
"core:window:allow-start-dragging",
"core:window:allow-current-monitor",
"core:window:allow-outer-position",
"core:webview:allow-webview-position",
"core:window:allow-scale-factor",
"global-shortcut:default",
"dialog:default",
"opener:default",
"clipboard-manager:allow-write-text",
"clipboard-manager:allow-write-image"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 859 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 763 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Some files were not shown because too many files have changed in this diff Show More