release: prepare Shift 0.1.8
parent
d9bb079ec2
commit
df35111326
18
README.md
18
README.md
|
|
@ -217,9 +217,9 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
|
|||
Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. Because it sits outside the bundle, **it survives an update and a reinstall**; the first launch after upgrading also adopts whatever the 0.1 webview had kept in its own store, so a list built before that change is not lost either. The main window's **Recent** card is that library:
|
||||
|
||||
- **Search** once the list grows past a few rows; it filters on the file name.
|
||||
- **Pin** a row to keep it through the capacity limit, a deleted file, and Clear.
|
||||
- **Remove** one row, or **Clear** the library - pinned rows stay.
|
||||
- **Drag a row out** into Finder, a mail composer or a chat window: the row carries a `file://` URL, so the receiving application gets the file rather than a path string. Plain text and Shift's own internal type travel with it for editors and for the ring.
|
||||
- **Favorite** a row to keep it through the capacity limit, a deleted file, and Clear.
|
||||
- **Remove** one row, or **Clear** the library - favorite rows stay.
|
||||
- **Drag a row out** into Finder, a mail composer or a chat window: the row carries a `file://` URL, so the receiving application gets the file rather than a path string. The plain-text path travels with it for editors.
|
||||
- Click a row to open it in the editor; the row's other buttons send, reveal, and pin it to the screen.
|
||||
|
||||
## OCR
|
||||
|
|
@ -292,7 +292,7 @@ Each is overridable in Settings. File actions offer a *collect everything in one
|
|||
|
||||
## Updates
|
||||
|
||||
A new macOS machine installs **`Shift-macOS-universal.dmg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer. Double-click the image, drag `Shift.app` to /Applications, then allow the first launch once (right-click → Open, or 允许 in System Settings → Privacy & Security). In-app updates download the same image without a browser, so they never prompt. Details in `docs/RELEASE.md`.
|
||||
A new macOS machine installs **`Shift-0.1.8-macOS-universal.dmg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer. Double-click the image, drag `Shift.app` to /Applications, then allow the first launch once (right-click → Open, or 允许 in System Settings → Privacy & Security). In-app updates download the same image without a browser, so they never prompt. Details in `docs/RELEASE.md`.
|
||||
|
||||
The update channel is this repository: a `releases` branch holding the installers plus `shift-update.json`, which names each artifact, its size and its SHA256. The feed URL is derived from the git remote at build time - Gitea, GitHub and GitLab forms are known, and `SHIFT_UPDATE_URL` overrides it - so no update service has to be deployed anywhere.
|
||||
|
||||
|
|
@ -363,17 +363,15 @@ cargo test --lib # Rust unit tests, from src-tauri/
|
|||
pnpm tauri build # release bundle
|
||||
```
|
||||
|
||||
Universal macOS build:
|
||||
Versioned release builds:
|
||||
|
||||
```bash
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
pnpm mac:drag-bridge
|
||||
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
||||
RUSTUP_TOOLCHAIN=stable \
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
pnpm mac:release
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
The result is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. To produce the Windows installers and portable ZIPs — x64 and ARM64, both — from macOS, run `scripts/build-windows-release.sh`; full details are in `docs/BUILD_WINDOWS.md`.
|
||||
The release pipeline deliberately emits exactly two installers: `Shift-0.1.8-macOS-universal.dmg` and `Shift-Setup-0.1.8-win-x64.exe`. The macOS app is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. Windows ARM64 uses the x64 installer through the update manifest's compatibility fallback. Full details are in `docs/BUILD_WINDOWS.md` and `docs/RELEASE.md`.
|
||||
|
||||
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio, and Local Network for **Send to a device**. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. A denied Local Network grant is quieter: Shift still sends its beacons and still answers anyone who addresses it directly, but it receives no group traffic, so the device list simply stays empty. Ad-hoc signed builds get a new code identity on every rebuild and macOS keys these grants to that identity, so an upgrade can ask again; distribution with Developer ID keeps them stable.
|
||||
|
||||
|
|
|
|||
|
|
@ -219,7 +219,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
|
|||
- 列表超过几行后出现**搜索**框,按文件名过滤。
|
||||
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。
|
||||
- **移除**单行,或**清空**整个库——收藏项会保留。
|
||||
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径与 Shift 内部类型,供编辑器与圆环使用。
|
||||
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径,供编辑器使用。
|
||||
- 单击某一行在编辑器中打开;行内其余按钮负责发送、在文件夹中显示、以及钉在屏幕上。
|
||||
|
||||
## OCR
|
||||
|
|
@ -294,7 +294,7 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
|
|||
|
||||
## 软件更新
|
||||
|
||||
新的 macOS 机器请安装 **`Shift-macOS-universal.dmg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者。双击挂载镜像,把 `Shift.app` 拖进「应用程序」,然后允许首次启动一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。软件内升级自己下载的是同一个镜像、不经浏览器,因此不会弹窗。详见 `docs/RELEASE.md`。
|
||||
新的 macOS 机器请安装 **`Shift-0.1.8-macOS-universal.dmg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者。双击挂载镜像,把 `Shift.app` 拖进「应用程序」,然后允许首次启动一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。软件内升级自己下载的是同一个镜像、不经浏览器,因此不会弹窗。详见 `docs/RELEASE.md`。
|
||||
|
||||
更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。
|
||||
|
||||
|
|
@ -360,17 +360,15 @@ cargo test --lib # Rust 单元测试,在 src-tauri/ 目录下执行
|
|||
pnpm tauri build # 发布构建
|
||||
```
|
||||
|
||||
macOS 通用(Universal)构建:
|
||||
带版本号的正式构建:
|
||||
|
||||
```bash
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
pnpm mac:drag-bridge
|
||||
PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH" \
|
||||
RUSTUP_TOOLCHAIN=stable \
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
pnpm mac:release
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
产物是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程。若要在 macOS 上生成 Windows 安装版与便携版(x64 与 ARM64 两种架构都会产出),运行 `scripts/build-windows-release.sh`;完整步骤见 `docs/BUILD_WINDOWS.md`。
|
||||
发布链只产出两个安装包:`Shift-0.1.8-macOS-universal.dmg` 与 `Shift-Setup-0.1.8-win-x64.exe`。macOS 是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程;Windows ARM64 通过更新清单的兼容回退使用 x64 安装包。完整步骤见 `docs/BUILD_WINDOWS.md` 与 `docs/RELEASE.md`。
|
||||
|
||||
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」,「发送到设备」需要「本地网络」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。「本地网络」被拒绝时比较安静:Shift 仍会发出广播、也能回应主动找它的实例,但收不到组播,设备列表于是始终为空。ad-hoc 签名每次重新构建都会得到新的代码身份,而 macOS 正是按这个身份记录上述授权,所以升级后可能重新询问;改用 Developer ID 签名即可保持稳定。
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
Shift 0.1.7 - macOS 通用(universal)
|
||||
Shift 0.1.8 - macOS 通用(universal)
|
||||
|
||||
本文件说明 macOS 安装包是怎么打出来的、在其它机器上会遇到什么,以及如何自己校验。
|
||||
完整细节见仓库 docs/RELEASE.md 的「macOS packaging」和 docs/ENGINEERING-NOTES.md
|
||||
|
|
@ -8,7 +8,7 @@ Shift 0.1.7 - macOS 通用(universal)
|
|||
关于这个安装包
|
||||
--------------
|
||||
|
||||
Shift 的 macOS 产物只有一个:Shift-macOS-universal.dmg,通用二进制,Apple silicon 与
|
||||
Shift 的 macOS 产物只有一个:Shift-0.1.8-macOS-universal.dmg,通用二进制,Apple silicon 与
|
||||
Intel 都能用。它既是新机器的首次安装方式,也是软件内升级的载体(更新清单里的 macos
|
||||
键指向它)。清单的键必须是 .dmg,因为软件内升级的交接脚本要用 hdiutil 挂载镜像再
|
||||
取出应用包;早期曾随包发布的 .pkg 在验证过 DMG 可用后就撤掉了,不为它多维护一份
|
||||
|
|
@ -23,7 +23,7 @@ Intel 都能用。它既是新机器的首次安装方式,也是软件内升
|
|||
----------------
|
||||
|
||||
新机器首次安装
|
||||
1. 下载并双击 Shift-macOS-universal.dmg 挂载镜像。
|
||||
1. 下载并双击 Shift-0.1.8-macOS-universal.dmg 挂载镜像。
|
||||
2. 把 Shift.app 拖进「应用程序」(或任何你有权限的位置)。
|
||||
3. 首次启动会被拦:「无法打开,因为来自身份不明的开发者」。点取消,然后
|
||||
右键 Shift.app → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。
|
||||
|
|
@ -70,8 +70,8 @@ macOS 权限
|
|||
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
|
||||
产物在 src-tauri/target/universal-apple-darwin/release/bundle/macos/ 下:Shift.app
|
||||
与 Shift-macOS-universal.dmg。发布流程(清单、签名、推送)见仓库 docs/RELEASE.md。
|
||||
`pnpm mac:release` 会构建、校验并复制为 artifacts/Shift-0.1.8-macOS-universal.dmg。
|
||||
发布流程(清单、签名、推送)见仓库 docs/RELEASE.md。
|
||||
|
||||
若希望更新通道能校验来源,构建时把 ed25519 公钥编进去(发布流程见仓库
|
||||
docs/RELEASE.md 的「Signing the channel」):
|
||||
|
|
@ -96,7 +96,7 @@ docs/RELEASE.md 的「Signing the channel」):
|
|||
|
||||
镜像完整性:
|
||||
|
||||
hdiutil verify Shift-macOS-universal.dmg
|
||||
hdiutil verify Shift-0.1.8-macOS-universal.dmg
|
||||
|
||||
校验后仍打不开的话,请确认不是在压缩包预览窗口里运行的,并按上面的「新机器首次安装」
|
||||
处理首次允许:右键 → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。
|
||||
|
|
|
|||
|
|
@ -35,28 +35,22 @@ 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:
|
||||
`scripts/build-windows-release.sh` cross-compiles the EXE and produces the
|
||||
Windows x64 installer without a Windows host:
|
||||
|
||||
```bash
|
||||
brew install makensis
|
||||
scripts/build-windows-release.sh # both architectures
|
||||
scripts/build-windows-release.sh --arch arm64 # one of them
|
||||
scripts/build-windows-release.sh --skip-build # repackage the EXEs already built
|
||||
scripts/build-windows-release.sh
|
||||
scripts/build-windows-release.sh --skip-build
|
||||
```
|
||||
|
||||
For each architecture asked for it writes
|
||||
`artifacts/Shift-Setup-<version>-win-<arch>.exe` (NSIS, per-user, no administrator
|
||||
rights) and `artifacts/Shift-Portable-<version>-win-<arch>.zip`, then refreshes
|
||||
`artifacts/SHA256SUMS.txt`. Before packaging an EXE the script checks its PE machine
|
||||
field — `0x8664` for x64, `0xAA64` for ARM64 — so a binary built for the wrong target
|
||||
cannot end up in the wrong package, and each installer refuses a machine of the other
|
||||
architecture. `scripts/windows-installer.nsi` installs into
|
||||
It writes `artifacts/Shift-Setup-<version>-win-x64.exe` (NSIS, per-user, no
|
||||
administrator rights), then refreshes `artifacts/SHA256SUMS.txt`. Before packaging
|
||||
the EXE the script checks its PE machine field (`0x8664`) and the installer refuses
|
||||
a non-x64 machine. `scripts/windows-installer.nsi` installs into
|
||||
`%LOCALAPPDATA%\Programs\Shift`, and its uninstaller only removes what the installer
|
||||
wrote.
|
||||
|
||||
The ARM64 build is cross-compiled and packaged from macOS, but it has not been run on
|
||||
Windows-on-ARM hardware, so treat it as unverified on the device.
|
||||
wrote. Windows ARM64 uses this x64 package through the update manifest's `windows`
|
||||
fallback; no ARM64 or portable package is produced.
|
||||
|
||||
## Runtime behavior
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Shift 工程回归台账
|
||||
|
||||
本文件记录 0.1.2 到 0.1.7 之间已经踩过、并且不应再次引入的工程问题,重点覆盖:
|
||||
本文件记录 0.1.2 到 0.1.8 之间已经踩过、并且不应再次引入的工程问题,重点覆盖:
|
||||
|
||||
- Drop / 局域网设备发现
|
||||
- DOCX、Markdown 与图片转换
|
||||
|
|
@ -19,6 +19,7 @@
|
|||
| 0.1.5 | macOS 改为 ad-hoc 签名并只发布通用 DMG,同时增加本地网络用途声明;但升级后出现 Drop 设备列表为空/只短暂闪现的回归。 |
|
||||
| 0.1.6 | 增加按网卡定向广播,改善过滤组播的网络,但用户实测仍只能短暂看到设备。 |
|
||||
| 0.1.7 | 增加单播扫描、普通信标回应、15 秒过期和 Windows 错误处理;用户实测 Mac 与 Windows 终端的 Drop 发现恢复正常。 |
|
||||
| 0.1.8 | 最近文件改为收藏并移除拖回主操作按钮的交互;Windows 增加单实例保护;macOS DOCX→PDF 改用 Quick Look 源,保留页眉、页脚与装订版式。 |
|
||||
|
||||
历史提交可以这样定位:
|
||||
|
||||
|
|
@ -137,32 +138,38 @@ cargo test share:: -- --ignored --nocapture
|
|||
| 输入 → 输出 | 当前实现 | 关键点 |
|
||||
| --- | --- | --- |
|
||||
| 纯图片 DOCX → PDF | `office::document_page_images` 按文档顺序抽取页面图片,再由 `pdf::images_to_pdf_with_progress` 生成 PDF | 保留页数和原始图片内容;这是扫描件路径,不经过 AppKit 文本排版。 |
|
||||
| 含文字和图片 DOCX → PDF | 先用 Pandoc `docx → html5`,通过 `--extract-media` 抽取图片到临时目录,再交给 `native/macos/doc-render.swift` | AppKit 的 OOXML 读取器会静默丢弃内嵌图片,所以这类 DOCX 不能直接交给它。 |
|
||||
| Markdown → PDF | 先由 Pandoc(可用时)或内置 `markdown::to_html` 转成 HTML,再交给 AppKit 渲染器;HTML 的 base URL 指向 Markdown 源目录 | 相对图片路径依赖源目录,不能用临时 HTML 所在目录。 |
|
||||
| 普通 DOCX → PDF | 先用 `/usr/bin/qlmanage -p` 生成系统的 Quick Look `Preview.html`,再由 `native/macos/doc-render.swift` 用 WebKit 渲染并按 A4 切片 | AppKit 的 OOXML 读取器只保留正文;把 Quick Look HTML 再转成 attributed string 还会重排表格并制造空白页。`qlmanage` 有 30 秒超时,且必须确认 `Preview.html` 存在。 |
|
||||
| Quick Look 不可用且含图 DOCX → PDF | 用 Pandoc `docx → html5`,通过 `--extract-media` 抽取图片到临时目录,再交给 `doc-render` | 保留图片的降级路径;Quick Look 失败或超时后才进入。 |
|
||||
| Markdown → PDF | 先由 Pandoc(可用时)或内置 `markdown::to_html` 转成 HTML,再交给 WebKit 渲染器;HTML 的 base URL 指向 Markdown 源目录 | 相对图片路径依赖源目录,不能用临时 HTML 所在目录。 |
|
||||
| Markdown → DOCX / RTF | Pandoc,并传 `--resource-path <源目录>` | Pandoc 的工作目录不是文档目录;缺少该参数会把相对图片替换成 alt 文本。 |
|
||||
| Markdown → HTML | Pandoc,并传 `--resource-path <源目录>` 和 `--self-contained` | 输出必须是可单独移动的单文件,不能引用从未生成的 `media/` 目录。 |
|
||||
| 含图 DOCX → HTML | Pandoc 加 `--self-contained` | 图片以内嵌 data URI 写入 HTML。 |
|
||||
| 任意含宽图的文档 → PDF | `doc-render.swift` 的 `fitAttachments` 把超宽附件按正文栏宽度等比缩放 | 不重采样像素,只修正排版请求的尺寸,避免截图被裁成碎片。 |
|
||||
| 任意含宽图的文档 → PDF | HTML 在 WebKit 测量前把超宽 `<img>` 等比缩到页面宽度;非 HTML 文档仍由 `fitAttachments` 调整 attachment bounds | 不重采样像素,只修正排版请求的尺寸,避免截图被裁成碎片。 |
|
||||
|
||||
### 不能随意改掉的约束
|
||||
|
||||
1. **不要把含图 DOCX 直接交给 AppKit OOXML 读取器。** 它会返回只有文字、没有附件的
|
||||
attributed string;问题发生在解析阶段,调页边距或打印参数无法找回图片。
|
||||
2. **纯图片 DOCX 的页面抽取要排在通用渲染之前。** 它决定扫描件的真实页数和页面顺序。
|
||||
3. **DOCX→HTML 后必须把 `--extract-media` 的临时目录作为 HTML base directory。**
|
||||
1. **普通 DOCX 不能直接交给 AppKit OOXML 读取器。** 它只保留正文,页眉页脚会消失;
|
||||
含图文档还会返回只有文字、没有附件的 attributed string。必须先走 Quick Look,
|
||||
失败后才允许回退。
|
||||
2. **HTML 必须交给 WebKit,不能再转成 NSAttributedString。** 后者会重新排版 Quick
|
||||
Look 的定位内容,把原本同页的页脚推到新页,并把 7 页内容拉成 9 页。
|
||||
3. **纯图片 DOCX 的页面抽取要排在通用渲染之前。** 它决定扫描件的真实页数和页面顺序。
|
||||
4. **DOCX→HTML 后必须把 `--extract-media` 的临时目录作为 HTML base directory。**
|
||||
Pandoc 会把图片写成相对路径;base 指向源 DOCX 目录会找不到已抽取媒体。
|
||||
4. **Markdown→PDF 的 HTML base URL 始终是源 Markdown 目录。** 即使 HTML 写在临时目录,
|
||||
5. **Markdown→PDF 的 HTML base URL 始终是源 Markdown 目录。** 即使 HTML 写在临时目录,
|
||||
也不能改用临时目录。
|
||||
5. **Pandoc 转 DOCX/RTF/HTML 必须保留 `--resource-path`。** 这是相对图片丢失问题的
|
||||
6. **Pandoc 转 DOCX/RTF/HTML 必须保留 `--resource-path`。** 这是相对图片丢失问题的
|
||||
根因修复,不应为了简化命令删掉。
|
||||
6. **HTML 输出必须保留 `--self-contained`。** 否则用户拿到的是一个引用不存在媒体目录
|
||||
7. **HTML 输出必须保留 `--self-contained`。** 否则用户拿到的是一个引用不存在媒体目录
|
||||
的 HTML 文件。
|
||||
7. **宽图适配在 `doc-render.swift` 中完成。** 仅修改 CSS 宽度不会影响 AppKit 对这种
|
||||
HTML `<img>` 单元格的实际 attachment bounds。
|
||||
8. **无 Pandoc 时保留 macOS 的降级路径。** 带图 DOCX 会退回旧的文本渲染,而不是让
|
||||
8. **宽图适配在 `doc-render.swift` 中完成。** HTML 必须在测量前缩放宽图;非 HTML
|
||||
文档的 AppKit `<img>` 单元格不会服从 CSS width,仍需调整 attachment bounds。
|
||||
9. **无 Pandoc 时保留 macOS 的降级路径。** 带图 DOCX 会退回旧的文本渲染,而不是让
|
||||
整个转换直接失败;修改时要明确产品选择,不能无意打破降级。
|
||||
9. **Swift 渲染器改动后重新运行 `pnpm mac:drag-bridge`。** 只改源码不重编伴生进程,
|
||||
10. **Swift 渲染器改动后重新运行 `pnpm mac:drag-bridge`。** 只改源码不重编伴生进程,
|
||||
打出的 DMG 不会包含修复。
|
||||
11. **Quick Look 临时目录必须在所有成功和失败路径清理。** 输出先写到临时目录,确认
|
||||
PDF 有效后再改名;不能把半成品留在用户的输出目录。
|
||||
|
||||
### 回归测试
|
||||
|
||||
|
|
@ -171,9 +178,19 @@ cargo test share:: -- --ignored --nocapture
|
|||
- `renders_image_only_docx_pages_to_pdf`
|
||||
- `keeps_pictures_when_rendering_a_text_docx_to_pdf`
|
||||
- `fits_a_wide_picture_onto_the_page`
|
||||
- `keeps_docx_headers_and_footers_when_converting_to_pdf`
|
||||
- `image_bearing_docx_to_html_embeds_images`
|
||||
- `keeps_markdown_images_when_converting_to_word`
|
||||
|
||||
## 升级后的单实例
|
||||
|
||||
Windows 安装器重启应用时可能留下旧进程,再启动新进程就会有两个托盘实例和两套窗口。
|
||||
`tauri-plugin-single-instance` 必须在 `tauri::Builder` 中**最先注册**:第二个进程在
|
||||
其余插件和窗口初始化前就把参数交给第一实例并退出,第一实例收到回调后显示主窗口。
|
||||
|
||||
macOS 的 `hotkeys::acquire_instance` 文件锁仍保留为热键所有权的额外保护,不能因为加入
|
||||
单实例插件而删除;但它不是 Windows 的解决方案,非 Unix 分支本身不会持有跨进程锁。
|
||||
|
||||
其中 `keeps_markdown_images_when_converting_to_word` 覆盖 DOCX 和 RTF;
|
||||
`image_bearing_docx_to_html_embeds_images` 检查 HTML 中的图片是 data URI 而不是
|
||||
`media/` 引用。很多用例在缺少 Pandoc 时跳过,因此本机安装 Pandoc 后才能得到完整结果。
|
||||
|
|
@ -202,13 +219,13 @@ cargo test share:: -- --ignored --nocapture
|
|||
Shift 的 macOS 产物只有:
|
||||
|
||||
```text
|
||||
Shift-macOS-universal.dmg
|
||||
Shift-<版本>-macOS-universal.dmg
|
||||
```
|
||||
|
||||
它是 Apple silicon 与 Intel 通用的应用包,同时用于首次安装和软件内升级。更新清单的
|
||||
`macos` 键必须指向这个 DMG,因为软件内升级脚本会用 `hdiutil` 挂载它再取出应用。
|
||||
不再发布 `.pkg`;`scripts/macos-pkg.sh` 可以保留作历史工具,但不能进入正式发布目录或
|
||||
更新清单。
|
||||
不再发布 `.pkg`;旧的 `scripts/macos-pkg.sh` 已从仓库删除,任何 `.pkg` 都不能进入
|
||||
正式发布目录或更新清单。
|
||||
|
||||
当前签名配置是:
|
||||
|
||||
|
|
@ -272,6 +289,62 @@ Mac 后,证书无法链到受信任根,下载的应用会被系统报告为
|
|||
该证书,不能把“已公证”写入发布说明。
|
||||
- 发布前不能只看构建机上的 `spctl` 结果;跨机器安装行为和系统提示类型才是有效证据。
|
||||
|
||||
## 截图、录制与圆环的键盘焦点
|
||||
|
||||
### 症状与真实原因
|
||||
|
||||
区域截图、区域录制时按 `ESC` 无法取消,拖动文件后出现的圆环按 `ESC` 也无反应。前端确实
|
||||
监听了 `keydown`,但事件根本没有到达页面。
|
||||
|
||||
在运行中的 Shift 上用 `lldb` 取证可以看到:
|
||||
|
||||
```text
|
||||
keyWindow = <TaoWindow "Shift Capture"> isKeyWindow = YES
|
||||
firstResponder = <TaoView> ← 页面在 contentView 的 subview 里,不在这里
|
||||
contentView = <TaoView> subviews = [<WryWebView>]
|
||||
```
|
||||
|
||||
窗口是 key window,但 AppKit 的键盘事件投递给的是窗口的 first responder,而 first
|
||||
responder 停在 tao 自己的 `TaoView` 上,所以页面收不到任何按键。链路上有两个成因:
|
||||
|
||||
- `WebviewWindow::set_focus()` 只做 `makeKeyAndOrderFront` 加激活应用
|
||||
(tao `platform_impl/macos/window.rs` 的 `set_focus`),不会动 first responder。
|
||||
- wry 在创建 webview 时调用过一次 `makeFirstResponder(webview)`,但之后每次
|
||||
`set_simple_fullscreen` 都会经 `toggle_style_mask` 再调
|
||||
`makeFirstResponder(ns_view)`(tao `util/mod.rs`)把它抢回去;窗口重新显示同样会丢。
|
||||
|
||||
因此**只要窗口被显示过一次,就必须再显式把键盘交给页面**。等价验证:在真实进程里执行
|
||||
`makeFirstResponder(WryWebView)` 之后,同一个 `ESC` 立刻被页面收到。
|
||||
|
||||
### 不能随意改掉的约束
|
||||
|
||||
| 约束 | 原因 |
|
||||
| --- | --- |
|
||||
| 显示 overlay / 圆环后必须调用 `crate::focus_page` | 只有 `Webview::set_focus`(`makeFirstResponder`)能让页面收到 `ESC`/`Enter`;`WebviewWindow::set_focus` 不够。 |
|
||||
| 采集前记住哪些 Shift 窗口是可见的,结束时按名单恢复 | 之前无条件 `show` 主窗口:面板开着会被截图吃掉,面板本来关着又会被凭空打开。 |
|
||||
| 录制期间不能恢复面板,`recording::stop` 才恢复 | 恢复出来的窗口会出现在被录制的区域里。 |
|
||||
| `restore_windows` 用 recorder HUD 判断是否在录制,不能去锁 `state.recording` | `recording::stop` 全程持有该 Mutex,从这条路再锁一次会自死锁。 |
|
||||
| 已有 overlay 或正在录制时,新一轮采集不得覆盖待恢复名单 | 否则后一次(面板不可见)会把“面板开着”的记录擦掉。 |
|
||||
|
||||
### 回归测试
|
||||
|
||||
`src-tauri/src/lib.rs` 中的源码断言守住调用点:
|
||||
|
||||
```bash
|
||||
cd src-tauri
|
||||
cargo test --lib capture
|
||||
```
|
||||
|
||||
键盘投递本身只能实测,最小矩阵(每步都要看窗口是否真的消失/回来):
|
||||
|
||||
1. 面板开着 → `Alt+Shift+2` → 直接按 `ESC` → overlay 消失且面板回来。
|
||||
2. 面板开着 → `Alt+Shift+3` → 直接按 `ESC` → 同上。
|
||||
3. 面板关着 → `Alt+Shift+2` → `ESC` → 不要凭空出现面板。
|
||||
4. 面板开着 → 选区录制 → 录制中面板保持隐藏 → 停止后面板回来,`.mov` 有效。
|
||||
5. 录制中再截一张图 → `ESC` 只关 overlay,录制与 HUD 不受影响。
|
||||
6. 圆环(拖文件到面板,或「文件转换」选文件后)→ `ESC` 收起圆环。
|
||||
7. `Enter` 仍能确认选区并保存截图。
|
||||
|
||||
## 修改这些路径时的统一回归命令
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ An orphan branch named `releases` holds exactly one release:
|
|||
releases/
|
||||
├── shift-update.json
|
||||
├── shift-update.sig
|
||||
├── Shift-macOS-universal.dmg
|
||||
└── Shift-Setup-0.1.1-win-x64.exe
|
||||
├── Shift-0.1.8-macOS-universal.dmg
|
||||
└── Shift-Setup-0.1.8-win-x64.exe
|
||||
```
|
||||
|
||||
`shift-update.json` names the version and, per platform, the artifact file, its size in
|
||||
|
|
@ -22,12 +22,12 @@ bytes and its SHA256:
|
|||
```json
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.8",
|
||||
"date": "2026-10-26",
|
||||
"notes": "",
|
||||
"artifacts": {
|
||||
"macos": { "file": "Shift-macOS-universal.dmg", "sha256": "57fc…", "size": 55479751 },
|
||||
"windows": { "file": "Shift-Setup-0.1.1-win-x64.exe", "sha256": "0255…", "size": 24545040 }
|
||||
"macos": { "file": "Shift-0.1.8-macOS-universal.dmg", "sha256": "…", "size": 0 },
|
||||
"windows": { "file": "Shift-Setup-0.1.8-win-x64.exe", "sha256": "…", "size": 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -41,13 +41,9 @@ not a code limit, and it decides what the channel may contain:
|
|||
| --- | --- | --- |
|
||||
| `macos` | yes | One universal bundle, Apple silicon and Intel, shipped as a DMG. Verified on a fresh machine by dragging it to /Applications — see "macOS packaging" |
|
||||
| `windows` | yes | x64, which is also what an ARM machine falls back to |
|
||||
| `windows-arm64` | no | Buildable — `build-windows-release.sh --arch arm64` still works — just not published |
|
||||
| `windows-arm64` | no | Runtime compatibility only: Windows on ARM installs the x64 package through `windows` |
|
||||
| `linux` | no | Build target, not a product; see below |
|
||||
|
||||
Publishing an ARM64 Windows build later needs no code change: the ladder already prefers
|
||||
`windows-arm64` and falls back to `windows`, so adding the file to `artifacts/` and
|
||||
re-publishing is enough.
|
||||
|
||||
The incident history, failure signatures and non-negotiable implementation constraints
|
||||
behind the current Drop, conversion and macOS packaging behaviour are recorded in
|
||||
[`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md). Read the relevant section before changing
|
||||
|
|
@ -104,7 +100,7 @@ project wants, and no release is worse off for losing a certificate no other Mac
|
|||
Reusing that identity again would mean installing it **and trusting it** on every machine,
|
||||
which is not something to ask of a user.
|
||||
|
||||
So: ad-hoc, and one container. The channel ships **`Shift-macOS-universal.dmg`** and nothing
|
||||
So: ad-hoc, and one container. The channel ships **`Shift-<version>-macOS-universal.dmg`** and nothing
|
||||
else on macOS — the earlier `.pkg` companion was dropped after the DMG was verified to work
|
||||
on a fresh machine, and one file per platform is less to keep straight.
|
||||
|
||||
|
|
@ -117,20 +113,19 @@ The `macos` manifest key is a DMG for the same reason: the in-app handoff mounts
|
|||
so pointing the key at a package would break every in-app update. That was the one real
|
||||
constraint the container had to satisfy, and a DMG satisfies it.
|
||||
|
||||
`scripts/macos-pkg.sh` — which staged the bundle under an `/Applications` root and ran
|
||||
`pkgbuild` — is kept in the tree but is no longer part of a release: it built a container
|
||||
with no manifest key, and the DMG covers the first install anyway.
|
||||
The retired `.pkg` packaging script has been removed. The DMG is the only macOS
|
||||
container in the release pipeline.
|
||||
|
||||
### macOS release gate
|
||||
|
||||
Every macOS release must pass all of these before it goes into `artifacts/`:
|
||||
|
||||
1. Rebuild the universal Swift sidecars with `pnpm mac:drag-bridge`, then build with
|
||||
`pnpm tauri build --target universal-apple-darwin --bundles app,dmg`.
|
||||
1. Run `pnpm mac:release`. It rebuilds the universal Swift sidecars, builds the app
|
||||
and DMG, verifies both, and copies the result to the versioned release name.
|
||||
2. Run `codesign --verify --deep --strict` on `Shift.app`, and confirm
|
||||
`codesign -dv --verbose=2` reports `Signature=adhoc`. A local certificate name here is
|
||||
a release blocker, not a stronger signature.
|
||||
3. Run `hdiutil verify Shift-macOS-universal.dmg` and verify `SHA256SUMS.txt` after copying
|
||||
3. Run `hdiutil verify artifacts/Shift-<version>-macOS-universal.dmg` and verify `SHA256SUMS.txt` after copying
|
||||
the final artifact into `artifacts/`.
|
||||
4. Confirm the release contains no `.pkg`, and that the manifest's `macos` entry points at
|
||||
the DMG. The in-app helper mounts that exact container with `hdiutil`.
|
||||
|
|
@ -159,7 +154,8 @@ UI to say why.
|
|||
## Publishing
|
||||
|
||||
```bash
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
pnpm mac:release
|
||||
scripts/build-windows-release.sh
|
||||
printf 'Fixes the ring on external displays.\n' > /tmp/notes.md
|
||||
scripts/publish-release.sh --notes /tmp/notes.md # hash, commit, push
|
||||
```
|
||||
|
|
@ -178,13 +174,12 @@ same Python pass that walks the files produces both.
|
|||
| `--no-push` | Commit locally on `releases` but leave the remote alone |
|
||||
| `--branch NAME` | Publish to another channel instead of `releases` |
|
||||
|
||||
Recognised installers: `Shift-macOS-universal.dmg` (macOS), `Shift-Setup-<version>-win-x64.exe`
|
||||
and `Shift-Setup-<version>-win-arm64.exe` (Windows, keys `windows` and `windows-arm64`),
|
||||
`*.AppImage` / `*.deb` (Linux). Other files in `artifacts/` — the portable ZIPs,
|
||||
`SHA256SUMS.txt`, the `README-Windows-<arch>.txt` notes and `README-macOS-universal.txt`,
|
||||
the packaging note explaining the ad-hoc signature and how to verify a download — travel
|
||||
with the branch and are downloadable from it, but are not offered as installers by the
|
||||
manifest. Dotfiles and an old manifest are skipped.
|
||||
Recognised installers are exactly `Shift-<version>-macOS-universal.dmg` (macOS) and
|
||||
`Shift-Setup-<version>-win-x64.exe` (Windows). Publishing fails if either is missing,
|
||||
or if any other `.dmg`, `.exe`, `.msi`, `.pkg`, `.zip`, AppImage or deb remains in
|
||||
`artifacts/`. `SHA256SUMS.txt`, the two platform notes and `README-macOS-universal.txt`
|
||||
travel with the branch as supporting files, never as installers. Dotfiles and an old
|
||||
manifest are skipped.
|
||||
|
||||
`README-macOS-universal.txt` is tracked in the repository as well as pushed to the channel,
|
||||
so the scheme is documented where a contributor reads it and not only next to a build
|
||||
|
|
@ -192,15 +187,12 @@ product. Every claim in it was checked against the shipped artifacts: the bundle
|
|||
published DMG is `Signature=adhoc`, and `shasum -a 256 -c SHA256SUMS.txt` passes on the
|
||||
published set.
|
||||
|
||||
Both Windows architectures come from one command, which cross-compiles each target,
|
||||
checks the PE machine field of the binary it just built (`0x8664` for x64, `0xAA64` for
|
||||
ARM64) so a wrong `--target` cannot ship an x64 EXE inside an arm64 package, and gates the
|
||||
installer to the matching machine:
|
||||
The Windows command cross-compiles one target, checks the PE machine field (`0x8664`)
|
||||
and gates the installer to x64:
|
||||
|
||||
```bash
|
||||
scripts/build-windows-release.sh # both architectures
|
||||
scripts/build-windows-release.sh --arch arm64 # one of them
|
||||
scripts/build-windows-release.sh --skip-build # repackage existing EXEs
|
||||
scripts/build-windows-release.sh
|
||||
scripts/build-windows-release.sh --skip-build
|
||||
```
|
||||
|
||||
## Signing the channel
|
||||
|
|
@ -213,8 +205,8 @@ scripts/release-key.py keygen ~/.config/shift-release/release.ed25519
|
|||
# -> prints the hex public key to bake into the build
|
||||
|
||||
export SHIFT_RELEASE_KEY=~/.config/shift-release/release.ed25519
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg # macOS
|
||||
scripts/build-windows-release.sh # both Windows architectures
|
||||
pnpm mac:release # macOS universal DMG
|
||||
scripts/build-windows-release.sh # Windows x64 installer
|
||||
scripts/publish-release.sh --key "$SHIFT_RELEASE_KEY"
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -39,8 +39,8 @@ names what is still missing.
|
|||
- Custom radial item ordering with per-file-type presets: the wedge catalogue lives in
|
||||
`src/lib/radialOrder.ts`, orders are stored per kind and ring in `settings.json`. The
|
||||
Settings tab that edited them was removed in 0.1.1, so orders now come from
|
||||
`settings.json` alone; `src/components/RadialOrderPanel.tsx` is kept for when an editor
|
||||
comes back.
|
||||
`settings.json` alone; the retired editor was removed in 0.1.8 and only the read path is
|
||||
retained for compatibility with existing user settings.
|
||||
- Undo history in the annotation canvas (annotations pop first, then image-level
|
||||
operations, matching the README table) and conflict-safe output naming: `unique_output`
|
||||
appends a numeric suffix instead of overwriting. There is no undo for a completed file
|
||||
|
|
@ -66,16 +66,12 @@ names what is still missing.
|
|||
repository has no second-machine fixture. Client-isolated Wi-Fi remains outside the app's
|
||||
control, and Windows still permits only one listener per machine. The exact invariants
|
||||
and manual matrix are in `docs/ENGINEERING-NOTES.md`.
|
||||
- Windows ARM64: `scripts/build-windows-release.sh` builds both architectures by
|
||||
default, checks each binary's PE machine field (`0x8664` / `0xAA64`) before packaging
|
||||
it, and gates each NSIS installer to the matching machine. The update manifest gained a
|
||||
`windows-arm64` key; an ARM build tries it first and falls back to `windows`, which
|
||||
Windows on ARM runs under emulation, so a channel that predates the ARM build still
|
||||
serves it. Verified by cross-building, packaging and publishing all of that from macOS;
|
||||
running the installer on real Windows-on-ARM hardware has not happened. Since 0.1.1 the
|
||||
shipped targets are macOS and Windows x64 only, so ARM64 stays a buildable architecture
|
||||
(`--arch arm64` still works, `windows-arm64` still falls back to `windows`) that nothing
|
||||
is published for.
|
||||
- Windows ARM64: the release pipeline ships only the x64 NSIS installer, checks its
|
||||
PE machine field (`0x8664`), and gates the installer to x64. An ARM machine tries the
|
||||
optional `windows-arm64` manifest key first and falls back to `windows`, which Windows
|
||||
on ARM runs through emulation. Verified by cross-building, packaging and publishing
|
||||
from macOS; running the installer on real Windows-on-ARM hardware has not happened.
|
||||
Since 0.1.1 the shipped installers are macOS universal and Windows x64 only.
|
||||
- Linux is supported as a build and run target but is **not a shipped product**: no deb or
|
||||
AppImage is published, so the update channel has no `linux` key and the platform table
|
||||
reports "no artifact" rather than a failure. `scripts/linux/Dockerfile` and the `linux` CI
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import AppKit
|
|||
import Foundation
|
||||
import PDFKit
|
||||
import Vision
|
||||
import WebKit
|
||||
|
||||
func fail(_ message: String) -> Never {
|
||||
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
|
||||
|
|
@ -121,8 +122,8 @@ func writeWordDocument(from pdf: URL, to output: URL) throws {
|
|||
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]")
|
||||
guard (3...5).contains(CommandLine.arguments.count) else {
|
||||
fail("usage: doc-render <input> <output> [html-base-dir] [--webkit]")
|
||||
}
|
||||
|
||||
let input = URL(fileURLWithPath: CommandLine.arguments[1])
|
||||
|
|
@ -168,13 +169,26 @@ var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [:]
|
|||
if let documentType {
|
||||
options[.documentType] = documentType
|
||||
}
|
||||
|
||||
if documentType == .html {
|
||||
let baseDirectory = CommandLine.arguments.count == 4
|
||||
? URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
|
||||
: CommandLine.arguments.count == 5
|
||||
? URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
|
||||
: input.deletingLastPathComponent()
|
||||
options[.baseURL] = baseDirectory
|
||||
}
|
||||
|
||||
if documentType == .html,
|
||||
CommandLine.arguments.count == 5,
|
||||
CommandLine.arguments[4] == "--webkit" {
|
||||
let baseDirectory = URL(fileURLWithPath: CommandLine.arguments[3], isDirectory: true)
|
||||
let renderer = HTMLRenderer(input: input, output: output, baseDirectory: baseDirectory)
|
||||
renderer.run()
|
||||
app.run()
|
||||
exit(0)
|
||||
}
|
||||
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: input)
|
||||
|
|
@ -228,6 +242,172 @@ func fitAttachments(
|
|||
return mutable
|
||||
}
|
||||
|
||||
/// Writes the tall PDF WebKit produces from the page as A4-sized slices.
|
||||
///
|
||||
/// `createPDF` keeps the HTML layout as one continuous page. Printing the web
|
||||
/// view directly can loop indefinitely on documents with positioned elements,
|
||||
/// so draw the single page into clipped A4 pages instead.
|
||||
func writePaginatedPDF(_ data: Data, to output: URL) {
|
||||
let pageSize = CGSize(width: 595.2, height: 841.8)
|
||||
guard let provider = CGDataProvider(data: data as CFData),
|
||||
let document = CGPDFDocument(provider),
|
||||
let source = document.page(at: 1) else {
|
||||
fail("could not read the rendered web page")
|
||||
}
|
||||
let sourceBounds = source.getBoxRect(.mediaBox)
|
||||
let height = max(1, sourceBounds.height)
|
||||
let pageCount = max(1, Int(ceil(height / pageSize.height)))
|
||||
var mediaBox = CGRect(origin: .zero, size: pageSize)
|
||||
guard let context = CGContext(output as CFURL, mediaBox: &mediaBox, nil) else {
|
||||
fail("could not create the PDF")
|
||||
}
|
||||
for index in 0..<pageCount {
|
||||
context.beginPDFPage(nil)
|
||||
context.saveGState()
|
||||
context.clip(to: mediaBox)
|
||||
let offset = max(0, height - CGFloat(index + 1) * pageSize.height)
|
||||
let remaining = max(0, height - CGFloat(index) * pageSize.height)
|
||||
// Full slices move up through the tall page. The final short slice is
|
||||
// top-aligned so the trailing whitespace sits below the content.
|
||||
let translationY = remaining < pageSize.height
|
||||
? pageSize.height - remaining
|
||||
: -offset
|
||||
context.translateBy(x: 0, y: translationY)
|
||||
context.drawPDFPage(source)
|
||||
context.restoreGState()
|
||||
context.endPDFPage()
|
||||
}
|
||||
context.closePDF()
|
||||
}
|
||||
|
||||
/// Renders HTML with WebKit instead of flattening it into an attributed
|
||||
/// string. Quick Look supplies Word page furniture and positioned tables as
|
||||
/// HTML; AppKit's text conversion reflows that content, which changes the page
|
||||
/// count and can move a footer onto a page of its own.
|
||||
final class HTMLRenderer: NSObject, WKNavigationDelegate {
|
||||
private let input: URL
|
||||
private let baseDirectory: URL
|
||||
private let output: URL
|
||||
private let webView: WKWebView
|
||||
private var finished = false
|
||||
|
||||
init(input: URL, output: URL, baseDirectory: URL) {
|
||||
self.input = input
|
||||
self.output = output
|
||||
self.baseDirectory = baseDirectory
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
|
||||
self.webView = WKWebView(
|
||||
frame: NSRect(x: 0, y: 0, width: 595.2, height: 841.8),
|
||||
configuration: configuration
|
||||
)
|
||||
super.init()
|
||||
webView.navigationDelegate = self
|
||||
}
|
||||
|
||||
func run() {
|
||||
webView.loadFileURL(input, allowingReadAccessTo: baseDirectory)
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
|
||||
guard !self.finished else { return }
|
||||
self.finished = true
|
||||
fail("could not render HTML before the 30 second deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
guard !finished else { return }
|
||||
webView.evaluateJavaScript(
|
||||
"""
|
||||
(() => {
|
||||
const pageWidth = document.documentElement.clientWidth;
|
||||
for (const image of document.images) {
|
||||
if (image.getBoundingClientRect().width > pageWidth) {
|
||||
image.style.width = `${pageWidth}px`;
|
||||
image.style.height = "auto";
|
||||
image.style.maxWidth = "100%";
|
||||
}
|
||||
}
|
||||
let contentBottom = 0;
|
||||
const range = document.createRange();
|
||||
const walker = document.createTreeWalker(
|
||||
document.body,
|
||||
NodeFilter.SHOW_TEXT
|
||||
);
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
if (!node.textContent.trim()) continue;
|
||||
range.selectNodeContents(node);
|
||||
const rect = range.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
contentBottom = Math.max(
|
||||
contentBottom,
|
||||
rect.bottom + window.scrollY
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const element of document.querySelectorAll(
|
||||
"img, svg, canvas, table, hr"
|
||||
)) {
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
contentBottom = Math.max(
|
||||
contentBottom,
|
||||
rect.bottom + window.scrollY
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
width: document.documentElement.scrollWidth,
|
||||
height: Math.max(1, Math.ceil(contentBottom))
|
||||
};
|
||||
})()
|
||||
"""
|
||||
) { value, error in
|
||||
guard !self.finished else { return }
|
||||
self.finished = true
|
||||
guard error == nil,
|
||||
let size = value as? [String: Any],
|
||||
let width = (size["width"] as? NSNumber)?.doubleValue,
|
||||
let height = (size["height"] as? NSNumber)?.doubleValue,
|
||||
width > 0,
|
||||
height > 0 else {
|
||||
fail("could not measure the rendered HTML")
|
||||
}
|
||||
let configuration = WKPDFConfiguration()
|
||||
configuration.rect = CGRect(x: 0, y: 0, width: width, height: height)
|
||||
webView.createPDF(configuration: configuration) { result in
|
||||
switch result {
|
||||
case .success(let data):
|
||||
writePaginatedPDF(data, to: self.output)
|
||||
NSApp.terminate(nil)
|
||||
case .failure(let error):
|
||||
fail("could not print HTML: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
didFail navigation: WKNavigation!,
|
||||
withError error: Error
|
||||
) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
fail("could not load HTML: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
didFailProvisionalNavigation navigation: WKNavigation!,
|
||||
withError error: Error
|
||||
) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
fail("could not load HTML: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
let printInfo = NSPrintInfo.shared.copy() as! NSPrintInfo
|
||||
printInfo.paperSize = NSSize(width: 595.2, height: 841.8)
|
||||
printInfo.topMargin = 42
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "shift",
|
||||
"private": true,
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"prepare:ocr": "bash scripts/prepare-ocr-assets.sh",
|
||||
|
|
@ -13,7 +13,8 @@
|
|||
"tauri": "tauri",
|
||||
"check": "tsc --noEmit",
|
||||
"test": "node --experimental-strip-types --test src/lib/*.test.ts",
|
||||
"mac:drag-bridge": "bash scripts/build-macos-drag-bridge.sh"
|
||||
"mac:drag-bridge": "bash scripts/build-macos-drag-bridge.sh",
|
||||
"mac:release": "bash scripts/build-macos-release.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ for arch in arm64 x86_64; do
|
|||
-framework AppKit \
|
||||
-framework PDFKit \
|
||||
-framework Vision \
|
||||
-framework WebKit \
|
||||
"$root_dir/native/macos/doc-render.swift" \
|
||||
-o "$tmp_dir/doc-render-$arch"
|
||||
done
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
#!/bin/bash
|
||||
# Build the universal macOS DMG and copy it to the versioned release name.
|
||||
#
|
||||
# scripts/build-macos-release.sh [--skip-build]
|
||||
#
|
||||
# Produces artifacts/Shift-<version>-macOS-universal.dmg.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# The Homebrew `cargo` on this host uses the non-rustup "system" toolchain, which
|
||||
# cannot build the second slice of a universal binary.
|
||||
export PATH="$HOME/.cargo/bin:$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
|
||||
export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
|
||||
|
||||
SKIP_BUILD=0
|
||||
usage() { echo "usage: $0 [--skip-build]" >&2 && exit 2; }
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1 ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
BUNDLE_DIR="src-tauri/target/universal-apple-darwin/release/bundle"
|
||||
APP="$BUNDLE_DIR/macos/Shift.app"
|
||||
OUTPUT="artifacts/Shift-$VERSION-macOS-universal.dmg"
|
||||
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
pnpm mac:drag-bridge
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
fi
|
||||
|
||||
test -d "$APP"
|
||||
DMG=$(find "$BUNDLE_DIR/dmg" -maxdepth 1 -type f -name '*.dmg' -print -quit)
|
||||
test -n "$DMG"
|
||||
|
||||
codesign --verify --deep --strict "$APP"
|
||||
hdiutil verify "$DMG" >/dev/null
|
||||
mkdir -p artifacts
|
||||
cp -f "$DMG" "$OUTPUT"
|
||||
hdiutil verify "$OUTPUT" >/dev/null
|
||||
|
||||
echo "== macOS release =="
|
||||
ls -lh "$OUTPUT"
|
||||
|
|
@ -1,13 +1,12 @@
|
|||
#!/bin/bash
|
||||
# Build the Windows release artefacts from current source.
|
||||
# Build the Windows x64 release installer from current source.
|
||||
#
|
||||
# scripts/build-windows-release.sh [--skip-build] [--arch x64|arm64]...
|
||||
# scripts/build-windows-release.sh [--skip-build]
|
||||
#
|
||||
# For every architecture asked for (both by default) this produces an NSIS
|
||||
# per-user installer plus a portable ZIP in artifacts/, then refreshes
|
||||
# Produces artifacts/Shift-Setup-<version>-win-x64.exe and refreshes
|
||||
# artifacts/SHA256SUMS.txt. Cross-compiled on macOS with cargo-xwin; makensis is
|
||||
# the Homebrew formula of the same name. publish-release.sh maps the installers
|
||||
# onto the "windows" and "windows-arm64" keys of the update manifest.
|
||||
# the Homebrew formula of the same name. Windows ARM64 runs this x64 package
|
||||
# through the update manifest's normal `windows` fallback.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
|
|
@ -18,24 +17,15 @@ export RUSTC="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/rustc"
|
|||
ROOT="$PWD"
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
|
||||
ARCHES=""
|
||||
SKIP_BUILD=0
|
||||
usage() { echo "usage: $0 [--skip-build] [--arch x64|arm64]..." >&2 && exit 2; }
|
||||
usage() { echo "usage: $0 [--skip-build]" >&2 && exit 2; }
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1 ;;
|
||||
--arch)
|
||||
shift
|
||||
case "${1:-}" in
|
||||
x64|arm64) ARCHES="$ARCHES $1" ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[ -n "$ARCHES" ] || ARCHES="x64 arm64"
|
||||
|
||||
# A build can only verify a signed channel if the release key is compiled in. Derive
|
||||
# it from the signing key when the caller gave us one, and never do this quietly: the
|
||||
|
|
@ -55,40 +45,34 @@ if [ "$SKIP_BUILD" != "1" ]; then
|
|||
TAURI_ENV_PLATFORM=windows pnpm build
|
||||
fi
|
||||
|
||||
# One target triple, one expected PE machine and one release-note label per
|
||||
# architecture. The PE check is what stops an x64 binary shipping inside an
|
||||
# arm64 package because a build was pointed at the wrong target.
|
||||
for ARCH in $ARCHES; do
|
||||
case "$ARCH" in
|
||||
x64) TARGET=x86_64-pc-windows-msvc; PE_MACHINE=8664; MACHINE="64 位" ;;
|
||||
arm64) TARGET=aarch64-pc-windows-msvc; PE_MACHINE=aa64; MACHINE=ARM64 ;;
|
||||
esac
|
||||
EXE="src-tauri/target/$TARGET/release/shift.exe"
|
||||
INSTALLER="artifacts/Shift-Setup-$VERSION-win-$ARCH.exe"
|
||||
PORTABLE="artifacts/Shift-Portable-$VERSION-win-$ARCH.zip"
|
||||
NOTES="artifacts/README-Windows-$ARCH.txt"
|
||||
ARCH=x64
|
||||
TARGET=x86_64-pc-windows-msvc
|
||||
PE_MACHINE=8664
|
||||
EXE="src-tauri/target/$TARGET/release/shift.exe"
|
||||
INSTALLER="artifacts/Shift-Setup-$VERSION-win-x64.exe"
|
||||
NOTES="artifacts/README-Windows-x64.txt"
|
||||
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
echo "== rust cross build ($ARCH: $TARGET) =="
|
||||
# --features tauri/custom-protocol is mandatory: without it Tauri derives
|
||||
# cfg(dev) and every window loads build.devUrl instead of the bundled assets.
|
||||
CROSS_LOG=$(mktemp /tmp/shift-win-build.XXXXXX)
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target "$TARGET" --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
echo "== rust cross build ($TARGET) =="
|
||||
# --features tauri/custom-protocol is mandatory: without it Tauri derives
|
||||
# cfg(dev) and every window loads build.devUrl instead of the bundled assets.
|
||||
CROSS_LOG=$(mktemp /tmp/shift-win-build.XXXXXX)
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target "$TARGET" --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
fi
|
||||
|
||||
test -f "$EXE"
|
||||
test -f "$EXE"
|
||||
|
||||
echo "== PE machine check ($ARCH) =="
|
||||
python3 - "$EXE" "$PE_MACHINE" <<PE
|
||||
echo "== PE machine check (x64) =="
|
||||
python3 - "$EXE" "$PE_MACHINE" <<PE
|
||||
import pathlib, struct, sys
|
||||
exe = pathlib.Path(sys.argv[1]).read_bytes()
|
||||
machine = struct.unpack_from("<H", exe, struct.unpack_from("<I", exe, 0x3C)[0] + 4)[0]
|
||||
|
|
@ -98,8 +82,8 @@ if machine != expected:
|
|||
print(f"pe machine ok: 0x{machine:04x}")
|
||||
PE
|
||||
|
||||
echo "== verify the frontend is embedded =="
|
||||
python3 - "$EXE" <<PY
|
||||
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]
|
||||
|
|
@ -125,18 +109,17 @@ if missing:
|
|||
print(f"embedded ok: {len(exe):,} byte exe carries the current dist/assets")
|
||||
PY
|
||||
|
||||
echo "== windows notes ($ARCH) =="
|
||||
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
|
||||
mkdir -p "$STAGE/portable/Shift-$VERSION-Windows-$ARCH"
|
||||
python3 - "$STAGE" "$VERSION" "$ARCH" "$MACHINE" <<PY
|
||||
echo "== windows notes (x64) =="
|
||||
STAGE=$(mktemp -d /tmp/shift-windows-release.XXXXXX)
|
||||
python3 - "$STAGE" "$VERSION" <<PY
|
||||
import pathlib, sys
|
||||
stage = pathlib.Path(sys.argv[1])
|
||||
version, arch, machine = sys.argv[2:5]
|
||||
text = f"""Shift {version} - Windows {arch}
|
||||
version = sys.argv[2]
|
||||
text = f"""Shift {version} - Windows x64
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11({machine})。
|
||||
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
|
||||
- Microsoft Edge WebView2 Runtime。当前 Windows 10/11 通常已内置;如果 Shift
|
||||
启动后窗口空白或无法打开,请从微软官方页面安装:
|
||||
https://developer.microsoft.com/microsoft-edge/webview2/
|
||||
|
|
@ -145,7 +128,7 @@ text = f"""Shift {version} - Windows {arch}
|
|||
|
||||
安装
|
||||
----
|
||||
1. 运行 Shift-Setup-{version}-win-{arch}.exe,默认安装到
|
||||
1. 运行 Shift-Setup-{version}-win-x64.exe,默认安装到
|
||||
%LOCALAPPDATA%\\Programs\\Shift,并创建开始菜单与桌面快捷方式。
|
||||
2. 这是未签名构建。若 SmartScreen 显示“Windows 已保护你的电脑”,请选择
|
||||
“更多信息” > “仍要运行”。
|
||||
|
|
@ -154,11 +137,6 @@ text = f"""Shift {version} - Windows {arch}
|
|||
如果之前拒绝过,请到“Windows 安全中心 > 防火墙和网络保护 > 允许应用通过
|
||||
防火墙”,勾选 Shift 的专用网络权限;否则“发送到设备”无法接收其它终端的信标。
|
||||
|
||||
便携版
|
||||
------
|
||||
不想安装时,解压 Shift-Portable-{version}-win-{arch}.zip,直接运行其中的
|
||||
shift.exe。请先完整解压,不要在压缩包的预览窗口里运行。
|
||||
|
||||
运行组件
|
||||
--------
|
||||
打开 Shift 主窗口,进入“设置” > “运行组件”:
|
||||
|
|
@ -181,34 +159,26 @@ WinGet 包映射:
|
|||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\\Shift-Setup-{version}-win-{arch}.exe -Algorithm SHA256
|
||||
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 ($ARCH) =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSHIFT_EXE="$PWD/$EXE" \
|
||||
-DLICENSE_FILE="$PWD/LICENSE" \
|
||||
-DNOTICES_FILE="$PWD/THIRD_PARTY_NOTICES.md" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$PWD/src-tauri/icons" \
|
||||
-DOUT_FILE="$PWD/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DARCH="$ARCH" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
|
||||
echo "== portable ZIP ($ARCH) =="
|
||||
cp "$EXE" "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/shift.exe"
|
||||
cp LICENSE "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/LICENSE.txt"
|
||||
cp THIRD_PARTY_NOTICES.md "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/THIRD_PARTY_NOTICES.txt"
|
||||
cp "$STAGE/README-Windows.txt" "$STAGE/portable/Shift-$VERSION-Windows-$ARCH/README-Windows.txt"
|
||||
(cd "$STAGE/portable" && zip -q -r -X -9 "$ROOT/$PORTABLE" "Shift-$VERSION-Windows-$ARCH")
|
||||
mv "$STAGE/README-Windows.txt" "$NOTES"
|
||||
done
|
||||
echo "== NSIS installer (x64) =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSHIFT_EXE="$PWD/$EXE" \
|
||||
-DLICENSE_FILE="$PWD/LICENSE" \
|
||||
-DNOTICES_FILE="$PWD/THIRD_PARTY_NOTICES.md" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$PWD/src-tauri/icons" \
|
||||
-DOUT_FILE="$PWD/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
mv "$STAGE/README-Windows.txt" "$NOTES"
|
||||
rm -rf "$STAGE"
|
||||
|
||||
echo "== checksums =="
|
||||
python3 - "$VERSION" <<PY
|
||||
|
|
@ -216,24 +186,12 @@ import hashlib, pathlib, sys
|
|||
version = sys.argv[1]
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
preferred = [
|
||||
"Shift-macOS-universal.dmg",
|
||||
"Shift-macOS-universal.zip",
|
||||
f"Shift-{version}-macOS-universal.dmg",
|
||||
f"Shift-Setup-{version}-win-x64.exe",
|
||||
f"Shift-Setup-{version}-win-arm64.exe",
|
||||
f"Shift-Portable-{version}-win-x64.zip",
|
||||
f"Shift-Portable-{version}-win-arm64.zip",
|
||||
"README-Windows-x64.txt",
|
||||
"README-Windows-arm64.txt",
|
||||
"README-macOS-universal.txt",
|
||||
]
|
||||
names = [name for name in preferred if (artifacts / name).is_file()]
|
||||
names += sorted(
|
||||
path.name
|
||||
for path in artifacts.iterdir()
|
||||
if path.is_file()
|
||||
and path.name not in names
|
||||
and path.name != "SHA256SUMS.txt"
|
||||
and not path.name.startswith(".")
|
||||
)
|
||||
lines = [f"{hashlib.sha256((artifacts / name).read_bytes()).hexdigest()} {name}" for name in names]
|
||||
(artifacts / "SHA256SUMS.txt").write_text("".join(line + "\n" for line in lines), encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
#!/bin/bash
|
||||
# Wrap a built Shift.app in a .pkg installer for the release channel.
|
||||
#
|
||||
# scripts/macos-pkg.sh <path/to/Shift.app> <output.pkg> [version]
|
||||
#
|
||||
# Why a package at all: this build is signed with a self-signed identity and is not
|
||||
# notarized, so Gatekeeper calls it an unidentified developer. Dragging the app out of
|
||||
# a disk image hands that verdict to the app itself, and a fresh machine refuses to open
|
||||
# it until the user allows it in System Settings > Privacy & Security. `installer` does
|
||||
# not propagate the quarantine flag onto what it installs, so a .pkg-installed copy
|
||||
# launches with no prompt at all. The disk image stays the auto-update transport, which
|
||||
# needs no administrator password; the package is what a new machine should install.
|
||||
#
|
||||
# The payload keeps the signature the app was built with; pkgbuild does not re-sign or
|
||||
# strip it. An installer-signing identity would let the package itself be signed too,
|
||||
# which needs a certificate with the Installer Signing purpose -- productsign rejects
|
||||
# an application identity, and this repository's build has only that one.
|
||||
set -euo pipefail
|
||||
|
||||
APP="${1:?usage: $0 <path/to/Shift.app> <output.pkg> [version]}"
|
||||
OUT="${2:?usage: $0 <path/to/Shift.app> <output.pkg> [version]}"
|
||||
VERSION="${3:-$(plutil -extract CFBundleShortVersionString raw "$APP/Contents/Info.plist" 2>/dev/null || echo 0.0.0)}"
|
||||
|
||||
[ -d "$APP" ] || { echo "not an app bundle: $APP" >&2; exit 2; }
|
||||
|
||||
STAGE=$(mktemp -d /tmp/shift-pkg-stage.XXXXXX)
|
||||
trap 'rm -rf "$STAGE"' EXIT
|
||||
mkdir -p "$STAGE/Applications"
|
||||
# ditto, not cp: it keeps resource forks, symlinks and code signatures intact.
|
||||
ditto "$APP" "$STAGE/Applications/$(basename "$APP")"
|
||||
|
||||
# install-location is the folder the payload is rooted at, so the app lands in
|
||||
# /Applications for every user of the machine.
|
||||
pkgbuild \
|
||||
--version "$VERSION" \
|
||||
--identifier "$(plutil -extract CFBundleIdentifier raw "$APP/Contents/Info.plist" 2>/dev/null || echo app.nex.shift)" \
|
||||
--install-location /Applications \
|
||||
--root "$STAGE/Applications" \
|
||||
--ownership preserve \
|
||||
"$OUT"
|
||||
|
||||
echo "wrote $OUT ($(stat -f%z "$OUT") bytes, version $VERSION)"
|
||||
echo "payload check:"
|
||||
pkgutil --payload-files "$OUT" | head -4
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
# scripts/publish-release.sh [--notes FILE] [--key FILE] [--dry-run]
|
||||
# [--no-push] [--branch NAME]
|
||||
#
|
||||
# Every installer in artifacts/ is copied onto an orphan `releases` branch together
|
||||
# The two release installers in artifacts/ are copied onto an orphan `releases` branch together
|
||||
# with `shift-update.json`, which names each file, its size and its SHA256. A running
|
||||
# Shift reads that manifest from the forge's raw endpoint, downloads its own
|
||||
# platform's artifact and refuses to launch it unless the recomputed hash matches, so
|
||||
|
|
@ -57,23 +57,12 @@ if not artifacts.is_dir():
|
|||
sys.exit("artifacts/ is missing; build a release first.")
|
||||
notes = pathlib.Path(notes_file).read_text(encoding="utf-8").strip() if notes_file else ""
|
||||
|
||||
# One installer per manifest key. Extra files such as the portable archive and the
|
||||
# checksum listing still travel with the branch, they are just not installers.
|
||||
# Windows is keyed per architecture: `windows` is what an x64 machine installs and
|
||||
# what an ARM machine falls back to, `windows-arm64` is the native ARM build. The
|
||||
# x64 pattern must not match the arm64 file, or every Windows machine would be
|
||||
# served whichever installer sorted first.
|
||||
# The channel intentionally has exactly two installers. Versioned, exact names keep
|
||||
# a stale DMG or an old architecture from slipping into a new release. Supporting
|
||||
# files such as the checksums and readmes still travel with the branch.
|
||||
PATTERNS = [
|
||||
("macos", [r"^Shift-macOS-universal\.dmg$", r"^[Ss]hift.*\.dmg$"]),
|
||||
(
|
||||
"windows",
|
||||
[rf"^Shift-Setup-{re.escape(version)}-win-x64\.exe$", r"-win-x64\.exe$"],
|
||||
),
|
||||
(
|
||||
"windows-arm64",
|
||||
[rf"^Shift-Setup-{re.escape(version)}-win-arm64\.exe$", r"-win-arm64\.exe$"],
|
||||
),
|
||||
("linux", [r"\.AppImage$", r"\.deb$"]),
|
||||
("macos", rf"^Shift-{re.escape(version)}-macOS-universal\.dmg$"),
|
||||
("windows", rf"^Shift-Setup-{re.escape(version)}-win-x64\.exe$"),
|
||||
]
|
||||
candidates = sorted(p.name for p in artifacts.iterdir() if p.is_file())
|
||||
|
||||
|
|
@ -89,20 +78,29 @@ manifest = {
|
|||
"artifacts": {},
|
||||
}
|
||||
chosen = []
|
||||
for platform, patterns in PATTERNS:
|
||||
for pattern in patterns:
|
||||
match = next((name for name in candidates if re.search(pattern, name)), None)
|
||||
if match:
|
||||
hash_value, size = digest(match)
|
||||
manifest["artifacts"][platform] = {"file": match, "sha256": hash_value, "size": size}
|
||||
chosen.append(match)
|
||||
break
|
||||
for platform, pattern in PATTERNS:
|
||||
match = next((name for name in candidates if re.search(pattern, name)), None)
|
||||
if not match:
|
||||
sys.exit(
|
||||
f"missing installer for {platform} at version {version}; expected "
|
||||
f"Shift-{version}-macOS-universal.dmg and "
|
||||
f"Shift-Setup-{version}-win-x64.exe"
|
||||
)
|
||||
hash_value, size = digest(match)
|
||||
manifest["artifacts"][platform] = {"file": match, "sha256": hash_value, "size": size}
|
||||
chosen.append(match)
|
||||
|
||||
if not manifest["artifacts"]:
|
||||
unexpected = [
|
||||
name
|
||||
for name in candidates
|
||||
if re.search(r"\.(dmg|exe|msi|pkg|zip|AppImage|deb)$", name, re.IGNORECASE)
|
||||
and name not in chosen
|
||||
]
|
||||
if unexpected:
|
||||
sys.exit(
|
||||
f"no installer found in artifacts/ for version {version}; "
|
||||
"expected Shift-macOS-universal.dmg and/or Shift-Setup-<version>-win-{x64,arm64}.exe"
|
||||
)
|
||||
"only the two versioned installers may be published; remove: "
|
||||
+ ", ".join(unexpected)
|
||||
)
|
||||
|
||||
payload = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
|
||||
sys.stdout.write(payload)
|
||||
|
|
|
|||
|
|
@ -2,15 +2,13 @@
|
|||
;
|
||||
; 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> [-DARCH=x64|arm64] \
|
||||
; -DVERSION=0.1.8 -DEST_SIZE_KB=<kb> \
|
||||
; scripts/windows-installer.nsi
|
||||
;
|
||||
; ARCH decides which machine the installer accepts: an x64 package refuses an ARM
|
||||
; machine and an arm64 package refuses x64, so nobody installs the wrong build and
|
||||
; finds out from a blank window. Omitting it keeps the previous x64 behaviour.
|
||||
; The installer accepts native x64 Windows only. Windows on ARM is served by the
|
||||
; same x64 build through its compatibility layer and the update manifest fallback.
|
||||
;
|
||||
; Install scope is deliberately per-user: Shift writes only to HKCU and its own
|
||||
; folder, which is also what the portable build already does.
|
||||
; Install scope is deliberately per-user: Shift writes only to HKCU and its own folder.
|
||||
|
||||
!include "MUI2.nsh"
|
||||
!include "LogicLib.nsh"
|
||||
|
|
@ -30,21 +28,6 @@
|
|||
!define EST_SIZE_KB "40000"
|
||||
!endif
|
||||
|
||||
!ifndef ARCH
|
||||
!define ARCH "x64"
|
||||
!endif
|
||||
|
||||
!if "${ARCH}" == "arm64"
|
||||
!define ARCH_GATE '${IsNativeARM64}'
|
||||
!define ARCH_GATE_MESSAGE "This build is for 64-bit Windows (ARM64)."
|
||||
!else
|
||||
!if "${ARCH}" != "x64"
|
||||
!error "ARCH is either x64 or arm64"
|
||||
!endif
|
||||
!define ARCH_GATE '${IsNativeAMD64}'
|
||||
!define ARCH_GATE_MESSAGE "This build is for 64-bit Windows (x64)."
|
||||
!endif
|
||||
|
||||
!define APP_NAME "Shift"
|
||||
!define APP_ID "app.nex.shift"
|
||||
!define APP_VERSION "${VERSION}"
|
||||
|
|
@ -68,7 +51,7 @@ VIAddVersionKey CompanyName "${PUBLISHER}"
|
|||
VIAddVersionKey LegalCopyright "Copyright ${BUILD_YEAR} ${PUBLISHER}"
|
||||
VIAddVersionKey FileDescription "${APP_NAME} installer"
|
||||
VIAddVersionKey FileVersion "${APP_VERSION}.0"
|
||||
VIAddVersionKey OriginalFilename "Shift-Setup.exe"
|
||||
VIAddVersionKey OriginalFilename "Shift-Setup-${VERSION}-win-x64.exe"
|
||||
|
||||
!define MUI_ICON "${ICONS_DIR}\icon.ico"
|
||||
!define MUI_UNICON "${ICONS_DIR}\icon.ico"
|
||||
|
|
@ -107,17 +90,11 @@ Function .onInit
|
|||
Abort
|
||||
${EndIf}
|
||||
|
||||
${IfNot} ${ARCH_GATE}
|
||||
MessageBox MB_OK|MB_ICONSTOP "${ARCH_GATE_MESSAGE}"
|
||||
${IfNot} ${IsNativeAMD64}
|
||||
MessageBox MB_OK|MB_ICONSTOP "This build is for 64-bit Windows (x64)."
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
!if "${ARCH}" == "arm64"
|
||||
; Read the real 64-bit registry view: on ARM64 the default view is emulated,
|
||||
; and the machine-wide WebView2 key looked up after install is not in it.
|
||||
SetRegView 64
|
||||
!endif
|
||||
|
||||
; Shift keeps a tray process alive and Windows refuses to overwrite a mapped
|
||||
; EXE, so ask before closing a conversion the user may be waiting on.
|
||||
; A silent install comes from Shift itself, which has already said it is about to
|
||||
|
|
|
|||
|
|
@ -3899,7 +3899,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "shift"
|
||||
version = "0.1.7"
|
||||
version = "0.1.8"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"calamine",
|
||||
|
|
@ -3921,6 +3921,7 @@ dependencies = [
|
|||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-global-shortcut",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"uuid",
|
||||
"which",
|
||||
"windows-sys 0.59.0",
|
||||
|
|
@ -4475,6 +4476,22 @@ dependencies = [
|
|||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "561cd99484561bc39c954768e7b41a66cebbe1ac3d9d081c34361f740c489e2c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.12.2"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "shift"
|
||||
version = "0.1.7"
|
||||
version = "0.1.8"
|
||||
description = "A radial file utility with screenshot, recording and OCR."
|
||||
authors = ["Shift Contributors"]
|
||||
edition = "2021"
|
||||
|
|
@ -18,6 +18,7 @@ tauri-plugin-clipboard-manager = "2"
|
|||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-global-shortcut = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
image = { version = "0.25.8", default-features = false, features = ["png", "jpeg", "webp", "tiff", "bmp", "gif"] }
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -273,13 +273,22 @@ fn screenshot_directory(app: &AppHandle) -> Result<PathBuf, String> {
|
|||
settings::screenshot_dir(app)
|
||||
}
|
||||
|
||||
/// Freeze the screen and raise the overlay for one capture mode.
|
||||
///
|
||||
/// The Shift windows go down before the grab so the frozen frame holds nothing of
|
||||
/// Shift, and come back whether the overlay ends in a file, a cancel, or a failure.
|
||||
pub fn begin_capture(app: &AppHandle, mode: &str) -> Result<CaptureSessionInfo, String> {
|
||||
ensure_screen_capture_access()?;
|
||||
for label in ["main", "radial", "editor"] {
|
||||
if let Some(window) = app.get_webview_window(label) {
|
||||
let _ = window.hide();
|
||||
}
|
||||
hide_shift_windows(app);
|
||||
let result = begin_overlay(app, mode);
|
||||
if result.is_err() {
|
||||
// A capture that never reached the screen must not leave the panel hidden.
|
||||
restore_windows(app);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn begin_overlay(app: &AppHandle, mode: &str) -> Result<CaptureSessionInfo, String> {
|
||||
std::thread::sleep(std::time::Duration::from_millis(90));
|
||||
let monitor = monitor_at_cursor(app)?;
|
||||
let source = capture_screen(app, &monitor)?;
|
||||
|
|
@ -314,12 +323,87 @@ pub fn begin_capture(app: &AppHandle, mode: &str) -> Result<CaptureSessionInfo,
|
|||
}
|
||||
window.show().map_err(|error| error.to_string())?;
|
||||
window.set_focus().map_err(|error| error.to_string())?;
|
||||
// Showing the overlay is not the same as giving it the keyboard: see `focus_page`.
|
||||
crate::focus_page(app, "capture");
|
||||
window
|
||||
.emit("capture://ready", info.clone())
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// True while a region recording is on screen. `recording::stop` holds the session
|
||||
/// lock while it finishes the file and restores the windows, so this reads the HUD
|
||||
/// rather than that mutex — locking it from here would self-deadlock.
|
||||
fn recording_active(app: &AppHandle) -> bool {
|
||||
app.get_webview_window("recorder")
|
||||
.and_then(|window| window.is_visible().ok())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The labels a capture clears off the screen, so the grab holds nothing of Shift.
|
||||
const CAPTURE_COVERED: [&str; 3] = ["main", "radial", "editor"];
|
||||
|
||||
/// Hide the Shift windows, remembering which ones were open. Without that record a
|
||||
/// capture could only guess on the way back, which is how "the panel was open, I
|
||||
/// took a screenshot, and the panel is gone" happens.
|
||||
fn hide_shift_windows(app: &AppHandle) {
|
||||
let mut hidden = Vec::new();
|
||||
for label in CAPTURE_COVERED {
|
||||
if let Some(window) = app.get_webview_window(label) {
|
||||
if window.is_visible().unwrap_or(false) {
|
||||
hidden.push(label.to_string());
|
||||
}
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
// Only a fresh capture writes the record. A second overlay raised on top of
|
||||
// the first, or a shot taken mid-recording, must leave the pending one alone
|
||||
// rather than trade the open panel for an empty list.
|
||||
let overlay_up = app
|
||||
.get_webview_window("capture")
|
||||
.and_then(|window| window.is_visible().ok())
|
||||
.unwrap_or(false);
|
||||
if !overlay_up && !recording_active(app) {
|
||||
if let Ok(mut restore) = state.capture_restore.lock() {
|
||||
*restore = hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put back the windows this capture hid. Called when the capture overlay leaves,
|
||||
/// whether the shot was taken, cancelled, or handed to the recorder.
|
||||
pub fn restore_windows(app: &AppHandle) {
|
||||
// Mid-recording the panel stays down, or it would appear inside the shot; the
|
||||
// recorder restores it when the video is written.
|
||||
if recording_active(app) {
|
||||
return;
|
||||
}
|
||||
let Some(state) = app.try_state::<AppState>() else {
|
||||
return;
|
||||
};
|
||||
let Ok(mut restore) = state.capture_restore.lock() else {
|
||||
return;
|
||||
};
|
||||
let mut restored_main = false;
|
||||
for label in restore.drain(..) {
|
||||
restored_main |= label == "main";
|
||||
if let Some(window) = app.get_webview_window(&label) {
|
||||
let _ = window.show();
|
||||
}
|
||||
}
|
||||
// The panel the capture came from is the thing the user was working in, so it
|
||||
// takes the keyboard back. A result card or editor opened after this still
|
||||
// focuses itself, so it wins when it is the more recent request.
|
||||
if restored_main {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.set_focus();
|
||||
crate::focus_page(app, "main");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn crop_session(
|
||||
app: &AppHandle,
|
||||
state: &AppState,
|
||||
|
|
@ -352,6 +436,16 @@ pub fn crop_session(
|
|||
}
|
||||
|
||||
pub fn dismiss_capture(app: &AppHandle) {
|
||||
close_overlay(app, true)
|
||||
}
|
||||
|
||||
/// End the overlay but leave the panel hidden, for the recorder: a restored window
|
||||
/// would land inside the region being filmed. `recording::stop` restores it instead.
|
||||
pub fn dismiss_capture_for_recording(app: &AppHandle) {
|
||||
close_overlay(app, false)
|
||||
}
|
||||
|
||||
fn close_overlay(app: &AppHandle, restore: bool) {
|
||||
let source = app
|
||||
.try_state::<AppState>()
|
||||
.and_then(|state| {
|
||||
|
|
@ -370,6 +464,9 @@ pub fn dismiss_capture(app: &AppHandle) {
|
|||
if let Some(path) = source {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
if restore {
|
||||
restore_windows(app);
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
|
@ -395,10 +492,6 @@ pub async fn start_capture(app: AppHandle, mode: String) -> Result<CaptureSessio
|
|||
#[tauri::command]
|
||||
pub fn cancel_capture(app: AppHandle) -> Result<(), String> {
|
||||
dismiss_capture(&app);
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -454,11 +547,7 @@ fn hand_off(app: &AppHandle, output: &Path) {
|
|||
|
||||
pub fn capture_fullscreen_core(app: &AppHandle, state: &AppState) -> Result<String, String> {
|
||||
ensure_screen_capture_access()?;
|
||||
for label in ["main", "radial", "editor"] {
|
||||
if let Some(window) = app.get_webview_window(label) {
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
hide_shift_windows(app);
|
||||
std::thread::sleep(std::time::Duration::from_millis(90));
|
||||
let monitor = monitor_at_cursor(app)?;
|
||||
let source = capture_screen(app, &monitor)?;
|
||||
|
|
@ -484,10 +573,7 @@ pub async fn capture_fullscreen(app: AppHandle) -> Result<String, String> {
|
|||
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();
|
||||
}
|
||||
restore_windows(&app);
|
||||
}
|
||||
result
|
||||
})
|
||||
|
|
@ -522,9 +608,10 @@ fn open_screen_recording_settings_sync() -> Result<(), String> {
|
|||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Could not open Screen Recording settings.".into())
|
||||
}
|
||||
return Err("Could not open Screen Recording settings.".into());
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
|
|
|
|||
|
|
@ -66,16 +66,13 @@ pub fn resolve_bridge_path(app: &AppHandle) -> Option<std::path::PathBuf> {
|
|||
return Some(dev);
|
||||
}
|
||||
let resource = app.path().resource_dir().ok()?;
|
||||
for candidate in [
|
||||
[
|
||||
resource.join("drag-bridge"),
|
||||
resource.join("binaries").join("drag-bridge"),
|
||||
resource.join(format!("drag-bridge-{triple}")),
|
||||
] {
|
||||
if candidate.exists() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
None
|
||||
]
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.exists())
|
||||
}
|
||||
|
||||
pub fn spawn(app: &AppHandle) {
|
||||
|
|
@ -482,6 +479,10 @@ pub fn show_radial(
|
|||
// Finder drag the non-activating window must stay unfocused.
|
||||
if !dragging {
|
||||
let _ = window.set_focus();
|
||||
// The window being key is not enough: AppKit delivers keys to the window's
|
||||
// first responder, which re-showing leaves on tao's own view rather than the
|
||||
// page, so Escape would never reach the ring. See `crate::focus_page`.
|
||||
crate::focus_page(app, "radial");
|
||||
}
|
||||
window
|
||||
.emit("radial://show", context.clone())
|
||||
|
|
|
|||
|
|
@ -636,10 +636,6 @@ fn video_encoder() -> &'static str {
|
|||
})
|
||||
}
|
||||
|
||||
pub(crate) fn video_encoder_name() -> &'static str {
|
||||
video_encoder()
|
||||
}
|
||||
|
||||
fn video_encode_args(crf: &'static str, bitrate: &'static str) -> Vec<&'static str> {
|
||||
match video_encoder() {
|
||||
"libx264" => vec![
|
||||
|
|
@ -927,6 +923,59 @@ pub(crate) fn doc_render_bridge() -> Option<PathBuf> {
|
|||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn quicklook_preview_html(work: &Path) -> Option<PathBuf> {
|
||||
fs::read_dir(work)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path().join("Preview.html"))
|
||||
.find(|candidate| candidate.is_file())
|
||||
}
|
||||
|
||||
/// Uses the same Quick Look preview Word documents show in Finder as the print
|
||||
/// source. AppKit's OOXML reader keeps only the body, so headers, footers and
|
||||
/// other page furniture disappear; the Quick Look HTML includes them.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn docx_pdf_via_quicklook(
|
||||
input: &Path,
|
||||
renderer: &Path,
|
||||
output_dir: Option<&Path>,
|
||||
) -> Option<PathBuf> {
|
||||
let work = std::env::temp_dir().join(format!("shift-docx-quicklook-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&work).ok()?;
|
||||
let result = (|| {
|
||||
let input_arg = input.to_string_lossy();
|
||||
let work_arg = work.to_string_lossy();
|
||||
let status = crate::process::status_with_timeout(
|
||||
"/usr/bin/qlmanage",
|
||||
&["-p", input_arg.as_ref(), "-o", work_arg.as_ref()],
|
||||
std::time::Duration::from_secs(30),
|
||||
)
|
||||
.ok()?;
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
let preview = quicklook_preview_html(&work)?;
|
||||
let generated = work.join("preview.pdf");
|
||||
let status = background_command(renderer)
|
||||
.arg(&preview)
|
||||
.arg(&generated)
|
||||
.arg(preview.parent()?)
|
||||
.arg("--webkit")
|
||||
.status()
|
||||
.ok()?;
|
||||
if !status.success() || !generated.exists() {
|
||||
return None;
|
||||
}
|
||||
let target_dir = output_dir
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| directory_of(input));
|
||||
rename_office_output(generated, input, &target_dir).ok()
|
||||
})();
|
||||
let _ = fs::remove_dir_all(work);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn native_document_pdf(
|
||||
input: &Path,
|
||||
|
|
@ -960,6 +1009,11 @@ fn native_document_pdf(
|
|||
return Ok(None);
|
||||
};
|
||||
let extension = extension_of(input);
|
||||
if extension == "docx" {
|
||||
if let Some(output) = docx_pdf_via_quicklook(input, &renderer, output_dir) {
|
||||
return Ok(Some(output));
|
||||
}
|
||||
}
|
||||
let mut source = input.to_path_buf();
|
||||
let mut temporary = None;
|
||||
// A DOCX with pictures cannot reach the AppKit reader: it silently drops
|
||||
|
|
@ -1020,12 +1074,16 @@ fn native_document_pdf(
|
|||
.to_path_buf();
|
||||
}
|
||||
let output = unique_output_in(input, output_dir, "", "pdf")?;
|
||||
let status = background_command(&renderer)
|
||||
let rendered = background_command(&renderer)
|
||||
.arg(&source)
|
||||
.arg(&output)
|
||||
.arg(&base_dir)
|
||||
.status()
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()
|
||||
.map_err(|error| format!("Could not start the document renderer: {error}"))?;
|
||||
let status = rendered.status;
|
||||
let renderer_error = String::from_utf8_lossy(&rendered.stderr);
|
||||
let renderer_error = renderer_error.trim();
|
||||
if let Some(path) = temporary {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
|
|
@ -1034,7 +1092,14 @@ fn native_document_pdf(
|
|||
}
|
||||
if !status.success() || !output.exists() {
|
||||
let _ = fs::remove_file(&output);
|
||||
return Err("Could not render this document to PDF.".into());
|
||||
if !renderer_error.is_empty() {
|
||||
return Err(format!(
|
||||
"Could not render this document to PDF: {renderer_error}"
|
||||
));
|
||||
}
|
||||
return Err(format!(
|
||||
"Could not render this document to PDF. Renderer exited with {status}."
|
||||
));
|
||||
}
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
|
@ -1941,18 +2006,6 @@ pub async fn reveal_file(path: String) -> Result<(), String> {
|
|||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn existing_files(paths: Vec<String>) -> Vec<String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
paths
|
||||
.into_iter()
|
||||
.filter(|path| Path::new(path).is_file())
|
||||
.collect()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_file(path: String) -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(move || open_path(Path::new(&path)))
|
||||
|
|
@ -2005,7 +2058,7 @@ pub async fn save_image_data(
|
|||
save_image_data_in(&source, &data_url, suffix.as_deref(), output_dir.as_deref())?;
|
||||
// Annotations saved from the editor are a result like any other, and this
|
||||
// path does not run through the action pipeline, so it records itself.
|
||||
crate::history::record(&app, &[output.clone()]);
|
||||
crate::history::record(&app, std::slice::from_ref(&output));
|
||||
Ok(output)
|
||||
})
|
||||
.await
|
||||
|
|
@ -2090,7 +2143,7 @@ pub async fn save_text_near(
|
|||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let output_dir = settings::files_output_dir(&app)?;
|
||||
let output = save_text_near_in(&source, &text, suffix.as_deref(), output_dir.as_deref())?;
|
||||
crate::history::record(&app, &[output.clone()]);
|
||||
crate::history::record(&app, std::slice::from_ref(&output));
|
||||
Ok(output)
|
||||
})
|
||||
.await
|
||||
|
|
@ -2136,6 +2189,62 @@ mod tests {
|
|||
image.save_with_format(path, ImageFormat::Png).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn docx_with_header_and_footer(path: &Path) {
|
||||
use std::io::Write as _;
|
||||
use zip::{write::SimpleFileOptions, ZipWriter};
|
||||
|
||||
let entries = [
|
||||
(
|
||||
"[Content_Types].xml",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
||||
<Default Extension="xml" ContentType="application/xml"/>
|
||||
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
||||
<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>
|
||||
<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>
|
||||
</Types>"#,
|
||||
),
|
||||
(
|
||||
"_rels/.rels",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
|
||||
</Relationships>"#,
|
||||
),
|
||||
(
|
||||
"word/document.xml",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p><w:r><w:t>Body content that must survive.</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rId1"/><w:footerReference w:type="default" r:id="rId2"/><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr></w:body></w:document>"#,
|
||||
),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>
|
||||
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>
|
||||
</Relationships>"#,
|
||||
),
|
||||
(
|
||||
"word/header1.xml",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:r><w:t>Shift Header Regression</w:t></w:r></w:p></w:hdr>"#,
|
||||
),
|
||||
(
|
||||
"word/footer1.xml",
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:r><w:t>Shift Footer Regression</w:t></w:r></w:p></w:ftr>"#,
|
||||
),
|
||||
];
|
||||
|
||||
let file = fs::File::create(path).unwrap();
|
||||
let mut zip = ZipWriter::new(file);
|
||||
for (name, content) in entries {
|
||||
zip.start_file(name, SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(content.as_bytes()).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_and_avoids_overwriting() {
|
||||
let dir = scratch_dir();
|
||||
|
|
@ -2488,6 +2597,21 @@ mod tests {
|
|||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn keeps_docx_headers_and_footers_when_converting_to_pdf() {
|
||||
let dir = scratch_dir();
|
||||
let input = dir.join("header.docx");
|
||||
docx_with_header_and_footer(&input);
|
||||
|
||||
let output = convert_document(&input, "pdf", None, None).unwrap();
|
||||
let text = pdf::text_of(&output).unwrap_or_default();
|
||||
assert!(text.contains("Shift Header Regression"), "{text}");
|
||||
assert!(text.contains("Body content that must survive"), "{text}");
|
||||
assert!(text.contains("Shift Footer Regression"), "{text}");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The bug this pins: AppKit's OOXML reader keeps the text of a DOCX and
|
||||
/// silently drops its pictures, so a report with figures printed as a text
|
||||
/// document with no figures at all. The PDF must carry the image.
|
||||
|
|
@ -2539,8 +2663,6 @@ mod tests {
|
|||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn fits_a_wide_picture_onto_the_page() {
|
||||
use lopdf::Object;
|
||||
|
||||
if which::which("pandoc").is_err() {
|
||||
return;
|
||||
}
|
||||
|
|
@ -2565,49 +2687,21 @@ mod tests {
|
|||
.success());
|
||||
|
||||
let output = convert_document(&input, "pdf", None, None).unwrap();
|
||||
let document = lopdf::Document::load(&output).unwrap();
|
||||
let page_id = *document.get_pages().values().next().expect("a page");
|
||||
let page = document.get_object(page_id).unwrap().as_dict().unwrap();
|
||||
let media = page.get(b"MediaBox").unwrap().as_array().unwrap();
|
||||
let coordinate = |index: usize| match &media[index] {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) => f64::from(*value),
|
||||
other => panic!("MediaBox entry is {other:?}"),
|
||||
};
|
||||
let page_width = coordinate(2) - coordinate(0);
|
||||
|
||||
let mut widest: f64 = 0.0;
|
||||
for object in document.objects.values() {
|
||||
let Object::Stream(stream) = object else {
|
||||
continue;
|
||||
};
|
||||
if stream
|
||||
.dict
|
||||
.get(b"Subtype")
|
||||
.ok()
|
||||
.and_then(|name| name.as_name().ok())
|
||||
!= Some(b"Form")
|
||||
{
|
||||
continue;
|
||||
let rendered = pdf::to_images_in(&output, "png", &dir.join("rendered")).unwrap();
|
||||
assert_eq!(rendered.len(), 1, "the short report grew an extra page");
|
||||
let page = image::open(&rendered[0]).unwrap().to_rgb8();
|
||||
let mut blue_columns = Vec::new();
|
||||
for (x, _y, pixel) in page.enumerate_pixels() {
|
||||
if pixel[2] > 150 && pixel[1] > 70 && pixel[0] < 100 {
|
||||
blue_columns.push(x);
|
||||
}
|
||||
let Ok(bbox) = stream.dict.get(b"BBox").and_then(|value| value.as_array()) else {
|
||||
continue;
|
||||
};
|
||||
let edge = |index: usize| match &bbox[index] {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) => f64::from(*value),
|
||||
_ => 0.0,
|
||||
};
|
||||
widest = widest.max(edge(2) - edge(0));
|
||||
}
|
||||
let left = *blue_columns.iter().min().expect("the picture disappeared");
|
||||
let right = *blue_columns.iter().max().expect("the picture disappeared");
|
||||
assert!(
|
||||
widest > 1.0,
|
||||
"no placed picture found in {}",
|
||||
output.display()
|
||||
);
|
||||
assert!(
|
||||
widest <= page_width,
|
||||
"picture placed {widest}pt wide on a {page_width}pt page"
|
||||
left > 1 && right + 2 < page.width(),
|
||||
"picture runs off the page: columns {left}..={right} of {}",
|
||||
page.width()
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
|
@ -2637,7 +2731,7 @@ mod tests {
|
|||
let output = convert_document(&input, target, None, None).unwrap();
|
||||
let bytes = fs::read(&output).unwrap();
|
||||
let embedded = if target == "docx" {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let names: Vec<String> = archive.file_names().map(str::to_string).collect();
|
||||
names.iter().any(|name| name.starts_with("word/media/"))
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -284,6 +284,7 @@ mod tests {
|
|||
assert_eq!(merged[0].at, 1_730_000_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_adds_unknown_paths_and_never_refreshes_a_timestamp() {
|
||||
let here = real_path();
|
||||
// The folder holding the test binary: a second path that really exists,
|
||||
|
|
|
|||
|
|
@ -53,7 +53,12 @@ pub fn acquire_instance(app: &AppHandle) -> bool {
|
|||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let Ok(file) = OpenOptions::new().create(true).write(true).open(&path) else {
|
||||
let Ok(file) = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.open(&path)
|
||||
else {
|
||||
// An unreadable config folder must not stop the app from starting.
|
||||
return true;
|
||||
};
|
||||
|
|
@ -157,7 +162,10 @@ pub async fn quit_other_instances() -> usize {
|
|||
}
|
||||
|
||||
fn stop_other_instances() -> usize {
|
||||
let mut stopped = 0;
|
||||
#[cfg(unix)]
|
||||
let mut stopped: usize = 0;
|
||||
#[cfg(not(unix))]
|
||||
let stopped: usize = 0;
|
||||
for pid in other_pids() {
|
||||
#[cfg(unix)]
|
||||
if unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) } == 0 {
|
||||
|
|
|
|||
|
|
@ -58,6 +58,8 @@ pub struct AppState {
|
|||
/// Mirrors settings.drag_enabled so the drag monitors can check it cheaply.
|
||||
pub drag_enabled: AtomicBool,
|
||||
pub pinned_image: Mutex<Option<editor::PinnedPreview>>,
|
||||
/// Shift windows a capture hid, so ending the capture can put them back.
|
||||
pub capture_restore: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
/// The language the native tray is showing. The webview sends this before any
|
||||
|
|
@ -92,6 +94,7 @@ impl Default for AppState {
|
|||
drag_enabled: AtomicBool::new(true),
|
||||
bridge: Mutex::new(None),
|
||||
pinned_image: Mutex::new(None),
|
||||
capture_restore: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -104,6 +107,21 @@ fn show_main(app: &AppHandle) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Hand the keyboard to the page itself.
|
||||
///
|
||||
/// `WebviewWindow::set_focus` only makes the window key, and AppKit keeps sending
|
||||
/// key events to whatever the window's first responder is. On macOS that is tao's
|
||||
/// own content view: wry injects the WKWebView as a *subview* and points the
|
||||
/// responder at it once, when the web view is built, and every later
|
||||
/// `set_simple_fullscreen` (its `toggle_style_mask`) or window re-show moves it
|
||||
/// back to `TaoView`. The page then never receives Escape or Enter, which is why
|
||||
/// the capture overlay cannot be cancelled by keyboard and the ring ignores it.
|
||||
pub(crate) fn focus_page(app: &AppHandle, label: &str) {
|
||||
if let Some(webview) = app.get_webview(label) {
|
||||
let _ = webview.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
fn report_error(app: &AppHandle, message: impl Into<String>) {
|
||||
let message = message.into();
|
||||
eprintln!("{message}");
|
||||
|
|
@ -367,6 +385,9 @@ pub fn run() {
|
|||
.build();
|
||||
|
||||
let app = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
show_main(app);
|
||||
}))
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_clipboard_manager::init())
|
||||
|
|
@ -379,7 +400,6 @@ pub fn run() {
|
|||
files::inspect_files,
|
||||
files::perform_file_action,
|
||||
files::reveal_file,
|
||||
files::existing_files,
|
||||
files::open_file,
|
||||
files::read_text_file,
|
||||
files::read_image_data,
|
||||
|
|
@ -406,7 +426,6 @@ pub fn run() {
|
|||
settings::set_update_check_enabled,
|
||||
settings::set_setup_reviewed,
|
||||
settings::get_wedge_orders,
|
||||
settings::set_wedge_order,
|
||||
settings::reveal_output_directory,
|
||||
update::update_check,
|
||||
update::update_status,
|
||||
|
|
@ -441,7 +460,6 @@ pub fn run() {
|
|||
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,
|
||||
|
|
@ -600,6 +618,64 @@ mod tests {
|
|||
assert_eq!(production.matches("TrayIconBuilder::with_id").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_single_instance_guard_runs_before_other_plugins() {
|
||||
// Plugins run in registration order. A second Windows process has to be
|
||||
// rejected before dialogs, shortcuts or windows can be initialised.
|
||||
let production = include_str!("lib.rs").split("#[cfg(test)]").next().unwrap();
|
||||
let guard = production
|
||||
.find(".plugin(tauri_plugin_single_instance::init")
|
||||
.expect("the single-instance plugin must be registered");
|
||||
let next = production
|
||||
.find(".plugin(tauri_plugin_opener::init")
|
||||
.expect("the opener plugin must be registered");
|
||||
assert!(guard < next);
|
||||
assert!(production[guard..next].contains("show_main(app)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_shown_for_capture_or_ring_hands_the_keyboard_to_its_page() {
|
||||
// AppKit sends key events to the window's first responder, and showing a
|
||||
// window leaves that on tao's own view instead of the WKWebView, so Escape
|
||||
// never reaches the page. `set_focus` on the window is not enough; only the
|
||||
// webview's own focus does it. Regression: ESC cancelled nothing in the
|
||||
// capture overlay, and the ring stopped answering it too.
|
||||
for (name, source) in [
|
||||
("capture.rs", include_str!("capture.rs")),
|
||||
("drag_bridge.rs", include_str!("drag_bridge.rs")),
|
||||
] {
|
||||
let production = source.split("#[cfg(test)]").next().unwrap();
|
||||
assert!(
|
||||
production.contains("focus_page"),
|
||||
"{name} shows a page without giving it the keyboard"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_capture_gives_the_open_panels_back() {
|
||||
// Captures hide whatever Shift windows are open. Without restoring them the
|
||||
// user loses an open panel to a screenshot, so both exit paths — the shot
|
||||
// ending, and the recorder taking over — are checked here.
|
||||
let production = include_str!("capture.rs")
|
||||
.split("#[cfg(test)]")
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
production.contains("restore_windows(app)"),
|
||||
"a dismissed capture must restore the windows it hid"
|
||||
);
|
||||
let recording = include_str!("recording.rs")
|
||||
.split("#[cfg(test)]")
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
recording.contains("dismiss_capture_for_recording")
|
||||
&& recording.contains("capture::restore_windows(app)"),
|
||||
"a recording must hold the panels back until the video is written"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_startup_uses_the_registry_api_not_reg_exe() {
|
||||
let production = include_str!("autostart.rs")
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ fn inline(text: &str) -> String {
|
|||
}
|
||||
}
|
||||
}
|
||||
output.push_str("!");
|
||||
output.push('!');
|
||||
index += 1;
|
||||
}
|
||||
'[' => {
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ pub struct CaptureSessionInfo {
|
|||
pub source: CaptureSource,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NormalizedRect {
|
||||
pub x: f64,
|
||||
|
|
@ -84,7 +84,7 @@ pub struct EditorInfo {
|
|||
/// The two switches are honest: `recording_capabilities` says which of them the
|
||||
/// current platform honours, and the overlay hides the rest, so a choice the backend
|
||||
/// would ignore can never be presented as applied.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RecordingOptions {
|
||||
/// Record audio alongside video.
|
||||
|
|
@ -94,15 +94,6 @@ pub struct RecordingOptions {
|
|||
pub fps: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for RecordingOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
audio: false,
|
||||
fps: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which recording switches this platform actually implements.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
|
|
|||
|
|
@ -454,7 +454,7 @@ fn markdown_table(rows: Vec<Vec<String>>) -> String {
|
|||
for _ in 0..columns {
|
||||
output.push_str(" --- |");
|
||||
}
|
||||
output.push_str("\n");
|
||||
output.push('\n');
|
||||
for row in rows.iter().skip(1) {
|
||||
output.push('|');
|
||||
for cell in padded(row) {
|
||||
|
|
|
|||
|
|
@ -366,7 +366,7 @@ fn to_docx_page_images(
|
|||
for page in 1..=pages.len() as u32 {
|
||||
on_page(page, pages.len() as u32, false);
|
||||
}
|
||||
return Ok(pages);
|
||||
Ok(pages)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
|
|
@ -1260,7 +1260,7 @@ mod tests {
|
|||
|
||||
fn embedded_image(path: &Path) -> (i64, i64, Option<String>) {
|
||||
let document = load(path).unwrap();
|
||||
for (_, object) in &document.objects {
|
||||
for object in document.objects.values() {
|
||||
if let Object::Stream(stream) = object {
|
||||
if is_name(stream.dict.get(b"Subtype"), b"Image") {
|
||||
let filter = stream
|
||||
|
|
@ -1615,7 +1615,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn rendered_page_names_sort_numerically_not_lexically() {
|
||||
let mut pages = vec![
|
||||
let mut pages = [
|
||||
PathBuf::from("Page-1.jpg"),
|
||||
PathBuf::from("Page-10.jpg"),
|
||||
PathBuf::from("Page-2.jpg"),
|
||||
|
|
|
|||
|
|
@ -300,7 +300,9 @@ pub fn start(
|
|||
started_at,
|
||||
stops_with_signal,
|
||||
});
|
||||
capture::dismiss_capture(app);
|
||||
// The overlay goes away, but the panel stays hidden until the recording ends:
|
||||
// a restored window would be filmed inside the selected region.
|
||||
capture::dismiss_capture_for_recording(app);
|
||||
|
||||
if let Some(window) = app.get_webview_window("recorder") {
|
||||
if let Ok(Some(monitor)) = app.primary_monitor() {
|
||||
|
|
@ -379,8 +381,18 @@ pub fn stop(app: &AppHandle, state: &AppState) -> Result<Option<RecordingInfo>,
|
|||
let Some(mut session) = guard.take() else {
|
||||
return Ok(None);
|
||||
};
|
||||
stop_process(&mut session)?;
|
||||
if !wait_for_output(&session.output) {
|
||||
let stopped = stop_process(&mut session);
|
||||
let saved = stopped.is_ok() && wait_for_output(&session.output);
|
||||
if let Some(window) = app.get_webview_window("recorder") {
|
||||
// The HUD goes down first: it is what tells `restore_windows` the recording
|
||||
// has ended, and the panel comes back with it.
|
||||
let _ = window.hide();
|
||||
}
|
||||
// The recorder held the panel down so it would not be filmed; it returns whether
|
||||
// or not the file came out, or a failed recording would lose the window.
|
||||
capture::restore_windows(app);
|
||||
stopped?;
|
||||
if !saved {
|
||||
return Err(
|
||||
"No video was saved. Allow Screen Recording for Shift in System Settings > Privacy & Security > Screen Recording, then try again."
|
||||
.into(),
|
||||
|
|
@ -390,9 +402,6 @@ pub fn stop(app: &AppHandle, state: &AppState) -> Result<Option<RecordingInfo>,
|
|||
output: session.output.to_string_lossy().to_string(),
|
||||
started_at: session.started_at,
|
||||
};
|
||||
if let Some(window) = app.get_webview_window("recorder") {
|
||||
let _ = window.hide();
|
||||
}
|
||||
match crate::settings::load(app).capture_after {
|
||||
crate::settings::CaptureAfter::Editor => {
|
||||
editor::show_recording_editor(app, &info)?;
|
||||
|
|
|
|||
|
|
@ -111,6 +111,7 @@ fn install_target(_id: &str) -> Option<InstallTarget> {
|
|||
None
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn component(
|
||||
id: &str,
|
||||
name: impl Into<String>,
|
||||
|
|
@ -174,7 +175,7 @@ fn external_component(
|
|||
fn document_pdf_component() -> RuntimeComponent {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(renderer) = files::doc_render_bridge() {
|
||||
return component(
|
||||
component(
|
||||
"document-pdf",
|
||||
"AppKit document renderer",
|
||||
"documents",
|
||||
|
|
@ -259,7 +260,7 @@ fn pdf_page_component() -> RuntimeComponent {
|
|||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let renderer = pdf::pdf_render_bridge();
|
||||
return component(
|
||||
component(
|
||||
"pdf-render",
|
||||
"PDFKit page renderer",
|
||||
"graphics",
|
||||
|
|
@ -268,7 +269,7 @@ fn pdf_page_component() -> RuntimeComponent {
|
|||
renderer.is_some(),
|
||||
None,
|
||||
renderer,
|
||||
);
|
||||
)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
|
|
@ -287,7 +288,7 @@ fn image_backend_component() -> RuntimeComponent {
|
|||
{
|
||||
let path = PathBuf::from("/usr/bin/sips");
|
||||
let available = path.is_file();
|
||||
return component(
|
||||
component(
|
||||
"image-backend",
|
||||
"macOS Core Image (sips)",
|
||||
"graphics",
|
||||
|
|
@ -296,7 +297,7 @@ fn image_backend_component() -> RuntimeComponent {
|
|||
available,
|
||||
None,
|
||||
Some(path),
|
||||
);
|
||||
)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
|
|
@ -568,11 +569,11 @@ fn os_version() -> String {
|
|||
return version;
|
||||
}
|
||||
}
|
||||
return "macOS".into();
|
||||
"macOS".into()
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
return windows_os_version();
|
||||
windows_os_version()
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
|
|
@ -584,11 +585,11 @@ fn os_version() -> String {
|
|||
return version.trim_matches('"').to_string();
|
||||
}
|
||||
}
|
||||
return "Linux".into();
|
||||
"Linux".into()
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
|
||||
{
|
||||
return env::consts::OS.into();
|
||||
env::consts::OS.into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use std::{
|
|||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
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
|
||||
|
|
@ -372,43 +372,6 @@ fn unix_day() -> i64 {
|
|||
|
||||
/// File kinds and rings a saved wedge order may name. Mirrors `ORDERABLE_KINDS`
|
||||
/// and `RadialRing` in `src/lib/radialOrder.ts`; anything else is rejected so a
|
||||
/// stale or hand-edited settings.json cannot grow entries the UI never reads.
|
||||
const WEDGE_ORDER_KINDS: [&str; 8] = [
|
||||
"image",
|
||||
"video",
|
||||
"audio",
|
||||
"pdf",
|
||||
"document",
|
||||
"presentation",
|
||||
"spreadsheet",
|
||||
"other",
|
||||
];
|
||||
const WEDGE_ORDER_RINGS: [&str; 2] = ["actions", "tools"];
|
||||
|
||||
/// Whether `"<kind>/<ring>"` names a ring the reorder screen offers. The format
|
||||
/// ring is catalogue-driven rather than a fixed list, so it has no preset.
|
||||
fn is_wedge_order_key(key: &str) -> bool {
|
||||
match key.split_once('/') {
|
||||
Some((kind, ring)) => {
|
||||
WEDGE_ORDER_KINDS.contains(&kind) && WEDGE_ORDER_RINGS.contains(&ring)
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop blank and repeated ids, keeping first appearance. The ring ignores ids it
|
||||
/// does not offer, so no further validation is needed.
|
||||
fn normalize_wedge_order(order: &[String]) -> Vec<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
order
|
||||
.iter()
|
||||
.map(|id| id.trim())
|
||||
.filter(|id| !id.is_empty())
|
||||
.filter(|id| seen.insert((*id).to_string()))
|
||||
.map(|id| id.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the daily startup probe may run. The day counter is stored rather than
|
||||
/// an instant so a restart cannot spend the day's check again.
|
||||
pub fn update_check_due(app: &AppHandle, interval: std::time::Duration) -> bool {
|
||||
|
|
@ -473,38 +436,6 @@ pub async fn get_wedge_orders(app: AppHandle) -> Result<HashMap<String, Vec<Stri
|
|||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Store the wedge order for one ring of one file kind. An empty list restores the
|
||||
/// built-in order, so "reset" needs no separate flag. The radial window listens for
|
||||
/// the broadcast so a change shows up in the next gesture without a restart.
|
||||
#[tauri::command]
|
||||
pub async fn set_wedge_order(
|
||||
app: AppHandle,
|
||||
kind: String,
|
||||
ring: String,
|
||||
order: Vec<String>,
|
||||
) -> Result<SettingsSnapshot, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let key = format!("{kind}/{ring}");
|
||||
if !is_wedge_order_key(&key) {
|
||||
return Err(format!("Unknown radial ring: {key}"));
|
||||
}
|
||||
let cleaned = normalize_wedge_order(&order);
|
||||
update_settings(&app, |settings| {
|
||||
if cleaned.is_empty() {
|
||||
settings.wedge_orders.remove(&key);
|
||||
} else {
|
||||
settings.wedge_orders.insert(key, cleaned);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let orders = load(&app).wedge_orders;
|
||||
let _ = app.emit("settings://wedge-orders", orders);
|
||||
snapshot(&app)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
/// Stamp the daily probe so the next launch waits for the interval instead of
|
||||
/// reaching the network again.
|
||||
pub fn note_update_check(app: &AppHandle) {
|
||||
|
|
@ -758,22 +689,4 @@ mod tests {
|
|||
assert!(directory.is_dir());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wedge_orders_are_limited_to_the_rings_the_ui_offers() {
|
||||
assert!(is_wedge_order_key("image/tools"));
|
||||
assert!(is_wedge_order_key("spreadsheet/actions"));
|
||||
assert!(is_wedge_order_key("other/tools"));
|
||||
// The format ring follows the catalogue, and an unknown kind is a typo.
|
||||
assert!(!is_wedge_order_key("image/formats"));
|
||||
assert!(!is_wedge_order_key("archive/tools"));
|
||||
assert!(!is_wedge_order_key("image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wedge_orders_drop_blanks_and_duplicates_in_order() {
|
||||
let cleaned =
|
||||
normalize_wedge_order(&[" crop ".into(), "crop".into(), String::new(), "ocr".into()]);
|
||||
assert_eq!(cleaned, vec!["crop".to_string(), "ocr".to_string()]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -182,7 +182,7 @@ impl ShareState {
|
|||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
peers.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
peers.sort_by_key(|peer| peer.name.to_lowercase());
|
||||
peers
|
||||
}
|
||||
|
||||
|
|
@ -757,10 +757,10 @@ fn beacon_loop(app: &AppHandle, mut sock: UdpSocket, local: &Beacon) {
|
|||
let mut last_peer_check = opened;
|
||||
|
||||
while opened.elapsed() < SOCKET_LIFETIME {
|
||||
let state = app.state::<ShareState>();
|
||||
let discoverable = state.is_enabled();
|
||||
let refresh = state.take_refresh_request();
|
||||
drop(state);
|
||||
let (discoverable, refresh) = {
|
||||
let state = app.state::<ShareState>();
|
||||
(state.is_enabled(), state.take_refresh_request())
|
||||
};
|
||||
if discoverable && (refresh || last_announce.elapsed() >= BEACON_INTERVAL) {
|
||||
announce(&sock, &payload);
|
||||
let destinations = app.state::<ShareState>().peer_destinations();
|
||||
|
|
@ -776,9 +776,10 @@ fn beacon_loop(app: &AppHandle, mut sock: UdpSocket, local: &Beacon) {
|
|||
|
||||
match sock.recv_from(&mut buffer) {
|
||||
Ok((length, from)) => {
|
||||
let state = app.state::<ShareState>();
|
||||
let received = register_beacon(&state, &buffer[..length], from, local);
|
||||
drop(state);
|
||||
let received = {
|
||||
let state = app.state::<ShareState>();
|
||||
register_beacon(&state, &buffer[..length], from, local)
|
||||
};
|
||||
if let Some(received) = received {
|
||||
if received.fresh {
|
||||
eprintln!("Shift share: found {} on {}", received.name, from.ip());
|
||||
|
|
@ -1264,7 +1265,7 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
|
|||
},
|
||||
);
|
||||
// Reuse the result pipeline so received files land in the history library.
|
||||
crate::history::record(app, &[path.clone()]);
|
||||
crate::history::record(app, std::slice::from_ref(&path));
|
||||
let _ = app.emit(
|
||||
"app://file-result",
|
||||
serde_json::json!({ "outputs": [path], "message": name }),
|
||||
|
|
@ -1287,11 +1288,6 @@ pub fn share_answer(
|
|||
state.resolve_pending(&transfer_id, accepted).is_some()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn share_peers(state: tauri::State<'_, ShareState>) -> Vec<Peer> {
|
||||
state.peers_visible()
|
||||
}
|
||||
|
||||
/// Ask the long-lived discovery socket for peers right away. A second socket on
|
||||
/// Windows cannot bind the shared port, and on unix it can steal the reply, so the
|
||||
/// panel wakes the existing thread instead.
|
||||
|
|
@ -1362,6 +1358,7 @@ pub async fn share_send(
|
|||
.map_err(|error| format!("share send failed: {error}"))?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn send_file(
|
||||
app: &AppHandle,
|
||||
transfer_id: &str,
|
||||
|
|
|
|||
|
|
@ -140,11 +140,7 @@ pub fn manifest_url() -> String {
|
|||
}
|
||||
|
||||
fn platform_key() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
"macos" => "macos",
|
||||
"windows" => "windows",
|
||||
other => other,
|
||||
}
|
||||
std::env::consts::OS
|
||||
}
|
||||
|
||||
/// Manifest keys a build accepts, most specific first. An ARM64 Windows build
|
||||
|
|
@ -681,7 +677,7 @@ pub async fn update_download(app: AppHandle) -> Result<UpdateStatus, String> {
|
|||
remembered_signed(&reporter),
|
||||
);
|
||||
status.state = "ready".into();
|
||||
status.message = format!("{actual}");
|
||||
status.message = actual;
|
||||
Ok(publish(&reporter, status))
|
||||
})
|
||||
.await
|
||||
|
|
@ -888,42 +884,45 @@ pub async fn update_install(app: AppHandle) -> Result<String, String> {
|
|||
quit_for_update(&app);
|
||||
return Ok(path);
|
||||
}
|
||||
// Reaching here means the update cannot be applied in place: a Linux build
|
||||
// has no in-place install, and a macOS binary run straight out of `target/`
|
||||
// has no bundle to replace. Both get the artifact opened instead.
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::process::command("/usr/bin/open")
|
||||
.arg(&artifact)
|
||||
.status()
|
||||
.map_err(|error| format!("Could not open the update: {error}"))?;
|
||||
// Linux bundles are not installed in place. An AppImage carries its own runtime
|
||||
// but arrives without the executable bit, which is enough to make a double-click
|
||||
// fail, so set that bit and start it directly. A .deb means nothing on its own
|
||||
// and goes to whatever handler the desktop registered for the package format.
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let bundle = artifact.clone();
|
||||
if bundle
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("appimage"))
|
||||
// Reaching here means the update cannot be applied in place: a Linux build
|
||||
// has no in-place install, and a macOS binary run straight out of `target/`
|
||||
// has no bundle to replace. Both get the artifact opened instead.
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::process::command("/usr/bin/open")
|
||||
.arg(&artifact)
|
||||
.status()
|
||||
.map_err(|error| format!("Could not open the update: {error}"))?;
|
||||
// Linux bundles are not installed in place. An AppImage carries its own runtime
|
||||
// but arrives without the executable bit, which is enough to make a double-click
|
||||
// fail, so set that bit and start it directly. A .deb means nothing on its own
|
||||
// and goes to whatever handler the desktop registered for the package format.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(&bundle)
|
||||
.map_err(|error| format!("Could not read the update: {error}"))?
|
||||
.permissions()
|
||||
.mode()
|
||||
| 0o111;
|
||||
fs::set_permissions(&bundle, fs::Permissions::from_mode(mode))
|
||||
.map_err(|error| format!("Could not make the update runnable: {error}"))?;
|
||||
crate::process::command(&bundle)
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not start the update: {error}"))?;
|
||||
} else {
|
||||
crate::files::open_path(&bundle)
|
||||
.map_err(|error| format!("Could not open the update: {error}"))?;
|
||||
let bundle = artifact.clone();
|
||||
if bundle
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("appimage"))
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(&bundle)
|
||||
.map_err(|error| format!("Could not read the update: {error}"))?
|
||||
.permissions()
|
||||
.mode()
|
||||
| 0o111;
|
||||
fs::set_permissions(&bundle, fs::Permissions::from_mode(mode))
|
||||
.map_err(|error| format!("Could not make the update runnable: {error}"))?;
|
||||
crate::process::command(&bundle)
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not start the update: {error}"))?;
|
||||
} else {
|
||||
crate::files::open_path(&bundle)
|
||||
.map_err(|error| format!("Could not open the update: {error}"))?;
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
Ok(path)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Update install failed: {error}"))?
|
||||
|
|
@ -1123,7 +1122,7 @@ mod tests {
|
|||
// Three distinct states, because collapsing "unusable" into "absent" would
|
||||
// turn a signed channel into an unsigned one while the UI still claimed the
|
||||
// build verifies signatures.
|
||||
assert_eq!(key_from_hex("").unwrap().is_none(), true, "absent");
|
||||
assert!(key_from_hex("").unwrap().is_none(), "absent");
|
||||
assert!(key_from_hex(TEST_PUBKEY).unwrap().is_some(), "usable");
|
||||
// Not 32 bytes of hex.
|
||||
assert!(key_from_hex("deadbeef").unwrap_err().contains("32 bytes"));
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Shift",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"identifier": "app.nex.shift",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
|
@ -116,7 +116,7 @@
|
|||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"targets": ["app", "dmg", "nsis"],
|
||||
"category": "Utility",
|
||||
"shortDescription": "Radial file utility, capture and OCR.",
|
||||
"longDescription": "Shift brings Tangerine-style radial file actions, CleanShot-style capture, screen recording and local OCR to macOS and Windows.",
|
||||
|
|
|
|||
|
|
@ -66,8 +66,6 @@ import type {
|
|||
SwitchUpdate,
|
||||
WriteCheck,
|
||||
} from "../types";
|
||||
import type { FileKind, RadialRing } from "../lib/radialOrder";
|
||||
|
||||
const FALLBACK_SETTINGS: AppSettings = {
|
||||
fileOutputMode: "alongside",
|
||||
fileOutputDir: "~/Downloads/Shift",
|
||||
|
|
@ -247,6 +245,9 @@ export function MainWindow() {
|
|||
const [dropAction, setDropAction] = useState<DropAction | null>(null);
|
||||
const [hotkeys, setHotkeys] = useState<HotkeyStatus | null>(null);
|
||||
const dropTargets = useRef<Partial<Record<DropAction, HTMLElement | null>>>({});
|
||||
// Recent rows can still be handed to other apps, but dropping one back onto
|
||||
// Shift's own action buttons is intentionally unsupported.
|
||||
const recentDragActive = useRef(false);
|
||||
const runtimeCheckStarted = useRef(false);
|
||||
|
||||
async function finishSetup() {
|
||||
|
|
@ -592,6 +593,7 @@ export function MainWindow() {
|
|||
if (isTauri()) {
|
||||
void getCurrentWebview()
|
||||
.onDragDropEvent((event) => {
|
||||
if (recentDragActive.current) return;
|
||||
if (event.payload.type === "enter") {
|
||||
setDragging(true);
|
||||
setDropAction(actionAt(event.payload.position));
|
||||
|
|
@ -883,17 +885,21 @@ export function MainWindow() {
|
|||
onDragStart={(event) => {
|
||||
// A row leaves Shift as the file itself: WebKit turns the file URL
|
||||
// in text/uri-list into a real file drop for Finder and friends,
|
||||
// while the plain path keeps editors and our own drop zones happy.
|
||||
// while the plain path remains readable for editors.
|
||||
event.dataTransfer.effectAllowed = "copy";
|
||||
recentDragActive.current = true;
|
||||
for (const [type, value] of Object.entries(dragOutPayload(item.path))) {
|
||||
event.dataTransfer.setData(type, value);
|
||||
}
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
recentDragActive.current = false;
|
||||
}}
|
||||
>
|
||||
<button
|
||||
className="home-recent-main"
|
||||
onClick={() => void api.openInEditor(item.path)}
|
||||
title={t("dragOutHint")}
|
||||
title={t("open")}
|
||||
>
|
||||
<RecentThumb item={item} />
|
||||
<span>
|
||||
|
|
@ -911,7 +917,7 @@ export function MainWindow() {
|
|||
void history.setPinned(item.path, !item.pinned).catch(() => undefined)
|
||||
}
|
||||
>
|
||||
<Star size={13} />
|
||||
<Star size={13} fill={item.pinned ? "currentColor" : "none"} />
|
||||
</button>
|
||||
<button title={t("sendTo")} onClick={() => setSharePaths([item.path])}>
|
||||
<Send size={13} />
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Copy, X } from "lucide-react";
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { decodeHexParam } from "../lib/utils";
|
||||
|
||||
interface PinnedPreview {
|
||||
id: number;
|
||||
|
|
@ -14,20 +15,10 @@ interface PinnedPreview {
|
|||
height: number;
|
||||
}
|
||||
|
||||
function decodePath(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 function PinnedImage() {
|
||||
const { t } = useI18n();
|
||||
const [path, setPath] = useState(() =>
|
||||
decodePath(new URLSearchParams(window.location.search).get("path")),
|
||||
decodeHexParam(new URLSearchParams(window.location.search).get("path")),
|
||||
);
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
|
|||
|
|
@ -46,11 +46,10 @@ import {
|
|||
defaultWedgeIds,
|
||||
orderWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
type WedgeOrders,
|
||||
} from "../lib/radialOrder";
|
||||
import { recognizeImage } from "../lib/ocr";
|
||||
import { basename, formatBytes } from "../lib/utils";
|
||||
import { formatBytes } from "../lib/utils";
|
||||
import type { FileInfo, RadialContext } from "../types";
|
||||
import { useI18n } from "../i18n";
|
||||
import { SharePanel } from "./SharePanel";
|
||||
|
|
@ -121,9 +120,8 @@ function sectorAt(x: number, y: number, count: number): number | null {
|
|||
}
|
||||
|
||||
/**
|
||||
* Icon for every wedge the rings can show. Labels come from `wedgeLabelKey` in
|
||||
* `src/lib/radialOrder.ts`, which is where the wedge catalogue and the reorder screen
|
||||
* in Settings agree on wording.
|
||||
* Icon for every wedge the rings can show. Labels map onto the catalogue ids in
|
||||
* `src/lib/radialOrder.ts`, which is the single source for the wedge rotation.
|
||||
*/
|
||||
const WEDGE_ICONS: Record<string, IconType> = {
|
||||
addBackground: ImagePlus,
|
||||
|
|
@ -162,6 +160,18 @@ if (wedgesWithoutIcons.length > 0) {
|
|||
console.warn("radial wedges without an icon:", wedgesWithoutIcons);
|
||||
}
|
||||
|
||||
const WEDGE_LABEL_KEYS: Record<string, string> = {
|
||||
grayscale: "blackWhite",
|
||||
resizeHalf: "halfSize",
|
||||
pdfOcr: "ocr",
|
||||
text: "extractText",
|
||||
metadata: "stripMetadata",
|
||||
};
|
||||
|
||||
function wedgeLabelKey(id: string): string {
|
||||
return WEDGE_LABEL_KEYS[id] ?? id;
|
||||
}
|
||||
|
||||
function formatIcon(format: string): IconType {
|
||||
if (format === "PDF" || format === "TXT" || format === "MD" || format === "DOCX") {
|
||||
return FileText;
|
||||
|
|
@ -351,14 +361,11 @@ export function RadialMenu() {
|
|||
});
|
||||
return;
|
||||
}
|
||||
// Saved wedge orders arrive with the context and again whenever Settings edits
|
||||
// one, so a reorder takes effect on the very next gesture.
|
||||
// Saved wedge orders still apply to builds upgraded from a version that had an
|
||||
// in-app editor, so the ring reads them once when this window opens.
|
||||
void api.getWedgeOrders().then((next) => {
|
||||
if (!disposed) setOrders(next);
|
||||
});
|
||||
void listen<WedgeOrders>("settings://wedge-orders", (event) => {
|
||||
setOrders(event.payload);
|
||||
}).then((unlisten) => unlisteners.push(unlisten));
|
||||
void api.getRadialContext().then((next) => {
|
||||
if (!disposed) applyContext(next);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,126 +0,0 @@
|
|||
import { ArrowDown, ArrowUp, RotateCcw } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import {
|
||||
ORDERABLE_KINDS,
|
||||
hasCustomOrder,
|
||||
isOrderDirty,
|
||||
moveWedge,
|
||||
orderWedgeIds,
|
||||
presetWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
type FileKind,
|
||||
type RadialRing,
|
||||
type WedgeOrders,
|
||||
} from "../lib/radialOrder";
|
||||
|
||||
/**
|
||||
* The reorder screen for the radial rings.
|
||||
*
|
||||
* It edits one preset at a time — a file kind plus a ring — and can only rearrange the
|
||||
* wedges that ring actually offers, so a preset can never invent an action. The list is
|
||||
* always the live catalogue in a saved order; saving an empty list (Reset) hands the
|
||||
* ring back to the built-in order. Every rule the screen applies lives in
|
||||
* `src/lib/radialOrder.ts`, which keeps them testable without mounting this panel.
|
||||
*/
|
||||
export function RadialOrderPanel({
|
||||
orders,
|
||||
onApply,
|
||||
}: {
|
||||
orders: WedgeOrders;
|
||||
onApply: (kind: FileKind, ring: RadialRing, order: string[]) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [kind, setKind] = useState<FileKind>("image");
|
||||
const [ring, setRing] = useState<RadialRing>("actions");
|
||||
const [draft, setDraft] = useState<string[]>([]);
|
||||
|
||||
const catalogue = useMemo(() => presetWedgeIds(kind, ring), [ring, kind]);
|
||||
const saved = savedOrderFor(orders, kind, ring);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(orderWedgeIds(catalogue, saved));
|
||||
}, [catalogue, saved]);
|
||||
|
||||
const custom = Boolean(saved);
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="home-settings-section">
|
||||
<div className="home-section-title">{t("radialKind")}</div>
|
||||
<div className="radial-kind-grid">
|
||||
{ORDERABLE_KINDS.map((entry) => (
|
||||
<button
|
||||
key={entry}
|
||||
className={entry === kind ? "is-active" : ""}
|
||||
onClick={() => setKind(entry)}
|
||||
>
|
||||
{t(`kind_${entry}`)}
|
||||
{hasCustomOrder(orders, entry) ? <span className="radial-kind-dot" /> : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="home-segment">
|
||||
<button
|
||||
className={ring === "actions" ? "is-active" : ""}
|
||||
onClick={() => setRing("actions")}
|
||||
>
|
||||
{t("ringActions")}
|
||||
</button>
|
||||
<button className={ring === "tools" ? "is-active" : ""} onClick={() => setRing("tools")}>
|
||||
{t("ringTools")}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="home-settings-section">
|
||||
<div className="runtime-section-head">
|
||||
<div className="home-section-title">{t("radialOrder", { count: draft.length })}</div>
|
||||
<button
|
||||
className="settings-link"
|
||||
onClick={() => onApply(kind, ring, [])}
|
||||
disabled={!custom}
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
{t("reset")}
|
||||
</button>
|
||||
</div>
|
||||
<p className="runtime-summary">{t("radialOrderBody")}</p>
|
||||
<ol className="radial-order-list">
|
||||
{draft.map((id, index) => (
|
||||
<li className="radial-order-row" key={id}>
|
||||
<span className="radial-order-index">{index + 1}</span>
|
||||
<span className="radial-order-label">{t(wedgeLabelKey(id))}</span>
|
||||
<span className="radial-order-buttons">
|
||||
<button
|
||||
onClick={() => setDraft(moveWedge(draft, index, -1))}
|
||||
disabled={index === 0}
|
||||
title={t("moveUp")}
|
||||
aria-label={t("moveUp")}
|
||||
>
|
||||
<ArrowUp size={12} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDraft(moveWedge(draft, index, 1))}
|
||||
disabled={index === draft.length - 1}
|
||||
title={t("moveDown")}
|
||||
aria-label={t("moveDown")}
|
||||
>
|
||||
<ArrowDown size={12} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<button
|
||||
className="settings-wide-button radial-order-save"
|
||||
onClick={() => onApply(kind, ring, draft)}
|
||||
disabled={!isOrderDirty(draft, catalogue, saved)}
|
||||
>
|
||||
{t("radialOrderSave")}
|
||||
</button>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import {
|
|||
import { useEffect, useRef, useState, type DragEvent } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { parseSharePaths, SHARE_PATHS_TYPE } from "../lib/dragOut";
|
||||
import { basename, dirname, formatBytes } from "../lib/utils";
|
||||
import type { SharePeer, ShareTransfer } from "../types";
|
||||
|
||||
|
|
@ -177,17 +178,8 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) {
|
|||
}
|
||||
|
||||
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;
|
||||
const raw = event.dataTransfer.getData(SHARE_PATHS_TYPE);
|
||||
return parseSharePaths(raw) ?? fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
@ -259,7 +251,7 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) {
|
|||
const files = checked ? selectedPaths : [path];
|
||||
event.dataTransfer.effectAllowed = "copy";
|
||||
event.dataTransfer.setData(
|
||||
"application/x-shift-share-paths",
|
||||
SHARE_PATHS_TYPE,
|
||||
JSON.stringify(files),
|
||||
);
|
||||
}}
|
||||
|
|
|
|||
51
src/i18n.ts
51
src/i18n.ts
|
|
@ -158,9 +158,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
shiftDrop: "ShiftDrop",
|
||||
autostart: "Launch at login",
|
||||
hotkeysNotLive:
|
||||
"macOS refused these shortcuts, usually because another app already uses them. Close the conflicting app and retry.",
|
||||
"Shift could not register these shortcuts, usually because another app already uses them. Close the conflicting app and retry.",
|
||||
hotkeysDead: "Another Shift is running, so this window's shortcuts are inactive.",
|
||||
hotkeysFix: "Quit the other copies and reclaim the shortcuts",
|
||||
hotkeysFix: "Quit other Shift copies and reclaim the shortcuts",
|
||||
accessCheck: "Write access",
|
||||
checking: "Checking…",
|
||||
checkAccess: "Check folders",
|
||||
|
|
@ -218,23 +218,6 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
updateBody:
|
||||
"Releases come from this repository’s release branch. Every download is re-hashed and must match the manifest before it can be installed. Installing replaces this copy and restarts it; a conversion still running is interrupted.",
|
||||
radial: "Radial rings",
|
||||
radialKind: "File type preset",
|
||||
ringActions: "Actions",
|
||||
ringTools: "Tools",
|
||||
radialOrder: "Order ({count} wedges)",
|
||||
radialOrderBody:
|
||||
"The ring only ever shows what this file type can do; this list decides where each wedge sits. Send always stays last.",
|
||||
radialOrderSave: "Save order",
|
||||
moveUp: "Move up",
|
||||
moveDown: "Move down",
|
||||
kind_image: "Images",
|
||||
kind_video: "Video",
|
||||
kind_audio: "Audio",
|
||||
kind_pdf: "PDF",
|
||||
kind_document: "Documents",
|
||||
kind_presentation: "Slides",
|
||||
kind_spreadsheet: "Spreadsheets",
|
||||
kind_other: "Other files",
|
||||
setupTitle: "Before you start",
|
||||
setupIntro: "Shift works offline and installs nothing. These are the four things that can quietly stop it working on this machine.",
|
||||
setupRecheck: "Run the checks again",
|
||||
|
|
@ -264,10 +247,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
clearHistory: "Clear",
|
||||
searchHistory: "Search captures and results",
|
||||
historyNoMatches: "Nothing matches “{query}”.",
|
||||
pinToRecent: "Keep in the library",
|
||||
unpinFromRecent: "Stop keeping",
|
||||
pinToRecent: "Favorite",
|
||||
unpinFromRecent: "Unfavorite",
|
||||
forget: "Remove from the list",
|
||||
dragOutHint: "Click to open, or drag this row out to hand over the file",
|
||||
captureAfter: "After capture",
|
||||
captureAfterCard: "Result card",
|
||||
captureAfterEditor: "Open editor",
|
||||
|
|
@ -430,9 +412,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
dragRings: "拖拽圆环",
|
||||
shiftDrop: "ShiftDrop",
|
||||
autostart: "开机时启动",
|
||||
hotkeysNotLive: "macOS 拒绝了这些快捷键,通常是被其他应用占用了。关闭冲突的应用后重试。",
|
||||
hotkeysNotLive: "Shift 未能注册这些快捷键,通常是被其他应用占用了。关闭冲突的应用后重试。",
|
||||
hotkeysDead: "另一个 Shift 正在运行,本窗口的快捷键无效。",
|
||||
hotkeysFix: "退出其他副本并重新接管快捷键",
|
||||
hotkeysFix: "退出其他 Shift 副本并重新接管快捷键",
|
||||
accessCheck: "写入权限",
|
||||
checking: "检测中…",
|
||||
checkAccess: "检测目录",
|
||||
|
|
@ -488,22 +470,6 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
updateBody:
|
||||
"更新包来自本仓库的 release 分支。下载后会重新计算 SHA256,只有与清单一致才允许安装。安装会替换当前版本并自动重启,正在进行的转换会被中断。",
|
||||
radial: "环形菜单",
|
||||
radialKind: "文件类型预设",
|
||||
ringActions: "快捷操作",
|
||||
ringTools: "工具",
|
||||
radialOrder: "顺序({count} 项)",
|
||||
radialOrderBody: "环形菜单只显示这种文件真正支持的操作,这里决定每一项的位置。“发送”始终排在最后。",
|
||||
radialOrderSave: "保存顺序",
|
||||
moveUp: "上移",
|
||||
moveDown: "下移",
|
||||
kind_image: "图片",
|
||||
kind_video: "视频",
|
||||
kind_audio: "音频",
|
||||
kind_pdf: "PDF",
|
||||
kind_document: "文档",
|
||||
kind_presentation: "演示文稿",
|
||||
kind_spreadsheet: "表格",
|
||||
kind_other: "其他文件",
|
||||
setupTitle: "开始前先检查",
|
||||
setupIntro: "Shift 全程离线运行,也不会往系统里装任何东西。以下四项是唯一可能让它在当前电脑上悄悄失效的地方。",
|
||||
setupRecheck: "重新检查",
|
||||
|
|
@ -532,10 +498,9 @@ const messages: Record<Lang, Record<string, string>> = {
|
|||
clearHistory: "清空",
|
||||
searchHistory: "搜索截图与结果",
|
||||
historyNoMatches: "没有与“{query}”匹配的记录。",
|
||||
pinToRecent: "保留在库中",
|
||||
unpinFromRecent: "取消保留",
|
||||
pinToRecent: "收藏",
|
||||
unpinFromRecent: "取消收藏",
|
||||
forget: "从列表移除",
|
||||
dragOutHint: "点击打开,或把这一行拖出去即可交付文件",
|
||||
captureAfter: "截图后",
|
||||
captureAfterCard: "结果卡片",
|
||||
captureAfterEditor: "打开编辑器",
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import type {
|
|||
UpdateStatus,
|
||||
WriteCheck,
|
||||
} from "../types";
|
||||
import type { FileKind, RadialRing, WedgeOrders } from "./radialOrder";
|
||||
import type { WedgeOrders } from "./radialOrder";
|
||||
|
||||
interface FileActionResultEvent {
|
||||
jobId: string;
|
||||
|
|
@ -119,7 +119,6 @@ export const api = {
|
|||
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"),
|
||||
|
|
@ -148,8 +147,6 @@ export const api = {
|
|||
invoke<SwitchState>("set_update_check_enabled", { enabled }),
|
||||
setSetupReviewed: (reviewed: boolean) => invoke<boolean>("set_setup_reviewed", { reviewed }),
|
||||
getWedgeOrders: () => invoke<WedgeOrders>("get_wedge_orders"),
|
||||
setWedgeOrder: (kind: FileKind, ring: RadialRing, order: string[]) =>
|
||||
invoke<AppSettings>("set_wedge_order", { kind, ring, order }),
|
||||
updateCheck: () =>
|
||||
invoke<{ status: UpdateStatus; downloadReady: boolean }>("update_check"),
|
||||
updateStatus: () => invoke<UpdateStatus | null>("update_status"),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { dragOutPayload, fileUrl } from "./dragOut.ts";
|
||||
import { dragOutPayload, fileUrl, parseSharePaths } from "./dragOut.ts";
|
||||
|
||||
test("unix paths become file URLs with separators kept", () => {
|
||||
assert.equal(fileUrl("/Users/me/Shift/photo.png"), "file:///Users/me/Shift/photo.png");
|
||||
|
|
@ -23,15 +23,25 @@ test("repeated separators collapse", () => {
|
|||
assert.equal(fileUrl("/Users//me///x.png"), "file:///Users/me/x.png");
|
||||
});
|
||||
|
||||
test("a row is offered as uri-list, plain path and share paths", () => {
|
||||
test("a row is offered as a file URL and a plain path", () => {
|
||||
const payload = dragOutPayload("/tmp/a.png");
|
||||
assert.deepEqual(payload, {
|
||||
"text/uri-list": "file:///tmp/a.png",
|
||||
"text/plain": "/tmp/a.png",
|
||||
"application/x-shift-share-paths": JSON.stringify(["/tmp/a.png"]),
|
||||
});
|
||||
});
|
||||
|
||||
test("unc shares are readable too", () => {
|
||||
assert.equal(fileUrl("\\\\server\\share\\a.pdf"), "file:///server/share/a.pdf");
|
||||
});
|
||||
|
||||
test("internal drag payloads round-trip as paths", () => {
|
||||
assert.deepEqual(parseSharePaths(JSON.stringify(["/tmp/a.png"])), ["/tmp/a.png"]);
|
||||
assert.deepEqual(parseSharePaths(JSON.stringify([])), []);
|
||||
});
|
||||
|
||||
test("malformed internal drag payloads are rejected", () => {
|
||||
assert.equal(parseSharePaths(""), null);
|
||||
assert.equal(parseSharePaths("{not json"), null);
|
||||
assert.equal(parseSharePaths(JSON.stringify(["ok", 2])), null);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,9 +3,8 @@
|
|||
*
|
||||
* A row is dragged as a file URL rather than as text: WebKit promotes a `file://`
|
||||
* entry in `text/uri-list` into a real file drop, so Finder, mail composers and chat
|
||||
* apps receive the file instead of a path string. Plain text still carries the path for
|
||||
* editors, and Shift's own drop zones read the internal type so a row can be dragged
|
||||
* back onto the ring.
|
||||
* apps receive the file instead of a path string. Plain text still carries the path
|
||||
* for editors.
|
||||
*/
|
||||
const SHARE_PATH_TYPE = "application/x-shift-share-paths";
|
||||
|
||||
|
|
@ -22,14 +21,27 @@ export function fileUrl(path: string): string {
|
|||
return `file:///${segments.join("/")}`;
|
||||
}
|
||||
|
||||
/** The three flavours a receiving application can pick up, keyed by MIME type. */
|
||||
/** The flavours a receiving application can pick up, keyed by MIME type. */
|
||||
export function dragOutPayload(path: string): Record<string, string> {
|
||||
const uri = fileUrl(path);
|
||||
return {
|
||||
"text/uri-list": uri,
|
||||
"text/plain": path,
|
||||
[SHARE_PATH_TYPE]: JSON.stringify([path]),
|
||||
};
|
||||
}
|
||||
|
||||
/** Read the internal path list from an in-app drag payload. */
|
||||
export function parseSharePaths(raw: string): string[] | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (Array.isArray(parsed) && parsed.every((path) => typeof path === "string")) {
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
// Malformed payloads fall through so callers can use their own default.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const SHARE_PATHS_TYPE = SHARE_PATH_TYPE;
|
||||
|
|
|
|||
|
|
@ -30,10 +30,3 @@ export async function recognizeImage(
|
|||
confidence: Number(result.data.confidence || 0),
|
||||
};
|
||||
}
|
||||
|
||||
export async function disposeOcrWorker() {
|
||||
if (!workerPromise) return;
|
||||
const worker = await workerPromise.catch(() => null);
|
||||
workerPromise = null;
|
||||
await worker?.terminate?.();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,13 +5,8 @@ import {
|
|||
ORDERABLE_KINDS,
|
||||
WEDGE_ACTION_IDS,
|
||||
defaultWedgeIds,
|
||||
hasCustomOrder,
|
||||
isOrderDirty,
|
||||
moveWedge,
|
||||
orderWedgeIds,
|
||||
presetWedgeIds,
|
||||
savedOrderFor,
|
||||
wedgeLabelKey,
|
||||
wedgeOrderKey,
|
||||
} from "./radialOrder.ts";
|
||||
|
||||
|
|
@ -95,14 +90,6 @@ test("no saved order means the default order", () => {
|
|||
assert.deepEqual(orderWedgeIds(ids, []), ids);
|
||||
});
|
||||
|
||||
test("moving a wedge clamps at both ends", () => {
|
||||
const ids = ["a", "b", "c"];
|
||||
assert.deepEqual(moveWedge(ids, 0, -1), ids);
|
||||
assert.deepEqual(moveWedge(ids, 2, 1), ids);
|
||||
assert.deepEqual(moveWedge(ids, 1, -1), ["b", "a", "c"]);
|
||||
assert.deepEqual(moveWedge(ids, 1, 1), ["a", "c", "b"]);
|
||||
});
|
||||
|
||||
test("orders are stored per kind and ring", () => {
|
||||
assert.equal(wedgeOrderKey("image", "tools"), "image/tools");
|
||||
const orders = { "image/tools": ["crop"] };
|
||||
|
|
@ -113,33 +100,6 @@ test("orders are stored per kind and ring", () => {
|
|||
assert.equal(savedOrderFor(undefined, "image", "tools"), undefined);
|
||||
});
|
||||
|
||||
test("wedge labels reuse the ring's own wording", () => {
|
||||
assert.equal(wedgeLabelKey("grayscale"), "blackWhite");
|
||||
assert.equal(wedgeLabelKey("resizeHalf"), "halfSize");
|
||||
assert.equal(wedgeLabelKey("pdfOcr"), "ocr");
|
||||
assert.equal(wedgeLabelKey("text"), "extractText");
|
||||
assert.equal(wedgeLabelKey("compress"), "compress");
|
||||
// The wedge strips, so the ring says so rather than offering a lookup.
|
||||
assert.equal(wedgeLabelKey("metadata"), "stripMetadata");
|
||||
});
|
||||
|
||||
test("a kind is marked custom once any of its rings is reordered", () => {
|
||||
const orders = { "image/tools": ["crop"], "pdf/actions": ["split"] };
|
||||
assert.equal(hasCustomOrder(orders, "image"), true);
|
||||
assert.equal(hasCustomOrder(orders, "pdf"), true);
|
||||
assert.equal(hasCustomOrder(orders, "video"), false);
|
||||
assert.equal(hasCustomOrder({ "image/tools": [] }, "image"), false);
|
||||
});
|
||||
|
||||
test("saving is offered only when the draft differs from storage", () => {
|
||||
const catalogue = ["compress", "crop", "ocr"];
|
||||
assert.equal(isOrderDirty(catalogue, catalogue), false);
|
||||
assert.equal(isOrderDirty(["crop", "compress", "ocr"], catalogue), true);
|
||||
// Reordering into the same visible sequence is not a change.
|
||||
assert.equal(isOrderDirty(["crop", "compress", "ocr"], catalogue, ["crop"]), false);
|
||||
assert.equal(isOrderDirty(["crop", "compress"], catalogue, ["crop"]), true);
|
||||
});
|
||||
|
||||
test("the derived action list covers every catalogue wedge", () => {
|
||||
// Send is appended by the menu, so it is deliberately absent.
|
||||
assert.equal(WEDGE_ACTION_IDS.includes("send"), false);
|
||||
|
|
@ -152,24 +112,3 @@ test("the derived action list covers every catalogue wedge", () => {
|
|||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a preset shows the wedges the ring offers for that kind", () => {
|
||||
// Convert only appears where a typical source of the kind has targets.
|
||||
assert.equal(presetWedgeIds("image", "actions").includes("convert"), true);
|
||||
assert.equal(presetWedgeIds("image", "actions").includes("crop"), true);
|
||||
assert.equal(presetWedgeIds("video", "tools").includes("extractAudio"), true);
|
||||
assert.equal(presetWedgeIds("pdf", "tools").includes("split"), true);
|
||||
assert.equal(presetWedgeIds("document", "actions").includes("convert"), true);
|
||||
// Merge follows the multi-select rule, so the preset always shows it.
|
||||
assert.equal(presetWedgeIds("image", "tools").at(-1), "merge");
|
||||
assert.equal(presetWedgeIds("audio", "tools").includes("merge"), false);
|
||||
// Send is appended after ordering, so it never appears in the editable list.
|
||||
assert.equal(presetWedgeIds("image", "tools").includes("send"), false);
|
||||
});
|
||||
|
||||
test("every kind has a preset for both editable rings", () => {
|
||||
for (const kind of ORDERABLE_KINDS) {
|
||||
assert.ok(presetWedgeIds(kind, "actions").length > 0, kind);
|
||||
assert.ok(presetWedgeIds(kind, "tools").length > 0, kind);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,16 +1,9 @@
|
|||
/**
|
||||
* The wedge catalogue for the radial rings, plus the ordering rules behind the
|
||||
* "custom radial order" setting.
|
||||
*
|
||||
* The rings used to hard-code their wedge lists inline in RadialMenu, which made a
|
||||
* user-chosen order impossible to express. Now every ring is described here as a
|
||||
* list of wedge ids for a file kind, and the menu only ever renders
|
||||
* `orderWedgeIds(defaultWedgeIds(...), savedOrder)` — so the default order is
|
||||
* whatever this module says, and a saved order can only rearrange those ids.
|
||||
* Ids the catalogue no longer offers are dropped, and new ids slide in at their
|
||||
* default position, so a saved order never hides or duplicates a wedge.
|
||||
* The wedge catalogue for the radial rings, plus the ordering rules for saved
|
||||
* `settings.json` entries. The menu renders `orderWedgeIds(defaultWedgeIds(...),
|
||||
* savedOrder)`, so a saved order can only rearrange ids the catalogue still
|
||||
* offers; removed ids disappear and new ids keep their default position.
|
||||
*/
|
||||
import { conversionFormats } from "./conversionFormats.ts";
|
||||
import type { FileInfo } from "../types";
|
||||
|
||||
export type RadialRing = "actions" | "formats" | "tools";
|
||||
|
|
@ -19,7 +12,7 @@ export type FileKind = FileInfo["kind"];
|
|||
/** Per-kind and per-ring saved orders, keyed by `wedgeOrderKey`. */
|
||||
export type WedgeOrders = Record<string, string[]>;
|
||||
|
||||
/** Kinds that get their own preset in Settings, in display order. */
|
||||
/** Every file kind that can appear in a saved order. */
|
||||
export const ORDERABLE_KINDS: FileKind[] = [
|
||||
"image",
|
||||
"video",
|
||||
|
|
@ -181,74 +174,3 @@ export function savedOrderFor(
|
|||
const value = orders?.[wedgeOrderKey(kind, ring)];
|
||||
return Array.isArray(value) && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A typical source extension per kind, so the reorder screen can show the same wedge
|
||||
* list the ring would build for that kind. The convert wedge only exists when the kind
|
||||
* has targets, and that depends on the source extension rather than the kind alone.
|
||||
*/
|
||||
const PRESET_SOURCE: Record<FileKind, string> = {
|
||||
image: "png",
|
||||
video: "mp4",
|
||||
audio: "wav",
|
||||
pdf: "pdf",
|
||||
document: "docx",
|
||||
presentation: "pptx",
|
||||
spreadsheet: "xlsx",
|
||||
other: "zip",
|
||||
};
|
||||
|
||||
/**
|
||||
* The wedge list the reorder screen shows for a preset: what the ring offers for a
|
||||
* typical source of that kind, multi-select included. Exported so the ordering rules
|
||||
* stay testable without mounting the settings panel.
|
||||
*/
|
||||
export function presetWedgeIds(kind: FileKind, ring: RadialRing): string[] {
|
||||
const formats = ring === "formats" ? [] : conversionFormats(kind, PRESET_SOURCE[kind]);
|
||||
return defaultWedgeIds(ring, kind, formats, true);
|
||||
}
|
||||
|
||||
/** Move one entry of an order list up or down; out-of-range moves are no-ops. */
|
||||
export function moveWedge(ids: string[], index: number, delta: number): string[] {
|
||||
const target = index + delta;
|
||||
if (index < 0 || index >= ids.length || target < 0 || target >= ids.length) return [...ids];
|
||||
const next = [...ids];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wedge ids whose label key differs from the id itself, so the reorder list can
|
||||
* reuse the wording the ring already uses.
|
||||
*/
|
||||
const LABEL_KEYS: Record<string, string> = {
|
||||
grayscale: "blackWhite",
|
||||
resizeHalf: "halfSize",
|
||||
pdfOcr: "ocr",
|
||||
text: "extractText",
|
||||
send: "sendShort",
|
||||
// The wedge removes metadata and writes a cleaned copy; it never shows what a file
|
||||
// carries. The id stays `metadata` so orders saved by earlier builds still resolve.
|
||||
metadata: "stripMetadata",
|
||||
};
|
||||
|
||||
export function wedgeLabelKey(id: string): string {
|
||||
return LABEL_KEYS[id] ?? id;
|
||||
}
|
||||
|
||||
/** Whether any ring of this kind carries a custom order, for the preset markers. */
|
||||
export function hasCustomOrder(orders: WedgeOrders, kind: FileKind): boolean {
|
||||
return Object.keys(orders).some(
|
||||
(key) => key.startsWith(`${kind}/`) && (orders[key]?.length ?? 0) > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a draft differs from what is stored, i.e. whether saving does anything. */
|
||||
export function isOrderDirty(
|
||||
draft: string[],
|
||||
catalogue: string[],
|
||||
saved?: string[],
|
||||
): boolean {
|
||||
const baseline = orderWedgeIds(catalogue, saved);
|
||||
return draft.length !== baseline.length || draft.some((id, index) => id !== baseline[index]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,6 @@ 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" : "Alt";
|
||||
|
||||
export function dirname(path: string): string {
|
||||
const normalized = path.replace(/\\/g, "/");
|
||||
|
|
@ -12,11 +10,6 @@ export function dirname(path: string): string {
|
|||
return index > 0 ? normalized.slice(0, index) : normalized;
|
||||
}
|
||||
|
||||
export function stripExtension(name: string): string {
|
||||
const index = name.lastIndexOf(".");
|
||||
return index > 0 ? name.slice(0, index) : name;
|
||||
}
|
||||
|
||||
export function extensionOf(path: string): string {
|
||||
const name = basename(path);
|
||||
const index = name.lastIndexOf(".");
|
||||
|
|
@ -53,10 +46,6 @@ export function timeAgo(
|
|||
return translate("agoDays", { count: Math.floor(hours / 24) });
|
||||
}
|
||||
|
||||
export function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
export function normalizeSelection(
|
||||
startX: number,
|
||||
startY: number,
|
||||
|
|
@ -178,17 +167,3 @@ export function subscribeRecent(listener: () => void) {
|
|||
};
|
||||
}
|
||||
|
||||
export function recentKind(path: string): RecentItem["kind"] {
|
||||
const extension = extensionOf(path);
|
||||
if (["png", "jpg", "jpeg", "webp", "tiff", "tif", "bmp", "gif", "heic", "avif"].includes(extension)) {
|
||||
return "image";
|
||||
}
|
||||
if (["mp4", "mov", "m4v", "avi", "mkv", "webm"].includes(extension)) {
|
||||
return "video";
|
||||
}
|
||||
if (["txt", "md", "csv", "tsv", "html", "htm"].includes(extension)) {
|
||||
return "text";
|
||||
}
|
||||
return "file";
|
||||
}
|
||||
|
||||
|
|
|
|||
974
src/styles.css
974
src/styles.css
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue