Compare commits
5 Commits
v1.4.2-loc
...
dd4083fe80
| Author | SHA1 | Date | |
|---|---|---|---|
| dd4083fe80 | |||
| d90e47e606 | |||
| 809b7b0299 | |||
| abeb426a43 | |||
| 47e71cf692 |
10
Cargo.lock
generated
10
Cargo.lock
generated
@@ -1684,7 +1684,6 @@ dependencies = [
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"tao",
|
||||
"url",
|
||||
"winreg",
|
||||
@@ -2822,15 +2821,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"
|
||||
|
||||
@@ -12,7 +12,6 @@ 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"
|
||||
|
||||
24
README.md
24
README.md
@@ -12,7 +12,8 @@
|
||||
|
||||
- **双击即开**:单个 exe(约 5.5 MB),不用安装;可设为 `.md` 的默认打开方式。
|
||||
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
|
||||
- **多标签 + 多窗口**:标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
|
||||
- **多标签 + 多窗口**:新标签页(New Tab)本身就是一个默认标签,标签栏的 `+` 新建一个 New Tab;在 New Tab 里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到 New Tab,只剩 New Tab 时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
|
||||
- **英文界面**:界面文案统一为英文,不随系统语言切换,避免中英文混排。
|
||||
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
|
||||
- **长文档友好**:
|
||||
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
|
||||
@@ -24,7 +25,7 @@
|
||||
|
||||
## 下载与运行
|
||||
|
||||
1. 在 [Releases](https://git.wucl12.cn/wucl12/md-preview/releases) 页下载 `MD-Preview-windows-x64.exe`(当前发布版本 `v1.4.2-local.3`,2026-10-28);
|
||||
1. 在 [Releases](https://git.wucl12.cn/wucl12/md-preview/releases) 页下载 `MD-Preview-windows-x64.exe`(当前发布版本 `v1.4.2-local.4`,2026-10-28);
|
||||
2. 放到一个固定目录(例如 `D:\Scripts\md-preview\`),不要随意改名/移动;
|
||||
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认;
|
||||
4. Windows 10/11 一般自带 WebView2 Runtime;若提示缺失,安装微软的 Evergreen Runtime 即可。
|
||||
@@ -36,11 +37,13 @@
|
||||
|
||||
| 操作 | 方式 |
|
||||
|---|---|
|
||||
| 打开文件 | 双击 `.md`、拖进窗口、`Ctrl+O`、首页“最近文件” |
|
||||
| 新建文件 | `Ctrl+N` |
|
||||
| 关闭标签 | `Ctrl+W` 或标签上的 ×;非最后窗口关掉最后一个标签会关闭该窗口 |
|
||||
| 在新窗口打开 | 右键标签 → “在新窗口打开”,或按住标签上下拖动超过约 24px(至少两个标签时可用) |
|
||||
| 打开文件所在位置 | 右键标签 → “打开文件所在位置”(文件丢失时打开所在目录) |
|
||||
| 打开文件 | 双击 `.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`(工具栏没有搜索按钮,快捷键随时可用) |
|
||||
@@ -48,6 +51,8 @@
|
||||
| 缩放 | `Ctrl+滚轮`、`Ctrl++`、`Ctrl+-`、`Ctrl+0` 复位 |
|
||||
| 折叠标题 | 鼠标移到标题左侧,点折角箭头 |
|
||||
|
||||
> New Tab 上打开文件会直接替换这个标签(和浏览器新标签页一样),不会额外留下空白标签;想同时保留新标签页,先按标签栏的 `+` 新建一个 New Tab。
|
||||
|
||||
设置与最近文件保存在 `%LOCALAPPDATA%\md-preview\`(`recent-files.txt`、`zoom.txt` 等);旧 `session.json` 不再读写。删除 exe 不会自动清掉这些记录。
|
||||
|
||||
## 和上游 1.4.2 的主要区别
|
||||
@@ -55,7 +60,7 @@
|
||||
| 方面 | 改动 |
|
||||
|---|---|
|
||||
| 联网 / 更新 | 移除 GitHub Releases 检查、自更新和 Update 按钮,彻底离线 |
|
||||
| 工具栏 | 移除 Open / Print / Find 按钮,只保留 编辑 / 缩放;快捷键和空状态入口保留 |
|
||||
| 工具栏 | 移除 Open / Print / Find 按钮,只保留 Edit / Zoom;快捷键和空状态入口保留 |
|
||||
| 缩放 | 支持 `Ctrl+滚轮`,步进 5%、范围 50%–300%,并跨重启记住 |
|
||||
| 代码配色 | GitHub 浅/深主题换成始终深色的 VS Dark,只换 CSS、不引新库 |
|
||||
| 换行 | 单个换行按换行显示(AI 输出常见),空行仍是段落分隔;有意的方言差异 |
|
||||
@@ -65,6 +70,7 @@
|
||||
| 路径处理 | 修复 Windows `\\?\` 前缀污染 Recent / base URL 的问题 |
|
||||
| 稳定性 | 关闭前落盘、外部修改热重载、单实例转发、缺失文件重定位 |
|
||||
| 多窗口 | 单进程多窗口;标签右键移出到新窗口;同一文件全局唯一;启动只保留最近文件,不恢复标签 |
|
||||
| 新标签页 / 英文界面 | New Tab 成为默认标签;`+` 新建 New Tab;新标签页新增 New File 按钮;只剩 New Tab 时标签栏隐藏;界面统一为英文 |
|
||||
|
||||
## 从源码构建
|
||||
|
||||
@@ -76,7 +82,7 @@
|
||||
- WebView2 Runtime
|
||||
|
||||
```powershell
|
||||
cargo test # 53 个测试
|
||||
cargo test # 59 个测试
|
||||
.\agent\scripts\build.ps1 # release 构建 + 校验 + 复制到固定 exe 路径
|
||||
```
|
||||
|
||||
|
||||
@@ -45,7 +45,12 @@
|
||||
- 正式构建用 `agent\scripts\build.ps1`(先关闭正在运行的 MD Preview)。
|
||||
- `git clean -xdf` 会删除被忽略的 `backup/` 与成品 exe,禁止使用。
|
||||
|
||||
## 4. 参考
|
||||
## 4. 发布镜像(用户已授权)
|
||||
|
||||
- release 构建成功并发布到 Gitea 后,可以将固定 exe 复制到 Nutstore 镜像:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`,并用 SHA256 校验一致。
|
||||
- 仅限该路径;其他工作区外修改仍需先询问用户。
|
||||
|
||||
## 5. 参考
|
||||
|
||||
- `docs/HANDOFF.md`:工具链、构建、完整性级别坑、验收。
|
||||
- `docs/STATUS.md`:当前进度、已确认决策、下一步。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
> 最后更新:2026-10-28
|
||||
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
|
||||
>
|
||||
> **当前:单进程多窗口 + 标签拖拽/菜单/多显示器修复完成;固定 exe 已替换为 2026-10-28 本地 release(5,507,584 字节,SHA256 0BFF7302…);Gitea release v1.4.2-local.3 准备发布。53 个测试通过。**
|
||||
> **当前:新标签页(New Tab)+ 全英文界面完成;59 个测试通过;固定 exe 已更新为 2026-10-28 release(5,499,392 字节,SHA256 7134BBC6…);Gitea release v1.4.2-local.4 已发布;Nutstore 镜像已同步。**
|
||||
|
||||
## 1. 仓库
|
||||
|
||||
@@ -32,21 +32,25 @@
|
||||
- `85b20ec` fix: 唯一标签时禁用“在新窗口打开”
|
||||
- `f9ccce0` fix: 处理独立评审发现的窗口归属、detach 回滚、聚焦 dirty、关闭语义、RecentChanged
|
||||
- `9ae2c13` fix: 新窗口留在源显示器、去掉多余 focus、标签拖拽、菜单路径/打开所在位置
|
||||
- 若干 docs 提交(状态/路线图/HANDOFF、local.3 release notes)
|
||||
- `809b7b0` feat: 新标签页(Home 作为无路径标签、`+` 新建标签、New File、单标签隐藏标签栏)
|
||||
- `d90e47e` feat: 界面统一为英文(移除语言检测/中文文案,标签名 New Tab)
|
||||
- 若干 docs 提交(状态/路线图/HANDOFF、local.3/local.4 release notes)
|
||||
- 忽略:`/target/`、`/MD-Preview-windows-x64.exe`、`/backup/`、`/agent/reports/*.png`
|
||||
- **不变量**:exe 固定为 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,默认 .md 打开方式指向它,不要改名/移动。
|
||||
|
||||
## 2. 当前构建/部署状态
|
||||
|
||||
- `cargo test`:53 passed / 0 failed(2026-10-28,标签/菜单修复后)。
|
||||
- `cargo test`:59 passed / 0 failed(2026-10-28,新标签页 + 全英文界面)。
|
||||
- 当前固定 exe(2026-10-28 部署):
|
||||
- 大小 5,507,584 字节;版本 1.4.2.0
|
||||
- SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`
|
||||
- 大小 5,499,392 字节;版本 1.4.2.0
|
||||
- SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`
|
||||
- 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。
|
||||
- 构建脚本:`agent/scripts/build.ps1 -SkipTests`
|
||||
- 构建方式:`cargo build --release` + `Copy-Item` + 同等校验。本机 DSH pwsh 下 `build.ps1` 会被 cargo 的 stderr 警告触发 `$ErrorActionPreference='Stop'`;脚本逻辑未改。
|
||||
- 上一版(v1.4.2-local.3):5,507,584 字节;SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`。
|
||||
- 上一版部署(v1.4.2-local.2):5,505,024 字节;SHA256 `7C8A3A8A...99BD95`。
|
||||
- Nutstore 镜像:工作区外的 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` **尚未更新**;按规则需用户确认后再覆盖。
|
||||
- CDP 复核:折叠按钮 30×30,位于内容左侧 `-34px`(H2 实测 left=14,heading left=48),垂直居中;hover `opacity .6`;两个 SVG 折角箭头按 `collapsed` 切换。
|
||||
- Nutstore 镜像:工作区外的 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` 已同步为 v1.4.2-local.4(5,499,392 字节,SHA256 `7134BBC6…`);用户已授权以后 Gitea release 后同步该路径。
|
||||
- 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. 功能进度
|
||||
|
||||
@@ -65,26 +69,30 @@
|
||||
| 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 |
|
||||
|
||||
## 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;非最后窗口关闭最后一个标签会关闭窗口,最后窗口保留空窗口;Cmd+Q 仅 macOS。详见 `agent/docs/design-single-process-multi-window.md`。
|
||||
- 多窗口:单进程、每窗口一个 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”;不随系统语言切换。
|
||||
- 新窗口位置:源窗口当前显示器内 +28,+28 偏移并 clamp;不逐窗口恢复位置。
|
||||
- 标签右键菜单:顶部路径(中间省略,保留开头和文件名),第一项“打开文件所在位置”,第二项“在新窗口打开”;右键时临时移除标签 tooltip。
|
||||
- 标签右键菜单:顶部路径(中间省略,保留开头和文件名),第一项 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 只监听目录;只在保存瞬间需要写权限。
|
||||
|
||||
@@ -94,26 +102,26 @@
|
||||
- 阶段 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`):标签右键自定义菜单“在新窗口打开”;移动语义。active 且 dirty 时由 JS 附带内容、Rust 先写盘再移动;inactive 且 dirty 时拒绝移动并提示;inactive 且 clean 时先 activate 再移动;源窗口最后一个标签移出后关闭源窗口;新窗口只含被移动标签;失败保留源标签。
|
||||
- 阶段 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。
|
||||
- 阶段 6:README/状态/release notes 已更新,已 push 并发布 Gitea release v1.4.2-local.3。
|
||||
- 固定 exe 已是最新构建(53 tests),不再有旧版。
|
||||
|
||||
## 6. 已知问题 / 候选修复
|
||||
@@ -151,10 +159,15 @@ cargo test
|
||||
## 9. 发布(Gitea)
|
||||
|
||||
- 实例 Gitea 24.5.4,仓库私有。
|
||||
- Release `v1.4.2-local.2`(最新):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.2
|
||||
- 附件 `MD-Preview-windows-x64.exe`,5,505,024 字节
|
||||
- SHA256 `7C8A3A8AE1DF4D93714F080663641EC1D7C9CD4B44476D90D020A2640999BD95`(已下载复核一致)
|
||||
- 正文来源:`agent/docs/release-notes-v1.4.2-local.2.md`
|
||||
- Release `v1.4.2-local.4`(最新,2026-10-28):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.4
|
||||
- 附件 `MD-Preview-windows-x64.exe`,5,499,392 字节
|
||||
- SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`(已下载复核一致)
|
||||
- 正文来源:`agent/docs/release-notes-v1.4.2-local.4.md`
|
||||
- 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)。
|
||||
|
||||
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 不再使用。
|
||||
399
src/main.rs
399
src/main.rs
@@ -36,6 +36,7 @@ struct SelfWriteRecord {
|
||||
#[derive(Debug)]
|
||||
enum UserEvent {
|
||||
NewFile(WindowId),
|
||||
NewTab(WindowId),
|
||||
OpenFile(WindowId),
|
||||
OpenPaths(Option<WindowId>, Vec<PathBuf>, bool),
|
||||
ActivateTab(WindowId, u64),
|
||||
@@ -169,29 +170,14 @@ fn print_help() {
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
enum Lang {
|
||||
Zh,
|
||||
En,
|
||||
}
|
||||
|
||||
fn detect_lang() -> Lang {
|
||||
sys_locale::get_locale()
|
||||
.map(|l| {
|
||||
if l.to_lowercase().starts_with("zh") {
|
||||
Lang::Zh
|
||||
} else {
|
||||
Lang::En
|
||||
}
|
||||
})
|
||||
.unwrap_or(Lang::En)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Strings {
|
||||
drop_hint: &'static str,
|
||||
cannot_read: &'static str,
|
||||
open_file: &'static str,
|
||||
new_file: &'static str,
|
||||
new_tab: &'static str,
|
||||
home_tab: &'static str,
|
||||
recent_title: &'static str,
|
||||
missing_title: &'static str,
|
||||
missing_body: &'static str,
|
||||
@@ -215,37 +201,16 @@ struct Strings {
|
||||
}
|
||||
|
||||
impl Strings {
|
||||
fn for_lang(lang: Lang) -> Self {
|
||||
match lang {
|
||||
Lang::Zh => Strings {
|
||||
drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open",
|
||||
cannot_read: "无法读取文件",
|
||||
open_file: "Open File",
|
||||
recent_title: "Recent",
|
||||
missing_title: "文件已移动或删除",
|
||||
missing_body: "这个标签会继续保留。你可以重新定位文件,或关闭标签。",
|
||||
locate_file: "重新定位",
|
||||
close_tab: "关闭标签",
|
||||
cannot_save: "修改无法保存(文件可能只读或被占用)。继续将丢弃这些修改,是否继续?",
|
||||
btn_edit: "编辑 (Cmd/Ctrl+E)",
|
||||
btn_preview: "预览 (Cmd/Ctrl+E)",
|
||||
btn_new: "新建 Markdown (Cmd/Ctrl+N)",
|
||||
btn_new_window: "在新窗口打开",
|
||||
btn_open_location: "打开文件所在位置",
|
||||
new_filename: "新建.md",
|
||||
fold_toggle: "折叠/展开",
|
||||
btn_zoom: "正文缩放",
|
||||
btn_zoom_out: "缩小正文 (Cmd/Ctrl+-)",
|
||||
btn_zoom_reset: "重置正文缩放 (Cmd/Ctrl+0)",
|
||||
btn_zoom_in: "放大正文 (Cmd/Ctrl++)",
|
||||
search_placeholder: "搜索",
|
||||
stat_words: "字",
|
||||
stat_chars: "字符",
|
||||
},
|
||||
Lang::En => Strings {
|
||||
/// The app ships a single English UI. There is deliberately no locale
|
||||
/// detection, so the interface never mixes Chinese and English labels.
|
||||
fn english() -> Self {
|
||||
Strings {
|
||||
drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open",
|
||||
cannot_read: "Cannot read file",
|
||||
open_file: "Open File",
|
||||
new_file: "New File",
|
||||
new_tab: "New Tab",
|
||||
home_tab: "New Tab",
|
||||
recent_title: "Recent",
|
||||
missing_title: "File Moved or Deleted",
|
||||
missing_body: "This tab is kept. Locate the file again or close the tab.",
|
||||
@@ -266,7 +231,6 @@ impl Strings {
|
||||
search_placeholder: "Find",
|
||||
stat_words: "non-space",
|
||||
stat_chars: "chars",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -865,15 +829,21 @@ fn tabs_json(session: &DocumentSession) -> String {
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|tab| {
|
||||
// The page owns the New Tab label; rust only flags the kind.
|
||||
let name = tab
|
||||
.path
|
||||
.file_name()
|
||||
.file_path()
|
||||
.and_then(|path| path.file_name())
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| tab.path.to_string_lossy().to_string());
|
||||
.unwrap_or_default();
|
||||
let path = tab
|
||||
.file_path()
|
||||
.map(|path| path.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
serde_json::json!({
|
||||
"id": tab.id,
|
||||
"name": name,
|
||||
"path": tab.path.to_string_lossy(),
|
||||
"path": path,
|
||||
"home": tab.is_home(),
|
||||
"active": session.active_id == Some(tab.id),
|
||||
"missing": tab.missing,
|
||||
"dirty": tab.dirty,
|
||||
@@ -1079,16 +1049,18 @@ fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec<St
|
||||
scripts
|
||||
}
|
||||
|
||||
fn empty_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String {
|
||||
fn home_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String {
|
||||
let empty_class = if recent_files.is_empty() {
|
||||
"empty"
|
||||
} else {
|
||||
"empty has-recent"
|
||||
};
|
||||
let mut html = format!(
|
||||
r#"<div class="{empty_class}"><div class="icon">#</div><div>{}</div><button class="empty-open" type="button" data-open-file>{}</button>"#,
|
||||
r#"<div class="{empty_class}"><div class="icon">#</div><div>{}</div><div class="empty-actions"><button class="empty-open" type="button" data-open-file>{}</button><button class="empty-open empty-new" type="button" data-new-file title="{}">{}</button></div>"#,
|
||||
html_escape_text(s.drop_hint),
|
||||
html_escape_text(s.open_file)
|
||||
html_escape_text(s.open_file),
|
||||
html_escape_attr(s.btn_new),
|
||||
html_escape_text(s.new_file)
|
||||
);
|
||||
|
||||
if !recent_files.is_empty() {
|
||||
@@ -1124,9 +1096,9 @@ fn build_page(
|
||||
base_href: Option<&str>,
|
||||
flags: EnhanceFlags,
|
||||
s: &Strings,
|
||||
empty: bool,
|
||||
home: bool,
|
||||
) -> String {
|
||||
let body_class = if empty { "empty" } else { "" };
|
||||
let body_class = if home { "home" } else { "" };
|
||||
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());
|
||||
@@ -1276,13 +1248,14 @@ body.has-tabs {{ --chrome-top: 50px; }}
|
||||
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
|
||||
.empty.has-recent {{
|
||||
justify-content: flex-start;
|
||||
min-height: calc(100vh - 48px);
|
||||
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 {{
|
||||
margin-top: 6px; min-height: 40px; padding: 0 16px;
|
||||
min-height: 40px; padding: 0 16px;
|
||||
border: 1px solid #ddd; border-radius: 8px; background: #fff;
|
||||
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
|
||||
}}
|
||||
@@ -1328,6 +1301,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
|
||||
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;
|
||||
@@ -1374,7 +1348,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
|
||||
transition: opacity 0.18s ease;
|
||||
}}
|
||||
html:hover .toolbar {{ opacity: 1; pointer-events: auto; }}
|
||||
body.empty .toolbar {{ display: none !important; }}
|
||||
body.home .toolbar {{ display: none !important; }}
|
||||
.toolbar button {{
|
||||
width: 34px; height: 34px; padding: 0;
|
||||
background: rgba(255,255,255,0.8);
|
||||
@@ -1510,7 +1484,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
#preview .mdp-fold-toggle {{ display: none !important; }}
|
||||
}}
|
||||
</style></head><body class="{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="{btn_new}" aria-label="{btn_new}">+</button></div>
|
||||
<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="{new_tab}" aria-label="{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">{btn_open_location}</button><button type="button" id="tab-menu-new-window">{btn_new_window}</button></div>
|
||||
<div class="toolbar">
|
||||
<button id="btn-toggle" title="{btn_edit}" aria-label="{btn_edit}"></button>
|
||||
@@ -1542,7 +1516,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>';
|
||||
var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
|
||||
var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
|
||||
var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}';
|
||||
var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}', L_HOME = '{home_tab}';
|
||||
window.__mdPreviewFoldLabel = '{fold_toggle}';
|
||||
window.__mdPreviewCannotSave = '{cannot_save_js}';
|
||||
|
||||
@@ -1578,6 +1552,9 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
var composingFind = false;
|
||||
var pendingFindTimer = 0;
|
||||
var FIND_DEBOUNCE_MS = 300;
|
||||
// The strip stays hidden while the only tab is Home, matching the
|
||||
// original start-up page. Set to false to keep the tab bar always on.
|
||||
var HIDE_SINGLE_HOME_TAB = true;
|
||||
var findHits = [];
|
||||
var currentFindHit = -1;
|
||||
var lastFindQuery = '';
|
||||
@@ -1683,15 +1660,16 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
suppressTabTooltips();
|
||||
tabMenuTargetId = id;
|
||||
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]');
|
||||
var isHome = tabEl ? tabEl.classList.contains('home') : false;
|
||||
var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
|
||||
if (tabMenuPath) {{
|
||||
tabMenuPath.textContent = shortenPath(path, 42);
|
||||
if (path) tabMenuPath.setAttribute('title', path);
|
||||
tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
|
||||
if (!isHome && path) tabMenuPath.setAttribute('title', path);
|
||||
else tabMenuPath.removeAttribute('title');
|
||||
}}
|
||||
tabMenu.hidden = false;
|
||||
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
|
||||
if (tabMenuReveal) tabMenuReveal.disabled = !path;
|
||||
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
|
||||
if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
|
||||
tabMenu.style.left = '0px';
|
||||
tabMenu.style.top = '0px';
|
||||
var rect = tabMenu.getBoundingClientRect();
|
||||
@@ -1765,8 +1743,13 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.ipc.postMessage('new-file');
|
||||
}}
|
||||
window.__mdPreviewNewFile = newFile;
|
||||
function newTab() {{
|
||||
// Reuse the close/activate path so a dirty editor is saved before the
|
||||
// Home tab replaces it.
|
||||
requestTabAction('new-tab', 0);
|
||||
}}
|
||||
function showFind() {{
|
||||
if (document.body.classList.contains('empty')) return;
|
||||
if (document.body.classList.contains('home')) return;
|
||||
if (inEdit()) return;
|
||||
document.body.classList.add('finding');
|
||||
setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0);
|
||||
@@ -1905,6 +1888,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.scrollTo(x, y);
|
||||
}}
|
||||
function enterEdit() {{
|
||||
if (document.body.classList.contains('home')) return;
|
||||
var progress = currentScrollProgress();
|
||||
document.body.classList.add('editing');
|
||||
btnToggle.innerHTML = ICON_VIEW;
|
||||
@@ -1937,7 +1921,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
if (activeTabId) requestTabAction('close', activeTabId);
|
||||
}};
|
||||
|
||||
tabOpen.addEventListener('click', newFile);
|
||||
tabOpen.addEventListener('click', newTab);
|
||||
if (tabMenuNewWindow) {{
|
||||
tabMenuNewWindow.addEventListener('click', function(e) {{
|
||||
e.preventDefault();
|
||||
@@ -1960,6 +1944,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
if (e.button !== 0 || tabCount <= 1) return;
|
||||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||
if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return;
|
||||
if (tab.classList.contains('home')) return;
|
||||
hideTabMenu();
|
||||
tabDrag = {{ id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false }};
|
||||
try {{ tab.setPointerCapture(e.pointerId); }} catch (err) {{}}
|
||||
@@ -2022,6 +2007,12 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||||
return;
|
||||
}}
|
||||
var newFileBtn = e.target && e.target.closest ? e.target.closest('[data-new-file]') : null;
|
||||
if (newFileBtn) {{
|
||||
e.preventDefault();
|
||||
newFile();
|
||||
return;
|
||||
}}
|
||||
var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
|
||||
if (openBtn) {{
|
||||
e.preventDefault();
|
||||
@@ -2192,28 +2183,34 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
|
||||
tabsEl.textContent = '';
|
||||
activeTabId = 0;
|
||||
document.body.classList.toggle('has-tabs', tabs.length > 0);
|
||||
var showTabBar = HIDE_SINGLE_HOME_TAB
|
||||
? (tabs.length > 1 || (tabs.length === 1 && !tabs[0].home))
|
||||
: tabs.length > 0;
|
||||
document.body.classList.toggle('has-tabs', showTabBar);
|
||||
tabs.forEach(function(tab) {{
|
||||
var isHome = !!tab.home;
|
||||
var item = document.createElement('div');
|
||||
item.className = 'tab' + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
|
||||
item.className = 'tab' + (isHome ? ' home' : '') + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
|
||||
item.setAttribute('data-tab-id', tab.id);
|
||||
item.setAttribute('data-tab-path', tab.path);
|
||||
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
|
||||
item.setAttribute('role', 'button');
|
||||
item.setAttribute('tabindex', '0');
|
||||
item.title = tab.path;
|
||||
item.title = isHome ? L_HOME : tab.path;
|
||||
if (tab.active) activeTabId = tab.id;
|
||||
var status = document.createElement('span');
|
||||
status.className = 'tab-status';
|
||||
status.textContent = tab.missing ? '!' : '';
|
||||
var name = document.createElement('span');
|
||||
name.className = 'tab-name';
|
||||
name.textContent = tab.name;
|
||||
name.textContent = isHome ? L_HOME : tab.name;
|
||||
var close = document.createElement('button');
|
||||
close.className = 'tab-close';
|
||||
close.type = 'button';
|
||||
close.setAttribute('data-close-tab', tab.id);
|
||||
close.setAttribute('aria-label', 'Close ' + tab.name);
|
||||
close.setAttribute('aria-label', 'Close ' + (isHome ? L_HOME : tab.name));
|
||||
close.textContent = '×';
|
||||
// A lone Home tab is the start-up page; there is nothing to close.
|
||||
if (tabCount === 1 && isHome) close.hidden = true;
|
||||
item.appendChild(status);
|
||||
item.appendChild(name);
|
||||
item.appendChild(close);
|
||||
@@ -2229,7 +2226,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||||
}});
|
||||
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
|
||||
document.body.classList.remove('empty');
|
||||
document.body.classList.remove('home');
|
||||
document.body.classList.remove('missing');
|
||||
hideFind();
|
||||
window.__setBaseHref(baseHref);
|
||||
@@ -2243,7 +2240,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
}}
|
||||
}};
|
||||
window.__setEmptyPreview = function(previewHtml) {{
|
||||
document.body.classList.add('empty');
|
||||
document.body.classList.add('home');
|
||||
document.body.classList.remove('missing');
|
||||
document.body.classList.remove('editing');
|
||||
btnToggle.innerHTML = ICON_EDIT;
|
||||
@@ -2260,7 +2257,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.scrollTo(0, 0);
|
||||
}};
|
||||
window.__setMissing = function(previewHtml) {{
|
||||
document.body.classList.remove('empty');
|
||||
document.body.classList.remove('home');
|
||||
document.body.classList.add('missing');
|
||||
document.body.classList.remove('editing');
|
||||
btnToggle.innerHTML = ICON_EDIT;
|
||||
@@ -2300,7 +2297,8 @@ if(window.__enhancePreview)window.__enhancePreview();
|
||||
base_tag = base_tag,
|
||||
preview_html = preview_html,
|
||||
raw_md_escaped = html_escape_ta(raw_md),
|
||||
btn_new = s.btn_new,
|
||||
new_tab = s.new_tab,
|
||||
home_tab = escape_js(s.home_tab),
|
||||
btn_new_window = s.btn_new_window,
|
||||
btn_open_location = s.btn_open_location,
|
||||
btn_edit = s.btn_edit,
|
||||
@@ -2379,7 +2377,7 @@ mod tests {
|
||||
fs::write(&file, "x".repeat(3 * 1024 * 1024)).unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
session.open(file, true);
|
||||
let page = build_startup_page(&Strings::for_lang(Lang::En));
|
||||
let page = build_startup_page(&Strings::english());
|
||||
assert!(
|
||||
page.len() < 2 * 1024 * 1024,
|
||||
"startup HTML has {} bytes",
|
||||
@@ -2724,7 +2722,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn page_blocks_native_preview_reload_paths() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
@@ -2781,7 +2779,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn page_separates_new_file_from_open_and_debounces_autosave() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
@@ -2792,8 +2790,21 @@ mod tests {
|
||||
);
|
||||
|
||||
assert!(page.contains("window.ipc.postMessage('new-file')"));
|
||||
assert!(page.contains("tabOpen.addEventListener('click', newFile)"));
|
||||
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)"));
|
||||
@@ -2830,7 +2841,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn headings_get_hover_fold_toggles() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# A\n\n## B\n\ntext"),
|
||||
"# A\n\n## B\n\ntext",
|
||||
@@ -2850,7 +2861,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn closing_the_last_editing_tab_restores_the_empty_preview() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
@@ -2885,7 +2896,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn page_expands_multi_column_tables() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | 4 |"),
|
||||
"",
|
||||
@@ -2902,11 +2913,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn empty_state_exposes_open_and_recent_files() {
|
||||
let strings = Strings::for_lang(Lang::En);
|
||||
let strings = Strings::english();
|
||||
let recent = vec![PathBuf::from("/tmp/example.md")];
|
||||
let html = empty_preview_html(&strings, &recent);
|
||||
let html = home_preview_html(&strings, &recent);
|
||||
|
||||
assert!(html.contains("Open File"));
|
||||
assert!(html.contains("New File"));
|
||||
assert!(html.contains("empty-actions"));
|
||||
assert!(html.contains("data-new-file"));
|
||||
assert!(html.contains("Recent"));
|
||||
assert!(html.contains("example.md"));
|
||||
assert!(html.contains("data-recent-index=\"0\""));
|
||||
@@ -2924,6 +2938,20 @@ mod tests {
|
||||
);
|
||||
assert!(page.contains(".empty.has-recent"));
|
||||
assert!(!page.contains(".empty.has-recent .recent { max-height"));
|
||||
assert!(page.contains("<body class=\"home\">"));
|
||||
assert!(page.contains("body.home .toolbar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_json_marks_home_tabs_without_a_file_path() {
|
||||
let mut session = DocumentSession::default();
|
||||
let home = session.open_home();
|
||||
|
||||
let json = tabs_json(&session);
|
||||
|
||||
assert!(json.contains(&format!(r#""id":{home}"#)), "{json}");
|
||||
assert!(json.contains(r#""home":true"#), "{json}");
|
||||
assert!(json.contains(r#""path":"""#), "{json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3048,11 +3076,11 @@ mod tests {
|
||||
#[test]
|
||||
fn finder_create_uses_non_conflicting_markdown_name() {
|
||||
let dir = temp_test_dir("finder-create");
|
||||
fs::write(dir.join("新建.md"), "existing").unwrap();
|
||||
fs::write(dir.join("Untitled.md"), "existing").unwrap();
|
||||
|
||||
let created = create_finder_file(&dir, "md").unwrap();
|
||||
|
||||
assert_eq!(created.file_name().unwrap(), "新建 2.md");
|
||||
assert_eq!(created.file_name().unwrap(), "Untitled 2.md");
|
||||
assert_eq!(fs::read_to_string(created).unwrap(), "");
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -3067,7 +3095,7 @@ fn load_window_icon() -> Option<tao::window::Icon> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn register_as_default(_lang: Lang) {
|
||||
fn register_as_default() {
|
||||
use std::process::Command;
|
||||
let marker = config_dir().join(".md-preview-registered");
|
||||
if marker.exists() {
|
||||
@@ -3092,7 +3120,7 @@ fn register_as_default(_lang: Lang) {
|
||||
/// extensions so MD Preview shows up in the "Open with" list. Win8+ blocks
|
||||
/// silent default-handler changes — only the Settings app can confirm those.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn register_as_default(_lang: Lang) {
|
||||
fn register_as_default() {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
@@ -3154,7 +3182,7 @@ fn register_as_default(_lang: Lang) {
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn register_as_default(_lang: Lang) {}
|
||||
fn register_as_default() {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
thread_local! {
|
||||
@@ -3651,11 +3679,11 @@ fn install_file_watcher(
|
||||
) {
|
||||
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();
|
||||
*last_self_write.lock().unwrap() = None;
|
||||
let target_path = path.clone();
|
||||
let callback_path = path.clone();
|
||||
let proxy = proxy.clone();
|
||||
@@ -3759,14 +3787,14 @@ fn create_finder_file(folder: &Path, kind: &str) -> std::io::Result<PathBuf> {
|
||||
"json" => ("json", b"{}\n"),
|
||||
"html" => (
|
||||
"html",
|
||||
b"<!doctype html>\n<html lang=\"zh-CN\">\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n</head>\n<body>\n</body>\n</html>\n",
|
||||
b"<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n</head>\n<body>\n</body>\n</html>\n",
|
||||
),
|
||||
_ => ("md", b""),
|
||||
};
|
||||
let mut path = folder.join(format!("新建.{extension}"));
|
||||
let mut path = folder.join(format!("Untitled.{extension}"));
|
||||
let mut index = 2;
|
||||
while path.exists() {
|
||||
path = folder.join(format!("新建 {index}.{extension}"));
|
||||
path = folder.join(format!("Untitled {index}.{extension}"));
|
||||
index += 1;
|
||||
}
|
||||
fs::write(&path, contents)?;
|
||||
@@ -3861,7 +3889,11 @@ fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> {
|
||||
let normalized = session::normalize_path(path.to_path_buf());
|
||||
for (window_id, ws) in &app.windows {
|
||||
let session = ws.session.lock().unwrap();
|
||||
if let Some(tab) = session.tabs.iter().find(|tab| tab.path == normalized) {
|
||||
if let Some(tab) = session
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.path.as_deref() == Some(normalized.as_path()))
|
||||
{
|
||||
return Some((*window_id, tab.id));
|
||||
}
|
||||
}
|
||||
@@ -3908,8 +3940,8 @@ fn focus_open_tab(
|
||||
.session
|
||||
.lock()
|
||||
.unwrap()
|
||||
.active()
|
||||
.map(|tab| tab.path.clone());
|
||||
.active_path()
|
||||
.map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path);
|
||||
true
|
||||
}
|
||||
@@ -3920,20 +3952,38 @@ fn update_tabs(webview: &WebView, session: &DocumentSession) {
|
||||
}
|
||||
|
||||
fn update_window_title(window: &Window, session: &DocumentSession) {
|
||||
let title = session
|
||||
.active()
|
||||
.map(|tab| {
|
||||
let name = tab
|
||||
.path
|
||||
let title = match session.active() {
|
||||
Some(tab) => match tab.file_path() {
|
||||
Some(path) => {
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| tab.path.to_string_lossy().to_string());
|
||||
.unwrap_or_else(|| path.to_string_lossy().to_string());
|
||||
format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name)
|
||||
})
|
||||
.unwrap_or_else(|| "MD Preview".to_string());
|
||||
}
|
||||
None => "MD Preview".to_string(),
|
||||
},
|
||||
None => "MD Preview".to_string(),
|
||||
};
|
||||
window.set_title(&title);
|
||||
}
|
||||
|
||||
fn render_home(
|
||||
webview: &WebView,
|
||||
window: &Window,
|
||||
session: &DocumentSession,
|
||||
recent_files: &Arc<Mutex<Vec<PathBuf>>>,
|
||||
strings: &Strings,
|
||||
) {
|
||||
let html = home_preview_html(strings, &recent_files.lock().unwrap());
|
||||
let _ = webview.evaluate_script(&format!(
|
||||
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
|
||||
escape_js(&html)
|
||||
));
|
||||
update_tabs(webview, session);
|
||||
update_window_title(window, session);
|
||||
}
|
||||
|
||||
fn render_active_document(
|
||||
webview: &WebView,
|
||||
window: &Window,
|
||||
@@ -3944,24 +3994,23 @@ fn render_active_document(
|
||||
strings: &Strings,
|
||||
) -> bool {
|
||||
let Some(active) = session.active().cloned() else {
|
||||
let html = empty_preview_html(strings, &recent_files.lock().unwrap());
|
||||
let _ = webview.evaluate_script(&format!(
|
||||
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
|
||||
escape_js(&html)
|
||||
));
|
||||
update_tabs(webview, session);
|
||||
update_window_title(window, session);
|
||||
render_home(webview, window, session, recent_files, strings);
|
||||
return false;
|
||||
};
|
||||
// Home tabs carry no file; they render the new-tab page.
|
||||
let Some(path) = active.file_path().map(Path::to_path_buf) else {
|
||||
render_home(webview, window, session, recent_files, strings);
|
||||
return false;
|
||||
};
|
||||
|
||||
match fs::read_to_string(&active.path) {
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(raw) => {
|
||||
if let Some(tab) = session.get_mut(active.id) {
|
||||
tab.missing = false;
|
||||
}
|
||||
remember_recent_file(recent_files, &active.path);
|
||||
let html = md_to_html_with_base(&raw, active.path.parent());
|
||||
let base_href = base_href_for_file(&active.path).unwrap_or_default();
|
||||
remember_recent_file(recent_files, &path);
|
||||
let html = md_to_html_with_base(&raw, path.parent());
|
||||
let base_href = base_href_for_file(&path).unwrap_or_default();
|
||||
let flags = enhance_flags_for(&raw);
|
||||
*enhance_flags.lock().unwrap() = flags;
|
||||
let _ = webview.evaluate_script(&format!(
|
||||
@@ -3996,7 +4045,7 @@ fn render_active_document(
|
||||
"The file disappeared while it still has unsaved edits. The editor content has been kept.",
|
||||
);
|
||||
} else {
|
||||
let html = missing_preview_html(active.id, &active.path, strings);
|
||||
let html = missing_preview_html(active.id, &path, strings);
|
||||
let _ = webview.evaluate_script(&format!(
|
||||
"if(window.__setMissing)window.__setMissing('{}');",
|
||||
escape_js(&html)
|
||||
@@ -4013,7 +4062,7 @@ fn render_active_document(
|
||||
r#"<div class="missing-file"><h2>{}</h2><p>{}</p><code>{}</code><button type="button" data-open-file>{}</button><button type="button" data-close-tab="{}">{}</button></div>"#,
|
||||
html_escape_text(strings.cannot_read),
|
||||
html_escape_text(&error.to_string()),
|
||||
html_escape_text(&active.path.to_string_lossy()),
|
||||
html_escape_text(&path.to_string_lossy()),
|
||||
html_escape_text(strings.open_file),
|
||||
active.id,
|
||||
html_escape_text(strings.close_tab),
|
||||
@@ -4036,7 +4085,7 @@ fn render_active_document(
|
||||
// persisted path data in this page; load the active tab after the ready IPC.
|
||||
fn build_startup_page(strings: &Strings) -> String {
|
||||
build_page(
|
||||
&empty_preview_html(strings, &[]),
|
||||
&home_preview_html(strings, &[]),
|
||||
"",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
@@ -4104,7 +4153,7 @@ fn build_webview(
|
||||
}
|
||||
}
|
||||
} else if let Some(url) = body.strip_prefix("open-local-link:") {
|
||||
let active_path = session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let active_path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
if let Some(path) = resolve_document_link(url, active_path.as_deref()) {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths(
|
||||
Some(window_id),
|
||||
@@ -4124,7 +4173,7 @@ fn build_webview(
|
||||
return;
|
||||
};
|
||||
if let Some(content) = pending_content {
|
||||
let path = session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
let Some(path) = path else {
|
||||
return;
|
||||
};
|
||||
@@ -4156,6 +4205,9 @@ fn build_webview(
|
||||
"detach" => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id));
|
||||
}
|
||||
"new-tab" => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::NewTab(window_id));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(id) = body.strip_prefix("locate-tab:") {
|
||||
@@ -4185,11 +4237,11 @@ fn build_webview(
|
||||
save_zoom(percent);
|
||||
}
|
||||
} else if body == "refresh" {
|
||||
if let Some(path) = session.lock().unwrap().active().map(|tab| tab.path.clone()) {
|
||||
if let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::FileChanged(window_id, path));
|
||||
}
|
||||
} else if let Some(content) = body.strip_prefix("save:") {
|
||||
let path = session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
if let Some(path) = path {
|
||||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
@@ -4325,6 +4377,10 @@ fn create_window_with_session(
|
||||
let window = builder.build(target).map_err(|error| error.to_string())?;
|
||||
let window_id = window.id();
|
||||
let page = build_startup_page(&app.strings);
|
||||
let mut initial_session = initial_session;
|
||||
if initial_session.tabs.is_empty() {
|
||||
initial_session.open_home();
|
||||
}
|
||||
let session = Arc::new(Mutex::new(initial_session));
|
||||
let last_self_write = Arc::new(Mutex::new(None));
|
||||
let recent_files = Arc::clone(&app.recent_files);
|
||||
@@ -4459,9 +4515,8 @@ fn main() {
|
||||
}
|
||||
};
|
||||
|
||||
let lang = detect_lang();
|
||||
let strings = Strings::for_lang(lang);
|
||||
register_as_default(lang);
|
||||
let strings = Strings::english();
|
||||
register_as_default();
|
||||
register_finder_extension();
|
||||
bench_log("after_register");
|
||||
|
||||
@@ -4469,6 +4524,9 @@ fn main() {
|
||||
for path in cli_paths {
|
||||
initial_session.open(path, edit_from_cli);
|
||||
}
|
||||
if initial_session.tabs.is_empty() {
|
||||
initial_session.open_home();
|
||||
}
|
||||
|
||||
let event_loop: EventLoop<UserEvent> = EventLoopBuilder::with_user_event().build();
|
||||
let proxy = event_loop.create_proxy();
|
||||
@@ -4485,7 +4543,8 @@ fn main() {
|
||||
|
||||
let title = initial_session
|
||||
.active()
|
||||
.and_then(|tab| tab.path.file_name())
|
||||
.and_then(|tab| tab.file_path())
|
||||
.and_then(|path| path.file_name())
|
||||
.map(|name| format!("{} — MD Preview", name.to_string_lossy()))
|
||||
.unwrap_or_else(|| "MD Preview".to_string());
|
||||
|
||||
@@ -4622,7 +4681,8 @@ fn main() {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.active()
|
||||
.and_then(|tab| tab.path.parent().map(Path::to_path_buf));
|
||||
.and_then(|tab| tab.file_path())
|
||||
.and_then(|path| path.parent().map(Path::to_path_buf));
|
||||
let mut dialog = rfd::FileDialog::new()
|
||||
.add_filter("Markdown", &["md", "markdown", "mdown", "mkd"])
|
||||
.set_file_name(strings.new_filename);
|
||||
@@ -4673,6 +4733,16 @@ fn main() {
|
||||
));
|
||||
}
|
||||
}
|
||||
TaoEvent::UserEvent(UserEvent::NewTab(window_id)) => {
|
||||
let Some(ws) = app.windows.get_mut(&window_id) else {
|
||||
return;
|
||||
};
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
session.open_home();
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None);
|
||||
}
|
||||
TaoEvent::UserEvent(UserEvent::OpenPaths(target, paths, edit_on_open)) => {
|
||||
let target_window = target.unwrap_or(app.active_window);
|
||||
let Some(ws) = app.windows.get_mut(&target_window) else {
|
||||
@@ -4719,7 +4789,11 @@ fn main() {
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
let previous_active = session.active_id;
|
||||
let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false);
|
||||
if !preserve_active && session.active_is_home() {
|
||||
session.open_reusing_home(path, edit_on_open);
|
||||
} else {
|
||||
session.open(path, edit_on_open);
|
||||
}
|
||||
if preserve_active {
|
||||
if let Some(id) = previous_active {
|
||||
session.activate(id);
|
||||
@@ -4731,7 +4805,7 @@ fn main() {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
}
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(
|
||||
&ws.watcher,
|
||||
&proxy,
|
||||
@@ -4749,7 +4823,7 @@ fn main() {
|
||||
if session.activate(id) {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
}
|
||||
}
|
||||
@@ -4759,20 +4833,34 @@ fn main() {
|
||||
return;
|
||||
};
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
let Some(target) = session.tabs.iter().find(|tab| tab.id == id) else {
|
||||
return;
|
||||
};
|
||||
let was_active = session.active_id == Some(id);
|
||||
if session.close(id) {
|
||||
if session.tabs.is_empty() {
|
||||
let sole_tab = session.tabs.len() == 1;
|
||||
let closing_home = target.is_home();
|
||||
if sole_tab {
|
||||
if multiple_windows {
|
||||
drop(session);
|
||||
close_window(&mut app, window_id, control_flow);
|
||||
} else {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
return;
|
||||
}
|
||||
} else if was_active {
|
||||
if closing_home {
|
||||
// The last window always keeps one Home tab.
|
||||
return;
|
||||
}
|
||||
// Closing the last file tab returns to the Home tab.
|
||||
session.close_with_home_fallback(id);
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None);
|
||||
return;
|
||||
}
|
||||
if session.close(id) {
|
||||
if was_active {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
} else {
|
||||
update_tabs(&ws.webview, &session);
|
||||
@@ -4787,6 +4875,9 @@ fn main() {
|
||||
let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else {
|
||||
return;
|
||||
};
|
||||
if tab.is_home() {
|
||||
return;
|
||||
}
|
||||
let target_active = session.active_id == Some(tab_id);
|
||||
if !target_active && tab.dirty {
|
||||
drop(session);
|
||||
@@ -4833,7 +4924,7 @@ fn main() {
|
||||
if !close_source {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
}
|
||||
}
|
||||
@@ -4848,7 +4939,8 @@ fn main() {
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.id == tab_id)
|
||||
.map(|tab| tab.path.clone())
|
||||
.and_then(|tab| tab.file_path())
|
||||
.map(Path::to_path_buf)
|
||||
});
|
||||
if let Some(path) = path {
|
||||
if !reveal_in_explorer(&path) {
|
||||
@@ -4901,7 +4993,7 @@ fn main() {
|
||||
if session.relocate(id, path) && session.activate(id) {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
} else {
|
||||
show_warning_dialog("Already Open", "That file is already open in another tab.");
|
||||
@@ -4912,14 +5004,7 @@ fn main() {
|
||||
let Some(ws) = app.windows.get_mut(&window_id) else {
|
||||
return;
|
||||
};
|
||||
if ws
|
||||
.session
|
||||
.lock()
|
||||
.unwrap()
|
||||
.active()
|
||||
.map(|tab| tab.path.as_path())
|
||||
== Some(path.as_path())
|
||||
{
|
||||
if ws.session.lock().unwrap().active_path() == Some(path.as_path()) {
|
||||
ws.pending_external_change = Some(path);
|
||||
let _ = ws.webview.evaluate_script(
|
||||
"if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();",
|
||||
@@ -4937,7 +5022,7 @@ fn main() {
|
||||
return;
|
||||
}
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
if session.active().map(|tab| tab.path.as_path()) == Some(path.as_path()) {
|
||||
if session.active_path() == Some(path.as_path()) {
|
||||
let session_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false);
|
||||
if should_protect_external_change(webview_dirty, session_dirty) {
|
||||
if let Some(tab) = session.active_mut() {
|
||||
@@ -4969,8 +5054,12 @@ fn main() {
|
||||
ws.warned_external_change = None;
|
||||
}
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
let active_matches = session.active().map(|tab| tab.path.as_path()) == Some(path.as_path());
|
||||
if let Some(tab) = session.tabs.iter_mut().find(|tab| tab.path == path) {
|
||||
let active_matches = session.active_path() == Some(path.as_path());
|
||||
if let Some(tab) = session
|
||||
.tabs
|
||||
.iter_mut()
|
||||
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
|
||||
{
|
||||
tab.dirty = false;
|
||||
tab.missing = false;
|
||||
}
|
||||
@@ -5052,13 +5141,13 @@ fn main() {
|
||||
.evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();");
|
||||
}
|
||||
TaoEvent::UserEvent(UserEvent::RecentChanged) => {
|
||||
let html = empty_preview_html(&strings, &recent_files.lock().unwrap());
|
||||
let html = home_preview_html(&strings, &recent_files.lock().unwrap());
|
||||
let js = format!(
|
||||
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
|
||||
escape_js(&html)
|
||||
);
|
||||
for ws in app.windows.values() {
|
||||
if ws.session.lock().unwrap().tabs.is_empty() {
|
||||
if ws.session.lock().unwrap().active_is_home() {
|
||||
let _ = ws.webview.evaluate_script(&js);
|
||||
}
|
||||
}
|
||||
@@ -5110,7 +5199,7 @@ fn main() {
|
||||
if !ws.page_ready {
|
||||
ws.page_ready = true;
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
}
|
||||
for (paths, edit) in ws.pending_launches.drain(..) {
|
||||
|
||||
210
src/session.rs
210
src/session.rs
@@ -1,15 +1,26 @@
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
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,
|
||||
}
|
||||
|
||||
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)]
|
||||
pub struct DocumentSession {
|
||||
pub tabs: Vec<DocumentTab>,
|
||||
@@ -20,8 +31,12 @@ pub struct DocumentSession {
|
||||
impl DocumentSession {
|
||||
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();
|
||||
if let Some(tab) = self
|
||||
.tabs
|
||||
.iter_mut()
|
||||
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
|
||||
{
|
||||
tab.missing = !path.exists();
|
||||
tab.edit_on_open |= edit_on_open;
|
||||
self.active_id = Some(tab.id);
|
||||
return tab.id;
|
||||
@@ -29,22 +44,82 @@ impl DocumentSession {
|
||||
|
||||
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,
|
||||
missing,
|
||||
edit_on_open,
|
||||
});
|
||||
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,
|
||||
edit_on_open: false,
|
||||
});
|
||||
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.edit_on_open |= 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.edit_on_open = edit_on_open;
|
||||
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
|
||||
}
|
||||
@@ -65,6 +140,17 @@ impl DocumentSession {
|
||||
true
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
if self.tabs.is_empty() {
|
||||
self.open_home();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn with_tab(tab: DocumentTab) -> Self {
|
||||
let id = tab.id;
|
||||
Self {
|
||||
@@ -76,6 +162,9 @@ impl DocumentSession {
|
||||
|
||||
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 {
|
||||
@@ -98,20 +187,36 @@ 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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -222,6 +327,83 @@ mod tests {
|
||||
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].edit_on_open);
|
||||
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);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn opened_paths_drop_windows_verbatim_prefix() {
|
||||
@@ -232,9 +414,13 @@ mod tests {
|
||||
|
||||
session.open(file.clone(), false);
|
||||
|
||||
let stored = session.tabs[0].path.to_string_lossy().to_string();
|
||||
let stored = session.tabs[0]
|
||||
.file_path()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
|
||||
assert!(session.tabs[0].path.ends_with("note.md"));
|
||||
assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user