From 8e6e6bd3afbab16214463105e06c013687b20d21 Mon Sep 17 00:00:00 2001 From: Mus Date: Thu, 19 Nov 2026 18:50:53 +0800 Subject: [PATCH 01/17] =?UTF-8?q?=E9=87=8D=E6=9E=84=EF=BC=9A=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E7=B1=BB=E5=9E=8B=E4=B8=8E=E8=AE=BE=E7=BD=AE=E5=88=86?= =?UTF-8?q?=E7=A6=BB=EF=BC=8C=E7=BB=9F=E8=AE=A1=E6=95=B0=E5=AD=97=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E7=94=B1=E5=90=8E=E7=AB=AF=E4=B8=8B=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按「前端负责页面与展示、后端负责计算与持久化、边界只传意图与状态」重整 bridge: - run.start 改为 {op, paths}:op 是 upload / check / download,不再把页面名 塞进 settings.remote 让后端反推;同一 op 只允许一轮 - settings.put 只保留「整份读、整份写」一条通道,删除 12 字段的增量补丁与 configOf 的合并逻辑 - 事件携带这一轮的累计 summary(file.progress / file.finished),前端删除 LiveCounters 与两份 20+ 字段的手工映射,跑动中和跑完后的口径不可能再打架 - scan.file 按请求路径聚合(目录就是一条结果带展开的文件),前端不再用路径 前缀去猜目录归属 - 删除 preview、app.hello、run.current 与 SSE 重连残留(run.current 服务的 「刷新页面接回」在 WebView2 里本就不可达) - 修复语言从未同步给后端:切到英文后后台文案仍是中文;改为启动/切换时推一次 i18n.set,不再给每个请求捎带一个没人读的 lang 工具链顺带清理:删除无调用方的导出与 ensureIconResource、start.mjs 的构建戳 改回 mtime 规则、release.yml 删掉三段阶段小结、清理工作流改为手动触发。 验证:go test ./internal/... 全绿;go build 与 vue-tsc --noEmit 通过;真实窗口 用本地 mock 图床跑过上传(含内容去重)、检测、运行中取消与中英文切换。 --- .../cleanup-obsolete-workflow-runs.yml | 5 +- .github/workflows/release.yml | 115 +------- docs/API.md | 17 +- docs/API.zh-CN.md | 13 +- docs/build.md | 3 +- docs/build.zh-CN.md | 1 + internal/app/app.go | 27 +- internal/app/app_test.go | 262 ++++++++-------- internal/app/dispatch.go | 31 -- internal/app/preview.go | 38 --- internal/app/runs.go | 178 +++++------ internal/app/scan.go | 114 ++++--- internal/app/settings.go | 100 ++----- internal/conv/remote.go | 11 +- internal/conv/run.go | 76 ++--- internal/conv/runner.go | 49 +++ internal/i18n/i18n.go | 5 + scripts/build.mjs | 7 +- scripts/lib/go.mjs | 36 --- scripts/lib/proc.mjs | 12 - scripts/lib/ui.mjs | 8 - scripts/lib/version.mjs | 6 - scripts/release-notes.mjs | 14 +- scripts/start.mjs | 109 +++---- tools/winres/main.go | 4 +- web/package.json | 6 - web/src/App.vue | 34 +-- web/src/api.ts | 77 ++--- web/src/composables/useRun/commands.ts | 74 +---- web/src/composables/useRun/events.ts | 279 ++++++++---------- web/src/composables/useRun/page.ts | 13 - web/src/composables/useRun/rows.ts | 85 +----- web/src/composables/useRun/scan.ts | 18 +- web/src/composables/useRun/stats.ts | 109 +++---- web/src/composables/useRun/types.ts | 9 - web/src/composables/useSettings.ts | 13 +- web/src/i18n/en.ts | 11 +- web/src/i18n/index.ts | 13 - web/src/i18n/zh.ts | 11 +- web/src/types.ts | 31 +- 40 files changed, 732 insertions(+), 1292 deletions(-) delete mode 100644 internal/app/preview.go 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/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/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..f260b58 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -71,27 +71,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 +92,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 +136,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 +218,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 +238,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 +256,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 +281,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 +324,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 +336,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 +365,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 +398,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 秒内跑完") } } 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/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..4ec8662 100644 --- a/internal/app/scan.go +++ b/internal/app/scan.go @@ -17,13 +17,13 @@ import ( // preview:界面点一下、Go 在 UI 线程上把整批文件扫完才返回。十个文件就是十次串行 // 读盘,慢的时候界面整段冻住,卡片也只能等全部扫完才出现。 // -// 现在拆成异步的 scan.start / scan.cancel: +// 现在是异步的 scan.start / scan.cancel: // - start 立刻返回,每个文件一个 goroutine,并发度按机器核数给上限; -// - 每个文件扫完就推一条 scan.file,界面按路径把结果贴回自己那张卡片; -// - 单个文件有独立 context,可以单独取消,也可以整批取消; -// - 每个文件有 20 秒上限:某个网络盘上的文件卡住,也不会让「开始」永远点不了。 +// - 每个请求路径扫完就推一条 scan.file,界面按路径把结果贴回自己那张卡片; +// - 单个路径有独立 context,可以单独取消,也可以整批取消; +// - 每个路径有 20 秒上限:某个网络盘上的文件卡住,也不会让「开始」永远点不了。 const ( - // scanFileTimeout 是单个文件的扫描上限。扫描只读文件、不发网络请求, + // scanFileTimeout 是单个路径的扫描上限。扫描只读文件、不发网络请求, // 正常文档是毫秒级的;给到 20 秒是留给网络盘和超大文档的余量。 scanFileTimeout = 20 * time.Second // scanMinParallel / scanMaxParallel 夹住并发度:太少体现不出并发, @@ -32,25 +32,25 @@ const ( scanMaxParallel = 6 ) -// scanParallelism 按机器核数给并发上限:一半核数,夹在 [2, 6],且不超过文件数。 -func scanParallelism(files int) int { - n := runtime.NumCPU() / 2 - if n < scanMinParallel { - n = scanMinParallel +// scanParallelism 按机器核数给并发上限:一半核数,夹在 [2, 6],且不超过路径数。 +func scanParallelism(n int) int { + parallel := runtime.NumCPU() / 2 + if parallel < scanMinParallel { + parallel = scanMinParallel } - if n > scanMaxParallel { - n = scanMaxParallel + if parallel > scanMaxParallel { + parallel = scanMaxParallel } - if files > 0 && files < n { - n = files + if n > 0 && n < parallel { + parallel = n } - if n < 1 { - n = 1 + if parallel < 1 { + parallel = 1 } - return n + return parallel } -// scanSession 是一批扫描的句柄:整批一个 context,每个文件再挂一个自己的。 +// scanSession 是一批扫描的句柄:整批一个 context,每个路径再挂一个自己的。 type scanSession struct { app *App scanID string @@ -58,7 +58,7 @@ type scanSession struct { cancel context.CancelFunc mu sync.Mutex - files map[string]context.CancelFunc // 路径 → 该文件的取消函数 + paths map[string]context.CancelFunc // 路径 → 该路径的取消函数 } // stop 取消整批扫描。 @@ -68,11 +68,11 @@ func (s *scanSession) stop() { } } -// 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 +82,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 +98,8 @@ 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"` } // startScan 立刻返回,真正的扫描在后台按并发度跑。 @@ -110,21 +109,25 @@ 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() @@ -134,7 +137,7 @@ func (a *App) startScan(params json.RawMessage) (any, error) { scanID: req.ScanID, ctx: ctx, cancel: cancel, - files: make(map[string]context.CancelFunc, len(paths)), + paths: make(map[string]context.CancelFunc, len(paths)), } a.mu.Lock() @@ -151,27 +154,15 @@ 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() -} - +// scanOne 是「一个请求路径」的扫描结果。 +// +// 目录是一等公民:用户拖进来的是一个目录,就该有一条对应该目录的结果,里面带上 +// 它展开出来的文件。以前这里只回一串平铺的文件,界面只好拿路径前缀自己去猜 +// 「哪几个文件属于这个目录、加起来几张图」—— 展开规则在 Go 这边,界面不该重算。 type scanOne struct { path string files []conv.FileResult @@ -180,10 +171,17 @@ type scanOne struct { } 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) @@ -193,7 +191,7 @@ func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) wg.Add(1) go func(path string) { defer wg.Done() - s.scanFile(cfg, lang, path, sem) + s.scanPath(cfg, lang, path, sem) }(path) } @@ -207,7 +205,7 @@ 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{}) { +func (s *scanSession) scanPath(cfg settings.Settings, lang i18n.Lang, path string, sem chan struct{}) { fileCtx, cancelFile := context.WithCancel(s.ctx) s.register(path, cancelFile) defer s.unregister(path) @@ -228,7 +226,7 @@ func (s *scanSession) scanFile(cfg settings.Settings, lang i18n.Lang, path strin done := make(chan []conv.FileResult, 1) go func() { - // 每个文件一个 Runner:Runner 内部带状态,多个文件共用一份会互相踩。 + // 每个路径一个 Runner:Runner 内部带状态,多个文件共用一份会互相踩。 runner := conv.NewRunner(cfg, lang, "preview", nil).UsePreview() files, _ := runner.RunCollect(fileCtx, []string{path}) done <- files @@ -294,7 +292,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/remote.go b/internal/conv/remote.go index eb28a93..12e4dd8 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() } 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..8d2111f 100644 --- a/internal/conv/runner.go +++ b/internal/conv/runner.go @@ -122,6 +122,17 @@ type Runner struct { // remoteCache 是跨运行的下载记录:上次已经下过、文件还在且大小对得上, // 就不再打一次网络。为 nil 或路径为空时等于关掉。 remoteCache *remotecache.Cache + + // runMu/runSum 是「这一轮到目前为止」的累计汇总:每处理完一个文件就并一次, + // 随 file.progress / file.finished 一起发出去。 + // + // 为什么由后端算:界面要在跑动中显示「替换了几处、失效几张、失败几张」。 + // 以前这些数由前端按事件自己加减(二十几个字段各来一遍),后端跑完又发一份 + // 汇总把它整个盖掉 —— 同一份数字两个算法,口径一旦有一处不同就当场对不上。 + // 现在只有一个算法,界面只负责显示。 + runMu sync.Mutex + runSum Summary + runAt time.Time } // abortsAfterFailures 是「认定图床不可用」的连续失败张数。 @@ -321,6 +332,44 @@ func (r *Runner) takeDoc(path string, data []byte) *mdscan.Document { return doc } +// 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/i18n/i18n.go b/internal/i18n/i18n.go index 1d4144d..19b1492 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -145,6 +145,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" @@ -575,6 +576,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/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..25c8937 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -19,6 +19,7 @@ import { pickFiles, pickFolder, revealPath, + setLang as pushLang, } from './api' import { useFileDrop } from './composables/useFileDrop' import { useHealth } from './composables/useHealth' @@ -44,7 +45,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 +70,7 @@ const { rememberCloseAction, update: updateSettings, discard: discardSettings, - snapshot: settingsSnapshot, + } = useSettings() const { @@ -377,15 +385,6 @@ function writeQueues(): void { } } -/** - * 这一轮要用的设置 = 面板里那份 + 当前菜单决定的远程图模式。 - * 模式不在表单里(它是菜单),所以用覆盖的方式塞进去:既不会让「未保存」变真, - * 也不会被当成用户改过的设置写回文件。 - */ -function jobSettings() { - return settingsSnapshot({ remote: mode.value }) -} - /** * 扫一遍某一页里还没扫过的行(切到这一页时顺手做,别让三页在启动时抢网络)。 * @@ -394,7 +393,7 @@ function jobSettings() { function scanPage(pageMode: RemoteMode): void { const paths = queuePagePendingPreview(pageMode) if (paths.length === 0) return - void scanPaths(pageMode, paths, settingsSnapshot({ remote: pageMode })) + void scanPaths(pageMode, paths) } /** 启动时把三页各自的队列接回来;正在跑的那一轮由 run.current 负责,别抢。 */ @@ -416,7 +415,7 @@ async function enqueue(paths: string[]): Promise { } rememberPaths(added) // 进队列就开始扫,但不等它:卡片先出来,扫完一份亮一份。 - void scanPaths(mode.value, added, jobSettings()) + void scanPaths(mode.value, added) } /** 卡片上的「取消扫描」/「恢复扫描」「重试」。 */ @@ -425,7 +424,7 @@ function handleCancelScan(id: string): void { } function handleRetryScan(id: string): void { - retryRowScan(id, jobSettings()) + retryRowScan(id) } // 拖进窗口就等于加进队列;拦不住 drag 事件的话 WebView2 会把窗口导航到那个文件 const { active: dropActive } = useFileDrop({ @@ -443,14 +442,11 @@ const { active: dropActive } = useFileDrop({ function handleRun(): void { if (!canStart.value) return - void start( - rowViews.value.map((row) => row.path), - jobSettings(), - ) + void start(rowViews.value.map((row) => row.path)) } async function handleSaveSettings(): Promise { - if (await saveSettings({ remote: mode.value })) await refreshHealth() + if (await saveSettings()) await refreshHealth() } /** diff --git a/web/src/api.ts b/web/src/api.ts index 9af3b1a..75388cf 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,16 +1,14 @@ import type { - CurrentRun, DialogResult, Health, OkResult, - PreviewResult, - RemoteMode, + RunOp, RunStartResult, ScanStartResult, Settings, UpdateStatus, } from './types' -import { langHeader, t } from './i18n' +import { t } from './i18n' /** * 界面与 Go 之间的通道。 @@ -40,22 +38,15 @@ declare global { /** 统一的 API 错误:保留服务端的错误码与服务端给的文案。 */ export class ApiError extends Error { - readonly status: number readonly code: string - constructor(status: number, code: string, message: string) { + constructor(code: string, message: string) { super(message) this.name = 'ApiError' - this.status = status this.code = code } } -/** 旧文案里会提到「本地服务」;现在没有服务了,保留这个函数只为兼容调用点。 */ -export function serviceOrigin(): string { - return 'MarkPic' -} - function isRecord(value: unknown): value is Record { 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,15 @@ 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 }): Promise { return call('scan.start', params) } @@ -177,19 +158,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 +180,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/composables/useRun/commands.ts b/web/src/composables/useRun/commands.ts index 075fc73..9c0afc9 100644 --- a/web/src/composables/useRun/commands.ts +++ b/web/src/composables/useRun/commands.ts @@ -4,14 +4,13 @@ * 每一个都只管「这一页」(activePage)—— 起跑记下 owner,之后切页也不影响进度往哪写。 * 请求都是异步的:飞在路上时用户可能已经切页,所以返回值一律用 withPage(owner, …) 写回。 */ -import { markRaw } from 'vue' import { cancelRun as requestCancelRun, describeError, startRun as requestStartRun } from '../../api' -import type { PreviewResult, RemoteMode, Settings } from '../../types' +import type { RemoteMode, RunOp } from '../../types' import { t } from '../../i18n' import { useHealth } from '../useHealth' import { useToasts } from '../useToasts' import { connected } from './events' -import { activePage, nextLocalId, pages, phase, rows, runId, savePage, summary, withPage } from './page' +import { activePage, nextLocalId, phase, rows, runId, summary, withPage } from './page' import { pathKey, splitPath } from './paths' import { cancelTimers, clearCancelTimer, clearRunning, markRunning, runningDebug, runningModes } from './running' import { @@ -32,14 +31,12 @@ export function resetRowsForRun(): void { row.phase = 'queued' row.uploaded = 0 row.liveItems = undefined - row.counted = undefined row.total = row.images ?? 0 row.workTotal = workUnitsIn(row.result, activePage) row.workDone = 0 // 上一轮的结果先留着:检测页/下载页的正文是「地址表」「远程→本地」, // 一开跑就清空会让正片在跑的时候变成空白页,看着像崩了。 // 这一轮每跑完一个文件,事件会把这个文件的结果换掉。 - row.scored = false } liveReset() seedImagesFromRows() @@ -93,65 +90,14 @@ export function addPaths(input: string[]): string[] { return added } -/** - * 用 /api/preview 的结果补齐队列行的图片数量(目录行按前缀汇总)。 - * - * 只更新这一次真的预检过的行:预览请求带的是刚加进来的那几个路径,返回的也只有它们 - * (以及目录里的文件)。早先对每一行都套这个结果,于是「先加一个目录、再加一个别的文件」 - * 会把那个目录的图片数从 4 改成 1,甚至把它标成「找不到」—— 新的预览结果里本来就没有它。 - */ -/** - * 把预检结果写进某一页。 - * - * 启动恢复时三页是连着扫的,扫到第三页时画面可能还在第一页 —— 所以结果要按「哪一页」 - * 落,不能按「当前 rows」落,否则预检白扫(行上的张数永远停在「待统计」)。 - */ -export function applyPreviewOn(mode: RemoteMode, result: PreviewResult, touched: readonly string[]): void { - if (mode === activePage) savePage() - const byPath = new Map(result.files.map(file => [pathKey(file.path), file])) - const touchedKeys = new Set(touched.map(pathKey)) - - for (const row of pages[mode].rows) { - const rowKey = pathKey(row.path) - if (!touchedKeys.has(rowKey) && !byPath.has(rowKey)) continue - const exact = byPath.get(pathKey(row.path)) - if (exact) { - // 预检结果也留在行上:行的 images 有了,逐图明细(L 行)才有出处, - // 否则展开一行 8 张图的文件会得到「没有可处理的本地图片」这种自相矛盾的话。 - if (!row.result) row.result = markRaw(exact) - row.images = exact.images - row.total = exact.images - row.missing = false - row.isDir = false - continue - } - - const prefix = `${pathKey(row.path)}\\` - let sum = 0 - let matched = false - for (const file of result.files) { - if (pathKey(file.path).startsWith(prefix)) { - sum += file.images - matched = true - } - } - // 预览返回的是「真正找到的文件」;什么都没匹配上说明这个路径不存在, - // 或者目录里没有 Markdown —— 明确说出来,别让行停在「待统计」。 - if (matched) { - row.images = sum - row.total = sum - row.missing = false - // 按前缀匹配上的,说明这一行是目录而不是某个具体文档。 - row.isDir = true - } else { - row.missing = true - } - } - - if (mode === activePage) seedImagesFromRows() +/** 页面 → 操作。三页各自对应的就是这三个动作,和设置里的 remote 无关。 */ +const OP_OF_PAGE: Record = { + ignore: 'upload', + check: 'check', + download: 'download', } -export async function start(paths: string[], settings: Settings): Promise { +export async function start(paths: string[]): Promise { const owner = activePage if (runningModes.has(owner)) return false if (paths.length === 0) { @@ -174,7 +120,7 @@ export async function start(paths: string[], settings: Settings): Promise() @@ -56,10 +57,54 @@ export function isRunEvent(value: unknown): value is RunEvent { return typeof record.runId === 'string' } +/** + * run.started 带的是操作名(upload / check / download),页面叫 ignore / check / download。 + * 两者不是同一套取值:一个说的是「用户点了什么」,一个说的是「文档里的网络图片怎么办」。 + */ +const PAGE_OF_OP: Record = { + upload: 'ignore', + check: 'check', + download: 'download', +} + export function matches(eventRunId: string): boolean { return runId.value !== null && runId.value === eventRunId } +/** + * 把后端带回来的累计汇总落到这一页上。 + * + * 只做一件事:覆盖。数字是后端算的,界面不再自己加减 —— 这也是「跑动中的数和跑完的数 + * 永远一致」的唯一保证。 + */ +function applySummary(next: RunSummary | undefined): void { + if (!next) return + summary.value = next + live.images = next.images + live.uploaded = next.uploaded + live.reused = next.reused + live.uploadRequests = next.uploadRequests ?? 0 + live.failed = next.failedImages + live.ok = next.ok + live.partial = next.partial + live.failedFiles = next.failed + live.noImages = next.noImages + live.localized = next.localized ?? 0 + live.localizedUnique = next.localizedUnique ?? 0 + live.remoteChecked = next.remoteChecked ?? 0 + live.remoteCheckedUnique = next.remoteCheckedUnique ?? 0 + live.remoteDead = next.remoteDead ?? 0 + live.remoteDeadUnique = next.remoteDeadUnique ?? 0 + live.remoteFailed = next.remoteFailed ?? 0 + live.remoteFailedUnique = next.remoteFailedUnique ?? 0 + live.remoteUnsupported = next.remoteUnsupported ?? 0 + live.localMissing = next.localMissing ?? 0 + live.remoteKept = next.remoteKept ?? 0 + live.filesChecked = next.filesChecked ?? 0 + live.remoteReused = next.remoteReused ?? 0 + live.abortReason = next.abortReason ?? '' +} + /** * 把一条事件送回它自己那一页。 * @@ -72,9 +117,10 @@ export function onSignal(event: RunEvent): void { onScanEvent(event) return } + const startedOp = event.type === 'run.started' ? event.mode : undefined const owner = - event.type === 'run.started' && (event.mode === 'ignore' || event.mode === 'check' || event.mode === 'download') - ? event.mode + startedOp !== undefined && startedOp in PAGE_OF_OP + ? PAGE_OF_OP[startedOp as RunOp] : 'runId' in event ? modeOfRun(event.runId) : null @@ -111,7 +157,6 @@ export function applyRunEvent(event: RunEvent, owner: RemoteMode): void { if (!matches(event.runId)) return const row = rowAt(event.id) if (!row) return - live.images += event.total - (row.images ?? row.total) // 进度是「这一篇处理了几张图」,不是「替换了几处」:只检测/只下载时上传数是 0, // 以前把进度累加进 uploaded,页脚会闪出「替换 13」这种没发生过的数字。 row.phase = 'running' @@ -125,23 +170,13 @@ export function applyRunEvent(event: RunEvent, owner: RemoteMode): void { // 「已取回」/「失败」。整份重发的话,一篇上万条明细会把事件通道撑爆。 seedLiveItems(row) if (row.liveItems && event.items?.length) { - const counted = row.counted ?? (row.counted = new Set()) for (const patch of event.items) { if (patch.index < 0 || patch.index >= row.liveItems.length) continue - // 页脚的「替换」也按刚处理完的引用走:卡片显示「已替换 4」而页脚还是 - // 「替换 0」会像没动。每处只记一次,进度事件重放不会把数字算重。 - const status = patch.item.status - if ( - !counted.has(patch.index) && - (status === 'uploaded' || status === 'reused' || status === 'cached') - ) { - counted.add(patch.index) - row.uploaded += 1 - live.uploaded += 1 - } row.liveItems[patch.index] = patch.item } } + // 页脚那几个数由后端算好了随事件带回来,这里只覆盖。 + applySummary(event.summary) return } case 'file.finished': { @@ -153,6 +188,7 @@ export function applyRunEvent(event: RunEvent, owner: RemoteMode): void { pushRow(row) } absorbResult(row, event.result) + applySummary(event.summary) return } case 'run.finished': { @@ -163,65 +199,25 @@ export function applyRunEvent(event: RunEvent, owner: RemoteMode): void { } clearRunning(owner, event.runId) clearCancelTimer(owner) - if (announcedRuns.has(event.runId)) { runId.value = null; phase.value = 'cancelled'; return } + if (announcedRuns.has(event.runId)) { + runId.value = null + phase.value = 'cancelled' + return + } flashIfAway() summary.value = event.summary + applySummary(event.summary) phase.value = event.summary.cancelled ? 'cancelled' : 'done' if (event.summary.cancelled) markUnsettledCancelled() runId.value = null - if (event.summary.cancelled) { - // 图床成片失败时这一轮是我们自己掐掉的,得把原因摆出来, - // 否则用户只看到「已取消」,以为是自己点错了。 - announcedRuns.add(event.runId) - if (event.summary.abortReason) danger(event.summary.abortReason) - else warning(cancelText(owner)) - } else if (owner === 'download') { - // 下载页用自己的口径:取回几张、几个地址没下下来。 - // 以前这里会落到「上传完成」「检测完成」的文案上——下载页说「检测完成」不对, - // 说「上传完成 · 0 张图片」更不对。 - const got = event.summary.localized ?? 0 - const failed = (event.summary.remoteFailed ?? 0) + (event.summary.remoteDead ?? 0) - if (got > 0 && failed > 0) warning(t('toast.runDownloadedPartial', { count: got, failed })) - else if (got > 0) success(t('toast.runDownloaded', { count: got })) - else if (failed > 0) warning(t('toast.runDownloadedFailed', { failed })) - else if (runningDebug.value && (event.summary.remoteKept ?? 0) > 0) - // 调试构建确实一张都没下,但说「没有可下载的远程图片」会让人以为扫描没扫到东西。 - warning(t('toast.runDownloadedDebug', { count: event.summary.remoteKept ?? 0 })) - else warning(t('toast.runDownloadedNone')) - } else if (runningDebug.value) { - // 调试构建整轮只扫描、不上传:这里落到「上传完成 · 0 张图片」像是什么都没找到。 - warning(t('toast.runFinishedDebug')) - } else if (event.summary.failedImages > 0) { - warning(t('toast.runFinishedPartial', { count: event.summary.failedImages })) - } else if ( - (event.summary.uploadRequests ?? 0) > 0 && - (event.summary.uploadRequests ?? 0) < event.summary.uploaded - ) { - // 同一份内容被多个名字引用时只上行一次:「替换 3 处」不等于「发了 3 张」。 - success( - t('toast.runFinishedDedup', { - refs: event.summary.uploaded, - requests: event.summary.uploadRequests ?? 0, - }), - ) - } else if (event.summary.uploaded === 0 && (event.summary.localized ?? 0) > 0) { - // 只下载的一轮:「下载完成」才说得清这一轮做了什么。 - success(t('toast.runDownloaded', { count: event.summary.localized ?? 0 })) - } else if (event.summary.uploaded === 0 && (event.summary.remoteChecked ?? 0) > 0) { - // 只检测的一轮:说清是几个地址、坏没坏,而不是「上传 0 张图片」。 - const dead = event.summary.remoteDead ?? 0 - if (dead > 0) warning(t('toast.runCheckedDead', { count: dead })) - else success(t('toast.runCheckedClean', { count: event.summary.remoteChecked ?? 0 })) - } else { - success(t('toast.runFinished', { count: event.summary.uploaded })) - } + announceOutcome(owner, event.summary, event.runId) return } case 'run.cancelled': { if (!matches(event.runId)) return clearRunning(owner, event.runId) clearCancelTimer(owner) - if (event.summary) summary.value = event.summary + if (event.summary) applySummary(event.summary) phase.value = 'cancelled' markUnsettledCancelled() runId.value = null @@ -242,6 +238,58 @@ export function applyRunEvent(event: RunEvent, owner: RemoteMode): void { } } +/** 一轮跑完之后的那句提示:按这一轮到底做了什么说,别让下载页说「上传完成」。 */ +function announceOutcome(owner: RemoteMode, sum: RunSummary, eventRunId: string): void { + if (sum.cancelled) { + // 图床成片失败时这一轮是我们自己掐掉的,得把原因摆出来, + // 否则用户只看到「已取消」,以为是自己点错了。 + announcedRuns.add(eventRunId) + if (sum.abortReason) danger(sum.abortReason) + else warning(cancelText(owner)) + return + } + if (owner === 'download') { + const got = sum.localized ?? 0 + const failed = (sum.remoteFailed ?? 0) + (sum.remoteDead ?? 0) + if (got > 0 && failed > 0) warning(t('toast.runDownloadedPartial', { count: got, failed })) + else if (got > 0) success(t('toast.runDownloaded', { count: got })) + else if (failed > 0) warning(t('toast.runDownloadedFailed', { failed })) + else if (runningDebug.value && (sum.remoteKept ?? 0) > 0) + // 调试构建确实一张都没下,但说「没有可下载的远程图片」会让人以为扫描没扫到东西。 + warning(t('toast.runDownloadedDebug', { count: sum.remoteKept ?? 0 })) + else warning(t('toast.runDownloadedNone')) + return + } + if (runningDebug.value) { + // 调试构建整轮只扫描、不上传:这里落到「上传完成 · 0 张图片」像是什么都没找到。 + warning(t('toast.runFinishedDebug')) + return + } + if (sum.failedImages > 0) { + warning(t('toast.runFinishedPartial', { count: sum.failedImages })) + return + } + const requests = sum.uploadRequests ?? 0 + if (requests > 0 && requests < sum.uploaded) { + // 同一份内容被多个名字引用时只上行一次:「替换 3 处」不等于「发了 3 张」。 + success(t('toast.runFinishedDedup', { refs: sum.uploaded, requests })) + return + } + if (sum.uploaded === 0 && (sum.localized ?? 0) > 0) { + // 只下载的一轮:「下载完成」才说得清这一轮做了什么。 + success(t('toast.runDownloaded', { count: sum.localized ?? 0 })) + return + } + if (sum.uploaded === 0 && (sum.remoteChecked ?? 0) > 0) { + // 只检测的一轮:说清是几个地址、坏没坏,而不是「上传 0 张图片」。 + const dead = sum.remoteDead ?? 0 + if (dead > 0) warning(t('toast.runCheckedDead', { count: dead })) + else success(t('toast.runCheckedClean', { count: sum.remoteChecked ?? 0 })) + return + } + success(t('toast.runFinished', { count: sum.uploaded })) +} + /** * 事件先攒起来,每帧统一应用一次。 * @@ -281,88 +329,6 @@ export function enqueue(event: RunEvent): void { } } -/** - * 把 Go 侧记着的「这一轮」接管过来。 - * - * 用在两种时刻:页面刚打开(刷新过,内存里的 runId 已经没了)、以及断线重连之后 - * (断的那段时间里 file.finished 全丢了)。文件清单来自快照,已完成的结果直接贴回 - * 对应的行,还在跑的标成「上传中」。 - * - * 但「上一次会话已经跑完的那一轮」不接管:它属于历史,不是这一页的队列。刚打开应用 - * 时页面上还没有任何行,接管它会把别的页的文件搬过来、把本页队列整个盖掉。 - */ -export function adoptSnapshot(mode: RemoteMode, snapshot: CurrentRun): void { - if (!snapshot.runId) return - // 这一轮的结果已经在界面上了(自己刚跑完),不要用快照再盖一遍。 - if (summary.value !== null && summary.value.runId === snapshot.runId) return - // 已经结束、而且这个页面早就见过它(比如用户跑完又清空了队列): - // 重连时别把旧结果重新变出来。 - if (!snapshot.running && adopted.runId === snapshot.runId) return - // 上一次会话已经收工的一轮不进队列:页面上还没有行时接管它,等于把那一轮的文件 - // 当成这一页的队列(还会把 localStorage 里别的页的路径覆盖掉)。 - if (!snapshot.running && rows.value.length === 0) return - adopted.runId = snapshot.runId - - runId.value = snapshot.runId - summary.value = snapshot.summary ?? null - phase.value = snapshot.running - ? 'running' - : snapshot.summary?.cancelled - ? 'cancelled' - : 'done' - // 接管的这一轮还在跑:它算这一页的作业,这一页的「开始」要继续拦住。 - if (snapshot.running) markRunning(mode, snapshot.runId) - else clearRunning(mode, snapshot.runId) - - // 还在跑的一轮才重建队列;已经收工的一轮只把结果贴回**已有的行**(断线重连那一路), - // 不会新造行、也不会动这份队列的组成。 - if (snapshot.running) applyStarted(snapshot.files ?? []) - - for (const result of snapshot.results ?? []) { - const matched = rowForResult(result.id, result.path) - const row = matched ?? (snapshot.running ? rowFromResult(result) : null) - if (row === null) continue - if (!rowAt(row.id) && !rowIndex.has(row.id)) pushRow(row) - absorbResult(row, result) - } - if (snapshot.running) { - for (const row of rows.value) { - if (row.phase === 'queued') row.phase = 'running' - } - } else if (snapshot.summary?.cancelled) { - markUnsettledCancelled() - } -} - -/** - * 和服务端对齐一次「现在在跑什么」。 - * - * 事件流是增量的:刷新页面会漏掉 run.started 和之前所有 file.finished,前端内存里的 - * runId 也没了,界面就退回「队列为空」—— 可 Go 侧其实还在跑,甚至已经跑完。 - * 所以每次连上事件流都先问一次现状,再接着吃增量。 - */ -async function resync(): Promise { - // 三页各问一次:一页在跑不代表另外两页没有历史快照。 - const requests = PAGES.map(async (mode) => { - try { - return { mode, snapshot: await getCurrentRun(mode) } - } catch { - return null - } - }) - for (const item of await Promise.all(requests)) { - if (item === null) continue - const { mode, snapshot } = item - // 判断必须在 withPage 里面做:pages[mode] 只在切页时落盘,当前页的 phase/runId - // 可能还新过它。请求飞在路上时用户也可能刚点了开始——这一页正在准备/跑同一轮就别盖。 - withPage(mode, () => { - if (phase.value === 'preparing') return - if (runId.value === snapshot.runId && phase.value === 'running') return - adoptSnapshot(mode, snapshot) - }) - } -} - export function connect(): void { if (sinkActive) return sinkActive = true @@ -381,21 +347,10 @@ export function connect(): void { } connected.value = true - if (reconnecting.value) { - reconnecting.value = false - success(t('toast.reconnected')) - } - // 连上(含重载)就先对一次现状:漏掉的事件靠这次补齐。 - void resync() } export function disconnect(): void { - if (reconnectTimer !== null) { - window.clearTimeout(reconnectTimer) - reconnectTimer = null - } sinkActive = false window.__markpicEvents = undefined connected.value = false - reconnecting.value = false } diff --git a/web/src/composables/useRun/page.ts b/web/src/composables/useRun/page.ts index 84c95d7..445195f 100644 --- a/web/src/composables/useRun/page.ts +++ b/web/src/composables/useRun/page.ts @@ -30,8 +30,6 @@ export interface QueuePage { phase: RunPhase summary: RunSummary | null runId: string | null - /** 最近一次从服务端快照接管过来的 runId(挡「重连把清空过的队列又填满」)。 */ - lastAdoptedRunId: string | null live: LiveCounters lastReveal: string | null lastRevealIndex: number @@ -49,7 +47,6 @@ function newPage(): QueuePage { phase: 'idle', summary: null, runId: null, - lastAdoptedRunId: null, live: emptyCounters(), lastReveal: null, lastRevealIndex: -1, @@ -106,14 +103,6 @@ export let eventIndex = pages[activePage].eventIndex export let pathIndex = pages[activePage].pathIndex export const summary = ref(pages[activePage].summary) export const runId = ref(pages[activePage].runId) -/** - * 最近一次从服务端快照接管过来的 runId。 - * - * 用来挡住「一轮已经结束、重连又把它变回界面」这种情况:结束时服务端还会留一份快照, - * 供刚刚刷新的页面接一次;但同一个页面不该靠重连把清空过的队列重新填满。 - */ -export const adopted = { runId: pages[activePage].lastAdoptedRunId as string | null } - /** * 运行中的统计用增量维护,不再「每来一条事件就把所有行重算一遍」。 * @@ -138,7 +127,6 @@ export function savePage(): void { page.phase = phase.value page.summary = summary.value page.runId = runId.value - page.lastAdoptedRunId = adopted.runId page.live = { ...live } page.lastReveal = lastReveal.value page.lastRevealIndex = revealIndex.value @@ -156,7 +144,6 @@ export function loadPage(mode: RemoteMode): void { phase.value = page.phase summary.value = page.summary runId.value = page.runId - adopted.runId = page.lastAdoptedRunId lastReveal.value = page.lastReveal revealIndex.value = page.lastRevealIndex seq.local = page.localSeq diff --git a/web/src/composables/useRun/rows.ts b/web/src/composables/useRun/rows.ts index 2fdae69..56ddf05 100644 --- a/web/src/composables/useRun/rows.ts +++ b/web/src/composables/useRun/rows.ts @@ -8,33 +8,12 @@ import { markRaw, shallowReactive } from 'vue' import type { FileResult, RemoteMode, RunFileInfo } from '../../types' import { t } from '../../i18n' import { activePage, eventIndex, lastReveal, live, pathIndex, revealIndex, rowIndex, rows } from './page' +import { emptyCounters } from './types' import { pathKey } from './paths' import type { RunRow } from './types' export function liveReset(): void { - live.images = 0 - live.uploaded = 0 - live.reused = 0 - live.uploadRequests = 0 - live.failed = 0 - live.ok = 0 - live.partial = 0 - live.failedFiles = 0 - live.noImages = 0 - live.localized = 0 - live.localizedUnique = 0 - live.remoteChecked = 0 - live.remoteCheckedUnique = 0 - live.remoteDead = 0 - live.remoteDeadUnique = 0 - live.remoteFailed = 0 - live.remoteFailedUnique = 0 - live.remoteUnsupported = 0 - live.localMissing = 0 - live.remoteKept = 0 - live.filesChecked = 0 - live.settled = 0 - live.abortReason = '' + Object.assign(live, emptyCounters()) lastReveal.value = null revealIndex.value = -1 } @@ -77,14 +56,6 @@ export function workUnitsIn(result: FileResult | null | undefined, mode: RemoteM return seen.size } -export function scoreStatus(status: FileResult['status'], sign: number): void { - if (status === 'ok') live.ok += sign - else if (status === 'partial') live.partial += sign - else if (status === 'failed') live.failedFiles += sign - else if (status === 'no-images') live.noImages += sign - else if (status === 'checked') live.filesChecked += sign -} - export function rowAt(id: string): RunRow | null { const index = eventIndex.get(id) ?? rowIndex.get(id) if (index === undefined) return null @@ -153,61 +124,17 @@ export function rowFromResult(result: FileResult): RunRow { * 「图片总数」这一项要把该行原先的贡献换掉(排队时是预估、预检时是预检结果、 * 完成后是真实结果),所以先减旧值再加新值。 */ -/** 服务端会在结果里直接给出复用张数;老版本没有这个字段时就退回自己数明细。 */ -function reusedInResult(result: FileResult): number { - if (typeof result.reused === 'number') return result.reused - return result.items.filter(item => item.status === 'reused' || item.status === 'cached').length -} - export function absorbResult(row: RunRow, result: FileResult): void { - if (row.scored && row.result) { - live.images -= row.result.images - live.reused -= reusedInResult(row.result) - live.failed -= row.result.failed - live.localized -= row.result.localized ?? 0 - live.localizedUnique -= row.result.localizedUnique ?? 0 - live.remoteChecked -= row.result.checked ?? 0 - live.remoteCheckedUnique -= row.result.checkedUnique ?? 0 - live.remoteDead -= row.result.dead ?? 0 - live.remoteDeadUnique -= row.result.deadUnique ?? 0 - live.remoteFailed -= row.result.remoteFailed ?? 0 - live.remoteFailedUnique -= row.result.remoteFailedUnique ?? 0 - live.remoteUnsupported -= row.result.remoteUnsupported ?? 0 - live.localMissing -= row.result.localMissing ?? 0 - live.remoteKept -= row.result.remoteKept ?? 0 - scoreStatus(row.result.status, -1) - } else { - live.images -= row.images ?? row.total - } - - live.images += result.images - live.uploaded += result.uploaded - row.uploaded - live.reused += reusedInResult(result) - live.failed += result.failed - live.localized += result.localized ?? 0 - live.localizedUnique += result.localizedUnique ?? 0 - live.remoteChecked += result.checked ?? 0 - live.remoteCheckedUnique += result.checkedUnique ?? 0 - live.remoteDead += result.dead ?? 0 - live.remoteDeadUnique += result.deadUnique ?? 0 - live.remoteFailed += result.remoteFailed ?? 0 - live.remoteFailedUnique += result.remoteFailedUnique ?? 0 - live.remoteUnsupported += result.remoteUnsupported ?? 0 - live.localMissing += result.localMissing ?? 0 - live.remoteKept += result.remoteKept ?? 0 + // 统计数字由后端随事件带回(event.summary),这里只管把结果落到行上。 // 这一篇的活干完了:用结果里的明细重新数一遍单元。第一个 file.progress 之前 // 的分母是按预览估算的,比真实值大的话会一直把总进度压低;一个单元都没有 // (纯本地图/纯远程图)就该从分母里消失,不能把进度条永远钉在中间。 row.workTotal = workUnitsIn(result, activePage) row.workDone = row.workTotal - scoreStatus(result.status, 1) - if (!row.scored && row.phase !== 'cancelled') live.settled += 1 const index = rowIndex.get(row.id) ?? (row.serverId ? eventIndex.get(row.serverId) : undefined) ?? -1 row.result = markRaw(result) row.liveItems = undefined - row.counted = undefined - row.scored = true row.phase = 'settled' row.uploaded = result.uploaded row.total = result.images @@ -252,12 +179,10 @@ export function applyStarted(files: RunFileInfo[]): void { existing.missing = false // 上一轮的明细先留着:这一轮每跑完一个文件,事件会把结果换掉。 // 立刻置空会让检测页/下载页在跑的过程中变成空白页(看着像崩了)。 - existing.scored = false existing.scan = 'ok' existing.scanError = undefined existing.scanBatch = undefined existing.liveItems = undefined - existing.counted = undefined return existing } return { @@ -283,7 +208,6 @@ export function applyStarted(files: RunFileInfo[]): void { uploaded: 0, total: row.images ?? 0, result: null, - scored: false, liveItems: undefined, })) @@ -310,7 +234,6 @@ export function markUnsettledCancelled(): void { for (const row of rows.value) { if (row.phase !== 'settled') row.phase = 'cancelled' } - live.settled = rows.value.length } /** @@ -322,4 +245,4 @@ export function markUnsettledCancelled(): void { */ export function seedLiveItems(row: RunRow): void { if (!row.liveItems) row.liveItems = shallowReactive([...(row.result?.items ?? [])]) -} +} \ No newline at end of file diff --git a/web/src/composables/useRun/scan.ts b/web/src/composables/useRun/scan.ts index 4fbb5df..c0ab530 100644 --- a/web/src/composables/useRun/scan.ts +++ b/web/src/composables/useRun/scan.ts @@ -7,7 +7,7 @@ */ import { markRaw } from 'vue' import { cancelScan as requestCancelScan, describeError, scanStart as requestScanStart } from '../../api' -import type { FileResult, RemoteMode, ScanEvent, Settings } from '../../types' +import type { FileResult, RemoteMode, ScanEvent } from '../../types' import { t } from '../../i18n' import { activePage, pageRows, rows } from './page' import { pathKey } from './paths' @@ -110,11 +110,7 @@ export function finishBatch(batch: ScanBatch, state: ScanState, message?: string * 事件回来。以前这里是 await 一次 preview,十个文件串着扫,界面整段冻住, * 卡片也只能等全部扫完才出现。 */ -export async function scanPaths( - mode: RemoteMode, - paths: readonly string[], - settings: Settings, -): Promise { +export async function scanPaths(mode: RemoteMode, paths: readonly string[]): Promise { const list: string[] = [] const seen = new Set() for (const raw of paths) { @@ -143,7 +139,7 @@ export async function scanPaths( }, SCAN_BATCH_TIMEOUT_MS) try { - await requestScanStart({ scanId: id, paths: list, settings }) + await requestScanStart({ scanId: id, paths: list }) } catch (err) { finishBatch(batch, 'failed', describeError(err, t('scan.failed'))) } @@ -224,11 +220,11 @@ export function cancelRowScan(id: string): void { } /** 重新扫一张卡片(取消/失败/超时之后)。 */ -export function retryRowScan(id: string, settings: Settings): void { +export function retryRowScan(id: string): void { const row = rows.value.find((item) => item.id === id) if (!row) return if ((row.scan ?? 'idle') === 'scanning') return - void scanPaths(activePage, [row.path], settings) + void scanPaths(activePage, [row.path]) } /** 掐掉这一页所有还在跑的扫描(清空队列、离开这一页时兜底)。 */ @@ -244,7 +240,3 @@ export function cancelPageScans(): void { } } -/** 这一页还有几行在扫(页头写「正在扫描 3/10」用)。 */ -export function pageScanningCount(mode: RemoteMode): number { - return pageRows(mode).filter((row) => (row.scan ?? 'idle') === 'scanning').length -} diff --git a/web/src/composables/useRun/stats.ts b/web/src/composables/useRun/stats.ts index b859e77..8945f56 100644 --- a/web/src/composables/useRun/stats.ts +++ b/web/src/composables/useRun/stats.ts @@ -1,12 +1,12 @@ /** * 顶栏、底栏要的那几个总数。 * - * 全是 computed:行自己的变化由行自己触发重渲染,这里只负责「一共几行、跑完几个、 - * 替换了几处」这类一眼要看到的数。 + * 数字全部来自后端:每个事件都带着「这一轮到目前为止」的累计汇总,这里只把它拼成 + * 界面的形状。前端不再自己数一遍 —— 跑动中和跑完后的口径因此不可能对不上。 */ import { computed } from 'vue' import type { RunRowView, RunStats } from './types' -import { lastReveal, live, rows, summary } from './page' +import { lastReveal, live, rows } from './page' /** * 传给列表的行数组。 @@ -18,69 +18,48 @@ export const rowViews = computed(() => rows.value.slice()) export const totalCount = computed(() => rows.value.length) -export const completedCount = computed(() => live.settled) - -export const stats = computed(() => { - const finished = summary.value - if (finished) { - return { - files: finished.files, - // 跑完之后目录已经展开成一个个文件了,这里不再有「目录」这回事。 - dirs: 0, - images: finished.images, - uploaded: finished.uploaded, - reused: finished.reused, - uploadRequests: finished.uploadRequests ?? 0, - failed: finished.failedImages, - ok: finished.ok, - partial: finished.partial, - failedFiles: finished.failed, - noImages: finished.noImages, - localized: finished.localized ?? 0, - localizedUnique: finished.localizedUnique ?? 0, - remoteChecked: finished.remoteChecked ?? 0, - remoteCheckedUnique: finished.remoteCheckedUnique ?? 0, - remoteDead: finished.remoteDead ?? 0, - remoteDeadUnique: finished.remoteDeadUnique ?? 0, - remoteFailed: finished.remoteFailed ?? 0, - remoteFailedUnique: finished.remoteFailedUnique ?? 0, - remoteUnsupported: finished.remoteUnsupported ?? 0, - localMissing: finished.localMissing ?? 0, - remoteKept: finished.remoteKept ?? 0, - filesChecked: finished.filesChecked ?? 0, - remoteReused: finished.remoteReused ?? 0, - abortReason: finished.abortReason ?? '', - } - } +/** + * 队列里已经收工的行数(有结果,或被取消)。 + * + * 不从后端的计数桶里拼:取消的文件不属于任何一个桶,拼出来的数会让进度条在取消后 + * 停在中途;队列行的相位才是「这一行还会不会动」的准确答案。 + */ +export const completedCount = computed( + () => rows.value.filter((row) => row.phase === 'settled' || row.phase === 'cancelled').length, +) - return { - files: rows.value.length, - dirs: rows.value.reduce((n, row) => n + (row.isDir ? 1 : 0), 0), - images: live.images, - uploaded: live.uploaded, - reused: live.reused, - uploadRequests: live.uploadRequests, - failed: live.failed, - ok: live.ok, - partial: live.partial, - failedFiles: live.failedFiles, - noImages: live.noImages, - localized: live.localized, - localizedUnique: live.localizedUnique, - remoteChecked: live.remoteChecked, - remoteCheckedUnique: live.remoteCheckedUnique, - remoteDead: live.remoteDead, - remoteDeadUnique: live.remoteDeadUnique, - remoteFailed: live.remoteFailed, - remoteFailedUnique: live.remoteFailedUnique, - remoteUnsupported: live.remoteUnsupported, - localMissing: live.localMissing, - remoteKept: live.remoteKept, - filesChecked: live.filesChecked, - remoteReused: live.remoteReused, - abortReason: live.abortReason, - } -}) +export const stats = computed(() => ({ + // 队列里有几行就是几个文件:跑动中它不能变成「已经处理了几个」, + // 否则底栏的文件数会随着进度往上跳。开跑时目录会展开成一个个文件, + // 所以跑起来之后 dirs 自然回到 0。 + files: rows.value.length, + dirs: rows.value.reduce((n, row) => n + (row.isDir ? 1 : 0), 0), + // 引用数是「队列里一共多少张」,不是「已经处理了几张」:底栏那行是读队列, + // 进度由页头的百分比和「替换 N」负责。 + images: rows.value.reduce((n, row) => n + (row.images ?? row.total), 0), + uploaded: live.uploaded, + reused: live.reused, + uploadRequests: live.uploadRequests, + failed: live.failed, + ok: live.ok, + partial: live.partial, + failedFiles: live.failedFiles, + noImages: live.noImages, + localized: live.localized, + localizedUnique: live.localizedUnique, + remoteChecked: live.remoteChecked, + remoteCheckedUnique: live.remoteCheckedUnique, + remoteDead: live.remoteDead, + remoteDeadUnique: live.remoteDeadUnique, + remoteFailed: live.remoteFailed, + remoteFailedUnique: live.remoteFailedUnique, + remoteUnsupported: live.remoteUnsupported, + localMissing: live.localMissing, + remoteKept: live.remoteKept, + filesChecked: live.filesChecked, + remoteReused: live.remoteReused, + abortReason: live.abortReason, +})) export const revealTarget = computed(() => { if (lastReveal.value !== null) return lastReveal.value diff --git a/web/src/composables/useRun/types.ts b/web/src/composables/useRun/types.ts index e0604c1..cdfa71c 100644 --- a/web/src/composables/useRun/types.ts +++ b/web/src/composables/useRun/types.ts @@ -48,8 +48,6 @@ export interface RunRow { result: FileResult | null /** 服务端为这次运行分配的 id(事件里的 id)。队列行的 id 由本地生成,两者都要能查到行。 */ serverId?: string - /** 内部记账:这份结果是否已经算进 live 统计(预检结果只贡献图片数)。 */ - scored?: boolean /** 这一行自己的扫描状态;只有 'ok' 的行才允许参与「开始」。 */ scan?: ScanState /** 扫描没通过时给人看的一句话(超时、找不到文件、后台报错)。 */ @@ -79,13 +77,6 @@ export interface RunRow { workTotal?: number /** 这一篇已经处理完的单元数;文件完成时补齐,运行中由 file.progress 推进。 */ workDone?: number - /** - * 这一轮已经计进页脚「替换」的明细下标。 - * - * 卡片每处理完一处就换状态,页脚也该跟着走;按位置去重,进度事件重放不会 - * 把数字算重。file.finished 会用结果校正一次,并清掉这份记账。 - */ - counted?: Set } /** 列表拿到的行就带着结果。保留这个别名,免得每个组件都改一遍类型。 */ diff --git a/web/src/composables/useSettings.ts b/web/src/composables/useSettings.ts index c62f2c1..9769da6 100644 --- a/web/src/composables/useSettings.ts +++ b/web/src/composables/useSettings.ts @@ -172,22 +172,14 @@ function discard(): void { adopt(baseline.value) } -/** 供发起转换 / 预览时使用的稳定快照。 - * override 用来盖住草稿里的值:远程图现在由菜单决定(转换 / 检测 / 下载), - * 那不是表单里的改动,不该让草稿变脏。 - */ -function snapshot(override?: Partial): Settings { - return normalize({ ...draft, ...override }) -} - -async function save(override?: Partial): Promise { +async function save(): Promise { if (saving.value) return false if (!loaded.value) { warning(t('error.settingsNotLoaded')) return false } - const merged = { ...draft, ...override } + const merged = { ...draft } const endpoint = merged.endpoint.trim() // 只有真要上传时才非得有 PicGo 地址:只检测 / 只下载远程图、以及调试构建都不上传, // 这时候拦住「保存」纯属添乱(服务端本来也会把空地址回落成默认值)。 @@ -249,7 +241,6 @@ export function useSettings() { rememberCloseAction, update, discard, - snapshot, outputModes: OUTPUT_MODES, } } diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index d6c2db6..43273e8 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -125,7 +125,6 @@ export const en: Record = { 'row.status.downloading': 'Downloading', 'row.status.checking': 'Checking', 'row.status.aborted': 'Stopped', - 'row.reason.aborted': 'The run was stopped early before this file was reached', 'row.status.cancelled': 'Cancelled', 'row.status.finished': 'Finished', 'row.status.notFound': 'Not found', @@ -331,8 +330,6 @@ export const en: Record = { 'toast.healthOnline': 'Refreshed · PicGo is connected', 'toast.healthOffline': 'Refreshed · PicGo is still unreachable', 'toast.healthNotNeeded': 'Refreshed · PicGo is not needed for this run', - 'toast.reconnected': 'Live connection restored', - 'toast.reconnecting': 'Live connection lost — reconnecting', 'toast.eventsNotReady': 'Live progress is not connected yet; progress may not update', 'toast.queueLocked': 'A run is in progress — the queue is locked', 'toast.clearLocked': 'A run is in progress — the queue is locked', @@ -352,7 +349,6 @@ export const en: Record = { 'error.pickPath': 'Could not choose paths: {detail}', 'error.scan': 'Scan failed: {detail}', 'error.pickDir': 'Could not choose a folder: {detail}', - 'error.preview': 'Could not read the image count: {detail}', 'error.revealOutput': 'Could not open the output folder: {detail}', 'error.openOutput': 'Could not open the output file: {detail}', 'error.openDataDir': 'Could not open the data folder', @@ -364,8 +360,6 @@ export const en: Record = { 'error.install': 'Could not install the update', 'error.releasePage': 'The release page address is not known yet', 'error.openBrowser': 'Could not open the browser', - 'error.network': 'Could not reach the local service ({origin})', - 'error.http': 'Request failed (HTTP {status})', 'error.loadSettings': 'Could not load the settings', 'error.settingsNotLoaded': 'The settings have not loaded yet, so they cannot be saved', 'error.picgoRequired': 'Enter the PicGo server address', @@ -428,7 +422,6 @@ export const en: Record = { 'check.group.bad': '{count} broken', 'check.group.unsupported': '{count} unsupported', 'check.row.pending': 'to check', - 'check.row.sources': '{count} refs', 'check.scanning': 'Checking the remote images in {count} file(s)…', 'check.empty.noRemote': 'No remote images in these files — this page only checks whether remote addresses load.', 'check.empty.filtered': 'Nothing under this filter.', @@ -457,11 +450,9 @@ export const en: Record = { 'scan.action.cancel': 'Cancel scan', 'scan.action.resume': 'Resume scan', 'scan.action.retry': 'Retry', - 'scan.pending': 'to scan', - 'scan.batch': 'Scanning {count} file(s)', 'scan.failed': 'Scan failed: {detail}', 'scan.notFound': "Can't find this file", 'scan.timeout': 'Scan timed out', 'footer.blocked.scanning': 'Scanning {count} file(s)…', 'footer.blocked.problem': '{count} file(s) have not passed scanning', -} +} \ No newline at end of file diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts index 95f214d..dbfab93 100644 --- a/web/src/i18n/index.ts +++ b/web/src/i18n/index.ts @@ -47,19 +47,6 @@ function setLang(next: Lang): void { apply() } -/** 当前语言,供 api.ts 之类的非组件代码使用。 */ -export function currentLang(): Lang { - return lang.value -} - -/** - * 每次请求都带上它:服务端返回的文字(逐图失败原因、PicGo 提示、更新错误等) - * 也要跟着界面语言走。 - */ -export function langHeader(): string { - return lang.value === 'en' ? 'en' : 'zh-CN' -} - /** 取文案;{name} 会被 params 里的同名值替换。 */ export function t(key: MessageKey, params?: Record): string { const text = CATALOG[lang.value][key] ?? zh[key] ?? key diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index 5782485..65cfd2d 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -125,7 +125,6 @@ export const zh = { 'row.status.downloading': '下载中', 'row.status.checking': '检测中', 'row.status.aborted': '已中止', - 'row.reason.aborted': '这一轮被提前掐断了,这张还没轮到', 'row.status.cancelled': '已取消', 'row.status.finished': '已结束', 'row.status.notFound': '未找到文件', @@ -328,8 +327,6 @@ export const zh = { 'toast.healthOnline': '刷新完成 · PicGo 已连接', 'toast.healthOffline': '刷新完成 · PicGo 仍未连接', 'toast.healthNotNeeded': '刷新完成 · 本次不需要 PicGo', - 'toast.reconnected': '已恢复实时连接', - 'toast.reconnecting': '实时连接已断开,正在重连', 'toast.eventsNotReady': '实时进度连接未就绪,转换进度可能不会更新', 'toast.queueLocked': '有作业正在跑,暂不能修改队列', 'toast.clearLocked': '有作业正在跑,暂不能清空队列', @@ -346,7 +343,6 @@ export const zh = { 'error.noBridge': '现在是在浏览器里预览界面,桌面窗口才能真的转换文件', 'error.pickPath': '选择路径失败:{detail}', 'error.pickDir': '选择目录失败:{detail}', - 'error.preview': '读取图片数量失败:{detail}', 'error.scan': '扫描失败:{detail}', 'error.revealOutput': '打开输出目录失败:{detail}', 'error.openOutput': '打开输出文件失败:{detail}', @@ -359,8 +355,6 @@ export const zh = { 'error.install': '安装更新失败', 'error.releasePage': '还不知道发布页地址', 'error.openBrowser': '打不开浏览器', - 'error.network': '无法连接本地服务({origin})', - 'error.http': '请求失败(HTTP {status})', 'error.loadSettings': '读取设置失败', 'error.settingsNotLoaded': '设置尚未读取成功,暂不能保存', 'error.picgoRequired': '请填写 PicGo 服务地址', @@ -423,7 +417,6 @@ export const zh = { 'check.group.bad': '{count} 个打不开', 'check.group.unsupported': '{count} 个没法处理', 'check.row.pending': '待检测', - 'check.row.sources': '{count} 处引用', 'check.scanning': '正在扫 {count} 个文件里的远程图片…', 'check.empty.noRemote': '这些文件里没有远程图片 —— 检测只看远程地址打不打得开。', 'check.empty.filtered': '这个筛选下没有地址。', @@ -452,11 +445,9 @@ export const zh = { 'scan.action.cancel': '取消扫描', 'scan.action.resume': '恢复扫描', 'scan.action.retry': '重试', - 'scan.pending': '待扫描', - 'scan.batch': '正在扫描 {count} 个文件', 'scan.failed': '扫描失败:{detail}', 'scan.notFound': '找不到这个文件', 'scan.timeout': '扫描超时', 'footer.blocked.scanning': '正在扫描 {count} 个文件…', 'footer.blocked.problem': '{count} 个文件还没扫描通过', -} as const +} as const \ No newline at end of file diff --git a/web/src/types.ts b/web/src/types.ts index 4adc62f..7f6a440 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -231,8 +231,17 @@ export type RunEvent = total: number /** 这一条进度里刚处理完的那几处(按 items 的下标),卡片据此逐条换状态。 */ items?: { index: number; item: ImageItem }[] + /** 这一轮到目前为止的累计汇总:页脚那几个数直接用,不再由前端重算一遍。 */ + summary?: RunSummary + } + | { + type: 'file.finished' + runId: string + id: string + result: FileResult + /** 同上:每跑完一个文件,后端把最新累计值一并带回来。 */ + summary?: RunSummary } - | { type: 'file.finished'; runId: string; id: string; result: FileResult } | { type: 'run.finished'; runId: string; summary: RunSummary } | { type: 'run.cancelled'; runId: string; summary?: RunSummary } | { type: 'log'; level: 'info' | 'warn' | 'error'; message: string } @@ -261,28 +270,14 @@ export type Health = { export type DialogResult = { paths: string[] } -export type PreviewResult = { files: FileResult[]; summary: RunSummary } +/** 用户点的是哪一个操作。它和设置里的 remote 是两件事:那是「文档里的网络图片怎么办」。 */ +export type RunOp = 'upload' | 'check' | 'download' -export type RunStartResult = { runId: string } +export type RunStartResult = { runId: string; op: RunOp } /** scan.start 的返回:只是确认收下了,结果走 scan.file 事件。 */ export type ScanStartResult = { scanId: string; paths: string[] } -/** - * 服务端眼里的「这一轮」。刷新页面之后前端内存里的 runId 就没了, - * 只能问服务端现在在跑什么、已经出了哪些结果。 - */ -export type CurrentRun = { - running: boolean - done: boolean - runId?: string - /** 这一轮属于哪一页:run.current 按页取,重连时各页各自接回自己的快照。 */ - mode?: RemoteMode - files?: RunFileInfo[] - results?: FileResult[] - summary?: RunSummary -} - export type OkResult = { ok: boolean } /** 更新包(清单里给出的地址、校验值与大小)。 */ From acfc0a3a9d9c0ed24736368fc525b43ea469f47b Mon Sep 17 00:00:00 2001 From: Mus Date: Thu, 19 Nov 2026 20:33:10 +0800 Subject: [PATCH 02/17] =?UTF-8?q?=E9=87=8D=E6=9E=84=EF=BC=9A=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E6=8C=81=E4=B9=85=E5=8C=96=E5=90=88=E5=B9=B6=E6=88=90?= =?UTF-8?q?=E4=B8=80=E4=BB=BD=E5=AE=9E=E7=8E=B0=EF=BC=8C=E4=BF=AE=E5=87=A0?= =?UTF-8?q?=E5=A4=84=E5=90=AF=E5=8A=A8=E6=9C=9F=E5=BC=80=E9=94=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 internal/diskcache:缓存文件的读取、合并、按使用时间淘汰、原子写回 只实现一次;uploadcache / remotecache 只保留各自的条目类型与命中规则。 上传缓存的时间字段从纳秒改成秒,并就地换算版本 1 的旧文件,用户不必重传。 - sameFile 改成分块比较:以前把两个文件各自读进内存再 bytes.Equal, 两张 50MB 的图就是 100MB 的峰值。 - 启动画面:paint 与 barRect 各算一遍同样的布局,合成一份 layout(); 计时器本来就只让进度条变脏,但 paint 无视脏区整窗重绘(4K 下 62 次/秒), 现在按 rcPaint 判断,只有整窗脏时才重画底、图标与标题。 - 图标组只枚举一次:以前每次切主题都 EnumResourceNamesW + 新建一个 syscall.NewCallback,而回调跳板是进程级永不回收的。 - WebView2 背景重试从 150×40ms 改成 60×100ms:同样的 6 秒覆盖窗口, 丢进窗口队列的 Dispatch 少四成。 - snapDebug 的目标路径只解析一次:它挂在窗口过程上,鼠标一动就是几十条。 评估后没做的:Win32 结构体/常量的跨文件合并。结构体字段名不同(size/cbSize、 fErase/erase),统一要改三个窗口过程,属于 ABI 级改动却只省约 40 行,风险 与收益不相称;常量与 NewProc 的重复只是同值别名,不存在漂移风险。 验证:go test ./internal/... 全绿;go build 通过;真实窗口跑过启动画面 (PrintWindow 抓图,未抢焦点)、主界面、主题切换亮/暗。 --- cmd/markpic/chrome_windows.go | 51 ++++++--- cmd/markpic/snap_windows.go | 25 ++++- cmd/markpic/splash_windows.go | 133 +++++++++++++---------- cmd/markpic/theme_windows.go | 6 +- internal/conv/remote.go | 32 +++++- internal/diskcache/diskcache.go | 97 +++++++++++++++++ internal/remotecache/remotecache.go | 99 +++++------------ internal/remotecache/remotecache_test.go | 6 +- internal/uploadcache/uploadcache.go | 108 ++++++------------ internal/uploadcache/uploadcache_test.go | 4 +- 10 files changed, 326 insertions(+), 235 deletions(-) create mode 100644 internal/diskcache/diskcache.go 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/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/internal/conv/remote.go b/internal/conv/remote.go index 12e4dd8..2bf6366 100644 --- a/internal/conv/remote.go +++ b/internal/conv/remote.go @@ -670,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 { @@ -682,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/diskcache/diskcache.go b/internal/diskcache/diskcache.go new file mode 100644 index 0000000..970e8c0 --- /dev/null +++ b/internal/diskcache/diskcache.go @@ -0,0 +1,97 @@ +// 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) { + 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/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, }, From a869d017b0595ee8ec282b94b7822b6cb39d6618 Mon Sep 17 00:00:00 2001 From: Mus Date: Thu, 19 Nov 2026 22:12:08 +0800 Subject: [PATCH 03/17] =?UTF-8?q?=E6=8B=96=E6=94=BE=EF=BC=9A=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E6=8E=A5=E7=AE=A1=E6=94=BE=E7=BD=AE=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=EF=BC=8C=E6=96=87=E6=A1=A3=E6=8C=89=E5=86=85=E5=AE=B9=E8=AF=86?= =?UTF-8?q?=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebView2 的 DataTransfer 里只有 File 对象,没有本地路径(File.path 早被 Chromium 删掉),从资源管理器拖文件进来时 text/uri-list 也是空的 —— 所以界面层永远拿不到 路径。改成在原生侧接管 OLE 放置目标: - 新增 cmd/markpic/drop_windows.go:实现 IDropTarget,先 RevokeDragDrop 掉 WebView2 自己的目标(它会把拖放当导航),再给顶层窗口与所有子窗口注册我们的目标; Drop 时从 CF_HDROP 用 DragQueryFileW 直接读路径,经 window.__markpicDrop 交给 界面。拖入/离开顺带驱动 __markpicDragOverlay,放置态照旧。 - 单文件、多文件、文件夹都是同一条 CF_HDROP 列表,不需要分别处理。 - 前端 useFileDrop 订阅这两个原生钩子;DOM 那套保留作为兜底(原生接管失败时 仍然要 preventDefault,否则 WebView2 会把窗口导航走)。 文档不再按后缀收: - 新增 internal/conv/markdown_detect.go。目录展开时 .md/.markdown 直接收;其它文件 先按「一眼是二进制」的后缀排掉,再读开头 64KB,UTF-16 转码、其余按原字节扫, 命中标题 / 图片 / 链接 / 表格 / 围栏代码 / Setext 下划线就算文档。 弱信号(列表项、引用)要三处以上才收 —— 单独一行「- 某某」的纯文本太常见。 - 于是 .txt 笔记、无后缀的片段都会被扫进来,图片、压缩包、日志里的普通文本跳过。 验证:go test ./internal/... 全绿(新增 Markdown 识别与目录展开的用例); 真实窗口里把文件夹交给 __markpicDrop,队列展开成 a.md / b.txt / notes 三份文档 (c.log 与 d.png 被正确排除),跑完上传后 b.txt 生成了 b.converted.md 且链接已替换。 --- cmd/markpic/drop_windows.go | 321 ++++++++++++++++++++++++++ cmd/markpic/window_windows.go | 3 + docs/usage.md | 14 +- docs/usage.zh-CN.md | 7 +- internal/conv/collect.go | 9 +- internal/conv/markdown_detect.go | 209 +++++++++++++++++ internal/conv/markdown_detect_test.go | 127 ++++++++++ web/src/composables/useFileDrop.ts | 46 +++- 8 files changed, 722 insertions(+), 14 deletions(-) create mode 100644 cmd/markpic/drop_windows.go create mode 100644 internal/conv/markdown_detect.go create mode 100644 internal/conv/markdown_detect_test.go diff --git a/cmd/markpic/drop_windows.go b/cmd/markpic/drop_windows.go new file mode 100644 index 0000000..7ba5f8b --- /dev/null +++ b/cmd/markpic/drop_windows.go @@ -0,0 +1,321 @@ +//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 // 继续枚举 +}) + +func dropQueryInterface(self, riid, ppv uintptr) uintptr { + if ppv == 0 { + return dropEPointer + } + guid := (*[16]byte)(unsafe.Pointer(riid)) + if *guid == iidDropTarget || *guid == iidUnknown { + *(*uintptr)(unsafe.Pointer(ppv)) = self + dropAddRef(self) + return dropSOK + } + *(*uintptr)(unsafe.Pointer(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)(unsafe.Pointer(effect)) = dropEffectCopy + return + } + *(*uint32)(unsafe.Pointer(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)(unsafe.Pointer(obj)) + if vtbl == 0 { + return 0 + } + return *(*uintptr)(unsafe.Pointer(vtbl + uintptr(index)*unsafe.Sizeof(uintptr(0)))) +} 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/usage.md b/docs/usage.md index 91e3bda..d9a2d51 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -15,10 +15,16 @@ 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 folder +is scanned recursively, and **the extension is not what decides**: a file counts as a +document when it is `.md` / `.markdown`, or when its opening bytes look like Markdown +(a heading, an image, a link, a table, a fenced block). So `.txt` notes and extension-less +fragments are picked up too, while images, archives and other binaries are skipped. + +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..08e3d34 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -14,7 +14,12 @@ - **检测**:只读,但也会指出「文档引用了、磁盘上却不存在」的本地图。 - **下载**:只处理远程图,本地图保留。 -拖入文件或整个文件夹,看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 +拖入单个文件、多个文件或整个文件夹都行。路径来自原生放置目标——WebView2 本身拿不到 +拖入文件的本地路径。文件夹会被递归扫描,而且**不是按后缀收文件**:`.md` / `.markdown` +直接收;其它文件看开头像不像 Markdown(标题、图片、链接、表格、围栏代码),像就收。 +所以 `.txt` 笔记、没有后缀的片段也会被扫进来,图片、压缩包这类二进制则跳过。 + +看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 同一张图只上传一次;已经上传/下载过且内容未变的图直接复用。 ## 输出方式 diff --git a/internal/conv/collect.go b/internal/conv/collect.go index d1d1cef..c9112e2 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、无后缀的片段,甚至 + // 别的编辑器存的 .markdown。收不收由内容判断(见 markdown_detect.go), + // 里面先按后缀与二进制特征把读盘省掉。 + if !markdownDocument(path) { + return nil + } add(path) return nil }) diff --git a/internal/conv/markdown_detect.go b/internal/conv/markdown_detect.go new file mode 100644 index 0000000..e8c4825 --- /dev/null +++ b/internal/conv/markdown_detect.go @@ -0,0 +1,209 @@ +package conv + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + + "github.com/geekMus/markpic/internal/textenc" +) + +// 目录里不一定只有 .md:笔记软件的导出、静态站点的源文件、没后缀的片段,都可能是 +// Markdown。后缀只当「先信一次」的快捷判断,真正决定收不收的是内容。 +// +// 判断必须便宜:一个目录里可能混着几千个文件,所以先按后缀排掉明显不是文档的, +// 再只读开头一小段。「像不像 Markdown」看的是结构(标题、链接、图片、围栏代码、 +// 表格),不是「能不能被解析」—— 任何纯文本都能被当成 Markdown,那样等于全都收。 + +// markdownSniffBytes 是嗅探时最多读多少:看清结构够了,又不至于把几百兆的日志读进来。 +const markdownSniffBytes = 64 << 10 + +// 围栏代码的三个反引号(写成字节,免得源码里出现三连反引号)。 +var fenceBacktick = []byte{0x60, 0x60, 0x60} + +// binaryExts 是「一眼看出不是文档」的后缀。先按名字排掉,省掉大量无谓的读盘; +// 没有列到的(比如 .txt / .log / 无后缀)仍然会读一小段再看内容。 +var binaryExts = map[string]bool{ + // 图片 + ".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true, ".bmp": true, + ".ico": true, ".tif": true, ".tiff": true, ".avif": true, ".psd": true, + // 压缩包 + ".zip": true, ".7z": true, ".rar": true, ".gz": true, ".tar": true, ".bz2": true, ".xz": true, ".zst": true, + // 可执行与库 + ".exe": true, ".dll": true, ".sys": true, ".so": true, ".dylib": true, ".bin": true, + ".class": true, ".o": true, ".a": true, ".lib": true, ".pdb": true, ".obj": true, + // 音视频 + ".mp4": true, ".mov": true, ".avi": true, ".mkv": true, ".webm": true, ".flv": true, + ".mp3": true, ".wav": true, ".flac": true, ".ogg": true, ".m4a": true, ".aac": true, + // 办公文档与 PDF + ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, + ".ppt": true, ".pptx": true, ".odt": true, ".ods": true, + // 字体与数据库 + ".ttf": true, ".otf": true, ".woff": true, ".woff2": true, ".eot": true, + ".db": true, ".sqlite": true, ".sqlite3": true, ".mdb": true, +} + +// markdownDocument 判断这个路径能不能当文档处理。 +func markdownDocument(path string) bool { + ext := strings.ToLower(filepath.Ext(path)) + switch ext { + case ".md", ".markdown", ".mdown", ".mkd", ".mdwn": + return true // 后缀已经说明问题了,不必读盘 + } + if binaryExts[ext] { + return false + } + raw, ok := readHead(path) + if !ok { + return false + } + text, ok := textHead(raw) + if !ok { + return false + } + return looksLikeMarkdown(text) +} + +// readHead 读文件开头一小段。 +func readHead(path string) ([]byte, bool) { + f, err := os.Open(path) + if err != nil { + return nil, false + } + defer func() { _ = f.Close() }() + buf := make([]byte, markdownSniffBytes) + n, err := io.ReadFull(f, buf) + if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF { + return nil, false + } + if n == 0 { + return nil, false + } + return buf[:n], true +} + +// textHead 把开头一段变成可以扫的字节,顺便否掉二进制。 +// +// UTF-8 与 ANSI 里的 ASCII 标记都还是原样字节(GBK 的尾字节只会 >=0x80), +// 所以这两种编码不必解码就能扫;只有 UTF-16 必须转换。 +func textHead(raw []byte) ([]byte, bool) { + switch { + case bytes.HasPrefix(raw, []byte{0xFF, 0xFE}), bytes.HasPrefix(raw, []byte{0xFE, 0xFF}): + // 截断可能落在代理对中间:先按偶数裁一刀,再不行就少两个字节重试。 + if len(raw)%2 == 1 { + raw = raw[:len(raw)-1] + } + if text, err := textenc.Decode(raw, textenc.Detect(raw)); err == nil { + return text, true + } + if len(raw) > 4 { + if text, err := textenc.Decode(raw[:len(raw)-2], textenc.Detect(raw)); err == nil { + return text, true + } + } + return nil, false + } + // 二进制文件(可执行、图片、压缩包)几乎都在开头几个字节里带 NUL。 + probe := raw + if len(probe) > 8192 { + probe = probe[:8192] + } + if bytes.IndexByte(probe, 0) >= 0 { + return nil, false + } + return raw, true +} + +// looksLikeMarkdown 看这段文本有没有 Markdown 的结构。 +// +// 强信号(任意一处即可):围栏代码、ATX 标题、图片、行内链接、表格、Setext 下划线。 +// 弱信号(三处以上):列表项、引用。单独一行「- 某某」的纯文本太常见了,只有一处 +// 就不该把整个文件当成文档。 +func looksLikeMarkdown(data []byte) bool { + strong := 0 + weak := 0 + prevText := false + for _, line := range bytes.Split(data, []byte("\n")) { + line = bytes.TrimRight(line, "\r") + trimmed := bytes.TrimLeft(line, " \t") + if len(trimmed) == 0 { + continue + } + switch { + case bytes.HasPrefix(trimmed, fenceBacktick), bytes.HasPrefix(trimmed, []byte("~~~")): + strong++ + case isATXHeading(trimmed): + strong++ + case bytes.Contains(line, []byte("![")): + strong++ + case bytes.Contains(line, []byte("](")): + strong++ + case isTableRow(trimmed): + strong++ + case prevText && isSetextUnderline(trimmed): + strong++ + case isListItem(line), bytes.Equal(trimmed, []byte(">")), bytes.HasPrefix(trimmed, []byte("> ")): + weak++ + } + prevText = true + } + return strong >= 1 || weak >= 3 +} + +// isATXHeading 判断「## 标题」这种写法(# 的数量 1~6,后面必须是空格或行尾)。 +func isATXHeading(line []byte) bool { + n := 0 + for n < len(line) && line[n] == '#' { + n++ + } + if n == 0 || n > 6 { + return false + } + if n == len(line) { + return true + } + return line[n] == ' ' || line[n] == '\t' +} + +// isListItem 判断「- 项」/「* 项」/「+ 项」/「1. 项」。 +func isListItem(line []byte) bool { + trimmed := bytes.TrimLeft(line, " \t") + if len(trimmed) >= 2 && (trimmed[0] == '-' || trimmed[0] == '*' || trimmed[0] == '+') { + return trimmed[1] == ' ' || trimmed[1] == '\t' + } + i := 0 + for i < len(trimmed) && trimmed[i] >= '0' && trimmed[i] <= '9' { + i++ + } + if i == 0 || i+1 >= len(trimmed) { + return false + } + return trimmed[i] == '.' && (trimmed[i+1] == ' ' || trimmed[i+1] == '\t') +} + +// isTableRow 判断「| a | b |」这种整行(首尾都是竖线、至少两列)。 +func isTableRow(trimmed []byte) bool { + if len(trimmed) < 3 || trimmed[0] != '|' || trimmed[len(trimmed)-1] != '|' { + return false + } + return bytes.Count(trimmed, []byte("|")) >= 2 +} + +// isSetextUnderline 判断「===」/「---」这种标题下划线。 +func isSetextUnderline(trimmed []byte) bool { + if len(trimmed) < 3 { + return false + } + ch := trimmed[0] + if ch != '=' && ch != '-' { + return false + } + for _, c := range trimmed { + if c != ch { + return false + } + } + return true +} diff --git a/internal/conv/markdown_detect_test.go b/internal/conv/markdown_detect_test.go new file mode 100644 index 0000000..65595e1 --- /dev/null +++ b/internal/conv/markdown_detect_test.go @@ -0,0 +1,127 @@ +package conv + +import ( + "os" + "path/filepath" + "testing" + "unicode/utf16" +) + +func TestLooksLikeMarkdown(t *testing.T) { + fence := "\x60\x60\x60go\nfmt.Println()\n\x60\x60\x60\n" + cases := []struct { + name string + text string + want bool + }{ + {"atx 标题", "# 标题\n正文\n", true}, + {"围栏代码", fence, true}, + {"图片", "看这张:![a](a.png)\n", true}, + {"行内链接", "见 [文档](https://example.com)\n", true}, + {"表格", "| a | b |\n| --- | --- |\n", true}, + {"setext 下划线", "标题\n====\n", true}, + {"引用", "> 引用一行\n", false}, + {"只有一行列表", "- 一件事\n", false}, + {"三行列表", "- 一\n- 二\n- 三\n", true}, + {"纯散文", "这是一段普通文字,没有任何标记。\n第二行也是。\n", false}, + {"空文件", "", false}, + {"井号但不是标题", "#标签# 写在一起\n", false}, + {"七级井号", "####### 不是标题\n", false}, + {"数字列表", "1. 一\n2. 二\n3. 三\n", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := looksLikeMarkdown([]byte(tc.text)); got != tc.want { + t.Fatalf("looksLikeMarkdown(%q) = %v, want %v", tc.text, got, tc.want) + } + }) + } +} + +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 +} + +func TestMarkdownDocument(t *testing.T) { + dir := t.TempDir() + + md := writeTemp(t, dir, "a.md", []byte("随便什么内容")) + txtTitle := writeTemp(t, dir, "b.txt", []byte("# 一篇笔记\n\n![图](x.png)\n")) + txtProse := writeTemp(t, dir, "c.txt", []byte("这是普通文本。\n没有标记。\n")) + noExt := writeTemp(t, dir, "notes", []byte("# 无后缀的笔记\n")) + binary := writeTemp(t, dir, "d.bin", []byte{0x00, 0x01, 0x02, 0x00}) + png := writeTemp(t, dir, "e.png", []byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00}) + empty := writeTemp(t, dir, "f.txt", nil) + + // UTF-16LE(带 BOM)的标题文档 + units := utf16.Encode([]rune("# 标题\n\n内容\n")) + utf16Bytes := []byte{0xFF, 0xFE} + for _, u := range units { + utf16Bytes = append(utf16Bytes, byte(u), byte(u>>8)) + } + utf16Path := writeTemp(t, dir, "g.txt", utf16Bytes) + + cases := []struct { + name string + path string + want bool + }{ + {".md 直接收", md, true}, + {".txt 但像 Markdown", txtTitle, true}, + {".txt 纯文本", txtProse, false}, + {"无后缀但是 Markdown", noExt, true}, + {"二进制", binary, false}, + {"图片", png, false}, + {"空文件", empty, false}, + {"UTF-16 文档", utf16Path, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := markdownDocument(tc.path); got != tc.want { + t.Fatalf("markdownDocument(%s) = %v, want %v", filepath.Base(tc.path), got, tc.want) + } + }) + } +} + +// 目录展开不再只看后缀:像 Markdown 的 .txt / 无后缀文件要收, +// 二进制与纯文本要被挡在外面,产物仍然先按名字跳掉。 +func TestExpandPathsAcceptsMarkdownByContent(t *testing.T) { + dir := t.TempDir() + writeTemp(t, dir, "a.md", []byte("# 一\n")) + writeTemp(t, dir, "b.txt", []byte("# 二\n\n![图](x.png)\n")) + writeTemp(t, dir, "c.txt", []byte("普通文本。\n")) + writeTemp(t, dir, "d.png", []byte{0x89, 'P', 'N', 'G', 0x00}) + writeTemp(t, dir, "notes", []byte("---\ntitle: 三\n---\n\n# 三\n")) + 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)) + } + want := map[string]bool{"a.md": true, "b.txt": true, "notes": true} + if len(names) != len(want) { + t.Fatalf("收进来的文件不对:%v", names) + } + for _, name := range names { + if !want[name] { + t.Fatalf("不该收 %q(%v)", name, names) + } + } +} diff --git a/web/src/composables/useFileDrop.ts b/web/src/composables/useFileDrop.ts index 78b7439..7c08dee 100644 --- a/web/src/composables/useFileDrop.ts +++ b/web/src/composables/useFileDrop.ts @@ -3,12 +3,17 @@ import { onBeforeUnmount, onMounted, ref } from 'vue' /** * 把文件/目录拖进窗口就等于把它们加进队列。 * - * 两件事都不能省: - * 1. dragover/drop 一定要 preventDefault —— 不拦的话 WebView2 会按浏览器默认行为 - * 直接导航到那个文件(file:///…),界面当场没了,只能重启。 - * 2. 拿到路径。Chromium 系里 `File` 不带本地路径,但拖文件时 `text/uri-list` - * 往往就是 `file:///C:/…`;拖一段文字(比如从记事本里选中的路径)落在 - * `text/plain` 里,那就当路径列表处理。都拿不到时返回空数组,由调用方说明情况。 + * 路径从原生侧来:WebView2 的 DataTransfer 里只有 File 对象,没有本地路径 + * (`File.path` 早被 Chromium 删掉),从资源管理器拖文件时 `text/uri-list` 也是空的。 + * 所以真正的拖放在原生侧接管了 OLE 放置目标(见 cmd/markpic/drop_windows.go), + * 拿到路径后调 `window.__markpicDrop(paths)`;拖入/离开则由 + * `window.__markpicDragOverlay(bool)` 驱动放置态。 + * + * 下面那套 DOM 处理仍然保留,理由有两个: + * 1. dragover/drop 一定要 preventDefault —— 原生接管失败时,不拦的话 WebView2 + * 会按浏览器默认行为直接导航到那个文件(file:///…),界面当场没了。 + * 2. 非 Windows 平台或原生接管失败时,这里还能从 text/uri-list、text/plain + * 里捞一捞(拖一段文字路径也能用)。 */ export interface FileDropHandlers { onPaths: (paths: string[]) => void @@ -115,7 +120,32 @@ export function useFileDrop(handlers: FileDropHandlers) { else handlers.onUnsupported(Array.from(event.dataTransfer?.files ?? []).length > 0) } + type NativeDropBridge = Window & { + /** 原生侧拿到拖入的路径后调用(文件、多个文件、文件夹都一样)。 */ + __markpicDrop?: (paths: unknown) => void + /** 原生侧拖入 / 离开时调用,用来点亮整窗的放置态。 */ + __markpicDragOverlay?: (on: boolean) => void + } + onMounted(() => { + const bridge = window as NativeDropBridge + bridge.__markpicDrop = (paths) => { + if (!Array.isArray(paths)) return + const clean: string[] = [] + const seen = new Set() + for (const item of paths) { + if (typeof item !== 'string') continue + const path = item.trim() + if (path === '' || seen.has(path.toLowerCase())) continue + seen.add(path.toLowerCase()) + clean.push(path) + } + if (clean.length > 0) handlers.onPaths(clean) + } + bridge.__markpicDragOverlay = (on) => { + active.value = on + } + window.addEventListener('dragenter', onDragEnter) window.addEventListener('dragover', onDragOver) window.addEventListener('dragleave', onDragLeave) @@ -123,6 +153,10 @@ export function useFileDrop(handlers: FileDropHandlers) { }) onBeforeUnmount(() => { + const bridge = window as NativeDropBridge + bridge.__markpicDrop = undefined + bridge.__markpicDragOverlay = undefined + window.removeEventListener('dragenter', onDragEnter) window.removeEventListener('dragover', onDragOver) window.removeEventListener('dragleave', onDragLeave) From 31af86fb0f1afc23c2f8c2141177203c1e8d5ff0 Mon Sep 17 00:00:00 2001 From: Mus Date: Thu, 19 Nov 2026 22:43:08 +0800 Subject: [PATCH 04/17] =?UTF-8?q?=E9=98=9F=E5=88=97=EF=BC=9A=E6=8B=96?= =?UTF-8?q?=E5=85=A5=E6=96=87=E4=BB=B6=E5=A4=B9=E5=B0=B1=E5=9C=B0=E5=B1=95?= =?UTF-8?q?=E5=BC=80=E6=88=90=E9=80=90=E4=BB=BD=E6=96=87=E6=A1=A3=E7=9A=84?= =?UTF-8?q?=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以前拖进一个文件夹,队列里只有一张目录卡片,要到点「开始」才会展开成一个个文件。 现在扫描结果一回来就把那一行换成文件卡片:文件夹里 10 份文档就是 10 张卡片, 1 份就是 1 张,队列里不再留目录卡片。 - scan.file 回来时,如果结果里没有与路径完全相同的文件、却有别的文件,说明这是个 目录:就地 splice 成 N 行(复用扫描结果作为行的明细,展开即可看逐图信息), 并重建该页的索引表(展开可能发生在别的页上)。 - 已经在队列里的文件不重复加:重复拖同一个目录、或先拖文件再拖它所在的目录, 都不会出现两张同名卡片。 - 目录卡片那套周边一起清掉:行的 isDir 字段、底栏「N 个目录」分支与两条文案、 stats.dirs、加入队列时按目录前缀去重的逻辑。现在一行的含义重新变成「一份文档」。 - 目录里一份 Markdown 都没有时仍然保留那一行并标「没有找到文件」,否则用户拖了 一个空目录/纯图片目录会看不到任何反馈。 验证:拖入含 4 个 .md、1 个 .txt(表格)、1 个 .log(纯文本)的目录,队列立刻是 5 张卡片(.log 被排除),页头「5 个文件」、底栏「5 个文件 · 4 张图」;重复拖同一 目录仍是 5 张;对着本地 mock 图床跑完上传,4 份 .md 都生成了 .converted.md 且链接已替换。 --- docs/usage.md | 3 +- docs/usage.zh-CN.md | 3 +- web/src/components/AppFooter.vue | 12 +--- web/src/components/FileRow.vue | 2 +- web/src/composables/useRun/commands.ts | 5 -- web/src/composables/useRun/rows.ts | 24 +++++--- web/src/composables/useRun/scan.ts | 85 ++++++++++++++++++-------- web/src/composables/useRun/stats.ts | 2 +- web/src/composables/useRun/types.ts | 10 --- web/src/i18n/en.ts | 2 - web/src/i18n/zh.ts | 2 - 11 files changed, 82 insertions(+), 68 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index d9a2d51..7a52294 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -17,7 +17,8 @@ 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 folder -is scanned recursively, and **the extension is not what decides**: a file counts as a +is scanned recursively and immediately expanded into one card per document — you never +see a folder card. **The extension is not what decides**: a file counts as a document when it is `.md` / `.markdown`, or when its opening bytes look like Markdown (a heading, an image, a link, a table, a fenced block). So `.txt` notes and extension-less fragments are picked up too, while images, archives and other binaries are skipped. diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index 08e3d34..7da22d5 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -15,7 +15,8 @@ - **下载**:只处理远程图,本地图保留。 拖入单个文件、多个文件或整个文件夹都行。路径来自原生放置目标——WebView2 本身拿不到 -拖入文件的本地路径。文件夹会被递归扫描,而且**不是按后缀收文件**:`.md` / `.markdown` +拖入文件的本地路径。文件夹会被递归扫描,并立刻展开成「一个文档一张卡片」—— 队列里不会出现文件夹卡片。 +而且**不是按后缀收文件**:`.md` / `.markdown` 直接收;其它文件看开头像不像 Markdown(标题、图片、链接、表格、围栏代码),像就收。 所以 `.txt` 笔记、没有后缀的片段也会被扫进来,图片、压缩包这类二进制则跳过。 diff --git a/web/src/components/AppFooter.vue b/web/src/components/AppFooter.vue index f7bc683..c68ed64 100644 --- a/web/src/components/AppFooter.vue +++ b/web/src/components/AppFooter.vue @@ -66,17 +66,7 @@ const parts = computed(() => { const stats = props.stats 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 (props.busyElsewhere) list.push({ text: props.busyElsewhere, tone: 'warn' }) list.push( stats.images > 0 diff --git a/web/src/components/FileRow.vue b/web/src/components/FileRow.vue index 7e75288..a01f637 100644 --- a/web/src/components/FileRow.vue +++ b/web/src/components/FileRow.vue @@ -574,7 +574,7 @@ function toggleExpanded(): void { diff --git a/web/src/composables/useRun/commands.ts b/web/src/composables/useRun/commands.ts index 9c0afc9..33d7948 100644 --- a/web/src/composables/useRun/commands.ts +++ b/web/src/composables/useRun/commands.ts @@ -59,10 +59,6 @@ export function addPaths(input: string[]): string[] { if (phase.value === 'done' || phase.value === 'cancelled') resetOutcome() const known = new Set(rows.value.map(row => pathKey(row.path))) - // 已经在队列里的目录,它下面的文件开跑时会被那个目录一起扫出来。 - // 这时候再单独加一份文件,等于同一篇文档进队列两次:页脚会把图片数算两遍, - // 跑完还会看到两行同名结果。所以目录里的路径直接并进那行目录,不再新开一行。 - const dirPrefixes = rows.value.filter(row => row.isDir).map(row => pathKey(row.path) + '\\') const added: string[] = [] for (const raw of input) { @@ -70,7 +66,6 @@ export function addPaths(input: string[]): string[] { if (path === '') continue const key = pathKey(path) if (key === '' || known.has(key)) continue - if (dirPrefixes.some(prefix => key.startsWith(prefix))) continue known.add(key) added.push(path) const { name, dir } = splitPath(path) diff --git a/web/src/composables/useRun/rows.ts b/web/src/composables/useRun/rows.ts index 56ddf05..aca94ad 100644 --- a/web/src/composables/useRun/rows.ts +++ b/web/src/composables/useRun/rows.ts @@ -7,7 +7,8 @@ import { markRaw, shallowReactive } from 'vue' import type { FileResult, RemoteMode, RunFileInfo } from '../../types' import { t } from '../../i18n' -import { activePage, eventIndex, lastReveal, live, pathIndex, revealIndex, rowIndex, rows } from './page' +import { activePage, eventIndex, lastReveal, live, pages, pathIndex, revealIndex, rowIndex, rows } from './page' +import type { QueuePage } from './page' import { emptyCounters } from './types' import { pathKey } from './paths' import type { RunRow } from './types' @@ -62,17 +63,22 @@ export function rowAt(id: string): RunRow | null { return rows.value[index] ?? null } -export function reindexRows(): void { - rowIndex.clear() - eventIndex.clear() - pathIndex.clear() - rows.value.forEach((row, index) => { - rowIndex.set(row.id, index) - if (row.serverId) eventIndex.set(row.serverId, index) - pathIndex.set(pathKey(row.path), index) +/** 重建某一页的三张索引表。目录展开时别的页也可能在动,所以要能按页重建。 */ +export function reindexPage(page: QueuePage): void { + page.rowIndex.clear() + page.eventIndex.clear() + page.pathIndex.clear() + page.rows.forEach((row, index) => { + page.rowIndex.set(row.id, index) + if (row.serverId) page.eventIndex.set(row.serverId, index) + page.pathIndex.set(pathKey(row.path), index) }) } +export function reindexRows(): void { + reindexPage(pages[activePage]) +} + export function pushRow(row: RunRow): void { rowIndex.set(row.id, rows.value.length) if (row.serverId) eventIndex.set(row.serverId, rows.value.length) diff --git a/web/src/composables/useRun/scan.ts b/web/src/composables/useRun/scan.ts index c0ab530..27fdf76 100644 --- a/web/src/composables/useRun/scan.ts +++ b/web/src/composables/useRun/scan.ts @@ -9,9 +9,9 @@ import { markRaw } from 'vue' import { cancelScan as requestCancelScan, describeError, scanStart as requestScanStart } from '../../api' import type { FileResult, RemoteMode, ScanEvent } from '../../types' import { t } from '../../i18n' -import { activePage, pageRows, rows } from './page' -import { pathKey } from './paths' -import { seedImagesFromRows } from './rows' +import { activePage, pages, pageRows, rows } from './page' +import { pathKey, splitPath } from './paths' +import { reindexPage, seedImagesFromRows } from './rows' import type { RunRow, ScanState } from './types' /* ---------------- 扫描(每张卡片自己扫) ---------------- */ @@ -48,12 +48,15 @@ export function rowOfPage(mode: RemoteMode, path: string): RunRow | undefined { } /** - * 把一份文件(或一个目录下的若干文件)的扫描结果写到行上。 + * 把一份路径的扫描结果写到行上。 * - * 目录行没有「自己」的结果 —— 前缀命中的那些加起来就是它的张数,和以前 - * preview 的做法一致;一份都没命中说明路径不存在或目录里没有 Markdown。 + * 三种情况: + * - 结果里有路径完全相同的文件:那就是这一份文档,直接落数; + * - 一条结果都没有:路径不存在,或目录里没有一份能当成 Markdown 的文件; + * - 结果里有别的文件:说明拖进来的其实是个目录 —— 把这一行就地换成 + * 文件一张卡片、目录本身不留(见 expandDirectoryRow)。 */ -export function writeScanResult(row: RunRow, files: readonly FileResult[]): void { +export function writeScanResult(mode: RemoteMode, row: RunRow, files: readonly FileResult[]): void { const key = pathKey(row.path) const exact = files.find((file) => pathKey(file.path) === key) if (exact) { @@ -61,27 +64,60 @@ export function writeScanResult(row: RunRow, files: readonly FileResult[]): void row.images = exact.images row.total = exact.images row.missing = false - row.isDir = false return } - const prefix = `${key}\\` - let sum = 0 - let matched = false - for (const file of files) { - if (pathKey(file.path).startsWith(prefix)) { - sum += file.images - matched = true - } - } - if (matched) { - row.images = sum - row.total = sum - row.missing = false - row.isDir = true - } else { + if (files.length === 0) { row.missing = true + row.images = null + return + } + + expandDirectoryRow(mode, row, files) +} + +/** + * 把一个目录行就地展开成逐份文档的卡片。 + * + * 队列里一张卡片就该对应一份要处理的文档;目录只是用户拖进来的那个路径, + * 真正要处理的是它展开出来的文件。展开只能发生在扫描结果回来的时候 —— + * 只有那一刻才知道目录里到底有哪些文件(以及哪些算 Markdown)。 + * + * 已经在队列里的文件不重复加:同一个文件只能有一张卡片。 + */ +function expandDirectoryRow(mode: RemoteMode, row: RunRow, files: readonly FileResult[]): void { + const page = pages[mode] + const index = page.rows.indexOf(row) + if (index < 0) return + + const known = new Set(page.rows.map((item) => pathKey(item.path))) + known.delete(pathKey(row.path)) // 这一行马上要被换掉 + + const expanded: RunRow[] = [] + for (const file of files) { + const key = pathKey(file.path) + if (known.has(key)) continue + known.add(key) + const fallback = splitPath(file.path) + expanded.push({ + id: `local-${++page.localSeq}`, + path: file.path, + name: file.name || fallback.name, + dir: file.dir || fallback.dir, + images: file.images, + phase: 'queued', + uploaded: 0, + total: file.images, + // 扫描结果就是这一份的明细:展开行时逐图信息直接有出处。 + result: markRaw(file), + scan: 'ok', + }) } + + // 原地替换(不是换数组):rows 就是这一页的数组引用,splice 才能让界面看到变化。 + page.rows.splice(index, 1, ...expanded) + reindexPage(page) + if (mode === activePage) seedImagesFromRows() } /** 收掉一批:清计时器、从表里摘掉,把没等到结果的行按 state 结掉。 */ @@ -184,7 +220,7 @@ export function onScanEvent(event: ScanEvent): void { return } - writeScanResult(row, files) + writeScanResult(batch.mode, row, files) row.scan = 'ok' row.scanError = undefined row.scanBatch = undefined @@ -239,4 +275,3 @@ export function cancelPageScans(): void { requestBatchCancel(batch) } } - diff --git a/web/src/composables/useRun/stats.ts b/web/src/composables/useRun/stats.ts index 8945f56..e83f873 100644 --- a/web/src/composables/useRun/stats.ts +++ b/web/src/composables/useRun/stats.ts @@ -33,7 +33,7 @@ export const stats = computed(() => ({ // 否则底栏的文件数会随着进度往上跳。开跑时目录会展开成一个个文件, // 所以跑起来之后 dirs 自然回到 0。 files: rows.value.length, - dirs: rows.value.reduce((n, row) => n + (row.isDir ? 1 : 0), 0), + // 引用数是「队列里一共多少张」,不是「已经处理了几张」:底栏那行是读队列, // 进度由页头的百分比和「替换 N」负责。 images: rows.value.reduce((n, row) => n + (row.images ?? row.total), 0), diff --git a/web/src/composables/useRun/types.ts b/web/src/composables/useRun/types.ts index cdfa71c..fd85660 100644 --- a/web/src/composables/useRun/types.ts +++ b/web/src/composables/useRun/types.ts @@ -31,14 +31,6 @@ export interface RunRow { total: number /** 预览跑过之后仍然没有任何文件与之匹配(路径不存在,或目录里没有 Markdown)。 */ missing?: boolean - /** - * 这一行是个目录:真正的文档要等开跑时才展开成一行一个。 - * - * 预览是按前缀把目录里的图片数加起来的,所以能分辨出「这一行不是文档」。 - * 底栏靠它说「1 个目录」而不是「1 个文件」—— 粘一个目录进去却看到「1 个文件」, - * 用户会以为只有一篇会被处理。 - */ - isDir?: boolean /** * 这一行的转换结果(或预检结果)。 * @@ -84,8 +76,6 @@ export type RunRowView = RunRow export interface RunStats { files: number - /** 队列里那些还没展开的目录行有几行(开跑之后目录展开成文件,这里回到 0)。 */ - dirs: number images: number // uploaded 是「替换了几处」,与行上的 done(处理了几张图)不是一个东西。 uploaded: number diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index 43273e8..0cbb809 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -238,8 +238,6 @@ export const en: Record = { 'footer.queueEmpty': 'Queue is empty', 'footer.files': '{count} files', 'footer.files.one': '{count} file', - 'footer.filesAndDirs': '{files} file(s) · {dirs} folder(s)', - 'footer.dirsOnly': '{dirs} folders', 'footer.images': '{count} images', 'footer.images.one': '{count} image', 'footer.noImages': 'No images found', diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index 65cfd2d..7fb9fe0 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -235,8 +235,6 @@ export const zh = { 'footer.queueEmpty': '队列为空', 'footer.files': '{count} 个文件', 'footer.files.one': '{count} 个文件', - 'footer.filesAndDirs': '{files} 个文件 · {dirs} 个目录', - 'footer.dirsOnly': '{dirs} 个目录', 'footer.images': '{count} 张图', 'footer.images.one': '{count} 张图', 'footer.noImages': '未发现图片', From f8779f4e77ec0083e6d37065e4bcce0e0397423f Mon Sep 17 00:00:00 2001 From: Mus Date: Thu, 19 Nov 2026 23:10:17 +0800 Subject: [PATCH 05/17] =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9=E5=B1=95?= =?UTF-8?q?=E5=BC=80=EF=BC=9A=E6=89=80=E6=9C=89=E6=96=87=E6=9C=AC=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E9=83=BD=E7=AE=97=E6=96=87=E6=A1=A3=EF=BC=8C=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E6=8C=89=20Markdown=20=E7=BB=93=E6=9E=84=E8=BF=87?= =?UTF-8?q?=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一版按「内容像不像 Markdown」筛选,纯文本的 .txt / .log 会被静默跳过 —— 用户看到的是「文件夹里有 3 个,队列里只有 2 张卡片」,而且无从知道少的是哪一个。 现在判据只有一条:它是不是文本文件。 - .md / .markdown 直接收(不读盘);其它文件先按后缀排掉明显的二进制 (图片、压缩包、可执行文件、音视频、PDF、Office),再读开头 64KB 确认没有 NUL, UTF-16 带 BOM 的照常认。 - 于是 .txt、.log、无后缀的笔记都会出现在队列里,哪怕里面一张要上传的图都没有; 卡片数因此永远和文件夹里对得上。 - 删掉整套「像不像 Markdown」的启发式(标题/图片/链接/表格/围栏代码/Setext), 连带它的测试;文件改名为 document_detect.go。 验证:目录里放 a.md + b.txt(无标记)+ c.log + notes(无后缀)+ images/ok.png, 拖入后队列是 4 张卡片,png 被排除;go test ./internal/... 全绿(用例改为验证 「文本收、二进制不收」)。 --- docs/usage.md | 8 +- docs/usage.zh-CN.md | 6 +- internal/conv/collect.go | 8 +- internal/conv/document_detect.go | 115 ++++++++++++++ internal/conv/document_detect_test.go | 98 ++++++++++++ internal/conv/markdown_detect.go | 209 -------------------------- internal/conv/markdown_detect_test.go | 127 ---------------- 7 files changed, 224 insertions(+), 347 deletions(-) create mode 100644 internal/conv/document_detect.go create mode 100644 internal/conv/document_detect_test.go delete mode 100644 internal/conv/markdown_detect.go delete mode 100644 internal/conv/markdown_detect_test.go diff --git a/docs/usage.md b/docs/usage.md index 7a52294..687c0b8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -18,10 +18,10 @@ 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 folder is scanned recursively and immediately expanded into one card per document — you never -see a folder card. **The extension is not what decides**: a file counts as a -document when it is `.md` / `.markdown`, or when its opening bytes look like Markdown -(a heading, an image, a link, a table, a fenced block). So `.txt` notes and extension-less -fragments are picked up too, while images, archives and other binaries are skipped. +see a folder card. **Every text file counts**: `.md`, `.txt`, `.log`, extension-less +notes, whether or not it has an image to upload. A document with nothing to upload still +gets a card, so the queue always matches what is in the folder. Only binaries are skipped: +images, archives, executables, PDFs and Office files. 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 diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index 7da22d5..bf39d57 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -16,9 +16,9 @@ 拖入单个文件、多个文件或整个文件夹都行。路径来自原生放置目标——WebView2 本身拿不到 拖入文件的本地路径。文件夹会被递归扫描,并立刻展开成「一个文档一张卡片」—— 队列里不会出现文件夹卡片。 -而且**不是按后缀收文件**:`.md` / `.markdown` -直接收;其它文件看开头像不像 Markdown(标题、图片、链接、表格、围栏代码),像就收。 -所以 `.txt` 笔记、没有后缀的片段也会被扫进来,图片、压缩包这类二进制则跳过。 +**所有文本文件都算文档**:`.md`、`.txt`、`.log`、没有后缀的片段,不管里面有没有要上传的 +图片,都会出现在队列里 —— 卡片数永远和文件夹里对得上,不会出现「明明有 3 个只显示 2 个」。 +只有二进制被跳过:图片、压缩包、可执行文件、PDF、Office 文档。 看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 同一张图只上传一次;已经上传/下载过且内容未变的图直接复用。 diff --git a/internal/conv/collect.go b/internal/conv/collect.go index c9112e2..770380e 100644 --- a/internal/conv/collect.go +++ b/internal/conv/collect.go @@ -72,10 +72,10 @@ func ExpandPaths(paths []string, suffix, skipDir string) (files []string, missin skipped = append(skipped, path) return nil } - // 后缀不再是唯一标准:目录里可能有 .txt、无后缀的片段,甚至 - // 别的编辑器存的 .markdown。收不收由内容判断(见 markdown_detect.go), - // 里面先按后缀与二进制特征把读盘省掉。 - if !markdownDocument(path) { + // 后缀不再是标准:目录里可能有 .txt、.log、无后缀的片段。 + // 只要是文本文件就收(见 document_detect.go),这样「文件夹里有几份 + // 文档就有几张卡片」,不会因为内容里恰好没有 Markdown 标记而被悄悄跳过。 + if !documentFile(path) { return nil } add(path) diff --git a/internal/conv/document_detect.go b/internal/conv/document_detect.go new file mode 100644 index 0000000..8452be9 --- /dev/null +++ b/internal/conv/document_detect.go @@ -0,0 +1,115 @@ +package conv + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + + "github.com/geekMus/markpic/internal/textenc" +) + +// 目录展开时收哪些文件。 +// +// 判据只有一条:**它是不是一个文本文件**。不按后缀点名,也不看内容「像不像 +// Markdown」—— 用户把整个目录拖进来时,期待的是「文件夹里有几份文档就有几张卡片」, +// 任何额外的过滤都会让卡片数对不上,而用户并不知道我们偷偷排掉了哪一个。 +// +// 只有二进制会被跳过:图片、压缩包、可执行文件、音视频、Office 文档。它们本来就不是 +// 文档,收进来只会得到一堆「解码失败」的卡片,反而添乱。 +// +// 判断必须便宜:一个目录里可能混着几千个文件,所以先按后缀排掉明显的二进制, +// 再只读开头一小段确认没有 NUL。 + +// docSniffBytes 是嗅探时最多读多少:看清是不是文本够了,不至于把几百兆的日志读进来。 +const docSniffBytes = 64 << 10 + +// binaryExts 是「一眼看出不是文档」的后缀。先按名字排掉,省掉大量无谓的读盘。 +var binaryExts = map[string]bool{ + // 图片 + ".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true, ".bmp": true, + ".ico": true, ".tif": true, ".tiff": true, ".avif": true, ".psd": true, + // 压缩包 + ".zip": true, ".7z": true, ".rar": true, ".gz": true, ".tar": true, ".bz2": true, ".xz": true, ".zst": true, + // 可执行与库 + ".exe": true, ".dll": true, ".sys": true, ".so": true, ".dylib": true, ".bin": true, + ".class": true, ".o": true, ".a": true, ".lib": true, ".pdb": true, ".obj": true, + // 音视频 + ".mp4": true, ".mov": true, ".avi": true, ".mkv": true, ".webm": true, ".flv": true, + ".mp3": true, ".wav": true, ".flac": true, ".ogg": true, ".m4a": true, ".aac": true, + // 办公文档与 PDF + ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, + ".ppt": true, ".pptx": true, ".odt": true, ".ods": true, + // 字体与数据库 + ".ttf": true, ".otf": true, ".woff": true, ".woff2": true, ".eot": true, + ".db": true, ".sqlite": true, ".sqlite3": true, ".mdb": true, +} + +// documentFile 判断这个路径能不能当文档处理。 +func documentFile(path string) bool { + ext := strings.ToLower(filepath.Ext(path)) + switch ext { + case ".md", ".markdown", ".mdown", ".mkd", ".mdwn": + return true // 后缀已经说明问题了,不必读盘 + } + if binaryExts[ext] { + return false + } + raw, ok := readHead(path) + if !ok { + return false + } + _, ok = textHead(raw) + return ok +} + +// readHead 读文件开头一小段。 +func readHead(path string) ([]byte, bool) { + f, err := os.Open(path) + if err != nil { + return nil, false + } + defer func() { _ = f.Close() }() + buf := make([]byte, docSniffBytes) + n, err := io.ReadFull(f, buf) + if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF { + return nil, false + } + if n == 0 { + return nil, false + } + return buf[:n], true +} + +// textHead 把开头一段变成可以扫的字节,顺便否掉二进制。 +// +// UTF-8 与 ANSI 里的 ASCII 都还是原样字节(GBK 的尾字节只会 >=0x80),所以这两种 +// 编码不必解码;只有 UTF-16 必须转换(它的 ASCII 字节里全是 0)。 +func textHead(raw []byte) ([]byte, bool) { + switch { + case bytes.HasPrefix(raw, []byte{0xFF, 0xFE}), bytes.HasPrefix(raw, []byte{0xFE, 0xFF}): + // 截断可能落在代理对中间:先按偶数裁一刀,再不行就少两个字节重试。 + if len(raw)%2 == 1 { + raw = raw[:len(raw)-1] + } + if text, err := textenc.Decode(raw, textenc.Detect(raw)); err == nil { + return text, true + } + if len(raw) > 4 { + if text, err := textenc.Decode(raw[:len(raw)-2], textenc.Detect(raw)); err == nil { + return text, true + } + } + return nil, false + } + // 二进制文件(可执行、图片、压缩包)几乎都在开头几个字节里带 NUL。 + probe := raw + if len(probe) > 8192 { + probe = probe[:8192] + } + if bytes.IndexByte(probe, 0) >= 0 { + return nil, false + } + return raw, true +} diff --git a/internal/conv/document_detect_test.go b/internal/conv/document_detect_test.go new file mode 100644 index 0000000..729bdf3 --- /dev/null +++ b/internal/conv/document_detect_test.go @@ -0,0 +1,98 @@ +package conv + +import ( + "os" + "path/filepath" + "testing" + "unicode/utf16" +) + +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」那条会把纯文本笔记排掉, +// 于是「文件夹里 3 份、队列里 2 张卡片」,用户无从知道少的是哪一个。 +func TestDocumentFile(t *testing.T) { + dir := t.TempDir() + + md := writeTemp(t, dir, "a.md", []byte("随便什么内容")) + plain := writeTemp(t, dir, "b.txt", []byte("普通文本,没有任何标记。\n")) + log := writeTemp(t, dir, "c.log", []byte("2026-11-19 22:00:00 INFO 启动\n")) + noExt := writeTemp(t, dir, "notes", []byte("无后缀的片段\n")) + binary := writeTemp(t, dir, "d.bin", []byte{0x00, 0x01, 0x02, 0x00}) + png := writeTemp(t, dir, "e.png", []byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00}) + empty := writeTemp(t, dir, "f.txt", nil) + + // UTF-16LE(带 BOM)的文本:ASCII 字节里全是 0,但不能当成二进制 + units := utf16.Encode([]rune("# 标题\n\n内容\n")) + utf16Bytes := []byte{0xFF, 0xFE} + for _, u := range units { + utf16Bytes = append(utf16Bytes, byte(u), byte(u>>8)) + } + utf16Path := writeTemp(t, dir, "g.txt", utf16Bytes) + + cases := []struct { + name string + path string + want bool + }{ + {".md", md, true}, + {"纯文本 .txt", plain, true}, + {"日志 .log", log, true}, + {"无后缀", noExt, true}, + {"二进制", binary, false}, + {"图片", png, false}, + {"空文件", empty, false}, + {"UTF-16 文本", utf16Path, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := documentFile(tc.path); got != tc.want { + t.Fatalf("documentFile(%s) = %v, want %v", filepath.Base(tc.path), got, tc.want) + } + }) + } +} + +// 目录展开:所有文本文件都收(不管内容里有没有 Markdown 标记), +// 二进制跳过,上一轮的产物仍然先按名字跳掉。 +func TestExpandPathsAcceptsEveryTextFile(t *testing.T) { + dir := t.TempDir() + writeTemp(t, dir, "a.md", []byte("# 一\n")) + writeTemp(t, dir, "b.txt", []byte("普通文本,没有标记。\n")) + writeTemp(t, dir, "c.log", []byte("2026-11-19 22:00:00 INFO 一行日志\n")) + writeTemp(t, dir, "d.png", []byte{0x89, 'P', 'N', 'G', 0x00}) + writeTemp(t, dir, "notes", []byte("无后缀的片段\n")) + 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)) + } + want := map[string]bool{"a.md": true, "b.txt": true, "c.log": true, "notes": true} + if len(names) != len(want) { + t.Fatalf("收进来的文件不对:%v", names) + } + for _, name := range names { + if !want[name] { + t.Fatalf("不该收 %q(%v)", name, names) + } + } +} diff --git a/internal/conv/markdown_detect.go b/internal/conv/markdown_detect.go deleted file mode 100644 index e8c4825..0000000 --- a/internal/conv/markdown_detect.go +++ /dev/null @@ -1,209 +0,0 @@ -package conv - -import ( - "bytes" - "io" - "os" - "path/filepath" - "strings" - - "github.com/geekMus/markpic/internal/textenc" -) - -// 目录里不一定只有 .md:笔记软件的导出、静态站点的源文件、没后缀的片段,都可能是 -// Markdown。后缀只当「先信一次」的快捷判断,真正决定收不收的是内容。 -// -// 判断必须便宜:一个目录里可能混着几千个文件,所以先按后缀排掉明显不是文档的, -// 再只读开头一小段。「像不像 Markdown」看的是结构(标题、链接、图片、围栏代码、 -// 表格),不是「能不能被解析」—— 任何纯文本都能被当成 Markdown,那样等于全都收。 - -// markdownSniffBytes 是嗅探时最多读多少:看清结构够了,又不至于把几百兆的日志读进来。 -const markdownSniffBytes = 64 << 10 - -// 围栏代码的三个反引号(写成字节,免得源码里出现三连反引号)。 -var fenceBacktick = []byte{0x60, 0x60, 0x60} - -// binaryExts 是「一眼看出不是文档」的后缀。先按名字排掉,省掉大量无谓的读盘; -// 没有列到的(比如 .txt / .log / 无后缀)仍然会读一小段再看内容。 -var binaryExts = map[string]bool{ - // 图片 - ".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true, ".bmp": true, - ".ico": true, ".tif": true, ".tiff": true, ".avif": true, ".psd": true, - // 压缩包 - ".zip": true, ".7z": true, ".rar": true, ".gz": true, ".tar": true, ".bz2": true, ".xz": true, ".zst": true, - // 可执行与库 - ".exe": true, ".dll": true, ".sys": true, ".so": true, ".dylib": true, ".bin": true, - ".class": true, ".o": true, ".a": true, ".lib": true, ".pdb": true, ".obj": true, - // 音视频 - ".mp4": true, ".mov": true, ".avi": true, ".mkv": true, ".webm": true, ".flv": true, - ".mp3": true, ".wav": true, ".flac": true, ".ogg": true, ".m4a": true, ".aac": true, - // 办公文档与 PDF - ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, - ".ppt": true, ".pptx": true, ".odt": true, ".ods": true, - // 字体与数据库 - ".ttf": true, ".otf": true, ".woff": true, ".woff2": true, ".eot": true, - ".db": true, ".sqlite": true, ".sqlite3": true, ".mdb": true, -} - -// markdownDocument 判断这个路径能不能当文档处理。 -func markdownDocument(path string) bool { - ext := strings.ToLower(filepath.Ext(path)) - switch ext { - case ".md", ".markdown", ".mdown", ".mkd", ".mdwn": - return true // 后缀已经说明问题了,不必读盘 - } - if binaryExts[ext] { - return false - } - raw, ok := readHead(path) - if !ok { - return false - } - text, ok := textHead(raw) - if !ok { - return false - } - return looksLikeMarkdown(text) -} - -// readHead 读文件开头一小段。 -func readHead(path string) ([]byte, bool) { - f, err := os.Open(path) - if err != nil { - return nil, false - } - defer func() { _ = f.Close() }() - buf := make([]byte, markdownSniffBytes) - n, err := io.ReadFull(f, buf) - if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF { - return nil, false - } - if n == 0 { - return nil, false - } - return buf[:n], true -} - -// textHead 把开头一段变成可以扫的字节,顺便否掉二进制。 -// -// UTF-8 与 ANSI 里的 ASCII 标记都还是原样字节(GBK 的尾字节只会 >=0x80), -// 所以这两种编码不必解码就能扫;只有 UTF-16 必须转换。 -func textHead(raw []byte) ([]byte, bool) { - switch { - case bytes.HasPrefix(raw, []byte{0xFF, 0xFE}), bytes.HasPrefix(raw, []byte{0xFE, 0xFF}): - // 截断可能落在代理对中间:先按偶数裁一刀,再不行就少两个字节重试。 - if len(raw)%2 == 1 { - raw = raw[:len(raw)-1] - } - if text, err := textenc.Decode(raw, textenc.Detect(raw)); err == nil { - return text, true - } - if len(raw) > 4 { - if text, err := textenc.Decode(raw[:len(raw)-2], textenc.Detect(raw)); err == nil { - return text, true - } - } - return nil, false - } - // 二进制文件(可执行、图片、压缩包)几乎都在开头几个字节里带 NUL。 - probe := raw - if len(probe) > 8192 { - probe = probe[:8192] - } - if bytes.IndexByte(probe, 0) >= 0 { - return nil, false - } - return raw, true -} - -// looksLikeMarkdown 看这段文本有没有 Markdown 的结构。 -// -// 强信号(任意一处即可):围栏代码、ATX 标题、图片、行内链接、表格、Setext 下划线。 -// 弱信号(三处以上):列表项、引用。单独一行「- 某某」的纯文本太常见了,只有一处 -// 就不该把整个文件当成文档。 -func looksLikeMarkdown(data []byte) bool { - strong := 0 - weak := 0 - prevText := false - for _, line := range bytes.Split(data, []byte("\n")) { - line = bytes.TrimRight(line, "\r") - trimmed := bytes.TrimLeft(line, " \t") - if len(trimmed) == 0 { - continue - } - switch { - case bytes.HasPrefix(trimmed, fenceBacktick), bytes.HasPrefix(trimmed, []byte("~~~")): - strong++ - case isATXHeading(trimmed): - strong++ - case bytes.Contains(line, []byte("![")): - strong++ - case bytes.Contains(line, []byte("](")): - strong++ - case isTableRow(trimmed): - strong++ - case prevText && isSetextUnderline(trimmed): - strong++ - case isListItem(line), bytes.Equal(trimmed, []byte(">")), bytes.HasPrefix(trimmed, []byte("> ")): - weak++ - } - prevText = true - } - return strong >= 1 || weak >= 3 -} - -// isATXHeading 判断「## 标题」这种写法(# 的数量 1~6,后面必须是空格或行尾)。 -func isATXHeading(line []byte) bool { - n := 0 - for n < len(line) && line[n] == '#' { - n++ - } - if n == 0 || n > 6 { - return false - } - if n == len(line) { - return true - } - return line[n] == ' ' || line[n] == '\t' -} - -// isListItem 判断「- 项」/「* 项」/「+ 项」/「1. 项」。 -func isListItem(line []byte) bool { - trimmed := bytes.TrimLeft(line, " \t") - if len(trimmed) >= 2 && (trimmed[0] == '-' || trimmed[0] == '*' || trimmed[0] == '+') { - return trimmed[1] == ' ' || trimmed[1] == '\t' - } - i := 0 - for i < len(trimmed) && trimmed[i] >= '0' && trimmed[i] <= '9' { - i++ - } - if i == 0 || i+1 >= len(trimmed) { - return false - } - return trimmed[i] == '.' && (trimmed[i+1] == ' ' || trimmed[i+1] == '\t') -} - -// isTableRow 判断「| a | b |」这种整行(首尾都是竖线、至少两列)。 -func isTableRow(trimmed []byte) bool { - if len(trimmed) < 3 || trimmed[0] != '|' || trimmed[len(trimmed)-1] != '|' { - return false - } - return bytes.Count(trimmed, []byte("|")) >= 2 -} - -// isSetextUnderline 判断「===」/「---」这种标题下划线。 -func isSetextUnderline(trimmed []byte) bool { - if len(trimmed) < 3 { - return false - } - ch := trimmed[0] - if ch != '=' && ch != '-' { - return false - } - for _, c := range trimmed { - if c != ch { - return false - } - } - return true -} diff --git a/internal/conv/markdown_detect_test.go b/internal/conv/markdown_detect_test.go deleted file mode 100644 index 65595e1..0000000 --- a/internal/conv/markdown_detect_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package conv - -import ( - "os" - "path/filepath" - "testing" - "unicode/utf16" -) - -func TestLooksLikeMarkdown(t *testing.T) { - fence := "\x60\x60\x60go\nfmt.Println()\n\x60\x60\x60\n" - cases := []struct { - name string - text string - want bool - }{ - {"atx 标题", "# 标题\n正文\n", true}, - {"围栏代码", fence, true}, - {"图片", "看这张:![a](a.png)\n", true}, - {"行内链接", "见 [文档](https://example.com)\n", true}, - {"表格", "| a | b |\n| --- | --- |\n", true}, - {"setext 下划线", "标题\n====\n", true}, - {"引用", "> 引用一行\n", false}, - {"只有一行列表", "- 一件事\n", false}, - {"三行列表", "- 一\n- 二\n- 三\n", true}, - {"纯散文", "这是一段普通文字,没有任何标记。\n第二行也是。\n", false}, - {"空文件", "", false}, - {"井号但不是标题", "#标签# 写在一起\n", false}, - {"七级井号", "####### 不是标题\n", false}, - {"数字列表", "1. 一\n2. 二\n3. 三\n", true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := looksLikeMarkdown([]byte(tc.text)); got != tc.want { - t.Fatalf("looksLikeMarkdown(%q) = %v, want %v", tc.text, got, tc.want) - } - }) - } -} - -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 -} - -func TestMarkdownDocument(t *testing.T) { - dir := t.TempDir() - - md := writeTemp(t, dir, "a.md", []byte("随便什么内容")) - txtTitle := writeTemp(t, dir, "b.txt", []byte("# 一篇笔记\n\n![图](x.png)\n")) - txtProse := writeTemp(t, dir, "c.txt", []byte("这是普通文本。\n没有标记。\n")) - noExt := writeTemp(t, dir, "notes", []byte("# 无后缀的笔记\n")) - binary := writeTemp(t, dir, "d.bin", []byte{0x00, 0x01, 0x02, 0x00}) - png := writeTemp(t, dir, "e.png", []byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00}) - empty := writeTemp(t, dir, "f.txt", nil) - - // UTF-16LE(带 BOM)的标题文档 - units := utf16.Encode([]rune("# 标题\n\n内容\n")) - utf16Bytes := []byte{0xFF, 0xFE} - for _, u := range units { - utf16Bytes = append(utf16Bytes, byte(u), byte(u>>8)) - } - utf16Path := writeTemp(t, dir, "g.txt", utf16Bytes) - - cases := []struct { - name string - path string - want bool - }{ - {".md 直接收", md, true}, - {".txt 但像 Markdown", txtTitle, true}, - {".txt 纯文本", txtProse, false}, - {"无后缀但是 Markdown", noExt, true}, - {"二进制", binary, false}, - {"图片", png, false}, - {"空文件", empty, false}, - {"UTF-16 文档", utf16Path, true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := markdownDocument(tc.path); got != tc.want { - t.Fatalf("markdownDocument(%s) = %v, want %v", filepath.Base(tc.path), got, tc.want) - } - }) - } -} - -// 目录展开不再只看后缀:像 Markdown 的 .txt / 无后缀文件要收, -// 二进制与纯文本要被挡在外面,产物仍然先按名字跳掉。 -func TestExpandPathsAcceptsMarkdownByContent(t *testing.T) { - dir := t.TempDir() - writeTemp(t, dir, "a.md", []byte("# 一\n")) - writeTemp(t, dir, "b.txt", []byte("# 二\n\n![图](x.png)\n")) - writeTemp(t, dir, "c.txt", []byte("普通文本。\n")) - writeTemp(t, dir, "d.png", []byte{0x89, 'P', 'N', 'G', 0x00}) - writeTemp(t, dir, "notes", []byte("---\ntitle: 三\n---\n\n# 三\n")) - 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)) - } - want := map[string]bool{"a.md": true, "b.txt": true, "notes": true} - if len(names) != len(want) { - t.Fatalf("收进来的文件不对:%v", names) - } - for _, name := range names { - if !want[name] { - t.Fatalf("不该收 %q(%v)", name, names) - } - } -} From b046925f5e10e39cbcdf7e00e8b58b43f2cfec6e Mon Sep 17 00:00:00 2001 From: Mus Date: Fri, 20 Nov 2026 00:03:11 +0800 Subject: [PATCH 06/17] =?UTF-8?q?=E6=89=AB=E6=8F=8F=EF=BC=9A=E8=BE=B9?= =?UTF-8?q?=E9=81=8D=E5=8E=86=E8=BE=B9=E4=B8=8A=E6=8A=A5=E8=BF=9B=E5=BA=A6?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89=E6=80=BB=E6=97=B6=E9=95=BF=E4=B8=8A?= =?UTF-8?q?=E9=99=90=EF=BC=8C=E6=94=AF=E6=8C=81=E9=9A=8F=E6=97=B6=E5=81=9C?= =?UTF-8?q?=E6=AD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以前是「一个路径一个协程,整棵树走完才推一条结果,整条路径 20 秒封顶」:拖一整块盘 必然超时,超时之前界面上只有「扫描中」,看不出任何进展,出问题也没法体面地停。 Go 侧: - 新增 conv.WalkDocuments:并行遍历(8 个协程读目录),发现一份文档就回调一份; 计数用 WalkCounts 实时累加,进度事件读的就是它,不必等走完。 - 扫描管线改成:遍历 → 文档进队列 → 固定协程池并行解析(每份各自 20 秒上限, 整批共享 docSlots 限制同时解析数)→ 每份推一条 scan.file,每 120ms 推一条 scan.progress。路径的 20 秒总上限删掉了。 - conv.Runner.ScanOne:只扫一份文档(不派工、不写盘、不汇总),供并行扫描复用。 - scan.cancel 立即生效:在途的那一份丢掉,已经推出去的保留。 前端: - 拖进来的目录行变成「扫描期间的宿主」:显示「扫描中 · 已找到 N 份」,文件一份份 追加到队列末尾(O(1),不再整体挪动);扫完宿主行自动摘掉。 - 超时改成「30 秒没有任何事件」才判死,扫描再久也不会被误杀。 - 点「取消扫描」先弹确认框;确认后已扫到的留在队列里,并提示「队列里只有扫到的部分」。 - 新增通用的 ConfirmDialog 组件。 - 修一个 bug:事件路由只把 scan.file/scan.done 交给扫描模块,新增的 scan.progress 因此被丢掉(表现是进度一直是 0);改成按 scan. 前缀路由。 验证:go test ./internal/... 全绿(新增流式扫描与取消两个用例);真实窗口拖 8000 份文档的目录,宿主行从 365 → 594 → 972 → 1212 → 1581 → 1944 滚动增长;拖 30000 份的目录并在中途停止,确认框出现,停止后队列保留 1291 份、宿主行消失、弹出提示。 --- docs/usage.md | 6 + docs/usage.zh-CN.md | 4 + internal/app/app_test.go | 84 +++++++++ internal/app/scan.go | 242 ++++++++++++++++++------- internal/conv/runner.go | 13 ++ internal/conv/scan_walk.go | 128 ++++++++++++++ internal/conv/types.go | 13 +- internal/i18n/i18n.go | 5 + web/src/App.vue | 29 ++- web/src/components/ConfirmDialog.vue | 103 +++++++++++ web/src/components/FileRow.vue | 1 + web/src/components/ScanBadge.vue | 13 +- web/src/composables/useRun/events.ts | 9 +- web/src/composables/useRun/scan.ts | 256 ++++++++++++++------------- web/src/composables/useRun/types.ts | 9 + web/src/i18n/en.ts | 6 + web/src/i18n/zh.ts | 6 + web/src/types.ts | 9 + 18 files changed, 737 insertions(+), 199 deletions(-) create mode 100644 internal/conv/scan_walk.go create mode 100644 web/src/components/ConfirmDialog.vue diff --git a/docs/usage.md b/docs/usage.md index 687c0b8..2edb093 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -23,6 +23,12 @@ notes, whether or not it has an image to upload. A document with nothing to uplo gets a card, so the queue always matches what is in the folder. Only binaries are skipped: images, archives, executables, PDFs and Office files. +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 cards appear as they are read. 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. diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index bf39d57..2472857 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -20,6 +20,10 @@ 图片,都会出现在队列里 —— 卡片数永远和文件夹里对得上,不会出现「明明有 3 个只显示 2 个」。 只有二进制被跳过:图片、压缩包、可执行文件、PDF、Office 文档。 +拖进来的目录很大时(整块盘、网盘同步目录),扫描是边扫边报的:目录那一行显示「已经找到 +多少份文档」,卡片一份份冒出来。扫描没有总时长上限,只按「多久没有动静」判死,随时可以 +停 —— 确认之后,已经扫到的都留在队列里,那一行也会说清「这个目录剩下的没扫」。 + 看队列、中途取消、失败重试、只看问题,每张图的明细可以展开。 同一张图只上传一次;已经上传/下载过且内容未变的图直接复用。 diff --git a/internal/app/app_test.go b/internal/app/app_test.go index f260b58..ccb98c0 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" @@ -550,3 +551,86 @@ 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", len(files)) + } + if progress == 0 { + t.Fatal("应该至少推一条 scan.progress") + } +} + +// 停止扫描:已经在跑的那一份丢掉,但收尾事件必须到达且带 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/scan.go b/internal/app/scan.go index 4ec8662..78181ec 100644 --- a/internal/app/scan.go +++ b/internal/app/scan.go @@ -3,6 +3,8 @@ package app import ( "context" "encoding/json" + "os" + "path/filepath" "runtime" "strings" "sync" @@ -13,26 +15,34 @@ 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 是遍历目录的并发度。 + scanWalkWorkers = 8 + // scanDocWorkers 是单个路径内并发解析文档的协程数;整批真正的上限由 + // scanSession.docSlots 把关,免得一次拖六块盘把机器打满。 + scanDocWorkers = 4 + // scanMinParallel / scanMaxParallel 夹住「同时处理几个路径」。 scanMinParallel = 2 scanMaxParallel = 6 ) -// scanParallelism 按机器核数给并发上限:一半核数,夹在 [2, 6],且不超过路径数。 +// scanParallelism 按机器核数给同时处理的路径数。 func scanParallelism(n int) int { parallel := runtime.NumCPU() / 2 if parallel < scanMinParallel { @@ -50,18 +60,32 @@ func scanParallelism(n int) int { return parallel } +// docSlotCount 是整批扫描里同时解析的文档数上限。 +func docSlotCount() int { + n := runtime.NumCPU() + if n < 2 { + n = 2 + } + if n > 8 { + n = 8 + } + return n +} + // scanSession 是一批扫描的句柄:整批一个 context,每个路径再挂一个自己的。 type scanSession struct { app *App scanID string ctx context.Context cancel context.CancelFunc + // docSlots 限制整批同时解析的文档数:几块盘一起拖进来时,别让几百个协程 + // 同时去读盘——机械盘那样只会更慢。 + docSlots chan struct{} mu sync.Mutex paths map[string]context.CancelFunc // 路径 → 该路径的取消函数 } -// stop 取消整批扫描。 func (s *scanSession) stop() { if s.cancel != nil { s.cancel() @@ -133,11 +157,12 @@ func (a *App) startScan(params json.RawMessage) (any, error) { ctx, cancel := context.WithCancel(context.Background()) session := &scanSession{ - app: a, - scanID: req.ScanID, - ctx: ctx, - cancel: cancel, - paths: make(map[string]context.CancelFunc, len(paths)), + app: a, + scanID: req.ScanID, + ctx: ctx, + cancel: cancel, + docSlots: make(chan struct{}, docSlotCount()), + paths: make(map[string]context.CancelFunc, len(paths)), } a.mu.Lock() @@ -158,18 +183,6 @@ func (a *App) startScan(params json.RawMessage) (any, error) { return map[string]any{"scanId": req.ScanID, "paths": paths}, nil } -// scanOne 是「一个请求路径」的扫描结果。 -// -// 目录是一等公民:用户拖进来的是一个目录,就该有一条对应该目录的结果,里面带上 -// 它展开出来的文件。以前这里只回一串平铺的文件,界面只好拿路径前缀自己去猜 -// 「哪几个文件属于这个目录、加起来几张图」—— 展开规则在 Go 这边,界面不该重算。 -type scanOne struct { - path string - files []conv.FileResult - cancelled bool - timedOut bool -} - func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) { // 整批跑完就把会话从表里摘掉,别抱着 paths、cancel 和 context 不放。 defer func() { @@ -191,7 +204,14 @@ func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) wg.Add(1) go func(path string) { defer wg.Done() - s.scanPath(cfg, lang, path, sem) + // 排队等名额时也要能被取消。 + select { + case sem <- struct{}{}: + defer func() { <-sem }() + case <-s.ctx.Done(): + return + } + s.scanPath(cfg, lang, path) }(path) } @@ -205,63 +225,149 @@ func (s *scanSession) run(cfg settings.Settings, lang i18n.Lang, paths []string) s.app.emit(ev) } -func (s *scanSession) scanPath(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} + info, err := os.Stat(path) + if err != nil { + // 路径不存在/读不了:回一条空结果,界面把这张卡片标成「找不到」。 + s.emitFile(path, nil) + return + } - // 排队等名额的时候也能被取消:十个文件、并发六个,剩下四个卡在排队, - // 用户点了取消不该等前面六个扫完才生效。 - select { - case sem <- struct{}{}: - defer func() { <-sem }() - case <-fileCtx.Done(): - result.cancelled = true - s.emitFile(result) + if !info.IsDir() { + if res, ok := s.scanDocument(ctx, cfg, 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 + walkEnded := make(chan struct{}) + + go func() { + 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.app.emit(conv.Event{ + Type: conv.EventScanProgress, + RunID: s.scanID, + Path: path, + Found: int(counts.Found.Load()), + Dirs: int(counts.Dirs.Load()), + }) + } + } + }() + + var wg sync.WaitGroup + for i := 0; i < scanDocWorkers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for file := range docs { + select { + case s.docSlots <- struct{}{}: + case <-ctx.Done(): + return + } + res, ok := s.scanDocument(ctx, cfg, lang, file) + <-s.docSlots + if !ok { + // 用户按了停止:已经在跑的这一份算白跑,不再往外报。 + return + } + s.emitFile(path, []conv.FileResult{res}) + } + }() + } + wg.Wait() + close(stopProgress) + <-walkEnded + + // 收尾再报一次最终数字,界面不用等最后一个 tick。 + s.app.emit(conv.Event{ + Type: conv.EventScanProgress, + RunID: s.scanID, + Path: path, + Found: int(counts.Found.Load()), + Dirs: int(counts.Dirs.Load()), + }) +} + +// scanDocument 解析一份文档,带单文件超时。 +// +// 返回 ok=false 表示这一份被取消了(用户点了停止),调用方不该再往外报。 +func (s *scanSession) scanDocument(ctx context.Context, cfg settings.Settings, lang i18n.Lang, path string) (conv.FileResult, bool) { + // 每份文档一个 Runner:超时之后那个协程会被丢下不管,让它自己跑完, + // 复用同一个 Runner 会和后面那一份抢内部状态。 + result := make(chan conv.FileResult, 1) + fileCtx, cancel := context.WithCancel(ctx) + defer cancel() + go func() { - // 每个路径一个 Runner:Runner 内部带状态,多个文件共用一份会互相踩。 - runner := conv.NewRunner(cfg, lang, "preview", nil).UsePreview() - files, _ := runner.RunCollect(fileCtx, []string{path}) - done <- files + runner := conv.NewRunner(cfg, lang, "scan", nil).UsePreview() + 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 + case <-ctx.Done(): + return conv.FileResult{}, 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 } - - s.emitFile(result) } -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, }) } diff --git a/internal/conv/runner.go b/internal/conv/runner.go index 8d2111f..74722a5 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" @@ -332,6 +333,18 @@ 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() diff --git a/internal/conv/scan_walk.go b/internal/conv/scan_walk.go new file mode 100644 index 0000000..b9b63e8 --- /dev/null +++ b/internal/conv/scan_walk.go @@ -0,0 +1,128 @@ +package conv + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" +) + +// WalkCounts 是遍历过程中的实时计数:遍历还在跑的时候就可以读。 +// +// 进度事件要在「还没走完」的时候报数,所以计数不能等遍历结束才回填 —— 那样拖一块 +// 大一点的盘,界面上会一直显示「已找到 0 份」。 +type WalkCounts struct { + Found atomic.Int64 + Dirs atomic.Int64 +} + +// 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) + + queue := make(chan string, 512) + // done 在「再也没有待处理的目录」时关闭。用计数而不是关闭 queue: + // 多个协程都在往 queue 里塞目录,谁也没有资格替别人关。 + done := make(chan struct{}) + + var mu sync.Mutex + pending := 0 + + push := func(dir string) bool { + mu.Lock() + pending++ + mu.Unlock() + select { + case queue <- dir: + return true + case <-ctx.Done(): + mu.Lock() + pending-- + mu.Unlock() + return false + } + } + + finish := func() { + mu.Lock() + pending-- + if pending == 0 { + close(done) + } + mu.Unlock() + } + + if counts == nil { + counts = &WalkCounts{} + } + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-done: + return + case <-ctx.Done(): + return + case dir := <-queue: + 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) { + finish() + return + } + } + } + finish() + } + } + }() + } + push(root) + wg.Wait() +} diff --git a/internal/conv/types.go b/internal/conv/types.go index 159b479..5c61bcb 100644 --- a/internal/conv/types.go +++ b/internal/conv/types.go @@ -188,12 +188,16 @@ 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"` } // 事件类型。 @@ -206,8 +210,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/i18n/i18n.go b/internal/i18n/i18n.go index 19b1492..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" @@ -300,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", diff --git a/web/src/App.vue b/web/src/App.vue index 25c8937..82d310f 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' @@ -418,9 +419,25 @@ async function enqueue(paths: string[]): Promise { void scanPaths(mode.value, added) } -/** 卡片上的「取消扫描」/「恢复扫描」「重试」。 */ +/** 待确认「停止扫描」的那一行;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 { @@ -775,6 +792,16 @@ onBeforeUnmount(() => { + + +import { nextTick, onMounted, ref } from 'vue' +import AppIcon from './AppIcon.vue' +import { useI18n } from '../i18n' + +/** + * 一个通用的是/否确认框。 + * + * 用在小而明确的操作上(比如「停止扫描?」):标题、正文、确认按钮文案由调用方给, + * 关掉的方式只有两个 —— 点确认、或者点取消/按 Esc。不做「不再询问」那种带记忆的 + * 选项,避免把一次性的决定变成长期设置。 + */ +const props = withDefaults( + defineProps<{ + title: string + body: string + confirmLabel: string + /** 确认按钮的样式:破坏性操作用 danger。 */ + tone?: 'primary' | 'danger' + }>(), + { tone: 'primary' }, +) + +const emit = defineEmits<{ confirm: []; cancel: [] }>() + +const { t } = useI18n() +const panel = ref(null) + +onMounted(() => { + void nextTick(() => panel.value?.focus()) +}) + + + + + diff --git a/web/src/components/FileRow.vue b/web/src/components/FileRow.vue index a01f637..d77d8dd 100644 --- a/web/src/components/FileRow.vue +++ b/web/src/components/FileRow.vue @@ -614,6 +614,7 @@ function toggleExpanded(): void { :state="row.scan ?? 'idle'" :error="row.scanError" :busy="busy" + :found="row.scanFound ?? 0" @cancel="emit('cancel-scan', row.id)" @retry="emit('retry-scan', row.id)" /> diff --git a/web/src/components/ScanBadge.vue b/web/src/components/ScanBadge.vue index 829b500..2e3e0af 100644 --- a/web/src/components/ScanBadge.vue +++ b/web/src/components/ScanBadge.vue @@ -19,8 +19,10 @@ const props = withDefaults( error?: string /** 这一轮正在跑:这时不该再动扫描,取消/重试都灰着。 */ busy?: boolean + /** 正在扫一个目录时,已经发现多少份文档(0 表示还没发现)。 */ + found?: number }>(), - { error: '', busy: false }, + { error: '', busy: false, found: 0 }, ) const emit = defineEmits<{ cancel: []; retry: [] }>() @@ -65,6 +67,10 @@ const hint = computed(() => {