修复bug
parent
3227e7c2d9
commit
c6eff4e131
|
|
@ -5,3 +5,9 @@ src-tauri/gen/
|
|||
artifacts/
|
||||
FileFlipper/
|
||||
.DS_Store
|
||||
scripts/windows-debug/
|
||||
/codesign*
|
||||
*.dSYM/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
|
|
|||
90
README.md
90
README.md
|
|
@ -18,6 +18,7 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
|
|||
- [Compression, naming, cancellation](#compression-naming-cancellation)
|
||||
- [Capture & annotation](#capture--annotation)
|
||||
- [OCR](#ocr)
|
||||
- [Send to a device](#send-to-a-device)
|
||||
- [Shortcuts](#shortcuts)
|
||||
- [Tray menu](#tray-menu)
|
||||
- [Output locations](#output-locations)
|
||||
|
|
@ -36,9 +37,9 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
|
|||
|
||||
## What it does
|
||||
|
||||
**The radial menu is the whole interface.** Hold `Shift` and drag a file in Finder (or `Ctrl + Shift` 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. The main window accepts drops too, and its `Convert files` / `File tools` buttons open the same rings for files you pick yourself.
|
||||
**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. The main window accepts drops too, and its `Convert files` / `File tools` buttons open the same rings for files you pick yourself.
|
||||
|
||||
**Everything is type-aware.** The ring only offers what the selected file can actually become — an image offers PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF, 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.
|
||||
**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.
|
||||
|
||||
|
|
@ -46,6 +47,8 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
|
|||
|
||||
**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.
|
||||
|
|
@ -62,9 +65,9 @@ Shift lives in the menu bar (macOS) and the notification area (Windows), and it
|
|||
> 💡 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 `Ctrl + 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`/`Ctrl` to flip between the format ring and the tool ring.
|
||||
**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 files straight onto the main window opens the action ring directly.
|
||||
**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 files straight onto the main window opens the action ring directly. Drop them **onto a button** instead and that button lights up and runs its own action: **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image.
|
||||
|
||||
**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.
|
||||
|
||||
|
|
@ -76,7 +79,7 @@ Recognition is by extension, against four tables in `src-tauri/src/files.rs`. Th
|
|||
|
||||
| Kind | Extensions |
|
||||
| --- | --- |
|
||||
| `image` | **`png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif`** `heic` `heif` `avif` |
|
||||
| `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`** |
|
||||
|
|
@ -87,37 +90,40 @@ Recognition is by extension, against four tables in `src-tauri/src/files.rs`. Th
|
|||
|
||||
Decoding and encoding are not symmetric, and the app does not pretend otherwise:
|
||||
|
||||
- **Image decode** is native (Rust `image`) for PNG, JPEG, WebP, TIFF, BMP, GIF, and every tool-ring operation uses that decoder. HEIC/HEIF/AVIF are not in it, so those formats convert through the system path — `sips` on macOS, ImageMagick elsewhere — but rotate, flip, B&W, 50% and compress will not read them until they are converted first.
|
||||
- **Image encode** for PNG, JPG, WebP, TIFF, BMP, GIF is native. HEIC export goes through `sips` on macOS and requires ImageMagick on Windows/Linux. AVIF reads fine and can be written by the same system path, but the ring does not offer it yet.
|
||||
- **Image decode** is native (Rust `image`) for PNG, JPEG, WebP, TIFF, BMP and GIF. HEIC/HEIF/AVIF first decode through the system codec — `sips` on macOS, ImageMagick elsewhere — and can then convert to every offered image target, including WEBP, or to PDF. The pixel tools still need a natively readable input, so convert those formats first before rotate, flip, B&W, 50% or compress.
|
||||
- **Image 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 arrow below is wired in `src-tauri/src/files.rs`.
|
||||
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 offers | Engine | Notes |
|
||||
| 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 — capped so a long recording cannot produce a 100 MB GIF |
|
||||
| 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` `RTF` | `lopdf` + Pandoc | Text layer becomes the document body; needs Pandoc |
|
||||
| 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` `ODT` | `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 |
|
||||
| Document `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` `ODT` | Pandoc | Markdown writes as GFM |
|
||||
| Document `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` `ODT` | Pandoc | The source format is omitted; Markdown writes as GFM, HTML and RTF as standalone documents |
|
||||
| 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.
|
||||
|
||||
> Note: unlike some radial converters, Shift does **not** hide the file's own format. Dragging a PNG still shows PNG, which makes it a quick way to re-encode a file in place.
|
||||
**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
|
||||
|
|
@ -199,6 +205,20 @@ Tesseract.js with the LSTM core, running as WASM inside the app. `eng` and `chi_
|
|||
- **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. 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`, plus a legacy broadcast copy for networks that drop multicast. Beacons carry the machine name, OS, and the ephemeral TCP port that will receive files.
|
||||
- A beacon that has not been repeated for nine seconds drops the device from the list, so switching networks clears stale entries by itself.
|
||||
- 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.
|
||||
|
||||
## Shortcuts
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
|
@ -207,7 +227,7 @@ Tesseract.js with the LSTM core, running as WASM inside the app. `eng` and `chi_
|
|||
| Record area | `⌥⇧3` | `Alt+Shift+3` |
|
||||
| Capture full screen | `⌥⇧4` | `Alt+Shift+4` |
|
||||
| Format ring while dragging | hold `⇧` | hold `Shift` |
|
||||
| Tool ring while dragging | `⌥⇧` | `Ctrl+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.
|
||||
|
||||
|
|
@ -224,7 +244,7 @@ The menu bar (macOS) and notification area (Windows) icon exposes the actions yo
|
|||
| OCR an image… | — | Pick an image and read its text locally |
|
||||
| Quit Shift | `Cmd/Ctrl+Q` | Exit; an in-flight recording is finalised first |
|
||||
|
||||
Tray labels are English only for now; everything inside the windows follows the app language.
|
||||
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**.
|
||||
|
||||
|
|
@ -246,11 +266,17 @@ Core conversion, radial menu, capture, and OCR work with nothing installed. Thes
|
|||
| --- | --- | --- | --- | --- |
|
||||
| FFmpeg | media convert/compress, 720p, mute, frame, mono; recording off-macOS | optional | **required** for recording | **required** |
|
||||
| Pandoc | document ↔ DOCX/RTF/ODT/HTML/TXT/MD | optional | needed | needed |
|
||||
| Poppler `pdftoppm` | PDF → images, scanned-PDF OCR | not needed (PDFKit) | needed | needed |
|
||||
| ImageMagick `magick` | HEIC/AVIF encode | not needed (`sips`) | 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 |
|
||||
|
||||
Tools are found on `PATH` at call time and results are cached, so a missing dependency degrades one wedge rather than the app.
|
||||
Settings -> **Runtime components** shows the tools found on the current machine,
|
||||
their versions and paths. Missing Pandoc, Typst, FFmpeg, Poppler and ImageMagick can be
|
||||
installed from the same panel through Homebrew on macOS or WinGet on Windows,
|
||||
then detected again automatically. 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
|
||||
|
||||
|
|
@ -265,6 +291,7 @@ Tools are found on `PATH` at call time and results are cached, so a missing depe
|
|||
| 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 |
|
||||
|
|
@ -284,6 +311,7 @@ pnpm tauri dev
|
|||
|
||||
```bash
|
||||
pnpm check # TypeScript, no emit
|
||||
pnpm test # conversion matrix and drag-target tests
|
||||
pnpm build # tsc + vite
|
||||
cargo test --lib # Rust unit tests, from src-tauri/
|
||||
pnpm tauri build # release bundle
|
||||
|
|
@ -294,17 +322,19 @@ Universal macOS build:
|
|||
```bash
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
pnpm mac:drag-bridge
|
||||
RUSTUP_TOOLCHAIN=stable pnpm tauri build --target universal-apple-darwin --bundles app
|
||||
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
||||
RUSTUP_TOOLCHAIN=stable \
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
```
|
||||
|
||||
The result is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. Windows build steps are in `docs/BUILD_WINDOWS.md`.
|
||||
The result is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. To produce the Windows installer and portable ZIP from macOS, run `scripts/build-windows-release.sh`; full details are in `docs/BUILD_WINDOWS.md`.
|
||||
|
||||
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. Dev builds signed with a local certificate keep those grants stable across rebuilds; distribution needs Developer ID plus notarization.
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
React UI one webview, five views
|
||||
React UI one webview, six views
|
||||
├─ main drop target, shortcuts, recent outputs, language, settings
|
||||
├─ radial transparent always-on-top ring, hit-tested by polar sector
|
||||
├─ capture frozen still + area selection
|
||||
|
|
@ -320,6 +350,7 @@ Tauri command layer src-tauri/src/
|
|||
├─ recording.rs screencapture / FFmpeg, with interrupt-based finalization
|
||||
├─ drag_bridge.rs global drag detection, ring mode, radial positioning
|
||||
├─ settings.rs output directories, write checks, privacy deep links
|
||||
├─ share.rs LAN beacons, peer list, AirDrop-style file transfer
|
||||
└─ editor.rs editor and pin window state
|
||||
|
||||
Platform adapters
|
||||
|
|
@ -336,10 +367,11 @@ The radial hit-test is pure geometry — one polar calculation shared by native
|
|||
|
||||
```text
|
||||
src/ React UI, i18n (en/zh), Tauri API bindings
|
||||
src/lib/ pure helpers and Node tests, including the conversion matrix
|
||||
src-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 asset staging, macOS sidecar build
|
||||
scripts/ OCR staging, macOS sidecars, Windows installer and release builds
|
||||
public/tesseract/ WASM core + traineddata, generated, not committed
|
||||
assets/ app icon source
|
||||
src-tauri/icons/ generated app icons per platform
|
||||
|
|
@ -350,7 +382,9 @@ FileFlipper/ separate companion project, its own repository
|
|||
|
||||
## Privacy
|
||||
|
||||
Shift makes no network requests. Files are read, converted, and written locally; OCR runs in-process against bundled models; recent outputs are a local list. Nothing is uploaded, and nothing is collected.
|
||||
Shift makes no internet requests. Files are read, converted, and written locally; OCR runs in-process against bundled models; recent outputs are a local list. Nothing is uploaded, and nothing is collected.
|
||||
|
||||
The one exception is opt-in by usage: **Send to a device** talks to your local network only — UDP beacons on `239.255.77.88:47888` plus a direct TCP connection between the two machines, carrying the machine name so each side can label the other. It is inert until you open that picker or another Shift sends you a file.
|
||||
|
||||
## Known limitations
|
||||
|
||||
|
|
@ -360,6 +394,8 @@ Shift makes no network requests. Files are read, converted, and written locally;
|
|||
- HEIC/HEIF/AVIF convert through the system decoder, but the pixel tools need a PNG/JPEG/WebP/TIFF/BMP/GIF input; AVIF is not yet an export target.
|
||||
- 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`.
|
||||
- LAN sharing needs a network that allows peer traffic. Multicast is skipped by some guest and corporate Wi-Fi; those networks still work over the broadcast and unicast fallbacks, but two copies cannot meet across a router that isolates clients.
|
||||
- On Windows only one Shift copy per machine can hold the discovery port, so extra instances do not appear as peers.
|
||||
- Windows paths build and pass CI, but gesture-level QA needs real Windows hardware.
|
||||
- Signing identity changes on macOS may require re-approving Screen Recording and Accessibility.
|
||||
|
||||
|
|
@ -368,7 +404,7 @@ 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 `Ctrl` at that moment for tools.
|
||||
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.
|
||||
|
|
@ -376,7 +412,7 @@ Unrecognised extensions get Open and Reveal only, and legacy Apple/Office format
|
|||
**❓ 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 app bundle, so macOS keeps the same Screen Recording identity across launches. Move the app and re-toggle it once.
|
||||
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.
|
||||
|
|
@ -385,7 +421,7 @@ No. There is no upload path in the code and no network call in the conversion or
|
|||
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 and native macOS permission prompts stay in English.
|
||||
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.
|
||||
|
||||
**❓ 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.
|
||||
|
|
@ -395,7 +431,7 @@ Quit from the tray and delete the app. Nothing is written outside your output fo
|
|||
|
||||
## Contributing
|
||||
|
||||
Adding a format is one entry in `formatSetFor` in `src/components/RadialMenu.tsx` plus its handling in `perform_action` in `src-tauri/src/files.rs`; adding a tool is one entry in `toolWedges` plus one match arm. CI runs `pnpm check`, `pnpm build`, `cargo test --lib`, and a debug bundle on macOS and Windows.
|
||||
Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`; adding a tool is one entry in `toolWedges` plus one match arm. Run `pnpm check`, `pnpm test`, `pnpm build` and `cargo test --lib` before pushing. CI builds debug bundles on macOS and Windows.
|
||||
|
||||
**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.
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
|
|||
- [压缩、命名与取消](#压缩命名与取消)
|
||||
- [截图与标注](#截图与标注)
|
||||
- [OCR](#ocr)
|
||||
- [发送到设备](#发送到设备)
|
||||
- [快捷键](#快捷键)
|
||||
- [菜单栏菜单](#菜单栏菜单)
|
||||
- [输出位置](#输出位置)
|
||||
|
|
@ -36,9 +37,9 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
|
|||
|
||||
## 能力概览
|
||||
|
||||
**环形菜单就是全部交互。** 在访达中按住 `Shift` 拖动文件(Windows 为 `Ctrl + Shift`),圆环会出现在光标下方。松开在某个格式上即完成转换;再加上 `Option`/`Alt` 可切换到工具环。主窗口同样接受拖放,其「文件转换」与「文件工具」按钮会先让你挑选文件,再弹出同一个圆环。
|
||||
**环形菜单就是全部交互。** 在访达中按住 `Shift` 拖动文件(Windows 为 `Shift + Alt`),圆环会出现在光标下方。松开在某个格式上即完成转换;再加上 `Option`/`Alt` 可切换到工具环。主窗口同样接受拖放,其「文件转换」与「文件工具」按钮会先让你挑选文件,再弹出同一个圆环。
|
||||
|
||||
**一切按类型驱动。** 圆环只列出所选文件真正能变成的格式——图片会给出 PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF,PPTX 给出 PDF 与 Markdown,而 `.key`、`.pages` 文件不会给出任何转换扇区,而不是等你点击后才失败。中心是毛玻璃预览,显示尺寸与体积;多选文件会渲染成一叠层叠图标。
|
||||
**一切按类型驱动。** 圆环只列出所选文件真正能变成的格式,并且不会重复显示文件自身的格式——图片可在 PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF 之间转换,但当前格式不会出现目标;PPTX 给出 PDF 与 Markdown,而 `.key`、`.pages` 文件不会给出任何转换扇区,而不是等你点击后才失败。中心是毛玻璃预览,显示尺寸与体积;多选文件会渲染成一叠层叠图标。
|
||||
|
||||
**默认批量处理。** 选中十个文件、一次拖拽,就产出十个结果。结果保存在源文件旁边并附带描述性后缀(`report (compressed).pdf`、`photo (rotated).png`),永不覆盖——重名时自动追加序号。也可在设置中改为统一收集到一个文件夹。
|
||||
|
||||
|
|
@ -46,6 +47,8 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
|
|||
|
||||
**OCR 在本机运行。** 英文与简体中文,使用随应用打包的 Tesseract WASM 引擎与语言模型。OCR 全流程不发生任何网络请求。
|
||||
|
||||
**文件可以送到另一台电脑。** 每个运行中的 Shift 都会在局域网里广播自己的存在,因此「最近使用」列表可以像 AirDrop 那样把文件交给另一台电脑——点一下设备名,看着进度条走完,文件就出现在对方电脑的 Shift 输出文件夹里。
|
||||
|
||||
## 快速上手
|
||||
|
||||
Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普通窗口。无需一直开着某个窗口——圆环在任何地方都能唤起。
|
||||
|
|
@ -62,9 +65,9 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
> 💡 改变主意了?把鼠标移回中心(内圈 92 px 之内)再松开,什么都不会发生。
|
||||
> 💡 靠近屏幕边缘时圆环会自动移回屏幕内;整个 760 px 的圆环会被约束在光标所在显示器范围内。
|
||||
|
||||
**使用工具(`Option + Shift`,Windows 为 `Ctrl + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Ctrl`,即可在格式环与工具环之间来回切换。
|
||||
**使用工具(`Option + Shift`,Windows 为 `Alt + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Alt`,即可在格式环与工具环之间来回切换。
|
||||
|
||||
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。直接把文件拖到主窗口上,会直接打开操作环。
|
||||
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。直接把文件拖到主窗口上,会直接打开操作环。**拖到按钮上**则按钮会高亮并只执行它自己的操作:「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。
|
||||
|
||||
**一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。
|
||||
|
||||
|
|
@ -76,7 +79,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
|
||||
| 类型 | 扩展名 |
|
||||
| --- | --- |
|
||||
| `image` | **`png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif`** `heic` `heif` `avif` |
|
||||
| `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`** |
|
||||
|
|
@ -87,37 +90,40 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
|
|||
|
||||
解码与编码能力并不对称,应用也不会假装对称:
|
||||
|
||||
- **图片解码**由 Rust `image` 原生完成,支持 PNG、JPEG、WebP、TIFF、BMP、GIF,工具环的每个操作都走这个解码器。HEIC/HEIF/AVIF 不在其中,它们的转换走系统通道——macOS 用 `sips`,其他系统用 ImageMagick——因此旋转、翻转、黑白、50%、压缩在处理这些格式前需要先转一次。
|
||||
- **图片编码**中的 PNG、JPG、WebP、TIFF、BMP、GIF 为原生实现。HEIC 导出在 macOS 走 `sips`,在 Windows/Linux 需要 ImageMagick。AVIF 可以正常读取,同一套系统通道也能写出,但圆环暂未提供该选项。
|
||||
- **图片解码**由 Rust `image` 原生完成,支持 PNG、JPEG、WebP、TIFF、BMP 与 GIF。HEIC/HEIF/AVIF 先走系统解码器——macOS 用 `sips`,其他系统用 ImageMagick——随后可转换为圆环提供的任意图片格式(包括 WEBP),也可生成 PDF。像素类工具仍需要可原生读取的输入,因此旋转、翻转、黑白、50%、压缩前请先转一次。
|
||||
- **图片编码**中的 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`。
|
||||
以下是各文件类型在格式环中的选项。每一条转换路径都实现在 `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——设有上限,避免长时间录屏产出上百 MB 的 GIF |
|
||||
| 视频 | `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` `RTF` | `lopdf` + Pandoc | 以文字层作为正文;需要 Pandoc |
|
||||
| PDF | `DOCX` | 页面渲染 + 原生 DOCX 封装 | macOS 用 PDFKit,Windows/Linux 用 Poppler;保留图片、图表和页面版式,不依赖 Microsoft Word |
|
||||
| PDF | `RTF` `ODT` | `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` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` `ODT` | Pandoc | Markdown 以 GFM 写出 |
|
||||
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` `ODT` | Pandoc | 自动省略源格式;Markdown 以 GFM 写出,HTML 与 RTF 写出完整独立文档 |
|
||||
| 演示文稿 `.pptx` | `MD` `PDF` | 纯 Rust + Pandoc | 按页生成标题、要点文字,**表格会输出为真正的 Markdown 表格**;PDF 仍是文字摘要版,非版面还原 |
|
||||
| 电子表格 | `MD` `PDF` | `calamine` / 纯 Rust | 每个工作表一张 Markdown 表;`csv`/`tsv` 直接解析 |
|
||||
|
||||
表中没有的转换不会出现在界面上——圆环在运行时按这份目录生成,因此看得见的扇区就是能用的扇区。若缺少依赖,扇区会直接告诉你需要安装什么,而不是静默失败。
|
||||
|
||||
> 说明:与部分环形转换工具不同,Shift **不会**隐藏文件自身的格式。拖动 PNG 时仍会出现 PNG,这也是一键重编码、统一画质的好办法。
|
||||
**页码进度遵循统一规则。** 能真实逐页处理的转换统一显示「正在转换第 N/M 页…」;当前包括图片型 DOCX→PDF 与带图 PDF→DOCX。一次性排版的文本 DOCX→PDF、以及纯文字 PDF→DOCX 无法可靠获得页数,因此显示「处理中…」,不会伪造页码。
|
||||
|
||||
> 说明:转换环不会重复列出文件自身的格式。例如 DOCX 不会出现 DOCX,避免无意义的整篇重写和版式损失。
|
||||
> 扫描件/纯图片 PDF 没有文字层,选 `TXT`/`MD` 会返回明确报错——请改用「文字识别」,它会先把每页渲染成图片。
|
||||
|
||||
## 工具
|
||||
|
|
@ -201,6 +207,20 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
- **扫描版 PDF**——先把各页渲染成图片,再逐页识别并显示每页进度,结果写入 ` (OCR)` 文本文件,页与页之间用 `--- Page N ---` 分隔。
|
||||
- **含文字层的 PDF**——请改用「提取文字」,它直接读取内嵌文字层,速度远快于 OCR。
|
||||
|
||||
## 发送到设备
|
||||
|
||||
Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 AirDrop 式传输。把鼠标移到「最近使用」的任意一行点击发送按钮,或打开文件的「文件工具」环并松开在「发送」扇区上——两种入口都会弹出每台设备一张卡片的设备选择面板,点击卡片即刻开始传输。工具环对每一种文件类型都提供「发送」,选中多个文件时按一批一起发送。
|
||||
|
||||
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
|
||||
|
||||
无需服务器、无需配置,发现机制如下:
|
||||
|
||||
- 每个实例每两秒向组播组 `239.255.77.88:47888` 发送一次小型 UDP 广播,并额外发送一份传统广播,以兼容丢弃组播的网络。广播内容包含机器名、操作系统,以及用于接收文件的动态 TCP 端口。
|
||||
- 九秒内没有再次收到广播,设备就会从列表移除,因此切换网络后过期条目会自动消失。
|
||||
- 文件字节通过直连 TCP 传输:`SHSF` 握手、JSON 头、文件内容,最后一字节确认;只有接收方已完整落盘,发送方才会报告成功。
|
||||
|
||||
整个过程只涉及本地网络——不会有任何数据走到互联网。接收端监听全部网卡,因此 macOS 首次分享时会弹出防火墙授权提示,允许后双向均可用。
|
||||
|
||||
## 快捷键
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
|
@ -209,7 +229,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
| 区域录屏 | `⌥⇧3` | `Alt+Shift+3` |
|
||||
| 全屏截图 | `⌥⇧4` | `Alt+Shift+4` |
|
||||
| 拖拽时显示格式环 | 按住 `⇧` | 按住 `Shift` |
|
||||
| 拖拽时显示工具环 | `⌥⇧` | `Ctrl+Shift` |
|
||||
| 拖拽时显示工具环 | `⌥⇧` | `Alt+Shift` |
|
||||
|
||||
三个截图快捷键注册为全局快捷键。拖拽圆环由修饰键驱动:在开始拖动之前就按住修饰键,圆环会直接出现在光标处,无需先让 Shift 获得焦点。
|
||||
|
||||
|
|
@ -226,7 +246,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
| OCR an image… | — | 选择图片并在本机识别文字 |
|
||||
| Quit Shift | `Cmd/Ctrl+Q` | 退出;若有正在进行的录屏会先收尾保存 |
|
||||
|
||||
菜单项文案目前仅有英文;窗口内的界面会跟随应用语言。
|
||||
菜单项文案会跟随应用语言;macOS 系统权限弹窗仍为英文。
|
||||
|
||||
设置面板的「行为」区有两个开关:**拖拽圆环**(Shift 拖拽手势的总开关)与**开机时启动**。
|
||||
|
||||
|
|
@ -248,11 +268,12 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
| --- | --- | --- | --- | --- |
|
||||
| FFmpeg | 音视频转换/压缩、720p、静音、截帧、单声道;非 macOS 的录屏 | 可选 | 录屏**必需** | **必需** |
|
||||
| Pandoc | 文档 ↔ DOCX/RTF/ODT/HTML/TXT/MD | 可选 | 需要 | 需要 |
|
||||
| Poppler `pdftoppm` | PDF 转图片、扫描件 OCR | 不需要(PDFKit) | 需要 | 需要 |
|
||||
| ImageMagick `magick` | HEIC/AVIF 编码 | 不需要(`sips`) | 需要 | 需要 |
|
||||
| Typst | Pandoc 文档转 PDF 引擎 | 不需要(AppKit) | 需要 | 需要 |
|
||||
| Poppler `pdftoppm` | PDF 转图片、PDF 转 Word、扫描件 OCR | 不需要(PDFKit) | 需要 | 需要 |
|
||||
| ImageMagick `magick` | HEIC/HEIF/AVIF 输入与 HEIC 输出 | 不需要(`sips`) | 需要 | 需要 |
|
||||
| LAME | 当 FFmpeg 缺少 `libmp3lame` 时的 MP3 编码 | 少见 | 少见 | 少见 |
|
||||
|
||||
这些工具在调用时从 `PATH` 查找并缓存结果,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
|
||||
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,并可一键安装缺失的 Pandoc、Typst、FFmpeg、Poppler 与 ImageMagick。macOS 使用 Homebrew,Windows 使用 WinGet;安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
|
||||
|
||||
## 平台支持情况
|
||||
|
||||
|
|
@ -267,6 +288,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
| 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) | 支持 | 支持 |
|
||||
|
|
@ -286,6 +308,7 @@ pnpm tauri dev
|
|||
|
||||
```bash
|
||||
pnpm check # TypeScript 类型检查,不产出文件
|
||||
pnpm test # 转换矩阵与拖拽命中测试
|
||||
pnpm build # tsc + vite
|
||||
cargo test --lib # Rust 单元测试,在 src-tauri/ 目录下执行
|
||||
pnpm tauri build # 发布构建
|
||||
|
|
@ -296,17 +319,19 @@ macOS 通用(Universal)构建:
|
|||
```bash
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
pnpm mac:drag-bridge
|
||||
RUSTUP_TOOLCHAIN=stable pnpm tauri build --target universal-apple-darwin --bundles app
|
||||
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
||||
RUSTUP_TOOLCHAIN=stable \
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
```
|
||||
|
||||
产物是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程。Windows 构建步骤见 `docs/BUILD_WINDOWS.md`。
|
||||
产物是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程。若要在 macOS 上同时生成 Windows 安装版与便携版,运行 `scripts/build-windows-release.sh`;完整步骤见 `docs/BUILD_WINDOWS.md`。
|
||||
|
||||
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。使用本地证书签名的开发构建,可以在反复重编译后保持这些授权稳定;对外分发则需要 Developer ID 证书与公证。
|
||||
|
||||
## 架构
|
||||
|
||||
```text
|
||||
React UI 单一 webview,五种视图
|
||||
React UI 单一 webview,六种视图
|
||||
├─ main 拖放目标、快捷键、最近输出、语言、设置
|
||||
├─ radial 透明置顶圆环,按极角扇区命中判定
|
||||
├─ capture 冻结画面 + 区域框选
|
||||
|
|
@ -322,6 +347,7 @@ Tauri 命令层 src-tauri/src/
|
|||
├─ recording.rs screencapture / FFmpeg,以中断方式收尾
|
||||
├─ drag_bridge.rs 全局拖拽检测、圆环模式、环形菜单定位
|
||||
├─ settings.rs 输出目录、可写检测、隐私面板深链
|
||||
├─ share.rs 局域网广播、设备列表、AirDrop 式文件传输
|
||||
└─ editor.rs 编辑器与钉图窗口状态
|
||||
|
||||
平台适配器
|
||||
|
|
@ -338,10 +364,11 @@ OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线
|
|||
|
||||
```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 伴生进程构建
|
||||
scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器与发布构建
|
||||
public/tesseract/ WASM 内核与语言模型,构建生成,不提交
|
||||
assets/ 应用图标源文件
|
||||
src-tauri/icons/ 各平台生成的应用图标
|
||||
|
|
@ -352,7 +379,9 @@ FileFlipper/ 独立姊妹项目,拥有自己的仓库
|
|||
|
||||
## 隐私
|
||||
|
||||
Shift 不发起任何网络请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;最近输出只是本地列表。既不上传,也不收集。
|
||||
Shift 不发起任何互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;最近输出只是本地列表。既不上传,也不收集。
|
||||
|
||||
唯一的例外取决于你是否使用:**发送到设备** 只与本地网络通信——`239.255.77.88:47888` 上的 UDP 广播,加上两台电脑之间的直连 TCP,其中携带机器名称以便双方互相标注。在你打开该面板、或有另一台 Shift 向你发送文件之前,它不会有任何动作。
|
||||
|
||||
## 已知限制
|
||||
|
||||
|
|
@ -362,6 +391,8 @@ Shift 不发起任何网络请求。文件在本地读取、转换、写回;OC
|
|||
- HEIC/HEIF/AVIF 通过系统解码器转换,但像素类工具需要 PNG/JPEG/WebP/TIFF/BMP/GIF 输入;AVIF 暂未提供为导出目标。
|
||||
- PDF 压缩会把内嵌图片降采样到最长边 1440 px、q60 JPEG。凡是不能确认可安全往返的内容都会原样保留——蒙版、索引色/CMYK、JPX/JBIG2/CCITT——因此部分特殊扫描件仍难以压缩。
|
||||
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。
|
||||
- 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。
|
||||
- Windows 上每台电脑只有一个 Shift 实例能占用发现端口,因此额外实例不会出现在设备列表中。
|
||||
- Windows 代码路径可编译并通过 CI,但手势层面的验证仍需真实 Windows 设备。
|
||||
- macOS 上签名身份变化后,可能需要重新授予「屏幕录制」与「辅助功能」权限。
|
||||
|
||||
|
|
@ -370,7 +401,7 @@ Shift 不发起任何网络请求。文件在本地读取、转换、写回;OC
|
|||
## 常见问题
|
||||
|
||||
**❓ 按住 Shift 拖文件,圆环没出现。**
|
||||
一定要先开始拖动——按住鼠标并把文件拖过拖动阈值——在拖动过程中按住 `Shift`。只选中文件再按 `Shift` 是没有反应的。Windows 需要在拖拽越过系统阈值的那一刻按住 `Shift`;同一时刻再按 `Ctrl` 则进入工具环。
|
||||
一定要先开始拖动——按住鼠标并把文件拖过拖动阈值——在拖动过程中按住 `Shift`。只选中文件再按 `Shift` 是没有反应的。Windows 需要在拖拽越过系统阈值的那一刻按住 `Shift`;同一时刻再按 `Alt` 则进入工具环。
|
||||
|
||||
**❓ 提示这类文件没有可用格式。**
|
||||
未识别的扩展名仅提供打开与在文件夹中显示;旧版 Apple/Office 格式(`.doc`、`.pages`、`.ppt`、`.key`、`.numbers`)刻意不提供转换。请先导出为 DOCX、PPTX 或 XLSX。
|
||||
|
|
@ -387,7 +418,7 @@ Shift 不发起任何网络请求。文件在本地读取、转换、写回;OC
|
|||
默认在源文件旁边,带描述性后缀。可先看主窗口的最近列表,点击条目即可打开结果;设置面板会列出全部实际输出路径并可在文件管理器中显示。
|
||||
|
||||
**❓ 支持哪些语言?**
|
||||
英文与简体中文,可在主窗口的设置中切换;首次启动时跟随系统语言。托盘菜单与 macOS 系统权限弹窗仍为英文。
|
||||
英文与简体中文,可在主窗口的设置中切换;首次启动时跟随系统语言。托盘菜单会跟随所选语言;macOS 系统权限弹窗仍为英文。
|
||||
|
||||
**❓ 能先标注、不保存原图吗?**
|
||||
可以。标注工作在画布副本上,只有「保存副本」或「复制」才会写盘,源文件永不被修改。也可以「钉在屏幕上」,把它作为浮动参考图。
|
||||
|
|
@ -397,7 +428,7 @@ Shift 不发起任何网络请求。文件在本地读取、转换、写回;OC
|
|||
|
||||
## 参与贡献
|
||||
|
||||
新增一种格式 = 在 `src/components/RadialMenu.tsx` 的 `formatSetFor` 中加一项,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `toolWedges` 加一项加一个 match 分支。CI 会执行 `pnpm check`、`pnpm build`、`cargo test --lib`,并在 macOS 与 Windows 上产出 debug 包。
|
||||
新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `toolWedges` 加一项加一个 match 分支。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build` 与 `cargo test --lib`。CI 会在 macOS 与 Windows 上产出 debug 包。
|
||||
|
||||
**欢迎二次开发。** 你可以免费使用、修改、再发布本代码,也可用于商业项目,只需保留原版权声明与 LICENSE 文件。
|
||||
|
||||
|
|
|
|||
|
|
@ -8,10 +8,17 @@
|
|||
- Node.js 20+ and pnpm 8+
|
||||
- Rust stable through rustup
|
||||
- FFmpeg on `PATH` for screen recording and media conversion
|
||||
- Pandoc on `PATH` for document conversion
|
||||
- Poppler (`pdftoppm`) on `PATH` for PDF-to-image rendering
|
||||
- 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
|
||||
|
|
@ -26,12 +33,31 @@ 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 both
|
||||
Windows artefacts without a Windows host:
|
||||
|
||||
```bash
|
||||
brew install makensis
|
||||
scripts/build-windows-release.sh # add --skip-build to reuse the EXE
|
||||
```
|
||||
|
||||
It writes `artifacts/Shift-Setup-<version>-win-x64.exe` (NSIS, per-user, no
|
||||
administrator rights), `artifacts/Shift-Portable-<version>-win-x64.zip` and
|
||||
refreshes `artifacts/SHA256SUMS.txt`. `scripts/windows-installer.nsi` installs
|
||||
into `%LOCALAPPDATA%\Programs\Shift`, and its uninstaller only removes what the
|
||||
installer wrote.
|
||||
|
||||
## 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 `Ctrl + Shift` for the tool ring.
|
||||
- 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
|
||||
|
||||
|
|
@ -39,19 +65,69 @@ The Windows-specific Rust code can be type-checked from macOS:
|
|||
|
||||
```bash
|
||||
rustup target add x86_64-pc-windows-msvc
|
||||
PATH="/opt/homebrew/opt/llvm/bin:$PATH" \
|
||||
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
|
||||
```
|
||||
|
||||
This proves `cfg(windows)` code compiles. Interactive drag/drop and FFmpeg recording still need a real Windows host for runtime QA.
|
||||
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
|
||||
cargo +stable xwin build --target x86_64-pc-windows-msvc --release
|
||||
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 and document conversion.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -1,17 +1,147 @@
|
|||
import AppKit
|
||||
import Foundation
|
||||
import PDFKit
|
||||
import Vision
|
||||
|
||||
func fail(_ message: String) -> Never {
|
||||
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
guard CommandLine.arguments.count == 3 else {
|
||||
fail("usage: doc-render <input> <output.pdf>")
|
||||
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 CommandLine.arguments.count == 3 || CommandLine.arguments.count == 4 else {
|
||||
fail("usage: doc-render <input> <output> [html-base-dir]")
|
||||
}
|
||||
|
||||
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?
|
||||
|
|
@ -39,7 +169,10 @@ if let documentType {
|
|||
options[.documentType] = documentType
|
||||
}
|
||||
if documentType == .html {
|
||||
options[.baseURL] = input.deletingLastPathComponent()
|
||||
let baseDirectory = CommandLine.arguments.count == 4
|
||||
? URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
|
||||
: input.deletingLastPathComponent()
|
||||
options[.baseURL] = baseDirectory
|
||||
}
|
||||
|
||||
let data: Data
|
||||
|
|
@ -56,9 +189,6 @@ do {
|
|||
fail("could not parse document: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.prohibited)
|
||||
|
||||
let printInfo = NSPrintInfo.shared.copy() as! NSPrintInfo
|
||||
printInfo.paperSize = NSSize(width: 595.2, height: 841.8)
|
||||
printInfo.topMargin = 42
|
||||
|
|
|
|||
|
|
@ -27,7 +27,9 @@ func cursorLocation() -> NSPoint {
|
|||
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
|
||||
|
|
@ -46,9 +48,10 @@ func tick() {
|
|||
}
|
||||
let mouseDown = NSEvent.pressedMouseButtons & 1 != 0
|
||||
let point = cursorLocation()
|
||||
|
||||
if !mouseDown {
|
||||
changeCountAtMouseDown = dragPasteboard.changeCount
|
||||
cancelled = false
|
||||
missingDragFiles = 0
|
||||
}
|
||||
|
||||
if !mouseDown && mouseWasDown && pickerShown {
|
||||
|
|
@ -64,6 +67,7 @@ func tick() {
|
|||
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 }
|
||||
|
|
@ -80,6 +84,19 @@ func tick() {
|
|||
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
|
||||
|
|
|
|||
|
|
@ -30,22 +30,33 @@ guard let document = PDFDocument(url: input) else {
|
|||
for index in 0..<document.pageCount {
|
||||
guard let page = document.page(at: index) else { continue }
|
||||
let bounds = page.bounds(for: .mediaBox)
|
||||
let scale = min(2.0, 3000.0 / max(bounds.width, bounds.height, 1.0))
|
||||
let size = NSSize(
|
||||
width: max(1, bounds.width * scale),
|
||||
height: max(1, bounds.height * scale)
|
||||
)
|
||||
let pageImage = page.thumbnail(of: size, for: .mediaBox)
|
||||
let canvas = NSImage(size: size)
|
||||
canvas.lockFocus()
|
||||
NSColor.white.setFill()
|
||||
NSRect(origin: .zero, size: size).fill()
|
||||
pageImage.draw(in: NSRect(origin: .zero, size: size))
|
||||
canvas.unlockFocus()
|
||||
|
||||
guard let tiff = canvas.tiffRepresentation,
|
||||
let bitmap = NSBitmapImageRep(data: tiff),
|
||||
let data = bitmap.representation(using: fileType, properties: [:]) else {
|
||||
// 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(
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@ for arch in arm64 x86_64; do
|
|||
-O \
|
||||
-target "$arch-apple-macosx13.0" \
|
||||
-framework AppKit \
|
||||
-framework PDFKit \
|
||||
-framework Vision \
|
||||
"$root_dir/native/macos/doc-render.swift" \
|
||||
-o "$tmp_dir/doc-render-$arch"
|
||||
done
|
||||
|
|
|
|||
|
|
@ -0,0 +1,168 @@
|
|||
#!/bin/bash
|
||||
# Build the Windows release artefacts from current source.
|
||||
#
|
||||
# scripts/build-windows-release.sh [--skip-build]
|
||||
#
|
||||
# Produces an NSIS per-user installer plus a portable ZIP in artifacts/, then
|
||||
# refreshes artifacts/SHA256SUMS.txt. Cross-compiled on macOS with cargo-xwin;
|
||||
# makensis is the Homebrew formula of the same name.
|
||||
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"
|
||||
EXE=src-tauri/target/x86_64-pc-windows-msvc/release/shift.exe
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
INSTALLER="artifacts/Shift-Setup-$VERSION-win-x64.exe"
|
||||
PORTABLE="artifacts/Shift-Portable-$VERSION-win-x64.zip"
|
||||
|
||||
if [ "${1:-}" != "--skip-build" ]; then
|
||||
echo "== frontend (Windows target: chrome105) =="
|
||||
TAURI_ENV_PLATFORM=windows pnpm build
|
||||
|
||||
echo "== rust cross build =="
|
||||
# --features tauri/custom-protocol is mandatory: without it Tauri derives
|
||||
# cfg(dev) and every window loads build.devUrl instead of the bundled assets.
|
||||
CROSS_LOG=$(mktemp /tmp/shift-win-build.XXXXXX)
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target x86_64-pc-windows-msvc --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
fi
|
||||
|
||||
test -f "$EXE"
|
||||
|
||||
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 =="
|
||||
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
|
||||
mkdir -p "$STAGE/portable/Shift-$VERSION-Windows-x64"
|
||||
python3 - "$STAGE" "$VERSION" <<'PY'
|
||||
import pathlib, sys
|
||||
stage, version = pathlib.Path(sys.argv[1]), sys.argv[2]
|
||||
text = f"""Shift {version} - Windows x64
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11(64 位)。
|
||||
- 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,无需手动删除文件。
|
||||
|
||||
便携版
|
||||
------
|
||||
不想安装时,解压 Shift-Portable-{version}-win-x64.zip,直接运行其中的
|
||||
shift.exe。请先完整解压,不要在压缩包的预览窗口里运行。
|
||||
|
||||
运行组件
|
||||
--------
|
||||
打开 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 =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSHIFT_EXE="$PWD/$EXE" \
|
||||
-DLICENSE_FILE="$PWD/LICENSE" \
|
||||
-DNOTICES_FILE="$PWD/THIRD_PARTY_NOTICES.md" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$PWD/src-tauri/icons" \
|
||||
-DOUT_FILE="$PWD/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
|
||||
echo "== portable ZIP =="
|
||||
cp "$EXE" "$STAGE/portable/Shift-$VERSION-Windows-x64/shift.exe"
|
||||
cp LICENSE "$STAGE/portable/Shift-$VERSION-Windows-x64/LICENSE.txt"
|
||||
cp THIRD_PARTY_NOTICES.md "$STAGE/portable/Shift-$VERSION-Windows-x64/THIRD_PARTY_NOTICES.txt"
|
||||
cp "$STAGE/README-Windows.txt" "$STAGE/portable/Shift-$VERSION-Windows-x64/README-Windows.txt"
|
||||
(cd "$STAGE/portable" && zip -q -r -X -9 "$ROOT/$PORTABLE" "Shift-$VERSION-Windows-x64")
|
||||
mv "$STAGE/README-Windows.txt" "artifacts/README-Windows.txt"
|
||||
|
||||
echo "== checksums =="
|
||||
python3 - "$INSTALLER" "$PORTABLE" <<'PY'
|
||||
import hashlib, pathlib, sys
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
names = ["Shift-macOS-universal.dmg", "Shift-macOS-universal.zip"]
|
||||
names += [pathlib.Path(arg).name for arg in sys.argv[1:]]
|
||||
names.append("README-Windows.txt")
|
||||
lines = []
|
||||
for name in names:
|
||||
path = artifacts / name
|
||||
lines.append(f"{hashlib.sha256(path.read_bytes()).hexdigest()} {name}")
|
||||
(artifacts / "SHA256SUMS.txt").write_text("".join(line + "\n" for line in lines), encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
PY
|
||||
|
||||
echo "== result =="
|
||||
ls -lh "$INSTALLER" "$PORTABLE"
|
||||
printf 'installer sha256: %s\n' "$(shasum -a 256 "$INSTALLER" | cut -d' ' -f1)"
|
||||
printf 'exe sha256: %s\n' "$(shasum -a 256 "$EXE" | cut -d' ' -f1)"
|
||||
|
|
@ -0,0 +1,189 @@
|
|||
; 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.0 -DEST_SIZE_KB=<kb> scripts/windows-installer.nsi
|
||||
;
|
||||
; Install scope is deliberately per-user: Shift writes only to HKCU and its own
|
||||
; folder, which is also what the portable build already does.
|
||||
|
||||
!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.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.
|
||||
${If} ${FileExists} "$INSTDIR\shift.exe"
|
||||
FindWindow $0 "" "${APP_NAME}"
|
||||
${If} $0 != 0
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(close_shift)" IDOK +2
|
||||
Abort
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
nsExec::Exec 'taskkill /IM shift.exe /F'
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
Function un.onInit
|
||||
nsExec::Exec 'taskkill /IM shift.exe /F'
|
||||
Pop $0
|
||||
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 == ""
|
||||
MessageBox MB_OK|MB_ICONINFORMATION "$(webview_missing)"
|
||||
${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
|
||||
|
|
@ -3820,6 +3820,7 @@ dependencies = [
|
|||
"base64 0.22.1",
|
||||
"calamine",
|
||||
"chrono",
|
||||
"flate2",
|
||||
"image",
|
||||
"libc",
|
||||
"lopdf 0.45.0",
|
||||
|
|
|
|||
|
|
@ -34,15 +34,30 @@ which = "7"
|
|||
[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",
|
||||
] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
flate2 = "1"
|
||||
|
||||
[profile.dev]
|
||||
debug = 1
|
||||
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,3 +1,4 @@
|
|||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../dist");
|
||||
tauri_build::build()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Default permissions for Shift windows.",
|
||||
"windows": ["main", "radial", "capture", "recorder", "editor", "pin-*"],
|
||||
"windows": ["main", "radial", "capture", "recorder", "editor", "pin"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
|
|
|
|||
|
|
@ -10,11 +10,7 @@ use std::path::PathBuf;
|
|||
|
||||
// Each helper is only pulled in where it is actually used, so no platform
|
||||
// carries dead imports.
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::{fs, process::Command};
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::process::Command;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[cfg(any(target_os = "macos", all(unix, not(target_os = "macos"))))]
|
||||
use std::fs;
|
||||
|
||||
/// Registers or unregisters Shift as a login item.
|
||||
|
|
@ -38,7 +34,20 @@ fn platform_set(enabled: bool) -> Result<(), String> {
|
|||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn platform_is_enabled() -> bool {
|
||||
agent_plist().is_some_and(|path| path.exists())
|
||||
let Some(path) = agent_plist() else {
|
||||
return false;
|
||||
};
|
||||
if !path.exists() {
|
||||
return false;
|
||||
}
|
||||
// A plist that still points at an old location is a leftover from a moved
|
||||
// app, so the toggle has to be used again to register the new path.
|
||||
let Some(current) = executable_path() else {
|
||||
return false;
|
||||
};
|
||||
fs::read_to_string(&path)
|
||||
.map(|plist| plist.contains(¤t.to_string_lossy().to_string()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
|
|
@ -75,17 +84,13 @@ fn platform_is_enabled() -> bool {
|
|||
false
|
||||
}
|
||||
|
||||
/// The app to launch. Inside a `.app` bundle this is the bundle itself, so the
|
||||
/// Dock name, icon and macOS TCC identity match what the user approved.
|
||||
/// The app to launch. On macOS this is the executable inside the `.app`
|
||||
/// bundle: a LaunchAgent cannot run a bundle, it can only run a program.
|
||||
/// Pointing it at the bundle makes launchd fail with `EX_CONFIG`, so the
|
||||
/// executable is used instead. It keeps the same bundle identity, icon and
|
||||
/// macOS TCC permission the user approved.
|
||||
fn executable_path() -> Option<PathBuf> {
|
||||
let current = std::env::current_exe().ok()?;
|
||||
let mut cursor = current.as_path();
|
||||
while let Some(parent) = cursor.parent() {
|
||||
if parent.extension().and_then(|value| value.to_str()) == Some("app") {
|
||||
return Some(parent.to_path_buf());
|
||||
}
|
||||
cursor = parent;
|
||||
}
|
||||
Some(current)
|
||||
}
|
||||
|
||||
|
|
@ -135,11 +140,11 @@ fn install_macos_agent() -> Result<(), String> {
|
|||
let domain = format!("gui/{}", unsafe { libc::getuid() });
|
||||
// Modern launchctl first, legacy load as a fallback. Either one succeeding
|
||||
// is enough, and the plist also takes effect at the next login regardless.
|
||||
let modern = Command::new("launchctl")
|
||||
let modern = crate::process::command("launchctl")
|
||||
.args(["bootstrap", domain.as_str(), &path.to_string_lossy()])
|
||||
.status();
|
||||
if !matches!(modern, Ok(status) if status.success()) {
|
||||
let _ = Command::new("launchctl")
|
||||
let _ = crate::process::command("launchctl")
|
||||
.args(["load", &path.to_string_lossy()])
|
||||
.status();
|
||||
}
|
||||
|
|
@ -155,10 +160,10 @@ fn remove_macos_agent() -> Result<(), String> {
|
|||
return Ok(());
|
||||
}
|
||||
let domain = format!("gui/{}", unsafe { libc::getuid() });
|
||||
let _ = Command::new("launchctl")
|
||||
let _ = crate::process::command("launchctl")
|
||||
.args(["bootout", domain.as_str(), &path.to_string_lossy()])
|
||||
.status();
|
||||
let _ = Command::new("launchctl")
|
||||
let _ = crate::process::command("launchctl")
|
||||
.args(["unload", &path.to_string_lossy()])
|
||||
.status();
|
||||
fs::remove_file(&path).map_err(|error| error.to_string())
|
||||
|
|
@ -167,34 +172,122 @@ fn remove_macos_agent() -> Result<(), String> {
|
|||
// -------------------------------------------------------------- Windows
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn registry_command(arguments: &[&str]) -> Result<std::process::ExitStatus, String> {
|
||||
Command::new("reg")
|
||||
.args(arguments)
|
||||
.status()
|
||||
.map_err(|error| format!("Could not run reg.exe: {error}"))
|
||||
fn wide(value: &str) -> Vec<u16> {
|
||||
value.encode_utf16().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
|
||||
/// Access the Run key in process. Spawning `reg.exe` for every settings
|
||||
/// snapshot made a GUI app flash a console window and added tens of
|
||||
/// milliseconds to each settings action.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn query_windows_run_key() -> bool {
|
||||
matches!(
|
||||
registry_command(&["query", RUN_KEY, "/v", "Shift"]),
|
||||
Ok(status) if status.success()
|
||||
)
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS},
|
||||
System::Registry::{
|
||||
RegCloseKey, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE,
|
||||
REG_SZ,
|
||||
},
|
||||
};
|
||||
|
||||
let subkey = wide(RUN_KEY);
|
||||
let name = wide("Shift");
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
let opened = unsafe {
|
||||
RegOpenKeyExW(
|
||||
HKEY_CURRENT_USER,
|
||||
subkey.as_ptr(),
|
||||
0,
|
||||
KEY_QUERY_VALUE,
|
||||
&mut key,
|
||||
)
|
||||
};
|
||||
if opened == ERROR_FILE_NOT_FOUND {
|
||||
return false;
|
||||
}
|
||||
if opened != ERROR_SUCCESS || key.is_null() {
|
||||
return false;
|
||||
}
|
||||
let mut kind = 0_u32;
|
||||
let mut size = 0_u32;
|
||||
let query = unsafe {
|
||||
RegQueryValueExW(
|
||||
key,
|
||||
name.as_ptr(),
|
||||
std::ptr::null(),
|
||||
&mut kind,
|
||||
std::ptr::null_mut(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
let exists = query == ERROR_SUCCESS && kind == REG_SZ && size > 0;
|
||||
unsafe { RegCloseKey(key) };
|
||||
exists
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_windows_run_key(enabled: bool) -> Result<(), String> {
|
||||
if enabled {
|
||||
use windows_sys::Win32::{
|
||||
Foundation::ERROR_SUCCESS,
|
||||
System::Registry::{
|
||||
RegCloseKey, RegCreateKeyExW, RegDeleteValueW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,
|
||||
KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_SZ,
|
||||
},
|
||||
};
|
||||
|
||||
let subkey = wide(RUN_KEY);
|
||||
let name = wide("Shift");
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
let opened = unsafe {
|
||||
RegCreateKeyExW(
|
||||
HKEY_CURRENT_USER,
|
||||
subkey.as_ptr(),
|
||||
0,
|
||||
std::ptr::null(),
|
||||
REG_OPTION_NON_VOLATILE,
|
||||
KEY_SET_VALUE,
|
||||
std::ptr::null(),
|
||||
&mut key,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if opened != ERROR_SUCCESS || key.is_null() {
|
||||
return Err(format!(
|
||||
"Could not open the Windows startup registry key ({opened})."
|
||||
));
|
||||
}
|
||||
|
||||
let result = if enabled {
|
||||
let target = executable_path().ok_or_else(|| "Could not locate Shift.".to_string())?;
|
||||
// Quote the path: it usually contains "Program Files" or a user name
|
||||
// with spaces, and the Run key performs no quoting of its own.
|
||||
let value = format!("\"{}\"", target.display());
|
||||
registry_command(&["add", RUN_KEY, "/v", "Shift", "/t", "REG_SZ", "/d", &value, "/f"])?;
|
||||
// The Run key executes the string as written; quote paths containing spaces.
|
||||
let value = wide(&format!("\"{}\"", target.display()));
|
||||
let bytes = unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
value.as_ptr().cast::<u8>(),
|
||||
value.len() * std::mem::size_of::<u16>(),
|
||||
)
|
||||
};
|
||||
unsafe {
|
||||
RegSetValueExW(
|
||||
key,
|
||||
name.as_ptr(),
|
||||
0,
|
||||
REG_SZ,
|
||||
bytes.as_ptr(),
|
||||
bytes.len() as u32,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
registry_command(&["delete", RUN_KEY, "/v", "Shift", "/f"])?;
|
||||
unsafe { RegDeleteValueW(key, name.as_ptr()) }
|
||||
};
|
||||
unsafe { RegCloseKey(key) };
|
||||
if result != ERROR_SUCCESS {
|
||||
return Err(format!(
|
||||
"Could not {} the Windows startup entry ({result}).",
|
||||
if enabled { "create" } else { "remove" }
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -236,3 +329,22 @@ fn remove_linux_autostart() -> Result<(), String> {
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_agent_points_at_an_executable_not_a_bundle() {
|
||||
let path = agent_plist().unwrap();
|
||||
// A LaunchAgent cannot run an `.app` bundle, so the plist must name a
|
||||
// program inside it.
|
||||
let target = executable_path().unwrap();
|
||||
assert!(
|
||||
target.extension().and_then(|value| value.to_str()) != Some("app"),
|
||||
"the agent must not point at a bundle: {target:?}"
|
||||
);
|
||||
assert!(path.ends_with(format!("{LABEL}.plist")));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use chrono::Local;
|
||||
|
|
@ -89,7 +88,7 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result<CaptureSo
|
|||
(monitor.size().width as f64 / scale).round() as u32,
|
||||
(monitor.size().height as f64 / scale).round() as u32,
|
||||
);
|
||||
let status = Command::new("/usr/sbin/screencapture")
|
||||
let status = crate::process::command("/usr/sbin/screencapture")
|
||||
.args([
|
||||
"-x",
|
||||
"-R",
|
||||
|
|
@ -110,43 +109,23 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result<CaptureSo
|
|||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let script = format!(
|
||||
r#"Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$point = [System.Windows.Forms.Cursor]::Position
|
||||
$screen = [System.Windows.Forms.Screen]::FromPoint($point)
|
||||
$bounds = $screen.Bounds
|
||||
$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
|
||||
$bitmap.Save('{}', [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()"#,
|
||||
output.to_string_lossy().replace('\'', "''")
|
||||
);
|
||||
let status = Command::new("powershell")
|
||||
.args(["-NoProfile", "-WindowStyle", "Hidden", "-Command", &script])
|
||||
.status()
|
||||
.map_err(|error| format!("Could not launch screen capture: {error}"))?;
|
||||
if !status.success() || !output.exists() {
|
||||
return Err("Screen capture failed.".into());
|
||||
}
|
||||
capture_windows_screen(monitor, &output)?;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let status = if let Some(grim) = crate::files::resolve_tool("grim") {
|
||||
if let Some(name) = monitor.name() {
|
||||
Command::new(grim)
|
||||
crate::process::command(grim)
|
||||
.args(["-o", name, output.to_string_lossy().as_ref()])
|
||||
.status()
|
||||
} else {
|
||||
Command::new(grim)
|
||||
crate::process::command(grim)
|
||||
.arg(output.to_string_lossy().as_ref())
|
||||
.status()
|
||||
}
|
||||
} else if let Some(gnome_screenshot) = crate::files::resolve_tool("gnome-screenshot") {
|
||||
Command::new(gnome_screenshot)
|
||||
crate::process::command(gnome_screenshot)
|
||||
.args(["-f", output.to_string_lossy().as_ref()])
|
||||
.status()
|
||||
} else {
|
||||
|
|
@ -170,6 +149,126 @@ $bitmap.Dispose()"#,
|
|||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(), String> {
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, GetDC,
|
||||
GetDIBits, ReleaseDC, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, CAPTUREBLT,
|
||||
DIB_RGB_COLORS, HGDIOBJ, SRCCOPY,
|
||||
};
|
||||
use windows_sys::Win32::UI::HiDpi::{
|
||||
SetThreadDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
|
||||
};
|
||||
// Capture only the monitor under the cursor. Grabbing the virtual desktop
|
||||
// would make a mixed-DPI or multi-monitor setup produce an image whose
|
||||
// origin no longer matches the overlay window.
|
||||
let x = monitor.position().x;
|
||||
let y = monitor.position().y;
|
||||
let width = monitor.size().width as i32;
|
||||
let height = monitor.size().height as i32;
|
||||
unsafe {
|
||||
// Tauri's monitor bounds are physical pixels. Pin this worker thread
|
||||
// to per-monitor-v2 while calling GDI; otherwise GetDC(NULL) may use a
|
||||
// thread-scaled virtual desktop and the capture no longer aligns with
|
||||
// the overlay.
|
||||
let previous_awareness =
|
||||
SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
|
||||
let restore_awareness = || {
|
||||
if !previous_awareness.is_null() {
|
||||
SetThreadDpiAwarenessContext(previous_awareness);
|
||||
}
|
||||
};
|
||||
if width <= 0 || height <= 0 {
|
||||
restore_awareness();
|
||||
return Err("Windows did not report a usable screen size.".into());
|
||||
}
|
||||
let screen = GetDC(std::ptr::null_mut());
|
||||
if screen.is_null() {
|
||||
restore_awareness();
|
||||
return Err("Windows could not open the desktop surface.".into());
|
||||
}
|
||||
let memory = CreateCompatibleDC(screen);
|
||||
let bitmap = CreateCompatibleBitmap(screen, width, height);
|
||||
if memory.is_null() || bitmap.is_null() {
|
||||
if !bitmap.is_null() {
|
||||
DeleteObject(bitmap as HGDIOBJ);
|
||||
}
|
||||
if !memory.is_null() {
|
||||
DeleteDC(memory);
|
||||
}
|
||||
ReleaseDC(std::ptr::null_mut(), screen);
|
||||
restore_awareness();
|
||||
return Err("Windows could not allocate a screenshot surface.".into());
|
||||
}
|
||||
let previous = SelectObject(memory, bitmap as HGDIOBJ);
|
||||
let copied = BitBlt(
|
||||
memory,
|
||||
0,
|
||||
0,
|
||||
width,
|
||||
height,
|
||||
screen,
|
||||
x,
|
||||
y,
|
||||
SRCCOPY | CAPTUREBLT,
|
||||
);
|
||||
let mut info = BITMAPINFO {
|
||||
bmiHeader: BITMAPINFOHEADER {
|
||||
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
|
||||
biWidth: width,
|
||||
// Negative height asks GDI for top-down rows, matching PNG.
|
||||
biHeight: -height,
|
||||
biPlanes: 1,
|
||||
biBitCount: 32,
|
||||
biCompression: BI_RGB,
|
||||
biSizeImage: 0,
|
||||
biXPelsPerMeter: 0,
|
||||
biYPelsPerMeter: 0,
|
||||
biClrUsed: 0,
|
||||
biClrImportant: 0,
|
||||
},
|
||||
bmiColors: [windows_sys::Win32::Graphics::Gdi::RGBQUAD {
|
||||
rgbBlue: 0,
|
||||
rgbGreen: 0,
|
||||
rgbRed: 0,
|
||||
rgbReserved: 0,
|
||||
}],
|
||||
};
|
||||
let mut pixels = vec![0_u8; width as usize * height as usize * 4];
|
||||
let rows = GetDIBits(
|
||||
memory,
|
||||
bitmap,
|
||||
0,
|
||||
height as u32,
|
||||
pixels.as_mut_ptr().cast(),
|
||||
&mut info,
|
||||
DIB_RGB_COLORS,
|
||||
);
|
||||
SelectObject(memory, previous);
|
||||
DeleteObject(bitmap as HGDIOBJ);
|
||||
DeleteDC(memory);
|
||||
ReleaseDC(std::ptr::null_mut(), screen);
|
||||
|
||||
if copied == 0 || rows == 0 {
|
||||
restore_awareness();
|
||||
return Err("Windows could not copy the screen surface.".into());
|
||||
}
|
||||
for pixel in pixels.chunks_exact_mut(4) {
|
||||
pixel.swap(0, 2);
|
||||
pixel[3] = 255;
|
||||
}
|
||||
let Some(image) = image::RgbaImage::from_raw(width as u32, height as u32, pixels) else {
|
||||
restore_awareness();
|
||||
return Err("Windows returned an invalid screenshot buffer.".into());
|
||||
};
|
||||
let result = image
|
||||
.save_with_format(output, image::ImageFormat::Png)
|
||||
.map_err(|error| format!("Could not save the screenshot: {error}"));
|
||||
restore_awareness();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn screenshot_directory(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
settings::screenshot_dir(app)
|
||||
}
|
||||
|
|
@ -284,9 +383,13 @@ pub fn get_capture_session(
|
|||
.clone())
|
||||
}
|
||||
|
||||
/// Capture work runs off the main thread: freezing a screen, decoding the grab
|
||||
/// and writing the crop all take longer than a frame budget.
|
||||
#[tauri::command]
|
||||
pub fn start_capture(app: AppHandle, mode: String) -> Result<CaptureSessionInfo, String> {
|
||||
begin_capture(&app, &mode)
|
||||
pub async fn start_capture(app: AppHandle, mode: String) -> Result<CaptureSessionInfo, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || begin_capture(&app, &mode))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
|
@ -300,12 +403,13 @@ pub fn cancel_capture(app: AppHandle) -> Result<(), String> {
|
|||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn capture_crop(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
rect: NormalizedRect,
|
||||
) -> Result<String, String> {
|
||||
finish_capture(&app, &state, &rect)
|
||||
pub async fn capture_crop(app: AppHandle, rect: NormalizedRect) -> Result<String, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let state = app.state::<AppState>();
|
||||
finish_capture(&app, &state, &rect)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
fn finish_capture(
|
||||
|
|
@ -359,29 +463,45 @@ pub fn capture_fullscreen_core(app: &AppHandle, state: &AppState) -> Result<Stri
|
|||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn capture_fullscreen(app: AppHandle, state: State<'_, AppState>) -> Result<String, String> {
|
||||
let result = capture_fullscreen_core(&app, &state);
|
||||
if result.is_err() {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
pub async fn capture_fullscreen(app: AppHandle) -> Result<String, String> {
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
let state = app.state::<AppState>();
|
||||
let result = capture_fullscreen_core(&app, &state);
|
||||
if result.is_err() {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn copy_file_to(source: String, destination: String) -> Result<(), String> {
|
||||
fs::copy(Path::new(&source), Path::new(&destination))
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
pub async fn copy_file_to(source: String, destination: String) -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
fs::copy(Path::new(&source), Path::new(&destination))
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_screen_recording_settings() -> Result<(), String> {
|
||||
pub async fn open_screen_recording_settings() -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(open_screen_recording_settings_sync)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
fn open_screen_recording_settings_sync() -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let status = Command::new("/usr/bin/open")
|
||||
let status = crate::process::command("/usr/bin/open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use std::thread;
|
|||
#[cfg(target_os = "macos")]
|
||||
use std::{
|
||||
io::{BufRead, BufReader},
|
||||
process::{Command, Stdio},
|
||||
process::Stdio,
|
||||
};
|
||||
|
||||
use serde::Serialize;
|
||||
|
|
@ -93,7 +93,7 @@ pub fn spawn(app: &AppHandle) {
|
|||
eprintln!("Shift drag bridge was not found. Shift-drag will be unavailable.");
|
||||
return;
|
||||
};
|
||||
let mut child = match Command::new(path)
|
||||
let mut child = match crate::process::command(path)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
|
|
@ -129,7 +129,7 @@ fn spawn_windows_monitor(app: &AppHandle) {
|
|||
Foundation::POINT,
|
||||
UI::{
|
||||
Input::KeyboardAndMouse::{
|
||||
GetAsyncKeyState, VK_CONTROL, VK_LBUTTON, VK_RBUTTON, VK_SHIFT,
|
||||
GetAsyncKeyState, VK_LBUTTON, VK_MENU, VK_RBUTTON, VK_SHIFT,
|
||||
},
|
||||
WindowsAndMessaging::{
|
||||
GetCursorPos, GetSystemMetrics, SM_CXDRAG, SM_CYDRAG, SM_SWAPBUTTON,
|
||||
|
|
@ -144,6 +144,9 @@ fn spawn_windows_monitor(app: &AppHandle) {
|
|||
let mut tools_mode = false;
|
||||
let mut down = POINT { x: 0, y: 0 };
|
||||
let mut ignore_press = false;
|
||||
// Gesture tracing is edge-triggered so the log stays readable on a 33ms poll.
|
||||
let mut reported_disabled = false;
|
||||
let mut reported_foreground = false;
|
||||
|
||||
loop {
|
||||
let swapped = unsafe { GetSystemMetrics(SM_SWAPBUTTON) } != 0;
|
||||
|
|
@ -155,16 +158,18 @@ fn spawn_windows_monitor(app: &AppHandle) {
|
|||
}
|
||||
|
||||
if !mouse_down {
|
||||
// Release ends the gesture. macOS gets an explicit `cancel` from its
|
||||
// bridge, but on Windows the ring only closes when a WebView2 OLE drop
|
||||
// or leave arrives, so a drag that Explorer never turned into an OLE
|
||||
// session (text, a shortcut, a drag started outside a shell folder)
|
||||
// would leave the ring on screen for good. Let the webview decide: it
|
||||
// knows whether OLE ever handed it files.
|
||||
if armed {
|
||||
armed = false;
|
||||
let window = app.get_webview_window("radial");
|
||||
if let Some(window) = window {
|
||||
thread::spawn(move || {
|
||||
thread::sleep(std::time::Duration::from_millis(360));
|
||||
let _ = window.hide();
|
||||
});
|
||||
if let Some(window) = app.get_webview_window("radial") {
|
||||
let _ = window.emit("radial://dragend", ());
|
||||
}
|
||||
}
|
||||
armed = false;
|
||||
mouse_was_down = false;
|
||||
thread::sleep(std::time::Duration::from_millis(33));
|
||||
continue;
|
||||
|
|
@ -176,20 +181,31 @@ fn spawn_windows_monitor(app: &AppHandle) {
|
|||
ignore_press = foreground_is_self();
|
||||
}
|
||||
if ignore_press {
|
||||
if !reported_foreground {
|
||||
reported_foreground = true;
|
||||
eprintln!("shift: press started inside Shift itself, ignoring this gesture");
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(33));
|
||||
continue;
|
||||
}
|
||||
reported_foreground = false;
|
||||
|
||||
let shift = unsafe { GetAsyncKeyState(VK_SHIFT as i32) } as u16 & 0x8000 != 0;
|
||||
let control = unsafe { GetAsyncKeyState(VK_CONTROL as i32) } as u16 & 0x8000 != 0;
|
||||
// Keep the drag gesture consistent with the Alt+Shift global shortcuts.
|
||||
let alt = unsafe { GetAsyncKeyState(VK_MENU as i32) } as u16 & 0x8000 != 0;
|
||||
let threshold_x = unsafe { GetSystemMetrics(SM_CXDRAG) }.max(4);
|
||||
let threshold_y = unsafe { GetSystemMetrics(SM_CYDRAG) }.max(4);
|
||||
|
||||
if !armed {
|
||||
if !drag_enabled(&app) {
|
||||
if !reported_disabled {
|
||||
reported_disabled = true;
|
||||
eprintln!("shift: drag ring is disabled in settings, ignoring the gesture");
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(100));
|
||||
continue;
|
||||
}
|
||||
reported_disabled = false;
|
||||
if !shift {
|
||||
thread::sleep(std::time::Duration::from_millis(33));
|
||||
continue;
|
||||
|
|
@ -201,12 +217,18 @@ fn spawn_windows_monitor(app: &AppHandle) {
|
|||
continue;
|
||||
}
|
||||
armed = true;
|
||||
tools_mode = control;
|
||||
tools_mode = alt;
|
||||
let (x, y) = physical_to_logical(&app, point);
|
||||
let mode = if tools_mode { "tools" } else { "formats" };
|
||||
let _ = show_radial(&app, Vec::new(), mode, Some((x, y)), true);
|
||||
} else if shift && control != tools_mode {
|
||||
tools_mode = control;
|
||||
match show_radial(&app, Vec::new(), mode, Some((x, y)), true) {
|
||||
Ok(_) => eprintln!(
|
||||
"shift: armed {mode} ring at logical ({x:.0}, {y:.0}) from physical ({}, {}) with threshold {threshold_x}x{threshold_y}",
|
||||
point.x, point.y
|
||||
),
|
||||
Err(error) => eprintln!("shift: could not open the {mode} ring: {error}"),
|
||||
}
|
||||
} else if shift && alt != tools_mode {
|
||||
tools_mode = alt;
|
||||
let mode = if tools_mode { "tools" } else { "formats" };
|
||||
let state = app.state::<AppState>();
|
||||
if let Ok(mut current) = state.radial_mode.lock() {
|
||||
|
|
@ -249,7 +271,34 @@ fn physical_to_logical(
|
|||
&& point.y <= y + monitor.size().height as i32
|
||||
});
|
||||
let scale = monitor.map(|monitor| monitor.scale_factor()).unwrap_or(1.0);
|
||||
(point.x as f64 / scale, point.y as f64 / scale)
|
||||
let logical = (point.x as f64 / scale, point.y as f64 / scale);
|
||||
// set_position(LogicalPosition) is scaled back up by tao using the *window's*
|
||||
// scale factor, not the cursor monitor's (tao window.rs set_outer_position). On a
|
||||
// mixed-DPI desktop those differ, which shifts the ring by the ratio between them,
|
||||
// so record both plus the match that produced the divisor.
|
||||
let window_scale = app
|
||||
.get_webview_window("radial")
|
||||
.and_then(|window| window.scale_factor().ok())
|
||||
.unwrap_or(1.0);
|
||||
let matched = match monitor {
|
||||
Some(monitor) => format!(
|
||||
"monitor {}x{} at {},{} scale {}",
|
||||
monitor.size().width,
|
||||
monitor.size().height,
|
||||
monitor.position().x,
|
||||
monitor.position().y,
|
||||
monitor.scale_factor()
|
||||
),
|
||||
None => format!(
|
||||
"no monitor contained the point ({} monitors)",
|
||||
monitors.len()
|
||||
),
|
||||
};
|
||||
eprintln!(
|
||||
"shift: ring coords physical ({}, {}) -> logical ({:.0}, {:.0}); {matched}; window scale {window_scale}",
|
||||
point.x, point.y, logical.0, logical.1
|
||||
);
|
||||
logical
|
||||
}
|
||||
|
||||
/// Whether the Shift-drag gesture may open a ring. Read by both the macOS
|
||||
|
|
@ -257,7 +306,11 @@ fn physical_to_logical(
|
|||
#[allow(dead_code)] // unused on Linux, which has no drag monitor yet
|
||||
fn drag_enabled(app: &AppHandle) -> bool {
|
||||
app.try_state::<AppState>()
|
||||
.map(|state| state.drag_enabled.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.map(|state| {
|
||||
state
|
||||
.drag_enabled
|
||||
.load(std::sync::atomic::Ordering::Relaxed)
|
||||
})
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
|
|
@ -303,14 +356,6 @@ fn handle_bridge_event(app: &AppHandle, event: BridgeEvent) {
|
|||
"radial://move"
|
||||
};
|
||||
let _ = window.emit(event_name, payload);
|
||||
|
||||
if event.event_type == "end" {
|
||||
let window = window.clone();
|
||||
thread::spawn(move || {
|
||||
thread::sleep(std::time::Duration::from_millis(500));
|
||||
let _ = window.hide();
|
||||
});
|
||||
}
|
||||
}
|
||||
"mode" => {
|
||||
let mode = if event.tools.unwrap_or(false) {
|
||||
|
|
@ -326,6 +371,7 @@ fn handle_bridge_event(app: &AppHandle, event: BridgeEvent) {
|
|||
let _ = window.emit("radial://mode", mode);
|
||||
}
|
||||
}
|
||||
"cancel" => hide(app),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
@ -405,6 +451,38 @@ pub fn show_radial(
|
|||
.set_position(LogicalPosition::new(origin_x, origin_y))
|
||||
.map_err(|error| error.to_string())?;
|
||||
window.show().map_err(|error| error.to_string())?;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let title = window
|
||||
.title()
|
||||
.map(|value| format!("{value:?}"))
|
||||
.unwrap_or_else(|error| format!("error({error})"));
|
||||
let visible = window
|
||||
.is_visible()
|
||||
.map(|value| value.to_string())
|
||||
.unwrap_or_else(|error| format!("error({error})"));
|
||||
let position = window
|
||||
.outer_position()
|
||||
.map(|value| format!("{},{}", value.x, value.y))
|
||||
.unwrap_or_else(|error| format!("error({error})"));
|
||||
let size = window
|
||||
.outer_size()
|
||||
.map(|value| format!("{}x{}", value.width, value.height))
|
||||
.unwrap_or_else(|error| format!("error({error})"));
|
||||
let scale = window
|
||||
.scale_factor()
|
||||
.map(|value| value.to_string())
|
||||
.unwrap_or_else(|error| format!("error({error})"));
|
||||
eprintln!(
|
||||
"shift: radial window after show: title={title} visible={visible} position={position} size={size} scale={scale}"
|
||||
);
|
||||
}
|
||||
// A drop has already finished when the main panel opens a ring. Focusing
|
||||
// that ring enables normal hover and keyboard handling. During a live
|
||||
// Finder drag the non-activating window must stay unfocused.
|
||||
if !dragging {
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
window
|
||||
.emit("radial://show", context.clone())
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
|
@ -422,10 +500,17 @@ pub fn hide(app: &AppHandle) {
|
|||
}
|
||||
}
|
||||
|
||||
/// The ring's own commands decode image previews, so they run off the main thread
|
||||
/// and the ring never waits on a batch of large photos.
|
||||
#[tauri::command]
|
||||
pub fn get_radial_context(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<Option<RadialContext>, String> {
|
||||
pub async fn get_radial_context(app: AppHandle) -> Result<Option<RadialContext>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || radial_context(&app))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
fn radial_context(app: &AppHandle) -> Result<Option<RadialContext>, String> {
|
||||
let state = app.state::<AppState>();
|
||||
let files = state
|
||||
.radial_files
|
||||
.lock()
|
||||
|
|
@ -439,14 +524,15 @@ pub fn get_radial_context(
|
|||
if files.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let dragging = *state
|
||||
.radial_dragging
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(Some(RadialContext {
|
||||
file_info: crate::files::inspect_paths(&files)?,
|
||||
files,
|
||||
mode,
|
||||
dragging: *state
|
||||
.radial_dragging
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?,
|
||||
dragging,
|
||||
}))
|
||||
}
|
||||
|
||||
|
|
@ -457,7 +543,7 @@ pub fn hide_radial(app: AppHandle) -> Result<(), String> {
|
|||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn show_files_in_radial(
|
||||
pub async fn show_files_in_radial(
|
||||
app: AppHandle,
|
||||
files: Vec<String>,
|
||||
mode: Option<String>,
|
||||
|
|
@ -465,12 +551,15 @@ pub fn show_files_in_radial(
|
|||
if files.is_empty() {
|
||||
return Err("No files selected.".into());
|
||||
}
|
||||
show_radial(
|
||||
&app,
|
||||
files,
|
||||
mode.as_deref().unwrap_or("actions"),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
show_radial(
|
||||
&app,
|
||||
files,
|
||||
mode.as_deref().unwrap_or("actions"),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine as _};
|
||||
use image::{GenericImageView, Rgba, RgbaImage};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use crate::{
|
||||
|
|
@ -63,50 +66,216 @@ pub fn open_in_editor(app: AppHandle, path: String) -> Result<EditorInfo, String
|
|||
show_editor(&app, Path::new(&path))
|
||||
}
|
||||
|
||||
fn hex_encode(value: &str) -> String {
|
||||
value
|
||||
.as_bytes()
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
const PIN_LABEL: &str = "pin";
|
||||
const PIN_PREVIEW_EDGE: u32 = 1040;
|
||||
static PIN_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
/// Decoding a 100 MP image needs several hundred MiB before it is reduced to
|
||||
/// the 1040 px preview. Keep the decode bounded so a large photo cannot exhaust
|
||||
/// memory and stall Windows while the user is pinning it.
|
||||
const PIN_MAX_PIXELS: u64 = 40_000_000;
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PinnedPreview {
|
||||
pub id: u64,
|
||||
pub path: String,
|
||||
pub data_url: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
fn pin_preview(path: &Path) -> Result<PinnedPreview, String> {
|
||||
let (width, height) =
|
||||
image::image_dimensions(path).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
if u64::from(width) * u64::from(height) > PIN_MAX_PIXELS {
|
||||
return Err("This image is too large to pin safely.".into());
|
||||
}
|
||||
let image = image::open(path).map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let preview = flatten_for_pin(image.thumbnail(PIN_PREVIEW_EDGE, PIN_PREVIEW_EDGE));
|
||||
let (preview_width, preview_height) = preview.dimensions();
|
||||
let mut jpeg = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 82)
|
||||
.encode_image(&preview)
|
||||
.map_err(|error| format!("Could not prepare the pinned image: {error}"))?;
|
||||
Ok(PinnedPreview {
|
||||
id: 0,
|
||||
path: path.to_string_lossy().to_string(),
|
||||
data_url: format!("data:image/jpeg;base64,{}", STANDARD.encode(jpeg)),
|
||||
width: preview_width,
|
||||
height: preview_height,
|
||||
})
|
||||
}
|
||||
|
||||
/// JPEG has no alpha channel. Compose transparent pixels onto white first so
|
||||
/// screenshots with transparent backgrounds cannot turn black or show a blank
|
||||
/// surface after the preview is encoded.
|
||||
fn flatten_for_pin(image: image::DynamicImage) -> image::DynamicImage {
|
||||
if !image.color().has_alpha() {
|
||||
return image;
|
||||
}
|
||||
let rgba = image.to_rgba8();
|
||||
let mut flattened = RgbaImage::new(rgba.width(), rgba.height());
|
||||
for (x, y, pixel) in rgba.enumerate_pixels() {
|
||||
let alpha = f32::from(pixel[3]) / 255.0;
|
||||
let blend = |channel: u8| -> u8 {
|
||||
(f32::from(channel) * alpha + 255.0 * (1.0 - alpha))
|
||||
.round()
|
||||
.clamp(0.0, 255.0) as u8
|
||||
};
|
||||
flattened.put_pixel(
|
||||
x,
|
||||
y,
|
||||
Rgba([blend(pixel[0]), blend(pixel[1]), blend(pixel[2]), 255]),
|
||||
);
|
||||
}
|
||||
image::DynamicImage::ImageRgba8(flattened)
|
||||
}
|
||||
|
||||
fn show_on_main(app: &AppHandle) {
|
||||
let app_for_main = app.clone();
|
||||
let _ = app.run_on_main_thread(move || {
|
||||
let app = app_for_main;
|
||||
if let Some(window) = app.get_webview_window(PIN_LABEL) {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn is_current_pin(requested: Option<u64>, current: Option<u64>) -> bool {
|
||||
matches!((requested, current), (Some(requested), Some(current)) if requested == current)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn pin_image(app: AppHandle, path: String) -> Result<(), String> {
|
||||
let source = Path::new(&path);
|
||||
if !source.is_file() {
|
||||
return Err("The image to pin was not found.".into());
|
||||
}
|
||||
let (width, height) = image::image_dimensions(source)
|
||||
.map_err(|error| format!("Could not read image: {error}"))?;
|
||||
let max_edge = 520.0_f64;
|
||||
let scale = (max_edge / width.max(height) as f64).min(1.0);
|
||||
let window_width = (width as f64 * scale).max(160.0);
|
||||
let window_height = (height as f64 * scale).max(100.0);
|
||||
let label = format!("pin-{}", uuid::Uuid::new_v4());
|
||||
let url = format!("index.html?view=pin&path={}", hex_encode(&path));
|
||||
let mut builder =
|
||||
tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(url.into()))
|
||||
.title("Shift Pin")
|
||||
.inner_size(window_width, window_height)
|
||||
.min_inner_size(120.0, 80.0)
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.always_on_top(true)
|
||||
.resizable(true)
|
||||
.skip_taskbar(true)
|
||||
.shadow(true);
|
||||
if let Ok(cursor) = app.cursor_position() {
|
||||
if let Ok(Some(monitor)) = app.primary_monitor() {
|
||||
let monitor_scale = monitor.scale_factor();
|
||||
builder = builder.position(
|
||||
cursor.x / monitor_scale - window_width / 2.0,
|
||||
cursor.y / monitor_scale - window_height / 2.0,
|
||||
);
|
||||
pub async fn pin_image(app: AppHandle, path: String) -> Result<(), String> {
|
||||
let source = Path::new(&path).to_path_buf();
|
||||
let mut preview = tauri::async_runtime::spawn_blocking(move || {
|
||||
if !source.is_file() {
|
||||
return Err("The image to pin was not found.".to_string());
|
||||
}
|
||||
pin_preview(&source)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())??;
|
||||
preview.id = PIN_SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let max_edge = 520.0_f64;
|
||||
let scale = (max_edge / preview.width.max(preview.height) as f64).min(1.0);
|
||||
let window_width = (preview.width as f64 * scale).max(160.0);
|
||||
let window_height = (preview.height as f64 * scale).max(100.0);
|
||||
let window = app
|
||||
.get_webview_window(PIN_LABEL)
|
||||
.ok_or_else(|| "Pin window is unavailable.".to_string())?;
|
||||
window
|
||||
.set_size(tauri::LogicalSize::new(window_width, window_height))
|
||||
.map_err(|error| error.to_string())?;
|
||||
if let Some((cursor, monitor_scale)) = app.cursor_position().ok().and_then(|cursor| {
|
||||
window
|
||||
.monitor_from_point(cursor.x, cursor.y)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|monitor| (cursor, monitor.scale_factor()))
|
||||
}) {
|
||||
let physical_width = window_width * monitor_scale;
|
||||
let physical_height = window_height * monitor_scale;
|
||||
window
|
||||
.set_position(tauri::PhysicalPosition::new(
|
||||
(cursor.x - physical_width / 2.0).round() as i32,
|
||||
(cursor.y - physical_height / 2.0).round() as i32,
|
||||
))
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
let state = app.state::<AppState>();
|
||||
*state
|
||||
.pinned_image
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())? = Some(preview.clone());
|
||||
// The page starts dark and pulls the preview when this window becomes
|
||||
// visible. Waiting for renderer-side decoding before showing the window
|
||||
// deadlocks on both WKWebView and WebView2 because hidden webviews throttle
|
||||
// images, animation frames and events.
|
||||
window.show().map_err(|error| error.to_string())?;
|
||||
window.set_focus().map_err(|error| error.to_string())?;
|
||||
window
|
||||
.emit("pin://show", preview)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called by the renderer after its bitmap has decoded or failed. A command is
|
||||
/// used instead of a one-shot event so it cannot arrive before Rust listens.
|
||||
/// The sequence id keeps a late reply from an older pin from revealing the
|
||||
/// newer one before it has painted.
|
||||
#[tauri::command]
|
||||
pub fn pin_ready(app: AppHandle, id: Option<u64>) -> Result<(), String> {
|
||||
let state = app.state::<AppState>();
|
||||
let current = state
|
||||
.pinned_image
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.as_ref()
|
||||
.map(|preview| preview.id);
|
||||
if !is_current_pin(id, current) {
|
||||
return Ok(());
|
||||
}
|
||||
show_on_main(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_pinned_image(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<Option<PinnedPreview>, String> {
|
||||
Ok(state
|
||||
.pinned_image
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.clone())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn close_pin(app: AppHandle) -> Result<(), String> {
|
||||
if let Some(window) = app.get_webview_window(PIN_LABEL) {
|
||||
window.hide().map_err(|error| error.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{flatten_for_pin, is_current_pin};
|
||||
use image::{DynamicImage, Rgba, RgbaImage};
|
||||
|
||||
#[test]
|
||||
fn only_the_newest_pin_can_reveal_the_window() {
|
||||
assert!(is_current_pin(Some(4), Some(4)));
|
||||
assert!(!is_current_pin(None, None));
|
||||
assert!(!is_current_pin(None, Some(4)));
|
||||
assert!(!is_current_pin(Some(3), Some(4)));
|
||||
assert!(!is_current_pin(Some(4), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pin_window_is_created_before_the_first_pin() {
|
||||
let config: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
|
||||
let pin = config["app"]["windows"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|window| window["label"] == "pin")
|
||||
.expect("the pin window must exist when the app starts");
|
||||
assert_eq!(pin["url"], "index.html?view=pin");
|
||||
assert_eq!(pin["visible"], false);
|
||||
assert_eq!(pin["transparent"], false);
|
||||
assert_eq!(pin["alwaysOnTop"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_pixels_are_flattened_onto_white() {
|
||||
let mut image = RgbaImage::from_pixel(4, 4, Rgba([0, 0, 0, 0]));
|
||||
image.put_pixel(1, 1, Rgba([10, 20, 30, 128]));
|
||||
let flattened = flatten_for_pin(DynamicImage::ImageRgba8(image)).to_rgba8();
|
||||
assert_eq!(flattened.get_pixel(0, 0).0, [255, 255, 255, 255]);
|
||||
assert_eq!(flattened.get_pixel(1, 1).0, [132, 137, 142, 255]);
|
||||
}
|
||||
builder
|
||||
.build()
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -104,10 +104,7 @@ pub fn other_pids() -> Vec<u32> {
|
|||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let Ok(output) = std::process::Command::new("/usr/bin/pgrep")
|
||||
.args(["-x", "shift"])
|
||||
.output()
|
||||
else {
|
||||
let Ok(output) = crate::process::output("/usr/bin/pgrep", &["-x", "shift"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
other_instances(&String::from_utf8_lossy(&output.stdout), std::process::id())
|
||||
|
|
@ -138,10 +135,8 @@ fn is_installed(exe: &str) -> bool {
|
|||
|
||||
#[cfg(unix)]
|
||||
fn command_path(pid: u32) -> Option<String> {
|
||||
let output = std::process::Command::new("/bin/ps")
|
||||
.args(["-p", &pid.to_string(), "-o", "comm="])
|
||||
.output()
|
||||
.ok()?;
|
||||
let output =
|
||||
crate::process::output("/bin/ps", &["-p", &pid.to_string(), "-o", "comm="]).ok()?;
|
||||
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
|
@ -153,7 +148,15 @@ fn command_path(_pid: u32) -> Option<String> {
|
|||
|
||||
/// Ask the other copies to quit so this one can own the hotkeys.
|
||||
#[tauri::command]
|
||||
pub fn quit_other_instances() -> usize {
|
||||
// These two commands start `pgrep`/`ps` subprocesses, so they run on a blocking
|
||||
// thread: the UI polls them while settings toggles are being clicked.
|
||||
pub async fn quit_other_instances() -> usize {
|
||||
tauri::async_runtime::spawn_blocking(stop_other_instances)
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn stop_other_instances() -> usize {
|
||||
let mut stopped = 0;
|
||||
for pid in other_pids() {
|
||||
#[cfg(unix)]
|
||||
|
|
@ -169,8 +172,10 @@ pub fn quit_other_instances() -> usize {
|
|||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn hotkey_status() -> HotkeyStatus {
|
||||
status()
|
||||
pub async fn hotkey_status() -> HotkeyStatus {
|
||||
tauri::async_runtime::spawn_blocking(status)
|
||||
.await
|
||||
.unwrap_or_else(|_| status())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -1,20 +1,25 @@
|
|||
mod capture;
|
||||
mod autostart;
|
||||
mod capture;
|
||||
mod drag_bridge;
|
||||
mod editor;
|
||||
mod files;
|
||||
mod hotkeys;
|
||||
mod locale;
|
||||
mod markdown;
|
||||
mod models;
|
||||
mod office;
|
||||
mod pdf;
|
||||
mod process;
|
||||
mod recording;
|
||||
mod runtime;
|
||||
mod settings;
|
||||
mod share;
|
||||
|
||||
use std::{
|
||||
process::Child,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Mutex,
|
||||
Mutex, OnceLock,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -28,6 +33,16 @@ use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut,
|
|||
use models::{CaptureSessionInfo, EditorInfo};
|
||||
use recording::RecordingSession;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HeadlessActionRequest {
|
||||
action: String,
|
||||
paths: Vec<String>,
|
||||
target: Option<String>,
|
||||
output_dir: Option<String>,
|
||||
report: String,
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub capture: Mutex<Option<CaptureSessionInfo>>,
|
||||
pub recording: Mutex<Option<RecordingSession>>,
|
||||
|
|
@ -39,6 +54,26 @@ pub struct AppState {
|
|||
pub bridge: Mutex<Option<Child>>,
|
||||
/// Mirrors settings.drag_enabled so the drag monitors can check it cheaply.
|
||||
pub drag_enabled: AtomicBool,
|
||||
pub pinned_image: Mutex<Option<editor::PinnedPreview>>,
|
||||
}
|
||||
|
||||
/// The language the native tray is showing. The webview sends this before any
|
||||
/// settings disk read is needed, so a language click never waits on storage and
|
||||
/// the tray never rebuilds from a stale file snapshot.
|
||||
static TRAY_LANGUAGE: OnceLock<Mutex<&'static str>> = OnceLock::new();
|
||||
|
||||
fn tray_language() -> &'static str {
|
||||
TRAY_LANGUAGE
|
||||
.get()
|
||||
.and_then(|language| language.lock().ok().map(|value| *value))
|
||||
.unwrap_or_else(locale::system_language)
|
||||
}
|
||||
|
||||
pub(crate) fn set_tray_language(next: &'static str) {
|
||||
let holder = TRAY_LANGUAGE.get_or_init(|| Mutex::new(next));
|
||||
if let Ok(mut current) = holder.lock() {
|
||||
*current = next;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
|
|
@ -53,6 +88,7 @@ impl Default for AppState {
|
|||
radial_dragging: Mutex::new(false),
|
||||
drag_enabled: AtomicBool::new(true),
|
||||
bridge: Mutex::new(None),
|
||||
pinned_image: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -71,54 +107,71 @@ fn report_error(app: &AppHandle, message: impl Into<String>) {
|
|||
let _ = app.emit("app://error", message);
|
||||
}
|
||||
|
||||
/// Run capture work off the main thread. The closure gets its own `AppHandle`,
|
||||
/// so the thread outlives the tray or hotkey callback that started it.
|
||||
fn spawn_capture_work(
|
||||
app: &AppHandle,
|
||||
work: impl FnOnce(AppHandle) -> Result<(), String> + Send + 'static,
|
||||
) {
|
||||
let worker = app.clone();
|
||||
let reporter = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let result = tauri::async_runtime::spawn_blocking(move || work(worker)).await;
|
||||
if let Err(error) = result.unwrap_or_else(|_| Err("Capture was interrupted.".into())) {
|
||||
report_error(&reporter, error);
|
||||
show_main(&reporter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn start_capture_from_event(app: &AppHandle, mode: &str) {
|
||||
if let Err(error) = capture::begin_capture(app, mode) {
|
||||
report_error(app, error);
|
||||
show_main(app);
|
||||
}
|
||||
let mode = mode.to_string();
|
||||
spawn_capture_work(app, move |app| {
|
||||
capture::begin_capture(&app, &mode).map(|_| ())
|
||||
});
|
||||
}
|
||||
|
||||
fn start_fullscreen_capture(app: &AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
if let Err(error) = capture::capture_fullscreen_core(app, &state) {
|
||||
report_error(app, error);
|
||||
show_main(app);
|
||||
}
|
||||
spawn_capture_work(app, move |app| {
|
||||
let state = app.state::<AppState>();
|
||||
capture::capture_fullscreen_core(&app, &state).map(|_| ())
|
||||
});
|
||||
}
|
||||
|
||||
fn toggle_recording(app: &AppHandle) {
|
||||
let Some(state) = app.try_state::<AppState>() else {
|
||||
let recording = app
|
||||
.try_state::<AppState>()
|
||||
.and_then(|state| state.recording.lock().ok().map(|session| session.is_some()))
|
||||
.unwrap_or(false);
|
||||
if !recording {
|
||||
start_capture_from_event(app, "recording");
|
||||
return;
|
||||
};
|
||||
let active = state
|
||||
.recording
|
||||
.lock()
|
||||
.map(|recording| recording.is_some())
|
||||
.unwrap_or(false);
|
||||
if active {
|
||||
if let Err(error) = recording::stop(app, &state) {
|
||||
report_error(app, error);
|
||||
}
|
||||
} else {
|
||||
start_capture_from_event(app, "recording");
|
||||
}
|
||||
// Stopping waits for the encoder to finalize the file, up to a few seconds.
|
||||
spawn_capture_work(app, move |app| {
|
||||
let state = app.state::<AppState>();
|
||||
recording::stop(&app, &state).map(|_| ())
|
||||
});
|
||||
}
|
||||
|
||||
fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
|
||||
let open = MenuItem::with_id(app, "open", "Open Shift", true, None::<&str>)?;
|
||||
let capture = MenuItem::with_id(app, "capture", "Capture area", true, Some("Alt+Shift+2"))?;
|
||||
/// The tray belongs to Rust, so it cannot read the language from the webview
|
||||
/// bundle. Build it from the in-memory language; never touch settings.json from
|
||||
/// the native UI path.
|
||||
fn tray_menu(app: &AppHandle, language: &str) -> tauri::Result<Menu<tauri::Wry>> {
|
||||
let titles = locale::tray_titles(language);
|
||||
let open = MenuItem::with_id(app, "open", titles.open, true, None::<&str>)?;
|
||||
let capture = MenuItem::with_id(app, "capture", titles.capture, true, Some("Alt+Shift+2"))?;
|
||||
let fullscreen = MenuItem::with_id(
|
||||
app,
|
||||
"fullscreen",
|
||||
"Capture full screen",
|
||||
titles.fullscreen,
|
||||
true,
|
||||
Some("Alt+Shift+4"),
|
||||
)?;
|
||||
let record = MenuItem::with_id(app, "record", "Record area", true, Some("Alt+Shift+3"))?;
|
||||
let ocr = MenuItem::with_id(app, "ocr", "OCR an image…", true, None::<&str>)?;
|
||||
let record = MenuItem::with_id(app, "record", titles.record, true, Some("Alt+Shift+3"))?;
|
||||
let ocr = MenuItem::with_id(app, "ocr", titles.ocr, true, None::<&str>)?;
|
||||
let separator = PredefinedMenuItem::separator(app)?;
|
||||
let quit = MenuItem::with_id(app, "quit", "Quit Shift", true, Some("CmdOrCtrl+Q"))?;
|
||||
let quit = MenuItem::with_id(app, "quit", titles.quit, true, Some("CmdOrCtrl+Q"))?;
|
||||
let menu = Menu::with_items(
|
||||
app,
|
||||
&[
|
||||
|
|
@ -131,6 +184,28 @@ fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
|
|||
&quit,
|
||||
],
|
||||
)?;
|
||||
Ok(menu)
|
||||
}
|
||||
|
||||
/// Rebuild the small menu and hand it to the tray in one operation. Updating
|
||||
/// each item separately waits once per item on the native main thread; a single
|
||||
/// `set_menu` reduces that to one hop.
|
||||
pub fn refresh_tray_language(app: &AppHandle) -> Result<(), String> {
|
||||
let Some(tray) = app.tray_by_id("shift") else {
|
||||
return Ok(());
|
||||
};
|
||||
let language = tray_language();
|
||||
let menu = tray_menu(app, language).map_err(|error| error.to_string())?;
|
||||
tray.set_menu(Some(menu))
|
||||
.map_err(|error| format!("Could not update the tray menu: {error}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
|
||||
let persisted = settings::load(app);
|
||||
let language = locale::preferred(Some(&persisted.language));
|
||||
set_tray_language(language);
|
||||
let menu = tray_menu(app, language)?;
|
||||
|
||||
let mut tray = TrayIconBuilder::with_id("shift")
|
||||
.menu(&menu)
|
||||
|
|
@ -158,17 +233,21 @@ fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
|
|||
/// Take back the capture hotkeys after duplicate copies were quit. macOS routes a
|
||||
/// hotkey to whichever client registered it first, so the survivor must register again.
|
||||
#[tauri::command]
|
||||
fn reclaim_hotkeys(app: AppHandle) -> hotkeys::HotkeyStatus {
|
||||
// Take the instance lock as well, so this copy is the owner once the others die.
|
||||
let _ = hotkeys::acquire_instance(&app);
|
||||
for shortcut in hotkeys::HOTKEYS {
|
||||
let _ = app.global_shortcut().unregister(shortcut);
|
||||
}
|
||||
let _ = register_shortcuts(&app);
|
||||
hotkeys::status()
|
||||
async fn reclaim_hotkeys(app: AppHandle) -> hotkeys::HotkeyStatus {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
// Take the instance lock as well, so this copy is the owner once the
|
||||
// others die.
|
||||
let _ = hotkeys::acquire_instance(&app);
|
||||
for shortcut in hotkeys::HOTKEYS {
|
||||
let _ = app.global_shortcut().unregister(shortcut);
|
||||
}
|
||||
let _ = register_shortcuts(&app);
|
||||
hotkeys::status()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| hotkeys::status())
|
||||
}
|
||||
|
||||
|
||||
fn shortcut_action(shortcut: &Shortcut) -> Option<&'static str> {
|
||||
if shortcut.matches(Modifiers::ALT | Modifiers::SHIFT, Code::Digit2) {
|
||||
Some("capture")
|
||||
|
|
@ -183,11 +262,7 @@ fn shortcut_action(shortcut: &Shortcut) -> Option<&'static str> {
|
|||
|
||||
fn register_shortcuts(app: &AppHandle) -> tauri::Result<()> {
|
||||
let mut all_ok = true;
|
||||
for shortcut in [
|
||||
"Alt+Shift+2",
|
||||
"Alt+Shift+3",
|
||||
"Alt+Shift+4",
|
||||
] {
|
||||
for shortcut in ["Alt+Shift+2", "Alt+Shift+3", "Alt+Shift+4"] {
|
||||
match app.global_shortcut().register(shortcut) {
|
||||
Ok(()) => {
|
||||
eprintln!("Registered global shortcut: {shortcut}");
|
||||
|
|
@ -202,8 +277,72 @@ fn register_shortcuts(app: &AppHandle) -> tauri::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs one file action without starting Tauri. This exists for unattended
|
||||
/// Windows integration tests, where the conversion engines must be exercised
|
||||
/// independently from the WebView and radial gesture.
|
||||
fn run_headless_action() -> Option<i32> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
if args.next().as_deref() != Some("--headless-action") {
|
||||
return None;
|
||||
}
|
||||
let Some(request_path) = args.next() else {
|
||||
return Some(2);
|
||||
};
|
||||
let request = match std::fs::read_to_string(&request_path)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|text| {
|
||||
serde_json::from_str::<HeadlessActionRequest>(&text).map_err(|error| error.to_string())
|
||||
}) {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
eprintln!("headless action request failed: {error}");
|
||||
return Some(2);
|
||||
}
|
||||
};
|
||||
let output_dir = request.output_dir.as_deref().map(std::path::Path::new);
|
||||
let result = files::perform_action(
|
||||
&request.action,
|
||||
&request.paths,
|
||||
request.target.as_deref(),
|
||||
output_dir,
|
||||
None,
|
||||
);
|
||||
let report = match &result {
|
||||
Ok(outcome) => serde_json::json!({
|
||||
"ok": true,
|
||||
"outcome": outcome,
|
||||
"error": null,
|
||||
}),
|
||||
Err(error) => serde_json::json!({
|
||||
"ok": false,
|
||||
"outcome": null,
|
||||
"error": error,
|
||||
}),
|
||||
};
|
||||
let report_path = std::path::Path::new(&request.report);
|
||||
if let Some(parent) = report_path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let payload = match serde_json::to_vec_pretty(&report) {
|
||||
Ok(payload) => payload,
|
||||
Err(error) => {
|
||||
eprintln!("headless action report serialization failed: {error}");
|
||||
return Some(2);
|
||||
}
|
||||
};
|
||||
if let Err(error) = std::fs::write(report_path, payload) {
|
||||
eprintln!("headless action report failed: {error}");
|
||||
return Some(2);
|
||||
}
|
||||
Some(if result.is_ok() { 0 } else { 1 })
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
if let Some(code) = run_headless_action() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
let shortcut_plugin = tauri_plugin_global_shortcut::Builder::new()
|
||||
.with_handler(|app, shortcut, event| {
|
||||
if event.state() != ShortcutState::Pressed {
|
||||
|
|
@ -224,26 +363,32 @@ pub fn run() {
|
|||
.plugin(tauri_plugin_clipboard_manager::init())
|
||||
.plugin(shortcut_plugin)
|
||||
.manage(AppState::default())
|
||||
.manage(share::ShareState::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
files::inspect_files,
|
||||
files::perform_file_action,
|
||||
files::reveal_file,
|
||||
files::existing_files,
|
||||
files::open_file,
|
||||
files::read_file_data_url,
|
||||
files::read_text_file,
|
||||
files::read_image_data,
|
||||
files::save_image_data,
|
||||
files::render_pdf_pages,
|
||||
files::cleanup_pdf_pages,
|
||||
files::save_text_near,
|
||||
settings::get_app_settings,
|
||||
settings::set_output_directory,
|
||||
settings::set_file_output_mode,
|
||||
settings::set_auto_reveal,
|
||||
settings::set_drag_enabled,
|
||||
settings::set_share_enabled,
|
||||
settings::set_autostart,
|
||||
settings::check_output_access,
|
||||
settings::set_language,
|
||||
settings::reveal_output_directory,
|
||||
settings::open_files_permission_settings,
|
||||
runtime::machine_info,
|
||||
runtime::install_runtime_component,
|
||||
capture::get_capture_session,
|
||||
capture::screen_capture_access_status,
|
||||
capture::start_capture,
|
||||
|
|
@ -262,20 +407,36 @@ pub fn run() {
|
|||
editor::close_editor,
|
||||
editor::open_in_editor,
|
||||
editor::pin_image,
|
||||
editor::get_pinned_image,
|
||||
editor::pin_ready,
|
||||
editor::close_pin,
|
||||
drag_bridge::get_radial_context,
|
||||
drag_bridge::hide_radial,
|
||||
drag_bridge::show_files_in_radial,
|
||||
share::share_peers,
|
||||
share::share_answer,
|
||||
share::share_refresh,
|
||||
share::share_send,
|
||||
])
|
||||
.setup(|app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
|
||||
// WebView2 does not reliably initialise drag-and-drop for windows
|
||||
// created hidden. The transparent radial can be shown at startup
|
||||
// and hidden here without becoming visible to the user.
|
||||
if let Some(radial) = app.get_webview_window("radial") {
|
||||
let _ = radial.hide();
|
||||
}
|
||||
|
||||
if !hotkeys::acquire_instance(app.handle()) {
|
||||
// A first copy already owns the hotkeys, so this copy's keyboard
|
||||
// shortcuts can never fire. Stay usable, but let the UI say so
|
||||
// instead of exiting silently: Settings offers a one-click takeover.
|
||||
hotkeys::note_registration_failed();
|
||||
eprintln!("Another Shift instance is running; the global hotkeys belong to that copy.");
|
||||
eprintln!(
|
||||
"Another Shift instance is running; the global hotkeys belong to that copy."
|
||||
);
|
||||
}
|
||||
|
||||
// Restore the persisted switch before the drag monitors start.
|
||||
|
|
@ -285,6 +446,7 @@ pub fn run() {
|
|||
.drag_enabled
|
||||
.store(persisted.drag_enabled, Ordering::Relaxed);
|
||||
}
|
||||
share::set_enabled(app.handle(), persisted.share_enabled);
|
||||
if persisted.autostart != autostart::is_enabled() {
|
||||
if let Err(error) = autostart::set_enabled(persisted.autostart) {
|
||||
eprintln!("Could not sync launch at login: {error}");
|
||||
|
|
@ -294,15 +456,26 @@ pub fn run() {
|
|||
setup_tray(app.handle())?;
|
||||
register_shortcuts(app.handle())?;
|
||||
drag_bridge::spawn(app.handle());
|
||||
share::spawn(app.handle());
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
if matches!(window.label(), "main" | "editor" | "radial") {
|
||||
if matches!(window.label(), "main" | "editor" | "radial" | "pin") {
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
// An incoming-file card that disappears without an answer means the
|
||||
// user dismissed it; tell the sender now instead of after its timeout.
|
||||
if let WindowEvent::Destroyed = event {
|
||||
if window.label().starts_with("share-") {
|
||||
window
|
||||
.app_handle()
|
||||
.state::<share::ShareState>()
|
||||
.reject_notice(window.label());
|
||||
}
|
||||
}
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building Shift");
|
||||
|
|
@ -340,7 +513,50 @@ mod tests {
|
|||
fn file_menu_hotkey_is_not_listening() {
|
||||
// The radial menu is driven by chosen files, so no hotkey reads the
|
||||
// file manager selection any more.
|
||||
assert_eq!(shortcut_action(&Shortcut::from_str("Alt+Shift+Space").unwrap()), None);
|
||||
assert_eq!(
|
||||
shortcut_action(&Shortcut::from_str("Alt+Shift+Space").unwrap()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_child_process_is_started_without_hiding_its_console() {
|
||||
// A Windows GUI build owns no console, so a bare `Command::new` allocates
|
||||
// a visible one: the "black window keeps blinking" report. Every spawn in
|
||||
// the app must go through a process helper that hides it.
|
||||
let sources = [
|
||||
("autostart.rs", include_str!("autostart.rs")),
|
||||
("capture.rs", include_str!("capture.rs")),
|
||||
("drag_bridge.rs", include_str!("drag_bridge.rs")),
|
||||
("editor.rs", include_str!("editor.rs")),
|
||||
("files.rs", include_str!("files.rs")),
|
||||
("hotkeys.rs", include_str!("hotkeys.rs")),
|
||||
("pdf.rs", include_str!("pdf.rs")),
|
||||
("recording.rs", include_str!("recording.rs")),
|
||||
("runtime.rs", include_str!("runtime.rs")),
|
||||
("settings.rs", include_str!("settings.rs")),
|
||||
("share.rs", include_str!("share.rs")),
|
||||
];
|
||||
for (name, source) in sources {
|
||||
// Tests may spawn freely; only shipped code needs the helper.
|
||||
let production = source
|
||||
.split("#[cfg(test)]")
|
||||
.next()
|
||||
.unwrap()
|
||||
.split("#[cfg(all(test")
|
||||
.next()
|
||||
.unwrap();
|
||||
for (index, line) in production.lines().enumerate() {
|
||||
let bare = line.contains("Command::new(")
|
||||
&& !line.contains("process::command(")
|
||||
&& !line.contains("process::hidden(");
|
||||
assert!(
|
||||
!bare,
|
||||
"{name}:{} starts a process without the console helper: {line}",
|
||||
index + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -351,4 +567,14 @@ mod tests {
|
|||
let production = include_str!("lib.rs").split("#[cfg(test)]").next().unwrap();
|
||||
assert_eq!(production.matches("TrayIconBuilder::with_id").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_startup_uses_the_registry_api_not_reg_exe() {
|
||||
let production = include_str!("autostart.rs")
|
||||
.split("#[cfg(test)]")
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(!production.contains("process::status(\"reg\""));
|
||||
assert!(!production.contains("Command::new(\"reg\""));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,245 @@
|
|||
//! Which language the interface should use before the webview can say otherwise.
|
||||
//!
|
||||
//! The tray menu is built in Rust, so it needs the same language the UI shows.
|
||||
//! A language chosen in Settings wins; otherwise the operating system's own UI
|
||||
//! language decides, which is what the webview does on a first run.
|
||||
|
||||
pub const ENGLISH: &str = "en";
|
||||
pub const CHINESE: &str = "zh";
|
||||
|
||||
/// Normalise anything language-shaped ("zh", "zh-CN", "zh_Hans") to a UI language.
|
||||
pub fn normalize(candidate: Option<&str>) -> Option<&'static str> {
|
||||
let value = candidate?.trim().to_ascii_lowercase();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if value.starts_with("zh") {
|
||||
return Some(CHINESE);
|
||||
}
|
||||
Some(ENGLISH)
|
||||
}
|
||||
|
||||
/// The operating system's UI language, as a UI language.
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub fn system_language() -> &'static str {
|
||||
normalize(Some(&system_locale())).unwrap_or(ENGLISH)
|
||||
}
|
||||
|
||||
/// The operating system's UI language, as a UI language.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn system_language() -> &'static str {
|
||||
system_language_windows()
|
||||
}
|
||||
|
||||
/// The first locale in the `AppleLanguages` list, which `defaults` prints as a
|
||||
/// parenthesised list with the most preferred locale first.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn first_apple_locale(text: &str) -> Option<&str> {
|
||||
text.lines()
|
||||
.map(|line| line.trim().trim_end_matches(',').trim())
|
||||
.filter(|entry| *entry != "(" && *entry != ")")
|
||||
.map(|entry| entry.trim_matches('"').trim())
|
||||
.find(|entry| !entry.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn system_locale() -> String {
|
||||
// `AppleLanguages` is what System Settings writes, and it survives the
|
||||
// stripped environment a LaunchAgent starts the app with.
|
||||
if let Ok(output) = crate::process::output("defaults", &["read", "-g", "AppleLanguages"]) {
|
||||
if output.status.success() {
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(first) = first_apple_locale(&text) {
|
||||
return first.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
std::env::var("LANG").unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `LANG_CHINESE` from the Windows language identifiers: one primary language
|
||||
/// covers every regional Chinese, the sub-language only picks the script.
|
||||
#[cfg(target_os = "windows")]
|
||||
const WINDOWS_LANG_CHINESE: u16 = 0x04;
|
||||
|
||||
/// Map a Windows UI LANGID to a UI language. The primary language sits in the
|
||||
/// low 10 bits; the sub-language is deliberately ignored because Shift offers one
|
||||
/// Chinese, the same reading the webview takes from `navigator.language`.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn from_windows_langid(langid: u16) -> &'static str {
|
||||
if (langid & 0x03FF) == WINDOWS_LANG_CHINESE {
|
||||
CHINESE
|
||||
} else {
|
||||
ENGLISH
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn system_language_windows() -> &'static str {
|
||||
use windows_sys::Win32::Globalization::GetUserDefaultUILanguage;
|
||||
|
||||
from_windows_langid(unsafe { GetUserDefaultUILanguage() })
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn system_locale() -> String {
|
||||
std::env::var("LC_ALL")
|
||||
.or_else(|_| std::env::var("LC_MESSAGES"))
|
||||
.or_else(|_| std::env::var("LANG"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A stored setting only counts when it is one of the two UI languages.
|
||||
pub fn from_setting(stored: Option<&str>) -> Option<&'static str> {
|
||||
match stored.map(str::trim).map(str::to_ascii_lowercase) {
|
||||
Some(value) if value == CHINESE => Some(CHINESE),
|
||||
Some(value) if value == ENGLISH => Some(ENGLISH),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The language the tray and any other native surface should use.
|
||||
pub fn preferred(stored: Option<&str>) -> &'static str {
|
||||
from_setting(stored).unwrap_or_else(system_language)
|
||||
}
|
||||
|
||||
/// Tray titles. Kept here rather than in the webview bundle because the tray has
|
||||
/// to be right before the first window has loaded.
|
||||
pub struct TrayTitles {
|
||||
pub open: &'static str,
|
||||
pub capture: &'static str,
|
||||
pub fullscreen: &'static str,
|
||||
pub record: &'static str,
|
||||
pub ocr: &'static str,
|
||||
pub quit: &'static str,
|
||||
}
|
||||
|
||||
pub fn tray_titles(language: &str) -> TrayTitles {
|
||||
if language == CHINESE {
|
||||
TrayTitles {
|
||||
open: "打开 Shift",
|
||||
capture: "区域截图",
|
||||
fullscreen: "全屏截图",
|
||||
record: "区域录屏",
|
||||
ocr: "识别图片文字…",
|
||||
quit: "退出 Shift",
|
||||
}
|
||||
} else {
|
||||
TrayTitles {
|
||||
open: "Open Shift",
|
||||
capture: "Capture area",
|
||||
fullscreen: "Capture full screen",
|
||||
record: "Record area",
|
||||
ocr: "OCR an image…",
|
||||
quit: "Quit Shift",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn chinese_variants_all_select_chinese() {
|
||||
for candidate in ["zh", "zh-CN", "zh-Hans", "zh_TW", " ZH-Hant "] {
|
||||
assert_eq!(normalize(Some(candidate)), Some(CHINESE), "{candidate}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_else_selects_english() {
|
||||
for candidate in ["en", "en-GB", "de", "ja", "fr-CA"] {
|
||||
assert_eq!(normalize(Some(candidate)), Some(ENGLISH), "{candidate}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_or_missing_candidate_is_no_preference() {
|
||||
assert_eq!(normalize(None), None);
|
||||
assert_eq!(normalize(Some("")), None);
|
||||
assert_eq!(normalize(Some(" ")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_two_ui_languages_can_be_persisted() {
|
||||
assert_eq!(from_setting(Some("zh")), Some(CHINESE));
|
||||
assert_eq!(from_setting(Some("en")), Some(ENGLISH));
|
||||
// A locale rather than a UI language, or a stray value, falls back to the OS.
|
||||
assert_eq!(from_setting(Some("zh-CN")), None);
|
||||
assert_eq!(from_setting(Some("german")), None);
|
||||
assert_eq!(from_setting(None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_choice_beats_the_system_language() {
|
||||
assert_eq!(preferred(Some("zh")), CHINESE);
|
||||
assert_eq!(preferred(Some("en")), ENGLISH);
|
||||
assert!(matches!(preferred(None), ENGLISH | CHINESE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tray_speaks_whichever_language_was_chosen() {
|
||||
let chinese = tray_titles(CHINESE);
|
||||
assert_eq!(chinese.quit, "退出 Shift");
|
||||
assert_eq!(chinese.capture, "区域截图");
|
||||
let english = tray_titles(ENGLISH);
|
||||
assert_eq!(english.quit, "Quit Shift");
|
||||
assert_eq!(english.capture, "Capture area");
|
||||
// Chinese is the only other language, so anything else means English.
|
||||
assert_eq!(tray_titles("de").open, english.open);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn every_windows_chinese_langid_selects_chinese() {
|
||||
// zh-CN, zh-TW and zh-SG share one primary language and differ only in
|
||||
// sub-language; anything else, including lookalike ids, stays English.
|
||||
for langid in [0x0804_u16, 0x0404, 0x1004] {
|
||||
assert_eq!(from_windows_langid(langid), CHINESE, "{langid:#06x}");
|
||||
}
|
||||
// 0x0409 en-US, 0x0407 de-DE, 0x0415 pl-PL, 0x0419 ru-RU, 0x040C fr-FR.
|
||||
for langid in [0x0409_u16, 0x0407, 0x0415, 0x0419, 0x040C] {
|
||||
assert_eq!(from_windows_langid(langid), ENGLISH, "{langid:#06x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_language_is_always_a_ui_language() {
|
||||
assert!(matches!(system_language(), ENGLISH | CHINESE));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
mod apple_locale_parsing {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_preferred_locale_wins() {
|
||||
let listing = "(\n \"zh-Hans-CN\",\n \"en-US\"\n)\n";
|
||||
assert_eq!(first_apple_locale(listing), Some("zh-Hans-CN"));
|
||||
assert_eq!(
|
||||
normalize(Some(first_apple_locale(listing).unwrap())),
|
||||
Some(CHINESE)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_english_first_list_stays_english() {
|
||||
let listing = "(\n \"en-US\",\n \"fr\"\n)\n";
|
||||
assert_eq!(normalize(first_apple_locale(listing)), Some(ENGLISH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_entry_list_still_parses() {
|
||||
let listing = "(\n \"zh-Hans-CN\"\n)\n";
|
||||
assert_eq!(first_apple_locale(listing), Some("zh-Hans-CN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_useful_is_no_preference() {
|
||||
assert_eq!(first_apple_locale("(\n)\n"), None);
|
||||
assert_eq!(first_apple_locale(""), None);
|
||||
assert_eq!(first_apple_locale("(\n \"\"\n)\n"), None);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,380 @@
|
|||
//! A small Markdown to HTML writer.
|
||||
//!
|
||||
//! Pandoc renders documents beautifully but is an optional external tool, and
|
||||
//! without it Markdown used to fall through to the plain-text path, which
|
||||
//! printed the markup verbatim. This covers the common syntax so headings,
|
||||
//! lists and code are rendered wherever Pandoc is missing.
|
||||
|
||||
fn escape_html(value: &str) -> String {
|
||||
let mut output = String::with_capacity(value.len());
|
||||
for character in value.chars() {
|
||||
match character {
|
||||
'&' => output.push_str("&"),
|
||||
'<' => output.push_str("<"),
|
||||
'>' => output.push_str(">"),
|
||||
'"' => output.push_str("""),
|
||||
other => output.push(other),
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Rewrites inline spans: code, emphasis, strikethrough and links.
|
||||
fn inline(text: &str) -> String {
|
||||
let characters: Vec<char> = text.chars().collect();
|
||||
let mut output = String::new();
|
||||
let mut index = 0;
|
||||
while index < characters.len() {
|
||||
let character = characters[index];
|
||||
match character {
|
||||
'`' => {
|
||||
if let Some(end) = find(&characters, index + 1, '`') {
|
||||
output.push_str("<code>");
|
||||
output.push_str(&escape_html(&String::from_iter(
|
||||
&characters[index + 1..end],
|
||||
)));
|
||||
output.push_str("</code>");
|
||||
index = end + 1;
|
||||
} else {
|
||||
output.push_str(&escape_html(&character.to_string()));
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
'!' if index + 1 < characters.len() && characters[index + 1] == '[' => {
|
||||
if let Some(closing) = find(&characters, index + 2, ']') {
|
||||
if closing + 1 < characters.len() && characters[closing + 1] == '(' {
|
||||
if let Some(end) = find(&characters, closing + 2, ')') {
|
||||
let alt = String::from_iter(&characters[index + 2..closing]);
|
||||
let url = String::from_iter(&characters[closing + 2..end]);
|
||||
output.push_str("<img src=\"");
|
||||
output.push_str(&escape_html(&url));
|
||||
output.push_str("\" alt=\"");
|
||||
output.push_str(&escape_html(&alt));
|
||||
output.push_str("\" />");
|
||||
index = end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push_str("!");
|
||||
index += 1;
|
||||
}
|
||||
'[' => {
|
||||
// A link needs `[text](` before the closing bracket is trusted.
|
||||
if let Some(closing) = find(&characters, index + 1, ']') {
|
||||
let label = &characters[index + 1..closing];
|
||||
if closing + 1 < characters.len() && characters[closing + 1] == '(' {
|
||||
if let Some(end) = find(&characters, closing + 2, ')') {
|
||||
let url = String::from_iter(&characters[closing + 2..end]);
|
||||
output.push_str("<a href=\"");
|
||||
output.push_str(&escape_html(&url));
|
||||
output.push_str("\">");
|
||||
output.push_str(&inline(&String::from_iter(label)));
|
||||
output.push_str("</a>");
|
||||
index = end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push_str(&escape_html(&character.to_string()));
|
||||
index += 1;
|
||||
}
|
||||
'~' if starts_at(&characters, index, "~~") => {
|
||||
if let Some(end) = find_pair(&characters, index + 2, "~~") {
|
||||
output.push_str("<del>");
|
||||
output.push_str(&inline(&String::from_iter(&characters[index + 2..end])));
|
||||
output.push_str("</del>");
|
||||
index = end + 2;
|
||||
} else {
|
||||
output.push_str(&escape_html(&character.to_string()));
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
'*' | '_' => {
|
||||
let double =
|
||||
starts_at(&characters, index, "**") || starts_at(&characters, index, "__");
|
||||
let width = if double { 2 } else { 1 };
|
||||
let marker = String::from_iter(characters[index..index + width].iter());
|
||||
if let Some(end) = find_pair(&characters, index + width, &marker) {
|
||||
let tag = if double { "strong" } else { "em" };
|
||||
let inner = String::from_iter(&characters[index + width..end]);
|
||||
if !inner.trim().is_empty() {
|
||||
output.push_str(&format!("<{tag}>"));
|
||||
output.push_str(&inline(&inner));
|
||||
output.push_str(&format!("</{tag}>"));
|
||||
index = end + width;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
output.push_str(&escape_html(&character.to_string()));
|
||||
index += 1;
|
||||
}
|
||||
other => {
|
||||
output.push_str(&escape_html(&other.to_string()));
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn find(haystack: &[char], from: usize, needle: char) -> Option<usize> {
|
||||
(from..haystack.len()).find(|index| haystack[*index] == needle)
|
||||
}
|
||||
|
||||
fn find_pair(haystack: &[char], from: usize, needle: &str) -> Option<usize> {
|
||||
let needle: Vec<char> = needle.chars().collect();
|
||||
if needle.is_empty() {
|
||||
return None;
|
||||
}
|
||||
(from..haystack.len().saturating_sub(needle.len() - 1))
|
||||
.find(|index| starts_at(haystack, *index, &String::from_iter(&needle)))
|
||||
}
|
||||
|
||||
fn starts_at(haystack: &[char], index: usize, needle: &str) -> bool {
|
||||
let needle: Vec<char> = needle.chars().collect();
|
||||
!needle.is_empty()
|
||||
&& index + needle.len() <= haystack.len()
|
||||
&& haystack[index..index + needle.len()] == needle[..]
|
||||
}
|
||||
|
||||
fn split_row(line: &str) -> Vec<String> {
|
||||
line.trim()
|
||||
.trim_matches('|')
|
||||
.split('|')
|
||||
.map(|cell| inline(cell.trim()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_rule(line: &str) -> bool {
|
||||
let trimmed = line.trim();
|
||||
trimmed.len() >= 3 && ["---", "***", "___"].contains(&trimmed)
|
||||
}
|
||||
|
||||
fn is_separator_row(line: &str) -> bool {
|
||||
let trimmed = line.trim().trim_matches('|');
|
||||
trimmed.contains('-')
|
||||
&& trimmed.split('|').all(|cell| {
|
||||
!cell.trim().is_empty() && cell.trim().chars().all(|c| matches!(c, '-' | ':' | ' '))
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders Markdown into a standalone HTML document.
|
||||
pub fn to_html(markdown: &str) -> String {
|
||||
let mut body = String::new();
|
||||
let lines: Vec<&str> = markdown.lines().collect();
|
||||
let mut index = 0;
|
||||
let mut paragraph: Vec<String> = Vec::new();
|
||||
|
||||
let flush_paragraph = |paragraph: &mut Vec<String>, body: &mut String| {
|
||||
if paragraph.is_empty() {
|
||||
return;
|
||||
}
|
||||
body.push_str("<p>");
|
||||
body.push_str(¶graph.join("<br />"));
|
||||
body.push_str("</p>\n");
|
||||
paragraph.clear();
|
||||
};
|
||||
|
||||
while index < lines.len() {
|
||||
let line = lines[index];
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
let fence = &trimmed[..3];
|
||||
let mut code: Vec<String> = Vec::new();
|
||||
index += 1;
|
||||
while index < lines.len() && !lines[index].trim().starts_with(fence) {
|
||||
code.push(escape_html(lines[index]));
|
||||
index += 1;
|
||||
}
|
||||
index += 1;
|
||||
body.push_str("<pre><code>");
|
||||
body.push_str(&code.join("\n"));
|
||||
body.push_str("</code></pre>\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
if trimmed.is_empty() {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_rule(trimmed) {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
body.push_str("<hr />\n");
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(level) = trimmed
|
||||
.find(' ')
|
||||
.filter(|_| trimmed.starts_with('#'))
|
||||
.map(|space| trimmed[..space].chars().filter(|c| *c == '#').count())
|
||||
.filter(|count| (1..=6).contains(count))
|
||||
{
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
let text = inline(trimmed[level..].trim());
|
||||
body.push_str(&format!("<h{level}>{text}</h{level}>\n"));
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if trimmed.contains('|') && index + 1 < lines.len() && is_separator_row(lines[index + 1]) {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
let header = split_row(trimmed);
|
||||
body.push_str("<table>\n<thead>\n<tr>");
|
||||
for cell in &header {
|
||||
body.push_str(&format!("<th>{cell}</th>"));
|
||||
}
|
||||
body.push_str("</tr>\n</thead>\n<tbody>\n");
|
||||
index += 2;
|
||||
while index < lines.len()
|
||||
&& lines[index].contains('|')
|
||||
&& !lines[index].trim().is_empty()
|
||||
{
|
||||
body.push_str("<tr>");
|
||||
for cell in split_row(lines[index]) {
|
||||
body.push_str(&format!("<td>{cell}</td>"));
|
||||
}
|
||||
body.push_str("</tr>\n");
|
||||
index += 1;
|
||||
}
|
||||
body.push_str("</tbody>\n</table>\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
if trimmed.starts_with("> ") || trimmed == ">" {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
let mut quote: Vec<String> = Vec::new();
|
||||
while index < lines.len()
|
||||
&& (lines[index].trim().starts_with("> ") || lines[index].trim() == ">")
|
||||
{
|
||||
quote.push(inline(lines[index].trim().trim_start_matches('>').trim()));
|
||||
index += 1;
|
||||
}
|
||||
body.push_str("<blockquote>");
|
||||
body.push_str("e.join("<br />"));
|
||||
body.push_str("</blockquote>\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
let bullet =
|
||||
trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with("+ ");
|
||||
let ordered = trimmed
|
||||
.find('.')
|
||||
.map(|dot| dot > 0 && trimmed[..dot].chars().all(|c| c.is_ascii_digit()))
|
||||
.unwrap_or(false)
|
||||
&& trimmed[trimmed.find('.').unwrap() + 1..].starts_with(' ');
|
||||
if bullet || ordered {
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
let tag = if ordered { "ol" } else { "ul" };
|
||||
body.push_str(&format!("<{tag}>\n"));
|
||||
while index < lines.len() {
|
||||
let item = lines[index].trim();
|
||||
let is_bullet =
|
||||
item.starts_with("- ") || item.starts_with("* ") || item.starts_with("+ ");
|
||||
let is_ordered = item
|
||||
.find('.')
|
||||
.map(|dot| dot > 0 && item[..dot].chars().all(|c| c.is_ascii_digit()))
|
||||
.unwrap_or(false)
|
||||
&& item.len() > item.find('.').unwrap() + 1
|
||||
&& item.as_bytes()[item.find('.').unwrap() + 1] == b' ';
|
||||
if (ordered && !is_ordered) || (bullet && !is_bullet && !is_ordered) {
|
||||
break;
|
||||
}
|
||||
let content = match item.find(' ') {
|
||||
Some(space) => inline(&item[space + 1..]),
|
||||
None => String::new(),
|
||||
};
|
||||
body.push_str(&format!("<li>{content}</li>\n"));
|
||||
index += 1;
|
||||
}
|
||||
body.push_str(&format!("</{tag}>\n"));
|
||||
continue;
|
||||
}
|
||||
|
||||
paragraph.push(inline(trimmed));
|
||||
index += 1;
|
||||
}
|
||||
flush_paragraph(&mut paragraph, &mut body);
|
||||
|
||||
format!(
|
||||
"<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<style>\n{}\n</style>\n</head>\n<body>\n{}\n</body>\n</html>\n",
|
||||
STYLE, body
|
||||
)
|
||||
}
|
||||
|
||||
/// Styles the rendered document so the PDF path produces a readable page.
|
||||
const STYLE: &str = r#"
|
||||
body { font-family: -apple-system, "Helvetica Neue", Arial, sans-serif; font-size: 13px; line-height: 1.6; color: #241a15; margin: 40px; }
|
||||
h1, h2, h3, h4, h5, h6 { margin: 18px 0 8px; line-height: 1.25; }
|
||||
h1 { font-size: 26px; } h2 { font-size: 21px; } h3 { font-size: 17px; }
|
||||
p { margin: 0 0 12px; }
|
||||
ul, ol { margin: 0 0 12px; padding-left: 22px; }
|
||||
code { font-family: "SF Mono", Menlo, monospace; font-size: 11.5px; background: rgba(120, 80, 55, 0.09); padding: 1px 4px; border-radius: 4px; }
|
||||
pre { background: rgba(120, 80, 55, 0.07); padding: 12px; border-radius: 8px; overflow-x: auto; }
|
||||
pre code { background: transparent; padding: 0; }
|
||||
blockquote { margin: 0 0 12px; padding-left: 12px; border-left: 3px solid rgba(200, 110, 60, 0.5); color: #5d463a; }
|
||||
table { border-collapse: collapse; margin: 0 0 12px; }
|
||||
th, td { border: 1px solid rgba(90, 60, 40, 0.25); padding: 6px 10px; text-align: left; }
|
||||
th { background: rgba(120, 80, 55, 0.08); }
|
||||
hr { border: 0; border-top: 1px solid rgba(90, 60, 40, 0.2); margin: 18px 0; }
|
||||
a { color: #c8541f; }
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_headings_and_emphasis() {
|
||||
let html =
|
||||
to_html("# Title\n\nSome **bold**, *some* `code` and [a link](https://example.com).\n");
|
||||
assert!(html.contains("<h1>Title</h1>"), "{html}");
|
||||
assert!(html.contains("<strong>bold</strong>"), "{html}");
|
||||
assert!(html.contains("<em>some</em>"), "{html}");
|
||||
assert!(html.contains("<code>code</code>"), "{html}");
|
||||
assert!(
|
||||
html.contains("<a href=\"https://example.com\">a link</a>"),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_lists_code_and_tables() {
|
||||
let html = to_html(
|
||||
"- one\n- two\n\n1. first\n2. second\n\n```rust\nlet x = 1;\n```\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n",
|
||||
);
|
||||
assert!(html.contains("<ul>\n<li>one</li>\n<li>two</li>"), "{html}");
|
||||
assert!(
|
||||
html.contains("<ol>\n<li>first</li>\n<li>second</li>"),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains("<pre><code>let x = 1;</code></pre>"),
|
||||
"{html}"
|
||||
);
|
||||
assert!(html.contains("<th>A</th>"), "{html}");
|
||||
assert!(html.contains("<td>2</td>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_raw_html_and_keeps_paragraphs() {
|
||||
let html = to_html("line one\nline two\n\n<script>alert(1)</script>\n");
|
||||
assert!(html.contains("line one<br />line two"), "{html}");
|
||||
assert!(html.contains("<script>"), "{html}");
|
||||
assert!(!html.contains("<script>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_relative_images() {
|
||||
let html = to_html("\n");
|
||||
assert!(
|
||||
html.contains(r#"<img src="images/system.png" alt="Architecture" />"#),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -48,6 +48,23 @@ pub struct ActionOutcome {
|
|||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionResultEvent {
|
||||
pub job_id: String,
|
||||
pub outcome: Option<ActionOutcome>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileActionProgress {
|
||||
pub job_id: String,
|
||||
pub done: u32,
|
||||
pub total: u32,
|
||||
pub packaging: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecordingInfo {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use std::{
|
||||
fs,
|
||||
io::Read,
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
|
|
@ -10,6 +10,148 @@ use zip::ZipArchive;
|
|||
|
||||
use crate::files::unique_output_in;
|
||||
|
||||
/// Extracts a DOCX whose body consists only of images, in document order.
|
||||
///
|
||||
/// AppKit's OOXML reader drops inline drawings from page-scan documents, which
|
||||
/// used to turn a 12-page file into one blank PDF page. Restricting this path
|
||||
/// to image-only bodies keeps normal text documents on the native renderer.
|
||||
pub fn document_page_images(
|
||||
input: &Path,
|
||||
output_dir: &Path,
|
||||
) -> Result<Option<Vec<PathBuf>>, String> {
|
||||
let file = fs::File::open(input).map_err(|error| error.to_string())?;
|
||||
let mut archive =
|
||||
ZipArchive::new(file).map_err(|error| format!("Could not read document: {error}"))?;
|
||||
let relationships = {
|
||||
let mut xml = String::new();
|
||||
archive
|
||||
.by_name("word/_rels/document.xml.rels")
|
||||
.map_err(|error| format!("Could not read document links: {error}"))?
|
||||
.read_to_string(&mut xml)
|
||||
.map_err(|error| error.to_string())?;
|
||||
document_image_links(&xml)?
|
||||
};
|
||||
let document = {
|
||||
let mut xml = String::new();
|
||||
archive
|
||||
.by_name("word/document.xml")
|
||||
.map_err(|error| format!("Could not read document body: {error}"))?
|
||||
.read_to_string(&mut xml)
|
||||
.map_err(|error| error.to_string())?;
|
||||
xml
|
||||
};
|
||||
let (image_ids, has_text) = document_body_summary(&document)?;
|
||||
if has_text || image_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut images = Vec::with_capacity(image_ids.len());
|
||||
for (index, relationship) in image_ids.into_iter().enumerate() {
|
||||
let Some(target) = relationships.get(&relationship) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let archive_path = if target.starts_with("word/") {
|
||||
target.clone()
|
||||
} else {
|
||||
format!("word/{}", target.trim_start_matches('/'))
|
||||
};
|
||||
if archive_path
|
||||
.split('/')
|
||||
.any(|part| part == ".." || part.is_empty())
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let extension = Path::new(target)
|
||||
.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.unwrap_or("img")
|
||||
.to_ascii_lowercase();
|
||||
let destination = output_dir.join(format!("page-{:03}.{extension}", index + 1));
|
||||
let mut entry = match archive.by_name(&archive_path) {
|
||||
Ok(entry) => entry,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut output = fs::File::create(&destination).map_err(|error| error.to_string())?;
|
||||
output
|
||||
.write_all(&bytes)
|
||||
.map_err(|error| error.to_string())?;
|
||||
images.push(destination);
|
||||
}
|
||||
Ok(Some(images))
|
||||
}
|
||||
|
||||
fn document_image_links(xml: &str) -> Result<std::collections::BTreeMap<String, String>, String> {
|
||||
let mut reader = XmlReader::from_str(xml);
|
||||
let mut links = std::collections::BTreeMap::new();
|
||||
loop {
|
||||
match reader.read_event() {
|
||||
Ok(Event::Start(element)) | Ok(Event::Empty(element))
|
||||
if local_name(element.name().as_ref()) == "Relationship" =>
|
||||
{
|
||||
let kind = attribute_value(&element, "Type").unwrap_or_default();
|
||||
if let (Some(id), Some(target)) = (
|
||||
attribute_value(&element, "Id"),
|
||||
attribute_value(&element, "Target"),
|
||||
) {
|
||||
if kind.ends_with("/image") {
|
||||
links.insert(id, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(_) => {}
|
||||
Err(error) => return Err(format!("Could not parse document links: {error}")),
|
||||
}
|
||||
}
|
||||
Ok(links)
|
||||
}
|
||||
|
||||
fn document_body_summary(xml: &str) -> Result<(Vec<String>, bool), String> {
|
||||
let mut reader = XmlReader::from_str(xml);
|
||||
reader.config_mut().trim_text(false);
|
||||
let mut images = Vec::new();
|
||||
let mut has_text = false;
|
||||
let mut in_text = false;
|
||||
loop {
|
||||
match reader.read_event() {
|
||||
Ok(Event::Start(element)) | Ok(Event::Empty(element)) => {
|
||||
match local_name(element.name().as_ref()) {
|
||||
"blip" => {
|
||||
if let Some(id) = attribute_value(&element, "embed") {
|
||||
images.push(id);
|
||||
}
|
||||
}
|
||||
"t" => in_text = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::Text(text)) if in_text => {
|
||||
let text = quick_xml::escape::unescape(&text)
|
||||
.map_err(|error| format!("Could not decode document text: {error}"))?;
|
||||
if !text.trim().is_empty() {
|
||||
has_text = true;
|
||||
}
|
||||
}
|
||||
Ok(Event::CData(text)) if in_text => {
|
||||
if !text.trim().is_empty() {
|
||||
has_text = true;
|
||||
}
|
||||
}
|
||||
Ok(Event::End(element)) if local_name(element.name().as_ref()) == "t" => {
|
||||
in_text = false;
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(_) => {}
|
||||
Err(error) => return Err(format!("Could not parse document body: {error}")),
|
||||
}
|
||||
}
|
||||
Ok((images, has_text))
|
||||
}
|
||||
|
||||
fn clean_cell(value: &calamine::Data) -> String {
|
||||
value
|
||||
.to_string()
|
||||
|
|
@ -93,43 +235,134 @@ fn local_name(raw: &str) -> &str {
|
|||
raw.rsplit(':').next().unwrap_or(raw)
|
||||
}
|
||||
|
||||
/// Reads an attribute value from a start element, ignoring namespace prefixes.
|
||||
fn attribute_value(element: &quick_xml::events::BytesStart, name: &str) -> Option<String> {
|
||||
element.attributes().flatten().find_map(|attribute| {
|
||||
if local_name(attribute.key.as_ref()) == name {
|
||||
attribute
|
||||
.normalized_value(quick_xml::XmlVersion::Implicit1_0)
|
||||
.ok()
|
||||
.map(|value| value.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves an entity reference such as `amp`, `lt` or a numeric `€`.
|
||||
fn resolve_entity(reference: &str) -> Option<String> {
|
||||
if let Some(character) = quick_xml::events::BytesRef::new(reference)
|
||||
.resolve_char_ref()
|
||||
.ok()
|
||||
.flatten()
|
||||
{
|
||||
return Some(character.to_string());
|
||||
}
|
||||
quick_xml::escape::resolve_predefined_entity(reference).map(str::to_string)
|
||||
}
|
||||
|
||||
/// Moves the collected run text into the paragraph or the table cell. Runs
|
||||
/// that follow each other are separated by a single space, the way the slide
|
||||
/// reads when it is shown.
|
||||
fn flush_run(pending: &mut String, target: &mut String) {
|
||||
let trimmed = pending.trim().to_string();
|
||||
pending.clear();
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
if !target.is_empty() && !target.ends_with(' ') {
|
||||
target.push(' ');
|
||||
}
|
||||
target.push_str(&trimmed);
|
||||
}
|
||||
|
||||
/// Moves the pending run text into whichever buffer is currently being read.
|
||||
fn flush_pending(pending: &mut String, in_table: bool, paragraph: &mut String, cell: &mut String) {
|
||||
if in_table {
|
||||
flush_run(pending, cell);
|
||||
} else {
|
||||
flush_run(pending, paragraph);
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts slide content in document order. Text is grouped per `<a:p>` as
|
||||
/// before; tables are additionally walked row by row so cells do not collapse
|
||||
/// into a single paragraph of prose.
|
||||
fn slide_blocks(xml: &str) -> Result<Vec<SlideBlock>, String> {
|
||||
let mut reader = XmlReader::from_str(xml);
|
||||
reader.config_mut().trim_text(true);
|
||||
// Whitespace inside a run is meaningful: it separates an entity
|
||||
// reference from the words around it, so it must not be trimmed away.
|
||||
reader.config_mut().trim_text(false);
|
||||
let mut buffer = Vec::new();
|
||||
let mut blocks: Vec<SlideBlock> = Vec::new();
|
||||
let mut paragraph = String::new();
|
||||
// Text of the run that is currently being read. Entity references and
|
||||
// CDATA land in the same buffer, so the spacing around them survives.
|
||||
let mut pending = String::new();
|
||||
// Table state. Nested tables are not a real PowerPoint layout, so a single
|
||||
// level of row/cell buffering is enough.
|
||||
let mut in_table = false;
|
||||
let mut rows: Vec<Vec<String>> = Vec::new();
|
||||
let mut row: Vec<String> = Vec::new();
|
||||
let mut cell = String::new();
|
||||
// A merged cell spans several grid columns, and a horizontally or
|
||||
// vertically merged cell is written as a continuation cell. Both would
|
||||
// otherwise shift every following column.
|
||||
let mut cell_span = 1_usize;
|
||||
let mut skip_cell = false;
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buffer) {
|
||||
Ok(Event::Start(element)) => match local_name(element.name().as_ref()) {
|
||||
"tbl" => {
|
||||
flush_pending(&mut pending, false, &mut paragraph, &mut cell);
|
||||
push_paragraph(&mut paragraph, &mut blocks);
|
||||
in_table = true;
|
||||
rows.clear();
|
||||
row.clear();
|
||||
}
|
||||
"tr" if in_table => row.clear(),
|
||||
"tc" if in_table => cell.clear(),
|
||||
"p" if !in_table => push_paragraph(&mut paragraph, &mut blocks),
|
||||
"tc" if in_table => {
|
||||
flush_pending(&mut pending, true, &mut paragraph, &mut cell);
|
||||
cell.clear();
|
||||
cell_span = attribute_value(&element, "gridSpan")
|
||||
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||
.unwrap_or(1)
|
||||
.max(1);
|
||||
// A horizontally merged cell continues the cell to its
|
||||
// left, so the grid span of that cell already covers it.
|
||||
skip_cell = attribute_value(&element, "hMerge")
|
||||
.map(|value| value.trim() == "1")
|
||||
.unwrap_or(false);
|
||||
}
|
||||
"p" if !in_table => {
|
||||
flush_pending(&mut pending, false, &mut paragraph, &mut cell);
|
||||
push_paragraph(&mut paragraph, &mut blocks);
|
||||
}
|
||||
"p" if in_table && !cell.trim().is_empty() => cell.push(' '),
|
||||
_ => {}
|
||||
},
|
||||
Ok(Event::End(element)) => {
|
||||
if local_name(element.name().as_ref()) == "t" {
|
||||
flush_pending(&mut pending, in_table, &mut paragraph, &mut cell);
|
||||
continue;
|
||||
}
|
||||
if !in_table {
|
||||
continue;
|
||||
}
|
||||
match local_name(element.name().as_ref()) {
|
||||
"tc" => row.push(std::mem::take(&mut cell)),
|
||||
"tc" => {
|
||||
if !skip_cell {
|
||||
flush_pending(&mut pending, true, &mut paragraph, &mut cell);
|
||||
row.push(std::mem::take(&mut cell));
|
||||
// A spanned cell occupies as many grid columns.
|
||||
for _ in 1..cell_span {
|
||||
row.push(String::new());
|
||||
}
|
||||
}
|
||||
skip_cell = false;
|
||||
cell_span = 1;
|
||||
}
|
||||
"tr" => {
|
||||
if row.iter().any(|value| !value.trim().is_empty()) {
|
||||
rows.push(std::mem::take(&mut row));
|
||||
|
|
@ -151,21 +384,16 @@ fn slide_blocks(xml: &str) -> Result<Vec<SlideBlock>, String> {
|
|||
Ok(Event::Text(value)) => {
|
||||
let unescaped = quick_xml::escape::unescape(&value)
|
||||
.map_err(|error| format!("Could not decode slide text: {error}"))?;
|
||||
let text = unescaped.trim();
|
||||
if text.is_empty() {
|
||||
pending.push_str(unescaped.as_ref());
|
||||
}
|
||||
Ok(Event::CData(value)) => {
|
||||
pending.push_str(value.as_ref());
|
||||
}
|
||||
Ok(Event::GeneralRef(reference)) => {
|
||||
let Some(resolved) = resolve_entity(reference.as_ref()) else {
|
||||
continue;
|
||||
}
|
||||
if in_table {
|
||||
if !cell.is_empty() {
|
||||
cell.push(' ');
|
||||
}
|
||||
cell.push_str(text);
|
||||
} else {
|
||||
if !paragraph.ends_with('\n') && !paragraph.is_empty() {
|
||||
paragraph.push(' ');
|
||||
}
|
||||
paragraph.push_str(text);
|
||||
}
|
||||
};
|
||||
pending.push_str(&resolved);
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Err(error) => return Err(format!("Could not parse slide XML: {error}")),
|
||||
|
|
@ -363,7 +591,6 @@ fn escape_markdown_cell(value: &str) -> String {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write as _;
|
||||
use zip::{write::SimpleFileOptions, ZipWriter};
|
||||
|
||||
#[test]
|
||||
|
|
@ -376,8 +603,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn extracts_pptx_slide_text() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-pptx-{}", uuid::Uuid::new_v4()));
|
||||
let directory = std::env::temp_dir().join(format!("shift-pptx-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = directory.join("slides.pptx");
|
||||
let file = fs::File::create(&input).unwrap();
|
||||
|
|
@ -401,7 +627,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn extracts_pptx_tables_as_markdown() {
|
||||
let directory = std::env::temp_dir().join(format!("shift-pptx-tbl-{}", uuid::Uuid::new_v4()));
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-pptx-tbl-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = directory.join("table.pptx");
|
||||
let file = fs::File::create(&input).unwrap();
|
||||
|
|
@ -462,4 +689,182 @@ mod tests {
|
|||
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
/// Builds a one-slide presentation with the given slide XML.
|
||||
fn pptx_with_slide(directory: &Path, name: &str, slide_xml: &str) -> PathBuf {
|
||||
let input = directory.join(name);
|
||||
let file = fs::File::create(&input).unwrap();
|
||||
let mut zip = ZipWriter::new(file);
|
||||
zip.start_file("ppt/slides/slide1.xml", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(slide_xml.as_bytes()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
input
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_xml_entities_in_slide_text() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-pptx-entity-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = pptx_with_slide(
|
||||
&directory,
|
||||
"entities.pptx",
|
||||
r#"<p:sld xmlns:p="p" xmlns:a="a"><a:p><a:r><a:t>A & B < C € D</a:t></a:r></a:p></p:sld>"#,
|
||||
);
|
||||
|
||||
let output = presentation_to_markdown(&input, None).unwrap();
|
||||
let markdown = fs::read_to_string(output).unwrap();
|
||||
assert!(markdown.contains("A & B < C € D"), "{markdown}");
|
||||
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_cdata_in_slide_text() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-pptx-cdata-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = pptx_with_slide(
|
||||
&directory,
|
||||
"cdata.pptx",
|
||||
r#"<p:sld xmlns:p="p" xmlns:a="a"><a:p><a:r><a:t>before </a:t></a:r><a:r><a:t><![CDATA[raw & wild]]></a:t></a:r></a:p></p:sld>"#,
|
||||
);
|
||||
|
||||
let output = presentation_to_markdown(&input, None).unwrap();
|
||||
let markdown = fs::read_to_string(output).unwrap();
|
||||
assert!(markdown.contains("raw & wild"), "{markdown}");
|
||||
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_merged_cells_aligned_in_slide_tables() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-pptx-merge-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
// The second row spans two columns and is followed by a continuation
|
||||
// cell; the third row is a vertical merge continuation.
|
||||
let input = pptx_with_slide(
|
||||
&directory,
|
||||
"merged.pptx",
|
||||
r#"<p:sld xmlns:p="p" xmlns:a="a"><a:tbl>
|
||||
<a:tr>
|
||||
<a:tc><a:p><a:r><a:t>A</a:t></a:r></a:p></a:tc>
|
||||
<a:tc><a:p><a:r><a:t>B</a:t></a:r></a:p></a:tc>
|
||||
<a:tc><a:p><a:r><a:t>C</a:t></a:r></a:p></a:tc>
|
||||
</a:tr><a:tr>
|
||||
<a:tc gridSpan="2"><a:p><a:r><a:t>Wide</a:t></a:r></a:p></a:tc>
|
||||
<a:tc hMerge="1"><a:p/></a:tc>
|
||||
<a:tc><a:p><a:r><a:t>Y</a:t></a:r></a:p></a:tc>
|
||||
</a:tr><a:tr>
|
||||
<a:tc vMerge="1"><a:p/></a:tc>
|
||||
<a:tc><a:p><a:r><a:t>E</a:t></a:r></a:p></a:tc>
|
||||
<a:tc><a:p><a:r><a:t>F</a:t></a:r></a:p></a:tc>
|
||||
</a:tr>
|
||||
</a:tbl></p:sld>"#,
|
||||
);
|
||||
|
||||
let output = presentation_to_markdown(&input, None).unwrap();
|
||||
let markdown = fs::read_to_string(output).unwrap();
|
||||
// Three grid columns, so every row keeps three cells.
|
||||
assert!(markdown.contains("| A | B | C |"), "{markdown}");
|
||||
assert!(markdown.contains("| Wide | | Y |"), "{markdown}");
|
||||
assert!(markdown.contains("| | E | F |"), "{markdown}");
|
||||
assert!(markdown.contains("| --- | --- | --- |"), "{markdown}");
|
||||
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_image_only_docx_pages_in_document_order() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-docx-pages-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = directory.join("pages.docx");
|
||||
let media = directory.join("media");
|
||||
fs::create_dir_all(&media).unwrap();
|
||||
let first = media.join("first.png");
|
||||
let second = media.join("second.png");
|
||||
image::RgbImage::from_pixel(4, 3, image::Rgb([255, 0, 0]))
|
||||
.save_with_format(&first, image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
image::RgbImage::from_pixel(4, 3, image::Rgb([0, 0, 255]))
|
||||
.save_with_format(&second, image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
|
||||
let file = fs::File::create(&input).unwrap();
|
||||
let mut zip = ZipWriter::new(file);
|
||||
zip.start_file("word/_rels/document.xml.rels", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(
|
||||
br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/second.png"/>
|
||||
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/first.png"/>
|
||||
</Relationships>"#,
|
||||
)
|
||||
.unwrap();
|
||||
zip.start_file("word/document.xml", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(
|
||||
br#"<w:document xmlns:w="w" xmlns:a="a" xmlns:r="r"><w:body>
|
||||
<w:p><w:r><w:drawing><a:blip r:embed="rId9"/></w:drawing></w:r></w:p>
|
||||
<w:p><w:r><w:drawing><a:blip r:embed="rId2"/></w:drawing></w:r></w:p>
|
||||
</w:body></w:document>"#,
|
||||
)
|
||||
.unwrap();
|
||||
zip.start_file("word/media/first.png", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(&fs::read(&first).unwrap()).unwrap();
|
||||
zip.start_file("word/media/second.png", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(&fs::read(&second).unwrap()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
|
||||
let output = directory.join("pages");
|
||||
fs::create_dir_all(&output).unwrap();
|
||||
let pages = document_page_images(&input, &output).unwrap().unwrap();
|
||||
assert_eq!(pages.len(), 2);
|
||||
let first_pixel = image::load_from_memory(&fs::read(&pages[0]).unwrap())
|
||||
.unwrap()
|
||||
.to_rgb8()
|
||||
.get_pixel(0, 0)
|
||||
.0;
|
||||
let second_pixel = image::load_from_memory(&fs::read(&pages[1]).unwrap())
|
||||
.unwrap()
|
||||
.to_rgb8()
|
||||
.get_pixel(0, 0)
|
||||
.0;
|
||||
assert_eq!(first_pixel, [0, 0, 255]);
|
||||
assert_eq!(second_pixel, [255, 0, 0]);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_text_documents_on_the_native_renderer() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("shift-docx-text-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
let input = directory.join("text.docx");
|
||||
let file = fs::File::create(&input).unwrap();
|
||||
let mut zip = ZipWriter::new(file);
|
||||
zip.start_file("word/_rels/document.xml.rels", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(
|
||||
br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>"#,
|
||||
)
|
||||
.unwrap();
|
||||
zip.start_file("word/document.xml", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(
|
||||
br#"<w:document xmlns:w="w"><w:body><w:p><w:r><w:t>Readable text</w:t></w:r></w:p></w:body></w:document>"#,
|
||||
)
|
||||
.unwrap();
|
||||
zip.finish().unwrap();
|
||||
|
||||
let output = directory.join("pages");
|
||||
fs::create_dir_all(&output).unwrap();
|
||||
assert!(document_page_images(&input, &output).unwrap().is_none());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,276 @@
|
|||
//! Process helpers that never open a console window.
|
||||
//!
|
||||
//! A GUI build owns no console, so on Windows every child process would
|
||||
//! otherwise allocate a fresh one: users see a black window blink for each tool
|
||||
//! probe, each conversion and each registry write. `CREATE_NO_WINDOW` suppresses
|
||||
//! that, and centralising it here means a new `Command` cannot forget it the way
|
||||
//! the scattered per-call constants did.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::io::{self, Read};
|
||||
use std::process::{Command, ExitStatus, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Windows console flag: run the child without giving it a window.
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
||||
#[cfg(target_os = "windows")]
|
||||
const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;
|
||||
|
||||
/// Keep probe output bounded while still draining the pipe. Stopping the read
|
||||
/// would let a verbose child fill the pipe and block until the deadline.
|
||||
const MAX_CAPTURED_OUTPUT: usize = 4 * 1024 * 1024;
|
||||
|
||||
fn drain_output(mut reader: impl Read) -> Vec<u8> {
|
||||
let mut captured = Vec::new();
|
||||
let mut buffer = [0_u8; 8192];
|
||||
loop {
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(count) => {
|
||||
let remaining = MAX_CAPTURED_OUTPUT.saturating_sub(captured.len());
|
||||
if remaining > 0 {
|
||||
captured.extend_from_slice(&buffer[..count.min(remaining)]);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
captured
|
||||
}
|
||||
|
||||
/// Suppress the child's console window. Every spawn in the app goes through this
|
||||
/// so a background tool call never flashes on screen.
|
||||
pub fn hidden(command: &mut Command) -> &mut Command {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// A separate process group also keeps a console attached to an inherited
|
||||
// launcher (WinGet, a debug terminal) from appearing above Shift.
|
||||
command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let _ = command;
|
||||
command
|
||||
}
|
||||
|
||||
/// Keep a long conversion below the UI's scheduling priority. A renderer that
|
||||
/// saturates every core can otherwise make the whole desktop appear frozen even
|
||||
/// though Shift itself is still responsive.
|
||||
pub fn background(command: &mut Command) -> &mut Command {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(
|
||||
CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | BELOW_NORMAL_PRIORITY_CLASS,
|
||||
);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let _ = command;
|
||||
command
|
||||
}
|
||||
|
||||
/// A new `Command` for `program` with the console and standard streams already
|
||||
/// detached, for the chained `Command::new(x).args(..).status()` shape.
|
||||
pub fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
hidden(&mut command);
|
||||
command
|
||||
}
|
||||
|
||||
/// `Command::output` with the console suppressed.
|
||||
pub fn output(program: impl AsRef<OsStr>, args: &[&str]) -> io::Result<Output> {
|
||||
let mut command = command(program);
|
||||
command
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
command.output()
|
||||
}
|
||||
|
||||
/// `Command::output` with a deadline. Version probes must never keep the
|
||||
/// component panel in "Inspecting…" because a tool is waiting for input.
|
||||
pub fn output_with_timeout(
|
||||
program: impl AsRef<OsStr>,
|
||||
args: &[&str],
|
||||
timeout: Duration,
|
||||
) -> Result<Output, String> {
|
||||
let mut command = command(program);
|
||||
command
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not start the command: {error}"))?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.map(|pipe| std::thread::spawn(move || drain_output(pipe)));
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.map(|pipe| std::thread::spawn(move || drain_output(pipe)));
|
||||
let result = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Ok(status),
|
||||
Ok(None) if Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break Err(format!(
|
||||
"The command did not finish within {} seconds.",
|
||||
timeout.as_secs()
|
||||
));
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(error) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break Err(format!("Could not monitor the command: {error}"));
|
||||
}
|
||||
}
|
||||
};
|
||||
let stdout = stdout
|
||||
.and_then(|reader| reader.join().ok())
|
||||
.unwrap_or_default();
|
||||
let stderr = stderr
|
||||
.and_then(|reader| reader.join().ok())
|
||||
.unwrap_or_default();
|
||||
result.map(|status| Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run a child with a hard deadline. Rendered PDF pages are the slowest step
|
||||
/// in PDF-to-Word, and a malformed page must not leave the UI processing
|
||||
/// forever. Returning an error also makes the caller remove partial output.
|
||||
#[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))]
|
||||
pub fn status_with_timeout(
|
||||
program: impl AsRef<OsStr>,
|
||||
args: &[&str],
|
||||
timeout: Duration,
|
||||
) -> Result<ExitStatus, String> {
|
||||
status_with_args_and_timeout(program, args, timeout)?
|
||||
.map(|(status, _)| status)
|
||||
.ok_or_else(|| "The converter exited without a status.".to_string())
|
||||
}
|
||||
|
||||
fn status_with_args_and_timeout(
|
||||
program: impl AsRef<OsStr>,
|
||||
args: &[&str],
|
||||
timeout: Duration,
|
||||
) -> Result<Option<(ExitStatus, Duration)>, String> {
|
||||
let mut command = crate::process::command(program);
|
||||
background(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let started = Instant::now();
|
||||
let deadline = started + timeout;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not start the converter: {error}"))?;
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return Ok(Some((status, started.elapsed()))),
|
||||
Ok(None) if Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!(
|
||||
"The conversion did not finish within {} seconds.",
|
||||
started.elapsed().as_secs()
|
||||
));
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(error) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("Could not monitor the converter: {error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_hidden_command_still_runs() {
|
||||
let output = if cfg!(windows) {
|
||||
output("cmd", &["/C", "echo shift"]).unwrap()
|
||||
} else {
|
||||
output("/bin/echo", &["shift"]).unwrap()
|
||||
};
|
||||
assert!(output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("shift"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_the_console_twice_changes_nothing() {
|
||||
let mut command = Command::new(if cfg!(windows) { "cmd" } else { "/bin/echo" });
|
||||
command.args(if cfg!(windows) {
|
||||
&["/C", "echo", "shift"][..]
|
||||
} else {
|
||||
&["shift"][..]
|
||||
});
|
||||
hidden(&mut command);
|
||||
assert!(hidden(&mut command).status().unwrap().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_commands_do_not_inherit_standard_streams() {
|
||||
let result = command(if cfg!(windows) { "cmd" } else { "/bin/echo" })
|
||||
.args(if cfg!(windows) {
|
||||
&["/C", "echo", "shift"][..]
|
||||
} else {
|
||||
&["shift"][..]
|
||||
})
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(result.status.success());
|
||||
assert!(result.stdout.is_empty());
|
||||
assert!(result.stderr.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_timed_out_child_is_killed() {
|
||||
let result = status_with_timeout("/bin/sleep", &["5"], Duration::from_millis(50));
|
||||
assert!(result.is_err(), "the timeout should terminate the child");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn captured_output_has_a_deadline() {
|
||||
let result = output_with_timeout("/bin/echo", &["shift"], Duration::from_secs(2)).unwrap();
|
||||
assert!(String::from_utf8_lossy(&result.stdout).contains("shift"));
|
||||
assert!(output_with_timeout("/bin/sleep", &["5"], Duration::from_millis(50)).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn verbose_output_is_drained_without_blocking_the_child() {
|
||||
let result = output_with_timeout(
|
||||
"/bin/sh",
|
||||
&["-c", "yes shift | head -c 8388608"],
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.status.success());
|
||||
assert_eq!(result.stdout.len(), MAX_CAPTURED_OUTPUT);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
process::{Child, ChildStdin, Command, Stdio},
|
||||
process::{Child, ChildStdin, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
|
@ -102,7 +102,7 @@ fn start_process(
|
|||
let _ = options.fps;
|
||||
let region = logical_region(app, state, rect)?;
|
||||
let output = output_path(app, "mov")?;
|
||||
let mut command = Command::new("/usr/sbin/screencapture");
|
||||
let mut command = crate::process::command("/usr/sbin/screencapture");
|
||||
command.args([
|
||||
"-x",
|
||||
"-v",
|
||||
|
|
@ -137,7 +137,7 @@ fn start_process(
|
|||
.ok_or_else(|| "Screen recording needs ffmpeg on Windows and Linux.".to_string())?;
|
||||
let region = physical_region(app, state, rect)?;
|
||||
let output = output_path(app, "mp4")?;
|
||||
let mut command = Command::new(ffmpeg);
|
||||
let mut command = crate::process::command(ffmpeg);
|
||||
#[cfg(target_os = "windows")]
|
||||
command.args([
|
||||
"-y",
|
||||
|
|
@ -344,22 +344,31 @@ pub fn stop_on_exit(app: &AppHandle, state: &AppState) {
|
|||
let _ = app;
|
||||
}
|
||||
|
||||
/// Starting a recording spawns a capture process and stopping one waits for the
|
||||
/// encoder to finalize the file (up to three seconds), so neither belongs on the
|
||||
/// main thread.
|
||||
#[tauri::command]
|
||||
pub fn start_recording(
|
||||
pub async fn start_recording(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
rect: NormalizedRect,
|
||||
options: Option<RecordingOptions>,
|
||||
) -> Result<RecordingInfo, String> {
|
||||
start(&app, &state, &rect, options.unwrap_or_default())
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let state = app.state::<AppState>();
|
||||
start(&app, &state, &rect, options.unwrap_or_default())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn stop_recording(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<RecordingInfo>, String> {
|
||||
stop(&app, &state)
|
||||
pub async fn stop_recording(app: AppHandle) -> Result<Option<RecordingInfo>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let state = app.state::<AppState>();
|
||||
stop(&app, &state)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
|
@ -378,6 +387,7 @@ pub fn recording_status(state: State<'_, AppState>) -> Result<Option<RecordingIn
|
|||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn stops_recording_process_cleanly() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,669 @@
|
|||
use std::{
|
||||
env,
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::files;
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::pdf;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeComponent {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub category: String,
|
||||
pub role: String,
|
||||
pub source: String,
|
||||
pub available: bool,
|
||||
pub installable: bool,
|
||||
pub version: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeInfo {
|
||||
pub platform: String,
|
||||
pub architecture: String,
|
||||
pub os_version: String,
|
||||
pub app_version: String,
|
||||
pub components: Vec<RuntimeComponent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct InstallTarget {
|
||||
name: &'static str,
|
||||
package_id: &'static str,
|
||||
executable: &'static str,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn macos_install_target(id: &str) -> Option<InstallTarget> {
|
||||
match id {
|
||||
"pandoc" => Some(InstallTarget {
|
||||
name: "Pandoc",
|
||||
package_id: "pandoc",
|
||||
executable: "pandoc",
|
||||
}),
|
||||
"media" => Some(InstallTarget {
|
||||
name: "FFmpeg",
|
||||
package_id: "ffmpeg",
|
||||
executable: "ffmpeg",
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
fn windows_install_target(id: &str) -> Option<InstallTarget> {
|
||||
match id {
|
||||
"pandoc" => Some(InstallTarget {
|
||||
name: "Pandoc",
|
||||
package_id: "JohnMacFarlane.Pandoc",
|
||||
executable: "pandoc",
|
||||
}),
|
||||
"media" => Some(InstallTarget {
|
||||
name: "FFmpeg",
|
||||
package_id: "Gyan.FFmpeg",
|
||||
executable: "ffmpeg",
|
||||
}),
|
||||
"pdf-render" => Some(InstallTarget {
|
||||
name: "Poppler",
|
||||
package_id: "oschwartz10612.Poppler",
|
||||
executable: "pdftoppm",
|
||||
}),
|
||||
// PDF-to-Word uses the same page renderer as PDF-to-image on Windows.
|
||||
"pdf-to-word" => Some(InstallTarget {
|
||||
name: "Poppler",
|
||||
package_id: "oschwartz10612.Poppler",
|
||||
executable: "pdftoppm",
|
||||
}),
|
||||
"image-backend" => Some(InstallTarget {
|
||||
name: "ImageMagick",
|
||||
package_id: "ImageMagick.ImageMagick",
|
||||
executable: "magick",
|
||||
}),
|
||||
"pdf-engine" => Some(InstallTarget {
|
||||
name: "Typst PDF engine",
|
||||
package_id: "Typst.Typst",
|
||||
executable: "typst",
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn install_target(id: &str) -> Option<InstallTarget> {
|
||||
macos_install_target(id)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn install_target(id: &str) -> Option<InstallTarget> {
|
||||
windows_install_target(id)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn install_target(_id: &str) -> Option<InstallTarget> {
|
||||
None
|
||||
}
|
||||
|
||||
fn component(
|
||||
id: &str,
|
||||
name: impl Into<String>,
|
||||
category: &str,
|
||||
role: impl Into<String>,
|
||||
source: &str,
|
||||
available: bool,
|
||||
version: Option<String>,
|
||||
path: Option<PathBuf>,
|
||||
) -> RuntimeComponent {
|
||||
RuntimeComponent {
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
category: category.into(),
|
||||
role: role.into(),
|
||||
source: source.into(),
|
||||
available,
|
||||
installable: install_target(id).is_some(),
|
||||
version,
|
||||
path: path.map(|value| value.to_string_lossy().to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_version(program: &Path, args: &[&str]) -> Option<String> {
|
||||
let output =
|
||||
crate::process::output_with_timeout(program, args, std::time::Duration::from_secs(4))
|
||||
.ok()?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
stdout
|
||||
.lines()
|
||||
.chain(stderr.lines())
|
||||
.find_map(meaningful_version_line)
|
||||
}
|
||||
|
||||
fn meaningful_version_line(line: &str) -> Option<String> {
|
||||
let line = line.trim_start_matches('\u{feff}').trim();
|
||||
(!line.is_empty()).then(|| line.chars().take(180).collect())
|
||||
}
|
||||
|
||||
fn external_component(
|
||||
id: &str,
|
||||
name: &str,
|
||||
category: &str,
|
||||
role: impl Into<String>,
|
||||
tool: &str,
|
||||
) -> RuntimeComponent {
|
||||
let path = files::resolve_tool(tool);
|
||||
component(
|
||||
id,
|
||||
name,
|
||||
category,
|
||||
role,
|
||||
"external",
|
||||
path.is_some(),
|
||||
None,
|
||||
path,
|
||||
)
|
||||
}
|
||||
|
||||
fn document_pdf_component() -> RuntimeComponent {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(renderer) = files::doc_render_bridge() {
|
||||
return component(
|
||||
"document-pdf",
|
||||
"AppKit document renderer",
|
||||
"documents",
|
||||
"DOCX / RTF / ODT / TXT / MD / HTML -> PDF",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
Some(renderer),
|
||||
);
|
||||
}
|
||||
|
||||
let pandoc = files::resolve_tool("pandoc");
|
||||
let pdf_engine = files::document_pdf_engine();
|
||||
let available = pandoc.is_some() && pdf_engine.is_some();
|
||||
let name = match pdf_engine.as_deref().and_then(Path::file_stem) {
|
||||
Some(engine) => format!("Pandoc + {}", engine.to_string_lossy()),
|
||||
None => "Pandoc PDF pipeline".into(),
|
||||
};
|
||||
component(
|
||||
"document-pdf",
|
||||
name,
|
||||
"documents",
|
||||
"DOCX / RTF / ODT / TXT / MD / HTML -> PDF",
|
||||
"external",
|
||||
available,
|
||||
None,
|
||||
pandoc.or(pdf_engine),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn document_pdf_engine_component() -> RuntimeComponent {
|
||||
let path = files::document_pdf_engine();
|
||||
let engine = path
|
||||
.as_deref()
|
||||
.and_then(Path::file_stem)
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "Typst".into());
|
||||
component(
|
||||
"pdf-engine",
|
||||
format!("Pandoc PDF engine: {engine}"),
|
||||
"documents",
|
||||
"DOCX / RTF / ODT / TXT / MD / HTML -> PDF",
|
||||
"external",
|
||||
path.is_some(),
|
||||
None,
|
||||
path,
|
||||
)
|
||||
}
|
||||
|
||||
fn pdf_to_word_component() -> RuntimeComponent {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
component(
|
||||
"pdf-to-word",
|
||||
"Built-in PDF text -> Word",
|
||||
"documents",
|
||||
"PDF text layer -> DOCX / RTF / ODT",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let path = files::resolve_tool("pdftoppm");
|
||||
component(
|
||||
"pdf-to-word",
|
||||
"Poppler PDF -> Word",
|
||||
"documents",
|
||||
"PDF pages -> image-preserving DOCX",
|
||||
"external",
|
||||
path.is_some(),
|
||||
None,
|
||||
path,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn pdf_page_component() -> RuntimeComponent {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let renderer = pdf::pdf_render_bridge();
|
||||
return component(
|
||||
"pdf-render",
|
||||
"PDFKit page renderer",
|
||||
"graphics",
|
||||
"PDF pages -> PNG / JPG / TIFF",
|
||||
"bundled",
|
||||
renderer.is_some(),
|
||||
None,
|
||||
renderer,
|
||||
);
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
external_component(
|
||||
"pdf-render",
|
||||
"Poppler pdftoppm",
|
||||
"graphics",
|
||||
"PDF pages -> PNG / JPG / TIFF",
|
||||
"pdftoppm",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn image_backend_component() -> RuntimeComponent {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let path = PathBuf::from("/usr/bin/sips");
|
||||
let available = path.is_file();
|
||||
return component(
|
||||
"image-backend",
|
||||
"macOS Core Image (sips)",
|
||||
"graphics",
|
||||
"HEIC / HEIF / AVIF and system image export",
|
||||
"system",
|
||||
available,
|
||||
None,
|
||||
Some(path),
|
||||
);
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
external_component(
|
||||
"image-backend",
|
||||
"ImageMagick",
|
||||
"graphics",
|
||||
"HEIC / HEIF / AVIF and system image export",
|
||||
"magick",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_capture_component() -> RuntimeComponent {
|
||||
component(
|
||||
"screen-capture",
|
||||
"Windows GDI capture",
|
||||
"capture",
|
||||
"Area / full-screen capture",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn media_component() -> RuntimeComponent {
|
||||
let path = files::resolve_tool("ffmpeg");
|
||||
component(
|
||||
"media",
|
||||
"FFmpeg",
|
||||
"video",
|
||||
"Video / audio conversion, compression and frames",
|
||||
"external",
|
||||
path.is_some(),
|
||||
None,
|
||||
path,
|
||||
)
|
||||
}
|
||||
|
||||
struct VersionProbe {
|
||||
id: String,
|
||||
handle: std::thread::JoinHandle<Option<String>>,
|
||||
}
|
||||
|
||||
fn version_args(id: &str) -> Option<&'static [&'static str]> {
|
||||
match id {
|
||||
"pandoc" | "document-pdf" | "pdf-engine" => Some(&["--version"]),
|
||||
"pdf-to-word" | "pdf-render" => Some(&["-v"]),
|
||||
"image-backend" => Some(&["--version"]),
|
||||
"media" => Some(&["-version"]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Version commands start together and are collected in one pass. Probing them
|
||||
/// one by one made a single slow executable delay every later row in the panel.
|
||||
fn fill_component_versions(components: &mut [RuntimeComponent]) {
|
||||
let mut probes = Vec::new();
|
||||
for component in components.iter() {
|
||||
if !component.available || component.source == "bundled" {
|
||||
continue;
|
||||
}
|
||||
let Some(args) = version_args(&component.id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(path) = component.path.as_ref().map(PathBuf::from) else {
|
||||
continue;
|
||||
};
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let args = args.to_vec();
|
||||
let id = component.id.clone();
|
||||
probes.push(VersionProbe {
|
||||
id,
|
||||
handle: std::thread::spawn(move || command_version(&path, &args)),
|
||||
});
|
||||
}
|
||||
for probe in probes {
|
||||
let version = probe.handle.join().ok().flatten();
|
||||
if let Some(component) = components
|
||||
.iter_mut()
|
||||
.find(|component| component.id == probe.id)
|
||||
{
|
||||
component.version = version;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn machine_info() -> Result<RuntimeInfo, String> {
|
||||
tauri::async_runtime::spawn_blocking(machine_info_sync)
|
||||
.await
|
||||
.map_err(|error| format!("Could not inspect runtime components: {error}"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_runtime_component(component_id: String) -> Result<String, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || install_runtime_component_sync(&component_id))
|
||||
.await
|
||||
.map_err(|error| format!("Could not install runtime component: {error}"))?
|
||||
}
|
||||
|
||||
fn install_runtime_component_sync(component_id: &str) -> Result<String, String> {
|
||||
let target =
|
||||
install_target(component_id).ok_or_else(|| "unsupported-runtime-component".to_string())?;
|
||||
let timeout = Duration::from_secs(15 * 60);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let brew = files::resolve_tool("brew").ok_or_else(|| "homebrew-missing".to_string())?;
|
||||
let status =
|
||||
crate::process::status_with_timeout(brew, &["install", target.package_id], timeout)
|
||||
.map_err(|error| format!("homebrew-install-failed: {error}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("homebrew-install-failed: {status}"));
|
||||
}
|
||||
if files::resolve_tool(target.executable).is_none() {
|
||||
return Err("homebrew-install-missing-binary".to_string());
|
||||
}
|
||||
Ok(format!("{} was installed.", target.name))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let winget = files::resolve_tool("winget").ok_or_else(|| "winget-missing".to_string())?;
|
||||
let status = crate::process::status_with_timeout(
|
||||
winget,
|
||||
&[
|
||||
"install",
|
||||
"--id",
|
||||
target.package_id,
|
||||
"--exact",
|
||||
"--silent",
|
||||
"--accept-package-agreements",
|
||||
"--accept-source-agreements",
|
||||
],
|
||||
timeout,
|
||||
)
|
||||
.map_err(|error| format!("winget-install-failed: {error}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("winget-install-failed: {status}"));
|
||||
}
|
||||
if files::resolve_tool(target.executable).is_none() {
|
||||
return Err("winget-install-missing-binary".to_string());
|
||||
}
|
||||
Ok(format!("{} was installed.", target.name))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = target;
|
||||
Err("runtime-install-unsupported".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn machine_info_sync() -> RuntimeInfo {
|
||||
let os_version = os_version();
|
||||
let mut components = vec![
|
||||
component(
|
||||
"native-pdf",
|
||||
"Built-in PDF engine",
|
||||
"documents",
|
||||
"PDF merge / split / rotate / compress / metadata",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
component(
|
||||
"office-parser",
|
||||
"Built-in Office parser",
|
||||
"documents",
|
||||
"PPTX / XLSX / CSV / TSV -> Markdown",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
pdf_to_word_component(),
|
||||
document_pdf_component(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
document_pdf_engine_component(),
|
||||
external_component(
|
||||
"pandoc",
|
||||
"Pandoc",
|
||||
"documents",
|
||||
"DOCX / RTF / ODT / MD / HTML conversion",
|
||||
"pandoc",
|
||||
),
|
||||
component(
|
||||
"native-image",
|
||||
"Rust image engine",
|
||||
"graphics",
|
||||
"PNG / JPEG / WebP / TIFF / BMP / GIF",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
pdf_page_component(),
|
||||
image_backend_component(),
|
||||
media_component(),
|
||||
component(
|
||||
"ocr",
|
||||
"Tesseract.js WASM",
|
||||
"ocr",
|
||||
"English + Simplified Chinese on-device OCR",
|
||||
"bundled",
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
];
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
components.push(component(
|
||||
"textutil",
|
||||
"macOS textutil",
|
||||
"documents",
|
||||
"DOCX / RTF / ODT / HTML fallback",
|
||||
"system",
|
||||
Path::new("/usr/bin/textutil").is_file(),
|
||||
None,
|
||||
Some(PathBuf::from("/usr/bin/textutil")),
|
||||
));
|
||||
#[cfg(target_os = "macos")]
|
||||
components.push(component(
|
||||
"screen-capture",
|
||||
"macOS screencapture",
|
||||
"capture",
|
||||
"Area/full-screen capture and recording",
|
||||
"system",
|
||||
Path::new("/usr/sbin/screencapture").is_file(),
|
||||
None,
|
||||
Some(PathBuf::from("/usr/sbin/screencapture")),
|
||||
));
|
||||
#[cfg(target_os = "windows")]
|
||||
components.push(windows_capture_component());
|
||||
|
||||
fill_component_versions(&mut components);
|
||||
|
||||
RuntimeInfo {
|
||||
platform: match env::consts::OS {
|
||||
"macos" => "macOS",
|
||||
"windows" => "Windows",
|
||||
"linux" => "Linux",
|
||||
other => other,
|
||||
}
|
||||
.into(),
|
||||
architecture: env::consts::ARCH.into(),
|
||||
os_version,
|
||||
app_version: env!("CARGO_PKG_VERSION").into(),
|
||||
components,
|
||||
}
|
||||
}
|
||||
|
||||
fn os_version() -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Ok(output) = crate::process::command("/usr/bin/sw_vers")
|
||||
.arg("-productVersion")
|
||||
.output()
|
||||
{
|
||||
let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if !version.is_empty() {
|
||||
return version;
|
||||
}
|
||||
}
|
||||
return "macOS".into();
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
return windows_os_version();
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if let Ok(contents) = std::fs::read_to_string("/etc/os-release") {
|
||||
if let Some(version) = contents
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("PRETTY_NAME="))
|
||||
{
|
||||
return version.trim_matches('"').to_string();
|
||||
}
|
||||
}
|
||||
return "Linux".into();
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
|
||||
{
|
||||
return env::consts::OS.into();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_os_version() -> String {
|
||||
use windows_sys::Win32::System::SystemInformation::{GetVersionExW, OSVERSIONINFOW};
|
||||
|
||||
let mut info: OSVERSIONINFOW = unsafe { std::mem::zeroed() };
|
||||
info.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOW>() as u32;
|
||||
let success = unsafe { GetVersionExW(&mut info) };
|
||||
if success == 0 {
|
||||
return "Windows".into();
|
||||
}
|
||||
let name = match (info.dwMajorVersion, info.dwMinorVersion) {
|
||||
(10, _) => "Windows 10/11",
|
||||
(6, 3) => "Windows 8.1",
|
||||
(6, 2) => "Windows 8",
|
||||
(6, 1) => "Windows 7",
|
||||
_ => "Windows",
|
||||
};
|
||||
format!(
|
||||
"{name} {}.{}.{}",
|
||||
info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn version_output_uses_the_first_meaningful_line() {
|
||||
assert_eq!(
|
||||
meaningful_version_line("\u{feff} Tool 1.2.3"),
|
||||
Some("Tool 1.2.3".into())
|
||||
);
|
||||
assert_eq!(meaningful_version_line(" "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn built_in_components_are_always_present() {
|
||||
let ids: Vec<String> = machine_info_sync()
|
||||
.components
|
||||
.into_iter()
|
||||
.map(|component| component.id)
|
||||
.collect();
|
||||
assert!(ids.contains(&"native-image".into()));
|
||||
assert!(ids.contains(&"native-pdf".into()));
|
||||
assert!(ids.contains(&"ocr".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installable_external_components_map_to_homebrew_formulae() {
|
||||
let pandoc = macos_install_target("pandoc").expect("Pandoc should be installable");
|
||||
assert_eq!(pandoc.package_id, "pandoc");
|
||||
let ffmpeg = macos_install_target("media").expect("FFmpeg should be installable");
|
||||
assert_eq!(ffmpeg.package_id, "ffmpeg");
|
||||
assert!(macos_install_target("native-pdf").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_external_components_map_to_winget_packages() {
|
||||
let pandoc = windows_install_target("pandoc").expect("Pandoc should be installable");
|
||||
assert_eq!(pandoc.package_id, "JohnMacFarlane.Pandoc");
|
||||
let ffmpeg = windows_install_target("media").expect("FFmpeg should be installable");
|
||||
assert_eq!(ffmpeg.package_id, "Gyan.FFmpeg");
|
||||
let poppler = windows_install_target("pdf-render").expect("Poppler should be installable");
|
||||
assert_eq!(poppler.package_id, "oschwartz10612.Poppler");
|
||||
let pdf_to_word =
|
||||
windows_install_target("pdf-to-word").expect("Poppler should install PDF-to-Word");
|
||||
assert_eq!(pdf_to_word.package_id, "oschwartz10612.Poppler");
|
||||
let magick =
|
||||
windows_install_target("image-backend").expect("ImageMagick should be installable");
|
||||
assert_eq!(magick.package_id, "ImageMagick.ImageMagick");
|
||||
let typst = windows_install_target("pdf-engine").expect("Typst should be installable");
|
||||
assert_eq!(typst.package_id, "Typst.Typst");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,29 @@
|
|||
use std::{fs, path::PathBuf};
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::{Mutex, MutexGuard, OnceLock},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
/// The switches only need their own value back. Rebuilding the full settings
|
||||
/// snapshot probes the login item and creates three folders, which can block on
|
||||
/// a network or cloud-synced volume and makes the switch feel slow.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SwitchState {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SwitchUpdate {
|
||||
pub state: SwitchState,
|
||||
/// The platform is the source of truth for launch-at-login.
|
||||
pub autostart: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FileOutputMode {
|
||||
|
|
@ -21,8 +42,12 @@ pub struct AppSettings {
|
|||
pub auto_reveal: bool,
|
||||
/// Master switch for the drag-to-open radial rings.
|
||||
pub drag_enabled: bool,
|
||||
/// Whether this copy announces itself to other Shift copies on the LAN.
|
||||
pub share_enabled: bool,
|
||||
/// Requested launch-at-login state; the platform is the source of truth.
|
||||
pub autostart: bool,
|
||||
/// UI language, "" until the user picks one. Unset follows the system.
|
||||
pub language: String,
|
||||
}
|
||||
|
||||
impl Default for AppSettings {
|
||||
|
|
@ -34,7 +59,9 @@ impl Default for AppSettings {
|
|||
recording_dir: None,
|
||||
auto_reveal: true,
|
||||
drag_enabled: true,
|
||||
share_enabled: true,
|
||||
autostart: false,
|
||||
language: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -48,7 +75,9 @@ pub struct SettingsSnapshot {
|
|||
pub recording_dir: String,
|
||||
pub auto_reveal: bool,
|
||||
pub drag_enabled: bool,
|
||||
pub share_enabled: bool,
|
||||
pub autostart: bool,
|
||||
pub language: String,
|
||||
pub default_file_output_dir: String,
|
||||
pub default_screenshot_dir: String,
|
||||
pub default_recording_dir: String,
|
||||
|
|
@ -71,6 +100,16 @@ fn settings_path(app: &AppHandle) -> Result<PathBuf, String> {
|
|||
.join("settings.json"))
|
||||
}
|
||||
|
||||
/// Every settings write is a read-modify-write of one JSON file. Without a
|
||||
/// process-wide guard, two quick toggle clicks can both read the old snapshot
|
||||
/// and the last writer silently restores the other switch.
|
||||
fn settings_write_lock() -> MutexGuard<'static, ()> {
|
||||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
LOCK.get_or_init(|| Mutex::new(()))
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub fn load(app: &AppHandle) -> AppSettings {
|
||||
settings_path(app)
|
||||
.ok()
|
||||
|
|
@ -84,11 +123,59 @@ fn save(app: &AppHandle, settings: &AppSettings) -> Result<(), String> {
|
|||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
}
|
||||
fs::write(
|
||||
path,
|
||||
serde_json::to_vec_pretty(settings).map_err(|error| error.to_string())?,
|
||||
)
|
||||
.map_err(|error| error.to_string())
|
||||
let contents = serde_json::to_vec_pretty(settings).map_err(|error| error.to_string())?;
|
||||
let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
|
||||
fs::write(&temporary, contents).map_err(|error| error.to_string())?;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
|
||||
};
|
||||
|
||||
let source: Vec<u16> = temporary
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let destination: Vec<u16> = path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let moved = unsafe {
|
||||
MoveFileExW(
|
||||
source.as_ptr(),
|
||||
destination.as_ptr(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
|
||||
)
|
||||
};
|
||||
if moved == 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
let _ = fs::remove_file(&temporary);
|
||||
return Err(format!("Could not replace settings.json: {error}"));
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
fs::rename(&temporary, &path).map_err(|error| error.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write one setting without losing a concurrent switch. The guard covers the
|
||||
/// whole load-mutate-save cycle, while each command still runs on a blocking
|
||||
/// worker so the webview remains responsive.
|
||||
fn update_settings<T>(
|
||||
app: &AppHandle,
|
||||
work: impl FnOnce(&mut AppSettings) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let _guard = settings_write_lock();
|
||||
let mut settings = load(app);
|
||||
let value = work(&mut settings)?;
|
||||
save(app, &settings)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn default_directory(app: &AppHandle, kind: &str) -> Result<PathBuf, String> {
|
||||
|
|
@ -144,6 +231,18 @@ pub fn auto_reveal(app: &AppHandle) -> bool {
|
|||
load(app).auto_reveal
|
||||
}
|
||||
|
||||
/// Landing folder for files shared from another machine over the LAN. Shared files
|
||||
/// join the normal Shift output folder so they also show up under "Recent".
|
||||
pub fn received_dir(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
let settings = load(app);
|
||||
match settings.file_output_mode {
|
||||
FileOutputMode::Custom => {
|
||||
configured_directory(app, "files", settings.file_output_dir.as_deref())
|
||||
}
|
||||
FileOutputMode::Alongside => configured_directory(app, "files", None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(app: &AppHandle) -> Result<SettingsSnapshot, String> {
|
||||
let settings = load(app);
|
||||
Ok(SettingsSnapshot {
|
||||
|
|
@ -162,8 +261,10 @@ pub fn snapshot(app: &AppHandle) -> Result<SettingsSnapshot, String> {
|
|||
recording_dir: recording_dir(app)?.to_string_lossy().to_string(),
|
||||
auto_reveal: settings.auto_reveal,
|
||||
drag_enabled: settings.drag_enabled,
|
||||
share_enabled: settings.share_enabled,
|
||||
// Report what the OS actually has registered, not what we last wrote.
|
||||
autostart: crate::autostart::is_enabled(),
|
||||
language: settings.language.clone(),
|
||||
default_file_output_dir: default_directory(app, "files")?
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
|
|
@ -176,9 +277,8 @@ pub fn snapshot(app: &AppHandle) -> Result<SettingsSnapshot, String> {
|
|||
})
|
||||
}
|
||||
|
||||
fn update_directory(app: &AppHandle, kind: &str, path: Option<String>) -> Result<(), String> {
|
||||
let mut settings = load(app);
|
||||
let normalized = match path {
|
||||
fn normalize_directory(path: Option<String>) -> Result<Option<String>, String> {
|
||||
match path {
|
||||
Some(value) if !value.trim().is_empty() => {
|
||||
let directory = PathBuf::from(value);
|
||||
if directory.exists() && !directory.is_dir() {
|
||||
|
|
@ -190,24 +290,10 @@ fn update_directory(app: &AppHandle, kind: &str, path: Option<String>) -> Result
|
|||
directory.display()
|
||||
)
|
||||
})?;
|
||||
Some(directory.to_string_lossy().to_string())
|
||||
Ok(Some(directory.to_string_lossy().to_string()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match kind {
|
||||
"screenshot" => settings.screenshot_dir = normalized,
|
||||
"recording" => settings.recording_dir = normalized,
|
||||
"files" => {
|
||||
settings.file_output_dir = normalized;
|
||||
settings.file_output_mode = if settings.file_output_dir.is_some() {
|
||||
FileOutputMode::Custom
|
||||
} else {
|
||||
FileOutputMode::Alongside
|
||||
};
|
||||
}
|
||||
other => return Err(format!("Unknown output type: {other}")),
|
||||
_ => Ok(None),
|
||||
}
|
||||
save(app, &settings)
|
||||
}
|
||||
|
||||
pub fn test_output_access(app: &AppHandle) -> Result<Vec<WriteCheck>, String> {
|
||||
|
|
@ -241,99 +327,194 @@ pub fn test_output_access(app: &AppHandle) -> Result<Vec<WriteCheck>, String> {
|
|||
.collect())
|
||||
}
|
||||
|
||||
// These commands run off the main thread: every one of them touches the disk
|
||||
// (settings.json, output-directory probes) and one slow folder — a cloud-synced
|
||||
// or network volume — would otherwise freeze the whole app behind a toggle.
|
||||
#[tauri::command]
|
||||
pub fn get_app_settings(app: AppHandle) -> Result<SettingsSnapshot, String> {
|
||||
snapshot(&app)
|
||||
pub async fn get_app_settings(app: AppHandle) -> Result<SettingsSnapshot, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || snapshot(&app))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_output_directory(
|
||||
pub async fn set_output_directory(
|
||||
app: AppHandle,
|
||||
kind: String,
|
||||
path: Option<String>,
|
||||
) -> Result<SettingsSnapshot, String> {
|
||||
update_directory(&app, &kind, path)?;
|
||||
snapshot(&app)
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let normalized = normalize_directory(path)?;
|
||||
update_settings(&app, |settings| {
|
||||
match kind.as_str() {
|
||||
"screenshot" => settings.screenshot_dir = normalized,
|
||||
"recording" => settings.recording_dir = normalized,
|
||||
"files" => {
|
||||
settings.file_output_dir = normalized;
|
||||
settings.file_output_mode = if settings.file_output_dir.is_some() {
|
||||
FileOutputMode::Custom
|
||||
} else {
|
||||
FileOutputMode::Alongside
|
||||
};
|
||||
}
|
||||
other => return Err(format!("Unknown output type: {other}")),
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
snapshot(&app)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_file_output_mode(
|
||||
pub async fn set_file_output_mode(
|
||||
app: AppHandle,
|
||||
mode: FileOutputMode,
|
||||
) -> Result<SettingsSnapshot, String> {
|
||||
let mut settings = load(&app);
|
||||
settings.file_output_mode = mode;
|
||||
save(&app, &settings)?;
|
||||
snapshot(&app)
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.file_output_mode = mode;
|
||||
Ok(())
|
||||
})?;
|
||||
snapshot(&app)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_auto_reveal(app: AppHandle, enabled: bool) -> Result<SettingsSnapshot, String> {
|
||||
let mut settings = load(&app);
|
||||
settings.auto_reveal = enabled;
|
||||
save(&app, &settings)?;
|
||||
snapshot(&app)
|
||||
pub async fn set_auto_reveal(app: AppHandle, enabled: bool) -> Result<SwitchState, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.auto_reveal = enabled;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(SwitchState { enabled })
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_drag_enabled(app: AppHandle, enabled: bool) -> Result<SettingsSnapshot, String> {
|
||||
let mut settings = load(&app);
|
||||
settings.drag_enabled = enabled;
|
||||
save(&app, &settings)?;
|
||||
pub async fn set_drag_enabled(app: AppHandle, enabled: bool) -> Result<SwitchState, String> {
|
||||
if let Some(state) = app.try_state::<crate::AppState>() {
|
||||
state.drag_enabled.store(enabled, std::sync::atomic::Ordering::Relaxed);
|
||||
state
|
||||
.drag_enabled
|
||||
.store(enabled, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
if !enabled {
|
||||
crate::drag_bridge::hide(&app);
|
||||
}
|
||||
snapshot(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_autostart(app: AppHandle, enabled: bool) -> Result<SettingsSnapshot, String> {
|
||||
crate::autostart::set_enabled(enabled)?;
|
||||
let mut settings = load(&app);
|
||||
settings.autostart = enabled;
|
||||
save(&app, &settings)?;
|
||||
snapshot(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn check_output_access(app: AppHandle) -> Result<Vec<WriteCheck>, String> {
|
||||
test_output_access(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn reveal_output_directory(app: AppHandle, kind: String) -> Result<(), String> {
|
||||
let directory = match kind.as_str() {
|
||||
"screenshot" => screenshot_dir(&app)?,
|
||||
"recording" => recording_dir(&app)?,
|
||||
"files" => match files_output_dir(&app)? {
|
||||
Some(directory) => directory,
|
||||
None => configured_directory(&app, "files", None)?,
|
||||
},
|
||||
other => return Err(format!("Unknown output type: {other}")),
|
||||
};
|
||||
crate::files::reveal_path(&directory)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_files_permission_settings() -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let status = std::process::Command::new("/usr/bin/open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders")
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.drag_enabled = enabled;
|
||||
Ok(())
|
||||
})?;
|
||||
if !enabled {
|
||||
crate::drag_bridge::hide(&app);
|
||||
}
|
||||
Err("Could not open Files and Folders settings.".into())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
Err("Files and Folders settings are macOS-specific.".into())
|
||||
}
|
||||
Ok(SwitchState { enabled })
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_share_enabled(app: AppHandle, enabled: bool) -> Result<SwitchState, String> {
|
||||
crate::share::set_enabled(&app, enabled);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.share_enabled = enabled;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(SwitchState { enabled })
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_autostart(app: AppHandle, enabled: bool) -> Result<SwitchUpdate, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
crate::autostart::set_enabled(enabled)?;
|
||||
settings.autostart = enabled;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(SwitchUpdate {
|
||||
state: SwitchState { enabled },
|
||||
autostart: Some(crate::autostart::is_enabled()),
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Remember the UI language and re-label the tray, which Rust owns. Return only
|
||||
/// the stored value: a full settings snapshot would probe the login item and
|
||||
/// create output folders, adding latency to a language switch.
|
||||
#[tauri::command]
|
||||
pub async fn set_language(app: AppHandle, language: String) -> Result<String, String> {
|
||||
let normalized = crate::locale::from_setting(Some(&language))
|
||||
.ok_or_else(|| "Unknown language.".to_string())?;
|
||||
// The tray is visible immediately; persistence must never gate its update.
|
||||
crate::set_tray_language(normalized);
|
||||
crate::refresh_tray_language(&app)?;
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update_settings(&app, |settings| {
|
||||
settings.language = normalized.to_string();
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(normalized.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn check_output_access(app: AppHandle) -> Result<Vec<WriteCheck>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || test_output_access(&app))
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn reveal_output_directory(app: AppHandle, kind: String) -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let directory = match kind.as_str() {
|
||||
"screenshot" => screenshot_dir(&app)?,
|
||||
"recording" => recording_dir(&app)?,
|
||||
"files" => match files_output_dir(&app)? {
|
||||
Some(directory) => directory,
|
||||
None => configured_directory(&app, "files", None)?,
|
||||
},
|
||||
other => return Err(format!("Unknown output type: {other}")),
|
||||
};
|
||||
crate::files::reveal_path(&directory)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_files_permission_settings() -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(|| {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let status = crate::process::command("/usr/bin/open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders")
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
Err("Could not open Files and Folders settings.".into())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
Err("Files and Folders settings are macOS-specific.".into())
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -345,6 +526,7 @@ mod tests {
|
|||
let settings = AppSettings::default();
|
||||
assert_eq!(settings.file_output_mode, FileOutputMode::Alongside);
|
||||
assert!(settings.auto_reveal);
|
||||
assert!(settings.share_enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -37,7 +37,7 @@
|
|||
"transparent": true,
|
||||
"alwaysOnTop": true,
|
||||
"skipTaskbar": true,
|
||||
"visible": false,
|
||||
"visible": true,
|
||||
"focus": false,
|
||||
"shadow": false,
|
||||
"acceptFirstMouse": true
|
||||
|
|
@ -72,6 +72,24 @@
|
|||
"shadow": false,
|
||||
"acceptFirstMouse": true
|
||||
},
|
||||
{
|
||||
"label": "pin",
|
||||
"title": "Shift Pin",
|
||||
"url": "index.html?view=pin",
|
||||
"width": 360,
|
||||
"height": 360,
|
||||
"minWidth": 120,
|
||||
"minHeight": 80,
|
||||
"resizable": true,
|
||||
"decorations": false,
|
||||
"transparent": false,
|
||||
"alwaysOnTop": true,
|
||||
"skipTaskbar": true,
|
||||
"visible": false,
|
||||
"focus": false,
|
||||
"shadow": false,
|
||||
"acceptFirstMouse": true
|
||||
},
|
||||
{
|
||||
"label": "editor",
|
||||
"title": "Shift Editor",
|
||||
|
|
@ -111,7 +129,9 @@
|
|||
],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "13.0",
|
||||
"infoPlist": "Info.plist"
|
||||
"infoPlist": "Info.plist",
|
||||
"signingIdentity": "Shift Local Signing",
|
||||
"hardenedRuntime": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { MainWindow } from "./components/MainWindow";
|
|||
import { PinnedImage } from "./components/PinnedImage";
|
||||
import { RadialMenu } from "./components/RadialMenu";
|
||||
import { RecorderHud } from "./components/RecorderHud";
|
||||
import { ShareNotice } from "./components/ShareNotice";
|
||||
import type { View } from "./types";
|
||||
|
||||
function resolveView(): View {
|
||||
|
|
@ -13,7 +14,8 @@ function resolveView(): View {
|
|||
value === "capture" ||
|
||||
value === "recorder" ||
|
||||
value === "editor" ||
|
||||
value === "pin"
|
||||
value === "pin" ||
|
||||
value === "share-notice"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
|
|
@ -35,6 +37,8 @@ export default function App() {
|
|||
return <Editor />;
|
||||
case "pin":
|
||||
return <PinnedImage />;
|
||||
case "share-notice":
|
||||
return <ShareNotice />;
|
||||
default:
|
||||
return <MainWindow />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -226,7 +226,6 @@ export function CaptureOverlay() {
|
|||
</span>
|
||||
<div>
|
||||
<strong>{t("dragSelect")}</strong>
|
||||
<span>{session.mode === "recording" ? t("recordingHint") : t("screenshotHint")}</span>
|
||||
</div>
|
||||
<kbd>ESC</kbd>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ export function Editor() {
|
|||
const [ocrProgress, setOcrProgress] = useState(0);
|
||||
const [ocrStatus, setOcrStatus] = useState("");
|
||||
const [ocrRunning, setOcrRunning] = useState(false);
|
||||
const [pinBusy, setPinBusy] = useState(false);
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
const [textContent, setTextContent] = useState("");
|
||||
const copyTimer = useRef<number | null>(null);
|
||||
|
|
@ -126,8 +127,8 @@ export function Editor() {
|
|||
setOcrProgress(0);
|
||||
setOcrStatus(t("ocrRunning"));
|
||||
try {
|
||||
const dataUrl = await api.readFileDataUrl(current.path);
|
||||
const result = await recognizeImage(dataUrl, (progress, status) => {
|
||||
const source = isTauri() ? convertFileSrc(current.path) : current.path;
|
||||
const result = await recognizeImage(source, (progress, status) => {
|
||||
setOcrProgress(progress);
|
||||
setOcrStatus(status || t("ocrRunning"));
|
||||
});
|
||||
|
|
@ -146,6 +147,19 @@ export function Editor() {
|
|||
}
|
||||
}
|
||||
|
||||
async function pinToScreen() {
|
||||
const current = sessionRef.current;
|
||||
if (!current || pinBusy) return;
|
||||
setPinBusy(true);
|
||||
try {
|
||||
await api.pinImage(current.path);
|
||||
} catch (error) {
|
||||
flashCopied(String(error).replace(/^Error:\s*/, ""));
|
||||
} finally {
|
||||
setPinBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <div className="editor-loading" />;
|
||||
}
|
||||
|
|
@ -164,7 +178,7 @@ export function Editor() {
|
|||
<div className="editor-title" data-tauri-drag-region>
|
||||
{name}
|
||||
</div>
|
||||
<button className="editor-close" onClick={() => void api.closeEditor()}>
|
||||
<button className="home-icon-button editor-close" onClick={() => void api.closeEditor()}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</header>
|
||||
|
|
@ -186,8 +200,12 @@ export function Editor() {
|
|||
</button>
|
||||
) : null}
|
||||
{session.kind === "image" ? (
|
||||
<button className="editor-button" onClick={() => void api.pinImage(session.path)}>
|
||||
<Pin size={16} />
|
||||
<button
|
||||
className="editor-button"
|
||||
onClick={() => void pinToScreen()}
|
||||
disabled={pinBusy}
|
||||
>
|
||||
{pinBusy ? <LoaderCircle size={16} className="spin" /> : <Pin size={16} />}
|
||||
{t("pin")}
|
||||
</button>
|
||||
) : null}
|
||||
|
|
@ -234,7 +252,6 @@ export function Editor() {
|
|||
<div>
|
||||
<span className="ocr-eyebrow">{t("ocr")}</span>
|
||||
<h2>{t("ocrTitle")}</h2>
|
||||
<p>{t("ocrHint")}</p>
|
||||
</div>
|
||||
<button className="editor-icon" onClick={() => setOcrOpen(false)}>
|
||||
<X size={16} />
|
||||
|
|
|
|||
|
|
@ -179,24 +179,32 @@ export function ImageAnnotator({ path, onSaved }: Props) {
|
|||
setTextPoint(null);
|
||||
setTextDraft("");
|
||||
setImageHistory([]);
|
||||
const source = isTauri()
|
||||
? api.readFileDataUrl(path)
|
||||
: Promise.resolve("/demo-preview.svg");
|
||||
void source.then((url) => {
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
if (cancelled) return;
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
if (cancelled) return;
|
||||
imageRef.current = image;
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
const context = canvas.getContext("2d");
|
||||
if (context) context.drawImage(image, 0, 0);
|
||||
};
|
||||
image.src = url;
|
||||
});
|
||||
imageRef.current = image;
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
const context = canvas.getContext("2d");
|
||||
if (context) context.drawImage(image, 0, 0);
|
||||
};
|
||||
image.onerror = () => {
|
||||
if (!cancelled) setError(t("pinLoadFailed"));
|
||||
};
|
||||
if (isTauri()) {
|
||||
void api
|
||||
.readImageData(path)
|
||||
.then((url) => {
|
||||
if (!cancelled) image.src = url;
|
||||
})
|
||||
.catch((reason) => {
|
||||
if (!cancelled) setError(String(reason).replace(/^Error:\s*/, ""));
|
||||
});
|
||||
} else {
|
||||
image.src = "/demo-preview.svg";
|
||||
}
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,11 +1,19 @@
|
|||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { writeImage } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { Copy, X } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
|
||||
interface PinnedPreview {
|
||||
id: number;
|
||||
path: string;
|
||||
dataUrl: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
function decodePath(value: string | null): string | null {
|
||||
if (!value || value.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(value)) return null;
|
||||
try {
|
||||
|
|
@ -18,24 +26,84 @@ function decodePath(value: string | null): string | null {
|
|||
|
||||
export function PinnedImage() {
|
||||
const { t } = useI18n();
|
||||
const path = decodePath(new URLSearchParams(window.location.search).get("path"));
|
||||
const [path, setPath] = useState(() =>
|
||||
decodePath(new URLSearchParams(window.location.search).get("path")),
|
||||
);
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const latestId = useRef(0);
|
||||
const renderedId = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!path) {
|
||||
setError("The pinned image is unavailable.");
|
||||
return;
|
||||
}
|
||||
if (!isTauri()) {
|
||||
setSrc("/demo-preview.svg");
|
||||
return;
|
||||
}
|
||||
void api
|
||||
.readFileDataUrl(path)
|
||||
.then(setSrc)
|
||||
.catch((reason) => setError(String(reason)));
|
||||
}, [path]);
|
||||
let disposed = false;
|
||||
const apply = (preview: PinnedPreview | null) => {
|
||||
if (disposed) return;
|
||||
if (!preview) {
|
||||
if (latestId.current === 0) setSrc(null);
|
||||
return;
|
||||
}
|
||||
if (preview.id < latestId.current) return;
|
||||
if (preview.id === renderedId.current) return;
|
||||
latestId.current = preview.id;
|
||||
setPath(preview.path);
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
if (disposed) return;
|
||||
renderedId.current = preview.id;
|
||||
setSrc(preview.dataUrl);
|
||||
setError(null);
|
||||
// Let React commit the loaded image before the native window is shown.
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (!disposed) void api.pinReady(preview.id);
|
||||
});
|
||||
});
|
||||
};
|
||||
image.onerror = () => {
|
||||
if (disposed) return;
|
||||
renderedId.current = preview.id;
|
||||
setError(t("pinLoadFailed"));
|
||||
void api.pinReady(preview.id);
|
||||
};
|
||||
image.src = preview.dataUrl;
|
||||
};
|
||||
const refresh = () => {
|
||||
void api
|
||||
.getPinnedImage()
|
||||
.then(apply)
|
||||
.catch((reason) => {
|
||||
if (disposed) return;
|
||||
setError(String(reason).replace(/^Error:\s*/, ""));
|
||||
void api.pinReady(null);
|
||||
});
|
||||
};
|
||||
const refreshWhenVisible = () => {
|
||||
if (document.visibilityState === "visible") refresh();
|
||||
};
|
||||
window.addEventListener("focus", refresh);
|
||||
document.addEventListener("visibilitychange", refreshWhenVisible);
|
||||
let unlisten: Promise<() => void> | null = null;
|
||||
// Register first: a reused pin window can receive a new image immediately
|
||||
// after the previous pin is closed. Querying first would lose that event.
|
||||
unlisten = listen<PinnedPreview>("pin://show", (event) => apply(event.payload)).then(
|
||||
(stopListening) => {
|
||||
if (!disposed) refresh();
|
||||
return stopListening;
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
disposed = true;
|
||||
window.removeEventListener("focus", refresh);
|
||||
document.removeEventListener("visibilitychange", refreshWhenVisible);
|
||||
void unlisten?.then((release) => release());
|
||||
};
|
||||
// Language changes only affect error text, not the image payload.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function copy() {
|
||||
if (!path) return;
|
||||
|
|
@ -51,10 +119,16 @@ export function PinnedImage() {
|
|||
<div
|
||||
className="pin-surface"
|
||||
data-tauri-drag-region
|
||||
onDoubleClick={() => void getCurrentWindow().close()}
|
||||
onDoubleClick={() => void api.closePin()}
|
||||
>
|
||||
{src ? (
|
||||
<img src={src} alt="" draggable={false} data-tauri-drag-region />
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
draggable={false}
|
||||
data-tauri-drag-region
|
||||
onError={() => setError(t("pinLoadFailed"))}
|
||||
/>
|
||||
) : (
|
||||
<div className="pin-loading" />
|
||||
)}
|
||||
|
|
@ -63,7 +137,7 @@ export function PinnedImage() {
|
|||
<button type="button" title={t("copy")} onClick={() => void copy()}>
|
||||
<Copy size={13} />
|
||||
</button>
|
||||
<button type="button" title={t("close")} onClick={() => void getCurrentWindow().close()}>
|
||||
<button type="button" title={t("close")} onClick={() => void api.closePin()}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { listen } from "@tauri-apps/api/event";
|
||||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { convertFileSrc, isTauri } from "@tauri-apps/api/core";
|
||||
import { getCurrentWebview } from "@tauri-apps/api/webview";
|
||||
import {
|
||||
CircleAlert,
|
||||
Camera,
|
||||
Contrast,
|
||||
Crop,
|
||||
|
|
@ -28,19 +29,23 @@ import {
|
|||
ScanText,
|
||||
Scaling,
|
||||
Scissors,
|
||||
Send,
|
||||
SlidersHorizontal,
|
||||
Tags,
|
||||
Video,
|
||||
Volume1,
|
||||
VolumeX,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { ComponentType } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { conversionFormats } from "../lib/conversionFormats";
|
||||
import { recognizeImage } from "../lib/ocr";
|
||||
import { basename, formatBytes, recentKind, rememberRecent } from "../lib/utils";
|
||||
import type { FileInfo, RadialContext } from "../types";
|
||||
import { useI18n } from "../i18n";
|
||||
import { SharePanel } from "./SharePanel";
|
||||
|
||||
const SIZE = 760;
|
||||
const CENTER = SIZE / 2;
|
||||
|
|
@ -135,31 +140,6 @@ function fileGlyph(kind: FileInfo["kind"]): IconType {
|
|||
}
|
||||
}
|
||||
|
||||
function formatSetFor(kind: FileInfo["kind"], extension: string): string[] {
|
||||
switch (kind) {
|
||||
case "image":
|
||||
return ["PNG", "JPG", "WEBP", "HEIC", "TIFF", "BMP", "GIF", "PDF"];
|
||||
case "video":
|
||||
return ["MP4", "MOV", "GIF", "M4A"];
|
||||
case "audio":
|
||||
return ["M4A", "WAV", "MP3"];
|
||||
case "pdf":
|
||||
return ["PNG", "JPG", "TIFF", "HEIC", "TXT", "MD", "DOCX", "RTF"];
|
||||
case "document":
|
||||
return ["docx", "rtf", "odt", "txt", "md", "html", "htm"].includes(extension)
|
||||
? ["PDF", "DOCX", "MD", "TXT", "HTML", "RTF", "ODT"]
|
||||
: [];
|
||||
case "presentation":
|
||||
return extension === "pptx" ? ["PDF", "MD"] : [];
|
||||
case "spreadsheet":
|
||||
return ["xlsx", "xls", "xlsb", "ods", "csv", "tsv"].includes(extension)
|
||||
? ["PDF", "MD"]
|
||||
: [];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function actionWedge(
|
||||
id: string,
|
||||
label: string,
|
||||
|
|
@ -169,6 +149,21 @@ function actionWedge(
|
|||
return { id, label, icon, format };
|
||||
}
|
||||
|
||||
function messageOf(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.replace(/^Error:\s*/, "") || "Unknown error";
|
||||
}
|
||||
|
||||
function waitForPaint() {
|
||||
return new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
window.setTimeout(resolve, 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function RadialMenu() {
|
||||
const { t } = useI18n();
|
||||
const [context, setContext] = useState<RadialContext | null>(null);
|
||||
|
|
@ -177,11 +172,24 @@ export function RadialMenu() {
|
|||
const [pointer, setPointer] = useState<Point | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Files waiting for a peer to be picked; the ring stays open behind the panel.
|
||||
const [sharePaths, setSharePaths] = useState<string[] | null>(null);
|
||||
const sharePathsRef = useRef<string[] | null>(null);
|
||||
// True once the send panel has reported an outcome; the ring then stays open
|
||||
// just long enough to show the message.
|
||||
const shareNoticeRef = useRef(false);
|
||||
const statusTimer = useRef<number | null>(null);
|
||||
const hoveredRef = useRef<number | null>(null);
|
||||
const ringRef = useRef<Ring>("actions");
|
||||
const contextRef = useRef<RadialContext | null>(null);
|
||||
const wedgesRef = useRef<Wedge[]>([]);
|
||||
// Whether WebView2's OLE drag has contributed to the current Windows gesture.
|
||||
const oleSeenRef = useRef(false);
|
||||
// Whether OLE finished this gesture (drop or leave), so a release-based safety
|
||||
// net knows to stand down. Cleared when the poller opens the next ring.
|
||||
const oleSettledRef = useRef(false);
|
||||
const releaseHideRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
ringRef.current = ring;
|
||||
|
|
@ -194,7 +202,7 @@ export function RadialMenu() {
|
|||
}, [context]);
|
||||
|
||||
const kind = context?.fileInfo[0]?.kind ?? "other";
|
||||
const formats = formatSetFor(kind, context?.fileInfo[0]?.extension ?? "");
|
||||
const formats = conversionFormats(kind, context?.fileInfo[0]?.extension ?? "");
|
||||
|
||||
const actions: Wedge[] =
|
||||
kind === "image"
|
||||
|
|
@ -300,7 +308,9 @@ export function RadialMenu() {
|
|||
: [
|
||||
actionWedge("open", t("open"), ExternalLink),
|
||||
actionWedge("reveal", t("reveal"), FolderOpen),
|
||||
];
|
||||
];
|
||||
// Sending works for any file, so the wedge joins every type's tool ring.
|
||||
toolWedges.push(actionWedge("send", t("sendShort"), Send));
|
||||
const wedges =
|
||||
ring === "formats" ? formatWedges : ring === "tools" ? toolWedges : actions;
|
||||
wedgesRef.current = wedges;
|
||||
|
|
@ -309,20 +319,38 @@ export function RadialMenu() {
|
|||
|
||||
function flash(message: string, duration = 1600) {
|
||||
if (statusTimer.current) window.clearTimeout(statusTimer.current);
|
||||
setError(null);
|
||||
setStatus(message);
|
||||
statusTimer.current = window.setTimeout(() => setStatus(null), duration);
|
||||
}
|
||||
|
||||
function showError(reason: unknown) {
|
||||
if (statusTimer.current) window.clearTimeout(statusTimer.current);
|
||||
setStatus(null);
|
||||
setError(messageOf(reason));
|
||||
}
|
||||
|
||||
function applyContext(next: RadialContext | null) {
|
||||
if (!next) return;
|
||||
if (statusTimer.current) window.clearTimeout(statusTimer.current);
|
||||
setStatus(null);
|
||||
setError(null);
|
||||
setSharePaths(null);
|
||||
sharePathsRef.current = null;
|
||||
shareNoticeRef.current = false;
|
||||
setContext(next);
|
||||
contextRef.current = next;
|
||||
let nextRing: Ring =
|
||||
next.mode === "formats" ? "formats" : next.mode === "tools" ? "tools" : "actions";
|
||||
// Opening the format ring straight from the home panel must never land on an
|
||||
// empty wheel, so unsupported types fall back to their action list.
|
||||
if (
|
||||
next.files.length > 0 &&
|
||||
nextRing === "formats" &&
|
||||
formatSetFor(next.fileInfo[0]?.kind ?? "other", next.fileInfo[0]?.extension ?? "").length === 0
|
||||
conversionFormats(
|
||||
next.fileInfo[0]?.kind ?? "other",
|
||||
next.fileInfo[0]?.extension ?? "",
|
||||
).length === 0
|
||||
) {
|
||||
nextRing = "actions";
|
||||
}
|
||||
|
|
@ -337,9 +365,8 @@ export function RadialMenu() {
|
|||
let disposed = false;
|
||||
const unlisteners: Array<() => void> = [];
|
||||
if (!isTauri()) {
|
||||
const demoMode = new URLSearchParams(window.location.search).get("mode") === "actions"
|
||||
? "actions"
|
||||
: "formats";
|
||||
const requested = new URLSearchParams(window.location.search).get("mode");
|
||||
const demoMode = requested === "actions" || requested === "tools" ? requested : "formats";
|
||||
applyContext({
|
||||
files: ["/Users/demo/tangerine tree.png"],
|
||||
fileInfo: [
|
||||
|
|
@ -360,10 +387,33 @@ export function RadialMenu() {
|
|||
void api.getRadialContext().then((next) => {
|
||||
if (!disposed) applyContext(next);
|
||||
});
|
||||
void listen<RadialContext>("radial://show", (event) => applyContext(event.payload)).then(
|
||||
(unlisten) => unlisteners.push(unlisten),
|
||||
);
|
||||
void listen<RadialContext>("radial://show", (event) => {
|
||||
// The poller opens a fresh ring at the start of every gesture, which is the
|
||||
// boundary for "has OLE said anything about this drag yet?".
|
||||
if (event.payload.dragging) {
|
||||
oleSeenRef.current = false;
|
||||
oleSettledRef.current = false;
|
||||
}
|
||||
applyContext(event.payload);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
// The native poller saw the mouse button go up. OLE reports a drop *after*
|
||||
// release, so this must only close a ring that OLE never touched; otherwise a
|
||||
// real drop would be hidden before it is delivered.
|
||||
void listen("radial://dragend", () => {
|
||||
if (!contextRef.current?.dragging || oleSettledRef.current) return;
|
||||
// A picker is open on top of the ring; the gesture ending must not close it.
|
||||
if (sharePathsRef.current) return;
|
||||
// OLE never spoke: nothing is coming, so close immediately. If it did speak,
|
||||
// give it a moment to deliver the pending drop before assuming it went silent.
|
||||
const delay = oleSeenRef.current ? 400 : 0;
|
||||
if (releaseHideRef.current) window.clearTimeout(releaseHideRef.current);
|
||||
releaseHideRef.current = window.setTimeout(() => {
|
||||
releaseHideRef.current = null;
|
||||
if (!oleSettledRef.current && contextRef.current?.dragging) void api.hideRadial();
|
||||
}, delay);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void listen<RadialEventPayload>("radial://move", (event) => {
|
||||
if (sharePathsRef.current) return;
|
||||
setPointer({ x: event.payload.x, y: event.payload.y });
|
||||
const count = wedgesRef.current.length;
|
||||
if (count === 0) return;
|
||||
|
|
@ -374,6 +424,9 @@ export function RadialMenu() {
|
|||
}
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void listen<RadialEventPayload>("radial://drop", (event) => {
|
||||
// The picker already opened during the drag; the release that ends the
|
||||
// gesture must not be read as a wedge choice.
|
||||
if (sharePathsRef.current) return;
|
||||
const activeRing = ringRef.current;
|
||||
const activeWedges = wedgesRef.current;
|
||||
const index = sectorAt(event.payload.x, event.payload.y, Math.max(activeWedges.length, 1));
|
||||
|
|
@ -401,11 +454,27 @@ export function RadialMenu() {
|
|||
disposed = true;
|
||||
unlisteners.forEach((unlisten) => unlisten());
|
||||
if (statusTimer.current) window.clearTimeout(statusTimer.current);
|
||||
if (releaseHideRef.current) window.clearTimeout(releaseHideRef.current);
|
||||
};
|
||||
// Geometry is recomputed from the current catalog; setup only needs to run once.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
function handleKeyDown(event: KeyboardEvent) {
|
||||
// Finder owns Escape during its own drag session; only the ring opened
|
||||
// from a completed drop on the main panel should handle it.
|
||||
if (event.key !== "Escape" || contextRef.current?.dragging) return;
|
||||
// While the send picker is open its own Escape handler owns the key.
|
||||
if (sharePathsRef.current) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void api.hideRadial();
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTauri() || !/Windows/i.test(navigator.userAgent)) return;
|
||||
let disposed = false;
|
||||
|
|
@ -414,11 +483,16 @@ export function RadialMenu() {
|
|||
.onDragDropEvent(async (event) => {
|
||||
if (disposed) return;
|
||||
const payload = event.payload;
|
||||
// OLE owns this gesture now, so the poller's release signal must not
|
||||
// hide the ring: OLE reports the drop after the button is already up.
|
||||
oleSeenRef.current = true;
|
||||
if (payload.type === "leave") {
|
||||
void api.hideRadial();
|
||||
oleSettledRef.current = true;
|
||||
if (!sharePathsRef.current) void api.hideRadial();
|
||||
return;
|
||||
}
|
||||
if (payload.type === "over") {
|
||||
if (sharePathsRef.current) return;
|
||||
const scale = window.devicePixelRatio || 1;
|
||||
const count = wedgesRef.current.length;
|
||||
if (count > 0) {
|
||||
|
|
@ -435,12 +509,22 @@ export function RadialMenu() {
|
|||
return;
|
||||
}
|
||||
if (!payload.paths.length) {
|
||||
void api.hideRadial();
|
||||
oleSettledRef.current = true;
|
||||
if (!sharePathsRef.current) void api.hideRadial();
|
||||
return;
|
||||
}
|
||||
// A drop is terminal even while inspectFiles is still running. Mark it
|
||||
// before awaiting so the release safety timer cannot hide the ring.
|
||||
if (payload.type === "drop") oleSettledRef.current = true;
|
||||
// The picker opened mid-gesture, so this drop has no wedge to run.
|
||||
if (sharePathsRef.current) return;
|
||||
try {
|
||||
const fileInfo = await api.inspectFiles(payload.paths);
|
||||
if (disposed || fileInfo.length === 0) return;
|
||||
if (disposed) return;
|
||||
if (fileInfo.length === 0) {
|
||||
oleSettledRef.current = true;
|
||||
return;
|
||||
}
|
||||
const mode: "formats" | "tools" = ringRef.current === "formats" ? "formats" : "tools";
|
||||
const next: RadialContext = {
|
||||
files: payload.paths,
|
||||
|
|
@ -499,16 +583,28 @@ export function RadialMenu() {
|
|||
}
|
||||
setBusy(true);
|
||||
flash(t("processing"), 12000);
|
||||
await waitForPaint();
|
||||
try {
|
||||
const outcome = await api.performFileAction("convert", current.files, format.toLowerCase());
|
||||
const outcome = await api.performFileAction(
|
||||
"convert",
|
||||
current.files,
|
||||
format.toLowerCase(),
|
||||
(done, total, packaging) => {
|
||||
flash(
|
||||
packaging
|
||||
? t("fileActionPackaging")
|
||||
: t("fileActionPageProgress", { done, total }),
|
||||
120000,
|
||||
);
|
||||
},
|
||||
);
|
||||
for (const output of outcome.outputs) {
|
||||
rememberRecent({ path: output, kind: recentKind(output), at: Date.now() });
|
||||
}
|
||||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
flash(String(error), 2600);
|
||||
window.setTimeout(() => void api.hideRadial(), 2600);
|
||||
showError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
|
@ -517,8 +613,14 @@ export function RadialMenu() {
|
|||
async function executeAction(id: string) {
|
||||
const current = contextRef.current;
|
||||
if (!current || busy) return;
|
||||
if (id === "send") {
|
||||
setSharePaths(current.files);
|
||||
sharePathsRef.current = current.files;
|
||||
shareNoticeRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (id === "convert") {
|
||||
const activeFormats = formatSetFor(
|
||||
const activeFormats = conversionFormats(
|
||||
current.fileInfo[0]?.kind ?? "other",
|
||||
current.fileInfo[0]?.extension ?? "",
|
||||
);
|
||||
|
|
@ -536,30 +638,34 @@ export function RadialMenu() {
|
|||
|
||||
if (id === "pdfOcr") {
|
||||
setBusy(true);
|
||||
flash(t("processing"), 120000);
|
||||
await waitForPaint();
|
||||
try {
|
||||
const pages = await api.renderPdfPages(current.files[0]);
|
||||
const chunks: string[] = [];
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
flash(
|
||||
`${t("ocrRunning")} ${index + 1}/${pages.length}`,
|
||||
120000,
|
||||
);
|
||||
const dataUrl = await api.readFileDataUrl(pages[index]);
|
||||
const result = await recognizeImage(dataUrl, (progress) => {
|
||||
try {
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
flash(
|
||||
`${t("ocrRunning")} ${index + 1}/${pages.length} · ${Math.round(progress * 100)}%`,
|
||||
`${t("ocrRunning")} ${index + 1}/${pages.length}`,
|
||||
120000,
|
||||
);
|
||||
});
|
||||
chunks.push(`--- Page ${index + 1} ---\n${result.text}`);
|
||||
const result = await recognizeImage(convertFileSrc(pages[index]), (progress) => {
|
||||
flash(
|
||||
`${t("ocrRunning")} ${index + 1}/${pages.length} · ${Math.round(progress * 100)}%`,
|
||||
120000,
|
||||
);
|
||||
});
|
||||
chunks.push(`--- Page ${index + 1} ---\n${result.text}`);
|
||||
}
|
||||
} finally {
|
||||
void api.cleanupPdfPages(pages).catch(() => undefined);
|
||||
}
|
||||
const output = await api.saveTextNear(current.files[0], chunks.join("\n\n"), " (OCR)");
|
||||
rememberRecent({ path: output, kind: "text", at: Date.now() });
|
||||
await api.openInEditor(output);
|
||||
void api.hideRadial();
|
||||
} catch (error) {
|
||||
flash(String(error), 3200);
|
||||
window.setTimeout(() => void api.hideRadial(), 3200);
|
||||
showError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
|
@ -581,6 +687,7 @@ export function RadialMenu() {
|
|||
if (id === "extractAudio" || id === "plain") {
|
||||
setBusy(true);
|
||||
flash(t("processing"), 12000);
|
||||
await waitForPaint();
|
||||
try {
|
||||
const outcome = await api.performFileAction(
|
||||
"convert",
|
||||
|
|
@ -593,8 +700,7 @@ export function RadialMenu() {
|
|||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
flash(String(error), 2600);
|
||||
window.setTimeout(() => void api.hideRadial(), 2600);
|
||||
showError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
|
@ -625,6 +731,7 @@ export function RadialMenu() {
|
|||
}
|
||||
setBusy(true);
|
||||
flash(t("processing"), 12000);
|
||||
await waitForPaint();
|
||||
try {
|
||||
const outcome = await api.performFileAction(action, current.files);
|
||||
for (const output of outcome.outputs) {
|
||||
|
|
@ -633,8 +740,7 @@ export function RadialMenu() {
|
|||
flash(outcome.message || t("saved"), 900);
|
||||
window.setTimeout(() => void api.hideRadial(), 850);
|
||||
} catch (error) {
|
||||
flash(String(error), 2600);
|
||||
window.setTimeout(() => void api.hideRadial(), 2600);
|
||||
showError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
|
@ -656,6 +762,24 @@ export function RadialMenu() {
|
|||
onPointerDown={(event) => {
|
||||
if (event.target === event.currentTarget) void api.hideRadial();
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
if (context.dragging || busy || sharePaths) return;
|
||||
const bounds = event.currentTarget.getBoundingClientRect();
|
||||
const next = sectorAt(
|
||||
event.clientX - bounds.left,
|
||||
event.clientY - bounds.top,
|
||||
wedgeCount,
|
||||
);
|
||||
if (next !== hoveredRef.current) {
|
||||
hoveredRef.current = next;
|
||||
setHovered(next);
|
||||
}
|
||||
}}
|
||||
onPointerLeave={() => {
|
||||
if (context.dragging) return;
|
||||
hoveredRef.current = null;
|
||||
setHovered(null);
|
||||
}}
|
||||
>
|
||||
<div className="radial-ambient" />
|
||||
<div className="radial-glass" />
|
||||
|
|
@ -748,7 +872,7 @@ export function RadialMenu() {
|
|||
);
|
||||
})}
|
||||
|
||||
<div className="radial-center">
|
||||
<div className={`radial-center ${busy ? "is-busy" : ""} ${error ? "has-error" : ""}`}>
|
||||
{context.fileInfo.length > 1 ? (
|
||||
<div
|
||||
className={`radial-file-stack stack-${Math.min(context.fileInfo.length, 3)}`}
|
||||
|
|
@ -782,6 +906,29 @@ export function RadialMenu() {
|
|||
: "—"}
|
||||
</div>
|
||||
</div>
|
||||
{busy ? (
|
||||
<div
|
||||
className="radial-progress"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={status || t("processing")}
|
||||
>
|
||||
<span className="radial-progress-ring" aria-hidden="true" />
|
||||
<div className="radial-progress-content">
|
||||
<LoaderCircle size={22} className="spin" aria-hidden="true" />
|
||||
<strong>{status || t("processing")}</strong>
|
||||
</div>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="radial-error" role="alert">
|
||||
<CircleAlert size={24} strokeWidth={1.8} aria-hidden="true" />
|
||||
<strong>{t("actionFailed")}</strong>
|
||||
<span className="radial-error-message">{error}</span>
|
||||
<button type="button" onClick={() => setError(null)} aria-label={t("close")}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{context.dragging && pointer && first?.preview ? (
|
||||
|
|
@ -797,14 +944,9 @@ export function RadialMenu() {
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
{busy || status || context.dragging ? (
|
||||
{!error && !busy && !sharePaths && (status || context.dragging) ? (
|
||||
<div className="radial-hint">
|
||||
{busy ? (
|
||||
<>
|
||||
<LoaderCircle size={15} className="spin" />
|
||||
{status || t("processing")}
|
||||
</>
|
||||
) : hoveredWedge ? (
|
||||
{hoveredWedge ? (
|
||||
ring === "formats" ? (
|
||||
<>
|
||||
{t("chooseFormat")}
|
||||
|
|
@ -826,6 +968,24 @@ export function RadialMenu() {
|
|||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{sharePaths ? (
|
||||
<SharePanel
|
||||
paths={sharePaths}
|
||||
onClose={() => {
|
||||
setSharePaths(null);
|
||||
sharePathsRef.current = null;
|
||||
// A result is flashed inside the ring, so the ring has to survive
|
||||
// long enough to show it; a plain close dismisses at once.
|
||||
const delay = shareNoticeRef.current ? 2_800 : 0;
|
||||
window.setTimeout(() => void api.hideRadial(), delay);
|
||||
}}
|
||||
onNotice={(message) => {
|
||||
shareNoticeRef.current = true;
|
||||
flash(message, 2_600);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,108 @@
|
|||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { Check, Inbox, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { decodeHexParam, formatBytes } from "../lib/utils";
|
||||
import type { ShareOffer } from "../types";
|
||||
|
||||
function readOffer(): ShareOffer | null {
|
||||
const raw = decodeHexParam(new URLSearchParams(window.location.search).get("offer"));
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as ShareOffer;
|
||||
return parsed.transferId && parsed.fileName ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The receiving half of a LAN transfer: a small always-on-top card that asks
|
||||
* whether to accept an incoming file. The Rust thread that opened this window is
|
||||
* blocked on the answer, so every path out of here has to answer or close.
|
||||
*/
|
||||
export function ShareNotice() {
|
||||
const { t } = useI18n();
|
||||
const offer = readOffer();
|
||||
const [left, setLeft] = useState(offer?.timeoutSeconds ?? 45);
|
||||
const [expired, setExpired] = useState(false);
|
||||
const settled = useRef(false);
|
||||
|
||||
// Closing the card without answering declines it on the Rust side, which is the
|
||||
// right outcome when the offer lapsed or was dismissed by hand.
|
||||
const close = useCallback(() => {
|
||||
void getCurrentWindow()
|
||||
.close()
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!offer) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
const started = Date.now();
|
||||
const timer = window.setInterval(() => {
|
||||
const elapsed = Math.floor((Date.now() - started) / 1000);
|
||||
const remaining = Math.max(0, offer.timeoutSeconds - elapsed);
|
||||
setLeft(remaining);
|
||||
if (remaining === 0) {
|
||||
window.clearInterval(timer);
|
||||
setExpired(true);
|
||||
// Give the "expired" label a beat to render before the card goes away.
|
||||
window.setTimeout(close, 900);
|
||||
}
|
||||
}, 250);
|
||||
return () => window.clearInterval(timer);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function answer(accepted: boolean) {
|
||||
if (!offer || settled.current) return;
|
||||
settled.current = true;
|
||||
try {
|
||||
await api.shareAnswer(offer.transferId, accepted);
|
||||
} catch {
|
||||
// A dead thread means the offer already timed out; closing is still right.
|
||||
}
|
||||
close();
|
||||
}
|
||||
|
||||
if (!offer) return <div className="share-notice is-empty" />;
|
||||
|
||||
const ratio = offer.timeoutSeconds > 0 ? left / offer.timeoutSeconds : 0;
|
||||
|
||||
return (
|
||||
<div className="share-notice" data-tauri-drag-region>
|
||||
<div className="share-notice-head" data-tauri-drag-region>
|
||||
<span className="share-notice-glyph">
|
||||
<Inbox size={16} />
|
||||
</span>
|
||||
<span className="share-notice-kicker" data-tauri-drag-region>
|
||||
{t("shareNoticeKicker", { peer: offer.peerName })}
|
||||
</span>
|
||||
<span className={`share-notice-count ${ratio < 0.25 ? "is-low" : ""}`}>
|
||||
{expired ? t("shareNoticeExpired") : `${left}s`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="share-notice-file" title={offer.fileName}>
|
||||
<strong data-tauri-drag-region>{offer.fileName}</strong>
|
||||
<small>{formatBytes(offer.size)}</small>
|
||||
</div>
|
||||
<div className="share-notice-actions">
|
||||
<button className="share-notice-decline" onClick={() => void answer(false)}>
|
||||
<X size={14} />
|
||||
{t("shareNoticeDecline")}
|
||||
</button>
|
||||
<button className="share-notice-accept" onClick={() => void answer(true)}>
|
||||
<Check size={14} />
|
||||
{t("shareNoticeAccept")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="share-notice-bar">
|
||||
<span style={{ width: `${(ratio * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,402 @@
|
|||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import {
|
||||
Apple,
|
||||
Check,
|
||||
CircleAlert,
|
||||
File as FileIcon,
|
||||
GripVertical,
|
||||
Laptop,
|
||||
LoaderCircle,
|
||||
Monitor,
|
||||
Radar,
|
||||
RefreshCw,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState, type DragEvent } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { basename, dirname, formatBytes } from "../lib/utils";
|
||||
import type { SharePeer, ShareTransfer } from "../types";
|
||||
|
||||
interface SharePanelProps {
|
||||
paths: string[];
|
||||
onClose: () => void;
|
||||
onNotice: (message: string) => void;
|
||||
}
|
||||
|
||||
const PLATFORM_LABEL: Record<string, string> = {
|
||||
macos: "shareMac",
|
||||
windows: "shareWindows",
|
||||
linux: "shareLinux",
|
||||
};
|
||||
|
||||
function PlatformIcon({ platform }: { platform: string }) {
|
||||
if (platform === "macos") return <Apple size={20} />;
|
||||
if (platform === "windows") return <Monitor size={20} />;
|
||||
return <Laptop size={20} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* AirDrop-style picker: Shift copies that answer our LAN beacon appear as cards and
|
||||
* tapping a card sends the file straight away.
|
||||
*/
|
||||
export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) {
|
||||
const { t } = useI18n();
|
||||
const [peers, setPeers] = useState<SharePeer[]>([]);
|
||||
const [searching, setSearching] = useState(true);
|
||||
const [busyPeer, setBusyPeer] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<ShareTransfer | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const sendingRef = useRef(false);
|
||||
const [selectedPaths, setSelectedPaths] = useState(paths);
|
||||
const [dragOverPeer, setDragOverPeer] = useState<string | null>(null);
|
||||
// Set while the peer decides, cleared by the first progress event or the reply.
|
||||
const [waitingFor, setWaitingFor] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTauri()) {
|
||||
setSearching(false);
|
||||
return;
|
||||
}
|
||||
const unlisteners: Array<() => void> = [];
|
||||
void listen<SharePeer[]>("share://peers", (event) => {
|
||||
setPeers(event.payload);
|
||||
if (event.payload.length > 0) setSearching(false);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void listen<ShareTransfer>("share://transfer", (event) => {
|
||||
const transfer = event.payload;
|
||||
// While this panel is sending, the progress events belong to us. Inbound
|
||||
// transfers are announced by the main window, which always listens.
|
||||
if (sendingRef.current) {
|
||||
setWaitingFor(null);
|
||||
setProgress(transfer);
|
||||
}
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void api
|
||||
.shareRefresh()
|
||||
.then((list) => {
|
||||
setPeers(list);
|
||||
if (list.length > 0) setSearching(false);
|
||||
})
|
||||
.catch(() => setSearching(false));
|
||||
// Beacons arrive within a couple of seconds; stop the spinner after that.
|
||||
const timer = window.setTimeout(() => setSearching(false), 4_000);
|
||||
return () => {
|
||||
unlisteners.forEach((unlisten) => unlisten());
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
async function send(peer: SharePeer, files: string[] = selectedPaths) {
|
||||
if (busyPeer || files.length === 0) return;
|
||||
setBusyPeer(peer.id);
|
||||
setFailed(false);
|
||||
setProgress(null);
|
||||
setWaitingFor(peer.name);
|
||||
sendingRef.current = true;
|
||||
try {
|
||||
const result = await api.shareSend(peer.id, files);
|
||||
setProgress(null);
|
||||
setWaitingFor(null);
|
||||
const peerName = result[0]?.peer ?? peer.name;
|
||||
onNotice(
|
||||
result.length > 1
|
||||
? t("shareSentMany", { count: result.length, peer: peerName })
|
||||
: t("shareSent", { name: result[0]?.name ?? basename(paths[0]), peer: peerName })
|
||||
);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
const message = String(error);
|
||||
setFailed(true);
|
||||
setProgress(null);
|
||||
setWaitingFor(null);
|
||||
const name =
|
||||
files.length > 1
|
||||
? t("shareFilesCount", { count: files.length })
|
||||
: basename(files[0]);
|
||||
if (message.includes("share-peer-gone")) onNotice(t("sharePeerGone"));
|
||||
else if (message.includes("share-unreachable")) onNotice(t("shareUnreachable"));
|
||||
// The peer's own answer arrives as an error, so these are not failures of ours.
|
||||
else if (message.includes("share-declined"))
|
||||
onNotice(t("shareDeclined", { name, peer: peer.name }));
|
||||
else if (message.includes("share-timeout"))
|
||||
onNotice(t("shareTimeout", { name, peer: peer.name }));
|
||||
else onNotice(t("shareFailed", { name }));
|
||||
} finally {
|
||||
sendingRef.current = false;
|
||||
setBusyPeer(null);
|
||||
}
|
||||
}
|
||||
|
||||
function searchAgain() {
|
||||
setSearching(true);
|
||||
setFailed(false);
|
||||
if (!isTauri()) {
|
||||
setSearching(false);
|
||||
return;
|
||||
}
|
||||
void api
|
||||
.shareRefresh()
|
||||
.then((list) => {
|
||||
setPeers(list);
|
||||
if (list.length > 0) setSearching(false);
|
||||
})
|
||||
.catch(() => setSearching(false));
|
||||
window.setTimeout(() => setSearching(false), 4_000);
|
||||
}
|
||||
|
||||
const sending = progress && progress.state === "sending";
|
||||
const ratio =
|
||||
sending && progress && progress.total > 0
|
||||
? Math.min(1, progress.sent / progress.total)
|
||||
: 0;
|
||||
// Keep the modal open while a transfer is live so the progress bar is visible.
|
||||
const closeDisabled = Boolean(busyPeer) || Boolean(sending);
|
||||
const allSelected = paths.length > 0 && selectedPaths.length === paths.length;
|
||||
|
||||
function togglePath(path: string) {
|
||||
setSelectedPaths((current) =>
|
||||
current.includes(path)
|
||||
? current.filter((candidate) => candidate !== path)
|
||||
: [...current, path],
|
||||
);
|
||||
}
|
||||
|
||||
function toggleAll() {
|
||||
setSelectedPaths(allSelected ? [] : paths);
|
||||
}
|
||||
|
||||
function dragPaths(event: DragEvent, fallback: string[]) {
|
||||
const raw = event.dataTransfer.getData("application/x-shift-share-paths");
|
||||
if (!raw) return fallback;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (Array.isArray(parsed) && parsed.every((path) => typeof path === "string")) {
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the current selection for malformed internal drags.
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="share-backdrop"
|
||||
onClick={() => {
|
||||
if (!closeDisabled) onClose();
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
className="share-panel"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("shareTitle")}
|
||||
>
|
||||
<header className="share-head">
|
||||
<span className="share-head-glyph">
|
||||
<Radar size={17} className={searching && peers.length === 0 ? "spin" : ""} />
|
||||
</span>
|
||||
<div className="share-head-copy">
|
||||
<h2>{t("shareTitle")}</h2>
|
||||
</div>
|
||||
<button
|
||||
className="home-icon-button"
|
||||
onClick={() => {
|
||||
if (!closeDisabled) onClose();
|
||||
}}
|
||||
aria-label={t("close")}
|
||||
title={t("close")}
|
||||
disabled={closeDisabled}
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="share-files" aria-label={t("shareFiles")}>
|
||||
<div className="share-files-head">
|
||||
<strong>{t("shareFiles")}</strong>
|
||||
<span>{t("shareSelectionCount", {
|
||||
selected: selectedPaths.length,
|
||||
total: paths.length,
|
||||
})}</span>
|
||||
{paths.length > 1 ? (
|
||||
<label className="share-select-all">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allSelected}
|
||||
onChange={toggleAll}
|
||||
disabled={closeDisabled}
|
||||
/>
|
||||
<span className="share-checkmark" aria-hidden="true">
|
||||
{allSelected ? <Check size={10} /> : null}
|
||||
</span>
|
||||
{t("shareSelectAll")}
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="share-file-list" role="group" aria-label={t("shareFiles")}>
|
||||
{paths.map((path) => {
|
||||
const checked = selectedPaths.includes(path);
|
||||
return (
|
||||
<label
|
||||
key={path}
|
||||
className={`share-file-row ${checked ? "is-checked" : ""}`}
|
||||
title={path}
|
||||
draggable={!closeDisabled}
|
||||
onDragStart={(event) => {
|
||||
const files = checked ? selectedPaths : [path];
|
||||
event.dataTransfer.effectAllowed = "copy";
|
||||
event.dataTransfer.setData(
|
||||
"application/x-shift-share-paths",
|
||||
JSON.stringify(files),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => togglePath(path)}
|
||||
disabled={closeDisabled}
|
||||
/>
|
||||
<span className="share-checkmark" aria-hidden="true">
|
||||
{checked ? <Check size={10} /> : null}
|
||||
</span>
|
||||
<FileIcon size={13} />
|
||||
<span className="share-file-copy">
|
||||
<strong>{basename(path)}</strong>
|
||||
<small>{dirname(path)}</small>
|
||||
</span>
|
||||
<GripVertical className="share-file-grip" size={13} aria-hidden="true" />
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{peers.length === 0 ? (
|
||||
<div className="share-empty">
|
||||
<span className="share-empty-glyph">
|
||||
{searching ? <LoaderCircle size={17} className="spin" /> : <Radar size={17} />}
|
||||
</span>
|
||||
<strong>{searching ? t("shareSearching") : t("shareNoPeers")}</strong>
|
||||
</div>
|
||||
) : (
|
||||
<div className="share-grid">
|
||||
{peers.map((peer) => {
|
||||
const active = busyPeer === peer.id;
|
||||
const dropTarget = dragOverPeer === peer.id;
|
||||
return (
|
||||
<button
|
||||
key={peer.id}
|
||||
className={`share-peer ${active ? "is-active" : ""} ${dropTarget ? "is-drop-target" : ""}`}
|
||||
onClick={() => void send(peer)}
|
||||
disabled={selectedPaths.length === 0 || (closeDisabled && !active)}
|
||||
title={peer.address}
|
||||
onDragEnter={(event) => {
|
||||
if (!closeDisabled) {
|
||||
event.preventDefault();
|
||||
setDragOverPeer(peer.id);
|
||||
}
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (!closeDisabled) {
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
}}
|
||||
onDragLeave={(event) => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
|
||||
setDragOverPeer((current) => (current === peer.id ? null : current));
|
||||
}
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragOverPeer(null);
|
||||
const files = dragPaths(event, selectedPaths);
|
||||
if (files.length > 0) void send(peer, files);
|
||||
}}
|
||||
>
|
||||
<span className="share-peer-avatar">
|
||||
{active ? <LoaderCircle size={20} className="spin" /> : <PlatformIcon platform={peer.platform} />}
|
||||
</span>
|
||||
<span className="share-peer-name">{peer.name}</span>
|
||||
<span className="share-peer-meta">
|
||||
{t(PLATFORM_LABEL[peer.platform] ?? "shareLinux")}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{waitingFor ? (
|
||||
<div className="share-progress">
|
||||
<div className="share-progress-head">
|
||||
<span className="share-progress-wait">
|
||||
<LoaderCircle size={12} className="spin" />
|
||||
{t("shareWaiting", { peer: waitingFor })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="share-bar is-indeterminate">
|
||||
<span />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{sending && progress && !waitingFor ? (
|
||||
<div className="share-progress">
|
||||
<div className="share-progress-head">
|
||||
<span>
|
||||
{t("shareSendingTo", {
|
||||
name: progress.fileName,
|
||||
peer: progress.peerName,
|
||||
})}
|
||||
</span>
|
||||
<small>
|
||||
{formatBytes(progress.sent)} / {formatBytes(progress.total)}
|
||||
</small>
|
||||
</div>
|
||||
<div className="share-bar">
|
||||
<span style={{ width: `${(ratio * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{failed ? (
|
||||
<div className="share-error">
|
||||
<CircleAlert size={13} />
|
||||
{t("shareFailed", {
|
||||
name:
|
||||
paths.length > 1 ? t("shareFilesCount", { count: paths.length }) : basename(paths[0]),
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<footer className="share-foot">
|
||||
<button
|
||||
className="share-reshow"
|
||||
onClick={searchAgain}
|
||||
disabled={closeDisabled}
|
||||
title={t("shareRefresh")}
|
||||
>
|
||||
<RefreshCw size={12} className={searching ? "spin" : ""} />
|
||||
{searching ? t("shareSearching") : t("shareRefresh")}
|
||||
</button>
|
||||
<kbd>Esc</kbd>
|
||||
</footer>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
205
src/i18n.ts
205
src/i18n.ts
|
|
@ -1,4 +1,6 @@
|
|||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "./lib/api";
|
||||
|
||||
export type Lang = "en" | "zh";
|
||||
|
||||
|
|
@ -23,7 +25,6 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
english: "English",
|
||||
chinese: "简体中文",
|
||||
privacy: "Local by design",
|
||||
privacyBody: "Files never leave your computer. OCR runs in the app's bundled engine.",
|
||||
chooseAction: "Choose an action",
|
||||
chooseFormat: "Release over a format",
|
||||
releaseCancel: "Move back to the center to cancel",
|
||||
|
|
@ -64,9 +65,13 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
file: "file",
|
||||
ready: "Ready",
|
||||
processing: "Processing…",
|
||||
fileActionPageProgress: "Converting page {done}/{total}…",
|
||||
fileActionPackaging: "Building document…",
|
||||
saved: "Saved",
|
||||
copy: "Copy",
|
||||
pin: "Pin",
|
||||
pinUnavailable: "The pinned image is unavailable.",
|
||||
pinLoadFailed: "The pinned image could not be displayed.",
|
||||
copyText: "Copy text",
|
||||
saveAs: "Save As…",
|
||||
open: "Open",
|
||||
|
|
@ -77,11 +82,8 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
stopRecording: "Stop recording",
|
||||
audio: "Audio",
|
||||
dragSelect: "Drag to select an area",
|
||||
screenshotHint: "Click the checkmark to capture",
|
||||
recordingHint: "Choose audio, then start recording",
|
||||
recordingSaved: "Recording saved",
|
||||
ocrTitle: "Extract text",
|
||||
ocrHint: "Run private, on-device OCR on this image.",
|
||||
ocrRunning: "Reading text…",
|
||||
ocrEmpty: "No readable text found.",
|
||||
extractText: "Extract text",
|
||||
|
|
@ -89,11 +91,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
captureFailed: "Capture failed",
|
||||
recordingFailed: "Recording failed",
|
||||
actionFailed: "That action could not be completed",
|
||||
comingSoon: "This tool is on the next milestone.",
|
||||
comingSoon: "Coming soon.",
|
||||
windowTitle: "Shift",
|
||||
allSet: "All set",
|
||||
permissionHint:
|
||||
"The first capture may ask for Screen Recording permission in System Settings.",
|
||||
openScreenSettings: "Open screen recording settings",
|
||||
source: "Source",
|
||||
quickActions: "Quick actions",
|
||||
|
|
@ -102,22 +102,44 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
unsupported: "No formats for this file type",
|
||||
homeDropTitle: "Drop files to get started",
|
||||
homeDropRelease: "Release to choose an action",
|
||||
homeDropBody: "Process images, PDFs, documents and media locally. Nothing leaves this Mac.",
|
||||
convertFiles: "Convert files",
|
||||
fileTools: "File tools",
|
||||
dragHint: "Or drag from Finder:",
|
||||
dragHintActive: "Release over a button to run just that action:",
|
||||
dragHintConvert: "convert",
|
||||
dragHintTools: "tools",
|
||||
items: "items",
|
||||
nothingYet: "Nothing yet",
|
||||
itemCount: "{count} items",
|
||||
recentEmpty: "Captures and processed files will appear here.",
|
||||
outputSettings: "Output & access",
|
||||
sendTo: "Send to another Shift",
|
||||
sendShort: "Send",
|
||||
shareTitle: "Send to a device",
|
||||
shareRefresh: "Search again",
|
||||
shareSearching: "Looking for devices…",
|
||||
shareNoPeers: "No other Shift found on this network.",
|
||||
shareFiles: "Files",
|
||||
shareSelectAll: "Select all",
|
||||
shareSelectionCount: "{selected} of {total} selected",
|
||||
shareNoFiles: "Select at least one file.",
|
||||
shareSent: "{name} sent to {peer}.",
|
||||
shareSentMany: "{count} files sent to {peer}.",
|
||||
shareFilesCount: "{count} files",
|
||||
shareReceived: "{peer} sent you {name}.",
|
||||
shareFailed: "Could not send {name}.",
|
||||
sharePeerGone: "That device is no longer reachable.",
|
||||
shareUnreachable: "The device refused the connection. Check its firewall.",
|
||||
shareSendingTo: "Sending {name} to {peer}",
|
||||
shareNoticeKicker: "{peer} wants to send you a file",
|
||||
shareNoticeAccept: "Accept",
|
||||
shareNoticeDecline: "Decline",
|
||||
shareNoticeExpired: "Expired",
|
||||
shareWaiting: "Waiting for {peer} to accept…",
|
||||
shareDeclined: "{peer} declined {name}.",
|
||||
shareTimeout: "No answer from {peer}, so {name} was not sent.",
|
||||
shareMac: "Mac",
|
||||
shareWindows: "Windows",
|
||||
shareLinux: "Linux",
|
||||
systemSettings: "System settings",
|
||||
fileResults: "File results",
|
||||
nextToOriginal: "Same folder",
|
||||
customFolder: "Custom folder",
|
||||
customFolderHint: "Processed files are collected in the folder below.",
|
||||
alongsideHint: "Processed files are saved in the same folder as the original with a descriptive suffix.",
|
||||
chooseFolder: "Choose",
|
||||
revealFolder: "Show folder",
|
||||
reset: "Reset",
|
||||
|
|
@ -125,33 +147,50 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
recordings: "Recordings",
|
||||
location: "Location",
|
||||
showInFinder: "Show results in Finder",
|
||||
showInFinderHint: "Reveal the newest output after a file action completes.",
|
||||
behaviour: "Behaviour",
|
||||
dragRings: "Drag rings",
|
||||
dragRingsHint: "Hold Shift while dragging a file to open the radial menu.",
|
||||
shiftDrop: "ShiftDrop",
|
||||
autostart: "Launch at login",
|
||||
autostartHint: "Start Shift automatically when you sign in.",
|
||||
hotkeys: "Keyboard shortcuts",
|
||||
hotkeysOk: "This copy of Shift owns the shortcuts, so the keyboard works.",
|
||||
hotkeysNotLive:
|
||||
"macOS refused these shortcuts, usually because another app already uses them. Close the conflicting app and retry.",
|
||||
hotkeysDead:
|
||||
"Another copy of Shift is running, so this window's keyboard shortcuts do nothing.",
|
||||
hotkeysOthers:
|
||||
"{count} other Shift process is already running. macOS gives global hotkeys to only one of them, so the shortcuts of the others do nothing.",
|
||||
hotkeysDead: "Another Shift is running, so this window's shortcuts are inactive.",
|
||||
hotkeysFix: "Quit the other copies and reclaim the shortcuts",
|
||||
accessCheck: "Write access",
|
||||
accessCheckHint: "Confirm Shift can write to each output folder. macOS may ask for permission the first time.",
|
||||
checking: "Checking…",
|
||||
checkAccess: "Check folders",
|
||||
accessOk: "Write access confirmed.",
|
||||
runtimeComponents: "Runtime components",
|
||||
languageSaveFailed: "The language could not be saved. Try again.",
|
||||
runtimeRefresh: "Refresh",
|
||||
runtimeChecking: "Inspecting…",
|
||||
runtimeSummary:
|
||||
"These are the components installed on this computer. Select Install for any missing component.",
|
||||
runtimeAvailable: "Available",
|
||||
runtimeMissing: "Missing",
|
||||
runtimeInstall: "Install",
|
||||
runtimeInstalling: "Installing…",
|
||||
runtimeInstallComplete: "Installed {name}.",
|
||||
runtimeInstallNeedsHomebrew:
|
||||
"Homebrew is required to install Pandoc and FFmpeg. Install Homebrew, then try again.",
|
||||
runtimeInstallNeedsWinget:
|
||||
"Automatic installation requires Microsoft App Installer (WinGet). Install or update it, then try again.",
|
||||
runtimeInstallUnsupported: "Automatic installation is not available for this component.",
|
||||
runtimeInstallFailed: "Installation failed.",
|
||||
runtimeOpenHomebrew: "Open brew.sh",
|
||||
runtimeOpenWinget: "WinGet setup guide",
|
||||
runtimeBundledInApp: "Included in Shift",
|
||||
runtimeDocuments: "Documents",
|
||||
runtimeGraphics: "Graphics & PDF",
|
||||
runtimeVideo: "Video & audio",
|
||||
runtimeCapture: "Capture",
|
||||
runtimeOcr: "OCR",
|
||||
runtimeSource_bundled: "Built-in",
|
||||
runtimeSource_system: "System",
|
||||
runtimeSource_external: "External",
|
||||
permissions: "Permissions",
|
||||
screenPermission: "Screen Recording",
|
||||
screenPermissionPrompt:
|
||||
"Screen Recording is off. Enable it to capture screenshots and recordings.",
|
||||
filesPermission: "Files & Folders",
|
||||
filesPermissionHint:
|
||||
"macOS grants file access per folder. Shift only reads files you choose; use Check folders to verify each output location.",
|
||||
agoNow: "just now",
|
||||
agoMinutes: "{count}m ago",
|
||||
agoHours: "{count}h ago",
|
||||
|
|
@ -177,7 +216,6 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
english: "English",
|
||||
chinese: "简体中文",
|
||||
privacy: "本地优先",
|
||||
privacyBody: "文件不会离开你的电脑,OCR 使用应用内置引擎。",
|
||||
chooseAction: "选择操作",
|
||||
chooseFormat: "松开鼠标即可转换",
|
||||
releaseCancel: "移回中心可取消",
|
||||
|
|
@ -218,9 +256,13 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
file: "个文件",
|
||||
ready: "就绪",
|
||||
processing: "处理中…",
|
||||
fileActionPageProgress: "正在转换第 {done}/{total} 页…",
|
||||
fileActionPackaging: "正在生成文档…",
|
||||
saved: "已保存",
|
||||
copy: "复制",
|
||||
pin: "钉在屏幕上",
|
||||
pinUnavailable: "无法读取要钉住的图片。",
|
||||
pinLoadFailed: "无法显示钉住的图片。",
|
||||
copyText: "复制文字",
|
||||
saveAs: "另存为…",
|
||||
open: "打开",
|
||||
|
|
@ -231,11 +273,8 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
stopRecording: "停止录屏",
|
||||
audio: "声音",
|
||||
dragSelect: "拖动框选区域",
|
||||
screenshotHint: "点击对勾完成截图",
|
||||
recordingHint: "选择是否录制声音,然后开始",
|
||||
recordingSaved: "录屏已保存",
|
||||
ocrTitle: "提取文字",
|
||||
ocrHint: "在本机识别这张图片中的文字。",
|
||||
ocrRunning: "正在识别文字…",
|
||||
ocrEmpty: "没有识别到可读文字。",
|
||||
extractText: "提取文字",
|
||||
|
|
@ -243,10 +282,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
captureFailed: "截图失败",
|
||||
recordingFailed: "录屏失败",
|
||||
actionFailed: "操作未能完成",
|
||||
comingSoon: "这个工具会在下一阶段开放。",
|
||||
comingSoon: "该功能即将推出。",
|
||||
windowTitle: "Shift",
|
||||
allSet: "准备就绪",
|
||||
permissionHint: "第一次截图时,macOS 可能要求你在系统设置中允许屏幕录制。",
|
||||
openScreenSettings: "打开屏幕录制设置",
|
||||
source: "来源",
|
||||
quickActions: "快捷操作",
|
||||
|
|
@ -255,22 +293,44 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
unsupported: "此文件类型暂时没有可用格式",
|
||||
homeDropTitle: "拖入文件开始处理",
|
||||
homeDropRelease: "松开即可选择操作",
|
||||
homeDropBody: "图片、PDF、文档和音视频全部在本机处理,不会上传。",
|
||||
convertFiles: "文件转换",
|
||||
fileTools: "文件工具",
|
||||
dragHint: "也可以从访达拖拽:",
|
||||
dragHintActive: "拖到哪个按钮就执行哪个操作:",
|
||||
dragHintConvert: "文件转换",
|
||||
dragHintTools: "文件工具",
|
||||
items: "项",
|
||||
nothingYet: "暂无内容",
|
||||
itemCount: "{count} 项",
|
||||
recentEmpty: "截图和处理后的文件会出现在这里。",
|
||||
outputSettings: "输出与权限",
|
||||
sendTo: "发送到其他 Shift",
|
||||
sendShort: "发送",
|
||||
shareTitle: "发送到设备",
|
||||
shareRefresh: "重新搜索",
|
||||
shareSearching: "正在查找设备…",
|
||||
shareNoPeers: "局域网内没有找到其他 Shift。",
|
||||
shareFiles: "文件",
|
||||
shareSelectAll: "全选",
|
||||
shareSelectionCount: "已选 {selected}/{total}",
|
||||
shareNoFiles: "请至少勾选一个文件。",
|
||||
shareSent: "已将 {name} 发送到 {peer}。",
|
||||
shareSentMany: "已发送 {count} 个文件到 {peer}。",
|
||||
shareFilesCount: "{count} 个文件",
|
||||
shareReceived: "{peer} 给你发送了 {name}。",
|
||||
shareFailed: "{name} 发送失败。",
|
||||
shareNoticeKicker: "{peer} 想发送一个文件给你",
|
||||
shareNoticeAccept: "接收",
|
||||
shareNoticeDecline: "拒绝",
|
||||
shareNoticeExpired: "已超时",
|
||||
shareWaiting: "等待 {peer} 确认接收…",
|
||||
shareDeclined: "{peer} 拒绝了 {name}。",
|
||||
shareTimeout: "{peer} 未应答,{name} 未发送。",
|
||||
sharePeerGone: "该设备已不可达。",
|
||||
shareUnreachable: "设备拒绝了连接,请检查它的防火墙设置。",
|
||||
shareSendingTo: "正在将 {name} 发送到 {peer}",
|
||||
shareMac: "Mac",
|
||||
shareWindows: "Windows",
|
||||
shareLinux: "Linux",
|
||||
systemSettings: "系统设置",
|
||||
fileResults: "文件处理结果",
|
||||
nextToOriginal: "原文件同目录",
|
||||
customFolder: "指定文件夹",
|
||||
customFolderHint: "处理后的文件会集中保存到下面的文件夹。",
|
||||
alongsideHint: "处理后的文件会保存在原文件所在目录,并自动添加说明后缀。",
|
||||
chooseFolder: "选择",
|
||||
revealFolder: "显示文件夹",
|
||||
reset: "恢复默认",
|
||||
|
|
@ -278,29 +338,46 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
recordings: "录屏",
|
||||
location: "保存位置",
|
||||
showInFinder: "完成后在访达中显示",
|
||||
showInFinderHint: "文件操作完成后自动定位到最新结果。",
|
||||
behaviour: "行为",
|
||||
dragRings: "拖拽圆环",
|
||||
dragRingsHint: "在访达或资源管理器中拖动文件时按住 Shift 即可唤出圆环。",
|
||||
shiftDrop: "ShiftDrop",
|
||||
autostart: "开机时启动",
|
||||
autostartHint: "登录系统后自动启动 Shift。",
|
||||
hotkeys: "键盘快捷键",
|
||||
hotkeysOk: "当前副本已持有快捷键,键盘快捷键可以正常使用。",
|
||||
hotkeysNotLive: "macOS 拒绝了这些快捷键,通常是被其他应用占用了。关闭冲突的应用后重试。",
|
||||
hotkeysDead: "另一个 Shift 副本正在运行,因此本窗口的键盘快捷键不会生效。",
|
||||
hotkeysOthers: "检测到 {count} 个其他 Shift 进程。macOS 只把全局快捷键交给其中一个,其余副本按键盘不会有任何反应。",
|
||||
hotkeysDead: "另一个 Shift 正在运行,本窗口的快捷键无效。",
|
||||
hotkeysFix: "退出其他副本并重新接管快捷键",
|
||||
accessCheck: "写入权限",
|
||||
accessCheckHint: "检查 Shift 是否可写入各输出目录。macOS 可能首次请求授权。",
|
||||
checking: "检测中…",
|
||||
checkAccess: "检测目录",
|
||||
accessOk: "写入权限正常。",
|
||||
runtimeComponents: "运行组件",
|
||||
languageSaveFailed: "语言设置保存失败,请重试。",
|
||||
runtimeRefresh: "重新检测",
|
||||
runtimeChecking: "检测中…",
|
||||
runtimeSummary: "以下是本机安装组件的情况,未安装的组件请点击安装。",
|
||||
runtimeAvailable: "可用",
|
||||
runtimeMissing: "缺失",
|
||||
runtimeInstall: "安装",
|
||||
runtimeInstalling: "安装中…",
|
||||
runtimeInstallComplete: "已安装 {name}。",
|
||||
runtimeInstallNeedsHomebrew: "自动安装需要 Homebrew。请先安装 Homebrew,然后重试。",
|
||||
runtimeInstallNeedsWinget:
|
||||
"Windows 自动安装需要“应用安装程序”(WinGet)。安装或更新后请重试。",
|
||||
runtimeInstallUnsupported: "此组件暂不支持自动安装。",
|
||||
runtimeInstallFailed: "安装失败。",
|
||||
runtimeOpenHomebrew: "打开 brew.sh",
|
||||
runtimeOpenWinget: "打开 WinGet 安装说明",
|
||||
runtimeBundledInApp: "随 Shift 内置",
|
||||
runtimeDocuments: "文档",
|
||||
runtimeGraphics: "图形与 PDF",
|
||||
runtimeVideo: "视频与音频",
|
||||
runtimeCapture: "截图与录屏",
|
||||
runtimeOcr: "文字识别",
|
||||
runtimeSource_bundled: "内置",
|
||||
runtimeSource_system: "系统",
|
||||
runtimeSource_external: "外部",
|
||||
permissions: "系统权限",
|
||||
screenPermission: "屏幕录制",
|
||||
screenPermissionPrompt: "屏幕录制权限未开启,截图和录屏需要该权限。",
|
||||
filesPermission: "文件与文件夹",
|
||||
filesPermissionHint:
|
||||
"macOS 按文件夹授权。Shift 只访问你选择的文件;可用“检测目录”验证每个输出位置。",
|
||||
agoNow: "刚刚",
|
||||
agoMinutes: "{count} 分钟前",
|
||||
agoHours: "{count} 小时前",
|
||||
|
|
@ -314,6 +391,24 @@ export function getInitialLang(): Lang {
|
|||
return navigator.language.toLowerCase().startsWith("zh") ? "zh" : "en";
|
||||
}
|
||||
|
||||
/// Tell Rust which language the interface uses. The tray menu is built natively,
|
||||
/// so it can only follow along when it is told.
|
||||
export function publishLang(lang: Lang) {
|
||||
localStorage.setItem("shift.lang", lang);
|
||||
document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
|
||||
window.dispatchEvent(new Event("shift:lang"));
|
||||
// The tray re-labels itself on the native side; nothing here waits for it.
|
||||
if (isTauri()) {
|
||||
void api.setLanguage(lang).catch((error) => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("shift:language-error", {
|
||||
detail: String(error).replace(/^Error:\s*/, ""),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function translate(lang: Lang, key: string, vars?: Record<string, string | number>): string {
|
||||
let value = messages[lang][key] ?? messages.en[key] ?? key;
|
||||
if (vars) {
|
||||
|
|
@ -336,9 +431,7 @@ export function useI18n() {
|
|||
};
|
||||
}, []);
|
||||
const setLang = useCallback((next: Lang) => {
|
||||
localStorage.setItem("shift.lang", next);
|
||||
document.documentElement.lang = next === "zh" ? "zh-CN" : "en";
|
||||
window.dispatchEvent(new Event("shift:lang"));
|
||||
publishLang(next);
|
||||
setLangState(next);
|
||||
}, []);
|
||||
const t = useCallback(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import type {
|
||||
ActionOutcome,
|
||||
AppSettings,
|
||||
|
|
@ -11,21 +12,79 @@ import type {
|
|||
RadialContext,
|
||||
RecordingInfo,
|
||||
RecordingOptions,
|
||||
SharePeer,
|
||||
RuntimeInfo,
|
||||
SwitchState,
|
||||
SwitchUpdate,
|
||||
WriteCheck,
|
||||
} from "../types";
|
||||
|
||||
interface FileActionResultEvent {
|
||||
jobId: string;
|
||||
outcome?: ActionOutcome;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface FileActionProgressEvent {
|
||||
jobId: string;
|
||||
done: number;
|
||||
total: number;
|
||||
packaging: boolean;
|
||||
}
|
||||
|
||||
async function performFileAction(
|
||||
action: string,
|
||||
paths: string[],
|
||||
target?: string,
|
||||
onProgress?: (done: number, total: number, packaging: boolean) => void,
|
||||
): Promise<ActionOutcome> {
|
||||
const jobId =
|
||||
typeof crypto.randomUUID === "function"
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
let resolveOutcome!: (outcome: ActionOutcome) => void;
|
||||
let rejectOutcome!: (reason?: unknown) => void;
|
||||
const completed = new Promise<ActionOutcome>((resolve, reject) => {
|
||||
resolveOutcome = resolve;
|
||||
rejectOutcome = reject;
|
||||
});
|
||||
const unlisten: UnlistenFn = await listen<FileActionResultEvent>(
|
||||
"app://file-action-finished",
|
||||
(event) => {
|
||||
if (event.payload.jobId !== jobId) return;
|
||||
if (event.payload.error) rejectOutcome(new Error(event.payload.error));
|
||||
else if (event.payload.outcome) resolveOutcome(event.payload.outcome);
|
||||
else rejectOutcome(new Error("File action returned no result."));
|
||||
},
|
||||
);
|
||||
const unlistenProgress = onProgress
|
||||
? await listen<FileActionProgressEvent>("app://file-action-progress", (event) => {
|
||||
if (event.payload.jobId === jobId) {
|
||||
onProgress(event.payload.done, event.payload.total, event.payload.packaging);
|
||||
}
|
||||
})
|
||||
: null;
|
||||
try {
|
||||
await invoke<void>("perform_file_action", { jobId, action, paths, target });
|
||||
return await completed;
|
||||
} finally {
|
||||
unlisten();
|
||||
unlistenProgress?.();
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
inspectFiles: (paths: string[]) => invoke<FileInfo[]>("inspect_files", { paths }),
|
||||
performFileAction: (action: string, paths: string[], target?: string) =>
|
||||
invoke<ActionOutcome>("perform_file_action", { action, paths, target }),
|
||||
performFileAction,
|
||||
revealFile: (path: string) => invoke<void>("reveal_file", { path }),
|
||||
existingFiles: (paths: string[]) => invoke<string[]>("existing_files", { paths }),
|
||||
openFile: (path: string) => invoke<void>("open_file", { path }),
|
||||
readFileDataUrl: (path: string) => invoke<string>("read_file_data_url", { path }),
|
||||
readTextFile: (path: string) => invoke<string>("read_text_file", { path }),
|
||||
readImageData: (path: string) => invoke<string>("read_image_data", { path }),
|
||||
saveImageData: (source: string, dataUrl: string, suffix?: string) =>
|
||||
invoke<string>("save_image_data", { source, dataUrl, suffix }),
|
||||
renderPdfPages: (path: string) => invoke<string[]>("render_pdf_pages", { path }),
|
||||
cleanupPdfPages: (paths: string[]) => invoke<void>("cleanup_pdf_pages", { paths }),
|
||||
saveTextNear: (source: string, text: string, suffix?: string) =>
|
||||
invoke<string>("save_text_near", { source, text, suffix }),
|
||||
copyFileTo: (source: string, destination: string) =>
|
||||
|
|
@ -46,18 +105,32 @@ export const api = {
|
|||
closeEditor: () => invoke<void>("close_editor"),
|
||||
openInEditor: (path: string) => invoke<EditorInfo>("open_in_editor", { path }),
|
||||
pinImage: (path: string) => invoke<void>("pin_image", { path }),
|
||||
getPinnedImage: () =>
|
||||
invoke<{ id: number; path: string; dataUrl: string; width: number; height: number } | null>(
|
||||
"get_pinned_image",
|
||||
),
|
||||
pinReady: (id: number | null) => invoke<void>("pin_ready", { id }),
|
||||
closePin: () => invoke<void>("close_pin"),
|
||||
getRadialContext: () => invoke<RadialContext | null>("get_radial_context"),
|
||||
hideRadial: () => invoke<void>("hide_radial"),
|
||||
showFilesInRadial: (files: string[], mode?: "actions" | "formats" | "tools") =>
|
||||
invoke<RadialContext>("show_files_in_radial", { files, mode }),
|
||||
sharePeers: () => invoke<SharePeer[]>("share_peers"),
|
||||
shareAnswer: (transferId: string, accepted: boolean) =>
|
||||
invoke<boolean>("share_answer", { transferId, accepted }),
|
||||
shareRefresh: () => invoke<SharePeer[]>("share_refresh"),
|
||||
shareSend: (peerId: string, paths: string[]) =>
|
||||
invoke<{ name: string; size: number; peer: string }[]>("share_send", { peerId, paths }),
|
||||
getSettings: () => invoke<AppSettings>("get_app_settings"),
|
||||
setOutputDirectory: (kind: "screenshot" | "recording" | "files", path: string | null) =>
|
||||
invoke<AppSettings>("set_output_directory", { kind, path }),
|
||||
setFileOutputMode: (mode: FileOutputMode) =>
|
||||
invoke<AppSettings>("set_file_output_mode", { mode }),
|
||||
setAutoReveal: (enabled: boolean) => invoke<AppSettings>("set_auto_reveal", { enabled }),
|
||||
setDragEnabled: (enabled: boolean) => invoke<AppSettings>("set_drag_enabled", { enabled }),
|
||||
setAutostart: (enabled: boolean) => invoke<AppSettings>("set_autostart", { enabled }),
|
||||
setAutoReveal: (enabled: boolean) => invoke<SwitchState>("set_auto_reveal", { enabled }),
|
||||
setDragEnabled: (enabled: boolean) => invoke<SwitchState>("set_drag_enabled", { enabled }),
|
||||
setShareEnabled: (enabled: boolean) => invoke<SwitchState>("set_share_enabled", { enabled }),
|
||||
setAutostart: (enabled: boolean) => invoke<SwitchUpdate>("set_autostart", { enabled }),
|
||||
setLanguage: (language: string) => invoke<string>("set_language", { language }),
|
||||
hotkeyStatus: () => invoke<HotkeyStatus>("hotkey_status"),
|
||||
quitOtherInstances: () => invoke<number>("quit_other_instances"),
|
||||
reclaimHotkeys: () => invoke<HotkeyStatus>("reclaim_hotkeys"),
|
||||
|
|
@ -65,4 +138,7 @@ export const api = {
|
|||
revealOutputDirectory: (kind: "screenshot" | "recording" | "files") =>
|
||||
invoke<void>("reveal_output_directory", { kind }),
|
||||
openFilesPermissionSettings: () => invoke<void>("open_files_permission_settings"),
|
||||
getRuntimeInfo: () => invoke<RuntimeInfo>("machine_info"),
|
||||
installRuntimeComponent: (componentId: string) =>
|
||||
invoke<string>("install_runtime_component", { componentId }),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { conversionFormats } from "./conversionFormats.ts";
|
||||
|
||||
test("document conversion never offers the source format again", () => {
|
||||
const cases = {
|
||||
docx: ["PDF", "MD", "TXT", "HTML", "RTF", "ODT"],
|
||||
rtf: ["PDF", "DOCX", "MD", "TXT", "HTML", "ODT"],
|
||||
odt: ["PDF", "DOCX", "MD", "TXT", "HTML", "RTF"],
|
||||
txt: ["PDF", "DOCX", "MD", "HTML", "RTF", "ODT"],
|
||||
md: ["PDF", "DOCX", "TXT", "HTML", "RTF", "ODT"],
|
||||
html: ["PDF", "DOCX", "MD", "TXT", "RTF", "ODT"],
|
||||
htm: ["PDF", "DOCX", "MD", "TXT", "RTF", "ODT"],
|
||||
};
|
||||
|
||||
for (const [extension, expected] of Object.entries(cases)) {
|
||||
assert.deepEqual(conversionFormats("document", extension), expected, extension);
|
||||
}
|
||||
});
|
||||
|
||||
test("aliases of the source format are not offered", () => {
|
||||
assert.ok(!conversionFormats("image", "jpeg").includes("JPG"));
|
||||
assert.ok(!conversionFormats("image", "tif").includes("TIFF"));
|
||||
assert.ok(!conversionFormats("image", "heif").includes("HEIC"));
|
||||
});
|
||||
|
||||
test("every convertible image source has real alternative targets", () => {
|
||||
for (const extension of [
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"webp",
|
||||
"tiff",
|
||||
"tif",
|
||||
"bmp",
|
||||
"gif",
|
||||
"heic",
|
||||
"heif",
|
||||
"avif",
|
||||
]) {
|
||||
const formats = conversionFormats("image", extension);
|
||||
assert.ok(formats.length > 0, extension);
|
||||
assert.ok(!formats.some((format) => format.toLowerCase() === extension), extension);
|
||||
}
|
||||
});
|
||||
|
||||
test("PDF conversion includes every implemented document target", () => {
|
||||
assert.deepEqual(conversionFormats("pdf", "pdf"), [
|
||||
"PNG",
|
||||
"JPG",
|
||||
"TIFF",
|
||||
"HEIC",
|
||||
"TXT",
|
||||
"MD",
|
||||
"DOCX",
|
||||
"RTF",
|
||||
"ODT",
|
||||
]);
|
||||
});
|
||||
|
||||
test("media conversion never repeats the source container or codec", () => {
|
||||
assert.deepEqual(conversionFormats("video", "mp4"), ["MOV", "GIF", "M4A"]);
|
||||
assert.deepEqual(conversionFormats("video", "mov"), ["MP4", "GIF", "M4A"]);
|
||||
assert.deepEqual(conversionFormats("audio", "mp3"), ["M4A", "WAV"]);
|
||||
assert.deepEqual(conversionFormats("audio", "wav"), ["M4A", "MP3"]);
|
||||
assert.deepEqual(conversionFormats("audio", "m4a"), ["WAV", "MP3"]);
|
||||
});
|
||||
|
||||
test("legacy formats stay visible only through open and edit actions", () => {
|
||||
assert.deepEqual(conversionFormats("document", "doc"), []);
|
||||
assert.deepEqual(conversionFormats("document", "pages"), []);
|
||||
assert.deepEqual(conversionFormats("presentation", "ppt"), []);
|
||||
assert.deepEqual(conversionFormats("presentation", "key"), []);
|
||||
assert.deepEqual(conversionFormats("spreadsheet", "numbers"), []);
|
||||
});
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
import type { FileInfo } from "../types";
|
||||
|
||||
type FileKind = FileInfo["kind"];
|
||||
|
||||
const DOCUMENT_SOURCES = new Set(["docx", "rtf", "odt", "txt", "md", "html", "htm"]);
|
||||
const PRESENTATION_SOURCES = new Set(["pptx"]);
|
||||
const SPREADSHEET_SOURCES = new Set(["xlsx", "xls", "xlsb", "ods", "csv", "tsv"]);
|
||||
|
||||
const IMAGE_FORMATS = ["PNG", "JPG", "WEBP", "HEIC", "TIFF", "BMP", "GIF", "PDF"];
|
||||
const VIDEO_FORMATS = ["MP4", "MOV", "GIF", "M4A"];
|
||||
const AUDIO_FORMATS = ["M4A", "WAV", "MP3"];
|
||||
const PDF_FORMATS = ["PNG", "JPG", "TIFF", "HEIC", "TXT", "MD", "DOCX", "RTF", "ODT"];
|
||||
const DOCUMENT_FORMATS = ["PDF", "DOCX", "MD", "TXT", "HTML", "RTF", "ODT"];
|
||||
|
||||
const FORMAT_ALIASES: Record<string, string> = {
|
||||
jpeg: "jpg",
|
||||
tif: "tiff",
|
||||
heif: "heic",
|
||||
htm: "html",
|
||||
markdown: "md",
|
||||
};
|
||||
|
||||
function canonicalFormat(extension: string) {
|
||||
const normalized = extension.toLowerCase();
|
||||
return FORMAT_ALIASES[normalized] ?? normalized;
|
||||
}
|
||||
|
||||
/** Formats offered for a source file, excluding pointless same-format output. */
|
||||
export function conversionFormats(kind: FileKind, extension: string): string[] {
|
||||
let formats: string[];
|
||||
switch (kind) {
|
||||
case "image":
|
||||
formats = IMAGE_FORMATS;
|
||||
break;
|
||||
case "video":
|
||||
formats = VIDEO_FORMATS;
|
||||
break;
|
||||
case "audio":
|
||||
formats = AUDIO_FORMATS;
|
||||
break;
|
||||
case "pdf":
|
||||
formats = PDF_FORMATS;
|
||||
break;
|
||||
case "document":
|
||||
formats = DOCUMENT_SOURCES.has(extension) ? DOCUMENT_FORMATS : [];
|
||||
break;
|
||||
case "presentation":
|
||||
formats = PRESENTATION_SOURCES.has(extension) ? ["PDF", "MD"] : [];
|
||||
break;
|
||||
case "spreadsheet":
|
||||
formats = SPREADSHEET_SOURCES.has(extension) ? ["PDF", "MD"] : [];
|
||||
break;
|
||||
default:
|
||||
formats = [];
|
||||
}
|
||||
const source = canonicalFormat(extension);
|
||||
return formats.filter((format) => canonicalFormat(format) !== source);
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { hitTestDropTarget, toWindowPoint } from "./dropTargets.ts";
|
||||
|
||||
const button = { left: 100, top: 200, right: 300, bottom: 260 };
|
||||
|
||||
test("macOS drag positions are already webview points", () => {
|
||||
assert.deepEqual(toWindowPoint({ x: 120, y: 220 }, "mac", 2), { x: 120, y: 220 });
|
||||
});
|
||||
|
||||
test("other platforms divide out the device pixel ratio only", () => {
|
||||
// The position is measured from the webview corner, so nothing is subtracted.
|
||||
assert.deepEqual(toWindowPoint({ x: 240, y: 440 }, "other", 2), { x: 120, y: 220 });
|
||||
assert.deepEqual(toWindowPoint({ x: 240, y: 440 }, "other", 0), { x: 240, y: 440 });
|
||||
});
|
||||
|
||||
test("a point on a button selects it", () => {
|
||||
assert.equal(
|
||||
hitTestDropTarget(
|
||||
[
|
||||
["formats", { left: 10, top: 10, right: 90, bottom: 50 }],
|
||||
["tools", button],
|
||||
["ocr", null],
|
||||
],
|
||||
{ x: 200, y: 230 },
|
||||
),
|
||||
"tools",
|
||||
);
|
||||
});
|
||||
|
||||
test("a point on no button selects nothing", () => {
|
||||
assert.equal(
|
||||
hitTestDropTarget(
|
||||
[
|
||||
["formats", { left: 10, top: 10, right: 90, bottom: 50 }],
|
||||
["tools", button],
|
||||
],
|
||||
{ x: 500, y: 500 },
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("a near miss still counts as aiming at the button", () => {
|
||||
assert.equal(hitTestDropTarget([["formats", button]], { x: 95, y: 205 }), "formats");
|
||||
});
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
/**
|
||||
* Geometry for "drop a file on a button to run just that action".
|
||||
*
|
||||
* Kept free of React and Tauri so the mapping rules can be reasoned about (and
|
||||
* checked) on their own.
|
||||
*/
|
||||
|
||||
export type Rect = { left: number; top: number; right: number; bottom: number };
|
||||
|
||||
/** Slack around a button so a near miss still counts as aiming at it. */
|
||||
const SLACK_X = 10;
|
||||
const SLACK_Y = 12;
|
||||
|
||||
/**
|
||||
* Turn a wry drag position into CSS pixels inside the window.
|
||||
*
|
||||
* The two platforms disagree in scale, not in origin: AppKit hands over
|
||||
* `draggingLocation`, which is already webview-relative points, while the
|
||||
* Windows and Linux drag controllers map screen cursor coordinates to client
|
||||
* coordinates, but they remain in physical pixels. Only the second reading
|
||||
* needs the device pixel ratio removed.
|
||||
*/
|
||||
export function toWindowPoint(
|
||||
position: { x: number; y: number },
|
||||
platform: "mac" | "other",
|
||||
scale: number,
|
||||
): { x: number; y: number } | null {
|
||||
if (platform === "mac") return position;
|
||||
const factor = scale || 1;
|
||||
return { x: position.x / factor, y: position.y / factor };
|
||||
}
|
||||
|
||||
/** The button a point sits on, or null when the drop is outside every button. */
|
||||
export function hitTestDropTarget<T extends string>(
|
||||
targets: Array<[T, Rect | null | undefined]>,
|
||||
point: { x: number; y: number },
|
||||
): T | null {
|
||||
for (const [action, rect] of targets) {
|
||||
if (!rect) continue;
|
||||
if (
|
||||
point.x >= rect.left - SLACK_X &&
|
||||
point.x <= rect.right + SLACK_X &&
|
||||
point.y >= rect.top - SLACK_Y &&
|
||||
point.y <= rect.bottom + SLACK_Y
|
||||
) {
|
||||
return action;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -20,11 +20,11 @@ async function getWorker(onProgress?: OcrProgress) {
|
|||
}
|
||||
|
||||
export async function recognizeImage(
|
||||
dataUrl: string,
|
||||
imageSource: string,
|
||||
onProgress?: OcrProgress,
|
||||
): Promise<{ text: string; confidence: number }> {
|
||||
const worker = await getWorker(onProgress);
|
||||
const result = await worker.recognize(dataUrl);
|
||||
const result = await worker.recognize(imageSource);
|
||||
return {
|
||||
text: String(result.data.text || "").trim(),
|
||||
confidence: Number(result.data.confidence || 0),
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ export function basename(path: string): string {
|
|||
|
||||
export const IS_MAC = /Mac/i.test(navigator.platform) || /Mac OS X/i.test(navigator.userAgent);
|
||||
export const OPTION_LABEL = IS_MAC ? "⌥" : "Alt";
|
||||
export const MODIFIER_NAME = IS_MAC ? "Option" : "Ctrl";
|
||||
export const MODIFIER_NAME = IS_MAC ? "Option" : "Alt";
|
||||
|
||||
export function dirname(path: string): string {
|
||||
const normalized = path.replace(/\\/g, "/");
|
||||
|
|
@ -86,6 +86,17 @@ export function normalizeSelection(
|
|||
};
|
||||
}
|
||||
|
||||
/** Rust passes window arguments hex-encoded, so they survive a URL query. */
|
||||
export function decodeHexParam(value: string | null): string | null {
|
||||
if (!value || value.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(value)) return null;
|
||||
try {
|
||||
const bytes = new Uint8Array((value.match(/../g) ?? []).map((pair) => parseInt(pair, 16)));
|
||||
return new TextDecoder().decode(bytes);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RecentItem {
|
||||
path: string;
|
||||
kind: "image" | "video" | "text" | "file";
|
||||
|
|
|
|||
1308
src/styles.css
1308
src/styles.css
File diff suppressed because it is too large
Load Diff
63
src/types.ts
63
src/types.ts
|
|
@ -1,4 +1,4 @@
|
|||
export type View = "main" | "radial" | "capture" | "recorder" | "editor" | "pin";
|
||||
export type View = "main" | "radial" | "capture" | "recorder" | "editor" | "pin" | "share-notice";
|
||||
|
||||
export interface FileInfo {
|
||||
path: string;
|
||||
|
|
@ -69,12 +69,24 @@ export interface AppSettings {
|
|||
recordingDir: string;
|
||||
autoReveal: boolean;
|
||||
dragEnabled: boolean;
|
||||
shareEnabled: boolean;
|
||||
autostart: boolean;
|
||||
/** "" until the user picks a language; the tray follows whatever is stored. */
|
||||
language: string;
|
||||
defaultFileOutputDir: string;
|
||||
defaultScreenshotDir: string;
|
||||
defaultRecordingDir: string;
|
||||
}
|
||||
|
||||
export interface SwitchState {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SwitchUpdate {
|
||||
state: SwitchState;
|
||||
autostart: boolean | null;
|
||||
}
|
||||
|
||||
export interface HotkeyStatus {
|
||||
/** False when another copy owns the global hotkeys. */
|
||||
live: boolean;
|
||||
|
|
@ -89,3 +101,52 @@ export interface WriteCheck {
|
|||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type RuntimeComponentCategory = "documents" | "graphics" | "video" | "capture" | "ocr";
|
||||
|
||||
export interface RuntimeComponent {
|
||||
id: string;
|
||||
name: string;
|
||||
category: RuntimeComponentCategory;
|
||||
role: string;
|
||||
source: "bundled" | "system" | "external";
|
||||
available: boolean;
|
||||
installable: boolean;
|
||||
version?: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface RuntimeInfo {
|
||||
platform: string;
|
||||
architecture: string;
|
||||
osVersion: string;
|
||||
appVersion: string;
|
||||
components: RuntimeComponent[];
|
||||
}
|
||||
|
||||
/** Another Shift copy discovered on the local network. */
|
||||
export interface SharePeer {
|
||||
id: string;
|
||||
name: string;
|
||||
platform: "macos" | "windows" | "linux" | string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
/** An incoming LAN file the user has not answered yet. */
|
||||
export interface ShareOffer {
|
||||
transferId: string;
|
||||
fileName: string;
|
||||
size: number;
|
||||
peerName: string;
|
||||
timeoutSeconds: number;
|
||||
}
|
||||
|
||||
export interface ShareTransfer {
|
||||
transferId: string;
|
||||
fileName: string;
|
||||
peerName: string;
|
||||
sent: number;
|
||||
total: number;
|
||||
state: "sending" | "received" | "error";
|
||||
path?: string | null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,5 +17,6 @@
|
|||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue