fix(drop): let Windows finish a row dropped on a button, and spend every button alike

A row dragged from Recent onto any of the three buttons did nothing on
Windows, and reported itself as a refusal. Both delivery paths can stay
silent on that platform, so the gesture now ends in `dragEnd`, which always
arrives and carries a point to hit-test.

The two paths are silent for two separate reasons. A Recent row is a real
file drag, and WebView2 registers its own OLE drop target on the window, so
the DOM drop never reaches the page; that target then reads only `CF_HDROP`,
which an in-page drag does not carry, so `enter_is_valid` stays false and the
native `over`/`drop`/`leave` are withheld too. `landed` keeps the fallback an
execution rather than a second one, and a release outside the window runs
nothing, because the hit-test has slack around every button and the row was
meant for Explorer.

An idle ring also stops getting in the way. It is borderless and always on
top, so one left open from a previous drop sits over the buttons; macOS
passes mouse events through its transparent pixels and Windows hands the
gesture to whichever HWND is under the pointer. Starting a row drag now puts
such a ring aside, while a ring owned by an in-flight Shift-drag gesture keeps
waiting for the release that decides its fate.

The availability rule stops being OCR's alone. `lib/dropCapabilities` answers
one question - can this button serve these files - and the button's spent
state, its candidacy while a drag is in flight, and the drop itself all ask
it, so Convert spends for a `.key` the way OCR spends for a PDF, on both
platforms, whichever drag source carried the file. Tools never spends: its
ring ends in Open, Reveal and Send. An unknown payload is not a refusal,
because spending on an empty path list would disable a gesture that works.

Two other reports this round were not about the drag at all:

- A file received over the LAN now reveals itself only when "show results in
  Finder" is on, the way a finished conversion already behaves, and a batch
  reveals once at its last file rather than once per file.
- Missing runtime components install as one request. Installs run one after
  another because the package managers hold a single lock, and one package
  answering two rows - Poppler for both PDF rows on Windows - is installed
  once. The panel re-reads the machine afterwards either way, since a batch
  that stopped at its first failure may have landed everything before it.
main
mula.liu 2026-11-06 23:13:41 +08:00
parent 84c4056a0d
commit 2bf63f2366
13 changed files with 447 additions and 81 deletions

View File

@ -72,7 +72,7 @@ Shift lives in the menu bar (macOS) and the notification area (Windows), and it
**Use a tool (`Option + Shift`, or `Alt + Shift` on Windows).** Same gesture, and the wedges become tools for that file type instead of formats. While the ring is open, keep `Shift` held and press or release `Option`/`Alt` to flip between the format ring and the tool ring.
**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. **OCR** greyed out means the file you are dragging is not one it can read: it refuses such a drop quietly rather than handing it to another ring, and it never answers with a message you have to dismiss.
**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. A button that cannot serve the file you are dragging goes grey for the length of the gesture - **OCR** for anything that is not an image, **Convert files** for a format with nothing to convert it into - and a grey button is the whole refusal: the drop does nothing, silently, instead of opening an empty ring or handing the file to another ring. **File tools** never greys out, because its ring ends in Open, Reveal and Send. The same rule decides a drop in every case, whichever platform you are on and whether the file came from the file manager or from the Recent list.
**Several files at once.** Multi-select with `⌘`/`Ctrl`-click, then drag. Every file is processed. With 2+ images or 2+ PDFs selected, a **Merge** wedge appears that combines them into a single PDF.
@ -235,7 +235,7 @@ Tesseract.js with the LSTM core, running as WASM inside the app. `eng` and `chi_
Shift keeps a live list of the other Shift copies on your network and uses it for an AirDrop-style transfer. Hover any row in **Recent** and press the send button, or open a file's **Tools** ring and release over **Send** — either way a picker opens with one card per device, and clicking a card starts the transfer. The Tools ring offers Send for every file type, and selecting several files sends them as one batch.
Nothing lands without consent: the receiving machine shows a small card naming the sender and the file, with **Accept** and **Decline** and a countdown. Declining, closing the card, or letting it expire stops the transfer before a single file byte moves. An accepted batch is asked once, then the remaining files of that batch follow on their own. Accepted files are written to Shift's output folder, appear in that machine's Recent list, and a note names the sender. Names that already exist get ` 2`, ` 3` appended, and a partial transfer never leaves a half-written file behind.
Nothing lands without consent: the receiving machine shows a small card naming the sender and the file, with **Accept** and **Decline** and a countdown. Declining, closing the card, or letting it expire stops the transfer before a single file byte moves. An accepted batch is asked once, then the remaining files of that batch follow on their own. Accepted files are written to Shift's output folder, appear in that machine's Recent list, and a note names the sender. Whether Finder (or Explorer) also comes forward is decided by the same **Show results in Finder** switch that governs finished conversions, and a batch reveals once rather than once per file. Names that already exist get ` 2`, ` 3` appended, and a partial transfer never leaves a half-written file behind.
How it finds peers, with no server and no configuration:
@ -320,7 +320,11 @@ their versions and paths, and what each one unlocks on this platform. A row that
as missing also says how to fix it: anything installable carries an **Install** button
(Pandoc and FFmpeg on macOS through Homebrew; Pandoc, FFmpeg, Poppler, ImageMagick and
Typst on Windows through WinGet), and a row with no button is either built in or simply
not used on that platform. Tools are also found on `PATH` and their
not used on that platform. When more than one row is missing, the panel header adds
**Install all**, which sends the missing rows as one request: the installs run one after
another because the package managers hold a single lock, and a package that answers two
rows — Poppler, which serves both PDF rows on Windows — is installed once. Tools are also
found on `PATH` and their
standard install locations at call time, so a missing dependency degrades one
wedge rather than the app.

View File

@ -72,7 +72,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
**使用工具(`Option + Shift`,Windows 为 `Alt + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Alt`,即可在格式环与工具环之间来回切换。
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。「文字识别」变灰,表示你正在拖动的文件不是它能读取的格式:这样的拖放会被安静地拒绝,不再转交给别的圆环,也不会弹出需要你确认的提示。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。**处理不了的按钮会在这次拖拽期间变灰**:不是图片的文件会让「文字识别」变灰,没有任何可转换目标的格式会让「文件转换」变灰,而变灰本身就是全部答复——松手时什么都不执行,安静地不做,既不会弹出一个空圆环,也不会转交给别的圆环。「文件工具」永远不变灰,因为它的环里总有打开、在文件夹中显示与发送。同一条规则在所有平台上、无论文件来自访达/资源管理器还是「最近使用」,判定结果都一致。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。
**一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。
@ -237,7 +237,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 AirDrop 式传输。把鼠标移到「最近使用」的任意一行点击发送按钮,或打开文件的「文件工具」环并松开在「发送」扇区上——两种入口都会弹出每台设备一张卡片的设备选择面板,点击卡片即刻开始传输。工具环对每一种文件类型都提供「发送」,选中多个文件时按一批一起发送。
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。是否顺带把访达(或资源管理器)带到前台,由「完成后在访达中显示」这个开关决定,与转换完成时的行为一致;一批文件只在最后一个落地时显示一次。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
无需服务器、无需配置,发现机制如下:
@ -317,7 +317,7 @@ Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手
| ImageMagick `magick` | HEIC/HEIF/AVIF 输入与 HEIC 输出 | 不需要(`sips`) | 需要 | 需要 |
| LAME | 当 FFmpeg 缺少 `libmp3lame` 时的 MP3 编码 | 少见 | 少见 | 少见 |
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,以及它们在本平台各自负责什么。显示为缺失的行同时给出出口:能装的都带**安装**按钮(macOS 通过 Homebrew 安装 Pandoc 与 FFmpeg;Windows 通过 WinGet 安装 Pandoc、FFmpeg、Poppler、ImageMagick 与 Typst),没有按钮的行说明该能力是内置的,或在本平台根本不会用到。安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,以及它们在本平台各自负责什么。显示为缺失的行同时给出出口:能装的都带**安装**按钮(macOS 通过 Homebrew 安装 Pandoc 与 FFmpeg;Windows 通过 WinGet 安装 Pandoc、FFmpeg、Poppler、ImageMagick 与 Typst),没有按钮的行说明该能力是内置的,或在本平台根本不会用到。缺失不止一项时,面板标题栏还会给出**一键安装 N 个组件**,把所有缺失项作为一个请求提交:安装依次执行(包管理器同一时刻只允许一个安装),而一个包能回答多行时只装一次(Windows 上 Poppler 同时服务两行 PDF)。安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
## 平台支持情况

View File

@ -393,6 +393,23 @@ cargo test --lib runtime
- `a_missing_component_always_offers_a_way_forward`:任何标记为缺失的行都必须要么可安装、
要么本来就不是 external。
## 「运行组件」可以一次装多个缺失项
面板原先一次只能装一个组件:`runtimeInstalling` 是一个 `string | null`,`install` 命令
只接受一个 `component_id`,任何一个按钮在忙时就把整片按钮全部禁用。缺失 Pandoc 与 FFmpeg
时用户要点两次、等两轮重新检测。
现在前端把缺失且可安装的组件收成一个列表,标题栏在**缺失不止一项**时给出「一键安装
N 个组件」,行内的单个安装按钮保持原样,两种入口调用同一个 `install_runtime_components`。
| 约束 | 原因 |
| --- | --- |
| 后端逐个串行安装,不能并发 | `brew` 与 `winget` 同一时刻只允许一个安装,并发只会互相锁住并报错。 |
| 同一个 `package_id` 只装一次 | Windows 上 `pdf-render` 与 `pdf-to-word` 都指向 Poppler,按行安装会重复下载同一个包。 |
| 第一个失败就中止整批 | 失败几乎总是包管理器本身(没装 brew / winget、网络不通),后面每行再等一次超时只是把同一个错误重复 N 遍。 |
| 无论成功失败都 `refreshRuntime()` | 中止的批次里先前的安装可能已经落盘,面板必须重新检测才能显示真实状态,不能相信这一个回复。 |
| 安装结果的名字由界面措辞 | `install_runtime_components` 返回 `()`:按既有约定,后端只报代号,`runtimeInstallComplete` / `runtimeInstallManyComplete` 两种数量由界面选择。 |
## 「最近使用」拖回主面板的三个按钮
0.1.8 曾经把这条交互关掉:一行拖出去是文件,拖回来却什么都不是,用户只能重新选一次文件。
@ -438,23 +455,78 @@ cargo test --lib runtime
| 两条投递路径都必须把"没命中按钮"当作同一种结果处理 | 内部拖拽与外部拖入的语义必须一致;只在 DOM 路径静默、原生路径仍兜底开环或弹提示,就会出现同一个动作两种结果。 |
| 点亮候选按钮的开关有两个来源 | 外部拖拽靠原生 `enter` 设置的 `dragging`,内部拖拽原生事件不一定到,必须另有 `rowDragging`,否则从列表拖起时按钮毫无反应。 |
| 面板不要用 `is-dragging` 自己做拖放反馈 | 内部拖拽拿不到原生事件,只有外部拖拽会点亮面板,两种拖法观感不同;把反馈收在按钮上,两条路径共用同一套 `has-drop-target`。 |
| 「文字识别」不接受兜底,也不解释拒绝 | `runOcrOn` 遇到非图片直接返回,既不转交格式环也不弹提示:按钮说做什么就做什么,"拖到 OCR 却弹出转换环"会让用户以为按钮被忽略了,而弹一条"为什么不行"等于让用户先做错再被纠正。判定发生在 `ocrCanRead(dragPaths)`,落在按钮的视觉状态上。 |
| 三个按钮共用 `src/lib/dropCapabilities.ts` 一条规则 | 判定原先只写在「文字识别」上,另外两个按钮照旧执行,于是"能处理就处理、不能处理就禁止"在同一个面板里有两种口径。视觉状态(`spent()`)、`dropFiles` 的实际执行、`aimedAction` 的点亮,三处必须问同一个函数,否则会出现"看着能按、按下去什么都不做"或者反过来。 |
| 「处理不了」不接受兜底,也不解释拒绝 | 按钮说做什么就做什么:既不能转交别的圆环,也不能弹一条"为什么不行"——那等于让用户先做错再被纠正。变灰就是全部答复。 |
| `actionCanServe` 在"文件未知"时必须返回 true | Windows 的拖拽在载荷可读之前可能报告 0 个文件;按空列表判定会把三个按钮全部禁掉,一次本来能用的手势就废了。只有"知道文件、且知道处理不了"才禁止。 |
| 「文件工具」永不禁止 | 它的环以打开 / 在文件夹中显示 / 发送收尾,任何存在的文件都能执行;把"其他"类型判成处理不了会让面板出现三个灰按钮。 |
| 拖出的行落在窗口之外时不能命中按钮 | `dragend` 的坐标也要经过 `actionAtPoint`,而命中判定四周有 `SLACK_X/SLACK_Y` 余量;不先判窗口边界,拖去资源管理器的一行会被当成落在按钮上。 |
| 拖拽结束时三处都要清空 `dragPaths` | 原生 `leave`、原生 `drop`、行的 `dragEnd` 都要清;`landRecentRow` 也清一次,因为部分引擎在落点已确定后才补 `dragEnd`,只靠它会让按钮在下一笔拖拽前一直显示为不可用。 |
### Windows:一次内部拖拽可能一次都不报告
0.1.10 用户实测:Windows 上把「最近使用」的行拖到三个按钮,**每一个都完不成**。台账
里"只保留 DOM,Windows 的原生投递会让拖拽失效"写反了方向——在 Windows 上两条路都可能不到:
1. **DOM 路径**:历史行是 `draggable` 的文件式拖拽,WebView2 在自己的窗口上注册了 OLE
`IDropTarget`(`wry/src/webview2/drag_drop.rs`),页面内的 drop 被它接管。
2. **原生路径**:那个 `IDropTarget::DragEnter` 只读 `CF_HDROP`;页内拖拽不带这个格式,
于是 `enter_is_valid` 保持 false,`DragOver` / `Drop` / `DragLeave` 一律不上报。
两条都静默,松手就没有任何事件,于是"什么都会发生"被用户读成"拒绝"。修法是让 `dragend`
成为兜底:它总会上报,且带 `clientX/clientY`,足够命中按钮;`landed` 标记保证它只在两条
投递路径都没到过的时候执行一次。
### Windows:闲置的圆环会压在按钮上
圆环窗口无边框、`always_on_top`,用完不关就停在原地等点击,而它可能正压在面板的按钮上。
开始拖动一行时先调用 `stand_down_radial` 让它让开;`radial_dragging` 为真说明这次圆环属于
一个正在进行的 Shift 拖拽手势,那时不能收——结束手势的松手才有权处置它。
注意不要把它改成"圆环在 `enter` 时自行让开":往打开的圆环上直接放文件、由落点扇区执行该
动作,是 Windows 现有的一条可用路径,被闲置判定挡掉就是功能倒退。
### 回归测试
`src/lib/dropTargets.test.ts` 覆盖命中区域与坐标换算;拖拽本身用浏览器实测(Chromium 与
WKWebView 两条路径都要走一遍):
`src/lib/dropTargets.test.ts` 覆盖命中区域与坐标换算,`src/lib/dropCapabilities.test.ts`
覆盖"谁能服务这次拖拽"这条规则(含类型表与后端一致、PDF 不落到 OCR、载荷未知时不禁止);
拖拽本身用浏览器实测(Chromium 与 WKWebView 两条路径都要走一遍):
1. 「最近使用」某行 → 拖到「文件转换」→ 只弹出一个格式环,且文件是这一行。
2. 同一行 → 拖到「文件工具」→ 只弹出工具环。
3. 图片行 → 拖到「文字识别」→ 按钮正常点亮,打开编辑器并自动开始识别;非图片行 → 「文字识别」拖拽全程为不可用态且不会点亮,松手后不打开编辑器、不开环、**不出现任何提示**,另外两个按钮仍可正常落点。
3b. `.key` / `.zip` 这类没有可转换目标的行 → 「文件转换」同样拖拽全程变灰、松手不执行;「文件工具」始终可用并正常弹出工具环。
3c. **Windows 必须单独跑一遍 1–3**:这一平台两条投递路径都可能不上报,兜底只在 `dragEnd` 里,macOS 通过不代表 Windows 通过。
3d. 先用「文件转换」弹出一个圆环、再拖一行到按钮上 → 圆环不能吃掉这次拖放(Windows 尤其要看这一条)。
4. 同一行 → 拖到面板空白处 / 标题栏 / 列表本身 → 不开环、不执行、**不出现任何提示浮层**。
5. 从访达拖文件到面板空白处 → 同样不执行、不提示;拖到任一按钮 → 执行该按钮的动作。
6. 行拖出到访达/聊天窗口 → 仍是文件本体,没有被 Shift 自己吃掉。
7. 两种拖法各拖一次 → 面板(`.home-drop`)在拖拽全程不缩放、不变色,标题文案不变;只有三个按钮在拖拽开始时同时亮起虚线候选态、松开后熄灭。
8. 松手之后(无论落在哪里)→ 按钮立刻恢复正常亮度,下一次拖拽不会残留不可用态。
## 「完成后在访达中显示」管到的两条落地路径
`auto_reveal` 这个开关原本只有转换完成时会读:`perform_file_action` 结束前判断一次,
弹出第一个输出。局域网收到的文件走的是 `share.rs::receive_file`,它自己 `emit`
`app://file-result` 并写入历史,从来不经过那条判断,所以「接收完就弹一个访达窗口」
不受任何设置控制。
现在两条落地路径共用同一条规则:**文件落地之后是否把文件管理器带到前台,由
`settings::auto_reveal` 决定**。批量接收沿用批处理的既有语义——一批只在最后一个文件
落地时显示一次(`reveals_on_landing`),而不是每个文件弹一次窗口,与一次转换十个文件
只弹一个输出的行为对齐。
| 约束 | 原因 |
| --- | --- |
| 接收路径必须读 `auto_reveal`,不能自己决定弹窗 | 同一件事有两种行为,用户只能理解为开关坏了;转换那侧已经是这个口径。 |
| 一批文件只按最后一个文件显示一次 | 显示的是文件管理器窗口,十个文件弹十次等于抢占前台十次。 |
| 批内序号必须在 `emit_transfer` 之前读 | 那条事件会把 `header.peer_name` 移出,之后再借用就是编译错误;先算成一个 `bool` 才能既保住顺序又保住借用检查。 |
| 缺字段的旧版本信标必须仍然显示 | `batch_index` / `batch_total` 都取默认 0 时,`index + 1 >= total` 成立,`saturating_add` 防的是 0 - 1 下溢。 |
### 回归测试
`cargo test --lib share` 的 `only_the_last_file_of_a_batch_reveals`:钉住单文件、批次中间、
批次末尾与旧版本信标四种头部的判定。
## 提示语由界面措辞,后端只报代号
同一件事在两个地方各说一遍,就一定会说成两样。0.1.10 之前正是这样:`perform_action` 直接返回

View File

@ -501,6 +501,28 @@ pub fn hide(app: &AppHandle) {
}
}
/// Whether the ring belongs to a Shift-drag gesture in flight, as opposed to waiting on
/// the pointer for a wedge to be clicked. The poller writes this before it shows the
/// ring, so it is the answer that is already true when a gesture the panel owns begins.
fn ring_is_dragging(app: &AppHandle) -> bool {
app.try_state::<AppState>()
.and_then(|state| state.radial_dragging.lock().ok().map(|value| *value))
.unwrap_or(false)
}
/// Put an idle ring away because a gesture the panel owns is beginning. A ring waiting
/// for a click is only ever in the way: it covers the buttons a row is about to be
/// dropped on, and it is borderless and always on top, so on Windows it also sits over
/// whatever the pointer is aimed at. A ring in the middle of a Shift-drag belongs to
/// that gesture, so it stays - the release that ends the gesture decides its fate.
#[tauri::command]
pub fn stand_down_radial(app: AppHandle) -> Result<(), String> {
if !ring_is_dragging(&app) {
hide(&app);
}
Ok(())
}
/// The ring's own commands decode image previews, so they run off the main thread
/// and the ring never waits on a batch of large photos.
#[tauri::command]

View File

@ -433,7 +433,7 @@ pub fn run() {
update::update_clear,
settings::open_files_permission_settings,
runtime::machine_info,
runtime::install_runtime_component,
runtime::install_runtime_components,
capture::get_capture_session,
capture::screen_capture_access_status,
capture::start_capture,
@ -458,6 +458,7 @@ pub fn run() {
editor::close_pin,
drag_bridge::get_radial_context,
drag_bridge::hide_radial,
drag_bridge::stand_down_radial,
drag_bridge::show_files_in_radial,
share::share_answer,
share::share_refresh,

View File

@ -36,7 +36,6 @@ pub struct RuntimeInfo {
#[derive(Debug, Clone, Copy)]
struct InstallTarget {
name: &'static str,
package_id: &'static str,
executable: &'static str,
}
@ -45,12 +44,10 @@ struct InstallTarget {
fn macos_install_target(id: &str) -> Option<InstallTarget> {
match id {
"pandoc" => Some(InstallTarget {
name: "Pandoc",
package_id: "pandoc",
executable: "pandoc",
}),
"media" => Some(InstallTarget {
name: "FFmpeg",
package_id: "ffmpeg",
executable: "ffmpeg",
}),
@ -62,33 +59,27 @@ fn macos_install_target(id: &str) -> Option<InstallTarget> {
fn windows_install_target(id: &str) -> Option<InstallTarget> {
match id {
"pandoc" => Some(InstallTarget {
name: "Pandoc",
package_id: "JohnMacFarlane.Pandoc",
executable: "pandoc",
}),
"media" => Some(InstallTarget {
name: "FFmpeg",
package_id: "Gyan.FFmpeg",
executable: "ffmpeg",
}),
"pdf-render" => Some(InstallTarget {
name: "Poppler",
package_id: "oschwartz10612.Poppler",
executable: "pdftoppm",
}),
// PDF-to-Word uses the same page renderer as PDF-to-image on Windows.
"pdf-to-word" => Some(InstallTarget {
name: "Poppler",
package_id: "oschwartz10612.Poppler",
executable: "pdftoppm",
}),
"image-backend" => Some(InstallTarget {
name: "ImageMagick",
package_id: "ImageMagick.ImageMagick",
executable: "magick",
}),
"pdf-engine" => Some(InstallTarget {
name: "Typst PDF engine",
package_id: "Typst.Typst",
executable: "typst",
}),
@ -415,15 +406,33 @@ pub async fn machine_info() -> Result<RuntimeInfo, String> {
}
#[tauri::command]
pub async fn install_runtime_component(component_id: String) -> Result<String, String> {
tauri::async_runtime::spawn_blocking(move || install_runtime_component_sync(&component_id))
pub async fn install_runtime_components(component_ids: Vec<String>) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || install_runtime_components_sync(&component_ids))
.await
.map_err(|error| format!("Could not install runtime component: {error}"))?
.map_err(|error| format!("Could not install runtime components: {error}"))?
}
fn install_runtime_component_sync(component_id: &str) -> Result<String, String> {
let target =
install_target(component_id).ok_or_else(|| "unsupported-runtime-component".to_string())?;
/// Install a group of components as one request. The package managers hold one lock
/// per tool, so the batch runs one install after another instead of racing itself,
/// and a package that serves several rows (Poppler answers both PDF rows on Windows)
/// is installed once. The first failure stops the batch: it is nearly always the
/// package manager itself, so repeating the same failure per row would only add waits.
/// Callers refresh afterwards, which is what reports the rows that did land.
fn install_runtime_components_sync(component_ids: &[String]) -> Result<(), String> {
let mut installed: Vec<&'static str> = Vec::new();
for component_id in component_ids {
let target = install_target(component_id)
.ok_or_else(|| "unsupported-runtime-component".to_string())?;
if installed.contains(&target.package_id) {
continue;
}
install_target_package(target)?;
installed.push(target.package_id);
}
Ok(())
}
fn install_target_package(target: InstallTarget) -> Result<(), String> {
let timeout = Duration::from_secs(15 * 60);
#[cfg(target_os = "macos")]
@ -438,7 +447,7 @@ fn install_runtime_component_sync(component_id: &str) -> Result<String, String>
if files::resolve_tool(target.executable).is_none() {
return Err("homebrew-install-missing-binary".to_string());
}
Ok(format!("{} was installed.", target.name))
Ok(())
}
#[cfg(target_os = "windows")]
@ -464,7 +473,7 @@ fn install_runtime_component_sync(component_id: &str) -> Result<String, String>
if files::resolve_tool(target.executable).is_none() {
return Err("winget-install-missing-binary".to_string());
}
Ok(format!("{} was installed.", target.name))
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]

View File

@ -1252,6 +1252,8 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
)?;
let name = safe_name(&header.file_name).unwrap_or_else(|| "file".into());
let path = target.to_string_lossy().to_string();
// Read the batch fields before the event below moves out of `header`.
let reveal = reveals_on_landing(&header);
emit_transfer(
app,
TransferEvent {
@ -1270,9 +1272,22 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
"app://file-result",
serde_json::json!({ "outputs": [path], "message": name }),
);
// A landed file follows the same rule as a finished conversion: the
// "show results in Finder" switch decides whether Finder comes forward.
if reveal && crate::settings::auto_reveal(app) {
let _ = crate::files::reveal_path(Path::new(&target));
}
Ok(())
}
/// Whether a file that just landed should bring the file manager forward. A batch
/// answers once, when its last file arrives, the way a batch conversion reveals one
/// output instead of one per file. The `saturating_add` and the `>=` keep a legacy
/// peer's header - which sends no batch fields, so both read 0 - still revealing.
fn reveals_on_landing(header: &TransferHeader) -> bool {
header.batch_index.saturating_add(1) >= header.batch_total
}
fn emit_transfer(app: &AppHandle, event: TransferEvent) {
let _ = app.emit("share://transfer", event);
}
@ -1639,6 +1654,37 @@ mod tests {
assert_eq!(MAGIC.len(), 4);
}
/// A landed file reveals once per batch, never once per file, and a peer that
/// sends no batch fields still reveals.
#[test]
fn only_the_last_file_of_a_batch_reveals() {
let single = TransferHeader {
batch_index: 0,
batch_total: 1,
..Default::default()
};
assert!(reveals_on_landing(&single));
let first = TransferHeader {
batch_index: 0,
batch_total: 3,
..Default::default()
};
let middle = TransferHeader {
batch_index: 1,
batch_total: 3,
..Default::default()
};
let last = TransferHeader {
batch_index: 2,
batch_total: 3,
..Default::default()
};
assert!(!reveals_on_landing(&first));
assert!(!reveals_on_landing(&middle));
assert!(reveals_on_landing(&last));
assert!(reveals_on_landing(&TransferHeader::default()));
}
#[test]
fn peer_signature_changes_only_with_the_peer_set() {
let state = ShareState::default();

View File

@ -50,6 +50,11 @@ import { getInitialLang, publishLang, tLive, useI18n } from "../i18n";
import { api } from "../lib/api";
import { FEEDBACK } from "../lib/feedback";
import { hitTestDropTarget, toWindowPoint } from "../lib/dropTargets";
import {
actionCanServe,
OCR_IMAGE_EXTENSIONS,
type DropAction,
} from "../lib/dropCapabilities";
import { SetupPanel } from "./SetupPanel";
import { SharePanel } from "./SharePanel";
import { UpdatePanel } from "./UpdatePanel";
@ -109,31 +114,13 @@ const DROP_ICONS = [
type OutputKind = "files" | "screenshot" | "recording";
/** The three primary buttons double as drop targets: files dropped on a button run that action. */
type DropAction = "formats" | "tools" | "ocr";
const OCR_EXTENSIONS = [
"png",
"jpg",
"jpeg",
"webp",
"tiff",
"tif",
"bmp",
"gif",
"heic",
"avif",
];
/* The three primary buttons double as drop targets: files dropped on a button run that
action. Which button a drag may land on is decided by `lib/dropCapabilities`. */
const ARC_STEP_DEG = 13;
const ARC_RADIUS = 140;
const ARC_LIFT = 32;
/** Whether every file a drag carries is one the OCR button can read. */
function ocrCanRead(paths: string[]) {
return paths.every((path) => OCR_EXTENSIONS.includes(extensionOf(path)));
}
// WKWebView renders HEIC/AVIF natively; the icon fallback covers any decode failure.
const THUMB_EXTENSIONS = [
"png",
@ -245,7 +232,7 @@ export function MainWindow() {
const [checking, setChecking] = useState(false);
const [runtimeInfo, setRuntimeInfo] = useState<RuntimeInfo | null>(null);
const [runtimeLoading, setRuntimeLoading] = useState(false);
const [runtimeInstalling, setRuntimeInstalling] = useState<string | null>(null);
const [runtimeInstalling, setRuntimeInstalling] = useState<string[]>([]);
const [runtimeError, setRuntimeError] = useState<string | null>(null);
const [runtimeInstallHelp, setRuntimeInstallHelp] = useState<
"homebrew" | "winget" | null
@ -317,7 +304,7 @@ export function MainWindow() {
filters: [
{
name: "Images",
extensions: OCR_EXTENSIONS,
extensions: OCR_IMAGE_EXTENSIONS,
},
],
});
@ -331,7 +318,7 @@ export function MainWindow() {
async function runOcrOn(paths: string[]) {
// The button already showed it could not take this file, so a release on it
// stays silent: no action, no message, nothing to acknowledge.
if (!ocrCanRead(paths)) return;
if (!actionCanServe("ocr", paths)) return;
await api.openInEditor(paths[0]);
window.setTimeout(() => {
void emitTo("editor", "editor://run-ocr", {});
@ -368,6 +355,9 @@ export function MainWindow() {
function dropFiles(paths: string[], action: DropAction | null) {
if (paths.length === 0) return Promise.resolve();
if (!action) return Promise.resolve();
// The same rule the button's appearance already applied: a button that cannot
// serve this file runs nothing, rather than opening a wheel with nothing in it.
if (!actionCanServe(action, paths)) return Promise.resolve();
if (action === "ocr") return runOcrOn(paths);
return api.showFilesInRadial(paths, action).then(() => undefined);
}
@ -541,19 +531,26 @@ export function MainWindow() {
return t(message);
}
async function installRuntimeComponent(component: RuntimeComponent) {
if (runtimeInstalling) return;
setRuntimeInstalling(component.id);
async function installRuntimeComponents(components: RuntimeComponent[]) {
if (runtimeInstalling.length > 0 || components.length === 0) return;
setRuntimeInstalling(components.map((component) => component.id));
setRuntimeError(null);
setRuntimeInstallHelp(null);
try {
await api.installRuntimeComponent(component.id);
await refreshRuntime();
flash(t("runtimeInstallComplete", { name: component.name }));
await api.installRuntimeComponents(components.map((component) => component.id));
flash(
components.length === 1
? t("runtimeInstallComplete", { name: components[0].name })
: t("runtimeInstallManyComplete", { count: components.length }),
FEEDBACK.done,
);
} catch (error) {
setRuntimeError(describeRuntimeInstallError(error));
} finally {
setRuntimeInstalling(null);
setRuntimeInstalling([]);
// A batch can stop at its first failure with the earlier installs already
// on disk, so the panel re-reads either way rather than trusting the reply.
await refreshRuntime();
}
}
@ -756,11 +753,13 @@ export function MainWindow() {
return recent.filter((item) => basename(item.path).toLowerCase().includes(needle));
}, [recent, historyQuery]);
// A drag the OCR button cannot serve shows it spent while the gesture is in
// flight, which is the whole notice: releasing on it then does nothing at all.
const ocrUnavailable = dragPaths !== null && !ocrCanRead(dragPaths);
// One rule for all three buttons and both platforms: a button that cannot serve the
// files in flight shows spent, and a release on it does nothing. Being spent is the
// whole notice - there is no message to explain a refusal the user can already see.
const spent = (action: DropAction) =>
dragPaths !== null && !actionCanServe(action, dragPaths);
// A button that cannot serve the drag is not a candidate, so it never lights up.
const aimedAction = ocrUnavailable && dropAction === "ocr" ? null : dropAction;
const aimedAction = dropAction && actionCanServe(dropAction, dragPaths) ? dropAction : null;
const outputLabel = (kind: WriteCheck["kind"]) =>
kind === "screenshot" ? t("screenshots") : kind === "recording" ? t("recordings") : t("fileResults");
@ -780,6 +779,12 @@ export function MainWindow() {
}))
.filter((group) => group.components.length > 0)
: [];
// What the panel can fix by itself, in the order the rows appear. A shared package
// (Poppler answers both PDF rows on Windows) is listed twice here; the backend
// installs it once.
const runtimeInstallable = runtimeInfo
? runtimeInfo.components.filter((component) => !component.available && component.installable)
: [];
return (
<div
@ -894,7 +899,9 @@ export function MainWindow() {
}`}
>
<button
className={`home-primary ${aimedAction === "formats" ? "is-drop-target" : ""}`}
className={`home-primary ${aimedAction === "formats" ? "is-drop-target" : ""} ${
spent("formats") ? "is-drop-unavailable" : ""
}`}
ref={(node) => {
dropTargets.current.formats = node;
}}
@ -910,7 +917,9 @@ export function MainWindow() {
{t("convertFiles")}
</button>
<button
className={`home-secondary ${aimedAction === "tools" ? "is-drop-target" : ""}`}
className={`home-secondary ${aimedAction === "tools" ? "is-drop-target" : ""} ${
spent("tools") ? "is-drop-unavailable" : ""
}`}
ref={(node) => {
dropTargets.current.tools = node;
}}
@ -925,12 +934,12 @@ export function MainWindow() {
</button>
<button
className={`home-secondary ${aimedAction === "ocr" ? "is-drop-target" : ""} ${
ocrUnavailable ? "is-drop-unavailable" : ""
spent("ocr") ? "is-drop-unavailable" : ""
}`}
ref={(node) => {
dropTargets.current.ocr = node;
}}
aria-disabled={ocrUnavailable ? "true" : undefined}
aria-disabled={spent("ocr") ? "true" : undefined}
onClick={() => void spring("ocr", chooseOcr)}
>
{busy === "ocr" ? <LoaderCircle size={18} className="spin" /> : <ScanText size={18} />}
@ -1011,18 +1020,42 @@ export function MainWindow() {
recentDrag.current = { path: item.path, landed: false };
setRowDragging(true);
setDragPaths([item.path]);
// A ring left open from the last drop sits over these buttons,
// borderless and always on top. Windows hands a drag to whichever
// window is under the pointer, so that ring would claim this drop
// and the button underneath would never see it.
if (isTauri()) void api.standDownRadial().catch(() => undefined);
for (const [type, value] of Object.entries(dragOutPayload(item.path))) {
event.dataTransfer.setData(type, value);
}
}}
onDragEnd={() => {
onDragEnd={(event) => {
const drag = recentDrag.current;
// A row is dragged as a file, and WebView2's OLE drop target only
// accepts `CF_HDROP`, which an in-page drag never carries. So on
// Windows neither the DOM drop nor the native drop is delivered:
// the gesture simply ends. `dragend` still reports where the
// pointer stopped, which is enough to find the button it was aimed
// at, and the `landed` flag keeps this a fallback rather than a
// second execution wherever a drop did arrive.
if (drag && !drag.landed) {
const point = { x: event.clientX, y: event.clientY };
// A row released outside the window went to Explorer or a chat
// window, where nothing of ours runs. The hit-test has slack
// around every button, so the edge has to be checked first.
const inside =
point.x >= 0 &&
point.y >= 0 &&
point.x <= window.innerWidth &&
point.y <= window.innerHeight;
landRecentRow(inside ? actionAtPoint(point) : null);
}
setDropAction(null);
setDragging(false);
setRowDragging(false);
setDragPaths(null);
// Some engines report the native drop only after the button is
// already up, so the gesture stays recognised for a moment.
const drag = recentDrag.current;
if (!drag) return;
window.setTimeout(() => {
if (recentDrag.current === drag) recentDrag.current = null;
@ -1391,14 +1424,32 @@ export function MainWindow() {
<Cpu size={17} />
{t("runtimeComponents")}
</div>
<button
className="settings-link runtime-refresh"
onClick={() => void refreshRuntime()}
disabled={runtimeLoading || runtimeInstalling !== null}
>
<RefreshCw size={13} className={runtimeLoading ? "spin" : ""} />
{runtimeLoading ? t("runtimeChecking") : t("runtimeRefresh")}
</button>
<div className="runtime-head-actions">
{runtimeInstallable.length > 1 ? (
<button
className="runtime-install runtime-install-all"
onClick={() => void installRuntimeComponents(runtimeInstallable)}
disabled={runtimeLoading || runtimeInstalling.length > 0}
>
{runtimeInstalling.length > 0 ? (
<LoaderCircle size={14} className="spin" />
) : (
<Download size={14} />
)}
{runtimeInstalling.length > 0
? t("runtimeInstalling")
: t("runtimeInstallAll", { count: runtimeInstallable.length })}
</button>
) : null}
<button
className="settings-link runtime-refresh"
onClick={() => void refreshRuntime()}
disabled={runtimeLoading || runtimeInstalling.length > 0}
>
<RefreshCw size={13} className={runtimeLoading ? "spin" : ""} />
{runtimeLoading ? t("runtimeChecking") : t("runtimeRefresh")}
</button>
</div>
</div>
<p className="runtime-summary">{t("runtimeSummary")}</p>
{runtimeError ? (
@ -1465,15 +1516,15 @@ export function MainWindow() {
{!component.available && component.installable ? (
<button
className="runtime-install"
onClick={() => void installRuntimeComponent(component)}
disabled={runtimeInstalling !== null || runtimeLoading}
onClick={() => void installRuntimeComponents([component])}
disabled={runtimeLoading || runtimeInstalling.length > 0}
>
{runtimeInstalling === component.id ? (
{runtimeInstalling.includes(component.id) ? (
<LoaderCircle size={14} className="spin" />
) : (
<Download size={14} />
)}
{runtimeInstalling === component.id
{runtimeInstalling.includes(component.id)
? t("runtimeInstalling")
: t("runtimeInstall")}
</button>

View File

@ -185,6 +185,8 @@ const messages: Record<Lang, Record<string, string>> = {
runtimeInstall: "Install",
runtimeInstalling: "Installing…",
runtimeInstallComplete: "Installed {name}.",
runtimeInstallAll: "Install {count} components",
runtimeInstallManyComplete: "Installed {count} components.",
runtimeInstallNeedsHomebrew:
"Homebrew is required to install Pandoc and FFmpeg. Install Homebrew, then try again.",
runtimeInstallNeedsWinget:
@ -435,6 +437,8 @@ const messages: Record<Lang, Record<string, string>> = {
runtimeInstall: "安装",
runtimeInstalling: "安装中…",
runtimeInstallComplete: "已安装 {name}。",
runtimeInstallAll: "一键安装 {count} 个组件",
runtimeInstallManyComplete: "已安装 {count} 个组件。",
runtimeInstallNeedsHomebrew: "自动安装需要 Homebrew。请先安装 Homebrew,然后重试。",
runtimeInstallNeedsWinget:
"Windows 自动安装需要“应用安装程序”(WinGet)。安装或更新后请重试。",

View File

@ -81,6 +81,8 @@ export const api = {
inspectFiles: (paths: string[]) => invoke<FileInfo[]>("inspect_files", { paths }),
performFileAction,
revealFile: (path: string) => invoke<void>("reveal_file", { path }),
/** Put an idle radial ring away so it cannot cover or claim the next drop. */
standDownRadial: () => invoke<void>("stand_down_radial"),
openFile: (path: string) => invoke<void>("open_file", { path }),
readTextFile: (path: string) => invoke<string>("read_text_file", { path }),
readImageData: (path: string) => invoke<string>("read_image_data", { path }),
@ -156,6 +158,6 @@ export const api = {
onUpdateStatus: (handler: (status: UpdateStatus | null) => void) =>
listen<UpdateStatus | null>("update://status", (event) => handler(event.payload)),
getRuntimeInfo: () => invoke<RuntimeInfo>("machine_info"),
installRuntimeComponent: (componentId: string) =>
invoke<string>("install_runtime_component", { componentId }),
installRuntimeComponents: (componentIds: string[]) =>
invoke<void>("install_runtime_components", { componentIds }),
};

View File

@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { actionCanServe, convertible, kindFromPath, ocrCanRead } from "./dropCapabilities.ts";
test("the classifier matches the backend's kind tables", () => {
assert.equal(kindFromPath("C:\\Users\\me\\photo.HEIC"), "image");
assert.equal(kindFromPath("/tmp/clip.mp4"), "video");
assert.equal(kindFromPath("/tmp/voice.m4a"), "audio");
assert.equal(kindFromPath("/tmp/report.pdf"), "pdf");
assert.equal(kindFromPath("/tmp/notes.pages"), "document");
assert.equal(kindFromPath("/tmp/deck.key"), "presentation");
assert.equal(kindFromPath("/tmp/sheet.numbers"), "spreadsheet");
assert.equal(kindFromPath("/tmp/archive.zip"), "other");
assert.equal(kindFromPath("README"), "other");
});
test("only images reach OCR", () => {
assert.ok(ocrCanRead(["/tmp/a.png", "C:\\tmp\\b.jpg"]));
assert.ok(!ocrCanRead(["/tmp/a.pdf"]));
// One unreadable file in a batch spends the button for the whole batch.
assert.ok(!ocrCanRead(["/tmp/a.png", "/tmp/b.txt"]));
assert.ok(!ocrCanRead([]));
});
test("a source with no conversion target spends convert", () => {
assert.ok(convertible(["/tmp/report.pdf"]));
assert.ok(!convertible(["/tmp/deck.key"]));
assert.ok(!convertible(["/tmp/archive.zip"]));
// A file that cannot convert spends the button for a mixed batch too.
assert.ok(!convertible(["/tmp/deck.key", "/tmp/a.png"]));
});
test("the tool ring serves any file", () => {
for (const paths of [["/tmp/a.png"], ["/tmp/x.zip"], ["/tmp/deck.key"], []]) {
assert.ok(actionCanServe("tools", paths));
}
});
test("an unknown payload is not a refusal", () => {
// Spending every button because a drag reported no paths would disable a gesture
// that does work, so "nothing known yet" leaves all three candidates lit.
for (const action of ["formats", "tools", "ocr"] as const) {
assert.ok(actionCanServe(action, null));
assert.ok(actionCanServe(action, []));
}
});
test("a PDF converts but never reaches the OCR button", () => {
assert.ok(actionCanServe("formats", ["/tmp/report.pdf"]));
assert.ok(actionCanServe("tools", ["/tmp/report.pdf"]));
assert.ok(!actionCanServe("ocr", ["/tmp/report.pdf"]));
});

View File

@ -0,0 +1,91 @@
/**
* Which of the three home-panel buttons can serve the files a drag is carrying.
*
* One rule for both platforms and both delivery paths: a button that can do something
* with the drag is a candidate, a button that cannot is spent for the length of the
* gesture and runs nothing when the file is released on it. It used to be that only
* 文字识别 spent, and that a file the ring has no target for still opened a wheel.
*
* The rule is deliberately one-way: a button is spent only when the files are known
* *and* known not to be servable. A drag that reports no files — which is what a
* Windows drag can look like before its payload is readable — leaves every button a
* candidate, because guessing from an empty list would spend buttons that do work.
*/
import { conversionFormats } from "./conversionFormats.ts";
import { extensionOf } from "./utils.ts";
import type { FileInfo } from "../types";
export type DropAction = "formats" | "tools" | "ocr";
type FileKind = FileInfo["kind"];
/** The same extension tables `src-tauri/src/files.rs::kind_of` classifies with. */
export const IMAGE_EXTENSIONS = [
"png",
"jpg",
"jpeg",
"webp",
"tiff",
"tif",
"bmp",
"gif",
"heic",
"heif",
"avif",
];
const VIDEO = ["mp4", "mov", "m4v", "avi", "mkv", "webm"];
const AUDIO = ["mp3", "wav", "m4a", "aiff", "aif", "caf", "flac", "ogg"];
const DOCUMENT = ["docx", "doc", "rtf", "odt", "txt", "md", "html", "htm", "pages"];
const PRESENTATION = ["pptx", "ppt", "key"];
const SPREADSHEET = ["xlsx", "xls", "xlsb", "ods", "csv", "tsv", "numbers"];
/** Classify by extension, so a decision exists before the file reaches a button. */
export function kindFromPath(path: string): FileKind {
const extension = extensionOf(path);
if (IMAGE_EXTENSIONS.includes(extension)) return "image";
if (VIDEO.includes(extension)) return "video";
if (AUDIO.includes(extension)) return "audio";
if (extension === "pdf") return "pdf";
if (DOCUMENT.includes(extension)) return "document";
if (PRESENTATION.includes(extension)) return "presentation";
if (SPREADSHEET.includes(extension)) return "spreadsheet";
return "other";
}
/** Whether OCR can read every file in the drag. The button says OCR, so images only. */
export function ocrCanRead(paths: string[]): boolean {
if (paths.length === 0) return false;
return paths.every((path) => IMAGE_EXTENSIONS.includes(extensionOf(path)));
}
/**
* Whether each file can become something else: the ring's own type-awareness moved
* forward in time. A `.key` has no conversion target, so 文件转换 spends rather than
* opening a wheel with nothing in it.
*/
export function convertible(paths: string[]): boolean {
if (paths.length === 0) return false;
return paths.every(
(path) => conversionFormats(kindFromPath(path), extensionOf(path)).length > 0,
);
}
/**
* Whether one button can serve the drag. `null` is a drag whose files are not known
* yet, which is not a refusal: every button stays a candidate.
*/
export function actionCanServe(action: DropAction, paths: string[] | null): boolean {
if (!paths || paths.length === 0) return true;
switch (action) {
case "formats":
return convertible(paths);
case "ocr":
return ocrCanRead(paths);
case "tools":
// The tool ring ends in Open, Reveal and Send, which serve any file that exists.
return true;
}
}
/** The extensions the image picker offers when OCR is started by hand. */
export const OCR_IMAGE_EXTENSIONS = IMAGE_EXTENSIONS;

View File

@ -2670,6 +2670,17 @@ kbd {
gap: 5px;
}
.runtime-head-actions {
display: flex;
flex: none;
align-items: center;
gap: 8px;
}
.runtime-install-all {
margin-top: 0;
}
.runtime-refresh:disabled {
cursor: default;
opacity: var(--dimmed);