Compare commits

..

No commits in common. "334082cd9b38afa7d2152fbbc756d90ee4b61a37" and "4ed236bd9ef76a4912da4d715991ff3ce0663c7e" have entirely different histories.

20 changed files with 50 additions and 489 deletions

View File

@ -121,7 +121,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. A DOCX with pictures goes through Pandoc → HTML first, because the AppKit reader drops images |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit renderer (macOS) · Pandoc elsewhere | macOS path needs no LaTeX or wkhtmltopdf |
| Document `docx` `rtf` `odt` `txt` `md` `html` | `DOCX` `RTF` `HTML` `TXT` `MD` | 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 |
@ -292,7 +292,7 @@ Each is overridable in Settings. File actions offer a *collect everything in one
## Updates
A new macOS machine installs **`Shift-macOS-universal.dmg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer. Double-click the image, drag `Shift.app` to /Applications, then allow the first launch once (right-click → Open, or 允许 in System Settings → Privacy & Security). In-app updates download the same image without a browser, so they never prompt. Details in `docs/RELEASE.md`.
A new macOS machine should install **`Shift-macOS-universal.pkg`**: builds are ad-hoc signed and not notarized, so Gatekeeper calls Shift an unidentified developer, and an installed package leaves the app free of the quarantine flag - it opens with no prompt. From the disk image, the first launch needs one approval (right-click → Open, or 允许 in System Settings → Privacy & Security). 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.

View File

@ -121,7 +121,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 会先经 Pandoc 转成 HTML,因为 AppKit 读取器会丢弃图片 |
| 文档 `docx` `rtf` `odt` `txt` `md` `html` | `PDF` | AppKit 渲染器(macOS)· 其他系统 Pandoc | macOS 路径不需要 LaTeX 或 wkhtmltopdf |
| 文档 `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` 直接解析 |
@ -294,7 +294,7 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供
## 软件更新
新的 macOS 机器请安装 **`Shift-macOS-universal.dmg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者。双击挂载镜像,把 `Shift.app` 拖进「应用程序」,然后允许首次启动一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。软件内升级自己下载的是同一个镜像、不经浏览器,因此不会弹窗。详见 `docs/RELEASE.md`。
新的 macOS 机器请安装 **`Shift-macOS-universal.pkg`**:本项目的构建采用 ad-hoc 签名且未做公证,Gatekeeper 会把 Shift 判为身份不明的开发者,而通过安装包安装不会把隔离属性带给应用,装好后打开不会再有提示。若改用磁盘镜像安装,首次打开需要允许一次(右键 → 打开,或在「系统设置 → 隐私与安全性」中点「允许」)。详见 `docs/RELEASE.md`。
更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。

View File

@ -1,89 +0,0 @@
Shift 0.1.4 - macOS 通用(universal)
本文件说明 macOS 安装包是怎么打出来的、在其它机器上会遇到什么,以及如何自己校验。
完整细节见仓库 docs/RELEASE.md 的「macOS packaging」。
关于这个安装包
--------------
Shift 的 macOS 产物只有一个:Shift-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-macOS-universal.dmg 挂载镜像。
2. 把 Shift.app 拖进「应用程序」(或任何你有权限的位置)。
3. 首次启动会被拦:「无法打开,因为来自身份不明的开发者」。点取消,然后
右键 Shift.app → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。
4. 只需允许一次,之后再打开正常。
macOS 权限
截图与录屏需要「屏幕录制」,输出目录需要「文件与文件夹」,带声音录屏需要
「麦克风」。Shift 会在打开截图遮罩前先检查屏幕录制权限,被拒绝时给的是可操作
的提示,而不是一张全黑截图。
注意:ad-hoc 构建每次的代码签名哈希都不同,而 macOS 把「屏幕录制」这类授权绑在
这个哈希上,所以一次升级后可能需要重新授权——这与手动重装是同一后果。要彻底消除
它,需要 Developer ID 证书加公证(见仓库 docs/ROADMAP.md 的 M5)。
软件内升级
设置 → 软件更新 里检查并安装: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
产物在 src-tauri/target/universal-apple-darwin/release/bundle/macos/ 下:Shift.app
与 Shift-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-macOS-universal.dmg
校验后仍打不开的话,请确认不是在压缩包预览窗口里运行的,并按上面的「新机器首次安装」
处理首次允许:右键 → 打开,或在「系统设置 → 隐私与安全性」中点「仍要打开」。

View File

@ -39,7 +39,8 @@ not a code limit, and it decides what the channel may contain:
| Key | Shipped | Notes |
| --- | --- | --- |
| `macos` | yes | One universal bundle, Apple silicon and Intel, shipped as a DMG. Verified on a fresh machine by dragging it to /Applications — see "macOS packaging" |
| `macos` | yes | One universal bundle, Apple silicon and Intel. The DMG, because that is what the in-app updater mounts |
| — | yes | `Shift-macOS-universal.pkg`, also macOS universal: the file to hand a machine installing Shift for the first time. It carries no manifest key — 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 |
| `linux` | no | Build target, not a product; see below |
@ -98,32 +99,32 @@ project wants, and no release is worse off for losing a certificate no other Mac
Reusing that identity again would mean installing it **and trusting it** on every machine,
which is not something to ask of a user.
So: ad-hoc, and one container. The channel ships **`Shift-macOS-universal.dmg`** and nothing
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.
So: ad-hoc, and the two containers each cover one job.
| Situation | What happens |
| Container | First launch on a fresh machine |
| --- | --- |
| 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**. |
| `.pkg`, via Installer.app or `installer` | `installer` does not propagate quarantine onto what it installs, so the app opens with **no prompt at all**. Verified: an installed copy carries `com.apple.provenance` and no `com.apple.quarantine`. The package itself is unsigned (`productsign` needs an *Installer Signing* certificate; a code-signing identity is rejected), so a browser-downloaded package may need right-click → 打开 once, before anything installs. `installer -pkg … -target /` needs nothing. |
| `.dmg`, app dragged to /Applications | The app keeps the browser's quarantine flag, so the first launch needs the one approval above. Shift's own downloader sets no quarantine flag, which is why **in-app updates never prompt** — only a browser download on a new machine does. |
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.
`scripts/macos-pkg.sh <Shift.app> <out.pkg>` builds the package: it stages the bundle under
an `/Applications` root and runs `pkgbuild`, which neither re-signs nor strips the payload —
the CDHash is identical in the built bundle, the DMG copy and the pkg copy.
`scripts/macos-pkg.sh` — which staged the bundle under an `/Applications` root and ran
`pkgbuild` — is kept in the tree but is no longer part of a release: it built a container
with no manifest key, and the DMG covers the first install anyway.
The `macos` manifest key stays a DMG on purpose: `update_install`'s handoff mounts the image
with `hdiutil` and copies the bundle out of it, so pointing the key at a `.pkg` would make
every in-app update fail to mount.
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 Screen Recording approval stops resetting between builds because the identity stops
changing.
`notarytool` + `stapler staple`. Then both containers open on double-click with no pane to
visit, and Screen Recording approval stops resetting between builds because the identity
stops changing.
## Publishing
```bash
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
scripts/macos-pkg.sh src-tauri/target/universal-apple-darwin/release/bundle/macos/Shift.app \
artifacts/Shift-macOS-universal.pkg # the first-install container
printf 'Fixes the ring on external displays.\n' > /tmp/notes.md
scripts/publish-release.sh --notes /tmp/notes.md # hash, commit, push
```
@ -144,17 +145,11 @@ same Python pass that walks the files produces both.
Recognised installers: `Shift-macOS-universal.dmg` (macOS), `Shift-Setup-<version>-win-x64.exe`
and `Shift-Setup-<version>-win-arm64.exe` (Windows, keys `windows` and `windows-arm64`),
`*.AppImage` / `*.deb` (Linux). Other files in `artifacts/` — the portable ZIPs,
`SHA256SUMS.txt`, the `README-Windows-<arch>.txt` notes and `README-macOS-universal.txt`,
the packaging note explaining the ad-hoc signature and how to verify a download — travel
with the branch and are downloadable from it, but are not offered as installers by the
manifest. Dotfiles and an old manifest are skipped.
`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.
`*.AppImage` / `*.deb` (Linux). Other files in `artifacts/` — the macOS `.pkg`, the portable
ZIPs, `SHA256SUMS.txt`, the `README-Windows-<arch>.txt` notes — travel with the branch and
are downloadable from it, but are not offered as installers by the manifest. The `.pkg`
carries no key on purpose: the `macos` key must stay a DMG so the in-app handoff can mount
it ("macOS packaging"). 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
@ -337,9 +332,8 @@ than trusting the local copy:
| `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 0.1.3 tree still carries the retired `Shift-macOS-universal.pkg`, because removing it
means re-publishing; it has no manifest key, so no client can be served it, and it is simply
not built any more ("macOS packaging"). macOS ships one artifact from the next publish on.
`Shift-macOS-universal.pkg` sits on the same branch with no manifest key, for first installs
("macOS packaging"); it was hashed the same way and downloaded back to check.
`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

View File

@ -108,13 +108,12 @@ names what is still missing.
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`. A Developer ID plus notarization removes the
prompt entirely and would also stop Screen Recording approval from resetting between
builds.
the user can approve. The channel also publishes `Shift-macOS-universal.pkg`, since
`installer` does not leave the installed copy quarantined and the app then opens with no
prompt at all. The `macos` manifest key stays a DMG so the in-app handoff can keep
mounting it; see "macOS packaging" in `docs/RELEASE.md`. A Developer ID plus notarization
removes the prompt entirely and would also stop Screen Recording approval from resetting
between builds.
- 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

View File

@ -189,45 +189,6 @@ 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
}
let printInfo = NSPrintInfo.shared.copy() as! NSPrintInfo
printInfo.paperSize = NSSize(width: 595.2, height: 841.8)
printInfo.topMargin = 42
@ -242,7 +203,6 @@ 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
@ -254,7 +214,7 @@ textView.textContainer?.containerSize = NSSize(
width: printable.width,
height: .greatestFiniteMagnitude
)
textView.textStorage?.setAttributedString(fitted)
textView.textStorage?.setAttributedString(attributed)
guard let layoutManager = textView.layoutManager,
let textContainer = textView.textContainer else {

View File

@ -1,7 +1,7 @@
{
"name": "shift",
"private": true,
"version": "0.1.4",
"version": "0.1.3",
"type": "module",
"scripts": {
"prepare:ocr": "bash scripts/prepare-ocr-assets.sh",

2
src-tauri/Cargo.lock generated
View File

@ -3899,7 +3899,7 @@ dependencies = [
[[package]]
name = "shift"
version = "0.1.4"
version = "0.1.3"
dependencies = [
"base64 0.22.1",
"calamine",

View File

@ -1,6 +1,6 @@
[package]
name = "shift"
version = "0.1.4"
version = "0.1.3"
description = "A radial file utility with screenshot, recording and OCR."
authors = ["Shift Contributors"]
edition = "2021"

View File

@ -962,28 +962,10 @@ fn native_document_pdf(
let extension = extension_of(input);
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
@ -1029,9 +1011,6 @@ fn native_document_pdf(
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());
@ -1039,34 +1018,6 @@ fn native_document_pdf(
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
@ -1220,13 +1171,6 @@ 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]);
}
@ -2488,170 +2432,6 @@ mod tests {
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() {
use lopdf::Object;
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 document = lopdf::Document::load(&output).unwrap();
let page_id = *document.get_pages().values().next().expect("a page");
let page = document.get_object(page_id).unwrap().as_dict().unwrap();
let media = page.get(b"MediaBox").unwrap().as_array().unwrap();
let coordinate = |index: usize| match &media[index] {
Object::Integer(value) => *value as f64,
Object::Real(value) => f64::from(*value),
other => panic!("MediaBox entry is {other:?}"),
};
let page_width = coordinate(2) - coordinate(0);
let mut widest: f64 = 0.0;
for object in document.objects.values() {
let Object::Stream(stream) = object else {
continue;
};
if stream
.dict
.get(b"Subtype")
.ok()
.and_then(|name| name.as_name().ok())
!= Some(b"Form")
{
continue;
}
let Ok(bbox) = stream.dict.get(b"BBox").and_then(|value| value.as_array()) else {
continue;
};
let edge = |index: usize| match &bbox[index] {
Object::Integer(value) => *value as f64,
Object::Real(value) => f64::from(*value),
_ => 0.0,
};
widest = widest.max(edge(2) - edge(0));
}
assert!(
widest > 1.0,
"no placed picture found in {}",
output.display()
);
assert!(
widest <= page_width,
"picture placed {widest}pt wide on a {page_width}pt page"
);
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 mut 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() {

View File

@ -301,12 +301,6 @@ 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
@ -327,7 +321,6 @@ 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

@ -84,23 +84,6 @@ 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();

View File

@ -178,7 +178,7 @@ fn document_pdf_component() -> RuntimeComponent {
"document-pdf",
"AppKit document renderer",
"documents",
"DOCX / RTF / ODT / TXT / MD / HTML -> PDF (a DOCX with pictures also needs Pandoc, which keeps the images)",
"DOCX / RTF / ODT / TXT / MD / HTML -> PDF",
"bundled",
true,
None,

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Shift",
"version": "0.1.4",
"version": "0.1.3",
"identifier": "app.nex.shift",
"build": {
"beforeDevCommand": "pnpm dev",

View File

@ -190,30 +190,20 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
<div className="update-actions">
{available && !verified ? (
<button
className="update-action is-commit"
onClick={() => void download()}
disabled={downloading}
>
{downloading ? <LoaderCircle size={13} className="spin" /> : <Download size={13} />}
<button className="runtime-install" onClick={() => void download()} disabled={downloading}>
{downloading ? <LoaderCircle size={12} className="spin" /> : <Download size={12} />}
{downloading ? t("updateDownloading") : t("updateDownload")}
</button>
) : null}
{verified ? (
<button
className="update-action is-commit"
onClick={() => void install()}
disabled={installing}
>
{installing ? <LoaderCircle size={13} className="spin" /> : <Check size={13} />}
<button className="runtime-install" onClick={() => void install()} disabled={installing}>
{installing ? <LoaderCircle size={12} className="spin" /> : <Check size={12} />}
{installing ? t("updateInstalling") : t("updateInstall")}
</button>
) : null}
{/* An install is a countdown to this process exiting, so the row drops the
choice that only resets what is already decided. */}
{verified && !installing ? (
<button className="update-action" onClick={() => void clear()}>
<X size={13} />
{verified ? (
<button className="settings-link" onClick={() => void clear()}>
<X size={12} />
{t("updateDiscard")}
</button>
) : null}

View File

@ -208,7 +208,7 @@ const messages: Record<Lang, Record<string, string>> = {
updateDownload: "Download & verify",
updateDownloading: "Downloading…",
updateInstall: "Install & relaunch",
updateInstalling: "Installing\u2026",
updateInstalling: "Installing\u2026 Shift restarts when it is done",
updateDiscard: "Discard",
updateVerified: "SHA256 matched the manifest.",
updateSigned: "Manifest signature verified against the release key.",
@ -477,7 +477,7 @@ const messages: Record<Lang, Record<string, string>> = {
updateDownload: "下载并校验",
updateDownloading: "下载中…",
updateInstall: "安装并重启",
updateInstalling: "正在安装…",
updateInstalling: "正在安装…完成后 Shift 会自动重启",
updateDiscard: "放弃",
updateVerified: "SHA256 与清单一致。",
updateSigned: "清单签名已用发布公钥验证通过。",

View File

@ -4578,59 +4578,10 @@ body[data-view="radial"] .share-backdrop {
.update-actions {
display: flex;
align-items: center;
gap: 8px;
gap: 10px;
margin-top: 12px;
}
/* The two ways an update can end. They sit in a panel whose own text is 12px, so
they are sized to that rather than to the Runtime tab's 8.5px rows they were
borrowed from, and both take the same box so the pair reads as a choice
instead of a button with a stray link beside it. */
.update-action {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 30px;
padding: 0 14px;
border: 1px solid rgba(91, 55, 35, 0.14);
border-radius: 9px;
color: #5f4437;
background: rgba(255, 255, 255, 0.72);
font-size: 12px;
font-weight: 640;
cursor: pointer;
transition:
border-color 0.16s ease,
background 0.16s ease,
box-shadow 0.16s ease;
}
.update-action:hover:not(:disabled) {
border-color: rgba(242, 106, 51, 0.26);
background: #fff;
box-shadow: 0 6px 14px rgba(96, 56, 33, 0.1);
}
.update-action:disabled {
cursor: default;
opacity: 0.72;
}
.update-action.is-commit {
border-color: transparent;
color: #fff8f2;
background: linear-gradient(135deg, #ff8248, #eb5427);
box-shadow: 0 6px 16px rgba(228, 83, 39, 0.24);
font-weight: 700;
}
.update-action.is-commit:hover:not(:disabled) {
border-color: transparent;
background: linear-gradient(135deg, #ff8e59, #f05c2b);
box-shadow: 0 8px 20px rgba(228, 83, 39, 0.3);
}
/* Capture result card: the four things a screenshot raises, one click each. */
.home-segment-after {
margin-top: 12px;