Compare commits

..

45 Commits
v0.1.3 ... main

Author SHA1 Message Date
mula.liu 0ab3768c5a fix(update): make the Windows handoff actually run
Reported: the 0.1.13 Windows build fails after download and restart. Two
independent defects sat on that path:

- The helper was launched as `cmd.exe /D /C "<path with spaces>" ...`.
  cmd strips the first and last quote when the command has more than one
  quoted token, so the script under `%TEMP%\Shift Updates` was never
  recognized. Shift quit and nothing installed. The script path now arrives
  in an environment variable, with the extra outer quote layer cmd needs.
- A silent install could still open the WebView2 warning. Nobody is present
  to dismiss it during an in-app update, so the installer waited forever.
  The manual warning stays; silent installs skip it.

The installer also waits briefly after taskkill before overwriting the EXE,
and the handoff logs its start and a missing target so a future failure is
visible in `%TEMP%\Shift Updates\handoff.log`.

Verified with Wine: the old command reproduces the quote-stripping failure,
the new one runs; the rebuilt installer completes silently without WebView2
and the full wait-install-relaunch handoff replaces the executable.
2026-11-20 18:29:16 +08:00
mula.liu 706ff6fb26 fix(icons): orange ground and white mark, as the product has always been
Reported: "你改的标注应用图标不对啊,我之前是橙底、白线的风格(参考 squid 的
图标)."

The previous commit inverted the figure/ground relationship. Chasing
consistency with the alpha-only tray mark, the app tile went to espresso
with a warm mark — technically consistent geometry, and it passed every
contrast check I ran, but those checks were pointed at the wrong axis.
Consistency has two of them here, geometry and light/dark, and the one a
returning user actually recognises is "orange tile".

Now the app icon is literally the tray mark with a colour turned on:
`#FF6B35` ground, which is the orange this project's own master already
carried, and `#FFF4EA` mark, the cream the app's panels are drawn on. The
plus stays a punched hole showing the ground rather than a third colour,
so both icons are one drawing on two different grounds. Two colours also
removes the failure mode the last version needed a rule to defend.

Tray PNG is byte-identical again; the .ico ladder (16/24/32/48/64/256) and
.icns entry set are unchanged, and every tracked PNG still matches its
committed dimensions.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 21:49:05 +08:00
mula.liu 06de22b840 release: prepare Shift 0.1.13
Versions and release docs for the two installers.

Numbered 0.1.13 rather than 0.1.12 because 0.1.12 was staged by a commit
that never shipped: the channel still serves 0.1.11, and this batch has
grown well past what that commit described.

Six reported issues:

- 系统小图标改为黑白单色模板图,由系统着色。
- 应用图标与托盘共用一份几何,但在 Dock 与界面里保持彩色。
- Windows 一键安装运行组件必然失败,四个独立原因藏在同一处。
- 钉在屏幕上的图片新增可用的放大/还原按钮。
- 「最近使用」的收藏行带上常驻指示器。
- 新固件在主面板顶部提示,点一下跳到设置 → 软件更新。
- 参照 nex_squid 降低闲置开销:四处采样节奏加上最近列表只解码视线内的图片。

Verified on this host: 191 Rust and 51 frontend tests, `cargo clippy -D
warnings`, and a GUI pass against a signed feed advertising 9.9.9 — the
banner appears on both the probe launch and a later same-day relaunch with
the feed unreachable, so the notice really is restored from disk.

The Windows install fix still wants a real Windows host: the exact prose a
dismissed UAC prompt prints, and whether each package accepts
`--scope user`, are handled defensively rather than verified.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 21:29:30 +08:00
mula.liu c8a5d41eca docs: document the release banner and the shared icon geometry
Two ledger sections, the README paragraphs for the banner, and the 0.1.13
version row.

「升级提示跨启动存活」records the constraint that is invisible in the code:
the probe is throttled to one a day, so a notice held only in memory is
visible on the morning a release is found and invisible on every launch
after — including the launch right after an update installs. It also
records why a restored notice is re-judged rather than trusted, since
remembering a claim is how you end up advertising the version the user is
already running.

「所有图标共用一份几何」records that the consistency the request asked for is
geometric, not chromatic: the tray mark must be flat and alpha-only
because the shell tints it, and the app mark must be coloured because
nothing tints a dock tile. What made the old icon read as another product
was the gradient, the shine, the shadow and six pastel wedge tints — not
the presence of colour.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 21:28:31 +08:00
mula.liu 8a4c9d2b0d feat(icons): one mark, drawn twice — tinted for the shell, coloured for the dock
Reported: "应用的图标问题,要和当前的单色图标保持一致设计" — and clarified:
consistency of *design*, but colour in the panel and the system.

So consistency comes from geometry and filling rules, not from the palette.
`scripts/build-icons.py` now defines the ring once (OUTER/INNER/HUB/GAP/
PLUS_ARM/PLUS_BAR) and emits both marks from it: the tray keeps the alpha-only
flat form because the shell tints it, and the app icon keeps the same figure
in three flat colours drawn from the UI itself — `#FFB25C` wedges and the
`#f04f24` accent the app's own buttons use, on an espresso tile that is also
what shows through the plus punched out of the hub.

What the old icon actually got wrong was not that it was colourful. It was a
gradient tile with a radial shine, a drop shadow and six pastel wedge tints,
which is a different visual language from a crisp flat mark no matter what
hue it wears. Hence the rule: at most three flat colours, and no gradient,
gloss, shadow or per-wedge tint.

The menu-bar icon is byte-for-byte unchanged; the generator reproduces the
committed PNG exactly, so this commit alters only the coloured surfaces. The
hub-inside-a-lighter-ring orientation is deliberately not inverted, because
flipping which end of the mark is dark would read to existing users as a
different product rather than a redraw.

`tauri icon` regenerates the whole tracked set, and the .icns entry set and
.ico size ladder come out identical to the committed ones, so nothing in the
packaging contracts moves.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 21:27:01 +08:00
mula.liu e1fb18bc6a feat(updates): announce a new release where the user is looking
Reported: "当有新固件时,在主面板顶部要显示有升级信息。点击跳转到设置的软件更新."

The banner is cheap; the reason it did not exist is that nothing on the main
panel could know about a release. `useUpdateFlow` was mounted only inside
Settings > 软件更新, so closing that panel dropped the only copy of the state.
Mounting a second copy is what the hook already supports — it reads the status
Rust remembers and subscribes to the broadcasts Rust already sends, so neither
view issues an extra network check, and the banner survives closing Settings.

The notice is persisted, which is the part without an obvious answer. The probe
runs at most once a day, so a remembered status that lives only in memory makes
"available" visible on the morning it is discovered and invisible every launch
after — including the launch straight after an update installs, exactly when the
user is most likely to look. Measured, not theorised: the first launch showed no
banner, and ageing the probe stamp was the only way to make one appear.

Remembering a claim means being wrong about it later, so a restored notice is
re-judged rather than trusted. A version that no longer leads is dropped, since
the user is already running it; `ready` keeps its promise only while the
installer file is really on disk, and otherwise says `available`, which is still
true and merely means downloading again. Restore runs before `setup_tray` so the
tray row cannot contradict the banner, and a copy told to stop checking restores
nothing, because that switch means "don't tell me".

Two banners that used to be mutually exclusive now stack. An update notice and a
broken screen-recording permission are different news, and chaining them meant a
user who fixed the first never learned the second existed.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 21:25:15 +08:00
mula.liu a95aebe1d0 docs: record the measured idle-cost A/B behind the sampling changes
The section quoted the sidecar's own micro-benchmark, which is not a
number anyone can reproduce. Replaced with a per-process A/B against the
installed 0.1.11 over 60 s idle: the sidecar drops 140 ms to 40 ms, and
that row is the only one that can be attributed cleanly, because the
sidecar has no window and so cannot be confounded by whether the main
window is open.

The main-process row is explicitly not offered as "the discovery thread
saved 40%": repeated runs of the same build swing by about 40 ms, the same
order as the difference itself. Saying so is cheaper than letting the next
person quote a coin flip.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 18:24:58 +08:00
mula.liu 9ba619c352 release: prepare Shift 0.1.12
Versions, release docs and the ledger's version row for the two installers.

Both artifacts were built from this tree with the release key baked in, so
either one can verify the signed channel: `Shift-0.1.12-macOS-universal.dmg`
(universal, `Signature=adhoc`, `codesign --verify --deep --strict` and
`hdiutil verify` both clean, no notarization) and
`Shift-Setup-0.1.12-win-x64.exe` (cross-compiled, PE machine `0x8664`
checked, the platform's own frontend confirmed embedded).

Four reported issues, and the fifth request:

- 系统小图标改为黑白单色模板图,由 `scripts/build-tray-icon.py` 重绘。
- Windows 一键安装组件:winget 的良性退出码、未钉源导致的挂死、缺失的提权
  路径,以及装完后进程内 PATH 仍是旧值,四个原因都在同一处。
- 钉在屏幕上的图片新增可用的放大/还原按钮。
- 「最近使用」的收藏行带上常驻指示器。
- 参照 nex_squid 降低闲置开销:伴生进程、Windows 手势监视、发现线程与主窗口
  时钟四处采样节奏,外加最近列表只解码视线内的缩略图。

The Windows install fix still wants a real Windows host: the exact prose a
dismissed UAC prompt prints, and whether each package accepts
`--scope user`, are both handled defensively rather than verified.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:52:32 +08:00
mula.liu ef68121aeb docs: record the release's constraints in the ledger and the READMEs
Three ledger sections, the 0.1.12 version row, and the user-facing lines
they describe.

「Windows 一键安装运行组件」is the fullest of them: four independent defects
hid in ten lines, and each one reads as "安装失败" from the UI, so the
section records which signal decides the outcome (exit code first, prose
only to break a tie) and why the attempt ladder starts on the command line
0.1.11 already sent.

「钉图窗口的放大与还原」and 「闲置时的取样节奏」record constraints that are
invisible in the code and easy to simplify back into a bug: sizing off
`monitor.size()` instead of the work area, mixing logical and physical
pixels between `set_size` and `set_position`, making a silent Shift copy
deaf in order to save 0.03%, and restoring `default_window_icon()` on the
tray because the colour wheel looked friendlier in the source.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:52:01 +08:00
mula.liu 7e3bf5efc1 perf: stop sampling when nothing is looking
Reported: "参考nex_squid的代码,进一步降低软件本身占用的系统资源." The
pattern worth copying out of nex_squid's `useSystemSnapshot` is that a
poll stops when nothing can see its answer. Shift had four places that
polled for the life of the process instead.

- `native/macos/drag-bridge.swift` — a separate tracked process polling at
  30 Hz forever, and allocating a CGEvent each pass to read a cursor
  position nothing wants while no button is held. A/B against the shipped
  0.1.11 binary: 20 ms CPU per 6 s idle is now 0 ms, while 12 s of holding
  the button still costs 30 ms either way, so a gesture is sampled exactly
  as finely as before and an idle Shift stops touching the CPU. It runs at
  10 Hz until the button goes down.
- `src-tauri/src/drag_bridge.rs` — the Windows gesture watch slept 33 ms
  unconditionally. An *enabled* ring keeps 33 ms, and not from
  conservatism: the loop has to observe the press to measure the drag
  threshold from where the button went down, so slowing it does not notice
  a gesture late, it never records it. Only a switched-off ring can afford
  a quarter second, since the one thing it waits for is the switch.
- `src-tauri/src/share.rs` — the discovery loop. Measured on the 0.1.11
  bundle: 0.22% CPU with ShiftDrop on, 0.03% with it off. Switching the
  feature off means "stop announcing", never "be deaf" — a silent copy
  still hears beacons so another machine can still find and send to it, and
  expiry must keep running or an hour-old peer pretends to be live forever.
  So the saving comes from waking less often while silent and from skipping
  bookkeeping when there is no peer to expire, not from probing less.
  Announce and sweep intervals are untouched, so discovery stays as fast.
  `a_silent_copy_still_knows_and_still_loses_peers` pins that distinction.
- `src/components/MainWindow.tsx` — the 30 s clock ticked for the life of
  the app while Shift sits parked in the menu bar with this window hidden,
  re-rendering a list nobody could see. It now exists only while the page is
  visible, and an empty library is not worth a render at all.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:50:57 +08:00
mula.liu 680b4f159e fix(pin): give a pinned image a working enlarge control
Reported: "钉在屏幕上的图片放大按钮无效." There was no enlarge button to
be ineffective — the pin window shipped exactly two actions, copy and
close, so the third press a user went looking for did not exist.

One button now covers both directions: fill the screen, or return to the
size the image was pinned at. An enlarged pin that cannot be shrunk back
is no longer usable as a reference, and a second control for that would
spend hover space on the less common half of the gesture.

Sizing and placement are the whole feature, and both are pinned by tests
because each is correct on the machine that builds it and wrong elsewhere:

- the bound is the monitor's work area, not its size, or the window grows
  under the menu bar and a borderless window cannot be dragged back onto
  itself;
- `set_size` is told in logical pixels and `set_position` in physical
  ones, which on a 2x display is the difference between filling the screen
  and filling it twice from the wrong corner;
- size is set before position, because on a mixed-DPI desktop resizing can
  move a window onto another monitor and change its own scale factor;
- growth is capped at 3x, since the preview is already capped at 1040 px
  and past that the button delivers mosaic, not detail;
- the window grows from its centre and is clamped inside the work area, so
  a pin parked against a screen edge grows inward rather than off.

A fresh pin always opens at the small size. The window is reused rather
than rebuilt, so without that a user who enlarged once would find every
later pin arriving full-screen and soft.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:49:30 +08:00
mula.liu 36d98044cc fix(ui): show a favourite without a hover, and decode only visible thumbnails
Two changes to the same row, so they land together.

Reported: "操作列表中 收藏的文件 前面增加一个指示器." The star that *sets*
a favourite lives in the row's action cluster, and that cluster is
`opacity: 0` until the pointer arrives, so in a list whose entire purpose
is outliving the files it names, a favourited file looked exactly like an
ordinary one until you hovered it. The mark now sits on the leading corner
of the thumbnail, on its own disc so it stays readable over a picture that
happens to be dark, and `pointer-events: none` keeps it from intercepting
the row's open or drag-out.

While the row was open: `loading="lazy"` only defers a decode, it never
releases one. Measured in WKWebView across 250 real screenshots, 13 images
were decoded at rest and the count climbed monotonically to 136 scrolling
to the bottom without ever dropping, because the whole list is laid out in
one scroller and every image is fetched on mount. Rows are now gated on an
IntersectionObserver rooted on the list itself — an ancestor's clip is
applied before the viewport root is consulted, so measuring against the
viewport would make the margin do nothing — holding roughly 20 live bitmaps
across the same scroll. A row that scrolls away gives its bitmap back, and
the kind glyph stands in, which is the face the row already showed before a
thumbnail arrived.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:48:28 +08:00
mula.liu 47f8bc69d9 fix(runtime): make the one-click component install work on Windows
Reported: "在windows机器上实测一键安装组件会失败." Four independent
defects hid inside the same ten lines of `install_target_package`:

- `winget`'s benign codes — 0x8A15002B already installed, 0x8A150016 no
  upgrade applicable — were read as failures, so a machine that already
  had the tool was guaranteed to be told the install failed.
- `--source` was never pinned, so on a host that also carries msstore
  `winget` could block on a source agreement `--silent` never answers,
  and the 15-minute deadline turned a hang into the same failure.
- Machine-level packages (Poppler, FFmpeg, ImageMagick, Typst) install
  into Program Files and need admin, and Shift is an unelevated GUI
  process. There was no elevation path at all.
- Post-install verification could not succeed even when the install did:
  a process keeps the environment block it was launched with, so the
  WinGet Links directory written to the registry never reached the live
  `which` lookup.

Attempts now run unscoped, then `--scope user`, then elevated machine
scope, and success is decided by whether the binary is on disk after the
process PATH has been re-read. The four outcomes a user can act on —
declined prompt, installed-but-not-on-PATH, no package source, timeout —
each say so in both languages instead of "安装失败".

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:46:52 +08:00
mula.liu 287b3af09d fix(tray): let the system draw a black/white mark, not the colour wheel
Reported: "收到系统小图标时采用黑/白单色图标." The tray was handed
`app.default_window_icon()`, the 512 px gradient wheel, and `tray-icon`
scales whatever it is given to 18 pt: on the menu bar and in the Windows
notification area that is a blob, not a mark.

The new icon is drawn flat and alpha-only by `scripts/build-tray-icon.py`,
in the shape of the ring the app itself paints so the two read as one
product, and `icon_as_template` lets macOS tint it black or white per the
menu bar. Windows has no tinting to ask of, so it gets the same glyph at a
size it can actually render.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-19 17:45:07 +08:00
mula.liu 85de468bc3 fix(drop): 拒绝改由光标表达,不再往按钮上叠禁止图标
按钮处理不了这次拖拽时保持 disable,鼠标光标换成禁止符号;能服务的光标仍是
AppKit 画的「+文件」。页面上那一层 .drop-ban 叠加层删掉了。

macOS 上外部文件走原生拖放通道,而 wry 的 draggingEntered:/draggingUpdated:
固定回报 NSDragOperation::Copy,页面改不动那条通道的光标。新增
src-tauri/src/drop_cursor.rs:页面把判定用 set_drop_refusal 交下来,原生侧在
运行时替换 wry 私有类的这两条方法(类名带 crate 版本,按前缀扫描),把 Copy
收窄成 NSDragOperationNone。两次都先调用 wry 自己的实现再改返回值——那次调用
正是 over/dragover 的投递入口,拒绝时提前 return 会让页面再也收不到指针移动,
一次拒绝就粘到整段手势结束。回报 None 时既没有 performDragOperation: 也没有
draggingExited:,所以拒绝期间盯一次鼠标松开,用 drop://cancelled 收起面板状态。
Windows 不需要这套:OLE 的回报跟随页面设置的 dropEffect。

实测:PDF 从「最近使用」和从访达分别拖到「文字识别」,两处都是按钮禁用+光标
禁止、无 hover、松手静默;中途拖到能服务的按钮立刻恢复并正常弹出圆环。
2026-11-07 12:43:06 +08:00
mula.liu 935de413d8 docs: 收录 2026-11 全面评审的修复与约束
评审轮改动此前只在本地:更新链路的下载与校验收紧、分享接收的失败上报与
「完成后在访达中显示」、截图/录屏/文件读取的边界处理,以及新增的
ARCHITECTURE / SPECIFICATION / SECURITY / CONTRIBUTING 四份文档和
publish-release、CI 的调整。 ENGINEERING-NOTES 补上「更新、分享与读取边界」
一节,把这些不应被简化掉的约束写进台账。

这些改动已随 0.1.11 构建物发布,此提交只是让源码与产物在服务器上保持一致。
2026-11-07 12:42:35 +08:00
mula.liu cb758c6a03 fix(drop): disable a spent button and mark it, so both drag paths agree
A file from the file manager arrives through the native drag channel, where wry fixes the macOS drag operation to Copy, so the cursor could never carry the refusal. The answer now lives on the button: it is disabled for the length of the gesture, shows a prohibition sign over its own label, and takes no hover feedback. A Recent row also stops being reported as 'no files' by the native enter, which had lit all three buttons for a file two of them could not serve.
2026-11-07 02:34:44 +08:00
mula.liu f625832856 fix(drop): show a forbidden cursor for spent buttons 2026-11-07 01:15:10 +08:00
mula.liu 3057c65d27 fix(drop): stop the drag-end fallback from eating the drop it waits for
0.1.11 made a dragged row do nothing on every button. The release added to
`dragEnd` landed the gesture immediately, and on macOS the native drop is
reported *after* the button is up: the fallback consumed the gesture with
`dragEnd`'s own position - which Chromium reports as the origin, not as where
the pointer stopped - and the drop that followed was read as a finished
gesture and thrown away. Three buttons, no feedback, on both platforms.

The fallback now waits, and only claims the gesture when it can actually name
a button. A release that aims nowhere stands back, so a real drop that arrives
later still runs, and `landed` keeps the two from both acting. A position of
(0, 0) is treated as no position reported, which is what it is on Chromium, and
answered with the last position the drag moved through.

A row dragged out of the window now carries the file rather than the row. Left
alone the engine photographs whatever is under the pointer, and a Recent row is
a thumbnail, a name, an age, a folder path and five hover buttons - a strip of
the list, which reads as the whole list coming along. The ghost is the file: the
picture the list already decoded, or the extension when there is no picture,
with the name under it, matching the figure the ring draws for a file it is
about to convert.

Rebuilt both 0.1.11 installers from this tree.
2026-11-07 00:53:09 +08:00
mula.liu be84d5640f release: prepare Shift 0.1.11
Versions, release docs and the ledger's version row for the two installers.

Both artifacts were built from this tree with the release key baked in, so
either one can verify the signed channel: `Shift-0.1.11-macOS-universal.dmg`
(ad-hoc signed, `hdiutil verify` valid, no notarization) and
`Shift-Setup-0.1.11-win-x64.exe` (cross-compiled, PE machine `0x8664` checked,
frontend confirmed embedded).

The Windows drop fix needs a real Windows host before it can be called done:
this forge has no second machine, and the two delivery paths that went silent
are exactly the ones only WebView2 exercises.
2026-11-06 23:14:57 +08:00
mula.liu 2bf63f2366 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.
2026-11-06 23:13:53 +08:00
mula.liu 84c4056a0d feat(ui): spend the OCR button instead of explaining it, and unify how the app speaks
Two changes, one goal: the same gesture and the same news should look and read the
same way wherever they happen.

Dropping a file OCR cannot read used to be answered after the fact - the drop ran,
refused, and popped "文字识别仅支持图片格式". The user had to do the wrong thing
first and then be told. Now the decision happens when the drag starts: MainWindow
records the files in flight (`dragPaths`, from the native `enter` payload or from a
Recent row's `dragstart`) and marks the button spent for the whole gesture with
`is-drop-unavailable`, so the refusal is visible before the pointer is committed and
releasing on it is inert and silent. Both drag sources were verified in a production
build, including the reverse case: an image still lights the button and opens the
editor. `over` carries no paths and `dataTransfer` is unreadable during `dragover`,
so the paths have to be registered at the start - a later refactor that reads them
from the move event gets nothing.

The audit that followed found the same class of problem in the messaging, and worse:
the app said one thing three ways.

Prompts were the largest gap. A Rust-authored sentence reached the screen verbatim,
so a Chinese interface answered Convert with `Saved 1 file.`, and macOS's first-run
write-permission failure was one long English line. Rust now names the outcome or the
failure (`outcomeSaved`, `errCaptureBlocked`) and the interface words it; `translate`
still returns an unknown key unchanged, so genuine technical detail - `ffmpeg exited
with status 137` - is reported as it is rather than flattened into a generic line.
`feedback.test.ts` scans the Rust sources and fails on any code without wording in
both languages, and on any outcome the worder does not know; both directions were
checked by breaking them. It also asserts the two dictionaries list identical keys,
which was silently false before.

Durations were arbitrary: the identical share result showed for 2.6s in the ring and
3.6s in the main window, one file's `processing` message lived 12s in one branch and
120s in another, and generic errors used 2200/2400/3000/3200/3800. `FEEDBACK` is now
the only ladder, and `hold` is reserved for tasks that report progress and must not
expire mid-task.

Error text had three normalisation idioms, two inside the same file; `messageFrom()`
is the only one left. Share failures reported twice at once - a banner saying "could
not send" plus a toast naming a different reason - and now report once, in the panel,
with the real reason. The editor's failure notices wore a green check and lasted 1.4s;
a clipboard refusal was silent, and an OCR failure printed into the text box as though
it had been read from the image.

Disabled controls were dimmed at nine different opacities across the app, three
buttons were disabled in JS with no CSS at all, and several `:hover` rules answered a
disabled control. `--dimmed` plus `cursor: default` and `:not(:disabled)` hovers is now
the single treatment, and the OCR drop-target state joins it. Every transient message
is a live region, three unlabeled icon buttons are named, Escape closes the settings
sheet and the first-run panel, the main toast is raised above every sheet of its
window, and nine raw px font sizes went back onto the type ladder.

Out of scope, deliberately: the accent is still ~87 literals rather than one variable,
and the muted warm greys are still written many ways. Both need a visual pass, not a
search and replace.
2026-11-01 16:18:20 +08:00
mula.liu 75405d84c4 release: prepare Shift 0.1.10
Version and release docs for the two installers.

The ledger's drop-gesture section now says which release did what: 0.1.9 removed
the action-ring fallback and added the explaining toast, 0.1.10 removed the toast
and the panel's own drag animation. Both were written as one change until the
published 0.1.9 tree was checked, and it still had the toast and the is-dragging
rule.
2026-11-01 12:48:57 +08:00
mula.liu 45325f0a6c feat(ui): quiet the drop gesture, and refuse files OCR cannot read
Four changes to how the main window answers a drag.

The tray row said "识别图片文字…" where the window says 文字识别, and the ellipsis
made it read like a preview rather than a command. It now carries the same words
as the button, in both languages.

OCR refuses a file it cannot read instead of handing it to the format ring. The
fallback was meant to be helpful - "the format ring is more useful than a failing
OCR run" - but from the user's side it looked like the button they dropped on had
ignored their file and opened something else. A drop on OCR is now either a read
or a refusal that names the reason.

Dragging an outside file and dragging a Recent row are now the same interaction.
The panel used to scale, recolour and swap its heading when a file entered the
window from Finder, while a row dragged from the list did none of that, because
an in-webview drag raises no native drag events. The panel no longer animates at
all: the is-dragging class, its two rules, and the transition they drove are
gone, and feedback lives only on the three buttons, which both paths already
share.

Releasing off a button no longer pops the toast. 0.1.9 added it to explain why
nothing had run, but it fired at the pointer, in a place the user had not chosen
to aim at, and the buttons already show where a drop lands. Off a button,
nothing happens, silently, on both paths.

The version comparison test gains the patch-component case: 0.1.10 is the first
release whose patch number reaches two digits, and the rule was only asserted for
the minor position.
2026-11-01 12:48:36 +08:00
mula.liu b524b69fc8 release: prepare Shift 0.1.9
Version, the release docs and the engineering ledger for the two installers.

The ledger gains a section on the Runtime components panel, because the bug it
records was invisible rather than broken: a dropped `return` made macOS answer
the document-PDF row with a Pandoc pipeline it never uses, so the panel reported
a missing component with no way to install it. The section states the invariant
that a row may not read as missing unless it also offers a way forward, which is
the part a future refactor is most likely to lose again.

README sections that described dropping files as "opens the action ring" now
describe the aimed rule, and the capture-behaviour option is gone from the
Settings tour.
2026-11-01 12:04:03 +08:00
mula.liu e6818e029e feat(ui): drop onto a button, and read the panels again
Three changes to the main window, requested together.

A file drop is now aimed. The three buttons are the only drop targets and the
button you release on is the action it runs; a release anywhere else on the
panel runs nothing and says so, instead of opening an action ring nobody asked
for. This replaces the old fallback in both delivery paths - the DOM handler and
the native webview drop - because two routes to the same gesture must not have
two different rules. dropFiles therefore takes a required action rather than an
optional one, and the actions ring is still reachable from the Shift-drag
gesture and from a file type with no convertible formats.

Recent rows can be dragged back onto those buttons. A row leaves Shift as a real
file drag, so one gesture can be reported twice, once by the DOM and once by the
native events, and which arrives first depends on the engine; recentDrag.landed
lets only the first through. The hint under the buttons names the affordance,
which is otherwise invisible, and all three buttons light up as candidates for as
long as any drag is in flight - a native one via dragging, an internal one via
rowDragging, since a row drag inside the webview does not raise native events.

Type sizes are on one ladder now (--text-3xs to --text-hero) instead of being
invented per rule, which is how the settings drawer drifted down to 7-8px. 92
declarations under 12px became one. The drawer is wider, its tabs are pills, and
the runtime, share, setup and radial surfaces moved onto the same scale.

The capture-behaviour setting is removed: the CaptureAfter enum, its field, its
command and its UI. A finished capture always shows the result card, falling back
to the editor when a card window cannot be created. Stored settings that still
carry captureAfter load unchanged, because the struct does not deny unknown
fields.

Also dropped 23 i18n keys no surface used, one dead re-export in history.ts, and
a stale .home-drop p rule that was outranking the new hint and sizing it as body
copy. tsconfig now turns on noUnusedLocals, noUnusedParameters and
noFallthroughCasesInSwitch, which is what keeps the dead imports from coming
back; the tree already passes all three.
2026-11-01 12:02:24 +08:00
mula.liu 23973cee8f fix(runtime): report the bundled renderer for document PDF on macOS
0.1.8 turned the renderer branch of document_pdf_component into a bare expression,
so the component it built was discarded and every Mac fell through to the Pandoc
row. That row requires a LaTeX or Typst engine macOS never runs, so Settings ->
Runtime components read 'Pandoc PDF pipeline: missing' with no Install button,
because document-pdf has no macOS install target.

The two platforms now have their own function, like every other platform-specific
row in the file, so the fall-through is a compile error rather than a silent one.
The Pandoc half is still real on macOS - it turns a picture-bearing DOCX into HTML
for the renderer - and it keeps its own row and install target.

Two guards cover it: the row must stay bundled on macOS, and no row may read as
missing without either an install entry or a non-external source. The second
reproduces the reported symptom exactly when the fix is reverted. The matching
PDF-engine error now names what the panel actually shows on each platform.
2026-11-01 11:59:42 +08:00
mula.liu 0aa929b2f5 build: bake release key into macOS packages 2026-10-27 18:49:21 +08:00
mula.liu df35111326 release: prepare Shift 0.1.8 2026-10-27 18:45:32 +08:00
mula.liu d9bb079ec2 docs: record discovery, conversion and macOS packaging regressions 2026-10-26 20:24:21 +08:00
mula.liu 708bb5b0b1 v 0.1.7 2026-10-26 20:11:20 +08:00
mula.liu 35cca5987c release: 0.1.6 — discover peers across filtered Wi-Fi 2026-10-26 19:53:35 +08:00
mula.liu 579fc6218a release: 0.1.5 — device discovery survives an upgrade
An upgrade emptied the "Send to a device" list, with nothing in the UI to say why.
share.rs was not the cause: the last commit to touch it is b732b91, which only
recorded received files in the history library.

The cause is the macOS Local Network grant. Builds are ad-hoc signed, so every
rebuild is a new code identity, and the grant is keyed to that identity rather than
to the bundle id - 系统设置 now holds five Shift rows, one per build this machine has
run. The declared NSLocalNetworkUsageDescription was missing, so a new identity was
never asked and simply received no group traffic: beacons still went out, direct
unicast was still answered, only the list stayed empty.

That declaration is bc5d3b8. Both READMEs and the packaged macOS note now name the
permission and say what a denial looks like, because unlike Screen Recording it
produces no error - just an empty list. The Developer ID item in M5 records that
this has now actually cost a user a feature, not merely "may reset approvals".

Also ships the Updates panel button pair from 22ff93a, which was merged after 0.1.4
and never published.

Gates: cargo fmt --check clean, cargo test --lib 152 passed / 2 ignored, pnpm check
clean, pnpm test 38 passed. Channel verified by downloading both artifacts back
from the raw endpoint and re-hashing against the manifest, and by the ignored feed
test run with the release key. 55,504,368 B DMG and 24,521,557 B installer.
2026-10-26 19:14:05 +08:00
mula.liu bc5d3b80d4 fix(share): declare the local network usage description
Discovery stopped working after an upgrade without any change to share.rs: the
last commit to touch it is b732b91, and only to record received files in the
history library.

What the upgrade does change is the code identity. Builds are ad-hoc signed, so
every rebuild is a different binary to macOS, and the Local Network grant is keyed
to that identity rather than to the bundle id - 系统设置 now lists five separate Shift
rows, one per build this machine has run. The copy installed by the upgrade has an
identity macOS has never been asked about.

It also has no way to be asked: NSLocalNetworkUsageDescription was never declared,
and macOS shows no local network prompt without it. The app then simply does not
receive the group traffic, silently. The panel confirms the symptom is not specific
to Shift's port - this Mac received zero mDNS and zero SSDP packets while its own
beacons looped back fine, and unicast to a peer still works, which is how the two
other copies were found by hand.

Declaring the string lets the prompt appear for a new identity. The durable fix is
the stable Developer ID identity already tracked under M5, which stops the grant
from being lost on every single build.
2026-10-26 18:54:25 +08:00
mula.liu ed4acee2e4 docs: record the published 0.1.4 channel
Both artifacts were downloaded back from the raw endpoint and re-hashed against
the manifest rather than read from the local build output, and shift-update.sig
verifies over the manifest's exact bytes against the release public key.

The retired .pkg left the branch with this publish: the tree is rebuilt from
artifacts/ on every run, so dropping it from the build was enough.
2026-10-26 17:36:47 +08:00
mula.liu 48b24acc2f fix(release): derive the public key from either key file
A raw ed25519 private key is 32 bytes and so is its public half, so
'pubkey KEY_FILE' could not tell them apart and printed the private bytes as a
public key. Baking those into a build produces a key no signature can verify
against, and build.rs accepts any 64 hex characters, so the mistake is silent at
build time and shows up on a user's machine as an update check that cannot verify
the manifest.

Anything not named *.pub is now read as the private key it came from and expanded,
so both documented spellings of the command yield the same key.
2026-10-26 17:29:59 +08:00
mula.liu 334082cd9b release: 0.1.4 — figures survive every conversion
Three conversion fixes since 0.1.3, all found with the same two documents:

- DOCX -> PDF kept the text and dropped the pictures, because AppKit's OOXML
  reader returns an attributed string with no attachments at all. An image-bearing
  DOCX now goes through Pandoc into HTML before the same printer, which keeps
  headings, tables and figures. Image-only DOCX files still take the page-scan
  path, and a machine without Pandoc falls back to the old text-only result
  rather than failing.
- Markdown -> DOCX/RTF/HTML lost the same figures for a different reason: a
  Markdown image is a path, Pandoc has to open the file to embed it, and it
  resolves that path against its own working directory, which for a running Shift
  is nowhere near the document. It now gets --resource-path of the source folder.
- A picture that did arrive printed as a cropped fragment. The layout sizes an
  attachment from the density header in the file - 72 dpi when it carries none -
  and ignores CSS, so a 1600 px screenshot asks for 1200 points on a 595 point
  page. The renderer fits oversized attachments to the text column, scaled and
  not resampled. Markdown and HTML documents with wide images are covered too.

The Updates panel's install and discard buttons are one matched pair now, sized to
the panel's own 12px scale instead of the dense 8.5px rows of the Runtime tab they
were borrowed from, and the row drops the discard control while an install is
counting down.

Gates: cargo test --lib 152 passed / 2 ignored, pnpm check clean, pnpm test 38
passed. Artifacts verified from the built bundles, not the build log: the DMG
carries 0.1.4, x86_64 + arm64, Signature=adhoc, and its bundled doc-render places
a wide image at 499pt inside the page; the Windows exe carries the feed URL and
the release public key.
2026-10-26 17:24:22 +08:00
mula.liu 22ff93a5fc fix(updates): make install and discard read as one decision
The row under a verified download took both controls from the Runtime tab, where
rows are dense: .runtime-install is 27px tall at 8.5px text and .settings-link is
a bare 8.5px text link with no box at all. In the Updates panel, whose own status
text, artifact chip and version pill are 12px, that produced an orange pill beside
floating text - the pair did not look like one choice, and the text link did not
read as a button you could press.

They get their own .update-action now, sized to the 12px scale the panel already
uses, and both take the same box so the eye groups them. The commit variant wears
the app's existing primary gradient, so the action that does something is the loud
one and Discard stays the quiet alternative.

"放弃" also stops competing at the moment it stops meaning anything: once the
handoff script is written the app is counting down to exit, so the row collapses
to the single control still in play. update_clear only resets the status, so this
is presentation, not a saved deletion.

updateInstalling was a whole sentence inside a fixed-height pill, which is what
made that button stretch unevenly against its neighbour. It is "正在安装…" now;
the panel's own closing paragraph already says Shift will restart and interrupt a
running conversion, so the button does not have to repeat it.
2026-10-26 16:22:34 +08:00
mula.liu 9950607cd4 fix(markdown): keep images when a document with relative figures is converted
Same class of bug as the DOCX one, different cause. A Markdown image is stored as
a path, so Pandoc has to open the file to embed it - and it resolves that path
against its own working directory, which for a running Shift is nowhere near the
document. 智飞空地一体化低空应用平台技术方案.md references images/system-architecture.png
and images/production-deployment-topology.png; both came back as "Could not fetch
resource", and Pandoc replaced each figure with its alt text. The DOCX was 22 KB
with no word/media entry at all.

Passing --resource-path of the source's own folder fixes DOCX, RTF and HTML in one
line. It is additive rather than a replacement: Pandoc still searches the working
directory too, so a figure that resolved before still resolves - verified with two
images of the same relative name in two different folders, both of which landed in
the output.

md -> pdf already worked, because Pandoc leaves the path untouched there and hands
the HTML to the renderer with a base URL pointing at the document's folder; only
the routes where Pandoc must read the bytes itself were affected. md -> html was
the quieter case: --self-contained promises one portable file, and without the
figures inlined the single HTML opened as a broken image icon.

keeps_markdown_images_when_converting_to_word pins docx and rtf. It fails against
the previous build with "docx ... lost the picture", and the RTF check reads the
pngblip marker rather than assuming a zip.
2026-10-26 15:43:59 +08:00
mula.liu 19602b79f0 fix(docx): keep figures when a DOCX is printed to PDF
Two bugs, both visible in 平台技术方案(带图测试专用).docx: one figure, eleven
tables and 357 paragraphs, whose PDF came out as a text-only document.

First, AppKit's OOXML reader returns the text of a DOCX and silently drops every
inline drawing - an attributed string with zero attachments for a document with a
picture in it. That is not a rendering loss, it is a parse loss, so no margin,
print setting or layout change can recover the figure: by the time the page is
drawn, the picture is simply not in the attributed string. A DOCX whose body
contains an image is now converted by Pandoc into HTML with its media extracted
beside it, and the HTML - which Pandoc reads faithfully, headings, tables and
pictures - goes to the same printer. Image-only DOCX files keep the existing
page-scan path, which runs first, and a machine without Pandoc falls back to the
old text-only behaviour rather than failing.

Second, once pictures could arrive they printed as a cropped fragment of
themselves. The layout sizes an attachment from the density header inside the
file, assumes 72 dpi when there is none, and ignores both bounds and CSS width: a
1600 px screenshot at 96 dpi asks for 1200 points and lands on a 595 pt page.
Measured across PNG pHYs and JPEG JFIF, the placed width is exactly
pixels / dpi * 64. A plain NSTextAttachment does honour bounds, so the renderer
now replaces any oversized attachment with one that fits the text column; the
print operation scales it to the page with the text, landing at 499pt, which is
the printable width the body text already uses. Nothing is resampled, only the
size the layout asks for changes. This also fixes Markdown and HTML documents
with wide images, which had the same overflow.

Both halves are pinned by tests, and both fail against the previous build:
keeps_pictures_when_rendering_a_text_docx_to_pdf sees no image at all, and
fits_a_wide_picture_onto_the_page reports a picture placed 1066.77pt wide on a
595pt page. The second reads the Form XObject's /BBox, so it needs no content
stream decoded and no pixel compared.
2026-10-26 14:50:52 +08:00
mula.liu 58949bebd2 docs: macOS ships the DMG alone, the pkg is retired
The .pkg existed to hand a fresh machine a copy that was not quarantined, so it
opened with no prompt at all. The DMG has now been verified to work on a fresh
machine - drag to /Applications, one approval on first launch - which is the same
one approval the DMG has always needed. So the second container bought nothing
and is dropped: one artifact per platform is less to keep straight, and nothing in
the channel changes.

What the docs say instead of recommending the package: install the DMG, allow the
first launch once. In-app updates still never prompt, because Shift's own
downloader sets no quarantine flag. The macos manifest key stays a DMG for the
reason it always did - the in-app handoff mounts it with hdiutil.

scripts/macos-pkg.sh stays in the tree and RELEASE.md says plainly that it is no
longer part of a release, so the next reader does not wonder whether a publish is
missing it. The 0.1.3 branch still holds the retired package because removing it
means re-publishing; it has no manifest key, so nothing can be served it.

The packaged note is rewritten for the same reason: it told a reader to download a
file that will no longer be built, and its verification section checked the
package instead of the image.
2026-10-26 10:47:48 +08:00
mula.liu f2a1ff6d52 docs: record the macOS packaging scheme next to the artifacts
The ad-hoc signature, the two containers and their different jobs, and how to
verify a download were explained only in docs/RELEASE.md. A user who downloads
Shift-macOS-universal.pkg from the releases branch never sees that file, so the
same write-up now also ships as artifacts/README-macOS-universal.txt, beside the
per-arch Windows notes that already travelled with the channel.

Every claim was checked against the shipped artifacts rather than carried over:
the .pkg payload is Signature=adhoc, pkgutil --check-signature reports no
signature for the package itself, and shasum -c passes on the published set. The
file is force-added to the repository even though artifacts/ is gitignored, so
the scheme is documented where a contributor reads it.
2026-10-26 10:40:33 +08:00
mula.liu 4ed236bd9e docs: correct why older builds opened
The commit before this one claimed releases that opened fine "were ad-hoc signed,
predating the config entry". They were not: every DMG this channel has published,
back to the first 0.1.0, carries Authority=Shift Local Signing, because Tauri selects
a keychain identity itself when signingIdentity is unset.

What survives is the verified part — a self-signed identity that cannot chain to a
trusted root elsewhere, and an ad-hoc binary that gets an approvable prompt instead of
a hard refusal — so the build change stands and only the archaeology is corrected.
2026-10-26 09:48:18 +08:00
mula.liu 42d6424e9f build: sign macOS ad-hoc so other machines can open the app
The published DMG was refused on a fresh Mac as damaged/malware, with only
"Move to Trash" — no 仍要打开, no pane entry to approve. That is not the
"unidentified developer" box, and it is worse than shipping unsigned.

Cause: `signingIdentity: "Shift Local Signing"`, a locally created self-signed
certificate. On the build host it looks healthy — `codesign` reports valid on disk
and satisfies its Designated Requirement, `spctl` even accepts it — but the
certificate lives only in this keychain, is self-issued and CA:FALSE, so it cannot
chain to a trusted root on any other machine. Sequoia turns an unchainable
signature on a quarantined download into a hard refusal.

Releases that opened fine predates that config entry and were ad-hoc signed, which
gets the softer prompt the user can clear (right-click → 打开, or 允许 in 隐私与安全性).
Set signingIdentity to "-" explicitly so this cannot drift back, and rebuild all
three macOS/Windows artifacts from it: app is `Signature=adhoc`, the DMG carries no
signature of its own, and the pkg payload is ad-hoc too.

Docs corrected: the earlier explanation in "macOS packaging" blamed the DMG
container, which was wrong — the container still matters for first install (an
installed app is not left quarantined, so a .pkg opens with no prompt), but the
malware verdict came from the certificate.
2026-10-26 09:44:53 +08:00
mula.liu e9760b8514 release: publish a macOS .pkg so a fresh machine can open Shift
Builds are signed with the self-signed "Shift Local Signing" identity and are not
notarized, so Gatekeeper calls Shift an unidentified developer. Dragging the app out
of the DMG hands that verdict to the app: a fresh machine refuses the first launch
until the user approves it in 系统设置 → 隐私与安全性.

`scripts/macos-pkg.sh` wraps the built bundle with pkgbuild and the channel now
publishes `Shift-macOS-universal.pkg` alongside the DMG. Verified rather than
assumed: installing a quarantined copy of the package leaves the installed app with
only `com.apple.provenance` — no `com.apple.quarantine` — and `codesign --verify
--deep --strict` still passes, because pkgbuild neither re-signs nor strips the
payload (CDHash identical across built bundle, DMG copy and pkg copy: 3b7fac6c…).

The package is unsigned because `productsign` needs an Installer Signing certificate
and this build has only a code-signing identity, so the approval does not vanish — it
moves to the download, once, before anything is installed. `installer -pkg … -target
/` needs no approval at all.

The `macos` manifest key stays a DMG on purpose: `update_install`'s handoff mounts the
image with hdiutil, so pointing the key at a .pkg would break in-app updates.
2026-10-26 09:22:39 +08:00
138 changed files with 8852 additions and 3103 deletions

View File

@ -19,12 +19,18 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin,x86_64-apple-darwin
components: rustfmt, clippy
- run: pnpm install --frozen-lockfile
- run: pnpm mac:drag-bridge
- run: pnpm check
- run: pnpm test
- run: pnpm build
- run: cargo fmt --check
working-directory: src-tauri
- run: cargo test --lib
working-directory: src-tauri
- run: cargo clippy --all-targets -- -D warnings
working-directory: src-tauri
- run: pnpm tauri build --target universal-apple-darwin --debug --bundles app
env:
RUSTUP_TOOLCHAIN: stable
@ -41,18 +47,21 @@ jobs:
node-version: 22
cache: pnpm
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test
- run: pnpm build
- run: cargo check
- run: cargo fmt --check
working-directory: src-tauri
- run: cargo test --lib
working-directory: src-tauri
- run: pnpm tauri build --debug --no-bundle
# The Linux paths (grim, wf-recorder, x11grab, Poppler) are the only ones with no
# build or test job today, so nothing in the repository has ever compiled them.
# Ubuntu's desktop runner carries the GTK and WebKit packages Tauri needs, which a
# macOS machine cannot provide; `scripts/linux/Dockerfile` is the same dependency set
# for building the packages off CI.
# Linux compiles and runs the same TypeScript/Rust tests. Runtime capture still
# needs a real Wayland/X11 desktop; `scripts/linux/Dockerfile` carries the same
# dependency set for building the packages outside this workflow.
linux:
runs-on: ubuntu-22.04
steps:
@ -65,6 +74,8 @@ jobs:
node-version: 22
cache: pnpm
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Install Tauri system dependencies
run: |
sudo apt-get update
@ -73,7 +84,10 @@ jobs:
libayatana-appindicator3-dev librsvg2-dev patchelf
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test
- run: pnpm build
- run: cargo fmt --check
working-directory: src-tauri
- run: cargo test --lib
working-directory: src-tauri
# Bundles deb and AppImage, so this is also the Linux release artifact that

141
CONTRIBUTING.md 100644
View File

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

108
README.md
View File

@ -1,12 +1,12 @@
# Shift
**A radial file workspace for macOS and Windows. Drag a file, release over a wedge, and the conversion happens on your machine.**
**A radial file workspace for macOS and Windows. Drag a file, release over a wedge, and the conversion happens on your machine.** Linux is a source-build target, not a shipped release.
**Language:** English · [简体中文](README.zh-CN.md)
Shift puts file conversion, screenshot, screen recording, annotation, and bilingual OCR behind one radial menu that appears wherever you drop a file. No uploads, no account, no cloud round-trip — every byte is processed locally.
Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour live behind per-platform adapters, so the radial menu, editor, and format catalogue are identical everywhere.
Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour live behind per-platform adapters, so the radial menu, editor, and format catalogue are shared wherever the platform provides the underlying gesture.
---
@ -29,6 +29,7 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
- [Platform status](#platform-status)
- [Build from source](#build-from-source)
- [Architecture](#architecture)
- [Documentation](#documentation)
- [Repository layout](#repository-layout)
- [Privacy](#privacy)
- [Known limitations](#known-limitations)
@ -40,13 +41,13 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour
## What it does
**The radial menu is the whole interface.** Hold `Shift` and drag a file in Finder (or `Shift + Alt` on Windows) and a ring opens under the cursor. Release over a format to convert, or add `Option`/`Alt` to switch to the tool ring. The main window accepts drops too, and its `Convert files` / `File tools` buttons open the same rings for files you pick yourself.
**The radial menu is the whole interface.** Hold `Shift` and drag a file in Finder (or `Shift + Alt` on Windows) and a ring opens under the cursor. Release over a format to convert, or add `Option`/`Alt` to switch to the tool ring. In the main window the same rings open from a file you drop on one of the three buttons, or pick through `Convert files` / `File tools`.
**Everything is type-aware.** The ring only offers what the selected file can actually become, and never repeats the source format — an image can target PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF except its current format, a PPTX offers PDF and Markdown, and a `.key` or `.pages` file offers no conversion wedges at all instead of failing later. The centre shows a glass preview with the file's dimensions and size; a multi-file selection renders a stacked icon deck.
**Batch by default.** Select ten files, drag, and one gesture produces ten outputs. Results land next to each source with a descriptive suffix (`report (compressed).pdf`, `photo (rotated).png`) and never overwrite — a numeric suffix is appended on collision. Settings can collect every result into one folder instead.
**Capture is built in.** Frozen-screen area capture, full-screen capture, and area recording with a floating timer, all aimed at the monitor under the pointer rather than always the primary display. A finished capture hands you a floating result card - Copy, Pin, Send, Reveal, Edit, one click each, and it steps aside on its own - or opens the annotation canvas straight away, whichever you choose in Settings. Recording options only ever offer what your platform actually does: microphone on macOS, frame rate on the FFmpeg backends.
**Capture is built in.** Frozen-screen area capture, full-screen capture, and area recording with a floating timer, all aimed at the monitor under the pointer rather than always the primary display. A finished capture hands you a floating result card - Copy, Pin, Send, Reveal, Edit, one click each, and it steps aside on its own. Recording options only ever offer what your platform actually does: microphone on macOS, frame rate on the FFmpeg backends.
**The rings are yours to arrange.** A saved order rearranges the wedges for each file type and each ring, so the convert you use hourly sits at the top of an image's action ring rather than the bottom. (The Settings screen that edited those orders was removed, so orders are applied from `settings.json` rather than changed in the app.)
@ -72,7 +73,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 files straight onto the main window opens the action ring directly. Drop them **onto a button** instead and that button lights up and runs its own action: **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image.
**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. A button that cannot serve the file you are dragging is **switched off for the length of the gesture**, and the cursor turns into a prohibition sign over it - **OCR** for anything that is not an image, **Convert files** for a format with nothing to convert it into. A switched-off button takes no hover feedback at all, and releasing on it does nothing, silently: no empty ring, no handover to another ring, no message. **File tools** never switches off, because its ring ends in Open, Reveal and Send. The same rule, and the same look, decide a drop in every case - whichever platform you are on, and whether the file came from the file manager or from the Recent list.
**Several files at once.** Multi-select with `⌘`/`Ctrl`-click, then drag. Every file is processed. With 2+ images or 2+ PDFs selected, a **Merge** wedge appears that combines them into a single PDF.
@ -121,7 +122,7 @@ The format ring for a given file type. Every target below is wired in `src-tauri
| PDF | `RTF` | `lopdf` + Pandoc | Text layer becomes the document body; needs Pandoc |
| PDF | `HEIC` | PDFKit / Poppler + `sips` | Pages render as PNG then transcode; needs a system HEIC codec |
| PDF | `PNG` `JPG` `TIFF` | PDFKit / Poppler | One file per page into a `… pages` folder |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit renderer (macOS) · Pandoc elsewhere | macOS path needs no LaTeX or wkhtmltopdf |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit renderer (macOS) · Pandoc elsewhere | macOS path needs no LaTeX or wkhtmltopdf. A DOCX with pictures goes through Pandoc → HTML first, because the AppKit reader drops images |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` | Pandoc | The source format is omitted; Markdown writes as GFM. HTML is a self-contained file with embedded images |
| Presentation `.pptx` | `MD` `PDF` | Pure Rust + Pandoc | Per-slide headings, bullet text and **tables as real Markdown tables**; PDF is a text summary, not a layout render |
| Spreadsheet | `MD` `PDF` | `calamine` / Rust | One Markdown table per sheet; `csv`/`tsv` parsed directly |
@ -160,7 +161,7 @@ The tool ring (`Option + Shift` while dragging). These are one-gesture operation
| Mono | audio | `.m4a`, ` (mono)` | Downmix to single-channel 128k AAC |
| Plain | document | `.txt` | Plain-text dump via Pandoc |
| OCR | image, PDF | `.txt`, ` (OCR)` | See [OCR](#ocr) |
| Edit / Annotate / Redact / Add BG | image | — | Opens the editor with the matching tool preselected |
| Edit / Annotate / Redact / Add BG | image | — | Opens the image editor; choose the annotation tool from its toolbar |
| Open · Reveal | any file | — | Hands off to the system default app or file manager |
## Compression, naming, cancellation
@ -191,13 +192,13 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
**Recording options are honest.** `capabilities()` in `src-tauri/src/recording.rs` reports what the backend actually implements, and the capture toolbar renders only those switches. macOS gets the microphone toggle (`screencapture -g`) and no frame-rate control, because `screencapture -v` has none; Windows and Linux get a frame-rate chip (15 / 24 / 30) that becomes ffmpeg's `-framerate`, and no microphone toggle, because no audio input is wired into the grab yet. Nothing in the UI can promise a setting the encoder would silently drop.
**Result card.** A finished screenshot or recording appears bottom-right as a card with **Copy**, **Pin**, **Send**, **Reveal** and **Edit**. Hovering holds it open; otherwise it steps aside on its own. Settings -> Screenshots chooses what happens at that moment - **Result card** or **Open in editor** - and the editor is the fallback whenever a card window cannot be created.
**Result card.** A finished screenshot or recording appears bottom-right as a card with **Copy**, **Pin**, **Send**, **Reveal** and **Edit**. Hovering holds it open; otherwise it steps aside on its own. The editor is the fallback whenever a card window cannot be created, so a capture is never left with no way to act on it.
**Annotation.** The editor canvas works at native resolution and writes a new PNG, so the source file is never modified.
| Tool | Behaviour |
| --- | --- |
| Rectangle, Arrow, Highlight, Text | Freehand placement, colour and weight per annotation |
| Rectangle, Arrow, Highlight, Text | Freehand placement; each tool has a fixed colour and line width |
| Redact | Solid black bar, burnt into the output — not an overlay |
| Pixelate | Real mosaic sampling of the region underneath, not a translucent fill |
| Blur | Gaussian blur of the region, clipped to the shape you drew |
@ -208,18 +209,19 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
| Cutout | Samples the four corners, averages the background, keys it out to transparency |
| Undo | Pops annotations first, then image-level operations |
| Save copy / Copy | New file with a suffix, or straight to the clipboard |
| Pin | Floats the image as an always-on-top window with copy and close |
| Pin | Floats the image as an always-on-top window with enlarge, copy and close |
**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as editable text. Every editor host has Copy, Save As, Open, Reveal in Folder, OCR and Copy Text.
**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as read-only text previews. Copy, Save As, Open and Reveal are available for every kind. OCR, Copy Text and Pin appear for images only; text is not edited in place. The editor refuses text over 8 MB and images over 64 MB or 40 megapixels, and reports the limit instead of loading them.
## Capture history library
Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. Because it sits outside the bundle, **it survives an update and a reinstall**; the first launch after upgrading also adopts whatever the 0.1 webview had kept in its own store, so a list built before that change is not lost either. The main window's **Recent** card is that library:
- **Search** once the list grows past a few rows; it filters on the file name.
- **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. A favourited row carries a star on its thumbnail, so the list can be read without hovering it.
- **Remove** one row, or **Clear** the library - favorite rows stay.
- **Drag a row out** into Finder, a mail composer or a chat window: the row carries a `file://` URL, so the receiving application gets the file rather than a path string. The plain-text path travels with it for editors.
- **Drag a row onto Convert files, File tools or OCR** to run just that action on a file you already used — the same gesture, inverted. Like any drop it has to land on a button; releasing it back over the list runs nothing.
- Click a row to open it in the editor; the row's other buttons send, reveal, and pin it to the screen.
## OCR
@ -234,12 +236,12 @@ 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:
- Every copy sends a small UDP beacon every two seconds to multicast group `239.255.77.88:47888`, plus a legacy broadcast copy for networks that drop multicast. Beacons carry the machine name, OS, and the ephemeral TCP port that will receive files.
- A beacon that has not been repeated for nine seconds drops the device from the list, so switching networks clears stale entries by itself.
- Every copy sends a small UDP beacon every two seconds to multicast group `239.255.77.88:47888`, a directed broadcast to every active IPv4 subnet, and a unicast subnet sweep that still finds peers when both multicast and broadcast are filtered. Every regular beacon gets a unicast answer, so a peer stays visible instead of flashing once and expiring. Beacons carry the machine name, OS, and the ephemeral TCP port that will receive files.
- A beacon that has not been repeated for fifteen seconds drops the device from the list, so switching networks clears stale entries by itself while older peers have time to answer again.
- File bytes move over a direct TCP connection: a `SHSF` handshake, a JSON header, the payload, then a one-byte acknowledgement, so a sender only reports success once the receiver has the whole file on disk.
Only the local network is involved — nothing reaches the internet. The receiver listens on all interfaces, so a macOS firewall prompt appears the first time Shift shares; allowing it enables both directions.
@ -272,7 +274,7 @@ The menu bar (macOS) and notification area (Windows) icon exposes the actions yo
| Capture area | `Alt+Shift+2` | Start an area screenshot |
| Capture full screen | `Alt+Shift+4` | Grab the monitor under the pointer |
| Record area | `Alt+Shift+3` | Start, or stop, an area recording |
| OCR an image… | — | Pick an image and read its text locally |
| OCR | — | Pick an image and read its text locally |
| Update available *x.y.z* | — | Only while an update is available; opens Settings → Updates |
| Quit Shift | `Cmd/Ctrl+Q` | Exit; an in-flight recording is finalised first |
@ -292,11 +294,13 @@ Each is overridable in Settings. File actions offer a *collect everything in one
## Updates
A new macOS machine installs **`Shift-0.1.13-macOS-universal.dmg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer. Double-click the image, drag `Shift.app` to /Applications, then allow the first launch once (right-click → Open, or 允许 in System Settings → Privacy & Security). In-app updates download the same image without a browser, so they never prompt. Details in `docs/RELEASE.md`.
The update channel is this repository: a `releases` branch holding the installers plus `shift-update.json`, which names each artifact, its size and its SHA256. The feed URL is derived from the git remote at build time - Gitea, GitHub and GitLab forms are known, and `SHIFT_UPDATE_URL` overrides it - so no update service has to be deployed anywhere.
Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A downloaded installer is checked twice before it can be installed: exact byte length, then a recomputed SHA256 that must match the manifest. A mismatch deletes the file and says so, so nothing half-downloaded launches. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`).
Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A release that has been found is announced at the top of the main window - **Shift x.y.z is available**, with one button that opens Settings -> Updates - and it stays announced across restarts, including the restart that follows an update, because the notice is remembered on disk rather than held in memory. Since the probe itself runs at most once a day, a notice that only lived in RAM would be visible on the morning it was discovered and invisible every launch after. A downloaded installer must match the manifest's exact byte length and recomputed SHA256, and both checks run again immediately before the handoff that installs it. A mismatch deletes the file and reports the error, so a truncated or replaced installer never launches. **Discard** removes the downloaded installer as well as the status. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`).
**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update.
**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The helper receives its paths as process arguments or environment variables, never by splicing them into the shell or batch script; the Windows launcher also keeps the outer quote layer `cmd.exe /C` otherwise strips from a path containing spaces. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update.
## External dependencies
@ -313,9 +317,15 @@ Core conversion, radial menu, capture, and OCR work with nothing installed. Thes
| LAME | MP3 encode when FFmpeg lacks `libmp3lame` | rare | rare | rare |
Settings -> **Runtime components** shows the tools found on the current machine,
their versions and paths. Missing Pandoc, Typst, FFmpeg, Poppler and ImageMagick can be
installed from the same panel through Homebrew on macOS or WinGet on Windows,
then detected again automatically. Tools are also found on `PATH` and their
their versions and paths, and what each one unlocks on this platform. A row that reads
as missing also says how to fix it: anything installable carries an **Install** button
(Pandoc and FFmpeg on macOS through Homebrew; Pandoc, FFmpeg, Poppler, ImageMagick and
Typst on Windows through WinGet), and a row with no button is either built in or simply
not used on that platform. When more than one row is missing, the panel header adds
**Install all**, which sends the missing rows as one request: the installs run one after
another because the package managers hold a single lock, and a package that answers two
rows — Poppler, which serves both PDF rows on Windows — is installed once. Tools are also
found on `PATH` and their
standard install locations at call time, so a missing dependency degrades one
wedge rather than the app.
@ -329,7 +339,7 @@ wedge rather than the app.
| Monitor under cursor | Yes | Yes | `grim` output selection |
| Area recording | `screencapture -v`, audio via `-g` | FFmpeg `x11grab` | `wf-recorder` under Wayland, FFmpeg `x11grab` under X11 |
| Recording frame-rate control | not offered (`screencapture` has none) | 15 / 24 / 30 | 15 / 24 / 30 (`-r` / `-framerate`) |
| History library, drag a row out | Yes | Yes | Yes |
| History library, drag a row out and back onto a button | Yes | Yes | Yes |
| Git-backed updates: SHA256 gate, optional signed manifest | Yes | x64 is the published installer; an ARM machine gets it through the `windows` fallback | Checks and downloads; nothing published for Linux, so the answer is "no artifact" |
| Image convert and edit | Yes | Yes | Yes |
| HEIC / AVIF encode | `sips` | ImageMagick | ImageMagick |
@ -361,19 +371,17 @@ 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.13-macOS-universal.dmg` and `Shift-Setup-0.1.13-win-x64.exe`. The macOS app is one universal Mach-O including universal drag, PDF-render and doc-render sidecars. Windows ARM64 uses the x64 installer through the update manifest's compatibility fallback. Full details are in `docs/BUILD_WINDOWS.md` and `docs/RELEASE.md`.
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. Dev builds signed with a local certificate keep those grants stable across rebuilds; distribution needs Developer ID plus notarization.
**Permissions (macOS).** Screen Recording for capture, Files & Folders for the output folders you choose, Microphone when recording with audio, and Local Network for **Send to a device**. Shift checks Screen Recording before opening the overlay, so a denial surfaces an actionable error rather than a black screenshot. A denied Local Network grant is quieter: Shift still sends its beacons and still answers anyone who addresses it directly, but it receives no group traffic, so the device list simply stays empty. Ad-hoc signed builds get a new code identity on every rebuild and macOS keys these grants to that identity, so an upgrade can ask again; distribution with Developer ID keeps them stable.
## Architecture
@ -413,6 +421,17 @@ OCR: Tesseract.js WASM + bundled eng/chi_sim, in-process, offline
The radial hit-test is pure geometry — one polar calculation shared by native pointer events, webview hover, and the Windows drop payload — so ring behaviour does not drift between platforms.
## Documentation
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — process/window model, module boundaries, event and data flows.
- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) — product behaviour, output naming, platform differences and acceptance criteria.
- [`docs/SECURITY.md`](docs/SECURITY.md) — trust boundaries, update integrity, LAN-transfer limits and residual risks.
- [`CONTRIBUTING.md`](CONTRIBUTING.md) — development setup, test gates and release checks.
- [`docs/README.md`](docs/README.md) — index of every technical and release document.
- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) — regression ledger for paths that must not be simplified back into earlier failures.
- [`docs/RELEASE.md`](docs/RELEASE.md) — release channel, signing and update handoff.
- [`docs/ROADMAP.md`](docs/ROADMAP.md) and [`docs/MOBILE.md`](docs/MOBILE.md) — future work and the mobile plan.
## Repository layout
```text
@ -424,22 +443,21 @@ native/macos/ Swift sidecars: drag bridge, PDF renderer, doc renderer,
compiled into src-tauri/binaries/ by pnpm mac:drag-bridge
scripts/ OCR staging, macOS sidecars, Windows installer, release build,
manifest publish and manifest signing
public/tesseract/ WASM core + traineddata, generated, not committed
public/tesseract/ WASM core + traineddata; refreshed by pnpm prepare:ocr and
tracked so a clean checkout builds and runs OCR offline
assets/ app icon source
src-tauri/icons/ generated app icons per platform
docs/ Windows build guide, release/update channel, roadmap, mobile plan
scripts/linux/ Dockerfile that builds the Linux deb/AppImage off CI
docs/ architecture, behaviour specification, security model, release
guide, engineering ledger, roadmap and mobile plan
scripts/linux/ Dockerfile that builds Linux deb/AppImage packages
.github/workflows/ CI definitions for macOS, Windows and Linux (see Contributing)
FileFlipper/ separate companion project, its own repository
```
## Privacy
Shift makes no internet requests for anything it does to your files. They are read, converted, and written locally; OCR runs in-process against bundled models; the history library is a local file. Nothing is uploaded, and nothing is collected.
Two paths touch the network, and neither carries file content unless you ask: the **update check** fetches a manifest over HTTPS at most once a day - and an installer only when you press the button - while **Send to a device** talks to your local network alone.
The one exception is opt-in by usage: **Send to a device** talks to your local network only — UDP beacons on `239.255.77.88:47888` plus a direct TCP connection between the two machines, carrying the machine name so each side can label the other. It is inert until you open that picker or another Shift sends you a file.
Two paths touch the network, and neither carries file content unless you explicitly start that feature. The **update check** fetches a manifest over HTTPS at most once a day; it downloads an installer only when you press the button. **Send to a device** uses UDP beacons on `239.255.77.88:47888` and a direct TCP connection only to the machine you choose (or from another Shift that offers you a file). Discovery is silent while sharing is disabled, and a transfer begins only after the receiver accepts. LAN traffic is not authenticated or encrypted; [`docs/SECURITY.md`](docs/SECURITY.md) describes that boundary.
## Known limitations
@ -448,13 +466,15 @@ The one exception is opt-in by usage: **Send to a device** talks to your local n
- `.doc`, `.pages`, `.ppt`, `.key` and `.numbers` are recognised but not parsed — export to DOCX/PPTX/XLSX first.
- HEIC/HEIF/AVIF are read through the system decoder, so conversion and the pixel tools both accept them. Neither format can be written on this path, so a pixel tool applied to one produces a PNG; AVIF is not an export target at all.
- PDF compression resamples embedded images to at most 1440 px as q60 JPEG. It deliberately skips anything it cannot prove it can round-trip — masks, indexed or CMYK colour, JPX/JBIG2/CCITT — so exotic scans may still resist shrinking.
- Windows recording and media conversion require `ffmpeg` on `PATH`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11, and neither path is exercised by the forge this repository is hosted on, so treat Linux capture as build-verified only.
- Windows recording and media conversion require `ffmpeg` on `PATH`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11. Those runtime paths are not exercised by the macOS development host, so treat Linux capture as build-verified until checked on real hardware.
- Linux is a build target, not a shipped product: no deb or AppImage is published, so the update channel carries no `linux` key and a Linux build finds nothing to download. `scripts/linux/Dockerfile` and the `linux` job in CI remain the recipe for anyone who wants one.
- Dragging a library row out uses the webview's file-URL drag support. It is the standard `text/uri-list` payload with a `file://` entry plus the plain path, and it needs a gesture-level check on each platform; until then, **Send**, **Reveal** and the row's own buttons are the guaranteed paths for handing a file over.
- LAN sharing needs a network that allows peer traffic. Multicast is skipped by some guest and corporate Wi-Fi; those networks still work over the broadcast and unicast fallbacks, but two copies cannot meet across a router that isolates clients.
- Dragging a library row out uses the webview's file-URL drag support. It is the standard `text/uri-list` payload with a `file://` entry plus the plain path, and it needs a gesture-level check on each platform; until then, **Send**, **Reveal** and the row's own buttons are the guaranteed paths for handing a file over. Dropping a row back onto Shift is checked: one gesture reports through the DOM, the native webview drop, or both, and the `landed` flag in `MainWindow.tsx` lets only the first through — the invariants are in `docs/ENGINEERING-NOTES.md`.
- LAN sharing needs a network that allows peer traffic. Multicast is skipped by some guest and corporate Wi-Fi; those networks still work over the broadcast and unicast fallbacks, but two copies cannot meet across a router that isolates clients. The discovery invariants, permission checks and regression matrix are in `docs/ENGINEERING-NOTES.md`.
- On Windows only one Shift copy per machine can hold the discovery port, so extra instances do not appear as peers.
- Windows and Linux paths are compile-verified here, and the forge hosting this repository runs no Actions, so nothing is ever built by CI on your behalf. Gesture-level QA needs real Windows and Linux hardware.
- Windows and Linux paths are compile-verified here and covered by the repository's CI definition where a runner is available; gesture-level QA still needs real Windows and Linux hardware.
- Signing identity changes on macOS may require re-approving Screen Recording and Accessibility.
- LAN sharing has no authentication or encryption. An accepted transfer proves only that you accepted an offer, not who sent it; use the feature on trusted networks.
- Office ZIP/XML parsing and PDF rendering still lack one shared resource quota across every codec and external renderer. Editor previews are bounded, but unusually large or adversarial documents should be treated as untrusted input.
Roadmap: `docs/ROADMAP.md`.
@ -494,9 +514,9 @@ Quit from the tray and delete the app. Nothing is written outside your output fo
## Contributing
Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`. Adding a tool is one id in the right list in `src/lib/radialOrder.ts`, its label, its icon in `WEDGE_ICONS`, and one match arm in `executeAction` - the ring renders the same catalogue, so it appears with no other registration. Run `pnpm check`, `pnpm test`, `pnpm build` and `cargo test --lib` before pushing.
Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`. Adding a tool is one id in the right list in `src/lib/radialOrder.ts`, its label, its icon in `WEDGE_ICONS`, and one match arm in `executeAction` - the ring renders the same catalogue, so it appears with no other registration. The full pre-push sequence is `pnpm check`, `pnpm test`, `pnpm build`, `cargo fmt --check`, `cargo test --lib`, `cargo clippy --all-targets -- -D warnings` and `git diff --check`; [`CONTRIBUTING.md`](CONTRIBUTING.md) has the platform setup and manual matrix.
`.github/workflows/ci.yml` carries macOS, Windows and Linux jobs, but **the forge hosting this repository has no Actions runner**, so those jobs are definitions rather than a live guarantee: nothing is built until a GitHub mirror, a Forgejo Actions instance, or a contributor runs them. The four commands above are what CI would run, plus `pnpm tauri build` per platform; `scripts/linux/Dockerfile` builds the Linux packages on a plain Docker host.
`.github/workflows/ci.yml` defines macOS, Windows and Linux jobs. The workflow runs type checks, TypeScript tests, Rust formatting and tests on every job, plus Clippy and a universal macOS app build. Whether the current forge executes it depends on whether that forge has a runner configured; a local run remains the release gate, and no CI result should be inferred without a linked log. Full setup and the pre-push checklist are in [`CONTRIBUTING.md`](CONTRIBUTING.md).
**Forks and derivative works are welcome.** You may use, modify, redistribute, and build on this code commercially, provided you keep the copyright notice and the LICENSE file.

View File

@ -1,12 +1,12 @@
# Shift
**面向 macOS 与 Windows 的环形文件工作台。拖住文件,松开在某个扇区上,转换就在你自己的机器上完成。**
**面向 macOS 与 Windows 的环形文件工作台。拖住文件,松开在某个扇区上,转换就在你自己的机器上完成。** Linux 是可从源码构建的目标,不是已发布产品。
**语言:** [English](README.md) · **简体中文**
Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部收进一个环形菜单,它出现在你放下文件的地方。不上传、不注册、不经云端中转——每一个字节都在本地处理。
基于 Tauri 2、Rust、React 与 TypeScript 构建。原生截屏与拖拽行为封装在各平台适配器之后,因此环形菜单、编辑器与格式目录在所有平台上完全一致。
基于 Tauri 2、Rust、React 与 TypeScript 构建。原生截屏与拖拽行为封装在各平台适配器之后,因此只要平台提供对应手势,环形菜单、编辑器与格式目录就保持一致。
---
@ -29,6 +29,7 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
- [平台支持情况](#平台支持情况)
- [从源码构建](#从源码构建)
- [架构](#架构)
- [技术文档](#技术文档)
- [仓库结构](#仓库结构)
- [隐私](#隐私)
- [已知限制](#已知限制)
@ -40,13 +41,13 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部
## 能力概览
**环形菜单就是全部交互。** 在访达中按住 `Shift` 拖动文件(Windows 为 `Shift + Alt`),圆环会出现在光标下方。松开在某个格式上即完成转换;再加上 `Option`/`Alt` 可切换到工具环。主窗口同样接受拖放,其「文件转换」与「文件工具」按钮会先让你挑选文件,再弹出同一个圆环。
**环形菜单就是全部交互。** 在访达中按住 `Shift` 拖动文件(Windows 为 `Shift + Alt`),圆环会出现在光标下方。松开在某个格式上即完成转换;再加上 `Option`/`Alt` 可切换到工具环。在主窗口里,把文件拖到三个按钮之一也会弹出同一个圆环,或者用「文件转换」「文件工具」先挑文件再弹环。
**一切按类型驱动。** 圆环只列出所选文件真正能变成的格式,并且不会重复显示文件自身的格式——图片可在 PNG/JPG/WEBP/HEIC/TIFF/BMP/GIF/PDF 之间转换,但当前格式不会出现目标;PPTX 给出 PDF 与 Markdown,而 `.key`、`.pages` 文件不会给出任何转换扇区,而不是等你点击后才失败。中心是毛玻璃预览,显示尺寸与体积;多选文件会渲染成一叠层叠图标。
**默认批量处理。** 选中十个文件、一次拖拽,就产出十个结果。结果保存在源文件旁边并附带描述性后缀(`report (compressed).pdf`、`photo (rotated).png`),永不覆盖——重名时自动追加序号。也可在设置中改为统一收集到一个文件夹。
**截图能力内置。** 冻结画面的区域截图、全屏截图,以及带悬浮计时器的区域录屏;一律对准光标所在的显示器,而非固定主屏。一次截图完成后会弹出一张浮动结果卡片——复制、钉住、发送、在文件夹中显示、编辑,各一键完成,稍候自行退场;也可在设置里改成直接进入标注画布。截图与录屏选项只给出当前平台真正支持的开关:macOS 提供麦克风,FFmpeg 后端提供帧率。
**截图能力内置。** 冻结画面的区域截图、全屏截图,以及带悬浮计时器的区域录屏;一律对准光标所在的显示器,而非固定主屏。一次截图完成后会弹出一张浮动结果卡片——复制、钉住、发送、在文件夹中显示、编辑,各一键完成,稍候自行退场。截图与录屏选项只给出当前平台真正支持的开关:macOS 提供麦克风,FFmpeg 后端提供帧率。
**圆环顺序由你决定。** 已保存的顺序会按文件类型、按环重新排列扇区,最常用的转换不再压在扇区环的最下面。(调整顺序的设置标签页已移除,顺序改由 `settings.json` 提供,应用内暂无修改入口。)
@ -72,7 +73,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
**使用工具(`Option + Shift`,Windows 为 `Alt + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Alt`,即可在格式环与工具环之间来回切换。
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。直接把文件拖到主窗口上,会直接打开操作环。**拖到按钮上**则按钮会高亮并只执行它自己的操作:「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。
**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。**处理不了的按钮会在这次拖拽期间被直接禁用,光标同时变成禁止符号**:不是图片的文件会禁用「文字识别」,没有任何可转换目标的格式会禁用「文件转换」。被禁用的按钮没有任何 hover 反馈,松手时什么都不执行、安静地不做,既不会弹出一个空圆环,也不会转交给别的圆环,也不会弹提示。「文件工具」永远不会被禁用,因为它的环里总有打开、在文件夹中显示与发送。同一条规则、同一种观感,在所有平台上、无论文件来自访达/资源管理器还是「最近使用」,判定结果都一致。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。
**一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。
@ -121,7 +122,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
| PDF | `RTF` | `lopdf` + Pandoc | 以文字层作为正文;需要 Pandoc |
| PDF | `HEIC` | PDFKit / Poppler + `sips` | 先渲染为 PNG 再转码;需要系统 HEIC 编码器 |
| PDF | `PNG` `JPG` `TIFF` | PDFKit / Poppler | 每页一个文件,输出到 `… pages` 文件夹 |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit 渲染器(macOS)· 其他系统 Pandoc | macOS 路径不需要 LaTeX 或 wkhtmltopdf |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit 渲染器(macOS)· 其他系统 Pandoc | macOS 路径不需要 LaTeX 或 wkhtmltopdf。带图片的 DOCX 会先经 Pandoc 转成 HTML,因为 AppKit 读取器会丢弃图片 |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` | Pandoc | 自动省略源格式;Markdown 以 GFM 写出。HTML 为图片内嵌的独立单文件 |
| 演示文稿 `.pptx` | `MD` `PDF` | 纯 Rust + Pandoc | 按页生成标题、要点文字,**表格会输出为真正的 Markdown 表格**;PDF 仍是文字摘要版,非版面还原 |
| 电子表格 | `MD` `PDF` | `calamine` / 纯 Rust | 每个工作表一张 Markdown 表;`csv`/`tsv` 直接解析 |
@ -160,7 +161,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普
| 单声道 | 音频 | `.m4a`,` (mono)` | 下混为单声道 128k AAC |
| 纯文本 | 文档 | `.txt` | 通过 Pandoc 导出纯文本 |
| 文字识别 | 图片、PDF | `.txt`,` (OCR)` | 见 [OCR](#ocr) |
| 编辑 / 标注 / 打码 / 加背景 | 图片 | — | 打开编辑器并预选对应工具 |
| 编辑 / 标注 / 打码 / 加背景 | 图片 | — | 打开图片编辑器,在工具栏中自行选择标注工具 |
| 打开 · 在文件夹中显示 | 任意文件 | — | 交由系统默认应用或文件管理器 |
## 压缩、命名与取消
@ -191,13 +192,13 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
**录屏选项是诚实的。** `src-tauri/src/recording.rs` 中的 `capabilities()` 报告当前后端真正实现的能力,截图工具条只渲染这些开关。macOS 有麦克风开关(`screencapture -g`)而没有帧率选项,因为 `screencapture -v` 根本不支持帧率;Windows 与 Linux 提供 15 / 24 / 30 三档帧率,它会成为 ffmpeg 的 `-framerate`,但没有麦克风开关,因为抓屏尚未接入音频输入。界面上不存在“按了却被编码器默默忽略”的选项。
**结果卡片。** 截图或录屏完成后,右下角出现一张卡片,提供**复制**、**钉住**、**发送**、**在文件夹中显示**、**编辑**。鼠标悬停时卡片停留,否则自行退场。设置 → 截图 可选择这一刻的行为是**结果卡片**还是**在编辑器中打开**;当卡片窗口无法创建时会自动回退到编辑器。
**结果卡片。** 截图或录屏完成后,右下角出现一张卡片,提供**复制**、**钉住**、**发送**、**在文件夹中显示**、**编辑**。鼠标悬停时卡片停留,否则自行退场。当卡片窗口无法创建时会自动回退到编辑器,因此一次截图不会落不到任何后续操作上。
**标注。** 编辑器画布按原始分辨率工作,并写出新的 PNG,因此源文件永远不会被修改。
| 工具 | 行为 |
| --- | --- |
| 矩形、箭头、高亮、文字 | 自由绘制,每条标注可单独设置颜色与粗细 |
| 矩形、箭头、高亮、文字 | 自由绘制;每种工具使用固定配色与线宽 |
| 打码 | 实心黑色遮挡条,直接烧入输出图像——不是覆盖层 |
| 马赛克 | 对下方区域做真实采样降采样,不是半透明填充 |
| 模糊 | 对区域做真正的高斯模糊,并按绘制形状裁切 |
@ -208,18 +209,19 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
| 抠图 | 采样四角、求平均背景色,并将其抠为透明 |
| 撤销 | 先回退标注,再回退图像级操作 |
| 保存副本 / 复制 | 另存为带后缀的新文件,或直接写入剪贴板 |
| 钉在屏幕上 | 将图片浮为置顶窗口,带复制与关闭按钮 |
| 钉在屏幕上 | 将图片浮为置顶窗口,带放大、复制与关闭按钮 |
**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以可编辑文本打开。每个编辑器都提供复制、另存为、打开、在文件夹中显示、文字识别与复制文字。
**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以**只读文本预览**打开。所有类型都提供复制、另存为、打开与在文件夹中显示;文字识别、复制文字与钉图只出现在图片编辑器中。文本不会在应用内就地编辑。文本超过 8 MB,或图片超过 64 MB / 4000 万像素时,编辑器会报告上限而不是加载。
## 截图历史库
每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。这份文件在应用包之外,**升级与重装都不会清空它**;升级后的首次启动还会接管 0.1 版本留在 Webview 自己的存储里的旧记录,因此那条改动之前积累的列表也不会丢。主窗口的「最近使用」卡片就是这个历史库:
- 列表超过几行后出现**搜索**框,按文件名过滤。
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。收藏的行会在缩略图角上带一颗星,不用悬停就能看出哪些是收藏的。
- **移除**单行,或**清空**整个库——收藏项会保留。
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径与 Shift 内部类型,供编辑器与圆环使用。
- **把某一行拖出去**即可交给访达、邮件撰写窗口或聊天软件:该行携带 `file://` 链接,因此接收方拿到的是文件本身而不是一段路径文本;同时附带纯文本路径,供编辑器使用。
- **把某一行拖到「文件转换 / 文件工具 / 文字识别」上**,就直接对这份用过的文件执行该操作——同一种手势反过来用。和所有拖放一样,它必须落在按钮上,拖回列表不会执行任何操作。
- 单击某一行在编辑器中打开;行内其余按钮负责发送、在文件夹中显示、以及钉在屏幕上。
## OCR
@ -236,12 +238,12 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 AirDrop 式传输。把鼠标移到「最近使用」的任意一行点击发送按钮,或打开文件的「文件工具」环并松开在「发送」扇区上——两种入口都会弹出每台设备一张卡片的设备选择面板,点击卡片即刻开始传输。工具环对每一种文件类型都提供「发送」,选中多个文件时按一批一起发送。
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
没有对方同意,文件不会落地:接收方会弹出一张小卡片,写明发送者与文件名,并提供「接收」「拒绝」两个按钮以及倒计时。点击拒绝、关掉卡片或任其超时,都会在文件字节开始传输之前就中止本次分享。多文件批次只会询问一次,同一批的其余文件随后自动接收。接收后的文件写入对方 Shift 的输出文件夹,出现在对方的「最近使用」列表里,同时弹出提示告知是谁发来的。是否顺带把访达(或资源管理器)带到前台,由「完成后在访达中显示」这个开关决定,与转换完成时的行为一致;一批文件只在最后一个落地时显示一次。同名文件自动追加 ` 2`、` 3`,传输中断不会留下写了一半的文件。
无需服务器、无需配置,发现机制如下:
- 每个实例每两秒向组播组 `239.255.77.88:47888` 发送一次小型 UDP 广播,并额外发送一份传统广播,以兼容丢弃组播的网络。广播内容包含机器名、操作系统,以及用于接收文件的动态 TCP 端口。
- 九秒内没有再次收到广播,设备就会从列表移除,因此切换网络后过期条目会自动消失。
- 每个实例每两秒向组播组 `239.255.77.88:47888` 发送一次小型 UDP 广播,并额外向每个已启用的 IPv4 子网发送定向广播;如果路由器同时丢弃组播与广播,还会通过单播扫描同一网段。每个普通信标都会得到一次单播回应,因此设备不会只闪现一次后过期。广播内容包含机器名、操作系统,以及用于接收文件的动态 TCP 端口。
- 十五秒内没有再次收到广播,设备就会从列表移除;这既能在切换网络后清掉过期条目,也给旧版本的再次回应留出时间。
- 文件字节通过直连 TCP 传输:`SHSF` 握手、JSON 头、文件内容,最后一字节确认;只有接收方已完整落盘,发送方才会报告成功。
整个过程只涉及本地网络——不会有任何数据走到互联网。接收端监听全部网卡,因此 macOS 首次分享时会弹出防火墙授权提示,允许后双向均可用。
@ -274,7 +276,7 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
| Capture area | `Alt+Shift+2` | 开始区域截图 |
| Capture full screen | `Alt+Shift+4` | 截取光标所在显示器 |
| Record area | `Alt+Shift+3` | 开始或停止区域录屏 |
| OCR an image… | — | 选择图片并在本机识别文字 |
| OCR | — | 选择图片并在本机识别文字 |
| Update available *x.y.z* | — | 仅在有可用更新时出现;打开设置 → 软件更新 |
| Quit Shift | `Cmd/Ctrl+Q` | 退出;若有正在进行的录屏会先收尾保存 |
@ -294,11 +296,13 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
## 软件更新
新的 macOS 机器请安装 **`Shift-0.1.13-macOS-universal.dmg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者。双击挂载镜像,把 `Shift.app` 拖进「应用程序」,然后允许首次启动一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。软件内升级自己下载的是同一个镜像、不经浏览器,因此不会弹窗。详见 `docs/RELEASE.md`。
更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。
Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。下载完成的安装包在安装前要通过两道校验:字节数完全一致,以及重新计算的 SHA256 与清单一致。任一不符即删除文件并明确报错,因此半成品永远不会被启动。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。
Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。发现的版本会显示在主窗口顶部——「Shift x.y.z 可以升级了」,旁边一个按钮直接跳到设置 → 软件更新——并且**跨启动保留**,包括升级装完之后的那一次启动:提示是记在磁盘上的,不是只存在内存里。探测本身一天最多跑一次,所以只活在内存里的话,新版本只在被发现的问题当天出现,之后每次启动都再也看不到。下载完成的安装包必须与清单的体积和重新计算的 SHA256 一致,而且这两项会在交接给安装脚本前**再次校验**。任一不符即删除文件并明确报错,因此半成品或被替换的安装包永远不会启动。点击「丢弃」会同时删除已下载的安装包和状态。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。
**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。
**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。辅助脚本通过进程参数或环境变量接收路径,路径不会被拼接进 shell 或批处理脚本文本;Windows 启动器还保留了一层外层引号,否则 `cmd.exe /C` 会把含空格路径的首尾引号剥掉。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。
## 外部依赖
@ -314,7 +318,7 @@ Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手
| ImageMagick `magick` | HEIC/HEIF/AVIF 输入与 HEIC 输出 | 不需要(`sips`) | 需要 | 需要 |
| LAME | 当 FFmpeg 缺少 `libmp3lame` 时的 MP3 编码 | 少见 | 少见 | 少见 |
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,并可一键安装缺失的 Pandoc、Typst、FFmpeg、Poppler 与 ImageMagick。macOS 使用 Homebrew,Windows 使用 WinGet;安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
Shift 会在设置 →「运行组件」中显示当前机器实际找到的工具、版本和路径,以及它们在本平台各自负责什么。显示为缺失的行同时给出出口:能装的都带**安装**按钮(macOS 通过 Homebrew 安装 Pandoc 与 FFmpeg;Windows 通过 WinGet 安装 Pandoc、FFmpeg、Poppler、ImageMagick 与 Typst),没有按钮的行说明该能力是内置的,或在本平台根本不会用到。缺失不止一项时,面板标题栏还会给出**一键安装 N 个组件**,把所有缺失项作为一个请求提交:安装依次执行(包管理器同一时刻只允许一个安装),而一个包能回答多行时只装一次(Windows 上 Poppler 同时服务两行 PDF)。安装后在界面中自动重新检测,无需重启。工具在调用时也会从 `PATH` 及系统常见安装目录查找,因此缺失某个依赖只会影响对应的扇区,不会影响整个应用。
## 平台支持情况
@ -326,7 +330,7 @@ Shift 会在设置 →「运行组件」中显示当前机器实际找到的工
| 跟随光标所在显示器 | 支持 | 支持 | `grim` 输出选择 |
| 区域录屏 | `screencapture -v`,`-g` 录麦克风 | FFmpeg `x11grab` | Wayland 用 `wf-recorder`,X11 用 FFmpeg `x11grab` |
| 录屏帧率控制 | 不提供(`screencapture` 不支持) | 15 / 24 / 30 | 15 / 24 / 30(`-r` / `-framerate`) |
| 截图历史库、把某一行拖出 | 支持 | 支持 | 支持 |
| 截图历史库、把某一行拖出与拖回按钮 | 支持 | 支持 | 支持 |
| 基于 git 的更新:SHA256 校验,清单可选签名 | 支持 | 发布的是 x64 安装包;ARM 机器经由 `windows` 回退拿到同一份 | 可检查并下载;Linux 没有发布产物,因此结果是「没有对应产物」 |
| 图片转换与编辑 | 支持 | 支持 | 支持 |
| HEIC / AVIF 编码 | `sips` | ImageMagick | ImageMagick |
@ -358,19 +362,17 @@ 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.13-macOS-universal.dmg` 与 `Shift-Setup-0.1.13-win-x64.exe`。macOS 是单个通用 Mach-O,内含通用版的拖拽、PDF 渲染与文档渲染伴生进程;Windows ARM64 通过更新清单的兼容回退使用 x64 安装包。完整步骤见 `docs/BUILD_WINDOWS.md` 与 `docs/RELEASE.md`。
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。使用本地证书签名的开发构建,可以在反复重编译后保持这些授权稳定;对外分发则需要 Developer ID 证书与公证。
**权限(macOS)。** 截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」授权,带声音录屏需要「麦克风」,「发送到设备」需要「本地网络」。Shift 会在打开截图遮罩前先检查屏幕录制权限,因此被拒绝时给出的是可操作的提示,而不是一张全黑的截图。「本地网络」被拒绝时比较安静:Shift 仍会发出广播、也能回应主动找它的实例,但收不到组播,设备列表于是始终为空。ad-hoc 签名每次重新构建都会得到新的代码身份,而 macOS 正是按这个身份记录上述授权,所以升级后可能重新询问;改用 Developer ID 签名即可保持稳定。
## 架构
@ -409,6 +411,17 @@ OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线
环形菜单的命中判定是纯几何计算——同一套极角运算同时服务于原生指针事件、webview 悬停与 Windows 的拖放数据,因此圆环行为不会在各平台之间产生偏差。
## 技术文档
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) —— 进程/窗口模型、模块边界、事件与数据流。
- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) —— 产品行为规范、输出命名、平台差异与验收标准。
- [`docs/SECURITY.md`](docs/SECURITY.md) —— 信任边界、更新完整性、局域网传输限制与剩余风险。
- [`CONTRIBUTING.md`](CONTRIBUTING.md) —— 开发环境、测试门禁与发布前检查。
- [`docs/README.md`](docs/README.md) —— 全部技术与发布文档的索引。
- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) —— 不允许退回到旧故障的工程回归台账。
- [`docs/RELEASE.md`](docs/RELEASE.md) —— 发布通道、签名与更新交接。
- [`docs/ROADMAP.md`](docs/ROADMAP.md) 与 [`docs/MOBILE.md`](docs/MOBILE.md) —— 后续计划与移动端方案。
## 仓库结构
```text
@ -420,20 +433,20 @@ native/macos/ Swift 伴生进程:拖拽桥、PDF 渲染器、文档渲
由 pnpm mac:drag-bridge 编译进 src-tauri/binaries/
scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器、发布构建、
清单发布与清单签名
public/tesseract/ WASM 内核与语言模型,构建生成,不提交
public/tesseract/ WASM 内核与语言模型;由 pnpm prepare:ocr 刷新,
已纳入仓库以保证干净检出可离线构建并离线 OCR
assets/ 应用图标源文件
src-tauri/icons/ 各平台生成的应用图标
docs/ Windows 构建指南、发布与更新通道、路线图、移动端规划
scripts/linux/ 在 CI 之外构建 Linux deb/AppImage 的 Dockerfile
docs/ 架构、行为规范、安全模型、发布指南、工程回归台账、路线图与移动端规划
scripts/linux/ 构建 Linux deb/AppImage 的 Dockerfile
.github/workflows/ macOS、Windows、Linux 的 CI 定义(见「参与贡献」)
FileFlipper/ 独立姊妹项目,拥有自己的仓库
```
## 隐私
Shift 对文件做的任何处理都不会发起互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;截图历史库只是一个本地文件。既不上传,也不收集。
只有两条路径会接触网络,且默认都不携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单(只有你按下按钮时才下载安装包);而**发送到设备** 只与本地网络通信——`239.255.77.88:47888` 上的 UDP 广播,加上两台电脑之间的直连 TCP,其中携带机器名称以便双方互相标注。在你打开该面板、或有另一台 Shift 向你发送文件之前,它不会有任何动作。
只有两条路径会接触网络,且只有你主动使用时才会携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单,只有你按下按钮时才下载安装包;**发送到设备**只在本地网络使用 `239.255.77.88:47888` 上的 UDP 信标和你所选设备之间的直连 TCP(或有另一台 Shift 主动向你发送文件)。分享关闭时发现不会启动,传输必须经接收方确认后才开始。局域网流量没有身份认证,也没有加密;该边界详见 [`docs/SECURITY.md`](docs/SECURITY.md)。
## 已知限制
@ -442,13 +455,15 @@ Shift 对文件做的任何处理都不会发起互联网请求。文件在本
- `.doc`、`.pages`、`.ppt`、`.key`、`.numbers` 可识别但不解析——请先导出为 DOCX/PPTX/XLSX。
- HEIC/HEIF/AVIF 可由系统解码器读取,格式转换与像素类工具都能直接使用。只是这两种格式无法经由该路径写出,因此对它们执行像素类工具时会输出 PNG;AVIF 仍不提供为导出目标。
- PDF 压缩会把内嵌图片降采样到最长边 1440 px、q60 JPEG。凡是不能确认可安全往返的内容都会原样保留——蒙版、索引色/CMYK、JPX/JBIG2/CCITT——因此部分特殊扫描件仍难以压缩。
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`;本仓库所在的代码托管平台不会执行这些路径,因此 Linux 的截图能力只能算「可编译」而非「已验证」。
- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`。这些运行路径尚未在 macOS 开发机上实际验证,因此 Linux 截图能力在真机确认前只能算「可编译」。
- Linux 是「可构建」而非「已发布」:不提供 deb 或 AppImage,更新通道里也没有 `linux` 键,因此 Linux 构建检查更新时会得到「没有对应产物」。想要自己动手的人,可照 `scripts/linux/Dockerfile` 或 CI 里的 `linux` 任务来做。
- 把历史库的某一行拖出去依赖 Webview 对 file URL 拖拽的支持。载荷使用标准的 `text/uri-list`(内含 `file://` 条目)并附带纯文本路径,仍需在每个平台上做手势级验证;在此之前,**发送**、**在文件夹中显示**以及行内按钮是交付文件的确定路径。
- 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。
- 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。发现机制的不可回退约束、权限排查与回归矩阵见 `docs/ENGINEERING-NOTES.md`。
- Windows 上每台电脑只有一个 Shift 实例能占用发现端口,因此额外实例不会出现在设备列表中。
- Windows 与 Linux 代码路径在本机通过编译验证,而托管本仓库的平台并不运行 Actions,因此 CI 不会替你构建任何东西;手势层面的验证仍需真实 Windows 与 Linux 设备。
- Windows 与 Linux 代码路径在本机通过编译验证,并在有执行器的托管平台上由仓库内的 CI 定义覆盖;手势层面的验证仍需真实 Windows 与 Linux 设备。
- macOS 上签名身份变化后,可能需要重新授予「屏幕录制」与「辅助功能」权限。
- 局域网分享没有认证与加密。接受一次传输只能证明你同意了这次请求,不能证明发送者身份;请只在可信网络使用。
- Office ZIP/XML 解析与 PDF 渲染尚未在所有编解码器和外部渲染器之间共享同一份资源配额。编辑器预览已有上限,但异常巨大或恶意的文档仍应按不可信输入处理。
路线图见 `docs/ROADMAP.md`。
@ -488,9 +503,9 @@ Shift 对文件做的任何处理都不会发起互联网请求。文件在本
## 参与贡献
新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `src/lib/radialOrder.ts` 的对应列表中加入 id、补上文案、在 `WEDGE_ICONS` 中加入图标,再在 `executeAction` 中加一个分支——圆环渲染的就是同一份目录,因此无需别处注册即可出现。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build` 与 `cargo test --lib`。
新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `src/lib/radialOrder.ts` 的对应列表中加入 id、补上文案、在 `WEDGE_ICONS` 中加入图标,再在 `executeAction` 中加一个分支——圆环渲染的就是同一份目录,因此无需别处注册即可出现。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build`、`cargo fmt --check`、`cargo test --lib`、`cargo clippy --all-targets -- -D warnings` 与 `git diff --check`;平台环境与手工验收矩阵见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
`.github/workflows/ci.yml` 内含 macOS、Windows、Linux 三个任务,但**本仓库所在的托管平台没有 Actions 执行器**,因此这些任务目前只是定义、而非实时保障:只有镜像到 GitHub、接入 Forgejo Actions,或由贡献者本地执行时才会真正构建。CI 会执行的就是上面这四条命令,外加各平台的 `pnpm tauri build`;Linux 安装包可在普通 Docker 主机上用 `scripts/linux/Dockerfile` 构建。
`.github/workflows/ci.yml` 定义了 macOS、Windows、Linux 三个任务。每个任务都会运行类型检查、TypeScript 测试、Rust 格式检查与单元测试;macOS 任务还运行 Clippy 和通用应用构建。当前托管平台是否真正执行这些任务,取决于它是否配置了执行器;本地运行仍是发布门禁,没有链接到实际日志时不得声称 CI 已通过。完整环境与推送前检查见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
**欢迎二次开发。** 你可以免费使用、修改、再发布本代码,也可用于商业项目,只需保留原版权声明与 LICENSE 文件。

View File

@ -0,0 +1,102 @@
Shift 0.1.13 - macOS 通用(universal)
本文件说明 macOS 安装包是怎么打出来的、在其它机器上会遇到什么,以及如何自己校验。
完整细节见仓库 docs/RELEASE.md 的「macOS packaging」和 docs/ENGINEERING-NOTES.md
的「macOS DMG 打包与跨机器安装」。
关于这个安装包
--------------
Shift 的 macOS 产物只有一个:Shift-0.1.13-macOS-universal.dmg,通用二进制,Apple silicon 与
Intel 都能用。它既是新机器的首次安装方式,也是软件内升级的载体(更新清单里的 macos
键指向它)。清单的键必须是 .dmg,因为软件内升级的交接脚本要用 hdiutil 挂载镜像再
取出应用包;早期曾随包发布的 .pkg 在验证过 DMG 可用后就撤掉了,不为它多维护一份
产物。
本项目的构建是 ad-hoc 签名(src-tauri/tauri.conf.json 里 signingIdentity 固定为
"-"),且没有 Apple Developer ID 可做公证。Gatekeeper 因此无法为任何 Shift 构建背书,
一台新机器上会看到「身份不明的开发者」提示——这是可以放行的,见下节。
在其它机器上安装
----------------
新机器首次安装
1. 下载并双击 Shift-0.1.13-macOS-universal.dmg 挂载镜像。
2. 把 Shift.app 拖进「应用程序」(或任何你有权限的位置)。
3. 首次启动会被拦:「无法打开,因为来自身份不明的开发者」。点取消,然后
右键 Shift.app → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。
4. 只需允许一次,之后再打开正常。
macOS 权限
截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」,带声音录屏需要
「麦克风」,「发送到设备」需要「本地网络」。Shift 会在打开截图遮罩前先检查屏幕
录制权限,被拒绝时给的是可操作的提示,而不是一张全黑截图。
「本地网络」被拒绝时 Shift 无法可靠地发送或接收设备信标,设备列表会一直是空的。
若看不到其它终端,请到「系统设置 → 隐私与安全性 → 本地网络」确认当前安装的
Shift 是打开的;那里可能留着多条目,因为每次重新构建都是一个新身份,请对准当前
安装的那一个。
注意:ad-hoc 构建每次的代码签名哈希都不同,而 macOS 把「屏幕录制」「本地网络」
这类授权绑在这个哈希上,所以一次升级后可能需要重新授权——这与手动重装是同一
后果。要彻底消除它,需要 Developer ID 证书加公证(见仓库 docs/ROADMAP.md 的 M5)。
发布前的硬性回归
构建机能够打开自己生成的 DMG,不代表发布包合格。每次发版前必须通过发布源在另
一台 Mac(最好从未安装过 Shift)用浏览器下载最终 DMG,以保留真实用户会遇到的
quarantine 标记;然后挂载、拖入 Applications、完成首次授权并启动,确认版本号
正确。随后打开 Drop,确认能看到另一台 Shift 终端且不会很快消失。若该版本同时
提供软件内升级,还要从上一版实际升级一次,确认不会出现 Gatekeeper 提示。任何
一项未通过都不得上传 DMG。
软件内升级
设置 → 软件更新 里检查并安装:Shift 自己下载 .dmg,先核对字节数与 SHA256,
再由一个独立脚本等本进程退出后挂载镜像、ditto 出新副本、去掉隔离属性、用两次
mv 换上新版本并重新打开。下载不走浏览器,新副本不带隔离属性,所以这一步没有任何
Gatekeeper 提示。
如何自己构建
------------
构建机需先装好两个 Rust 目标,以及 macOS 侧的原生伴生进程(AppKit 拖拽桥、PDFKit
与文档渲染,会被打成通用二进制):
rustup target add aarch64-apple-darwin x86_64-apple-darwin
pnpm install
pnpm mac:drag-bridge
生成通用应用与 DMG:
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
`pnpm mac:release` 会构建、校验并复制为 artifacts/Shift-0.1.13-macOS-universal.dmg。
发布流程(清单、签名、推送)见仓库 docs/RELEASE.md。
若希望更新通道能校验来源,构建时把 ed25519 公钥编进去(发布流程见仓库
docs/RELEASE.md 的「Signing the channel」):
export SHIFT_RELEASE_KEY=~/.config/shift-release/release.ed25519
export SHIFT_UPDATE_PUBKEY=$(python3 scripts/release-key.py pubkey \
~/.config/shift-release/release.ed25519)
如何校验
--------
哈希(本目录下的 SHA256SUMS.txt 覆盖所有产物):
shasum -a 256 -c SHA256SUMS.txt
签名形态(adhoc 是当前刻意选择的形式,不是出错):
codesign -dv --verbose=2 /Applications/Shift.app 2>&1 | grep -E 'Signature|Identifier'
# Signature=adhoc
# Identifier=app.nex.shift
镜像完整性:
hdiutil verify Shift-0.1.13-macOS-universal.dmg
校验后仍打不开的话,请确认不是在压缩包预览窗口里运行的,并按上面的「新机器首次安装」
处理首次允许:右键 → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。

View File

@ -1,30 +1,13 @@
<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="bg" x1="120" y1="92" x2="884" y2="930" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFB25C"/>
<stop offset="0.48" stop-color="#FF6B35"/>
<stop offset="1" stop-color="#C66BFF"/>
</linearGradient>
<radialGradient id="shine" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(344 276) rotate(46) scale(760)">
<stop stop-color="white" stop-opacity="0.32"/>
<stop offset="1" stop-color="white" stop-opacity="0"/>
</radialGradient>
<filter id="shadow" x="86" y="110" width="852" height="852" filterUnits="userSpaceOnUse">
<feDropShadow dx="0" dy="24" stdDeviation="28" flood-color="#7A3018" flood-opacity="0.28"/>
</filter>
</defs>
<rect width="1024" height="1024" rx="228" fill="url(#bg)"/>
<rect width="1024" height="1024" rx="228" fill="url(#shine)"/>
<g filter="url(#shadow)">
<circle cx="512" cy="512" r="326" fill="#FFF4EA" fill-opacity="0.96"/>
<path d="M512 186A326 326 0 0 1 808.5 358L604.4 476A145 145 0 0 0 512 367V186Z" fill="#FFE9D5"/>
<path d="M808.5 358A326 326 0 0 1 808.5 666L604.4 548A145 145 0 0 0 604.4 476L808.5 358Z" fill="#FFDCC4"/>
<path d="M808.5 666A326 326 0 0 1 512 838V657A145 145 0 0 0 604.4 548L808.5 666Z" fill="#FFE3CE"/>
<path d="M512 838A326 326 0 0 1 215.5 666L419.6 548A145 145 0 0 0 512 657V838Z" fill="#FFD7C0"/>
<path d="M215.5 666A326 326 0 0 1 215.5 358L419.6 476A145 145 0 0 0 419.6 548L215.5 666Z" fill="#FFE9D5"/>
<path d="M215.5 358A326 326 0 0 1 512 186V367A145 145 0 0 0 419.6 476L215.5 358Z" fill="#FFF0E2"/>
<circle cx="512" cy="512" r="157" fill="#FFF9F4"/>
<circle cx="512" cy="512" r="120" fill="#FF6B35"/>
<path d="M512 420V604M420 512H604" stroke="#FFF9F4" stroke-width="46" stroke-linecap="round"/>
<rect x="102" y="102" width="820" height="820" rx="182.58" fill="#FF6B35"/>
<g fill="#FFF4EA">
<path d="M526.79 186.34 A326.00 326.00 0 0 1 786.64 336.36 L663.77 414.94 A180.16 180.16 0 0 0 520.17 332.03 Z"/>
<path d="M801.43 361.97 A326.00 326.00 0 0 1 801.43 662.03 L671.95 594.91 A180.16 180.16 0 0 0 671.95 429.09 Z"/>
<path d="M786.64 687.64 A326.00 326.00 0 0 1 526.79 837.66 L520.17 691.97 A180.16 180.16 0 0 0 663.77 609.06 Z"/>
<path d="M497.21 837.66 A326.00 326.00 0 0 1 237.36 687.64 L360.23 609.06 A180.16 180.16 0 0 0 503.83 691.97 Z"/>
<path d="M222.57 662.03 A326.00 326.00 0 0 1 222.57 361.97 L352.05 429.09 A180.16 180.16 0 0 0 352.05 594.91 Z"/>
<path d="M237.36 336.36 A326.00 326.00 0 0 1 497.21 186.34 L503.83 332.03 A180.16 180.16 0 0 0 360.23 414.94 Z"/>
</g>
<circle cx="512" cy="512" r="108.09" fill="#FFF4EA"/>
<path d="M445.08 512H578.92M512 445.08V578.92" stroke="#FF6B35" stroke-width="24.02"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

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

View File

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

View File

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

View File

@ -32,7 +32,7 @@ already perform every day:
| --- | --- | --- |
| Shift-drag out of the Finder row, release over a wedge | **Share sheet**, including the drag-and-drop share from Files/Photos/Safari where the picker slides out from under the finger | **Share sheet**, same shape, from any app |
| Radial ring of wedges | The share sheet's own app list, plus a Share Extension whose UI we own | Share sheet targets, plus an Action/Share Activity we own |
| Ring reorder in Settings | Share sheet "Edit Actions" ordering, mirrored in our Settings | Same, mirrored |
| Ring order (desktop reads `settings.json`; no editor UI in 0.1.11) | Share sheet "Edit Actions" ordering, mirrored in a mobile Settings surface | Same, mirrored |
So the mobile pitch is not "Shift in your pocket", it is: **release a share over a Shift
action**. Concretely: long-press an image in Files → Share → Shift → *HEIC → PNG, then

28
docs/README.md 100644
View File

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

View File

@ -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.13-macOS-universal.dmg
└── Shift-Setup-0.1.13-win-x64.exe
```
`shift-update.json` names the version and, per platform, the artifact file, its size in
@ -22,16 +22,21 @@ bytes and its SHA256:
```json
{
"schema": 1,
"version": "0.1.1",
"version": "0.1.13",
"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.13-macOS-universal.dmg", "sha256": "…", "size": 0 },
"windows": { "file": "Shift-Setup-0.1.13-win-x64.exe", "sha256": "…", "size": 0 }
}
}
```
Artifact names are restricted to ASCII letters, digits, `.`, `-` and `_`; path
separators, `..`, spaces and shell metacharacters are rejected. The app also
refuses a manifest over 256 KiB. These checks keep malformed manifest data out
of download paths and out of the native handoff arguments.
## Supported release targets
**Shift ships two installers: macOS (universal) and Windows x64.** That is a scope decision,
@ -39,14 +44,16 @@ not a code limit, and it decides what the channel may contain:
| Key | Shipped | Notes |
| --- | --- | --- |
| `macos` | yes | One universal bundle, Apple silicon and Intel |
| `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
those paths; this release guide defines the channel, while the engineering ledger explains
why the current shape must not be simplified back into an earlier failure.
Keys are platform, then platform and architecture where they differ. A build picks the
first key its own architecture matches and never crosses operating systems:
@ -67,10 +74,93 @@ by a test rather than by a comment.
The branch is rebuilt as a fresh root commit on every publish and force-pushed, so it
never accumulates gigabytes of installer history while `main` stays clean.
## macOS packaging
Shift builds are **ad-hoc signed** (`signingIdentity: "-"` in `tauri.conf.json`) and are
**not notarized** — notarization needs an Apple Developer ID account, which this project
does not have. Gatekeeper therefore cannot vouch for any Shift build, and what a fresh
machine says depends on how the binary is signed:
| Signing | What a fresh machine says |
| --- | --- |
| Ad-hoc (`Signature=adhoc`) — **current** | "cannot be opened because it is from an unidentified developer", and the box offers a way through: Cancel, then right-click → 打开, or 允许 in 系统设置 → 隐私与安全性 |
| Self-signed certificate | "cannot be opened because it is damaged" / reported as malware, with **only 移至废纸篓** — no override, no pane entry to approve |
| Developer ID + notarized | Opens on double-click, no prompt |
The middle row is what a release shipped with, and it is a trap because it looks healthy
locally: `codesign` reports `valid on disk` and `satisfies its Designated Requirement`, and
`spctl` accepts it on the build host. The certificate ("Shift Local Signing") is self-issued,
`CA:FALSE`, and present in only that one Mac's keychain, so on any other machine it cannot
chain to a trusted root — and an unchainable signature on a quarantined download is a hard
refusal rather than a prompt.
One correction worth keeping, because the obvious story is wrong: every DMG this channel has
ever published carries that same `Authority=Shift Local Signing`, including the earliest 0.1.0
ones, because Tauri picks a keychain identity itself when `signingIdentity` is unset. So
"older builds were ad-hoc" is **not** why one machine accepted them — a machine that had been
shown the app before may already trust the certificate, and Gatekeeper's own heuristics have
changed across macOS versions. What is verified is the direction of the fix: an ad-hoc binary
is reported as an unidentified developer with a way through, which is the behaviour this
project wants, and no release is worse off for losing a certificate no other Mac can check.
Reusing that identity again would mean installing it **and trusting it** on every machine,
which is not something to ask of a user.
So: ad-hoc, and one container. The channel ships **`Shift-<version>-macOS-universal.dmg`** and nothing
else on macOS — the earlier `.pkg` companion was dropped after the DMG was verified to work
on a fresh machine, and one file per platform is less to keep straight.
| Situation | What happens |
| --- | --- |
| A machine installing Shift for the first time | Double-click the DMG, drag `Shift.app` to /Applications. The app keeps the browser's quarantine flag, so the **first launch** needs the one approval above: right-click → 打开, or 允许 in 系统设置 → 隐私与安全性. Every launch after that is normal. |
| An installed Shift updating itself | `update_install`'s handoff downloads the DMG, mounts it with `hdiutil`, copies the bundle out and drops the quarantine flag. Shift's own downloader sets no quarantine flag (`curl` sets none, and the handoff strips it anyway), so **in-app updates never prompt**. |
The `macos` manifest key is a DMG for the same reason: the in-app handoff mounts the image,
so pointing the key at a package would break every in-app update. That was the one real
constraint the container had to satisfy, and a DMG satisfies it.
The retired `.pkg` packaging script has been removed. The DMG is the only macOS
container in the release pipeline.
### macOS release gate
Every macOS release must pass all of these before it goes into `artifacts/`:
1. Run `pnpm mac:release`. It rebuilds the universal Swift sidecars, builds the app
and DMG, verifies both, and copies the result to the versioned release name.
2. Run `codesign --verify --deep --strict` on `Shift.app`, and confirm
`codesign -dv --verbose=2` reports `Signature=adhoc`. A local certificate name here is
a release blocker, not a stronger signature.
3. Run `hdiutil verify artifacts/Shift-<version>-macOS-universal.dmg` and verify `SHA256SUMS.txt` after copying
the final artifact into `artifacts/`.
4. Confirm the release contains no `.pkg`, and that the manifest's `macos` entry points at
the DMG. The in-app helper mounts that exact container with `hdiutil`.
5. Transfer the DMG to a different Mac, preferably one that has never installed Shift.
Download the final artifact through a browser from the release feed when possible so the
quarantine flag matches the real user path; if a USB or AirDrop transfer is used, confirm
the quarantine attribute is present, otherwise Gatekeeper was not exercised. Drag
`Shift.app` to `/Applications`, approve the first launch once, and verify the version.
6. On that same machine, open Drop and confirm another Shift peer appears and stays in the
list. A packaging or signing change can invalidate Local Network approval even when the
app itself starts correctly.
7. For an update release, install the previous version on that machine and run the in-app
update once. It must restart on the new version without a Gatekeeper prompt.
The build host opening its own DMG proves neither cross-machine installation nor the
quarantine behaviour. Step 5 is the hard release gate. The full incident record and the
manual Drop matrix are in [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md).
Closing this for good means an Apple Developer ID: `Developer ID Application` +
`notarytool` + `stapler staple`. Then the DMG opens on double-click with no pane to visit,
and the privacy grants keyed to that identity — Screen Recording, and Local Network, which
is what device discovery needs — stop resetting between builds. That reset is not
theoretical: a 0.1.4 user found the device list empty after upgrading, with nothing in the
UI to say why.
## Publishing
```bash
pnpm tauri build … # bundles land in artifacts/
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
```
@ -89,21 +179,25 @@ 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 — travel with the branch but are
not offered as installers. 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.
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:
`README-macOS-universal.txt` is tracked in the repository as well as pushed to the channel,
so the scheme is documented where a contributor reads it and not only next to a build
product. Every claim in it was checked against the shipped artifacts: the bundle inside the
published DMG is `Signature=adhoc`, and `shasum -a 256 -c SHA256SUMS.txt` passes on the
published set.
The Windows command cross-compiles one target, checks the PE machine field (`0x8664`)
and gates the installer to x64:
```bash
scripts/build-windows-release.sh # 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
@ -116,15 +210,15 @@ 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"
```
Give the release build `SHIFT_UPDATE_PUBKEY` (the hex key) and it can verify the feed; give
it `SHIFT_RELEASE_KEY` (the private key) and `build-windows-release.sh` derives the public
key from it, so a cross-build can never be packaged with a key that does not match the
signature `publish-release.sh --key` produces. Without either, the script prints
it `SHIFT_RELEASE_KEY` (the private key) and both release scripts derive the public key from
it, so a build can never be packaged with a key that does not match the signature
`publish-release.sh --key` produces. Without either, the script prints
`no release key: this build will report the feed as unsigned` rather than letting it pass
for a quieter log.
@ -145,6 +239,12 @@ a new baked key; leaking it means an attacker can publish anything to the channe
as leaking push access to `releases` already does today. Keep it outside the repository —
`~/.config/shift-release/` is where the local publishing machine keeps it.
`scripts/release-key.py` treats a file ending in `.pub` as an ed25519 public
key and every other path as the 32-byte private key. `keygen` writes the private
key (`release.ed25519`, mode 0600) and its public companion (`release.pub`). Keep
the private key out of CI logs and do not rename the public file to a non-`.pub`
name when using `pubkey`.
## Where a build looks for updates
`src-tauri/build.rs` derives the feed from the `origin` remote at build time:
@ -176,15 +276,17 @@ guessing at one.
so restarts cannot spend the day's check twice.
2. Versions are compared with semver rules, prereleases included: `0.2.0-alpha` sorts
below `0.2.0`, so a test build does not offer to downgrade itself.
3. Download writes into a temp folder, then two gates run before anything can be
installed: the byte length must equal the manifest's `size`, and the recomputed SHA256
must equal the manifest's `sha256`. A mismatch deletes the file and reports the error,
so a truncated or swapped installer never reaches the installer step.
3. Download writes into a temp folder, then two gates run: the byte length must equal the
manifest's `size`, and the recomputed SHA256 must equal the manifest's `sha256`. Both
checks run again immediately before the handoff. A mismatch deletes the file and
reports the error, so a truncated or swapped installer never reaches the installer
step.
4. **Install & relaunch** applies the verified artifact and restarts Shift on it, as
described in the next section; **Discard** removes the download. When an update is
available the tray menu gains a row that opens Settings on the Updates tab.
described in the next section; **Discard** removes the downloaded artifact as well as
the update status. When an update is available the tray menu gains a row that opens
Settings on the Updates tab.
Manifest `schema` is checked, and a newer schema than this build understands is refused
Manifest `schema` is checked; this build accepts exactly `1` and refuses anything else
instead of being parsed optimistically. Unknown platform keys are ignored, so the
manifest can name a platform an older app has never heard of. The Updates panel always
states which of the two properties the current feed satisfies, so an unsigned channel
@ -205,15 +307,20 @@ for that pid to disappear and only then touches the installed copy.
Both scripts are written so a failure cannot end with Shift simply closed: every macOS
failure path still `open`s the bundle it had, and the swap is `move aside, move in`, so a
copy that fails halfway leaves the previous version where it was. Before the handoff
starts, macOS writes a probe file next to the bundle — a root-owned copy in
`/Applications` is reported as "open the downloaded installer yourself" rather than
quietly quitting on an update that could not be applied.
copy that fails halfway leaves the previous version where it was. The scripts themselves
are fixed constants; the pid, installer, bundle and log paths arrive through process
arguments or environment variables, never interpolated into shell or batch source. The
Windows launcher also keeps the outer quote layer that `cmd.exe /C` would otherwise strip
from a script path containing spaces. Before the handoff starts, macOS
writes a probe file next to the bundle — a root-owned copy in `/Applications` is reported
as "open the downloaded installer yourself" rather than quietly quitting on an update
that could not be applied.
The Windows installer is the same one a user runs by hand, so the update path cannot drift
from the manual one. Because the silent install comes from Shift itself, `${Silent}` skips
the interactive "Shift is running, close it?" box: the app already told the user it is
about to restart, and a box nobody can answer would abort the update.
the interactive "Shift is running, close it?" box and the WebView2 warning: the app
already told the user it is about to restart, and a box nobody can answer would abort or
hang the update.
This is not a delta update and not a signature check on the running binary: the same
SHA256 gate that guards a manual install is the only integrity gate, and the manifest
@ -264,18 +371,25 @@ test, which is the proof that the check is real and not a pass-through.
## State of the published channel
Checked against the live `releases` branch of this repository:
This section is a historical audit of the published channel at the time it was
performed. It is not a claim that the current `releases` branch still contains
this version or that CI produced it. Re-run the verification below before using
these numbers in release notes.
Version **0.1.3**, checked by downloading each artifact back from the raw endpoint rather
Version **0.1.7**, checked by downloading each artifact back from the raw endpoint rather
than trusting the local copy:
| Key | Artifact | Verified from the remote |
| --- | --- | --- |
| `macos` | `Shift-macOS-universal.dmg` (55,528,662 B) | bytes downloaded, SHA256 matches the manifest |
| `windows` | `Shift-Setup-0.1.3-win-x64.exe` (24,517,835 B) | bytes downloaded, SHA256 matches the manifest |
| `macos` | `Shift-macOS-universal.dmg` (55,585,331 B) | bytes downloaded, SHA256 matches the manifest |
| `windows` | `Shift-Setup-0.1.7-win-x64.exe` (24,514,334 B) | bytes downloaded, SHA256 matches the manifest |
| `windows-arm64` | not published | by choice — see "Supported release targets" |
| `linux` | not published | by choice: Linux is a build target here, not a shipped product |
The retired `Shift-macOS-universal.pkg` left the branch with this publish: the branch is
rebuilt from `artifacts/` on every run, so dropping it from the build was enough. macOS now
ships the one container ("macOS packaging").
`shift-update.sig` verifies over the manifest's exact bytes against the key baked into both
artifacts. The channel's home is derived from `origin` at build time, and this forge is
Gitea, so the raw form is `/raw/branch/releases/`.
@ -284,9 +398,9 @@ Both artifacts carry the key and the feed URL, which is what makes an in-app upg
possible at all: a build whose binary predates those constants reports "this build has no
feed" and can never see the channel, however new it is.
The forge runs **no Actions**, so nothing on this list was built by CI: every artifact was
cross-compiled on one macOS host and pushed with `scripts/publish-release.sh`. Treat "pass
CI" in the contributing guide as a definition to run locally, not a gate that already ran.
The workflow defines separate macOS, Windows and Linux jobs, but this audit did
not record a linked CI run. Treat the local commands in `CONTRIBUTING.md` as the
release gate unless a green run is attached to the release.
A Linux release would slot in under the `linux` key with no code change — `artifact_keys_for`
already answers `linux` for that host — so publishing one is a build task, not a feature.

View File

@ -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
@ -57,16 +57,21 @@ names what is still missing.
thread to per-monitor-v2 DPI awareness so a mixed-DPI or multi-monitor desktop cannot
shift the image out from under the overlay. PowerShell is nowhere in the capture path; it
is used only as the HTTP client for the update download.
- Windows ARM64: `scripts/build-windows-release.sh` builds both architectures by
default, checks each binary's PE machine field (`0x8664` / `0xAA64`) before packaging
it, and gates each NSIS installer to the matching machine. The update manifest gained a
`windows-arm64` key; an ARM build tries it first and falls back to `windows`, which
Windows on ARM runs under emulation, so a channel that predates the ARM build still
serves it. Verified by cross-building, packaging and publishing all of that from macOS;
running the installer on real Windows-on-ARM hardware has not happened. Since 0.1.1 the
shipped targets are macOS and Windows x64 only, so ARM64 stays a buildable architecture
(`--arch arm64` still works, `windows-arm64` still falls back to `windows`) that nothing
is published for.
- LAN Drop discovery is working again in 0.1.7: the shared discovery socket now combines
multicast, per-interface directed broadcast, limited broadcast and a bounded `/24`
unicast sweep; ordinary beacons receive one marked reply, and peer expiry is long enough
for older copies to answer. The user-observed acceptance run covered one Mac and one
Windows x64 machine after an upgrade. Unit tests cover the scan bounds, timeout and reply
semantics, but the live two-host check is manual because the repository has no
second-machine fixture. Client-isolated Wi-Fi remains outside the app's
control, and Windows still permits only one listener per machine. The exact invariants
and manual matrix are in `docs/ENGINEERING-NOTES.md`.
- Windows ARM64: the release pipeline ships only the x64 NSIS installer, checks its
PE machine field (`0x8664`), and gates the installer to x64. An ARM machine tries the
optional `windows-arm64` manifest key first and falls back to `windows`, which Windows
on ARM runs through emulation. Verified by cross-building, packaging and publishing
from macOS; running the installer on real Windows-on-ARM hardware has not happened.
Since 0.1.1 the shipped installers are macOS universal and Windows x64 only.
- Linux is supported as a build and run target but is **not a shipped product**: no deb or
AppImage is published, so the update channel has no `linux` key and the platform table
reports "no artifact" rather than a failure. `scripts/linux/Dockerfile` and the `linux` CI
@ -104,7 +109,21 @@ names what is still missing.
launch after an upgrade, re-deriving each entry's kind from the file rather than trusting
the older store's guess, then the legacy key is dropped so a later upgrade cannot
resurrect rows the user has since removed.
- Signed and notarized macOS package: pending (builds are signed with a local identity).
- Signed and notarized macOS package: pending. Builds are **ad-hoc** signed, deliberately:
signing with a locally created certificate made every other machine refuse the app as
*damaged / malware* with no override, because that certificate cannot chain to a trusted
root anywhere else, while an ad-hoc binary gets the softer "unidentified developer" box
the user can approve. The channel ships one macOS container, the DMG: it was verified on a
fresh machine (drag to /Applications, one approval on first launch), so the `.pkg` that
once accompanied it was dropped rather than kept as a second thing to maintain. The `macos`
manifest key has to stay a DMG anyway, because the in-app handoff mounts it with `hdiutil`;
see "macOS packaging" in `docs/RELEASE.md` and the packaging incident record in
`docs/ENGINEERING-NOTES.md`. The release gate deliberately requires installation from the
transferred DMG on a different Mac; opening the build host's own image is not evidence.
A Developer ID plus notarization removes the prompt entirely and would also stop Screen
Recording and Local Network approval from resetting between builds — both are keyed to the
signing identity, so an ad-hoc rebuild loses them, and a lost Local Network grant empties
the device list with no message anywhere in the UI.
- Signed Windows installer: pending.
- Manifest signing is done. `scripts/release-key.py` mints the release key,
`publish-release.sh --key` publishes a detached `shift-update.sig` over the manifest's
@ -143,9 +162,10 @@ Restricted to work this repository can do something about; hardware QA is last b
commit closes it. Each item states the check that closes it. Linux packaging is deliberately
absent — the platform is supported, not shipped.
1. **A real CI run.** The forge (Gitea) returns 404 for `/actions/runs`, so `ci.yml` is
never executed. Either mirror to GitHub or install Forgejo Actions. Close: one green run
per platform whose log is linked from the release notes.
1. **A verified CI run.** `ci.yml` defines macOS, Windows and Linux jobs, but no linked
run in this repository proves that the current hosting forge executes them. Either
configure a runner or run the workflow on a mirror. Close: one green run per platform
whose log is linked from the release notes.
2. **Persistent job queue with cancel and retry.** `perform_file_action` already emits
`app://file-action-progress` with real page counts, but a batch dies with the window and
an error aborts the rest of the batch. Close: a queued batch survives an app restart,

193
docs/SECURITY.md 100644
View File

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

View File

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

View File

@ -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)
@ -189,6 +203,211 @@ do {
fail("could not parse document: \(error.localizedDescription)")
}
/// Fits every picture into the width of the printed page.
///
/// The layout sizes an attachment from the density header inside the file —
/// 72 dpi is assumed when the file carries none — and the cell AppKit builds
/// for an `<img>` honours neither `bounds` nor a CSS width, so a 1600 px
/// screenshot saved at 96 dpi asks for 1200 points and prints as a cropped
/// fragment of itself. A plain `NSTextAttachment` does honour `bounds`, and the
/// print operation then scales it onto the page along with the text. Aspect
/// ratio is kept and nothing is resampled: only the size the layout asks for
/// changes.
func fitAttachments(
_ source: NSAttributedString,
to containerWidth: CGFloat
) -> NSMutableAttributedString {
let mutable = NSMutableAttributedString(attributedString: source)
let wanted = max(1, containerWidth)
mutable.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: mutable.length),
options: []
) { value, range, _ in
guard let old = value as? NSTextAttachment,
let contents = old.fileWrapper?.regularFileContents,
let image = NSImage(data: contents),
image.size.width > wanted else { return }
let scale = wanted / image.size.width
let replacement = NSTextAttachment()
replacement.image = image
replacement.bounds = NSRect(
x: 0,
y: 0,
width: (image.size.width * scale).rounded(),
height: (image.size.height * scale).rounded()
)
mutable.addAttribute(.attachment, value: replacement, range: range)
}
return mutable
}
/// Writes the tall PDF WebKit produces from the page as A4-sized slices.
///
/// `createPDF` keeps the HTML layout as one continuous page. Printing the web
/// view directly can loop indefinitely on documents with positioned elements,
/// so draw the single page into clipped A4 pages instead.
func writePaginatedPDF(_ data: Data, to output: URL) {
let pageSize = CGSize(width: 595.2, height: 841.8)
guard let provider = CGDataProvider(data: data as CFData),
let document = CGPDFDocument(provider),
let source = document.page(at: 1) else {
fail("could not read the rendered web page")
}
let sourceBounds = source.getBoxRect(.mediaBox)
let height = max(1, sourceBounds.height)
let pageCount = max(1, Int(ceil(height / pageSize.height)))
var mediaBox = CGRect(origin: .zero, size: pageSize)
guard let context = CGContext(output as CFURL, mediaBox: &mediaBox, nil) else {
fail("could not create the PDF")
}
for index in 0..<pageCount {
context.beginPDFPage(nil)
context.saveGState()
context.clip(to: mediaBox)
let offset = max(0, height - CGFloat(index + 1) * pageSize.height)
let remaining = max(0, height - CGFloat(index) * pageSize.height)
// Full slices move up through the tall page. The final short slice is
// top-aligned so the trailing whitespace sits below the content.
let translationY = remaining < pageSize.height
? pageSize.height - remaining
: -offset
context.translateBy(x: 0, y: translationY)
context.drawPDFPage(source)
context.restoreGState()
context.endPDFPage()
}
context.closePDF()
}
/// Renders HTML with WebKit instead of flattening it into an attributed
/// string. Quick Look supplies Word page furniture and positioned tables as
/// HTML; AppKit's text conversion reflows that content, which changes the page
/// count and can move a footer onto a page of its own.
final class HTMLRenderer: NSObject, WKNavigationDelegate {
private let input: URL
private let baseDirectory: URL
private let output: URL
private let webView: WKWebView
private var finished = false
init(input: URL, output: URL, baseDirectory: URL) {
self.input = input
self.output = output
self.baseDirectory = baseDirectory
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
self.webView = WKWebView(
frame: NSRect(x: 0, y: 0, width: 595.2, height: 841.8),
configuration: configuration
)
super.init()
webView.navigationDelegate = self
}
func run() {
webView.loadFileURL(input, allowingReadAccessTo: baseDirectory)
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
guard !self.finished else { return }
self.finished = true
fail("could not render HTML before the 30 second deadline")
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard !finished else { return }
webView.evaluateJavaScript(
"""
(() => {
const pageWidth = document.documentElement.clientWidth;
for (const image of document.images) {
if (image.getBoundingClientRect().width > pageWidth) {
image.style.width = `${pageWidth}px`;
image.style.height = "auto";
image.style.maxWidth = "100%";
}
}
let contentBottom = 0;
const range = document.createRange();
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT
);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (!node.textContent.trim()) continue;
range.selectNodeContents(node);
const rect = range.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
contentBottom = Math.max(
contentBottom,
rect.bottom + window.scrollY
);
}
}
for (const element of document.querySelectorAll(
"img, svg, canvas, table, hr"
)) {
const rect = element.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
contentBottom = Math.max(
contentBottom,
rect.bottom + window.scrollY
);
}
}
return {
width: document.documentElement.scrollWidth,
height: Math.max(1, Math.ceil(contentBottom))
};
})()
"""
) { value, error in
guard !self.finished else { return }
self.finished = true
guard error == nil,
let size = value as? [String: Any],
let width = (size["width"] as? NSNumber)?.doubleValue,
let height = (size["height"] as? NSNumber)?.doubleValue,
width > 0,
height > 0 else {
fail("could not measure the rendered HTML")
}
let configuration = WKPDFConfiguration()
configuration.rect = CGRect(x: 0, y: 0, width: width, height: height)
webView.createPDF(configuration: configuration) { result in
switch result {
case .success(let data):
writePaginatedPDF(data, to: self.output)
NSApp.terminate(nil)
case .failure(let error):
fail("could not print HTML: \(error.localizedDescription)")
}
}
}
}
func webView(
_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error
) {
guard !finished else { return }
finished = true
fail("could not load HTML: \(error.localizedDescription)")
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
guard !finished else { return }
finished = true
fail("could not load HTML: \(error.localizedDescription)")
}
}
let printInfo = NSPrintInfo.shared.copy() as! NSPrintInfo
printInfo.paperSize = NSSize(width: 595.2, height: 841.8)
printInfo.topMargin = 42
@ -203,6 +422,7 @@ printInfo.jobDisposition = .save
printInfo.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output
let printable = printInfo.imageablePageBounds
let fitted = fitAttachments(attributed, to: printable.width)
let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: printable.width, height: 1))
textView.isEditable = false
textView.isSelectable = false
@ -214,7 +434,7 @@ textView.textContainer?.containerSize = NSSize(
width: printable.width,
height: .greatestFiniteMagnitude
)
textView.textStorage?.setAttributedString(attributed)
textView.textStorage?.setAttributedString(fitted)
guard let layoutManager = textView.layoutManager,
let textContainer = textView.textContainer else {

View File

@ -1,6 +1,21 @@
import AppKit
import Foundation
// Idle, this process has one job: notice the moment the mouse goes down. It used to do
// that 30 times a second, and every tick allocated a CGEvent to read a cursor position
// nothing needs while no button is held. Measured A/B against the 0.1.11 binary on the
// 2026-11 idle review: 20ms of CPU per 6s idle (~0.3%, and 30 wakeups a second,
// forever) against 0ms for the same window now, while 12s of holding the button costs
// 30ms either way. So the gesture is sampled exactly as finely as it ever was and an
// idle Shift stops touching the CPU at all.
//
// 10 Hz while idle delays only the discovery that the button went down. The ring still
// cannot appear until Finder has published the dragged files on the drag pasteboard,
// which needs the drag threshold crossed first, and a press is what moves this timer to
// 30 Hz - so the arming path is unchanged in every respect a user can feel.
let idleInterval = 1.0 / 10.0
let gestureInterval = 1.0 / 30.0
struct Payload: Encodable {
let type: String
let x: Double?
@ -47,14 +62,18 @@ func tick() {
exit(0)
}
let mouseDown = NSEvent.pressedMouseButtons & 1 != 0
let point = cursorLocation()
// Reading the cursor costs a CGEvent allocation, and nothing downstream wants a
// position unless a press is in progress or has just ended. An idle tick is then
// one read of `pressedMouseButtons` and a couple of integer tests.
let pressEnded = mouseWasDown && !mouseDown
let point = mouseDown || pressEnded ? cursorLocation() : NSPoint(x: 0, y: 0)
if !mouseDown {
changeCountAtMouseDown = dragPasteboard.changeCount
cancelled = false
missingDragFiles = 0
}
if !mouseDown && mouseWasDown && pickerShown {
if pressEnded && pickerShown {
pickerShown = false
emit(Payload(type: "end", x: point.x, y: point.y, files: nil, tools: nil))
}
@ -104,8 +123,23 @@ func tick() {
}
}
let timer = Timer(timeInterval: 1.0 / 30.0, repeats: true) { _ in
tick()
var timer: Timer?
var timerIsGesture = false
func reschedule(gesture: Bool) {
guard gesture != timerIsGesture || timer == nil else { return }
timerIsGesture = gesture
timer?.invalidate()
let next = Timer(timeInterval: gesture ? gestureInterval : idleInterval, repeats: true) { _ in
let down = NSEvent.pressedMouseButtons & 1 != 0
tick()
// A press changes the pace on the next tick; the timer is replaced rather
// than retuned because NSTimer cannot change its own interval.
if down != timerIsGesture { reschedule(gesture: down) }
}
timer = next
RunLoop.main.add(next, forMode: .common)
}
RunLoop.main.add(timer, forMode: .common)
reschedule(gesture: NSEvent.pressedMouseButtons & 1 != 0)
RunLoop.main.run()

View File

@ -1,7 +1,7 @@
{
"name": "shift",
"private": true,
"version": "0.1.3",
"version": "0.1.13",
"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",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

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

View File

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

View File

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

View File

@ -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,16 +128,14 @@ 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 已保护你的电脑”,请选择
“更多信息” > “仍要运行”。
3. 卸载请在“设置 > 应用”中移除 Shift,无需手动删除文件。
便携版
------
不想安装时,解压 Shift-Portable-{version}-win-{arch}.zip,直接运行其中的
shift.exe。请先完整解压,不要在压缩包的预览窗口里运行。
4. 首次启动若 Windows 安全中心询问网络访问,请允许 Shift 访问“专用网络”。
如果之前拒绝过,请到“Windows 安全中心 > 防火墙和网络保护 > 允许应用通过
防火墙”,勾选 Shift 的专用网络权限;否则“发送到设备”无法接收其它终端的信标。
运行组件
--------
@ -178,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
@ -213,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))

View File

@ -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
@ -31,15 +31,34 @@ NO_PUSH=0
while [ $# -gt 0 ]; do
case "$1" in
--notes) NOTES_FILE="$2"; shift 2 ;;
--notes|--key|--branch)
if [ "$#" -lt 2 ] || [ -z "${2:-}" ]; then
echo "$1 needs a value" >&2
exit 2
fi
case "$1" in
--notes) NOTES_FILE="$2" ;;
--key) KEY_FILE="$2" ;;
--branch) BRANCH="$2" ;;
esac
shift 2
;;
--dry-run) DRY_RUN=1; shift ;;
--no-push) NO_PUSH=1; shift ;;
--branch) BRANCH="$2"; shift 2 ;;
--key) KEY_FILE="$2"; shift 2 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
[ -n "$BRANCH" ] || { echo "--branch cannot be empty" >&2; exit 2; }
[ -z "$NOTES_FILE" ] || [ -f "$NOTES_FILE" ] || {
echo "notes file not found: $NOTES_FILE" >&2
exit 2
}
[ -z "$KEY_FILE" ] || [ -f "$KEY_FILE" ] || {
echo "release key not found: $KEY_FILE" >&2
exit 2
}
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
PLAN=$(mktemp /tmp/shift-release-plan.XXXXXX)
INDEX_FILE=$(mktemp /tmp/shift-release-index.XXXXXX)
@ -57,23 +76,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 +97,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)

View File

@ -28,7 +28,19 @@ USAGE = __doc__
def public_hex(path):
key = Ed25519PublicKey.from_public_bytes(path.read_bytes())
"""Hex of the public half of a key file, whichever half was handed over.
A raw ed25519 private key is 32 bytes and so is its public half, so the two
cannot be told apart by content. Baking the private bytes as if they were a
public key produces a key no signature ever verifies against, and the build
accepts it without complaint, so the mistake only surfaces on a user's
machine as "this build cannot verify the manifest". Anything not named
``*.pub`` is therefore read as the private key it came from and expanded.
"""
if path.suffix == ".pub":
key = Ed25519PublicKey.from_public_bytes(path.read_bytes())
else:
key = Ed25519PrivateKey.from_private_bytes(path.read_bytes()).public_key()
return key.public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
).hex()

View File

@ -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
@ -134,11 +111,15 @@ Function .onInit
nsExec::Exec 'taskkill /IM shift.exe /F'
Pop $0
; taskkill returns once termination is requested; give Windows a moment to
; release the mapped EXE before File tries to overwrite it.
Sleep 800
FunctionEnd
Function un.onInit
nsExec::Exec 'taskkill /IM shift.exe /F'
Pop $0
Sleep 800
FunctionEnd
Section "Install"
@ -185,7 +166,12 @@ Section "PostInstall"
ReadRegStr $0 HKCU "${WEBVIEW_KEY}" "pv"
${EndIf}
${If} $0 == ""
MessageBox MB_OK|MB_ICONINFORMATION "$(webview_missing)"
; A silent install is driven by Shift's updater and has nobody to dismiss a
; dialog. The missing runtime is still worth saying out loud on a manual
; install, but a box here would hold the update open forever.
${IfNot} ${Silent}
MessageBox MB_OK|MB_ICONINFORMATION "$(webview_missing)"
${EndIf}
${EndIf}
SectionEnd

20
src-tauri/Cargo.lock generated
View File

@ -3899,7 +3899,7 @@ dependencies = [
[[package]]
name = "shift"
version = "0.1.3"
version = "0.1.13"
dependencies = [
"base64 0.22.1",
"calamine",
@ -3910,6 +3910,7 @@ dependencies = [
"image",
"libc",
"lopdf 0.45.0",
"objc2",
"printpdf",
"quick-xml 0.42.0",
"serde",
@ -3921,6 +3922,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 +4477,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"

View File

@ -1,6 +1,6 @@
[package]
name = "shift"
version = "0.1.3"
version = "0.1.13"
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"] }
@ -53,8 +54,14 @@ windows-sys = { version = "0.59", features = [
"Win32_UI_WindowsAndMessaging",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
] }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
[target.'cfg(unix)'.dependencies]
libc = "0.2"

View File

@ -4,6 +4,8 @@
<dict>
<key>NSScreenCaptureUsageDescription</key>
<string>Shift captures the area you select for screenshots and screen recordings.</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Shift looks for other Shift copies on the same network so you can send files between them.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Shift can include microphone audio in screen recordings when you enable it.</string>
<key>NSDesktopFolderUsageDescription</key>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 859 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 763 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 941 B

After

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 1000 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 1000 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 757 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 1000 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 199 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -28,10 +28,7 @@ fn ensure_screen_capture_access() -> Result<(), String> {
return Ok(());
}
}
Err(
"Screen Recording permission is required. Enable Shift in System Settings > Privacy & Security > Screen Recording, then restart Shift if macOS asks."
.into(),
)
Err("errScreenPermission".into())
}
#[cfg(not(target_os = "macos"))]
@ -70,7 +67,7 @@ fn monitor_at_cursor(app: &AppHandle) -> Result<tauri::Monitor, String> {
&& cursor.y <= y + monitor.size().height as f64
})
.or_else(|| app.primary_monitor().ok().flatten())
.ok_or_else(|| "No monitor found under the cursor.".to_string())
.ok_or_else(|| "errNoMonitor".to_string())
}
fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result<CaptureSource, String> {
@ -100,10 +97,7 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result<CaptureSo
.status()
.map_err(|error| format!("Could not launch screencapture: {error}"))?;
if !status.success() {
return Err(
"Screen capture was cancelled or blocked. Allow Screen Recording in System Settings."
.into(),
);
return Err("errCaptureBlocked".into());
}
}
@ -129,16 +123,21 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result<CaptureSo
.args(["-f", output.to_string_lossy().as_ref()])
.status()
} else {
return Err("Install grim or gnome-screenshot to capture the screen on Linux.".into());
return Err("errCaptureToolMissing".into());
};
let status = status.map_err(|error| error.to_string())?;
if !status.success() {
return Err("Screen capture failed.".into());
return Err("errCaptureFailed".into());
}
}
let (width, height) =
image::image_dimensions(&output).map_err(|error| format!("Invalid capture: {error}"))?;
let (width, height) = match image::image_dimensions(&output) {
Ok(dimensions) => dimensions,
Err(error) => {
let _ = fs::remove_file(&output);
return Err(format!("Invalid capture: {error}"));
}
};
Ok(CaptureSource {
path: output.to_string_lossy().to_string(),
width,
@ -180,12 +179,12 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(),
};
if width <= 0 || height <= 0 {
restore_awareness();
return Err("Windows did not report a usable screen size.".into());
return Err("errWinScreenSize".into());
}
let screen = GetDC(std::ptr::null_mut());
if screen.is_null() {
restore_awareness();
return Err("Windows could not open the desktop surface.".into());
return Err("errWinDesktopDC".into());
}
let memory = CreateCompatibleDC(screen);
let bitmap = CreateCompatibleBitmap(screen, width, height);
@ -198,7 +197,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(),
}
ReleaseDC(std::ptr::null_mut(), screen);
restore_awareness();
return Err("Windows could not allocate a screenshot surface.".into());
return Err("errWinSurfaceAlloc".into());
}
let previous = SelectObject(memory, bitmap as HGDIOBJ);
let copied = BitBlt(
@ -251,7 +250,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(),
if copied == 0 || rows == 0 {
restore_awareness();
return Err("Windows could not copy the screen surface.".into());
return Err("errWinSurfaceCopy".into());
}
for pixel in pixels.chunks_exact_mut(4) {
pixel.swap(0, 2);
@ -259,7 +258,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(),
}
let Some(image) = image::RgbaImage::from_raw(width as u32, height as u32, pixels) else {
restore_awareness();
return Err("Windows returned an invalid screenshot buffer.".into());
return Err("errWinSurfaceBuffer".into());
};
let result = image
.save_with_format(output, image::ImageFormat::Png)
@ -273,13 +272,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 +322,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,
@ -339,19 +422,33 @@ pub fn crop_session(
let crop_width = (rect.width.clamp(0.0, 1.0) * width as f64).round() as u32;
let crop_height = (rect.height.clamp(0.0, 1.0) * height as f64).round() as u32;
if crop_width < 2 || crop_height < 2 || x >= width || y >= height {
return Err("Select an area first.".into());
return Err("errNoSelection".into());
}
let cropped = image.crop_imm(x, y, crop_width.min(width - x), crop_height.min(height - y));
let directory = screenshot_directory(app)?;
let name = format!("Shift-{}.png", Local::now().format("%Y%m%d-%H%M%S"));
let output = directory.join(name);
let stem = format!("Shift-{}", Local::now().format("%Y%m%d-%H%M%S"));
let output = unique_capture_path(&directory, &stem)?;
cropped
.save_with_format(&output, image::ImageFormat::Png)
.map_err(|error| error.to_string())?;
Ok(output)
}
fn unique_capture_path(directory: &Path, stem: &str) -> Result<PathBuf, String> {
crate::files::unique_output_in(Path::new(stem), Some(directory), "", "png")
}
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 +467,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 +495,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(())
}
@ -430,35 +526,25 @@ fn finish_capture(
app,
ActionOutcome {
outputs: vec![output.to_string_lossy().to_string()],
message: "Screenshot saved.".into(),
message: "outcomeSaved".into(),
},
);
Ok(output.to_string_lossy().to_string())
}
/// Route a finished capture per the Capture-after setting. The card is allowed to
/// fail silently: a screenshot that saved is more important than an overlay that
/// could not be built, and the file is already on disk and copied by then.
/// Show the result card for a finished capture. The card is allowed to fail
/// silently: a screenshot that saved is more important than an overlay that could
/// not be built, and the file is already on disk and copied by then. The editor is
/// the fallback so a capture is never left with no way to act on it.
fn hand_off(app: &AppHandle, output: &Path) {
match settings::load(app).capture_after {
settings::CaptureAfter::Editor => {
let _ = editor::show_editor(app, output);
}
settings::CaptureAfter::Card => {
if result_card::show(app, output).is_err() {
let _ = editor::show_editor(app, output);
}
}
if result_card::show(app, output).is_err() {
let _ = editor::show_editor(app, output);
}
}
pub fn capture_fullscreen_core(app: &AppHandle, state: &AppState) -> Result<String, String> {
ensure_screen_capture_access()?;
for label in ["main", "radial", "editor"] {
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 +570,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,12 +605,33 @@ 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"))]
{
Err("Screen Recording settings are macOS-specific.".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_captures_in_the_same_second_do_not_overwrite() {
let directory =
std::env::temp_dir().join(format!("shift-capture-name-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&directory).unwrap();
let stem = "Shift-20260101-120000";
let first = unique_capture_path(&directory, stem).unwrap();
fs::write(&first, b"first").unwrap();
let second = unique_capture_path(&directory, stem).unwrap();
assert_ne!(first, second);
assert_eq!(second.file_name().unwrap(), "Shift-20260101-120000 2.png");
assert_eq!(fs::read(&first).unwrap(), b"first");
fs::remove_dir_all(directory).ok();
}
}

View File

@ -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) {
@ -156,6 +153,8 @@ fn spawn_windows_monitor(app: &AppHandle) {
unsafe {
GetCursorPos(&mut point);
}
// Read once per pass so the sleep below and the arming test below agree.
let enabled = drag_enabled(&app);
if !mouse_down {
// Release ends the gesture. macOS gets an explicit `cancel` from its
@ -171,7 +170,7 @@ fn spawn_windows_monitor(app: &AppHandle) {
}
armed = false;
mouse_was_down = false;
thread::sleep(std::time::Duration::from_millis(33));
thread::sleep(monitor_pause(enabled, false));
continue;
}
@ -185,7 +184,7 @@ fn spawn_windows_monitor(app: &AppHandle) {
reported_foreground = true;
eprintln!("shift: press started inside Shift itself, ignoring this gesture");
}
thread::sleep(std::time::Duration::from_millis(33));
thread::sleep(monitor_pause(enabled, armed));
continue;
}
reported_foreground = false;
@ -197,23 +196,23 @@ fn spawn_windows_monitor(app: &AppHandle) {
let threshold_y = unsafe { GetSystemMetrics(SM_CYDRAG) }.max(4);
if !armed {
if !drag_enabled(&app) {
if !enabled {
if !reported_disabled {
reported_disabled = true;
eprintln!("shift: drag ring is disabled in settings, ignoring the gesture");
}
thread::sleep(std::time::Duration::from_millis(100));
thread::sleep(monitor_pause(enabled, armed));
continue;
}
reported_disabled = false;
if !shift {
thread::sleep(std::time::Duration::from_millis(33));
thread::sleep(monitor_pause(enabled, armed));
continue;
}
if (point.x - down.x).abs() <= threshold_x
&& (point.y - down.y).abs() <= threshold_y
{
thread::sleep(std::time::Duration::from_millis(33));
thread::sleep(monitor_pause(enabled, armed));
continue;
}
armed = true;
@ -239,11 +238,34 @@ fn spawn_windows_monitor(app: &AppHandle) {
}
}
thread::sleep(std::time::Duration::from_millis(33));
thread::sleep(monitor_pause(enabled, armed));
}
});
}
/// How long the Windows gesture watch sleeps before reading the mouse again.
///
/// The thread used to poll at 33ms for the whole life of the app: four user-input
/// calls, thirty times a second, forever, including on a machine where the ring is
/// switched off in Settings and no gesture can ever start. A disabled ring can afford
/// a quarter second, because the only thing it is waiting for is the switch itself,
/// and a flip in Settings is worth noticing within a blink rather than a frame.
///
/// An enabled ring keeps the original 33ms. That is not conservatism: the gesture is
/// a press-drag-release, and the loop has to observe the press in order to measure
/// the drag threshold from where the button went down. A slower watch does not merely
/// notice a finished gesture late, it never records the press at all, so the ring
/// silently stops opening for users who drag quickly. Once a gesture is in flight the
/// fast cadence is required for the same reason, which is why `armed` outranks `enabled`.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn monitor_pause(enabled: bool, armed: bool) -> std::time::Duration {
if enabled || armed {
std::time::Duration::from_millis(33)
} else {
std::time::Duration::from_millis(250)
}
}
#[cfg(target_os = "windows")]
fn foreground_is_self() -> bool {
use windows_sys::Win32::UI::WindowsAndMessaging::{
@ -482,6 +504,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())
@ -500,6 +526,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]
@ -549,7 +597,7 @@ pub async fn show_files_in_radial(
mode: Option<String>,
) -> Result<RadialContext, String> {
if files.is_empty() {
return Err("No files selected.".into());
return Err("errNoFiles".into());
}
tauri::async_runtime::spawn_blocking(move || {
show_radial(
@ -563,3 +611,39 @@ pub async fn show_files_in_radial(
.await
.map_err(|error| error.to_string())?
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_enabled_ring_keeps_the_press_by_polling_at_33ms() {
// The gesture is only recognised because the loop sees the button go down and
// measures the drag threshold from that point, so the watch cannot be slowed
// while the feature is switched on.
assert_eq!(
monitor_pause(true, false),
std::time::Duration::from_millis(33),
"an enabled ring must keep sampling at the original cadence"
);
}
#[test]
fn a_disabled_ring_is_watched_four_times_a_second_instead_of_thirty() {
assert_eq!(
monitor_pause(false, false),
std::time::Duration::from_millis(250),
"a switched-off ring should not cost a 33ms input poll for the life of the app"
);
}
#[test]
fn a_gesture_in_flight_outranks_the_switch_being_flipped_off() {
// Settings can be reached mid-drag; a gesture that has already armed must not
// slow down and drop the rest of the movement it is tracking.
assert_eq!(
monitor_pause(false, true),
std::time::Duration::from_millis(33)
);
}
}

View File

@ -0,0 +1,248 @@
//! Who decides the drag cursor above a webview.
//!
//! A button that cannot serve the files in flight is switched off for the length of the
//! gesture, and the cursor says it too: the copy badge AppKit paints beside the pointer
//! *is* the answer to "does this destination want the file", so the refusal belongs there
//! rather than in a mark drawn on top of the button.
//!
//! The page cannot put it there for a file from the file manager: that drag never reaches
//! the DOM, wry takes it, and `draggingUpdated:` reports `NSDragOperation::Copy` whatever
//! the page thinks (`wry/src/wkwebview/drag_drop.rs`). So the verdict is handed down here.
//! Both entry points keep calling wry — the events the page listens for and the drop it
//! accepts are wry's business; only the one word that says "welcome" is ours.
//!
//! Windows needs none of this: there the drag goes through OLE, whose report follows the
//! `dropEffect` the page set, so the cursor already answers `none` when asked.
#[cfg(target_os = "macos")]
use std::ffi::c_void;
#[cfg(target_os = "macos")]
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[cfg(target_os = "macos")]
use std::sync::Once;
#[cfg(target_os = "macos")]
use std::{thread, time::Duration};
use tauri::AppHandle;
#[cfg(target_os = "macos")]
use tauri::Emitter;
/// Whether the button under the pointer refuses the files in flight.
#[cfg(target_os = "macos")]
static REFUSE: AtomicBool = AtomicBool::new(false);
/// One release watcher at a time, and only while a refusal is on screen.
#[cfg(target_os = "macos")]
static WATCHING: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "macos")]
static INSTALL: Once = Once::new();
/// wry's own implementations, kept so that only the report changes.
#[cfg(target_os = "macos")]
static WRY_ENTERED: AtomicUsize = AtomicUsize::new(0);
#[cfg(target_os = "macos")]
static WRY_UPDATED: AtomicUsize = AtomicUsize::new(0);
/// `NSDragOperationNone`. Anything else tells AppKit the drop is welcome, and the cursor
/// of the session follows that report rather than anything the page renders.
#[cfg(target_os = "macos")]
const OPERATION_NONE: usize = 0;
/// The shape of `draggingEntered:` and `draggingUpdated:`, which both report an
/// `NSDragOperation`: an option set the size of `NSInteger`.
#[cfg(target_os = "macos")]
type DragReport =
unsafe extern "C-unwind" fn(*mut c_void, objc2::runtime::Sel, *mut c_void) -> usize;
/// Hand the cursor's answer to the native layer.
///
/// The page is the only thing that knows what the drag carries and which button the
/// pointer sits on; this is the one word it has about the cursor. Fire and forget - the
/// drag moves on while the call is in flight, and the newest report is the one that counts.
#[tauri::command]
pub fn set_drop_refusal(app: AppHandle, refused: bool) {
#[cfg(target_os = "macos")]
{
install();
let was_refusing = REFUSE.swap(refused, Ordering::AcqRel);
if refused && !was_refusing && !WATCHING.swap(true, Ordering::AcqRel) {
watch_for_release(app);
}
}
#[cfg(not(target_os = "macos"))]
{
// OLE asks this process what the drop is worth on every move, and WebView2's own
// drag controller forwards the effect the page set, so the cursor already answers
// `none` where it was asked to. There is nothing to override.
let _ = (app, refused);
}
}
/// The end of a refused drag is never delivered to the page: a destination that reports
/// `None` gets no `performDragOperation:`, and no `draggingExited:` either, so its buttons
/// would stay switched off with nothing in the air. The release of the button that started
/// the drag is watched here instead, and only while a refusal is on screen.
#[cfg(target_os = "macos")]
fn watch_for_release(app: AppHandle) {
thread::spawn(move || {
// The end of the gesture, told to the page so it can stand its buttons down.
let finish = || {
WATCHING.store(false, Ordering::Release);
// Only a gesture still being refused needs telling: one that moved onto a
// button that can serve it is over, and its drop is on its way.
if REFUSE.swap(false, Ordering::AcqRel) {
let _ = app.emit_to("main", "drop://cancelled", ());
}
};
// A drag presses, so a session where nothing is held is one the page watches end
// by itself; clearing the refusal here would only cut a working gesture short.
if !primary_button_held() {
WATCHING.store(false, Ordering::Release);
return;
}
// The ceiling is a held button for two minutes, which no real gesture reaches.
for _ in 0..4800 {
if !REFUSE.load(Ordering::Acquire) || !primary_button_held() {
break;
}
thread::sleep(Duration::from_millis(25));
}
finish();
});
}
/// Whether the primary mouse button is held: a drag always is, so its release ends the
/// session.
#[cfg(target_os = "macos")]
fn primary_button_held() -> bool {
/// `kCGEventSourceStateCombinedSessionState`
const SESSION: i32 = -1;
/// `kCGMouseButtonLeft`
const PRIMARY: i32 = 0;
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGEventSourceButtonState(state: i32, button: i32) -> bool;
}
unsafe { CGEventSourceButtonState(SESSION, PRIMARY) }
}
/// Replace the two report methods of wry's webview class.
///
/// Once, on first use: the class exists only after a window has been built, and changing
/// an implementation is safe from any thread.
#[cfg(target_os = "macos")]
fn install() {
INSTALL.call_once(|| {
let Some(class) = wry_web_view_class() else {
eprintln!("Shift could not find the webview class; refusals stay on the buttons.");
return;
};
let entered = swap(
class,
objc2::sel!(draggingEntered:),
dragging_entered,
&WRY_ENTERED,
);
let updated = swap(
class,
objc2::sel!(draggingUpdated:),
dragging_updated,
&WRY_UPDATED,
);
// The one way to notice that the swap never happened is that the cursor never
// says no, which is a thing to find in the log rather than by hand.
if entered && updated {
eprintln!(
"Shift answers for the drag cursor: {}",
class.name().to_string_lossy()
);
}
});
}
/// Replace one method and remember what was there before.
#[cfg(target_os = "macos")]
fn swap(
class: &'static objc2::runtime::AnyClass,
selector: objc2::runtime::Sel,
replacement: DragReport,
slot: &AtomicUsize,
) -> bool {
let Some(method) = class.instance_method(selector) else {
return false;
};
let implementation =
unsafe { std::mem::transmute::<DragReport, objc2::runtime::Imp>(replacement) };
let previous = unsafe { method.set_implementation(implementation) };
slot.store(previous as *const c_void as usize, Ordering::Release);
true
}
/// The class wry builds its webviews from.
///
/// Its name is generated from the module path plus the crate version, so it is looked for
/// rather than written down: an upgrade that only moves the version keeps working, and the
/// parent view of the same module cannot be mistaken for it.
#[cfg(target_os = "macos")]
fn wry_web_view_class() -> Option<&'static objc2::runtime::AnyClass> {
const NAME: &[u8] = b"wry::wkwebview::class::wry_web_view::WryWebView";
objc2::runtime::AnyClass::classes()
.iter()
.find(|class| class.name().to_bytes().starts_with(NAME))
.copied()
}
/// A session always begins permissive: the page answers a moment later, and refusing
/// before the carried files are known would waste a drag that works. The verdict is read
/// again after wry has run, so an entry that arrives while the page is still deciding
/// welcomes the file like any other.
#[cfg(target_os = "macos")]
unsafe extern "C-unwind" fn dragging_entered(
this: *mut c_void,
selector: objc2::runtime::Sel,
info: *mut c_void,
) -> usize {
REFUSE.store(false, Ordering::Release);
let welcome = report(WRY_ENTERED.load(Ordering::Acquire), this, selector, info);
refuse_if_verdict_says_so(welcome, REFUSE.load(Ordering::Acquire))
}
#[cfg(target_os = "macos")]
unsafe extern "C-unwind" fn dragging_updated(
this: *mut c_void,
selector: objc2::runtime::Sel,
info: *mut c_void,
) -> usize {
let welcome = report(WRY_UPDATED.load(Ordering::Acquire), this, selector, info);
refuse_if_verdict_says_so(welcome, REFUSE.load(Ordering::Acquire))
}
/// Say no where wry would have said yes, and never the other way round.
///
/// wry's implementation is always called first, and its answer is the one that gets
/// narrowed rather than replaced: that call is what carries `over` on to the page, and a
/// refusal that skipped it would also stop the page from hearing that the pointer had
/// moved. A destination that refuses once and then never hears again cannot change its
/// mind, and a gesture that started on a button which cannot serve the file would be lost
/// even after it moved onto one that can.
#[cfg(target_os = "macos")]
fn refuse_if_verdict_says_so(welcome: usize, refused: bool) -> usize {
if refused && welcome != OPERATION_NONE {
OPERATION_NONE
} else {
welcome
}
}
/// Call wry's own implementation, so everything except the report is untouched.
#[cfg(target_os = "macos")]
fn report(
previous: usize,
this: *mut c_void,
selector: objc2::runtime::Sel,
info: *mut c_void,
) -> usize {
if previous == 0 {
return OPERATION_NONE;
}
let previous: DragReport = unsafe { std::mem::transmute(previous) };
unsafe { previous(this, selector, info) }
}

View File

@ -1,5 +1,5 @@
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use base64::{engine::general_purpose::STANDARD, Engine as _};
use image::{GenericImageView, Rgba, RgbaImage};
@ -69,6 +69,18 @@ pub fn open_in_editor(app: AppHandle, path: String) -> Result<EditorInfo, String
const PIN_LABEL: &str = "pin";
const PIN_PREVIEW_EDGE: u32 = 1040;
static PIN_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// The longest edge of a freshly pinned window. A pin is a reference, so it must
/// not cover the screen the user is working on until they ask for more.
const PIN_SMALL_EDGE: f64 = 520.0;
/// How much of the monitor's work area an enlarged pin may take. Leaving a margin
/// keeps the window's own edges and the desktop around it reachable.
const PIN_FIT_FRACTION: f64 = 0.9;
/// How far past its own pixels an enlarged pin may grow. The preview is at most
/// 1040 px across, so a small picture pushed any further is mush rather than detail.
const PIN_MAX_GROWTH: f64 = 3.0;
/// Whether the visible pin is currently enlarged. The window is reused rather than
/// rebuilt, so this is the only record of which of the two sizes it is showing.
static PIN_ENLARGED: AtomicBool = AtomicBool::new(false);
/// Decoding a 100 MP image needs several hundred MiB before it is reduced to
/// the 1040 px preview. Keep the decode bounded so a large photo cannot exhaust
/// memory and stall Windows while the user is pinning it.
@ -146,6 +158,159 @@ fn is_current_pin(requested: Option<u64>, current: Option<u64>) -> bool {
matches!((requested, current), (Some(requested), Some(current)) if requested == current)
}
/// The window size in logical pixels that shows a `preview`-sized image, keeping
/// its aspect ratio.
///
/// Small is the freshly pinned reference: never larger than the picture itself,
/// never longer than 520 px on its longest edge. Enlarged fills up to
/// `PIN_FIT_FRACTION` of the monitor's work area and is allowed to grow past the
/// picture's own pixels, because "放大" means making it bigger to read, not
/// resampling it losslessly. `work_area` of `None` means the monitor could not be
/// read; that answers with the small size rather than a guess, since a pin sized
/// off a phantom screen is one the user cannot reach.
fn pin_window_size(
preview: (u32, u32),
work_area: Option<(f64, f64)>,
enlarged: bool,
) -> (f64, f64) {
let width = f64::from(preview.0.max(1));
let height = f64::from(preview.1.max(1));
let scale = match (enlarged, work_area) {
(true, Some((area_width, area_height))) => (area_width * PIN_FIT_FRACTION / width)
.min(area_height * PIN_FIT_FRACTION / height)
.min(PIN_MAX_GROWTH),
// A pin is never shrunk below the picture's own pixels at either size.
_ => (PIN_SMALL_EDGE / width.max(height)).min(1.0),
};
((width * scale).max(160.0), (height * scale).max(100.0))
}
/// The part of a monitor a window may be placed on: the screen minus the menu bar
/// and any dock, in the physical pixels the platform positions windows in.
#[derive(Clone, Copy, Debug)]
struct PinArea {
left: f64,
top: f64,
width: f64,
height: f64,
}
impl PinArea {
fn of(monitor: &tauri::Monitor) -> PinArea {
let area = monitor.work_area();
PinArea {
left: f64::from(area.position.x),
top: f64::from(area.position.y),
width: f64::from(area.size.width),
height: f64::from(area.size.height),
}
}
/// How much of it a window may be sized to, in the logical pixels `set_size`
/// is told in. Only the extent converts this way: the origin is asked in
/// physical pixels and is left alone.
fn logical_size(self, scale: f64) -> (f64, f64) {
(self.width / scale, self.height / scale)
}
}
/// The monitor a pin is on, with its usable area in both units and the scale factor
/// between them. `current_monitor` is preferred, with the primary monitor as the
/// answer for a window the platform cannot place; `None` when there is no monitor.
struct PinScreen {
/// Usable extent, in the logical pixels `set_size` is told in.
size: (f64, f64),
/// The same rectangle, in the physical pixels `set_position` is told in.
physical: PinArea,
scale: f64,
}
fn pin_screen(window: &tauri::WebviewWindow) -> Option<PinScreen> {
let monitor = window
.current_monitor()
.ok()
.flatten()
.or_else(|| window.primary_monitor().ok().flatten())?;
let scale = monitor.scale_factor().max(f64::MIN_POSITIVE);
let physical = PinArea::of(&monitor);
Some(PinScreen {
size: physical.logical_size(scale),
physical,
scale,
})
}
/// Where to put an enlarged pin so it stays centred on the window it replaces. All
/// three arguments are physical: growing from the centre is what makes the button
/// read as zooming the picture rather than moving a window, and clamping to the work
/// area is what stops a pin parked against a screen edge from growing away off it.
fn pin_placement(size: (f64, f64), scale: f64, centre: (f64, f64), area: PinArea) -> (i32, i32) {
let width = size.0 * scale;
let height = size.1 * scale;
let edge = |start: f64, length: f64, start_of_area: f64, span: f64| {
// An oversized window sits on the near edge instead of hanging off the far one.
if length >= span {
start_of_area
} else {
start.clamp(start_of_area, start_of_area + span - length)
}
};
(
edge(centre.0 - width / 2.0, width, area.left, area.width).round() as i32,
edge(centre.1 - height / 2.0, height, area.top, area.height).round() as i32,
)
}
/// The middle of the window as it stands, in physical pixels, so that changing its
/// size can hold the picture in place instead of sliding it down and right.
fn pin_centre(window: &tauri::WebviewWindow) -> Option<(f64, f64)> {
let position = window.outer_position().ok()?;
let size = window.outer_size().ok()?;
Some((
f64::from(position.x) + f64::from(size.width) / 2.0,
f64::from(position.y) + f64::from(size.height) / 2.0,
))
}
/// Enlarge the pin until it fills the screen, or put it back the size it arrived at.
/// One button for both directions, because an enlarged pin has to be shrunk again to
/// be usable as a reference, and a second control would spend hover space on the less
/// common half of the gesture. Returns whether the pin is now enlarged, so the page
/// can label the button the way the window looks.
#[tauri::command]
pub fn zoom_pin(app: AppHandle) -> Result<bool, String> {
let window = app
.get_webview_window(PIN_LABEL)
.ok_or_else(|| "Pin window is unavailable.".to_string())?;
let state = app.state::<AppState>();
let preview = state
.pinned_image
.lock()
.map_err(|error| error.to_string())?
.clone()
.ok_or_else(|| "Nothing is pinned.".to_string())?;
let enlarged = !PIN_ENLARGED.load(Ordering::Relaxed);
let screen =
pin_screen(&window).ok_or_else(|| "No display was found for this pin.".to_string())?;
let centre = pin_centre(&window);
let size = pin_window_size(
(preview.width, preview.height),
enlarged.then_some(screen.size),
enlarged,
);
window
.set_size(tauri::LogicalSize::new(size.0, size.1))
.map_err(|error| error.to_string())?;
if let Some(centre) = centre {
let (x, y) = pin_placement(size, screen.scale, centre, screen.physical);
window
.set_position(tauri::PhysicalPosition::new(x, y))
.map_err(|error| error.to_string())?;
}
PIN_ENLARGED.store(enlarged, Ordering::Relaxed);
Ok(enlarged)
}
#[tauri::command]
pub async fn pin_image(app: AppHandle, path: String) -> Result<(), String> {
let source = Path::new(&path).to_path_buf();
@ -158,30 +323,35 @@ pub async fn pin_image(app: AppHandle, path: String) -> Result<(), String> {
.await
.map_err(|error| error.to_string())??;
preview.id = PIN_SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1;
let max_edge = 520.0_f64;
let scale = (max_edge / preview.width.max(preview.height) as f64).min(1.0);
let window_width = (preview.width as f64 * scale).max(160.0);
let window_height = (preview.height as f64 * scale).max(100.0);
// A fresh pin always opens as the small reference, whatever the last one was
// showing, so an enlarged pin being replaced does not come back huge.
PIN_ENLARGED.store(false, Ordering::Relaxed);
let window = app
.get_webview_window(PIN_LABEL)
.ok_or_else(|| "Pin window is unavailable.".to_string())?;
// The small size is bounded by the picture, not the screen, so it needs no monitor.
let (window_width, window_height) =
pin_window_size((preview.width, preview.height), None, false);
window
.set_size(tauri::LogicalSize::new(window_width, window_height))
.map_err(|error| error.to_string())?;
if let Some((cursor, monitor_scale)) = app.cursor_position().ok().and_then(|cursor| {
if let Some((cursor, monitor_scale, work_area)) =
app.cursor_position().ok().and_then(|cursor| {
window
.monitor_from_point(cursor.x, cursor.y)
.ok()
.flatten()
.map(|monitor| (cursor, monitor.scale_factor(), PinArea::of(&monitor)))
})
{
let (x, y) = pin_placement(
(window_width, window_height),
monitor_scale,
(cursor.x, cursor.y),
work_area,
);
window
.monitor_from_point(cursor.x, cursor.y)
.ok()
.flatten()
.map(|monitor| (cursor, monitor.scale_factor()))
}) {
let physical_width = window_width * monitor_scale;
let physical_height = window_height * monitor_scale;
window
.set_position(tauri::PhysicalPosition::new(
(cursor.x - physical_width / 2.0).round() as i32,
(cursor.y - physical_height / 2.0).round() as i32,
))
.set_position(tauri::PhysicalPosition::new(x, y))
.map_err(|error| error.to_string())?;
}
let state = app.state::<AppState>();
@ -242,9 +412,88 @@ pub async fn close_pin(app: AppHandle) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::{flatten_for_pin, is_current_pin};
use super::{flatten_for_pin, is_current_pin, pin_placement, pin_window_size, PinArea};
use image::{DynamicImage, Rgba, RgbaImage};
/// The screen the tests place pins on: a 1512x982 laptop with a 2x backing
/// scale and a 37 px menu bar already taken out of the usable height.
fn retina() -> (PinArea, f64) {
(
PinArea {
left: 0.0,
top: 37.0,
width: 3024.0,
height: 1890.0,
},
2.0,
)
}
#[test]
fn a_fresh_pin_never_exceeds_its_own_picture_or_520_px() {
// The reference size is a ceiling, not a stretch: a small screenshot pinned
// at 320 px must stay 320 px rather than arrive blown up and blurry.
let small = pin_window_size((320, 200), Some((1512.0, 945.0)), false);
assert_eq!(small, (320.0, 200.0));
let large = pin_window_size((2400, 1200), Some((1512.0, 945.0)), false);
assert_eq!(large, (520.0, 260.0));
// And it is the same answer with no monitor at all, which is what a hidden
// pin window on a headless or mid-sleep display has to fall back to.
assert_eq!(pin_window_size((2400, 1200), None, false), large);
}
#[test]
fn enlarging_fills_the_screen_but_stays_inside_it() {
let (area, scale) = retina();
let logical = area.logical_size(scale);
let size = pin_window_size((1040, 520), Some(logical), true);
assert!(
size.0 <= logical.0 && size.1 <= logical.1,
"{size:?} out of {logical:?}"
);
// 90% of the usable width is what binds for a 2:1 screenshot, and the point
// of the button is that the picture really does grow past its preview.
assert!(size.0 > logical.0 * 0.85, "{size:?} did not grow");
assert!((size.0 / size.1 - 2.0).abs() < 0.01, "aspect ratio lost");
}
#[test]
fn a_small_picture_is_not_blown_up_to_the_ceiling() {
// The preview is capped at 1040 px, so an 80 px icon enlarged threefold is
// already as much softness as this button should sell. Without the cap a
// pinned emoji would fill the display and dissolve.
let (area, scale) = retina();
let size = pin_window_size((80, 80), Some(area.logical_size(scale)), true);
assert_eq!(size, (240.0, 240.0));
}
#[test]
fn an_enlarged_pin_grows_from_its_centre() {
let (area, scale) = retina();
let centre = (800.0, 600.0);
let placed = pin_placement((600.0, 400.0), scale, centre, area);
// Centre is preserved in physical pixels: 800 - (600 x 2)/2, 600 - (400 x 2)/2.
assert_eq!(placed, (200, 200));
}
#[test]
fn a_pin_against_a_screen_edge_grows_inward_not_off_screen() {
let (area, scale) = retina();
// Pinned hard against the top-left: enlarging must pull it back inside the
// work area instead of pushing half the picture under the menu bar.
let placed = pin_placement((1000.0, 800.0), scale, (100.0, 120.0), area);
assert_eq!(placed, (0, area.top as i32));
// And the same at the far corner, where the clamp is against the right edge.
let far = pin_placement((1000.0, 800.0), scale, (2950.0, 1900.0), area);
assert_eq!(
far,
(
(area.width - 2000.0) as i32,
(area.top + area.height - 1600.0) as i32
)
);
}
#[test]
fn only_the_newest_pin_can_reveal_the_window() {
assert!(is_current_pin(Some(4), Some(4)));

View File

@ -1,7 +1,7 @@
use std::{
ffi::OsStr,
fs::{self, File},
io::{BufReader, Cursor, Write},
io::{BufReader, Cursor, Read, Write},
path::{Path, PathBuf},
process::Command,
sync::OnceLock,
@ -31,6 +31,13 @@ const DOCUMENT_EXTENSIONS: &[&str] = &[
];
const PRESENTATION_EXTENSIONS: &[&str] = &["pptx", "ppt", "key"];
const SPREADSHEET_EXTENSIONS: &[&str] = &["xlsx", "xls", "xlsb", "ods", "csv", "tsv", "numbers"];
/// Inline editor data crosses the Tauri IPC boundary twice (read and save), so a
/// file that is unusually large for an image is refused before it is base64
/// encoded or decoded a second time.
const MAX_EDITOR_IMAGE_BYTES: u64 = 64 * 1024 * 1024;
const MAX_EDITOR_IMAGE_PIXELS: u64 = 40_000_000;
const MAX_EDITOR_DATA_URL_BYTES: usize = 128 * 1024 * 1024;
const MAX_EDITOR_TEXT_BYTES: u64 = 8 * 1024 * 1024;
fn extension_of(path: &Path) -> String {
path.extension()
@ -77,7 +84,16 @@ fn preview_for(path: &Path, ext: &str) -> Option<(String, Option<u32>, Option<u3
if !IMAGE_EXTENSIONS.contains(&ext) {
return None;
}
let image = image::open(path).ok()?;
let bytes = read_file_limited(path, MAX_EDITOR_IMAGE_BYTES, "errImageTooLarge").ok()?;
let (width, height) = image::ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()
.ok()?
.into_dimensions()
.ok()?;
if u64::from(width) * u64::from(height) > MAX_EDITOR_IMAGE_PIXELS {
return None;
}
let image = image::load_from_memory(&bytes).ok()?;
let (width, height) = image.dimensions();
let preview = image.thumbnail(520, 520);
let mut png = Vec::new();
@ -91,6 +107,34 @@ fn preview_for(path: &Path, ext: &str) -> Option<(String, Option<u32>, Option<u3
))
}
fn read_file_limited(path: &Path, limit: u64, too_large: &str) -> Result<Vec<u8>, String> {
let metadata = fs::metadata(path).map_err(|error| error.to_string())?;
if !metadata.is_file() {
return Err("errNotAFile".into());
}
if metadata.len() > limit {
return Err(too_large.into());
}
let file = File::open(path).map_err(|error| error.to_string())?;
let metadata = file.metadata().map_err(|error| error.to_string())?;
if !metadata.is_file() {
return Err("errNotAFile".into());
}
if metadata.len() > limit {
return Err(too_large.into());
}
let mut bytes = Vec::new();
file.take(limit + 1)
.read_to_end(&mut bytes)
.map_err(|error| error.to_string())?;
if bytes.len() as u64 > limit {
return Err(too_large.into());
}
Ok(bytes)
}
pub fn inspect_paths(paths: &[String]) -> Result<Vec<FileInfo>, String> {
let mut files = Vec::new();
for raw_path in paths {
@ -204,13 +248,11 @@ fn save_image(
fn describe_write_error(output: &Path, error: std::io::Error) -> String {
if error.kind() == std::io::ErrorKind::PermissionDenied {
return format!(
"Shift cannot write to {}. Allow access in System Settings > Privacy & Security > Files and Folders, or choose another output folder in Settings.",
output
.parent()
.unwrap_or(output)
.display()
);
// The interface words this; a sentence written here could only ever be
// English, and the panel that shows it knows the language. The folder is
// what a log needs, so it goes there instead of into the message.
eprintln!("cannot write to {}", output.display());
return "errWriteDenied".into();
}
format!("Could not write {}: {error}", output.display())
}
@ -554,11 +596,16 @@ fn find_winget_package_tool(name: &str, file_names: &[String]) -> Option<PathBuf
None
}
/// Resolved Windows tool paths, keyed by the command name the caller asked for. The
/// search walks several install trees, so it is done once per name; `reset_tool_cache`
/// is what forgets it after an install changes the machine.
#[cfg(target_os = "windows")]
static WINDOWS_TOOL_CACHE: OnceLock<std::sync::Mutex<std::collections::HashMap<String, PathBuf>>> =
OnceLock::new();
#[cfg(target_os = "windows")]
fn find_windows_tool(name: &str) -> Option<PathBuf> {
static FOUND: OnceLock<std::sync::Mutex<std::collections::HashMap<String, PathBuf>>> =
OnceLock::new();
let cache = FOUND.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
let cache = WINDOWS_TOOL_CACHE.get_or_init(Default::default);
if let Some(path) = cache.lock().ok().and_then(|tools| tools.get(name).cloned()) {
return Some(path);
}
@ -571,6 +618,114 @@ fn find_windows_tool(name: &str) -> Option<PathBuf> {
found
}
/// Forget every resolved tool path. A package manager has just installed something, and
/// a path found before that install is no longer a safe answer.
#[cfg(target_os = "windows")]
pub(crate) fn reset_tool_cache() {
if let Some(cache) = WINDOWS_TOOL_CACHE.get() {
if let Ok(mut tools) = cache.lock() {
tools.clear();
}
}
}
/// Pick up a PATH that changed while Shift was running.
///
/// An install writes the new directory into the registry, and a fresh shell or Explorer
/// window picks it up from there; a running process keeps the environment block it was
/// launched with. Without this, a component Shift has *just* installed stays invisible to
/// its own resolver, and the panel reports an install that succeeded as a failure.
/// Reading the two registry PATHs into the live environment also means every child
/// process Shift starts from now on inherits it.
#[cfg(target_os = "windows")]
pub(crate) fn refresh_process_path() {
let current = std::env::var_os("PATH").unwrap_or_default();
let mut directories: Vec<PathBuf> = std::env::split_paths(&current)
.filter(|directory| !directory.as_os_str().is_empty())
.collect();
let before = directories.len();
for key in [
(
windows_sys::Win32::System::Registry::HKEY_CURRENT_USER,
r"Environment",
),
(
windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
),
] {
let Some(path) = windows_registry_path(key.0, key.1) else {
continue;
};
for directory in std::env::split_paths(&path) {
if !directory.as_os_str().is_empty() && !directories.contains(&directory) {
directories.push(directory);
}
}
}
if directories.len() == before {
return;
}
if let Ok(path) = std::env::join_paths(directories) {
std::env::set_var("PATH", path);
}
}
/// `Path` from a registry environment key: `HKCU\Environment` for the per-user PATH
/// and the Session Manager key for the machine PATH.
///
/// `RegGetValueW` is asked without `RRF_NOEXPAND`, so a value stored as
/// `REG_EXPAND_SZ` arrives with `%SystemRoot%`-style references already resolved, which
/// is how the system builds a process environment from the same key.
#[cfg(target_os = "windows")]
fn windows_registry_path(
root: windows_sys::Win32::System::Registry::HKEY,
subkey: &str,
) -> Option<std::ffi::OsString> {
use std::os::windows::ffi::OsStringExt;
use windows_sys::Win32::System::Registry::{RegGetValueW, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ};
let subkey: Vec<u16> = subkey.encode_utf16().chain(std::iter::once(0)).collect();
let name: Vec<u16> = "Path".encode_utf16().chain(std::iter::once(0)).collect();
let filter = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ;
let mut size = 0_u32;
let queried = unsafe {
RegGetValueW(
root,
subkey.as_ptr(),
name.as_ptr(),
filter,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut size,
)
};
if queried != 0 || size == 0 {
return None;
}
let mut buffer = vec![0_u16; size as usize / std::mem::size_of::<u16>()];
let read = unsafe {
RegGetValueW(
root,
subkey.as_ptr(),
name.as_ptr(),
filter,
std::ptr::null_mut(),
buffer.as_mut_ptr().cast(),
&mut size,
)
};
if read != 0 {
return None;
}
let end = buffer
.iter()
.position(|value| *value == 0)
.unwrap_or(buffer.len());
let raw = std::ffi::OsString::from_wide(&buffer[..end]);
Some(raw)
}
#[cfg(target_os = "windows")]
fn find_windows_tool_uncached(name: &str) -> Option<PathBuf> {
let file_names = windows_tool_file_names(name);
@ -636,10 +791,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 +1078,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,12 +1164,35 @@ 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
// every inline drawing, so the PDF keeps the text and loses the figures.
// Pandoc reads the same file as HTML with the media extracted next to it.
let mut work_dir = None;
if extension == "docx" && office::contains_inline_images(input).unwrap_or(false) {
let work = std::env::temp_dir().join(format!("shift-docx-html-{}", uuid::Uuid::new_v4()));
if fs::create_dir_all(&work).is_ok() {
if let Some(html) = docx_html_via_pandoc(input, &work) {
source = html;
work_dir = Some(work);
} else {
let _ = fs::remove_dir_all(work);
}
}
}
let mut base_dir = input
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
if let Some(work) = work_dir.as_ref() {
base_dir = work.clone();
}
if matches!(extension.as_str(), "md" | "markdown") {
// Markdown must never reach the renderer as plain text: without that
// step the PDF is a printout of the markup. Pandoc is nicer when it is
@ -1002,22 +1229,64 @@ 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);
}
if let Some(directory) = work_dir {
let _ = fs::remove_dir_all(directory);
}
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))
}
/// Renders a DOCX into the HTML document the macOS printer prints from.
///
/// Pandoc's reader keeps the pictures, tables and heading levels; the body is
/// wrapped in the stylesheet the Markdown path already uses, and the media
/// stays as files in `work` rather than base64 inside the HTML, which would
/// bloat a document whose figures are photographs.
#[cfg(target_os = "macos")]
fn docx_html_via_pandoc(input: &Path, work: &Path) -> Option<PathBuf> {
let pandoc = resolve_tool("pandoc")?;
let html = work.join("document.html");
let status = background_command(&pandoc)
.arg(input)
.args(["-f", "docx", "-t", "html5"])
.arg("--extract-media")
.arg(work.join("media"))
.args(["-o", html.to_string_lossy().as_ref()])
.status()
.ok()?;
if !status.success() || !html.exists() {
return None;
}
let body = fs::read_to_string(&html).ok()?;
if fs::write(&html, crate::markdown::page(&body)).is_err() {
return None;
}
Some(html)
}
/// Converts through the built-in macOS text converter.
///
/// Pandoc is an optional tool, and machines without it used to fail every
@ -1141,6 +1410,16 @@ fn convert_document(
let target = target.to_ascii_lowercase();
let pdf_engine = (target == "pdf").then(document_pdf_engine).flatten();
if target == "pdf" && pdf_engine.is_none() {
// Only Windows and Linux drive a PDF engine through Pandoc, and only they list
// one in Settings > Runtime components. Reaching this on macOS means the
// built-in renderer is unavailable too, so pointing at a Typst row there would
// send the user to a row that panel never shows.
#[cfg(target_os = "macos")]
return Err(
"PDF output needs the built-in document renderer or a Pandoc PDF engine (Typst, WeasyPrint, or a LaTeX engine on your PATH)."
.into(),
);
#[cfg(not(target_os = "macos"))]
return Err(
"PDF output needs a Pandoc PDF engine. Install Typst from Settings > Runtime Components or add a supported engine to your PATH."
.into(),
@ -1171,6 +1450,13 @@ fn convert_document(
let output = unique_output_in(input, output_dir, "", extension)?;
let mut command = background_command(&pandoc);
command.arg(input);
// Pandoc resolves an image path relative to its own working directory,
// which for a running Shift is nowhere near the document. Without this a
// Markdown image is reported as unfetchable and replaced by its alt text,
// so the DOCX/RTF/HTML output silently loses every figure.
if let Some(directory) = input.parent().filter(|value| !value.as_os_str().is_empty()) {
command.arg("--resource-path").arg(directory);
}
if let Some(writer) = writer {
command.args(["-t", writer]);
}
@ -1518,20 +1804,20 @@ pub fn perform_action(
on_progress: Option<&(dyn Fn(u32, u32, bool) + Sync)>,
) -> Result<ActionOutcome, String> {
if paths.is_empty() {
return Err("No files selected.".into());
return Err("errNoFiles".into());
}
if action == "reveal" {
reveal_path(Path::new(&paths[0]))?;
return Ok(ActionOutcome {
outputs: vec![],
message: "Revealed in file manager.".into(),
message: "outcomeRevealed".into(),
});
}
if action == "open" {
open_path(Path::new(&paths[0]))?;
return Ok(ActionOutcome {
outputs: vec![],
message: "Opened.".into(),
message: "outcomeOpened".into(),
});
}
@ -1545,7 +1831,7 @@ pub fn perform_action(
let output = pdf::merge(&pdf_paths, output_dir)?;
return Ok(ActionOutcome {
outputs: vec![output.to_string_lossy().to_string()],
message: "Merged PDFs.".into(),
message: "outcomeMergedPdfs".into(),
});
}
let image_paths: Vec<PathBuf> = paths
@ -1557,21 +1843,21 @@ pub fn perform_action(
let output = pdf::images_to_pdf(&image_paths, output_dir)?;
return Ok(ActionOutcome {
outputs: vec![output.to_string_lossy().to_string()],
message: "Combined images into a PDF.".into(),
message: "outcomeImagesToPdf".into(),
});
}
return Err("Merge works with multiple PDFs or multiple images.".into());
return Err("errMergeKinds".into());
}
if action == "split" {
if pdf_paths.is_empty() {
return Err("Split works with PDF files.".into());
return Err("errSplitPdf".into());
}
let mut outputs = Vec::new();
for path in &pdf_paths {
outputs.extend(pdf::split(path, output_dir)?);
}
return Ok(ActionOutcome {
message: format!("Saved {} PDF pages.", outputs.len()),
message: "outcomePdfPages".into(),
outputs: outputs
.into_iter()
.map(|path| path.to_string_lossy().to_string())
@ -1580,14 +1866,14 @@ pub fn perform_action(
}
if action == "text" {
if pdf_paths.is_empty() {
return Err("Text extraction currently works with PDF files.".into());
return Err("errTextPdf".into());
}
let mut outputs = Vec::new();
for path in &pdf_paths {
outputs.push(pdf::extract_text(path, output_dir)?);
}
return Ok(ActionOutcome {
message: "Extracted PDF text.".into(),
message: "outcomePdfText".into(),
outputs: outputs
.into_iter()
.map(|path| path.to_string_lossy().to_string())
@ -1611,7 +1897,7 @@ pub fn perform_action(
outputs.extend(pdf::to_images(path, extension, output_dir)?);
}
return Ok(ActionOutcome {
message: format!("Saved {} PDF pages.", outputs.len()),
message: "outcomePdfPages".into(),
outputs: outputs
.into_iter()
.map(|path| path.to_string_lossy().to_string())
@ -1665,12 +1951,7 @@ pub fn perform_action(
let _ = fs::remove_file(&temporary);
result?
}
"convert" if is_pdf => {
return Err(
"Pick a supported target for this PDF: an image format, TXT, MD, DOCX or RTF."
.into(),
)
}
"convert" if is_pdf => return Err("errPdfTarget".into()),
"convert"
if is_image
&& target
@ -1768,11 +2049,7 @@ pub fn perform_action(
outputs.push(output.to_string_lossy().to_string());
}
Ok(ActionOutcome {
message: if outputs.len() == 1 {
"Saved 1 file.".into()
} else {
format!("Saved {} files.", outputs.len())
},
message: "outcomeSaved".into(),
outputs,
})
}
@ -1885,18 +2162,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)))
@ -1906,11 +2171,14 @@ pub async fn open_file(path: String) -> Result<(), String> {
#[tauri::command]
pub async fn read_text_file(path: String) -> Result<String, String> {
tauri::async_runtime::spawn_blocking(move || {
fs::read_to_string(path).map_err(|error| error.to_string())
})
.await
.map_err(|error| error.to_string())?
tauri::async_runtime::spawn_blocking(move || read_text_file_in(Path::new(&path)))
.await
.map_err(|error| error.to_string())?
}
fn read_text_file_in(path: &Path) -> Result<String, String> {
let bytes = read_file_limited(path, MAX_EDITOR_TEXT_BYTES, "errTextTooLarge")?;
String::from_utf8(bytes).map_err(|error| error.to_string())
}
/// Return image bytes as a data URL. The editor draws this into a canvas and
@ -1928,7 +2196,17 @@ fn image_data_url(path: &Path) -> Result<String, String> {
if !IMAGE_EXTENSIONS.contains(&ext.as_str()) {
return Err("This file is not a supported image.".to_string());
}
let bytes = fs::read(path).map_err(|error| error.to_string())?;
let bytes = read_file_limited(path, MAX_EDITOR_IMAGE_BYTES, "errImageTooLarge")?;
if image::ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()
.ok()
.and_then(|reader| reader.into_dimensions().ok())
.is_some_and(|(width, height)| {
u64::from(width) * u64::from(height) > MAX_EDITOR_IMAGE_PIXELS
})
{
return Err("errImageTooLarge".into());
}
Ok(format!(
"data:{};base64,{}",
image_mime(&ext),
@ -1949,7 +2227,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
@ -1962,6 +2240,9 @@ fn save_image_data_in(
suffix: Option<&str>,
output_dir: Option<&Path>,
) -> Result<String, String> {
if data_url.len() > MAX_EDITOR_DATA_URL_BYTES {
return Err("errEditDataTooLarge".into());
}
let encoded = data_url
.split_once(',')
.map(|(_, value)| value)
@ -1969,6 +2250,19 @@ fn save_image_data_in(
let bytes = STANDARD
.decode(encoded)
.map_err(|error| format!("Invalid image data: {error}"))?;
if bytes.len() as u64 > MAX_EDITOR_IMAGE_BYTES {
return Err("errEditDataTooLarge".into());
}
if image::ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()
.ok()
.and_then(|reader| reader.into_dimensions().ok())
.is_some_and(|(width, height)| {
u64::from(width) * u64::from(height) > MAX_EDITOR_IMAGE_PIXELS
})
{
return Err("errImageTooLarge".into());
}
let image = image::load_from_memory(&bytes)
.map_err(|error| format!("Could not decode edited image: {error}"))?;
let input = Path::new(source);
@ -2034,7 +2328,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
@ -2047,6 +2341,9 @@ fn save_text_near_in(
suffix: Option<&str>,
output_dir: Option<&Path>,
) -> Result<String, String> {
if text.len() as u64 > MAX_EDITOR_TEXT_BYTES {
return Err("errTextTooLarge".into());
}
let input = Path::new(source);
let output = unique_output_in(input, output_dir, suffix.unwrap_or(" (OCR)"), "txt")?;
fs::write(&output, text).map_err(|error| describe_write_error(&output, error))?;
@ -2080,6 +2377,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();
@ -2187,6 +2540,26 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn editor_reads_are_bounded_before_they_allocate() {
let dir = scratch_dir();
let text = dir.join("too-large.txt");
File::create(&text)
.unwrap()
.set_len(MAX_EDITOR_TEXT_BYTES + 1)
.unwrap();
assert_eq!(read_text_file_in(&text).unwrap_err(), "errTextTooLarge");
assert_eq!(read_text_file_in(&dir).unwrap_err(), "errNotAFile");
let image = dir.join("too-large.png");
File::create(&image)
.unwrap()
.set_len(MAX_EDITOR_IMAGE_BYTES + 1)
.unwrap();
assert_eq!(image_data_url(&image).unwrap_err(), "errImageTooLarge");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn saves_edited_image_data() {
let dir = scratch_dir();
@ -2432,6 +2805,155 @@ 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.
#[cfg(target_os = "macos")]
#[test]
fn keeps_pictures_when_rendering_a_text_docx_to_pdf() {
if which::which("pandoc").is_err() {
return;
}
let dir = scratch_dir();
let picture = dir.join("figure.png");
sample_image(&picture);
// Pandoc writes the fixture so the DOCX is a file a real reader accepts,
// with text and a picture in the same body.
let markdown = dir.join("report.md");
fs::write(
&markdown,
format!(
"# Report\n\nArchitecture overview.\n\n![Figure]({})\n",
picture.display()
),
)
.unwrap();
let input = dir.join("report.docx");
let status = background_command("pandoc")
.arg(&markdown)
.args(["-o", input.to_string_lossy().as_ref()])
.status()
.unwrap();
assert!(status.success() && input.exists());
assert!(office::contains_inline_images(&input).unwrap());
let output = convert_document(&input, "pdf", None, None).unwrap();
assert!(
pdf::has_embedded_images(&output).unwrap(),
"the figure was dropped from {}",
output.display()
);
let text = pdf::text_of(&output).unwrap_or_default();
assert!(text.contains("Architecture overview"), "{text}");
fs::remove_dir_all(dir).unwrap();
}
/// The second half of the same bug. The layout sizes a picture from the
/// density header inside the file, so a screenshot saved at 96 dpi asks for
/// 1200 points and prints as a cropped fragment of itself. The renderer has
/// to fit it to the page; a Form XObject's `/BBox` reports that width
/// without needing the content stream decoded.
#[cfg(target_os = "macos")]
#[test]
fn fits_a_wide_picture_onto_the_page() {
if which::which("pandoc").is_err() {
return;
}
let dir = scratch_dir();
let picture = dir.join("screenshot.png");
// 1200 px, and 72 dpi is what the layout assumes for a file with none.
RgbaImage::from_pixel(1200, 400, Rgba([30, 120, 200, 255]))
.save_with_format(&picture, ImageFormat::Png)
.unwrap();
let markdown = dir.join("shot.md");
fs::write(
&markdown,
format!("# Shot\n\nbefore\n\n![S]({})\n\nafter\n", picture.display()),
)
.unwrap();
let input = dir.join("shot.docx");
assert!(background_command("pandoc")
.arg(&markdown)
.args(["-o", input.to_string_lossy().as_ref()])
.status()
.unwrap()
.success());
let output = convert_document(&input, "pdf", None, None).unwrap();
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 left = *blue_columns.iter().min().expect("the picture disappeared");
let right = *blue_columns.iter().max().expect("the picture disappeared");
assert!(
left > 1 && right + 2 < page.width(),
"picture runs off the page: columns {left}..={right} of {}",
page.width()
);
fs::remove_dir_all(dir).unwrap();
}
/// A Markdown image is stored as a path, so Pandoc has to fetch the file to
/// embed it. It resolves that path against its own working directory, which
/// for a running Shift is nowhere near the document, and a figure it cannot
/// read is quietly replaced by its alt text.
#[test]
fn keeps_markdown_images_when_converting_to_word() {
if which::which("pandoc").is_err() {
return;
}
let dir = scratch_dir();
let nested = dir.join("images");
fs::create_dir_all(&nested).unwrap();
let picture = nested.join("architecture.png");
sample_image(&picture);
let input = dir.join("report.md");
fs::write(
&input,
"# Report\n\n![Architecture](images/architecture.png)\n",
)
.unwrap();
for target in ["docx", "rtf"] {
let output = convert_document(&input, target, None, None).unwrap();
let bytes = fs::read(&output).unwrap();
let embedded = if target == "docx" {
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 {
bytes.windows(7).any(|window| window == b"pngblip")
};
assert!(
embedded,
"{target} written from {} lost the picture",
input.display()
);
}
fs::remove_dir_all(dir).unwrap();
}
#[cfg(target_os = "macos")]
#[test]
fn renders_presentations_to_pdf() {
@ -2555,7 +3077,7 @@ mod tests {
None,
)
.unwrap_err();
assert!(error.contains("DOCX or RTF"), "{error}");
assert_eq!(error, "errPdfTarget");
fs::remove_dir_all(dir).unwrap();
}

View File

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

View File

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

View File

@ -1,6 +1,7 @@
mod autostart;
mod capture;
mod drag_bridge;
mod drop_cursor;
mod editor;
mod files;
mod history;
@ -58,6 +59,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 +95,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 +108,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}");
@ -120,7 +139,7 @@ fn spawn_capture_work(
let reporter = app.clone();
tauri::async_runtime::spawn(async move {
let result = tauri::async_runtime::spawn_blocking(move || work(worker)).await;
if let Err(error) = result.unwrap_or_else(|_| Err("Capture was interrupted.".into())) {
if let Err(error) = result.unwrap_or_else(|_| Err("errCaptureInterrupted".into())) {
report_error(&reporter, error);
show_main(&reporter);
}
@ -206,16 +225,29 @@ pub fn refresh_tray_language(app: &AppHandle) -> Result<(), String> {
Ok(())
}
/// The wheel mark, drawn flat and alpha-only so the shell can tint it.
/// Regenerate with `scripts/build-icons.py`, which draws the app icon from the
/// same geometry so the two cannot drift apart.
const TRAY_ICON: &[u8] = include_bytes!("../icons/tray-template.png");
fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
let persisted = settings::load(app);
let language = locale::preferred(Some(&persisted.language));
set_tray_language(language);
let menu = tray_menu(app, language)?;
// The system draws this one, not the app's colour wheel: a flat mark that
// macOS tints black or white for the menu bar, and that stays legible at the
// 16 px the Windows notification area allows. The coloured icon is unreadable
// at both sizes, which is what "use a black/white system icon" asked for.
let icon = tauri::image::Image::from_bytes(TRAY_ICON)?;
let mut tray = TrayIconBuilder::with_id("shift")
let tray = TrayIconBuilder::with_id("shift")
.menu(&menu)
.show_menu_on_left_click(true)
.tooltip("Shift")
.icon(icon)
// Template images are a macOS idea; Windows has no tinting to ask of.
.icon_as_template(cfg!(target_os = "macos"))
.on_menu_event(|app, event| match event.id().as_ref() {
"open" => show_main(app),
"capture" => start_capture_from_event(app, "screenshot"),
@ -232,9 +264,6 @@ fn setup_tray(app: &AppHandle) -> tauri::Result<()> {
"quit" => app.exit(0),
_ => {}
});
if let Some(icon) = app.default_window_icon() {
tray = tray.icon(icon.clone());
}
tray.build(app)?;
Ok(())
}
@ -367,6 +396,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 +411,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,
@ -402,12 +433,11 @@ pub fn run() {
settings::set_autostart,
settings::check_output_access,
settings::set_language,
settings::set_capture_after,
settings::set_update_check_enabled,
settings::set_setup_reviewed,
settings::get_wedge_orders,
settings::set_wedge_order,
settings::reveal_output_directory,
drop_cursor::set_drop_refusal,
update::update_check,
update::update_status,
update::update_download,
@ -415,7 +445,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,
@ -438,10 +468,11 @@ pub fn run() {
editor::get_pinned_image,
editor::pin_ready,
editor::close_pin,
editor::zoom_pin,
drag_bridge::get_radial_context,
drag_bridge::hide_radial,
drag_bridge::stand_down_radial,
drag_bridge::show_files_in_radial,
share::share_peers,
share::share_answer,
share::share_refresh,
share::share_send,
@ -481,6 +512,9 @@ pub fn run() {
}
}
// Before the tray is built, so a release noticed on an earlier run also
// brings back its tray row and not just the banner.
update::restore_notice(app.handle());
setup_tray(app.handle())?;
register_shortcuts(app.handle())?;
drag_bridge::spawn(app.handle());
@ -600,6 +634,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")

View File

@ -128,7 +128,7 @@ pub fn tray_titles(language: &str) -> TrayTitles {
capture: "区域截图",
fullscreen: "全屏截图",
record: "区域录屏",
ocr: "识别图片文字…",
ocr: "文字识别",
update: "发现新版本 ",
quit: "退出 Shift",
}
@ -138,7 +138,7 @@ pub fn tray_titles(language: &str) -> TrayTitles {
capture: "Capture area",
fullscreen: "Capture full screen",
record: "Record area",
ocr: "OCR an image…",
ocr: "OCR",
update: "Update available ",
quit: "Quit Shift",
}
@ -198,9 +198,13 @@ mod tests {
let chinese = tray_titles(CHINESE);
assert_eq!(chinese.quit, "退出 Shift");
assert_eq!(chinese.capture, "区域截图");
// The tray row carries the same words as the window's own OCR button, and
// no ellipsis: every other row is a command, not a preview.
assert_eq!(chinese.ocr, "文字识别");
let english = tray_titles(ENGLISH);
assert_eq!(english.quit, "Quit Shift");
assert_eq!(english.capture, "Capture area");
assert_eq!(english.ocr, "OCR");
// Chinese is the only other language, so anything else means English.
assert_eq!(tray_titles("de").open, english.open);
}

View File

@ -56,7 +56,7 @@ fn inline(text: &str) -> String {
}
}
}
output.push_str("!");
output.push('!');
index += 1;
}
'[' => {
@ -301,6 +301,12 @@ pub fn to_html(markdown: &str) -> String {
}
flush_paragraph(&mut paragraph, &mut body);
page(&body)
}
/// Wraps an HTML body in the document every renderer path prints from, so a
/// Pandoc-produced body and a built-in Markdown body reach the page the same way.
pub fn page(body: &str) -> String {
format!(
"<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<style>\n{}\n</style>\n</head>\n<body>\n{}\n</body>\n</html>\n",
STYLE, body
@ -321,6 +327,7 @@ blockquote { margin: 0 0 12px; padding-left: 12px; border-left: 3px solid rgba(2
table { border-collapse: collapse; margin: 0 0 12px; }
th, td { border: 1px solid rgba(90, 60, 40, 0.25); padding: 6px 10px; text-align: left; }
th { background: rgba(120, 80, 55, 0.08); }
img { max-width: 100%; height: auto; }
hr { border: 0; border-top: 1px solid rgba(90, 60, 40, 0.2); margin: 18px 0; }
a { color: #c8541f; }
"#;

View File

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

View File

@ -84,6 +84,23 @@ pub fn document_page_images(
Ok(Some(images))
}
/// Whether the document body embeds at least one image.
///
/// Decides whether a DOCX can be handed to the native renderer, which drops
/// every inline drawing, or has to travel through a reader that keeps them.
pub fn contains_inline_images(input: &Path) -> Result<bool, String> {
let file = fs::File::open(input).map_err(|error| error.to_string())?;
let mut archive =
ZipArchive::new(file).map_err(|error| format!("Could not read document: {error}"))?;
let mut xml = String::new();
archive
.by_name("word/document.xml")
.map_err(|error| format!("Could not read document body: {error}"))?
.read_to_string(&mut xml)
.map_err(|error| error.to_string())?;
Ok(!document_body_summary(&xml)?.0.is_empty())
}
fn document_image_links(xml: &str) -> Result<std::collections::BTreeMap<String, String>, String> {
let mut reader = XmlReader::from_str(xml);
let mut links = std::collections::BTreeMap::new();
@ -437,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) {

View File

@ -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"),

View File

@ -23,6 +23,11 @@ const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;
/// would let a verbose child fill the pipe and block until the deadline.
const MAX_CAPTURED_OUTPUT: usize = 4 * 1024 * 1024;
/// Present in every message this module returns for a child that outlived its deadline.
/// A caller that must treat "never answered" differently from "answered no" matches on
/// this rather than on the whole sentence, whose seconds count varies.
pub const TIMEOUT_MARKER: &str = "did not finish within";
fn drain_output(mut reader: impl Read) -> Vec<u8> {
let mut captured = Vec::new();
let mut buffer = [0_u8; 8192];
@ -127,7 +132,7 @@ pub fn output_with_timeout(
let _ = child.kill();
let _ = child.wait();
break Err(format!(
"The command did not finish within {} seconds.",
"The command {TIMEOUT_MARKER} {} seconds.",
timeout.as_secs()
));
}
@ -166,6 +171,64 @@ pub fn status_with_timeout(
.ok_or_else(|| "The converter exited without a status.".to_string())
}
/// `output_with_timeout` for a long-running install. The installer's exit code is only
/// half the answer - `winget` says the things that matter ("already installed", "needs
/// administrator") in its output - so this captures both, keeps the console hidden, and
/// runs the child below the UI's priority the way `status_with_timeout` does.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub fn output_hidden_with_timeout(
program: impl AsRef<OsStr>,
args: &[&str],
timeout: Duration,
) -> Result<Output, String> {
let mut command = command(program);
background(&mut command);
command
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let deadline = Instant::now() + timeout;
let mut child = command
.spawn()
.map_err(|error| format!("Could not start the command: {error}"))?;
let stdout = child
.stdout
.take()
.map(|pipe| std::thread::spawn(move || drain_output(pipe)));
let stderr = child
.stderr
.take()
.map(|pipe| std::thread::spawn(move || drain_output(pipe)));
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() >= deadline => {
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"The command {TIMEOUT_MARKER} {} seconds.",
timeout.as_secs()
));
}
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
Err(error) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("Could not monitor the command: {error}"));
}
}
};
Ok(Output {
status,
stdout: stdout
.and_then(|reader| reader.join().ok())
.unwrap_or_default(),
stderr: stderr
.and_then(|reader| reader.join().ok())
.unwrap_or_default(),
})
}
fn status_with_args_and_timeout(
program: impl AsRef<OsStr>,
args: &[&str],
@ -190,7 +253,7 @@ fn status_with_args_and_timeout(
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"The conversion did not finish within {} seconds.",
"The conversion {TIMEOUT_MARKER} {} seconds.",
started.elapsed().as_secs()
));
}

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