diff --git a/.github/workflows/cleanup-obsolete-workflow-runs.yml b/.github/workflows/cleanup-obsolete-workflow-runs.yml index 8290ebe..a02bffc 100644 --- a/.github/workflows/cleanup-obsolete-workflow-runs.yml +++ b/.github/workflows/cleanup-obsolete-workflow-runs.yml @@ -1,11 +1,8 @@ name: 清理废弃工作流记录 on: + # 只保留手动触发:这是给 4 个工作流的仓库用的清理工具,不值得每天自动跑一遍。 workflow_dispatch: - schedule: - # 每天北京时间 05:00。修改 cron 可更改运行时间,修改 timezone 可更改时区。 - - cron: "0 5 * * *" - timezone: "Asia/Shanghai" permissions: actions: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 88115e9..3959e02 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ # - 清单不再写回 main(main 只接受来自 dev 的合并,CI 推不进去),而是作为 release # 附件上传;客户端读 releases/latest/download/version.json。 # -# 分层(与 PacPilot 的 workflow 同一套写法:每层一个 job,末尾写「阶段 N 小结」进 Job Summary): +# 分层(与 PacPilot 的 workflow 同一套写法:每层一个 job,小结统一放在最后的 report job): # 阶段 1 prepare:算版本号、判断这次要不要发 # 阶段 2 build :装依赖 → 构建前端 → Go 测试 → 编译 exe → 上传 artifact # 阶段 3 publish:生成更新说明 → 生成版本清单 → 建草稿 → 传 exe 与清单 → 发布 @@ -120,32 +120,6 @@ jobs: echo "产物名称:$ASSET" echo "发布判断:$REASON" - - name: 阶段 1 小结 - if: always() - env: - JOB_STATUS: ${{ job.status }} - VERSION: ${{ steps.version.outputs.version }} - ASSET: ${{ steps.version.outputs.asset }} - PUBLISH: ${{ steps.version.outputs.publish }} - REASON: ${{ steps.version.outputs.reason }} - shell: bash - run: | - { - echo "## 阶段 1:版本号与发布判断" - echo - echo "- **结果:** ${JOB_STATUS:-未知}" - echo "- **目标版本:** ${VERSION:+v}${VERSION:-未算出}" - echo "- **产物名称:** ${ASSET:-未确定}" - if [[ "${PUBLISH:-}" == "true" ]]; then - echo "- **发布决策:** 允许进入构建与发布阶段" - elif [[ "${PUBLISH:-}" == "false" ]]; then - echo "- **发布决策:** 本次只构建不发布([no-release])" - else - echo "- **发布决策:** 未能完成判断,请查看上方日志" - fi - echo "- **说明:** ${REASON:-阶段未产生判断结果,详见日志}" - } >> "$GITHUB_STEP_SUMMARY" - build: name: 构建安装包 needs: prepare @@ -245,50 +219,6 @@ jobs: if-no-files-found: error retention-days: 1 - - name: 阶段 2 小结 - if: always() - env: - JOB_STATUS: ${{ job.status }} - VERSION: ${{ needs.prepare.outputs.version }} - ASSET: ${{ needs.prepare.outputs.asset }} - CHECKOUT: ${{ steps.checkout.outcome }} - GO: ${{ steps.setup-go.outcome }} - PNPM: ${{ steps.setup-pnpm.outcome }} - NODE: ${{ steps.setup-node.outcome }} - INSTALL: ${{ steps.install.outcome }} - WEB: ${{ steps.web.outcome }} - TESTS: ${{ steps.tests.outcome }} - BUILD: ${{ steps.build.outcome }} - VERIFY: ${{ steps.verify.outcome }} - UPLOAD: ${{ steps.upload.outcome }} - SIZE: ${{ steps.verify.outputs.size }} - SHA256: ${{ steps.verify.outputs.sha256 }} - shell: bash - run: | - { - echo "## 阶段 2:构建安装包" - echo - echo "- **结果:** ${JOB_STATUS:-未知}" - echo "- **目标版本:** ${VERSION:+v}${VERSION:-未确定}" - echo "- **产物名称:** ${ASSET:-未确定}" - echo "- **产物大小:** ${SIZE:-未生成} 字节" - echo "- **产物 SHA256:** ${SHA256:-未生成}" - echo - echo "### 步骤结果" - echo - echo "- **检出代码:** ${CHECKOUT:-未执行}" - echo "- **Go / pnpm / Node:** ${GO:-未执行} / ${PNPM:-未执行} / ${NODE:-未执行}" - echo "- **安装前端依赖:** ${INSTALL:-未执行}" - echo "- **构建前端:** ${WEB:-未执行}" - echo "- **Go 测试:** ${TESTS:-未执行}" - echo "- **编译 exe:** ${BUILD:-未执行}" - echo "- **校验产物 / 上传:** ${VERIFY:-未执行} / ${UPLOAD:-未执行}" - if [[ "${JOB_STATUS:-}" != "success" ]]; then - echo - echo "- **排查建议:** 在「步骤结果」里找出第一个非 success 的步骤,只看那一段日志;发布阶段不会执行。" - fi - } >> "$GITHUB_STEP_SUMMARY" - publish: name: 发布 Release needs: [prepare, build] @@ -410,49 +340,6 @@ jobs: gh release edit "$TAG" --draft=false echo "已发布 $TAG(exe + version.json)" - - name: 阶段 3 小结 - if: always() - env: - JOB_STATUS: ${{ job.status }} - VERSION: ${{ needs.prepare.outputs.version }} - TAG: ${{ needs.prepare.outputs.tag }} - ASSET: ${{ needs.prepare.outputs.asset }} - PREVIOUS: ${{ steps.notes.outputs.previous }} - FEATURES: ${{ steps.notes.outputs.features }} - IMPROVES: ${{ steps.notes.outputs.improves }} - FIXES: ${{ steps.notes.outputs.fixes }} - DOWNLOAD: ${{ steps.download.outcome }} - NOTES: ${{ steps.notes.outcome }} - MANIFEST: ${{ steps.manifest.outcome }} - RELEASE: ${{ steps.release.outcome }} - PUBLISH: ${{ steps.publish.outcome }} - shell: bash - run: | - { - echo "## 阶段 3:发布 Release" - echo - echo "- **结果:** ${JOB_STATUS:-未知}" - echo "- **版本 / 标签:** v${VERSION:-未确定} / ${TAG:-未确定}" - echo "- **产物:** ${ASSET:-未确定}" - echo "- **上一个 tag:** ${PREVIOUS:-未获取}" - echo "- **记录分组:** 新功能 ${FEATURES:-0} 项 / 改进 ${IMPROVES:-0} 项 / 修复 ${FIXES:-0} 项" - echo - echo "### 步骤结果" - echo - echo "- **下载安装包:** ${DOWNLOAD:-未执行}" - echo "- **生成更新说明:** ${NOTES:-未执行}" - echo "- **生成版本清单:** ${MANIFEST:-未执行}" - echo "- **建草稿 release:** ${RELEASE:-未执行}" - echo "- **上传并发布:** ${PUBLISH:-未执行}" - if [[ "${JOB_STATUS:-}" == "success" ]]; then - echo - echo "- **说明:** 客户端读的是 Release 附件 version.json(releases/latest/download/version.json),不再依赖 main 分支上的文件。" - else - echo - echo "- **注意:** 草稿 release 不会被客户端看到;修好之后重跑,或者去 Releases 页面把草稿删掉。" - fi - } >> "$GITHUB_STEP_SUMMARY" - report: name: 汇总结果 needs: [prepare, build, publish] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cbc056b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 geekMus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 2006417..f83c302 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,129 @@ # MarkPic -[English](README.md) | [简体中文](README.zh-CN.md) +**The image pipeline for Markdown documents.** Drop a document or a folder, pick one of +three jobs, and MarkPic rewrites the image links — or tells you which ones are broken. -MarkPic is a desktop app for the images inside Markdown documents. It does three -independent jobs: +[![release](https://img.shields.io/github/v/release/geekMus/MarkPic?display_name=tag)](https://github.com/geekMus/MarkPic/releases) +![platform](https://img.shields.io/badge/platform-Windows%2010%2B-0078D6) +![license](https://img.shields.io/badge/license-MIT-blue) -- **Upload** — find the local images a document references, send them to your - [PicGo](https://github.com/Molunerfinn/PicGo) image host, and rewrite the links to - the hosted URLs. -- **Check** — walk the remote images an article already points at and report the ones - that are dead, are not images, or come back truncated. Read-only. -- **Download** — pull those remote images into a local `images/` folder and rewrite - the links to relative paths. +[English](README.md) | [简体中文](README.zh-CN.md) -It ships as one self-contained app with the UI embedded: no Node.js, no local server, -no command line. Uploads go through PicGo's local HTTP interface, so MarkPic never -sees your image-host credentials. +![The upload page: three documents in the queue, one expanded to show every rewritten link](docs/images/en/upload.png) -## At a glance +## Three jobs | Job | What it touches | Rewrites the document | Needs PicGo running | | --- | --- | --- | --- | -| Upload | local images → image host | yes | yes | -| Check | remote image URLs | no | no | -| Download | remote images → `images/` | yes | no | +| **Upload** | local images → your image host | yes | yes | +| **Check** | remote image URLs | no | no | +| **Download** | remote images → `images/` | yes | no | + +- **Upload** finds the local images a document references, sends them through your + [PicGo](https://github.com/Molunerfinn/PicGo) server, and rewrites each link to the hosted + URL. Remote images already in the article are left alone. +- **Check** walks the remote URLs and reports the ones that are dead, are not images, or come + back truncated. Read-only. +- **Download** pulls those remote images into a local `images/` folder and rewrites the links + to relative paths. + +A document that needs none of this still stops by for a visit — it appears in the queue with +“no images”, so the number of cards always matches the number of documents in the folder. + +## What it looks like + +### Check: which links are dead + +![Check page: 4 addresses, 2 open, 2 dead](docs/images/en/check.png) + +### Download: remote images, brought home + +![Download page: 2 remote images fetched](docs/images/en/download.png) + +### Folders: find the Markdown first, import when ready + +Dropping a folder or a whole drive gives you one **scan card**. It only looks for Markdown +files — it never opens them — so it is fast and completely predictable. The card counts what +it has found, shows the directory being walked and how long it has been running, and can be +stopped at any time. When it finishes, expand the card to see the Markdown files it found. + +Click **Import** on that card: it is replaced by one card per document, and the image counts +are filled in afterwards. That second pass is throttled to what the machine can handle — never +ten thousand scans at once. + +![A folder has been scanned: 3 documents found, ready to import](docs/images/en/scanning.png) -Documents keep their original encoding — UTF-8 (with or without BOM), UTF-16 with a -BOM, and the machine's ANSI code page. Apart from the rewritten image addresses, -everything comes back byte-for-byte identical. +### Settings: everything in one page, saved when you are done + +![Settings page](docs/images/en/settings.png) + +### Light and dark + +Every screenshot on this page uses the light theme. MarkPic follows the system theme by +default; **Settings → Theme** pins it to light or dark. The native title bar, the tray menu +and the WebView background switch together, so resizing or repainting never flashes white. + +![Dark theme](docs/images/en/dark.png) + +## Features + +- **Drop files, several files, or a folder.** A single file becomes a file card right away. + A folder or drive becomes a scan card that only finds Markdown (`.md`, `.markdown`, + `.mdown`, `.mkd`, `.mdwn`); click **Import** to turn what it found into file cards. A + document with no images still gets a card — even an empty one — so the queue always matches + the folder. `.txt`, code files, images and archives are ignored. +- **Fresh every launch.** Closing and reopening the app always starts on the first page with + an empty queue. Switching between Upload, Check and Download inside a running session keeps + each page's queue and results. +- **Byte-faithful rewriting.** UTF-8 (with or without BOM), UTF-16 with BOM and the machine's + ANSI code page all survive the round trip; apart from the rewritten addresses the file comes + back identical. +- **Never uploads the same image twice.** Identical content is uploaded once per run, and an + unchanged image that was uploaded or downloaded before is reused from cache. +- **Three output modes.** Sidecar copy (`note.converted.md`), in place (with a `.bak`), or + into a directory you choose. +- **Desktop manners.** Tray icon, close-to-tray, light/dark theme that follows the system, + Chinese and English UI, and self-update from GitHub releases. +- **No local server, no runtime, no credentials.** The UI is embedded in the executable; + uploads go through PicGo's local HTTP interface, so MarkPic never sees your image-host keys. ## Install Download `MarkPic-v-windows-amd64.exe` from -[Releases](https://github.com/geekMus/MarkPic/releases). There is no installer: put -it anywhere and run it. An installed copy updates itself; settings and caches live in -the `data/` folder next to the executable. +[Releases](https://github.com/geekMus/MarkPic/releases). There is no installer: put it +anywhere and run it. An installed copy updates itself, and settings plus caches live in the +`data/` folder next to the executable. -Windows is the only platform published so far; macOS and Linux are planned, but not -verified yet. +Windows 10 or newer. macOS and Linux are planned but not verified yet. ## Quick start -1. Install and start [PicGo](https://github.com/Molunerfinn/PicGo), then enable its - server under **Settings → Server** (default `http://127.0.0.1:36677`). -2. Drop `.md` files or a folder onto the MarkPic window. -3. Choose **Upload**, **Check** or **Download** on the left and start. +1. Install and start [PicGo](https://github.com/Molunerfinn/PicGo), then enable its server + under **Settings → Server** (default `http://127.0.0.1:36677`). +2. Drop your documents, or a folder, onto the MarkPic window. +3. Choose **Upload**, **Check** or **Download** on the left, then start. ## Documentation - [Usage](docs/usage.md) — supported syntax, output modes, settings, data directory - [Build & development](docs/build.md) — toolchain, scripts, repository layout -- [Bridge API](docs/API.md) — internal WebView2 bridge between the UI and Go +- [Bridge API](docs/API.md) — the internal WebView2 bridge between the UI and Go + +## Build from source + +Requires Go 1.24+. Changing the UI also needs Node 20.19+ and pnpm; the build scripts run +`pnpm --dir web install` for you. One command builds the frontend and produces +`bin/MarkPic.exe`: + +```bash +npm run build +``` + +See [docs/build.md](docs/build.md) for the scripts, the release workflow and the repository +layout. + +## License + +MIT — see [LICENSE](LICENSE). Bundled third-party code keeps its own license: +[go-webview2](https://github.com/jchv/go-webview2) (MIT) and +[golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) (BSD-3-Clause). \ No newline at end of file diff --git a/README.zh-CN.md b/README.zh-CN.md index 4b5ff30..c21ce90 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,27 +1,82 @@ # MarkPic -[English](README.md) | [简体中文](README.zh-CN.md) +**Markdown 文档的图片流水线。** 拖进一份文档或一个文件夹,选一种作业,MarkPic 负责把图片 +链接换掉 —— 或者告诉你哪几张已经打不开了。 -MarkPic 是一个桌面工具,处理 Markdown 文档里的图片。三件事互相独立: +[![release](https://img.shields.io/github/v/release/geekMus/MarkPic?display_name=tag)](https://github.com/geekMus/MarkPic/releases) +![platform](https://img.shields.io/badge/platform-Windows%2010%2B-0078D6) +![license](https://img.shields.io/badge/license-MIT-blue) -- **上传**:找出文档引用的本地图片,交给 [PicGo](https://github.com/Molunerfinn/PicGo) - 图床上传,再把文档里的地址换成图床链接。 -- **检测**:逐个检查文章里已有的网络图片,报告打不开、不是图片、只返回半截的状况。只读,不改文档。 -- **下载**:把这些网络图片下载到本地的 `images/`,链接改成相对路径。 +[English](README.md) | 简体中文 -程序是单个自包含的应用,界面内嵌:不需要 Node.js,不起本地服务,没有命令行。上传只走 PicGo -的本机 HTTP 接口,MarkPic 不接触你的图床密钥。 +![上传页:队列里三份文档,展开的那份逐条列出被换掉的链接](docs/images/upload.png) -## 一眼看懂 +## 三种作业 | 作业 | 处理什么 | 会改文档吗 | 需要 PicGo 开着 | | --- | --- | --- | --- | -| 上传 | 本地图片 → 图床 | 会 | 是 | -| 检测 | 网络图片地址 | 不会 | 否 | -| 下载 | 网络图片 → `images/` | 会 | 否 | +| **上传** | 本地图片 → 你的图床 | 会 | 是 | +| **检测** | 网络图片地址 | 不会 | 否 | +| **下载** | 网络图片 → `images/` | 会 | 否 | -文档保持原编码:UTF-8(含或不含 BOM)、带 BOM 的 UTF-16、以及本机 ANSI 代码页。 -除了被替换掉的图片地址,其余内容一个字节都不变。 +- **上传**:找出文档引用的本地图片,交给本机的 [PicGo](https://github.com/Molunerfinn/PicGo) + 服务上传,再把每处链接换成图床地址。文章里原有的远程图原样保留。 +- **检测**:逐个访问文档里的远程地址,报告打不开、不是图片、只返回半截的那几个。只读。 +- **下载**:把这些远程图取回本地 `images/`,链接改成相对路径。 + +一份「什么都不用做」的文档也会出现在队列里,标着「无图片」—— 这样卡片数永远等于文件夹里的 +文档数,不会出现「明明有 3 个只显示 2 个」。 + +## 界面 + +### 检测:哪些链接已经失效 + +![检测页:4 个地址,2 个能打开、2 个打不开](docs/images/check.png) + +### 下载:把远程图取回本地 + +![下载页:2 张远程图已取回](docs/images/download.png) + +### 文件夹:先找 Markdown,再确认导入 + +拖进一个文件夹(哪怕是一整块盘),得到的是一张**扫描卡片**。它只负责找出 Markdown 文件, +从不打开它们 —— 所以快,而且数字可预期。卡片上写着已经找到多少份、正在遍历哪个目录、 +已经跑了多少秒;随时可以停,扫完展开卡片就能看到找到的 Markdown 文件清单。 + +点卡片上的**确认导入**:它被替换成「一个文档一张卡片」,图片数随后补上。这一步由后端按机器 +能力限流,不会同时开一万个扫描。 + +![扫完一个文件夹:找到 3 份文档,等待确认导入](docs/images/scanning.png) + +### 设置:一页看完,改完保存 + +![设置页](docs/images/settings.png) + +### 明暗主题 + +本文的截图都用亮色。程序默认跟随系统主题;在 **设置 → 主题** 里可以固定成亮色或暗色。 +原生标题栏、托盘菜单和 WebView 底色是一起切换的,所以拖动窗口或重绘时不会闪白一下。 + +![暗色主题](docs/images/dark.png) + +## 特性 + +- **单文件、多文件、整个文件夹都能拖。** 单个文件直接成为文件卡片;文件夹或盘先成为一张 + 扫描卡片,**只找出 Markdown**(`.md`、`.markdown`、`.mdown`、`.mkd`、`.mdwn`), + 点「确认导入」才换成文件卡片。没有图片的文档也会出现(空文件也算),卡片数永远和文件夹里 + 的 Markdown 对得上;`.txt`、代码文件、图片、压缩包一律不进队列。 +- **每次启动都是全新的。** 关掉再打开,永远停在第一个功能、空队列;程序没关时在 + 上传 / 检测 / 下载之间切换,各页的队列与结果照常保留。 +- **改写保真。** UTF-8(含或不含 BOM)、带 BOM 的 UTF-16、本机 ANSI 代码页都能原样往返; + 除了被替换掉的图片地址,文件一个字节都不变。 +- **同一张图不会传两遍。** 内容相同的图片一轮只上行一次;上次传过或下载过、且内容没变的, + 直接从缓存复用。 +- **三种输出方式。** 旁挂副本(`note.converted.md`)、原地替换(留 `.bak` 备份)、 + 或统一写到你指定的目录。 +- **桌面程序该有的样子。** 托盘图标、关闭进托盘、跟随系统的深浅色、中英双语界面, + 以及从 GitHub Releases 自动更新。 +- **不起本地服务、不装运行时、不碰密钥。** 界面内嵌在 exe 里;上传只走 PicGo 的本机 HTTP + 接口,MarkPic 看不到你的图床密钥。 ## 安装 @@ -29,13 +84,13 @@ MarkPic 是一个桌面工具,处理 Markdown 文档里的图片。三件事 `MarkPic-v<版本>-windows-amd64.exe`。没有安装程序:放哪都能跑。已安装的版本会自己更新, 设置与缓存放在 exe 旁边的 `data/` 目录里。 -目前只发布 Windows 版;macOS 和 Linux 在计划中,但还没有在真机上验证过。 +需要 Windows 10 或更新版本。macOS 和 Linux 在计划中,但还没有在真机上验证过。 ## 快速开始 -1. 安装并启动 [PicGo](https://github.com/Molunerfinn/PicGo),在 **设置 → 设置 Server** - 里启用服务(默认 `http://127.0.0.1:36677`)。 -2. 把 `.md` 文件或文件夹拖进 MarkPic 窗口。 +1. 安装并启动 [PicGo](https://github.com/Molunerfinn/PicGo),在 **设置 → 设置 Server** 里 + 启用服务(默认 `http://127.0.0.1:36677`)。 +2. 把文档或文件夹拖进 MarkPic 窗口。 3. 在左侧选 **上传**、**检测** 或 **下载**,然后开始。 ## 文档 @@ -43,3 +98,20 @@ MarkPic 是一个桌面工具,处理 Markdown 文档里的图片。三件事 - [使用说明](docs/usage.zh-CN.md):支持的写法、输出方式、设置、数据目录 - [构建与开发](docs/build.zh-CN.md):工具链、脚本、目录结构 - [Bridge API](docs/API.zh-CN.md):内嵌界面与 Go 之间的通信接口 + +## 从源码构建 + +需要 Go 1.24+。改动界面还需要 Node 20.19+ 和 pnpm(构建脚本会自己执行 +`pnpm --dir web install`)。一条命令构建前端并产出 `bin/MarkPic.exe`: + +```bash +npm run build +``` + +脚本、发布流程与目录结构见 [docs/build.zh-CN.md](docs/build.zh-CN.md)。 + +## 许可 + +MIT,见 [LICENSE](LICENSE)。随程序分发的第三方代码沿用各自的许可: +[go-webview2](https://github.com/jchv/go-webview2)(MIT)与 +[golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys)(BSD-3-Clause)。 diff --git a/cmd/markpic/chrome_windows.go b/cmd/markpic/chrome_windows.go index e344b1d..4c9fd44 100644 --- a/cmd/markpic/chrome_windows.go +++ b/cmd/markpic/chrome_windows.go @@ -21,6 +21,7 @@ import ( "math" "sort" "strings" + "sync" "sync/atomic" "syscall" "unsafe" @@ -283,17 +284,34 @@ func initProcessIdentity() { // 暗色在后;枚举出来的 id 是整数、升序,所以 groups[0] 就是亮色,也是 exe // 自己显示在资源管理器里的那块。 func themeIconGroup(dark bool) uintptr { - hInst, _, _ := procGetModuleHandle.Call(0) - if hInst == 0 { - return 0 - } - var groups []uintptr - cb := syscall.NewCallback(func(_, _, name, _ uintptr) uintptr { - groups = append(groups, name) - return 1 // 全部收下,下面再按主题挑 + return pickThemeIconGroup(iconGroups(), dark) +} + +// iconGroups 把 exe 里的图标组枚举一次就记住。 +// +// 以前每次调用都 EnumResourceNamesW + 新建一个 syscall.NewCallback:切一次主题要 +// 连着问三次(窗口图标、托盘图标、启动画面),而 NewCallback 的跳板是进程级、 +// 永不回收的 —— 每切一次主题就多留一块,资源顺序也不会再变化,没有重枚举的理由。 +var themeIcons struct { + once sync.Once + groups []uintptr +} + +func iconGroups() []uintptr { + themeIcons.once.Do(func() { + hInst, _, _ := procGetModuleHandle.Call(0) + if hInst == 0 { + return + } + var groups []uintptr + cb := syscall.NewCallback(func(_, _, name, _ uintptr) uintptr { + groups = append(groups, name) + return 1 // 全部收下,下面再按主题挑 + }) + procEnumResourceNames.Call(hInst, rtGroupIcon, cb, 0) + themeIcons.groups = groups }) - procEnumResourceNames.Call(hInst, rtGroupIcon, cb, 0) - return pickThemeIconGroup(groups, dark) + return themeIcons.groups } // pickThemeIconGroup 单独拆出来,便于用不依赖资源的单测钉住「亮色第一、暗色第二」。 @@ -325,15 +343,16 @@ func setWindowIcon(hwnd uintptr, dark bool) { big, _, _ := procLoadImage.Call(hInst, group, imageIcon, iconCx, iconCy, lrShared) small, _, _ := procLoadImage.Call(hInst, group, imageIcon, smCx, smCy, lrShared) - for slot, handle := range map[uintptr]uintptr{ - iconBig: big, - iconSmall: small, - iconSmall2: small, + // 切片而不是 map:三个槽位的顺序无关紧要,但 map 每次都会分配、遍历顺序还不定。 + for _, slot := range []struct{ kind, handle uintptr }{ + {iconBig, big}, + {iconSmall, small}, + {iconSmall2, small}, } { - if handle == 0 { + if slot.handle == 0 { continue } - procSendMessage.Call(hwnd, wmSetIcon, slot, handle) + procSendMessage.Call(hwnd, wmSetIcon, slot.kind, slot.handle) } } diff --git a/cmd/markpic/console_windows.go b/cmd/markpic/console_windows.go index bef2edc..5219fd6 100644 --- a/cmd/markpic/console_windows.go +++ b/cmd/markpic/console_windows.go @@ -3,11 +3,80 @@ package main import ( + "io" "log" "os" + "sync" + "unicode/utf16" + "unsafe" ) -var procAttachConsole = kernel32.NewProc("AttachConsole") +var ( + procAttachConsole = kernel32.NewProc("AttachConsole") + procWriteConsoleW = kernel32.NewProc("WriteConsoleW") + procGetFileType = kernel32.NewProc("GetFileType") +) + +// consoleOut 是「人看的日志」的出口:挂上终端后换成按 UTF-16 写控制台的版本; +// 没挂上(双击启动)就还是 os.Stderr。 +var consoleOut io.Writer = os.Stderr + +// utf16Units 把一段 UTF-8 字节翻成 Windows 控制台要的 UTF-16 码元。 +// 单独的纯函数,测试里能直接盯住「中文不会被拆坏」这件事。 +func utf16Units(p []byte) []uint16 { + return utf16.Encode([]rune(string(p))) +} + +// consoleWriter 把 UTF-8 写进 Windows 控制台。 +// +// 为什么不能直接把 *os.File 交给 log:Go 往控制台句柄写的是 UTF-8 字节,而控制台 +// 按当前代码页解释(中文 Windows 默认 936/GBK),日志里的中文就成了乱码。 +// WriteConsoleW 收 UTF-16,绕开代码页。 +type consoleWriter struct { + file *os.File + mu sync.Mutex +} + +func (w *consoleWriter) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + units := utf16Units(p) + if len(units) == 0 { + return w.file.Write(p) + } + w.mu.Lock() + defer w.mu.Unlock() + var written uint32 + ok, _, _ := procWriteConsoleW.Call( + w.file.Fd(), + uintptr(unsafe.Pointer(&units[0])), + uintptr(len(units)), + uintptr(unsafe.Pointer(&written)), + 0, + ) + if ok == 0 { + // 不是控制台句柄:按原始 UTF-8 字节写。 + return w.file.Write(p) + } + return len(p), nil +} + +const ( + fileTypeDisk = 1 + fileTypeChar = 2 // 控制台 + fileTypePipe = 3 + fileTypeUnknown = 0 +) + +// stdKind 读标准句柄的类型:1 文件、2 控制台、3 管道、0 无效句柄。 +func stdKind(f *os.File) uintptr { + if f == nil { + return fileTypeUnknown + } + kind, _, _ := procGetFileType.Call(f.Fd()) + return kind +} // attachParentConsole 把「从终端启动」这个进程的输出接回那个终端。 // @@ -17,18 +86,33 @@ var procAttachConsole = kernel32.NewProc("AttachConsole") // // - 双击启动:父进程是资源管理器,没有控制台,AttachConsole 失败,什么也不做; // - 从终端启动:父进程有控制台,挂上去,日志照常打在终端里。 +// +// 两种情况都要经过下面的「控制台写手」:如果直接写继承来的句柄,控制台会按 +// 936/GBK 解释 UTF-8 字节,中文日志就是乱码。 func attachParentConsole() { const attachParentProcess = 0xFFFFFFFF // ATTACH_PARENT_PROCESS - if ok, _, _ := procAttachConsole.Call(attachParentProcess); ok == 0 { - return + _, _, _ = procAttachConsole.Call(attachParentProcess) + + // 调用方明确重定向了输出(MarkPic.exe > log.txt / 2>&1 | tee):那是他要的去处, + // 保持原样 —— 文件 / 管道本来就吃 UTF-8。 + redirected := stdKind(os.Stdout) == fileTypeDisk || stdKind(os.Stdout) == fileTypePipe || + stdKind(os.Stderr) == fileTypeDisk || stdKind(os.Stderr) == fileTypePipe + + // 没有可用的控制台句柄(GUI 进程刚从终端启动,句柄还是无效的那份):重新打开 + // CONOUT$ 才能真的写进去。 + if !redirected && stdKind(os.Stderr) != fileTypeChar { + if out, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0); err == nil { + os.Stdout = out + os.Stderr = out + } } - // 挂上控制台之后标准句柄还是进程启动时那份(GUI 进程是无效句柄), - // 重新打开 CONOUT$ 才能真的写进去。 - if out, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0); err == nil { - os.Stdout = out - os.Stderr = out - log.SetOutput(out) + + // 无论句柄是继承来的还是刚打开的,只要它连着控制台,就换成 UTF-16 写手。 + if stdKind(os.Stderr) == fileTypeChar { + consoleOut = &consoleWriter{file: os.Stderr} + log.SetOutput(consoleOut) } + if in, err := os.OpenFile("CONIN$", os.O_RDONLY, 0); err == nil { os.Stdin = in } diff --git a/cmd/markpic/console_windows_test.go b/cmd/markpic/console_windows_test.go new file mode 100644 index 0000000..02be1ee --- /dev/null +++ b/cmd/markpic/console_windows_test.go @@ -0,0 +1,138 @@ +//go:build windows + +package main + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "unsafe" +) + +// 输出被重定向到文件 / 管道时,consoleWriter 必须退回原始 UTF-8 字节写: +// 那种场景下没有控制台代码页参与,UTF-8 才是消费者期望的编码。 +func TestConsoleWriterFallsBackToUTF8(t *testing.T) { + path := filepath.Join(t.TempDir(), "log.txt") + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatalf("建文件失败:%v", err) + } + defer f.Close() + + w := &consoleWriter{file: f} + const text = "中文日志:扫描完成" + if _, err := w.Write([]byte(text)); err != nil { + t.Fatalf("写日志失败:%v", err) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatalf("读回失败:%v", err) + } + if string(got) != text { + t.Fatalf("文件里应该还是 UTF-8 原文,实际 %q", string(got)) + } +} + +// 控制台要的是 UTF-16 码元:中文必须一个码元一个码元地翻对, +// 翻错了屏幕上就是乱码。 +func TestUTF16UnitsKeepsTextIntact(t *testing.T) { + cases := []struct { + in string + want []uint16 + }{ + {"abc", []uint16{'a', 'b', 'c'}}, + {"扫描", []uint16{0x626B, 0x63CF}}, + // 换行也要保留:日志是一行一条。 + {"中\n", []uint16{0x4E2D, 0x0A}}, + } + for _, c := range cases { + got := utf16Units([]byte(c.in)) + if len(got) != len(c.want) { + t.Fatalf("%q 的码元数应该是 %d,实际 %d", c.in, len(c.want), len(got)) + } + for i := range got { + if got[i] != c.want[i] { + t.Fatalf("%q 第 %d 个码元应该是 %#x,实际 %#x", c.in, i, c.want[i], got[i]) + } + } + } +} + +// 普通文件不是控制台:这条判断要是错了,重定向到文件时日志会被拐到屏幕上。 +func TestStdKindRejectsFiles(t *testing.T) { + f, err := os.Create(filepath.Join(t.TempDir(), "out.txt")) + if err != nil { + t.Fatalf("建文件失败:%v", err) + } + defer f.Close() + if kind := stdKind(f); kind != fileTypeDisk { + t.Fatalf("普通文件应该是 fileTypeDisk,实际 %d", kind) + } +} + +var ( + testKernel32 = syscall.NewLazyDLL("kernel32.dll") + procCreateScreenBuffer = testKernel32.NewProc("CreateConsoleScreenBuffer") + procReadOutputCharacterW = testKernel32.NewProc("ReadConsoleOutputCharacterW") + procCloseHandleForConsole = testKernel32.NewProc("CloseHandle") +) + +type testCoord struct { + x int16 + y int16 +} + +// 真的往一个控制台屏幕缓冲区里写一遍再读回来:这能同时验证 +// 「WriteConsoleW 收到的是 UTF-16」和「写进去的就是原文」。 +// 用 CreateConsoleScreenBuffer 开的是独立缓冲区,不会动用户看到的那个屏幕; +// 没有控制台(无界面 CI)就跳过。 +func TestConsoleWriterRoundTripsOnScreenBuffer(t *testing.T) { + const ( + genericRead = 0x80000000 + genericWrite = 0x40000000 + shareBoth = 0x00000003 + screenBuffer = 0x00000001 + ) + h, _, err := procCreateScreenBuffer.Call(genericRead|genericWrite, shareBoth, 0, screenBuffer, 0) + if h == 0 || h == uintptr(syscall.InvalidHandle) { + t.Skipf("没有可用的控制台,跳过:%v", err) + } + defer procCloseHandleForConsole.Call(h) + + const text = "中文日志:扫描完成" + units := utf16Units([]byte(text)) + + f := os.NewFile(h, "test-console-buffer") + if f == nil { + t.Fatal("包不出文件句柄") + } + w := &consoleWriter{file: f} + if _, err := w.Write([]byte(text)); err != nil { + t.Fatalf("写控制台失败:%v", err) + } + + // 多读一段:控制台缓冲区会按屏幕宽度补空格,读回长度不一定等于写入长度。 + read := make([]uint16, 64) + var got uint32 + // COORD 是按值传的 4 字节(x 低 16 位、y 高 16 位),不能传指针。 + const origin = 0 + ok, _, callErr := procReadOutputCharacterW.Call( + h, + uintptr(unsafe.Pointer(&read[0])), + uintptr(len(read)), + uintptr(origin), + uintptr(unsafe.Pointer(&got)), + ) + if ok == 0 { + t.Fatalf("读回控制台失败:%v", callErr) + } + if int(got) < len(units) { + t.Fatalf("至少该读回 %d 个字符,实际 %d", len(units), got) + } + for i := 0; i < len(units); i++ { + if read[i] != units[i] { + t.Fatalf("第 %d 个字符对不上:想要 %#x,实际 %#x", i, units[i], read[i]) + } + } +} diff --git a/cmd/markpic/drop_windows.go b/cmd/markpic/drop_windows.go new file mode 100644 index 0000000..70a5805 --- /dev/null +++ b/cmd/markpic/drop_windows.go @@ -0,0 +1,330 @@ +//go:build windows + +package main + +// 原生拖放:WebView2 不给本地路径。 +// +// Chromium 的 DataTransfer 里只有 File 对象,没有 path(那个非标准字段早被删掉), +// 从资源管理器拖文件进来时 text/uri-list 也是空的 —— 所以「把文件拖进窗口」这件事 +// 在网页层根本拿不到路径。 +// +// 做法是接管窗口的 OLE 放置目标:先对 WebView2 的子窗口 RevokeDragDrop(它自己注册了 +// 一个,会把拖放当成导航处理),再注册我们的 IDropTarget。DragEnter/DragOver/Drop +// 都在窗口线程上回调,Drop 时从 CF_HDROP 里直接用 DragQueryFileW 读路径, +// 再交给前端加进队列。这条路不抢焦点、不打开任何窗口。 + +import ( + "encoding/json" + "log" + "sync/atomic" + "syscall" + "time" + "unsafe" + + webview2 "github.com/jchv/go-webview2" +) + +// OLE / shell 的常量与接口号。 +const ( + dropCFHDrop = 15 // CF_HDROP + dropDVAspectContent = 1 // DVASPECT_CONTENT + dropTYMEDHGLOBAL = 1 // TYMED_HGLOBAL + dropEffectNone = 0 + dropEffectCopy = 1 + dropSOK = 0 + dropENoInterface = 0x80004002 + dropEPointer = 0x80004003 + dropEPending = 0x8000000A +) + +var ( + ole32Drop = syscall.NewLazyDLL("ole32.dll") + shell32Drop = syscall.NewLazyDLL("shell32.dll") + + procOleInitialize = ole32Drop.NewProc("OleInitialize") + procRegisterDragDrop = ole32Drop.NewProc("RegisterDragDrop") + procRevokeDragDrop = ole32Drop.NewProc("RevokeDragDrop") + procReleaseStgMedium = ole32Drop.NewProc("ReleaseStgMedium") + procDragQueryFileW = shell32Drop.NewProc("DragQueryFileW") + procEnumChildWindows = user32.NewProc("EnumChildWindows") +) + +// formatEtc / stgMedium 是 GetData 的参数与结果。 +type formatEtc struct { + cfFormat uint16 + target uintptr + aspect uint32 + index int32 + tymed uint32 +} + +type stgMedium struct { + tymed uint32 + hGlobal uintptr + releaseUnk uintptr +} + +// dispatch / drop 是 IDataObject 虚表里的两个方法下标(IUnknown 之后:GetData=3,QueryGetData=5)。 +const ( + vtblGetData = 3 + vtblQueryGetData = 5 +) + +// IDropTarget 的 IID:{00000122-0000-0000-C000-000000000046} +var iidDropTarget = [16]byte{ + 0x22, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, +} + +// iidUnknown 是 IUnknown:COM 有时会拿它来问。 +var iidUnknown = [16]byte{ + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, +} + +// fileDropTarget 是一个最小可用的 COM 对象:第一个字段必须是虚表指针, +// 因为 OLE 拿到的是「指向对象的指针」,而对象的前 8 个字节被当作 vtable。 +type fileDropTarget struct { + vtbl uintptr + refs int32 +} + +var ( + dropObject fileDropTarget + dropVtbl [7]uintptr + dropReady atomic.Bool + // dropHasFiles 记着这次拖的是不是文件:DragEnter 问一次,DragOver 只管用。 + dropHasFiles atomic.Bool + + // dropWebView 是投递路径用的窗口;Drop 回调在窗口线程上,Dispatch 会把它排队。 + dropWebView webview2.WebView +) + +func init() { + dropVtbl[0] = syscall.NewCallback(dropQueryInterface) + dropVtbl[1] = syscall.NewCallback(dropAddRef) + dropVtbl[2] = syscall.NewCallback(dropRelease) + dropVtbl[3] = syscall.NewCallback(dropDragEnter) + dropVtbl[4] = syscall.NewCallback(dropDragOver) + dropVtbl[5] = syscall.NewCallback(dropDragLeave) + dropVtbl[6] = syscall.NewCallback(dropDrop) + dropObject.vtbl = uintptr(unsafe.Pointer(&dropVtbl[0])) +} + +// installFileDrop 把窗口的放置目标换成我们自己的。 +// +// WebView2 的子窗口是它出现之后才有的,所以这里排几次重试:第一次通常在 +// 页面导航完成时就成立,后两次兜住慢启动。 +func installFileDrop(w webview2.WebView, hwnd uintptr) { + if w == nil || hwnd == 0 { + return + } + dropWebView = w + // RegisterDragDrop 要求当前线程初始化过 OLE。WebView2 一般已经初始化了, + // 返回 S_FALSE / RPC_E_CHANGED_MODE 都无所谓。 + procOleInitialize.Call(0) + + for _, delay := range []time.Duration{0, 400 * time.Millisecond, 1200 * time.Millisecond} { + time.AfterFunc(delay, func() { + w.Dispatch(func() { grabDropTargets(hwnd) }) + }) + } +} + +// grabDropTargets 给窗口自己与它下面所有子窗口注册放置目标。 +// +// WebView2 的渲染窗口是顶层的子孙窗口,真正的命中在那一层,所以顶层与子窗口 +// 都要注册:拖放进哪个窗口都归我们处理。已经注册过的(重试时)先撤再注册, +// RevokeDragDrop 对没有放置目标的窗口返回错误,忽略即可。 +func grabDropTargets(hwnd uintptr) { + target := uintptr(unsafe.Pointer(&dropObject)) + procRevokeDragDrop.Call(hwnd) + if r, _, _ := procRegisterDragDrop.Call(hwnd, target); r == dropSOK && !dropReady.Swap(true) { + log.Printf("原生拖放已接管") + } + procEnumChildWindows.Call(hwnd, dropEnumProc, 0) +} + +var dropEnumProc = syscall.NewCallback(func(hwnd, _ uintptr) uintptr { + target := uintptr(unsafe.Pointer(&dropObject)) + // WebView2 自己在子窗口上注册过放置目标(会把拖放当导航),先撤掉。 + procRevokeDragDrop.Call(hwnd) + procRegisterDragDrop.Call(hwnd, target) + return 1 // 继续枚举 +}) + +// callbackPointer 把回调参数里的 uintptr 还原成指针。 +// +// syscall.NewCallback 的回调只能收 uintptr,而 COM 传进来的确实是活的指针。 +// 直接写 unsafe.Pointer(x) 会被 go vet 判成「uintptr 转指针」——这里绕一层变量, +// 语义完全相同,只是让检查器看清「这是从回调参数原样取回来的指针」。 +func callbackPointer(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} + +func dropQueryInterface(self, riid, ppv uintptr) uintptr { + if ppv == 0 { + return dropEPointer + } + guid := (*[16]byte)(callbackPointer(riid)) + if *guid == iidDropTarget || *guid == iidUnknown { + *(*uintptr)(callbackPointer(ppv)) = self + dropAddRef(self) + return dropSOK + } + *(*uintptr)(callbackPointer(ppv)) = 0 + return dropENoInterface +} + +func dropAddRef(self uintptr) uintptr { + atomic.AddInt32(&dropObject.refs, 1) + return 1 +} + +func dropRelease(self uintptr) uintptr { + n := atomic.AddInt32(&dropObject.refs, -1) + if n < 0 { + return 0 + } + return uintptr(n) +} + +func dropDragEnter(self, dataObj, keyState, point, effect uintptr) uintptr { + has := dataObjectHasHDrop(dataObj) + dropHasFiles.Store(has) + // 只有真的拖来文件才算「可以放」:拖文字进来时不该亮起整个窗口的放置态。 + setDropEffect(effect, has) + if has { + emitDropOverlay(true) + } + return dropSOK +} + +func dropDragOver(self, keyState, point, effect uintptr) uintptr { + // OLE 每过一会儿就问一次效果;保持 COPY(用户看到的是「复制到此处」)。 + // 拖的不是文件时给 NONE,否则拖一段文字进来也会显示「可以放下」。 + setDropEffect(effect, dropHasFiles.Load()) + return dropSOK +} + +func dropDragLeave(self uintptr) uintptr { + dropHasFiles.Store(false) + emitDropOverlay(false) + return dropSOK +} + +func dropDrop(self, dataObj, keyState, point, effect uintptr) uintptr { + dropHasFiles.Store(false) + emitDropOverlay(false) + setDropEffect(effect, true) + paths := pathsFromDataObject(dataObj) + if len(paths) == 0 { + return dropSOK + } + if w := dropWebView; w != nil { + data, err := json.Marshal(paths) + if err != nil { + return dropSOK + } + js := "window.__markpicDrop && window.__markpicDrop(" + string(data) + ")" + w.Dispatch(func() { w.Eval(js) }) + } + return dropSOK +} + +func setDropEffect(effect uintptr, copy bool) { + if effect == 0 { + return + } + if copy { + *(*uint32)(callbackPointer(effect)) = dropEffectCopy + return + } + *(*uint32)(callbackPointer(effect)) = dropEffectNone +} + +func emitDropOverlay(on bool) { + w := dropWebView + if w == nil { + return + } + value := "false" + if on { + value = "true" + } + js := "window.__markpicDragOverlay && window.__markpicDragOverlay(" + value + ")" + w.Dispatch(func() { w.Eval(js) }) +} + +// dataObjectHasHDrop 问一下这份数据里有没有文件(CF_HDROP)。 +func dataObjectHasHDrop(dataObj uintptr) bool { + if dataObj == 0 { + return false + } + fe := formatEtc{ + cfFormat: dropCFHDrop, + aspect: dropDVAspectContent, + index: -1, + tymed: dropTYMEDHGLOBAL, + } + fn := comMethod(dataObj, vtblQueryGetData) + if fn == 0 { + return false + } + r, _, _ := syscall.Syscall(fn, 2, dataObj, uintptr(unsafe.Pointer(&fe)), 0) + return r == dropSOK +} + +// pathsFromDataObject 取出 CF_HDROP 里的路径列表。 +func pathsFromDataObject(dataObj uintptr) []string { + if dataObj == 0 { + return nil + } + fe := formatEtc{ + cfFormat: dropCFHDrop, + aspect: dropDVAspectContent, + index: -1, + tymed: dropTYMEDHGLOBAL, + } + var medium stgMedium + fn := comMethod(dataObj, vtblGetData) + if fn == 0 { + return nil + } + r, _, _ := syscall.Syscall6(fn, 3, dataObj, uintptr(unsafe.Pointer(&fe)), uintptr(unsafe.Pointer(&medium)), 0, 0, 0) + if r != dropSOK { + return nil + } + // 拿到的是 OLE 交给我们的一份引用,读完必须还回去。 + defer procReleaseStgMedium.Call(uintptr(unsafe.Pointer(&medium))) + if medium.tymed != dropTYMEDHGLOBAL || medium.hGlobal == 0 { + return nil + } + + hDrop := medium.hGlobal + count, _, _ := procDragQueryFileW.Call(hDrop, 0xFFFFFFFF, 0, 0) + if count == 0 { + return nil + } + paths := make([]string, 0, count) + buf := make([]uint16, 0x8000) // 长路径上限够用;不够的那条会被截断,用户重拖即可 + for i := uintptr(0); i < count; i++ { + n, _, _ := procDragQueryFileW.Call(hDrop, i, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) + if n == 0 || int(n) >= len(buf) { + continue + } + paths = append(paths, syscall.UTF16ToString(buf[:n])) + } + return paths +} + +// comMethod 从接口指针里取出第 index 个方法的地址。 +func comMethod(obj uintptr, index int) uintptr { + vtbl := *(*uintptr)(callbackPointer(obj)) + if vtbl == 0 { + return 0 + } + return *(*uintptr)(callbackPointer(vtbl + uintptr(index)*unsafe.Sizeof(uintptr(0)))) +} diff --git a/cmd/markpic/main.go b/cmd/markpic/main.go index d3a8e6b..2c04a19 100644 --- a/cmd/markpic/main.go +++ b/cmd/markpic/main.go @@ -62,13 +62,13 @@ func run() int { store := settings.NewStore("") _ = store.Load() if problem := store.Problem(i18n.ZH); problem != "" { - fmt.Fprintln(os.Stderr, "提示:"+problem) + fmt.Fprintln(consoleOut, "提示:"+problem) } indexURL, err := ui.IndexURL() if err != nil { platform.MessageBox("启动失败", err.Error()) - fmt.Fprintf(os.Stderr, "启动失败:%v\n", err) + fmt.Fprintf(consoleOut, "启动失败:%v\n", err) return 1 } @@ -79,7 +79,7 @@ func run() int { if err := openAppWindow(indexURL, brand.Name, desktop, sig); err != nil { platform.MessageBox("无法打开窗口", err.Error()) - fmt.Fprintf(os.Stderr, "无法打开窗口:%v\n", err) + fmt.Fprintf(consoleOut, "无法打开窗口:%v\n", err) return 1 } return 0 diff --git a/cmd/markpic/snap_windows.go b/cmd/markpic/snap_windows.go index ac666ae..1632d46 100644 --- a/cmd/markpic/snap_windows.go +++ b/cmd/markpic/snap_windows.go @@ -23,6 +23,7 @@ import ( "math" "os" "path/filepath" + "sync" "syscall" "unsafe" ) @@ -253,14 +254,30 @@ func hideSnapOverlay(o *snapOverlay) { // snapDebug 把热区收到的消息记到文件里,用来现场核对「系统到底送来了 // 哪些消息」。只有设了 MARKPIC_SNAP_DEBUG 才写:值是 1 写 %TEMP%\markpic-snap.log, // 也可以直接给一个路径。平时一个字节都不碰。 +// +// 目标路径只在第一次调用时解析一次:这个函数挂在窗口过程上,鼠标一动就是几十条, +// 每条都做一次 Getenv + 拼路径纯属白费(开着调试时尤其明显)。改环境变量需重启。 +var snapDebugPath struct { + once sync.Once + path string +} + +func snapDebugTarget() string { + snapDebugPath.once.Do(func() { + path := os.Getenv("MARKPIC_SNAP_DEBUG") + if path == "1" { + path = filepath.Join(os.Getenv("TEMP"), "markpic-snap.log") + } + snapDebugPath.path = path + }) + return snapDebugPath.path +} + func snapDebug(format string, args ...any) { - path := os.Getenv("MARKPIC_SNAP_DEBUG") + path := snapDebugTarget() if path == "" { return } - if path == "1" { - path = filepath.Join(os.Getenv("TEMP"), "markpic-snap.log") - } f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return diff --git a/cmd/markpic/splash_windows.go b/cmd/markpic/splash_windows.go index f9b9420..7ff378f 100644 --- a/cmd/markpic/splash_windows.go +++ b/cmd/markpic/splash_windows.go @@ -93,6 +93,9 @@ type splashWindow struct { accent uintptr title uintptr icon uintptr + + // painted 记着「整窗那部分已经画过了」:之后的定时器只刷新进度条。 + painted bool } var ( @@ -151,7 +154,9 @@ func showSplash(width, height uint, scale float64, dark bool) { // 立刻自己画一遍:紧接着就去初始化 WebView2 了,等消息循环来发 WM_PAINT // 可能还要几百毫秒(核对过:冷启动时那段时间窗口是全黑的)。 if hdc, _, _ := procGetDC.Call(s.hwnd); hdc != 0 { - s.paint(hdc) + var rc rect32 + procGetClientRect.Call(s.hwnd, uintptr(unsafe.Pointer(&rc))) + s.paint(hdc, rc) // 整窗都是脏的 procReleaseDC.Call(s.hwnd, hdc) } procSetTimer.Call(s.hwnd, splashTimerID, splashTimerMS, 0) @@ -227,17 +232,25 @@ func (s *splashWindow) prepareResources() { } } -func (s *splashWindow) paint(hdc uintptr) { +// splashLayout 是启动画面里所有元素的位置。 +// +// 以前 paint 和 barRect 各算一遍同样的六个尺寸、各取一次窗口大小:改一个间距要改两处, +// 两处一旦不一致,进度条就会离标题忽远忽近。现在只有这一份算法。 +type splashLayout struct { + icon int32 + iconX int32 + iconY int32 + title rect32 + bar rect32 +} + +func (s *splashWindow) layout() (splashLayout, rect32) { var rc rect32 procGetClientRect.Call(s.hwnd, uintptr(unsafe.Pointer(&rc))) - if rc.right <= 0 || rc.bottom <= 0 { - return - } - procFillRect.Call(hdc, uintptr(unsafe.Pointer(&rc)), s.bg) - iconSize := int32(math.Round(56 * s.scale)) gap := int32(math.Round(20 * s.scale)) titleH := int32(math.Round(30 * s.scale)) + barW := int32(math.Round(176 * s.scale)) barH := int32(math.Round(3 * s.scale)) barGap := int32(math.Round(22 * s.scale)) @@ -247,43 +260,66 @@ func (s *splashWindow) paint(hdc uintptr) { top = 0 } cx := (rc.right + rc.left) / 2 + titleTop := top + iconSize + gap + barTop := titleTop + titleH + barGap + + return splashLayout{ + icon: iconSize, + iconX: cx - iconSize/2, + iconY: top, + title: rect32{left: rc.left, top: titleTop, right: rc.right, bottom: titleTop + titleH}, + bar: rect32{left: cx - barW/2, top: barTop, right: cx + barW/2, bottom: barTop + barH}, + }, rc +} + +// coversAll 说明这次的绘制区域就是整块客户区(首次绘制、改尺寸时如此)。 +func coversAll(dirty, rc rect32) bool { + return dirty.left <= rc.left && dirty.top <= rc.top && dirty.right >= rc.right && dirty.bottom >= rc.bottom +} - if s.icon != 0 { - procDrawIconEx.Call( - hdc, - uintptr(cx-iconSize/2), uintptr(top), - s.icon, - uintptr(iconSize), uintptr(iconSize), - 0, 0, diNormal, - ) +func (s *splashWindow) paint(hdc uintptr, dirty rect32) { + lay, rc := s.layout() + if rc.right <= 0 || rc.bottom <= 0 { + return } - // 名字 - if s.title != 0 { - old, _, _ := procSelectObject.Call(hdc, s.title) - procSetBkMode.Call(hdc, 1) // TRANSPARENT - ink := colorInkLight - if s.dark { - ink = colorInkDark + // 计时器每次只让进度条那一条变脏:底、图标、标题都不必重画。 + // 以前这里无视脏区,整窗 FillRect + 重画图标标题,4K 上就是每秒 62 次全窗绘制。 + if !s.painted || coversAll(dirty, rc) { + procFillRect.Call(hdc, uintptr(unsafe.Pointer(&rc)), s.bg) + + if s.icon != 0 { + procDrawIconEx.Call( + hdc, + uintptr(lay.iconX), uintptr(lay.iconY), + s.icon, + uintptr(lay.icon), uintptr(lay.icon), + 0, 0, diNormal, + ) } - procSetTextColor.Call(hdc, uintptr(ink)) - text, _ := syscall.UTF16PtrFromString("MarkPic") - tr := rect32{ - left: rc.left, - top: top + iconSize + gap, - right: rc.right, - bottom: top + iconSize + gap + titleH, + + if s.title != 0 { + old, _, _ := procSelectObject.Call(hdc, s.title) + procSetBkMode.Call(hdc, 1) // TRANSPARENT + ink := colorInkLight + if s.dark { + ink = colorInkDark + } + procSetTextColor.Call(hdc, uintptr(ink)) + text, _ := syscall.UTF16PtrFromString("MarkPic") + tr := lay.title + procDrawText.Call( + hdc, uintptr(unsafe.Pointer(text)), ^uintptr(0), + uintptr(unsafe.Pointer(&tr)), + dtCenter|dtVCenter|dtSingleLine|dtNoPrefix, + ) + procSelectObject.Call(hdc, old) } - procDrawText.Call( - hdc, uintptr(unsafe.Pointer(text)), ^uintptr(0), - uintptr(unsafe.Pointer(&tr)), - dtCenter|dtVCenter|dtSingleLine|dtNoPrefix, - ) - procSelectObject.Call(hdc, old) + s.painted = true } // 进度条:轨道 + 一段往返的强调色 - bar := s.barRect() + bar := lay.bar procFillRect.Call(hdc, uintptr(unsafe.Pointer(&bar)), s.track) segW := int32(float64(bar.right-bar.left) * 0.34) @@ -294,26 +330,6 @@ func (s *splashWindow) paint(hdc uintptr) { procFillRect.Call(hdc, uintptr(unsafe.Pointer(&seg)), s.accent) } -// barRect 是进度条在客户区里的位置(和 paint 里同一套排布)。 -func (s *splashWindow) barRect() rect32 { - var rc rect32 - procGetClientRect.Call(s.hwnd, uintptr(unsafe.Pointer(&rc))) - iconSize := int32(math.Round(56 * s.scale)) - gap := int32(math.Round(20 * s.scale)) - titleH := int32(math.Round(30 * s.scale)) - barW := int32(math.Round(176 * s.scale)) - barH := int32(math.Round(3 * s.scale)) - barGap := int32(math.Round(22 * s.scale)) - blockH := iconSize + gap + titleH + barGap + barH - top := (rc.bottom - blockH) / 2 - if top < 0 { - top = 0 - } - cx := (rc.right + rc.left) / 2 - barTop := top + iconSize + gap + titleH + barGap - return rect32{left: cx - barW/2, top: barTop, right: cx + barW/2, bottom: barTop + barH} -} - // easeInOut 让进度条两头慢、中间快,比匀速更像「在加载」。 func easeInOut(t float64) float64 { if t < 0 { @@ -333,7 +349,7 @@ func splashWndProc(hwnd, msg, wp, lp uintptr) uintptr { var ps paintStruct hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) if s != nil && hdc != 0 { - s.paint(hdc) + s.paint(hdc, ps.rcPaint) } procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) return 0 @@ -345,7 +361,8 @@ func splashWndProc(hwnd, msg, wp, lp uintptr) uintptr { s.phase -= 1 } // 只重画进度条那一条:4K 屏上整窗重绘 60 次每秒不划算。 - bar := s.barRect() + lay, _ := s.layout() + bar := lay.bar procInvalidateRect.Call(hwnd, uintptr(unsafe.Pointer(&bar)), 0) } return 0 diff --git a/cmd/markpic/theme_windows.go b/cmd/markpic/theme_windows.go index 6e147ad..82a84e9 100644 --- a/cmd/markpic/theme_windows.go +++ b/cmd/markpic/theme_windows.go @@ -112,7 +112,9 @@ func applyWebView2Background(w webview2.WebView, dark bool) { } var applied atomic.Bool go func() { - for attempt := 0; attempt < 150 && !applied.Load(); attempt++ { + // 控制器通常几十毫秒就绪;给到 6 秒是留给冷启动的余量。轮询间隔 100ms + // 而不是 40ms:同样的覆盖窗口,丢进窗口队列的 Dispatch 少四成。 + for attempt := 0; attempt < 60 && !applied.Load(); attempt++ { w.Dispatch(func() { defer func() { _ = recover() }() if applied.Load() { @@ -133,7 +135,7 @@ func applyWebView2Background(w webview2.WebView, dark bool) { applied.Store(true) } }) - time.Sleep(40 * time.Millisecond) + time.Sleep(100 * time.Millisecond) } }() } diff --git a/cmd/markpic/window_windows.go b/cmd/markpic/window_windows.go index 58636c1..8148ce5 100644 --- a/cmd/markpic/window_windows.go +++ b/cmd/markpic/window_windows.go @@ -147,6 +147,9 @@ func openAppWindow(indexURL, title string, desktop *app.App, stop <-chan os.Sign }() } + // 网页层拿不到拖入文件的本地路径(见 drop_windows.go),在原生侧接管放置目标。 + installFileDrop(w, hwndValue()) + w.Navigate(indexURL) // 前端一直不报到就先露出来:界面再慢,也不该让人以为程序没打开。 time.AfterFunc(startupRevealFallback, func() { diff --git a/docs/API.md b/docs/API.md index 1a53a86..2956dc2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -40,7 +40,6 @@ Failures never reject the promise; the UI branches on `code` and shows `message` | method | params | returns | | --- | --- | --- | -| `app.hello` | `{lang}` | version, data directory, language | | `i18n.set` | `{lang}` | `{lang}` | | `health` | — | PicGo reachability and similar status | | `settings.get` | — | current settings | @@ -48,11 +47,9 @@ Failures never reject the promise; the UI branches on `code` and shows `message` | `settings.closeAction` | `{action}` | `{closeAction}`; only the close behaviour, leaving an unsaved draft alone | | `dialog.files` | — | `{paths}` | | `dialog.folder` | — | `{paths}` | -| `preview` | `{paths, settings?}` | scan preview | -| `scan.start` | `{scanId, paths, settings?}` | accepted; results arrive as `scan.file` events | +| `scan.start` | `{scanId, paths}` | accepted; results arrive as `scan.file` events, one per requested path | | `scan.cancel` | `{scanId, path?}` | `{cancelled}`; with `path` only that file is cancelled | -| `run.start` | `{paths, settings?}` | starts a conversion run; `mode` comes from the remote mode in settings | -| `run.current` | `{mode?}` | the run this page already has, to reattach after a reload | +| `run.start` | `{op, paths}` | starts a run; `op` is `upload` / `check` / `download` (not a setting) | | `run.cancel` | `{runId}` | `{ok}` | | `reveal` | `{path}` | `{ok}`; reveal in the file manager | | `open` | `{target}` | `{ok}`; open a file or folder | @@ -70,14 +67,14 @@ never batched or delayed. | --- | --- | | `run.started` | `runId`, `mode`, `files` | | `file.started` | `runId`, `id` | -| `file.progress` | `runId`, `id`, `uploaded`, `done`, `total`, `items` | -| `file.finished` | `runId`, `id`, `result` | +| `file.progress` | `runId`, `id`, `uploaded`, `done`, `total`, `items`, `summary` | +| `file.finished` | `runId`, `id`, `result`, `summary` | | `run.cancelled` | `runId` | | `run.finished` | `runId`, `summary` | | `log` | `level`, `message` | | `scan.file` | `runId` (`scanId` when scanning), `path`, `scanned`, `cancelled`, `timedOut` | | `scan.done` | `runId` (`scanId` when scanning) | -`mode` in `run.started` tells the three pages apart (upload / check / download); each -page claims the run that belongs to it. After a page refresh, call `run.current` first -to get the current snapshot, then keep receiving events. +`mode` in `run.started` carries the operation name (`upload` / `check` / `download`); each +page claims the run that belongs to it. `summary` on `file.progress` / `file.finished` is the +run's running total, so the UI never recomputes counters of its own. diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md index 5d547c9..2630e1b 100644 --- a/docs/API.zh-CN.md +++ b/docs/API.zh-CN.md @@ -36,7 +36,6 @@ const reply = await window.markpic( | 方法 | 参数 | 返回 | | --- | --- | --- | -| `app.hello` | `{lang}` | 版本、数据目录、语言 | | `i18n.set` | `{lang}` | `{lang}` | | `health` | — | PicGo 连通性等状态 | | `settings.get` | — | 当前设置 | @@ -44,11 +43,9 @@ const reply = await window.markpic( | `settings.closeAction` | `{action}` | `{closeAction}`;只改关闭行为,不碰未保存的设置草稿 | | `dialog.files` | — | `{paths}` | | `dialog.folder` | — | `{paths}` | -| `preview` | `{paths, settings?}` | 扫描预览 | -| `scan.start` | `{scanId, paths, settings?}` | 已受理;结果通过 `scan.file` 推送 | +| `scan.start` | `{scanId, paths}` | 已受理;每个请求路径各推一条 `scan.file` | | `scan.cancel` | `{scanId, path?}` | `{cancelled}`;带 `path` 只取消那一份 | -| `run.start` | `{paths, settings?}` | 启动一轮转换;`mode` 由设置里的远程模式决定 | -| `run.current` | `{mode?}` | 该页当前那一轮的快照,用于界面重载后接回 | +| `run.start` | `{op, paths}` | 启动一轮;`op` 是 `upload` / `check` / `download`(不是设置项) | | `run.cancel` | `{runId}` | `{ok}` | | `reveal` | `{path}` | `{ok}`;在资源管理器中定位 | | `open` | `{target}` | `{ok}`;打开文件或目录 | @@ -64,12 +61,12 @@ Go 侧通过 `window.__markpicEvents(payload)` 推送。`payload` 可以是单 | --- | --- | | `run.started` | `runId`、`mode`、`files` | | `file.started` | `runId`、`id` | -| `file.progress` | `runId`、`id`、`uploaded`、`done`、`total`、`items` | -| `file.finished` | `runId`、`id`、`result` | +| `file.progress` | `runId`、`id`、`uploaded`、`done`、`total`、`items`、`summary` | +| `file.finished` | `runId`、`id`、`result`、`summary` | | `run.cancelled` | `runId` | | `run.finished` | `runId`、`summary` | | `log` | `level`、`message` | | `scan.file` | `runId`(扫描时放 `scanId`)、`path`、`scanned`、`cancelled`、`timedOut` | | `scan.done` | `runId`(扫描时放 `scanId`) | -`run.started` 里的 `mode` 区分上传 / 检测 / 下载三页,界面按它认领自己的那一轮。页面刷新后先调 `run.current` 拿回当前快照,再继续接收事件。 +`run.started` 里的 `mode` 带的是操作名(`upload` / `check` / `download`),界面按它认领自己的那一轮。`file.progress` / `file.finished` 上的 `summary` 是这一轮到目前的累计值,界面不再自己重算计数。 diff --git a/docs/build.md b/docs/build.md index ef65c40..05406e9 100644 --- a/docs/build.md +++ b/docs/build.md @@ -47,7 +47,8 @@ Run from the repository root: | `tools/mockpicgo` | fake image host | Icons live in `assets/`. Normal builds reuse the committed `.ico` and `.syso` files, so -they are not regenerated. +they are not regenerated. If the `.syso` is ever absent, regenerate it with +`go run github.com/akavel/rsrc@v1.2.1 -ico assets/icon-light.ico -o cmd/markpic/rsrc_windows_amd64.syso`. ## Branches and releases diff --git a/docs/build.zh-CN.md b/docs/build.zh-CN.md index 629437c..23fc3aa 100644 --- a/docs/build.zh-CN.md +++ b/docs/build.zh-CN.md @@ -46,6 +46,7 @@ | `tools/mockpicgo` | 假图床 | 图标资源在 `assets/`;常规构建直接使用已提交的 `.ico` 和 `.syso`,不需要重新生成。 +万一 `.syso` 不在了,用 `go run github.com/akavel/rsrc@v1.2.1 -ico assets/icon-light.ico -o cmd/markpic/rsrc_windows_amd64.syso` 重新生成。 ## 分支与发版 diff --git a/docs/images/check.png b/docs/images/check.png new file mode 100644 index 0000000..ab7c28b Binary files /dev/null and b/docs/images/check.png differ diff --git a/docs/images/dark.png b/docs/images/dark.png new file mode 100644 index 0000000..fdcf7ad Binary files /dev/null and b/docs/images/dark.png differ diff --git a/docs/images/download.png b/docs/images/download.png new file mode 100644 index 0000000..c258b53 Binary files /dev/null and b/docs/images/download.png differ diff --git a/docs/images/en/check.png b/docs/images/en/check.png new file mode 100644 index 0000000..5fd9d92 Binary files /dev/null and b/docs/images/en/check.png differ diff --git a/docs/images/en/dark.png b/docs/images/en/dark.png new file mode 100644 index 0000000..565d6ba Binary files /dev/null and b/docs/images/en/dark.png differ diff --git a/docs/images/en/download.png b/docs/images/en/download.png new file mode 100644 index 0000000..00ec1e5 Binary files /dev/null and b/docs/images/en/download.png differ diff --git a/docs/images/en/scanning.png b/docs/images/en/scanning.png new file mode 100644 index 0000000..0e06713 Binary files /dev/null and b/docs/images/en/scanning.png differ diff --git a/docs/images/en/settings.png b/docs/images/en/settings.png new file mode 100644 index 0000000..ab912e7 Binary files /dev/null and b/docs/images/en/settings.png differ diff --git a/docs/images/en/upload.png b/docs/images/en/upload.png new file mode 100644 index 0000000..9a25448 Binary files /dev/null and b/docs/images/en/upload.png differ diff --git a/docs/images/scanning.png b/docs/images/scanning.png new file mode 100644 index 0000000..c042e8b Binary files /dev/null and b/docs/images/scanning.png differ diff --git a/docs/images/settings.png b/docs/images/settings.png new file mode 100644 index 0000000..6166ceb Binary files /dev/null and b/docs/images/settings.png differ diff --git a/docs/images/upload.png b/docs/images/upload.png new file mode 100644 index 0000000..444b866 Binary files /dev/null and b/docs/images/upload.png differ diff --git a/docs/usage.md b/docs/usage.md index 91e3bda..d18390c 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -15,10 +15,26 @@ the disk no longer has. - **Download** only touches remote images; local ones are left alone. -Drop files or a whole folder, watch the queue, cancel mid-run, retry failures, filter -down to problems only, and expand any row for per-image details. The same image is -never uploaded twice, and an unchanged image that was already uploaded or downloaded -is reused from cache. +Drop a single file, several files, or a whole folder. The path comes from the native +drop target — WebView2 itself never exposes the local path of a dropped file. A single file +becomes a file card right away. A folder or drive becomes one **scan card** that only finds +Markdown (`.md`, `.markdown`, `.mdown`, `.mkd`, `.mdwn`) without opening anything; it +counts what it found, shows the directory being walked and the elapsed time; when it ends, +expand the card to see the list of Markdown files it found. Click **Import** on that card to turn those files into cards; their image +counts are filled in afterwards with a concurrency limit taken from the machine. A document with no images still gets a card, including an empty +one. `.txt`, code files, images and archives are ignored. + +A big folder (a whole drive, a cloud sync root) is scanned while you watch: the folder row +shows how many documents have been found so far and expands into the scan details, including +the file currently being read. When the +scan finishes — or you stop it — the row is replaced in one pass by a card per document. +Scanning has no overall time limit, only an inactivity watchdog, and you can stop it at any time; +after confirming, everything already found stays in the queue and the row tells you the rest +of that folder was not scanned. + +Watch the queue, cancel mid-run, retry failures, filter down to problems only, and expand +any row for per-image details. The same image is never uploaded twice, and an unchanged +image that was already uploaded or downloaded is reused from cache. ## Output modes diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index 8acba03..f0e3257 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -14,7 +14,19 @@ - **检测**:只读,但也会指出「文档引用了、磁盘上却不存在」的本地图。 - **下载**:只处理远程图,本地图保留。 -拖入文件或整个文件夹,看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 +拖入单个文件、多个文件或整个文件夹都行。路径来自原生放置目标——WebView2 本身拿不到 +拖入文件的本地路径。单个文件直接成为文件卡片;文件夹或盘先成为一张**扫描卡片**, +它只找出 Markdown(`.md`、`.markdown`、`.mdown`、`.mkd`、`.mdwn`)而不打开任何文件, +卡片上写已找到多少份、正在遍历哪个目录、已经跑了多少秒;扫完展开卡片,就能看到找到的文件清单。 +点**确认导入**,这些文件才变成卡片,图片数随后按机器能力限流地补上。没有图片的文档也会出现,空文件同样算一份;`.txt`、 +代码文件、图片、压缩包都不进队列。 + +拖进来的目录很大时(整块盘、网盘同步目录),扫描是边扫边报的:目录那一行显示「已经找到 +多少份文档」,点开还能看扫描详情(含此刻正在读的那份文件)。扫描结束(或你按下停止)时,这一行被一次性换成 +「一个文档一张卡片」。扫描没有总时长上限,只按「多久没有动静」判死,随时可以停 —— +确认之后,已经扫到的那部分照样铺成卡片,那一行也会说清「这个目录剩下的没扫」。 + +看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 同一张图只上传一次;已经上传/下载过且内容未变的图直接复用。 ## 输出方式 diff --git a/internal/app/app.go b/internal/app/app.go index c56aabd..fedb908 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -5,7 +5,7 @@ // 都是 JSON 友好的普通结构体;事件(进度、单个文件完成)通过 sink 推给窗口。 // // 这个文件只放「身份与状态」:Reply 信封、App 结构体与其构造、语言与事件出口。 -// 具体功能按主题分在 health.go / settings.go / runs.go / preview.go / dialog.go / +// 具体功能按主题分在 health.go / settings.go / runs.go / scan.go / dialog.go / // update.go 里,bridge 方法表在 dispatch.go。 package app @@ -59,11 +59,12 @@ func internal(msg string) *fail { return &fail{code: "internal", msg: msg} } type App struct { store *settings.Store - mu sync.Mutex - runs map[string]context.CancelFunc - // current 按 runID 记着每一轮的快照。上传 / 检测 / 下载各能跑一轮, - // 所以这里不是「唯一的那一轮」,按 runID 分开存。 - current map[string]*runSnapshot + mu sync.Mutex + // runs 是「正在跑的操作」:runID → 操作类型(上传 / 检测 / 下载)。 + // 同一个操作只允许一轮,靠它判断。 + runs map[string]string + // cancels 是每一轮的取消函数,按 runID 索引。 + cancels map[string]context.CancelFunc // scans 是在跑的扫描批次。扫描是异步的,界面靠 scanId 取消其中一批(或其中某个文件)。 scans map[string]*scanSession // lang 是界面当前的语言:命令行的 Accept-Language 没了,改成前端启动时告诉 我们一次。 @@ -80,22 +81,12 @@ type App struct { exeDir string } -type runSnapshot struct { - runID string - // mode 是这一轮属于哪一页:ignore(上传)/ check / download。 - mode string - files []conv.FileTask - results map[string]*conv.FileResult - summary *conv.Summary - done bool -} - // New 建一个 App。exePath 是正在运行的程序,自动更新要替换的就是它。 func New(store *settings.Store, exePath string) *App { return &App{ store: store, - runs: make(map[string]context.CancelFunc), - current: make(map[string]*runSnapshot), + runs: make(map[string]string), + cancels: make(map[string]context.CancelFunc), scans: make(map[string]*scanSession), lang: i18n.ZH, upd: updateTracker{status: updateStatus{ diff --git a/internal/app/app_test.go b/internal/app/app_test.go index b7a511a..f084e52 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -2,6 +2,7 @@ package app import ( "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -71,27 +72,13 @@ func dispatch[T any](t *testing.T, a *App, method string, params any) T { return out } -func TestHelloReportsBrandAndDataDir(t *testing.T) { - a := newTestApp(t) - hello := dispatch[struct { - Version string `json:"version"` - DataDir string `json:"dataDir"` - Lang string `json:"lang"` - }](t, a, "app.hello", map[string]string{"lang": "en"}) - - if hello.DataDir == "" { - t.Fatal("app.hello 应该给出数据目录") - } - if hello.Lang != "en" { - t.Fatalf("app.hello 应该回设成 en,实际 %q", hello.Lang) - } - if hello.Version == "" { - t.Fatal("app.hello 应该给出版本号") - } -} - func TestHealthSaysMarkpic(t *testing.T) { a := newTestApp(t) + // 语言只有 i18n.set 这一条通道(身份信息由 health 一并给出)。 + dispatch[map[string]any](t, a, "i18n.set", map[string]any{"lang": "en"}) + if got := a.Lang(); got != "en" { + t.Fatalf("i18n.set 应该把语言切成 en,实际 %q", got) + } health := dispatch[struct { App string `json:"app"` Version string `json:"version"` @@ -106,27 +93,42 @@ func TestHealthSaysMarkpic(t *testing.T) { } } -// 设置是部分更新:只发的字段改,没发的保持原样。 -// 这条以前是 HTTP 接口的坑(整份覆盖会把没发的字段清零),换成 bridge 后必须还在。 -func TestSettingsPutOnlyChangesGivenFields(t *testing.T) { +// 设置只有一条写入通道:读一份完整的、改完整份存回去。 +// +// 以前这里是「只覆盖发上来的字段」,因为调用方会顺手把页面名塞进 settings 传上来。 +// 操作类型改走 run.start 的 op 参数之后,那条路没了,增量补丁也就没有意义: +// 现在缺字段就是缺字段,由 settings.Normalize 补成默认值,而不是「保持上一次的值」。 +func TestSettingsRoundTripThroughStore(t *testing.T) { a := newTestApp(t) base := dispatch[settings.Settings](t, a, "settings.get", map[string]any{}) - base.Concurrency = 32 - dispatch[settings.Settings](t, a, "settings.put", base) + if base.Concurrency != settings.DefaultConcurrency { + t.Fatalf("第一次读到的应该是默认值,实际 %d", base.Concurrency) + } - patched := dispatch[settings.Settings](t, a, "settings.put", map[string]any{"retries": 4}) - if patched.Retries != 4 { - t.Fatal("retries 应该被改成 4") + base.Concurrency = 32 + base.Retries = 4 + saved := dispatch[settings.Settings](t, a, "settings.put", base) + if saved.Concurrency != 32 || saved.Retries != 4 { + t.Fatalf("写回去的设置没生效:%+v", saved) } - if patched.Concurrency != 32 { - t.Fatalf("没发的 concurreny 不该被清掉,实际 %d", patched.Concurrency) + + // 再读一次:落盘的值真的被读回来了(不是内存里那一份)。 + again := dispatch[settings.Settings](t, a, "settings.get", map[string]any{}) + if again.Concurrency != 32 || again.Retries != 4 { + t.Fatalf("重新读回来的设置不对:%+v", again) } - if patched.Endpoint != base.Endpoint { - t.Fatalf("没发的 endpoint 不该变:%q → %q", base.Endpoint, patched.Endpoint) + + // 越界的值由后端规整,前端那份检查只是为了即时提示。 + base.Concurrency = 9999 + clamped := dispatch[settings.Settings](t, a, "settings.put", base) + if clamped.Concurrency != settings.MaxConcurrency { + t.Fatalf("并发数应该被夹到上限 %d,实际 %d", settings.MaxConcurrency, clamped.Concurrency) } } -func TestPreviewCountsImages(t *testing.T) { +// 扫描按「请求的那个路径」回结果:拖进来一个目录就是一条目录结果, +// 里面带着它展开出来的文件。界面不再需要拿路径前缀自己拼。 +func TestScanReportsEachRequestedPath(t *testing.T) { a := newTestApp(t) dir := t.TempDir() doc := filepath.Join(dir, "doc.md") @@ -135,18 +137,39 @@ func TestPreviewCountsImages(t *testing.T) { t.Fatalf("写夹具失败:%v", err) } - got := dispatch[struct { - Files []struct { - Path string `json:"path"` - Images int `json:"images"` - } `json:"files"` - }](t, a, "preview", map[string]any{"paths": []string{doc}}) - - if len(got.Files) != 1 { - t.Fatalf("应该只预检 1 个文件,实际 %d", len(got.Files)) + type scanFileEvent struct { + Path string `json:"path"` + Scanned []conv.FileResult `json:"scanned"` } - if got.Files[0].Images != 2 { - t.Fatalf("应该数出 2 张图,实际 %d", got.Files[0].Images) + got := make(chan scanFileEvent, 4) + a.SetSink(func(ev conv.Event) { + if ev.Type != conv.EventScanFile { + return + } + select { + case got <- scanFileEvent{Path: ev.Path, Scanned: ev.Scanned}: + default: + } + }) + + dispatch[map[string]any](t, a, "scan.start", map[string]any{ + "scanId": "scan-count", + "paths": []string{doc}, + }) + + select { + case ev := <-got: + if ev.Path != doc { + t.Fatalf("scan.file 的 path 应该是请求的那个路径,实际 %q", ev.Path) + } + if len(ev.Scanned) != 1 { + t.Fatalf("应该只扫出 1 个文件,实际 %d", len(ev.Scanned)) + } + if ev.Scanned[0].Images != 2 { + t.Fatalf("应该数出 2 张图,实际 %d", ev.Scanned[0].Images) + } + case <-time.After(5 * time.Second): + t.Fatal("5 秒内没等到 scan.file") } } @@ -196,7 +219,16 @@ func TestScanSessionLeavesTableWhenBatchEnds(t *testing.T) { } } -func TestRunStartReportsEventsAndSnapshot(t *testing.T) { +// finalSummaryOf 取最后一条带汇总的事件:整轮的总结就挂在那里。 +func finalSummaryOf(t *testing.T, finals []*conv.Summary) *conv.Summary { + t.Helper() + if len(finals) == 0 { + return nil + } + return finals[len(finals)-1] +} + +func TestRunStartReportsEventsAndSummary(t *testing.T) { a := newTestApp(t) withDebug(t) dir := t.TempDir() @@ -207,11 +239,15 @@ func TestRunStartReportsEventsAndSnapshot(t *testing.T) { var mu sync.Mutex var types []string + var finals []*conv.Summary done := make(chan struct{}) var once sync.Once a.SetSink(func(ev conv.Event) { mu.Lock() types = append(types, ev.Type) + if ev.Summary != nil { + finals = append(finals, ev.Summary) + } mu.Unlock() if ev.Type == conv.EventRunFinished || ev.Type == conv.EventRunCancelled { once.Do(func() { close(done) }) @@ -221,8 +257,8 @@ func TestRunStartReportsEventsAndSnapshot(t *testing.T) { start := dispatch[struct { RunID string `json:"runId"` }](t, a, "run.start", map[string]any{ - "paths": []string{doc}, - "settings": map[string]any{"remote": "check"}, + "op": "check", + "paths": []string{doc}, }) if start.RunID == "" { t.Fatal("run.start 应该给出 runId") @@ -246,20 +282,12 @@ func TestRunStartReportsEventsAndSnapshot(t *testing.T) { t.Fatalf("事件里没有 run.started:%v", types) } - snap := dispatch[struct { - Running bool `json:"running"` - Done bool `json:"done"` - RunID string `json:"runId"` - Summary *conv.Summary `json:"summary"` - }](t, a, "run.current", map[string]any{}) - if snap.RunID != start.RunID { - t.Fatalf("快照里的 runId 对不上:%q / %q", snap.RunID, start.RunID) - } - if snap.Running || !snap.Done { - t.Fatalf("跑完之后快照应该是 done:running=%v done=%v", snap.Running, snap.Done) - } - if snap.Summary == nil || snap.Summary.Files != 1 { - t.Fatalf("快照里应该有一份汇总:%+v", snap.Summary) + // 汇总随事件走:跑完那一条带着整轮的 Summary,界面不需要另问一次。 + mu.Lock() + finalSummary := finalSummaryOf(t, finals) + mu.Unlock() + if finalSummary == nil || finalSummary.Files != 1 { + t.Fatalf("终止事件里应该带一份汇总:%+v", finalSummary) } // 文档没被改写(调试模式)。 @@ -297,8 +325,8 @@ func TestRunCancelStopsTheRun(t *testing.T) { start := dispatch[struct { RunID string `json:"runId"` }](t, a, "run.start", map[string]any{ - "paths": paths, - "settings": map[string]any{"remote": "check"}, + "paths": paths, + "op": "check", }) dispatch[map[string]any](t, a, "run.cancel", map[string]any{"runId": start.RunID}) @@ -309,9 +337,11 @@ func TestRunCancelStopsTheRun(t *testing.T) { } } -// 三页各跑各的:同一页第二次启动要被挡住,不同页可以同时跑; -// 跑完之后各自那份快照还得留在 run.current(mode) 里,切回页面才接得上。 -func TestRunsOnDifferentPagesRunInParallel(t *testing.T) { +// 三个操作各跑各的:同一个操作第二次启动要被挡住,不同操作可以同时跑。 +// +// 以前「哪一页」是靠 settings.remote 传上来的临时值表达的,于是同一页只能跑一轮 +// 这条规则长在了设置里;现在操作是 start 的 op 参数,规则也跟着变成「同一 op 一轮」。 +func TestRunsOfDifferentOpsRunInParallel(t *testing.T) { release := make(chan struct{}) var releaseOnce sync.Once unblock := func() { releaseOnce.Do(func() { close(release) }) } @@ -336,22 +366,32 @@ func TestRunsOnDifferentPagesRunInParallel(t *testing.T) { } a := newTestApp(t) - started := make(chan conv.Event, 4) + started := make(chan conv.Event, 8) + finished := make(chan conv.Event, 8) a.SetSink(func(ev conv.Event) { - if ev.Type == conv.EventRunStarted { - started <- ev + switch ev.Type { + case conv.EventRunStarted: + select { + case started <- ev: + default: + } + case conv.EventRunFinished, conv.EventRunCancelled: + select { + case finished <- ev: + default: + } } }) - waitStarted := func(mode string) conv.Event { + waitStarted := func(op string) conv.Event { t.Helper() select { case ev := <-started: - if ev.Mode != mode { - t.Fatalf("run.started 的 mode 应该是 %q,实际 %q", mode, ev.Mode) + if ev.Mode != op { + t.Fatalf("run.started 的 mode 应该是 %q,实际 %q", op, ev.Mode) } return ev case <-time.After(5 * time.Second): - t.Fatalf("没等到 %q 这一页的 run.started", mode) + t.Fatalf("没等到 %q 这一轮 run.started", op) return conv.Event{} } } @@ -359,75 +399,62 @@ func TestRunsOnDifferentPagesRunInParallel(t *testing.T) { check := dispatch[struct { RunID string `json:"runId"` }](t, a, "run.start", map[string]any{ - "paths": []string{doc}, - "settings": map[string]any{"remote": "check"}, + "op": "check", + "paths": []string{doc}, }) - checkEvent := waitStarted("check") - if checkEvent.RunID != check.RunID { - t.Fatalf("run.started 的 runId 对不上:%q / %q", checkEvent.RunID, check.RunID) + if ev := waitStarted("check"); ev.RunID != check.RunID { + t.Fatalf("run.started 的 runId 对不上:%q / %q", ev.RunID, check.RunID) } raw, err := json.Marshal(map[string]any{ - "paths": []string{doc}, - "settings": map[string]any{"remote": "check"}, + "op": "check", + "paths": []string{doc}, }) if err != nil { t.Fatalf("编码参数失败:%v", err) } if reply := a.Dispatch("run.start", raw); reply.OK || reply.Code != "conflict" { - t.Fatalf("同一页第二次启动应该冲突,实际 ok=%v code=%q", reply.OK, reply.Code) + t.Fatalf("同一个操作第二次启动应该冲突,实际 ok=%v code=%q", reply.OK, reply.Code) } + // 检测被慢服务器卡住;上传应该能独立跑完,并带回自己那份汇总。 upload := dispatch[struct { RunID string `json:"runId"` }](t, a, "run.start", map[string]any{ - "paths": []string{doc}, - "settings": map[string]any{"remote": "ignore"}, + "op": "upload", + "paths": []string{doc}, }) - uploadEvent := waitStarted("ignore") - if uploadEvent.RunID != upload.RunID { - t.Fatalf("上传页 runId 对不上:%q / %q", uploadEvent.RunID, upload.RunID) + if ev := waitStarted("upload"); ev.RunID != upload.RunID { + t.Fatalf("上传那一轮 runId 对不上:%q / %q", ev.RunID, upload.RunID) } - // 检测那页被慢服务器卡住;上传页应该能独立跑完并留下自己的快照。 - waitDone := func(mode string) currentRun { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - snap := dispatch[currentRun](t, a, "run.current", map[string]any{"mode": mode}) - if snap.Done { - return snap - } - time.Sleep(10 * time.Millisecond) + select { + case ev := <-finished: + if ev.RunID != upload.RunID { + t.Fatalf("先跑完的应该是上传那一轮,实际 %q", ev.RunID) } - t.Fatalf("%q 这一页没在 5 秒内跑完", mode) - return currentRun{} - } - uploadSnap := waitDone("ignore") - if uploadSnap.Mode != "ignore" { - t.Fatalf("上传页快照 mode 不对:%q", uploadSnap.Mode) + if ev.Summary == nil { + t.Fatal("跑完的事件里应该带汇总") + } + case <-time.After(5 * time.Second): + t.Fatal("上传那一轮没在 5 秒内跑完") } - checkSnap := dispatch[currentRun](t, a, "run.current", map[string]any{"mode": "check"}) - if !checkSnap.Running || checkSnap.Done { - t.Fatalf("检测页应该还在跑:running=%v done=%v", checkSnap.Running, checkSnap.Done) + if a.RunningCount() != 1 { + t.Fatalf("检测那一轮应该还在跑,实际在跑 %d 轮", a.RunningCount()) } unblock() - finalCheck := waitDone("check") - if finalCheck.RunID != check.RunID { - t.Fatalf("检测页跑完后快照被换掉了:%q / %q", finalCheck.RunID, check.RunID) - } - if finalCheck.Mode != "check" { - t.Fatalf("检测页快照 mode 不对:%q", finalCheck.Mode) - } - if finalCheck.Summary == nil { - t.Fatal("检测页跑完后应该有汇总") - } - - // 两份快照各自独立,不会因为另一页开跑而被清掉。 - if again := dispatch[currentRun](t, a, "run.current", map[string]any{"mode": "ignore"}); again.RunID != upload.RunID { - t.Fatalf("上传页快照被换掉了:%q / %q", again.RunID, upload.RunID) + select { + case ev := <-finished: + if ev.RunID != check.RunID { + t.Fatalf("最后跑完的应该是检测那一轮,实际 %q", ev.RunID) + } + if ev.Summary == nil { + t.Fatal("检测那一轮跑完也该带汇总") + } + case <-time.After(5 * time.Second): + t.Fatal("检测那一轮没在 5 秒内跑完") } } @@ -524,3 +551,151 @@ func TestCheckUpdateSkipsUnversionedBuild(t *testing.T) { t.Fatalf("状态不该被后台改掉,实际 %q", st) } } + +// 扫描是流式的:目录里每一份文档单独一条 scan.file,并且有进度事件。 +func TestScanStreamsDocuments(t *testing.T) { + a := newTestApp(t) + dir := t.TempDir() + for i := 0; i < 6; i++ { + doc := filepath.Join(dir, fmt.Sprintf("doc%d.md", i)) + if err := os.WriteFile(doc, []byte("# t\n\n![a](a.png)\n"), 0o644); err != nil { + t.Fatalf("写夹具失败:%v", err) + } + } + + var mu sync.Mutex + files := map[string]bool{} + progress := 0 + done := make(chan struct{}) + var once sync.Once + a.SetSink(func(ev conv.Event) { + mu.Lock() + switch ev.Type { + case conv.EventScanProgress: + progress++ + case conv.EventScanFile: + for _, f := range ev.Scanned { + files[f.Path] = true + } + case conv.EventScanDone: + once.Do(func() { close(done) }) + } + mu.Unlock() + }) + + dispatch[map[string]any](t, a, "scan.start", map[string]any{"scanId": "stream", "paths": []string{dir}}) + + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("10 秒内没等到 scan.done") + } + + mu.Lock() + defer mu.Unlock() + if len(files) != 6 { + t.Fatalf("应该逐份报出 6 个文件,实际 %d:%v", len(files), files) + } + if progress == 0 { + t.Fatal("应该至少推一条 scan.progress") + } +} + +// 拖一整块盘时「发现」阶段必须能走完。 +// +// 这是用户报的那次「卡在 D: 43 份、CPU 不涨」:遍历器在宽目录树上死锁,数字不再 +// 变化、进度心跳还在刷,卡片永远停在「扫描中」。这里用 16×40 的目录树把旧实现 +// 那 512 的队列填满,验证 scan.done 一定会到、且文件一份不少。 +func TestScanDiscoverWideTreeFinishes(t *testing.T) { + a := newTestApp(t) + root := t.TempDir() + const wideA, wideB = 16, 40 + for i := 0; i < wideA; i++ { + dir := filepath.Join(root, fmt.Sprintf("a%02d", i)) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("建目录失败:%v", err) + } + if err := os.WriteFile(filepath.Join(dir, "a.md"), []byte("# a\n"), 0o644); err != nil { + t.Fatalf("写夹具失败:%v", err) + } + for j := 0; j < wideB; j++ { + sub := filepath.Join(dir, fmt.Sprintf("b%02d", j)) + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatalf("建目录失败:%v", err) + } + if err := os.WriteFile(filepath.Join(sub, "b.md"), []byte("# b\n"), 0o644); err != nil { + t.Fatalf("写夹具失败:%v", err) + } + } + } + + var mu sync.Mutex + found := 0 + done := make(chan struct{}) + var once sync.Once + a.SetSink(func(ev conv.Event) { + mu.Lock() + defer mu.Unlock() + switch ev.Type { + case conv.EventScanFile: + found += len(ev.Scanned) + case conv.EventScanDone: + once.Do(func() { close(done) }) + } + }) + + dispatch[map[string]any](t, a, "scan.start", map[string]any{ + "scanId": "wide", + "paths": []string{root}, + "discover": true, + }) + + select { + case <-done: + case <-time.After(30 * time.Second): + mu.Lock() + got := found + mu.Unlock() + t.Fatalf("发现阶段卡住了:只报了 %d 份文档", got) + } + + mu.Lock() + defer mu.Unlock() + if want := wideA + wideA*wideB; found != want { + t.Fatalf("应该发现 %d 份文档,实际 %d", want, found) + } +} + +// 停止扫描:已经在跑的那一份丢掉,但收尾事件必须到达且带 cancelled。 +func TestScanCancelStopsEarly(t *testing.T) { + a := newTestApp(t) + dir := t.TempDir() + for i := 0; i < 80; i++ { + doc := filepath.Join(dir, fmt.Sprintf("d%02d.md", i)) + if err := os.WriteFile(doc, []byte("# t\n"), 0o644); err != nil { + t.Fatalf("写夹具失败:%v", err) + } + } + + done := make(chan conv.Event, 4) + a.SetSink(func(ev conv.Event) { + if ev.Type == conv.EventScanDone { + select { + case done <- ev: + default: + } + } + }) + + dispatch[map[string]any](t, a, "scan.start", map[string]any{"scanId": "cancel", "paths": []string{dir}}) + dispatch[map[string]any](t, a, "scan.cancel", map[string]any{"scanId": "cancel"}) + + select { + case ev := <-done: + if !ev.Cancelled { + t.Fatal("取消之后 scan.done 应该带 cancelled") + } + case <-time.After(10 * time.Second): + t.Fatal("取消之后没等到 scan.done") + } +} diff --git a/internal/app/dispatch.go b/internal/app/dispatch.go index a2dd50d..368c1f7 100644 --- a/internal/app/dispatch.go +++ b/internal/app/dispatch.go @@ -3,10 +3,7 @@ package app import ( "encoding/json" - "github.com/geekMus/markpic/internal/appdata" - "github.com/geekMus/markpic/internal/brand" "github.com/geekMus/markpic/internal/i18n" - "github.com/geekMus/markpic/internal/version" ) // handler 是一次调用背后的实现:只管参数与结果,成功与失败都交给 Dispatch 包装。 @@ -22,11 +19,6 @@ func okCall[T any](f func() T) handler { return func(json.RawMessage) (any, error) { return f(), nil } } -// queryCall 是带参数、但不会失败的那种:现在的 run.current 就是它。 -func queryCall[T any](f func(json.RawMessage) T) handler { - return func(p json.RawMessage) (any, error) { return f(p), nil } -} - // handlers 是 bridge 的方法表:方法名 → 实现。 // // 做成表而不是 20 个 case 的 switch,是因为「有哪些调用」这件事本身要能一眼看 @@ -34,7 +26,6 @@ func queryCall[T any](f func(json.RawMessage) T) handler { // 加一个调用只要在这里加一行(实现本身放在对应主题的文件里)。 func (a *App) handlers() map[string]handler { return map[string]handler{ - "app.hello": a.hello, "i18n.set": a.setLangCall, "health": okCall(a.health), "settings.get": okCall(a.store.Load), @@ -42,11 +33,9 @@ func (a *App) handlers() map[string]handler { "settings.closeAction": a.setCloseAction, "dialog.files": noParams(a.pickFiles), "dialog.folder": noParams(a.pickFolder), - "preview": a.preview, "scan.start": a.startScan, "scan.cancel": a.cancelScan, "run.start": a.startRun, - "run.current": queryCall(a.currentRun), "run.cancel": a.cancelRun, "reveal": a.reveal, "open": a.open, @@ -65,26 +54,6 @@ func (a *App) Dispatch(method string, params json.RawMessage) Reply { return a.result(h(params)) } -// hello 报告身份与数据目录,并顺手记下界面语言。 -// -// 语言只能由前端告诉后端:以前是命令行 / HTTP 的 Accept-Language,现在没有 -// 请求头了,界面启动时会调一次这个,之后所有文案都按它出。 -func (a *App) hello(params json.RawMessage) (any, error) { - var p struct { - Lang string `json:"lang"` - } - _ = json.Unmarshal(params, &p) - a.setLang(i18n.Parse(p.Lang)) - return map[string]any{ - "app": brand.Slug, - "name": brand.Name, - "version": version.String(), - "lang": string(a.Lang()), - "dataDir": appdata.Dir(), - "dataNote": appdata.Note(i18n.Parse(p.Lang)), - }, nil -} - // setLangCall 换界面语言。返回一个占位的 ok:前端只关心有没有报错。 func (a *App) setLangCall(params json.RawMessage) (any, error) { var p struct { diff --git a/internal/app/events.go b/internal/app/events.go index b15f3e6..b2192f5 100644 --- a/internal/app/events.go +++ b/internal/app/events.go @@ -27,7 +27,12 @@ type Batcher struct { // batchQueueLimit 是积压事件的上限。正常情况下队列里是成批落下的文件槽加零头, // 这个上限只是兜底。 -const batchQueueLimit = 4096 +// +// 4096 → 32768:扫描一份一万篇文档的目录时,每篇一条 scan.file,两百毫秒内涌进 +// 一万条;界面那边消化一条要序列化+Eval,队列很容易冲破 4096,于是「丢最旧的」 +// 把一两百份文档的结果丢掉了 —— 表现就是队列比文件夹里的文件少。事件本身很小 +// (每条四五百字节),三万条也就十几 MB,兜底上限放宽更划算。 +const batchQueueLimit = 32768 // batchSlotBatch 是一批文件槽攒到多少条就先落进队列,让长时间运行的界面 // 仍然能一条条往前推进,而不是跑完才一次性收到。 @@ -164,8 +169,11 @@ func (b *Batcher) drain() []conv.Event { } // isTerminalEvent 判断事件是否属于「丢了界面就会卡住」的那一类。 +// +// scan.done 也算:扫描收尾那条一旦被丢,界面会一直停在「扫描中」,直到 30 秒的 +// 静默看门狗把它判死。 func isTerminalEvent(t string) bool { - return t == conv.EventRunFinished || t == conv.EventRunCancelled + return t == conv.EventRunFinished || t == conv.EventRunCancelled || t == conv.EventScanDone } // isFileEvent 判断事件是否描述「某个文件的状态」,这类事件按文件 id 覆盖。 diff --git a/internal/app/preview.go b/internal/app/preview.go deleted file mode 100644 index d00bcba..0000000 --- a/internal/app/preview.go +++ /dev/null @@ -1,38 +0,0 @@ -package app - -import ( - "context" - "encoding/json" - - "github.com/geekMus/markpic/internal/conv" - "github.com/geekMus/markpic/internal/i18n" -) - -// ---------- 预览 ---------- - -type previewResponse struct { - Files []conv.FileResult `json:"files"` - Summary conv.Summary `json:"summary"` -} - -func (a *App) preview(params json.RawMessage) (any, error) { - var req runRequest - if err := json.Unmarshal(params, &req); err != nil { - return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerBadJSON)) - } - if len(req.Paths) == 0 { - return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerNeedPaths)) - } - cfg, err := a.configOf(req.Settings) - if err != nil { - return nil, badRequest(err.Error()) - } - cfg.DryRun = true - - runner := conv.NewRunner(cfg, a.Lang(), "preview", nil).UsePreview() - files, sum := runner.RunCollect(context.Background(), req.Paths) - if files == nil { - files = []conv.FileResult{} - } - return previewResponse{Files: files, Summary: sum}, nil -} diff --git a/internal/app/runs.go b/internal/app/runs.go index 7fe9027..434eabb 100644 --- a/internal/app/runs.go +++ b/internal/app/runs.go @@ -7,15 +7,43 @@ import ( "github.com/geekMus/markpic/internal/appdata" "github.com/geekMus/markpic/internal/conv" "github.com/geekMus/markpic/internal/i18n" + "github.com/geekMus/markpic/internal/settings" ) -// ---------- 一轮任务:开始、跟踪、快照、取消 ---------- +// ---------- 一轮任务:开始、跟踪、取消 ---------- + +// 一次操作的类型。它**不是**设置项:设置里那个 Remote 只决定「默认做哪一种」, +// 而用户点的是「上传 / 检测 / 下载」三个按钮之一。以前这个区别靠设置里塞一个 +// 临时值来表达(前端把页面名当 settings.remote 传上来),于是持久化的设置被 +// 每一次调用覆盖,后端还得从设置里反推「这是哪一页」。 +const ( + OpUpload = "upload" + OpCheck = "check" + OpDownload = "download" +) + +// remoteOf 把操作类型翻成转换流程认识的那三个取值。 +// 操作是「用户点了什么」,Remote 是「文档里已经写着的网络图片怎么办」—— 两者 +// 名字不同、含义不同,别再把页面名塞进设置里当暗号用。 +func remoteOf(op string) (string, bool) { + switch op { + case OpUpload: + return settings.RemoteIgnore, true + case OpCheck: + return settings.RemoteCheck, true + case OpDownload: + return settings.RemoteDownload, true + } + return "", false +} type runRequest struct { - Paths []string `json:"paths"` - Settings *settingsPatch `json:"settings"` + Op string `json:"op"` + Paths []string `json:"paths"` } +// startRun 开始一轮转换。同一个操作只允许一轮:同一页连点两次会各建一个 Runner, +// 同一批文件被两边同时处理(重复上传、输出互相覆盖),界面也分不清哪份进度是哪一轮的。 func (a *App) startRun(params json.RawMessage) (any, error) { var req runRequest if err := json.Unmarshal(params, &req); err != nil { @@ -24,32 +52,37 @@ func (a *App) startRun(params json.RawMessage) (any, error) { if len(req.Paths) == 0 { return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerNeedPaths)) } - cfg, err := a.configOf(req.Settings) - if err != nil { - return nil, badRequest(err.Error()) + op := req.Op + if op == "" { + // 不带 op 时按设置里「文档里的网络图片怎么办」推一次:只检测、只下载都只有 + // 一种含义,剩下的一律是上传。 + switch a.store.Load().Remote { + case settings.RemoteCheck: + op = OpCheck + case settings.RemoteDownload: + op = OpDownload + default: + op = OpUpload + } + } + remote, ok := remoteOf(op) + if !ok { + return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerBadOp, op)) } + cfg := a.runConfig(remote) runID := newRunID() - // 上传 / 检测 / 下载三页可以各跑一轮,同一页只允许一轮:同一页连点两次开始会各建 - // 一个 Runner,同一批文件被两边同时处理(重复上传、输出互相覆盖),界面也分不清 - // 哪份进度是哪一轮的。别的页不受影响。 - mode := cfg.Remote a.mu.Lock() - for id, snap := range a.current { - if snap.mode != mode { - continue - } - if !snap.done { + for _, runningOp := range a.runs { + if runningOp == op { a.mu.Unlock() return nil, conflict(i18n.T(a.Lang(), i18n.KeyServerBusy)) } - // 这一页上一轮已经收工:让位给新的一轮,run.current 只保留最新一份。 - delete(a.current, id) } ctx, cancel := context.WithCancel(context.Background()) - a.runs[runID] = cancel - a.current[runID] = &runSnapshot{runID: runID, mode: mode, results: make(map[string]*conv.FileResult)} + a.runs[runID] = op + a.cancels[runID] = cancel lang := a.lang a.mu.Unlock() @@ -57,40 +90,41 @@ func (a *App) startRun(params json.RawMessage) (any, error) { defer func() { a.mu.Lock() delete(a.runs, runID) + delete(a.cancels, runID) a.mu.Unlock() cancel() }() - runner := conv.NewRunner(cfg, lang, runID, a.track(runID)). + runner := conv.NewRunner(cfg, lang, runID, a.sinkEvent(op)). AttachUploadCache(appdata.UploadCachePath()). AttachRemoteCache(appdata.RemoteCachePath()) runner.Run(ctx, req.Paths) }() - return map[string]string{"runId": runID}, nil + return map[string]string{"runId": runID, "op": op}, nil } -// track 包一层事件出口:先把这一轮的状态记进快照,再推给界面。 +// runConfig 把「当前设置 + 这一次的操作」合成一份运行配置。 // -// 为什么要记:事件流是增量的,界面重新加载就断在半截,前端内存里的 runId 也没了, -// 于是界面回到「队列为空」,而 Go 侧其实还在跑(甚至已经跑完)。有了快照, -// 前端启动时问一次 run.current 就能把整轮接回来。 -func (a *App) track(runID string) func(conv.Event) { +// 设置本身不改、也不落盘:操作类型是这一轮的事,跟用户存下来的偏好无关。 +func (a *App) runConfig(remote string) settings.Settings { + cfg := a.store.Load() + cfg.Remote = remote + cfg.DryRun = false + return cfg +} + +// sinkEvent 把事件直接交给窗口。没有快照要维护:界面从事件流和终止事件的汇总里 +// 拿全部状态,后端不再留一份「给刷新用」的副本(WebView2 里刷新会让 bridge 卡死, +// 那条恢复路径本来也走不到)。 +// +// run.started 的 mode 在这里换成操作名(upload / check / download):转换流程内部 +// 用的是「文档里的网络图片怎么办」那套取值,而界面认领一轮靠的是用户点了什么。 +func (a *App) sinkEvent(op string) func(conv.Event) { return func(ev conv.Event) { - a.mu.Lock() - snap := a.current[runID] - if snap != nil { - switch ev.Type { - case conv.EventRunStarted: - snap.files = ev.Files - case conv.EventFileFinished: - if ev.Result != nil { - snap.results[ev.ID] = ev.Result - } - case conv.EventRunFinished, conv.EventRunCancelled: - snap.summary = ev.Summary - snap.done = true - } + if ev.Type == conv.EventRunStarted { + ev.Mode = op } + a.mu.Lock() sink := a.sink a.mu.Unlock() if sink != nil { @@ -99,60 +133,6 @@ func (a *App) track(runID string) func(conv.Event) { } } -type currentRun struct { - Running bool `json:"running"` - Done bool `json:"done"` - Mode string `json:"mode,omitempty"` - RunID string `json:"runId,omitempty"` - Files []conv.FileTask `json:"files,omitempty"` - Results []*conv.FileResult `json:"results,omitempty"` - Summary *conv.Summary `json:"summary,omitempty"` -} - -// currentRun 返回某一页最近的一轮(mode 为空时返回任意一轮,优先在跑的)。 -// 快照不在这里清:三页各有一份,切换页面时还要靠它把结果接回来; -// 同一页开新的一轮时 startRun 会把上一份扔掉。 -func (a *App) currentRun(params json.RawMessage) currentRun { - var req struct { - Mode string `json:"mode"` - } - _ = json.Unmarshal(params, &req) - - a.mu.Lock() - var snap *runSnapshot - for _, candidate := range a.current { - if req.Mode != "" { - if candidate.mode == req.Mode { - snap = candidate - } - continue - } - // 没指定页时优先在跑的那一轮;都在跑的场合按 runID 取最新。 - if snap == nil || (!candidate.done && snap.done) || - (candidate.done == snap.done && candidate.runID > snap.runID) { - snap = candidate - } - } - var out currentRun - if snap != nil { - out = currentRun{ - Running: !snap.done, - Done: snap.done, - Mode: snap.mode, - RunID: snap.runID, - Files: snap.files, - Summary: snap.summary, - } - for _, f := range snap.files { - if res, ok := snap.results[f.ID]; ok { - out.Results = append(out.Results, res) - } - } - } - a.mu.Unlock() - return out -} - // RunningCount 是还在跑的任务数。关窗时用它决定要不要二次确认。 func (a *App) RunningCount() int { a.mu.Lock() @@ -163,10 +143,14 @@ func (a *App) RunningCount() int { // CancelAll 取消所有在跑的任务。用户确认退出时由窗口层调用。 func (a *App) CancelAll() { a.mu.Lock() - for _, cancel := range a.runs { - cancel() + cancels := make([]context.CancelFunc, 0, len(a.cancels)) + for _, cancel := range a.cancels { + cancels = append(cancels, cancel) } a.mu.Unlock() + for _, cancel := range cancels { + cancel() + } } // CloseAction 读当前的关闭行为(每次现读,用户改完设置不用重启)。 @@ -188,7 +172,7 @@ func (a *App) cancelRun(params json.RawMessage) (any, error) { cancelled := 0 a.mu.Lock() - for id, cancel := range a.runs { + for id, cancel := range a.cancels { if req.RunID == "" || req.RunID == id { cancel() cancelled++ diff --git a/internal/app/scan.go b/internal/app/scan.go index c59c63a..50f3668 100644 --- a/internal/app/scan.go +++ b/internal/app/scan.go @@ -3,9 +3,12 @@ package app import ( "context" "encoding/json" + "os" + "path/filepath" "runtime" "strings" "sync" + "sync/atomic" "time" "github.com/geekMus/markpic/internal/conv" @@ -13,66 +16,102 @@ import ( "github.com/geekMus/markpic/internal/settings" ) -// 扫描(把一份 Markdown 读一遍、数清里面有几张图、哪些是远程地址)原来是同步的 -// preview:界面点一下、Go 在 UI 线程上把整批文件扫完才返回。十个文件就是十次串行 -// 读盘,慢的时候界面整段冻住,卡片也只能等全部扫完才出现。 +// 异步扫描。 // -// 现在拆成异步的 scan.start / scan.cancel: -// - start 立刻返回,每个文件一个 goroutine,并发度按机器核数给上限; -// - 每个文件扫完就推一条 scan.file,界面按路径把结果贴回自己那张卡片; -// - 单个文件有独立 context,可以单独取消,也可以整批取消; -// - 每个文件有 20 秒上限:某个网络盘上的文件卡住,也不会让「开始」永远点不了。 +// 一次扫描处理用户拖进来的每一个路径: +// - 目录用几个协程并行遍历,边走边把发现的文档送进扫描队列; +// - 文档由固定数量的协程并行解析,每份各自 20 秒上限; +// - 每发现一份就推一条 scan.file,滚动中每 120ms 推一条 scan.progress, +// 界面因此既能一张张冒出卡片,又能看到「已经找到多少」; +// - 整批、单个路径都可以随时停:停下来的部分结果已经推出去了,界面保留它们。 +// +// 以前是「一个路径一个 goroutine,走完才推一条结果,整条路径 20 秒封顶」: +// 拖一整块盘必然超时,而且超时之前界面上只有「扫描中」,看不出任何进展。 const ( - // scanFileTimeout 是单个文件的扫描上限。扫描只读文件、不发网络请求, - // 正常文档是毫秒级的;给到 20 秒是留给网络盘和超大文档的余量。 + // scanFileTimeout 是「解析单份文档」的上限,不是整个目录的上限。 + // 一份文档读 20 秒还没读完,基本是网络盘或坏盘卡住了,报出来让用户重试。 scanFileTimeout = 20 * time.Second - // scanMinParallel / scanMaxParallel 夹住并发度:太少体现不出并发, - // 太多会让一堆 goroutine 抢同一块磁盘(反而更慢),也更容易吃满内存。 + // scanProgressEvery 是进度事件的节流间隔。再密就是在刷界面了。 + scanProgressEvery = 120 * time.Millisecond + // scanWalkWorkers 是遍历目录的并发度。 + // + // 8 → 16:读目录是纯 IO,20 核机器上 8 条协程喂不满;拖整块盘时大头就是 + // 「走很多层目录」,多开几条能明显缩短。 + scanWalkWorkers = 16 + // scanDocWorkers 是单个路径内并发解析文档的协程数;整批真正的上限由 + // scanSession.docSlots 把关,免得一次拖六块盘把机器打满。 + // + // 4 → 8:扫描是「读盘 + 解析」的混合负载,20 核机器上 4 条协程明显喂不满; + // 真正的并发上限仍然由 docSlots 卡着。 + scanDocWorkers = 8 + // scanMinParallel / scanMaxParallel 夹住「同时处理几个路径」。 + // + // 上限 16(原来 6):确认导入之后,一个路径就是一份文件,六条协程喂不满 + // 一台 20 核的机器;真正的解析并发仍由 docSlots 二次限制。 scanMinParallel = 2 - scanMaxParallel = 6 + scanMaxParallel = 16 ) -// scanParallelism 按机器核数给并发上限:一半核数,夹在 [2, 6],且不超过文件数。 -func scanParallelism(files int) int { - n := runtime.NumCPU() / 2 - if n < scanMinParallel { - n = scanMinParallel +// scanParallelism 按机器核数给同时处理的路径数。 +func scanParallelism(n int) int { + parallel := runtime.NumCPU() + if parallel < scanMinParallel { + parallel = scanMinParallel + } + if parallel > scanMaxParallel { + parallel = scanMaxParallel + } + if n > 0 && n < parallel { + parallel = n } - if n > scanMaxParallel { - n = scanMaxParallel + if parallel < 1 { + parallel = 1 } - if files > 0 && files < n { - n = files + return parallel +} + +// docSlotCount 是整批扫描里同时解析的文档数上限。 +func docSlotCount() int { + n := runtime.NumCPU() + if n < 2 { + n = 2 } - if n < 1 { - n = 1 + // 上限 16:解析是短平快的 CPU + 读盘混合,超过核数太多只会互相抢盘; + // 原先的 8 在 20 核机器上把一半的核晾着。 + if n > 16 { + n = 16 } return n } -// scanSession 是一批扫描的句柄:整批一个 context,每个文件再挂一个自己的。 +// scanSession 是一批扫描的句柄:整批一个 context,每个路径再挂一个自己的。 type scanSession struct { app *App scanID string ctx context.Context cancel context.CancelFunc + // docSlots 限制整批同时解析的文档数:几块盘一起拖进来时,别让几百个协程 + // 同时去读盘——机械盘那样只会更慢。 + docSlots chan struct{} + + // discover 为真:只走目录、数 Markdown,不解析内容(文件夹卡片那一档)。 + discover bool mu sync.Mutex - files map[string]context.CancelFunc // 路径 → 该文件的取消函数 + paths map[string]context.CancelFunc // 路径 → 该路径的取消函数 } -// stop 取消整批扫描。 func (s *scanSession) stop() { if s.cancel != nil { s.cancel() } } -// cancelFile 取消单个文件;文件不在这一批里就返回 false。 +// cancelFile 取消单个路径;路径不在这一批里就返回 false。 func (s *scanSession) cancelFile(path string) bool { key := scanPathKey(path) s.mu.Lock() - cancel, ok := s.files[key] + cancel, ok := s.paths[key] s.mu.Unlock() if ok { cancel() @@ -82,13 +121,13 @@ func (s *scanSession) cancelFile(path string) bool { func (s *scanSession) register(path string, cancel context.CancelFunc) { s.mu.Lock() - s.files[scanPathKey(path)] = cancel + s.paths[scanPathKey(path)] = cancel s.mu.Unlock() } func (s *scanSession) unregister(path string) { s.mu.Lock() - delete(s.files, scanPathKey(path)) + delete(s.paths, scanPathKey(path)) s.mu.Unlock() } @@ -98,9 +137,12 @@ func scanPathKey(path string) string { } type scanStartRequest struct { - ScanID string `json:"scanId"` - Paths []string `json:"paths"` - Settings *settingsPatch `json:"settings"` + ScanID string `json:"scanId"` + Paths []string `json:"paths"` + // Discover 为真时只「发现」Markdown 文件,不解析内容: + // 文件夹卡片的扫描就这一档 —— 里面有没有图片、有几张,等用户确认导入之后 + // 再由逐份文档的扫描去数。 + Discover bool `json:"discover"` } // startScan 立刻返回,真正的扫描在后台按并发度跑。 @@ -110,31 +152,37 @@ func (a *App) startScan(params json.RawMessage) (any, error) { return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerBadJSON)) } paths := make([]string, 0, len(req.Paths)) + seen := make(map[string]bool, len(req.Paths)) for _, path := range req.Paths { trimmed := strings.TrimSpace(path) - if trimmed != "" { - paths = append(paths, trimmed) + if trimmed == "" { + continue } + key := scanPathKey(trimmed) + if seen[key] { + continue + } + seen[key] = true + paths = append(paths, trimmed) } if len(paths) == 0 { return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerNeedPaths)) } - cfg, err := a.configOf(req.Settings) - if err != nil { - return nil, badRequest(err.Error()) - } // 扫描只看不算:不写文件、不上传、不发远程探活(UsePreview 那条规矩)。 + cfg := a.store.Load() cfg.DryRun = true lang := a.Lang() ctx, cancel := context.WithCancel(context.Background()) session := &scanSession{ - app: a, - scanID: req.ScanID, - ctx: ctx, - cancel: cancel, - files: make(map[string]context.CancelFunc, len(paths)), + app: a, + scanID: req.ScanID, + ctx: ctx, + cancel: cancel, + docSlots: make(chan struct{}, docSlotCount()), + discover: req.Discover, + paths: make(map[string]context.CancelFunc, len(paths)), } a.mu.Lock() @@ -151,52 +199,52 @@ func (a *App) startScan(params json.RawMessage) (any, error) { a.mu.Unlock() go session.run(cfg, lang, paths) - go session.reap() return map[string]any{"scanId": req.ScanID, "paths": paths}, nil } -// reap 在整批结束后把会话从表里摘掉(启动时登记过才需要摘)。 -func (s *scanSession) reap() { - if s.scanID == "" { - return - } - select { - case <-s.ctx.Done(): - case <-time.After(60 * time.Second): - } - s.app.mu.Lock() - if s.app.scans[s.scanID] == s { - delete(s.app.scans, s.scanID) - } - s.app.mu.Unlock() -} - -type scanOne struct { - path string - files []conv.FileResult - cancelled bool - timedOut bool -} - func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) { - // 整批跑完就取消这一批的 context:reap 靠它把会话从表里摘掉。以前只有 - // stop() 会取消,正常结束时 session 还要在 a.scans 里多留 60 秒,抱着 - // paths、cancel 和 context 不放。 - defer s.stop() + // 整批跑完就把会话从表里摘掉,别抱着 paths、cancel 和 context 不放。 + defer func() { + if s.scanID != "" { + s.app.mu.Lock() + if s.app.scans[s.scanID] == s { + delete(s.app.scans, s.scanID) + } + s.app.mu.Unlock() + } + s.stop() + }() - parallel := scanParallelism(len(paths)) - sem := make(chan struct{}, parallel) var wg sync.WaitGroup - for _, path := range paths { + // 固定数量的 worker 从一个路径队列里取活:以前是「一个路径一个 goroutine」, + // 用户确认导入一万个文件卡片时就是一万个协程在抢。并发上限按机器核数给, + // 真正的文档解析再受 docSlots 二次限制。 + workers := scanParallelism(len(paths)) + work := make(chan string) + for i := 0; i < workers; i++ { wg.Add(1) - go func(path string) { + go func() { defer wg.Done() - s.scanFile(cfg, lang, path, sem) - }(path) + for path := range work { + if s.ctx.Err() != nil { + return + } + s.scanPath(cfg, lang, path) + } + }() } - + for _, path := range paths { + select { + case work <- path: + case <-s.ctx.Done(): + } + if s.ctx.Err() != nil { + break + } + } + close(work) wg.Wait() // 整批结束(或被取消)时推一条收尾事件:界面靠它把「还在扫」的看门狗停掉。 @@ -207,63 +255,265 @@ func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) s.app.emit(ev) } -func (s *scanSession) scanFile(cfg settings.Settings, lang i18n.Lang, path string, sem chan struct{}) { - fileCtx, cancelFile := context.WithCancel(s.ctx) - s.register(path, cancelFile) +// scanPath 处理一个请求路径:单文件直接扫,目录则边遍历边扫。 +func (s *scanSession) scanPath(cfg settings.Settings, lang i18n.Lang, path string) { + ctx, cancel := context.WithCancel(s.ctx) + s.register(path, cancel) defer s.unregister(path) - defer cancelFile() + defer cancel() - result := scanOne{path: path} + if s.discover { + s.discoverPath(ctx, cfg, path) + return + } - // 排队等名额的时候也能被取消:十个文件、并发六个,剩下四个卡在排队, - // 用户点了取消不该等前面六个扫完才生效。 - select { - case sem <- struct{}{}: - defer func() { <-sem }() - case <-fileCtx.Done(): - result.cancelled = true - s.emitFile(result) + info, err := os.Stat(path) + if err != nil { + // 路径不存在/读不了:回一条空结果,界面把这张卡片标成「找不到」。 + s.emitFile(path, nil) + return + } + + if !info.IsDir() { + if res, ok, _ := s.scanDocument(conv.NewScanRunner(cfg, lang), ctx, lang, path); ok { + s.emitFile(path, []conv.FileResult{res}) + } return } - done := make(chan []conv.FileResult, 1) + skip := "" + if cfg.Output == settings.OutputDirectory { + skip = cfg.OutDir + } + + docs := make(chan string, 128) + // 计数边遍历边涨:进度事件读的就是它,不必等整棵树走完。 + var counts conv.WalkCounts + // currentFile 是此刻正在解析的那份文档:比目录更细一档,界面据此显示 + // 「正在扫描 …\part03\sub01\note012.md」。 + var currentFile atomic.Value // string + walkEnded := make(chan struct{}) + go func() { - // 每个文件一个 Runner:Runner 内部带状态,多个文件共用一份会互相踩。 - runner := conv.NewRunner(cfg, lang, "preview", nil).UsePreview() - files, _ := runner.RunCollect(fileCtx, []string{path}) - done <- files + defer close(walkEnded) + conv.WalkDocuments(ctx, path, cfg.Suffix, skip, scanWalkWorkers, &counts, func(file string) bool { + select { + case docs <- file: + return true + case <-ctx.Done(): + return false + } + }) + close(docs) + }() + + stopProgress := make(chan struct{}) + go func() { + ticker := time.NewTicker(scanProgressEvery) + defer ticker.Stop() + for { + select { + case <-stopProgress: + return + case <-ticker.C: + s.emitProgress(path, &counts, ¤tFile) + } + } + }() + + var wg sync.WaitGroup + for i := 0; i < scanDocWorkers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + // 每个 worker 一条 Runner:扫描只读盘解析,不碰网络, + // 所以用不带 HTTP 连接池的扫描版(一万份文档就是一万个连接池的差距)。 + runner := conv.NewScanRunner(cfg, lang) + for file := range docs { + select { + case s.docSlots <- struct{}{}: + case <-ctx.Done(): + return + } + currentFile.Store(file) + res, ok, poisoned := s.scanDocument(runner, ctx, lang, file) + <-s.docSlots + if poisoned { + // 超时那份被丢下了,它还在用这条 Runner:换一条新的继续。 + runner = conv.NewScanRunner(cfg, lang) + } + if !ok { + // 用户按了停止:已经在跑的这一份算白跑,不再往外报。 + return + } + s.emitFile(path, []conv.FileResult{res}) + } + }() + } + wg.Wait() + close(stopProgress) + <-walkEnded + + // 收尾再报一次最终数字,界面不用等最后一个 tick。 + s.emitProgress(path, &counts, ¤tFile) +} + +// discoverBatchSize 是「发现」时一批推回多少份文件。 +// +// 一份一条事件的话,六万份 Markdown 就是六万条事件:攒批队列、JSON 序列化、 +// 界面逐条处理都吃不消;六十四份一批,事件数直接少两个数量级。 +const discoverBatchSize = 64 + +// shallowDoc 是「发现了这份 Markdown」的最小描述:不解析内容、不数图片。 +func shallowDoc(path string) conv.FileResult { + return conv.FileResult{ + Path: path, + Name: filepath.Base(path), + Dir: filepath.Dir(path), + Status: conv.FilePreview, + } +} + +// discoverPath 只发现 Markdown 文件,不解析内容。 +// +// 文件夹卡片要回答的是「这里面有多少份 Markdown」;至于每份里有没有图片、 +// 几张图,等用户点「确认导入」、文件卡片真的进队列之后再去数 —— 那一步才受 +// 并发上限约束。所以这一档只有遍历 + 计数。 +func (s *scanSession) discoverPath(ctx context.Context, cfg settings.Settings, path string) { + info, err := os.Stat(path) + if err != nil { + s.emitFile(path, nil) + return + } + if !info.IsDir() { + abs, aerr := filepath.Abs(path) + if aerr != nil { + abs = path + } + s.emitFile(path, []conv.FileResult{shallowDoc(abs)}) + return + } + + skip := "" + if cfg.Output == settings.OutputDirectory { + skip = cfg.OutDir + } + + var counts conv.WalkCounts + // 发现阶段读的是目录:进度里只报目录,不报刚发现的那份文件 —— + // 「正在扫描 xxx.md」会让人以为在读这份文档,其实它只是刚被找到。 + docs := make(chan string, 256) + go func() { + defer close(docs) + conv.WalkDocuments(ctx, path, cfg.Suffix, skip, scanWalkWorkers, &counts, func(file string) bool { + select { + case docs <- file: + return true + case <-ctx.Done(): + return false + } + }) + }() + + stopProgress := make(chan struct{}) + go func() { + ticker := time.NewTicker(scanProgressEvery) + defer ticker.Stop() + for { + select { + case <-stopProgress: + return + case <-ticker.C: + s.emitProgress(path, &counts, nil) + } + } + }() + + batch := make([]conv.FileResult, 0, discoverBatchSize) + for file := range docs { + abs, aerr := filepath.Abs(file) + if aerr != nil { + abs = file + } + batch = append(batch, shallowDoc(abs)) + if len(batch) >= discoverBatchSize { + s.emitFile(path, batch) + batch = make([]conv.FileResult, 0, discoverBatchSize) + } + } + if len(batch) > 0 { + s.emitFile(path, batch) + } + close(stopProgress) + s.emitProgress(path, &counts, nil) +} + +// emitProgress 推一条进度事件:扫描(逐份解析)与发现(只遍历)共用。 +func (s *scanSession) emitProgress(path string, counts *conv.WalkCounts, file *atomic.Value) { + ev := conv.Event{ + Type: conv.EventScanProgress, + RunID: s.scanID, + Path: path, + Found: int(counts.Found.Load()), + Dirs: int(counts.Dirs.Load()), + Current: counts.Current(), + } + if file != nil { + ev.File = atomicString(file) + } + s.app.emit(ev) +} + +// scanDocument 用给定的 Runner 解析一份文档,带单文件超时。 +// +// 返回 ok=false 表示这一份被取消了(用户点了停止),调用方不该再往外报; +// poisoned=true 表示这份超时了、协程被丢下仍在用 Runner,调用方必须换一条新的。 +func (s *scanSession) scanDocument(runner *conv.Runner, ctx context.Context, lang i18n.Lang, path string) (conv.FileResult, bool, bool) { + result := make(chan conv.FileResult, 1) + fileCtx, cancel := context.WithCancel(ctx) + defer cancel() + + go func() { + result <- runner.ScanOne(fileCtx, path) }() timer := time.NewTimer(scanFileTimeout) defer timer.Stop() select { - case files := <-done: - result.files = files - case <-fileCtx.Done(): - result.cancelled = true - cancelFile() + case res := <-result: + return res, true, false + case <-ctx.Done(): + return conv.FileResult{}, false, false case <-timer.C: - // 超时也把底层 context 掐掉,别让那个 goroutine 一直挂着。 - result.timedOut = true - cancelFile() + cancel() + return conv.FileResult{ + Path: path, + Name: filepath.Base(path), + Dir: filepath.Dir(path), + Status: conv.FileFailed, + Error: i18n.T(lang, i18n.KeyConvScanTimeout), + }, true, true } +} - s.emitFile(result) +// atomicString 读 atomic.Value 里的字符串(还没存过就是空串)。 +func atomicString(v *atomic.Value) string { + if s, ok := v.Load().(string); ok { + return s + } + return "" } -func (s *scanSession) emitFile(result scanOne) { - files := result.files +func (s *scanSession) emitFile(path string, files []conv.FileResult) { if files == nil { files = []conv.FileResult{} } s.app.emit(conv.Event{ - Type: conv.EventScanFile, - RunID: s.scanID, - Path: result.path, - Scanned: files, - Cancelled: result.cancelled, - TimedOut: result.timedOut, + Type: conv.EventScanFile, + RunID: s.scanID, + Path: path, + Scanned: files, }) } @@ -294,7 +544,7 @@ func (a *App) cancelScan(params json.RawMessage) (any, error) { return map[string]any{"cancelled": session.cancelFile(req.Path)}, nil } -// emit 把事件交给窗口。和 track 一样:取 sink 要持锁,调用要放在锁外。 +// emit 把事件交给窗口。 func (a *App) emit(ev conv.Event) { a.mu.Lock() sink := a.sink diff --git a/internal/app/settings.go b/internal/app/settings.go index bd1ccec..69629e2 100644 --- a/internal/app/settings.go +++ b/internal/app/settings.go @@ -10,63 +10,28 @@ import ( // ---------- 设置 ---------- -// settingsPatch 是「只覆盖用户改动过的字段」的参数。 -// 不能用整个 Settings:前端漏发一个字段就会把用户已保存的设置悄悄重置成零值。 -type settingsPatch struct { - Endpoint *string `json:"endpoint"` - Concurrency *int `json:"concurrency"` - Retries *int `json:"retries"` - Output *string `json:"output"` - Suffix *string `json:"suffix"` - OutDir *string `json:"outDir"` - Backup *bool `json:"backup"` - Reuse *bool `json:"reuseUploads"` - Remote *string `json:"remote"` - RemoteDir *string `json:"remoteDir"` - CloseAction *string `json:"closeAction"` - StartInTray *bool `json:"startInTray"` -} - -func (p *settingsPatch) apply(cfg *settings.Settings) { - if p == nil { - return - } - if p.Endpoint != nil { - cfg.Endpoint = *p.Endpoint - } - if p.Concurrency != nil { - cfg.Concurrency = *p.Concurrency - } - if p.Retries != nil { - cfg.Retries = *p.Retries - } - if p.Output != nil { - cfg.Output = *p.Output - } - if p.Suffix != nil { - cfg.Suffix = *p.Suffix - } - if p.OutDir != nil { - cfg.OutDir = *p.OutDir - } - if p.Backup != nil { - cfg.Backup = *p.Backup - } - if p.Reuse != nil { - cfg.ReuseUploads = *p.Reuse - } - if p.Remote != nil { - cfg.Remote = *p.Remote - } - if p.RemoteDir != nil { - cfg.RemoteDir = *p.RemoteDir +// putSettings 把前端交上来的设置整份写下去。 +// +// 前端持有完整的一份设置(草稿 + 已保存值),保存时交上来的一定是完整的: +// 以前这里按「只覆盖发上来的字段」做增量,是因为要兼容「某次调用顺带改一个字段」 +// 的用法(把页面名当设置传上来)。现在操作类型走 start 的 op 参数,设置只有 +// 「读一份、改一改、整份存回去」这一条路,增量补丁那套(12 个指针字段 + 逐字段 +// 判空)就没有存在的理由了。 +func (a *App) putSettings(params json.RawMessage) (any, error) { + var incoming settings.Settings + if len(params) > 0 { + if err := json.Unmarshal(params, &incoming); err != nil { + return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerBadJSON)) + } } - if p.CloseAction != nil { - cfg.CloseAction = *p.CloseAction + cfg, err := a.configOf(&incoming) + if err != nil { + return nil, badRequest(err.Error()) } - if p.StartInTray != nil { - cfg.StartInTray = *p.StartInTray + if err := a.store.Save(cfg); err != nil { + return nil, internal(i18n.T(a.Lang(), i18n.KeyServerSaveFailed, err)) } + return a.store.Load(), nil } // setCloseAction 只改关闭行为。关窗时勾了「不再询问」的话,前端把这次选的动作存下来, @@ -91,26 +56,15 @@ func (a *App) setCloseAction(params json.RawMessage) (any, error) { return map[string]string{"closeAction": cfg.CloseAction}, nil } -func (a *App) putSettings(params json.RawMessage) (any, error) { - var patch settingsPatch - if len(params) > 0 { - if err := json.Unmarshal(params, &patch); err != nil { - return nil, badRequest(i18n.T(a.Lang(), i18n.KeyServerBadJSON)) - } +// configOf 把交上来的一份设置规整成可用的运行参数。 +// +// 校验只有这一处:前端那份「保存前先拦一下」的检查只是为了让用户马上看到问题, +// 真正说了算的是这里(settings.Normalize)。 +func (a *App) configOf(incoming *settings.Settings) (settings.Settings, error) { + cfg := settings.Default() + if incoming != nil { + cfg = *incoming } - cfg, err := a.configOf(&patch) - if err != nil { - return nil, badRequest(err.Error()) - } - if err := a.store.Save(cfg); err != nil { - return nil, internal(i18n.T(a.Lang(), i18n.KeyServerSaveFailed, err)) - } - return a.store.Load(), nil -} - -func (a *App) configOf(patch *settingsPatch) (settings.Settings, error) { - cfg := a.store.Load() - patch.apply(&cfg) // 调试构建整轮只扫描、不写文件;发布构建里这一位恒为 false。 // 它不是用户设置:界面没有开关,也不会从 settings.put 传上来。 cfg.DryRun = version.DebugMode() diff --git a/internal/conv/collect.go b/internal/conv/collect.go index d1d1cef..770380e 100644 --- a/internal/conv/collect.go +++ b/internal/conv/collect.go @@ -65,9 +65,6 @@ func ExpandPaths(paths []string, suffix, skipDir string) (files []string, missin return nil } lower := strings.ToLower(d.Name()) - if !strings.HasSuffix(lower, ".md") && !strings.HasSuffix(lower, ".markdown") { - return nil - } // 产物名是 .md,stem 一定非空。名字正好等于 suffix+".md" 的 // 文件不可能是产物(剥掉后缀什么都不剩),它更可能是一篇名字就这样的文档: // `--suffix a` 时 a.md 曾被这条规则吃掉,报「没有找到任何可处理的文件」。 @@ -75,6 +72,12 @@ func ExpandPaths(paths []string, suffix, skipDir string) (files []string, missin skipped = append(skipped, path) return nil } + // 后缀不再是标准:目录里可能有 .txt、.log、无后缀的片段。 + // 只要是文本文件就收(见 document_detect.go),这样「文件夹里有几份 + // 文档就有几张卡片」,不会因为内容里恰好没有 Markdown 标记而被悄悄跳过。 + if !documentFile(path) { + return nil + } add(path) return nil }) diff --git a/internal/conv/document_detect.go b/internal/conv/document_detect.go new file mode 100644 index 0000000..f62ebc8 --- /dev/null +++ b/internal/conv/document_detect.go @@ -0,0 +1,30 @@ +package conv + +import ( + "path/filepath" + "strings" +) + +// 目录展开时收哪些文件:只看后缀,只认 Markdown。 +// +// 为什么不再看内容:拖进来的目录可能有几万份文件,逐份嗅探既慢又难解释;更要紧的是 +// 「收什么」必须可预期 —— 只认 Markdown 后缀,用户看一眼目录就知道会出几张卡片。 +// .txt、.log、代码文件都不进队列。 +// +// 空文件也算一份文档:它是 Markdown,只是里面没有内容(卡片上会显示「无图片」)。 +// 之前按内容嗅探时,0 字节的 .md 会被当成「不是文档」跳过 —— 那正是「文件夹里明明 +// 有两个 .md,却只出来一张卡片」的来源。 + +// markdownExts 是认可的 Markdown 后缀。 +var markdownExts = map[string]bool{ + ".md": true, + ".markdown": true, + ".mdown": true, + ".mkd": true, + ".mdwn": true, +} + +// documentFile 判断这个路径是不是一份 Markdown 文档。 +func documentFile(path string) bool { + return markdownExts[strings.ToLower(filepath.Ext(path))] +} diff --git a/internal/conv/document_detect_test.go b/internal/conv/document_detect_test.go new file mode 100644 index 0000000..e62a30c --- /dev/null +++ b/internal/conv/document_detect_test.go @@ -0,0 +1,82 @@ +package conv + +import ( + "os" + "path/filepath" + "testing" +) + +func writeTemp(t *testing.T, dir, name string, data []byte) string { + t.Helper() + path := filepath.Join(dir, name) + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatalf("写夹具失败:%v", err) + } + return path +} + +// 只有 Markdown 后缀算文档;内容不看,空文件也算。 +func TestDocumentFile(t *testing.T) { + dir := t.TempDir() + + cases := []struct { + name string + data []byte + want bool + }{ + {"a.md", []byte("# 标题\n"), true}, + {"empty.md", nil, true}, + {"upper.MD", []byte("text"), true}, + {"b.markdown", []byte("text"), true}, + {"c.txt", []byte("# 看着像 Markdown 也不算\n"), false}, + {"d.log", []byte("日志\n"), false}, + {"notes", []byte("# 无后缀\n"), false}, + {"e.png", []byte{0x89, 'P', 'N', 'G', 0x00}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + path := writeTemp(t, dir, tc.name, tc.data) + if got := documentFile(path); got != tc.want { + t.Fatalf("documentFile(%s) = %v, want %v", tc.name, got, tc.want) + } + }) + } +} + +// 目录展开只收 Markdown:.txt / .log / 无后缀 / 图片都不进队列, +// 上一轮的产物按名字跳过,空 .md 照收。 +func TestExpandPathsAcceptsOnlyMarkdown(t *testing.T) { + dir := t.TempDir() + writeTemp(t, dir, "a.md", []byte("# 一\n")) + writeTemp(t, dir, "empty.md", nil) + writeTemp(t, dir, "b.txt", []byte("普通文本\n")) + writeTemp(t, dir, "c.log", []byte("日志\n")) + writeTemp(t, dir, "notes", []byte("无后缀\n")) + writeTemp(t, dir, "d.png", []byte{0x89, 'P', 'N', 'G', 0x00}) + writeTemp(t, dir, "a.converted.md", []byte("# 上一轮的产物\n")) + + files, missing, skipped, err := ExpandPaths([]string{dir}, ".converted", "") + if err != nil { + t.Fatalf("ExpandPaths:%v", err) + } + if len(missing) != 0 { + t.Fatalf("不该有缺失路径:%v", missing) + } + if len(skipped) != 1 { + t.Fatalf("应该跳掉 1 个产物,实际 %v", skipped) + } + + names := make([]string, 0, len(files)) + for _, f := range files { + names = append(names, filepath.Base(f)) + } + if len(names) != 2 { + t.Fatalf("应该收 2 份 Markdown(含空文件),实际 %v", names) + } + want := map[string]bool{"a.md": true, "empty.md": true} + for _, name := range names { + if !want[name] { + t.Fatalf("不该收 %q(%v)", name, names) + } + } +} diff --git a/internal/conv/remote.go b/internal/conv/remote.go index eb28a93..2bf6366 100644 --- a/internal/conv/remote.go +++ b/internal/conv/remote.go @@ -163,11 +163,12 @@ func (r *Runner) runUnits(ctx context.Context, id string, docDir string, groups // 下游(app.Batcher、测试里的收集函数)都按「同一个文件的事件是顺序来的」写, // 一旦并发进来,done 会倒退、Items 增量会在并发追加里丢掉。 r.notify(Event{ - Type: EventFileProgress, - ID: id, - Done: progress, - Total: total, - Items: patches, + Type: EventFileProgress, + ID: id, + Done: progress, + Total: total, + Items: patches, + Summary: r.liveSummary(), }) mu.Unlock() } @@ -669,6 +670,9 @@ func looksComplete(path string) bool { } // sameFile 逐字节比较两个文件。大小不同直接返回 false,省掉一次读盘。 +// +// 分块比较而不是各自 os.ReadFile 再 bytes.Equal:两张 50 MB 的图那样比一次就是 +// 100 MB 的峰值内存,而这里真正需要的只是「这两串字节一不一样」。 func sameFile(a, b string) (bool, error) { sa, err := os.Stat(a) if err != nil { @@ -681,15 +685,38 @@ func sameFile(a, b string) (bool, error) { if sa.Size() != sb.Size() { return false, nil } - da, err := os.ReadFile(a) + + fa, err := os.Open(a) if err != nil { return false, err } - db, err := os.ReadFile(b) + defer func() { _ = fa.Close() }() + fb, err := os.Open(b) if err != nil { return false, err } - return bytes.Equal(da, db), nil + defer func() { _ = fb.Close() }() + + const chunk = 64 << 10 + bufA := make([]byte, chunk) + bufB := make([]byte, chunk) + for { + na, errA := io.ReadFull(fa, bufA) + nb, errB := io.ReadFull(fb, bufB) + if na != nb || !bytes.Equal(bufA[:na], bufB[:nb]) { + return false, nil + } + // 两边大小相同,所以「读到尾」也只会在同一次迭代里发生。 + if errA == io.EOF || errA == io.ErrUnexpectedEOF { + return true, nil + } + if errA != nil { + return false, errA + } + if errB != nil { + return false, errB + } + } } // firstFileInPath 从 dir 往上找第一个「存在但不是目录」的那一层,返回它。 diff --git a/internal/conv/run.go b/internal/conv/run.go index 4645717..bfe93ae 100644 --- a/internal/conv/run.go +++ b/internal/conv/run.go @@ -11,6 +11,44 @@ import ( "github.com/geekMus/markpic/internal/textenc" ) +// addFileToSummary 把一个文件的结果并进一份汇总。 +// +// 终局汇总(跑完)与中途快照(每处理完一个文件发一次)都走这里:两处各写一遍 +// switch 的话,以后加一个计数项就会漏掉其中一边,界面上的数和最后的报告对不上。 +func addFileToSummary(sum *Summary, res *FileResult) { + sum.Files++ + sum.Images += res.Images + sum.Uploaded += res.Uploaded + sum.Localized += res.Localized + sum.LocalizedUnique += res.LocalizedUnique + sum.RemoteChecked += res.Checked + sum.RemoteCheckedUnique += res.CheckedUnique + sum.RemoteDead += res.Dead + sum.RemoteDeadUnique += res.DeadUnique + sum.RemoteFailed += res.RemoteFailed + sum.RemoteFailedUnique += res.RemoteFailedUnique + sum.RemoteUnsupported += res.RemoteUnsupported + sum.RemoteKept += res.RemoteKept + sum.LocalMissing += res.LocalMissing + sum.FailedImages += res.Failed + switch res.Status { + case FileOK: + sum.OK++ + case FilePartial: + sum.Partial++ + case FileNoImages: + sum.NoImages++ + case FileFailed: + sum.Failed++ + case FileCancelled: + // 取消的文件既不算成功也不算失败:界面自己会显示「已取消」。 + case FilePreview: + sum.OK++ + case FileChecked: + sum.FilesChecked++ + } +} + // Run 执行整轮转换并返回汇总。 func (r *Runner) Run(ctx context.Context, paths []string) Summary { _, sum := r.RunCollect(ctx, paths) @@ -102,6 +140,7 @@ func (r *Runner) RunCollect(ctx context.Context, paths []string) ([]FileResult, // 预检算出来的路径也就是真正会写出去的路径。 r.planOutputs(files) + r.beginRun(started) r.notify(Event{Type: EventRunStarted, Mode: string(r.cfg.Remote), Files: tasks}) results := make([]FileResult, len(files)) @@ -125,7 +164,7 @@ func (r *Runner) RunCollect(ctx context.Context, paths []string) ([]FileResult, r.notify(Event{Type: EventFileStarted, ID: task.ID}) res := r.processFile(ctx, task.ID, task.Path) results[idx] = res - r.notify(Event{Type: EventFileFinished, ID: task.ID, Result: &res}) + r.notify(Event{Type: EventFileFinished, ID: task.ID, Result: &res, Summary: r.absorbResult(&res)}) } }() } @@ -139,38 +178,9 @@ func (r *Runner) RunCollect(ctx context.Context, paths []string) ([]FileResult, close(work) wg.Wait() - for _, res := range results { - sum.Files++ - sum.Images += res.Images - sum.Uploaded += res.Uploaded - sum.Localized += res.Localized - sum.LocalizedUnique += res.LocalizedUnique - sum.RemoteChecked += res.Checked - sum.RemoteCheckedUnique += res.CheckedUnique - sum.RemoteDead += res.Dead - sum.RemoteDeadUnique += res.DeadUnique - sum.RemoteFailed += res.RemoteFailed - sum.RemoteFailedUnique += res.RemoteFailedUnique - sum.RemoteUnsupported += res.RemoteUnsupported - sum.RemoteKept += res.RemoteKept - sum.LocalMissing += res.LocalMissing - sum.FailedImages += res.Failed - switch res.Status { - case FileOK: - sum.OK++ - case FilePartial: - sum.Partial++ - case FileNoImages: - sum.NoImages++ - case FileFailed: - sum.Failed++ - case FileCancelled: - // 取消的文件既不算成功也不算失败:界面自己会显示「已取消」。 - case FilePreview: - sum.OK++ - case FileChecked: - sum.FilesChecked++ - } + // 终局汇总与中途快照共用 addFileToSummary:一处口径,两边不会漂。 + for i := range results { + addFileToSummary(&sum, &results[i]) } sum.DurationMs = time.Since(started).Milliseconds() sum.Cancelled = ctx.Err() != nil diff --git a/internal/conv/runner.go b/internal/conv/runner.go index ca0d4bc..4ee7b5e 100644 --- a/internal/conv/runner.go +++ b/internal/conv/runner.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "os" + "path/filepath" "strings" "sync" "sync/atomic" @@ -122,6 +123,17 @@ type Runner struct { // remoteCache 是跨运行的下载记录:上次已经下过、文件还在且大小对得上, // 就不再打一次网络。为 nil 或路径为空时等于关掉。 remoteCache *remotecache.Cache + + // runMu/runSum 是「这一轮到目前为止」的累计汇总:每处理完一个文件就并一次, + // 随 file.progress / file.finished 一起发出去。 + // + // 为什么由后端算:界面要在跑动中显示「替换了几处、失效几张、失败几张」。 + // 以前这些数由前端按事件自己加减(二十几个字段各来一遍),后端跑完又发一份 + // 汇总把它整个盖掉 —— 同一份数字两个算法,口径一旦有一处不同就当场对不上。 + // 现在只有一个算法,界面只负责显示。 + runMu sync.Mutex + runSum Summary + runAt time.Time } // abortsAfterFailures 是「认定图床不可用」的连续失败张数。 @@ -289,6 +301,30 @@ func NewRunner(cfg settings.Settings, lang i18n.Lang, runID string, emit Emit) * } } +// NewScanRunner 造一个「只扫描」的 Runner:不建任何网络客户端。 +// +// 扫描一份文档只需要读盘、解码、解析引用、分类;picgo 与 remoteimg 的客户端 +// 各自带着一条 HTTP 连接池,在扫描里纯属浪费 —— 之前每份文档造一个,一万份文档 +// 就是一万个连接池,实测占掉扫描时间的一大半。 +// +// 用它的地方必须保持 previewOnly(这里已经设好):扫描永远走不到网络分支, +// 真走过去 client / remote 都是 nil。 +func NewScanRunner(cfg settings.Settings, lang i18n.Lang) *Runner { + if lang == "" { + lang = i18n.ZH + } + return &Runner{ + cfg: cfg, + lang: lang, + previewOnly: true, + stamps: make(map[string]stamp), + scanDocs: make(map[string]*mdscan.Document), + // 预扫也要算一遍输出路径(界面上写「计划输出到 …」),用到这两张表。 + outPlan: make(map[string]string), + usedOut: make(map[string]bool), + } +} + // rememberDoc 记下预扫结果,供正式处理时复用。 func (r *Runner) rememberDoc(path string, doc *mdscan.Document) { r.scanMu.Lock() @@ -321,6 +357,56 @@ func (r *Runner) takeDoc(path string, data []byte) *mdscan.Document { return doc } +// ScanOne 扫描单个文件:读盘、解析引用、逐张分类,不发任何网络请求。 +// +// 异步扫描用它逐份处理目录里发现的文档。和 Run 的区别是它不碰整轮的状态机 +// (不派工、不写文件、不汇总),所以可以同时开好几个、各自处理各自的文件。 +func (r *Runner) ScanOne(ctx context.Context, path string) FileResult { + abs, err := filepath.Abs(path) + if err != nil { + abs = path + } + return r.processFile(ctx, "", abs) +} + +// beginRun 清空这一轮的累计汇总,并记下起跑时刻。 +func (r *Runner) beginRun(at time.Time) { + r.runMu.Lock() + r.runSum = Summary{RunID: r.runID} + r.runAt = at + r.runMu.Unlock() +} + +// absorbResult 把一个刚处理完的文件并进累计汇总,返回可以随事件发出去的快照。 +func (r *Runner) absorbResult(res *FileResult) *Summary { + r.runMu.Lock() + defer r.runMu.Unlock() + addFileToSummary(&r.runSum, res) + return r.liveSummaryLocked() +} + +// liveSummary 返回「到目前为止」的汇总快照(进度事件用)。 +func (r *Runner) liveSummary() *Summary { + r.runMu.Lock() + defer r.runMu.Unlock() + return r.liveSummaryLocked() +} + +// liveSummaryLocked 组装快照。调用方必须已持有 runMu。 +// +// 「省下了几次」三个计数来自缓存与计数器,不在 addFileToSummary 里: +// 它们算的是这一轮少发了几次请求,不是某个文件的处理结果。 +func (r *Runner) liveSummaryLocked() *Summary { + snap := r.runSum + snap.Reused = r.uploads.Hits() + snap.UploadRequests = int(r.sent.Load()) + snap.RemoteReused = r.remoteCacheHits() + if !r.runAt.IsZero() { + snap.DurationMs = time.Since(r.runAt).Milliseconds() + } + return &snap +} + func (r *Runner) notify(ev Event) { if r.emit == nil { return diff --git a/internal/conv/scan_walk.go b/internal/conv/scan_walk.go new file mode 100644 index 0000000..e8a9928 --- /dev/null +++ b/internal/conv/scan_walk.go @@ -0,0 +1,185 @@ +package conv + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" +) + +// WalkCounts 是遍历过程中的实时计数:遍历还在跑的时候就可以读。 +// +// 进度事件要在「还没走完」的时候报数,所以计数不能等遍历结束才回填 —— 那样拖一块 +// 大一点的盘,界面上会一直显示「已找到 0 份」。 +type WalkCounts struct { + Found atomic.Int64 + Dirs atomic.Int64 + // current 是「此刻正在读的那个目录」。拖动一块盘时,用户最想知道的就是 + // 「现在走到哪儿了」——只报「已找到 N 份」看不出还在不在动。 + // 并行遍历下它只是「最近一个开工的目录」,不是严格顺序,作为进度提示足够。 + current atomic.Value // string +} + +func (c *WalkCounts) setCurrent(dir string) { + c.current.Store(dir) +} + +// Current 返回最近开始读取的目录(还没开始走时是空串)。 +func (c *WalkCounts) Current() string { + if v, ok := c.current.Load().(string); ok { + return v + } + return "" +} + +// WalkDocuments 递归遍历一个目录,把「能当文档处理」的文件逐个交给 yield。 +// +// 为什么不是先走完再返回:拖进来一整块盘、一个网盘目录时,走完可能要几分钟。 +// 先攒清单再统一处理的话,界面上除了「扫描中」三个字什么也看不到。这里边发现边 +// 回调,界面就能一份份往外冒卡片、同时看到「已经找到多少」。 +// +// 为什么并行:机械盘上串行 ReadDir 是整条链路的瓶颈,开几个协程读目录能快一截 +// (SSD/网盘上收益小一些,但也不会更慢)。 +// +// yield 返回 false 表示「不要了」(用户点了停止):遍历立刻收工。 +// counts 可以为 nil(不需要进度时)。 +func WalkDocuments(ctx context.Context, root, suffix, skipDir string, workers int, counts *WalkCounts, yield func(string) bool) { + if workers < 1 { + workers = 1 + } + ownSuffix := strings.ToLower(suffix + ".md") + skip := normalizeDir(skipDir) + + // 待读目录放在一个带锁的栈里,而不是定长 channel。 + // + // 曾经用容量 512 的 channel 派发:worker 既是消费者又是生产者,16 个 worker + // 同时往满队列塞子目录时会全部阻塞,再没有谁去取任务 —— 整棵树就地停住, + // 界面上的数字不再变化、CPU 归零,进度心跳却还在刷,于是卡片永远「扫描中」。 + // 拖一整块盘(目录多、每层宽)时必现。 + var mu sync.Mutex + cond := sync.NewCond(&mu) + stack := make([]string, 0, 1024) + // pending 是「已入栈 + 正在读」的目录数;归零就是整棵树走完了。 + pending := 0 + stopped := false + + push := func(dir string) bool { + mu.Lock() + defer mu.Unlock() + if stopped { + return false + } + pending++ + stack = append(stack, dir) + cond.Signal() + return true + } + + // pop 取一个待读目录;没有活可干时返回 false(遍历结束,或被取消)。 + pop := func() (string, bool) { + mu.Lock() + defer mu.Unlock() + for { + if stopped || pending == 0 { + return "", false + } + if n := len(stack); n > 0 { + dir := stack[n-1] + stack = stack[:n-1] + return dir, true + } + cond.Wait() + } + } + + finish := func() { + mu.Lock() + pending-- + if pending == 0 { + // 最后一个目录读完:叫醒所有还在等的 worker,让它们收工。 + cond.Broadcast() + } + mu.Unlock() + } + + halt := func() { + mu.Lock() + stopped = true + cond.Broadcast() + mu.Unlock() + } + + if counts == nil { + counts = &WalkCounts{} + } + + // ctx 取消时也得把等在 cond 上的 worker 叫醒,否则它们会一直睡着。 + watchDone := make(chan struct{}) + go func() { + select { + case <-ctx.Done(): + halt() + case <-watchDone: + } + }() + defer close(watchDone) + + // root 先入栈再开 worker:否则 worker 抢在入栈之前看到 pending==0,直接空跑收工。 + push(root) + + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + dir, ok := pop() + if !ok { + return + } + counts.setCurrent(dir) + entries, err := os.ReadDir(dir) + if err == nil { + for _, entry := range entries { + full := filepath.Join(dir, entry.Name()) + if entry.IsDir() { + name := strings.ToLower(entry.Name()) + // .git / node_modules 之类:跳过去,别把仓库当文档树走。 + if name == ".git" || name == "node_modules" || name == ".svn" || name == ".obsidian" { + continue + } + if skip != "" && normalizeDir(full) == skip { + continue + } + counts.Dirs.Add(1) + if !push(full) { + finish() + return + } + continue + } + lower := strings.ToLower(entry.Name()) + // 上一轮的产物:名字是 .md,原样跳掉。 + if strings.HasSuffix(lower, ownSuffix) && len(lower) > len(ownSuffix) { + continue + } + if !documentFile(full) { + continue + } + counts.Found.Add(1) + if !yield(full) { + // 用户点了停止:其余 worker 一起收工,别把整棵树走完。 + halt() + finish() + return + } + } + } + finish() + } + }() + } + wg.Wait() +} diff --git a/internal/conv/scan_walk_real_test.go b/internal/conv/scan_walk_real_test.go new file mode 100644 index 0000000..713f008 --- /dev/null +++ b/internal/conv/scan_walk_real_test.go @@ -0,0 +1,39 @@ +package conv + +import ( + "context" + "os" + "sync/atomic" + "testing" + "time" +) + +// 只在显式设置 MARKPIC_REAL_WALK 时跑:拿真实的盘验证遍历能走完、耗时多少。 +// +// 这就是当初「卡在 D: 43 份、CPU 归零」的场景:真实盘上目录宽、层数深, +// 单元测试的临时目录太干净,复现不出来。 +func TestWalkDocumentsRealDrive(t *testing.T) { + root := os.Getenv("MARKPIC_REAL_WALK") + if root == "" { + t.Skip("未设置 MARKPIC_REAL_WALK") + } + + var counts WalkCounts + var found atomic.Int64 + done := make(chan struct{}) + start := time.Now() + go func() { + defer close(done) + WalkDocuments(context.Background(), root, ".converted", "", 16, &counts, func(string) bool { + found.Add(1) + return true + }) + }() + + select { + case <-done: + t.Logf("走完 %s:%d 份文档、%d 个目录、耗时 %s", root, found.Load(), counts.Dirs.Load(), time.Since(start).Round(time.Millisecond)) + case <-time.After(10 * time.Minute): + t.Fatalf("遍历卡住了:找到 %d 份、走过 %d 个目录之后不再前进", counts.Found.Load(), counts.Dirs.Load()) + } +} diff --git a/internal/conv/scan_walk_test.go b/internal/conv/scan_walk_test.go new file mode 100644 index 0000000..1ae8abc --- /dev/null +++ b/internal/conv/scan_walk_test.go @@ -0,0 +1,145 @@ +package conv + +import ( + "context" + "fmt" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +// 遍历要把文档挑出来,同时跳过 .git / node_modules / 上一轮的产物。 +func TestWalkDocumentsSkipsJunk(t *testing.T) { + dir := t.TempDir() + writeTemp(t, dir, "a.md", []byte("# a\n")) + writeTemp(t, dir, "b.txt", []byte("普通文本\n")) + writeTemp(t, dir, "c.png", []byte{0x89, 'P', 'N', 'G', 0x00}) + writeTemp(t, dir, "a.converted.md", []byte("# 产物\n")) + + gitDir := filepath.Join(dir, ".git") + if err := os.MkdirAll(gitDir, 0o755); err != nil { + t.Fatal(err) + } + writeTemp(t, gitDir, "inside.md", []byte("# 不该被走进去\n")) + + mods := filepath.Join(dir, "node_modules") + if err := os.MkdirAll(mods, 0o755); err != nil { + t.Fatal(err) + } + writeTemp(t, mods, "dep.md", []byte("# 也不该\n")) + + sub := filepath.Join(dir, "sub") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatal(err) + } + writeTemp(t, sub, "deep.md", []byte("# 深一层\n")) + + var counts WalkCounts + var found []string + WalkDocuments(context.Background(), dir, ".converted", "", 4, &counts, func(path string) bool { + found = append(found, filepath.Base(path)) + return true + }) + + // 只认 Markdown:b.txt 虽然存在,但不算文档。 + if len(found) != 2 { + t.Fatalf("应该找到 2 份 Markdown,实际 %v", found) + } + want := map[string]bool{"a.md": true, "deep.md": true} + for _, name := range found { + if !want[name] { + t.Fatalf("不该收 %q(%v)", name, found) + } + } + if got := counts.Found.Load(); got != 2 { + t.Fatalf("实时计数应该是 2,实际 %d", got) + } + // 只有 sub 会被算进去:.git / node_modules 在计数之前就被跳掉了。 + if got := counts.Dirs.Load(); got != 1 { + t.Fatalf("应该走过 1 个子目录,实际 %d", got) + } +} + +// yield 返回 false 表示用户点了停止:遍历要立刻收工,而不是把整棵树走完。 +func TestWalkDocumentsStopsWhenYieldSaysNo(t *testing.T) { + dir := t.TempDir() + for i := 0; i < 50; i++ { + writeTemp(t, dir, "doc"+string(rune('a'+i%26))+string(rune('0'+i/26))+".md", []byte("# x\n")) + } + + var counts WalkCounts + visited := 0 + WalkDocuments(context.Background(), dir, ".converted", "", 4, &counts, func(string) bool { + visited++ + return false // 第一份就喊停 + }) + + if visited != 1 { + t.Fatalf("喊停之后不该再回调,实际 %d 次", visited) + } +} + +// 宽目录树曾经会把遍历彻底卡死。 +// +// 旧实现用容量 512 的 channel 派发子目录,worker 既是消费者又是生产者:16 个 +// worker 同时往满队列里塞目录时全部阻塞,再没有谁去取任务,整棵树就此停住。 +// 界面上的表现是「已找到 N 份」不再变化、CPU 归零,但进度事件还在刷(那是另一个 +// goroutine),于是卡片永远停在「扫描中」——拖一整块盘时必现。 +func TestWalkDocumentsWideTreeFinishes(t *testing.T) { + root := t.TempDir() + // 16 × 40 = 640 个子目录:超过旧实现那 512 的队列容量,必定把它填满。 + const wideA, wideB = 16, 40 + for a := 0; a < wideA; a++ { + da := filepath.Join(root, fmt.Sprintf("a%02d", a)) + if err := os.MkdirAll(da, 0o755); err != nil { + t.Fatal(err) + } + writeTemp(t, da, "a.md", []byte("# a\n")) + for b := 0; b < wideB; b++ { + db := filepath.Join(da, fmt.Sprintf("b%02d", b)) + if err := os.MkdirAll(db, 0o755); err != nil { + t.Fatal(err) + } + writeTemp(t, db, "b.md", []byte("# b\n")) + } + } + + var counts WalkCounts + var found atomic.Int64 + done := make(chan struct{}) + go func() { + defer close(done) + WalkDocuments(context.Background(), root, ".converted", "", 16, &counts, func(string) bool { + found.Add(1) + return true + }) + }() + + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatalf("遍历卡住了:找到 %d 份、走过 %d 个目录之后不再前进", counts.Found.Load(), counts.Dirs.Load()) + } + + // 每个 a 目录一份 + 每个 b 目录一份。 + if want := int64(wideA + wideA*wideB); found.Load() != want { + t.Fatalf("应该找到 %d 份,实际 %d", want, found.Load()) + } +} + +// 已经取消的 context:不该有任何回调,也不该卡住。 +func TestWalkDocumentsHonoursContext(t *testing.T) { + dir := t.TempDir() + writeTemp(t, dir, "a.md", []byte("# a\n")) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + var counts WalkCounts + WalkDocuments(ctx, dir, "", "", 4, &counts, func(string) bool { + t.Fatal("已取消的遍历不该回调") + return false + }) +} diff --git a/internal/conv/types.go b/internal/conv/types.go index 159b479..62abae1 100644 --- a/internal/conv/types.go +++ b/internal/conv/types.go @@ -188,12 +188,20 @@ type Event struct { Level string `json:"level,omitempty"` Message string `json:"message,omitempty"` - // 下面四个只用在扫描事件上(scan.file)。扫描是异步的、可以单文件取消: + // 下面几个只用在扫描事件上。扫描是异步的、可以随时停: // 前端要能按路径把「扫到了什么」贴回对应的那张卡片,也要能说清这次为什么没扫成。 Path string `json:"path,omitempty"` Scanned []FileResult `json:"scanned,omitempty"` Cancelled bool `json:"cancelled,omitempty"` TimedOut bool `json:"timedOut,omitempty"` + // Found / Dirs 只用在 scan.progress 上:这个路径到目前为止发现了多少份文档、 + // 走过了多少目录。拖一整块盘时没有总数可报,只能报「已经找到多少」。 + Found int `json:"found,omitempty"` + Dirs int `json:"dirs,omitempty"` + // Current 是此刻正在读的目录,界面上写成「正在扫描 D:\…」。 + Current string `json:"current,omitempty"` + // File 是此刻正在解析的那份文档(比目录更细一档)。 + File string `json:"file,omitempty"` } // 事件类型。 @@ -206,8 +214,9 @@ const ( EventRunCancelled = "run.cancelled" EventLog = "log" - // 扫描(preview)用自己的两个事件:它不写文件、可以多份同时在跑, + // 扫描用自己的三个事件:它不写文件、可以多份同时在跑, // 也不能和「一轮转换」混在同一条 runId 上。RunID 位置放的是前端生成的 scanId。 - EventScanFile = "scan.file" - EventScanDone = "scan.done" + EventScanProgress = "scan.progress" + EventScanFile = "scan.file" + EventScanDone = "scan.done" ) diff --git a/internal/diskcache/diskcache.go b/internal/diskcache/diskcache.go new file mode 100644 index 0000000..f0bdce3 --- /dev/null +++ b/internal/diskcache/diskcache.go @@ -0,0 +1,101 @@ +// Package diskcache 管「一份按字符串索引的缓存怎么落到一个 JSON 文件上」。 +// +// 上传结果缓存与下载记录缓存要做的是同样四件事:读回来、把别的进程刚写进去的条目 +// 并进来、按使用时间淘汰、原子写回。差别只有条目类型和淘汰上限,那部分留在各自包里。 +// 缓存不是用户数据:文件不存在、读坏了、版本不认识,一律当空缓存重新算一遍。 +package diskcache + +import ( + "encoding/json" + "os" + "path/filepath" + "sort" +) + +// Version 是缓存文件的结构版本。版本对不上就当空缓存:里面只是「上次做过什么」, +// 丢了顶多重做一次,不值得为它写迁移。 +const Version = 2 + +type file[V any] struct { + Version int `json:"version"` + Entries map[string]V `json:"entries"` +} + +// Read 读回磁盘上的条目,同时给出文件里记着的版本。 +// +// 版本交给调用方是为了让老文件能就地换算(上传缓存从纳秒改成了秒), +// 而不是让用户白白重传一轮。 +func Read[V any](path string) (map[string]V, int) { + entries := make(map[string]V) + if path == "" { + return entries, Version + } + raw, err := os.ReadFile(path) + if err != nil { + return entries, Version + } + var f file[V] + if err := json.Unmarshal(raw, &f); err != nil || f.Entries == nil { + return entries, Version + } + return f.Entries, f.Version +} + +// Save 把 entries 合并进磁盘上已有的内容(界面与其它进程可能同时在写), +// 交给 prune 淘汰之后原子写回,返回真正落盘的那一份。 +func Save[V any](path string, entries map[string]V, prune func(map[string]V)) (map[string]V, error) { + // 没给路径 = 这个缓存是关掉的:什么都不写,也不要报错。 + if path == "" { + return entries, nil + } + merged := make(map[string]V, len(entries)) + if raw, err := os.ReadFile(path); err == nil { + var f file[V] + if json.Unmarshal(raw, &f) == nil && f.Version == Version { + for k, v := range f.Entries { + merged[k] = v + } + } + } + for k, v := range entries { + merged[k] = v + } + if prune != nil { + prune(merged) + } + raw, err := json.MarshalIndent(file[V]{Version: Version, Entries: merged}, "", " ") + if err != nil { + return entries, err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return entries, err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, raw, 0o644); err != nil { + return entries, err + } + if err := os.Rename(tmp, path); err != nil { + _ = os.Remove(tmp) + return entries, err + } + return merged, nil +} + +// PruneByUse 按「最后使用时间」保留最近的 max 条(最旧的先走)。 +func PruneByUse[V any](entries map[string]V, max int, usedAt func(V) int64) { + if max <= 0 || len(entries) <= max { + return + } + type kv struct { + key string + at int64 + } + all := make([]kv, 0, len(entries)) + for k, v := range entries { + all = append(all, kv{key: k, at: usedAt(v)}) + } + sort.Slice(all, func(i, j int) bool { return all[i].at < all[j].at }) + for i := 0; i < len(all)-max; i++ { + delete(entries, all[i].key) + } +} diff --git a/internal/diskcache/diskcache_test.go b/internal/diskcache/diskcache_test.go new file mode 100644 index 0000000..5d94d73 --- /dev/null +++ b/internal/diskcache/diskcache_test.go @@ -0,0 +1,106 @@ +package diskcache + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +type item struct { + Name string `json:"name"` + Used int64 `json:"used"` +} + +func TestReadSaveRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + entries := map[string]item{"a": {Name: "a.png", Used: 10}} + + merged, err := Save(path, entries, nil) + if err != nil { + t.Fatalf("Save:%v", err) + } + if len(merged) != 1 { + t.Fatalf("写回的条目数不对:%d", len(merged)) + } + + back, version := Read[item](path) + if version != Version { + t.Fatalf("版本应该是 %d,实际 %d", Version, version) + } + if got := back["a"]; got.Name != "a.png" || got.Used != 10 { + t.Fatalf("读回来的条目不对:%+v", got) + } +} + +// 缓存文件坏了不该让程序起不来:读不出来就当空的。 +func TestReadToleratesBrokenFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + if err := os.WriteFile(path, []byte("{ not json"), 0o644); err != nil { + t.Fatal(err) + } + entries, version := Read[item](path) + if len(entries) != 0 { + t.Fatalf("坏文件应该读出空表,实际 %d 条", len(entries)) + } + if version != Version { + t.Fatalf("坏文件应该回落到当前版本,实际 %d", version) + } +} + +// 写回时要把磁盘上已有的条目并进来:界面和另一个进程可能同时在写。 +func TestSaveMergesWhatIsAlreadyOnDisk(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + if _, err := Save(path, map[string]item{"old": {Name: "old.png", Used: 1}}, nil); err != nil { + t.Fatal(err) + } + merged, err := Save(path, map[string]item{"new": {Name: "new.png", Used: 2}}, nil) + if err != nil { + t.Fatal(err) + } + if len(merged) != 2 || merged["old"].Name != "old.png" || merged["new"].Name != "new.png" { + t.Fatalf("合并结果不对:%+v", merged) + } +} + +// 版本对不上的旧文件不参与合并:里面的时间单位可能已经变了,不能拿来混用。 +func TestSaveIgnoresForeignVersion(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + raw, _ := json.Marshal(map[string]any{"version": 1, "entries": map[string]item{"old": {Name: "old.png"}}}) + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + merged, err := Save(path, map[string]item{"new": {Name: "new.png"}}, nil) + if err != nil { + t.Fatal(err) + } + if _, ok := merged["old"]; ok { + t.Fatalf("旧版本的条目不该被并进来:%+v", merged) + } +} + +func TestPruneByUseKeepsNewest(t *testing.T) { + entries := map[string]item{} + for i := 0; i < 10; i++ { + key := string(rune('a' + i)) + entries[key] = item{Name: key, Used: int64(i)} + } + PruneByUse(entries, 3, func(v item) int64 { return v.Used }) + if len(entries) != 3 { + t.Fatalf("应该只剩 3 条,实际 %d", len(entries)) + } + for _, key := range []string{"h", "i", "j"} { + if _, ok := entries[key]; !ok { + t.Fatalf("应该保留最新的 %q:%+v", key, entries) + } + } +} + +func TestDisabledSaveWritesNothing(t *testing.T) { + if _, err := Save("", map[string]item{"a": {Name: "a"}}, nil); err != nil { + t.Fatalf("空路径不该报错:%v", err) + } + if entries, _ := Read[item](""); len(entries) != 0 { + t.Fatalf("空路径应该回空表,实际 %d 条", len(entries)) + } +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index 1d4144d..d87456a 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -69,6 +69,7 @@ const ( KeyConvWriteLocked Key = "conv.writeLocked" KeyConvTargetIsDir Key = "conv.targetIsDir" KeyConvReadLocked Key = "conv.readLocked" + KeyConvScanTimeout Key = "conv.scanTimeout" KeyConvOutDirIsFile Key = "conv.outDirIsFile" KeyConvOutDirIsSourceDir Key = "conv.outDirIsSourceDir" KeyConvRemoteDirIsFile Key = "conv.remoteDirIsFile" @@ -145,6 +146,7 @@ const ( KeyServerNoDialog Key = "server.noDialog" KeyServerNeedPaths Key = "server.needPaths" KeyServerBusy Key = "server.busy" + KeyServerBadOp Key = "server.badOp" KeyServerMissingFilePath Key = "server.missingFilePath" KeyServerMissingPath Key = "server.missingPath" KeyServerBadJSON Key = "server.badJSON" @@ -299,6 +301,10 @@ var catalog = map[Key]entry{ "读不出来:文件正被别的程序占用,或者没有读取权限:%s(关掉占用它的程序再试)", "Could not read: the file is in use by another program, or you lack read permission: %s (close whatever is using it and try again)", }, + KeyConvScanTimeout: { + "读取超时:这份文档在 20 秒内没读完(网络盘掉线,或者文件被别的程序占着?)", + "Timed out: this document did not finish reading within 20 seconds (network drive dropped, or the file is locked by another program?)", + }, KeyConvReferenceStyle: { "第 %d 行:引用式图片的标签在文档里找不到对应定义,已跳过", "Line %d: the reference-style image's label has no definition in this document, so it was skipped", @@ -575,6 +581,10 @@ var catalog = map[Key]entry{ "这一页已经有一个任务在跑,等它结束或先取消再试", "A task is already running on this page — wait for it to finish or cancel it first", }, + KeyServerBadOp: { + "不认识的操作:%s(只支持 upload / check / download)", + "Unknown operation: %s (expected upload, check or download)", + }, KeyServerMissingFilePath: { "缺少文件路径", "Missing file path", diff --git a/internal/remotecache/remotecache.go b/internal/remotecache/remotecache.go index 910bfe5..06f6e07 100644 --- a/internal/remotecache/remotecache.go +++ b/internal/remotecache/remotecache.go @@ -7,14 +7,12 @@ package remotecache import ( - "encoding/json" - "os" "path/filepath" - "sort" "strings" "sync" "time" + "github.com/geekMus/markpic/internal/diskcache" "github.com/geekMus/markpic/internal/remoteimg" ) @@ -45,11 +43,6 @@ type entry struct { UsedAt int64 `json:"usedAt"` } -type file struct { - Version int `json:"version"` - Entries map[string]entry `json:"entries"` -} - // Cache 是一份下载记录。零值不可用,用 Open 造。 type Cache struct { mu sync.Mutex @@ -98,19 +91,10 @@ func dirOfKey(key string) string { // Open 读入缓存文件。文件不存在或读坏了都返回一个空缓存(不是错误: // 缓存丢了只意味着这次要重新下载)。 func Open(path string) *Cache { - c := &Cache{path: path, entries: make(map[string]entry)} - if path == "" { - return c - } - raw, err := os.ReadFile(path) - if err != nil { - return c - } - var f file - if err := json.Unmarshal(raw, &f); err != nil { - return c - } - for k, v := range f.Entries { + c := &Cache{path: path} + entries, _ := diskcache.Read[entry](path) + c.entries = make(map[string]entry, len(entries)) + for k, v := range entries { if v.Name != "" { c.entries[k] = v } @@ -164,12 +148,13 @@ func (c *Cache) Lookup(rawURL, dir string) (name string, size int64, ok bool) { } c.mu.Lock() defer c.mu.Unlock() - e, found := c.entries[cacheKey(rawURL, dir)] + key := cacheKey(rawURL, dir) + e, found := c.entries[key] if !found || e.Name == "" { return "", 0, false } e.UsedAt = time.Now().Unix() - c.entries[cacheKey(rawURL, dir)] = e + c.entries[key] = e return e.Name, e.Size, true } @@ -257,61 +242,27 @@ func (c *Cache) Save() error { c.mu.Unlock() return nil } - merged := make(map[string]entry, len(c.entries)) - if raw, err := os.ReadFile(c.path); err == nil { - var f file - if json.Unmarshal(raw, &f) == nil { - for k, v := range f.Entries { - merged[k] = v + path := c.path + entries := c.entries + c.mu.Unlock() + + now := time.Now().Unix() + merged, err := diskcache.Save(path, entries, func(m map[string]entry) { + cutoff := now - int64(TTL/time.Second) + for k, v := range m { + if v.UsedAt < cutoff { + delete(m, k) } } + diskcache.PruneByUse(m, maxEntries, func(e entry) int64 { return e.UsedAt }) + }) + if err != nil { + return err } - now := time.Now().Unix() - for k, v := range c.entries { - merged[k] = v - } - prune(merged, now) + c.mu.Lock() c.entries = merged - // 合并进来的条目(别的进程写的)也要能被 Owner 反查到。 - c.reindex() + c.reindex() // 合并进来的条目(别的进程写的)也要能被 Owner 反查到。 c.dirty = false c.mu.Unlock() - - raw, err := json.MarshalIndent(file{Version: 1, Entries: merged}, "", " ") - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(c.path), 0o755); err != nil { - return err - } - tmp := c.path + ".tmp" - if err := os.WriteFile(tmp, raw, 0o644); err != nil { - return err - } - return os.Rename(tmp, c.path) -} - -// prune 丢掉太旧的记录,并保证不超过 maxEntries(按最后使用时间留最近的)。 -func prune(entries map[string]entry, now int64) { - cutoff := now - int64(TTL/time.Second) - for k, v := range entries { - if v.UsedAt < cutoff { - delete(entries, k) - } - } - if len(entries) <= maxEntries { - return - } - type kv struct { - key string - usedAt int64 - } - all := make([]kv, 0, len(entries)) - for k, v := range entries { - all = append(all, kv{key: k, usedAt: v.UsedAt}) - } - sort.Slice(all, func(i, j int) bool { return all[i].usedAt < all[j].usedAt }) - for i := 0; i < len(all)-maxEntries; i++ { - delete(entries, all[i].key) - } + return nil } diff --git a/internal/remotecache/remotecache_test.go b/internal/remotecache/remotecache_test.go index a67cbfa..2870e2a 100644 --- a/internal/remotecache/remotecache_test.go +++ b/internal/remotecache/remotecache_test.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "testing" + + "github.com/geekMus/markpic/internal/diskcache" ) func TestLookupNeedsSameDirectory(t *testing.T) { @@ -136,7 +138,7 @@ func TestDisabledCacheDoesNothing(t *testing.T) { // 太旧的记录在保存时被清掉(TTL 只用于清理,不参与命中判断)。 func TestPruneDropsStaleEntries(t *testing.T) { path := filepath.Join(t.TempDir(), "remote-cache.json") - stale := file{Version: 1, Entries: map[string]entry{ + stale := map[string]any{"version": 1, "entries": map[string]entry{ cacheKey("https://cdn.example.com/old.png", `C:\docs`): { Name: "old.png", Size: 10, CachedAt: 1, UsedAt: 1, }, @@ -168,7 +170,7 @@ func TestPruneKeepsMostRecentlyUsed(t *testing.T) { key := string(rune('a'+i%26)) + string(rune('0'+i%10)) + itoa(i) entries[key] = entry{Name: "x.png", Size: 1, UsedAt: int64(i)} } - prune(entries, int64(maxEntries+100)) + diskcache.PruneByUse(entries, maxEntries, func(e entry) int64 { return e.UsedAt }) if len(entries) != maxEntries { t.Fatalf("应该裁到 %d 条,实际 %d", maxEntries, len(entries)) } diff --git a/internal/uploadcache/uploadcache.go b/internal/uploadcache/uploadcache.go index 8ba13dd..248d66a 100644 --- a/internal/uploadcache/uploadcache.go +++ b/internal/uploadcache/uploadcache.go @@ -10,13 +10,11 @@ package uploadcache import ( - "encoding/json" - "os" - "path/filepath" - "sort" "strings" "sync" "time" + + "github.com/geekMus/markpic/internal/diskcache" ) // maxEntries 是缓存条数上限,超出后按「最后使用时间」淘汰最旧的。 @@ -25,6 +23,8 @@ const maxEntries = 4000 // TTL 是条目最长能用多久,超过就重新上传。 const TTL = 30 * 24 * time.Hour +// entry 的时间字段一律是 Unix 秒。早先是纳秒,两种单位混在一起最容易在 +// 「比较 / 排序 / 换算」上出错,统一成秒之后和下载缓存也对得上了。 type entry struct { URL string `json:"url"` Size int64 `json:"size"` @@ -33,11 +33,6 @@ type entry struct { UsedAt int64 `json:"usedAt"` } -type file struct { - Version int `json:"version"` - Entries map[string]entry `json:"entries"` -} - // Cache 是一个上传结果缓存。路径为空时所有操作都是空转(等于关掉)。 type Cache struct { mu sync.Mutex @@ -50,26 +45,27 @@ type Cache struct { // Open 读取缓存文件;文件不存在或读坏了都从空缓存开始(大不了重传一遍)。 func Open(path string) *Cache { - c := &Cache{path: path, entries: make(map[string]entry)} - if path == "" { - return c - } - raw, err := os.ReadFile(path) - if err != nil { - return c + c := &Cache{path: path} + entries, version := diskcache.Read[entry](path) + // 版本 1 存的是纳秒;就地换成秒,别让用户为一次改版白重传一轮。 + if version == 1 { + for key, e := range entries { + e.CachedAt /= int64(time.Second) + e.UsedAt /= int64(time.Second) + entries[key] = e + } } - var f file - if err := json.Unmarshal(raw, &f); err != nil || f.Entries == nil { - return c + if entries == nil { + entries = make(map[string]entry) } - c.entries = f.Entries + c.entries = entries return c } // Enabled 表示这个缓存是不是真的会落盘。 func (c *Cache) Enabled() bool { return c != nil && c.path != "" } -// key 把图床地址并进索引:换了图床就不该再复用旧地址。 +// cacheKey 把图床地址并进索引:换了图床就不该再复用旧地址。 func cacheKey(endpoint, path string) string { return strings.ToLower(strings.TrimRight(endpoint, "/")) + "\x00" + strings.ToLower(path) } @@ -81,17 +77,19 @@ func (c *Cache) Lookup(endpoint, path string, size, mtime int64) (string, bool) } c.mu.Lock() defer c.mu.Unlock() - e, ok := c.entries[cacheKey(endpoint, path)] + key := cacheKey(endpoint, path) + e, ok := c.entries[key] if !ok || e.URL == "" || e.Size != size || e.ModTime != mtime { return "", false } - if now := time.Now(); now.Sub(time.Unix(0, e.CachedAt)) > TTL { - delete(c.entries, cacheKey(endpoint, path)) + now := time.Now() + if now.Sub(time.Unix(e.CachedAt, 0)) > TTL { + delete(c.entries, key) c.dirty = true return "", false } - e.UsedAt = time.Now().UnixNano() - c.entries[cacheKey(endpoint, path)] = e + e.UsedAt = now.Unix() + c.entries[key] = e c.hits++ return e.URL, true } @@ -101,7 +99,7 @@ func (c *Cache) Store(endpoint, path string, size, mtime int64, url string) { if !c.Enabled() || url == "" { return } - now := time.Now().UnixNano() + now := time.Now().Unix() c.mu.Lock() c.entries[cacheKey(endpoint, path)] = entry{URL: url, Size: size, ModTime: mtime, CachedAt: now, UsedAt: now} c.stores++ @@ -143,59 +141,19 @@ func (c *Cache) Save() error { c.mu.Unlock() return nil } - merged := make(map[string]entry, len(c.entries)) - if raw, err := os.ReadFile(c.path); err == nil { - var f file - if json.Unmarshal(raw, &f) == nil { - for k, v := range f.Entries { - merged[k] = v - } - } - } - for k, v := range c.entries { - merged[k] = v - } - pruned := prune(merged, maxEntries) - c.entries = pruned - c.dirty = false path := c.path + entries := c.entries c.mu.Unlock() - data, err := json.MarshalIndent(file{Version: 1, Entries: pruned}, "", " ") + merged, err := diskcache.Save(path, entries, func(m map[string]entry) { + diskcache.PruneByUse(m, maxEntries, func(e entry) int64 { return e.UsedAt }) + }) if err != nil { return err } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return err - } - tmp := path + ".tmp" - if err := os.WriteFile(tmp, data, 0o644); err != nil { - return err - } - if err := os.Rename(tmp, path); err != nil { - _ = os.Remove(tmp) - return err - } + c.mu.Lock() + c.entries = merged + c.dirty = false + c.mu.Unlock() return nil } - -// prune 在超过上限时按最后使用时间留下最近的 limit 条。 -func prune(in map[string]entry, limit int) map[string]entry { - if len(in) <= limit { - return in - } - type kv struct { - key string - at int64 - } - all := make([]kv, 0, len(in)) - for k, v := range in { - all = append(all, kv{key: k, at: v.UsedAt}) - } - sort.Slice(all, func(i, j int) bool { return all[i].at > all[j].at }) - out := make(map[string]entry, limit) - for _, item := range all[:limit] { - out[item.key] = in[item.key] - } - return out -} diff --git a/internal/uploadcache/uploadcache_test.go b/internal/uploadcache/uploadcache_test.go index 22da6fc..ad0c4e3 100644 --- a/internal/uploadcache/uploadcache_test.go +++ b/internal/uploadcache/uploadcache_test.go @@ -73,7 +73,9 @@ func TestSaveMergesWhatIsAlreadyOnDisk(t *testing.T) { func TestExpiredEntryIsNotReused(t *testing.T) { path := filepath.Join(t.TempDir(), "cache.json") old := time.Now().Add(-TTL - time.Hour).UnixNano() - raw, err := json.Marshal(file{Version: 1, Entries: map[string]entry{ + // 版本 1 的缓存文件(时间字段是纳秒):打开时应当换算成秒, + // 而不是把用户的老缓存当成坏的丢掉。 + raw, err := json.Marshal(map[string]any{"version": 1, "entries": map[string]entry{ cacheKey("http://127.0.0.1:36677", `C:\pic\a.png`): { URL: "https://cdn/a.png", Size: 100, ModTime: 7, CachedAt: old, UsedAt: old, }, diff --git a/package.json b/package.json index b08282f..b6635b0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "markpic", "private": true, + "license": "MIT", "repository": { "type": "git", "url": "https://github.com/geekMus/MarkPic.git" }, "description": "Markdown image manager: upload local images to your PicGo host, check or download the remote ones. No installer, no local server, no command line.", "//": "任务入口:Node 脚本跨平台,真正的依赖在 web/package.json;需要 Node 20.19+。", diff --git a/scripts/build.mjs b/scripts/build.mjs index 789bd75..881275a 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -9,7 +9,6 @@ import { defaultExe, repoRoot } from './lib/paths.mjs'; import { ui } from './lib/ui.mjs'; import { buildGo, - ensureIconResource, resolveGo, runGoTest, targetGoarch, @@ -26,7 +25,6 @@ const HELP = ` 前端产物 internal/ui/dist 是 go:embed 的输入,不进版本库。 选项: - --web 兼容旧用法;现在默认就会构建前端 --no-web 跳过前端构建,直接编 Go(要求 internal/ui/dist 已存在) --test 编译前跑一遍 go test ./... --debug 编成调试模式(只扫描,不写文件、不上传) @@ -42,7 +40,6 @@ function parseCli(argv) { allowPositionals: false, strict: true, options: { - web: { type: 'boolean', default: false }, 'no-web': { type: 'boolean', default: false }, test: { type: 'boolean', default: false }, debug: { type: 'boolean', default: false }, @@ -56,7 +53,7 @@ function parseCli(argv) { } /** - * 供其它脚本复用:不解析命令行,只做「前端 → 测试 → 图标 → 编译 → 版本信息」。 + * 供其它脚本复用:不解析命令行,只做「前端 → 测试 → 编译 → 版本信息」。 */ export function buildProject(options = {}) { const go = options.go || resolveGo(options.goHint ?? ''); @@ -81,8 +78,6 @@ export function buildProject(options = {}) { runGoTest(go); } - ensureIconResource(go, target); - ui.step(`编译 exe(${target}/${targetGoarch()})`); ui.detail(`版本 ${version},提交 ${commit}`); buildGo({ go, output, version, commit, debug: Boolean(options.debug), target }); diff --git a/scripts/lib/go.mjs b/scripts/lib/go.mjs index b86d55e..2e03c08 100644 --- a/scripts/lib/go.mjs +++ b/scripts/lib/go.mjs @@ -116,42 +116,6 @@ export function buildGo(options) { return output; } -/** 图标资源是提交过的;只有删了才联网重新生成。 */ -export function ensureIconResource(go, target = targetGoos()) { - if (target !== 'windows') return; - const light = path.join(repoRoot, 'assets', 'icon-light.ico'); - const dark = path.join(repoRoot, 'assets', 'icon-dark.ico'); - const syso = path.join(repoRoot, 'cmd', 'markpic', 'rsrc_windows_amd64.syso'); - if (fs.existsSync(syso)) return; - if (!fs.existsSync(light) || !fs.existsSync(dark)) { - ui.warn('找不到 assets 下的 ico,exe 会使用默认图标。'); - return; - } - if (!isWindows) { - ui.warn('当前不是 Windows,跳过图标资源生成;交叉编译出来的 exe 没有自定义图标。'); - return; - } - ui.step('生成图标资源(只做一次)'); - try { - run( - go, - [ - 'run', - 'github.com/akavel/rsrc@latest', - '-ico', - `${light},${dark}`, - '-arch', - 'amd64', - '-o', - syso, - ], - { cwd: repoRoot, label: '生成图标资源' }, - ); - } catch (error) { - ui.warn(`图标资源没生成成功:${error.message}`); - } -} - /** 把版本信息与 asInvoker 清单写进 PE;失败不影响 exe 运行。 */ export function writeWinres(go, exe, version) { if (!isWindows) { diff --git a/scripts/lib/proc.mjs b/scripts/lib/proc.mjs index 3c1ae64..a304238 100644 --- a/scripts/lib/proc.mjs +++ b/scripts/lib/proc.mjs @@ -88,10 +88,6 @@ export function which(name) { return null; } -export function looksLikeFile(value) { - return Boolean(value) && isFile(expandHome(value)); -} - export function formatCommand(command, args = []) { const quote = (value) => { const text = String(value); @@ -273,11 +269,3 @@ export async function stopProcess(child, graceMs = 2500) { ]); if (!exited) killTree(child, 'SIGKILL'); } - -export function formatBytes(bytes) { - if (!Number.isFinite(bytes) || bytes < 0) return String(bytes); - if (bytes < 1024) return `${bytes} B`; - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; - if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`; - return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`; -} diff --git a/scripts/lib/ui.mjs b/scripts/lib/ui.mjs index 8671626..543d3fe 100644 --- a/scripts/lib/ui.mjs +++ b/scripts/lib/ui.mjs @@ -24,12 +24,4 @@ export const ui = { error(message) { console.error(paint(31, `错误:${message}`)); }, - blank() { - console.log(''); - }, }; - -export function fail(message) { - ui.error(message); - process.exit(1); -} diff --git a/scripts/lib/version.mjs b/scripts/lib/version.mjs index d596737..44ab8dc 100644 --- a/scripts/lib/version.mjs +++ b/scripts/lib/version.mjs @@ -1,5 +1,3 @@ -import crypto from 'node:crypto'; -import fs from 'node:fs'; import process from 'node:process'; import { git, gitOrNull } from './proc.mjs'; @@ -57,7 +55,3 @@ export function resolveCommit() { return text ? text.trim() : 'none'; } -export function sha256(file) { - return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); -} - diff --git a/scripts/release-notes.mjs b/scripts/release-notes.mjs index 7624298..263c508 100644 --- a/scripts/release-notes.mjs +++ b/scripts/release-notes.mjs @@ -53,7 +53,7 @@ for (const section of SECTIONS) { } /** 发版机器人自己写的提交、合并提交、纯版本号提交,都不进更新说明。 */ -export function shouldSkip(subject) { +function shouldSkip(subject) { const text = String(subject || '').trim(); if (!text) return true; if (/^merge\b/iu.test(text)) return true; @@ -63,7 +63,7 @@ export function shouldSkip(subject) { } /** 一条提交主题 → { key, text }:按「前缀:正文」归类,前缀认不出就归到 DEFAULT_SECTION。 */ -export function classify(subject) { +function classify(subject) { const cleaned = String(subject || '') .replace(/\s*\[[^\]]*\]\s*$/u, '') .trim(); @@ -75,7 +75,7 @@ export function classify(subject) { } /** git log 的「短 SHA \t 主题」文本 → 提交数组。 */ -export function parseGitLog(text) { +function parseGitLog(text) { const commits = []; for (const line of String(text || '').split('\n')) { if (!line.trim()) continue; @@ -89,7 +89,7 @@ export function parseGitLog(text) { } /** 提交数组 → { features: [...], improves: [...], ... },每项带好正文和短 SHA。 */ -export function groupCommits(commits) { +function groupCommits(commits) { const groups = {}; for (const section of SECTIONS) groups[section.key] = []; for (const commit of commits) { @@ -100,7 +100,7 @@ export function groupCommits(commits) { return groups; } -export function countGroups(groups) { +function countGroups(groups) { const counts = {}; for (const section of SECTIONS) counts[section.key] = (groups[section.key] || []).length; counts.total = SECTIONS.reduce(function (sum, section) { return sum + counts[section.key]; }, 0); @@ -108,7 +108,7 @@ export function countGroups(groups) { } /** 一句话摘要:写进 version.json 的 notes,程序里的「有新版本」对话框读的就是它。 */ -export function oneLineSummary(counts, isFirstRelease) { +function oneLineSummary(counts, isFirstRelease) { if (isFirstRelease) return '首个版本。'; const parts = []; if (counts.features) parts.push('新功能 ' + counts.features + ' 项'); @@ -126,7 +126,7 @@ function commitLink(repo, sha) { } /** 渲染成 GitHub Release 正文。 */ -export function renderNotes(options) { +function renderNotes(options) { const groups = options.groups; const counts = countGroups(groups); const lines = []; diff --git a/scripts/start.mjs b/scripts/start.mjs index 22ff284..3714a5d 100644 --- a/scripts/start.mjs +++ b/scripts/start.mjs @@ -87,29 +87,8 @@ function parsePort(raw, flag) { return port; } -/** - * 把 cmd/ 与 internal/ 下的 .go(加上 go.mod / go.sum)揉成一个指纹: - * 文件数、总字节、最新的修改时间。只要有一样变了就该重编。 - * - * 用轮询而不是 fs.watch:recursive 在各平台上支持得参差不齐,而这里要看的 - * 文件一共几百个,500ms 走一遍的开销可以忽略。 - */ -function goSourceStamp() { - let files = 0; - let bytes = 0; - let newest = 0; - - const note = (file) => { - try { - const stat = fs.statSync(file); - files += 1; - bytes += stat.size; - if (stat.mtimeMs > newest) newest = stat.mtimeMs; - } catch { - // 半秒前还在、现在没了:下一次轮询会看到变化。 - } - }; - +/** 走一遍 cmd/ 与 internal/ 下的 .go(加上 go.mod / go.sum),每个文件调一次 note。 */ +function eachGoSource(note) { const visit = (dir) => { let entries; try { @@ -130,52 +109,60 @@ function goSourceStamp() { for (const dir of WATCH_DIRS) visit(path.join(repoRoot, dir)); for (const file of WATCH_FILES) note(path.join(repoRoot, file)); - return `${files}:${bytes}:${newest}`; -} - -/** 编译记录跟在 exe 旁边(bin/.build-stamp.json),不进版本库。 */ -function buildStampPath() { - return path.join(path.dirname(defaultExe), '.build-stamp.json'); -} - -function readBuildStamp() { - try { - const parsed = JSON.parse(fs.readFileSync(buildStampPath(), 'utf8')); - return parsed && typeof parsed === 'object' ? parsed : null; - } catch { - return null; - } } /** - * 上一次编出来的 exe 还能不能用:源码指纹、版本号、提交号、调试开关四样都对得上, - * 而且 exe 本体没被换过(大小与写入时刻一致)。 + * 把上面那些文件揉成一个指纹:文件数、总字节、最新的修改时间。 + * 只要有一样变了就该重编。这个指纹只给监视器用。 * - * mtime 用整数毫秒判等,不靠比大小 —— 时钟回拨、文件被拷回来的情况都能挡住。 + * 用轮询而不是 fs.watch:recursive 在各平台上支持得参差不齐,而这里要看的 + * 文件一共几百个,500ms 走一遍的开销可以忽略。 */ -function buildIsFresh(stamp) { - const saved = readBuildStamp(); - if (!saved) return false; - if (saved.source !== stamp.source || saved.version !== stamp.version) return false; - if (saved.commit !== stamp.commit || saved.debug !== stamp.debug) return false; +function goSourceStamp() { + let files = 0; + let bytes = 0; + let newest = 0; + + eachGoSource((file) => { + try { + const stat = fs.statSync(file); + files += 1; + bytes += stat.size; + if (stat.mtimeMs > newest) newest = stat.mtimeMs; + } catch { + // 半秒前还在、现在没了:下一次轮询会看到变化。 + } + }); + + return `${files}:${bytes}:${newest}`; +} + +/** 参与编译的源码里最新的那个写入时刻:.go / go.mod / go.sum,外加嵌入的 dist/index.html。 */ +function newestSourceMtime() { + let newest = 0; + eachGoSource((file) => { + try { + const stat = fs.statSync(file); + if (stat.mtimeMs > newest) newest = stat.mtimeMs; + } catch { + // 文件刚好不在了:留给下一次启动判断。 + } + }); try { - const exe = fs.statSync(defaultExe); - return exe.size === saved.bytes && Math.round(exe.mtimeMs) === saved.mtimeMs; + const dist = fs.statSync(path.join(repoRoot, 'internal', 'ui', 'dist', 'index.html')); + if (dist.mtimeMs > newest) newest = dist.mtimeMs; } catch { - return false; + // 产物还没建;上面 ensureEmbeddedUi 会补。 } + return newest; } -function writeBuildStamp(stamp) { +/** exe 比上面每一份都新,才算不用重编。 */ +function exeIsFresh() { try { - const exe = fs.statSync(defaultExe); - fs.writeFileSync( - buildStampPath(), - `${JSON.stringify({ ...stamp, bytes: exe.size, mtimeMs: Math.round(exe.mtimeMs) }, null, 2)}\n`, - 'utf8', - ); + return fs.statSync(defaultExe).mtimeMs > newestSourceMtime(); } catch { - // 记不下来只是下次多编一遍,不影响启动。 + return false; } } @@ -184,7 +171,7 @@ function writeBuildStamp(stamp) { * * 一次 go build 约 2.4 秒、后面 winres 再 0.55 秒,是启动耗时里最大的一块; * 而绝大多数时候源码根本没变(改 .vue 有 Vite 热更新,连 exe 都不用换)。 - * 源码指纹、版本、提交、调试开关都对得上时,直接用 bin 里那份。 + * 只看时间:exe 比所有参与编译的文件都新,就直接用 bin 里那份。 * 想推翻这个判断:--rebuild,或者删掉 bin 里的 exe。 */ function ensureBuilt({ go, debug, force }) { @@ -192,13 +179,11 @@ function ensureBuilt({ go, debug, force }) { if (ensureEmbeddedUi()) force = true; const version = resolveBuildVersion(); const commit = resolveCommit(); - const stamp = { source: goSourceStamp(), version, commit, debug }; - if (!force && buildIsFresh(stamp)) { + if (!force && exeIsFresh()) { ui.detail('源码没变,跳过编译(要强制重编加 --rebuild)'); return; } - const built = buildProject({ go, debug, output: defaultExe, version, commit, web: false }); - writeBuildStamp({ source: stamp.source, version: built.version, commit: built.commit, debug }); + buildProject({ go, debug, output: defaultExe, version, commit, web: false }); } /** 盯着 Go 源码;变了就调 onChange。编辑器保存一次往往要写好几个文件,所以留一点防抖。 */ diff --git a/tools/winres/main.go b/tools/winres/main.go index 01c49ba..cbb1b5c 100644 --- a/tools/winres/main.go +++ b/tools/winres/main.go @@ -4,7 +4,7 @@ // rsrc_windows_amd64.syso 是给图标用的(rsrc 只做图标和清单,不做版本信息); // 再放第二个 .syso 会和它抢同一段 .rsrc,链接器不接受。所以版本信息和清单 // 统一走 Windows 自己的资源 API(BeginUpdateResource/UpdateResource), -// 在 build.ps1 里编译完之后原地打进去,不引入任何第三方依赖、不需要联网。 +// 在 scripts/build.mjs 里编译完之后原地打进去,不引入任何第三方依赖、不需要联网。 // // 这两样东西不是装饰:没有版本信息、没有 asInvoker 清单的未知 exe, // 杀毒软件和 SmartScreen 都更容易把它当成可疑样本。 @@ -269,8 +269,6 @@ func versionInfo(ver, product, company, desc, copyright string) []byte { // 不写 DPI 相关设置——DPI 感知是程序启动时自己调的(cmd/markpic/dpi_windows.go), // 清单里再写一遍会和它打架。 func manifestXML(ver string) string { - identity := strings.TrimSuffix(ver, ".0") // 清单版本要 4 段,但 1.0.0 更像发布版本号 - _ = identity return ` diff --git a/web/package.json b/web/package.json index 0234b77..99b00a7 100644 --- a/web/package.json +++ b/web/package.json @@ -2,12 +2,6 @@ "name": "markpic-web", "private": true, "type": "module", - "scripts": { - "dev": "vite", - "build": "vue-tsc --noEmit && vite build", - "preview": "vite preview", - "typecheck": "vue-tsc --noEmit" - }, "dependencies": { "vue": "^3.5.45" }, diff --git a/web/src/App.vue b/web/src/App.vue index 507bfe3..07fb97a 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -7,6 +7,7 @@ import AppIcon from './components/AppIcon.vue' import AppRail from './components/AppRail.vue' import CheckPage from './components/CheckPage.vue' import CloseConfirmDialog from './components/CloseConfirmDialog.vue' +import ConfirmDialog from './components/ConfirmDialog.vue' import DownloadPage from './components/DownloadPage.vue' import FileQueue from './components/FileQueue.vue' import OptionsPanel from './components/OptionsPanel.vue' @@ -19,15 +20,14 @@ import { pickFiles, pickFolder, revealPath, + setLang as pushLang, } from './api' import { useFileDrop } from './composables/useFileDrop' import { useHealth } from './composables/useHealth' import { cancelRowScan, - currentQueuePage, - queuePagePaths, + confirmImport, queuePagePendingPreview, - restoreQueuePage, retryRowScan, scanPaths, setQueuePage, @@ -44,7 +44,14 @@ import { JOB_VIEWS, modeOfView, viewOfMode, type JobView, type RemoteMode, type const queueRef = ref | null>(null) const { toasts, dismiss, warning, success, info } = useToasts() -const { t } = useI18n() +const { t, lang: uiLang } = useI18n() + +// 后端自己出文案(失败原因、提示),语言必须在启动时推一次、切换时再推一次。 +watch(uiLang, (next) => { + void pushLang(next).catch(() => { + // 后端没起来时推不进去:它回退到中文默认值,不该因此打断界面 + }) +}, { immediate: true }) const { resolved: theme, cycle: toggleTheme } = useTheme() // 窗口没有系统边框,缩放热区得由界面在四条边上铺出来 const { available: windowChrome, minimize, tray, quit, startResize } = useWindowControls() @@ -62,7 +69,7 @@ const { rememberCloseAction, update: updateSettings, discard: discardSettings, - snapshot: settingsSnapshot, + } = useSettings() const { @@ -74,7 +81,8 @@ const { isRunBusy, totalCount, completedCount, - revealTarget, + taskRows, + scanCardCount, connect, disconnect, addPaths, @@ -87,21 +95,9 @@ const { // 主视图 = 侧边栏上的菜单项。左边三项是作业视图(共用一条队列,区别只在远程图 // 怎么处理),右边两项是表单页(结果写到哪 / 怎么跑)。设置不再占用弹窗。 // -// 关掉再打开要回到上次停留的那一页:队列本来就是按页存的,回来时接着看。 -const VIEW_KEY = 'markpic.view' -const SAVED_VIEWS: readonly View[] = [...JOB_VIEWS, 'settings'] - -function readView(): View { - try { - const raw = window.localStorage.getItem(VIEW_KEY) - if (raw !== null && (SAVED_VIEWS as readonly string[]).includes(raw)) return raw as View - } catch { - /* 存不了就当没存过 */ - } - return 'convert' -} - -const view = ref(readView()) +// 每次启动都从第一个功能开始:不记住上次停在哪一页,也不恢复上一次的队列。 +// 程序没关的时候,三页之间照常来回切 —— 那是内存里的状态,不落盘。 +const view = ref('convert') /** 作业视图对应的远程图处理方式;表单页没有这个属性。 */ function jobModeOf(next: View): RemoteMode | null { @@ -122,16 +118,9 @@ const isFormView = computed(() => !isJobView.value) * 切菜单 = 换一页:转换里的文件、结果、进度留在转换,下载那一页还是它自己的样子; * 切回来接着看。跑着的那一轮不跟着画面走,它留在开始它的那一页上。 */ -const JOB_MODES: readonly RemoteMode[] = ['ignore', 'download', 'check'] - watch( view, (next) => { - try { - localStorage.setItem(VIEW_KEY, next) - } catch { - /* 存不下不影响切换 */ - } const nextMode = jobModeOf(next) if (nextMode === null) return setQueuePage(nextMode) @@ -159,7 +148,8 @@ const jobBusy = computed(() => isRunBusy(mode.value)) const jobProgress = computed(() => { let done = 0 let total = 0 - for (const row of rowViews.value) { + // 只按任务行算:文件夹卡片还没数图,混进分母会让进度条永远差一截。 + for (const row of taskRows.value) { const units = row.workTotal ?? 0 if (units <= 0) continue total += units @@ -274,27 +264,37 @@ const debug = computed(() => health.value?.debug === true) * 这些行参与不了这一轮 —— 图片数和远程地址都是跑之前就要算清的东西, * 带着一份没扫通的文件去跑,只会跑到一半才发现数不对。 */ -const scanBlocked = computed(() => rowViews.value.filter((row) => (row.scan ?? 'idle') !== 'ok')) +const scanBlocked = computed(() => taskRows.value.filter((row) => (row.scan ?? 'idle') !== 'ok')) /** 正在扫的行数:底栏据此说「正在扫描 2 个文件…」,而不是干灰着按钮。 */ const scanningCount = computed( - () => rowViews.value.filter((row) => (row.scan ?? 'idle') === 'scanning').length, + () => taskRows.value.filter((row) => (row.scan ?? 'idle') === 'scanning').length, ) -// 全都扫通了才允许开始。强行点击也进不来:handleRun 还要再判一次 canStart。 +/** + * 能不能开始:**只有文件卡片才算任务**。 + * + * 扫描卡片(文件夹 / 盘)不算 —— 它还没有被「确认导入」拆成一份份文档,用户也没 + * 表达过要处理里面哪些文件。以前这里只看「队列里有几行」,于是一张扫完的文件夹卡片 + * 就让「开始上传」亮着,点下去却什么也跑不了。 + * + * 强行点击也进不来:handleRun 还要再判一次 canStart。 + */ const canStart = computed( - () => !isRunBusy(mode.value) && rowViews.value.length > 0 && scanBlocked.value.length === 0, + () => !isRunBusy(mode.value) && taskRows.value.length > 0 && scanBlocked.value.length === 0, ) /** 按钮为什么是灰的:给底栏一句话,别让人对着禁用按钮猜。 */ const startHint = computed(() => { if (isRunBusy(mode.value)) return '' - if (rowViews.value.length === 0) return '' + if (taskRows.value.length === 0) { + // 队列里只有文件夹 / 盘:说清楚要先「确认导入」,别让人以为程序没反应。 + return scanCardCount.value > 0 ? t('footer.blocked.import') : '' + } if (scanningCount.value > 0) return t('footer.blocked.scanning', { count: scanningCount.value }) if (scanBlocked.value.length > 0) return t('footer.blocked.problem', { count: scanBlocked.value.length }) return '' }) -const canReveal = computed(() => revealTarget.value !== null) async function pick(kind: 'files' | 'folder'): Promise { try { @@ -339,53 +339,6 @@ function rememberPaths(paths: string[]): void { } } -/* 队列本身也记一份:关掉程序再打开,昨天拖进来的东西还在。 - 三页各记各的(转换 / 检测 / 下载),只记路径不记结果 —— 结果要重新扫一遍才算数。 */ -const QUEUE_KEY = 'markpic.queue' // 老版本只存一条队列,读一次当转换那一页的 -const QUEUES_KEY = 'markpic.queues' - -function strings(raw: unknown): string[] { - return Array.isArray(raw) ? raw.filter((item): item is string => typeof item === 'string') : [] -} - -function readQueues(): Partial> { - try { - const raw = JSON.parse(localStorage.getItem(QUEUES_KEY) ?? 'null') as unknown - if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) { - const out: Partial> = {} - for (const pageMode of JOB_MODES) { - out[pageMode] = strings((raw as Record)[pageMode]) - } - return out - } - } catch { - /* 存档坏了就当没有,下面再试老键 */ - } - try { - const legacy = JSON.parse(localStorage.getItem(QUEUE_KEY) ?? 'null') as unknown - return { ignore: strings(legacy) } - } catch { - return {} - } -} - -function writeQueues(): void { - try { - localStorage.setItem(QUEUES_KEY, JSON.stringify(queuePagePaths())) - } catch { - /* 存不下就算了,别为了记住路径把转换拦下来 */ - } -} - -/** - * 这一轮要用的设置 = 面板里那份 + 当前菜单决定的远程图模式。 - * 模式不在表单里(它是菜单),所以用覆盖的方式塞进去:既不会让「未保存」变真, - * 也不会被当成用户改过的设置写回文件。 - */ -function jobSettings() { - return settingsSnapshot({ remote: mode.value }) -} - /** * 扫一遍某一页里还没扫过的行(切到这一页时顺手做,别让三页在启动时抢网络)。 * @@ -394,18 +347,7 @@ function jobSettings() { function scanPage(pageMode: RemoteMode): void { const paths = queuePagePendingPreview(pageMode) if (paths.length === 0) return - void scanPaths(pageMode, paths, settingsSnapshot({ remote: pageMode })) -} - -/** 启动时把三页各自的队列接回来;正在跑的那一轮由 run.current 负责,别抢。 */ -async function restoreQueue(): Promise { - const saved = readQueues() - for (const pageMode of JOB_MODES) { - const paths = saved[pageMode] ?? [] - if (paths.length === 0 || isRunBusy(pageMode)) continue - restoreQueuePage(pageMode, paths) - } - if (!isRunBusy(mode.value)) scanPage(currentQueuePage()) + void scanPaths(pageMode, paths) } async function enqueue(paths: string[]): Promise { @@ -415,17 +357,45 @@ async function enqueue(paths: string[]): Promise { return } rememberPaths(added) - // 进队列就开始扫,但不等它:卡片先出来,扫完一份亮一份。 - void scanPaths(mode.value, added, jobSettings()) + // 先「发现」:拖进来的可能是文件(直接成一张文件卡),也可能是文件夹/盘 + // (先出扫描卡片,等用户确认导入再铺文件卡片)。 + void scanPaths(mode.value, added, true) } -/** 卡片上的「取消扫描」/「恢复扫描」「重试」。 */ +/** 待确认「停止扫描」的那一行;null 表示没有待确认的操作。 */ +const scanStopId = ref(null) + +/** + * 卡片上的「取消扫描」:先问一句再停。 + * + * 拖进来的是一个目录时,停下意味着「这个目录里还有没扫到的」—— 这是用户事后 + * 会追问的那句话,所以停下来之前先确认,停下来之后再说一遍。 + */ function handleCancelScan(id: string): void { + scanStopId.value = id +} + +function confirmStopScan(): void { + const id = scanStopId.value + scanStopId.value = null + if (id === null) return cancelRowScan(id) + warning(t('scan.stopped')) } function handleRetryScan(id: string): void { - retryRowScan(id, jobSettings()) + retryRowScan(id) +} + +/** + * 扫描卡片上的「确认导入」:把发现的文件铺成文件卡片,并开始统计图片数。 + * + * 文件是一次性交给后端的:路径池与文档槽在后端按机器能力限流,前端不需要 + * 自己算「同时开几个扫描」。 + */ +function handleConfirmImport(id: string): void { + const count = confirmImport(mode.value, id) + if (count > 0) success(t('toast.imported', { count })) } // 拖进窗口就等于加进队列;拦不住 drag 事件的话 WebView2 会把窗口导航到那个文件 const { active: dropActive } = useFileDrop({ @@ -441,16 +411,19 @@ const { active: dropActive } = useFileDrop({ }, }) +/** + * 开跑:只把**文件卡片**的路径交给后端。 + * + * 文件夹 / 盘留在队列里不动 —— 它们要先「确认导入」变成一张张文件卡片,才谈得上 + * 上传 / 检测 / 下载。这条规矩对三个作业页一视同仁。 + */ function handleRun(): void { if (!canStart.value) return - void start( - rowViews.value.map((row) => row.path), - jobSettings(), - ) + void start(taskRows.value.map((row) => row.path)) } async function handleSaveSettings(): Promise { - if (await saveSettings({ remote: mode.value })) await refreshHealth() + if (await saveSettings()) await refreshHealth() } /** @@ -468,16 +441,6 @@ async function handleRefreshHealth(): Promise { else info(t('toast.healthNotNeeded')) } -async function handleReveal(): Promise { - const target = revealTarget.value - if (target === null) return - try { - await revealPath(target) - } catch (error) { - warning(t('error.revealOutput', { detail: describeError(error, t('error.unknown')) })) - } -} - /** 行上的「在资源管理器里打开」:改完文档总要去看一眼 */ async function revealRow(path: string): Promise { try { @@ -519,7 +482,7 @@ function goView(next: View): void { }) } -/** Ctrl/Cmd + Enter 开始转换;Esc 收起点开的东西。弹窗优先,关于在设置之上。 */ +/** Esc 收起点开的东西。弹窗优先,关于在设置之上。 */ function handleKeydown(event: KeyboardEvent): void { const mod = event.ctrlKey || event.metaKey if (mod && event.key.toLowerCase() === 'o') { @@ -561,21 +524,6 @@ function handleKeydown(event: KeyboardEvent): void { return } } - if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { - // 表单页上回车是「保存」——底栏那个「开始」按钮不在这两页上 - if (isFormView.value) { - if (dirty.value) { - event.preventDefault() - void handleSaveSettings() - } - return - } - if (aboutOpen.value) return - if (canStart.value) { - event.preventDefault() - handleRun() - } - } } /** @@ -598,12 +546,6 @@ onMounted(() => { // 后端点叉号时调用;浏览器预览里没有这个函数,弹窗也就不会出现。 closeBridge.__markpicCloseRequest = handleCloseRequest connect() - // 队列记在本地;加进来/清掉时同步写一次 - watch( - () => [view.value, ...rowViews.value.map((row) => row.path)], - () => writeQueues(), - ) - window.setTimeout(() => void restoreQueue(), 700) // 首屏要这两份数据:拿到(或失败)再让原生窗口露面,别把半张空架子推给人。 void revealWindowWhenReady(Promise.allSettled([refreshHealth(), loadSettings()])) window.addEventListener('keydown', handleKeydown) @@ -683,6 +625,7 @@ onBeforeUnmount(() => { @clear="clearQueue" @cancel-scan="handleCancelScan" @retry-scan="handleRetryScan" + @confirm-import="handleConfirmImport" /> { @clear="clearQueue" @cancel-scan="handleCancelScan" @retry-scan="handleRetryScan" + @confirm-import="handleConfirmImport" /> { @clear="clearQueue" @cancel-scan="handleCancelScan" @retry-scan="handleRetryScan" + @confirm-import="handleConfirmImport" /> { { :remote-mode="mode" :busy="jobBusy" :can-start="canStart" - :can-reveal="canReveal" :debug="mode !== 'check' && debug" @run="handleRun" @cancel="cancel" - @reveal="handleReveal" /> @@ -779,6 +723,16 @@ onBeforeUnmount(() => { + + { return typeof value === 'object' && value !== null } @@ -64,7 +55,7 @@ function isRecord(value: unknown): value is Record { function toError(reply: Reply): ApiError { const code = reply.code ?? 'unknown' const message = (reply.message ?? '').trim() - return new ApiError(0, code, message || t('error.bridge')) + return new ApiError(code, message || t('error.bridge')) } /** 调一个 Go 侧方法,成功时返回 data。 */ @@ -72,13 +63,13 @@ async function call(method: string, params: unknown = {}): Promise { const bridge = window.markpic if (!bridge) { // 在浏览器里直接开 Vite 页面调试时没有 bridge,给一句能看懂的提示。 - throw new ApiError(0, 'no-bridge', t('error.noBridge')) + throw new ApiError('no-bridge', t('error.noBridge')) } let reply: Reply try { - reply = await bridge(method, JSON.stringify({ ...(isRecord(params) ? params : {}), lang: langHeader() })) + reply = await bridge(method, JSON.stringify(isRecord(params) ? params : {})) } catch (error) { - throw new ApiError(0, 'bridge-failed', error instanceof Error ? error.message : String(error)) + throw new ApiError('bridge-failed', error instanceof Error ? error.message : String(error)) } if (!reply || !reply.ok) { throw toError(reply ?? { ok: false, code: 'empty', message: '' }) @@ -109,18 +100,13 @@ export function isDialogUnsupported(error: unknown): boolean { return error instanceof ApiError && error.code === 'unsupported' } -/** 应用与数据目录的基本信息(语言由参数带上,Go 侧据此回本地化文案)。 */ -export type Hello = { - version: string - dataDir: string - dataNote: string - lang: string -} - -export function hello(lang: string): Promise { - return call('app.hello', { lang }) -} - +/** + * 告诉后端界面现在用哪种语言。 + * + * 后端回的文字(逐图失败原因、PicGo 提示、更新错误)由它自己出,所以语言得同步过去; + * 这是一条独立通道,不再随每次调用捎带 —— 以前 api.ts 给每个请求都塞一个 lang, + * 而后端从来没读过它,切到英文之后后台文案仍然是中文。 + */ export function setLang(lang: string): Promise<{ lang: string }> { return call<{ lang: string }>('i18n.set', { lang }) } @@ -133,7 +119,7 @@ export function getSettings(): Promise { return call('settings.get') } -export function putSettings(settings: Partial): Promise { +export function putSettings(settings: Settings): Promise { return call('settings.put', settings) } @@ -154,20 +140,17 @@ export async function pickFolder(): Promise { return data.paths } -export function preview(paths: string[], settings?: Partial): Promise { - return call('preview', { paths, settings }) -} - /** - * 让后端开扫一批文件。 + * 让后端开扫一批路径。 * - * 回来的只是「已经收下了」:每个文件扫完会推一条 scan.file 事件回来。 + * 回来的只是「已经收下了」:每个路径扫完会推一条 scan.file 事件回来。 * scanId 由前端生成,取消和事件归属都靠它认。 */ export function scanStart(params: { scanId: string paths: string[] - settings?: Partial + /** true = 只发现 Markdown(文件夹卡片);false = 逐份统计图片数(文件卡片)。 */ + discover?: boolean }): Promise { return call('scan.start', params) } @@ -177,19 +160,20 @@ export function cancelScan(params: { scanId: string; path?: string }): Promise<{ return call<{ cancelled: boolean }>('scan.cancel', params) } -export function startRun(paths: string[], settings?: Partial): Promise { - return call('run.start', { paths, settings }) +/** + * 开始一轮转换。 + * + * op 是用户点了什么(上传 / 检测 / 下载),不是设置:设置里那个 remote 说的是 + * 「文档里已经写着的网络图片怎么办」,跟这一轮做什么无关。 + */ +export function startRun(op: RunOp, paths: string[]): Promise { + return call('run.start', { op, paths }) } export function cancelRun(runId: string): Promise { return call('run.cancel', { runId }) } -/** Go 侧那一页现在在跑哪一轮、已经出了哪些结果(界面重载后靠它接回来)。 */ -export function getCurrentRun(mode?: RemoteMode): Promise { - return call('run.current', mode === undefined ? {} : { mode }) -} - export function revealPath(path: string): Promise { return call('reveal', { path }) } @@ -198,20 +182,15 @@ export function openTarget(target: string): Promise { return call('open', { target }) } -/** 当前更新状态(不联网,读的是 Go 侧记住的那份)。 */ +/** 更新检查 / 安装 / 状态。 */ export function getUpdateStatus(): Promise { return call('update.status') } -/** - * 检查更新。检查失败不会抛异常:Go 侧把原因写进 status.error, - * 这样对话框可以把它当成一种状态展示,而不是一个红色的请求失败。 - */ export function checkUpdate(): Promise { return call('update.check') } -/** 下载、校验、替换并重启。之后用 getUpdateStatus 轮询进度。 */ export function installUpdate(): Promise { return call('update.install') -} \ No newline at end of file +} diff --git a/web/src/assets/layout.css b/web/src/assets/layout.css index 9dc768f..45908bd 100644 --- a/web/src/assets/layout.css +++ b/web/src/assets/layout.css @@ -41,8 +41,8 @@ .group-card__head { display: flex; align-items: center; - gap: 12px; - padding: 12px 16px; + gap: 8px; + padding: 12px 14px; border-bottom: 1px solid var(--line); } @@ -138,16 +138,21 @@ flex: none; align-items: center; gap: 6px; + height: 24px; } +/* 徽标、查看详情、图标按钮共用 24px 高的一条基线,右边才齐 */ .badge { - padding: 1px 7px; + display: inline-flex; + align-items: center; + height: 24px; + padding: 0 9px; border: 1px solid var(--line); border-radius: var(--r-pill); background: var(--panel-2); color: var(--ink-2); font-size: var(--fs-1); - line-height: 1.6; + line-height: 1; white-space: nowrap; } @@ -232,10 +237,24 @@ display: inline-flex; flex: none; align-items: center; - gap: 6px; + gap: 4px; + height: 24px; + padding: 0 8px; + border: 1px solid transparent; + border-radius: var(--r-pill); color: var(--ink-3); font-size: var(--fs-1); + line-height: 1; white-space: nowrap; + transition: + color var(--t-fast) var(--ease), + background var(--t-fast) var(--ease); +} + +.group-card__head:hover .group-card__more, +.group-card__head:focus-within .group-card__more { + color: var(--ink-2); + background: var(--panel-2); } .group-card__more--on { @@ -249,8 +268,25 @@ display: flex; flex: none; align-items: center; - gap: 2px; + gap: 4px; margin-left: 2px; + padding-right: 2px; +} + +.group-card__import { + margin-right: 6px; +} + +/* 扫描卡片的文件清单:只在展开后的折叠区里出现。 + 外层不留内边距(否则收起时 0fr 的格子里还会露出那点空白), + 内边距加在清单根元素上,收起来时跟着一起被裁掉。 */ +.group-card__scan { + min-height: 0; + overflow: hidden; +} + +.group-card__scan-list { + padding: 4px 14px 10px; } .group-card__tools .icon-btn { @@ -275,6 +311,10 @@ } .group-card__chev { + display: inline-grid; + place-items: center; + width: 14px; + height: 14px; transition: transform 200ms var(--ease); } @@ -298,3 +338,55 @@ .group-card__fold--open { grid-template-rows: 1fr; } + +/* 窗口窄的时候,扫描卡头右侧的徽标/按钮会把文档名挤没:只让扫描卡片换行, + 名字至少留 160px,按钮组掉到下一行靠右。上传页的 FileRow 用同一套做法。 */ +@media (max-width: 820px) { + .group-card__head--scan { + flex-wrap: wrap; + row-gap: 6px; + } + + .group-card__head--scan .group-card__text { + min-width: 160px; + } + + .group-card__head--scan .group-card__badges { + flex-wrap: wrap; + justify-content: flex-end; + } + + .group-card__head--scan .group-card__tools { + flex-wrap: wrap; + justify-content: flex-end; + margin-left: auto; + row-gap: 4px; + padding-bottom: 10px; + } +} + +/* 再窄一档:所有卡片都折成两行(名字一行,徽标与按钮一行),否则 270px 的卡 + 连文档名都放不下。 */ +@media (max-width: 620px) { + .group-card__head { + flex-wrap: wrap; + row-gap: 6px; + } + + .group-card__head .group-card__text { + min-width: 160px; + } + + .group-card__head .group-card__badges { + flex-wrap: wrap; + justify-content: flex-end; + } + + .group-card__head .group-card__tools { + flex-wrap: wrap; + justify-content: flex-end; + margin-left: auto; + row-gap: 4px; + padding-bottom: 10px; + } +} diff --git a/web/src/components/AppFooter.vue b/web/src/components/AppFooter.vue index f7bc683..6838679 100644 --- a/web/src/components/AppFooter.vue +++ b/web/src/components/AppFooter.vue @@ -7,12 +7,18 @@ import { useI18n, type MessageKey } from '../i18n' const props = defineProps<{ stats: RunStats phase: RunPhase + /** + * 队列里还有几张「文件夹 / 盘」扫描卡片等着确认导入。 + * + * 它们不算任务(不参与开始、不参与计数),但用户必须知道它们还在那儿 —— + * 否则「队列里有 3 行,底栏却说 0 个文件」看着像丢了东西。 + */ + pendingFolders?: number /** 远程图模式:调试构建 + 下载模式下,「没动的远程图」是这一轮没去下,不是按策略保留。 */ remoteMode?: 'ignore' | 'check' | 'download' busy: boolean canStart: boolean - canReveal: boolean - /** 调试构建:整轮只扫描、不写文件,所以「打开输出目录」必然打空。 */ + /** 调试构建:这一轮不写文件,有些读数得换个说法(见 remoteKept)。 */ debug: boolean /** * 另一页正在跑时的一句说明(「转换 正在运行」)。 @@ -33,7 +39,6 @@ const props = defineProps<{ const emit = defineEmits<{ run: [] cancel: [] - reveal: [] }>() const { t } = useI18n() @@ -64,19 +69,18 @@ function countText(key: MessageKey, count: number): string { /** 状态栏读数:文件数、引用数,跑完之后追加替换与失败计数。 */ const parts = computed(() => { const stats = props.stats + const folders = props.pendingFolders ?? 0 + // 队列里只剩文件夹卡片:既不是「空队列」,也不该说「0 个文件」——直接讲清楚 + // 它们还等着确认导入。 + if (stats.files === 0 && folders > 0) { + const list: Part[] = [{ text: countText('footer.folders', folders), tone: 'plain' }] + if (props.busyElsewhere) list.push({ text: props.busyElsewhere, tone: 'warn' }) + return list + } if (stats.files === 0) return [{ text: t('footer.queueEmpty'), tone: 'plain' }] - // 队列里还留着目录行时,说「1 个文件」会让粘了整个目录的人以为只处理一篇; - // 目录行开跑之后会展开成一行一个文档,所以这里只在还没展开的时候改口。 - const dirs = stats.dirs - const filesOnly = stats.files - dirs - const filePart: Part = - dirs === 0 - ? { text: countText('footer.files', stats.files), tone: 'plain' } - : filesOnly === 0 - ? { text: t('footer.dirsOnly', { dirs }), tone: 'plain' } - : { text: t('footer.filesAndDirs', { files: filesOnly, dirs }), tone: 'plain' } - const list: Part[] = [filePart] + const list: Part[] = [{ text: countText('footer.files', stats.files), tone: 'plain' }] + if (folders > 0) list.push({ text: countText('footer.folders', folders), tone: 'plain' }) if (props.busyElsewhere) list.push({ text: props.busyElsewhere, tone: 'warn' }) list.push( stats.images > 0 @@ -220,13 +224,7 @@ const parts = computed(() => { return list }) -// 调试构建没有真正写出文件,别给一个必然失败的「打开输出目录」 -const showReveal = computed( - () => - props.canReveal && !props.debug && (props.phase === 'done' || props.phase === 'cancelled'), -) -const showShortcut = computed(() => props.canStart && !props.busy)