Compare commits
68 Commits
v1.4.2-loc
...
0bbb840778
| Author | SHA1 | Date | |
|---|---|---|---|
| 0bbb840778 | |||
| e911876bbb | |||
| f300abf359 | |||
| 10f1d4fca2 | |||
| 0544c78633 | |||
| 171fbaf59d | |||
| a206ce8450 | |||
| 9f12b91a14 | |||
| 2117551af7 | |||
| a58a94b05f | |||
| 715c8068f8 | |||
| 8b4d1fa03e | |||
| b2a4fd41ca | |||
| 0bb804e4df | |||
| 6c0bb8253b | |||
| a5c0b0801d | |||
| 3ecf96fb04 | |||
| fb10fc5de0 | |||
| 1208386452 | |||
| d78d1aa722 | |||
| 1ad4a265c3 | |||
| a4616d0228 | |||
| 9a568774d8 | |||
| 2fc3f740ca | |||
| 590a9a016c | |||
| 0b97bcb6dc | |||
| fadba614a8 | |||
| d0e374a02c | |||
| d5ba2495ba | |||
| 1115052762 | |||
| 44fe93ec20 | |||
| 8221eb5908 | |||
| c783a6dc56 | |||
| dfe38890e0 | |||
| 8d98b5e7a9 | |||
| d2b1630a35 | |||
| 301e042bec | |||
| d54b953094 | |||
| 618ac47b83 | |||
| 8644966b10 | |||
| dd4083fe80 | |||
| d90e47e606 | |||
| 809b7b0299 | |||
| abeb426a43 | |||
| 47e71cf692 | |||
| 52de3f9a0f | |||
| 9ae2c134ad | |||
| 5f2234493b | |||
| 8c6c862f5a | |||
| f9ccce066c | |||
| 5f08b71d07 | |||
| 85b20ece8a | |||
| fe32d6fe3e | |||
| 5740274a86 | |||
| bab8e96197 | |||
| e24733ad96 | |||
| 55d78485dd | |||
| 39deeac3f5 | |||
| 593dc29f21 | |||
| 7d4091ddad | |||
| 625ffdb1b6 | |||
| bbfc4cfb0b | |||
| 7fda49b425 | |||
| 743ae5d6ee | |||
| 53c39af0c8 | |||
| 968e89bf98 | |||
| 07ac99764f | |||
| 2a4df2e3c5 |
3
.gitattributes
vendored
3
.gitattributes
vendored
@@ -1 +1,4 @@
|
||||
* text=auto eol=lf
|
||||
# cmd.exe wants CRLF; keep it stable in the working tree.
|
||||
*.cmd text eol=crlf
|
||||
*.bat text eol=crlf
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,6 +5,9 @@
|
||||
# 上游源码备份:本地保留,不入 git(用户决定)
|
||||
/backup/
|
||||
|
||||
# 本机草稿目录(不属于仓库)
|
||||
/test/
|
||||
|
||||
# 日志与临时文件
|
||||
*.log
|
||||
/agent/tmp/
|
||||
|
||||
90
Cargo.lock
generated
90
Cargo.lock
generated
@@ -1676,18 +1676,13 @@ version = "1.4.2"
|
||||
dependencies = [
|
||||
"image",
|
||||
"notify",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"open",
|
||||
"pulldown-cmark",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"tao",
|
||||
"url",
|
||||
"winreg",
|
||||
"winresource",
|
||||
"wry",
|
||||
]
|
||||
@@ -2822,15 +2817,6 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-locale"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-deps"
|
||||
version = "6.2.2"
|
||||
@@ -3735,15 +3721,6 @@ dependencies = [
|
||||
"windows-targets 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||
dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
@@ -3786,21 +3763,6 @@ dependencies = [
|
||||
"windows_x86_64_msvc 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.48.5",
|
||||
"windows_aarch64_msvc 0.48.5",
|
||||
"windows_i686_gnu 0.48.5",
|
||||
"windows_i686_msvc 0.48.5",
|
||||
"windows_x86_64_gnu 0.48.5",
|
||||
"windows_x86_64_gnullvm 0.48.5",
|
||||
"windows_x86_64_msvc 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
@@ -3841,12 +3803,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -3859,12 +3815,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -3877,12 +3827,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -3901,12 +3845,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -3919,12 +3857,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -3937,12 +3869,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -3955,12 +3881,6 @@ version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -3994,16 +3914,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winresource"
|
||||
version = "0.1.31"
|
||||
|
||||
@@ -12,19 +12,10 @@ rfd = "0.15"
|
||||
notify = "7"
|
||||
open = "5"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "ico"] }
|
||||
sys-locale = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
url = "2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.52"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6.4"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSAlert", "NSApplication", "NSButton", "NSCell", "NSControl", "NSEvent", "NSImage", "NSMenu", "NSMenuItem", "NSResponder", "NSView"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["objc2-core-foundation", "NSString"] }
|
||||
|
||||
[target.'cfg(windows)'.build-dependencies]
|
||||
winresource = "0.1"
|
||||
|
||||
|
||||
65
README.md
65
README.md
@@ -12,20 +12,23 @@
|
||||
|
||||
- **双击即开**:单个 exe(约 5.5 MB),不用安装;可设为 `.md` 的默认打开方式。
|
||||
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
|
||||
- **多标签 + 会话恢复**:关掉再开,上次的标签还在;最近文件列表、缺失文件重新定位。
|
||||
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
|
||||
- **多标签 + 多窗口**:新标签页(New Tab)本身就是一个默认标签,标签栏的 `+` 新建一个 New Tab;在 New Tab 里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到 New Tab,只剩 New Tab 时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
|
||||
- **英文界面**:界面文案统一为英文,不随系统语言切换,避免中英文混排。
|
||||
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑模式与滚动位置按标签记忆,切回时恢复;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
|
||||
- **编辑更顺手**:Tab 插入 2 个空格、Shift+Tab 反缩进,多行选区整体缩进;Enter 自动跟随上一行缩进;保留原生撤销。
|
||||
- **长文档友好**:
|
||||
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
|
||||
- `Ctrl+滚轮` 缩放正文,5% 一档、范围 50%–300%,并记住上次的缩放。
|
||||
- **代码块始终是深色**(Visual Studio Dark 配色),浅色主题下也保持深色,读代码不刺眼;行内代码仍跟随系统主题。
|
||||
- **渲染齐全**:GFM、表格、任务列表、front matter、GitHub Alerts、`==高亮==`、KaTeX 公式、Mermaid 图。
|
||||
- **单实例**:再次双击文件会交给已打开的窗口,不会开一堆进程。
|
||||
- **渲染齐全**:GFM、表格、任务列表、脚注、定义列表、front matter、GitHub Alerts、`==高亮==`、KaTeX 公式、Mermaid 图。
|
||||
- **对 AI 输出友好**:单个换行按换行显示(空行仍然是段落);这是本工具有意采用的方言,和严格 CommonMark 查看器不同。
|
||||
- **单实例**:再次双击文件会交给已打开的进程;文件已在其他窗口打开时只聚焦,不会重复开。
|
||||
|
||||
## 下载与运行
|
||||
|
||||
1. 在仓库的 **Releases** 页下载 `MD-Preview-windows-x64.exe`;
|
||||
2. 放到一个固定目录(例如 `D:\Scripts\md-preview\`),不要随意改名/移动;
|
||||
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认;
|
||||
1. 在 [Releases](https://git.wucl12.cn/wucl12/md-preview/releases) 页下载 `MD-Preview-windows-x64.exe`(当前发布版本 `v1.4.2-local.5`,2026-10-30);
|
||||
2. 放到一个固定目录(例如 `C:\Tools\md-preview\`),不要随意改名/移动;
|
||||
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认(程序本身不再写注册表;首次需要在“打开方式 → 选择其他应用”里选一次);
|
||||
4. Windows 10/11 一般自带 WebView2 Runtime;若提示缺失,安装微软的 Evergreen Runtime 即可。
|
||||
|
||||
> exe 未做代码签名,SmartScreen 可能提示“未知发布者”,选择“更多信息 → 仍要运行”即可。
|
||||
@@ -35,30 +38,41 @@
|
||||
|
||||
| 操作 | 方式 |
|
||||
|---|---|
|
||||
| 打开文件 | 双击 `.md`、拖进窗口、`Ctrl+O`、首页“最近文件” |
|
||||
| 新建文件 | `Ctrl+N` |
|
||||
| 关闭标签 | `Ctrl+W` 或标签上的 × |
|
||||
| 打开文件 | 双击 `.md`、拖进窗口、`Ctrl+O`、新标签页的“Open File / Recent” |
|
||||
| 新建文件 | `Ctrl+N` 或新标签页的“New File”按钮 |
|
||||
| 新建标签 | 标签栏 `+`(新开一个 New Tab) |
|
||||
| 返回新标签页 | 点击标签栏的“New Tab”标签;只剩 New Tab 时标签栏自动隐藏 |
|
||||
| 关闭标签 | `Ctrl+W` 或标签上的 ×;关闭最后一个文件标签会回到 New Tab;非最后窗口关掉最后一个标签会关闭该窗口 |
|
||||
| 在新窗口打开 | 右键标签 → “Open in New Window”,或按住标签上下拖动超过约 24px(至少两个标签时可用) |
|
||||
| 打开文件所在位置 | 右键标签 → “Show in Explorer”(文件丢失时打开所在目录) |
|
||||
| 预览 / 编辑切换 | `Ctrl+E` |
|
||||
| 保存 | 自动(停止输入 700ms)或 `Ctrl+S` |
|
||||
| 查找 | `Ctrl+F`(工具栏没有搜索按钮,快捷键随时可用) |
|
||||
| 查找 | `Ctrl+F`(工具栏没有搜索按钮,快捷键随时可用);阅读模式选中文字后会自动填入,打开时不滚动 |
|
||||
| 打印 | `Ctrl+P` |
|
||||
| 缩放 | `Ctrl+滚轮`、`Ctrl++`、`Ctrl+-`、`Ctrl+0` 复位 |
|
||||
| 折叠标题 | 鼠标移到标题左侧,点折角箭头 |
|
||||
|
||||
设置与会话保存在 `%LOCALAPPDATA%\md-preview\`(`session.json`、`recent-files.txt`、`zoom.txt` 等),删除 exe 不会自动清掉这些记录。
|
||||
> New Tab 上打开文件会直接替换这个标签(和浏览器新标签页一样),不会额外留下空白标签;想同时保留新标签页,先按标签栏的 `+` 新建一个 New Tab。
|
||||
|
||||
设置与最近文件保存在 `%LOCALAPPDATA%\md-preview\`(`recent-files.txt`、`zoom.txt` 等);旧 `session.json` 不再读写。删除 exe 不会自动清掉这些记录。
|
||||
|
||||
## 和上游 1.4.2 的主要区别
|
||||
|
||||
| 方面 | 改动 |
|
||||
|---|---|
|
||||
| 联网 / 更新 | 移除 GitHub Releases 检查、自更新和 Update 按钮,彻底离线 |
|
||||
| 工具栏 | 移除 Open / Print / Find 按钮,只保留 编辑 / 缩放;快捷键和空状态入口保留 |
|
||||
| 工具栏 | 移除 Open / Print / Find 按钮,只保留 Edit / Zoom;快捷键和空状态入口保留 |
|
||||
| 缩放 | 支持 `Ctrl+滚轮`,步进 5%、范围 50%–300%,并跨重启记住 |
|
||||
| 代码配色 | GitHub 浅/深主题换成始终深色的 VS Dark,只换 CSS、不引新库 |
|
||||
| 换行 | 单个换行按换行显示(AI 输出常见),空行仍是段落分隔;有意的方言差异 |
|
||||
| 脚注/定义列表 | 开启 GFM 脚注与定义列表扩展,并补浅色/深色样式 |
|
||||
| 标题折叠 | 新增 hover 折角箭头,按标题层级折叠;查找命中会自动展开,打印时全部展开 |
|
||||
| 只读文件 | 保存失败不再每 700ms 弹窗、不再卡住关闭;关闭时询问是否丢弃修改 |
|
||||
| 路径处理 | 修复 Windows `\\?\` 前缀污染 Recent / base URL 的问题 |
|
||||
| 稳定性 | 关闭前落盘、外部修改热重载、单实例转发、缺失文件重定位 |
|
||||
| 多窗口 | 单进程多窗口;标签右键移出到新窗口;同一文件全局唯一;启动只保留最近文件,不恢复标签 |
|
||||
| 新标签页 / 英文界面 | New Tab 成为默认标签;`+` 新建 New Tab;新标签页新增 New File 按钮;只剩 New Tab 时标签栏隐藏;界面统一为英文 |
|
||||
| 编辑 / 查找 | Tab/Shift+Tab 两空格缩进、Enter 跟随缩进;阅读模式 Find 支持选区填入,从选区打开时不滚动 |
|
||||
|
||||
## 从源码构建
|
||||
|
||||
@@ -70,32 +84,39 @@
|
||||
- WebView2 Runtime
|
||||
|
||||
```powershell
|
||||
cargo test # 43 个测试
|
||||
.\agent\scripts\build.ps1 # release 构建 + 校验 + 复制到固定 exe 路径
|
||||
cargo test
|
||||
.\agent\scripts\build.ps1 # release 构建 + 校验(产物留在 target\release\)
|
||||
.\agent\tests\ui-smoke.cmd # 发布前 UI 冒烟(普通桌面 PowerShell + Node 21+)
|
||||
.\agent\scripts\publish.ps1 # 发布到 Nutstore(用户手动,普通 PowerShell)
|
||||
```
|
||||
|
||||
构建脚本会打印 exe 的 SHA256、检查已移除功能的字符串,并确认文件完整性级别为 Medium。
|
||||
构建脚本会打印 exe 的 SHA256、检查已移除功能的字符串,并报告完整性级别;开发构建是 Low,`publish.ps1` 会把它升到 Medium 并复制到 Nutstore。
|
||||
更细的维护说明(工具链、完整性级别坑、验收清单)见 [`agent/docs/HANDOFF.md`](agent/docs/HANDOFF.md)。
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
src/ Rust 源码(main.rs 界面/渲染/事件循环,session.rs 会话,instance.rs 单实例)
|
||||
assets/ 全部内嵌资源:highlight.js、KaTeX、Mermaid、图标、暗色代码主题
|
||||
agent/ 维护者文档、构建/冒烟脚本、测试夹具
|
||||
docs/ HANDOFF、STATUS、roadmap、扫描记录
|
||||
scripts/build.ps1 release 构建与校验
|
||||
src/ Rust 源码(main.rs 启动/事件循环,app 逻辑仍在 main.rs;markdown.rs md→html,
|
||||
page.rs 页面组装,config.rs 路径/zoom/窗口状态,session.rs 会话,instance.rs 单实例)
|
||||
assets/ 全部内嵌资源:page/ 页面 HTML+CSS+JS、highlight.js、KaTeX、Mermaid、图标、暗色代码主题
|
||||
agent/ 维护者文档、构建/冒烟/发布脚本、测试夹具
|
||||
docs/ HANDOFF、STATUS、roadmap、migration、扫描记录
|
||||
scripts/build.ps1 开发构建(release + 校验)
|
||||
scripts/publish.ps1 发布到 Nutstore(用户手动)
|
||||
tests/ 冒烟脚本与 Markdown 样例
|
||||
backup/ 上游源码备份(本地保留,不入 git)
|
||||
```
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 仅面向 Windows;源码里仍有未维护的 macOS 分支。
|
||||
- 仅面向 Windows;macOS/Linux 分支已于 2026-11-03 删除。
|
||||
- exe 未签名,首次运行可能被 SmartScreen 拦截。
|
||||
- 按设计不自动更新,升级方式是手动替换 exe。
|
||||
- 折叠状态不持久化,每次打开都是全部展开。
|
||||
- 拖拽标签只用于移出到新窗口;不支持拖回、窗口合并或跨窗口同步编辑。
|
||||
- 单换行按换行显示;如果源文件是按固定列硬折行的长段落,预览会保留这些断点,不随窗口宽度重排。
|
||||
- 只读文件可以看、可以改,但保存会被拒绝(会明确提示,不会卡死)。
|
||||
- 只识别 Markdown 扩展名(`.md` / `.markdown` / `.mdown` / `.mkd`);`.txt` 不再作为文档打开。
|
||||
|
||||
## 许可
|
||||
|
||||
|
||||
@@ -4,49 +4,72 @@
|
||||
|
||||
## 0. 工作区边界(最重要)
|
||||
|
||||
1. **只在工作区 `D:\Scripts\md-preview` 内创建、修改、删除文件。**
|
||||
2. **任何工作区外的修改都必须先停下询问用户**,包括但不限于:
|
||||
1. **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`(2026-11-02 迁移后)。只在这个目录内创建、修改、删除文件。
|
||||
- DSH 工作区是父目录 `D:\Scripts\md-preview`;代码仓库在其下的 `AgentLowWorking`。改代码/跑 git 前先 `cd AgentLowWorking`(或 `git -C AgentLowWorking`)。
|
||||
- 父目录只放用户指定的小文件(发布启动器、AGENTS 指针);不要放源码/构建产物。
|
||||
- 仓库内**新增文件不需要事先询问**:按职责拆模块、抽资源、加测试是正常的代码组织手段。
|
||||
2. **任何仓库外的修改都必须先停下询问用户**,包括但不限于:
|
||||
- `%TEMP%` / `%LOCALAPPDATA%` / 用户目录 / 其它磁盘;
|
||||
- 注册表、计划任务、服务、环境变量;
|
||||
- 删除或移动任何不是本次刚在工作区内生成的文件。
|
||||
- 删除或移动任何不是本次刚在仓库内生成的文件。
|
||||
询问时要给出:完整路径、要做的操作、原因、影响范围;得到明确同意后才执行。
|
||||
3. 不允许为了省事把构建/测试的临时文件写到工作区外。本仓库约定临时目录放在
|
||||
`target\test-tmp`、`target\tmp` 下(均被 `.gitignore` 忽略)。
|
||||
4. 每次收尾前自查:`git status` 是否只剩预期改动;本次是否在工作区外留下文件;
|
||||
3. 构建/测试的临时文件留在 `target\tmp`、`target\test-tmp`(已忽略),不写 `%TEMP%`。
|
||||
4. 每次收尾前自查:`git status` 是否只剩预期改动;本次是否在仓库外留下文件;
|
||||
若发现历史残留,只报告并询问,不擅自删除。
|
||||
5. DSH 当前以 **danger-full-access** 运行,没有文件系统护栏——这条规则是唯一防线,不得绕过。
|
||||
5. DSH 以 **workspace-write(Low 完整性)** 运行;仓库整棵树是 Low,因此可以正常改代码、编译、commit。**不要**把仓库改回 Medium,**不要**申请 danger-full-access 来改代码。
|
||||
6. 截图、录屏等二进制验证产物**不入库**:放 `agent/tmp/`(已忽略)或 `target/tmp/`,看完即删;`agent/reports/` 只保留文本记录。
|
||||
7. `test/` 是本机草稿目录,已 gitignore;不要提交,不要当作仓库内容。
|
||||
|
||||
## 1. 不变量
|
||||
|
||||
- 产物路径固定:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,默认 `.md` 打开方式指向它,不改名、不移动。
|
||||
- **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`。
|
||||
- **发布产物**:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium);默认 `.md` 打开方式指向它。
|
||||
- 仓库内**不放成品 exe**;旧的 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 已删除,不要再生成。
|
||||
- Agent 编译出的 `target\release\md-preview.exe` 是 **Low**,不能直接双击运行(会 os error 5);冒烟必须把 `MD_PREVIEW_CONFIG_DIR` 指到仓库内目录。
|
||||
- 离线:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
||||
- 轻量:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
||||
- 轻量是硬约束:exe 体积以 `build.ps1` 输出为准(2026-11 约 5.5 MB)。不为小功能引入新库,优先原生 JS/CSS 与已有依赖;要 vendor 新的离线资源(>200 KB)先说明并确认。
|
||||
- 可读性优先:单文件按职责拆分,不为“少几个文件”把逻辑堆进 `main.rs`;模块边界以“改一个功能只需动一两个文件”为准。
|
||||
- 右键菜单保持禁用;缩放只用 Ctrl + 滚轮与工具栏/快捷键。
|
||||
- 工作区完整性级别是 **Medium**;不要把工作区改成 Low。
|
||||
|
||||
## 2. 改动流程
|
||||
|
||||
1. 一次只做一个功能;**加功能前先给方案,用户确认后再写代码**。
|
||||
2. 改动超出已确认范围(新增文件、改公共接口、动构建脚本、碰工作区外)时,立即停下询问。
|
||||
3. 写完先 `cargo test` 全绿,再部署验收;部署要替换固定 exe 并校验 SHA256/完整性级别。
|
||||
4. 每个功能一个 conventional commit,推送到 `origin main`。
|
||||
1. 一次只做一件事;**用户可感知的功能/行为变化先给方案,用户确认后再写代码**。
|
||||
2. bug 修复、纯重构、测试、文档、格式与静态检查可以直接处理:每项独立提交,`cargo test` 全绿,提交信息写清行为变化。
|
||||
3. 代码级决策(拆模块、新增文件、内部接口、命名)由 agent 自行决定,不需要逐项询问。
|
||||
4. 只有这些要先停下询问:仓库外的文件/注册表/环境变量;发布;新增第三方库或 >200 KB 的 vendored 资源;改变不变量(离线、轻量、右键禁用、只支持 Windows 等)。
|
||||
5. 写完先 `cargo test` 全绿(含新增测试);改动页面 JS 时额外做一次语法检查。
|
||||
6. 每个改动一个 conventional commit,推送到 `origin main`。
|
||||
7. **发布只能由用户手动执行**:用户在普通 PowerShell(Medium)运行 `agent\scripts\publish.ps1`。Agent 不运行发布脚本、不改注册表、不碰 Nutstore。
|
||||
|
||||
## 3. 构建与测试
|
||||
|
||||
- 测试时把临时目录指到工作区内,避免 `%TEMP%` 残留:
|
||||
- 测试/构建前把临时目录指到仓库内:
|
||||
|
||||
```powershell
|
||||
$env:TEMP = "$PWD\target\test-tmp"; $env:TMP = $env:TEMP
|
||||
~~~powershell
|
||||
$env:TEMP = "$PWD\target\tmp"; $env:TMP = $env:TEMP
|
||||
New-Item -ItemType Directory -Force $env:TEMP | Out-Null
|
||||
cargo test
|
||||
```
|
||||
~~~
|
||||
|
||||
- 正式构建用 `agent\scripts\build.ps1`(先关闭正在运行的 MD Preview)。
|
||||
- `git clean -xdf` 会删除被忽略的 `backup/` 与成品 exe,禁止使用。
|
||||
- 开发构建:`.\agent\scripts\build.ps1`(cargo test + build --release + 字符串校验;产物留在 `target\release\`)。
|
||||
- DSH 的 pwsh 执行策略可能阻止未签名脚本;先运行 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force`。
|
||||
- 开发冒烟:`$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"; .\target\release\md-preview.exe <file>`。
|
||||
- **UI/GUI 验证只能由用户执行**:DSH 沙箱禁止命名管道,WebView2/Chromium 起不来(窗口白屏、`msedgewebview2.exe` 立即退出;这不是应用 bug)。
|
||||
- 请用户在自己的桌面 PowerShell 运行 `.\agent\tests\ui-smoke.cmd`(`.ps1` 在 AllSigned 策略下会被拒;`.cmd` 内部用 `-ExecutionPolicy Bypass`),然后读 `target\ui-test\ui-smoke.json` 与 `ui-smoke.png` 判断。
|
||||
- 发布前必跑;改页面 HTML/CSS/JS 或 Rust→JS 调用后必跑。细节见 `docs/HANDOFF.md` §4.1。
|
||||
- **Rust → JS 调用没有编译器检查**:改参数列表时同步改页面函数签名,并保留“精确输出 + 页面签名”测试(`set_content_script_matches_the_page_signature`)。
|
||||
- 不要把 `target\release\md-preview.exe` 复制到任何固定路径,也不要覆盖 Nutstore。
|
||||
- `git clean -xdf` 会删除被忽略的 `backup/`,禁止使用。
|
||||
|
||||
## 4. 参考
|
||||
## 4. 发布(用户手动)
|
||||
|
||||
- `docs/HANDOFF.md`:工具链、构建、完整性级别坑、验收。
|
||||
- 用户在**普通 PowerShell**(Medium)运行 `agent\scripts\publish.ps1`。
|
||||
- 脚本流程:复制 `target\release\md-preview.exe` → Nutstore → 设 Medium → 校验 SHA256 → 刷新 `.md` 关联 → 删除旧 exe。
|
||||
- 发布前必须关闭正在运行的 MD Preview。
|
||||
- 仅 Nutstore 这一个仓库外目标;其他仓库外修改仍需先询问用户。
|
||||
|
||||
## 5. 参考
|
||||
|
||||
- `docs/HANDOFF.md`:工具链、构建、完整性级别、验收。
|
||||
- `docs/STATUS.md`:当前进度、已确认决策、下一步。
|
||||
- `docs/migration-2026-11-02.md`:Low 工作区迁移与目录移动步骤。
|
||||
- `docs/roadmap.md`:功能方案与验收标准。
|
||||
|
||||
@@ -1,49 +1,58 @@
|
||||
# agent/ — MD Preview 维护者工作区
|
||||
|
||||
这里是本项目的“Agent 附属区”:文档、构建/冒烟脚本、测试夹具与验证记录。应用代码仍在 `src/`。
|
||||
这里是本项目的“Agent 附属区”:文档、构建/冒烟/发布脚本、测试夹具与验证记录。应用代码仍在 `src/`。
|
||||
|
||||
## 规则
|
||||
|
||||
维护本仓库前先读 [`AGENTS.md`](AGENTS.md):**最高优先级是工作区边界——任何工作区外的文件修改都必须先停下询问用户。**
|
||||
维护本仓库前先读 [`AGENTS.md`](AGENTS.md):**最高优先级是仓库边界——任何仓库外的文件修改都必须先停下询问用户。**
|
||||
|
||||
## 目录
|
||||
|
||||
| 路径 | 用途 |
|
||||
|---|---|
|
||||
| `AGENTS.md` | Agent 运行规则(工作区边界、改动流程) |
|
||||
| `docs/HANDOFF.md` | 主交接文档(工具链、构建、坑、验收) |
|
||||
| `AGENTS.md` | Agent 运行规则(仓库边界、改动流程) |
|
||||
| `docs/HANDOFF.md` | 主交接文档(工具链、构建、完整性级别、验收) |
|
||||
| `docs/migration-2026-11-02.md` | Low 工作区迁移与目录移动步骤 |
|
||||
| `docs/scan-2026-10-21.md` | 代码扫描:残留、bug、修复建议 |
|
||||
| `docs/roadmap.md` | 功能路线图与验收标准 |
|
||||
| `scripts/build.ps1` | release 构建 → 固定 exe 路径 → 校验 |
|
||||
| `scripts/build.ps1` | 开发构建(cargo test + build --release + 校验) |
|
||||
| `scripts/publish.ps1` | 用户手动发布到 Nutstore(Medium) |
|
||||
| `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 |
|
||||
| `tests/ui-smoke.cmd` / `ui-smoke.ps1` + `ui-smoke.mjs` | 发布前 UI 冒烟:CDP 断言页面渲染、截图、JSON 报告(需普通桌面 PowerShell + Node 21+;`.cmd` 内部用 Bypass,适合 AllSigned 策略) |
|
||||
| `tests/fixtures/` | 手工/冒烟用 Markdown 样例 |
|
||||
| `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) |
|
||||
| `notes/` | 草稿 |
|
||||
|
||||
## 不变量
|
||||
|
||||
1. **产物路径固定**:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。默认 `.md` 打开方式指向它,不要改名/移动。
|
||||
1. **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`。默认 `.md` 打开方式指向 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`。
|
||||
2. **离线**:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
||||
3. **轻量**:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
||||
4. **测试**:`cargo test` 必须保持全绿;UI 行为用 `tests/fixtures` 做手工/冒烟回归。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```powershell
|
||||
# 构建并校验(推荐)
|
||||
~~~powershell
|
||||
# 开发构建(DSH workspace-write 可运行)
|
||||
.\agent\scripts\build.ps1
|
||||
|
||||
# 只跑测试
|
||||
cargo test
|
||||
|
||||
# 冒烟(含注册表与可选启动)
|
||||
# 冒烟(发布后;含注册表与可选启动)
|
||||
.\agent\tests\smoke.ps1 -Launch
|
||||
```
|
||||
|
||||
# 发布前 UI 冒烟(用户桌面;CDP + 截图)
|
||||
.\agent\tests\ui-smoke.cmd
|
||||
|
||||
# 发布(必须由用户在自己的普通 PowerShell 运行)
|
||||
.\agent\scripts\publish.ps1
|
||||
~~~
|
||||
|
||||
## 环境注意
|
||||
|
||||
工作区是 **Medium** 完整性级别。DSH 用 `workspace-write` 打开时进程是 **Low**,会写不动(EPERM / os error 5)。改代码、编译、替换 exe 需要 DSH 以 **danger-full-access** 运行,或在你自己的普通 PowerShell 里执行。详见 `docs/HANDOFF.md` 第 4 节。
|
||||
仓库整棵树是 **Low** 完整性级别,DSH 以 `workspace-write` 运行即可改代码/编译。构建产物 `target\release\md-preview.exe` 也是 Low,不能直接双击;开发冒烟用 `MD_PREVIEW_CONFIG_DIR` 指到仓库内目录。发布由用户手动运行 `publish.ps1` 升到 Medium 并复制到 Nutstore。详见 `docs/migration-2026-11-02.md`。
|
||||
|
||||
## Git
|
||||
|
||||
仓库由用户自行初始化(私有)。`backup/` 与成品 exe 不入库;`agent/` 全量入库。
|
||||
仓库由用户自行初始化(私有)。`backup/`、成品 exe、`test/` 不入库;`agent/` 全量入库(`agent/tmp/` 与日志/截图除外)。
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
# MD Preview 本地维护交接
|
||||
|
||||
> 最后更新:2026-10-21
|
||||
> 最后更新:2026-11-06
|
||||
> 维护范围:仅 Windows 本地构建,目标产物 `MD-Preview-windows-x64.exe`
|
||||
>
|
||||
> **Agent 必须先读 `agent/AGENTS.md`**:最高优先级是工作区边界,任何工作区外的文件修改都要先停下询问用户。
|
||||
|
||||
> **2026-11-02 迁移(重要)**:代码仓库移到 `D:\Scripts\md-preview\AgentLowWorking`;DSH 工作区仍是父目录 `D:\Scripts\md-preview`;
|
||||
> 仓库整棵树为 **Low**,DSH 用 **workspace-write** 即可改代码/编译;
|
||||
> 成品只发布到 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium),仓库内不再放 exe。
|
||||
> 本文第 4 节等处的 “Medium / danger-full-access” 是旧模型;以 `agent/docs/migration-2026-11-02.md` 和 `AGENTS.md` 为准。
|
||||
>
|
||||
> **2026-11-06**:编辑区已切到内嵌 CodeMirror 5(行号/折叠/查找替换/按标签行号恢复),63 tests 全绿,ui-smoke 8/8。重构阶段 3–5 见 `STATUS.md` §11;CM5 细节见 `next-2026-11-03.md` §4.2。
|
||||
|
||||
## 1. 当前状态
|
||||
|
||||
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
|
||||
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
|
||||
- 源码规模:`src/main.rs` 4354 行、`src/session.rs` 281 行、`src/instance.rs` 207 行
|
||||
- 当前产物:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`
|
||||
- 大小 5,501,440 字节
|
||||
- SHA256 `F76BC3963BA13BBFC8259BC2B4E3D24468C34E3C9E26491D364D5D364BEDE96C`
|
||||
- 测试:`cargo test` → 43 passed, 0 failed
|
||||
- 编译警告:1 个 `dead_code`(macOS 专用事件枚举,Windows 下未构造),可忽略
|
||||
- 源码规模(2026-11-06):`src/main.rs` 18 行(入口)、`src/app.rs` 约 1950 行(CLI/启动/状态/渲染/事件循环)、`src/markdown.rs` 628 行、`src/session.rs` 488 行、`src/files.rs` 458 行、`src/page.rs` 约 300 行、`src/config.rs` 235 行、`src/instance.rs` 207 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`,CM5 在 `assets/codemirror/`
|
||||
- 当前产物(2026-11-02 起):`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`
|
||||
- 当前发布版见 `STATUS.md` 第 2 节(v1.4.2-local.5,5,505,024 字节)
|
||||
- 仓库内不再放成品 exe;旧 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 由 `publish.ps1` 删除
|
||||
- 测试:`cargo test` → 60 passed, 0 failed(2026-11-06)
|
||||
- 编译警告:0;`cargo clippy --all-targets` 0 warning,`cargo fmt -- --check` 通过
|
||||
- 2026-10-21 的全部功能需求已完成并部署,细节与实现要点见第 14 节。
|
||||
|
||||
## 2. 本机工具链
|
||||
@@ -36,63 +43,51 @@ DSH 的 pwsh 可能没有继承 PATH,构建时用完整路径:
|
||||
|
||||
## 3. 构建与运行
|
||||
|
||||
```powershell
|
||||
cd D:\Scripts\md-preview
|
||||
cargo build --release
|
||||
copy .\target\release\md-preview.exe .\MD-Preview-windows-x64.exe
|
||||
.\MD-Preview-windows-x64.exe
|
||||
```
|
||||
~~~powershell
|
||||
cd D:\Scripts\md-preview\AgentLowWorking
|
||||
.\agent\scripts\build.ps1 # 开发构建(cargo test + build --release)
|
||||
# 发布由用户在自己的普通 PowerShell 运行:
|
||||
.\agent\scripts\publish.ps1
|
||||
~~~
|
||||
|
||||
- 增量构建约 15 秒,清理后约 1–2 分钟(16 核,release 开启 LTO + opt-level=z)
|
||||
- 依赖锁定在 `Cargo.lock`(435 个包),**不要随手 `cargo update`**
|
||||
- 调试可 `cargo build`(debug,快),产物在 `target\debug\`
|
||||
|
||||
## 4. ⚠️ 必读:完整性级别与 os error 5
|
||||
## 4. ⚠️ 必读:Low 工作区与发布(2026-11-02 起)
|
||||
|
||||
这是本次维护踩过最大的坑,务必先读:
|
||||
- 仓库根 `D:\Scripts\md-preview\AgentLowWorking` 整棵树是 **Low** 完整性级别;DSH 以 **workspace-write** 运行即可改代码、编译、commit。
|
||||
- 从 Low 工作区编译出的 exe 也是 Low:启动后写 `%LOCALAPPDATA%\md-preview\instance.lock` 会被 no-write-up 拒绝(os error 5)。这不是应用 bug。
|
||||
- 开发冒烟不要双击 `target\release\md-preview.exe`,用隔离配置目录:
|
||||
|
||||
- DSH 的 **workspace-write** 模式会把子进程降为 **Low 完整性级别(Low IL)**,并期望工作区文件也是 Low。
|
||||
- 从被标成 Low 的目录编译出的 exe 会继承 Low 标签;启动后写 `%LOCALAPPDATA%\md-preview\instance.lock` 会被 Windows 的 no-write-up 拒绝,弹窗:
|
||||
~~~powershell
|
||||
$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"
|
||||
.\target\release\md-preview.exe path\to\file.md
|
||||
~~~
|
||||
|
||||
```
|
||||
Could Not Open MD Preview
|
||||
拒绝访问 (os error 5)
|
||||
```
|
||||
- 发布:用户在**普通 PowerShell(Medium)**运行 `agent\scripts\publish.ps1`。脚本会复制到 Nutstore、设 Medium、校验 SHA256、刷新 `.md` 关联,最后删除旧 exe。
|
||||
- 如果发布后仍报 os error 5:`icacls <Nutstore exe> | Select-String 'Mandatory Label'` 应为 Medium;确认不是从 Low 目录直接启动。
|
||||
- 不要再把仓库改回 Medium,也不要为了改代码申请 danger-full-access。
|
||||
|
||||
- 这不是应用 bug。同一个 exe 复制到 `D:\Installer\MD-Preview\` 就能正常运行(目标目录是 Medium)。
|
||||
### 4.1 UI 验证:只能由用户执行(2026-11-04 起)
|
||||
|
||||
当前仓库状态:工作区已设为 **Medium**,DSH 必须以 **danger-full-access** 运行才能编辑/编译此目录。
|
||||
如果你用 workspace-write 打开本仓库,DSH 进程是 Low,会写不动 Medium 工作区(表现是编辑/编译全部 Access denied)。
|
||||
**DSH 沙箱禁止命名管道**,Chromium/WebView2 的 Mojo IPC 起不来:应用窗口会出现,但 `msedgewebview2.exe` 立即退出、页面白屏;Edge headless 也会报 `FATAL: mojo platform_channel ... 拒绝访问 (0x5)`。这是环境限制,不是应用 bug,也不要用沙箱里的白屏判断页面好坏。
|
||||
|
||||
### 如果 exe 又报 os error 5
|
||||
因此 GUI/UI 验证统一走这条链路:
|
||||
|
||||
```powershell
|
||||
# 方案 1:把工作区(含 target)改回 Medium 后重建
|
||||
icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Medium" /T /C
|
||||
cargo build --release
|
||||
1. 用户在自己桌面 PowerShell 运行 `.\agent\tests\ui-smoke.cmd`(默认跑 `target\release\md-preview.exe`,独立配置目录 `target\ui-test\config`)。
|
||||
- 机器执行策略是 AllSigned,未签名 `.ps1` 会被拒;`.cmd` 内部用 `-ExecutionPolicy Bypass`,不改系统策略。
|
||||
- 需要 Node 21+(本机 `C:\Program Files\nodejs` 的 24.x);脚本会自己找,也可 `-Node <path>`。
|
||||
- 用 `-Exe <path>` 测发布版;`-KeepOpen` 失败时留窗口。
|
||||
2. 脚本流程:启动应用 → 等 `http://127.0.0.1:9333/json/list` 就绪 → `ui-smoke.mjs` 通过 CDP 断言页面(加载完成、`#preview` 有内容、`window.ipc`、页面 API、标题/折叠按钮/代码高亮/正文长度)→ 截图 → 关闭应用。
|
||||
3. 产物:`target\ui-test\ui-smoke.json`(checks/snapshot/errors)、`ui-smoke.png`、`app.stdout.log` / `app.stderr.log`。Agent 直接读 JSON 和截图判断。
|
||||
4. 何时跑:每次发布前;改页面 HTML/CSS/JS 后;改 Rust→JS 调用后。2026-11-04 的“白屏 + 数字 1234”就是发布前没跑它。
|
||||
|
||||
# 方案 2:不改标签,直接把 exe 复制到普通目录再运行
|
||||
copy .\target\release\md-preview.exe D:\Installer\MD-Preview\MD-Preview-windows-x64.exe
|
||||
```
|
||||
|
||||
检查标签:
|
||||
|
||||
```powershell
|
||||
icacls .\MD-Preview-windows-x64.exe # 应显示 Medium,不能是 Low
|
||||
```
|
||||
|
||||
### 若坚持用 workspace-write 沙箱
|
||||
|
||||
工作区必须保持 Low,DSH 才能写;构建输出必须放到工作区外(否则 exe 又是 Low):
|
||||
|
||||
1. `icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Low" /T /C`
|
||||
2. 项目内 `.cargo\config.toml`:
|
||||
```toml
|
||||
[build]
|
||||
target-dir = "D:/MD-Preview-build/target"
|
||||
```
|
||||
3. 在**自己的普通 PowerShell**里构建,再把 exe 复制到 `D:\Installer\MD-Preview\`
|
||||
维护细节(改脚本前看):
|
||||
|
||||
- 就绪判断必须用 `/json/list` 真的返回,不能只看 TCP 端口——WebView2 的端口可能只开一瞬间。
|
||||
- Node 解析要用 `Get-Command` 结果的 `.Path`(或常见安装目录),不要拿命令对象直接喂 `Test-Path`。
|
||||
- **Rust → JS 调用没有编译器检查**:改 `__setContent` / `__setPreview` 等参数列表时必须同步页面签名,并用 `set_content_script_matches_the_page_signature` 这类“精确输出 + 页面签名”测试锁住;白屏就是多传了一个 `active.id`,标签 id 被当 HTML 渲染。
|
||||
## 5. 已删除的联网/更新功能(不要加回来)
|
||||
|
||||
- 工具栏 Update 按钮、`#btn-update`、更新相关 CSS/JS
|
||||
@@ -114,8 +109,10 @@ python -c "d=open(r'MD-Preview-windows-x64.exe','rb').read(); print(d.count(b'ap
|
||||
|
||||
## 6. 保留的功能(回归时必须覆盖)
|
||||
|
||||
- 多标签、会话恢复、最近文件、缺失文件标签与重新定位
|
||||
- 多标签、最近文件、缺失文件标签与重新定位
|
||||
- 编辑模式与滚动位置按标签记忆:切回标签恢复离开时的模式与位置(2026-11-03)
|
||||
- Markdown 预览(GFM、表格、任务列表、front matter、GitHub Alerts、高亮)
|
||||
- 文档类型只认 `.md/.markdown/.mdown/.mkd`(2026-11-03 起不再打开 `.txt`)
|
||||
- 源码编辑 + 700ms 防抖自动保存,关闭前 flush
|
||||
- 查找(`Ctrl+F`;工具栏的 Find 按钮已移除)、打印、正文缩放 50%–300%(Ctrl+滚轮 / Ctrl± / Ctrl+0)、滚动进度保持
|
||||
- 标题 hover 折叠(H1–H6;点 H2 折到下一个 H2、点 H3 折到下一个 H3;查找自动展开;打印全展开;不持久化)
|
||||
@@ -129,30 +126,23 @@ python -c "d=open(r'MD-Preview-windows-x64.exe','rb').read(); print(d.count(b'ap
|
||||
|
||||
## 7. 目录结构
|
||||
|
||||
```
|
||||
D:\Scripts\md-preview
|
||||
├─ Cargo.toml / Cargo.lock / build.rs
|
||||
├─ src/main.rs 界面、页面模板、渲染、事件循环、Windows 集成(4354 行)
|
||||
├─ src/session.rs 标签会话持久化
|
||||
├─ src/instance.rs 单实例锁与本地端口转发
|
||||
├─ assets/ 8 个被 include_str!/include_bytes! 内嵌的资源
|
||||
│ ├─ icon.ico
|
||||
│ ├─ enhance/preview-enhance.js
|
||||
│ ├─ hljs/(highlight.min.js、delphi、vs-dark.css)
|
||||
│ ├─ katex/…
|
||||
│ └─ mermaid/mermaid.min.js
|
||||
├─ backup/md-preview-master.zip 上游源码备份(3.77 MB,本地保留,不入 git)
|
||||
├─ MD-Preview-windows-x64.exe 构建产物(不入 git;默认打开方式指向此路径)
|
||||
├─ target/ 编译缓存(不入 git,可删)
|
||||
├─ agent/ Agent 文档 / 脚本 / 测试夹具
|
||||
│ ├─ AGENTS.md Agent 运行规则(最高优先级)
|
||||
│ ├─ README.md
|
||||
│ ├─ docs/{HANDOFF.md, STATUS.md, scan-2026-10-21.md, roadmap.md}
|
||||
│ ├─ scripts/build.ps1
|
||||
│ └─ tests/{smoke.ps1, fixtures/}
|
||||
├─ README.md 入口,指向 agent/docs/HANDOFF.md
|
||||
├─ LICENSE / .gitignore / .gitattributes
|
||||
```
|
||||
~~~
|
||||
D:\Scripts\md-preview\
|
||||
├─ AgentLowWorking\ ← 仓库根(整棵树 Low)
|
||||
│ ├─ Cargo.toml / Cargo.lock / build.rs
|
||||
│ ├─ src/ 应用源码
|
||||
│ ├─ assets/ 内嵌资源
|
||||
│ ├─ backup/ 上游源码备份(不入 git)
|
||||
│ ├─ target/ 编译缓存(不入 git,可删)
|
||||
│ ├─ agent/ Agent 文档 / 脚本 / 测试夹具
|
||||
│ │ ├─ AGENTS.md
|
||||
│ │ ├─ docs/{HANDOFF.md, STATUS.md, migration-2026-11-02.md, ...}
|
||||
│ │ ├─ scripts/{build.ps1, publish.ps1}
|
||||
│ │ └─ tests/{smoke.ps1, fixtures/}
|
||||
│ ├─ README.md / LICENSE / .gitignore / .gitattributes
|
||||
│ └─ test/ 本机草稿(已忽略)
|
||||
└─ MD-Preview-windows-x64.exe 旧产物;publish.ps1 成功后删除
|
||||
~~~
|
||||
|
||||
Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git)。`.gitignore` 已忽略 `/target/`、`MD-Preview-windows-x64.exe`、`/backup/` 与临时日志。
|
||||
|
||||
@@ -160,7 +150,7 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
||||
|
||||
`%LOCALAPPDATA%\md-preview\`:
|
||||
|
||||
- `session.json`:打开的标签与 active tab
|
||||
- 旧 `session.json`:已停用,不读不写(可手动删除)
|
||||
- `recent-files.txt`:最近文件(最多 8 个)
|
||||
- `window.geom` / `theme.txt` / `zoom.txt`(正文缩放,50–300)
|
||||
- `instance.lock` / `instance.json`:单实例
|
||||
@@ -171,7 +161,7 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
||||
## 9. 已知问题 / 风险
|
||||
|
||||
1. exe **未签名**。本机通过 Explorer 启动未再出现 SmartScreen,Defender 自定义扫描也未报毒;换机器仍可能提示。可选:本地自签名 + 信任,或加 Defender 排除(需管理员)。
|
||||
2. 源码里仍保留 macOS/Linux 分支和 `objc2` 依赖(`cfg` 裁掉,Windows 不编译)。彻底精简可再删约 900 行 + 3 个 target 依赖。
|
||||
2. macOS/Linux 分支、Finder 扩展和 `objc2` 依赖已于 2026-11-03 删除;仓库现在只能在 Windows 上编译。
|
||||
3. 删除更新功能后,应用完全离线;外部链接仍会交给系统浏览器(这是保留功能,不是自更新)。
|
||||
4. 单实例依赖本地 TCP 回环端口;如被防火墙/安全软件拦截,会表现为第二实例报错或无法转发。
|
||||
|
||||
@@ -183,21 +173,25 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
||||
|
||||
## 11. 验收清单
|
||||
|
||||
```powershell
|
||||
cd D:\Scripts\md-preview
|
||||
cargo test # 43 passed
|
||||
cargo build --release # Finished
|
||||
.\MD-Preview-windows-x64.exe path\to\file.md
|
||||
```
|
||||
~~~powershell
|
||||
cd D:\Scripts\md-preview\AgentLowWorking
|
||||
cargo test
|
||||
.\agent\scripts\build.ps1
|
||||
# 发布前 UI 冒烟(普通桌面 PowerShell / Node 21+):
|
||||
.\agent\tests\ui-smoke.cmd
|
||||
# 发布由用户在自己的普通 PowerShell 运行:
|
||||
.\agent\scripts\publish.ps1
|
||||
~~~
|
||||
|
||||
手工检查:
|
||||
|
||||
- [ ] `ui-smoke.cmd` 输出 `OK: N checks`,截图里能看到正文、标题和代码高亮
|
||||
- [ ] 窗口标题为 `文件名 — MD Preview`
|
||||
- [ ] 工具栏只有 编辑 / 缩放(无 Update / Open / Print / Find)
|
||||
- [ ] 多标签切换、关闭、会话恢复
|
||||
- [ ] 多标签切换、关闭;切回标签仍保持编辑模式和滚动位置
|
||||
- [ ] 编辑后 700ms 自动保存,关闭前落盘
|
||||
- [ ] 第二个实例打开文件时,第一个实例新增标签、第二个退出
|
||||
- [ ] `icacls MD-Preview-windows-x64.exe` 为 Medium
|
||||
- [ ] `icacls "C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe"` 为 Medium
|
||||
|
||||
## 12. 追加修复(2026-10-21 下午)
|
||||
|
||||
@@ -296,7 +290,7 @@ cargo build --release # Finished
|
||||
### 14.3 验证配方
|
||||
|
||||
```powershell
|
||||
cargo test # 43 passed
|
||||
cargo test # 59 passed
|
||||
.\agent\scripts\build.ps1 # 先关闭正在运行的实例;会打印 SHA256 并校验 Medium
|
||||
```
|
||||
|
||||
@@ -313,7 +307,13 @@ cargo test # 43 passed
|
||||
- 非 md 本地链接仍交给系统打开;`session.json` 非原子写;macOS 残留(`show_info_dialog` / `mdPreviewQuit:`);5 个未构造的 `UserEvent` 警告;大文档折叠未做性能基准。
|
||||
- 历史提交里还有 4 张旧截图(约 0.5 MB),彻底瘦身需 `git filter-repo`(本次未做)。
|
||||
|
||||
### 14.5 下一次开工检查
|
||||
### 14.5 发布
|
||||
|
||||
- Gitea Release `v1.4.2-local.1`:https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.1
|
||||
- 附件 `MD-Preview-windows-x64.exe`(5,501,440 字节,SHA256 `F76BC396…BEDE96C`),发布说明见 `agent/docs/release-notes-v1.4.2-local.1.md`。
|
||||
- 发版流程:改版本 / 写 release notes → `build.ps1` → 用户在普通 PowerShell 运行 `publish.ps1` → 推 tag / 用 Gitea API 建 release 并上传 Nutstore 那份 exe。API 需要 `write:repository` scope 的 token,用完即删。
|
||||
|
||||
### 14.6 下一次开工检查
|
||||
|
||||
1. 读 `agent/AGENTS.md` + `agent/docs/STATUS.md`;
|
||||
2. 关掉正在运行的 MD Preview(build.ps1 会拒绝覆盖);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# 项目状态(滚动更新)
|
||||
|
||||
> 最后更新:2026-10-21 17:32
|
||||
> 最后更新:2026-11-03
|
||||
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
|
||||
>
|
||||
> **当前:所有已提需求(功能 1–6)完成并部署;短期不再修改。** 下次开工先读第 14 节交接。
|
||||
> **当前(2026-11-03):仓库根 `D:\Scripts\md-preview\AgentLowWorking`,整棵树 Low、DSH workspace-write 可编译;成品只发布到 Nutstore;仓库内 exe 已删除。功能基线 v1.4.2-local.5 + 本地未发布修复(59 tests);仓库已是 Windows-only。**
|
||||
>
|
||||
> 2026-11-03 已做:编辑模式与滚动位置按标签记忆;不再把 `.txt` 当文档;clippy 清零、`cargo fmt` 通过;AGENTS 允许拆模块/新增文件;功能不变地拆出 page/markdown/escape/config 模块并删除 macOS/Linux 死代码。未做功能与下一步见 `docs/next-2026-11-03.md`。
|
||||
|
||||
## 1. 仓库
|
||||
|
||||
@@ -20,18 +22,46 @@
|
||||
- `097d2ee` fix: 保存失败不再卡住关闭;正文 padding 48px
|
||||
- `b01553e` feat: 折叠三角固定尺寸 + 折角箭头(并移除历史截图)
|
||||
- `7dbd1e8` chore: 截图不入库(.gitignore + AGENTS 规则)
|
||||
- 若干 docs 提交(状态/路线图/HANDOFF)
|
||||
- `07ac997` feat: AI 输出方言兼容(softbreak→`<br>`、脚注、定义列表、BOM)
|
||||
- `968e89b` docs: 记录方言兼容状态
|
||||
- `53c39af` test: 多行数学公式回归测试
|
||||
- `7fda49b` docs: v1.4.2-local.2 release notes
|
||||
- `625ffdb` docs: 单进程多窗口设计与实施计划
|
||||
- `7d4091d` refactor: 引入 AppState/WindowState,事件按 WindowId 路由(阶段 1)
|
||||
- `39deeac` feat: 运行中创建额外空窗口(阶段 2)
|
||||
- `e24733a` feat: 全局同文件聚焦 + 取消 session 恢复(阶段 3/4)
|
||||
- `5740274` feat: 标签右键在新窗口打开(阶段 5)
|
||||
- `85b20ec` fix: 唯一标签时禁用“在新窗口打开”
|
||||
- `f9ccce0` fix: 处理独立评审发现的窗口归属、detach 回滚、聚焦 dirty、关闭语义、RecentChanged
|
||||
- `9ae2c13` fix: 新窗口留在源显示器、去掉多余 focus、标签拖拽、菜单路径/打开所在位置
|
||||
- `809b7b0` feat: 新标签页(Home 作为无路径标签、`+` 新建标签、New File、单标签隐藏标签栏)
|
||||
- `d90e47e` feat: 界面统一为英文(移除语言检测/中文文案,标签名 New Tab)
|
||||
- `8644966` feat: 编辑 Tab/Shift+Tab 缩进 + 回车跟随缩进
|
||||
- `618ac47` feat: 阅读 Find 选区填入、选区锚点、零滚动打开
|
||||
- 若干 docs 提交(状态/路线图/HANDOFF、local.3/local.4/local.5 release notes)
|
||||
- `d2b1630` chore: switch to Low workspace and Nutstore-only publish
|
||||
- `8d98b5e` fix: add UTF-8 BOM to PowerShell scripts
|
||||
- `dfe3889` fix: remember edit mode and scroll position per tab
|
||||
- `c783a6d` fix: stop treating .txt as a supported document
|
||||
- `8221eb5` chore: clear clippy warnings and tighten the build guard
|
||||
- 忽略:`/target/`、`/MD-Preview-windows-x64.exe`、`/backup/`、`/agent/reports/*.png`
|
||||
- **不变量**:exe 固定为 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,默认 .md 打开方式指向它,不要改名/移动。
|
||||
- **不变量(2026-11-02 起)**:仓库根 `D:\Scripts\md-preview\AgentLowWorking`;成品固定为 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium),默认 .md 打开方式指向它;仓库内不再放 exe。
|
||||
|
||||
## 2. 当前构建/部署状态
|
||||
|
||||
- `cargo test`:43 passed / 0 failed。
|
||||
- 已部署(2026-10-21 17:25 左右):
|
||||
- 大小 5,501,440 字节
|
||||
- SHA256 `F76BC3963BA13BBFC8259BC2B4E3D24468C34E3C9E26491D364D5D364BEDE96C`(快照,不保证可复现)
|
||||
- 完整性级别 Medium - OK;禁用字符串检查全 0。
|
||||
- CDP 复核:折叠按钮 30×30,位于内容左侧 `-34px`(H2 实测 left=14,heading left=48),垂直居中;hover `opacity .6`;两个 SVG 折角箭头按 `collapsed` 切换。
|
||||
- `cargo test`:59 passed / 0 failed(2026-11-03;删除死代码时移除了 3 个平台专用测试)。
|
||||
- `cargo clippy --all-targets`:0 warning;`cargo fmt -- --check`:通过(2026-11-03)。
|
||||
- 当前固定 exe(2026-10-30 部署):
|
||||
- 大小 5,505,024 字节;版本 1.4.2.0
|
||||
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`
|
||||
- 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。
|
||||
- 构建方式:`cargo build --release`(build.ps1 已改为 Low 工作区版,不再复制到固定路径;cargo stderr 不会再触发 Stop)。
|
||||
- 上一版(v1.4.2-local.4):5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`。
|
||||
- 上一版部署(v1.4.2-local.3):5,507,584 字节;SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`。
|
||||
- Nutstore 镜像:工作区外的 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` 已同步为 v1.4.2-local.5(5,505,024 字节,SHA256 `A632EF03…`)。
|
||||
- CDP 复核(2026-10-30):WIP 文档 8 个“为什么”逐个选区 Ctrl+F,滚动变化均为 0px,序号 1/8–8/8 正确;4/8 按 Enter 到 5/8 正常滚动;Tab/Shift+Tab/Enter/撤销均通过。
|
||||
- CDP 复核(2026-10-28,release):New Tab 标签名、Open File / New File 按钮、单 New Tab 隐藏标签栏、`+` 新建 New Tab、首页打开文件复用标签、关闭最后文件回 New Tab、脏内容先保存;界面无中文、无 JS 异常。
|
||||
- CDP 复核(旧):折叠按钮 30×30,位于内容左侧 `-34px`(H2 实测 left=14,heading left=48),垂直居中;hover `opacity .6`;两个 SVG 折角箭头按 `collapsed` 切换。
|
||||
|
||||
## 3. 功能进度
|
||||
|
||||
@@ -43,30 +73,84 @@
|
||||
| 4 | 标题 hover 折叠 | 完成并部署 `f74a04b` |
|
||||
| 5 | 布局微调 + 只读文件保存失败修复 | 完成并部署 `097d2ee` |
|
||||
| 6 | 折叠三角固定 90% + 折角箭头 | 完成并部署 `b01553e` |
|
||||
| 7 | AI 输出方言兼容:softbreak→`<br>`、GFM 脚注、定义列表、UTF-8 BOM | 完成并部署(`07ac997` + `53c39af`),52 tests |
|
||||
| 8 | 单进程多窗口:阶段 1 状态重构 | 完成 `7d4091d`;行为不变 |
|
||||
| 9 | 单进程多窗口:阶段 2 运行中创建空窗口 | 完成 `39deeac`;暂无界面入口;共享 WebContext、焦点、16 上限 |
|
||||
| 10 | 单进程多窗口:阶段 3 全局同文件聚焦 | 完成 `e24733a`;重复打开聚焦已有窗口/标签 |
|
||||
| 11 | 单进程多窗口:阶段 4 取消 session 恢复 | 完成 `e24733a`;只保留 recent;51 tests |
|
||||
| 12 | 单进程多窗口:阶段 5 标签右键新窗口 | 完成 `5740274`;先保存后移动;源窗口空则关闭;52 tests |
|
||||
| 13 | 新窗口留在源显示器 + 标签拖拽 + 菜单路径/打开所在位置 | 完成 `9ae2c13`;53 tests;固定 exe 已更新 |
|
||||
| 14 | 新标签页(New Tab):默认标签、`+` 新建、New File、单标签隐藏标签栏 | 完成并发布 v1.4.2-local.4;59 tests |
|
||||
| 15 | 界面统一为英文(移除系统语言检测/中文文案,标签名 New Tab) | 完成并发布 v1.4.2-local.4;59 tests |
|
||||
| 16 | 编辑 Tab/Shift+Tab 缩进(2 空格)+ 回车跟随缩进 | 完成,`8644966`;原生撤销保留 |
|
||||
| 17 | 阅读 Find 选区填入、选区锚点、从选区打开不滚动、视口起点 | 完成,`618ac47`;CDP 8/8 零滚动 |
|
||||
|
||||
## 4. 已确认的产品决策
|
||||
|
||||
- 缩放:Ctrl + 滚轮,步进 5%,范围 50%–300%,90ms 节流,无鼠标锚点,预览/编辑都生效;持久化到 `config_dir()/zoom.txt`。
|
||||
- 代码块**始终深色**(Visual Studio Dark),不跟随应用主题;行内代码仍跟随主题。
|
||||
- 不加主题按钮/主题切换(Windows 版没有主题 UI),应用主题仍跟随系统。
|
||||
- 工具栏只剩 编辑 / 缩放;Find 按钮已删,`Ctrl+F` 与查找条保留。
|
||||
- 工具栏只剩 Edit / Zoom;Find 按钮已删,`Ctrl+F` 与查找条保留。
|
||||
- 标题折叠:三角按钮 hover 才显示;**固定尺寸**(30px 热区、折角箭头 13.5×20,约为原二级标题实心三角的 90%),所有级别一致;点 H2 折到下一个 H2、点 H3 折到下一个 H3(含子级);**不持久化**;不做“全部折叠/展开”UI;查找命中折叠区自动展开;打印强制展开并隐藏按钮。
|
||||
- 正文/编辑区左右 padding 48px。
|
||||
- **单换行按换行显示**(softbreak→`<br>`),空行仍是段落分隔;标题内不转换。这是本工具面向 AI 输出的有意方言,和严格 CommonMark 不同;硬折行的长段落会保留断点。
|
||||
- 开启 GFM 脚注与定义列表;UTF-8 BOM 在渲染前忽略。
|
||||
- 编辑模式保留 700ms 自动保存 + `Ctrl+S` 立即保存。
|
||||
- 多窗口:单进程、每窗口一个 WebView2/DocumentSession;标签右键“在新窗口打开”或上下拖动标签(>24px)为移动语义;同一文件只开一个;不恢复 session,只保留 recent;非最后窗口关闭最后一个标签会关闭窗口,最后窗口关闭最后一个文件标签会回到 New Tab;Cmd+Q 仅 macOS。详见 `agent/docs/design-single-process-multi-window.md`。
|
||||
- 新标签页(New Tab,2026-10-28 确认):New Tab 是**无路径的普通标签**(可多个,浏览器新标签页语义);`+` 追加并激活 New Tab;新标签页上 Open File / Recent / New File / 拖入文件会复用当前 New Tab;关闭最后一个文件标签回到 New Tab;只有 New Tab 时隐藏标签栏(`HIDE_SINGLE_HOME_TAB = true`,一行可关);New Tab 不可拖出/不可新窗口打开、不监听文件、不参与查重;New File 按钮取代原 `+` 的建文件语义,`Ctrl+N` 仍新建文件。
|
||||
- 界面语言(2026-10-28 确认):**只提供英文界面**;移除 `Lang` / `detect_lang` 和中文 `Strings`,删除 `sys-locale` 依赖;标签名从“首页/Home”改为“New Tab”;不随系统语言切换。
|
||||
- 编辑缩进(2026-10-30 确认):Tab 固定插入 2 个空格,Shift+Tab 反缩进;多行选区整块处理;不插入字面 Tab;保留 textarea 原生撤销;输入法组合期间不拦截。回车复制当前行光标前前导空白,空行不继续叠加;列表续行暂不做。
|
||||
- 阅读 Find(2026-10-30 确认):有选区时 Ctrl+F 自动填入;多行取第一行非空内容;从选区打开时不滚动、不展开折叠,只高亮并显示序号;点下一个/上一个或按 Enter 才滚动;无选区的新查询从当前视口开始;下方无匹配时选上方最近匹配。编辑模式 Find 继续用 WebView2 原生查找,不统一。
|
||||
- 新窗口位置:源窗口当前显示器内 +28,+28 偏移并 clamp;不逐窗口恢复位置。
|
||||
- 标签右键菜单:顶部路径(中间省略,保留开头和文件名),第一项 Show in Explorer,第二项 Open in New Window;右键时临时移除标签 tooltip。
|
||||
|
||||
## 5. 保存失败(只读文件)处理
|
||||
|
||||
- 自动保存失败时:弹一次警告,调用 `window.__markSaveBlocked()` 暂停该文件的自动保存,标签保持 dirty,不再每 700ms 弹窗。
|
||||
- 关闭窗口失败时:弹一次 Ok/Cancel「无法保存,仍要关闭并丢弃修改?」,Ok 直接退出,Cancel 留在应用;不会再出现“关不掉”。
|
||||
- 关闭窗口失败时:弹一次 Ok/Cancel 对话框(标题 “Could Not Save”),Ok 直接退出,Cancel 留在应用;不会再出现“关不掉”。
|
||||
- 已进入 blocked 状态的标签,关闭/切换时用 `window.confirm` 确认是否丢弃修改(确认后发送不带内容的 tab-action)。
|
||||
- 文件本身**没有长期占用**:保存是 `fs::write` 打开-写入-关闭,watcher 只监听目录;只在保存瞬间需要写权限。
|
||||
|
||||
## 5.1 单进程多窗口进度
|
||||
|
||||
- 阶段 1(`7d4091d`):AppState/WindowState、UserEvent 携带 WindowId、IPC/事件按窗口路由;仍只有一个窗口,用户可见行为不变;52 tests。
|
||||
- 阶段 2(`39deeac`):抽出 build_webview 工厂;共享 WebContext;内部 IPC `new-window` 可创建第二个空窗口;新窗口 +28,+28 偏移、焦点切换、主窗口几何保留、16 上限;关闭单个窗口不再退出整个进程。
|
||||
- 阶段 3(`e24733a`):`find_open_path` 跨窗口查重;双击/转发打开已在其他窗口的文件时,聚焦该窗口和标签,不再重复打开;若当前标签有未保存修改且目标不是当前标签,不强行切换,避免丢编辑。
|
||||
- 阶段 4(`e24733a`):启动不再读 `session.json`,不再写 session;只保留 recent-files.txt。旧 session.json 留在磁盘但不主动删除。删除了 session 往返测试,52→51。
|
||||
- 阶段 5(`5740274`):标签右键自定义菜单 Open in New Window;移动语义。active 且 dirty 时由 JS 附带内容、Rust 先写盘再移动;inactive 且 dirty 时拒绝移动并提示;inactive 且 clean 时先 activate 再移动;源窗口最后一个标签移出后关闭源窗口;新窗口只含被移动标签;失败保留源标签。
|
||||
- 修复(`85b20ec`):只有 1 个标签时菜单项置灰禁用;2 个及以上才可点。
|
||||
- 标签/显示修复(`9ae2c13`):
|
||||
- 新窗口用源窗口 `current_monitor()` + 物理坐标,修复在第二屏 detach 却跳到主屏;
|
||||
- `OpenPaths` 查重前不再无条件 focus,重复打开只 focus 最终目标;
|
||||
- 标签上下拖动 >24px 新窗口;唯一标签禁止;拖动后抑制 click;
|
||||
- 菜单更紧凑,顶部显示中间省略路径;新增 Show in Explorer;
|
||||
- 菜单打开时临时移除标签 tooltip,关闭后恢复。
|
||||
- 评审修复(`f9ccce0`):
|
||||
- `OpenPaths` 携带目标 WindowId;拖放/导航/IPC/Ready 不再统一落到 active window;批次 target 固定;
|
||||
- detach 不再在创建新窗口前激活源 session;创建/移除失败不会改写源 active;
|
||||
- `focus_open_tab` 在源 active 或目标标签 dirty 时拒绝切换并提示,不再静默丢焦点;
|
||||
- 非最后窗口关闭最后一个标签会关闭该窗口;最后窗口关闭最后一个文件标签会回到 New Tab;
|
||||
- `RecentChanged` 不再清空有标签窗口;
|
||||
- 移除了不可达的内部 `new-window` 路径。
|
||||
- 用户可见变化:启动不再恢复上次标签;同文件重复打开聚焦已有窗口/标签;标签右键现在有 Open in New Window,这是第一个普通用户可操作的多窗口入口。
|
||||
- 已验证:菜单显示;active dirty 保存后再移动;inactive clean 移动且源窗口保留;源窗口唯一标签移动后源窗口关闭;新窗口正常显示文件。
|
||||
- 独立评审报告:`agent/reports/multi-window-update-report-2026-10-28.md`;评审回应:`agent/reports/multi-window-review-response-2026-10-28.md`。
|
||||
- Release notes:`agent/docs/release-notes-v1.4.2-local.3.md`;固定 exe 已是该构建。
|
||||
- 阶段 6:README/状态/release notes 已更新,已 push 并发布 Gitea release v1.4.2-local.3。
|
||||
- 固定 exe 已是最新构建(53 tests),不再有旧版。
|
||||
|
||||
## 6. 已知问题 / 候选修复
|
||||
|
||||
- 非 md 本地链接目前交系统打开;可改为站内预览。
|
||||
- `session.json` 非原子写;可加 `.bak`。
|
||||
- `session.json` 已不再读写;旧文件可手动删除,不主动处理。
|
||||
- macOS 残留:`show_info_dialog` 未定义、`mdPreviewQuit:` 未注册(不影响 Windows)。
|
||||
- 5 个未构造的 `UserEvent` 变体警告(`CloseActiveTab` / `ToggleEdit` / `ShowFind` / `SetTheme` / `Quit`)。
|
||||
- 调试 exe(`target\debug`)是 console subsystem + 未优化/带符号,约 9.8MB,双击会带 cmd 窗口;release exe 是 Windows GUI subsystem、LTO/strip,约 5.5MB,无双击 cmd。用户测试应使用 release;固定 exe 已更新。
|
||||
- 标签右键菜单有“打开文件所在位置”和“在新窗口打开”;支持上下拖拽移出;仍不做拖回、窗口合并;无键盘入口。
|
||||
- 源窗口最后一个标签移出后直接关闭,不弹“是否关闭源窗口”。
|
||||
- Quit 仍只处理 active window 的保存/退出;Windows 无 Cmd+Q,暂不影响 Windows;接入多窗口 Quit 前需补全遍历。
|
||||
- dirty 仍是 JS/tab/ws 三份副本,没有显式状态机;当前主路径靠“先保存再移动”规避。
|
||||
- 多显示器新窗口已使用源窗口当前显示器;混合 DPI/跨屏精细位置仍只做基础 clamp;不逐窗口记忆位置;primary 关闭后按 HashMap 任意提升。
|
||||
- 大文档折叠性能尚未做基准。
|
||||
- 历史提交里仍有 4 张旧截图(约 0.5 MB);如需彻底瘦身要改写历史(filter-repo),暂不做。
|
||||
|
||||
@@ -74,15 +158,82 @@
|
||||
|
||||
```powershell
|
||||
cargo test
|
||||
.\agent\scripts\build.ps1 # 需要先关闭正在运行的 MD Preview
|
||||
.\agent\tests\smoke.ps1 -Launch
|
||||
.\agent\scripts\build.ps1 # 开发构建;产物在 target\release\
|
||||
.\agent\tests\smoke.ps1 -Launch # 发布后冒烟(Nutstore exe)
|
||||
.\agent\scripts\publish.ps1 # 发布:用户在自己的普通 PowerShell 运行
|
||||
```
|
||||
|
||||
## 8. 环境与规则
|
||||
|
||||
- **最高优先级**:`agent/AGENTS.md` —— 只在工作区内改文件;工作区外的任何修改先停下询问用户。
|
||||
- 工作区是 Medium 完整性级别;DSH 需 danger-full-access 才能改/编译(workspace-write 会 EPERM / os error 5)。
|
||||
- 不要把工作区改成 Low。
|
||||
- **最高优先级**:`agent/AGENTS.md` —— 只在仓库内改文件;仓库外的任何修改先停下询问用户。
|
||||
- 仓库根 `D:\Scripts\md-preview\AgentLowWorking` 整棵树是 **Low**;DSH 用 **workspace-write** 即可改/编译。
|
||||
- 构建产物是 Low,不能直接双击;冒烟用 `MD_PREVIEW_CONFIG_DIR` 指到仓库内。
|
||||
- 发布由用户手动运行 `publish.ps1`(Medium);Agent 不运行发布脚本、不改注册表。
|
||||
- `git clean -xdf` 会删除被忽略的 backup 与 exe。
|
||||
- 截图/录屏等二进制验证产物**不入库**:放 `agent/tmp/` 或 `target/tmp/`,看完即删;`agent/reports/` 只留文本。
|
||||
- `%TEMP%` 历史测试残留已于 2026-10-21 16:38 经用户同意清理;之后的测试/构建把 TEMP/TMP 指向 `target\tmp` 与 `target\test-tmp`。
|
||||
|
||||
## 9. 发布(Gitea)
|
||||
|
||||
- 实例 Gitea 24.5.4,仓库私有。
|
||||
- Release `v1.4.2-local.5`(最新,2026-10-30):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.5
|
||||
- 附件 `MD-Preview-windows-x64.exe`,5,505,024 字节
|
||||
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`(已下载复核一致)
|
||||
- 正文来源:`agent/docs/release-notes-v1.4.2-local.5.md`
|
||||
- Release `v1.4.2-local.4`(上一版,2026-10-28):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.4
|
||||
- 附件 5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`(已下载复核一致)
|
||||
- Release `v1.4.2-local.3`(上一版):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.3
|
||||
- 附件 5,507,584 字节;SHA256 `0BFF7302...2372E`
|
||||
- 正文来源:`agent/docs/release-notes-v1.4.2-local.3.md`
|
||||
- Release `v1.4.2-local.2`(上一版):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.2
|
||||
- 附件 5,505,024 字节;SHA256 `7C8A3A8A...99BD95`
|
||||
- Release `v1.4.2-local.1`(上一版):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.1
|
||||
- 附件 5,501,440 字节;SHA256 `F76BC396...BEDE96C`
|
||||
- 仓库描述与 topics 已通过 API 设置(topics:windows, markdown, markdown-preview, rust, webview2, offline, desktop-app)。
|
||||
- **Gitea token 位置**:`C:\Users\wucl1\.gitea-token`(工作区外;保留,不要提交/删除;读取后不要打印内容)。
|
||||
- 工作区内的 `.gitea-token` 旧路径已 gitignore;以后优先使用上面的用户目录文件。
|
||||
|
||||
## 10. 2026-11-02 迁移(Low 工作区)
|
||||
|
||||
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`(整棵树 Low)。
|
||||
- DSH 工作区仍是父目录 `D:\Scripts\md-preview`;代码在子目录 `AgentLowWorking`。
|
||||
- DSH 以 `workspace-write` 运行;不再需要 danger-full-access。
|
||||
- 开发构建:`.\agent\scripts\build.ps1`(产物 `target\release\md-preview.exe` 是 Low)。
|
||||
- 开发冒烟:`$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"; .\target\release\md-preview.exe <file>`。
|
||||
- 发布:用户在自己的普通 PowerShell(Medium)运行 `.\agent\scripts\publish.ps1`;脚本复制到 Nutstore、设 Medium、校验 SHA256、刷新 `.md` 关联、删除旧 exe。
|
||||
- 仓库内不再放成品 exe;默认打开指向 Nutstore。
|
||||
- 迁移步骤与回滚见 `agent/docs/migration-2026-11-02.md`。
|
||||
|
||||
## 11. 2026-11-03 维护与待决策
|
||||
|
||||
- 已确认并实现(未发布):
|
||||
- 编辑模式按标签记忆(原先属于窗口);切换标签恢复该标签离开时的编辑/阅读状态;detach 保留编辑状态。
|
||||
- 滚动位置按标签记忆(相对比例,抗缩放/回流);标签动作携带比例,滚动回报带标签 id,避免迟到回报落到新标签;编辑/阅读切换仍保持滚动。
|
||||
- `.txt` 不再作为文档类型:打开、重新定位、本地链接、命令行都只认 `md/markdown/mdown/mkd`。
|
||||
- 非 md 本地链接(pdf/png/html)仍无反应,仅记录,不处理。
|
||||
- 代码整理:`cargo fmt` 通过;clippy 7 条清零;保存写盘合并为 `save_active_file()`;`build.ps1` 的禁止字符串不再包含泛化的 `powershell`。
|
||||
- 架构拆分阶段 1(功能不变,`1115052`):`assets/page/{page.html,page.css,page.js}` 存页面;新增 `src/markdown.rs`(md→html 管线)、`src/page.rs`(页面组装,只填 `__MDP_*__` 占位符)、`src/escape.rs`(JS/HTML 转义)。`main.rs` 5535 → 3709 行;页面输出用 home/doc/startup 三组快照做 sha256 对比,逐字节一致。
|
||||
- 架构拆分阶段 2(功能不变,2026-11-03 晚):新增 `src/config.rs`(路径/zoom/窗口几何/对话框);删除 macOS/Linux/Finder 扩展代码、非 Windows 分支和 `objc2` 依赖(仓库现在只能在 Windows 编译);测试模块移到文件末尾;`main.rs` 3709 → 2822 行。59 tests(删除死代码时移除 3 个平台专用测试)。
|
||||
- 架构拆分阶段 3(功能不变,2026-11-06,`1208386`):新增 `src/files.rs`(最近文件、保存写盘、文件监听、扩展名、本地链接、Explorer)与 `src/testutil.rs`;对应测试随模块搬迁。`main.rs` 2822 → 2365 行。
|
||||
- 架构拆分阶段 4(功能不变,2026-11-06,`fb10fc5`):新增 `src/app.rs`(`UserEvent`/`WindowState`/`AppState`、渲染、`build_webview`、窗口创建/关闭、`run_event_loop`);`main.rs` 只留 CLI、启动装配、`main()` 和测试(2365 → 804 行)。60 tests 全绿,clippy/fmt 干净,release 仍是 5,502,464 字节。
|
||||
- 架构拆分阶段 5(功能不变,2026-11-06,`a5c0b08`):测试全部随模块迁移(app 7、markdown 23、page 5、config 2、files 10、session 10、instance 3,共 60),共享 `testutil::temp_dir`;启动装配与 CLI 移入 `app::run()`,`main.rs` 18 行(仅模块声明 + `app::run()`)。
|
||||
- HKCU 关联:应用启动时不再写注册表(`register_as_default` 及 `winreg` 依赖已删除);`publish.ps1` 维持现状(继续写 ProgID/关联)。首次使用需在 Windows“打开方式 → 选择其他应用”里选一次。
|
||||
- 白屏 bug(2026-11-04 修复):当时 `render_active_document` 给 `window.__setContent` 传了 8 个参数,页面签名只有 7 个(多传了 `active.id`),标签 id 被当成 `previewHtml` 渲染——窗口白屏、打开标签依次显示 1/2/3/4。修复:抽出 `set_content_script()`(单一参数源),新增精确输出 + 页面签名对照测试 `set_content_script_matches_the_page_signature`(60 tests)。教训:Rust→JS 这条边界没有编译器检查。
|
||||
- 发布前 UI 冒烟:`agent/tests/ui-smoke.cmd`(普通桌面 PowerShell;启动 CDP、断言页面渲染、截图、写 `target/ui-test/ui-smoke.json`)。DSH 沙箱禁止命名管道,WebView2/Chromium 在沙箱内无法启动(窗口白屏、`msedgewebview2.exe` 立即退出),所以这一项只能由用户手动跑。**2026-11-04 已在本机跑通:8/8 checks,截图确认页面正常渲染**(`target/ui-test/ui-smoke.png`,不入库)。
|
||||
- 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。
|
||||
- 编辑区 CodeMirror 5(2026-11-06 完成,未发布;`8b4d1fa` → `e911876`):
|
||||
- `assets/codemirror/` vendored 5.65.16:core + xml/meta/markdown + searchcursor/search/dialog + foldcode/foldgutter,约 218 KB,附 LICENSE。启动 HTML 不含 CM;首次进编辑通过 `need-editor` IPC 注入,注入失败保留 textarea。
|
||||
- page.js 先抽 `createTextareaEditor`/`createCodeMirrorEditor` 适配层;编辑模式有行号、markdown 着色(标题/加粗/斜体/链接/引用,标记不隐藏)、标题+围栏折叠、CM 内部滚动;页面滚动改到 `#app` 容器,阅读/编辑滚动条都在标签栏下沿。
|
||||
- 折叠:围栏状态按文档缓存、change 行处增量失效;只有开围栏有箭头,折叠包含收尾围栏;代码块里的 `#` 不再当标题。
|
||||
- 查找替换:页面自己的两行 findbar(Find + ↑↓× / Replace + Replace All),Esc 只关查找条;Ctrl+E 退出编辑;阅读模式 find 保持原样。
|
||||
- 滚动:JS `cmTabLines` 按标签记顶部行号,Rust `scroll_ratio` 兜底;`__setContent` 增加第 8 参数 tab id,切标签先加载目标内容、在绘制前滚到行首。
|
||||
- BOM:编辑器值去掉开头 U+FEFF,保存时原样加回;首行标题/围栏识别正常。
|
||||
- 大文档(>2 MB 或 >2 万行)回退 textarea:无行号/折叠/编辑查找。
|
||||
- 已知限制:编辑查找为字面匹配、大小写不敏感,不支持 CM 对话框的 `/re/` 正则;阅读→编辑滚动仍按比例近似;打印只有 CSS 层验证。
|
||||
|
||||
## 12. 测试与验证(2026-11-04 起)
|
||||
|
||||
- 代码级:`cargo test`(当前 63)、`cargo clippy --all-targets`、`cargo fmt -- --check`、`agent\scripts\build.ps1`。
|
||||
- UI 级:**只能由用户**在桌面 PowerShell 运行 `agent\tests\ui-smoke.cmd`;Agent 读 `target\ui-test\ui-smoke.json` + `ui-smoke.png`。原因与流程见 `HANDOFF.md` §4.1(DSH 沙箱禁止命名管道,WebView2 无法启动)。
|
||||
- 边界:Rust→JS 调用没有编译器检查;改参数必须同步页面签名,并保留 `set_content_script_matches_the_page_signature` 这类测试。
|
||||
- 已验证(2026-11-04、2026-11-06 多次):ui-smoke 8/8 checks,截图确认页面正常渲染。CM5 改版后由用户手动验证编辑/保存/折叠/替换/滚动,ui-smoke 仍 8/8。
|
||||
|
||||
469
agent/docs/design-multi-process-tabs.md
Normal file
469
agent/docs/design-multi-process-tabs.md
Normal file
@@ -0,0 +1,469 @@
|
||||
# 多进程标签窗口方案(端口扫描)
|
||||
|
||||
> 状态:设计讨论稿,未写代码。独立评估报告结论为 No-go(当前方案),见 agent/reports/multi-process-tabs-feasibility.md;等待用户决定方向。
|
||||
> 日期:2026-10-27
|
||||
> 关联:agent/AGENTS.md、agent/docs/STATUS.md
|
||||
|
||||
## 1. 结论摘要
|
||||
|
||||
采用“方案 2:端口扫描 + 本地 TCP 握手”,把当前的单窗口单 WebView 应用扩展为多个平等进程:
|
||||
|
||||
- 每个进程一个窗口、一个 WebView2、一个独立的标签列表;
|
||||
- 取消启动时恢复标签,只保留“最近打开文件”;
|
||||
- 所有进程平等,没有主/子、没有 session owner;
|
||||
- 64 个候选端口,最多 16 个监听实例;
|
||||
- 新进程扫描端口,找到已有实例后询问“这个文件开了吗”;
|
||||
- 文件已打开则聚焦已有窗口,不重复打开;
|
||||
- 文件未打开则按入口决定加到已有窗口或启动新进程;
|
||||
- 最多 16 个窗口,超出提示,不启动第 17 个;
|
||||
- 用短生命周期 startup.lock 串行化“扫描—查重—启动/打开”;
|
||||
- 不做拖出、不做拖回、不做窗口合并、不做文件注册表。
|
||||
|
||||
## 2. 背景
|
||||
|
||||
当前应用:
|
||||
|
||||
- src/main.rs 创建一个 tao Window 和一个 wry WebView;
|
||||
- 所有标签在同一个页面里渲染,DocumentSession 是单个进程内的标签列表;
|
||||
- src/instance.rs 用 instance.lock + instance.json + TCP 做单实例转发;
|
||||
- session.json 保存标签,启动时恢复;
|
||||
- 最近文件、缩放、窗口位置、主题等分别存在 config_dir()。
|
||||
|
||||
目标不是把单进程改造成多窗口,而是让“标签页在新窗口打开”变成“启动一个新的独立进程”。这样窗口生命周期、WebView2 实例、关闭行为都由操作系统隔离,不需要复杂的窗口状态迁移。
|
||||
|
||||
## 3. 目标与非目标
|
||||
|
||||
### 目标
|
||||
|
||||
1. 标签页右键菜单提供“在新窗口打开”。
|
||||
2. 默认双击 .md 仍优先在已有窗口加标签。
|
||||
3. 所有窗口可接收新的打开请求,不依赖单一接收者。
|
||||
4. 同一个 md 不会在两个窗口同时打开;已打开时聚焦已有窗口。
|
||||
5. 最多 16 个窗口,超出提示。
|
||||
6. 只持久化最近打开文件,不恢复标签。
|
||||
7. Windows 为主,代码尽量兼容 macOS/Linux。
|
||||
8. 不新增依赖,不联网,不使用 Windows 注册表。
|
||||
|
||||
### 非目标
|
||||
|
||||
- 不支持把标签拖出窗口,也不支持拖回。
|
||||
- 不支持独立窗口合并回主窗口。
|
||||
- 不恢复上次的标签、激活标签、滚动位置、编辑状态。
|
||||
- 不实现跨进程编辑合并或文件锁。
|
||||
- 不做多用户隔离或安全认证。
|
||||
- 不处理多窗口的窗口位置级联;窗口位置仍按现有 window.geom 行为。
|
||||
- 不改变 .md 文件关联和固定 exe 路径。
|
||||
|
||||
## 4. 术语
|
||||
|
||||
- 实例:一个独立进程,拥有一个窗口和一个 WebView2。
|
||||
- 监听实例:成功绑定端口并接受握手的实例。
|
||||
- peer:扫描时能正确握手的其他实例。
|
||||
- 普通打开:双击 .md、命令行带文件、最近文件、拖入文件、本地链接等。
|
||||
- 显式新窗口:右键标签选择“在新窗口打开”。
|
||||
- 目标窗口:已打开某文件、需要被聚焦的实例。
|
||||
- startup.lock:config_dir() 下的短生命周期文件锁,只用于串行化打开流程。
|
||||
- recent:最近打开文件列表,唯一的跨进程持久化状态。
|
||||
|
||||
## 5. 总体架构
|
||||
|
||||
每个进程:
|
||||
|
||||
- 一个 tao Window + 一个 wry WebView;
|
||||
- 一个内存中的 DocumentSession(标签列表,不持久化);
|
||||
- 一个 TCP listener,绑定 127.0.0.1 的端口段内端口;
|
||||
- 一个 instance_id(进程内随机生成,只用于握手);
|
||||
- 共享 recent 文件,但更新时加锁;
|
||||
- 没有全局 session,不读写 session.json。
|
||||
|
||||
进程之间只有一次性请求/响应:
|
||||
|
||||
- 扫描握手;
|
||||
- 查询文件是否已打开;
|
||||
- 请求聚焦某个文件;
|
||||
- 请求在目标实例打开文件;
|
||||
- 子进程向父进程报告 detach ready。
|
||||
|
||||
没有长期连接、没有后台心跳、没有共享内存。
|
||||
|
||||
## 6. 端口与握手
|
||||
|
||||
### 6.1 端口段
|
||||
|
||||
- 固定 64 个候选端口,例如 25100–25163。
|
||||
- 选低于 32768 的段,避开 Linux 常见的临时端口范围;Windows/macOS 也可用。
|
||||
- 只绑定 127.0.0.1,不监听外部网卡。
|
||||
- 每个进程从段内选择最小空闲端口。
|
||||
- 最多 16 个监听实例;达到 16 后不再启动第 17 个窗口。
|
||||
- 端口段可用测试环境变量覆盖,避免测试连到生产实例。
|
||||
|
||||
### 6.2 监听上限
|
||||
|
||||
- 新进程扫描 64 个端口,统计握手成功的实例数。
|
||||
- 文件已打开时,聚焦优先,不受 16 上限影响。
|
||||
- 文件未打开且已有 16 个实例时,提示“最多同时打开 16 个窗口”,不启动。
|
||||
- 关闭一个窗口后端口释放,下一次打开可以再启动。
|
||||
- 进程崩溃时端口自动关闭,不占名额。
|
||||
- 如果 64 个端口都被其他程序占用,应用仍可打开,但无法监听;需要提示这是降级状态。
|
||||
|
||||
### 6.3 帧格式
|
||||
|
||||
每次连接只处理一个请求/响应:
|
||||
|
||||
- 4 字节小端长度 + UTF-8 JSON;
|
||||
- 最大帧 1 MiB;
|
||||
- 连接和读取设置短超时;
|
||||
- 请求和响应都带 magic、version、nonce。
|
||||
|
||||
请求字段:
|
||||
|
||||
- magic:固定字符串,例如 md-preview;
|
||||
- version:协议版本;
|
||||
- config_id:配置目录的稳定哈希,避免测试/生产串线;
|
||||
- nonce:随机串;
|
||||
- instance_id:发送方实例 ID;
|
||||
- op:hello / query / focus / open / detach-ready;
|
||||
- paths:可选,规范化后的路径列表;
|
||||
- edit:可选,是否编辑模式。
|
||||
|
||||
响应字段:
|
||||
|
||||
- magic、version、nonce;
|
||||
- instance_id;
|
||||
- ok;
|
||||
- found、tab_id、focused 等按 op 返回;
|
||||
- error:可选错误文本。
|
||||
|
||||
握手只做协议识别和防误连,不是安全机制。GUID/常量编码在程序内部即可,不宣传成认证。
|
||||
|
||||
### 6.4 扫描策略
|
||||
|
||||
- 64 个端口分批并行连接,避免串行超时累积。
|
||||
- 每个连接 20–50 ms 超时;localhost 拒绝连接通常立即返回。
|
||||
- 收集所有有效响应,按端口升序选择第一个。
|
||||
- 有效响应必须 magic、version、config_id、nonce 全部匹配。
|
||||
- 其他程序占用的端口握手失败,直接跳过。
|
||||
- 扫描失败/超时不应阻塞 UI;启动阶段完成后再建窗口。
|
||||
|
||||
## 7. 打开流程
|
||||
|
||||
### 7.1 startup.lock
|
||||
|
||||
所有打开入口都必须先获取 config_dir()/startup.lock:
|
||||
|
||||
- 普通双击;
|
||||
- 显式新窗口;
|
||||
- Open 对话框;
|
||||
- 最近文件;
|
||||
- 拖入文件;
|
||||
- 本地链接打开;
|
||||
- 命令行启动带文件。
|
||||
|
||||
锁的持有范围:
|
||||
|
||||
- 从开始扫描到目标窗口打开并完成监听;
|
||||
- 如果只是把文件转发给已有实例,收到 ack 后释放;
|
||||
- 如果启动新窗口,监听建立、文件打开后释放;
|
||||
- 超时或失败必须释放;
|
||||
- 进程崩溃时由操作系统释放文件锁。
|
||||
|
||||
startup.lock 不是常驻主进程,也不是注册表;它只保证打开决策串行化。
|
||||
|
||||
等待 startup.lock、扫描端口、查询 peer 这些操作不能放在 UI 事件循环里同步执行,否则另一个进程启动较慢时,当前窗口会卡住。普通启动可以在建窗口前同步执行;运行中的打开、最近文件、拖入、右键新窗口都应放到后台任务,完成后通过 UserEvent 回到事件循环。
|
||||
|
||||
### 7.2 普通双击
|
||||
|
||||
1. 解析并校验路径;
|
||||
2. 如果路径在本进程已打开,激活本地标签;
|
||||
3. 获取 startup.lock;
|
||||
4. 扫描 64 端口;
|
||||
5. 查询每个实例是否已打开该路径;
|
||||
6. 如果已打开:请求目标实例聚焦对应标签,更新 recent,释放锁,退出;
|
||||
7. 如果未打开:
|
||||
- 有 peer:把路径发给最小端口的 peer,更新 recent,释放锁,退出;
|
||||
- 无 peer:启动新窗口,绑定端口,打开文件,释放锁。
|
||||
8. 目标实例聚焦失败时,提示“文件已在另一个窗口打开,但无法切换到前台”,不重复打开。
|
||||
|
||||
### 7.3 显式新窗口
|
||||
|
||||
1. 校验路径;
|
||||
2. 如果本进程已打开,激活本地标签;
|
||||
3. 获取 startup.lock;
|
||||
4. 扫描并查询是否已打开;
|
||||
5. 已打开:聚焦目标,不新建;
|
||||
6. 未打开:检查实例数;小于 16 则启动新进程,只打开目标文件;等于 16 则提示上限;
|
||||
7. 释放锁。
|
||||
|
||||
显式新窗口不把文件加到已有窗口,但仍然遵守“同一文件只开一个窗口”和 16 上限。
|
||||
|
||||
### 7.4 无文件启动
|
||||
|
||||
- 扫描并查询 peer;
|
||||
- 有 peer:聚焦最小端口实例,自己退出;
|
||||
- 无 peer:启动空窗口,显示 recent 列表和打开按钮;
|
||||
- 不恢复任何标签;
|
||||
- 空窗口也占一个监听名额。
|
||||
|
||||
### 7.5 已运行进程内部的打开
|
||||
|
||||
运行中的进程从 Open 对话框、recent、拖入、本地链接打开文件时:
|
||||
|
||||
1. 如果本进程已有该标签,激活;
|
||||
2. 获取 startup.lock;
|
||||
3. 查询其他实例是否已打开;
|
||||
4. 已打开:聚焦目标,本进程不新增标签;
|
||||
5. 未打开:在本进程新增标签(不新建窗口);
|
||||
6. 释放锁。
|
||||
|
||||
运行中进程不需要检查 16 上限,因为它已经有窗口。
|
||||
|
||||
## 8. 去重与聚焦
|
||||
|
||||
### 8.1 路径规范化
|
||||
|
||||
所有比较使用统一规范化:
|
||||
|
||||
- 转绝对路径;
|
||||
- 去掉 Windows 的 \\?\ 前缀;
|
||||
- 对存在的文件做 canonicalize;
|
||||
- 对不存在的文件规范化父目录;
|
||||
- Windows 路径比较不区分大小写;
|
||||
- 符号链接、短路径、相对路径尽量归一到同一结果;
|
||||
- 查询和响应都使用规范化路径。
|
||||
|
||||
### 8.2 查询
|
||||
|
||||
- 请求 op=query,带一个或多个规范化路径;
|
||||
- 目标实例遍历自己的标签,返回 found 和 tab_id;
|
||||
- 不返回未打开文件的完整列表,减少信息量;
|
||||
- 多路径时逐个处理;只要有一个已在其他实例打开,就优先聚焦。
|
||||
|
||||
### 8.3 聚焦
|
||||
|
||||
- 目标实例收到 op=focus;
|
||||
- 在事件循环中 set_minimized(false)、set_focus()、激活对应标签;
|
||||
- 可能使用 request_user_attention 作为兜底;
|
||||
- Windows 前台锁可能只让任务栏闪烁,不能保证一定到最前;
|
||||
- 返回 focused=true/false;失败时发送方提示,不重复打开。
|
||||
|
||||
### 8.4 并发
|
||||
|
||||
startup.lock 串行化“查询 + 启动/打开”,关闭两个同时冷启动的竞态。
|
||||
如果锁等待超时,提示用户重试,不绕过锁直接打开。
|
||||
|
||||
## 9. 右键“在新窗口打开”
|
||||
|
||||
### 9.1 UI
|
||||
|
||||
- 只对标签页放开右键;其他区域继续保持禁用;
|
||||
- 右键菜单是自定义 HTML 菜单,只有一项“在新窗口打开”;
|
||||
- 点击外部、Esc、滚动时关闭;
|
||||
- 菜单不超出窗口边界;
|
||||
- 不做原生菜单。
|
||||
|
||||
### 9.2 移动语义
|
||||
|
||||
推荐移动语义:新窗口成功打开后关闭原标签;失败则保留原标签。
|
||||
|
||||
### 9.3 事务
|
||||
|
||||
1. 获取 startup.lock;
|
||||
2. 如果当前标签 dirty,先把内容写入磁盘;写失败则中止,保留标签;
|
||||
3. 查询其他实例是否已打开该文件(排除自己);
|
||||
4. 如果其他实例已打开,聚焦对方,保留原标签;
|
||||
5. 如果已有 16 个窗口,提示上限,保留原标签;
|
||||
6. 启动子进程,传入目标路径和父进程端点信息;
|
||||
7. 子进程打开文件、绑定端口,向父进程发送 detach-ready;
|
||||
8. 父进程收到 ready 后关闭原标签,释放锁;
|
||||
9. 超时或子进程失败:父进程保留标签,释放锁,并清理子进程。
|
||||
|
||||
注意:第 7–9 步不应阻塞 UI 事件循环;需要后台线程或异步事务,把结果再送回事件循环。
|
||||
|
||||
等待 ready 期间,父进程仍在显示原标签;必须把该标签标记为“正在移出”,暂时禁止编辑/自动保存,避免用户在子进程启动期间继续修改导致内容不一致。失败或超时后解除标记,保留原内容。
|
||||
|
||||
detach 子进程是父进程的可信交接对象,不再扫描、不再查重、不再检查 16 上限,也不获取 startup.lock;这些检查由父进程在锁内完成。子进程只负责打开文件、绑定端口、发送 ready。这样可以避免父子进程互相等待 startup.lock 死锁。
|
||||
|
||||
### 9.4 简化备选
|
||||
|
||||
如果 ready 握手成本过高,第一版可以接受“spawn 成功即关闭原标签”,但存在子进程 WebView 初始化失败时标签丢失的风险。建议先实现 ready 握手,至少保留超时和错误提示。
|
||||
|
||||
## 10. 最近文件
|
||||
|
||||
- 只保留 recent,不再读写 session.json;
|
||||
- recent 是唯一的跨进程持久化状态;
|
||||
- 打开/聚焦文件后更新 recent;
|
||||
- 使用 recent.lock + 读改写 + 临时文件原子替换;
|
||||
- Windows 上替换前需要处理目标文件已存在的情况;
|
||||
- recent 仍要过滤不存在/不支持的文件;
|
||||
- 启动无文件时用 recent 渲染空状态;
|
||||
- 不记录 active tab、滚动位置、编辑状态。
|
||||
|
||||
## 11. 移除 session 恢复
|
||||
|
||||
需要处理:
|
||||
|
||||
- DocumentSession::load / save、PersistedSession、session_path 的调用;
|
||||
- main.rs 中所有 persist_session 调用;
|
||||
- 启动时 initial_session 的加载;
|
||||
- 关闭窗口时的 session 保存;
|
||||
- 相关测试(persisted_session_*);
|
||||
- 旧 session.json 文件:不再读取,可保留不删,避免动用户数据;在文档中说明已停用。
|
||||
|
||||
DocumentSession 仍保留标签列表、active_id、dirty、missing 等进程内状态;只删除持久化职责。
|
||||
|
||||
## 12. 窗口与生命周期
|
||||
|
||||
- 所有进程平等,不建立父子管理;
|
||||
- 父进程 spawn 子进程后不等待其退出;
|
||||
- 子进程关闭不影响父进程;
|
||||
- 父进程关闭不影响子进程;
|
||||
- 不做窗口位置级联;window.geom 仍由最后关闭的进程写入;
|
||||
- zoom、theme 仍共享文件,启动时读取,运行中不实时同步;
|
||||
- 关闭最后一个窗口不会触发 session 保存。
|
||||
|
||||
## 13. 失败处理
|
||||
|
||||
| 场景 | 行为 |
|
||||
|---|---|
|
||||
| 端口段全被其他程序占用 | 应用可启动但不监听;提示降级 |
|
||||
| 握手 magic/version 不匹配 | 跳过该端口 |
|
||||
| config_id 不匹配 | 跳过,避免测试/生产串线 |
|
||||
| 查询超时 | 视为未找到;继续扫描;最终可能重复打开,需要提示 |
|
||||
| 聚焦失败 | 不重复打开;提示文件已在另一窗口 |
|
||||
| startup.lock 超时 | 提示重试,不绕过 |
|
||||
| 16 窗口上限 | 提示关闭一个窗口;不启动第 17 个 |
|
||||
| 保存失败(detach) | 不启动子进程,保留原标签 |
|
||||
| 子进程 ready 超时 | 保留原标签,清理子进程 |
|
||||
| 子进程启动失败 | 保留原标签,提示 |
|
||||
| recent 写失败 | 不阻止打开;记录错误日志 |
|
||||
| 端口绑定失败 | 该进程不监听;后续打开可能找不到它,提示降级 |
|
||||
| 文件不存在/不支持 | 不转发,直接报错 |
|
||||
| 路径别名 | 统一规范化后再比较;无法归一则可能重复,记录风险 |
|
||||
|
||||
## 14. 代码影响
|
||||
|
||||
### src/instance.rs
|
||||
|
||||
- 移除 acquire/Primary 的单接收者模型,改为:
|
||||
- 端口段选择;
|
||||
- listener 生命周期;
|
||||
- 握手和帧协议;
|
||||
- 扫描与查询;
|
||||
- focus/open/detach-ready 请求。
|
||||
- 保留 Launch 路径数据结构,但扩展协议字段。
|
||||
- 现有 instance 测试需要重写。
|
||||
|
||||
### src/main.rs
|
||||
|
||||
- 启动流程:解析参数、startup.lock、扫描/查询、决定启动或转发;
|
||||
- 移除 session 加载/保存调用;
|
||||
- 增加 recent 锁;
|
||||
- 增加 UserEvent:FocusPath、OpenPaths、DetachReady 等;
|
||||
- 增加标签右键菜单和“在新窗口打开”;
|
||||
- 增加子进程启动和 ready 超时;
|
||||
- 启动监听、端口绑定、实例 ID;
|
||||
- 保留现有 IPC、文件监听、缩放、折叠等功能。
|
||||
|
||||
### src/session.rs
|
||||
|
||||
- 保留 DocumentSession;
|
||||
- 删除 PersistedSession、load、save;
|
||||
- 删除/改写持久化测试;
|
||||
- 保留 normalize_path / strip_verbatim,并补充路径比较辅助。
|
||||
|
||||
### 测试与文档
|
||||
|
||||
- 新增端口扫描、握手、查询、聚焦、16 上限、startup.lock、recent 锁、路径规范化测试;
|
||||
- 更新 STATUS、HANDOFF、roadmap;
|
||||
- 新增本设计文档;
|
||||
- 独立评估报告放 agent/reports/。
|
||||
|
||||
## 15. 测试计划
|
||||
|
||||
### 单元测试
|
||||
|
||||
- 路径规范化:大小写、\\?\、相对路径、符号链接、父目录不存在;
|
||||
- 端口段选择:占用、跳过、满;
|
||||
- 帧编解码:长度、超大帧、截断;
|
||||
- 握手校验:magic/version/config_id/nonce;
|
||||
- recent 读改写与锁;
|
||||
- DocumentSession 无持久化后的标签行为。
|
||||
|
||||
### 集成测试
|
||||
|
||||
- 启动两个实例,扫描并转发;
|
||||
- 查询已打开文件并聚焦;
|
||||
- 两个实例同时打开同一文件,startup.lock 串行化;
|
||||
- 16 上限提示;
|
||||
- 关闭实例后端口释放;
|
||||
- 端口被其他程序占用;
|
||||
- 子进程 ready 成功/超时;
|
||||
- 保存失败中止 detach;
|
||||
- recent 多进程更新不丢。
|
||||
|
||||
### 手工验收
|
||||
|
||||
- 双击 .md 进已有窗口;
|
||||
- 右键标签在新窗口打开,原标签关闭;
|
||||
- 同一文件双击只聚焦,不重复;
|
||||
- 16 个窗口时提示;
|
||||
- 关闭全部后重启只显示 recent,不恢复标签;
|
||||
- 编辑、保存、外部修改、缩放、折叠、打印不回归;
|
||||
- 进程崩溃不残留端口;
|
||||
- 固定 exe、.md 关联、离线行为不变。
|
||||
|
||||
## 16. 实施阶段
|
||||
|
||||
0. 等待独立评估报告,确认端口扫描、聚焦、detach 事务可行。
|
||||
1. 移除 session 恢复,改为 recent-only;更新测试。
|
||||
2. 重写 instance 发现与监听:端口段、握手、扫描、16 上限。
|
||||
3. 接入打开流程:startup.lock、查询、聚焦、重复打开防护。
|
||||
4. 加入标签右键菜单和 detach 事务(ready 握手)。
|
||||
5. 全量测试、手工验收、构建部署;由用户确认后再 git。
|
||||
|
||||
## 17. 待确认/待评估
|
||||
|
||||
- 聚焦在 Windows 上是否可靠;失败提示是否足够。
|
||||
- detach 的 ready 握手是否值得;是否先接受 spawn 成功即关闭。
|
||||
- 64 端口段是否被安全软件干扰;是否需要并行扫描。
|
||||
- 16 上限是否包含空窗口/降级实例。
|
||||
- recent 文件锁的实现方式与跨平台原子替换。
|
||||
- 是否保留旧 session.json 作为用户数据备份。
|
||||
|
||||
## 18. 验收标准
|
||||
|
||||
- 默认双击在已有窗口加标签,不重复开同一文件;
|
||||
- 右键新窗口成功移动标签,失败不丢标签;
|
||||
- 同一文件跨窗口不会同时出现;
|
||||
- 聚焦失败只提示,不重复打开;
|
||||
- 最多 16 个窗口,超出提示;
|
||||
- 重启只显示 recent,不恢复标签;
|
||||
- 多进程 recent 不丢记录;
|
||||
- 无 session.json 读写;
|
||||
- 无新增依赖、无联网、无注册表;
|
||||
- Windows 构建通过,现有 52 个测试及新增测试全绿;
|
||||
- 手工验证缩放、折叠、保存、打印、外部修改不回归。
|
||||
|
||||
## 19. 独立评估结论(2026-10-27)
|
||||
|
||||
评估报告:agent/reports/multi-process-tabs-feasibility.md。该报告只基于方案文本,未读实现、未构建,工作量为粗略估计。
|
||||
|
||||
报告结论:当前“多进程 + 64 端口 + 单阶段 detach”方案 No-go,不建议直接实现。主要理由:
|
||||
|
||||
- 端口扫描/握手可行,但查重必须枚举全部 64 端口,不能只取最低有效响应;本设计确实计划全量查询,最低端口只用于选择目标。
|
||||
- 16 上限存在并发竞态,需要统一准入锁 + 槽位预留/TTL;仅仅“先扫描再启动”不够。
|
||||
- startup.lock 不能覆盖等待子进程完整启动,否则可能死锁;应只覆盖扫描、查重、决策和槽位预留。
|
||||
- detach 需要两阶段:prepared/commit,且需要 Job Object 或等价机制清理子进程树;否则可能丢标签或留孤儿。
|
||||
- 多进程共享 WebView2 User Data Folder 未验证,可能是最大技术风险;可改为每进程独立 UDF。
|
||||
- 路径身份(大小写、UNC、短路径、junction)和 Windows 前台聚焦限制需要明确降级。
|
||||
- 报告推荐单进程多 tao 窗口/多 WebView,估计 5–8 人日;多进程完整方案 15–22 人日,MVP 8–12 人日但不建议上线。
|
||||
|
||||
本设计文档保留为方案 2 的完整讨论稿,不代表已批准实施。若继续方案 2,至少先满足:
|
||||
|
||||
1. 全量 peer 枚举,不提前停止;
|
||||
2. 统一准入锁 + 槽位预留/TTL;
|
||||
3. 两阶段 detach + 子进程树清理;
|
||||
4. 路径身份统一规范化;
|
||||
5. WebView2 共享 UDF 实测,必要时独立 UDF;
|
||||
6. 默认上限降到 8 或给出低配降级策略;
|
||||
7. 聚焦失败文案和降级行为。
|
||||
400
agent/docs/design-single-process-multi-window.md
Normal file
400
agent/docs/design-single-process-multi-window.md
Normal file
@@ -0,0 +1,400 @@
|
||||
# 单进程多窗口方案
|
||||
|
||||
> 状态:设计讨论稿,未写代码。
|
||||
> 日期:2026-10-27
|
||||
> 关联:agent/AGENTS.md、agent/docs/STATUS.md、agent/docs/design-multi-process-tabs.md、agent/reports/multi-process-tabs-feasibility.md
|
||||
|
||||
## 1. 结论摘要
|
||||
|
||||
在一个进程内创建多个 tao Window,每个窗口一个 wry WebView2,每个窗口拥有自己的 DocumentSession。标签右键“在新窗口打开”时,把标签从源窗口移动到新窗口。
|
||||
|
||||
这个方案不需要:
|
||||
|
||||
- 端口扫描;
|
||||
- TCP 握手/查询;
|
||||
- 外部注册文件;
|
||||
- startup.lock;
|
||||
- 多进程 WebView2 User Data Folder;
|
||||
- 跨进程 detach 事务和子进程清理。
|
||||
|
||||
仍然保留:
|
||||
|
||||
- 现有单实例转发(双击 .md 交给已运行进程);
|
||||
- 取消 session 恢复,只保留 recent;
|
||||
- 标签右键菜单;
|
||||
- 不做拖出、不做拖回、不做窗口合并;
|
||||
- 最多窗口数限制(可选,建议保留 16)。
|
||||
|
||||
## 2. 为什么先评估这个方案
|
||||
|
||||
多进程方案的主要复杂度不在“打开新窗口”,而在:
|
||||
|
||||
- 进程发现;
|
||||
- 跨进程查重和聚焦;
|
||||
- 16 上限的并发准入;
|
||||
- detach 的 ready/commit 和孤儿进程;
|
||||
- WebView2 共享数据目录;
|
||||
- 路径身份和配置并发写。
|
||||
|
||||
单进程多窗口把这些都收敛到一个事件循环里:
|
||||
|
||||
- 窗口列表就是一个 Vec/HashMap;
|
||||
- 是否已打开文件,直接遍历所有窗口的 session;
|
||||
- 聚焦就是 set_focus + activate tab;
|
||||
- 窗口数量精确可数;
|
||||
- 不需要跨进程协议;
|
||||
- 不需要多进程 UDF;
|
||||
- detach 是内存中的标签移动,不需要 ready 握手。
|
||||
|
||||
代价是 main.rs 的单窗口假设需要重构,但这是“集中式重构”,不是“分布式边界情况”。
|
||||
|
||||
## 3. 目标与非目标
|
||||
|
||||
### 目标
|
||||
|
||||
1. 右键标签 → 在新窗口打开;标签从源窗口移动到新窗口。
|
||||
2. 默认双击仍由现有单实例转发交给已运行进程,在活动窗口加标签。
|
||||
3. 同一文件在任意窗口只开一次;已打开则聚焦已有窗口和标签。
|
||||
4. 关闭一个窗口只影响该窗口;非最后窗口关闭最后一个标签时关闭该窗口;最后一个窗口关闭最后一个标签时保留空窗口;关闭最后一个窗口时退出进程。
|
||||
5. 取消 session 恢复,只保留 recent;重启不恢复标签。
|
||||
6. 保留现有缩放、折叠、打印、保存失败、外部修改提示。
|
||||
7. 不新增依赖,不联网,不使用注册表。
|
||||
|
||||
### 非目标
|
||||
|
||||
- 不做拖出/拖回/窗口合并。
|
||||
- 不做窗口位置恢复或级联布局;新窗口使用简单偏移。
|
||||
- 不做跨进程隔离;单进程崩溃会影响所有窗口。
|
||||
- 不做跨窗口标签拖拽;只做右键移动。
|
||||
- 不恢复 active tab、滚动位置、编辑状态。
|
||||
|
||||
## 4. 总体架构
|
||||
|
||||
### 4.1 AppState
|
||||
|
||||
事件循环持有一个 AppState:
|
||||
|
||||
struct AppState {
|
||||
windows: HashMap<WindowId, WindowState>,
|
||||
window_order: Vec<WindowId>,
|
||||
active_window: Option<WindowId>,
|
||||
web_context: WebContext,
|
||||
recent_files: Arc<Mutex<Vec<PathBuf>>>,
|
||||
strings: Strings,
|
||||
proxy: EventLoopProxy<UserEvent>,
|
||||
// 现有全局状态:bench、hljs_bootstrap 等
|
||||
}
|
||||
|
||||
### 4.2 WindowState
|
||||
|
||||
每个窗口一个 WindowState:
|
||||
|
||||
struct WindowState {
|
||||
window: Window,
|
||||
webview: WebView,
|
||||
session: Arc<Mutex<DocumentSession>>,
|
||||
last_self_write: Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||
watcher: Option<RecommendedWatcher>,
|
||||
page_ready: bool,
|
||||
loaded_enhancers: EnhanceFlags,
|
||||
pending_close: bool,
|
||||
warned_external_change: Option<PathBuf>,
|
||||
pending_external_change: Option<PathBuf>,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
现有 main() 里的局部变量(loaded_enhancers、page_ready、pending_window_close、warned_external_change 等)要搬进 WindowState。
|
||||
|
||||
### 4.3 WebContext
|
||||
|
||||
- 一个进程只创建一个 WebContext,复用现有 config_dir()/WebView2 数据目录;
|
||||
- wry 的 WebContext 明确支持多个 WebView 共享;
|
||||
- AppState 持有 WebContext,确保 WebView 存活期间 context 不 drop;
|
||||
- 每次创建窗口时用 WebViewBuilder::with_web_context(&mut app.web_context) 构建新的 WebView;
|
||||
- 不需要为每个窗口单独建 WebView2 Environment,也不需要多进程 UDF 验证。
|
||||
|
||||
### 4.4 窗口创建
|
||||
|
||||
事件循环的 run 闭包第二个参数就是 EventLoopWindowTarget:
|
||||
|
||||
event_loop.run(move |event, target, control_flow| { ... })
|
||||
|
||||
创建新窗口时:
|
||||
|
||||
1. WindowBuilder::new().build(target);
|
||||
2. 用共享 WebContext 构建 WebView;
|
||||
3. 生成新的 WindowId(由 tao 返回);
|
||||
4. 初始化 WindowState 并插入 AppState;
|
||||
5. 加载 startup page,等待该窗口的 Ready 事件;
|
||||
6. 把目标标签/文件渲染进去。
|
||||
|
||||
tao 0.33 的 WindowBuilder::build 接受 &EventLoopWindowTarget,支持运行中建窗口。
|
||||
|
||||
## 5. 事件与 IPC 路由
|
||||
|
||||
### 5.1 UserEvent 带窗口身份
|
||||
|
||||
现有 UserEvent 多数需要加 WindowId 或“目标窗口”:
|
||||
|
||||
- OpenPaths(Option<WindowId>, Vec<PathBuf>, bool)
|
||||
- NewFile(WindowId)
|
||||
- OpenFile(WindowId)
|
||||
- ActivateTab(WindowId, u64)
|
||||
- CloseTab(WindowId, u64)
|
||||
- CloseActiveTab(WindowId)
|
||||
- LocateTab(WindowId, u64)
|
||||
- FileChanged(WindowId, PathBuf) 或按 path 查找窗口
|
||||
- FileSaved(WindowId, PathBuf)
|
||||
- SaveFailed(WindowId, PathBuf, String)
|
||||
- DirtyChanged(WindowId, bool)
|
||||
- ToggleEdit(WindowId)
|
||||
- ShowFind(WindowId)
|
||||
- Print(WindowId)
|
||||
- RecentChanged (广播所有窗口)
|
||||
- Ready(WindowId)
|
||||
- DetachTab(WindowId, u64)
|
||||
- NewWindow(DocumentSession/PathBuf)
|
||||
- SetTheme(ThemeChoice) 广播
|
||||
- Quit 全局
|
||||
|
||||
对于按路径的事件(FileChanged/FileSaved/SaveFailed),也可以遍历窗口找到包含该路径的 session,不需要窗口 ID;但显式带 ID 更简单,文件监听器在创建时就知道窗口。
|
||||
|
||||
### 5.2 IPC handler
|
||||
|
||||
每个 WebView 的 IPC handler 捕获:
|
||||
|
||||
- window_id;
|
||||
- 该窗口的 session Arc;
|
||||
- 该窗口的 last_self_write Arc;
|
||||
- recent_files Arc;
|
||||
- proxy。
|
||||
|
||||
消息格式仍沿用现有字符串协议;tab-action、save、zoom、print、ready 等按窗口路由。窗口销毁后迟到的消息应安全忽略。
|
||||
|
||||
### 5.3 活动窗口
|
||||
|
||||
- WindowEvent::Focused(true) 更新 active_window;
|
||||
- 新窗口创建后设为 active;
|
||||
- 默认 OpenPaths(来自实例转发或命令行)优先使用 active_window;
|
||||
- 如果没有窗口,创建第一个窗口;
|
||||
- 关闭 active 窗口后,选择相邻/最近窗口。
|
||||
|
||||
## 6. 打开文件与去重
|
||||
|
||||
### 6.1 默认双击
|
||||
|
||||
1. 现有 instance::acquire 仍然只允许一个进程;新进程把路径转发给已运行进程,自己退出。
|
||||
2. 已运行进程收到 OpenPaths:
|
||||
- 在所有窗口的 session 中查找规范化路径;
|
||||
- 已打开:聚焦该窗口,激活对应标签;
|
||||
- 未打开:在 active_window 新增标签;没有窗口则创建。
|
||||
3. 更新 recent。
|
||||
4. 不再有端口扫描、startup.lock、16 准入跨进程锁。
|
||||
|
||||
### 6.2 Open 对话框 / recent / 拖入 / 本地链接
|
||||
|
||||
统一走同一个 open_paths 函数:
|
||||
|
||||
- 先遍历所有窗口查重;
|
||||
- 已打开则聚焦;
|
||||
- 未打开则加入当前窗口;
|
||||
- 多文件逐个处理。
|
||||
|
||||
### 6.3 路径规范化
|
||||
|
||||
本机文件、单进程,规范化可以适度:
|
||||
|
||||
- 转绝对路径;
|
||||
- 去掉 Windows \\?\ 前缀;
|
||||
- 对存在文件做 canonicalize(会解析 junction/symlink,返回实际大小写);
|
||||
- 对不存在文件规范化父目录;
|
||||
- Windows 比较时忽略大小写;
|
||||
- recent 读写也使用同样的规范化结果。
|
||||
|
||||
不需要句柄级文件 ID。正常使用下,路径别名主要来自大小写、相对路径、junction/符号链接;canonicalize + 大小写折叠足够覆盖大多数情况。低概率的 UNC/映射盘别名可以接受,不做额外复杂处理。
|
||||
|
||||
### 6.4 同一文件多开标签
|
||||
|
||||
现状:DocumentSession::open 按路径去重,同一文件在单个窗口内只开一个标签。
|
||||
|
||||
评估结论:**第一版保持全局单开,不允许同一文件在多个标签/多个窗口同时编辑。**
|
||||
|
||||
原因:
|
||||
|
||||
- 同一窗口内多开也只是同一个编辑器的不同标签,切换时仍要保存/重读磁盘,价值低;
|
||||
- 不同窗口可以同时编辑同一文件,没有文档同步;
|
||||
- 自动保存是 700ms 防抖 + 直接写盘,两个窗口会互相覆盖,最后写入者赢;
|
||||
- 外部修改 watcher 按窗口存在,可能出现“自己的保存触发另一个窗口的外部修改提示”;
|
||||
- 看错/覆盖风险高于多标签带来的便利。
|
||||
|
||||
如果以后确实需要,建议只支持“只读副本”或“同窗口多标签但只有一个可编辑”,不要直接支持两个可编辑窗口。
|
||||
|
||||
## 7. 标签右键“在新窗口打开”
|
||||
|
||||
### 7.1 UI
|
||||
|
||||
- 只对标签页放开右键;其他区域继续禁用;
|
||||
- 自定义 HTML 菜单,一项“在新窗口打开”;
|
||||
- 点击外部/Esc 关闭,位置不超出窗口;
|
||||
- 不引入原生菜单。
|
||||
|
||||
### 7.2 流程
|
||||
|
||||
1. 右键标签,发 detach:
|
||||
- 如果该标签是当前活动标签且 dirty,带上编辑器内容;
|
||||
- 否则只带 tab id。
|
||||
2. Rust 侧:
|
||||
- 如果带内容,先同步写盘;失败则中止,保留标签;
|
||||
- 从源 session 取出该 tab(先不销毁);
|
||||
- 创建新窗口和新 WebView;
|
||||
- 新窗口 session 只包含这个 tab;
|
||||
- 新窗口 Ready 后渲染该 tab;
|
||||
- 成功后从源 session 移除该 tab;
|
||||
- 如果源窗口没有标签,关闭源窗口。
|
||||
3. 失败时:
|
||||
- 新窗口构建失败:保留源标签,不移动;
|
||||
- 写入失败:保留标签并提示;
|
||||
- 新窗口 Ready 前失败:销毁新窗口,保留源标签。
|
||||
|
||||
因为在同一进程内,窗口创建是同步的;不需要 ready 跨进程握手,但 WebView Ready 仍是异步的。可以在插入新窗口时就放入 tab,Ready 后渲染,不需要“prepared/commit”协议。
|
||||
|
||||
### 7.3 源窗口没有标签时
|
||||
|
||||
已确认:**关闭源窗口**。
|
||||
|
||||
- 新窗口创建成功、目标标签移动完成后,如果源窗口没有标签,关闭源窗口;
|
||||
- 如果源窗口不是最后一个窗口,应用继续运行;
|
||||
- 如果这是最后一步操作,新窗口已经存在,不会退出应用;
|
||||
- 失败时保留源窗口和标签。
|
||||
|
||||
## 8. 窗口关闭与生命周期
|
||||
|
||||
- CloseRequested 按 window_id 处理;
|
||||
- 如果该窗口有 dirty 标签,先保存;失败时用现有 Ok/Cancel 丢弃逻辑;
|
||||
- 保存成功/确认丢弃后销毁该窗口;
|
||||
- 关闭窗口的最后一个标签:如果还有别的窗口,关闭该窗口;如果这是最后一个窗口,保留空窗口,不退出进程;
|
||||
- 从 windows/order 中移除;
|
||||
- 如果还有窗口,选择下一个 active;如果没有,ControlFlow::Exit;
|
||||
- WindowEvent::Destroyed 作为兜底清理;
|
||||
- Quit/Cmd+Q 仅 macOS 分支;Windows 版没有 Cmd+Q。Quit 按全局退出处理,关闭所有窗口。
|
||||
|
||||
## 9. 最近文件
|
||||
|
||||
- 取消 session.json 读写;
|
||||
- 启动不恢复标签;
|
||||
- recent-files.txt 仍是唯一持久化;
|
||||
- 单进程内更新 recent 不需要跨进程锁;
|
||||
- 仍要保证原子写/去重/过滤不存在文件;
|
||||
- 启动无文件时用 recent 显示空状态;
|
||||
- 新窗口继承 recent 列表,但不清空其他窗口的标签。
|
||||
|
||||
## 10. 需要改动的代码区域
|
||||
|
||||
### src/main.rs
|
||||
|
||||
- 把 main() 里的单窗口局部状态搬入 AppState/WindowState;
|
||||
- 提取 create_window(target, session, ...);
|
||||
- 事件循环按 window_id 路由;
|
||||
- UserEvent 加 window id;
|
||||
- IPC handler 捕获 window_id 和 per-window Arcs;
|
||||
- 添加 DetachTab / NewWindow;
|
||||
- 添加标签右键菜单;
|
||||
- 移除 session load/save;
|
||||
- 保留 instance::acquire 单实例转发;
|
||||
- 关闭/退出逻辑改为按窗口;
|
||||
- recent 更新保持单进程;
|
||||
- window.geom 简化为初始窗口位置,新窗口偏移,不做每窗口恢复。
|
||||
|
||||
### src/session.rs
|
||||
|
||||
- 保留 DocumentSession 的标签模型;
|
||||
- 删除 PersistedSession、load、save;
|
||||
- 删除持久化测试;
|
||||
- 保留 normalize_path / strip_verbatim;
|
||||
- 可增加 path 比较辅助。
|
||||
|
||||
### src/instance.rs
|
||||
|
||||
- 基本不变;仍负责单实例转发;
|
||||
- 转发目标由事件循环的 active_window 决定;
|
||||
- 不需要端口扫描/注册表。
|
||||
|
||||
### WebView/页面
|
||||
|
||||
- 页面本身不需要知道多窗口;
|
||||
- 每个 WebView 独立加载同一 build_page 模板;
|
||||
- 标签栏只显示当前窗口的 session;
|
||||
- 现有折叠、查找、缩放、保存逻辑按窗口独立。
|
||||
|
||||
## 11. 工作量估算
|
||||
|
||||
粗略拆分(按当前 main.rs 的耦合程度):
|
||||
|
||||
| 工作 | 估算 |
|
||||
|---|---|
|
||||
| AppState/WindowState 重构,局部状态迁移 | 2–3 天 |
|
||||
| 运行中创建 Window/WebView、共享 WebContext、Ready | 1–2 天 |
|
||||
| UserEvent/IPC 按窗口路由 | 2–3 天 |
|
||||
| 每窗口 session/关闭/dirty/watcher/标题/标签栏 | 2–3 天 |
|
||||
| 右键菜单 + detach 移动 + 跨窗口查重/聚焦 | 1–2 天 |
|
||||
| 移除 session 恢复、recent-only、路径规范化 | 0.5–1 天 |
|
||||
| 测试、手工回归、窗口生命周期边界 | 2–3 天 |
|
||||
| 合计 | 约 9–15 人日 |
|
||||
|
||||
独立报告估计单进程多窗口 5–8 人日,但它没有读实现;按当前 main.rs 单文件、单窗口闭包的耦合程度,我认为 9–15 更现实。仍低于多进程完整方案的 15–22 人日。
|
||||
|
||||
主要风险不是窗口 API,而是:
|
||||
|
||||
- main.rs 事件循环闭包捕获大量局部状态,迁移面大;
|
||||
- 每个事件处理函数都要从“全局 window/webview”改成“按 window_id 查找”;
|
||||
- 关闭/保存/文件监听的边界比新增窗口本身更耗时。
|
||||
|
||||
## 12. 测试计划
|
||||
|
||||
- 启动一个窗口,打开多个标签;
|
||||
- 右键标签 → 新窗口,标签移动,源标签关闭;
|
||||
- 源窗口最后一个标签移出后,源窗口关闭;
|
||||
- 两个窗口打开同一文件,第二次只聚焦;
|
||||
- 关闭其中一个窗口,其他窗口继续工作;
|
||||
- 非最后窗口关闭最后一个标签会关闭该窗口;
|
||||
- 最后窗口关闭最后一个标签时保留空窗口;
|
||||
- 关闭最后一个窗口,进程退出;
|
||||
- dirty 标签 detach,保存成功/失败;
|
||||
- 新窗口创建失败(模拟)保留源标签;
|
||||
- 双击 .md 仍进已有进程的活动窗口;
|
||||
- recent 更新/去重/过滤;
|
||||
- 缩放、折叠、查找、打印、外部修改提示不回归;
|
||||
- 窗口关闭时保存失败/只读文件;
|
||||
- 多窗口同时编辑不同文件;
|
||||
- 路径大小写/相对路径/junction 去重;
|
||||
- 多窗口内存/句柄基本检查。
|
||||
|
||||
## 13. 与多进程方案的对比要点
|
||||
|
||||
优势:
|
||||
|
||||
- 无端口/注册表/跨进程协议;
|
||||
- 查重、聚焦、窗口计数都是进程内;
|
||||
- 无 WebView2 多进程 UDF 风险;
|
||||
- 无 startup.lock/detach 事务/孤儿进程;
|
||||
- 仍保留现有单实例转发和固定 exe 关联。
|
||||
|
||||
代价:
|
||||
|
||||
- main.rs 大重构;
|
||||
- 单进程崩溃影响所有窗口;
|
||||
- 多个 WebView 共享一个进程,内存/句柄仍需观察;
|
||||
- 窗口位置/生命周期语义要重新定义。
|
||||
|
||||
## 14. 验收标准
|
||||
|
||||
- 右键标签在新窗口打开,原标签移除;失败保留;
|
||||
- 源窗口最后一个标签移出后关闭源窗口;
|
||||
- 同一文件不会在两个窗口同时打开;已打开则聚焦;
|
||||
- 默认双击仍进已有进程;
|
||||
- 重启不恢复标签,只显示 recent;
|
||||
- 关闭非最后窗口的最后一个标签会关闭该窗口;最后窗口的最后一个标签关闭后保留空窗口;关闭最后窗口才退出;
|
||||
- dirty/只读/保存失败行为不回退;
|
||||
- 缩放、折叠、查找、打印、外部修改不回归;
|
||||
- 无端口扫描、无外部注册文件、无新增依赖;
|
||||
- cargo test 全绿,手工验收通过。
|
||||
202
agent/docs/design-window-options-comparison.md
Normal file
202
agent/docs/design-window-options-comparison.md
Normal file
@@ -0,0 +1,202 @@
|
||||
# 多窗口实现方案对比(单进程 vs 多进程)
|
||||
|
||||
> 状态:设计讨论稿,未写代码。
|
||||
> 日期:2026-10-27
|
||||
> 关联:
|
||||
> - agent/docs/design-single-process-multi-window.md
|
||||
> - agent/docs/design-multi-process-tabs.md
|
||||
> - agent/reports/multi-process-tabs-feasibility.md
|
||||
|
||||
## 1. 对比结论
|
||||
|
||||
按“功能满足 + 总工作量 + 风险”综合,推荐:
|
||||
|
||||
**单进程多窗口**。
|
||||
|
||||
理由:
|
||||
|
||||
- 功能上仍然是一个进程、多个窗口;默认双击仍交给已有进程;不需要端口、注册表、跨进程协议;
|
||||
- 同一文件查重、聚焦、窗口计数、标签移动都在进程内完成,边界情况少;
|
||||
- 没有多进程 WebView2 User Data Folder 风险;
|
||||
- 没有 startup.lock、detach ready/commit、孤儿进程、16 准入竞态;
|
||||
- 代价是 main.rs 单窗口假设需要重构,但这是集中式重构。
|
||||
|
||||
多进程方案(TCP 扫描或外部注册文件)只有在“进程隔离/崩溃隔离”是硬需求时才值得做;外部注册文件不是捷径,它只是替换发现方式,其他多进程复杂度仍然存在。
|
||||
|
||||
## 2. 三个方案
|
||||
|
||||
### 方案 A:单进程多窗口
|
||||
|
||||
- 一个进程,多个 tao Window;
|
||||
- 每个窗口一个 wry WebView2,共享一个 WebContext;
|
||||
- 每个窗口一个 DocumentSession;
|
||||
- 标签右键“在新窗口打开” = 内存中移动 tab;
|
||||
- 单实例转发不变;
|
||||
- 无端口、无注册表、无 startup.lock。
|
||||
|
||||
设计文档:agent/docs/design-single-process-multi-window.md
|
||||
|
||||
### 方案 B:多进程 + TCP 端口扫描
|
||||
|
||||
- 每个窗口一个进程;
|
||||
- 64 个候选端口,最多 16 个监听实例;
|
||||
- 握手 magic/version/config_id/nonce/instance_id;
|
||||
- 查询 peer 是否已打开文件,已打开则聚焦;
|
||||
- startup.lock 串行化扫描/查重/启动;
|
||||
- detach 需要子进程 ready 回执和清理;
|
||||
- 共享 WebView2 UDF 需要实测或每进程独立 UDF。
|
||||
|
||||
设计文档:agent/docs/design-multi-process-tabs.md
|
||||
独立评估:agent/reports/multi-process-tabs-feasibility.md(No-go,建议单进程多窗口)
|
||||
|
||||
### 方案 C:多进程 + 外部注册文件
|
||||
|
||||
- 每个进程在 config_dir()/instances/ 写一个 JSON:pid、instance_id、port、token、started_at;
|
||||
- 新进程扫描该目录,清理死条目,选择/查询已有进程;
|
||||
- 仍然每进程监听一个端口(或命名管道)做实际请求;
|
||||
- 不需要扫 64 个端口,但需要文件锁、原子写、死条目清理、PID/端口复用处理;
|
||||
- 其他多进程问题(WebView2 UDF、detach、查重、聚焦、16 准入、路径一致性)全部保留。
|
||||
|
||||
设计文档:尚未单独写;可作为方案 B 的发现层替代。
|
||||
|
||||
## 3. 详细对比
|
||||
|
||||
| 维度 | 方案 A:单进程多窗口 | 方案 B:多进程 TCP | 方案 C:多进程注册表 |
|
||||
|---|---|---|---|
|
||||
| 进程数 | 1 | N | N |
|
||||
| 窗口数 | N | N | N |
|
||||
| 发现方式 | 不需要 | 64 端口扫描 + 握手 | instances/*.json + 端口/管道 |
|
||||
| 默认双击 | 现有单实例转发到活动窗口 | 扫描并转发/加到已有 | 读注册表并转发/加到已有 |
|
||||
| 同一文件查重 | 遍历本进程所有窗口 | 查询所有 peer | 查询所有 peer |
|
||||
| 聚焦 | set_focus,同进程 | 跨进程,受前台锁限制 | 跨进程,同 B |
|
||||
| 窗口上限 | 精确计数 | 需要准入锁 + 槽位 | 需要文件锁 + 槽位 |
|
||||
| 标签移动 | 内存移动,简单 | 需要 ready/commit、子进程清理 | 同 B |
|
||||
| WebView2 UDF | 一个进程一个 context,风险低 | 多进程共享或每进程独立,需验证 | 同 B |
|
||||
| session | 每窗口内存,无恢复 | 每进程内存,无恢复 | 每进程内存,无恢复 |
|
||||
| recent | 单进程内更新,无需跨进程锁 | 需要文件锁 | 需要文件锁 |
|
||||
| 崩溃影响 | 所有窗口 | 单窗口 | 单窗口 |
|
||||
| main.rs 重构 | 大 | 中 | 中 |
|
||||
| 新增文件 | 无 | 无 | instances/*.json |
|
||||
| 新增协议 | 无 | 握手/查询/聚焦/open | 文件格式 + 端口/管道协议 |
|
||||
| 新增依赖 | 无 | 无 | 无 |
|
||||
| 主要风险 | 事件循环/状态重构 | 分布式竞态、UDF、detach | 文件竞态 + 分布式竞态 |
|
||||
| 估算工作量 | 约 9–15 人日 | 约 15–22 人日 | 约 14–20 人日 |
|
||||
|
||||
## 4. 工作量估算依据
|
||||
|
||||
### 方案 A:单进程多窗口
|
||||
|
||||
| 工作 | 估算 |
|
||||
|---|---|
|
||||
| AppState/WindowState 重构,局部状态迁移 | 2–3 天 |
|
||||
| 运行中创建 Window/WebView、共享 WebContext、Ready | 1–2 天 |
|
||||
| UserEvent/IPC 按窗口路由 | 2–3 天 |
|
||||
| 每窗口 session/关闭/dirty/watcher/标题/标签栏 | 2–3 天 |
|
||||
| 右键菜单 + detach 移动 + 跨窗口查重/聚焦 | 1–2 天 |
|
||||
| 移除 session 恢复、recent-only、路径规范化 | 0.5–1 天 |
|
||||
| 测试、手工回归、窗口生命周期边界 | 2–3 天 |
|
||||
| 合计 | 约 9–15 人日 |
|
||||
|
||||
独立报告估计 5–8 人日,但它没有读实现;按当前 main.rs 单文件、单窗口闭包的耦合程度,9–15 更现实。
|
||||
|
||||
### 方案 B:多进程 TCP
|
||||
|
||||
独立报告估算:
|
||||
|
||||
- 完整方案 15–22 人日;
|
||||
- 只做 happy path 的 MVP 8–12 人日,但不建议上线。
|
||||
|
||||
主要成本:
|
||||
|
||||
- 实例发现、握手、查询、聚焦;
|
||||
- startup.lock + 16 准入/槽位;
|
||||
- detach 两阶段 + 子进程清理;
|
||||
- WebView2 UDF 验证;
|
||||
- 路径规范化、recent 锁、并发测试。
|
||||
|
||||
### 方案 C:多进程注册表
|
||||
|
||||
估算 14–20 人日:
|
||||
|
||||
- 比 TCP 少了端口扫描,但多了文件锁、原子写、死条目清理、PID/端口复用;
|
||||
- WebView2 UDF、detach、查重、聚焦、16 准入仍然要做;
|
||||
- 发现层不是主要成本,所以不会显著比 TCP 简单。
|
||||
|
||||
## 5. 路径规范化
|
||||
|
||||
用户问:都是本机提供的路径,不一致概率大吗?
|
||||
|
||||
结论:**正常使用概率不大,但值得做适度规范化,不需要过度设计。**
|
||||
|
||||
主要来源:
|
||||
|
||||
- Windows 大小写不敏感,命令行/最近文件/对话框可能大小写不同;
|
||||
- 相对路径 vs 绝对路径;
|
||||
- \\?\ 前缀;
|
||||
- junction / symlink;
|
||||
- 短路径(8.3);
|
||||
- UNC vs 映射盘;
|
||||
- 尾随空格/点。
|
||||
|
||||
单进程多窗口下:
|
||||
|
||||
- 所有路径都来自同一个进程,规范化只需要:
|
||||
- 转绝对路径;
|
||||
- 去 \\?\;
|
||||
- 存在文件 canonicalize;
|
||||
- 不存在文件规范化父目录;
|
||||
- Windows 比较忽略大小写;
|
||||
- 不需要文件句柄级 ID;
|
||||
- 成本约 0.5 天。
|
||||
|
||||
多进程方案下还需要保证协议、recent、标签身份使用同一规范路径,成本约 1 天,但不是主要工作量。
|
||||
|
||||
## 6. 16 上限与聚焦
|
||||
|
||||
用户说这两点不是重点,对比时也不作为决定性因素:
|
||||
|
||||
- 单进程:窗口数精确可数,16 上限就是一个 if;
|
||||
- 多进程:需要准入锁/槽位,竞态更复杂;
|
||||
- 单进程:聚焦同进程,基本可靠;
|
||||
- 多进程:受 Windows 前台锁限制,只能 best-effort。
|
||||
|
||||
所以这两点反而支持单进程方案。
|
||||
|
||||
## 7. 方案 C 是否值得
|
||||
|
||||
外部注册文件的优点:
|
||||
|
||||
- 发现确定,不用扫端口;
|
||||
- 可以看到 pid/started_at;
|
||||
- 跨平台文件系统可用。
|
||||
|
||||
缺点:
|
||||
|
||||
- 需要文件锁、原子写、死条目清理;
|
||||
- 需要处理 PID 复用、端口复用、进程崩溃残留;
|
||||
- 仍然要每进程监听端口/管道;
|
||||
- 仍然要 WebView2 UDF、detach、查重、聚焦、16 准入;
|
||||
- 没有消除多进程的分布式复杂度,只是换了一种发现方式。
|
||||
|
||||
结论:**方案 C 不比 B 简单,不作为首选;如果 B 的端口扫描被安全软件/端口冲突证明不可行,再考虑 C。**
|
||||
|
||||
## 8. 推荐路径
|
||||
|
||||
1. 选方案 A(单进程多窗口),先做设计确认。
|
||||
2. 分阶段实施:
|
||||
- 阶段 1:AppState/WindowState 重构,仍只开一个窗口,行为不变;
|
||||
- 阶段 2:支持创建第二个空窗口;
|
||||
- 阶段 3:每窗口 session/IPC/事件路由;
|
||||
- 阶段 4:右键 detach + 跨窗口查重/聚焦;
|
||||
- 阶段 5:移除 session 恢复、recent-only;
|
||||
- 阶段 6:回归测试、构建、手工验收。
|
||||
3. 不在第一阶段引入多进程/端口/注册表。
|
||||
4. 如果以后“崩溃隔离”成为硬需求,再评估 B/C;届时 A 的窗口模型和 UI 可以复用。
|
||||
|
||||
## 9. 仍需确认
|
||||
|
||||
1. 接受单进程多窗口作为主方案吗?
|
||||
2. 源窗口最后一个标签移出后,保留空窗口还是自动关闭?建议保留。
|
||||
3. 关闭最后一个窗口才退出进程,可以吗?
|
||||
4. 新窗口位置使用简单偏移(例如 +28,+28),不恢复每窗口位置,可以吗?
|
||||
5. 标签移动是否采用“移动语义”(原标签关闭),不做复制?
|
||||
493
agent/docs/implementation-plan-single-process-multi-window.md
Normal file
493
agent/docs/implementation-plan-single-process-multi-window.md
Normal file
@@ -0,0 +1,493 @@
|
||||
# 单进程多窗口主实施报告
|
||||
|
||||
> 状态:施工计划,未写代码。
|
||||
> 日期:2026-10-27
|
||||
> 主方案:单进程多窗口
|
||||
> 关联:
|
||||
> - agent/docs/design-single-process-multi-window.md
|
||||
> - agent/docs/design-window-options-comparison.md
|
||||
> - agent/docs/design-multi-process-tabs.md(已降级为历史备选)
|
||||
> - agent/reports/multi-process-tabs-feasibility.md
|
||||
|
||||
## 1. 报告目的
|
||||
|
||||
这份报告不是架构草案,而是准备进入施工前的“施工图”:
|
||||
|
||||
- 固定已确认的产品决策;
|
||||
- 清理多进程阶段留下的决策残留;
|
||||
- 给出 file-by-file 改造顺序;
|
||||
- 列出 UserEvent/IPC 的窗口路由变化;
|
||||
- 给出用户可感知的功能影响清单;
|
||||
- 给出测试、验收、风险和回滚边界。
|
||||
|
||||
## 2. 已确认决策
|
||||
|
||||
1. 主方案:单进程,多 tao Window,每窗口一个 WebView2。
|
||||
2. 标签右键“在新窗口打开”,移动语义:新窗口成功打开后关闭原标签。
|
||||
3. 源窗口最后一个标签移出后,关闭源窗口。
|
||||
4. 新窗口位置使用简单偏移,不恢复每个窗口的位置。
|
||||
5. 取消启动时恢复标签;只保留 recent;不记录 active tab。
|
||||
6. 默认双击仍由现有单实例转发交给已运行进程。
|
||||
7. 不做拖出/拖回/窗口合并。
|
||||
8. 不新增依赖,不联网,不使用注册表/端口扫描。
|
||||
9. 同一文件默认全局只开一个标签/窗口;详见第 6 节。
|
||||
10. 最多窗口数建议保留 16;单进程下只是一个计数判断。
|
||||
11. 普通关闭标签时:非最后窗口关闭最后一个标签会关闭该窗口;最后一个窗口关闭最后一个标签时保留空窗口;关闭最后一个窗口才退出。
|
||||
12. Cmd+Q 只属于 macOS 分支,Windows 版没有 Cmd+Q;Quit 事件按全局退出处理。
|
||||
|
||||
## 3. 多进程决策残留清理
|
||||
|
||||
必须明确哪些旧决定继续有效,哪些废弃,避免施工时把多进程逻辑带进来。
|
||||
|
||||
| 旧决定 | 在新方案中的处理 |
|
||||
|---|---|
|
||||
| 所有进程平等,无主/子 | 不再需要“进程角色”;单进程内多窗口 |
|
||||
| 64 个候选端口 | 删除;不使用端口 |
|
||||
| 最多 16 个监听实例 | 改为最多 16 个窗口,事件循环内计数 |
|
||||
| TCP 握手 magic/version/config_id/nonce/instance_id | 删除 |
|
||||
| 扫描所有 peer、查询是否已打开文件 | 改为遍历本进程所有窗口的 session |
|
||||
| 跨进程聚焦 best-effort | 改为同进程 set_focus,基本可靠 |
|
||||
| startup.lock 串行化扫描/查重/启动 | 删除;单进程事件循环天然串行 |
|
||||
| 16 上限准入锁 + 槽位租约 | 删除;窗口计数在 AppState 内 |
|
||||
| 子进程 ready/detach 两阶段 | 删除;改为进程内新窗口 + Ready 事件 |
|
||||
| Job Object/子进程树清理 | 删除 |
|
||||
| 多进程 WebView2 UDF 实测 | 删除;一个进程一个 WebContext |
|
||||
| recent 跨进程文件锁 | 删除;单进程内更新,保留原子写 |
|
||||
| 外部注册文件 instances/*.json | 不做 |
|
||||
| --new-window / --detached-child 进程参数 | 不需要;新窗口由事件循环创建 |
|
||||
| session owner / 临时会话 | 删除;每窗口一个内存 DocumentSession |
|
||||
| 无 session 恢复,只保留 recent | 保留 |
|
||||
| 标签右键新窗口、移动语义、不做拖回 | 保留 |
|
||||
| 新窗口位置简单偏移 | 保留 |
|
||||
| 路径规范化 | 保留适度版本 |
|
||||
| 单实例锁 + instance.json + TCP 转发 | 保留,基本不动 |
|
||||
| 固定 exe / .md 关联 / 离线 / 无新依赖 | 保留 |
|
||||
|
||||
### 3.1 容易残留的旧假设
|
||||
|
||||
施工时要特别检查:
|
||||
|
||||
- 不能再有“全局 session”的假设;每个窗口各有 session。
|
||||
- 不能再有“全局 active tab”的假设;active 是每窗口的。
|
||||
- 不能再有“APP_DIRTY 一个全局布尔”的假设;dirty 按窗口/标签。
|
||||
- 不能再有“一个 window/webview”变量被所有事件处理函数共享。
|
||||
- 不能再有“关闭窗口 = 退出应用”的假设;只有最后一个窗口退出。
|
||||
- 不能再有“session.json 恢复标签”的假设;启动时只读 recent。
|
||||
- 不能再有“所有打开入口都进同一个窗口”的假设;要按目标窗口路由。
|
||||
- 不能再有“新窗口 = 新进程”的假设;新窗口是同一进程内创建。
|
||||
- 不能再有“窗口位置只有一个”的假设;但也不做每个窗口位置恢复。
|
||||
|
||||
## 4. 目标数据模型
|
||||
|
||||
### 4.1 AppState
|
||||
|
||||
事件循环持有:
|
||||
|
||||
AppState {
|
||||
windows: HashMap<WindowId, WindowState>,
|
||||
window_order: Vec<WindowId>,
|
||||
active_window: Option<WindowId>,
|
||||
web_context: WebContext,
|
||||
recent_files: Arc<Mutex<Vec<PathBuf>>>,
|
||||
strings: Strings,
|
||||
proxy: EventLoopProxy<UserEvent>,
|
||||
pending_detach: HashMap<WindowId, PendingDetach>,
|
||||
}
|
||||
|
||||
### 4.2 WindowState
|
||||
|
||||
每个窗口持有:
|
||||
|
||||
WindowState {
|
||||
window: Window,
|
||||
webview: WebView,
|
||||
session: Arc<Mutex<DocumentSession>>,
|
||||
last_self_write: Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||
watcher: Option<RecommendedWatcher>,
|
||||
enhance_flags: Arc<Mutex<EnhanceFlags>>,
|
||||
loaded_enhancers: EnhanceFlags,
|
||||
page_ready: bool,
|
||||
pending_launches: Vec<(Vec<PathBuf>, bool)>,
|
||||
pending_close: bool,
|
||||
warned_external_change: Option<PathBuf>,
|
||||
pending_external_change: Option<PathBuf>,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
### 4.3 PendingDetach
|
||||
|
||||
PendingDetach {
|
||||
source_window: WindowId,
|
||||
tab_id: u64,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
新窗口 Ready 后完成移动;失败/销毁时清理并保留源标签。
|
||||
|
||||
### 4.4 WebContext
|
||||
|
||||
- 单进程共享一个 WebContext;
|
||||
- AppState 持有,WebView 存活期间不 drop;
|
||||
- 创建新窗口时用 WebViewBuilder::with_web_context(&mut app.web_context);
|
||||
- 不需要每窗口独立 UDF。
|
||||
|
||||
## 5. 事件与 IPC 路由
|
||||
|
||||
### 5.1 UserEvent 变化
|
||||
|
||||
| 现有 | 新形态 |
|
||||
|---|---|
|
||||
| NewFile | NewFile(WindowId) |
|
||||
| OpenFile | OpenFile(WindowId) |
|
||||
| OpenPaths(paths, edit) | OpenPaths(Option<WindowId>, paths, edit) |
|
||||
| ActivateTab(id) | ActivateTab(WindowId, id) |
|
||||
| CloseTab(id) | CloseTab(WindowId, id) |
|
||||
| CloseActiveTab | CloseActiveTab(WindowId) |
|
||||
| LocateTab(id) | LocateTab(WindowId, id) |
|
||||
| FileChanged(path) | FileChanged(WindowId, path) |
|
||||
| ExternalChangeResolved(bool) | ExternalChangeResolved(WindowId, bool) |
|
||||
| FileSaved(path) | FileSaved(WindowId, path) |
|
||||
| SaveFailed(path, err) | SaveFailed(WindowId, path, err) |
|
||||
| DirtyChanged(bool) | DirtyChanged(WindowId, bool) |
|
||||
| ToggleEdit | ToggleEdit(WindowId) |
|
||||
| ShowFind | ShowFind(WindowId) |
|
||||
| Print | Print(WindowId) |
|
||||
| Ready | Ready(WindowId) |
|
||||
| RecentChanged | RecentChanged(广播) |
|
||||
| SetTheme | SetTheme(广播) |
|
||||
| Quit | Quit(全局) |
|
||||
| 新增 | DetachTab(WindowId, tab_id) |
|
||||
| 新增 | DetachReady(WindowId) / DetachFailed(WindowId) |
|
||||
| 新增 | NewWindow(WindowId?)/CreateWindow(内部) |
|
||||
|
||||
### 5.2 事件处理改造
|
||||
|
||||
- WindowEvent::CloseRequested { window_id, .. }:只处理该窗口。
|
||||
- WindowEvent::Destroyed { window_id, .. }:移除 WindowState,清理 watcher/pending。
|
||||
- WindowEvent::Focused(true):更新 active_window。
|
||||
- WindowEvent::Resized/Moved:可选保存 geometry;第一版不做每窗口恢复。
|
||||
- TaoEvent::UserEvent:先按 WindowId 找到 WindowState;找不到则安全忽略。
|
||||
- 按路径的事件(FileChanged/FileSaved/SaveFailed):带 WindowId 最直接;文件监听器创建时已知窗口。
|
||||
- 实例转发(Primary.listen)不带 WindowId:事件循环选择 active_window;没有窗口则创建。
|
||||
|
||||
### 5.3 IPC handler
|
||||
|
||||
每个 WebView 创建时捕获:
|
||||
|
||||
- window_id;
|
||||
- window.session Arc;
|
||||
- window.last_self_write Arc;
|
||||
- recent_files Arc;
|
||||
- proxy。
|
||||
|
||||
现有消息:
|
||||
|
||||
- new-file、open、open-recent、open-local-link;
|
||||
- tab-action(activate/close/detach);
|
||||
- locate-tab;
|
||||
- dirty:1/0;
|
||||
- external-change: dirty/clean;
|
||||
- print、ready、zoom:、refresh、save:。
|
||||
|
||||
新增:
|
||||
|
||||
- detach-action 或 tab-action:detach:<id>;
|
||||
- 可选 focus 不需要 IPC(同进程)。
|
||||
|
||||
所有 handler 发出的 UserEvent 都带 window_id。
|
||||
|
||||
## 6. 同一文件多开标签的评估
|
||||
|
||||
### 6.1 现状
|
||||
|
||||
- DocumentSession::open 按路径去重;
|
||||
- 同一文件在同一个窗口内只开一个标签;
|
||||
- 编辑内容只存在于当前活动 textarea;
|
||||
- 切换标签时先保存当前内容,再读磁盘渲染目标标签;
|
||||
- 自动保存 700ms 防抖,直接写盘;
|
||||
- 外部修改由 watcher 提示。
|
||||
|
||||
### 6.2 如果允许同一文件多开
|
||||
|
||||
同一窗口内:
|
||||
|
||||
- 同一时间只有一个 active 编辑器;
|
||||
- 切换会保存/重读,技术上可以串行;
|
||||
- 但两个标签显示同一文件,用户很难理解哪个是“当前版本”;
|
||||
- 关闭/激活/最近文件逻辑变复杂。
|
||||
|
||||
不同窗口:
|
||||
|
||||
- 两个窗口可以同时编辑同一文件;
|
||||
- 没有文档同步/冲突合并;
|
||||
- 两个自动保存互相覆盖,最后写入者赢;
|
||||
- watcher 可能把另一个窗口的保存识别为外部修改;
|
||||
- 数据丢失风险高。
|
||||
|
||||
### 6.3 建议
|
||||
|
||||
**第一版保持全局单开:同一文件只允许一个标签/窗口。**
|
||||
|
||||
重复打开时聚焦已有窗口和标签。
|
||||
|
||||
如果以后确实需要多开:
|
||||
|
||||
- 只支持“只读副本”;或
|
||||
- 同窗口多标签但只有一个可编辑;或
|
||||
- 引入明确的文件锁/冲突提示。
|
||||
|
||||
不要直接支持两个可编辑窗口。这个决策需要你最后确认。
|
||||
|
||||
## 7. 功能影响清单
|
||||
|
||||
### 7.1 启动与打开
|
||||
|
||||
| 场景 | 新行为 |
|
||||
|---|---|
|
||||
| 无实例、无文件启动 | 创建空窗口,显示 recent |
|
||||
| 无实例、带文件启动 | 创建窗口并打开文件 |
|
||||
| 已有实例,双击 .md | 交给已有进程,在 active_window 加标签 |
|
||||
| 已有多个窗口,双击 .md | 加到 active_window |
|
||||
| 文件已在某窗口打开 | 聚焦该窗口和标签,不重复打开 |
|
||||
| 打开多个文件 | 逐个查重,未打开的加入 active_window |
|
||||
| Open 对话框 | 在当前窗口打开;已打开则聚焦 |
|
||||
| 最近文件 | 当前窗口打开;已打开则聚焦 |
|
||||
| 拖入文件 | 在拖入的窗口打开;已打开则聚焦 |
|
||||
| 本地链接 | 当前窗口打开;已打开则聚焦 |
|
||||
|
||||
### 7.2 新窗口与标签
|
||||
|
||||
| 场景 | 新行为 |
|
||||
|---|---|
|
||||
| 右键标签 → 在新窗口打开 | 移动标签到新窗口,原标签关闭 |
|
||||
| 源窗口还有其他标签 | 源窗口保留,标签移除 |
|
||||
| 源窗口最后一个标签移出 | 关闭源窗口;新窗口继续运行 |
|
||||
| 新窗口创建失败 | 保留源窗口和标签 |
|
||||
| 保存失败 | 中止移动,保留标签,提示 |
|
||||
| 新窗口位置 | 相对源窗口偏移(如 +28,+28),不恢复位置 |
|
||||
| 新窗口启动 | 只包含目标标签;不复制源窗口其他标签 |
|
||||
| 窗口数达到 16 | 提示上限,不创建;标签保留 |
|
||||
| 拖出/拖回/合并 | 不支持 |
|
||||
| 同一文件多标签/多窗口 | 第一版不支持;聚焦已有 |
|
||||
|
||||
### 7.3 关闭与退出
|
||||
|
||||
| 场景 | 新行为 |
|
||||
|---|---|
|
||||
| 关闭一个窗口 | 只影响该窗口;其他窗口继续 |
|
||||
| 关闭窗口时有 dirty | 先保存;失败走现有 Ok/Cancel 丢弃逻辑 |
|
||||
| 关闭窗口的最后一个标签,且还有其他窗口 | 关闭该窗口 |
|
||||
| 关闭最后一个窗口的最后一个标签 | 保留空窗口,不退出 |
|
||||
| 关闭最后一个窗口 | 退出进程 |
|
||||
| 应用 Quit / Cmd+Q | 仅 macOS 菜单分支;全部窗口退出;Windows 版没有 Cmd+Q |
|
||||
| 单进程崩溃 | 所有窗口一起消失;这是单进程方案接受的代价 |
|
||||
|
||||
### 7.4 编辑与保存
|
||||
|
||||
| 场景 | 影响 |
|
||||
|---|---|
|
||||
| 自动保存 | 按窗口/标签独立;仍然 700ms 防抖 |
|
||||
| Ctrl+S | 只保存当前窗口的 active tab |
|
||||
| 只读文件保存失败 | 现有每标签 blocked 逻辑保留 |
|
||||
| 外部修改 | watcher 按窗口;提示/暂停自动保存逻辑保留 |
|
||||
| 同一文件多开 | 不支持,避免覆盖 |
|
||||
| 切换标签 | 仍先保存当前内容再渲染目标标签 |
|
||||
|
||||
### 7.5 界面与快捷键
|
||||
|
||||
| 功能 | 影响 |
|
||||
|---|---|
|
||||
| 标签栏 | 只显示当前窗口的标签 |
|
||||
| 工具栏 Edit/Zoom | 针对当前窗口 |
|
||||
| Ctrl+O/P/F | 针对当前窗口 |
|
||||
| Ctrl+W / 关闭标签 | 当前窗口;最后一个标签关闭窗口 |
|
||||
| 查找 | 每窗口独立 |
|
||||
| 缩放 | 每窗口内存状态;共享 zoom.txt,其他窗口不实时同步 |
|
||||
| 折叠 | 每窗口 DOM 状态;不持久化 |
|
||||
| 打印 | 当前窗口 |
|
||||
| 主题 | 仍跟随系统;无主题 UI |
|
||||
| 右键菜单 | 只对标签开放;其他区域仍禁用 |
|
||||
|
||||
### 7.6 最近文件与窗口位置
|
||||
|
||||
| 项 | 影响 |
|
||||
|---|---|
|
||||
| session.json | 不再读写;旧文件可保留但不恢复 |
|
||||
| recent-files.txt | 唯一持久化;单进程无需跨进程锁;仍原子写 |
|
||||
| active tab | 不持久化 |
|
||||
| window.geom | 只作为首个窗口默认位置;新窗口偏移;不恢复每窗口位置 |
|
||||
| 关闭窗口 | 是否保存 geom 需定;建议最后关闭的窗口写一次 |
|
||||
| recent 更新 | 所有窗口的发布时间线共享;空状态可广播刷新 |
|
||||
|
||||
### 7.7 实例转发
|
||||
|
||||
| 场景 | 影响 |
|
||||
|---|---|
|
||||
| 双击 .md 已有进程 | 现有 instance::acquire 转发不变 |
|
||||
| 转发目标窗口 | active_window;没有则创建 |
|
||||
| 实例锁/instance.json | 保留,基本不改 |
|
||||
| 多进程 | 不再使用 |
|
||||
|
||||
## 8. 代码施工计划
|
||||
|
||||
### 阶段 0:开工前检查
|
||||
|
||||
- 关闭正在运行的 MD Preview(需要用户确认);
|
||||
- 确认工作区干净(除 test/ 和设计文档);
|
||||
- cargo test 基线 52 passed;
|
||||
- 记录当前 HEAD、exe 状态;
|
||||
- 确认不提交/不推送,除非用户明确。
|
||||
|
||||
### 阶段 1:AppState/WindowState 重构(行为不变)
|
||||
|
||||
目标:仍只开一个窗口,但所有状态已按窗口组织。
|
||||
|
||||
步骤:
|
||||
|
||||
1. 定义 WindowState、AppState、PendingDetach;
|
||||
2. 把 main() 中 window/webview/session/enhance_flags/loaded_enhancers/page_ready/pending_launches/pending_close/warned/pending_external/watcher 搬入 WindowState;
|
||||
3. APP_DIRTY 改为 WindowState.dirty + AppState.any_dirty();
|
||||
4. render_active_document/update_tabs/update_window_title 改为接收窗口状态;
|
||||
5. 事件循环先按 window_id 查找 WindowState;
|
||||
6. 保持一个窗口,行为不变;
|
||||
7. cargo test + 手工 smoke。
|
||||
|
||||
风险:这是最大的一步;建议单独提交(refactor),不混入新功能。
|
||||
|
||||
### 阶段 2:运行中创建窗口
|
||||
|
||||
目标:能创建第二个空窗口,但不做标签移动。
|
||||
|
||||
步骤:
|
||||
|
||||
1. 使用 event_loop 的 EventLoopWindowTarget 创建窗口;
|
||||
2. 创建 WebView,复用 AppState.web_context;
|
||||
3. 初始化 WindowState,插入 windows/order;
|
||||
4. 监听 WindowEvent::Destroyed,移除状态;
|
||||
5. 新窗口位置 = active 窗口 +28,+28,clamp 可见;
|
||||
6. 设置 active_window/focus;
|
||||
7. 新窗口加载 startup page,Ready 后渲染空状态;
|
||||
8. 16 窗口上限判断;
|
||||
9. 手工验证:两个空窗口、关闭一个、关闭最后一个退出。
|
||||
|
||||
### 阶段 3:UserEvent/IPC 按窗口路由
|
||||
|
||||
目标:每个窗口的标签、编辑、查找、缩放、保存独立。
|
||||
|
||||
步骤:
|
||||
|
||||
1. UserEvent 加 WindowId(按第 5 节表);
|
||||
2. IPC handler 捕获 window_id,所有消息带窗口;
|
||||
3. ActivateTab/CloseTab/NewFile/OpenFile/LocateTab/Print/ToggleEdit/ShowFind 按窗口;
|
||||
4. FileChanged/FileSaved/SaveFailed/ExternalChangeResolved/DirtyChanged 按窗口;
|
||||
5. Ready 按窗口,注入 hljs/zoom、render active;
|
||||
6. RecentChanged 广播所有窗口;
|
||||
7. 实例 OpenPaths(Option<WindowId>) 选 active_window;
|
||||
8. WindowEvent::Focused 更新 active_window;
|
||||
9. 手工验证:两窗口各自打开/编辑/查找/缩放,互不串。
|
||||
|
||||
### 阶段 4:移除 session 恢复,recent-only
|
||||
|
||||
目标:启动不恢复标签,只显示 recent。
|
||||
|
||||
步骤:
|
||||
|
||||
1. 删除 DocumentSession::load/save、PersistedSession、session_path;
|
||||
2. 删除 main 中 initial_session 加载、persist_session 调用;
|
||||
3. 启动 session 为空;CLI 路径逐个 open;
|
||||
4. 关闭窗口不再保存 session;
|
||||
5. recent 读写保留,加原子写/去重/过滤;
|
||||
6. 更新 session.rs 测试;
|
||||
7. 手工验证:重启无标签恢复,recent 存在。
|
||||
|
||||
### 阶段 5:标签右键 + detach
|
||||
|
||||
目标:移动标签到新窗口。
|
||||
|
||||
步骤:
|
||||
|
||||
1. HTML/CSS 增加标签右键菜单,仅标签页放开 contextmenu;
|
||||
2. JS 菜单项发 detach:<id>,active dirty 时带内容;
|
||||
3. Rust IPC 保存内容,发 DetachTab(window_id, id);
|
||||
4. 事件循环:
|
||||
- 查重(排除源窗口);
|
||||
- 检查 16 上限;
|
||||
- 从源 session 取 tab 数据(先不删除);
|
||||
- 创建新 WindowState,session 只含该 tab;
|
||||
- pending_detach 记录;
|
||||
- 新窗口 Ready 后,从源 session 移除该 tab;
|
||||
- 如果源窗口为空,关闭源窗口;
|
||||
- 失败/销毁:取消 pending,保留源标签,关闭新窗口;
|
||||
5. 源标签在等待期间标记 moving,禁止编辑/自动保存;
|
||||
6. 失败时恢复;
|
||||
7. 手工验证:单标签/多标签、dirty、保存失败、16 上限、关闭新窗口、关闭源窗口。
|
||||
|
||||
### 阶段 6:回归、清理、验收
|
||||
|
||||
1. 删除临时调试入口;
|
||||
2. 更新 STATUS/HANDOFF/README(如需要);
|
||||
3. 全量 cargo test;
|
||||
4. 手工回归:编辑/保存/只读/外部修改/查找/折叠/缩放/打印/拖入/本地链接;
|
||||
5. 构建部署(由用户确认);
|
||||
6. git commit/push(由用户确认)。
|
||||
|
||||
## 9. 测试计划
|
||||
|
||||
### 单元测试
|
||||
|
||||
- WindowState/AppState 的 pure helper(窗口选择、位置偏移、active 选择);
|
||||
- DocumentSession 无持久化后的 open/activate/close;
|
||||
- 路径规范化/比较;
|
||||
- recent 更新;
|
||||
- 窗口数上限判断;
|
||||
- pending detach 状态机(如可抽纯函数)。
|
||||
|
||||
### 集成/手工
|
||||
|
||||
- 单窗口多标签;
|
||||
- 双窗口,各自多标签;
|
||||
- 右键移动标签;源窗口最后一个标签关闭窗口;
|
||||
- 移动失败保留;
|
||||
- 同一文件双击聚焦;
|
||||
- 关闭窗口只影响该窗口;
|
||||
- 关闭最后窗口退出;
|
||||
- dirty 保存/失败/只读;
|
||||
- 外部修改;
|
||||
- 查找/缩放/折叠/打印;
|
||||
- 拖入文件到指定窗口;
|
||||
- 实例转发到 active_window;
|
||||
- recent 更新;
|
||||
- 16 上限;
|
||||
- 多 WebView 内存/句柄观察;
|
||||
- 窗口位置偏移/边界。
|
||||
|
||||
## 10. 风险
|
||||
|
||||
1. main.rs 重构面大:单窗口闭包捕获状态多,阶段 1 是最大风险。
|
||||
2. WebView 生命周期:多 WebView + 共享 WebContext;需要确保 context 存活、窗口销毁时正确 drop。
|
||||
3. 事件路由遗漏:任何仍用全局 window/webview 的 handler 会在多窗口下写错窗口。
|
||||
4. 关闭语义:dirty 保存、最后标签、最后窗口、Quit 的组合需要逐一验证。
|
||||
5. 编辑冲突:只支持全局单开,避免双窗口编辑同一文件。
|
||||
6. 多 WebView 资源:单进程多个 WebView2 的内存/句柄需要实测。
|
||||
7. 窗口位置:只做偏移,不恢复;用户已接受。
|
||||
|
||||
## 11. 工作量与提交策略
|
||||
|
||||
- 估算:约 9–15 人日(阶段 1–6)。
|
||||
- 建议提交拆分:
|
||||
1. refactor: per-window state foundation(阶段 1,行为不变);
|
||||
2. feat: detach tab to new window(阶段 2–5);
|
||||
3. 可选 chore: remove session persistence(如果阶段 4 单独)。
|
||||
- 但用户要求“一个功能一个 commit”;阶段 1 是内部重构,是否单独提交需要用户确认。
|
||||
- 不管怎么拆,所有 commit/push 都要用户确认;本轮不提交。
|
||||
|
||||
## 12. 已确认事项
|
||||
|
||||
1. 同一文件第一版不支持多开;重复打开只聚焦。
|
||||
2. 非最后窗口关闭最后一个标签会关闭该窗口;最后一个窗口关闭最后一个标签时保留空窗口。
|
||||
3. 关闭最后一个窗口才退出进程。
|
||||
4. Cmd+Q 仅 macOS 分支;Windows 版没有 Cmd+Q,Quit 按全局退出处理。
|
||||
5. 源窗口最后一个标签移出后关闭源窗口(新窗口已存在)。
|
||||
6. 新窗口偏移 +28,+28;不恢复每窗口位置。
|
||||
7. 16 窗口上限保留。
|
||||
8. Git 不建分支;commit 由 agent 决定,颗粒度可细;不推送。
|
||||
101
agent/docs/migration-2026-11-02.md
Normal file
101
agent/docs/migration-2026-11-02.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# 2026-11-02 迁移:Low 工作区 + Nutstore 单一发布
|
||||
|
||||
> 目标:DSH 以 **workspace-write(Low)** 运行就能改代码、编译、测试;成品只通过用户手动运行的 `publish.ps1` 发布到 Nutstore。
|
||||
> 执行前先读 `agent/AGENTS.md`。
|
||||
|
||||
## 1. 最终结构
|
||||
|
||||
~~~
|
||||
D:\Scripts\md-preview\
|
||||
├─ AgentLowWorking\ ← 仓库根(整棵树 Low,含 .git)
|
||||
│ ├─ src / assets / agent / target / Cargo.* / README.md ...
|
||||
│ └─ test\ 本机草稿(已 gitignore)
|
||||
└─ MD-Preview-windows-x64.exe 旧产物(Medium);publish.ps1 成功后删除
|
||||
~~~
|
||||
|
||||
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`
|
||||
- 发布产物:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium)
|
||||
- 默认 `.md` 打开方式:由 `publish.ps1` 指向 Nutstore
|
||||
- 仓库内不再放 exe
|
||||
|
||||
## 2. 一次性移动(用户执行)
|
||||
|
||||
DSH 工作区保持在父目录 `D:\Scripts\md-preview`,所以**不需要关 DSH**;只要没有编辑器/进程占用仓库文件即可。如果 `Move-Item` 报“文件被占用”,再关掉 DSH/编辑器重试。
|
||||
|
||||
~~~powershell
|
||||
$old = 'D:\Scripts\md-preview'
|
||||
$new = Join-Path $old 'AgentLowWorking'
|
||||
|
||||
# 1) 创建新仓库根(继承 Low)
|
||||
New-Item -ItemType Directory -Path $new -Force | Out-Null
|
||||
|
||||
# 2) 移动除旧 exe 和新目录以外的全部内容(含 .git、target、backup、test)
|
||||
Get-ChildItem -LiteralPath $old -Force |
|
||||
Where-Object { $_.Name -notin @('AgentLowWorking', 'MD-Preview-windows-x64.exe') } |
|
||||
Move-Item -Destination $new -Force
|
||||
|
||||
# 3) 整棵树 relabel 成 Low(对目录用 /T,顶层文件也会覆盖)
|
||||
icacls $new /setintegritylevel "(OI)(CI)Low" /T /C
|
||||
|
||||
# 4) 校验:前三项 Low,最后一项 Medium
|
||||
icacls (Join-Path $new 'src\main.rs') | Select-String 'Mandatory Label'
|
||||
icacls (Join-Path $new 'Cargo.toml') | Select-String 'Mandatory Label'
|
||||
icacls (Join-Path $new '.git') | Select-String 'Mandatory Label'
|
||||
icacls (Join-Path $old 'MD-Preview-windows-x64.exe') | Select-String 'Mandatory Label'
|
||||
~~~
|
||||
|
||||
移动是同卷 rename,`.git` 一起走:历史、分支、远程都不受影响,**不需要任何 rename 提交**。
|
||||
|
||||
## 3. 移动后继续
|
||||
|
||||
不需要重开 DSH;在 DSH 里 `cd AgentLowWorking`(或所有命令用绝对路径)。验证:
|
||||
|
||||
~~~powershell
|
||||
# 在 DSH 的 pwsh 里应能写
|
||||
Set-Content "$PWD\target\tmp\probe.txt" 'ok'; Get-Content "$PWD\target\tmp\probe.txt"; Remove-Item "$PWD\target\tmp\probe.txt"
|
||||
cargo test
|
||||
~~~
|
||||
|
||||
## 4. 开发循环
|
||||
|
||||
~~~powershell
|
||||
.\agent\scripts\build.ps1
|
||||
# 产物 target\release\md-preview.exe 是 Low,不能直接双击
|
||||
$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"
|
||||
.\target\release\md-preview.exe path\to\file.md
|
||||
~~~
|
||||
|
||||
## 5. 发布(用户手动,普通 PowerShell)
|
||||
|
||||
~~~powershell
|
||||
cd D:\Scripts\md-preview\AgentLowWorking
|
||||
.\agent\scripts\publish.ps1
|
||||
~~~
|
||||
|
||||
脚本会:检查 Medium 权限和进程占用 → 复制到 Nutstore → 设 Medium → 校验 SHA256 → 刷新 `.md` 关联 → 删除 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。
|
||||
|
||||
## 6. 回滚
|
||||
|
||||
如果新模型不可用:
|
||||
|
||||
1. 关掉 DSH。
|
||||
2. 把 `AgentLowWorking` 里的内容移回 `D:\Scripts\md-preview`(同样排除 `AgentLowWorking`)。
|
||||
3. `icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Medium" /T /C`(旧模型)。
|
||||
4. 旧 exe 若已被删除,从 Nutstore 复制回来或重新发布。
|
||||
5. DSH 改回 danger-full-access。
|
||||
|
||||
## 7. 注意
|
||||
|
||||
- `publish.ps1` 只应在**普通 / Medium** PowerShell 里运行;DSH 的 Low shell 会被脚本拒绝。
|
||||
- 发布前关闭 MD Preview;Nutstore 同步也可能短暂锁文件。
|
||||
- 开发版写不了 HKCU,不会抢默认打开;不要用 Medium 的旧 exe 启动,否则关联会被改回旧路径。
|
||||
- `test/` 已 gitignore,移动后仍不提交。
|
||||
|
||||
## 8. 迁移后待办
|
||||
|
||||
- 在 DSH 里确认可写、`cargo test` 全绿。
|
||||
- 父目录可选:`publish.ps1` 启动器 + `AGENTS.md` 指针(让新会话在父目录也能找到仓库规则)。
|
||||
- 给 `.gitignore` 加 `/test/`(本机草稿目录)。
|
||||
- 更新根 `README.md` 的目录树/构建命令。
|
||||
- 提交:`git add -A && git commit -m "chore: move to Low workspace and Nutstore-only publish"`(不要提交 `test/`)。
|
||||
- 需要切换默认打开并删除旧 exe 时,运行 `publish.ps1`。
|
||||
113
agent/docs/next-2026-11-03.md
Normal file
113
agent/docs/next-2026-11-03.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# 下一步交接(2026-11-03)
|
||||
|
||||
> 用途:这一轮只做了“功能不变”的架构整理。功能改动(HKCU、编辑区样式化)**一个都没做**,下次从这里继续。
|
||||
> 先读 `agent/AGENTS.md`;发布仍由用户手动运行 `agent\scripts\publish.ps1`。
|
||||
|
||||
## 1. 基线
|
||||
|
||||
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`;Windows-only(macOS/Linux 代码已在 `1115052` 之后的提交里删除)。
|
||||
- `cargo test` 59 passed;`cargo clippy --all-targets` 0 warning;`cargo fmt -- --check` 通过。
|
||||
- 源码:`main.rs` 约 2820 行、`config.rs` 212、`markdown.rs` 405、`session.rs` 488、`instance.rs` 207、`page.rs` 65、`escape.rs` 25。
|
||||
- 页面资源:`assets/page/{page.html,page.css,page.js}`。
|
||||
- 未发布:Nutstore 上的 exe 仍是 v1.4.2-local.5;这一轮的构建只在 `target\release\`(Low)。
|
||||
|
||||
## 2. 已完成(本轮,均未改变 Windows 行为)
|
||||
|
||||
1. 页面 HTML/CSS/JS 搬出 `format!`,`build_page` 只填 `__MDP_*__` 占位符。
|
||||
2. 拆出 `src/markdown.rs`(md→html)、`src/page.rs`、`src/escape.rs`、`src/config.rs`(路径/zoom/窗口几何/对话框)。
|
||||
3. 删除 macOS/Linux 死代码、Finder 扩展、非 Windows 分支与 `objc2` 依赖;`Cargo.toml` 只剩 Windows 依赖。
|
||||
4. 测试模块移到文件末尾(clippy items_after_test_module)。
|
||||
|
||||
## 3. 剩余重构(仍不改行为,建议顺序)
|
||||
|
||||
1. ✅ `src/files.rs`(2026-11-06,`1208386`):最近文件、保存写盘、文件监听、支持的扩展名、本地链接解析、Explorer 定位;附带 `src/testutil.rs`。
|
||||
2. ✅ `src/app.rs`(2026-11-06,`fb10fc5`):`UserEvent`/`WindowState`/`AppState`、find/focus、`render_*`、`build_webview`、窗口创建/关闭、`run_event_loop`。
|
||||
3. ✅ `main.rs` 只留 `main()`、CLI、启动装配和测试(事件 match 仍在 `app::run_event_loop` 里,可按需再拆处理函数)。
|
||||
4. ✅ 测试已随模块走(2026-11-06,`a5c0b08`):app 7、markdown 23、page 5、config 2、files 10、session 10、instance 3;共享 `testutil::temp_dir`。启动装配与 CLI 也移入 `app::run()`,`main.rs` 只剩 18 行。
|
||||
5. 遗留:`UserEvent` 里 5 个未构造变体(`CloseActiveTab/ToggleEdit/ShowFind/Quit/SetTheme`)要么接键盘路径,要么删除。
|
||||
|
||||
## 4. 待做功能(都需要先讨论/确认)
|
||||
|
||||
### 4.1 移除应用自身的 HKCU 写入(2026-11-04 已完成)
|
||||
|
||||
- 已删除 `main()` 里的 `register_as_default()` 调用、该函数以及 `winreg` 依赖;应用不再写注册表。
|
||||
- **`publish.ps1` 维持现状**(继续写 ProgID/关联),这是用户明确决定。
|
||||
- 影响:新机器上应用不再自动出现在“打开方式”;首次在 Windows“打开方式 → 选择其他应用”里选一次;exe 移动后由发布脚本刷新关联。
|
||||
- README 第 3 步、STATUS §11 已同步。
|
||||
|
||||
### 4.2 编辑区样式化(已完成:内嵌 CodeMirror 5,2026-11-06)
|
||||
|
||||
需求:编辑模式里 `**加粗**` 显示为粗体、`# 标题` 整行加粗加大、行内代码换字体。**标记保持显示**。用户已确认行号、编辑区折叠、替换近期一定会做。
|
||||
|
||||
**决策(2026-11-06)**:
|
||||
|
||||
- 采用 **CodeMirror 5**(单文件 UMD、离线 vendored,MIT;core + markdown/xml mode + search + fold + lineNumbers 约 +270–320 KB,exe 约 5.50 → 5.8 MB)。用户已确认这项 >200 KB vendored 资源。
|
||||
- 弃用透明叠加层(方案 A):只能同字号着色,覆盖不了行号/折叠/替换。
|
||||
- 不选自研 contenteditable(方案 B)。
|
||||
|
||||
**实现顺序**:
|
||||
|
||||
1. 先在 page.js 抽出编辑器适配层(`getValue/setValue/focus/getScrollRatio/setScrollRatio/onChange/setEditable`);textarea 作为默认实现,行为不变。
|
||||
2. vendor CM5 到 `assets/codemirror/`(附 LICENSE),由 page 注入;保持离线、单 exe。
|
||||
3. CM5 适配器:markdown/xml mode、lineNumbers、foldGutter + 按标题计算折叠区间、search(find/replace);样式沿用现有配色,`cm-strong` 加粗、标题行加粗/着色,标记不隐藏。
|
||||
4. 滚动模型:编辑模式由 CM 内部滚动(隐藏页面滚动条),编辑/阅读各自记住比例,切换时近似同步;按标签独立(`DocumentTab` 可能需要两个比例字段)。
|
||||
5. autosave 仍 700ms,接 `onChange`;`__setContent`/标签切换/缩放/暗色主题都要重新验证;超大文档保护(>2 MB 或 >2 万行)可保留。
|
||||
6. 阅读模式既有 find 与折叠不动;编辑模式 find/replace 由 CM search 提供,UI 统一是后续小工作。
|
||||
|
||||
**状态(2026-11-06)**:已完成并推送(`8b4d1fa` → `e911876`)。实现与计划的差异:
|
||||
- CM 资源改为首次进编辑时经 `need-editor` IPC 注入,启动 HTML 不增加;
|
||||
- 查找替换没有用 CM 自带 dialog,改为页面两行 findbar(Find + ↑↓× / Replace + Replace All),Esc 只关查找条;
|
||||
- 滚动没有拆两个比例字段:JS `cmTabLines` 按标签记顶部行号,Rust `scroll_ratio` 仅作重启兜底;`__setContent` 增加第 8 参数 tab id;
|
||||
- 补充 BOM 保留、围栏缓存、代码块内 `#` 不折叠、`#app` 容器滚动等修复。
|
||||
|
||||
**验证**:用户已手动验证编辑/保存/切标签/折叠/替换/滚动;ui-smoke 8/8。已知限制:编辑查找不支持 `/re/` 正则;超大文档回退 textarea;阅读→编辑滚动仍是比例近似。
|
||||
|
||||
## 5. 验证配方
|
||||
|
||||
~~~powershell
|
||||
$env:TEMP = "$PWD\target\tmp"; $env:TMP = $env:TEMP
|
||||
cargo test
|
||||
cargo clippy --all-targets
|
||||
cargo fmt -- --check
|
||||
.\agent\scripts\build.ps1 # release 构建 + 字符串校验 + 大小/SHA
|
||||
~~~
|
||||
|
||||
页面输出逐字节对比(重构时用):
|
||||
|
||||
1. 临时加一个 `#[test]`,用 `build_page`/build_startup_page 把 home、含公式/mermaid 的文档、启动页写到 `$env:MDP_DUMP_DIR`;
|
||||
2. 重构前后各跑一次,`Get-FileHash` 对比 sha256;
|
||||
3. 用完删除该测试。
|
||||
|
||||
手动冒烟(无自动化):多标签切换、编辑/阅读、Ctrl+F、Ctrl+P、折叠、拖拽打开、外部修改提示、只读保存失败。
|
||||
|
||||
## 5.1 发布前 UI 冒烟(必须由用户在普通 PowerShell 跑)
|
||||
|
||||
**为什么不能由 Agent 跑**:DSH 的 Windows 沙箱禁止命名管道,Chromium/WebView2 的 Mojo IPC 起不来。
|
||||
实测:md-preview 能启动、窗口出现,但 `msedgewebview2.exe` 立刻退出(数据目录只建了一半),页面白屏;Edge headless 报
|
||||
`FATAL:mojo\public\cpp\platform\platform_channel.cc Check failed: 拒绝访问 (0x5)`。
|
||||
这是沙箱限制,不是应用 bug;同时开发 exe 是 Low 完整性,从这里 `icacls /setintegritylevel Medium` 会被拒绝(无 write-up)。
|
||||
|
||||
**用法**(普通 PowerShell,Node 21+;本机 `C:\Program Files\nodejs\node.exe` 是 24.x):
|
||||
|
||||
~~~powershell
|
||||
cd D:\Scripts\md-preview\AgentLowWorking
|
||||
.\agent\tests\ui-smoke.cmd # 推荐:双击或从 cmd 运行,脚本内部用 Bypass
|
||||
.\agent\tests\ui-smoke.ps1 # 若执行策略允许 .ps1
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File .\agent\tests\ui-smoke.ps1
|
||||
~~~
|
||||
|
||||
> 本机执行策略可能是 AllSigned:直接跑未签名 .ps1 会被拒绝,所以提供了 `.cmd` 包装(内部 `-ExecutionPolicy Bypass`,不修改系统策略)。
|
||||
|
||||
- 脚本用独立配置目录(`target\ui-test\config`)启动 exe,设置 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`,等端口起来后调用 `agent/tests/ui-smoke.mjs`。
|
||||
- mjs 通过 CDP 读取页面快照、断言(页面加载、`#preview` 有内容、`window.ipc` 桥、页面 API、标题/折叠按钮/代码高亮),再截图,写 `target/ui-test/ui-smoke.json` 与 `ui-smoke.png`。
|
||||
- Agent 可以直接读这两个文件定位问题;失败时把 report 里的 checks 贴出来即可。
|
||||
- 已知边界:只验证“页面真的渲染了 + 基础 API 在”,不覆盖标签切换、保存、外部修改等 Rust 侧流程(那些靠单元测试和人工点)。
|
||||
- 2026-11-04 起应用启动不再写注册表,所以用发布版做冒烟也不会改 .md 关联;默认的开发构建仍是 Low,配置目录隔离在 `target/ui-test`。
|
||||
|
||||
## 6. 注意
|
||||
|
||||
- 本仓库现在**只能在 Windows 上编译**;`cargo test` 里仍有 `cfg(target_os = "windows")` 的 Windows 专用测试。
|
||||
- `main.rs` 顶部的 `windows_subsystem` 只对 release 生效;debug 构建带控制台,属正常。
|
||||
- 页面 JS 改动后建议做一次语法检查(临时测试把页面写到文件,再 `node --check`)。
|
||||
- **Rust → JS 调用没有编译器检查**:改 `__setContent` / `__setPreview` 等参数列表时,必须同步改页面的函数签名,并用 `set_content_script_matches_the_page_signature` 这类“精确输出 + 页面签名”测试锁住。2026-11-04 的白屏就是这么来的(多传了一个 `active.id`,标签 id 被当 HTML 渲染)。
|
||||
- 构建/测试临时文件放 `target\tmp`;不要写 `%TEMP%`。
|
||||
43
agent/docs/release-notes-v1.4.2-local.2.md
Normal file
43
agent/docs/release-notes-v1.4.2-local.2.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# v1.4.2-local.2(2026-10-27)
|
||||
|
||||
Windows 本地 Markdown 预览器,基于上游 `md-preview 1.4.2` 的离线定制版。本次更新主要面向 AI 输出中常见的非标准 Markdown 写法。
|
||||
|
||||
## 下载
|
||||
|
||||
- **MD-Preview-windows-x64.exe**
|
||||
- 大小:5,505,024 字节
|
||||
- SHA256:`7C8A3A8AE1DF4D93714F080663641EC1D7C9CD4B44476D90D020A2640999BD95`
|
||||
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
|
||||
- 免安装:下载后放到固定目录直接运行;可在 `.md` 的“打开方式”里设为默认。
|
||||
|
||||
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
|
||||
|
||||
## 本次更新
|
||||
|
||||
- **单换行按换行显示**:AI 输出常用单个换行分隔规则或句子;现在预览会把它显示成换行,而不是折叠成空格。标题、代码块、表格和 raw HTML 不受影响;空行仍然是段落分隔。
|
||||
- **GFM 脚注**:支持 `正文[^1]` 和 `[^1]: 注释`,并补齐浅色/深色样式。
|
||||
- **定义列表**:支持 `Term` + `: Definition` 的 CommonMark-HS 定义列表。
|
||||
- **UTF-8 BOM 容错**:文件开头带 BOM 时,标题和 front matter 仍能正常识别。
|
||||
- **文档更新**:README 和状态文档写明“单换行按换行显示”是本工具有意采用的方言,并提示硬折行长段落会保留断点。
|
||||
|
||||
## 包含上一版功能
|
||||
|
||||
- 完全离线,无联网检查、自动更新或遥测。
|
||||
- 工具栏只保留 编辑 / 缩放;Open、Print、Find 按钮移除,快捷键保留。
|
||||
- `Ctrl+滚轮` 缩放:步进 5%、范围 50%–300%,跨重启记住。
|
||||
- 代码块始终深色(Visual Studio Dark),行内代码跟随系统主题。
|
||||
- 标题 hover 折角箭头,按 H1–H6 层级折叠;查找命中自动展开,打印时全部展开。
|
||||
- 只读文件保存失败只提示一次并暂停自动保存,关闭时可确认丢弃修改。
|
||||
- 路径、Recent、相对链接/图片、会话恢复、外部修改热重载、单实例转发等修复。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 仅 Windows(源码中 macOS 分支未维护)。
|
||||
- 不自动更新;升级请手动替换 exe。
|
||||
- 折叠状态每次打开重置为全部展开。
|
||||
- 单换行按换行显示;如果源文件是按固定列硬折行的长段落,预览会保留这些断点,不随窗口宽度重排。
|
||||
- 只读文件可以编辑,但保存会被拒绝并提示。
|
||||
|
||||
## 从上一版升级
|
||||
|
||||
直接退出旧程序,用新 exe 覆盖原文件即可。设置、会话和缩放记录在 `%LOCALAPPDATA%\md-preview\`,不会被覆盖。
|
||||
53
agent/docs/release-notes-v1.4.2-local.3.md
Normal file
53
agent/docs/release-notes-v1.4.2-local.3.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# v1.4.2-local.3(2026-10-28)
|
||||
|
||||
Windows 本地 Markdown 预览器,基于上游 md-preview 1.4.2 的离线定制版。本次更新加入单进程多窗口,并打磨标签操作与多显示器行为。
|
||||
|
||||
## 下载
|
||||
|
||||
- **MD-Preview-windows-x64.exe**
|
||||
- 大小:5,507,584 字节
|
||||
- SHA256:0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E
|
||||
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
|
||||
- 免安装:下载后放到固定目录直接运行;可在 .md 的“打开方式”里设为默认。
|
||||
|
||||
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
|
||||
|
||||
## 本次更新
|
||||
|
||||
- **单进程多窗口**:共享一个 WebView2 WebContext;每个窗口独立的标签、编辑、查找、缩放状态;最多 16 个窗口。
|
||||
- **标签右键“在新窗口打开”**:移动语义;新窗口只包含该标签;源窗口如果还有标签则保留,否则关闭源窗口。
|
||||
- **拖标签开新窗口**:按住标签上下拖动超过约 24px 后松开即可;只有一个标签时不允许拖动。仍保留右键菜单入口。
|
||||
- **新窗口位置修复**:新窗口在源窗口所在显示器内偏移 +28,+28,不再跳到主屏;混合 DPI 下按物理坐标处理。
|
||||
- **重复打开聚焦修复**:同一文件已在其他窗口打开时只聚焦最终目标,不再先激活一个窗口再切换,减少多余的前台切换。
|
||||
- **右键菜单打磨**:菜单更紧凑;顶部显示路径(中间省略,保留开头和文件名);新增“打开文件所在位置”,直接调用资源管理器定位。
|
||||
- **标签提示避让**:右键菜单打开时临时移除标签 tooltip,关闭菜单后恢复,避免 tooltip 遮挡菜单。
|
||||
- **先保存再移动**:当前标签有未保存修改时,先写盘再移动;保存失败则拒绝移动。
|
||||
- **唯一标签禁用**:只有一个标签时“在新窗口打开”置灰,避免误操作。
|
||||
- **同一文件全局唯一**:文件已在其他窗口打开时只聚焦已有窗口/标签,不再重复打开。
|
||||
- **启动不恢复标签**:只保留最近文件;旧 session.json 不再读写,也不会主动删除。
|
||||
- **关闭语义**:非最后窗口关闭最后一个标签会关闭该窗口;最后窗口关闭最后一个标签保留空窗口;关闭最后窗口才退出进程。
|
||||
|
||||
## 包含上一版功能
|
||||
|
||||
- 完全离线,无联网检查、自动更新或遥测。
|
||||
- 工具栏只保留 编辑 / 缩放;Open、Print、Find 按钮移除,快捷键保留。
|
||||
- Ctrl+滚轮缩放:步进 5%、范围 50%–300%,跨重启记住。
|
||||
- 代码块始终深色(Visual Studio Dark),行内代码跟随系统主题。
|
||||
- 标题 hover 折角箭头,按 H1–H6 层级折叠;查找命中自动展开,打印时全部展开。
|
||||
- 只读文件保存失败只提示一次并暂停自动保存,关闭时可确认丢弃修改。
|
||||
- AI 输出方言:单换行按换行显示、GFM 脚注、定义列表、UTF-8 BOM 容错。
|
||||
- 相对链接/图片、外部修改热重载、单实例转发等修复。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 仅 Windows(源码中 macOS 分支未维护)。
|
||||
- 不自动更新;升级请手动替换 exe。
|
||||
- 不做标签拖回、窗口合并、跨窗口编辑同步;拖拽只用于“移出到新窗口”。
|
||||
- 多窗口下不恢复上次窗口位置;新窗口相对源窗口偏移,但不会逐窗口记忆。
|
||||
- 多显示器下新窗口在源显示器内偏移并做基础 clamp;跨屏/混合 DPI 的精细位置仍不保证。
|
||||
- 标签右键菜单无键盘入口。
|
||||
- 只读文件可以编辑,但保存会被拒绝并提示。
|
||||
|
||||
## 从上一版升级
|
||||
|
||||
直接退出旧程序,用新 exe 覆盖原文件即可。设置、最近文件和缩放记录在 %LOCALAPPDATA%\md-preview\;旧 session.json 不再使用。
|
||||
53
agent/docs/release-notes-v1.4.2-local.4.md
Normal file
53
agent/docs/release-notes-v1.4.2-local.4.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# v1.4.2-local.4(2026-10-28)
|
||||
|
||||
Windows 本地 Markdown 预览器,基于上游 md-preview 1.4.2 的离线定制版。本次更新把首页改成真正的“新标签页(New Tab)”,并把界面统一为英文。
|
||||
|
||||
## 下载
|
||||
|
||||
- **MD-Preview-windows-x64.exe**
|
||||
- 大小:5,499,392 字节
|
||||
- SHA256:7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D
|
||||
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
|
||||
- 免安装:下载后放到固定目录直接运行;可在 .md 的“打开方式”里设为默认。
|
||||
|
||||
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
|
||||
|
||||
## 本次更新
|
||||
|
||||
- **新标签页(New Tab)**:默认标签就是 New Tab;标签栏的 `+` 新建一个 New Tab,不再弹“新建文件”对话框。
|
||||
- **新标签页打开文件复用标签**:在 New Tab 里 Open File、点 Recent、拖入文件或 New File,会直接替换当前 New Tab(浏览器新标签页语义),不会额外留下一个空白标签。
|
||||
- **关闭回退**:关闭最后一个文件标签会回到 New Tab;只剩一个 New Tab 时标签栏自动隐藏,外观和原来的首页一致。
|
||||
- **New File 按钮**:New Tab 上 Open File 右侧新增 New File 按钮,接管原 `+` 的建文件功能;`Ctrl+N` 仍然可用。
|
||||
- **界面统一为英文**:移除系统语言检测和中文文案,标签名从“首页/Home”改为“New Tab”,避免中英文混排;macOS Finder 新建文件也改用 Untitled 默认名。
|
||||
- **编辑保护**:在 New Tab 上按 `Ctrl+E` 不再进入空白编辑器。
|
||||
- **保存保护**:在脏文件上点 `+` 会先保存再切到 New Tab;不会丢失未保存内容。
|
||||
- **布局修复**:New Tab 与标签栏同时出现时,标签栏不再被 .empty 样式挤窄。
|
||||
- **窗口标题 / 文件监听**:New Tab 显示 `MD Preview` 标题;切换到 New Tab 时会清空文件监听,避免误报外部修改。
|
||||
- **标签约束**:New Tab 不可拖出到新窗口,右键菜单里的 Show in Explorer / Open in New Window 会置灰。
|
||||
|
||||
## 包含上一版功能
|
||||
|
||||
- 单进程多窗口:每个窗口独立标签/编辑/查找/缩放状态,最多 16 个窗口。
|
||||
- 标签右键或上下拖动移出到新窗口;同一文件全局只开一次,重复打开只聚焦。
|
||||
- 完全离线,无联网检查、自动更新或遥测。
|
||||
- 工具栏只保留 Edit / Zoom;Open、Print、Find 按钮移除,快捷键保留。
|
||||
- Ctrl+滚轮缩放:步进 5%、范围 50%–300%,跨重启记住。
|
||||
- 代码块始终深色(Visual Studio Dark),行内代码跟随主题。
|
||||
- 标题 hover 折角箭头,按 H1–H6 层级折叠;查找命中自动展开,打印时全部展开。
|
||||
- 只读文件保存失败只提示一次并暂停自动保存,关闭时可确认丢弃修改。
|
||||
- AI 输出方言:单换行按换行显示、GFM 脚注、定义列表、UTF-8 BOM 容错。
|
||||
- 相对链接/图片、外部修改热重载、单实例转发、缺失文件重定位等。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 仅 Windows(源码中 macOS 分支未维护)。
|
||||
- 界面只有英文,不随系统语言切换。
|
||||
- 不自动更新;升级请手动替换 exe。
|
||||
- 不做标签拖回、窗口合并、跨窗口编辑同步;拖拽只用于“移出到新窗口”。
|
||||
- 多窗口下不恢复上次窗口位置;新窗口相对源窗口偏移,但不会逐窗口记忆。
|
||||
- 标签右键菜单无键盘入口。
|
||||
- 只读文件可以编辑,但保存会被拒绝并提示。
|
||||
|
||||
## 从上一版升级
|
||||
|
||||
直接退出旧程序,用新 exe 覆盖原文件即可。设置、最近文件和缩放记录保存在 %LOCALAPPDATA%\md-preview\;旧 session.json 不再使用。
|
||||
40
agent/docs/release-notes-v1.4.2-local.5.md
Normal file
40
agent/docs/release-notes-v1.4.2-local.5.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# v1.4.2-local.5(2026-10-30)
|
||||
|
||||
Windows 本地 Markdown 预览器,基于上游 md-preview 1.4.2 的离线定制版。本次更新集中在编辑与阅读查找体验:Tab/Shift+Tab 缩进、回车自动跟随缩进,以及阅读模式 Find 的选区填入与“不滚动”打开。
|
||||
|
||||
## 下载
|
||||
|
||||
- **MD-Preview-windows-x64.exe**
|
||||
- 大小:5,505,024 字节
|
||||
- SHA256:A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988
|
||||
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
|
||||
- 免安装:下载后放到固定目录直接运行;可在 .md 的“打开方式”里设为默认。
|
||||
|
||||
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
|
||||
|
||||
## 本次更新
|
||||
|
||||
- **Tab / Shift+Tab 缩进**:编辑模式下 Tab 插入 2 个空格,Shift+Tab 反缩进;多行选区会整块缩进/反缩进;保留 textarea 原生撤销,一次 Tab 可以一步 Ctrl+Z 撤回;输入法组合期间不拦截。
|
||||
- **回车自动跟随缩进**:按 Enter 复制当前行光标前的前导空白;空行不会继续叠加缩进。列表续行(`- `、`1. `、`> `)暂未加入,留作后续单独功能。
|
||||
- **Find 自动填入阅读选区**:阅读模式选中文字后 Ctrl+F,会自动填入 Find 框;多行选区取第一行非空内容。
|
||||
- **从选区打开 Find 时不滚动**:双击某个词再 Ctrl+F,页面保持原位,只高亮并显示当前序号(例如 4/8);点“下一个/上一个”或按 Enter 时才正常滚动到目标。
|
||||
- **查找起点跟随位置**:没有选区时输入新查询,会从当前视口附近开始找,而不是每次都从文档开头跳;如果下方没有匹配,选择上方最近的匹配,避免直接回到第 1 个。
|
||||
- **编辑模式 Find 保持原样**:仍使用 WebView2 自带查找;本次不统一两种 Find。
|
||||
|
||||
## 包含上一版功能
|
||||
|
||||
- 新标签页(New Tab):默认标签、`+` 新建、New File 按钮、关闭回退、单 New Tab 隐藏标签栏。
|
||||
- 全英文界面;移除语言检测和中文文案。
|
||||
- 单进程多窗口、标签右键/拖拽移出、同文件全局聚焦。
|
||||
- 标题折叠、Ctrl+滚轮缩放、始终深色代码块、自动保存、外部修改热重载、单实例转发。
|
||||
- GFM 脚注、定义列表、front matter、GitHub Alerts、`==高亮==`、KaTeX、Mermaid;单换行按换行显示。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 编辑模式仍是纯 textarea,没有语法高亮、列表续行或富文本渲染。
|
||||
- 编辑模式 Find 与阅读模式 Find 行为不同;阅读模式才使用应用的 findbar。
|
||||
- 仅 Windows;不自动更新;升级请手动替换 exe。
|
||||
|
||||
## 从上一版升级
|
||||
|
||||
直接退出旧程序,用新 exe 覆盖原文件即可。设置、最近文件和缩放记录保存在 `%LOCALAPPDATA%\md-preview\`;旧 session.json 不再使用。
|
||||
196
agent/docs/review-single-process-multi-window.md
Normal file
196
agent/docs/review-single-process-multi-window.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# 单进程多窗口:实施前复核
|
||||
|
||||
日期:2026-10-27
|
||||
状态:只读复核;未改功能代码,未提交,未推送。
|
||||
|
||||
## 结论
|
||||
|
||||
方案可行,但当前代码是“单窗口 + 单 WebView + 一个 event_loop 闭包”的结构,阶段 1 不是小改,而是把主循环的状态所有权重新划分。建议按报告中的阶段 1 先做“行为不变”的重构,再逐项加窗口能力。
|
||||
|
||||
复核依据:src/main.rs、src/session.rs、src/instance.rs、Cargo.toml、Cargo.lock。
|
||||
|
||||
## 1. 现有实现与计划的对应关系
|
||||
|
||||
- 入口和主循环:src/main.rs:3718 的 main();event_loop.run 在 src/main.rs:4073;整个窗口、WebView、session、watcher、page_ready 等都捕获在同一个闭包里。
|
||||
- 单个 WindowState 的雏形:window 在 src/main.rs:3822 创建;webview 在 src/main.rs:4042 创建;没有 AppState/WindowState。
|
||||
- 单个 WebContext:src/main.rs:3854 的 wry::WebContext::new;src/main.rs:3857 用 with_web_context 构建 WebView。
|
||||
- 启动 session:src/main.rs:3786 调用 DocumentSession::load(&session_path());session_path 在 src/main.rs:800。
|
||||
- 持久化:persist_session 在 src/main.rs:3578;调用点包括 3831、4153、4174、4193、4229、4298、4331、4347、4396、4478。
|
||||
- 全局 dirty:APP_DIRTY 在 src/main.rs:28;读取在 4389、4471;写入在 3614、3697、4275、4311、4360。它只反映当前 active tab。
|
||||
- 事件枚举:UserEvent 在 src/main.rs:37-57;没有 WindowId。
|
||||
- IPC:with_ipc_handler 在 src/main.rs:3877;闭包固定捕获一份 session_for_ipc、last_self_write_for_ipc、recent_files_for_ipc,无法按窗口路由。
|
||||
- 标签栏 JS:tab-action 消息在 src/main.rs:1591;关闭/激活的 IPC 处理在 src/main.rs:3904;右键拦截在 src/main.rs:1562。
|
||||
- 关闭逻辑:CloseTab 在 src/main.rs:4189;CloseActiveTab 在 4212;Quit 在 4388;CloseRequested 在 4467。没有 WindowEvent::Destroyed,也没有 Focused 的 active_window 维护。
|
||||
- 单实例:src/instance.rs:35 的 acquire;src/instance.rs:110 的 listen;转发仍可用,但回调只发 UserEvent::OpenPaths,需由事件循环选 active_window。
|
||||
- 依赖:Cargo.toml 的 wry 0.50、tao 0.33;Cargo.lock 实际是 wry 0.50.5、tao 0.33.0,支持多窗口和共享 WebContext。
|
||||
- 现有测试:52 passed;session 持久化往返测试在 src/session.rs:254,移除持久化后会少 1 个测试(先按 51 计,后续再补新测试)。
|
||||
|
||||
## 2. 计划与代码的冲突点
|
||||
|
||||
### 2.1 状态所有权(阶段 1 最大风险)
|
||||
|
||||
现状:window、webview、session、watcher、loaded_enhancers、page_ready、pending_launches、pending_window_close、warned_external_change、pending_external_change、last_self_write 全是 main() 的局部变量。
|
||||
|
||||
计划:AppState + 每个窗口一个 WindowState。
|
||||
|
||||
冲突:这些变量的生命周期、借用关系、闭包捕获会整体变化;不能只把 window 放进 HashMap,否则 IPC/事件循环仍会拿到旧 session。
|
||||
|
||||
处理:阶段 1 先建立 AppState/WindowState,仍只创建一个窗口,保持行为;所有状态从闭包局部变量搬入 WindowState。此阶段不删 session 持久化、不加右键菜单,先把“等价重构”做完。
|
||||
|
||||
### 2.2 UserEvent 没有窗口标识
|
||||
|
||||
现状:OpenPaths、ActivateTab、CloseTab、CloseActiveTab、Ready、FileChanged、FileSaved、SaveFailed、DirtyChanged、ToggleEdit、ShowFind、Print、SetTheme、Quit 都是全局事件。
|
||||
|
||||
计划:事件带 WindowId;全局事件(OpenPaths、RecentChanged、Quit)单独路由。
|
||||
|
||||
冲突:每个 match 分支都要先找到窗口;找不到窗口时的行为要定义。实例转发的 OpenPaths 需要 active_window;没有窗口时创建初始窗口。
|
||||
|
||||
处理:阶段 1 给事件加 WindowId,但只创建一个窗口;阶段 2 再加第二个窗口。Todo:为每个事件列 routing 表,避免漏掉一个分支。
|
||||
|
||||
### 2.3 IPC 闭包只绑定一个 session
|
||||
|
||||
现状:src/main.rs:3877 的 IPC handler 捕获 session_for_ipc;save/tab-action/open-local-link/refresh 都默认当前窗口。
|
||||
|
||||
计划:每个 WebView 创建时捕获自己的 window_id + session + last_self_write。
|
||||
|
||||
冲突:wry 的 IPC 回调只给消息,不给窗口;必须在建窗时把 per-window 状态捕获进去。tab-action 的“先保存再切换/关闭”逻辑还要保留。
|
||||
|
||||
处理:阶段 1 先按 per-window 捕获,仍只有一个窗口;阶段 3 验证两个窗口不会串消息。
|
||||
|
||||
### 2.4 关闭矩阵现状不符合新决策
|
||||
|
||||
现状:
|
||||
- CloseTab 只从 session 删除;最后一条被删后 render 空状态,窗口不关。
|
||||
- CloseActiveTab 在没有 active 时直接 ControlFlow::Exit。
|
||||
- CloseRequested 保存并退出进程;Quit 也退出。
|
||||
- Cmd+W 在 JS 里只关闭 active tab;没有 active 时什么也不做。
|
||||
|
||||
新决策:
|
||||
- 非最后窗口关闭最后一个标签 -> 关闭该窗口。
|
||||
- 最后窗口关闭最后一个标签 -> 保留空窗口。
|
||||
- 关闭最后窗口 -> 退出进程。
|
||||
- 源窗口最后一个标签移出 -> 关闭源窗口(新窗口已存在)。
|
||||
- Quit 全局退出;Cmd+Q 仅 macOS。
|
||||
|
||||
冲突:CloseTab 和 CloseActiveTab 需要合并成统一的“关闭标签后检查窗口是否为空”的逻辑;不能再用 ControlFlow::Exit 表示“没有 active tab”。
|
||||
|
||||
处理:抽一个 close_tab_and_maybe_window(window_id, tab_id) 或等价函数;关闭窗口走统一 destroy 流程;Quit 只负责退出所有窗口。第一阶段先不改语义,等阶段 4/5 再改。
|
||||
|
||||
### 2.5 同一文件全局查重不存在
|
||||
|
||||
现状:DocumentSession::open 只在当前 session 内查重(src/session.rs:53);没有跨窗口扫描。
|
||||
|
||||
计划:全局只开一个标签/窗口;重复打开聚焦已有窗口。
|
||||
|
||||
冲突:OpenPaths、detach、LocateTab 都要先扫所有 WindowState;当前只有一份 session,无法实现。
|
||||
|
||||
处理:阶段 3/5 加 find_window_for_path;路径用 normalize_path 比较;Windows 大小写按计划处理。打开失败/已打开只聚焦不重复。
|
||||
|
||||
### 2.6 标签右键菜单与全局右键禁用冲突
|
||||
|
||||
现状:src/main.rs:1562 的 contextmenu 监听器在非编辑态一律 preventDefault;编辑态只有 textarea 允许浏览器菜单。标签栏没有自己的菜单。
|
||||
|
||||
计划:标签右键显示自定义 HTML 菜单;其他区域仍禁用;编辑 textarea 保留原生菜单。
|
||||
|
||||
冲突:现在的全局 preventDefault 会吞掉标签右键;自定义菜单还需要处理定位、点击外部关闭、Escape、滚动关闭。
|
||||
|
||||
处理:阶段 5 在 contextmenu 监听器里先判断 e.target.closest('[data-tab-id]'),是标签才显示菜单并 preventDefault;其余保持原逻辑。菜单项先做“在新窗口打开”,不做拖拽。
|
||||
|
||||
### 2.7 非 active 的 dirty 标签无法直接 detach
|
||||
|
||||
现状:编辑器内容只在 #editor 里;tab.dirty 可能留在非 active 标签;切标签时 requestTabAction('activate') 会把 active 内容写回 active path。
|
||||
|
||||
计划:右键任意标签 -> 在新窗口打开,移动语义。
|
||||
|
||||
风险:如果右键的是非 active 且 dirty 的标签,当前 DOM 只有 active 标签的内容;直接 detach 可能丢失或写错内容。
|
||||
|
||||
建议:第一版 detach 只对 active 标签开放,或者 detach 前先 activate 该标签、等待保存/渲染完成再移动。这个需要确认;不建议在阶段 5 之前猜。
|
||||
|
||||
### 2.8 建立第二个窗口的 API 与 WebContext 生命周期
|
||||
|
||||
现状:WindowBuilder::new().build(&event_loop) 在 run 之前;WebContext 是 main 的局部变量。
|
||||
|
||||
计划:event_loop.run 的第二个参数 EventLoopWindowTarget;WindowBuilder::build(target);WebViewBuilder::with_web_context(&mut web_context)。
|
||||
|
||||
冲突/风险:
|
||||
- WebContext 必须活得比所有 WebView 长;放进 AppState 后,AppState 又包含 WebView,注意 Drop 顺序。
|
||||
- 初始窗口仍可在 run 前创建;第二个窗口必须在 run 回调里用 target 创建。
|
||||
- 每个窗口的 WebView 都加载同一个 build_page 模板;页面内的 tabbar 只显示当前窗口 session。
|
||||
- 新窗口创建失败时,不能移动源标签;pending_detach 要在 Ready 后才提交。
|
||||
|
||||
处理:阶段 2 先只创建“空窗口”,验证 WebContext 和第二个 WebView 能正常显示;阶段 5 再做 detach。
|
||||
|
||||
### 2.9 session 持久化删除的影响
|
||||
|
||||
现状:启动 load;每次 open/activate/close/save 都 persist;session.rs 有 PersistedSession、save、load、roundtrip 测试。
|
||||
|
||||
计划:不恢复标签;只保留 recent;删除 load/save/PersistedSession/session_path/persist_session;session.rs 只留标签模型。
|
||||
|
||||
冲突:
|
||||
- main.rs:3786 的初始 session 要改为空 + CLI 路径。
|
||||
- 所有 persist_session 调用点要删。
|
||||
- session.rs 的 roundtrip 测试删除;测试数 52 -> 51。
|
||||
- 旧 session.json 不主动删除;只是不读不写。
|
||||
- 初次启动标题从 active tab 推导,空 session 时显示 MD Preview。
|
||||
|
||||
处理:阶段 4 单独做,避免和 AppState 重构混在一起。
|
||||
|
||||
### 2.10 窗口几何/标题/主题
|
||||
|
||||
现状:window.geom 单文件;load_window_geom/save_window_geom;标题由 active tab 决定;主题是全局配置。
|
||||
|
||||
计划:新窗口 +28,+28 偏移,clamp 可见;不恢复每个窗口位置;标题按窗口 active tab;主题仍全局。
|
||||
|
||||
冲突:save_window_geom 只能在初始/主窗口关闭时保存,不能每个窗口都覆盖。需要区分“主窗口几何”和“临时新窗口”。第一版可保留主窗口几何,新窗口不保存。
|
||||
|
||||
### 2.11 16 窗口上限
|
||||
|
||||
现状:没有上限。
|
||||
|
||||
计划:16 窗口上限,超限提示。
|
||||
|
||||
处理:阶段 2/5 在创建窗口前检查 windows.len();失败不移动标签。提示文案需要中英文 Strings 增加一项。
|
||||
|
||||
### 2.12 测试与验收
|
||||
|
||||
现状:52 tests;session 持久化测试 1 个;没有多窗口测试。
|
||||
|
||||
计划新增:
|
||||
- DocumentSession 移动标签/空 session 的单元测试;
|
||||
- 全局查重(多个 session 的路径比较)测试;
|
||||
- 关闭矩阵测试(用纯函数抽出来,不启动 GUI);
|
||||
- 标签右键菜单/JS 字符串断言;
|
||||
- 手工验收:两个窗口、焦点、关闭、detach、16 上限、dirty、只读、recent、缩放。
|
||||
|
||||
注意:GUI 多窗口无法用现有 cargo test 覆盖,必须保留手工验收清单。
|
||||
|
||||
## 3. 用户可感知变化(复核版)
|
||||
|
||||
- 启动不再恢复上次标签,只显示 recent;active tab 不保存。
|
||||
- 双击 .md:已有进程 -> active 窗口;文件已打开 -> 聚焦已有窗口/标签;不会重复开。
|
||||
- 标签右键 -> “在新窗口打开”;源窗口最后一个标签移出后源窗口关闭;新窗口偏移 +28,+28。
|
||||
- 非最后窗口关闭最后一个标签 -> 关闭该窗口;最后窗口关闭最后一个标签 -> 保留空窗口;关闭最后窗口 -> 退出。
|
||||
- 16 窗口上限,超出提示。
|
||||
- 缩放/查找/折叠/编辑/保存按窗口独立;zoom.txt 仍共享,但其他窗口不实时同步。
|
||||
- 窗口位置不逐窗恢复;主窗口几何保留。
|
||||
- 单进程崩溃影响所有窗口(接受)。
|
||||
- Cmd+Q 仅 macOS;Windows 没有 Cmd+Q。
|
||||
|
||||
## 4. 建议施工顺序(确认后)
|
||||
|
||||
阶段 1:AppState/WindowState + UserEvent 窗口标识 + per-window 状态,仍一个窗口,行为不变。单独 commit。
|
||||
阶段 2:运行中创建第二个空窗口;共享 WebContext;16 上限;窗口焦点/标题。
|
||||
阶段 3:IPC/事件按窗口路由;全局查重;同一文件聚焦。
|
||||
阶段 4:移除 session 恢复/持久化;recent-only;删旧测试,补新测试。
|
||||
阶段 5:标签右键菜单 + detach 移动 + 源窗口关闭;决定非 active dirty 标签策略。
|
||||
阶段 6:回归、手工验收、构建、文档、清理;不 push。
|
||||
|
||||
## 5. 需要用户确认的点
|
||||
|
||||
1. 非 active 且 dirty 的标签 detach:第一版是否只允许 active 标签?还是先 activate 再 detach?(建议前者,风险最低)
|
||||
2. Quit 时多个窗口有 dirty:沿用现有“保存 active/提示”还是逐个窗口处理?(建议先沿用现有单窗口语义,阶段 6 再统一)
|
||||
3. 阶段 1 是否接受“只重构、不加功能”的单独 commit?(建议接受)
|
||||
4. 主窗口几何保留、新窗口不恢复,是否确认?
|
||||
5. 16 上限提示文案是否用现有中英文 Strings 新增一项?
|
||||
|
||||
以上不阻塞阶段 1;阶段 1 只做等价重构。
|
||||
@@ -101,7 +101,7 @@
|
||||
|
||||
- [ ] 窗口标题 `文件名 — MD Preview`,脏状态显示 `•`
|
||||
- [ ] 工具栏无 Open / Print / Find
|
||||
- [ ] 多标签、关闭、会话恢复、缺失文件重定位
|
||||
- [ ] 多标签、关闭、缺失文件重定位;切回标签保持编辑模式与滚动位置
|
||||
- [ ] 编辑 700ms 自动保存;关闭前落盘
|
||||
- [ ] 外部修改提示与保护
|
||||
- [ ] 查找(含中文输入法组合输入)
|
||||
|
||||
82
agent/reports/multi-process-tabs-feasibility.md
Normal file
82
agent/reports/multi-process-tabs-feasibility.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# 多进程标签窗口方案可行性评估
|
||||
|
||||
评估对象:MD Preview(Windows,Rust + tao/wry/WebView2)从单窗口单 WebView 迁移到多进程标签窗口。仅基于方案文本评估,未读取实现、未运行构建或测试。
|
||||
|
||||
## 结论
|
||||
|
||||
- **No-go(按当前方案)**:端口扫描与握手本身可行,但“取最低有效响应”、16 上限竞态、startup.lock 作用域、detach 单阶段提交和多进程共享 WebView2 数据目录存在结构性缺口,直接实现大概率出现重复窗口、标签丢失或启动卡死。
|
||||
- **推荐先做单进程多窗口**:同一进程内多个 tao/wry 窗口,共享标签模型,可去掉端口、跨进程锁和 detach 事务,工作量和风险显著更低。
|
||||
- 仅当“窗口级崩溃隔离/进程隔离”是硬需求时,才在完成本报告修订项后 conditional go。
|
||||
|
||||
## 可行性
|
||||
|
||||
- **端口扫描/握手:可行,但发现逻辑要改**。127.0.0.1 + magic/version/config_id/nonce/instance_id 足以做协议识别和防误连;固定 64 端口实现简单。问题是不能“固定顺序取最低端口有效响应”就停止——查重和“查询所有实例”必须枚举全部 64 端口并收集所有 peer;最低端口只用于自身绑定或首选联系节点。串行 64 次连接会拖慢启动,应并行或非阻塞,连接/读取超时要短。
|
||||
- **16 上限与竞态:方案最薄弱处**。两个进程可能同时看到 15 个实例而都启动,仅靠“先扫描再启动”无法防止超限。必须在同一把跨进程准入锁内完成“统计活跃实例 + 预留槽位”,并给预留设置 token/TTL;崩溃或超时后回收。16 个 WebView2 窗口的内存和句柄开销偏大,建议默认上限降到 8,或按可用内存动态拒绝。
|
||||
- **startup.lock:方向对,作用域有死锁风险**。若父进程持锁 spawn 子进程并等待 ready,而子进程启动也要拿同一把锁,会死锁。锁应只覆盖“扫描—查重—决策—预留”,不覆盖子进程完整启动;子进程凭预留 token 绑定端口。锁必须是 OS 文件锁(进程崩溃自动释放),并设置获取超时和明确的失败提示。
|
||||
- **查询聚焦:需要全量 peer 和明确超时语义**。只问最低端口会漏掉其他窗口。路径已打开但聚焦失败时“只提示、不重复打开”是对的;但查询超时应视为“未知”,不能当作未打开而静默新建。多个实例都报告同一路径时,按 instance_id 或打开时间选一个,并记录异常。
|
||||
- **路径规范化:高风险细节**。Windows 大小写不敏感,还存在 \\?\ 前缀、短路径、斜杠方向、UNC/映射盘、symlink/junction、尾随空格和点。打开前统一转绝对规范路径(尽量用 GetFinalPathNameByHandle),比较时大小写不敏感;不存在的文件走词法绝对化。协议、recent 和标签身份都使用规范路径,显示路径另存。
|
||||
- **Windows 聚焦限制:只能 best-effort**。SetForegroundWindow 受前台锁限制,后台进程通常只能闪任务栏。用户操作发起的进程可调用 AllowSetForegroundWindow 授权目标 PID,目标再 restore + SetForegroundWindow;跨虚拟桌面不保证成功。产品文案要接受“已打开但无法自动聚焦”。
|
||||
- **detach ready 事务:单阶段不够**。建议流程:父保存并标记 moving → 隐藏/禁用原标签 → spawn 带 move token 的子进程 → 子进程隐藏加载、绑定端口、发 prepared → 父移除标签并发 commit → 子显示。父崩溃、子崩溃、ready 迟到、绑定失败都要按 token 幂等清理;父进程应使用 Job Object 管理子进程树,避免孤儿 WebView2。
|
||||
- **recent 锁:可行,但必须锁住读改写全过程**。只给写加锁仍会丢更新;应在锁内重读、去重、截断、写临时文件、fsync,再原子替换。Windows 覆盖重命名可能因文件句柄失败,需要短重试。锁等待不能阻塞 UI,失败不应阻断打开文件。
|
||||
- **session 移除:方向正确**。多进程共享 session.json 必然互相覆盖;建议取消全局标签恢复,只保留 recent,不持久化 active tab。如果未来要恢复多窗口,改为 per-instance 文件并清理崩溃残留,不要回到单一 session.json。
|
||||
- **WebView2 数据目录:方案未提,但可能是最大技术风险**。多个进程共用同一 User Data Folder 需要实机验证;并发创建 Environment 可能冲突或锁住配置。备选是每窗口独立 UDF(牺牲共享缓存),或直接采用单进程多窗口。
|
||||
- **代码影响:中高**。instance.rs 要从“单实例锁 + 转发”改为“发现 + 监听 + RPC + 限额 + 预留”;启动层要改 CLI、spawn、Job Object;标签 UI 要加查询、聚焦、moving 态;session 要移除;recent/geom/zoom 要加锁;还要新增路径规范化。
|
||||
|
||||
## 关键风险
|
||||
|
||||
- **P0 启动竞态**:并发双击突破 16 上限,或本应复用窗口却新建多个。
|
||||
- **P0 detach 丢标签/孤儿进程**:父或子在 ready 前后崩溃,原标签已关、新窗口未稳定。
|
||||
- **P0 WebView2 共享 UDF**:并发 Environment 创建失败或 profile 锁冲突,导致窗口打不开。
|
||||
- **P1 路径身份不一致**:大小写、UNC、junction 导致重复打开或聚焦错标签。
|
||||
- **P1 聚焦失败**:Windows 前台锁使“双击即到”不可靠,用户感知为无响应。
|
||||
- **P1 startup.lock 死锁/卡顿**:持锁等待子进程或网络请求。
|
||||
- **P1 配置并发写**:recent、window.geom、zoom 丢失更新或文件损坏。
|
||||
- **P2 端口冲突/安全软件**:固定范围被占用或被拦截;不同版本握手不兼容形成“双实例”。
|
||||
- **P2 资源压力**:16 个 WebView2 进程在低配机上内存、句柄、启动时延不可接受。
|
||||
|
||||
## 流程建议
|
||||
|
||||
1. **默认双击**:获取 startup 锁 → 规范化路径 → 并行扫描全部端口 → 查重 → 已打开则请求聚焦(失败只提示)→ 未打开则选一个健康 peer 发送 open(带 request id 和超时)→ 无 peer 则绑定监听并建窗 → 释放锁。
|
||||
2. **显式新窗口**:在同一把准入锁内统计活跃实例并预留槽位 → spawn 带 new-window token 的子进程 → 子进程绑定并上报 ready → 父确认。子进程必须跳过“加入已有窗口”的默认逻辑,否则会直接退出。
|
||||
3. **detach**:保存成功后才进入 moving;查重必须排除源实例自身;若文件已在第三窗口,停止移动并聚焦,不产生第三份。父进程删除原标签后若已无标签,应关闭源窗口并释放端口。
|
||||
4. **超时/取消**:父进程保留原标签、恢复编辑、kill 子进程树,并按 move token 拒绝迟到消息;子进程在无 commit 时自杀,避免孤儿。
|
||||
5. **锁顺序**:统一为 startup → windows/admission → recent → session,所有锁有上限;网络和文件等待全部放后台任务,UI 只显示进度和取消按钮。
|
||||
|
||||
## 代码区域
|
||||
|
||||
- **src/instance.rs**:替换单实例锁与固定转发,新增 peer 扫描、监听、握手、open/focus/query/detach RPC、16 限额与槽位预留;旧的 instance.json 单实例语义要删除,不能叠加。
|
||||
- **src/main.rs / 启动层**:CLI 参数(文件、--new-window、move token)、startup 锁、子进程 spawn、Job Object、就绪握手、退出清理。
|
||||
- **src/session.rs**:移除全局标签恢复与 active tab 持久化;如保留窗口恢复,改 per-instance 文件。
|
||||
- **标签/窗口 UI 与 WebView bridge**:查询已打开、聚焦指定标签、右键“在新窗口打开”、moving 态、禁用编辑、失败提示。
|
||||
- **配置层**:recent-files.txt、zoom.txt、window.geom 的跨进程锁与原子写;新增路径规范化模块。
|
||||
- **WebView2 初始化**:验证共享 UDF;必要时按窗口创建独立 UDF。
|
||||
|
||||
## 测试建议
|
||||
|
||||
- 并发启动 2/5/17 个双击,验证窗口数、16 上限、槽位回收;杀进程后端口和预留是否释放。
|
||||
- 同时双击同一文件,以及大小写、斜杠、UNC、短路径、junction 变体,验证只开一个并聚焦。
|
||||
- 聚焦失败场景:最小化、其他虚拟桌面、前台锁拒绝;验证不重复打开且有提示。
|
||||
- detach 故障注入:子启动失败、bind 失败、prepared 前崩溃、ready 后崩溃、父等待中关闭、迟到 ready;验证标签、进程、端口清理。
|
||||
- recent 20 进程并发写、写入中断、只读目录;验证无丢失、无损坏。
|
||||
- 端口被占、伪造握手、旧版本、不同 config_id、WebView2 UDF 并发创建。
|
||||
- 16 窗口的内存/句柄/启动时延基准,低配机降级策略。
|
||||
|
||||
## 工作量
|
||||
|
||||
- **多进程方案(含竞态、故障处理和测试)**:约 15–22 人日;只做 happy path 的 MVP 约 8–12 人日,但不建议上线。
|
||||
- **单进程多窗口替代**:约 5–8 人日,风险显著更低。
|
||||
- 主要成本在实例协议、detach 事务、WebView2 验证和并发测试,不在标签 UI。
|
||||
|
||||
## 替代方案
|
||||
|
||||
- **A. 单进程多 tao 窗口/多 WebView(推荐)**:共享标签模型,无需端口、跨进程锁和 detach;聚焦直接可靠。缺点是单进程崩溃影响所有窗口。
|
||||
- **B. 单进程多窗口 + 每窗口独立 WebView2 环境**:需要渲染隔离但不想多进程时的折中。
|
||||
- **C. 保留 TCP,但增加 launcher/registry 进程统一分配窗口**:竞态最简单,但引入主进程,违背“全部平等”。
|
||||
- **D. Named pipe + 命名 mutex 替代端口扫描**:ACL 更好、无端口冲突,但仍比单进程方案复杂,且需要现有 Win32 绑定。
|
||||
- **E. 拖出/拖回/窗口合并维持不做**:先把打开、聚焦、关闭、崩溃恢复主路径做稳。
|
||||
|
||||
## 最终建议
|
||||
|
||||
- 对当前“多进程 + 64 端口 + 单阶段 detach”方案:**No-go,暂不进入实现**。
|
||||
- 优先实现**单进程多窗口**;若必须进程隔离,先满足以下门槛再评审:全量 peer 枚举、统一准入锁 + 槽位租约、两阶段 detach + Job Object、完整路径身份、WebView2 共享 UDF 实测、默认上限降至 8、聚焦失败文案与降级。
|
||||
- 满足门槛后可 conditional go,但预计工作量和回归风险约为单进程方案的 2–3 倍。
|
||||
110
agent/reports/multi-window-review-response-2026-10-28.md
Normal file
110
agent/reports/multi-window-review-response-2026-10-28.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# 多窗口改动独立评审回应与自检
|
||||
|
||||
日期:2026-10-28
|
||||
对应评审对象:`agent/reports/multi-window-update-report-2026-10-28.md`
|
||||
对应修复提交:`f9ccce0` `fix: address multi-window review findings`
|
||||
|
||||
## 1. 独立评审结论
|
||||
|
||||
评审结论:方向可接受,但“需修”;没有必现的丢数据阻断项,但发现 3 个确定性行为/状态缺陷应在替换固定 exe 前修复。
|
||||
|
||||
评审提出的高严重度问题:
|
||||
|
||||
1. `OpenPaths` 没有窗口归属,拖放/多选/新窗口未 ready 时可能进错窗口;
|
||||
2. `DetachTab` 在创建新窗口前就 `activate` 源 session,失败时源 session.active 与编辑器显示脱节,后续 save 可能写错文件;
|
||||
3. `focus_open_tab` 在目标 dirty 时静默早退,调用方仍把后续文件放进该窗口;
|
||||
4. Quit/CloseActiveTab 仍以 active window 为中心;
|
||||
5. dirty 状态有三份副本,保存与移动不是原子状态机。
|
||||
|
||||
中低严重度包括:空窗口路径不可达、多显示器 clamp 只取第一个 monitor、primary 按 HashMap 任意提升、RecentChanged 广播会清空有标签窗口、右键菜单只有鼠标可达等。
|
||||
|
||||
## 2. 我们的复核结果
|
||||
|
||||
确认成立并已修:
|
||||
|
||||
- **H1 成立**:拖放 handler 确实没有把自己的 `window_id` 带进 `OpenPaths`;`OpenPaths` 按 `active_window` 落点,dedupe 命中后还会改写批次 target。
|
||||
- **H2 成立**:`DetachTab` 在 create 前 `activate`,失败路径没有回滚。
|
||||
- **H3 成立**:`focus_open_tab` 早退后调用方仍把 target 改为该窗口;另外目标标签自身 dirty 时也有 reload 风险。
|
||||
- **RecentChanged 问题成立**:对全部窗口广播空预览,会清空有标签窗口。
|
||||
- **普通 CloseTab 语义不完整成立**:非最后窗口关闭最后一个标签不会关闭窗口。
|
||||
|
||||
未在本次修复(保留为已知风险):
|
||||
|
||||
- **H4**:Windows 版没有 Cmd+Q;Quit/CloseActiveTab 的多窗口保存/关闭语义仍不完整。CloseActiveTab 已改为“空窗口且还有其他窗口时关闭该窗口,不退出进程”,但多窗口 Quit 的保存遍历仍未做。
|
||||
- **H5**:dirty 仍是 JS dirty + tab.dirty + ws.dirty 三份,异步保存没有显式状态机。当前主路径通过“先写盘再移动”规避,但设计风险仍在。
|
||||
- 多显示器几何、primary 提升、无键盘菜单、无 GUI 自动化测试仍保留。
|
||||
|
||||
## 3. 本次修复内容
|
||||
|
||||
### 3.1 OpenPaths 窗口归属
|
||||
|
||||
`UserEvent::OpenPaths` 改为:
|
||||
|
||||
```rust
|
||||
OpenPaths(Option<WindowId>, Vec<PathBuf>, bool)
|
||||
```
|
||||
|
||||
- 拖放、导航、IPC 的 open-recent/open-local-link 都带自己的 `window_id`;
|
||||
- 实例转发、Finder/Opened 等系统级入口使用 `None`,落 active window;
|
||||
- 事件循环先确定 target,批次内不再因 dedupe 改写 target;
|
||||
- `pending_launches` 在对应窗口 Ready 后用自己的 id 重发。
|
||||
|
||||
### 3.2 DetachTab 提交顺序
|
||||
|
||||
- 删除了 create 前的 `session.activate(tab_id)`;
|
||||
- 仍保留“inactive 且 dirty 拒绝移动”的守卫;
|
||||
- 新窗口创建成功后才从源 session `detach`;
|
||||
- 创建失败/取消失败不会改变源 session 的 active;
|
||||
- 源 session detach 失败时关闭新窗口并提示。
|
||||
|
||||
### 3.3 focus_open_tab
|
||||
|
||||
- 返回 `bool`;
|
||||
- 目标不是 active 且(源 active dirty 或目标标签自身 dirty)时拒绝切换,不设置 `active_window`、不渲染;
|
||||
- 调用方在拒绝时提示“文件已在其他窗口打开且存在未保存修改”;
|
||||
- 目标 active dirty 时只聚焦、不 reload。
|
||||
|
||||
### 3.4 关闭窗口/标签语义
|
||||
|
||||
- `CloseTab` 删除最后一个标签时:
|
||||
- 还有其他窗口 → 关闭该窗口;
|
||||
- 是最后一个窗口 → 保留空窗口;
|
||||
- `CloseActiveTab` 空窗口且还有其他窗口 → 关闭该窗口,不再退出整个进程;
|
||||
- 关闭最后窗口才退出。
|
||||
|
||||
### 3.5 其他
|
||||
|
||||
- 删除不可达的内部 `new-window` IPC/`NewWindow` 事件/`create_empty_window` 路径;现在窗口只由 detach 产生,减少多余入口。
|
||||
- `RecentChanged` 只对没有标签的窗口更新空预览,不再清空有标签窗口。
|
||||
|
||||
## 4. 验证
|
||||
|
||||
- `cargo test`:52 passed / 0 failed;
|
||||
- 页面测试保留单标签菜单禁用断言;
|
||||
- 手工 CDP:
|
||||
- 两标签 A/B,移动 A 后新窗口 A、源窗口 B;
|
||||
- 关闭源窗口 B 的最后标签 → 源窗口关闭,A 保留;
|
||||
- 关闭最后窗口 A 的最后标签 → 保留空窗口,进程不退出;
|
||||
- 单标签右键菜单 disabled=true;
|
||||
- 之前已验证 dirty 保存后移动。
|
||||
- 未重新构建 release:上一份 release 构建在 `f9ccce0` 之前,不能作为最终发布产物。
|
||||
- 固定 exe 未替换。
|
||||
|
||||
## 5. 当前成果自述
|
||||
|
||||
改动方向合理:单进程多窗口 + 共享 WebContext + 全局唯一 + recent-only,对当前规模是更稳的取舍;没有引入端口、注册表、外部注册文件或新依赖。
|
||||
|
||||
代码质量目前属于“可继续开发、但还不能直接发布”:核心主路径(保存后移动、源窗口关闭、最后窗口保留、同文件聚焦)已经可用;H1/H2/H3、RecentChanged、CloseTab 语义已修。剩余主要风险是 Quit 的多窗口保存遍历、dirty 状态机、多显示器几何和无 GUI 自动化测试。
|
||||
|
||||
在替换固定 exe 前,至少应:
|
||||
|
||||
1. 重新跑 `cargo test` 和 release 构建;
|
||||
2. 回归 dirty detach、非 active 标签、最后窗口关闭、同文件聚焦;
|
||||
3. 决定 Quit 多窗口 dirty 的行为;
|
||||
4. 再做固定 exe/Release 部署。
|
||||
|
||||
## 6. 评审建议的接受情况
|
||||
|
||||
- 接受并修复:H1、H2、H3、RecentChanged、CloseTab/CloseActiveTab 空窗口语义、不可达 new-window 路径。
|
||||
- 接受但暂缓:H4(Windows 不可达,需产品决定)、H5(状态机重构,风险大,建议单独阶段)、多显示器几何、键盘菜单、GUI 自动化。
|
||||
- 不接受为“必须现在修”:把全部 dirty 状态改造成显式状态机;当前主路径已用保存后移动规避,强行改造会扩大回归面。
|
||||
218
agent/reports/multi-window-update-report-2026-10-28.md
Normal file
218
agent/reports/multi-window-update-report-2026-10-28.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# MD Preview 单进程多窗口改动评估包
|
||||
|
||||
日期:2026-10-28
|
||||
评估对象:`src/main.rs`、`src/session.rs` 及相关设计文档
|
||||
当前状态:代码已在本地提交,未 push;固定 exe 尚未替换,仍是 v1.4.2-local.2。
|
||||
审查后状态:本报告是独立评审时的快照;评审发现的问题及修复见 agent/reports/multi-window-review-response-2026-10-28.md。
|
||||
|
||||
## 1. 评估边界
|
||||
|
||||
这是一份独立改动报告,只包含:
|
||||
|
||||
- 改动的前因后果;
|
||||
- 必要的设计理由;
|
||||
- 当前源码位置;
|
||||
- 已知限制和需要评估的问题。
|
||||
|
||||
不包含对话记录、用户个人环境或发布凭据。评估者应以源码和本报告为准,不依赖其他上下文。
|
||||
|
||||
## 2. 项目背景
|
||||
|
||||
MD Preview 是一个 Windows 本地 Markdown 预览器/编辑器:
|
||||
|
||||
- Rust + tao 0.33 + wry 0.50 + WebView2;
|
||||
- 完全离线,无自动更新、无遥测;
|
||||
- 默认 .md 打开方式指向固定 exe:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`;
|
||||
- 改动前是一个进程、一个原生窗口、一个 WebView2,页面内用自定义标签栏承载多个文档;
|
||||
- 标签状态由 `DocumentSession` 保存,启动时恢复 `session.json`;
|
||||
- 已有功能:Ctrl+滚轮缩放、代码块深色、标题折叠、单换行按换行显示、只读/保存失败保护。
|
||||
|
||||
## 3. 改动目标
|
||||
|
||||
引入多窗口能力,同时避免多进程方案的复杂度:
|
||||
|
||||
1. 一个进程内可以打开多个原生窗口;
|
||||
2. 每个窗口有自己的 WebView2、标签、编辑状态;
|
||||
3. 标签右键“在新窗口打开”,移动语义,不做拖拽/拖回;
|
||||
4. 同一文件全局只允许打开一次,重复打开聚焦已有窗口/标签;
|
||||
5. 取消启动时恢复标签,只保留最近文件;
|
||||
6. 保持离线、不新增依赖、不引入端口/注册表/外部注册文件;
|
||||
7. 第一版不做窗口合并、不做跨窗口同步编辑、不做拖出/拖回。
|
||||
|
||||
## 4. Git 改动序列
|
||||
|
||||
以下提交位于 `bbfc4cf`(v1.4.2-local.2 文档)之后:
|
||||
|
||||
| 提交 | 类型 | 目的 |
|
||||
|---|---|---|
|
||||
| `625ffdb` | docs | 记录单进程多窗口设计、方案对比、实施计划、复核报告 |
|
||||
| `7d4091d` | refactor | 阶段 1:引入 AppState/WindowState,事件携带 WindowId,IPC/事件按窗口路由;仍只有一个窗口,行为不变 |
|
||||
| `39deeac` | feat | 阶段 2:抽出 build_webview 工厂;共享 WebContext;运行中创建额外空窗口;焦点、16 上限、单窗口关闭不退出整个进程 |
|
||||
| `e24733a` | feat | 阶段 3/4:跨窗口同文件查重与聚焦;删除 session 读写,启动只保留 recent |
|
||||
| `5740274` | feat | 阶段 5:标签右键菜单“在新窗口打开”;先保存再移动;源窗口空则关闭 |
|
||||
| `85b20ec` | fix | 唯一标签时禁用“在新窗口打开” |
|
||||
| `593dc29` `bab8e96` `55d7848` `fe32d6f` `5f08b71` | docs | 各阶段状态记录 |
|
||||
|
||||
累计源码差异约:
|
||||
|
||||
- `src/main.rs`:约 1310 行变动;
|
||||
- `src/session.rs`:约 121 行变动;
|
||||
- 设计/状态文档:约 1800 行新增。
|
||||
|
||||
## 5. 变更后的行为
|
||||
|
||||
### 5.1 用户可见
|
||||
|
||||
- 启动不再恢复上次标签;只显示最近文件。
|
||||
- 标签右键出现自定义菜单“在新窗口打开” / “Open in New Window”。
|
||||
- 只有 1 个标签时该菜单项置灰禁用;2 个及以上才可点。
|
||||
- 点击后:
|
||||
- 目标标签移动到新窗口,新窗口只含这个标签;
|
||||
- 源窗口如果还有标签,继续保留并显示剩余活动标签;
|
||||
- 源窗口如果只剩这个标签,源窗口关闭;
|
||||
- 新窗口相对源窗口偏移 +28,+28,并 clamp 到可见区域。
|
||||
- 目标标签是当前标签且有未保存修改:JS 在 `tab-action` 消息中附带编辑器内容,Rust 先写盘,再移动。
|
||||
- 目标标签不是当前标签且 dirty:拒绝移动并提示,避免丢失编辑器内容。
|
||||
- 目标标签不是当前标签且 clean:先在源 session 中 activate,再移动。
|
||||
- 关闭单个窗口不再退出整个进程;关闭最后一个窗口才退出。
|
||||
- 同一文件重复打开不新增标签/窗口,而是聚焦已有窗口和标签。
|
||||
- 普通“关闭标签”仍保持旧行为:最后一条标签删掉后显示空窗口,不会自动关闭非最后窗口;这一点尚未按此前产品决策实现,是本轮已知缺口。
|
||||
|
||||
### 5.2 内部结构
|
||||
|
||||
`AppState`:
|
||||
|
||||
- `windows: HashMap<WindowId, WindowState>`;
|
||||
- `active_window`;
|
||||
- `recent_files`;
|
||||
- `strings`;
|
||||
- `web_context: WebContext`(共享,字段顺序保证在 WebView 之后释放)。
|
||||
|
||||
`WindowState`:
|
||||
|
||||
- `webview` / `window`(WebView 先声明,保证先于原生窗口释放);
|
||||
- 每窗口 `Arc<Mutex<DocumentSession>>`;
|
||||
- 每窗口 `last_self_write`、`watcher`、`enhance_flags`、`loaded_enhancers`;
|
||||
- 每窗口 `page_ready`、`pending_launches`、`pending_close`、外部变化提示、`dirty`、`is_primary`。
|
||||
|
||||
`UserEvent` 的窗口相关事件携带 `WindowId`;IPC 在建 WebView 时捕获窗口 id、session Arc、last_self_write、recent 列表。
|
||||
|
||||
## 6. 关键设计决定与理由
|
||||
|
||||
### 6.1 单进程多窗口,而不是多进程
|
||||
|
||||
曾评估多进程方案:每个窗口一个进程,通过本机 TCP/端口扫描/注册表发现彼此。最终放弃,原因:
|
||||
|
||||
- Windows 桌面应用没有天然的跨进程窗口合并;
|
||||
- 端口扫描、握手、注册表、启动锁、子进程生命周期、WebView2 多 UDF 都会引入新的失败面;
|
||||
- 单进程内窗口创建、查重、聚焦、计数都是内存操作;
|
||||
- 共享一个 WebContext 可以避免多进程 WebView2 数据目录问题;
|
||||
- 代价是崩溃影响所有窗口,接受。
|
||||
|
||||
### 6.2 取消 session 恢复
|
||||
|
||||
多窗口下“哪个窗口拥有 session、active tab 属于谁、重启如何还原”会显著复杂化。第一版选择:
|
||||
|
||||
- 不恢复标签;
|
||||
- 只保留 recent-files.txt;
|
||||
- 旧 session.json 不读、不写、不主动删除。
|
||||
|
||||
### 6.3 同一文件全局唯一
|
||||
|
||||
编辑状态没有跨窗口同步;两个窗口打开同一文件会互相覆盖。因此第一版全局只允许一份,重复打开只聚焦。
|
||||
|
||||
### 6.4 保存后移动
|
||||
|
||||
移动标签前必须确保磁盘内容是最新的:
|
||||
|
||||
- active dirty:JS 附带内容,Rust 写盘成功后才移动;
|
||||
- inactive dirty:拒绝移动;
|
||||
- inactive clean:activate 后移动。
|
||||
|
||||
### 6.5 关闭语义
|
||||
|
||||
- 关闭一个非最后窗口:不影响其他窗口;
|
||||
- 关闭最后窗口:进程退出;
|
||||
- detach 导致源窗口空:关闭源窗口;
|
||||
- 既有的“普通关闭标签在非最后窗口应关闭窗口”尚未实现,见风险。
|
||||
|
||||
## 7. 源码入口
|
||||
|
||||
- `src/main.rs`
|
||||
- `UserEvent`、`WindowState`、`AppState`(文件顶部);
|
||||
- `build_webview`:统一 WebView 构建,含 IPC、导航、拖放;
|
||||
- `secondary_geom` / `create_window_with_session` / `create_empty_window` / `close_window`;
|
||||
- `find_open_path` / `focus_open_tab`:跨窗口查重与聚焦;
|
||||
- 事件循环中的 `DetachTab` 分支;
|
||||
- `build_page` 内的标签右键菜单 HTML/CSS/JS;
|
||||
- `Strings` 的中英文菜单文案。
|
||||
- `src/session.rs`
|
||||
- `DocumentSession::with_tab`、`detach`;
|
||||
- 删除 `PersistedSession`、`load`、`save`;
|
||||
- 保留路径 normalize/strip_verbatim。
|
||||
- `agent/docs/design-single-process-multi-window.md`:设计。
|
||||
- `agent/docs/implementation-plan-single-process-multi-window.md`:实施计划。
|
||||
- `agent/docs/review-single-process-multi-window.md`:实施前复核。
|
||||
|
||||
## 8. 验证情况
|
||||
|
||||
- `cargo test`:52 passed / 0 failed。
|
||||
- 新增测试:`detaching_a_tab_keeps_source_and_adopts_it_in_new_session`;
|
||||
- 页面测试新增:标签菜单标记、单标签禁用条件;
|
||||
- 手工/CDP 验证:
|
||||
- 单标签右键菜单 disabled=true;
|
||||
- 两标签 A/B,移动 A 后源窗口保留 B,新窗口只含 A;
|
||||
- 唯一标签移动后源窗口关闭;
|
||||
- active dirty 编辑后立即移动,文件内容写入且新窗口预览正确;
|
||||
- debug 构建可通过 CDP 多 target 验证两个 WebView。
|
||||
- 已知警告:5 个 macOS-only `UserEvent` 变体从未构造。
|
||||
- 构建:
|
||||
- debug exe 9,838,080 字节,Windows Console subsystem;
|
||||
- release exe 5,501,440 字节,Windows GUI subsystem,无 cmd 窗口;
|
||||
- 固定 exe 尚未替换。
|
||||
|
||||
## 9. 已知缺口 / 风险
|
||||
|
||||
1. **普通关闭标签的窗口语义尚未按产品决策实现**
|
||||
当前 `CloseTab` 删掉最后一个标签后只显示空窗口,不会关闭非最后窗口;最后窗口保留空窗口的语义也未统一。需要单独修。
|
||||
|
||||
2. **多窗口 GUI 缺少自动化测试**
|
||||
cargo test 覆盖 session/页面字符串/纯逻辑;窗口生命周期、IPC 路由、焦点、detach 主要靠 CDP 手工验证。
|
||||
|
||||
3. **非 active dirty 标签的 detach 被拒绝**
|
||||
这是有意的保守行为,但用户可能觉得“为什么不能移动”;需要产品上确认是否要支持先激活并保存。
|
||||
|
||||
4. **主窗口几何/primary 的简化**
|
||||
`is_primary` 只用于决定是否写窗口几何;主窗口关闭后从 HashMap 任取一个窗口提升为 primary,没有窗口顺序。多显示器/窗口恢复不完整。
|
||||
|
||||
5. **Quit / CloseActiveTab 的多窗口语义仍不完整**
|
||||
`Quit` 仍只处理 active window;`CloseActiveTab` 空窗口时可能直接退出。Cmd+Q 只在 macOS 分支,Windows 不涉及。
|
||||
|
||||
6. **session 删除但旧文件保留**
|
||||
旧 `session.json` 不读不写,用户可能误以为还能恢复;文档已说明,但产品上可能需要清理/迁移提示。
|
||||
|
||||
7. **detach 的失败/竞态路径未全部覆盖**
|
||||
新窗口创建成功后源标签移除失败、窗口创建中途失败、保存写入与 FileSaved 事件顺序等,代码有兜底但缺少压力测试。
|
||||
|
||||
8. **右键菜单可用性**
|
||||
只有一项;菜单定位、键盘操作、屏幕边缘、暗色主题已验证基础,但没有完整无障碍/多显示器测试。
|
||||
|
||||
## 10. 请评估者重点回答
|
||||
|
||||
1. 这次改动的方向(单进程多窗口 + recent-only + 全局唯一文件)是否合理?是否有更简单或更稳的替代方案?
|
||||
2. `AppState` / `WindowState` 的所有权、生命周期、释放顺序是否可靠?有无悬垂/泄漏/死锁风险?
|
||||
3. `build_webview` 抽取、共享 `WebContext`、多 WebView 的做法是否正确?
|
||||
4. `DetachTab` 的“先保存再移动”是否完整?active/inactive dirty、FileSaved 顺序、失败回滚是否有漏洞?
|
||||
5. `find_open_path` / `focus_open_tab` 的全局查重和焦点切换是否可能丢编辑、死锁或错误激活?
|
||||
6. 删除 session 恢复是否留下了隐性回归?recent 的行为是否足够?
|
||||
7. 现有测试是否覆盖关键风险?建议补哪些最小测试?
|
||||
8. 用户感知变化是否合理?有没有“看起来能用但实际会丢数据”的边缘情况?
|
||||
|
||||
## 11. 复现/构建
|
||||
|
||||
- 工作区:`D:\Scripts\md-preview`
|
||||
- 测试:`cargo test`(TEMP/TMP 指到 `target\test-tmp`)
|
||||
- debug:`cargo build` → `target\debug\md-preview.exe`
|
||||
- release:`cargo build --release` → `target\release\md-preview.exe`
|
||||
- 隔离验证:设置 `MD_PREVIEW_CONFIG_DIR` 到工作区内临时目录,设置 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=PORT`,通过 CDP 操作页面。
|
||||
- 不要修改固定 exe 或工作区外文件;不要 push。
|
||||
@@ -1,14 +1,13 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
MD Preview 发布构建脚本
|
||||
固定产物:D:\Scripts\md-preview\MD-Preview-windows-x64.exe
|
||||
|
||||
运行环境:普通 PowerShell(Medium),或 DSH 的 danger-full-access。
|
||||
workspace-write 是 Low 完整性级别,写不动本目录(EPERM / os error 5)。
|
||||
MD Preview 开发构建(DSH workspace-write / Low 完整性可运行)
|
||||
- cargo test + cargo build --release
|
||||
- 只做校验,不复制到任何固定 exe 路径
|
||||
- 产物:target\release\md-preview.exe(Low)
|
||||
- 发布:用户在自己的普通 PowerShell 里运行 agent\scripts\publish.ps1
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputPath = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||
[switch]$SkipTests
|
||||
)
|
||||
|
||||
@@ -16,7 +15,7 @@ $ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
# 工作区规则(agent/AGENTS.md):构建/测试的临时文件也留在 target\ 下,不污染 %TEMP%。
|
||||
# 工作区规则(agent/AGENTS.md):临时文件留在 target\ 下,不污染 %TEMP%。
|
||||
$tmpRoot = Join-Path $repoRoot 'target\tmp'
|
||||
New-Item -ItemType Directory -Force $tmpRoot | Out-Null
|
||||
$env:TEMP = $tmpRoot
|
||||
@@ -29,53 +28,53 @@ if (-not (Test-Path $cargo)) {
|
||||
|
||||
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
||||
|
||||
function Assert-TargetNotRunning([string]$path) {
|
||||
$ids = @()
|
||||
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$pPath = $null
|
||||
try { $pPath = $p.Path } catch { }
|
||||
if ($pPath -eq $path) { $ids += $p.Id }
|
||||
function Invoke-Cargo([string[]]$arguments) {
|
||||
$previous = $ErrorActionPreference
|
||||
$code = 0
|
||||
try {
|
||||
# cargo 把进度/警告写到 stderr;Stop 会把它们当成终止错误
|
||||
$ErrorActionPreference = 'Continue'
|
||||
& $cargo @arguments
|
||||
$code = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if ($ids.Count -gt 0) {
|
||||
throw ('MD Preview 正在运行(PID ' + ($ids -join ', ') + '),请先关闭窗口再构建。')
|
||||
if ($code -ne 0) {
|
||||
throw ('cargo ' + ($arguments -join ' ') + ' failed with exit code ' + $code)
|
||||
}
|
||||
}
|
||||
|
||||
Assert-TargetNotRunning $OutputPath
|
||||
$built = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||
|
||||
$running = @()
|
||||
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$path = $null
|
||||
try { $path = $process.Path } catch { }
|
||||
if ($path -eq $built) { $running += [string]$process.Id }
|
||||
}
|
||||
if ($running.Count -gt 0) {
|
||||
throw ('开发版 MD Preview 正在运行(PID ' + ($running -join ', ') + '),请先关闭。')
|
||||
}
|
||||
|
||||
if (-not $SkipTests) {
|
||||
Step 'cargo test'
|
||||
& $cargo test
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
||||
Invoke-Cargo @('test')
|
||||
}
|
||||
|
||||
Step 'cargo build --release'
|
||||
& $cargo build --release
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }
|
||||
Invoke-Cargo @('build', '--release')
|
||||
|
||||
$built = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||
if (-not (Test-Path $built)) { throw ('missing build output: ' + $built) }
|
||||
|
||||
Step ('copy -> ' + $OutputPath)
|
||||
$outDir = Split-Path -Parent $OutputPath
|
||||
if (-not (Test-Path $outDir)) { New-Item -ItemType Directory -Path $outDir | Out-Null }
|
||||
Assert-TargetNotRunning $OutputPath
|
||||
try {
|
||||
Copy-Item $built $OutputPath -Force -ErrorAction Stop
|
||||
} catch {
|
||||
throw ('复制失败(目标可能被占用):' + $_.Exception.Message)
|
||||
}
|
||||
|
||||
$info = Get-Item $OutputPath
|
||||
$hash = (Get-FileHash $OutputPath -Algorithm SHA256).Hash
|
||||
Write-Host ('size : {0:N0} bytes' -f $info.Length)
|
||||
Write-Host ('sha256 : ' + $hash)
|
||||
Write-Host ('version : ' + $info.VersionInfo.FileVersion)
|
||||
$info = Get-Item $built
|
||||
$hash = (Get-FileHash $built -Algorithm SHA256).Hash
|
||||
|
||||
Step 'check removed update strings'
|
||||
$bytes = [IO.File]::ReadAllBytes($OutputPath)
|
||||
$bytes = [IO.File]::ReadAllBytes($built)
|
||||
$ascii = [Text.Encoding]::ASCII.GetString($bytes)
|
||||
$forbidden = @('api.github', 'btn-update', 'Check for Updates', 'powershell', 'update-check-result', 'open-url')
|
||||
# Guard the removed updater. 'powershell' used to be on this list, but that word
|
||||
# can legitimately show up in user-facing text; the updater itself needs these.
|
||||
$forbidden = @('api.github', 'btn-update', 'Check for Updates', 'Start-Process', 'Invoke-WebRequest', 'update-check-result', 'open-url')
|
||||
$bad = @()
|
||||
foreach ($needle in $forbidden) {
|
||||
$count = ([regex]::Matches($ascii, [regex]::Escape($needle), 'IgnoreCase')).Count
|
||||
@@ -84,13 +83,14 @@ foreach ($needle in $forbidden) {
|
||||
}
|
||||
if ($bad.Count -gt 0) { throw ('removed features still present: ' + ($bad -join ', ')) }
|
||||
|
||||
Step 'check integrity level'
|
||||
$acl = (icacls $OutputPath | Out-String)
|
||||
if ($acl -match 'Medium Mandatory Level') {
|
||||
Write-Host ' Medium - OK'
|
||||
} else {
|
||||
Write-Warning '不是 Medium:启动时可能报 os error 5,见 agent/docs/HANDOFF.md 第 4 节'
|
||||
}
|
||||
|
||||
Step 'report'
|
||||
$acl = (icacls $built | Out-String)
|
||||
$integrity = 'Unknown'
|
||||
if ($acl -match 'Mandatory Label\\(Low|Medium|High) Mandatory Level') { $integrity = $Matches[1] }
|
||||
Write-Host ('output : ' + $built)
|
||||
Write-Host ('size : {0:N0} bytes' -f $info.Length)
|
||||
Write-Host ('sha256 : ' + $hash)
|
||||
Write-Host ('version : ' + $info.VersionInfo.FileVersion)
|
||||
Write-Host ('integrity : ' + $integrity + ' (workspace-write builds are Low)')
|
||||
Write-Host ''
|
||||
Write-Host ('DONE ' + $OutputPath) -ForegroundColor Green
|
||||
Write-Host 'DONE (build only). Publish: .\agent\scripts\publish.ps1 (normal PowerShell, Medium)' -ForegroundColor Green
|
||||
|
||||
114
agent/scripts/publish.ps1
Normal file
114
agent/scripts/publish.ps1
Normal file
@@ -0,0 +1,114 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
MD Preview 发布(必须由用户在自己的普通 PowerShell / Medium 运行)
|
||||
- 源:target\release\md-preview.exe(Low)
|
||||
- 目标:C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe(Medium)
|
||||
- 校验 SHA256 + Medium,刷新 .md 关联,最后删除旧 exe
|
||||
- 不要从 DSH 的 workspace-write shell 运行
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Source = '',
|
||||
[string]$NutstorePath = 'C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe',
|
||||
[string]$OldExe = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||
[switch]$KeepOldExe
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
if (-not $Source) { $Source = Join-Path $repoRoot 'target\release\md-preview.exe' }
|
||||
|
||||
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
||||
|
||||
function Assert-Medium {
|
||||
$groups = (whoami /groups | Out-String)
|
||||
if ($groups -match 'Low Mandatory Level') {
|
||||
throw '当前是 Low 完整性(DSH 沙箱)。请在自己的普通 PowerShell(Medium)里运行本脚本。'
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-NotRunning([string[]]$paths) {
|
||||
$running = @()
|
||||
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$path = $null
|
||||
try { $path = $process.Path } catch { }
|
||||
if ($path -and ($paths -contains $path)) {
|
||||
$running += ($process.ProcessName + ' (PID ' + $process.Id + '): ' + $path)
|
||||
}
|
||||
}
|
||||
if ($running.Count -gt 0) {
|
||||
throw ('请先关闭 MD Preview:' + [Environment]::NewLine + ($running -join [Environment]::NewLine))
|
||||
}
|
||||
}
|
||||
|
||||
function Get-Integrity([string]$path) {
|
||||
$out = (icacls $path | Out-String)
|
||||
if ($out -match 'Mandatory Label\\(Low|Medium|High) Mandatory Level') { return $Matches[1] }
|
||||
return 'Unknown'
|
||||
}
|
||||
|
||||
function Set-RegistryDefault([string]$path, [string]$value) {
|
||||
if (-not (Test-Path $path)) { New-Item -Path $path -Force | Out-Null }
|
||||
Set-ItemProperty -Path $path -Name '(default)' -Value $value
|
||||
}
|
||||
|
||||
Assert-Medium
|
||||
if (-not (Test-Path -LiteralPath $Source)) {
|
||||
throw ('找不到构建产物:' + $Source + ';先运行 agent\scripts\build.ps1')
|
||||
}
|
||||
|
||||
Assert-NotRunning @($Source, $NutstorePath, $OldExe)
|
||||
|
||||
$sourceHash = (Get-FileHash -LiteralPath $Source -Algorithm SHA256).Hash
|
||||
|
||||
Step ('copy -> ' + $NutstorePath)
|
||||
$nutstoreDir = Split-Path -Parent $NutstorePath
|
||||
if (-not (Test-Path $nutstoreDir)) { New-Item -ItemType Directory -Path $nutstoreDir -Force | Out-Null }
|
||||
Copy-Item -LiteralPath $Source -Destination $NutstorePath -Force -ErrorAction Stop
|
||||
|
||||
Step 'set Nutstore exe integrity -> Medium'
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
icacls $NutstorePath /setintegritylevel Medium | Out-Null
|
||||
$icaclsCode = $LASTEXITCODE
|
||||
$ErrorActionPreference = $previous
|
||||
if ($icaclsCode -ne 0) { throw ('icacls failed with exit code ' + $icaclsCode) }
|
||||
|
||||
$integrity = Get-Integrity $NutstorePath
|
||||
if ($integrity -ne 'Medium') { throw ('完整性级别不是 Medium:' + $integrity) }
|
||||
|
||||
$targetHash = (Get-FileHash -LiteralPath $NutstorePath -Algorithm SHA256).Hash
|
||||
if ($sourceHash -ne $targetHash) {
|
||||
throw ('SHA256 不一致:source=' + $sourceHash + ' target=' + $targetHash)
|
||||
}
|
||||
|
||||
Step 'refresh .md association -> Nutstore'
|
||||
$progid = 'MDPreview.md'
|
||||
$command = '"' + $NutstorePath + '" "%1"'
|
||||
Set-RegistryDefault ('HKCU:\Software\Classes\' + $progid + '\shell\open\command') $command
|
||||
Set-RegistryDefault ('HKCU:\Software\Classes\' + $progid + '\DefaultIcon') ('"' + $NutstorePath + '",0')
|
||||
Set-RegistryDefault ('HKCU:\Software\Classes\Applications\MD-Preview-windows-x64.exe\shell\open\command') $command
|
||||
|
||||
$actual = (Get-ItemProperty ('HKCU:\Software\Classes\' + $progid + '\shell\open\command')).'(default)'
|
||||
if ($actual -ne $command) { throw ('关联写入失败:' + $actual) }
|
||||
|
||||
$userChoiceKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.md\UserChoiceLatest\ProgId'
|
||||
$userChoice = $null
|
||||
if (Test-Path $userChoiceKey) { $userChoice = (Get-ItemProperty $userChoiceKey).ProgId }
|
||||
if ($userChoice -ne $progid) {
|
||||
Write-Warning ('.md 的 UserChoice ProgId 是 ' + $userChoice + ',不是 ' + $progid + ';请在 设置 -> 默认应用 里选择一次 MD Preview。')
|
||||
}
|
||||
|
||||
if (-not $KeepOldExe -and (Test-Path -LiteralPath $OldExe)) {
|
||||
Step ('delete old exe -> ' + $OldExe)
|
||||
Remove-Item -LiteralPath $OldExe -Force -ErrorAction Stop
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host ('size : {0:N0} bytes' -f (Get-Item -LiteralPath $NutstorePath).Length)
|
||||
Write-Host ('sha256 : ' + $targetHash)
|
||||
Write-Host ('integrity : ' + $integrity)
|
||||
Write-Host ('default : ' + $actual)
|
||||
Write-Host ('old exe : ' + $OldExe)
|
||||
Write-Host 'DONE' -ForegroundColor Green
|
||||
@@ -2,25 +2,46 @@
|
||||
<#
|
||||
MD Preview 冒烟测试
|
||||
cargo test + 关联检查 + 可选隔离启动(不污染真实 %LOCALAPPDATA%)
|
||||
默认测试 Nutstore 发布版;-Dev 测试 target\release 开发版
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Exe = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||
[switch]$Launch
|
||||
[string]$Exe = 'C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe',
|
||||
[switch]$Launch,
|
||||
[switch]$Dev
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
$tmpRoot = Join-Path $repoRoot 'target\tmp'
|
||||
New-Item -ItemType Directory -Force $tmpRoot | Out-Null
|
||||
$env:TEMP = $tmpRoot
|
||||
$env:TMP = $tmpRoot
|
||||
|
||||
$cargo = Join-Path $env:USERPROFILE '.cargo\bin\cargo.exe'
|
||||
if (-not (Test-Path $cargo)) { $cargo = (Get-Command cargo -ErrorAction Stop).Source }
|
||||
|
||||
if (-not (Test-Path $Exe)) { throw ('missing exe: ' + $Exe + ' (先运行 agent/scripts/build.ps1)') }
|
||||
if ($Dev) {
|
||||
$Exe = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||
if (-not $env:MD_PREVIEW_CONFIG_DIR) {
|
||||
$env:MD_PREVIEW_CONFIG_DIR = Join-Path $repoRoot 'target\smoke'
|
||||
New-Item -ItemType Directory -Force $env:MD_PREVIEW_CONFIG_DIR | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Exe)) {
|
||||
throw ('missing exe: ' + $Exe + '(先运行 agent/scripts/build.ps1,或先发布)')
|
||||
}
|
||||
|
||||
Write-Host '==> cargo test' -ForegroundColor Cyan
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
& $cargo test
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
||||
$code = $LASTEXITCODE
|
||||
$ErrorActionPreference = $previous
|
||||
if ($code -ne 0) { throw 'cargo test failed' }
|
||||
|
||||
Write-Host '==> --help' -ForegroundColor Cyan
|
||||
$help = (& $Exe --help 2>&1 | Out-String)
|
||||
@@ -30,20 +51,24 @@ if ($help -match 'MD Preview') {
|
||||
Write-Warning '--help 无输出(GUI 子系统在部分终端下不回显,可忽略)'
|
||||
}
|
||||
|
||||
Write-Host '==> registry association' -ForegroundColor Cyan
|
||||
$reg = Get-ItemProperty 'HKCU:\Software\Classes\MDPreview.md\shell\open\command' -ErrorAction SilentlyContinue
|
||||
$expected = '"' + $Exe + '" "%1"'
|
||||
if ($null -eq $reg) {
|
||||
Write-Warning 'ProgID 未注册(先运行一次 exe)'
|
||||
} elseif ($reg.'(default)' -ne $expected) {
|
||||
Write-Warning ('ProgID 指向不一致: ' + $reg.'(default)')
|
||||
if ($Dev) {
|
||||
Write-Host '==> registry association (skipped: Low build cannot write HKCU)' -ForegroundColor Cyan
|
||||
} else {
|
||||
Write-Host '==> registry association' -ForegroundColor Cyan
|
||||
$reg = Get-ItemProperty 'HKCU:\Software\Classes\MDPreview.md\shell\open\command' -ErrorAction SilentlyContinue
|
||||
$expected = '"' + $Exe + '" "%1"'
|
||||
if ($null -eq $reg) {
|
||||
Write-Warning 'ProgID 未注册(先运行一次 exe)'
|
||||
} elseif ($reg.'(default)' -ne $expected) {
|
||||
Write-Warning ('ProgID 指向不一致: ' + $reg.'(default)')
|
||||
} else {
|
||||
Write-Host ' OK'
|
||||
}
|
||||
}
|
||||
|
||||
if ($Launch) {
|
||||
Write-Host '==> launch with isolated config' -ForegroundColor Cyan
|
||||
$config = Join-Path $env:TEMP ('mdp-smoke-' + [guid]::NewGuid().ToString('N'))
|
||||
$config = Join-Path $tmpRoot ('mdp-smoke-' + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $config | Out-Null
|
||||
$fixture = Join-Path $PSScriptRoot 'fixtures\long-headings.md'
|
||||
$env:MD_PREVIEW_CONFIG_DIR = $config
|
||||
|
||||
11
agent/tests/ui-smoke.cmd
Normal file
11
agent/tests/ui-smoke.cmd
Normal file
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
setlocal
|
||||
rem Double-clickable wrapper: Windows PowerShell may refuse unsigned .ps1 files
|
||||
rem (AllSigned policy). This runs the script with a process-scoped Bypass.
|
||||
set "SCRIPT=%~dp0ui-smoke.ps1"
|
||||
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %*
|
||||
set "CODE=%ERRORLEVEL%"
|
||||
if not "%CODE%"=="0" echo.&echo UI smoke exited with code %CODE%.
|
||||
rem Keep the window open when launched without arguments (double-click).
|
||||
if "%~1"=="" pause
|
||||
exit /b %CODE%
|
||||
206
agent/tests/ui-smoke.mjs
Normal file
206
agent/tests/ui-smoke.mjs
Normal file
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env node
|
||||
// Pre-release UI check for MD Preview.
|
||||
//
|
||||
// The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
|
||||
// it. Run this from a normal desktop shell via ui-smoke.ps1: it talks to the
|
||||
// already-running app over the DevTools protocol and writes a JSON report plus
|
||||
// a screenshot under --out.
|
||||
//
|
||||
// Usage: node ui-smoke.mjs --port 9333 --out target/ui-test [--expect home|doc]
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { argv, exit } from "node:process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
function parseArgs(list) {
|
||||
const args = {};
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const item = list[i];
|
||||
if (!item.startsWith("--")) continue;
|
||||
const key = item.slice(2);
|
||||
const next = list[i + 1];
|
||||
if (next === undefined || next.startsWith("--")) args[key] = true;
|
||||
else { args[key] = next; i++; }
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
||||
|
||||
async function findPageTarget(port, timeoutMs) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError = "no targets";
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2000) });
|
||||
const targets = await response.json();
|
||||
const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
|
||||
if (page) return page;
|
||||
lastError = `${targets.length} target(s), none is a page`;
|
||||
} catch (error) {
|
||||
lastError = String(error && error.message ? error.message : error);
|
||||
}
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`no page target on port ${port}: ${lastError}`);
|
||||
}
|
||||
|
||||
class Cdp {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.nextId = 1;
|
||||
this.pending = new Map();
|
||||
this.socket = null;
|
||||
}
|
||||
|
||||
async connect(timeoutMs) {
|
||||
const socket = new WebSocket(this.url);
|
||||
this.socket = socket;
|
||||
socket.addEventListener("message", (event) => {
|
||||
let message;
|
||||
try { message = JSON.parse(String(event.data)); } catch { return; }
|
||||
if (message.id && this.pending.has(message.id)) {
|
||||
const { resolve, reject } = this.pending.get(message.id);
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) reject(new Error(`${message.error.code}: ${message.error.message}`));
|
||||
else resolve(message.result);
|
||||
}
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error("CDP connect timed out")), timeoutMs);
|
||||
socket.addEventListener("open", () => { clearTimeout(timer); resolve(); });
|
||||
socket.addEventListener("error", () => { clearTimeout(timer); reject(new Error("CDP socket error")); });
|
||||
});
|
||||
}
|
||||
|
||||
send(method, params = {}, timeoutMs = 10000) {
|
||||
const id = this.nextId++;
|
||||
const payload = JSON.stringify({ id, method, params });
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`CDP timeout: ${method}`));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, {
|
||||
resolve: (value) => { clearTimeout(timer); resolve(value); },
|
||||
reject: (error) => { clearTimeout(timer); reject(error); },
|
||||
});
|
||||
this.socket.send(payload);
|
||||
});
|
||||
}
|
||||
|
||||
async evaluate(expression, timeoutMs = 10000) {
|
||||
const result = await this.send("Runtime.evaluate", {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
userGesture: true,
|
||||
}, timeoutMs);
|
||||
if (result.exceptionDetails) {
|
||||
throw new Error(`page exception: ${result.exceptionDetails.text || "unknown"}`);
|
||||
}
|
||||
return result.result ? result.result.value : undefined;
|
||||
}
|
||||
|
||||
close() {
|
||||
try { this.socket.close(); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
const SNAPSHOT = `(() => {
|
||||
const preview = document.getElementById('preview');
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
return {
|
||||
readyState: document.readyState,
|
||||
bodyClass: document.body.className,
|
||||
previewChildren: preview ? preview.children.length : -1,
|
||||
previewTextLength: preview ? preview.innerText.length : -1,
|
||||
firstHeading: (document.querySelector('#preview h1, #preview h2, #preview h3') || {}).textContent || '',
|
||||
headings: document.querySelectorAll('#preview h1, #preview h2, #preview h3, #preview h4, #preview h5, #preview h6').length,
|
||||
foldToggles: document.querySelectorAll('.mdp-fold-toggle').length,
|
||||
codeBlocks: document.querySelectorAll('#preview pre code').length,
|
||||
highlighted: document.querySelectorAll('#preview pre code.hljs').length,
|
||||
hasIpc: !!(window.ipc && typeof window.ipc.postMessage === 'function'),
|
||||
hasApi: ['__setContent', '__setTabs', '__setPreview', '__setEmptyPreview', '__markSaved']
|
||||
.every((name) => typeof window[name] === 'function'),
|
||||
zoom: style.getPropertyValue('--content-scale').trim(),
|
||||
tabs: document.querySelectorAll('#tabs .tab').length,
|
||||
tabBarVisible: document.body.classList.contains('has-tabs'),
|
||||
findApi: typeof window.__mdPreviewShowFind === 'function',
|
||||
};
|
||||
})()`;
|
||||
|
||||
export async function run(options) {
|
||||
const { port, outDir, expect } = options;
|
||||
const report = {
|
||||
startedAt: new Date().toISOString(),
|
||||
port,
|
||||
expect,
|
||||
checks: [],
|
||||
errors: [],
|
||||
screenshot: null,
|
||||
snapshot: null,
|
||||
};
|
||||
const check = (name, pass, detail) => report.checks.push({ name, pass: !!pass, detail });
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
let cdp;
|
||||
try {
|
||||
const target = await findPageTarget(port, options.waitMs ?? 15000);
|
||||
report.targetUrl = target.url;
|
||||
cdp = new Cdp(target.webSocketDebuggerUrl);
|
||||
await cdp.connect(5000);
|
||||
await cdp.send("Runtime.enable");
|
||||
await cdp.send("Page.enable");
|
||||
|
||||
// Let hljs / katex / mermaid / folding settle after the first paint.
|
||||
await sleep(900);
|
||||
const snapshot = await cdp.evaluate(SNAPSHOT);
|
||||
report.snapshot = snapshot;
|
||||
|
||||
check("page loaded", snapshot && snapshot.readyState === "complete", snapshot && snapshot.readyState);
|
||||
check("preview has content", snapshot && snapshot.previewChildren > 0, snapshot && `${snapshot.previewChildren} child nodes`);
|
||||
check("webview IPC bridge", snapshot && snapshot.hasIpc, "window.ipc.postMessage");
|
||||
check("page API installed", snapshot && snapshot.hasApi, "setContent/setTabs/setPreview");
|
||||
|
||||
if (expect === "doc") {
|
||||
check("headings rendered", snapshot && snapshot.headings > 0, snapshot && `${snapshot.headings} headings`);
|
||||
check("heading fold toggles", snapshot && snapshot.foldToggles > 0, snapshot && `${snapshot.foldToggles} toggles`);
|
||||
check("code blocks highlighted", snapshot && snapshot.codeBlocks > 0 && snapshot.highlighted > 0, snapshot && `${snapshot.highlighted}/${snapshot.codeBlocks} highlighted`);
|
||||
check("preview text is not empty", snapshot && snapshot.previewTextLength > 20, snapshot && `${snapshot.previewTextLength} chars`);
|
||||
} else {
|
||||
check("home page body", snapshot && snapshot.bodyClass.includes("home"), snapshot && snapshot.bodyClass);
|
||||
}
|
||||
|
||||
const shot = await cdp.send("Page.captureScreenshot", { format: "png" }, 15000);
|
||||
if (shot && shot.data) {
|
||||
const file = `${outDir}/ui-smoke.png`;
|
||||
writeFileSync(file, Buffer.from(shot.data, "base64"));
|
||||
report.screenshot = file;
|
||||
} else {
|
||||
report.errors.push("captureScreenshot returned no data");
|
||||
}
|
||||
} catch (error) {
|
||||
report.errors.push(String(error && error.message ? error.message : error));
|
||||
} finally {
|
||||
if (cdp) cdp.close();
|
||||
}
|
||||
|
||||
const failed = report.checks.filter((item) => !item.pass);
|
||||
const ok = failed.length === 0 && report.errors.length === 0;
|
||||
const reportPath = `${outDir}/ui-smoke.json`;
|
||||
writeFileSync(reportPath, JSON.stringify({ ...report, ok }, null, 2));
|
||||
console.log(JSON.stringify({ ok, failed: failed.length, errors: report.errors, report: reportPath, screenshot: report.screenshot }, null, 2));
|
||||
return { ok, report, reportPath };
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
|
||||
const args = parseArgs(argv.slice(2));
|
||||
const port = Number(args.port ?? 9333);
|
||||
const outDir = args.out ?? "target/ui-test";
|
||||
const expect = args.expect ?? "doc";
|
||||
run({ port, outDir, expect })
|
||||
.then(({ ok }) => exit(ok ? 0 : 1))
|
||||
.catch((error) => { console.error(error); exit(2); });
|
||||
}
|
||||
151
agent/tests/ui-smoke.ps1
Normal file
151
agent/tests/ui-smoke.ps1
Normal file
@@ -0,0 +1,151 @@
|
||||
<#
|
||||
MD Preview 发布前 UI 冒烟(需要普通桌面 PowerShell)
|
||||
- 通过 WebView2 的 CDP 端口检查页面是否真的渲染,并截图
|
||||
- 默认使用仓库里的开发构建(Low 完整性,启动时写不了 HKCU,安全)
|
||||
- 不要在 DSH 沙箱里跑:沙箱禁止命名管道,Chromium/WebView2 起不来
|
||||
#>
|
||||
#requires -Version 5.1
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Exe = '',
|
||||
[string]$Fixture = '',
|
||||
[int]$Port = 9333,
|
||||
[ValidateSet('doc', 'home')]
|
||||
[string]$Expect = 'doc',
|
||||
[string]$OutDir = '',
|
||||
[string]$Node = '',
|
||||
[switch]$KeepOpen
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
if (-not $Exe) { $Exe = Join-Path $repoRoot 'target\release\md-preview.exe' }
|
||||
if (-not $Fixture) { $Fixture = Join-Path $repoRoot 'agent\tests\fixtures\code-samples.md' }
|
||||
if (-not $OutDir) { $OutDir = Join-Path $repoRoot 'target\ui-test' }
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Exe)) { throw ('missing exe: ' + $Exe + '(先运行 agent\scripts\build.ps1)') }
|
||||
if (-not (Test-Path -LiteralPath $Fixture)) { throw ('missing fixture: ' + $Fixture) }
|
||||
function Resolve-Node {
|
||||
$command = Get-Command node -ErrorAction SilentlyContinue
|
||||
if ($command) {
|
||||
if ($command.Path) { return $command.Path }
|
||||
if ($command.Source) { return $command.Source }
|
||||
}
|
||||
$candidates = @()
|
||||
if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles 'nodejs\node.exe') }
|
||||
if (${env:ProgramFiles(x86)}) { $candidates += (Join-Path ${env:ProgramFiles(x86)} 'nodejs\node.exe') }
|
||||
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') }
|
||||
foreach ($candidate in $candidates) {
|
||||
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
if ($Node) { $node = $Node } else { $node = Resolve-Node }
|
||||
if (-not $node) {
|
||||
throw 'Node.js 未找到(需要 Node 21+)。用 -Node 指定路径,或安装 Node 后重试。'
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $node)) { throw ('Node 路径无效:' + $node) }
|
||||
& $node -e "process.exit(('WebSocket' in globalThis) ? 0 : 1)" 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { throw ('Node 版本太旧:需要 Node 21+ 的内置 WebSocket(当前 ' + (& $node --version) + ')') }
|
||||
|
||||
New-Item -ItemType Directory -Force $OutDir | Out-Null
|
||||
$configDir = Join-Path $OutDir 'config'
|
||||
$logOut = Join-Path $OutDir 'app.stdout.log'
|
||||
$logErr = Join-Path $OutDir 'app.stderr.log'
|
||||
$reportPath = Join-Path $OutDir 'ui-smoke.json'
|
||||
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
|
||||
Remove-Item -Force $logOut, $logErr, $reportPath, (Join-Path $OutDir 'ui-smoke.png') -ErrorAction SilentlyContinue
|
||||
|
||||
# 单实例:如果目标 exe 已经在跑,新的启动会被转发出去,CDP 端口就不会出现。
|
||||
$exePath = (Resolve-Path -LiteralPath $Exe).Path
|
||||
$running = @()
|
||||
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$path = $null
|
||||
try { $path = $process.Path } catch { }
|
||||
if ($path -and ($path -ieq $exePath)) { $running += [string]$process.Id }
|
||||
}
|
||||
if ($running.Count -gt 0) {
|
||||
throw ('目标 exe 已在运行(PID ' + ($running -join ', ') + '),请先关闭它;否则启动会被单实例转发。')
|
||||
}
|
||||
|
||||
# CDP 就绪探测:TCP 端口可能只开一瞬间(WebView2 起来后立刻退出),
|
||||
# 所以以 /json/list 真正能返回为准。
|
||||
function Test-Cdp([int]$port) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -Uri ('http://127.0.0.1:' + $port + '/json/list') -TimeoutSec 2
|
||||
return ($response.StatusCode -eq 200)
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
$previousConfig = $env:MD_PREVIEW_CONFIG_DIR
|
||||
$previousArgs = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$proc = $null
|
||||
$exitCode = 1
|
||||
try {
|
||||
$env:MD_PREVIEW_CONFIG_DIR = $configDir
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=' + $Port
|
||||
|
||||
Write-Host ('==> launching ' + $exePath) -ForegroundColor Cyan
|
||||
$proc = Start-Process -FilePath $exePath -ArgumentList @('"' + $Fixture + '"') -PassThru -RedirectStandardOutput $logOut -RedirectStandardError $logErr
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(25)
|
||||
$up = $false
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($proc.HasExited) { break }
|
||||
if (Test-Cdp $Port) { $up = $true; break }
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
|
||||
if (-not $up) {
|
||||
Write-Host 'ERROR: CDP 端口没有起来。' -ForegroundColor Red
|
||||
Write-Host ' - 不要在 DSH 沙箱里运行本脚本:沙箱禁止命名管道,Chromium/WebView2 无法启动。'
|
||||
Write-Host ' - 确认没有其它 MD Preview 实例占用同一个配置目录。'
|
||||
if (Test-Path -LiteralPath $logErr) {
|
||||
$err = Get-Content -LiteralPath $logErr -ErrorAction SilentlyContinue | Select-Object -Last 10
|
||||
if ($err) { Write-Host ' app.stderr:'; $err | ForEach-Object { Write-Host (' ' + $_) } }
|
||||
}
|
||||
if ($proc.HasExited) { Write-Host (' app 已退出,exit code ' + $proc.ExitCode) }
|
||||
throw 'CDP port did not open'
|
||||
}
|
||||
|
||||
Write-Host ('==> node agent\tests\ui-smoke.mjs --port ' + $Port + ' --expect ' + $Expect) -ForegroundColor Cyan
|
||||
& $node (Join-Path $repoRoot 'agent\tests\ui-smoke.mjs') --port $Port --out $OutDir --expect $Expect
|
||||
$exitCode = $LASTEXITCODE
|
||||
|
||||
if (Test-Path -LiteralPath $reportPath) {
|
||||
$report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json
|
||||
$failed = @($report.checks | Where-Object { -not $_.pass })
|
||||
if ($report.ok) {
|
||||
Write-Host ('OK: ' + @($report.checks).Count + ' checks') -ForegroundColor Green
|
||||
} else {
|
||||
if ($failed.Count -gt 0) {
|
||||
Write-Host 'FAILED checks:' -ForegroundColor Red
|
||||
$failed | ForEach-Object { Write-Host (' - ' + $_.name + ': ' + $_.detail) -ForegroundColor Red }
|
||||
}
|
||||
if ($report.errors) {
|
||||
Write-Host 'errors:' -ForegroundColor Red
|
||||
$report.errors | ForEach-Object { Write-Host (' - ' + $_) -ForegroundColor Red }
|
||||
}
|
||||
}
|
||||
if ($report.screenshot) { Write-Host ('screenshot: ' + $report.screenshot) }
|
||||
Write-Host ('report : ' + $reportPath)
|
||||
}
|
||||
} finally {
|
||||
if ($proc -and -not $KeepOpen) {
|
||||
try {
|
||||
if (-not $proc.HasExited) {
|
||||
$proc.CloseMainWindow() | Out-Null
|
||||
if (-not $proc.WaitForExit(5000)) { $proc.Kill() }
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
if ($null -eq $previousConfig) { Remove-Item Env:\MD_PREVIEW_CONFIG_DIR -ErrorAction SilentlyContinue } else { $env:MD_PREVIEW_CONFIG_DIR = $previousConfig }
|
||||
if ($null -eq $previousArgs) { Remove-Item Env:\WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS -ErrorAction SilentlyContinue } else { $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $previousArgs }
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
21
assets/codemirror/LICENSE
Normal file
21
assets/codemirror/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (C) 2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
17
assets/codemirror/README.md
Normal file
17
assets/codemirror/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# CodeMirror 5.65.16 (vendored)
|
||||
|
||||
MIT-licensed source editor used only in edit mode. Nothing here is loaded at
|
||||
startup: Rust injects the concatenated bundle the first time the page asks for
|
||||
it (`need-editor` IPC), then calls `window.__mdpOnEditorSource()`.
|
||||
|
||||
Files are the minified builds from the cdnjs 5.65.16 package
|
||||
(`https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/`):
|
||||
|
||||
- `codemirror.min.js`, `codemirror.min.css`
|
||||
- `mode/xml/xml.min.js`, `mode/meta.min.js`, `mode/markdown/markdown.min.js`
|
||||
- `addon/search/searchcursor.min.js`, `addon/search/search.min.js`
|
||||
- `addon/dialog/dialog.min.js`, `addon/dialog/dialog.css`
|
||||
- `addon/fold/foldcode.min.js`, `addon/fold/foldgutter.min.js`, `addon/fold/foldgutter.css`
|
||||
|
||||
See `LICENSE` for the upstream license. Keep this directory offline-only; do
|
||||
not point the page at a CDN.
|
||||
32
assets/codemirror/addon/dialog/dialog.css
vendored
Normal file
32
assets/codemirror/addon/dialog/dialog.css
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
.CodeMirror-dialog {
|
||||
position: absolute;
|
||||
left: 0; right: 0;
|
||||
background: inherit;
|
||||
z-index: 15;
|
||||
padding: .1em .8em;
|
||||
overflow: hidden;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.CodeMirror-dialog-top {
|
||||
border-bottom: 1px solid #eee;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.CodeMirror-dialog-bottom {
|
||||
border-top: 1px solid #eee;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.CodeMirror-dialog input {
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
width: 20em;
|
||||
color: inherit;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.CodeMirror-dialog button {
|
||||
font-size: 70%;
|
||||
}
|
||||
1
assets/codemirror/addon/dialog/dialog.min.js
vendored
Normal file
1
assets/codemirror/addon/dialog/dialog.min.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){function f(e,o,n){var e=e.getWrapperElement(),t=e.appendChild(document.createElement("div"));return t.className=n?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof o?t.innerHTML=o:t.appendChild(o),s.addClass(e,"dialog-opened"),t}function p(e,o){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=o}s.defineExtension("openDialog",function(e,o,n){n=n||{},p(this,null);var t=f(this,e,n.bottom),i=!1,r=this;function u(e){"string"==typeof e?l.value=e:i||(i=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),r.focus(),n.onClose&&n.onClose(t))}var l=t.getElementsByTagName("input")[0];return l?(l.focus(),n.value&&(l.value=n.value,!1!==n.selectValueOnOpen&&l.select()),n.onInput&&s.on(l,"input",function(e){n.onInput(e,l.value,u)}),n.onKeyUp&&s.on(l,"keyup",function(e){n.onKeyUp(e,l.value,u)}),s.on(l,"keydown",function(e){n&&n.onKeyDown&&n.onKeyDown(e,l.value,u)||((27==e.keyCode||!1!==n.closeOnEnter&&13==e.keyCode)&&(l.blur(),s.e_stop(e),u()),13==e.keyCode&&o(l.value,e))}),!1!==n.closeOnBlur&&s.on(t,"focusout",function(e){null!==e.relatedTarget&&u()})):(e=t.getElementsByTagName("button")[0])&&(s.on(e,"click",function(){u(),r.focus()}),!1!==n.closeOnBlur&&s.on(e,"blur",u),e.focus()),u}),s.defineExtension("openConfirm",function(e,o,n){p(this,null);var t=f(this,e,n&&n.bottom),i=t.getElementsByTagName("button"),r=!1,u=this,l=1;function a(){r||(r=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),u.focus())}i[0].focus();for(var c=0;c<i.length;++c){var d=i[c];!function(o){s.on(d,"click",function(e){s.e_preventDefault(e),a(),o&&o(u)})}(o[c]),s.on(d,"blur",function(){--l,setTimeout(function(){l<=0&&a()},200)}),s.on(d,"focus",function(){++l})}}),s.defineExtension("openNotification",function(e,o){p(this,r);var n,t=f(this,e,o&&o.bottom),i=!1,e=o&&void 0!==o.duration?o.duration:5e3;function r(){i||(i=!0,clearTimeout(n),s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t))}return s.on(t,"click",function(e){s.e_preventDefault(e),r()}),e&&(n=setTimeout(r,e)),r})});
|
||||
1
assets/codemirror/addon/fold/foldcode.min.js
vendored
Normal file
1
assets/codemirror/addon/fold/foldcode.min.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
!function(n){"object"==typeof exports&&"object"==typeof module?n(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],n):n(CodeMirror)}(function(c){"use strict";function t(t,i,n,f){n&&n.call?(l=n,n=null):l=a(t,n,"rangeFinder"),"number"==typeof i&&(i=c.Pos(i,0));var l,d=a(t,n,"minFoldSize");function o(n){var o=l(t,i);if(!o||o.to.line-o.from.line<d)return null;if("fold"===f)return o;for(var e=t.findMarksAt(o.from),r=0;r<e.length;++r)if(e[r].__isFold){if(!n)return null;o.cleared=!0,e[r].clear()}return o}var e,r,u=o(!0);if(a(t,n,"scanUp"))for(;!u&&i.line>t.firstLine();)i=c.Pos(i.line-1,0),u=o(!1);u&&!u.cleared&&"unfold"!==f&&(e=function(n,o,e){n=a(n,o,"widget");"function"==typeof n&&(n=n(e.from,e.to));"string"==typeof n?(o=document.createTextNode(n),(n=document.createElement("span")).appendChild(o),n.className="CodeMirror-foldmarker"):n=n&&n.cloneNode(!0);return n}(t,n,u),c.on(e,"mousedown",function(n){r.clear(),c.e_preventDefault(n)}),(r=t.markText(u.from,u.to,{replacedWith:e,clearOnEnter:a(t,n,"clearOnEnter"),__isFold:!0})).on("clear",function(n,o){c.signal(t,"unfold",t,n,o)}),c.signal(t,"fold",t,u.from,u.to))}c.newFoldFunction=function(e,r){return function(n,o){t(n,o,{rangeFinder:e,widget:r})}},c.defineExtension("foldCode",function(n,o,e){t(this,n,o,e)}),c.defineExtension("isFolded",function(n){for(var o=this.findMarksAt(n),e=0;e<o.length;++e)if(o[e].__isFold)return!0}),c.commands.toggleFold=function(n){n.foldCode(n.getCursor())},c.commands.fold=function(n){n.foldCode(n.getCursor(),null,"fold")},c.commands.unfold=function(n){n.foldCode(n.getCursor(),{scanUp:!1},"unfold")},c.commands.foldAll=function(e){e.operation(function(){for(var n=e.firstLine(),o=e.lastLine();n<=o;n++)e.foldCode(c.Pos(n,0),{scanUp:!1},"fold")})},c.commands.unfoldAll=function(e){e.operation(function(){for(var n=e.firstLine(),o=e.lastLine();n<=o;n++)e.foldCode(c.Pos(n,0),{scanUp:!1},"unfold")})},c.registerHelper("fold","combine",function(){var t=Array.prototype.slice.call(arguments,0);return function(n,o){for(var e=0;e<t.length;++e){var r=t[e](n,o);if(r)return r}}}),c.registerHelper("fold","auto",function(n,o){for(var e=n.getHelpers(o,"fold"),r=0;r<e.length;r++){var t=e[r](n,o);if(t)return t}});var r={rangeFinder:c.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};function a(n,o,e){if(o&&void 0!==o[e])return o[e];o=n.options.foldOptions;return(o&&void 0!==o[e]?o:r)[e]}c.defineOption("foldOptions",null),c.defineExtension("foldOption",function(n,o){return a(this,n,o)})});
|
||||
20
assets/codemirror/addon/fold/foldgutter.css
vendored
Normal file
20
assets/codemirror/addon/fold/foldgutter.css
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
.CodeMirror-foldmarker {
|
||||
color: blue;
|
||||
text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
|
||||
font-family: arial;
|
||||
line-height: .3;
|
||||
cursor: pointer;
|
||||
}
|
||||
.CodeMirror-foldgutter {
|
||||
width: .7em;
|
||||
}
|
||||
.CodeMirror-foldgutter-open,
|
||||
.CodeMirror-foldgutter-folded {
|
||||
cursor: pointer;
|
||||
}
|
||||
.CodeMirror-foldgutter-open:after {
|
||||
content: "\25BE";
|
||||
}
|
||||
.CodeMirror-foldgutter-folded:after {
|
||||
content: "\25B8";
|
||||
}
|
||||
1
assets/codemirror/addon/fold/foldgutter.min.js
vendored
Normal file
1
assets/codemirror/addon/fold/foldgutter.min.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("./foldcode")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./foldcode"],t):t(CodeMirror)}(function(n){"use strict";n.defineOption("foldGutter",!1,function(t,o,e){e&&e!=n.Init&&(t.clearGutter(t.state.foldGutter.options.gutter),t.state.foldGutter=null,t.off("gutterClick",d),t.off("changes",u),t.off("viewportChange",l),t.off("fold",m),t.off("unfold",m),t.off("swapDoc",u),t.off("optionChange",a)),o&&(t.state.foldGutter=new r(function(t){!0===t&&(t={});null==t.gutter&&(t.gutter="CodeMirror-foldgutter");null==t.indicatorOpen&&(t.indicatorOpen="CodeMirror-foldgutter-open");null==t.indicatorFolded&&(t.indicatorFolded="CodeMirror-foldgutter-folded");return t}(o)),f(t),t.on("gutterClick",d),t.on("changes",u),t.on("viewportChange",l),t.on("fold",m),t.on("unfold",m),t.on("swapDoc",u),t.on("optionChange",a))});var c=n.Pos;function r(t){this.options=t,this.from=this.to=0}function s(t,o){for(var e=t.findMarks(c(o,0),c(o+1,0)),n=0;n<e.length;++n)if(e[n].__isFold){var r=e[n].find(-1);if(r&&r.line===o)return e[n]}}function p(t){var o;return"string"==typeof t?((o=document.createElement("div")).className=t+" CodeMirror-guttermarker-subtle",o):t.cloneNode(!0)}function i(r,t,o){var i=r.state.foldGutter.options,f=t-1,d=r.foldOption(i,"minFoldSize"),a=r.foldOption(i,"rangeFinder"),u="string"==typeof i.indicatorFolded&&e(i.indicatorFolded),l="string"==typeof i.indicatorOpen&&e(i.indicatorOpen);r.eachLine(t,o,function(t){++f;var o=null,e=(e=t.gutterMarkers)&&e[i.gutter];if(s(r,f)){if(u&&e&&u.test(e.className))return;o=p(i.indicatorFolded)}else{var n=c(f,0),n=a&&a(r,n);if(n&&n.to.line-n.from.line>=d){if(l&&e&&l.test(e.className))return;o=p(i.indicatorOpen)}}(o||e)&&r.setGutterMarker(t,i.gutter,o)})}function e(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}function f(t){var o=t.getViewport(),e=t.state.foldGutter;e&&(t.operation(function(){i(t,o.from,o.to)}),e.from=o.from,e.to=o.to)}function d(t,o,e){var n=t.state.foldGutter;!n||e==(e=n.options).gutter&&((n=s(t,o))?n.clear():t.foldCode(c(o,0),e))}function a(t,o){"mode"==o&&u(t)}function u(t){var o,e=t.state.foldGutter;e&&(o=e.options,e.from=e.to=0,clearTimeout(e.changeUpdate),e.changeUpdate=setTimeout(function(){f(t)},o.foldOnChangeTimeSpan||600))}function l(o){var t,e=o.state.foldGutter;e&&(t=e.options,clearTimeout(e.changeUpdate),e.changeUpdate=setTimeout(function(){var t=o.getViewport();e.from==e.to||20<t.from-e.to||20<e.from-t.to?f(o):o.operation(function(){t.from<e.from&&(i(o,t.from,e.from),e.from=t.from),t.to>e.to&&(i(o,e.to,t.to),e.to=t.to)})},t.updateViewportTimeSpan||400))}function m(t,o){var e=t.state.foldGutter;!e||(o=o.line)>=e.from&&o<e.to&&i(t,o,o+1)}});
|
||||
1
assets/codemirror/addon/search/search.min.js
vendored
Normal file
1
assets/codemirror/addon/search/search.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/addon/search/searchcursor.min.js
vendored
Normal file
1
assets/codemirror/addon/search/searchcursor.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/codemirror.min.css
vendored
Normal file
1
assets/codemirror/codemirror.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/codemirror.min.js
vendored
Normal file
1
assets/codemirror/codemirror.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/mode/markdown/markdown.min.js
vendored
Normal file
1
assets/codemirror/mode/markdown/markdown.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/mode/meta.min.js
vendored
Normal file
1
assets/codemirror/mode/meta.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
assets/codemirror/mode/xml/xml.min.js
vendored
Normal file
1
assets/codemirror/mode/xml/xml.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
469
assets/page/page.css
Normal file
469
assets/page/page.css
Normal file
@@ -0,0 +1,469 @@
|
||||
:root { color-scheme: light dark; --chrome-top: 10px; --content-scale: 1; }
|
||||
/* The document scrolls inside #app, below the tab strip. Preview and edit mode
|
||||
therefore show the same scrollbar position and size. */
|
||||
html { overflow: hidden; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
||||
margin: 0; padding: 0;
|
||||
line-height: 1.6; font-size: 15px;
|
||||
color: #1a1a1a; background: #fff;
|
||||
height: 100vh; display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
body.has-tabs { --chrome-top: 50px; }
|
||||
#app { flex: 1 1 auto; min-height: 0; width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; overflow-y: auto; overflow-x: hidden; scrollbar-gutter: stable; }
|
||||
#app::-webkit-scrollbar { width: 10px; }
|
||||
#app::-webkit-scrollbar-track { background: transparent; }
|
||||
#app::-webkit-scrollbar-thumb { background: rgba(128,128,128,.45); border-radius: 6px; }
|
||||
#app::-webkit-scrollbar-thumb:hover { background: rgba(128,128,128,.65); }
|
||||
#preview { font-size: calc(15px * var(--content-scale)); }
|
||||
#preview .front-matter {
|
||||
margin: 0 0 1.5em;
|
||||
padding: .85em 0;
|
||||
border-top: 1px solid #e1e4e8;
|
||||
border-bottom: 1px solid #e1e4e8;
|
||||
color: #59636e;
|
||||
}
|
||||
#preview .front-matter pre {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
overflow: visible;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
#preview h1,#preview h2,#preview h3,#preview h4 { margin-top: 1.4em; }
|
||||
#preview h1 { border-bottom: 1px solid #e1e4e8; padding-bottom: .3em; }
|
||||
#preview h2 { border-bottom: 1px solid #e1e4e8; padding-bottom: .2em; }
|
||||
/* Heading folding: triangle shows on heading hover; the body collapses down to
|
||||
the next heading of the same or higher level. State is per-render only. */
|
||||
#preview .mdp-fold > h1,
|
||||
#preview .mdp-fold > h2,
|
||||
#preview .mdp-fold > h3,
|
||||
#preview .mdp-fold > h4,
|
||||
#preview .mdp-fold > h5,
|
||||
#preview .mdp-fold > h6 { position: relative; }
|
||||
/* Fixed 90%-of-H2 size for every heading level. */
|
||||
#preview .mdp-fold-toggle {
|
||||
position: absolute; left: -34px; top: 50%;
|
||||
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: grid; place-items: center;
|
||||
background: transparent; color: #999; cursor: pointer;
|
||||
opacity: 0; transition: opacity .12s ease, background .12s ease;
|
||||
}
|
||||
#preview .mdp-fold-toggle svg { grid-area: 1 / 1; overflow: visible; }
|
||||
#preview .mdp-fold-toggle .mdp-fold-i-right { display: none; width: 13.5px; height: 20px; }
|
||||
#preview .mdp-fold-toggle .mdp-fold-i-down { display: block; width: 20px; height: 13.5px; }
|
||||
#preview h1:hover > .mdp-fold-toggle,
|
||||
#preview h2:hover > .mdp-fold-toggle,
|
||||
#preview h3:hover > .mdp-fold-toggle,
|
||||
#preview h4:hover > .mdp-fold-toggle,
|
||||
#preview h5:hover > .mdp-fold-toggle,
|
||||
#preview h6:hover > .mdp-fold-toggle,
|
||||
#preview .mdp-fold-toggle:focus-visible { opacity: .6; }
|
||||
#preview .mdp-fold-toggle:hover { opacity: 1; background: rgba(0,0,0,.07); }
|
||||
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-right { display: block; }
|
||||
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-down { display: none; }
|
||||
#preview .mdp-fold.collapsed > .mdp-fold-body { display: none; }
|
||||
#preview code { background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 90%; }
|
||||
/* Code blocks stay dark (VS Dark) even in the light app theme. */
|
||||
#preview pre { background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 8px; overflow-x: auto; }
|
||||
#preview pre code { background: none; padding: 0; font-size: 14px; }
|
||||
#preview blockquote { border-left: 4px solid #ddd; margin: 0; padding: 0 1em; color: #666; }
|
||||
#preview .markdown-alert-note,
|
||||
#preview .markdown-alert-tip,
|
||||
#preview .markdown-alert-important,
|
||||
#preview .markdown-alert-warning,
|
||||
#preview .markdown-alert-caution {
|
||||
margin: 1em 0;
|
||||
padding: 0.75em 1em;
|
||||
border-radius: 6px;
|
||||
color: inherit;
|
||||
}
|
||||
#preview .markdown-alert-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .35em;
|
||||
margin: 0 0 .45em;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
#preview .markdown-alert-title + p { margin-top: 0; }
|
||||
#preview .markdown-alert-note { border-color: #0969da; background: #ddf4ff; }
|
||||
#preview .markdown-alert-tip { border-color: #1a7f37; background: #dafbe1; }
|
||||
#preview .markdown-alert-important { border-color: #8250df; background: #fbefff; }
|
||||
#preview .markdown-alert-warning { border-color: #9a6700; background: #fff8c5; }
|
||||
#preview .markdown-alert-caution { border-color: #cf222e; background: #ffebe9; }
|
||||
#preview .markdown-alert-note .markdown-alert-title { color: #0969da; }
|
||||
#preview .markdown-alert-tip .markdown-alert-title { color: #1a7f37; }
|
||||
#preview .markdown-alert-important .markdown-alert-title { color: #8250df; }
|
||||
#preview .markdown-alert-warning .markdown-alert-title { color: #9a6700; }
|
||||
#preview .markdown-alert-caution .markdown-alert-title { color: #cf222e; }
|
||||
#preview .mdp-mark { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
|
||||
#preview mark.search-hit { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
|
||||
#preview mark.search-hit.current { background: #ffcc4d; color: #1a1a1a; }
|
||||
#preview table { border-collapse: collapse; width: 100%; }
|
||||
#preview .mdp-table-wrap {
|
||||
width: min(calc(100vw - 64px), 1280px);
|
||||
margin: 1em 0 1em 50%;
|
||||
transform: translateX(-50%);
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
#preview .mdp-table-wrap table { width: max-content; min-width: 100%; }
|
||||
#preview table th, #preview table td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
|
||||
#preview table th { background: #f6f8fa; font-weight: 600; color: #1a1a1a; white-space: nowrap; }
|
||||
#preview table td { min-width: 64px; max-width: 360px; vertical-align: top; overflow-wrap: break-word; }
|
||||
#preview img { max-width: 100%; }
|
||||
#preview .katex-display { overflow-x: auto; overflow-y: hidden; padding: 0.15em 0; }
|
||||
#preview .mdp-mermaid { margin: 1.2em 0; overflow-x: auto; text-align: center; }
|
||||
/* Compensate zoom's percentage width so window-fitted diagrams can grow and scroll. */
|
||||
#preview .mdp-mermaid svg { max-width: 100%; height: auto; display: block; margin: 0 auto; width: calc(100% * var(--content-scale)); zoom: var(--content-scale); }
|
||||
#preview .mdp-mermaid-error, #preview .mdp-math-error { color: #b42318; }
|
||||
#preview hr { border: none; border-top: 1px solid #e1e4e8; margin: 2em 0; }
|
||||
#preview a { color: #0969da; text-decoration: none; }
|
||||
#preview a:hover { text-decoration: underline; }
|
||||
#preview ul, #preview ol { padding-left: 2em; }
|
||||
#preview input[type="checkbox"] { margin-right: 6px; }
|
||||
#preview dl { margin: 1em 0; }
|
||||
#preview dt { font-weight: 600; }
|
||||
#preview dd { margin: 0 0 .6em 1.5em; }
|
||||
#preview .footnote-reference { font-size: .75em; }
|
||||
#preview .footnote-definition {
|
||||
margin-top: 1.5em;
|
||||
padding-top: .75em;
|
||||
border-top: 1px solid #e1e4e8;
|
||||
color: #59636e;
|
||||
font-size: .9em;
|
||||
}
|
||||
#preview .footnote-definition-label { margin-right: .35em; font-weight: 600; }
|
||||
.empty { display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }
|
||||
.empty.has-recent {
|
||||
justify-content: flex-start;
|
||||
min-height: calc(100vh - var(--chrome-top) - 38px);
|
||||
padding: clamp(56px, 10vh, 96px) 0 40px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.empty .icon { font-size: 48px; opacity: 0.4; }
|
||||
.empty-actions { display: flex; gap: 8px; margin-top: 6px; }
|
||||
.empty-open {
|
||||
min-height: 40px; padding: 0 16px;
|
||||
border: 1px solid #ddd; border-radius: 8px; background: #fff;
|
||||
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
|
||||
}
|
||||
.empty-open:hover { background: #f5f5f5; color: #000; }
|
||||
.recent { width: min(480px, 100%); margin-top: 16px; text-align: left; }
|
||||
.recent-title { margin: 0 0 8px; padding: 0; border: 0; font-size: 11px; font-weight: 600; letter-spacing: 0; color: #b6b6b6; text-transform: uppercase; }
|
||||
.recent-list { display: grid; gap: 6px; }
|
||||
.recent-item {
|
||||
width: 100%; min-height: 44px; padding: 7px 10px; border: 1px solid #eee;
|
||||
border-radius: 8px; background: #fff; color: inherit; text-align: left; cursor: pointer;
|
||||
display: grid; gap: 1px;
|
||||
}
|
||||
.recent-item:hover { background: #f7f7f7; }
|
||||
.recent-name { color: #555; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.recent-path { color: #aaa; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tabbar {
|
||||
display: none; flex: none; position: sticky; top: 0; z-index: 110; height: 40px;
|
||||
box-sizing: border-box; align-items: stretch; gap: 4px; padding: 4px 8px;
|
||||
border-bottom: 1px solid #e6e6e6; background: rgba(248,248,248,0.96);
|
||||
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
||||
}
|
||||
body.has-tabs .tabbar { display: flex; }
|
||||
.tabs { display: flex; flex: 1; min-width: 0; gap: 4px; overflow-x: auto; scrollbar-width: none; }
|
||||
.tabs::-webkit-scrollbar { display: none; }
|
||||
.tab {
|
||||
flex: 0 1 180px; min-width: 96px; max-width: 200px; height: 31px;
|
||||
display: flex; align-items: center; gap: 7px; padding: 0 8px 0 10px;
|
||||
box-sizing: border-box; border: 1px solid transparent; border-radius: 7px;
|
||||
color: #6b6b6b; background: transparent; cursor: default; user-select: none;
|
||||
font-size: 13px;
|
||||
}
|
||||
.tab:hover { background: rgba(0,0,0,0.045); }
|
||||
.tab.dragging { opacity: .55; cursor: grabbing; }
|
||||
.tab.active { color: #202020; background: #fff; border-color: #ddd; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
|
||||
.tab.missing { color: #a15c00; }
|
||||
.tab-status { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: transparent; }
|
||||
.tab.dirty .tab-status { background: #2979c9; }
|
||||
.tab.missing .tab-status { width: auto; height: auto; background: none; border-radius: 0; font-weight: 700; }
|
||||
.tab-name { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab-close {
|
||||
width: 20px; height: 20px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 5px;
|
||||
display: grid; place-items: center; color: inherit; background: transparent; cursor: pointer;
|
||||
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
|
||||
}
|
||||
.tab-close:hover { opacity: 1; background: rgba(0,0,0,.08); }
|
||||
.tab-close[hidden] { display: none; }
|
||||
.tab-menu {
|
||||
position: fixed; z-index: 200; min-width: 188px; padding: 4px;
|
||||
background: #fff; border: 1px solid #ddd; border-radius: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,.16);
|
||||
}
|
||||
.tab-menu[hidden] { display: none; }
|
||||
.tab-menu-path {
|
||||
max-width: 280px; padding: 3px 8px 5px; overflow: hidden;
|
||||
color: #8a8a8a; font-size: 11px; line-height: 1.3;
|
||||
white-space: nowrap; text-overflow: ellipsis;
|
||||
}
|
||||
.tab-menu button {
|
||||
display: block; width: 100%; padding: 5px 8px; border: 0; border-radius: 5px;
|
||||
background: transparent; color: #222; text-align: left; font: inherit;
|
||||
font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.tab-menu button:hover { background: #f2f2f2; }
|
||||
.tab-menu button:disabled { opacity: .42; cursor: default; }
|
||||
.tab-menu button:disabled:hover { background: transparent; }
|
||||
.tab-open {
|
||||
width: 31px; height: 31px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 7px;
|
||||
color: #666; background: transparent; cursor: pointer; font: 20px/1 -apple-system, sans-serif;
|
||||
}
|
||||
.tab-open:hover { color: #111; background: rgba(0,0,0,.06); }
|
||||
.doc-stats {
|
||||
flex: 0 0 auto; align-self: center; padding: 0 6px;
|
||||
color: #8b8b8b; font-size: 11px; white-space: nowrap; user-select: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.missing-file { min-height: 55vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; }
|
||||
.missing-file h2, .missing-file p { margin: 0; }
|
||||
.missing-file p { color: #777; }
|
||||
.missing-file code { max-width: min(620px, 90vw); overflow-wrap: anywhere; color: #8a5a12; }
|
||||
.missing-mark { width: 38px; height: 38px; border: 2px solid #c98322; border-radius: 50%; display: grid; place-items: center; color: #a15c00; font-weight: 700; font-size: 22px; }
|
||||
.missing-actions { display: flex; gap: 8px; margin-top: 8px; }
|
||||
.missing-actions button { min-height: 36px; padding: 0 13px; border: 1px solid #d8d8d8; border-radius: 7px; background: #fff; color: #333; cursor: pointer; font: inherit; }
|
||||
.missing-actions button:hover { background: #f4f4f4; }
|
||||
|
||||
/* Floating toolbar (top-right) — hover-reveal, hidden in empty state */
|
||||
.toolbar {
|
||||
position: fixed; top: var(--chrome-top); right: 12px;
|
||||
display: flex; gap: 6px; z-index: 100;
|
||||
opacity: 0; pointer-events: none;
|
||||
transition: opacity 0.18s ease;
|
||||
}
|
||||
html:hover .toolbar { opacity: 1; pointer-events: auto; }
|
||||
body.home .toolbar { display: none !important; }
|
||||
.toolbar button {
|
||||
width: 34px; height: 34px; padding: 0;
|
||||
background: rgba(255,255,255,0.8);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
border: 1px solid rgba(0,0,0,0.08);
|
||||
border-radius: 8px;
|
||||
display: grid; place-items: center;
|
||||
cursor: pointer; color: #555;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.toolbar button:hover { color: #000; background: rgba(255,255,255,1); }
|
||||
.toolbar button[hidden] { display: none !important; }
|
||||
.zoom-control { position: relative; }
|
||||
.zoom-popover {
|
||||
position: absolute; top: 40px; right: 0;
|
||||
display: none; align-items: center; gap: 2px; padding: 4px;
|
||||
border: 1px solid rgba(0,0,0,.1); border-radius: 8px;
|
||||
background: rgba(255,255,255,.96); box-shadow: 0 6px 20px rgba(0,0,0,.12);
|
||||
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||||
}
|
||||
.zoom-control.open .zoom-popover { display: flex; }
|
||||
.toolbar .zoom-popover button { width: 30px; height: 30px; border: 0; background: transparent; }
|
||||
.toolbar .zoom-popover button:hover { background: rgba(0,0,0,.06); }
|
||||
.toolbar .zoom-popover .zoom-reset {
|
||||
width: 52px; font-size: 11px; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.findbar {
|
||||
position: fixed; top: var(--chrome-top); left: 50%; transform: translateX(-50%);
|
||||
display: none; align-items: center; gap: 6px; z-index: 101;
|
||||
padding: 6px; border: 1px solid rgba(0,0,0,0.08); border-radius: 10px;
|
||||
background: rgba(255,255,255,0.96); box-shadow: 0 8px 24px rgba(0,0,0,0.12);
|
||||
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||||
}
|
||||
body.finding .findbar:not(#edit-findbar) { display: flex; }
|
||||
.findbar input {
|
||||
width: min(42vw, 320px); height: 30px; box-sizing: border-box; border: 0;
|
||||
outline: none; background: transparent; color: inherit; font: inherit;
|
||||
}
|
||||
.findbar span { min-width: 14px; color: #8c959f; text-align: center; }
|
||||
.findbar button {
|
||||
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px;
|
||||
display: grid; place-items: center; color: #555; background: transparent; cursor: pointer;
|
||||
}
|
||||
.findbar button:hover { background: #f0f0f0; color: #111; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { color: #d4d4d4; background: #1e1e1e; }
|
||||
#preview a { color: #6cb6ff; }
|
||||
#preview h1, #preview h2 { border-color: #333; }
|
||||
#preview .mdp-fold-toggle { color: #aaa; }
|
||||
#preview .mdp-fold-toggle:hover { background: rgba(255,255,255,.1); }
|
||||
#preview .front-matter { border-color: #333; color: #a9b1ba; }
|
||||
#preview .front-matter pre { background: transparent !important; }
|
||||
#preview code:not(pre code) { background: #2d2d2d; }
|
||||
#preview blockquote { border-color: #444; color: #aaa; }
|
||||
#preview .footnote-definition { border-color: #444; color: #aaa; }
|
||||
#preview .markdown-alert-note,
|
||||
#preview .markdown-alert-tip,
|
||||
#preview .markdown-alert-important,
|
||||
#preview .markdown-alert-warning,
|
||||
#preview .markdown-alert-caution { background: #161b22; color: #d4d4d4; }
|
||||
#preview .markdown-alert-note { border-color: #2f81f7; }
|
||||
#preview .markdown-alert-tip { border-color: #3fb950; }
|
||||
#preview .markdown-alert-important { border-color: #a371f7; }
|
||||
#preview .markdown-alert-warning { border-color: #d29922; }
|
||||
#preview .markdown-alert-caution { border-color: #f85149; }
|
||||
#preview .markdown-alert-note .markdown-alert-title { color: #2f81f7; }
|
||||
#preview .markdown-alert-tip .markdown-alert-title { color: #3fb950; }
|
||||
#preview .markdown-alert-important .markdown-alert-title { color: #a371f7; }
|
||||
#preview .markdown-alert-warning .markdown-alert-title { color: #d29922; }
|
||||
#preview .markdown-alert-caution .markdown-alert-title { color: #f85149; }
|
||||
#preview table th { background: #2d2d2d; color: #f0f0f0; }
|
||||
#preview table td, #preview table th { border-color: #444; }
|
||||
#preview hr { border-color: #333; }
|
||||
.toolbar button {
|
||||
background: rgba(40,40,40,0.8);
|
||||
border-color: rgba(255,255,255,0.1);
|
||||
color: #bbb;
|
||||
}
|
||||
.toolbar button:hover { color: #fff; background: rgba(55,55,55,1); }
|
||||
.zoom-popover { background: rgba(34,34,34,.96); border-color: rgba(255,255,255,.12); }
|
||||
.toolbar .zoom-popover button:hover { background: rgba(255,255,255,.1); }
|
||||
.empty-open { background: #242424; border-color: #444; color: #ddd; }
|
||||
.empty-open:hover { background: #2d2d2d; color: #fff; }
|
||||
.recent-name { color: #ddd; }
|
||||
.recent-item { background: #242424; border-color: #333; }
|
||||
.recent-item:hover { background: #2d2d2d; }
|
||||
.findbar { background: rgba(34,34,34,0.96); border-color: rgba(255,255,255,0.1); }
|
||||
.findbar button:hover { background: #333; color: #fff; }
|
||||
.tabbar { background: rgba(28,28,28,.96); border-color: #363636; }
|
||||
.tab { color: #aaa; }
|
||||
.tab:hover { background: rgba(255,255,255,.07); }
|
||||
.tab.active { color: #eee; background: #2c2c2c; border-color: #444; }
|
||||
.tab.missing { color: #e3a04b; }
|
||||
.tab-close:hover, .tab-open:hover { background: rgba(255,255,255,.1); color: #fff; }
|
||||
.tab-menu { background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }
|
||||
.tab-menu-path { color: #999; }
|
||||
.tab-menu button { color: #ddd; }
|
||||
.tab-menu button:hover { background: rgba(255,255,255,.08); }
|
||||
.tab-menu button:disabled:hover { background: transparent; }
|
||||
.missing-file p { color: #aaa; }
|
||||
.missing-actions button { background: #292929; border-color: #444; color: #ddd; }
|
||||
.missing-actions button:hover { background: #333; }
|
||||
}
|
||||
|
||||
/* Source editor textarea — height is auto-grown by JS to match content,
|
||||
so the page (html) owns the only vertical scrollbar. */
|
||||
#editor {
|
||||
display: none;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
border: none; outline: none; resize: none;
|
||||
overflow: hidden;
|
||||
font: calc(14px * var(--content-scale))/1.6 "SF Mono","Menlo","Consolas",monospace;
|
||||
background: transparent; color: inherit;
|
||||
padding: 0;
|
||||
}
|
||||
body.editing #preview { display: none; }
|
||||
body.editing #editor { display: block; padding: 16px 48px; }
|
||||
body.editing #app { max-width: none; padding: 0; }
|
||||
|
||||
@page {
|
||||
margin: 12mm;
|
||||
}
|
||||
|
||||
@media print {
|
||||
.toolbar, .tabbar, #editor { display: none !important; }
|
||||
#preview { display: block !important; }
|
||||
#app { max-width: none; padding: 0; }
|
||||
#preview .mdp-table-wrap { width: auto; margin: 1em 0; transform: none; overflow: visible; }
|
||||
#preview pre { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
#preview .mdp-fold-body { display: block !important; }
|
||||
#preview .mdp-fold-toggle { display: none !important; }
|
||||
}
|
||||
|
||||
/* ---- CodeMirror source editor ------------------------------------------- */
|
||||
#cm-editor { display: none; }
|
||||
body.editing.cm-active { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
|
||||
body.editing.cm-active .tabbar { flex: none; }
|
||||
body.editing.cm-active #app { flex: 1; min-height: 0; width: 100%; max-width: none; padding: 0; overflow: hidden; scrollbar-gutter: auto; }
|
||||
body.editing.cm-active #editor { display: none; }
|
||||
body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px 0 0 14px; box-sizing: border-box; }
|
||||
#cm-editor .CodeMirror { height: 100%; background: transparent; color: inherit; font: 14px/1.6 "SF Mono","Menlo","Consolas",monospace; }
|
||||
#cm-editor .CodeMirror-gutters { background: transparent; border-right: 1px solid rgba(128,128,128,.18); }
|
||||
#cm-editor .CodeMirror-linenumber { color: #9aa0a6; padding: 0 10px 0 4px; }
|
||||
#cm-editor .CodeMirror-foldgutter { width: .9em; }
|
||||
#cm-editor .CodeMirror-foldgutter-open, #cm-editor .CodeMirror-foldgutter-folded { color: #9aa0a6; }
|
||||
#cm-editor .CodeMirror-cursor { border-left: 1.5px solid #333; }
|
||||
#cm-editor .CodeMirror-selected { background: #d7e4f5; }
|
||||
#cm-editor .CodeMirror-focused .CodeMirror-selected { background: #b9d3f2; }
|
||||
#cm-editor .cm-searching { background: rgba(255, 213, 0, .45); }
|
||||
#cm-editor .CodeMirror-matchingbracket { color: inherit; text-decoration: underline; }
|
||||
#cm-editor .cm-header { font-weight: 700; color: #0550ae; }
|
||||
#cm-editor .cm-strong { font-weight: 700; }
|
||||
#cm-editor .cm-em { font-style: italic; }
|
||||
#cm-editor .cm-link { color: #0969da; }
|
||||
#cm-editor .cm-url { color: #6e7781; }
|
||||
#cm-editor .cm-comment { color: #6e7781; }
|
||||
#cm-editor .cm-quote { color: #57606a; font-style: italic; }
|
||||
#cm-editor .cm-formatting { color: #8c959f; }
|
||||
#cm-editor .cm-variable-2 { color: #953800; }
|
||||
#cm-editor .CodeMirror-dialog { background: #fff; color: #1a1a1a; border-color: #ddd; }
|
||||
#cm-editor .CodeMirror-dialog input { font: inherit; }
|
||||
#cm-editor .CodeMirror-dialog button { color: #1a1a1a; }
|
||||
#cm-editor .CodeMirror-foldmarker { color: #0550ae; text-shadow: none; background: rgba(9,105,218,.08); border-radius: 3px; padding: 0 .3em; }
|
||||
#cm-editor .CodeMirror-lines { padding: 4px 24px 24px 0; }
|
||||
#cm-editor .CodeMirror-scroll { overflow-x: hidden !important; }
|
||||
#cm-editor .CodeMirror-scrollbar-filler { display: none !important; }
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
#cm-editor .CodeMirror { color: #d4d4d4; }
|
||||
#cm-editor .CodeMirror-gutters { border-color: rgba(255,255,255,.12); }
|
||||
#cm-editor .CodeMirror-linenumber { color: #6b7280; }
|
||||
#cm-editor .CodeMirror-foldgutter-open, #cm-editor .CodeMirror-foldgutter-folded { color: #6b7280; }
|
||||
#cm-editor .CodeMirror-cursor { border-left-color: #e6e6e6; }
|
||||
#cm-editor .CodeMirror-selected { background: #264f78; }
|
||||
#cm-editor .CodeMirror-focused .CodeMirror-selected { background: #2f5f8f; }
|
||||
#cm-editor .cm-header { color: #79c0ff; }
|
||||
#cm-editor .cm-link { color: #58a6ff; }
|
||||
#cm-editor .cm-url, #cm-editor .cm-comment { color: #8b949e; }
|
||||
#cm-editor .cm-quote { color: #a8b1bb; }
|
||||
#cm-editor .cm-formatting { color: #7d8590; }
|
||||
#cm-editor .cm-variable-2 { color: #ffa657; }
|
||||
#cm-editor .CodeMirror-dialog { background: #2a2a2a; color: #ddd; border-color: #444; }
|
||||
#cm-editor .CodeMirror-dialog button { color: #ddd; }
|
||||
#cm-editor .CodeMirror-foldmarker { color: #79c0ff; background: rgba(88,166,255,.12); }
|
||||
}
|
||||
|
||||
@media print {
|
||||
#cm-editor { display: none !important; }
|
||||
.findbar { display: none !important; }
|
||||
html, body { height: auto !important; overflow: visible !important; display: block !important; }
|
||||
#app { flex: none !important; height: auto !important; min-height: 0 !important; overflow: visible !important; scrollbar-gutter: auto; }
|
||||
}
|
||||
|
||||
/* Edit-mode find/replace bar: same look as the preview findbar. */
|
||||
html.cm-editing { overflow: hidden; scrollbar-gutter: auto; }
|
||||
#edit-findbar { top: calc(var(--chrome-top) + 8px); z-index: 130; width: min(560px, calc(100vw - 32px)); padding: 8px 10px; }
|
||||
body.edit-finding #edit-findbar { display: flex; flex-direction: column; align-items: stretch; gap: 6px; }
|
||||
#edit-findbar .edit-find-row { display: flex; align-items: center; gap: 6px; width: 100%; }
|
||||
#edit-findbar .edit-find-row input { flex: 1 1 auto; width: auto; min-width: 0; }
|
||||
#edit-findbar .edit-replace-row { display: flex; align-items: center; gap: 6px; width: 100%; border-top: 1px solid rgba(0,0,0,.08); padding-top: 6px; }
|
||||
#edit-findbar .edit-replace-row[hidden] { display: none; }
|
||||
#edit-findbar #edit-replace-input { flex: 1 1 auto; width: auto; min-width: 0; }
|
||||
#edit-findbar button.edit-replace-btn { width: auto; height: 30px; min-width: 0; padding: 0 8px; border: 0; border-radius: 7px; background: transparent; color: #666; font: inherit; font-size: 15px; font-weight: 600; }
|
||||
#edit-findbar button.edit-replace-btn:hover { background: #f0f0f0; color: #111; }
|
||||
#cm-editor .cm-edit-find-hit { background: rgba(255, 213, 0, .38); }
|
||||
|
||||
/* Use the same thin scrollbar inside CodeMirror as the preview container. */
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar { width: 10px; }
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-track { background: transparent; }
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb { background: rgba(128,128,128,.45); border-radius: 6px; }
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb:hover { background: rgba(128,128,128,.65); }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
#app::-webkit-scrollbar-thumb { background: rgba(200,200,200,.35); }
|
||||
#app::-webkit-scrollbar-thumb:hover { background: rgba(200,200,200,.55); }
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb { background: rgba(200,200,200,.35); }
|
||||
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb:hover { background: rgba(200,200,200,.55); }
|
||||
#edit-findbar .edit-replace-row { border-top-color: rgba(255,255,255,.12); }
|
||||
#edit-findbar button.edit-replace-btn { color: #bbb; }
|
||||
#edit-findbar button.edit-replace-btn:hover { background: #333; color: #fff; }
|
||||
}
|
||||
53
assets/page/page.html
Normal file
53
assets/page/page.html
Normal file
@@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html><html><head><meta charset="utf-8">
|
||||
__MDP_BASE_TAG__
|
||||
<style id="hljs-code">__MDP_CSS_CODE__</style>
|
||||
<style>
|
||||
__MDP_PAGE_CSS__
|
||||
</style>
|
||||
<style id="cm-css">__MDP_CM_CSS__</style></head><body class="__MDP_BODY_CLASS__">
|
||||
<div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="__MDP_NEW_TAB__" aria-label="__MDP_NEW_TAB__">+</button></div>
|
||||
<div class="tab-menu" id="tab-menu" hidden><div class="tab-menu-path" id="tab-menu-path"></div><button type="button" id="tab-menu-reveal">__MDP_BTN_OPEN_LOCATION__</button><button type="button" id="tab-menu-new-window">__MDP_BTN_NEW_WINDOW__</button></div>
|
||||
<div class="toolbar">
|
||||
<button id="btn-toggle" title="__MDP_BTN_EDIT__" aria-label="__MDP_BTN_EDIT__"></button>
|
||||
<div class="zoom-control" id="zoom-control">
|
||||
<button id="btn-zoom" title="__MDP_BTN_ZOOM__" aria-label="__MDP_BTN_ZOOM__"></button>
|
||||
<div class="zoom-popover">
|
||||
<button id="btn-zoom-out" title="__MDP_BTN_ZOOM_OUT__" aria-label="__MDP_BTN_ZOOM_OUT__">−</button>
|
||||
<button id="btn-zoom-reset" class="zoom-reset" title="__MDP_BTN_ZOOM_RESET__" aria-label="__MDP_BTN_ZOOM_RESET__">100%</button>
|
||||
<button id="btn-zoom-in" title="__MDP_BTN_ZOOM_IN__" aria-label="__MDP_BTN_ZOOM_IN__">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="findbar" role="search">
|
||||
<input id="find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
|
||||
<span id="find-state"></span>
|
||||
<button id="find-prev" title="Previous" aria-label="Previous"></button>
|
||||
<button id="find-next" title="Next" aria-label="Next"></button>
|
||||
<button id="find-close" title="Close" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="findbar" id="edit-findbar" role="search" hidden>
|
||||
<div class="edit-find-row">
|
||||
<input id="edit-find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
|
||||
<span id="edit-find-state"></span>
|
||||
<button id="edit-find-prev" title="Previous" aria-label="Previous"></button>
|
||||
<button id="edit-find-next" title="Next" aria-label="Next"></button>
|
||||
<button id="edit-find-close" title="Close" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="edit-replace-row" id="edit-replace-group" hidden>
|
||||
<input id="edit-replace-input" type="text" placeholder="Replace with" aria-label="Replace with">
|
||||
<button id="edit-replace-one" class="edit-replace-btn" type="button">Replace</button>
|
||||
<button id="edit-replace-all" class="edit-replace-btn" type="button">Replace All</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="app">
|
||||
<div id="preview">__MDP_PREVIEW_HTML__</div>
|
||||
<textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea>
|
||||
<div id="cm-editor" aria-label="Source editor"></div>
|
||||
</div>
|
||||
<script>
|
||||
__MDP_PAGE_JS__
|
||||
window.__mdPreviewFeatureFlags = { math: __MDP_NEEDS_MATH__, mermaid: __MDP_NEEDS_MERMAID__ };
|
||||
__MDP_PREVIEW_ENHANCE_JS__
|
||||
if(window.__enhancePreview)window.__enhancePreview();
|
||||
</script>
|
||||
</body></html>
|
||||
1456
assets/page/page.js
Normal file
1456
assets/page/page.js
Normal file
File diff suppressed because it is too large
Load Diff
1996
src/app.rs
Normal file
1996
src/app.rs
Normal file
File diff suppressed because it is too large
Load Diff
235
src/config.rs
Normal file
235
src/config.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
//! User data paths, persisted window/zoom/theme state, and the blocking dialogs.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use tao::event_loop::EventLoop;
|
||||
use tao::window::{Theme, Window};
|
||||
|
||||
// Window defaults, in logical pixels.
|
||||
pub const DEFAULT_W: f64 = 900.0;
|
||||
pub const DEFAULT_H: f64 = 700.0;
|
||||
|
||||
use crate::app::UserEvent;
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ThemeChoice {
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl ThemeChoice {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ThemeChoice::System => "system",
|
||||
ThemeChoice::Light => "light",
|
||||
ThemeChoice::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_str(value: &str) -> Self {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"light" => ThemeChoice::Light,
|
||||
"dark" => ThemeChoice::Dark,
|
||||
_ => ThemeChoice::System,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tao_theme(self) -> Option<Theme> {
|
||||
match self {
|
||||
ThemeChoice::System => None,
|
||||
ThemeChoice::Light => Some(Theme::Light),
|
||||
ThemeChoice::Dark => Some(Theme::Dark),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config_dir() -> PathBuf {
|
||||
if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") {
|
||||
return PathBuf::from(path);
|
||||
}
|
||||
std::env::var_os("LOCALAPPDATA")
|
||||
.or_else(|| std::env::var_os("APPDATA"))
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("md-preview")
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct WindowGeom {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub w: f64,
|
||||
pub h: f64,
|
||||
}
|
||||
|
||||
pub fn geom_path() -> PathBuf {
|
||||
config_dir().join("window.geom")
|
||||
}
|
||||
|
||||
pub fn theme_path() -> PathBuf {
|
||||
config_dir().join("theme.txt")
|
||||
}
|
||||
|
||||
pub fn load_theme_choice() -> ThemeChoice {
|
||||
fs::read_to_string(theme_path())
|
||||
.map(|raw| ThemeChoice::from_str(&raw))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save_theme_choice(choice: ThemeChoice) {
|
||||
let dir = config_dir();
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let _ = fs::write(dir.join("theme.txt"), choice.as_str());
|
||||
}
|
||||
|
||||
const ZOOM_MIN: u32 = 50;
|
||||
const ZOOM_MAX: u32 = 300;
|
||||
|
||||
pub fn zoom_path() -> PathBuf {
|
||||
config_dir().join("zoom.txt")
|
||||
}
|
||||
|
||||
pub fn clamp_zoom(percent: u32) -> u32 {
|
||||
percent.clamp(ZOOM_MIN, ZOOM_MAX)
|
||||
}
|
||||
|
||||
pub fn load_zoom() -> u32 {
|
||||
fs::read_to_string(zoom_path())
|
||||
.ok()
|
||||
.and_then(|raw| raw.trim().parse::<u32>().ok())
|
||||
.map(clamp_zoom)
|
||||
.unwrap_or(100)
|
||||
}
|
||||
|
||||
pub fn save_zoom(percent: u32) {
|
||||
let dir = config_dir();
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string());
|
||||
}
|
||||
|
||||
pub fn show_warning_dialog(title: &str, description: &str) {
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Warning)
|
||||
.set_title(title)
|
||||
.set_description(description)
|
||||
.show();
|
||||
}
|
||||
|
||||
pub fn confirm_discard_unsaved(error: &str) -> bool {
|
||||
matches!(
|
||||
rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Warning)
|
||||
.set_title("Could Not Save")
|
||||
.set_description(format!(
|
||||
"{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?"
|
||||
))
|
||||
.set_buttons(rfd::MessageButtons::OkCancel)
|
||||
.show(),
|
||||
rfd::MessageDialogResult::Ok
|
||||
)
|
||||
}
|
||||
|
||||
pub fn load_window_geom() -> Option<WindowGeom> {
|
||||
let txt = fs::read_to_string(geom_path()).ok()?;
|
||||
let parts: Vec<&str> = txt.trim().split(',').collect();
|
||||
if parts.len() != 4 {
|
||||
return None;
|
||||
}
|
||||
Some(WindowGeom {
|
||||
x: parts[0].parse().ok()?,
|
||||
y: parts[1].parse().ok()?,
|
||||
w: parts[2].parse().ok()?,
|
||||
h: parts[3].parse().ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save_window_geom(window: &Window) {
|
||||
let Ok(pos) = window.outer_position() else {
|
||||
return;
|
||||
};
|
||||
let scale = window.scale_factor();
|
||||
let size = window.inner_size();
|
||||
let geom = WindowGeom {
|
||||
x: pos.x as f64 / scale,
|
||||
y: pos.y as f64 / scale,
|
||||
w: size.width as f64 / scale,
|
||||
h: size.height as f64 / scale,
|
||||
};
|
||||
if geom.w < 200.0 || geom.h < 150.0 {
|
||||
return;
|
||||
}
|
||||
let dir = config_dir();
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let _ = fs::write(
|
||||
dir.join("window.geom"),
|
||||
format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h),
|
||||
);
|
||||
}
|
||||
|
||||
/// Return the saved geometry only when its center still falls inside
|
||||
/// some connected monitor — prevents the window from landing off-screen
|
||||
/// after a display swap.
|
||||
pub fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop<UserEvent>) -> bool {
|
||||
let cx = geom.x + geom.w / 2.0;
|
||||
let cy = geom.y + geom.h / 2.0;
|
||||
event_loop.available_monitors().any(|mon| {
|
||||
let scale = mon.scale_factor();
|
||||
let mp = mon.position();
|
||||
let ms = mon.size();
|
||||
let mx = mp.x as f64 / scale;
|
||||
let my = mp.y as f64 / scale;
|
||||
let mw = ms.width as f64 / scale;
|
||||
let mh = ms.height as f64 / scale;
|
||||
cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh
|
||||
})
|
||||
}
|
||||
|
||||
pub fn centered_geom(event_loop: &EventLoop<UserEvent>) -> WindowGeom {
|
||||
if let Some(mon) = event_loop.primary_monitor() {
|
||||
let scale = mon.scale_factor();
|
||||
let mp = mon.position();
|
||||
let ms = mon.size();
|
||||
let mx = mp.x as f64 / scale;
|
||||
let my = mp.y as f64 / scale;
|
||||
let mw = ms.width as f64 / scale;
|
||||
let mh = ms.height as f64 / scale;
|
||||
WindowGeom {
|
||||
x: mx + (mw - DEFAULT_W) / 2.0,
|
||||
y: my + (mh - DEFAULT_H) / 2.0,
|
||||
w: DEFAULT_W,
|
||||
h: DEFAULT_H,
|
||||
}
|
||||
} else {
|
||||
WindowGeom {
|
||||
x: 100.0,
|
||||
y: 100.0,
|
||||
w: DEFAULT_W,
|
||||
h: DEFAULT_H,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zoom_percent_is_clamped_to_supported_range() {
|
||||
assert_eq!(clamp_zoom(10), 50);
|
||||
assert_eq!(clamp_zoom(50), 50);
|
||||
assert_eq!(clamp_zoom(105), 105);
|
||||
assert_eq!(clamp_zoom(300), 300);
|
||||
assert_eq!(clamp_zoom(999), 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_choice_parses_menu_values() {
|
||||
assert_eq!(ThemeChoice::from_str("system"), ThemeChoice::System);
|
||||
assert_eq!(ThemeChoice::from_str("light"), ThemeChoice::Light);
|
||||
assert_eq!(ThemeChoice::from_str("dark"), ThemeChoice::Dark);
|
||||
assert_eq!(ThemeChoice::from_str("unexpected"), ThemeChoice::System);
|
||||
assert_eq!(ThemeChoice::Dark.as_str(), "dark");
|
||||
}
|
||||
}
|
||||
25
src/escape.rs
Normal file
25
src/escape.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! Small text/JS escaping helpers shared by the page builder, the Markdown
|
||||
//! pipeline and the renderer.
|
||||
|
||||
pub fn escape_js(s: &str) -> String {
|
||||
s.replace('\\', "\\\\")
|
||||
.replace('\'', "\\'")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\r', "\\r")
|
||||
}
|
||||
|
||||
pub fn html_escape_ta(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<")
|
||||
}
|
||||
|
||||
pub fn html_escape_attr(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('"', """)
|
||||
.replace('<', "<")
|
||||
}
|
||||
|
||||
pub fn html_escape_text(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
458
src/files.rs
Normal file
458
src/files.rs
Normal file
@@ -0,0 +1,458 @@
|
||||
//! File-system side effects: the recent-files list, saving the active tab,
|
||||
//! the single-file watcher, supported document types, local-link resolution
|
||||
//! and Explorer integration.
|
||||
|
||||
use notify::{Event, RecursiveMode, Watcher};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tao::event_loop::EventLoopProxy;
|
||||
use tao::window::WindowId;
|
||||
|
||||
use crate::app::UserEvent;
|
||||
use crate::session::{self, DocumentSession};
|
||||
|
||||
pub const MAX_RECENT_FILES: usize = 8;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SelfWriteRecord {
|
||||
pub path: PathBuf,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
fn recent_files_path() -> PathBuf {
|
||||
crate::config::config_dir().join("recent-files.txt")
|
||||
}
|
||||
|
||||
pub fn load_recent_files() -> Vec<PathBuf> {
|
||||
let Ok(txt) = fs::read_to_string(recent_files_path()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut files = Vec::new();
|
||||
for line in txt.lines() {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let path = session::strip_verbatim(PathBuf::from(line));
|
||||
if !path.exists() || files.iter().any(|p| p == &path) {
|
||||
continue;
|
||||
}
|
||||
files.push(path);
|
||||
if files.len() == MAX_RECENT_FILES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
fn save_recent_files(files: &[PathBuf]) {
|
||||
let dir = crate::config::config_dir();
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let body = files
|
||||
.iter()
|
||||
.take(MAX_RECENT_FILES)
|
||||
.map(|p| p.to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let _ = fs::write(dir.join("recent-files.txt"), body);
|
||||
}
|
||||
|
||||
pub fn remember_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) {
|
||||
let mut recent = files.lock().unwrap();
|
||||
recent.retain(|p| p != path);
|
||||
recent.insert(0, path.to_path_buf());
|
||||
recent.truncate(MAX_RECENT_FILES);
|
||||
save_recent_files(&recent);
|
||||
}
|
||||
|
||||
pub fn forget_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) -> bool {
|
||||
let mut recent = files.lock().unwrap();
|
||||
let original_len = recent.len();
|
||||
recent.retain(|p| p != path);
|
||||
if recent.len() == original_len {
|
||||
return false;
|
||||
}
|
||||
save_recent_files(&recent);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn is_supported_document(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.map(|extension| {
|
||||
matches!(
|
||||
extension.to_string_lossy().to_ascii_lowercase().as_str(),
|
||||
"md" | "markdown" | "mdown" | "mkd"
|
||||
)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn reveal_in_explorer(path: &Path) -> bool {
|
||||
let mut command = std::process::Command::new("explorer.exe");
|
||||
if path.is_file() {
|
||||
command.arg("/select,").arg(path);
|
||||
} else if let Some(parent) = path.parent().filter(|parent| parent.is_dir()) {
|
||||
command.arg(parent);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
command.spawn().is_ok()
|
||||
}
|
||||
|
||||
pub fn resolve_document_link(value: &str, active: Option<&Path>) -> Option<PathBuf> {
|
||||
let url = match url::Url::parse(value) {
|
||||
Ok(url) => url,
|
||||
Err(url::ParseError::RelativeUrlWithoutBase) => {
|
||||
url::Url::from_file_path(active?).ok()?.join(value).ok()?
|
||||
}
|
||||
Err(_) => return None,
|
||||
};
|
||||
local_document_path_from_url(url.as_str())
|
||||
}
|
||||
|
||||
pub fn local_document_path_from_url(value: &str) -> Option<PathBuf> {
|
||||
let url = url::Url::parse(value).ok()?;
|
||||
if url.scheme() != "file" {
|
||||
return None;
|
||||
}
|
||||
let path = url.to_file_path().ok()?;
|
||||
if !path.is_file() || !is_supported_document(&path) {
|
||||
return None;
|
||||
}
|
||||
fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
pub fn watch_scope_for_file(path: &Path) -> &Path {
|
||||
path.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.unwrap_or(path)
|
||||
}
|
||||
|
||||
fn event_path_matches_file(event_path: &Path, target: &Path) -> bool {
|
||||
event_path == target
|
||||
|| (target.file_name().is_some()
|
||||
&& event_path.file_name() == target.file_name()
|
||||
&& event_path.parent() == target.parent())
|
||||
}
|
||||
|
||||
pub fn event_should_reload_file(ev: &Event, target: &Path) -> bool {
|
||||
if ev.need_rescan() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if !(ev.kind.is_modify() || ev.kind.is_create() || ev.kind.is_remove()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ev.paths
|
||||
.iter()
|
||||
.any(|event_path| event_path_matches_file(event_path, target))
|
||||
}
|
||||
|
||||
/// Watch the active file's directory and turn real external changes into
|
||||
/// `FileChanged` events. Watches only the parent directory, so sibling edits
|
||||
/// still arrive and get filtered by [`event_should_reload_file`].
|
||||
pub fn install_file_watcher(
|
||||
holder: &Arc<Mutex<Option<notify::RecommendedWatcher>>>,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||
window_id: WindowId,
|
||||
path: Option<PathBuf>,
|
||||
) {
|
||||
let mut current = holder.lock().unwrap();
|
||||
*current = None;
|
||||
*last_self_write.lock().unwrap() = None;
|
||||
let Some(path) = path else {
|
||||
return;
|
||||
};
|
||||
let mut observed_content = fs::read(&path).ok();
|
||||
let target_path = path.clone();
|
||||
let callback_path = path.clone();
|
||||
let proxy = proxy.clone();
|
||||
let last_self_write = Arc::clone(last_self_write);
|
||||
if let Ok(mut watcher) = notify::recommended_watcher(move |result: Result<Event, _>| {
|
||||
if let Ok(event) = result {
|
||||
if event_should_reload_file(&event, &callback_path) {
|
||||
let content = fs::read(&callback_path).ok();
|
||||
let mut last_self_write = last_self_write.lock().unwrap();
|
||||
if file_content_should_reload(
|
||||
&callback_path,
|
||||
content,
|
||||
&mut observed_content,
|
||||
&mut last_self_write,
|
||||
) {
|
||||
let _ =
|
||||
proxy.send_event(UserEvent::FileChanged(window_id, callback_path.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}) {
|
||||
let scope = watch_scope_for_file(&target_path);
|
||||
if scope.exists() && watcher.watch(scope, RecursiveMode::NonRecursive).is_ok() {
|
||||
*current = Some(watcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_content_should_reload(
|
||||
path: &Path,
|
||||
content: Option<Vec<u8>>,
|
||||
observed: &mut Option<Vec<u8>>,
|
||||
last_self_write: &mut Option<SelfWriteRecord>,
|
||||
) -> bool {
|
||||
if content == *observed {
|
||||
return false;
|
||||
}
|
||||
let is_self_write = last_self_write.as_ref().is_some_and(|record| {
|
||||
record.path == path && content.as_deref() == Some(record.content.as_bytes())
|
||||
});
|
||||
*observed = content;
|
||||
if is_self_write {
|
||||
return false;
|
||||
}
|
||||
// A subsequent revert to our old snapshot is a real change too.
|
||||
if observed.is_some() {
|
||||
*last_self_write = None;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn self_write_still_matches_disk(record: Option<&SelfWriteRecord>, path: &Path) -> bool {
|
||||
let Some(record) = record else {
|
||||
return false;
|
||||
};
|
||||
record.path == path
|
||||
&& fs::read(path)
|
||||
.map(|content| content == record.content.as_bytes())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn should_protect_external_change(webview_dirty: bool, session_dirty: bool) -> bool {
|
||||
webview_dirty || session_dirty
|
||||
}
|
||||
|
||||
pub fn normalize_new_markdown_path(mut path: PathBuf) -> PathBuf {
|
||||
if !is_supported_document(&path) {
|
||||
path.set_extension("md");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// Write the active tab's file and remember the write as our own so the file
|
||||
/// watcher does not treat it as an external change. Returns false when nothing
|
||||
/// was written (no active file, or the write failed and SaveFailed was sent).
|
||||
pub fn save_active_file(
|
||||
session: &Arc<Mutex<DocumentSession>>,
|
||||
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
window_id: WindowId,
|
||||
content: &str,
|
||||
) -> bool {
|
||||
let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) else {
|
||||
return false;
|
||||
};
|
||||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: content.to_string(),
|
||||
});
|
||||
match fs::write(&path, content) {
|
||||
Ok(()) => {
|
||||
let _ = proxy.send_event(UserEvent::FileSaved(window_id, path));
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = proxy.send_event(UserEvent::SaveFailed(window_id, path, error.to_string()));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::temp_dir;
|
||||
use notify::EventKind;
|
||||
|
||||
#[test]
|
||||
fn only_markdown_extensions_are_supported_documents() {
|
||||
for name in ["note.md", "note.MARKDOWN", "note.mdown", "note.mkd"] {
|
||||
assert!(is_supported_document(Path::new(name)), "{name}");
|
||||
}
|
||||
for name in ["note.txt", "note.html", "note", "note.md.bak"] {
|
||||
assert!(!is_supported_document(Path::new(name)), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_urls_only_open_existing_supported_documents() {
|
||||
let dir = temp_dir("document-links");
|
||||
let linked = dir.join("含 空格.md");
|
||||
let unsupported = dir.join("page.html");
|
||||
fs::write(&linked, "# Linked").unwrap();
|
||||
fs::write(&unsupported, "<h1>Page</h1>").unwrap();
|
||||
|
||||
let linked_url = url::Url::from_file_path(&linked).unwrap().to_string();
|
||||
let unsupported_url = url::Url::from_file_path(&unsupported).unwrap().to_string();
|
||||
let missing_url = url::Url::from_file_path(dir.join("missing.md"))
|
||||
.unwrap()
|
||||
.to_string();
|
||||
|
||||
assert_eq!(
|
||||
local_document_path_from_url(&format!("{linked_url}#section")),
|
||||
Some(fs::canonicalize(&linked).unwrap())
|
||||
);
|
||||
assert_eq!(local_document_path_from_url(&unsupported_url), None);
|
||||
assert_eq!(local_document_path_from_url(&missing_url), None);
|
||||
assert_eq!(
|
||||
local_document_path_from_url("https://example.com/readme.md"),
|
||||
None
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_links_resolve_against_active_file_without_webview_base() {
|
||||
let dir = temp_dir("relative-doc-links");
|
||||
fs::create_dir_all(dir.join("folder")).unwrap();
|
||||
let active = dir.join("folder/current.md");
|
||||
let linked = dir.join("含 空格.md");
|
||||
fs::write(&linked, "# Linked").unwrap();
|
||||
let expected = Some(fs::canonicalize(&linked).unwrap());
|
||||
assert_eq!(
|
||||
resolve_document_link("../含%20空格.md#section", Some(&active)),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_document_link("../含 空格.md", Some(&active)),
|
||||
expected
|
||||
);
|
||||
assert_eq!(resolve_document_link("missing.md", Some(&active)), None);
|
||||
assert_eq!(
|
||||
resolve_document_link("https://example.com/file.md", Some(&active)),
|
||||
None
|
||||
);
|
||||
assert_eq!(resolve_document_link("../", Some(&active)), None);
|
||||
assert_eq!(resolve_document_link("relative.md", None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_markdown_path_keeps_markdown_extensions_and_replaces_other_extensions() {
|
||||
assert_eq!(
|
||||
normalize_new_markdown_path(PathBuf::from("/tmp/plan")),
|
||||
PathBuf::from("/tmp/plan.md")
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_new_markdown_path(PathBuf::from("/tmp/plan.markdown")),
|
||||
PathBuf::from("/tmp/plan.markdown")
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_new_markdown_path(PathBuf::from("/tmp/plan.txt")),
|
||||
PathBuf::from("/tmp/plan.md")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vim_style_target_rewrite_events_reload_current_file() {
|
||||
let target = PathBuf::from("/tmp/note.md");
|
||||
let ev = Event::new(EventKind::Create(notify::event::CreateKind::File))
|
||||
.add_path(PathBuf::from("/tmp/note.md"));
|
||||
|
||||
assert!(event_should_reload_file(&ev, &target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_file_events_do_not_reload_current_file() {
|
||||
let target = PathBuf::from("/tmp/note.md");
|
||||
let ev = Event::new(EventKind::Modify(notify::event::ModifyKind::Data(
|
||||
notify::event::DataChange::Any,
|
||||
)))
|
||||
.add_path(PathBuf::from("/tmp/other.md"));
|
||||
|
||||
assert!(!event_should_reload_file(&ev, &target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_write_suppression_checks_disk_content_not_only_time() {
|
||||
let dir = temp_dir("self-write-suppression");
|
||||
let path = dir.join("note.md");
|
||||
fs::write(&path, "saved by app").unwrap();
|
||||
let record = SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: "saved by app".to_string(),
|
||||
};
|
||||
|
||||
assert!(self_write_still_matches_disk(Some(&record), &path));
|
||||
|
||||
fs::write(&path, "external edit").unwrap();
|
||||
assert!(!self_write_still_matches_disk(Some(&record), &path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_events_ignore_identical_bytes_but_detect_external_edits_and_reverts() {
|
||||
let path = PathBuf::from("note.md");
|
||||
let mut observed = Some(b"initial".to_vec());
|
||||
let mut own = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: "saved".to_string(),
|
||||
});
|
||||
assert!(!file_content_should_reload(
|
||||
&path,
|
||||
Some(b"initial".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
assert!(!file_content_should_reload(
|
||||
&path,
|
||||
Some(b"saved".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
for _ in 0..100 {
|
||||
assert!(!file_content_should_reload(
|
||||
&path,
|
||||
Some(b"saved".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
}
|
||||
assert!(file_content_should_reload(
|
||||
&path,
|
||||
Some(b"external".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
assert!(file_content_should_reload(
|
||||
&path,
|
||||
Some(b"saved".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
assert!(file_content_should_reload(
|
||||
&path,
|
||||
None,
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
assert!(file_content_should_reload(
|
||||
&path,
|
||||
Some(b"saved".to_vec()),
|
||||
&mut observed,
|
||||
&mut own
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_change_protection_uses_dirty_state_from_either_side() {
|
||||
assert!(!should_protect_external_change(false, false));
|
||||
assert!(should_protect_external_change(true, false));
|
||||
assert!(should_protect_external_change(false, true));
|
||||
assert!(should_protect_external_change(true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_watch_scope_is_parent_directory() {
|
||||
let target = PathBuf::from("/tmp/note.md");
|
||||
|
||||
assert_eq!(watch_scope_for_file(&target), Path::new("/tmp"));
|
||||
}
|
||||
}
|
||||
4355
src/main.rs
4355
src/main.rs
File diff suppressed because it is too large
Load Diff
628
src/markdown.rs
Normal file
628
src/markdown.rs
Normal file
@@ -0,0 +1,628 @@
|
||||
//! Markdown -> HTML pipeline.
|
||||
//!
|
||||
//! GFM plus the app's deliberate dialect: single newlines are visible line
|
||||
//! breaks (AI output), front matter is split off, local images are embedded as
|
||||
//! data URLs, ==highlight== becomes <mark>, and headings get stable ids for
|
||||
//! folding and anchor navigation.
|
||||
|
||||
use crate::escape::html_escape_text;
|
||||
use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn md_to_html(md: &str) -> String {
|
||||
md_to_html_with_base(md, None)
|
||||
}
|
||||
|
||||
pub fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
|
||||
// A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it
|
||||
// before front-matter detection so both `---` metadata and a leading
|
||||
// heading still parse.
|
||||
let md = md.strip_prefix('\u{feff}').unwrap_or(md);
|
||||
let (front_matter, markdown) = split_yaml_front_matter(md)
|
||||
.map(|(metadata, body)| (Some(metadata), body))
|
||||
.unwrap_or((None, md));
|
||||
let opts = Options::ENABLE_TABLES
|
||||
| Options::ENABLE_STRIKETHROUGH
|
||||
| Options::ENABLE_TASKLISTS
|
||||
| Options::ENABLE_HEADING_ATTRIBUTES
|
||||
| Options::ENABLE_MATH
|
||||
| Options::ENABLE_GFM
|
||||
| Options::ENABLE_FOOTNOTES
|
||||
| Options::ENABLE_DEFINITION_LIST;
|
||||
let parser = Parser::new_ext(markdown, opts);
|
||||
let events = render_softbreaks_as_hard(embed_local_images(
|
||||
add_mark_highlights(add_heading_ids(parser.collect())),
|
||||
base_dir,
|
||||
));
|
||||
let mut html_out = String::new();
|
||||
if let Some(metadata) = front_matter {
|
||||
html_out.push_str(r#"<aside class="front-matter"><pre>"#);
|
||||
html_out.push_str(&html_escape_text(metadata.trim_end_matches(['\r', '\n'])));
|
||||
html_out.push_str("</pre></aside>\n");
|
||||
}
|
||||
html::push_html(&mut html_out, events.into_iter());
|
||||
html_out
|
||||
}
|
||||
|
||||
/// AI-generated Markdown often uses a single newline as a visual line break.
|
||||
/// Treat those soft breaks as hard breaks in normal prose, but keep headings
|
||||
/// untouched: a multi-line setext heading should stay one visual line.
|
||||
fn render_softbreaks_as_hard<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||
let mut heading_depth = 0usize;
|
||||
let mut out = Vec::with_capacity(events.len());
|
||||
for event in events {
|
||||
match &event {
|
||||
MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1,
|
||||
MdEvent::End(TagEnd::Heading(_)) => {
|
||||
heading_depth = heading_depth.saturating_sub(1);
|
||||
}
|
||||
MdEvent::SoftBreak if heading_depth == 0 => {
|
||||
out.push(MdEvent::HardBreak);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.push(event);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> {
|
||||
let mut lines = md.split_inclusive('\n');
|
||||
let first = lines.next()?;
|
||||
if first.trim_end_matches(['\r', '\n']) != "---" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let metadata_start = first.len();
|
||||
let mut offset = metadata_start;
|
||||
for line in lines {
|
||||
let value = line.trim_end_matches(['\r', '\n']);
|
||||
if value == "---" || value == "..." {
|
||||
let metadata = &md[metadata_start..offset];
|
||||
let body = &md[offset + line.len()..];
|
||||
return Some((metadata, body));
|
||||
}
|
||||
offset += line.len();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn embed_local_images<'a>(events: Vec<MdEvent<'a>>, base_dir: Option<&Path>) -> Vec<MdEvent<'a>> {
|
||||
let Some(base_dir) = base_dir else {
|
||||
return events;
|
||||
};
|
||||
|
||||
events
|
||||
.into_iter()
|
||||
.map(|event| match event {
|
||||
MdEvent::Start(Tag::Image {
|
||||
link_type,
|
||||
dest_url,
|
||||
title,
|
||||
id,
|
||||
}) => {
|
||||
let embedded = local_image_data_url(base_dir, dest_url.as_ref());
|
||||
MdEvent::Start(Tag::Image {
|
||||
link_type,
|
||||
dest_url: embedded.map(CowStr::from).unwrap_or(dest_url),
|
||||
title,
|
||||
id,
|
||||
})
|
||||
}
|
||||
_ => event,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn local_image_data_url(base_dir: &Path, url: &str) -> Option<String> {
|
||||
let image_path = resolve_local_relative_image_path(base_dir, url)?;
|
||||
let mime = image_mime_type(&image_path)?;
|
||||
let bytes = fs::read(image_path).ok()?;
|
||||
Some(format!("data:{mime};base64,{}", base64_encode(&bytes)))
|
||||
}
|
||||
|
||||
fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option<PathBuf> {
|
||||
let path_part = url.split(['#', '?']).next()?.trim();
|
||||
if !is_local_relative_url(path_part) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut candidate = base_dir.to_path_buf();
|
||||
for segment in path_part.split('/') {
|
||||
if segment.is_empty() || segment == "." {
|
||||
continue;
|
||||
}
|
||||
let decoded = percent_decode_path_segment(segment)?;
|
||||
let segment_path = Path::new(&decoded);
|
||||
if segment_path
|
||||
.components()
|
||||
.any(|component| !matches!(component, Component::Normal(_)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
candidate.push(segment_path);
|
||||
}
|
||||
|
||||
if candidate == base_dir {
|
||||
return None;
|
||||
}
|
||||
Some(candidate)
|
||||
}
|
||||
|
||||
fn is_local_relative_url(url: &str) -> bool {
|
||||
!url.is_empty()
|
||||
&& !url.starts_with('#')
|
||||
&& !url.starts_with('/')
|
||||
&& !url.starts_with('\\')
|
||||
&& !url.starts_with("//")
|
||||
&& !url.contains(':')
|
||||
}
|
||||
|
||||
fn percent_decode_path_segment(segment: &str) -> Option<String> {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' {
|
||||
let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?;
|
||||
let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?;
|
||||
out.push((hi << 4) | lo);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok()
|
||||
}
|
||||
|
||||
fn hex_value(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn image_mime_type(path: &Path) -> Option<&'static str> {
|
||||
match path
|
||||
.extension()?
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase()
|
||||
.as_str()
|
||||
{
|
||||
"png" => Some("image/png"),
|
||||
"jpg" | "jpeg" => Some("image/jpeg"),
|
||||
"gif" => Some("image/gif"),
|
||||
"webp" => Some("image/webp"),
|
||||
"svg" => Some("image/svg+xml"),
|
||||
"bmp" => Some("image/bmp"),
|
||||
"ico" => Some("image/x-icon"),
|
||||
"avif" => Some("image/avif"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn base64_encode(bytes: &[u8]) -> String {
|
||||
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||
let mut index = 0;
|
||||
while index + 3 <= bytes.len() {
|
||||
let n = ((bytes[index] as u32) << 16)
|
||||
| ((bytes[index + 1] as u32) << 8)
|
||||
| bytes[index + 2] as u32;
|
||||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[(n & 0x3f) as usize] as char);
|
||||
index += 3;
|
||||
}
|
||||
|
||||
match &bytes[index..] {
|
||||
[a] => {
|
||||
let n = (*a as u32) << 16;
|
||||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||
out.push('=');
|
||||
out.push('=');
|
||||
}
|
||||
[a, b] => {
|
||||
let n = ((*a as u32) << 16) | ((*b as u32) << 8);
|
||||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||||
out.push('=');
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn add_mark_highlights<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||
let mut out = Vec::with_capacity(events.len());
|
||||
let mut code_block_depth = 0usize;
|
||||
|
||||
for event in events {
|
||||
match &event {
|
||||
MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
|
||||
MdEvent::End(TagEnd::CodeBlock) => {
|
||||
code_block_depth = code_block_depth.saturating_sub(1);
|
||||
}
|
||||
MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => {
|
||||
push_mark_highlight_events(text.as_ref(), &mut out);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.push(event);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec<MdEvent<'a>>) {
|
||||
let mut rest = text;
|
||||
|
||||
while let Some(open) = rest.find("==") {
|
||||
let after_open = open + 2;
|
||||
let Some(close_rel) = rest[after_open..].find("==") else {
|
||||
break;
|
||||
};
|
||||
let close = after_open + close_rel;
|
||||
let body = &rest[after_open..close];
|
||||
if body.trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
if open > 0 {
|
||||
out.push(MdEvent::Text(CowStr::Boxed(
|
||||
rest[..open].to_string().into_boxed_str(),
|
||||
)));
|
||||
}
|
||||
out.push(MdEvent::Html(CowStr::Borrowed(
|
||||
r#"<mark class="mdp-mark">"#,
|
||||
)));
|
||||
out.push(MdEvent::Text(CowStr::Boxed(
|
||||
body.to_string().into_boxed_str(),
|
||||
)));
|
||||
out.push(MdEvent::Html(CowStr::Borrowed("</mark>")));
|
||||
rest = &rest[close + 2..];
|
||||
}
|
||||
|
||||
if !rest.is_empty() {
|
||||
out.push(MdEvent::Text(CowStr::Boxed(
|
||||
rest.to_string().into_boxed_str(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn add_heading_ids<'a>(mut events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||
|
||||
for i in 0..events.len() {
|
||||
let generate_id = match &events[i] {
|
||||
MdEvent::Start(Tag::Heading { id: Some(id), .. }) => {
|
||||
register_heading_id(id.as_ref(), &mut seen);
|
||||
false
|
||||
}
|
||||
MdEvent::Start(Tag::Heading { id: None, .. }) => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if !generate_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = collect_heading_text(&events, i);
|
||||
let base = heading_slug(&text);
|
||||
let id_value = unique_heading_id(base, &mut seen);
|
||||
if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] {
|
||||
*id = Some(CowStr::Boxed(id_value.into_boxed_str()));
|
||||
}
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String {
|
||||
let mut text = String::new();
|
||||
|
||||
for event in events.iter().skip(start + 1) {
|
||||
match event {
|
||||
MdEvent::End(TagEnd::Heading(_)) => break,
|
||||
MdEvent::Text(value)
|
||||
| MdEvent::Code(value)
|
||||
| MdEvent::InlineMath(value)
|
||||
| MdEvent::DisplayMath(value) => text.push_str(value.as_ref()),
|
||||
MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
text
|
||||
}
|
||||
|
||||
fn heading_slug(text: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut last_dash = false;
|
||||
|
||||
for c in text.trim().chars().flat_map(char::to_lowercase) {
|
||||
if c.is_alphanumeric() || c == '_' || c == '-' {
|
||||
slug.push(c);
|
||||
last_dash = false;
|
||||
} else if c.is_whitespace() && !slug.is_empty() && !last_dash {
|
||||
slug.push('-');
|
||||
last_dash = true;
|
||||
}
|
||||
}
|
||||
|
||||
while slug.ends_with('-') {
|
||||
slug.pop();
|
||||
}
|
||||
|
||||
if slug.is_empty() {
|
||||
"section".to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
fn register_heading_id(id: &str, seen: &mut HashMap<String, usize>) {
|
||||
if !id.is_empty() {
|
||||
*seen.entry(id.to_string()).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_heading_id(base: String, seen: &mut HashMap<String, usize>) -> String {
|
||||
let count = seen.entry(base.clone()).or_insert(0);
|
||||
let id = if *count == 0 {
|
||||
base
|
||||
} else {
|
||||
format!("{base}-{count}")
|
||||
};
|
||||
*count += 1;
|
||||
id
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::temp_dir;
|
||||
|
||||
#[test]
|
||||
fn base64_matches_known_vectors() {
|
||||
assert_eq!(base64_encode(b""), "");
|
||||
assert_eq!(base64_encode(b"f"), "Zg==");
|
||||
assert_eq!(base64_encode(b"fo"), "Zm8=");
|
||||
assert_eq!(base64_encode(b"foo"), "Zm9v");
|
||||
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
#[test]
|
||||
fn dollar_math_is_protected_from_markdown_escapes() {
|
||||
let html = md_to_html(r"$\{x\}$");
|
||||
|
||||
assert!(html.contains(r#"<span class="math math-inline">\{x\}</span>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dollar_math_is_protected_from_markdown_emphasis() {
|
||||
let html = md_to_html(r"$\bar{\mu}_{n}$ and $x_{n}$");
|
||||
|
||||
assert!(html.contains(r#"<span class="math math-inline">\bar{\mu}_{n}</span>"#));
|
||||
assert!(html.contains(r#"<span class="math math-inline">x_{n}</span>"#));
|
||||
assert!(!html.contains("<em>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_display_math_is_not_split_by_hard_breaks() {
|
||||
let html = md_to_html("$$\na + b\n$$");
|
||||
|
||||
assert!(html.contains(r#"class="math math-display""#), "{html}");
|
||||
assert!(html.contains("a + b"), "{html}");
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_alerts_render_as_markdown_alert_blockquotes() {
|
||||
let html = md_to_html("> [!IMPORTANT]\n> This is an alert");
|
||||
|
||||
assert!(html.contains(r#"<blockquote class="markdown-alert-important">"#));
|
||||
assert!(html.contains("<p>This is an alert</p>"));
|
||||
assert!(!html.contains("[!IMPORTANT]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_breaks_render_as_hard_breaks_in_paragraphs() {
|
||||
let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。");
|
||||
|
||||
assert!(
|
||||
html.contains("2.1 默认只读讨论。<br />\n2.2 默认工作流"),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_still_create_paragraphs() {
|
||||
let html = md_to_html("first line\n\nsecond line");
|
||||
|
||||
assert_eq!(html.matches("<p>").count(), 2, "{html}");
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_breaks_inside_headings_stay_soft() {
|
||||
let html = md_to_html("First heading line\nsecond heading line\n===");
|
||||
|
||||
assert!(html.contains("<h1"), "{html}");
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_breaks_in_list_items_become_hard_breaks() {
|
||||
let html = md_to_html("- first line\n second line");
|
||||
|
||||
assert!(html.contains("<li>first line<br />"), "{html}");
|
||||
assert!(html.contains("second line</li>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_blocks_keep_newlines_without_br() {
|
||||
let html = md_to_html("~~~text\nline one\nline two\n~~~");
|
||||
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
assert!(html.contains("line one\nline two"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gfm_footnotes_render_reference_and_definition() {
|
||||
let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body.");
|
||||
|
||||
assert!(html.contains(r#"class="footnote-reference""#), "{html}");
|
||||
assert!(html.contains(r#"class="footnote-definition""#), "{html}");
|
||||
assert!(html.contains("The footnote body."), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_lists_render_as_dl_dt_dd() {
|
||||
let html = md_to_html("Term\n: Definition");
|
||||
|
||||
assert!(html.contains("<dl>"), "{html}");
|
||||
assert!(html.contains("<dt>Term</dt>"), "{html}");
|
||||
assert!(html.contains("<dd>Definition</dd>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_bom_is_ignored_before_heading_and_front_matter() {
|
||||
let heading = md_to_html("\u{feff}# BOM heading");
|
||||
assert!(
|
||||
heading.contains(r#"<h1 id="bom-heading">BOM heading</h1>"#),
|
||||
"{heading}"
|
||||
);
|
||||
|
||||
let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body");
|
||||
assert!(
|
||||
front_matter.contains(r#"class="front-matter""#),
|
||||
"{front_matter}"
|
||||
);
|
||||
assert!(front_matter.contains("title: BOM"), "{front_matter}");
|
||||
assert!(
|
||||
front_matter.contains(r#"<h1 id="body">Body</h1>"#),
|
||||
"{front_matter}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_equals_highlight_renders_mark_without_touching_code() {
|
||||
let html = md_to_html("Use ==highlight & tag== here and `==literal==` there.");
|
||||
|
||||
assert!(html.contains(r#"Use <mark class="mdp-mark">highlight & tag</mark> here"#));
|
||||
assert!(html.contains("<code>==literal==</code>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_code_blocks_keep_double_equals_literal() {
|
||||
let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```");
|
||||
|
||||
assert!(
|
||||
html.contains("m_Profile == null"),
|
||||
"comparison must stay literal"
|
||||
);
|
||||
assert!(
|
||||
html.contains("a == b"),
|
||||
"every comparison must be preserved"
|
||||
);
|
||||
assert!(
|
||||
!html.contains("mdp-mark"),
|
||||
"code blocks must not get highlight markup"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_relative_images_are_embedded_from_markdown_directory() {
|
||||
let dir = temp_dir("local-image");
|
||||
let assets = dir.join("assets");
|
||||
fs::create_dir_all(&assets).unwrap();
|
||||
fs::write(assets.join("pixel.png"), b"abc").unwrap();
|
||||
|
||||
let html = md_to_html_with_base("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="data:image/png;base64,YWJj" alt="pixel" />"#));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_relative_images_keep_original_src_when_unreadable() {
|
||||
let dir = temp_dir("missing-image");
|
||||
|
||||
let html = md_to_html_with_base("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="assets/missing.png" alt="missing" />"#));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_relative_images_do_not_embed_parent_traversal() {
|
||||
let dir = temp_dir("traversal-image");
|
||||
|
||||
let html = md_to_html_with_base("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="../secret.png" alt="secret" />"#));
|
||||
assert!(!html.contains("data:image/png"));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_front_matter_keeps_metadata_readable_without_blank_lines() {
|
||||
let html = md_to_html(
|
||||
"---\nname: skill-creator-lite\ndescription: Skill 创建封装工具。\n---\n# Body",
|
||||
);
|
||||
|
||||
assert!(html.contains(r#"<aside class="front-matter">"#));
|
||||
assert!(html.contains("name: skill-creator-lite"));
|
||||
assert!(html.contains("description: Skill 创建封装工具。"));
|
||||
assert!(html.contains("<h1 id=\"body\">Body</h1>"));
|
||||
assert!(!html.contains("<h2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_front_matter_accepts_dots_and_escapes_html() {
|
||||
let html = md_to_html("---\ntitle: <script>alert(1)</script>\n...\nParagraph");
|
||||
|
||||
assert!(html.contains("title: <script>alert(1)</script>"));
|
||||
assert!(!html.contains("<script>alert(1)</script>"));
|
||||
assert!(html.contains("<p>Paragraph</p>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_rules_and_setext_headings_are_not_front_matter() {
|
||||
let html = md_to_html("Title\n---\n\nParagraph\n\n---");
|
||||
|
||||
assert!(!html.contains(r#"<aside class="front-matter">"#));
|
||||
assert!(html.contains(r#"<h2 id="title">Title</h2>"#));
|
||||
assert!(html.contains("<hr />"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_heading_ids_support_cjk_anchor_links() {
|
||||
let html = md_to_html("1. [需求概述](#需求概述)\n\n## 需求概述");
|
||||
|
||||
assert!(html.contains(r##"<a href="#%E9%9C%80%E6%B1%82%E6%A6%82%E8%BF%B0">需求概述</a>"##));
|
||||
assert!(html.contains(r#"<h2 id="需求概述">需求概述</h2>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_heading_ids_are_unique_and_keep_explicit_ids() {
|
||||
let html = md_to_html("## Intro\n## Intro\n## Custom {#fixed}\n## Fixed");
|
||||
|
||||
assert!(html.contains(r#"<h2 id="intro">Intro</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="intro-1">Intro</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="fixed">Custom</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="fixed-1">Fixed</h2>"#));
|
||||
}
|
||||
}
|
||||
337
src/page.rs
Normal file
337
src/page.rs
Normal file
@@ -0,0 +1,337 @@
|
||||
//! The single in-memory HTML document the webview loads.
|
||||
//!
|
||||
//! Markup, CSS and JS live in `assets/page/`; this module fills the
|
||||
//! `__MDP_*__` placeholders. Keeping the UI out of the Rust source means
|
||||
//! editing the page no longer requires escaping braces inside a `format!`
|
||||
//! string, and the JS can be syntax-checked as a real file.
|
||||
//!
|
||||
//! User content is substituted last so a document that happens to contain a
|
||||
//! placeholder-looking string is not rewritten by an earlier replacement.
|
||||
|
||||
use crate::app::{EnhanceFlags, Strings};
|
||||
use crate::escape::{escape_js, html_escape_attr, html_escape_ta};
|
||||
|
||||
const PAGE_HTML: &str = include_str!("../assets/page/page.html");
|
||||
const PAGE_CSS: &str = include_str!("../assets/page/page.css");
|
||||
const PAGE_JS: &str = include_str!("../assets/page/page.js");
|
||||
const PREVIEW_ENHANCE_JS: &str = include_str!("../assets/enhance/preview-enhance.js");
|
||||
const HLJS_CODE: &str = include_str!("../assets/hljs/vs-dark.css");
|
||||
const CM_CSS: &str = concat!(
|
||||
include_str!("../assets/codemirror/codemirror.min.css"),
|
||||
"\n",
|
||||
include_str!("../assets/codemirror/addon/fold/foldgutter.css"),
|
||||
"\n",
|
||||
include_str!("../assets/codemirror/addon/dialog/dialog.css"),
|
||||
);
|
||||
|
||||
pub fn build_page(
|
||||
preview_html: &str,
|
||||
raw_md: &str,
|
||||
base_href: Option<&str>,
|
||||
flags: EnhanceFlags,
|
||||
s: &Strings,
|
||||
home: bool,
|
||||
) -> String {
|
||||
let base_tag = base_href
|
||||
.map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href)))
|
||||
.unwrap_or_else(|| r#"<base id="base-href">"#.to_string());
|
||||
|
||||
PAGE_HTML
|
||||
.replace("__MDP_CSS_CODE__", HLJS_CODE)
|
||||
.replace("__MDP_CM_CSS__", CM_CSS)
|
||||
.replace("__MDP_PAGE_CSS__", PAGE_CSS)
|
||||
.replace("__MDP_PAGE_JS__", PAGE_JS)
|
||||
.replace("__MDP_PREVIEW_ENHANCE_JS__", PREVIEW_ENHANCE_JS)
|
||||
.replace("__MDP_BASE_TAG__", &base_tag)
|
||||
.replace("__MDP_BODY_CLASS__", if home { "home" } else { "" })
|
||||
.replace("__MDP_NEW_TAB__", s.new_tab)
|
||||
.replace("__MDP_BTN_OPEN_LOCATION__", s.btn_open_location)
|
||||
.replace("__MDP_BTN_NEW_WINDOW__", s.btn_new_window)
|
||||
.replace("__MDP_BTN_EDIT__", s.btn_edit)
|
||||
.replace("__MDP_BTN_PREVIEW__", s.btn_preview)
|
||||
.replace("__MDP_HOME_TAB__", &escape_js(s.home_tab))
|
||||
.replace("__MDP_FOLD_TOGGLE__", s.fold_toggle)
|
||||
.replace("__MDP_CANNOT_SAVE_JS__", &escape_js(s.cannot_save))
|
||||
.replace("__MDP_BTN_ZOOM__", s.btn_zoom)
|
||||
.replace("__MDP_BTN_ZOOM_OUT__", s.btn_zoom_out)
|
||||
.replace("__MDP_BTN_ZOOM_RESET__", s.btn_zoom_reset)
|
||||
.replace("__MDP_BTN_ZOOM_IN__", s.btn_zoom_in)
|
||||
.replace("__MDP_SEARCH_PLACEHOLDER__", s.search_placeholder)
|
||||
.replace("__MDP_STAT_WORDS_JS__", &escape_js(s.stat_words))
|
||||
.replace("__MDP_STAT_CHARS_JS__", &escape_js(s.stat_chars))
|
||||
.replace(
|
||||
"__MDP_NEEDS_MATH__",
|
||||
if flags.math { "true" } else { "false" },
|
||||
)
|
||||
.replace(
|
||||
"__MDP_NEEDS_MERMAID__",
|
||||
if flags.mermaid { "true" } else { "false" },
|
||||
)
|
||||
.replace("__MDP_PREVIEW_HTML__", preview_html)
|
||||
.replace("__MDP_RAW_MD_ESCAPED__", &html_escape_ta(raw_md))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::{EnhanceFlags, Strings};
|
||||
use crate::markdown::md_to_html;
|
||||
|
||||
#[test]
|
||||
fn page_blocks_native_preview_reload_paths() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("document.addEventListener('contextmenu'"));
|
||||
assert!(page.contains("window.ipc.postMessage('refresh')"));
|
||||
assert!(!page.contains("id=\"btn-open\""));
|
||||
assert!(!page.contains("id=\"btn-print\""));
|
||||
assert!(!page.contains("id=\"btn-search\""));
|
||||
assert!(page.contains("window.ipc.postMessage('open')"));
|
||||
assert!(page.contains("window.__mdPreviewOpenFile = openFile"));
|
||||
assert!(page.contains("window.__mdPreviewShowFind = showFind"));
|
||||
assert!(page.contains("window.__mdPreviewToggleEdit"));
|
||||
assert!(page.contains("function selectionSeed()"));
|
||||
assert!(page.contains("showFind(seed ? seed.text : ''"));
|
||||
assert!(page.contains("function findStartIndex(anchorTop)"));
|
||||
assert!(page.contains("return lastAbove >= 0 ? lastAbove : 0"));
|
||||
assert!(page.contains("findInput.focus({ preventScroll: true })"));
|
||||
assert!(page.contains("selectFindHit(findStartIndex(anchorTop), reveal)"));
|
||||
assert!(page.contains("runFindQuery(seed, anchorTop, false)"));
|
||||
assert!(page.contains("var INDENT = ' ';"));
|
||||
assert!(page.contains("insertNewlineWithIndent"));
|
||||
assert!(page.contains("document.execCommand('insertText'"));
|
||||
assert!(page.contains("id=\"hljs-code\""));
|
||||
assert!(page.contains("#preview pre { background: #1e1e1e;"));
|
||||
assert!(!page.contains("hljs-light"));
|
||||
assert!(page.contains("ta.focus({ preventScroll: true })"));
|
||||
assert!(page.contains("window.__setEmptyPreview"));
|
||||
assert!(page.contains("id=\"tabbar\""));
|
||||
assert!(page.contains("window.__setTabs"));
|
||||
assert!(page.contains("tab-action:'));") || page.contains("'tab-action:' + action"));
|
||||
assert!(page.contains("window.__markSaved"));
|
||||
assert!(
|
||||
!page.contains("window.ipc.postMessage('save:' + ta.value);\n\t setDirty(false);")
|
||||
);
|
||||
assert!(page.contains("compositionstart"));
|
||||
assert!(page.contains("e.isComposing"));
|
||||
assert!(page.contains("focusFindInput"));
|
||||
assert!(page.contains("FIND_DEBOUNCE_MS = 300"));
|
||||
assert!(page.contains("document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT"));
|
||||
assert!(page.contains("mark.className = 'search-hit'"));
|
||||
assert!(page.contains("selectFindHit(currentFindHit + (backward ? -1 : 1))"));
|
||||
assert!(page.contains("#preview mark.search-hit.current"));
|
||||
assert!(page.contains("restoreFindInput(selectionStart, selectionEnd)"));
|
||||
assert!(page.contains("findInput.setSelectionRange(selectionStart, selectionEnd)"));
|
||||
assert!(page.contains("bindAnchorNavigation"));
|
||||
assert!(page.contains("event.target.closest('#preview a[href]')"));
|
||||
assert!(page.contains("window.ipc.postMessage('open-local-link:' + href)"));
|
||||
assert!(page.contains(".markdown-alert-important"));
|
||||
assert!(page.contains(".markdown-alert-title"));
|
||||
let light_alert = page.find("background: #dafbe1").unwrap();
|
||||
let dark_alert = page.rfind("background: #161b22; color: #d4d4d4").unwrap();
|
||||
assert!(dark_alert > light_alert);
|
||||
assert!(page.contains(".mdp-mark"));
|
||||
assert!(!page.contains("Local-first Markdown preview for AI-generated docs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_separates_new_file_from_open_and_debounces_autosave() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("window.ipc.postMessage('new-file')"));
|
||||
assert!(page.contains("tabOpen.addEventListener('click', newTab)"));
|
||||
assert!(!page.contains("tabOpen.addEventListener('click', newFile)"));
|
||||
assert!(!page.contains("tabOpen.addEventListener('click', openFile)"));
|
||||
assert!(page.contains("requestTabAction('new-tab', 0)"));
|
||||
assert!(page.contains("data-new-file"));
|
||||
assert!(page.contains("HIDE_SINGLE_HOME_TAB = true"));
|
||||
assert!(page.contains("tabs.length === 1 && !tabs[0].home"));
|
||||
assert!(page.contains("L_HOME = 'New Tab'"));
|
||||
assert!(
|
||||
page.matches("if (document.body.classList.contains('home')) return;")
|
||||
.count()
|
||||
>= 2
|
||||
);
|
||||
assert!(page.contains("if (tabCount === 1 && isHome) close.hidden = true"));
|
||||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1 || isHome"));
|
||||
assert!(page.contains("AUTOSAVE_DEBOUNCE_MS = 700"));
|
||||
assert!(page.contains("pendingAutosaveTimer = setTimeout"));
|
||||
assert!(page.contains("window.__markSaved = function(savedRaw)"));
|
||||
assert!(page.contains("window.__markSaveBlocked"));
|
||||
assert!(page.contains("var saveBlocked = false"));
|
||||
assert!(page.contains("window.__mdPreviewCannotSave"));
|
||||
assert!(page.contains("window.__mdPreviewResolveExternalChange"));
|
||||
assert!(page.contains("'external-change:' + (dirty ? 'dirty' : 'clean')"));
|
||||
assert!(page.contains("(e.key === 'n' || e.key === 'N')"));
|
||||
assert!(page.contains("id=\"doc-stats\""));
|
||||
assert!(page.contains("id=\"tab-menu\""));
|
||||
assert!(page.contains("id=\"tab-menu-path\""));
|
||||
assert!(page.contains("id=\"tab-menu-reveal\""));
|
||||
assert!(page.contains("data-tab-path"));
|
||||
assert!(page.contains("function shortenPath"));
|
||||
assert!(page.contains("tabsEl.addEventListener('pointerdown'"));
|
||||
assert!(page.contains("suppressTabClickUntil"));
|
||||
assert!(page.contains("tabCount = tabs.length"));
|
||||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1"));
|
||||
assert!(page.contains("updateDocumentStats"));
|
||||
assert!(page.contains("restoreScrollProgress"));
|
||||
assert!(page.contains("postMessage('scroll:' + activeTabId"));
|
||||
assert!(page.contains("setEditMode(!!editing)"));
|
||||
assert!(page.contains("postMessage('edit-mode:' + activeTabId"));
|
||||
assert!(page.contains("postMessage('zoom:' + zoomPercent)"));
|
||||
assert!(page.contains("window.__mdPreviewSetZoom"));
|
||||
assert!(page.contains("id=\"btn-zoom-in\""));
|
||||
assert!(page.contains("id=\"btn-zoom-out\""));
|
||||
assert!(page.contains("id=\"btn-zoom-reset\""));
|
||||
assert!(page.contains("var ZOOM_MIN = 50"));
|
||||
assert!(page.contains("var ZOOM_MAX = 300"));
|
||||
assert!(page.contains("var ZOOM_STEP = 5"));
|
||||
assert!(page.contains("ZOOM_WHEEL_THROTTLE_MS = 90"));
|
||||
assert!(page.contains("if (!e.ctrlKey) return;"));
|
||||
assert!(
|
||||
page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_get_hover_fold_toggles() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# A\n\n## B\n\ntext"),
|
||||
"# A\n\n## B\n\ntext",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("mdp-fold-toggle"));
|
||||
assert!(page.contains("mdp-fold-body"));
|
||||
assert!(page.contains(".mdp-fold.collapsed > .mdp-fold-body { display: none; }"));
|
||||
assert!(page.contains("window.__mdPreviewFoldLabel"));
|
||||
assert!(page.contains("window.__mdPreviewExpandFold"));
|
||||
assert!(page.contains("sectionizeFolds"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_loads_codemirror_lazily_on_first_edit() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
// The editor bundle arrives through Rust on demand, never in the
|
||||
// first-paint HTML; the page only declares the host and the hook.
|
||||
assert!(page.contains(r#"<div id="cm-editor""#));
|
||||
assert!(page.contains("window.ipc.postMessage('need-editor')"));
|
||||
assert!(page.contains("window.__mdpOnEditorSource"));
|
||||
assert!(page.contains("function createCodeMirror()"));
|
||||
assert!(page.contains("CM_MAX_BYTES = 2 * 1024 * 1024"));
|
||||
assert!(page.contains("CodeMirror-linenumbers"));
|
||||
assert!(page.contains("rangeFinder: markdownFoldRange"));
|
||||
assert!(page.contains("body.finding .findbar:not(#edit-findbar)"));
|
||||
assert!(page.contains("var fileHasBom = false"));
|
||||
assert!(page.contains("function fileContentForSave()"));
|
||||
assert!(page.contains("pendingEditFind"));
|
||||
assert!(page.contains("var switched ="));
|
||||
assert!(page.contains("function fenceCharAt"));
|
||||
assert!(page.contains("__mdpFenceCache"));
|
||||
assert!(page.contains("specialChars: /["));
|
||||
assert!(!page.contains("\\ufeff"));
|
||||
assert!(page.contains("openEditFind(false)"));
|
||||
assert!(page.contains("openEditFind(true)"));
|
||||
assert!(!page.contains("CodeMirror.defineMode"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_mode_find_bar_has_clickable_controls_and_no_escape_exit() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# A\n\ntext"),
|
||||
"# A\n\ntext",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains(r#"id="edit-findbar""#));
|
||||
assert!(page.contains(r#"id="edit-find-input""#));
|
||||
assert!(page.contains(r#"id="edit-find-prev""#));
|
||||
assert!(page.contains(r#"id="edit-find-next""#));
|
||||
assert!(page.contains(r#"id="edit-replace-input""#));
|
||||
assert!(page.contains(r#"id="edit-replace-all""#));
|
||||
assert!(page.contains("function openEditFind(replaceMode)"));
|
||||
assert!(page.contains("function closeEditFind()"));
|
||||
assert!(page.contains("cm.getSearchCursor(query"));
|
||||
assert!(page.contains("document.documentElement.classList.toggle('cm-editing'"));
|
||||
assert!(page.contains("minFoldSize: 0"));
|
||||
assert!(page.contains("var lineNo = typeof line === 'number'"));
|
||||
assert!(page.contains("appEl.addEventListener('scroll', reportScroll"));
|
||||
assert!(page.contains("cm.lineAtHeight(info.top + 1, 'local')"));
|
||||
assert!(page.contains("function cmScrollToLine(line)"));
|
||||
assert!(page.contains("width: min(560px, calc(100vw - 32px))"));
|
||||
assert!(page.contains("edit-find-row"));
|
||||
assert!(page.contains("widget: '⋯'"));
|
||||
// Escape closes the find bar; it must not leave edit mode anymore.
|
||||
assert!(!page.contains("if (e.key === 'Escape' && inEdit()) { leaveEdit(); }"));
|
||||
assert!(!page.contains("'Esc': function() { leaveEdit(); }"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_expands_multi_column_tables() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | 4 |"),
|
||||
"",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("mdp-table-wrap"));
|
||||
assert!(page.contains("width: min(calc(100vw - 64px), 1280px)"));
|
||||
assert!(page.contains("if(window.__enhancePreview)window.__enhancePreview();"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_last_editing_tab_restores_the_empty_preview() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
let empty_start = page.find("window.__setEmptyPreview = function").unwrap();
|
||||
let missing_start = page.find("window.__setMissing = function").unwrap();
|
||||
let empty_handler = &page[empty_start..missing_start];
|
||||
|
||||
assert!(empty_handler.contains("document.body.classList.add('home')"));
|
||||
assert!(empty_handler.contains("setEditMode(false)"));
|
||||
}
|
||||
}
|
||||
399
src/session.rs
399
src/session.rs
@@ -1,15 +1,29 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DocumentTab {
|
||||
pub id: u64,
|
||||
pub path: PathBuf,
|
||||
/// `None` marks the built-in Home tab; Home has no file on disk.
|
||||
pub path: Option<PathBuf>,
|
||||
pub dirty: bool,
|
||||
pub missing: bool,
|
||||
pub edit_on_open: bool,
|
||||
/// Edit mode belongs to the tab, so switching tabs restores the mode the
|
||||
/// tab was left in instead of carrying one global mode across documents.
|
||||
pub editing: bool,
|
||||
/// Viewport position as a 0.0 (top) ..= 1.0 (bottom) fraction. Stores a
|
||||
/// ratio rather than pixels so zoom and reflow do not move the reader.
|
||||
pub scroll_ratio: f32,
|
||||
}
|
||||
|
||||
impl DocumentTab {
|
||||
pub fn is_home(&self) -> bool {
|
||||
self.path.is_none()
|
||||
}
|
||||
|
||||
pub fn file_path(&self) -> Option<&Path> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -19,64 +33,101 @@ pub struct DocumentSession {
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct PersistedSession {
|
||||
version: u8,
|
||||
active: Option<usize>,
|
||||
tabs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl DocumentSession {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let Ok(raw) = fs::read(path) else {
|
||||
return Self::default();
|
||||
};
|
||||
let Ok(saved) = serde_json::from_slice::<PersistedSession>(&raw) else {
|
||||
return Self::default();
|
||||
};
|
||||
if saved.version != 1 {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let mut session = Self::default();
|
||||
for path in saved.tabs {
|
||||
session.open(path, false);
|
||||
}
|
||||
session.active_id = saved
|
||||
.active
|
||||
.and_then(|index| session.tabs.get(index))
|
||||
.map(|tab| tab.id)
|
||||
.or_else(|| session.tabs.last().map(|tab| tab.id));
|
||||
session
|
||||
}
|
||||
|
||||
pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
|
||||
let path = normalize_path(path);
|
||||
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) {
|
||||
tab.missing = !tab.path.exists();
|
||||
tab.edit_on_open |= edit_on_open;
|
||||
if let Some(tab) = self
|
||||
.tabs
|
||||
.iter_mut()
|
||||
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
|
||||
{
|
||||
tab.missing = !path.exists();
|
||||
tab.editing |= edit_on_open;
|
||||
self.active_id = Some(tab.id);
|
||||
return tab.id;
|
||||
}
|
||||
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
let missing = !path.exists();
|
||||
self.tabs.push(DocumentTab {
|
||||
id,
|
||||
missing: !path.exists(),
|
||||
path,
|
||||
path: Some(path),
|
||||
dirty: false,
|
||||
edit_on_open,
|
||||
missing,
|
||||
editing: edit_on_open,
|
||||
scroll_ratio: 0.0,
|
||||
});
|
||||
self.active_id = Some(id);
|
||||
id
|
||||
}
|
||||
|
||||
/// Append and activate a Home tab (the in-app "new tab page").
|
||||
pub fn open_home(&mut self) -> u64 {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.tabs.push(DocumentTab {
|
||||
id,
|
||||
path: None,
|
||||
dirty: false,
|
||||
missing: false,
|
||||
editing: false,
|
||||
scroll_ratio: 0.0,
|
||||
});
|
||||
self.active_id = Some(id);
|
||||
id
|
||||
}
|
||||
|
||||
/// Open `path`, turning the active Home tab into the document when possible
|
||||
/// (browser-style navigation). Falls back to appending a tab otherwise.
|
||||
pub fn open_reusing_home(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
|
||||
let Some(active_id) = self.active_id else {
|
||||
return self.open(path, edit_on_open);
|
||||
};
|
||||
if !self
|
||||
.tabs
|
||||
.iter()
|
||||
.any(|tab| tab.id == active_id && tab.is_home())
|
||||
{
|
||||
return self.open(path, edit_on_open);
|
||||
}
|
||||
|
||||
let path = normalize_path(path);
|
||||
if let Some(existing) = self
|
||||
.tabs
|
||||
.iter_mut()
|
||||
.find(|tab| tab.id != active_id && tab.path.as_deref() == Some(path.as_path()))
|
||||
{
|
||||
existing.missing = !path.exists();
|
||||
existing.editing |= edit_on_open;
|
||||
let existing_id = existing.id;
|
||||
// The blank tab did its job; drop it the way a browser would.
|
||||
self.tabs.retain(|tab| tab.id != active_id);
|
||||
self.active_id = Some(existing_id);
|
||||
return existing_id;
|
||||
}
|
||||
|
||||
let missing = !path.exists();
|
||||
let tab = self
|
||||
.tabs
|
||||
.iter_mut()
|
||||
.find(|tab| tab.id == active_id)
|
||||
.expect("active tab disappeared");
|
||||
tab.path = Some(path);
|
||||
tab.missing = missing;
|
||||
tab.dirty = false;
|
||||
tab.editing = edit_on_open;
|
||||
tab.scroll_ratio = 0.0;
|
||||
active_id
|
||||
}
|
||||
|
||||
pub fn activate(&mut self, id: u64) -> bool {
|
||||
let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else {
|
||||
return false;
|
||||
};
|
||||
tab.missing = !tab.path.exists();
|
||||
if let Some(path) = tab.path.as_deref() {
|
||||
tab.missing = !path.exists();
|
||||
}
|
||||
self.active_id = Some(id);
|
||||
true
|
||||
}
|
||||
@@ -97,26 +148,41 @@ impl DocumentSession {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn save(&self, path: &Path) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
/// Close a tab and leave a fresh Home tab behind when it was the last one.
|
||||
pub fn close_with_home_fallback(&mut self, id: u64) -> bool {
|
||||
if !self.close(id) {
|
||||
return false;
|
||||
}
|
||||
let active = self
|
||||
.active_id
|
||||
.and_then(|id| self.tabs.iter().position(|tab| tab.id == id));
|
||||
let saved = PersistedSession {
|
||||
version: 1,
|
||||
active,
|
||||
tabs: self.tabs.iter().map(|tab| tab.path.clone()).collect(),
|
||||
};
|
||||
let body = serde_json::to_vec_pretty(&saved).map_err(io::Error::other)?;
|
||||
let temporary = path.with_extension("json.tmp");
|
||||
fs::write(&temporary, body)?;
|
||||
#[cfg(target_os = "windows")]
|
||||
if path.exists() {
|
||||
fs::remove_file(path)?;
|
||||
if self.tabs.is_empty() {
|
||||
self.open_home();
|
||||
}
|
||||
fs::rename(temporary, path)
|
||||
true
|
||||
}
|
||||
|
||||
pub fn with_tab(tab: DocumentTab) -> Self {
|
||||
let id = tab.id;
|
||||
Self {
|
||||
tabs: vec![tab],
|
||||
active_id: Some(id),
|
||||
next_id: id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detach(&mut self, id: u64) -> Option<DocumentTab> {
|
||||
let index = self.tabs.iter().position(|tab| tab.id == id)?;
|
||||
if self.tabs[index].is_home() {
|
||||
return None;
|
||||
}
|
||||
let was_active = self.active_id == Some(id);
|
||||
let tab = self.tabs.remove(index);
|
||||
if was_active {
|
||||
self.active_id = self
|
||||
.tabs
|
||||
.get(index)
|
||||
.or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i)))
|
||||
.map(|tab| tab.id);
|
||||
}
|
||||
Some(tab)
|
||||
}
|
||||
|
||||
pub fn active(&self) -> Option<&DocumentTab> {
|
||||
@@ -129,25 +195,68 @@ impl DocumentSession {
|
||||
self.tabs.iter_mut().find(|tab| tab.id == id)
|
||||
}
|
||||
|
||||
pub fn active_path(&self) -> Option<&Path> {
|
||||
self.active().and_then(DocumentTab::file_path)
|
||||
}
|
||||
|
||||
pub fn active_is_home(&self) -> bool {
|
||||
self.active().is_some_and(DocumentTab::is_home)
|
||||
}
|
||||
|
||||
/// Remember the viewport of the active tab (0.0 top .. 1.0 bottom).
|
||||
pub fn set_active_scroll_ratio(&mut self, ratio: f32) {
|
||||
if !ratio.is_finite() {
|
||||
return;
|
||||
}
|
||||
if let Some(tab) = self.active_mut() {
|
||||
tab.scroll_ratio = ratio.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Store the viewport by tab id; late scroll reports must not land on a tab
|
||||
/// that was activated in the meantime.
|
||||
pub fn set_tab_scroll_ratio(&mut self, id: u64, ratio: f32) {
|
||||
if !ratio.is_finite() {
|
||||
return;
|
||||
}
|
||||
if let Some(tab) = self.get_mut(id) {
|
||||
tab.scroll_ratio = ratio.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_tab_editing(&mut self, id: u64, editing: bool) {
|
||||
if let Some(tab) = self.get_mut(id) {
|
||||
tab.editing = editing;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
|
||||
self.tabs.iter_mut().find(|tab| tab.id == id)
|
||||
}
|
||||
|
||||
pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool {
|
||||
let path = normalize_path(path);
|
||||
if self.tabs.iter().any(|tab| tab.id != id && tab.path == path) {
|
||||
if self
|
||||
.tabs
|
||||
.iter()
|
||||
.any(|tab| tab.id != id && tab.path.as_deref() == Some(path.as_path()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let missing = !path.exists();
|
||||
let Some(tab) = self.get_mut(id) else {
|
||||
return false;
|
||||
};
|
||||
tab.path = path;
|
||||
tab.missing = !tab.path.exists();
|
||||
if tab.is_home() {
|
||||
return false;
|
||||
}
|
||||
tab.path = Some(path);
|
||||
tab.missing = missing;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_path(path: PathBuf) -> PathBuf {
|
||||
pub(crate) fn normalize_path(path: PathBuf) -> PathBuf {
|
||||
let absolute = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
@@ -211,7 +320,7 @@ mod tests {
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert_eq!(session.active_id, Some(first));
|
||||
assert!(session.tabs[0].edit_on_open);
|
||||
assert!(session.tabs[0].editing);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
@@ -234,6 +343,126 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detaching_a_tab_keeps_source_and_adopts_it_in_new_session() {
|
||||
let dir = temp_dir("detach");
|
||||
let mut session = DocumentSession::default();
|
||||
let first = session.open(dir.join("one.md"), false);
|
||||
let second = session.open(dir.join("two.md"), false);
|
||||
session.activate(first);
|
||||
|
||||
let moved = session.detach(second).unwrap();
|
||||
assert_eq!(session.active_id, Some(first));
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
|
||||
let adopted = DocumentSession::with_tab(moved);
|
||||
assert_eq!(adopted.active_id, Some(second));
|
||||
assert_eq!(adopted.tabs.len(), 1);
|
||||
assert_eq!(adopted.tabs[0].id, second);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_tab_is_a_tab_without_a_file_path() {
|
||||
let mut session = DocumentSession::default();
|
||||
|
||||
let home = session.open_home();
|
||||
|
||||
assert_eq!(session.active_id, Some(home));
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert!(session.tabs[0].is_home());
|
||||
assert_eq!(session.active_path(), None);
|
||||
assert!(session.active_is_home());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_file_from_home_reuses_the_home_tab() {
|
||||
let dir = temp_dir("home-reuse");
|
||||
let file = dir.join("note.md");
|
||||
fs::write(&file, "# Note").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
let home = session.open_home();
|
||||
|
||||
let opened = session.open_reusing_home(file.clone(), true);
|
||||
|
||||
assert_eq!(opened, home);
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert!(!session.tabs[0].is_home());
|
||||
assert_eq!(session.tabs[0].file_path(), Some(file.as_path()));
|
||||
assert!(session.tabs[0].editing);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_an_already_open_file_from_home_drops_the_blank_tab() {
|
||||
let dir = temp_dir("home-dedupe");
|
||||
let first = dir.join("one.md");
|
||||
fs::write(&first, "one").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
let first_id = session.open(first.clone(), false);
|
||||
let home = session.open_home();
|
||||
|
||||
let opened = session.open_reusing_home(first, false);
|
||||
|
||||
assert_eq!(opened, first_id);
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert_eq!(session.active_id, Some(first_id));
|
||||
assert!(!session.tabs.iter().any(|tab| tab.id == home));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_tab_cannot_be_detached_or_relocated() {
|
||||
let dir = temp_dir("home-guard");
|
||||
let mut session = DocumentSession::default();
|
||||
let home = session.open_home();
|
||||
|
||||
assert!(session.detach(home).is_none());
|
||||
assert!(!session.relocate(home, dir.join("note.md")));
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_last_file_leaves_a_home_tab() {
|
||||
let dir = temp_dir("close-home");
|
||||
let file = dir.join("note.md");
|
||||
fs::write(&file, "").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
let file_id = session.open(file, false);
|
||||
|
||||
assert!(session.close_with_home_fallback(file_id));
|
||||
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert!(session.active().unwrap().is_home());
|
||||
assert_eq!(session.active_id, Some(session.tabs[0].id));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_mode_and_scroll_position_are_remembered_per_tab() {
|
||||
let dir = temp_dir("per-tab-view");
|
||||
let mut session = DocumentSession::default();
|
||||
let first = session.open(dir.join("one.md"), true);
|
||||
session.set_active_scroll_ratio(0.75);
|
||||
let second = session.open(dir.join("two.md"), false);
|
||||
|
||||
assert_ne!(first, second);
|
||||
assert!(!session.active().unwrap().editing);
|
||||
assert_eq!(session.active().unwrap().scroll_ratio, 0.0);
|
||||
|
||||
assert!(session.activate(first));
|
||||
assert!(session.active().unwrap().editing);
|
||||
assert_eq!(session.active().unwrap().scroll_ratio, 0.75);
|
||||
|
||||
// Late reports address the tab by id, not by whichever tab is active.
|
||||
session.set_tab_scroll_ratio(second, 0.4);
|
||||
assert!(session.activate(second));
|
||||
assert_eq!(session.active().unwrap().scroll_ratio, 0.4);
|
||||
assert!(!session.active().unwrap().editing);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn opened_paths_drop_windows_verbatim_prefix() {
|
||||
@@ -244,38 +473,16 @@ mod tests {
|
||||
|
||||
session.open(file.clone(), false);
|
||||
|
||||
let stored = session.tabs[0].path.to_string_lossy().to_string();
|
||||
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
|
||||
assert!(session.tabs[0].path.ends_with("note.md"));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_session_keeps_missing_tabs_and_active_order() {
|
||||
let dir = temp_dir("roundtrip");
|
||||
let state_path = dir.join("session.json");
|
||||
let existing = dir.join("existing.md");
|
||||
let missing = dir.join("missing.md");
|
||||
fs::write(&existing, "# Existing").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
session.open(existing.clone(), false);
|
||||
session.open(missing.clone(), false);
|
||||
|
||||
session.save(&state_path).unwrap();
|
||||
let restored = DocumentSession::load(&state_path);
|
||||
|
||||
assert_eq!(restored.tabs.len(), 2);
|
||||
assert_eq!(
|
||||
restored.tabs[0].path,
|
||||
strip_verbatim(fs::canonicalize(existing).unwrap())
|
||||
let stored = session.tabs[0]
|
||||
.file_path()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
assert!(
|
||||
!stored.starts_with(r"\\?\"),
|
||||
"verbatim prefix leaked: {stored}"
|
||||
);
|
||||
assert_eq!(
|
||||
restored.tabs[1].path,
|
||||
strip_verbatim(fs::canonicalize(&dir).unwrap()).join(missing.file_name().unwrap())
|
||||
);
|
||||
assert!(!restored.tabs[0].missing);
|
||||
assert!(restored.tabs[1].missing);
|
||||
assert_eq!(restored.active_id, restored.tabs.get(1).map(|tab| tab.id));
|
||||
assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
18
src/testutil.rs
Normal file
18
src/testutil.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
//! Test-only helpers shared by the module test suites.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Create a unique scratch directory under the platform temp dir (the test
|
||||
/// runner points TEMP/TMP at `target\tmp`).
|
||||
pub fn temp_dir(name: &str) -> PathBuf {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("md-preview-{name}-{}-{unique}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
Reference in New Issue
Block a user