diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..375e32a
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+vendor/pandoc/pandoc.exe filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
index 1f30cbe..8cbe11d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,8 @@ html/
.DS_Store
Thumbs.db
+
+pack/.tools/
+pack/.venv/
+pack/logs/
+pack/output/
diff --git a/MDHelper.spec b/MDHelper.spec
index dc84a36..01cd2be 100644
--- a/MDHelper.spec
+++ b/MDHelper.spec
@@ -6,11 +6,12 @@ from pathlib import Path
project_root = Path(SPECPATH)
datas = [
- (str(project_root / "icon_glass.png"), "."),
- (str(project_root / "sample.md"), "."),
+ (str(project_root / "icon_glass.ico"), "."),
+ (str(project_root / "packaging" / "sample.md"), "."),
(str(project_root / "docs"), "docs"),
- (str(project_root / "media"), "media"),
+ (str(project_root / "media" / "screenshot.png"), "media"),
(str(project_root / "mdhelper" / "resources"), "mdhelper/resources"),
+ (str(project_root / "vendor" / "pandoc"), "vendor/pandoc"),
]
a = Analysis(
@@ -22,23 +23,46 @@ a = Analysis(
hookspath=[str(project_root / "hooks")],
hooksconfig={},
runtime_hooks=[],
- excludes=[],
+ excludes=["PIL"],
noarchive=False,
optimize=0,
)
+
+
+def keep_runtime_data(entry):
+ target = str(entry[0]).replace("/", "\\").lower()
+ if ".debug." in target or "qtwebengine_devtools_resources" in target:
+ return False
+ if "\\plugins\\qmltooling\\" in target:
+ return False
+ if "\\translations\\" in target:
+ filename = Path(target).name
+ return any(locale in filename for locale in ("zh_cn", "zh-cn", "en_us", "en-us", "en_gb", "en-gb", "_en."))
+ return True
+
+
+def keep_runtime_binary(entry):
+ source = str(entry[1]).replace("/", "\\").lower()
+ # PyInstaller resolves transitive DLLs through PATH. Codex adds bundled
+ # Poppler/libheif directories there, whose ICU/UCRT DLLs are incompatible
+ # with the Windows system libraries expected by PySide6.
+ return "\\codex-runtimes\\" not in source
+
+
+a.binaries = [entry for entry in a.binaries if keep_runtime_binary(entry)]
+a.datas = [entry for entry in a.datas if keep_runtime_data(entry)]
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
- a.binaries,
- a.datas,
[],
+ exclude_binaries=True,
name="MDHelper",
debug=False,
bootloader_ignore_signals=False,
strip=False,
- upx=True,
+ upx=False,
upx_exclude=[],
runtime_tmpdir=None,
console=False,
@@ -49,3 +73,13 @@ exe = EXE(
entitlements_file=None,
icon=str(project_root / "icon_glass.ico"),
)
+
+# Install this directory once; ordinary launches no longer extract Qt/Pandoc.
+coll = COLLECT(
+ exe,
+ a.binaries,
+ a.datas,
+ strip=False,
+ upx=False,
+ name="MDHelper",
+)
diff --git a/MDHelper_design.md b/MDHelper_design.md
index 8749c93..4aa9da8 100644
--- a/MDHelper_design.md
+++ b/MDHelper_design.md
@@ -31,7 +31,7 @@ Python 3.13
| Pygments | 2.20.0 | 代码块和代码文件高亮 |
| Pillow | 12.2.0 | 图片相关处理 |
| python-docx | 1.2.0 | DOCX 导出备选实现 |
-| PyInstaller | 6.20.0 | Windows 单文件 exe 打包 |
+| PyInstaller | 6.20.0 | Windows 目录式程序打包;Inno Setup 制作安装 EXE |
外部可选工具:
@@ -81,18 +81,17 @@ MDHelper/
```text
+---------------------------------------------------------------+
| 菜单栏:文件 编辑 书签 工具 主题 样式 关于 |
-+----------------------+--------------------------+-------------+
-| 文档栏 | 多标签阅读区 | 当前文档目录 |
-| - 打开/刷新/查找按钮 | QWebEngineView / 编辑器 | QTreeWidget |
-| - 搜索框 | Markdown 转换后的 HTML | 当前标题高亮 |
-| - 搜索结果 | 图片/音频/视频/代码/公式 | |
-| - 文件树 | | |
-+----------------------+--------------------------+-------------+
-| 状态栏:当前路径、链接目标、阅读进度 QProgressBar |
++----------------------+----------------------------------------+
+| 左侧导航栏 | 多标签阅读区 |
+| - 目录:搜索与文件树 | QWebEngineView / 编辑器 |
+| - 大纲:标题点击跳转 | Markdown 转换后的 HTML |
+| | 图片/音频/视频/代码/公式 |
++----------------------+----------------------------------------+
+| 状态栏:当前路径、链接目标 |
+---------------------------------------------------------------+
```
-当前阅读模式中,正文在 `QWebEngineView` 内滚动;阅读进度条和右侧文档目录仍是 Qt 控件。滚动时页面通过 WebChannel 把进度和当前标题回传给 Python,再由 Python 更新 Qt 状态栏和目录树。
+当前阅读模式中,正文在 `QWebEngineView` 内滚动。左侧 `QTabWidget` 在文件目录与当前文档大纲间切换;大纲仅在点击时跳转,不随滚动选中标题。状态栏不显示阅读进度。
## 6. 当前渲染流程
@@ -136,61 +135,54 @@ MDHelper/
- 草稿只写入配置中的恢复数据,不直接覆盖正式文件。
- 分屏滚动同步按比例近似同步,标题点击用于精确定位。
-## 9. 0.2.0 阅读体验重构方案
+## 9. 阅读导航与滚动性能
### 9.1 背景
-当前滚动不够跟手的主要原因不是 Markdown 转译,而是滚动过程中仍存在 WebChannel 回传和 Qt 控件更新:
+为避免长文档滚动时的额外计算,阅读滚动不再驱动导航界面:
```text
WebEngine 滚动
- -> reader.js 计算滚动进度和当前标题
- -> WebChannel 调用 Python
- -> Python 更新 QProgressBar
- -> Python 查找并更新 QTreeWidget 当前目录项
+ -> Chromium 自行绘制正文
+ -> 固定低频定时器只读取 window.scrollY
+ -> 保存阅读位置
```
-即使已经做了节流和缓存,这条链路仍然比浏览器内部 DOM 更新更重。
+滚动过程中不计算百分比、不搜索当前标题、不更新大纲选中项,也不发送持续的 WebChannel 滚动事件。
### 9.2 目标架构
-0.2.0 目标是把“当前文档目录”和“阅读进度”作为阅读页 HTML 的一部分生成。
+大纲保持在 Qt 左侧导航中,与文件目录共用一个位置:
```text
-Markdown / 代码源文件
- -> 渲染正文 HTML
- -> 同时生成 in-page TOC HTML
- -> 同时生成 in-page progress HTML
- -> QWebEngineView 显示完整阅读页面
- -> reader.js 在页面内部处理滚动进度和目录高亮
- -> Python 只接收低频保存滚动位置、打开链接、保存图片等必要事件
+左侧导航
+ -> 目录页签:搜索、文件树
+ -> 大纲页签:当前文档标题层级
+ -> 用户点击标题
+ -> Python 执行一次锚点或源码跳转
```
### 9.3 预期收益
-- 滚动时不再频繁更新 Qt 右侧目录树。
-- 阅读进度条由网页内部 CSS/JS 更新,减少 Python 主线程压力。
-- 目录高亮、滚动进度和正文滚动在同一个浏览器上下文中完成,更接近浏览器手感。
-- 导出的 HTML 可以复用类似结构,后续更容易做自包含 HTML 或离线分享。
+- 阅读区不被网页内大纲占用,正文宽度稳定。
+- 滚动不触发标题定位、进度计算或 Qt 目录更新。
+- 文件目录和文档大纲都在左侧,用户可明确切换。
+- 阅读、编辑和代码文件仍保留按需标题跳转能力。
### 9.4 分阶段实现
-1. 在 `MarkdownRenderer` 中生成标题列表数据,避免主窗口重复提取。
-2. 在 HTML 模板中增加阅读页外壳:正文区、页面内目录、页面内进度条。
-3. 在 `reader.css` 中实现内嵌目录和进度条的浅色/深色主题样式。
-4. 在 `reader.js` 内部完成目录点击跳转、滚动高亮和进度条更新。
-5. 阅读模式关闭或弱化 Qt 右侧目录树和状态栏进度条。
-6. WebChannel 滚动上报降为低频保存阅读位置,不参与每次视觉更新。
-7. 编辑模式保留源码目录定位能力,预览内目录点击通过离散事件回传源码定位。
-8. 增加设置项:是否显示网页内目录、是否保留外部目录栏。
-9. 补充 GUI smoke:目录点击、滚动进度、主题切换、编辑模式定位。
+1. 删除状态栏进度条和网页内进度条。
+2. 删除网页内大纲及其 CSS、JS 与预览桥接。
+3. 删除滚动时的进度计算、当前标题二分定位和 WebChannel 上报。
+4. 将文件目录和当前文档大纲合并到左侧切换页签。
+5. 保留固定低频滚动坐标保存,用于历史返回和重新打开恢复。
+6. 补充单元测试和 GUI smoke,覆盖左侧切换、标题跳转和无导航装饰的 HTML。
### 9.5 风险与约束
-- 网页内目录会占用阅读区宽度,需要在窄窗口下自动折叠或隐藏。
-- 很长文档的大纲 DOM 可能较大,需要虚拟化或折叠策略作为后续优化。
-- 编辑模式不能丢失源码定位能力,不能简单删除 Qt 目录栏。
-- 外部目录栏和网页内目录同时存在时可能造成重复,需要明确默认策略。
+- 大纲列表在文档打开或内容刷新时重建,不在滚动时重建。
+- 编辑模式的大纲点击直接定位源码标题。
+- 阅读位置保存仍是异步低频调用,不参与逐帧渲染。
- WebEngine 的滚动手感仍受页面复杂度影响,Mermaid、公式和大图片仍可能造成局部卡顿。
## 10. 导出设计
@@ -202,11 +194,7 @@ Markdown / 代码源文件
- MHTML:将当前 HTML 打包为 MHTML 文本。
- DOCX:提供 `pandoc` 和内置 `python-docx` 相关实现作为用户可选项。
-0.2.0 后如果阅读页引入内嵌目录和进度条,需要区分“阅读用 HTML”和“导出用 HTML”:
-
-- 导出 HTML 默认应保留正文、样式、代码高亮和媒体引用。
-- 是否导出网页内目录应作为选项或使用导出专用模板。
-- 阅读进度条通常不应出现在导出文档中。
+阅读页本身不包含大纲或进度条,因此导出 HTML 无需额外剥离阅读导航控件。
## 11. 打包设计
@@ -220,6 +208,6 @@ PyInstaller 使用 `MDHelper.spec`。必须包含:
推荐打包命令:
```powershell
-.\mdhelper_env\Scripts\python.exe -m PyInstaller .\MDHelper.spec --noconfirm --clean
-.\dist\MDHelper.exe --check --project-root .
-```
\ No newline at end of file
+.\pack\_installer.cmd
+.\dist\MDHelper\MDHelper.exe --check --project-root .
+```
diff --git a/README.md b/README.md
index 21b636b..e33495f 100644
--- a/README.md
+++ b/README.md
@@ -39,48 +39,24 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构
-> 文件变化、样式变化、主题变化或手动刷新时重新生成 HTML 并 setHtml
```
-正常滚动浏览时不会重新转译 Markdown,也不会重新生成 HTML。滚动阶段主要由 Qt WebEngine 内部的 Chromium 渲染;当前仍会低频把滚动进度和当前章节通过 WebChannel 回传给 Python,用于更新状态栏进度和 Qt 目录树。
+正常滚动浏览时不会重新转译 Markdown,也不会重新生成 HTML。滚动阶段由 Qt WebEngine 内部的 Chromium 渲染;应用只按固定低频保存滚动坐标,用于重新打开或历史返回时恢复位置。
-## 0.2.0 重点方向
+## 当前导航设计
-`0.2.0` 的主线目标是提升阅读流畅度,让阅读模式更接近浏览器打开网页的手感。
+左侧导航栏提供两个页签:
-计划将“当前文档大纲”和“阅读进度”从外部 Qt 控件逐步迁移进 HTML 阅读页:
+- `目录`:显示当前文件夹中的文档、搜索框和搜索结果。
+- `大纲`:显示当前文档的标题层级,点击标题时跳转。
-```text
-当前方案:
-QWebEngineView 正文滚动
- -> JS 计算滚动位置
- -> WebChannel 回传 Python
- -> Python 更新 QProgressBar 和 QTreeWidget
-
-0.2.0 目标方案:
-QWebEngineView 内部同时包含正文、大纲和进度条
- -> JS 在网页内部更新目录高亮和进度条
- -> Python 只接收低频滚动位置保存、链接打开、图片保存等必要事件
-```
-
-预期收益:
-
-- 滚动时减少 Python / Qt 控件更新,降低 WebChannel 往返。
-- 大纲高亮、阅读进度和正文滚动都由浏览器内部处理,交互更轻。
-- 阅读模式和导出的 HTML 更接近同一套页面结构,便于调试和后续导出增强。
-
-需要保留的边界:
-
-- 左侧文件树、全文搜索、多标签、菜单、设置仍由 Qt 提供。
-- 编辑模式保留源码定位能力;预览内大纲点击需要能回传到编辑器定位标题。
-- 自动刷新仍以源文件为准,文件变化后重新 Markdown -> HTML。
-- 对大文档可以评估“临时 HTML 文件 + load(file://)”作为可选路径,但它不是滚动流畅度的首要优化。
+大纲不会跟随正文滚动高亮。阅读页不生成页面内大纲或阅读进度条,也不在滚动时搜索当前标题、计算进度或通过 WebChannel 连续回传状态。这能避免长文档滚动时的额外计算和界面同步。
## 编辑模式注意事项
编辑模式和阅读模式会区别处理:
-- 阅读模式优先追求浏览器式流畅滚动,大纲和进度条可内嵌到 HTML。
-- 编辑模式保留源码编辑、源码目录、分屏预览和保存冲突检测。
-- 编辑预览刷新需要防抖,避免每次输入都完整重建 HTML 和大纲。
-- 预览中的大纲点击如果要定位源码,需要通过 WebChannel 发送离散事件,而不是持续同步滚动位置。
+- 阅读模式只显示正文,左侧大纲按需点击跳转。
+- 编辑模式保留源码编辑、左侧大纲、分屏预览和保存冲突检测。
+- 编辑预览刷新使用防抖,避免每次输入都完整重建 HTML。
## 快捷键
@@ -129,18 +105,38 @@ QWebEngineView 内部同时包含正文、大纲和进度条
.\mdhelper_env\Scripts\python.exe .\tests\gui_smoke.py
```
-打包为单文件 exe:
+一键生成 Windows 安装程序(推荐):
```powershell
-.\mdhelper_env\Scripts\python.exe -m PyInstaller .\MDHelper.spec --noconfirm --clean
+.\pack\_installer.cmd
```
-生成文件位于 `dist\MDHelper.exe`。打包后建议执行:
+也可直接双击 `pack\_installer.cmd`。脚本自动检查依赖、运行回归测试、生成程序目录并制作安装 EXE。
+首次缺少 Inno Setup 时会从官方来源下载、校验发布者签名并安装到 `pack\.tools`;后续构建复用。
+需要可用的 64 位 Python 3.10+;兼容当前项目的两种 `mdhelper_env` 目录布局。
+
+安装程序位于 `pack\output\MDHelper-Setup-0.2.0-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。
+默认按当前用户安装,提供开始菜单入口、可选桌面快捷方式,以及 Windows 卸载入口。
+程序运行时无需单独安装 Python 或 Pandoc。
+
+开发用程序目录为 `dist\MDHelper\`,必须保留整个目录,不能只复制其中的 EXE。
+旧的 `dist\MDHelper.exe` 不再更新。打包后可执行:
```powershell
-.\dist\MDHelper.exe --check --project-root .
+.\dist\MDHelper\MDHelper.exe --check --project-root .
```
+完整构建说明见 [pack/README.md](pack/README.md)。
+
+## 启动优化
+
+- 使用目录式程序和安装包,Qt、Pandoc 等资源只在安装时解压一次。
+- 欢迎页使用普通 Qt 控件;打开文档时才创建浏览器页面。
+- 先显示主窗口,后台扫描初始目录;去掉读取设置前的重复扫描和打开初始文件时的重复扫描。
+- 普通文档不加载公式、图表运行库;公式与图表按页面内容分别加载。
+- 缓存阅读样式、脚本和高亮样式;仅在使用 PDF 页码解析时加载相关依赖。
+- 启动日志记录模块导入之后到窗口显示的耗时;该时间不包含进程启动和模块导入。
+
## 依赖
核心依赖已写入 `requirements.txt`:
@@ -151,11 +147,12 @@ markdown-it-py==4.2.0
Pygments==2.20.0
Pillow==12.2.0
python-docx==1.2.0
+pypdf==6.14.2
PyInstaller==6.20.0
```
-外部可选工具:
+配套工具:
-- `pandoc`:用于增强 DOCX 导出。
+- `pandoc`:用于增强 DOCX 导出,正式 EXE 已内置,无需用户另行安装或配置 PATH。
- 系统默认浏览器 / 默认文件关联:用于打开外部链接和非预览文件。
diff --git a/docs/README.md b/docs/README.md
index 6b01ee5..854b79c 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -13,7 +13,7 @@
| 主题 | 文档 |
|---|---|
| 启动、打开文件夹、路径参数 | [快速开始](quick_start.md) |
-| 阅读界面、网页内大纲、纸张宽度 | [用户手册](user_manual.md) |
+| 阅读界面、左侧大纲、纸张宽度 | [用户手册](user_manual.md) |
| Markdown 编辑、分屏预览、草稿 | [用户手册](user_manual.md) |
| 文件类型展示、代码文件阅读 | [用户手册](user_manual.md) |
| PDF/HTML/DOCX/MHTML 导出 | [用户手册](user_manual.md) |
@@ -28,5 +28,5 @@
打包版:
```powershell
-.\dist\MDHelper.exe --check --project-root .
+.\dist\MDHelper\MDHelper.exe --check --project-root .
```
diff --git a/docs/quick_start.md b/docs/quick_start.md
index 033638d..dddbc19 100644
--- a/docs/quick_start.md
+++ b/docs/quick_start.md
@@ -23,7 +23,7 @@
打包版同样支持路径参数:
```powershell
-.\dist\MDHelper.exe D:\CODE\SomeProject
+.\dist\MDHelper\MDHelper.exe D:\CODE\SomeProject
```
## 2. 打开文档
@@ -44,11 +44,12 @@
- `正文字号倍率`:调整阅读字号。
- `鼠标滚轮速度`:调整滚轮滚动倍率。
- `纸张宽度`:默认 A4,可选 `A4 × 1.25` 到 `A4 × 2`。
-- `阅读导航`:网页内大纲、外部目录栏、网页内进度条。
- `展示文件类型`:Markdown / 网页、Python、C / C++、Fortran。
纸张宽度越大,同一行能显示的文字越多。
+左侧导航栏可在 `目录` 和 `大纲` 间切换。大纲只在点击标题时跳转,不跟随正文滚动。
+
## 4. 搜索
左侧搜索框用于搜索当前文件夹:
@@ -77,7 +78,9 @@
- DOCX
- MHTML
-DOCX 可使用 pandoc 或 python-docx。MHTML 适合把 HTML 和资源打包成单个文件。
+导出 PDF 时可设置四边页边距。PDF 会使用白色页面,并在正文前自动生成带页码的目录页。
+
+DOCX 可使用 Pandoc 或 python-docx;正式安装版已包含 Pandoc,无需额外安装。MHTML 适合把 HTML 和资源打包成单个文件。
## 7. 文档检查
@@ -90,6 +93,6 @@ DOCX 可使用 pandoc 或 python-docx。MHTML 适合把 HTML 和资源打包成
打包版:
```powershell
-.\dist\MDHelper.exe --check --project-root .
+.\dist\MDHelper\MDHelper.exe --check --project-root .
```
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 9bf00e5..036b9fe 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -1,19 +1,14 @@
# MDHelper 常见问题
-## 右侧外部目录栏还显示
+## 找不到文档大纲
-默认推荐使用网页内文档大纲,位置在正文右侧。若仍看到最右侧 Qt 目录栏,请检查:
+大纲已经移到左侧导航栏:
-1. 打开 `工具 - 设置`。
-2. 勾选 `网页内大纲`。
-3. 取消或禁用 `外部目录栏`。
-4. 刷新当前文档。
+1. 点击左侧的 `大纲` 页签。
+2. 点击标题即可跳转。
+3. 如果列表为空,请确认当前文档包含 Markdown 标题,必要时刷新当前文档。
-当网页内大纲开启时,外部目录栏会自动隐藏。
-
-## 文档大纲在正文左侧
-
-0.2.0 当前布局应为正文在左、大纲在正文右侧。如果仍在左侧,说明正在运行旧 exe 或旧源码。请重新运行最新源码,或重新打包 exe。
+大纲不会跟随正文滚动选中当前章节,这是为了避免持续定位和界面同步。
## 每行文字太少或太多
@@ -29,8 +24,6 @@
可尝试:
-- 使用网页内大纲和网页内进度条。
-- 关闭外部目录栏。
- 将鼠标滚轮速度保持在 `1.0` 附近。
- 对超大代码文件,避免同时启用过多文件类型。
- Mermaid、公式、大图片和超长代码块很多的文档会更依赖 WebEngine 渲染性能。
@@ -71,12 +64,11 @@ MDHelper 读取文档时不会锁定文件,外部编辑器仍可保存。
检查:
-- 是否安装 pandoc。
- 是否安装 python-docx。
- 当前文档路径和输出目录是否可写。
- 文档中引用的图片路径是否存在。
-如果 pandoc 不可用,可切换到 python-docx 相关实现;复杂 Markdown 的 DOCX 版式通常 pandoc 更稳定。
+正式安装版 MDHelper 已包含 Pandoc,无需用户安装或配置 PATH。如果提示“未找到程序内置的 Pandoc”,说明程序文件可能不完整,请重新获取完整版本。也可临时切换到 python-docx 或内置基础导出;复杂 Markdown 的 DOCX 版式通常 Pandoc 更稳定。
## PDF 导出失败
@@ -112,13 +104,13 @@ MDHelper 读取文档时不会锁定文件,外部编辑器仍可保存。
说明 PyInstaller 打包时没有正确带上 PySide6 或 WebEngine 资源。请使用项目根目录下的 `MDHelper.spec` 打包:
```powershell
-.\mdhelper_env\Scripts\python.exe -m PyInstaller .\MDHelper.spec --noconfirm --clean
+.\pack\_installer.cmd
```
打包后执行:
```powershell
-.\dist\MDHelper.exe --check --project-root .
+.\dist\MDHelper\MDHelper.exe --check --project-root .
```
## 如何定位日志
diff --git a/docs/user_manual.md b/docs/user_manual.md
index e692a25..5db4bd6 100644
--- a/docs/user_manual.md
+++ b/docs/user_manual.md
@@ -31,22 +31,21 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,适合阅读项目
打包版可以同样接收路径参数:
```powershell
-.\dist\MDHelper.exe D:\CODE\SomeProject
+.\dist\MDHelper\MDHelper.exe D:\CODE\SomeProject
```
MDHelper 支持同时运行多个程序窗口。不同窗口可以打开不同文件夹,标签页、搜索、设置和自动刷新状态互不影响。
## 3. 主界面
-界面主要分为三部分:
+界面主要分为两部分:
| 区域 | 功能 |
|---|---|
-| 左侧文档栏 | 打开文件夹、刷新、搜索、文件树、文件类型过滤结果。 |
+| 左侧导航栏 | 在“目录”和“大纲”间切换;目录包含搜索与文件树,大纲显示当前文档标题。 |
| 中间标签页 | 阅读、编辑、预览、媒体页面和欢迎页。 |
-| 文档内容右侧 | 网页内文档大纲,随正文滚动高亮当前章节。 |
-默认阅读模式会把文档大纲和阅读进度放在网页内部,减少 Qt 控件同步,让滚动更接近浏览器网页。右侧旧 Qt 目录栏默认关闭;只有在设置中关闭网页内大纲并启用外部目录栏时才显示。
+阅读页只显示正文,不在网页内部生成大纲或进度条。左侧大纲不会随正文滚动高亮;只有用户点击标题时才执行跳转,避免长文档滚动时持续计算当前位置。
## 4. 阅读 Markdown
@@ -60,9 +59,7 @@ Markdown 支持:
- 本地图片、GIF、音频和视频。
- 本地链接跳转和外部链接打开。
-阅读页内的文档大纲位于正文右侧,点击章节可跳转。窄窗口下大纲会自动折叠或隐藏。
-
-右下角阅读进度条会跟随主题改变颜色。进度条只在网页内部更新,Python 端只低频保存滚动位置。
+切换左侧的 `大纲` 页签并点击章节即可跳转。滚动位置仍会低频保存,用于重新打开文档时恢复阅读位置。
## 5. 纸张宽度与每行字数
@@ -115,12 +112,15 @@ Markdown 支持:
- 行号和当前行高亮。
- 查找、替换、区分大小写、全词匹配。
- 插入标题、加粗、斜体、代码块、表格、链接、图片、提示块、Mermaid、公式。
+- 点击“转换latex公式到md”,可将全文中的 `\\[` 和 `\\]` 一键转换为 `$$`,并支持回退撤销。
+- 打开文件夹后,可通过“文件 → 新建文件”或左侧目录树右键菜单直接创建 `.md` 文件。新文件会在目标目录中自动生成并进入文件名编辑状态,无需打开浏览窗口。
+- 左侧目录树支持多选文件;右键单个文件可重命名,右键选择“删除”并确认后可批量移入系统回收站。右键非根文件夹还可在确认后删除该文件夹及其内容。
- `Ctrl+S` 保存。
- 另存为。
- 自动保存草稿和恢复草稿。
- 保存前检测磁盘文件是否被外部程序修改,避免覆盖外部编辑。
-编辑预览中的网页内大纲可点击定位源码标题。预览刷新使用防抖机制,避免每次按键都重新渲染。
+编辑时左侧大纲可点击定位源码标题。预览刷新使用防抖机制,避免每次按键都重新渲染。
## 9. 样式管理
@@ -186,7 +186,9 @@ MDHelper 读取文档时不会独占文件,外部程序仍可修改文件。
- DOCX
- MHTML
-DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。导出的 HTML 默认不包含网页内阅读进度条,避免把阅读状态写进文档。
+PDF 导出前会显示设置窗口,可分别设置上、下、左、右页边距。导出文件固定使用白色纸张背景,自动移除阅读页大纲和进度条,并在正文前生成带真实页码的目录;正文从目录后的新页面开始。
+
+DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。正式安装版已包含 Pandoc,无需用户另行下载或配置 PATH。导出的 HTML 与阅读页一样不包含阅读进度控件。
## 13. 配置与迁移
@@ -226,6 +228,6 @@ MDHelper 会保存:
打包版:
```powershell
-.\dist\MDHelper.exe --check --project-root .
+.\dist\MDHelper\MDHelper.exe --check --project-root .
```
diff --git a/mdhelper/app.py b/mdhelper/app.py
index f58b8f0..018c4a6 100644
--- a/mdhelper/app.py
+++ b/mdhelper/app.py
@@ -5,11 +5,12 @@ import logging
import os
import sys
import tempfile
+import time
from pathlib import Path
os.environ.setdefault(
"QTWEBENGINE_CHROMIUM_FLAGS",
- "--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --log-level=3",
+ "--log-level=3",
)
os.environ.setdefault(
"QT_LOGGING_RULES",
@@ -92,6 +93,7 @@ def configure_process_runtime(log_root: Path) -> Path:
def main(argv: list[str] | None = None) -> int:
+ startup_started = time.perf_counter()
args = parse_arguments(list(sys.argv[1:] if argv is None else argv))
content_root, log_root = runtime_paths()
search_roots = (Path.cwd(), log_root, content_root)
@@ -123,8 +125,11 @@ def main(argv: list[str] | None = None) -> int:
log_root,
)
- icon_path = content_root / "icon_glass.png"
- if icon_path.exists():
+ icon_path = next(
+ (candidate for candidate in (content_root / "icon_glass.png", content_root / "icon_glass.ico") if candidate.exists()),
+ None,
+ )
+ if icon_path is not None:
app.setWindowIcon(QIcon(str(icon_path)))
window = MainWindow(
@@ -132,7 +137,9 @@ def main(argv: list[str] | None = None) -> int:
initial_path=cli_initial_path,
app_root=content_root,
prompt_for_project=project_root is None,
+ defer_startup=True,
)
window.show()
+ logging.getLogger(__name__).info("Main window shown in %.3f s (after imports)", time.perf_counter() - startup_started)
return app.exec()
diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py
index 6cfb228..93bc063 100644
--- a/mdhelper/docx_exporter.py
+++ b/mdhelper/docx_exporter.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import html
+import shutil
import subprocess
+import sys
import tempfile
import zipfile
from dataclasses import dataclass
@@ -24,6 +26,24 @@ class DocxExportError(RuntimeError):
pass
+def resolve_pandoc_executable() -> Path | None:
+ """Locate the bundled Pandoc first, with PATH as a development fallback."""
+ roots: list[Path] = []
+ bundled_root = getattr(sys, "_MEIPASS", None)
+ if bundled_root:
+ roots.append(Path(bundled_root))
+ roots.append(Path(__file__).resolve().parent.parent)
+
+ executable_name = "pandoc.exe" if sys.platform == "win32" else "pandoc"
+ for root in roots:
+ candidate = root / "vendor" / "pandoc" / executable_name
+ if candidate.is_file():
+ return candidate
+
+ path_executable = shutil.which("pandoc")
+ return Path(path_executable) if path_executable else None
+
+
def export_markdown_to_docx(
source: str,
output_path: Path,
@@ -58,6 +78,10 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path:
output_path = output_path.with_suffix(".docx")
output_path.parent.mkdir(parents=True, exist_ok=True)
+ pandoc_path = resolve_pandoc_executable()
+ if pandoc_path is None:
+ raise DocxExportError("未找到程序内置的 Pandoc,当前 MDHelper 安装包可能不完整,请重新获取完整版本。")
+
temporary_path: Path | None = None
input_path = source_path if source_path is not None and source_path.exists() else None
if input_path is None:
@@ -66,7 +90,10 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path:
temporary_path = Path(handle.name)
input_path = temporary_path
- command = ["pandoc", str(input_path), "-o", str(output_path), "--standalone"]
+ command = [str(pandoc_path), str(input_path), "-o", str(output_path), "--standalone"]
+ run_options: dict[str, object] = {}
+ if sys.platform == "win32":
+ run_options["creationflags"] = subprocess.CREATE_NO_WINDOW
try:
result = subprocess.run(
command,
@@ -75,9 +102,10 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path:
text=True,
timeout=120,
check=False,
+ **run_options,
)
except FileNotFoundError as exc:
- raise DocxExportError("未找到 pandoc,请确认 pandoc 已安装并加入 PATH。") from exc
+ raise DocxExportError("程序内置的 Pandoc 无法启动,当前 MDHelper 安装包可能不完整。") from exc
except subprocess.TimeoutExpired as exc:
raise DocxExportError("pandoc 导出超时。") from exc
finally:
diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py
index ace87cf..db16442 100644
--- a/mdhelper/main_window.py
+++ b/mdhelper/main_window.py
@@ -15,7 +15,7 @@ from email.policy import default as email_default_policy
from pathlib import Path
from urllib.parse import unquote, urlsplit
-from PySide6.QtCore import QFileSystemWatcher, QObject, QPoint, QProcess, QSettings, QSignalBlocker, QSize, QTimer, QUrl, Qt, Signal, Slot
+from PySide6.QtCore import QFile, QFileSystemWatcher, QObject, QPoint, QProcess, QSettings, QSignalBlocker, QSize, QThreadPool, QTimer, QUrl, Qt, Signal, Slot
from PySide6.QtGui import (
QAction,
QActionGroup,
@@ -36,6 +36,7 @@ from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
from PySide6.QtWidgets import (
+ QAbstractItemView,
QApplication,
QComboBox,
QFileDialog,
@@ -47,7 +48,6 @@ from PySide6.QtWidgets import (
QMainWindow,
QMenu,
QMessageBox,
- QProgressBar,
QPushButton,
QSlider,
QSplitter,
@@ -56,6 +56,7 @@ from PySide6.QtWidgets import (
QStyle,
QTabBar,
QTabWidget,
+ QTextBrowser,
QTreeWidget,
QTreeWidgetItem,
QHBoxLayout,
@@ -83,10 +84,18 @@ from .markdown_utils import Heading, extract_headings, extract_headings_from_tex
from .markdown_editor import MarkdownEditorDialog as RichMarkdownEditorDialog
from .markdown_renderer import MarkdownRenderer
from .media import is_markdown_url, is_qt_video_player_url, is_webpage_url, media_kind, media_mime_type
+from .pdf_export import (
+ PdfExportSettingsDialog,
+ PdfMargins,
+ build_pdf_export_html,
+ build_pdf_page_layout,
+ extract_heading_page_numbers,
+)
from .search import SearchIndex
from .settings_dialog import AppPreferences, SettingsDialog
from .style_dialog import DocumentStyleEditorDialog, build_document_style_css
from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback
+from .startup_scan import StartupScan
BOOKMARKS_SETTING_KEY = "bookmarks/items"
@@ -101,6 +110,17 @@ THEME_COLOR_VALUES = {"white", "black", "dark_gray", "colorful"}
WHEEL_SCROLL_SPEED_MIN = 0.5
WHEEL_SCROLL_SPEED_MAX = 3.0
READER_WIDTH_SCALES = (1.0, 1.25, 1.5, 1.75, 2.0)
+
+
+def available_new_markdown_path(directory: Path) -> Path:
+ candidate = directory / "新建文件.md"
+ sequence = 2
+ while candidate.exists():
+ candidate = directory / f"新建文件 ({sequence}).md"
+ sequence += 1
+ return candidate
+
+
DOCUMENT_STYLE_PRESETS = {
"default": {
"name": "默认阅读",
@@ -260,14 +280,9 @@ class ReaderPage(QWebEnginePage):
class ReaderBridge(QObject):
- scroll_changed = Signal(float, str, int)
image_save_requested = Signal(str)
image_reveal_requested = Signal(str)
- @Slot(float, str, int)
- def reportScroll(self, progress: float, heading_id: str, scroll_y: int) -> None:
- self.scroll_changed.emit(progress, heading_id, scroll_y)
-
@Slot(str)
def saveImage(self, url: str) -> None:
self.image_save_requested.emit(url)
@@ -489,34 +504,34 @@ class MainWindow(QMainWindow):
initial_path: Path | None = None,
app_root: Path | None = None,
prompt_for_project: bool = False,
+ defer_startup: bool = False,
) -> None:
super().__init__()
self.app_root = (app_root or project_root or Path.cwd()).resolve()
self.resources_dir = Path(__file__).resolve().parent / "resources"
- self.base_window_icon_path = self.app_root / "icon_glass.png"
+ self.base_window_icon_path = next(
+ (candidate for candidate in (self.app_root / "icon_glass.png", self.app_root / "icon_glass.ico") if candidate.exists()),
+ self.app_root / "icon_glass.png",
+ )
self.project_root = (project_root or self.app_root).resolve()
self.has_project = project_root is not None
+ self._startup_generation = 0
+ self._startup_scan_pending = defer_startup and self.has_project
+ self._startup_initial_path = initial_path
+ self._startup_prompt = prompt_for_project
self.settings = QSettings("MDHelper", "MDHelper")
self.document_file_groups = DEFAULT_DOCUMENT_FILE_GROUPS
self.renderer = MarkdownRenderer(self.project_root)
- self.entries: list[DocumentEntry] = (
- discover_documents(self.project_root, self.document_file_groups) if self.has_project else []
- )
+ self.entries: list[DocumentEntry] = []
self.search_index = SearchIndex(self.entries)
self.current_file: Path | None = None
self.current_fragment = ""
self.pending_fragment = ""
self.pending_find_text = ""
self.pending_scroll_y: int | None = None
- self.pending_toc_heading_id = ""
- self.last_toc_heading_id = ""
- self.toc_items_by_slug: dict[str, QTreeWidgetItem] = {}
self.font_scale = 1.0
self.wheel_scroll_speed = 1.0
self.reader_width_scale = 1.0
- self.reader_embedded_toc = True
- self.reader_external_toc = False
- self.reader_embedded_progress = True
self.theme = "light"
self.theme_color = "colorful"
self.theme_background = "none"
@@ -544,8 +559,11 @@ class MainWindow(QMainWindow):
self.watched_file_signatures: dict[Path, tuple[int, int] | None] = {}
self.pending_changed_files: set[Path] = set()
self.pending_directory_refresh = False
+ self._new_file_rename_item: QTreeWidgetItem | None = None
+ self._new_file_rename_path: Path | None = None
+ self._tree_rename_is_new = False
self.document_entries_signature = self._document_entries_signature(self.entries)
- self.document_directory_signature = document_directory_signature(self.project_root, self.document_file_groups) if self.has_project else tuple()
+ self.document_directory_signature = tuple()
self.file_watcher = QFileSystemWatcher(self)
self.file_watcher.fileChanged.connect(self._on_watched_file_changed)
self.file_watcher.directoryChanged.connect(self._on_watched_directory_changed)
@@ -568,13 +586,8 @@ class MainWindow(QMainWindow):
self.scroll_capture_timer.setInterval(1500)
self.scroll_capture_timer.timeout.connect(self._save_current_scroll_position)
- self.toc_highlight_timer = QTimer(self)
- self.toc_highlight_timer.setSingleShot(True)
- self.toc_highlight_timer.setInterval(160)
- self.toc_highlight_timer.timeout.connect(self._apply_pending_toc_highlight)
-
self._load_preferences()
- if self.has_project:
+ if self.has_project and not defer_startup:
self.entries = discover_documents(self.project_root, self.document_file_groups)
self.document_entries_signature = self._document_entries_signature(self.entries)
self.document_directory_signature = document_directory_signature(self.project_root, self.document_file_groups)
@@ -595,17 +608,62 @@ class MainWindow(QMainWindow):
self.resize(1280, 820)
QTimer.singleShot(0, self._apply_navigation_style)
+ if defer_startup:
+ if self.has_project:
+ self.status_label.setText(f"正在加载目录:{self.project_root}")
+ QTimer.singleShot(0, self._finish_startup)
+ else:
+ self._open_startup_document(initial_path, prompt_for_project)
+
+ def _finish_startup(self) -> None:
+ if self._startup_generation != 0:
+ return
+ if self.has_project:
+ job = StartupScan(self._startup_generation, self.project_root, self.document_file_groups)
+ job.signals.finished.connect(self._on_startup_scan_finished)
+ QThreadPool.globalInstance().start(job)
+ self._open_startup_document(self._startup_initial_path, self._startup_prompt)
+
+ @Slot(object)
+ def _on_startup_scan_finished(self, result: object) -> None:
+ generation, root, groups, entries, signature, error = result
+ if generation != self._startup_generation or not self.has_project or root != self.project_root:
+ return
+ self._startup_scan_pending = False
+ if groups != self.document_file_groups:
+ self._refresh_document_entries(force=True)
+ return
+ if error:
+ LOGGER.warning("Initial directory scan failed: %s", error)
+ self.status_label.setText(f"目录加载失败:{error}")
+ else:
+ self.entries = entries
+ self.document_entries_signature = self._document_entries_signature(entries)
+ self.document_directory_signature = signature
+ self.search_index.rebuild(entries)
+ if self.current_file and self.current_file.exists() and self._is_supported_document_path(self.current_file):
+ self._ensure_document_entry(self.current_file)
+ self._populate_tree()
+ self._filter_tree(self.search_box.text())
+ if self.current_file is None:
+ self.status_label.setText(f"已打开文件夹:{self.project_root}")
+ LOGGER.info("Initial directory ready: %s documents", len(entries))
+ self._update_watched_paths()
+ self._apply_auto_refresh_timing()
+
+ def _open_startup_document(self, initial_path: Path | None, prompt_for_project: bool) -> None:
if initial_path is not None and initial_path.exists():
initial = initial_path.resolve()
- if initial.suffix.lower() in {".md", ".markdown"}:
+ if not self.has_project or self.project_root != initial.parent:
self.set_project_root(initial.parent, save=True)
+ else:
+ self.settings.setValue(LAST_PROJECT_ROOT_SETTING_KEY, str(self.project_root))
+ if initial.suffix.lower() in {".md", ".markdown"}:
self._ensure_document_entry(initial)
self.open_document(initial)
elif initial.suffix.lower() in {".html", ".htm", ".xhtml"}:
- self.set_project_root(initial.parent, save=True)
self._open_webpage_file_now(initial)
else:
- self.set_project_root(initial.parent, save=True)
QTimer.singleShot(0, lambda path=initial: self._open_local_file_now(path))
elif self.has_project:
self.status_label.setText(f"已打开文件夹:{self.project_root}")
@@ -671,6 +729,12 @@ class MainWindow(QMainWindow):
self.open_action.triggered.connect(self.open_markdown_file)
file_menu.addAction(self.open_action)
+ self.new_file_action = QAction("新建文件", self)
+ self.new_file_action.setShortcut("Ctrl+N")
+ self.new_file_action.setEnabled(self.has_project)
+ self.new_file_action.triggered.connect(lambda checked=False: self.create_new_markdown_file())
+ file_menu.addAction(self.new_file_action)
+
self.open_folder_action = QAction("打开文件夹", self)
self.open_folder_action.triggered.connect(self.open_project_folder)
file_menu.addAction(self.open_folder_action)
@@ -791,9 +855,12 @@ class MainWindow(QMainWindow):
self.tree = QTreeWidget()
self.tree.setObjectName("navigationTree")
self.tree.setHeaderHidden(True)
+ self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self._configure_navigation_tree(self.tree)
self.tree.itemActivated.connect(self._open_tree_item)
self.tree.itemClicked.connect(self._open_tree_item)
+ self.tree.itemChanged.connect(self._finish_new_file_rename)
+ self.tree.itemDelegate().closeEditor.connect(self._on_tree_name_editor_closed)
self.tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self._show_tree_context_menu)
@@ -851,19 +918,45 @@ class MainWindow(QMainWindow):
self.search_results.itemClicked.connect(self._open_search_result)
self.search_results.hide()
+ self.toc_tree = QTreeWidget()
+ self.toc_tree.setObjectName("tocTree")
+ self.toc_tree.setHeaderHidden(True)
+ self._configure_navigation_tree(self.toc_tree)
+ self.toc_tree.itemActivated.connect(lambda item, column: self._open_toc_item(item))
+ self.toc_tree.itemPressed.connect(lambda item, column: self._open_toc_item(item))
+
+ directory_page = QWidget()
+ directory_layout = QVBoxLayout(directory_page)
+ directory_layout.setContentsMargins(0, 0, 0, 0)
+ directory_layout.setSpacing(10)
+ directory_layout.addLayout(search_controls)
+ directory_layout.addWidget(self.search_box)
+ directory_layout.addWidget(self.find_result_label)
+ directory_layout.addWidget(self.search_results_label)
+ directory_layout.addWidget(self.search_results)
+ directory_layout.addWidget(self.tree)
+
+ outline_page = QWidget()
+ outline_layout = QVBoxLayout(outline_page)
+ outline_layout.setContentsMargins(0, 0, 0, 0)
+ outline_layout.addWidget(self.toc_tree)
+
+ self.navigation_tabs = QTabWidget()
+ self.navigation_tabs.setObjectName("navigationTabs")
+ self.navigation_tabs.setDocumentMode(True)
+ self.navigation_tabs.tabBar().setExpanding(True)
+ self.navigation_tabs.tabBar().setUsesScrollButtons(False)
+ self.navigation_tabs.addTab(directory_page, "目录")
+ self.navigation_tabs.addTab(outline_page, "大纲")
+
left_panel = QWidget()
left_panel.setObjectName("navigationPanel")
left_panel.setMinimumWidth(260)
left_layout = QVBoxLayout(left_panel)
left_layout.setContentsMargins(12, 12, 12, 12)
left_layout.setSpacing(10)
- left_layout.addWidget(self._panel_title("文档", "本地帮助文件"))
- left_layout.addLayout(search_controls)
- left_layout.addWidget(self.search_box)
- left_layout.addWidget(self.find_result_label)
- left_layout.addWidget(self.search_results_label)
- left_layout.addWidget(self.search_results)
- left_layout.addWidget(self.tree)
+ left_layout.addWidget(self._panel_title("导航", "目录与当前文档大纲"))
+ left_layout.addWidget(self.navigation_tabs)
tab_bar = QTabBar()
tab_bar.setMovable(True)
@@ -882,32 +975,14 @@ class MainWindow(QMainWindow):
self.tabs.setMovable(True)
self.tabs.currentChanged.connect(self._on_tab_changed)
self.tabs.tabCloseRequested.connect(self._close_tab)
- self.web_view = self._create_reader_view()
+ self.web_view = None
self._show_welcome_tab()
- self.toc_tree = QTreeWidget()
- self.toc_tree.setObjectName("tocTree")
- self.toc_tree.setHeaderHidden(True)
- self._configure_navigation_tree(self.toc_tree)
- self.toc_tree.itemActivated.connect(lambda item, column: self._open_toc_item(item))
- self.toc_tree.itemPressed.connect(lambda item, column: self._open_toc_item(item))
-
- self.toc_panel = QWidget()
- toc_panel = self.toc_panel
- toc_panel.setObjectName("tocPanel")
- toc_panel.setMinimumWidth(220)
- toc_layout = QVBoxLayout(toc_panel)
- toc_layout.setContentsMargins(12, 12, 12, 12)
- toc_layout.setSpacing(10)
- toc_layout.addWidget(self._panel_title("目录", "当前文档章节"))
- toc_layout.addWidget(self.toc_tree)
-
self.splitter = QSplitter(Qt.Orientation.Horizontal)
self.splitter.setObjectName("mainSplitter")
self.splitter.addWidget(left_panel)
self.splitter.addWidget(self.tabs)
- self.splitter.addWidget(toc_panel)
- self.splitter.setSizes([320, 820, 280])
+ self.splitter.setSizes([320, 1100])
self.splitter.setStretchFactor(1, 1)
self.setCentralWidget(self.splitter)
@@ -916,12 +991,6 @@ class MainWindow(QMainWindow):
self.status_label = QLabel("就绪")
self.status_label.setObjectName("statusPathLabel")
status.addWidget(self.status_label)
- self.reading_progress = QProgressBar()
- self.reading_progress.setRange(0, 100)
- self.reading_progress.setFixedWidth(150)
- self.reading_progress.setTextVisible(True)
- self.reading_progress.setFormat("%p%")
- status.addPermanentWidget(self.reading_progress)
self._update_theme_menu_state()
self._update_math_engine_actions()
self._apply_auto_refresh_timing()
@@ -929,7 +998,6 @@ class MainWindow(QMainWindow):
self._apply_navigation_style()
self._update_recent_menu()
self._update_bookmarks_menu()
- self._apply_reader_navigation_visibility()
def _build_theme_menu(self) -> None:
self.theme_color_menu = self.theme_menu.addMenu("主题颜色")
@@ -1051,7 +1119,6 @@ class MainWindow(QMainWindow):
web_view.reader_bridge = ReaderBridge()
web_view.reader_channel = QWebChannel(web_view)
web_view.reader_channel.registerObject("mdhelperBridge", web_view.reader_bridge)
- web_view.reader_bridge.scroll_changed.connect(self._on_reader_scroll_changed)
web_view.reader_bridge.image_save_requested.connect(self._save_image_from_url)
web_view.reader_bridge.image_reveal_requested.connect(self._reveal_image_from_url)
page = ReaderPage(web_view)
@@ -1124,7 +1191,7 @@ class MainWindow(QMainWindow):
点击 文件 - 打开文件夹 选择帮助文档所在文件夹。
点击 文件 - 打开 选择某个 Markdown 文件,MDHelper 会自动把它所在目录作为当前文件夹。
左侧文档栏会显示当前文件夹下的 Markdown 和网页文件,文件夹默认折叠,点击文件可在标签页中打开。
- 网页内文档大纲用于跳转当前文档标题;编辑 Markdown 时预览大纲也可以定位到源码标题。
+ 左侧导航栏可切换“目录”和“大纲”;点击大纲标题即可跳转,阅读滚动不会触发大纲定位计算。
点击 编辑当前 Markdown 可在标签页内进入分屏编辑。
常用操作
@@ -1136,39 +1203,41 @@ class MainWindow(QMainWindow):
请选择文件夹或文件开始阅读。
"""
- return self.renderer.wrap_body_for_display(
- body,
- "欢迎",
- theme=self.theme,
- font_scale=self.font_scale,
- wheel_scroll_speed=self.wheel_scroll_speed,
- document_width_scale=self.reader_width_scale,
- document_font_family=self.document_font_family,
- document_font_size=self.document_font_size,
- document_style_css=self._document_style_css(),
- math_engine=self.math_engine,
+ font = html.escape(self.document_font_family or "Microsoft YaHei UI", quote=True)
+ return (
+ f''
+ f'{body}'
)
+ def _render_welcome(self, widget: QTextBrowser) -> None:
+ dark = self.theme == "dark"
+ background, foreground = ("#17191f", "#f3f4f6") if dark else ("#ffffff", "#1f2937")
+ widget.setStyleSheet(
+ f"QTextBrowser {{background-color: {background}; color: {foreground}; border: 0; padding: 24px;}}"
+ )
+ widget.document().setDocumentMargin(12)
+ widget.setHtml(self._welcome_html())
+
def _refresh_welcome_tab(self) -> None:
index = self._welcome_tab_index()
if index < 0:
return
widget = self.tabs.widget(index)
- if not isinstance(widget, ReaderView):
+ if not isinstance(widget, QTextBrowser):
return
- widget.setHtml(self._welcome_html(), QUrl.fromLocalFile(str(self.app_root) + os.sep))
- if self.tabs.currentIndex() == index:
- self.web_view = widget
+ self._render_welcome(widget)
def _show_welcome_tab(self) -> None:
if self._welcome_tab_index() >= 0:
return
- web_view = self._create_reader_view()
+ web_view = QTextBrowser()
+ web_view.setOpenExternalLinks(False)
web_view.setProperty("is_welcome", True)
- web_view.setHtml(self._welcome_html(), QUrl.fromLocalFile(str(self.app_root) + os.sep))
+ self._render_welcome(web_view)
index = self.tabs.addTab(web_view, "欢迎")
self.tabs.setCurrentIndex(index)
- self.web_view = web_view
self.current_file = None
self.current_fragment = ""
if hasattr(self, "toc_tree"):
@@ -1455,9 +1524,6 @@ class MainWindow(QMainWindow):
branch_closed_icon = self._stylesheet_url(self.resources_dir / "tree_closed.svg")
branch_open_icon = self._stylesheet_url(self.resources_dir / "tree_open.svg")
search_box_height = max(22, round(self.fontMetrics().height() * 1.5))
- progress_bg = palette["surface"]
- progress_chunk = palette["selected"]
- progress_text = palette["text"]
pattern_style = ""
chrome_pattern_style = ""
if pattern_file:
@@ -1489,19 +1555,6 @@ class MainWindow(QMainWindow):
background: transparent;
}}
- QProgressBar {{
- color: {progress_text};
- background: {progress_bg};
- border: 1px solid {border};
- border-radius: 5px;
- text-align: center;
- }}
-
- QProgressBar::chunk {{
- background: {progress_chunk};
- border-radius: 4px;
- }}
-
QMenuBar::item {{
padding: 5px 9px;
background: transparent;
@@ -1776,13 +1829,6 @@ class MainWindow(QMainWindow):
if hasattr(self, "tabs"):
self._refresh_welcome_tab()
- def _apply_reader_navigation_visibility(self) -> None:
- current = self.tabs.currentWidget() if hasattr(self, "tabs") else None
- show_external_toc = self.reader_external_toc and not self.reader_embedded_toc
- if hasattr(self, "toc_panel"):
- self.toc_panel.setVisible(show_external_toc)
- if hasattr(self, "reading_progress"):
- self.reading_progress.setVisible(not self.reader_embedded_progress)
def _apply_window_title_bar_style(self, background: str, foreground: str) -> None:
if os.name != "nt":
return
@@ -1832,7 +1878,6 @@ class MainWindow(QMainWindow):
def _on_tab_changed(self, index: int) -> None:
widget = self.tabs.widget(index)
- self._apply_reader_navigation_visibility()
if widget is None:
return
if bool(widget.property("is_welcome")):
@@ -2256,6 +2301,9 @@ class MainWindow(QMainWindow):
visit(self.tree.topLevelItem(index))
def _populate_tree(self) -> None:
+ self._new_file_rename_item = None
+ self._new_file_rename_path = None
+ self._tree_rename_is_new = False
expanded_keys = self._expanded_tree_keys()
selected_path = self.current_file
self.tree.clear()
@@ -2321,10 +2369,157 @@ class MainWindow(QMainWindow):
if self.set_project_root(Path(folder), save=True):
self.status_label.setText(f"已打开文件夹:{self.project_root}")
+ def _new_file_directory(self, item: QTreeWidgetItem | None = None) -> Path | None:
+ if not self.has_project:
+ return None
+ selected_item = item or self.tree.currentItem()
+ if selected_item is None:
+ return self.project_root
+
+ file_data = selected_item.data(0, Qt.ItemDataRole.UserRole)
+ if file_data:
+ directory = Path(str(file_data)).resolve().parent
+ else:
+ tooltip = selected_item.toolTip(0)
+ directory = Path(tooltip).resolve() if tooltip else self.project_root
+
+ if directory.is_dir() and self._is_relative_to(directory, self.project_root):
+ return directory
+ return self.project_root
+
+ def create_new_markdown_file(self, target_item: QTreeWidgetItem | None = None) -> Path | None:
+ directory = self._new_file_directory(target_item)
+ if directory is None:
+ self.status_label.setText("请先打开一个文件夹")
+ return None
+
+ new_path = available_new_markdown_path(directory)
+ try:
+ new_path.write_text("", encoding="utf-8", newline="")
+ except OSError as exc:
+ LOGGER.exception("Failed to create Markdown file: %s", new_path)
+ QMessageBox.warning(self, "新建失败", f"无法创建 Markdown 文件:\n{new_path}\n\n{exc}")
+ return None
+
+ self._refresh_document_entries(force=True)
+ self.pending_directory_refresh = False
+ item = self.path_to_item.get(new_path.resolve())
+ if item is None:
+ QMessageBox.warning(self, "新建失败", f"文件已创建,但无法在目录窗口中定位:\n{new_path}")
+ return new_path
+
+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
+ with QSignalBlocker(self.tree):
+ item.setText(0, new_path.name)
+ self._new_file_rename_item = item
+ self._new_file_rename_path = new_path.resolve()
+ self._tree_rename_is_new = True
+ parent = item.parent()
+ while parent is not None:
+ parent.setExpanded(True)
+ parent = parent.parent()
+ self.tree.setCurrentItem(item)
+ self.tree.scrollToItem(item)
+ self.status_label.setText(f"已新建:{self._display_path(new_path)},请输入文件名")
+ QTimer.singleShot(0, lambda target=item: self._start_new_file_rename(target))
+ return new_path
+
+ def _start_new_file_rename(self, item: QTreeWidgetItem) -> None:
+ if item is self._new_file_rename_item:
+ self.tree.editItem(item, 0)
+
+ def _retry_new_file_rename(self, item: QTreeWidgetItem, original_name: str) -> None:
+ with QSignalBlocker(self.tree):
+ item.setText(0, original_name)
+ QTimer.singleShot(0, lambda target=item: self._start_new_file_rename(target))
+
+ def _finish_new_file_rename(self, item: QTreeWidgetItem, column: int) -> None:
+ source_path = self._new_file_rename_path
+ is_new_file = self._tree_rename_is_new
+ if column != 0 or item is not self._new_file_rename_item or source_path is None:
+ return
+
+ entered_name = item.text(0).strip()
+ if not entered_name:
+ QMessageBox.warning(self, "名称无效", "文件名不能为空。")
+ self._retry_new_file_rename(item, source_path.name)
+ return
+ if Path(entered_name).name != entered_name or entered_name in {".", ".."}:
+ QMessageBox.warning(self, "名称无效", "文件名不能包含路径或目录分隔符。")
+ self._retry_new_file_rename(item, source_path.name)
+ return
+ if is_new_file and not entered_name.lower().endswith(".md"):
+ if Path(entered_name).suffix:
+ QMessageBox.warning(self, "名称无效", "新建文件目前仅支持 .md 格式。")
+ self._retry_new_file_rename(item, source_path.name)
+ return
+ entered_name += ".md"
+
+ target_path = source_path.with_name(entered_name)
+ if target_path != source_path and target_path.exists():
+ QMessageBox.warning(self, "文件已存在", f"同名文件已存在:\n{target_path.name}")
+ self._retry_new_file_rename(item, source_path.name)
+ return
+
+ try:
+ if target_path != source_path:
+ if not self._close_tab_indexes(self._tab_indexes_for_paths({source_path}), show_welcome=True):
+ self._new_file_rename_item = None
+ self._new_file_rename_path = None
+ self._tree_rename_is_new = False
+ self._refresh_document_entries(force=True)
+ self.status_label.setText("已取消重命名")
+ return
+ source_path.rename(target_path)
+ except OSError as exc:
+ LOGGER.exception("Failed to rename new Markdown file: %s -> %s", source_path, target_path)
+ QMessageBox.warning(self, "重命名失败", f"无法修改文件名:\n{target_path}\n\n{exc}")
+ self._retry_new_file_rename(item, source_path.name)
+ return
+
+ self._new_file_rename_item = None
+ self._new_file_rename_path = None
+ self._tree_rename_is_new = False
+ self._refresh_document_entries(force=True)
+ self.pending_directory_refresh = False
+ self._select_tree_item(target_path.resolve())
+ action_label = "已新建" if is_new_file else "已重命名"
+ self.status_label.setText(f"{action_label}:{self._display_path(target_path)}")
+
+ def _on_tree_name_editor_closed(self, editor: QWidget, hint: object) -> None:
+ if self._new_file_rename_item is not None:
+ QTimer.singleShot(0, self._finish_unchanged_new_file_rename)
+
+ def _finish_unchanged_new_file_rename(self) -> None:
+ item = self._new_file_rename_item
+ if item is not None:
+ self._finish_new_file_rename(item, 0)
+
+ def rename_tree_file(self, item: QTreeWidgetItem) -> bool:
+ data = item.data(0, Qt.ItemDataRole.UserRole)
+ if not data:
+ return False
+ path = Path(str(data)).resolve()
+ if not path.is_file() or not self._is_relative_to(path, self.project_root):
+ return False
+
+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
+ with QSignalBlocker(self.tree):
+ item.setText(0, path.name)
+ self._new_file_rename_item = item
+ self._new_file_rename_path = path
+ self._tree_rename_is_new = False
+ self.tree.setCurrentItem(item)
+ self.status_label.setText(f"正在重命名:{self._display_path(path)}")
+ QTimer.singleShot(0, lambda target=item: self._start_new_file_rename(target))
+ return True
+
def close_project_folder(self) -> None:
if not self._close_all_tabs(show_welcome=False):
return
+ self._startup_generation += 1
+ self._startup_scan_pending = False
self.has_project = False
self.project_root = self.app_root
self.renderer = MarkdownRenderer(self.project_root)
@@ -2378,6 +2573,8 @@ class MainWindow(QMainWindow):
if root_changed and not self._close_all_tabs(show_welcome=False):
return False
+ self._startup_generation += 1
+ self._startup_scan_pending = False
self.project_root = project_root
self.has_project = True
self.renderer = MarkdownRenderer(self.project_root)
@@ -2395,6 +2592,7 @@ class MainWindow(QMainWindow):
self._ensure_welcome_if_empty()
if save:
self.settings.setValue(LAST_PROJECT_ROOT_SETTING_KEY, str(self.project_root))
+ self._update_actions()
return True
def edit_current_markdown(self) -> None:
@@ -3002,6 +3200,11 @@ class MainWindow(QMainWindow):
def export_current_pdf(self) -> None:
if self.current_file is None:
return
+ settings_dialog = PdfExportSettingsDialog(self._saved_pdf_margins(), self)
+ if settings_dialog.exec() != QDialog.DialogCode.Accepted:
+ return
+ margins = settings_dialog.margins()
+
default_name = self.current_file.with_suffix(".pdf").name
file_name, _ = QFileDialog.getSaveFileName(
self,
@@ -3012,20 +3215,155 @@ class MainWindow(QMainWindow):
if not file_name:
return
- output_path = self.export_pdf_to_path(Path(file_name))
+ self._save_pdf_margins(margins)
+ output_path = self.export_pdf_to_path(Path(file_name), margins)
if output_path is None:
return
LOGGER.info("Exporting PDF: %s", output_path)
self.status_label.setText(f"正在导出 PDF:{output_path}")
- def export_pdf_to_path(self, output_path: Path) -> Path | None:
+ def export_pdf_to_path(self, output_path: Path, margins: PdfMargins | None = None) -> Path | None:
if self.current_file is None:
return None
+ if getattr(self, "_pdf_export_page", None) is not None:
+ QMessageBox.information(self, "正在导出", "已有一个 PDF 导出任务正在进行,请稍候。")
+ return None
if output_path.suffix.lower() != ".pdf":
output_path = output_path.with_suffix(".pdf")
- self.web_view.page().printToPdf(str(output_path))
+
+ selected_margins = margins or self._saved_pdf_margins()
+ if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file):
+ try:
+ content = self._render_document_file(self.current_file)
+ headings = self._pdf_headings(self.current_file)
+ except (OSError, UnicodeDecodeError) as exc:
+ LOGGER.exception("Failed to render PDF export: %s", self.current_file)
+ QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}")
+ return None
+ self._begin_pdf_export(output_path, content, headings, selected_margins)
+ else:
+ self.web_view.page().toHtml(
+ lambda content, target=output_path, selected=selected_margins: self._begin_pdf_export(
+ target,
+ content,
+ [],
+ selected,
+ )
+ )
return output_path
+ def _saved_pdf_margins(self) -> PdfMargins:
+ def setting(name: str) -> float:
+ try:
+ return max(0.0, min(50.0, float(self.settings.value(f"pdf/{name}_margin_mm", 15.0))))
+ except (TypeError, ValueError):
+ return 15.0
+
+ return PdfMargins(
+ top=setting("top"),
+ bottom=setting("bottom"),
+ left=setting("left"),
+ right=setting("right"),
+ )
+
+ def _save_pdf_margins(self, margins: PdfMargins) -> None:
+ self.settings.setValue("pdf/top_margin_mm", margins.top)
+ self.settings.setValue("pdf/bottom_margin_mm", margins.bottom)
+ self.settings.setValue("pdf/left_margin_mm", margins.left)
+ self.settings.setValue("pdf/right_margin_mm", margins.right)
+
+ def _pdf_headings(self, path: Path) -> list[Heading]:
+ if is_code_document(path):
+ return extract_code_headings(path, self._read_text_preview(path))
+ return extract_headings(path)
+
+ def _begin_pdf_export(
+ self,
+ output_path: Path,
+ content: str,
+ headings: list[Heading],
+ margins: PdfMargins,
+ ) -> None:
+ printable_headings = [heading for heading in headings if heading.level <= 3]
+ self._pdf_export_output_path = output_path
+ self._pdf_export_base_html = content
+ self._pdf_export_headings = printable_headings
+ self._pdf_export_layout = build_pdf_page_layout(margins)
+ self._pdf_export_stage = "probe"
+
+ page = QWebEnginePage(self)
+ self._pdf_export_page = page
+ self._configure_web_settings(page.settings())
+ page.loadFinished.connect(self._on_pdf_export_page_loaded)
+ page.pdfPrintingFinished.connect(self._on_dedicated_pdf_printing_finished)
+ base_path = str(self.current_file.parent.resolve()) + os.sep if self.current_file is not None else str(self.project_root) + os.sep
+ self._pdf_export_base_url = QUrl.fromLocalFile(base_path)
+ page.setHtml(
+ build_pdf_export_html(content, printable_headings),
+ self._pdf_export_base_url,
+ )
+ self.status_label.setText(f"正在生成 PDF 目录页码:{output_path}")
+
+ def _on_pdf_export_page_loaded(self, ok: bool) -> None:
+ if not ok:
+ self._fail_pdf_export("PDF 导出页面加载失败。")
+ return
+ stage = getattr(self, "_pdf_export_stage", "")
+ QTimer.singleShot(800, lambda expected=stage: self._print_pdf_export_stage(expected))
+
+ def _print_pdf_export_stage(self, expected_stage: str) -> None:
+ page = getattr(self, "_pdf_export_page", None)
+ if page is None or expected_stage != getattr(self, "_pdf_export_stage", ""):
+ return
+ if expected_stage == "probe":
+ page.printToPdf(self._on_pdf_probe_ready, self._pdf_export_layout)
+ elif expected_stage == "final":
+ page.printToPdf(str(self._pdf_export_output_path), self._pdf_export_layout)
+
+ def _on_pdf_probe_ready(self, pdf_data: object) -> None:
+ page = getattr(self, "_pdf_export_page", None)
+ if page is None or getattr(self, "_pdf_export_stage", "") != "probe":
+ return
+ raw_pdf = bytes(pdf_data)
+ if not raw_pdf:
+ self._fail_pdf_export("无法生成 PDF 页码预览。")
+ return
+ try:
+ page_numbers = extract_heading_page_numbers(raw_pdf, len(self._pdf_export_headings))
+ except Exception as exc:
+ LOGGER.exception("Failed to extract PDF heading pages")
+ self._fail_pdf_export(str(exc))
+ return
+
+ self._pdf_export_stage = "final"
+ page.setHtml(
+ build_pdf_export_html(
+ self._pdf_export_base_html,
+ self._pdf_export_headings,
+ page_numbers,
+ include_page_markers=False,
+ ),
+ self._pdf_export_base_url,
+ )
+ self.status_label.setText(f"正在导出 PDF:{self._pdf_export_output_path}")
+
+ def _on_dedicated_pdf_printing_finished(self, file_path: str, success: bool) -> None:
+ self._on_pdf_printing_finished(file_path, success)
+ self._cleanup_pdf_export()
+
+ def _fail_pdf_export(self, message: str) -> None:
+ output_path = getattr(self, "_pdf_export_output_path", Path(""))
+ LOGGER.error("PDF export failed: %s (%s)", output_path, message)
+ QMessageBox.warning(self, "导出失败", f"无法导出 PDF:\n{output_path}\n\n{message}")
+ self._cleanup_pdf_export()
+
+ def _cleanup_pdf_export(self) -> None:
+ page = getattr(self, "_pdf_export_page", None)
+ if page is not None:
+ page.deleteLater()
+ self._pdf_export_page = None
+ self._pdf_export_stage = ""
+
def export_current_html(self) -> None:
if self.current_file is None:
return
@@ -3044,19 +3382,9 @@ class MainWindow(QMainWindow):
if output_path.suffix.lower() not in {".html", ".htm"}:
output_path = output_path.with_suffix(".html")
- if self.current_file.suffix.lower() in {".md", ".markdown"}:
+ if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file):
try:
- content = self.renderer.render_file(
- self.current_file,
- theme=self.theme,
- font_scale=self.font_scale,
- wheel_scroll_speed=self.wheel_scroll_speed,
- document_width_scale=self.reader_width_scale,
- document_font_family=self.document_font_family,
- document_font_size=self.document_font_size,
- document_style_css=self._document_style_css(),
- math_engine=self.math_engine,
- )
+ content = self._render_document_file(self.current_file)
except (OSError, UnicodeDecodeError) as exc:
LOGGER.exception("Failed to render HTML export: %s", self.current_file)
QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}")
@@ -3145,19 +3473,9 @@ class MainWindow(QMainWindow):
return None
if output_path.suffix.lower() not in {".mhtml", ".mht"}:
output_path = output_path.with_suffix(".mhtml")
- if self.current_file.suffix.lower() in {".md", ".markdown"}:
+ if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file):
try:
- content = self.renderer.render_file(
- self.current_file,
- theme=self.theme,
- font_scale=self.font_scale,
- wheel_scroll_speed=self.wheel_scroll_speed,
- document_width_scale=self.reader_width_scale,
- document_font_family=self.document_font_family,
- document_font_size=self.document_font_size,
- document_style_css=self._document_style_css(),
- math_engine=self.math_engine,
- )
+ content = self._render_document_file(self.current_file)
except (OSError, UnicodeDecodeError) as exc:
LOGGER.exception("Failed to render MHTML export: %s", self.current_file)
QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}")
@@ -3275,9 +3593,6 @@ class MainWindow(QMainWindow):
"font_scale": self.font_scale,
"wheel_scroll_speed": self.wheel_scroll_speed,
"reader_width_scale": self.reader_width_scale,
- "reader_embedded_toc": self.reader_embedded_toc,
- "reader_external_toc": self.reader_external_toc,
- "reader_embedded_progress": self.reader_embedded_progress,
"ui_font_family": self.ui_font_family,
"ui_font_point_size": self.ui_font_point_size,
"document_font_family": self.document_font_family,
@@ -3327,9 +3642,6 @@ class MainWindow(QMainWindow):
self.reader_width_scale = self._normalized_reader_width_scale(
reader.get("reader_width_scale", self.reader_width_scale)
)
- self.reader_embedded_toc = bool(reader.get("reader_embedded_toc", self.reader_embedded_toc))
- self.reader_external_toc = bool(reader.get("reader_external_toc", self.reader_external_toc)) and not self.reader_embedded_toc
- self.reader_embedded_progress = bool(reader.get("reader_embedded_progress", self.reader_embedded_progress))
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
try:
self.document_font_size = max(12, min(28, int(reader.get("document_font_size", self.document_font_size))))
@@ -3489,8 +3801,6 @@ class MainWindow(QMainWindow):
document_font_size=self.document_font_size,
document_style_css=self._document_style_css(),
math_engine=self.math_engine,
- include_reader_toc=self.reader_embedded_toc,
- include_reader_progress=self.reader_embedded_progress,
)
return self.renderer.render_file(
@@ -3503,8 +3813,6 @@ class MainWindow(QMainWindow):
document_font_size=self.document_font_size,
document_style_css=self._document_style_css(),
math_engine=self.math_engine,
- include_reader_toc=self.reader_embedded_toc,
- include_reader_progress=self.reader_embedded_progress,
)
def refresh_project_view(self) -> None:
@@ -3567,8 +3875,8 @@ class MainWindow(QMainWindow):
if widget is None:
return
- if bool(widget.property("is_welcome")) and isinstance(widget, ReaderView):
- widget.setHtml(self._welcome_html(), QUrl.fromLocalFile(str(self.app_root) + os.sep))
+ if bool(widget.property("is_welcome")) and isinstance(widget, QTextBrowser):
+ self._render_welcome(widget)
return
if isinstance(widget, RichMarkdownEditorDialog):
@@ -3652,7 +3960,6 @@ class MainWindow(QMainWindow):
self._set_theme_color("white" if self.theme == "dark" else "black")
self._update_theme_menu_state()
self._apply_navigation_style()
- self._apply_reader_navigation_visibility()
self._save_preferences()
self.refresh_all_tab_appearances()
@@ -3660,7 +3967,6 @@ class MainWindow(QMainWindow):
self._set_theme_color(str(action.data() or "colorful"))
self._update_theme_menu_state()
self._apply_navigation_style()
- self._apply_reader_navigation_visibility()
self._save_preferences()
self.refresh_all_tab_appearances()
@@ -3672,7 +3978,6 @@ class MainWindow(QMainWindow):
self.theme_background = background
self._update_theme_menu_state()
self._apply_navigation_style()
- self._apply_reader_navigation_visibility()
self._save_preferences()
self.refresh_all_tab_appearances()
@@ -3852,7 +4157,6 @@ class MainWindow(QMainWindow):
self.ui_font_point_size = font.pointSize()
self._apply_ui_font()
self._apply_navigation_style()
- self._apply_reader_navigation_visibility()
self._save_preferences()
def choose_document_font(self) -> None:
@@ -3940,9 +4244,6 @@ class MainWindow(QMainWindow):
font_scale=self.font_scale,
wheel_scroll_speed=self.wheel_scroll_speed,
reader_width_scale=self.reader_width_scale,
- reader_embedded_toc=self.reader_embedded_toc,
- reader_external_toc=self.reader_external_toc,
- reader_embedded_progress=self.reader_embedded_progress,
auto_refresh=self.auto_refresh_enabled,
auto_refresh_mode=self.auto_refresh_mode,
auto_refresh_delay_ms=self.auto_refresh_delay_ms,
@@ -3963,19 +4264,11 @@ class MainWindow(QMainWindow):
font_changed = abs(preferences.font_scale - self.font_scale) > 0.001
wheel_changed = abs(preferences.wheel_scroll_speed - self.wheel_scroll_speed) > 0.001
width_changed = abs(preferences.reader_width_scale - self.reader_width_scale) > 0.001
- navigation_changed = (
- preferences.reader_embedded_toc != self.reader_embedded_toc
- or preferences.reader_external_toc != self.reader_external_toc
- or preferences.reader_embedded_progress != self.reader_embedded_progress
- )
self._set_theme_color(preferences.theme_color)
self.theme_background = self._normalized_theme_background(preferences.theme_background)
self.font_scale = preferences.font_scale
self.wheel_scroll_speed = self._normalized_wheel_scroll_speed(preferences.wheel_scroll_speed)
self.reader_width_scale = self._normalized_reader_width_scale(preferences.reader_width_scale)
- self.reader_embedded_toc = preferences.reader_embedded_toc
- self.reader_external_toc = preferences.reader_external_toc and not self.reader_embedded_toc
- self.reader_embedded_progress = preferences.reader_embedded_progress
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
self.auto_refresh_enabled = preferences.auto_refresh
self.auto_refresh_mode = preferences.auto_refresh_mode
@@ -3988,12 +4281,11 @@ class MainWindow(QMainWindow):
self._apply_auto_refresh_timing()
self._update_theme_menu_state()
self._apply_navigation_style()
- self._apply_reader_navigation_visibility()
self._save_preferences()
if wheel_changed:
self._apply_wheel_scroll_speed_to_tabs()
- if theme_changed or font_changed or width_changed or navigation_changed:
+ if theme_changed or font_changed or width_changed:
self.refresh_document()
LOGGER.info("Updated preferences: %s", preferences)
@@ -4167,7 +4459,52 @@ class MainWindow(QMainWindow):
return False
def _show_tree_context_menu(self, position: QPoint) -> None:
+ menu = self._build_tree_context_menu(position)
+ menu.exec(self.tree.viewport().mapToGlobal(position))
+
+ def _build_tree_context_menu(self, position: QPoint) -> QMenu:
menu = QMenu(self)
+ target_item = self.tree.itemAt(position)
+ if target_item is None:
+ self.tree.clearSelection()
+ elif target_item.data(0, Qt.ItemDataRole.UserRole) is None:
+ self.tree.clearSelection()
+ target_item.setSelected(True)
+ self.tree.setCurrentItem(target_item)
+ elif not target_item.isSelected():
+ self.tree.clearSelection()
+ target_item.setSelected(True)
+ self.tree.setCurrentItem(target_item)
+
+ new_file_action = QAction("新建文件", menu)
+ new_file_action.setEnabled(self.has_project)
+ new_file_target = target_item
+ if new_file_target is None and self.tree.topLevelItemCount():
+ new_file_target = self.tree.topLevelItem(0)
+ new_file_action.triggered.connect(
+ lambda checked=False, item=new_file_target: self.create_new_markdown_file(item)
+ )
+ menu.addAction(new_file_action)
+
+ target_data = target_item.data(0, Qt.ItemDataRole.UserRole) if target_item is not None else None
+ selected_files = self._selected_tree_file_paths()
+ if target_data and len(selected_files) == 1:
+ rename_action = QAction("重命名", menu)
+ rename_action.triggered.connect(lambda checked=False, item=target_item: self.rename_tree_file(item))
+ menu.addAction(rename_action)
+ if target_data and selected_files:
+ delete_action = QAction("删除", menu)
+ delete_action.triggered.connect(lambda checked=False: self.delete_selected_tree_files())
+ menu.addAction(delete_action)
+ elif target_item is not None and target_data is None:
+ folder_path = self._tree_folder_path(target_item)
+ if folder_path is not None and folder_path != self.project_root.resolve():
+ delete_folder_action = QAction("删除文件夹", menu)
+ delete_folder_action.triggered.connect(
+ lambda checked=False, path=folder_path: self.delete_tree_folder(path)
+ )
+ menu.addAction(delete_folder_action)
+ menu.addSeparator()
label_group = QActionGroup(menu)
label_group.setExclusive(True)
@@ -4185,7 +4522,157 @@ class MainWindow(QMainWindow):
label_group.addAction(filename_action)
menu.addAction(filename_action)
- menu.exec(self.tree.viewport().mapToGlobal(position))
+ return menu
+
+ def _tree_folder_path(self, item: QTreeWidgetItem) -> Path | None:
+ if item.data(0, Qt.ItemDataRole.UserRole) is not None:
+ return None
+ tooltip = item.toolTip(0)
+ if not tooltip:
+ return None
+ path = Path(tooltip).resolve()
+ if path.is_dir() and self._is_relative_to(path, self.project_root):
+ return path
+ return None
+
+ def _selected_tree_file_paths(self) -> list[Path]:
+ selected_paths: set[Path] = set()
+ for item in self.tree.selectedItems():
+ data = item.data(0, Qt.ItemDataRole.UserRole)
+ if not data:
+ continue
+ path = Path(str(data)).resolve()
+ if path.is_file() and self._is_relative_to(path, self.project_root):
+ selected_paths.add(path)
+ return sorted(selected_paths, key=lambda path: str(path).casefold())
+
+ def _tab_indexes_for_paths(self, paths: set[Path]) -> list[int]:
+ indexes: list[int] = []
+ for index in range(self.tabs.count()):
+ widget = self.tabs.widget(index)
+ file_value = widget.property("current_file") if widget is not None else None
+ if not file_value:
+ continue
+ try:
+ tab_path = Path(str(file_value)).resolve()
+ except OSError:
+ continue
+ if tab_path in paths:
+ indexes.append(index)
+ return indexes
+
+ def _move_file_to_trash(self, path: Path) -> bool:
+ return bool(QFile.moveToTrash(str(path)))
+
+ def _open_tab_paths_within(self, directory: Path) -> set[Path]:
+ paths: set[Path] = set()
+ for index in range(self.tabs.count()):
+ widget = self.tabs.widget(index)
+ file_value = widget.property("current_file") if widget is not None else None
+ if not file_value:
+ continue
+ try:
+ path = Path(str(file_value)).resolve()
+ except OSError:
+ continue
+ if self._is_relative_to(path, directory):
+ paths.add(path)
+ return paths
+
+ def delete_tree_folder(self, folder_path: Path) -> bool:
+ folder_path = folder_path.resolve()
+ if (
+ not self.has_project
+ or folder_path == self.project_root.resolve()
+ or not folder_path.is_dir()
+ or not self._is_relative_to(folder_path, self.project_root)
+ ):
+ return False
+
+ choice = QMessageBox.question(
+ self,
+ "删除文件夹",
+ f"确定将此文件夹及其中的全部内容移入回收站吗?\n\n{self._display_path(folder_path)}",
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
+ QMessageBox.StandardButton.No,
+ )
+ if choice != QMessageBox.StandardButton.Yes:
+ return False
+
+ contained_paths = self._open_tab_paths_within(folder_path)
+ if not self._close_tab_indexes(self._tab_indexes_for_paths(contained_paths), show_welcome=True):
+ self.status_label.setText("已取消删除文件夹")
+ return False
+
+ try:
+ deleted = self._move_file_to_trash(folder_path)
+ except OSError:
+ LOGGER.exception("Failed to move folder to trash: %s", folder_path)
+ deleted = False
+ if not deleted:
+ QMessageBox.warning(self, "删除失败", f"无法将文件夹移入回收站:\n{folder_path}")
+ return False
+
+ for path in contained_paths:
+ self._clear_editor_draft(path)
+ self.pending_directory_refresh = False
+ self._refresh_document_entries(force=True)
+ self.status_label.setText(f"已移入回收站:{self._display_path(folder_path)}")
+ return True
+
+ def delete_selected_tree_files(self) -> bool:
+ paths = self._selected_tree_file_paths()
+ if not paths:
+ return False
+
+ displayed_paths = [self._display_path(path) for path in paths]
+ preview = "\n".join(f"• {path}" for path in displayed_paths[:12])
+ if len(displayed_paths) > 12:
+ preview += f"\n• ……另有 {len(displayed_paths) - 12} 个文件"
+ prompt = (
+ f"确定将选中的 {len(paths)} 个文件移入回收站吗?\n\n{preview}"
+ if len(paths) > 1
+ else f"确定将此文件移入回收站吗?\n\n{preview}"
+ )
+ choice = QMessageBox.question(
+ self,
+ "删除文件",
+ prompt,
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
+ QMessageBox.StandardButton.No,
+ )
+ if choice != QMessageBox.StandardButton.Yes:
+ return False
+
+ path_set = set(paths)
+ if not self._close_tab_indexes(self._tab_indexes_for_paths(path_set), show_welcome=True):
+ self.status_label.setText("已取消删除")
+ return False
+
+ deleted: list[Path] = []
+ failed: list[Path] = []
+ for path in paths:
+ try:
+ if self._move_file_to_trash(path):
+ deleted.append(path)
+ self._clear_editor_draft(path)
+ else:
+ failed.append(path)
+ except OSError:
+ LOGGER.exception("Failed to move file to trash: %s", path)
+ failed.append(path)
+
+ self.pending_directory_refresh = False
+ self._refresh_document_entries(force=True)
+ if failed:
+ failure_list = "\n".join(self._display_path(path) for path in failed[:12])
+ QMessageBox.warning(
+ self,
+ "部分文件删除失败",
+ f"已移入回收站:{len(deleted)} 个\n删除失败:{len(failed)} 个\n\n{failure_list}",
+ )
+ self.status_label.setText(f"已移入回收站:{len(deleted)} 个文件")
+ return bool(deleted) and not failed
def set_document_tree_label_mode(self, mode: str) -> None:
if mode not in {"title", "filename"} or mode == self.document_tree_label_mode:
@@ -4267,22 +4754,12 @@ class MainWindow(QMainWindow):
self._scroll_to_position(self.pending_scroll_y)
self.pending_scroll_y = None
- def _on_reader_scroll_changed(self, progress: float, heading_id: str, scroll_y: int) -> None:
- sender_bridge = self.sender()
- current = self.tabs.currentWidget()
- if not isinstance(current, ReaderView) or getattr(current, "reader_bridge", None) is not sender_bridge:
- return
-
- current.setProperty("scroll_y", max(0, int(scroll_y)))
- if not self.reader_embedded_progress:
- self.reading_progress.setValue(max(0, min(100, int(round(progress)))))
- if self.reader_external_toc and not self.reader_embedded_toc:
- self._schedule_toc_highlight(heading_id)
-
def _update_actions(self) -> None:
history = self._current_history()
self.back_action.setEnabled(history.can_go_back)
self.forward_action.setEnabled(history.can_go_forward)
+ if hasattr(self, "new_file_action"):
+ self.new_file_action.setEnabled(self.has_project)
if hasattr(self, "edit_current_action"):
can_edit = self.current_file is not None and self.current_file.suffix.lower() in {".md", ".markdown"}
self.edit_current_action.setEnabled(can_edit)
@@ -4330,16 +4807,12 @@ class MainWindow(QMainWindow):
def _populate_toc_items(self, headings: list[Heading]) -> None:
self.toc_tree.clear()
- self.toc_items_by_slug = {}
- self.pending_toc_heading_id = ""
- self.last_toc_heading_id = ""
stack: list[tuple[int, QTreeWidgetItem]] = []
for heading in headings:
item = QTreeWidgetItem([heading.title])
item.setData(0, Qt.ItemDataRole.UserRole, heading.slug)
item.setToolTip(0, f"#{heading.slug}")
- self.toc_items_by_slug[heading.slug] = item
while stack and stack[-1][0] >= heading.level:
stack.pop()
@@ -4353,37 +4826,6 @@ class MainWindow(QMainWindow):
self.toc_tree.expandAll()
- def _schedule_toc_highlight(self, heading_id: str) -> None:
- if not heading_id or heading_id == self.last_toc_heading_id:
- return
- self.pending_toc_heading_id = heading_id
- if hasattr(self, "toc_highlight_timer") and not self.toc_highlight_timer.isActive():
- self.toc_highlight_timer.start()
- elif not hasattr(self, "toc_highlight_timer"):
- self._highlight_toc_heading(heading_id)
-
- def _apply_pending_toc_highlight(self) -> None:
- heading_id = self.pending_toc_heading_id
- self.pending_toc_heading_id = ""
- if heading_id:
- self._highlight_toc_heading(heading_id)
-
- def _highlight_toc_heading(self, heading_id: str) -> None:
- if not heading_id or heading_id == self.last_toc_heading_id:
- return
-
- item = self.toc_items_by_slug.get(heading_id)
- if item is None or item.treeWidget() is not self.toc_tree:
- matches = self.toc_tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive)
- item = next((match for match in matches if match.data(0, Qt.ItemDataRole.UserRole) == heading_id), None)
- if item is not None:
- self.toc_items_by_slug[heading_id] = item
- if item is None:
- return
- if self.toc_tree.currentItem() is not item:
- self.toc_tree.setCurrentItem(item)
- self.last_toc_heading_id = heading_id
-
def _open_toc_item(self, item: QTreeWidgetItem) -> None:
slug = item.data(0, Qt.ItemDataRole.UserRole)
if slug:
@@ -4515,9 +4957,6 @@ class MainWindow(QMainWindow):
self.reader_width_scale = self._normalized_reader_width_scale(
self.settings.value("reader/width_scale", 1.0)
)
- self.reader_embedded_toc = self.settings.value("reader/embedded_toc", True, type=bool)
- self.reader_external_toc = self.settings.value("reader/external_toc", False, type=bool) and not self.reader_embedded_toc
- self.reader_embedded_progress = self.settings.value("reader/embedded_progress", True, type=bool)
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
try:
self.document_font_size = max(12, min(28, int(self.settings.value("reader/document_font_size", self.document_font_size))))
@@ -4599,7 +5038,7 @@ class MainWindow(QMainWindow):
self.pending_directory_refresh = False
return
if hasattr(self, "directory_poll_timer"):
- if self.has_project and self._auto_refresh_allows("directory"):
+ if self.has_project and not self._startup_scan_pending and self._auto_refresh_allows("directory"):
self.directory_poll_timer.start()
else:
self.directory_poll_timer.stop()
@@ -4612,9 +5051,9 @@ class MainWindow(QMainWindow):
self.settings.setValue("reader/font_scale", self.font_scale)
self.settings.setValue("reader/wheel_scroll_speed", self.wheel_scroll_speed)
self.settings.setValue("reader/width_scale", self.reader_width_scale)
- self.settings.setValue("reader/embedded_toc", self.reader_embedded_toc)
- self.settings.setValue("reader/external_toc", self.reader_external_toc)
- self.settings.setValue("reader/embedded_progress", self.reader_embedded_progress)
+ self.settings.remove("reader/embedded_toc")
+ self.settings.remove("reader/external_toc")
+ self.settings.remove("reader/embedded_progress")
self.settings.setValue("reader/ui_font_family", self.ui_font_family)
self.settings.setValue("reader/ui_font_point_size", self.ui_font_point_size)
self.settings.setValue("reader/document_font_family", self.document_font_family)
@@ -4681,7 +5120,8 @@ class MainWindow(QMainWindow):
def _save_current_scroll_position(self) -> None:
if self.current_file is None:
return
- if not isinstance(self.tabs.currentWidget(), ReaderView):
+ current_view = self.tabs.currentWidget()
+ if not isinstance(current_view, ReaderView):
return
path_key = str(self.current_file)
@@ -4691,8 +5131,10 @@ class MainWindow(QMainWindow):
except (TypeError, ValueError):
position = 0
self.scroll_positions[path_key] = max(0, position)
+ if current_view is self.tabs.currentWidget():
+ current_view.setProperty("scroll_y", max(0, position))
- self.web_view.page().runJavaScript("Math.max(0, window.scrollY || 0)", store_scroll)
+ current_view.page().runJavaScript("Math.max(0, window.scrollY || 0)", store_scroll)
def _scroll_to_position(self, scroll_y: int) -> None:
script = f"(() => {{ window.scrollTo({{top: {max(0, scroll_y)}, behavior: 'instant'}}); }})();"
@@ -4753,8 +5195,12 @@ class MainWindow(QMainWindow):
self.file_watcher.addPaths(dir_paths)
def _poll_directory_changes(self) -> None:
+ if self._startup_scan_pending:
+ return
if not self.has_project or not self._auto_refresh_allows("directory"):
return
+ if self._new_file_rename_item is not None:
+ return
signature = document_directory_signature(self.project_root, self.document_file_groups)
if signature == self.document_directory_signature:
return
@@ -4908,6 +5354,8 @@ class MainWindow(QMainWindow):
def _on_watched_directory_changed(self, changed_path: str) -> None:
if not self.auto_refresh_enabled or self.auto_refresh_mode == "off" or not self.has_project:
return
+ if self._new_file_rename_item is not None:
+ return
changed = Path(changed_path).resolve()
docs_dir = (self.project_root / "docs").resolve()
if self._auto_refresh_allows("directory") and changed in {self.project_root, docs_dir}:
@@ -4964,6 +5412,12 @@ class MainWindow(QMainWindow):
self._update_watched_paths()
def _refresh_document_entries(self, force: bool = False, directory_signature: tuple[tuple[str, int, int], ...] | None = None) -> None:
+ if self._startup_scan_pending:
+ if not force:
+ return
+ self._startup_generation += 1
+ self._startup_scan_pending = False
+ self._apply_auto_refresh_timing()
if not self.has_project:
return
previous_current = self.current_file
@@ -4993,6 +5447,8 @@ class MainWindow(QMainWindow):
self._update_watched_paths()
def closeEvent(self, event: QCloseEvent) -> None:
+ self._startup_generation += 1
+ self._startup_scan_pending = False
self._save_current_scroll_position()
self._save_preferences()
super().closeEvent(event)
diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py
index 683a62c..91d1ee7 100644
--- a/mdhelper/markdown_editor.py
+++ b/mdhelper/markdown_editor.py
@@ -6,7 +6,7 @@ import re
from pathlib import Path
from typing import Callable
-from PySide6.QtCore import QObject, QRect, QSize, QTimer, QUrl, Qt, Signal, Slot
+from PySide6.QtCore import QRect, QSize, QTimer, QUrl, Qt, Signal
from PySide6.QtGui import (
QAction,
QColor,
@@ -19,7 +19,6 @@ from PySide6.QtGui import (
QTextDocument,
QTextFormat,
)
-from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineCore import QWebEngineSettings
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import (
@@ -49,6 +48,12 @@ from .markdown_utils import slugify_heading
MAX_SYNTAX_HIGHLIGHT_CHARS = 1_000_000
+def convert_latex_display_delimiters(source: str) -> tuple[str, int]:
+ """Convert LaTeX display-math delimiters to Markdown ``$$`` delimiters."""
+ replacement_count = source.count("\\[") + source.count("\\]")
+ return source.replace("\\[", "$$").replace("\\]", "$$"), replacement_count
+
+
class LineNumberArea(QWidget):
def __init__(self, editor: "MarkdownSourceEditor") -> None:
super().__init__(editor)
@@ -228,12 +233,6 @@ class MarkdownSyntaxHighlighter(QSyntaxHighlighter):
-class MarkdownPreviewBridge(QObject):
- heading_requested = Signal(str)
-
- @Slot(str)
- def openHeading(self, slug: str) -> None:
- self.heading_requested.emit(str(slug))
class MarkdownEditorDialog(QDialog):
save_requested = Signal(object, str, object)
close_requested = Signal()
@@ -271,7 +270,6 @@ class MarkdownEditorDialog(QDialog):
self.document_width_scale = document_width_scale
self.document_style_css = document_style_css
self.math_engine = math_engine
- self.preview_embedded_toc = True
self.file_signature = file_signature
self.draft_callback = draft_callback
self._preview_dirty = True
@@ -366,11 +364,6 @@ class MarkdownEditorDialog(QDialog):
self.splitter.addWidget(self.editor)
self.preview = QWebEngineView()
- self.preview_bridge = MarkdownPreviewBridge(self)
- self.preview_bridge.heading_requested.connect(self._open_preview_heading_in_source)
- self.preview_channel = QWebChannel(self.preview)
- self.preview_channel.registerObject("mdhelperPreviewBridge", self.preview_bridge)
- self.preview.page().setWebChannel(self.preview_channel)
self.preview.loadFinished.connect(self._restore_preview_scroll)
self._configure_preview_settings(self.preview.settings())
self.splitter.addWidget(self.preview)
@@ -501,6 +494,11 @@ class MarkdownEditorDialog(QDialog):
action.triggered.connect(lambda checked=False, item=template: self.insert_template(item))
self.insert_toolbar.addAction(action)
+ self.convert_latex_formula_action = QAction("转换latex公式到md", self)
+ self.convert_latex_formula_action.setToolTip("将文档中的 \\[ 和 \\] 转换为 $$")
+ self.convert_latex_formula_action.triggered.connect(self.convert_latex_formulas_to_markdown)
+ self.insert_toolbar.addAction(self.convert_latex_formula_action)
+
def insert_template(self, template: str) -> None:
cursor = self.editor.textCursor()
selection = cursor.selectedText().replace("\u2029", "\n")
@@ -509,6 +507,32 @@ class MarkdownEditorDialog(QDialog):
self.editor.setTextCursor(cursor)
self.editor.setFocus()
+ def convert_latex_formulas_to_markdown(self) -> int:
+ converted_source, replacement_count = convert_latex_display_delimiters(self.source_text())
+ if replacement_count == 0:
+ self.editor.setFocus()
+ return 0
+
+ current_cursor = self.editor.textCursor()
+ anchor = current_cursor.anchor()
+ position = current_cursor.position()
+
+ document_cursor = QTextCursor(self.editor.document())
+ document_cursor.beginEditBlock()
+ document_cursor.select(QTextCursor.SelectionType.Document)
+ document_cursor.insertText(converted_source)
+ document_cursor.endEditBlock()
+
+ restored_cursor = self.editor.textCursor()
+ restored_cursor.setPosition(anchor)
+ restored_cursor.setPosition(
+ position,
+ QTextCursor.MoveMode.KeepAnchor if position != anchor else QTextCursor.MoveMode.MoveAnchor,
+ )
+ self.editor.setTextCursor(restored_cursor)
+ self.editor.setFocus()
+ return replacement_count
+
def scroll_to_heading(self, slug: str) -> bool:
target_line = self._heading_line_for_slug(slug)
if target_line is None:
@@ -554,9 +578,6 @@ class MarkdownEditorDialog(QDialog):
return None
- def _open_preview_heading_in_source(self, slug: str) -> None:
- if self.scroll_to_heading(str(slug)) and hasattr(self, "find_status_label"):
- self.find_status_label.setText(f"已定位标题:#{slug}")
def _scroll_preview_to_heading(self, slug: str) -> None:
if not isValid(self) or not isValid(self.preview):
return
@@ -752,8 +773,6 @@ class MarkdownEditorDialog(QDialog):
document_width_scale=self.document_width_scale,
document_style_css=self.document_style_css,
math_engine=self.math_engine,
- include_reader_toc=self.preview_embedded_toc,
- include_reader_progress=False,
)
base_path = str(self.save_target_path.parent.resolve()) + os.sep
self.preview.setHtml(html_content, QUrl.fromLocalFile(base_path))
diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py
index 6e6f2f8..2960186 100644
--- a/mdhelper/markdown_renderer.py
+++ b/mdhelper/markdown_renderer.py
@@ -2,11 +2,14 @@ from __future__ import annotations
import html
import re
+from functools import lru_cache
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlsplit
from markdown_it import MarkdownIt
+from markdown_it.rules_block.state_block import StateBlock
+from markdown_it.rules_inline.state_inline import StateInline
from markdown_it.token import Token
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
@@ -14,11 +17,21 @@ from pygments.lexers import get_lexer_by_name
from pygments.lexers.special import TextLexer
from pygments.util import ClassNotFound
-from .code_structure import extract_code_headings
-from .markdown_utils import Heading, slugify_heading
+from .markdown_utils import slugify_heading
from .media import is_qt_video_player_url, media_kind, media_mime_type
+@lru_cache(maxsize=16)
+def _resource_text(path: Path, modified_ns: int, size: int) -> str:
+ """Share static resources across tabs, invalidating on development edits."""
+ return path.read_text(encoding="utf-8")
+
+
+@lru_cache(maxsize=1)
+def _highlight_css() -> str:
+ return HtmlFormatter().get_style_defs(".highlight")
+
+
class MarkdownRenderer:
def __init__(self, project_root: Path) -> None:
self.project_root = project_root
@@ -35,8 +48,17 @@ class MarkdownRenderer:
self.markdown.renderer.rules["fence"] = self._render_fence
self.markdown.renderer.rules["code_block"] = self._render_code_block
+ self.markdown.renderer.rules["math_block"] = self._render_math_block
+ self.markdown.renderer.rules["math_inline"] = self._render_math_inline
self.markdown.renderer.rules["image"] = self._render_image
self.markdown.renderer.rules["link_open"] = self._render_link_open
+ self.markdown.block.ruler.before(
+ "fence",
+ "mdhelper_math_block",
+ self._parse_math_block,
+ {"alt": ["paragraph", "reference", "blockquote", "list"]},
+ )
+ self.markdown.inline.ruler.before("escape", "mdhelper_math_inline", self._parse_math_inline)
self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids)
self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions)
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
@@ -52,13 +74,10 @@ class MarkdownRenderer:
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
- include_reader_toc: bool = False,
- include_reader_progress: bool = False,
) -> str:
source = markdown_path.read_text(encoding="utf-8")
env: dict[str, Any] = {"path": str(markdown_path), "headings": []}
body = self.markdown.render(source, env)
- headings = self._env_headings(env)
return self._wrap_html(
body=body,
title=markdown_path.name,
@@ -70,9 +89,6 @@ class MarkdownRenderer:
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
- headings=headings,
- include_reader_toc=include_reader_toc,
- include_reader_progress=include_reader_progress,
)
def render_source(
@@ -87,12 +103,9 @@ class MarkdownRenderer:
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
- include_reader_toc: bool = False,
- include_reader_progress: bool = False,
) -> str:
env: dict[str, Any] = {"path": str(markdown_path), "headings": []}
body = self.markdown.render(source, env)
- headings = self._env_headings(env)
return self._wrap_html(
body=body,
title=markdown_path.name,
@@ -104,9 +117,6 @@ class MarkdownRenderer:
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
- headings=headings,
- include_reader_toc=include_reader_toc,
- include_reader_progress=include_reader_progress,
)
def render_code_source(
@@ -122,13 +132,10 @@ class MarkdownRenderer:
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
- include_reader_toc: bool = False,
- include_reader_progress: bool = False,
) -> str:
label = html.escape(language or code_path.suffix.lstrip(".") or "text")
language_class = f" language-{html.escape(language)}" if language else ""
highlighted = self._highlight_code(source, language, line_anchors=True)
- headings = extract_code_headings(code_path, source)
title = html.escape(code_path.name)
body = (
f"{title}
"
@@ -148,9 +155,6 @@ class MarkdownRenderer:
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
- headings=headings,
- include_reader_toc=include_reader_toc,
- include_reader_progress=include_reader_progress,
)
def wrap_body_for_display(
@@ -165,9 +169,6 @@ class MarkdownRenderer:
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
- headings: list[Heading] | None = None,
- include_reader_toc: bool = False,
- include_reader_progress: bool = False,
) -> str:
return self._wrap_html(
body=body,
@@ -180,9 +181,6 @@ class MarkdownRenderer:
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
- headings=headings or [],
- include_reader_toc=include_reader_toc,
- include_reader_progress=include_reader_progress,
)
def _render_fence(
@@ -231,6 +229,137 @@ class MarkdownRenderer:
"\n"
)
+ def _parse_math_block(
+ self,
+ state: StateBlock,
+ start_line: int,
+ end_line: int,
+ silent: bool,
+ ) -> bool:
+ if state.is_code_block(start_line):
+ return False
+
+ start = state.bMarks[start_line] + state.tShift[start_line]
+ opening = state.src[start : state.eMarks[start_line]].strip()
+ delimiters = {"$$": "$$", r"\[": r"\]"}
+ closing = delimiters.get(opening)
+ if closing is None:
+ return False
+
+ close_line = start_line + 1
+ while close_line < end_line:
+ line_start = state.bMarks[close_line] + state.tShift[close_line]
+ line = state.src[line_start : state.eMarks[close_line]].strip()
+ if line == closing:
+ break
+ close_line += 1
+ else:
+ return False
+
+ if silent:
+ return True
+
+ token = state.push("math_block", "math", 0)
+ token.content = state.getLines(
+ start_line + 1,
+ close_line,
+ state.sCount[start_line],
+ False,
+ )
+ token.markup = opening
+ token.map = [start_line, close_line + 1]
+ state.line = close_line + 1
+ return True
+
+ def _parse_math_inline(self, state: StateInline, silent: bool) -> bool:
+ start = state.pos
+ source = state.src
+
+ if source.startswith("$$", start):
+ opening = closing = "$$"
+ elif source.startswith(r"\(", start):
+ opening, closing = r"\(", r"\)"
+ elif source.startswith("$", start):
+ opening = closing = "$"
+ else:
+ return False
+
+ content_start = start + len(opening)
+ content_end = self._find_math_closing_delimiter(
+ source,
+ closing,
+ content_start,
+ state.posMax,
+ )
+ if content_end < 0 or content_end == content_start:
+ return False
+ if "\n" in source[content_start:content_end]:
+ return False
+
+ if not silent:
+ token = state.push("math_inline", "math", 0)
+ token.content = source[content_start:content_end]
+ token.markup = opening
+ state.pos = content_end + len(closing)
+ return True
+
+ def _find_math_closing_delimiter(
+ self,
+ source: str,
+ delimiter: str,
+ start: int,
+ end: int,
+ ) -> int:
+ position = start
+ while position < end:
+ position = source.find(delimiter, position, end)
+ if position < 0:
+ return -1
+
+ if delimiter == "$" and (
+ (position > start and source[position - 1] == "$")
+ or (position + 1 < end and source[position + 1] == "$")
+ ):
+ position += 1
+ continue
+
+ backslashes = 0
+ cursor = position - 1
+ while cursor >= start and source[cursor] == "\\":
+ backslashes += 1
+ cursor -= 1
+ if backslashes % 2 == 0:
+ return position
+ position += len(delimiter)
+ return -1
+
+ def _render_math_block(
+ self,
+ tokens: list[Token],
+ idx: int,
+ options: dict[str, Any],
+ env: dict[str, Any],
+ ) -> str:
+ token = tokens[idx]
+ opening = token.markup or "$$"
+ closing = r"\]" if opening == r"\[" else "$$"
+ content = html.escape(token.content.rstrip("\n"))
+ return f'{opening}\n{content}\n{closing}
\n'
+
+ def _render_math_inline(
+ self,
+ tokens: list[Token],
+ idx: int,
+ options: dict[str, Any],
+ env: dict[str, Any],
+ ) -> str:
+ token = tokens[idx]
+ opening = token.markup or "$"
+ closing = r"\)" if opening == r"\(" else opening
+ class_name = "math-display" if opening == "$$" else "math-inline"
+ content = html.escape(token.content)
+ return f'{opening}{content}{closing}'
+
def _render_image(
self,
tokens: list[Token],
@@ -543,15 +672,18 @@ class MarkdownRenderer:
document_font_size: int | None,
document_style_css: str,
math_engine: str,
- headings: list[Heading] | None = None,
- include_reader_toc: bool = False,
- include_reader_progress: bool = False,
) -> str:
- css = (self.resources_dir / "reader.css").read_text(encoding="utf-8")
- js = (self.resources_dir / "reader.js").read_text(encoding="utf-8")
- math_assets = self._math_assets(math_engine)
- mermaid_script = self._script_tag(self._resource_uri("vendor/mermaid/mermaid.min.js"))
- pygments_css = HtmlFormatter().get_style_defs(".highlight")
+ css_path = self.resources_dir / "reader.css"
+ js_path = self.resources_dir / "reader.js"
+ css_stat, js_stat = css_path.stat(), js_path.stat()
+ css = _resource_text(css_path, css_stat.st_mtime_ns, css_stat.st_size)
+ js = _resource_text(js_path, js_stat.st_mtime_ns, js_stat.st_size)
+ # Include raw HTML math delimiters too: wrap_body_for_display is public.
+ needs_math = bool(re.search(r'math-(?:inline|block|display)|\$|\\[\[(]', body))
+ math_assets = self._math_assets(math_engine) if needs_math else {"css": "", "js": "", "config": ""}
+ needs_mermaid = bool(re.search(r'class=[\"\'][^\"\']*\bmermaid\b', body))
+ mermaid_script = self._script_tag(self._resource_uri("vendor/mermaid/mermaid.min.js")) if needs_mermaid else ""
+ pygments_css = _highlight_css()
escaped_title = html.escape(title)
escaped_theme = html.escape(theme, quote=True)
escaped_math_engine = html.escape(self._normalized_math_engine(math_engine), quote=True)
@@ -568,12 +700,10 @@ class MarkdownRenderer:
font_size = max(12, min(int(document_font_size or fallback_font_size), 28))
font_family = self._css_font_family(document_font_family)
escaped_font_family = html.escape(font_family, quote=False)
- reader_shell = self._reader_shell_html(body, headings or [], include_reader_toc, include_reader_progress)
- toc_flag = "1" if include_reader_toc and headings else "0"
- progress_flag = "1" if include_reader_progress else "0"
+ reader_shell = self._reader_shell_html(body)
return f"""
-
+
@@ -582,6 +712,7 @@ class MarkdownRenderer:
:root {{
--reader-font-family: {escaped_font_family};
--reader-font-size: {font_size}px;
+ --reader-math-font-size: var(--reader-font-size);
--reader-paper-width: {paper_width_px}px;
}}
{pygments_css}
@@ -601,60 +732,8 @@ class MarkdownRenderer:
"""
- def _env_headings(self, env: dict[str, Any]) -> list[Heading]:
- raw_headings = env.get("headings", [])
- headings: list[Heading] = []
- if not isinstance(raw_headings, list):
- return headings
- for item in raw_headings:
- if not isinstance(item, dict):
- continue
- try:
- level = max(1, min(6, int(item.get("level", 1))))
- except (TypeError, ValueError):
- level = 1
- title = str(item.get("title", "")).strip()
- slug = str(item.get("slug", "")).strip()
- if title and slug:
- headings.append(Heading(level=level, title=title, slug=slug))
- return headings
-
- def _reader_shell_html(
- self,
- body: str,
- headings: list[Heading],
- include_reader_toc: bool,
- include_reader_progress: bool,
- ) -> str:
- progress = ""
- if include_reader_progress:
- progress = (
- ' \n'
- )
- toc = self._reader_toc_html(headings) if include_reader_toc and headings else ""
- shell_class = "reader-shell has-reader-toc" if toc else "reader-shell"
- return f'{progress} \n{toc} \n{body}\n \n
'
-
- def _reader_toc_html(self, headings: list[Heading]) -> str:
- links = []
- for heading in headings:
- level = max(1, min(6, int(heading.level)))
- title = html.escape(heading.title)
- slug = html.escape(heading.slug, quote=True)
- links.append(
- f'{title}'
- )
- links_html = "\n".join(links)
- return (
- ' \n'
- )
+ def _reader_shell_html(self, body: str) -> str:
+ return f' \n \n{body}\n \n
'
def _resource_uri(self, relative_path: str) -> str:
path = self.resources_dir / relative_path
if not path.exists():
diff --git a/mdhelper/pdf_export.py b/mdhelper/pdf_export.py
new file mode 100644
index 0000000..008c921
--- /dev/null
+++ b/mdhelper/pdf_export.py
@@ -0,0 +1,303 @@
+from __future__ import annotations
+
+import html
+import re
+from dataclasses import dataclass
+from io import BytesIO
+from pathlib import Path
+
+from PySide6.QtCore import QMarginsF
+from PySide6.QtGui import QPageLayout, QPageSize
+from PySide6.QtWidgets import (
+ QDialog,
+ QDialogButtonBox,
+ QDoubleSpinBox,
+ QFormLayout,
+ QLabel,
+ QVBoxLayout,
+ QWidget,
+)
+
+from .markdown_utils import Heading
+
+
+PDF_BODY_MARKER = "MDHELPER_PDF_BODY_START_7A61"
+PDF_HEADING_MARKER_PREFIX = "MDHELPER_PDF_HEADING_"
+
+
+@dataclass(frozen=True)
+class PdfMargins:
+ top: float = 15.0
+ bottom: float = 15.0
+ left: float = 15.0
+ right: float = 15.0
+
+
+def build_pdf_page_layout(margins: PdfMargins | None = None) -> QPageLayout:
+ selected = margins or PdfMargins()
+ return QPageLayout(
+ QPageSize(QPageSize.PageSizeId.A4),
+ QPageLayout.Orientation.Portrait,
+ QMarginsF(selected.left, selected.top, selected.right, selected.bottom),
+ QPageLayout.Unit.Millimeter,
+ )
+
+
+class PdfExportSettingsDialog(QDialog):
+ def __init__(self, margins: PdfMargins, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.setWindowTitle("PDF 导出设置")
+ self.setModal(True)
+
+ note = QLabel("纸张:A4;导出背景:白色;正文前自动生成带页码目录。")
+ note.setWordWrap(True)
+
+ self.top_spin = self._margin_spin(margins.top)
+ self.bottom_spin = self._margin_spin(margins.bottom)
+ self.left_spin = self._margin_spin(margins.left)
+ self.right_spin = self._margin_spin(margins.right)
+
+ form = QFormLayout()
+ form.addRow("上边距", self.top_spin)
+ form.addRow("下边距", self.bottom_spin)
+ form.addRow("左边距", self.left_spin)
+ form.addRow("右边距", self.right_spin)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+
+ layout = QVBoxLayout(self)
+ layout.addWidget(note)
+ layout.addLayout(form)
+ layout.addWidget(buttons)
+
+ def margins(self) -> PdfMargins:
+ return PdfMargins(
+ top=float(self.top_spin.value()),
+ bottom=float(self.bottom_spin.value()),
+ left=float(self.left_spin.value()),
+ right=float(self.right_spin.value()),
+ )
+
+ def _margin_spin(self, value: float) -> QDoubleSpinBox:
+ spin = QDoubleSpinBox()
+ spin.setRange(0.0, 50.0)
+ spin.setDecimals(1)
+ spin.setSingleStep(1.0)
+ spin.setSuffix(" mm")
+ spin.setValue(value)
+ return spin
+
+
+def build_pdf_export_html(
+ html_document: str,
+ headings: list[Heading],
+ page_numbers: dict[int, int] | None = None,
+ *,
+ include_page_markers: bool = True,
+) -> str:
+ printable_headings = [heading for heading in headings if heading.level <= 3]
+ marked_document = _insert_heading_markers(html_document, printable_headings) if include_page_markers else html_document
+ toc_html = _toc_html(printable_headings, page_numbers or {})
+ print_css = _print_css(len(printable_headings))
+
+ marked_document = marked_document.replace("", f"{print_css}\n ", 1)
+ body_class = ' class="pdf-export"'
+ marked_document = marked_document.replace("", f"", 1)
+ body_marker = f'{PDF_BODY_MARKER}
\n' if include_page_markers else ""
+ export_front_matter = f"\n{toc_html}\n{body_marker}"
+ return marked_document.replace(f"", f"{export_front_matter}", 1)
+
+
+def extract_heading_page_numbers(pdf_data: bytes, heading_count: int) -> dict[int, int]:
+ from pypdf import PdfReader
+
+ reader = PdfReader(BytesIO(pdf_data))
+ page_texts = [(page.extract_text() or "") for page in reader.pages]
+ normalized_page_texts = [_normalized_marker_text(text) for text in page_texts]
+ normalized_body_marker = _normalized_marker_text(PDF_BODY_MARKER)
+ body_page_index = next(
+ (index for index, text in enumerate(normalized_page_texts) if normalized_body_marker in text),
+ None,
+ )
+ if body_page_index is None:
+ raise ValueError("无法在预打印 PDF 中定位正文起始页。")
+
+ page_numbers: dict[int, int] = {}
+ for heading_index in range(heading_count):
+ marker = _normalized_marker_text(f"{PDF_HEADING_MARKER_PREFIX}{heading_index:04d}")
+ page_index = next(
+ (index for index in range(body_page_index, len(normalized_page_texts)) if marker in normalized_page_texts[index]),
+ None,
+ )
+ if page_index is not None:
+ page_numbers[heading_index] = page_index + 1
+
+ if heading_count and len(page_numbers) != heading_count:
+ missing = sorted(set(range(heading_count)) - set(page_numbers))
+ raise ValueError(f"无法识别全部目录页码,缺少标题索引:{missing}")
+ return page_numbers
+
+
+def _normalized_marker_text(value: str) -> str:
+ return re.sub(r"[^A-Z0-9]", "", value.upper())
+
+
+def _insert_heading_markers(html_document: str, headings: list[Heading]) -> str:
+ marked = html_document
+ search_from = 0
+ for index, heading in enumerate(headings):
+ escaped_slug = html.escape(heading.slug, quote=True)
+ positions = [
+ position
+ for needle in (f'id="{escaped_slug}"', f"id='{escaped_slug}'")
+ if (position := marked.find(needle, search_from)) >= 0
+ ]
+ if not positions:
+ continue
+ attribute_position = min(positions)
+ tag_end = marked.find(">", attribute_position)
+ if tag_end < 0:
+ continue
+ marker = (
+ ''
+ f"{PDF_HEADING_MARKER_PREFIX}{index:04d}"
+ ""
+ )
+ marked = f"{marked[:tag_end + 1]}{marker}{marked[tag_end + 1:]}"
+ search_from = tag_end + len(marker) + 1
+ return marked
+
+
+def _toc_html(headings: list[Heading], page_numbers: dict[int, int]) -> str:
+ density_class = " pdf-toc--dense" if len(headings) > 28 else ""
+ if len(headings) > 70:
+ density_class += " pdf-toc--very-dense"
+ rows = []
+ for index, heading in enumerate(headings):
+ title = html.escape(heading.title)
+ slug = html.escape(heading.slug, quote=True)
+ page_number = str(page_numbers.get(index, "--"))
+ rows.append(
+ f''
+ f'{title}'
+ ''
+ f'{page_number}'
+ )
+ items = "\n".join(rows) or '本文档没有可用的章节标题。'
+ return (
+ f''
+ '目录
'
+ f'{items}
'
+ ""
+ )
+
+
+def _print_css(heading_count: int) -> str:
+ column_count = 2 if heading_count > 28 else 1
+ return f"""
+ @media print {{
+ html,
+ body,
+ .reader-shell,
+ .reader {{
+ background: #ffffff !important;
+ background-image: none !important;
+ }}
+ html,
+ body {{
+ margin: 0 !important;
+ padding: 0 !important;
+ }}
+ .reader-shell {{
+ display: block !important;
+ width: 100% !important;
+ min-height: 0 !important;
+ padding: 0 !important;
+ }}
+ .reader {{
+ box-sizing: border-box !important;
+ width: 100% !important;
+ max-width: none !important;
+ min-height: 0 !important;
+ margin: 0 !important;
+ padding: 0 !important;
+ border: 0 !important;
+ box-shadow: none !important;
+ }}
+ .image-lightbox {{
+ display: none !important;
+ }}
+ .pdf-toc {{
+ display: block !important;
+ box-sizing: border-box;
+ width: 100%;
+ min-height: 100%;
+ color: #111827;
+ background: #ffffff !important;
+ break-after: page;
+ page-break-after: always;
+ }}
+ .pdf-toc h1 {{
+ margin: 0 0 10mm;
+ padding: 0 0 4mm;
+ border-bottom: 1px solid #cbd5e1;
+ color: #111827;
+ font-size: 24pt;
+ line-height: 1.2;
+ }}
+ .pdf-toc__list {{
+ column-count: {column_count};
+ column-gap: 10mm;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }}
+ .pdf-toc__item {{
+ margin: 0 0 3.2mm;
+ break-inside: avoid;
+ page-break-inside: avoid;
+ font-size: 10.5pt;
+ line-height: 1.35;
+ }}
+ .pdf-toc--dense .pdf-toc__item {{
+ margin-bottom: 2.2mm;
+ font-size: 9.5pt;
+ }}
+ .pdf-toc--very-dense .pdf-toc__item {{
+ margin-bottom: 1.4mm;
+ font-size: 8.5pt;
+ }}
+ .pdf-toc__item a {{
+ display: flex;
+ align-items: baseline;
+ color: inherit !important;
+ text-decoration: none !important;
+ }}
+ .pdf-toc__item--level-2 {{ padding-left: 5mm; }}
+ .pdf-toc__item--level-3 {{ padding-left: 10mm; }}
+ .pdf-toc__text {{ max-width: 78%; }}
+ .pdf-toc__dots {{
+ min-width: 8mm;
+ margin: 0 2mm;
+ flex: 1;
+ border-bottom: 1px dotted #94a3b8;
+ }}
+ .pdf-toc__page {{
+ min-width: 8mm;
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ }}
+ .pdf-body-start-marker,
+ .pdf-heading-marker {{
+ color: #ffffff !important;
+ font-size: 1px !important;
+ line-height: 1px !important;
+ }}
+ .pdf-body-start-marker {{
+ height: 1px;
+ overflow: hidden;
+ }}
+ }}
+ """
diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css
index 7b2dd5e..4e93ee9 100644
--- a/mdhelper/resources/reader.css
+++ b/mdhelper/resources/reader.css
@@ -38,196 +38,6 @@ html[data-theme="dark"] .reader {
min-height: 100vh;
}
-.reader-shell.has-reader-toc {
- display: grid;
- grid-template-columns: minmax(0, var(--reader-paper-width)) minmax(190px, 240px);
- gap: 24px;
- justify-content: center;
- align-items: start;
- padding: 0 24px;
-}
-
-.reader-shell.has-reader-toc .reader {
- grid-column: 1;
- grid-row: 1;
- width: 100%;
- margin: 0;
-}
-
-.reader-toc {
- box-sizing: border-box;
- grid-column: 2;
- grid-row: 1;
- position: sticky;
- top: 18px;
- max-height: calc(100vh - 36px);
- margin: 24px 0;
- padding: 14px 10px 16px;
- overflow: auto;
- border: 1px solid #d9dee7;
- border-radius: 8px;
- background: rgba(255, 255, 255, 0.92);
- box-shadow: 0 8px 24px rgba(22, 34, 51, 0.08);
-}
-
-.reader-toc__title {
- margin: 0 6px 10px;
- color: #526071;
- font-size: 0.82em;
- font-weight: 700;
-}
-
-.reader-toc__nav {
- display: grid;
- gap: 2px;
-}
-
-.reader-toc__link {
- display: block;
- min-height: 24px;
- padding: 4px 8px;
- border-radius: 6px;
- color: #415064;
- font-size: 0.86em;
- line-height: 1.35;
- text-decoration: none;
-}
-
-.reader-toc__link:hover {
- background: #eef4fb;
- text-decoration: none;
-}
-
-.reader-toc__link.is-active {
- background: #dbeafe;
- color: #124a7c;
- font-weight: 700;
-}
-
-.reader-toc__link--level-2 {
- padding-left: 18px;
-}
-
-.reader-toc__link--level-3 {
- padding-left: 30px;
-}
-
-.reader-toc__link--level-4,
-.reader-toc__link--level-5,
-.reader-toc__link--level-6 {
- padding-left: 42px;
-}
-
-.reader-progress {
- position: fixed;
- right: 18px;
- bottom: 16px;
- z-index: 20;
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 128px;
- padding: 7px 9px;
- border: 1px solid #d3dbe7;
- border-radius: 8px;
- background: rgba(255, 255, 255, 0.9);
- color: #384557;
- box-shadow: 0 8px 22px rgba(22, 34, 51, 0.12);
- font-size: 12px;
- backdrop-filter: blur(8px);
-}
-
-.reader-progress__track {
- flex: 1;
- height: 5px;
- overflow: hidden;
- border-radius: 999px;
- background: #d9e2ef;
-}
-
-.reader-progress__bar {
- width: 0%;
- height: 100%;
- border-radius: inherit;
- background: #3577b9;
-}
-
-.reader-progress__text {
- min-width: 34px;
- text-align: right;
- font-variant-numeric: tabular-nums;
-}
-
-html[data-theme="dark"] .reader-toc {
- border-color: #3a4352;
- background: rgba(32, 36, 44, 0.92);
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
-}
-
-html[data-theme="dark"] .reader-toc__title {
- color: #aeb8c8;
-}
-
-html[data-theme="dark"] .reader-toc__link {
- color: #c7d0de;
-}
-
-html[data-theme="dark"] .reader-toc__link:hover {
- background: #2b3543;
-}
-
-html[data-theme="dark"] .reader-toc__link.is-active {
- background: #1f4a73;
- color: #f2f7ff;
-}
-
-html[data-theme="dark"] .reader-progress {
- border-color: #3a4352;
- background: rgba(32, 36, 44, 0.9);
- color: #dce5f3;
- box-shadow: 0 8px 22px rgba(0, 0, 0, 0.32);
-}
-
-html[data-theme="dark"] .reader-progress__track {
- background: #3b4656;
-}
-
-html[data-theme="dark"] .reader-progress__bar {
- background: #6aa9e9;
-}
-
-@media (max-width: 1080px) {
- .reader-shell.has-reader-toc {
- display: block;
- padding: 0;
- }
-
- .reader-shell.has-reader-toc .reader {
- margin: 0 auto;
- }
-
- .reader-toc {
- grid-column: auto;
- grid-row: auto;
- position: static;
- max-width: var(--reader-paper-width);
- max-height: 34vh;
- margin: 16px auto 0;
- }
-}
-
-@media (max-width: 720px) {
- .reader-toc {
- display: none;
- }
-
- .reader-progress {
- right: 10px;
- bottom: 10px;
- min-width: 108px;
- }
-}
-
h1,
h2,
h3,
@@ -828,6 +638,20 @@ html[data-theme="dark"] .diagram-title {
padding: 1em;
}
+.math-block,
+.math-display {
+ font-size: var(--reader-math-font-size, 1em);
+}
+
+.math-block .katex,
+.math-display .katex,
+.math-inline .katex,
+.math-block mjx-container,
+.math-display mjx-container,
+.math-inline mjx-container {
+ font-size: 1em !important;
+}
+
.diagram-missing-runtime::before {
content: "Mermaid 本地资源未加载,下面显示原始图表代码。";
display: block;
@@ -1121,6 +945,3 @@ html[data-theme="dark"] hr {
padding: 24px 20px 42px;
}
}
-
-
-
diff --git a/mdhelper/resources/reader.js b/mdhelper/resources/reader.js
index bcb0a5e..9f4b4f1 100644
--- a/mdhelper/resources/reader.js
+++ b/mdhelper/resources/reader.js
@@ -37,6 +37,18 @@ document.addEventListener("DOMContentLoaded", () => {
}
};
+ const syncMathFontSize = () => {
+ const reader = document.querySelector(".reader");
+ if (!reader) {
+ return;
+ }
+ const reference = reader.querySelector(":scope > p") || reader.querySelector("p") || reader;
+ const fontSize = window.getComputedStyle(reference).fontSize;
+ if (fontSize) {
+ reader.style.setProperty("--reader-math-font-size", fontSize);
+ }
+ };
+
const renderMath = () => {
const reader = document.querySelector(".reader");
const engine = document.documentElement.dataset.mathEngine || "katex";
@@ -61,6 +73,8 @@ document.addEventListener("DOMContentLoaded", () => {
};
renderMermaidDiagrams();
+ window.mdhelperSyncMathFontSize = syncMathFontSize;
+ syncMathFontSize();
renderMath();
document.querySelectorAll(".code-block").forEach((block) => {
@@ -337,122 +351,7 @@ document.addEventListener("DOMContentLoaded", () => {
}
});
- const headingElements = [...document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")];
- const tocLinks = [...document.querySelectorAll(".reader-toc__link[data-toc-target]")];
- const tocLinkById = new Map(tocLinks.map((link) => [link.dataset.tocTarget, link]));
- const progressBar = document.querySelector(".reader-progress__bar");
- const progressText = document.querySelector(".reader-progress__text");
- const SCROLL_REPORT_INTERVAL = 500;
let bridge = null;
- let previewBridge = null;
- let ticking = false;
- let visualTicking = false;
- let reportTimer = 0;
- let lastReportAt = 0;
- let activeTocLink = null;
- let lastVisualState = { progress: -1, activeId: "" };
-
- const scrollState = () => {
- const documentElement = document.documentElement;
- const maxScroll = Math.max(1, documentElement.scrollHeight - window.innerHeight);
- const progress = Math.max(0, Math.min(100, (window.scrollY / maxScroll) * 100));
- let activeId = "";
- let low = 0;
- let high = headingElements.length - 1;
- const threshold = Math.max(0, window.scrollY || 0) + 96;
- while (low <= high) {
- const middle = Math.floor((low + high) / 2);
- if (headingElements[middle].offsetTop <= threshold) {
- activeId = headingElements[middle].id;
- low = middle + 1;
- } else {
- high = middle - 1;
- }
- }
- return { progress, activeId, scrollY: Math.max(0, Math.round(window.scrollY || 0)) };
- };
-
- const updateReaderChrome = ({ progress, activeId }) => {
- const roundedProgress = Math.max(0, Math.min(100, Math.round(progress)));
- if (progressBar && Math.abs(progress - lastVisualState.progress) >= 0.2) {
- progressBar.style.width = `${progress.toFixed(2)}%`;
- }
- if (progressText && roundedProgress !== Math.round(lastVisualState.progress)) {
- progressText.textContent = `${roundedProgress}%`;
- }
- if (activeId !== lastVisualState.activeId) {
- if (activeTocLink) {
- activeTocLink.classList.remove("is-active");
- }
- activeTocLink = tocLinkById.get(activeId) || null;
- if (activeTocLink) {
- activeTocLink.classList.add("is-active");
- }
- }
- lastVisualState = { progress, activeId };
- };
-
- const updateVisualScrollState = () => {
- visualTicking = false;
- updateReaderChrome(scrollState());
- };
-
- const scheduleVisualUpdate = () => {
- if (!visualTicking) {
- visualTicking = true;
- window.requestAnimationFrame(updateVisualScrollState);
- }
- };
-
- const reportScroll = () => {
- ticking = false;
- lastReportAt = performance.now();
- const state = scrollState();
- if (bridge && bridge.reportScroll) {
- bridge.reportScroll(state.progress, state.activeId, state.scrollY);
- }
- };
-
- const requestScrollReport = () => {
- if (!ticking) {
- ticking = true;
- window.requestAnimationFrame(reportScroll);
- }
- };
-
- const scheduleReport = () => {
- const elapsed = performance.now() - lastReportAt;
- if (elapsed >= SCROLL_REPORT_INTERVAL) {
- requestScrollReport();
- return;
- }
- if (!reportTimer) {
- reportTimer = window.setTimeout(() => {
- reportTimer = 0;
- requestScrollReport();
- }, SCROLL_REPORT_INTERVAL - elapsed);
- }
- };
-
- tocLinks.forEach((link) => {
- link.addEventListener("click", (event) => {
- const targetId = link.dataset.tocTarget;
- const target = targetId ? document.getElementById(targetId) : null;
- if (!target) {
- return;
- }
- event.preventDefault();
- target.scrollIntoView({ block: "start", behavior: "auto" });
- if (targetId) {
- window.history.replaceState(null, "", `#${encodeURIComponent(targetId)}`);
- if (previewBridge && previewBridge.openHeading) {
- previewBridge.openHeading(targetId);
- }
- }
- scheduleVisualUpdate();
- scheduleReport();
- });
- });
const configuredWheelSpeed = () => {
const speed = Number(document.documentElement.dataset.wheelScrollSpeed || "1");
@@ -526,14 +425,6 @@ document.addEventListener("DOMContentLoaded", () => {
top: delta.y * speed,
behavior: "auto",
});
- if (
- scroller === document.scrollingElement ||
- scroller === document.documentElement ||
- scroller === document.body
- ) {
- scheduleVisualUpdate();
- scheduleReport();
- }
};
const syncCustomWheelHandler = () => {
@@ -554,20 +445,7 @@ document.addEventListener("DOMContentLoaded", () => {
if (window.qt && window.qt.webChannelTransport) {
new QWebChannel(window.qt.webChannelTransport, (channel) => {
bridge = channel.objects.mdhelperBridge || null;
- previewBridge = channel.objects.mdhelperPreviewBridge || null;
- reportScroll();
});
}
-
- window.addEventListener("scroll", () => {
- scheduleVisualUpdate();
- scheduleReport();
- }, { passive: true });
- window.addEventListener("resize", () => {
- scheduleVisualUpdate();
- scheduleReport();
- });
- scheduleVisualUpdate();
- reportScroll();
});
diff --git a/mdhelper/settings_dialog.py b/mdhelper/settings_dialog.py
index 4d8e7a1..2cc78b7 100644
--- a/mdhelper/settings_dialog.py
+++ b/mdhelper/settings_dialog.py
@@ -24,9 +24,6 @@ class AppPreferences:
font_scale: float
wheel_scroll_speed: float
reader_width_scale: float
- reader_embedded_toc: bool
- reader_external_toc: bool
- reader_embedded_progress: bool
auto_refresh: bool
auto_refresh_mode: str
auto_refresh_delay_ms: int
@@ -87,23 +84,6 @@ class SettingsDialog(QDialog):
width_index = self.reader_width_scale_combo.findData(float(preferences.reader_width_scale))
self.reader_width_scale_combo.setCurrentIndex(max(0, width_index))
- self.reader_embedded_toc_check = QCheckBox("网页内大纲")
- self.reader_embedded_toc_check.setChecked(preferences.reader_embedded_toc)
- self.reader_external_toc_check = QCheckBox("外部目录栏")
- self.reader_external_toc_check.setChecked(preferences.reader_external_toc and not preferences.reader_embedded_toc)
- self.reader_embedded_toc_check.toggled.connect(self._update_navigation_availability)
- self.reader_embedded_progress_check = QCheckBox("网页内进度条")
- self.reader_embedded_progress_check.setChecked(preferences.reader_embedded_progress)
-
- navigation_widget = QWidget()
- navigation_layout = QVBoxLayout(navigation_widget)
- navigation_layout.setContentsMargins(0, 0, 0, 0)
- navigation_layout.setSpacing(4)
- navigation_layout.addWidget(self.reader_embedded_toc_check)
- navigation_layout.addWidget(self.reader_external_toc_check)
- navigation_layout.addWidget(self.reader_embedded_progress_check)
- self._update_navigation_availability()
-
self.auto_refresh_mode_combo = QComboBox()
self.auto_refresh_mode_combo.addItem("当前文档、资源和目录", "all")
self.auto_refresh_mode_combo.addItem("当前文档和引用资源", "resources")
@@ -151,7 +131,6 @@ class SettingsDialog(QDialog):
form.addRow("正文字号倍率", self.font_scale_spin)
form.addRow("鼠标滚轮速度", self.wheel_scroll_speed_spin)
form.addRow("纸张宽度", self.reader_width_scale_combo)
- form.addRow("阅读导航", navigation_widget)
form.addRow("自动刷新", self.auto_refresh_mode_combo)
form.addRow("刷新延迟", self.auto_refresh_delay_combo)
form.addRow("其他本地文件", self.non_preview_combo)
@@ -188,9 +167,6 @@ class SettingsDialog(QDialog):
font_scale=float(self.font_scale_spin.value()),
wheel_scroll_speed=float(self.wheel_scroll_speed_spin.value()),
reader_width_scale=float(self.reader_width_scale_combo.currentData() or 1.0),
- reader_embedded_toc=self.reader_embedded_toc_check.isChecked(),
- reader_external_toc=self.reader_external_toc_check.isChecked() and not self.reader_embedded_toc_check.isChecked(),
- reader_embedded_progress=self.reader_embedded_progress_check.isChecked(),
auto_refresh=auto_refresh_mode != "off",
auto_refresh_mode=auto_refresh_mode,
auto_refresh_delay_ms=int(self.auto_refresh_delay_combo.currentData() or 1000),
@@ -198,12 +174,6 @@ class SettingsDialog(QDialog):
document_file_groups=normalized_document_file_groups(document_file_groups),
)
- def _update_navigation_availability(self) -> None:
- embedded_toc = self.reader_embedded_toc_check.isChecked()
- self.reader_external_toc_check.setEnabled(not embedded_toc)
- if embedded_toc:
- self.reader_external_toc_check.setChecked(False)
-
def _update_background_availability(self) -> None:
enabled = str(self.theme_color_combo.currentData()) == "colorful"
self.theme_background_combo.setEnabled(enabled)
diff --git a/mdhelper/startup_scan.py b/mdhelper/startup_scan.py
new file mode 100644
index 0000000..442c910
--- /dev/null
+++ b/mdhelper/startup_scan.py
@@ -0,0 +1,28 @@
+"""Read the initial project in a worker, never touching widgets or settings."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from PySide6.QtCore import QObject, QRunnable, Signal
+
+from .document_tree import discover_documents, document_directory_signature
+
+
+class ScanSignals(QObject):
+ finished = Signal(object)
+
+
+class StartupScan(QRunnable):
+ def __init__(self, generation: int, root: Path, groups: tuple[str, ...]) -> None:
+ super().__init__()
+ self.generation, self.root, self.groups = generation, root, groups
+ self.signals = ScanSignals()
+
+ def run(self) -> None:
+ try:
+ entries = discover_documents(self.root, self.groups)
+ signature = document_directory_signature(self.root, self.groups)
+ result = (entries, signature, None)
+ except Exception as exc:
+ result = ([], (), str(exc))
+ self.signals.finished.emit((self.generation, self.root, self.groups, *result))
diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py
index a9a4b02..795996b 100644
--- a/mdhelper/style_dialog.py
+++ b/mdhelper/style_dialog.py
@@ -50,9 +50,14 @@ DEFAULT_ENGLISH_FONT = "Times New Roman"
def build_document_style_css(rules: dict[str, dict[str, Any]] | None, extra_css: str = "") -> str:
parts: list[str] = []
+ normalized_rules = rules if isinstance(rules, dict) else {}
+ paragraph_rule = normalized_rules.get("paragraph", {})
+ paragraph_font_size = _positive_float(paragraph_rule.get("font_size")) if isinstance(paragraph_rule, dict) else 0.0
+ if paragraph_font_size > 0:
+ parts.append(f".reader {{\n --reader-math-font-size: {_format_number(paragraph_font_size)}px;\n}}")
selector_by_target = {target_id: selector for target_id, _label, selector in STYLE_TARGETS}
for target_id, selector in selector_by_target.items():
- rule = rules.get(target_id, {}) if isinstance(rules, dict) else {}
+ rule = normalized_rules.get(target_id, {})
declarations = _css_declarations(rule)
if declarations:
parts.append(f"{selector} {{\n" + "\n".join(f" {declaration}" for declaration in declarations) + "\n}")
diff --git a/pack/MDHelper.iss b/pack/MDHelper.iss
new file mode 100644
index 0000000..6c3b33a
--- /dev/null
+++ b/pack/MDHelper.iss
@@ -0,0 +1,45 @@
+#ifndef AppVersion
+ #error AppVersion must be supplied by build_installer.ps1
+#endif
+#ifndef SourceRoot
+ #error SourceRoot must be supplied by build_installer.ps1
+#endif
+
+[Setup]
+AppId={{83D889E1-616A-49D3-B055-9216AE9E3124}
+AppName=MDHelper
+AppVersion={#AppVersion}
+AppPublisher=MDHelper
+DefaultDirName={localappdata}\Programs\MDHelper
+DefaultGroupName=MDHelper
+DisableProgramGroupPage=yes
+PrivilegesRequired=lowest
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+MinVersion=10.0
+OutputDir={#SourceRoot}\pack\output
+OutputBaseFilename=MDHelper-Setup-{#AppVersion}-x64
+SetupIconFile={#SourceRoot}\icon_glass.ico
+UninstallDisplayIcon={app}\MDHelper.exe
+Compression=lzma2
+SolidCompression=yes
+WizardStyle=modern
+CloseApplications=yes
+RestartApplications=no
+SetupLogging=yes
+
+[Languages]
+Name: "english"; MessagesFile: "compiler:Default.isl"
+
+[Tasks]
+Name: "desktopicon"; Description: "Create a desktop shortcut"; Flags: unchecked
+
+[Files]
+Source: "{#SourceRoot}\dist\MDHelper\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
+
+[Icons]
+Name: "{group}\MDHelper"; Filename: "{app}\MDHelper.exe"; WorkingDir: "{app}"
+Name: "{autodesktop}\MDHelper"; Filename: "{app}\MDHelper.exe"; WorkingDir: "{app}"; Tasks: desktopicon
+
+[Run]
+Filename: "{app}\MDHelper.exe"; Description: "Launch MDHelper"; Flags: nowait postinstall skipifsilent
diff --git a/pack/README.md b/pack/README.md
new file mode 100644
index 0000000..8a226d2
--- /dev/null
+++ b/pack/README.md
@@ -0,0 +1,54 @@
+# Windows 安装版构建
+
+双击本目录的 `_installer.cmd`,或在任意工作目录调用它的完整路径。
+成功、失败都会显示结果并保留窗口;失败返回非零退出码,并停止后续打包。
+
+## 产物
+
+- `pack/output/MDHelper-Setup-<版本号>-x64.exe`:发给用户的安装程序。
+- 同名 `.exe.sha256`:SHA256 校验值。
+- `dist/MDHelper/`:安装器使用的完整程序目录。内部 EXE 不能单独复制使用。
+- `pack/logs/build-*.log`:构建日志。
+
+安装器默认安装到当前用户的 `%LOCALAPPDATA%\Programs\MDHelper`,可修改目标目录。
+提供开始菜单入口、可选桌面快捷方式,以及 Windows“已安装的应用”中的卸载入口。
+更新安装沿用固定 AppId 和原安装目录。配置、书签等沿用旧版 QSettings,卸载不删除用户文档和阅读配置。
+安装后不需要 Python、Pandoc 或联网;公式和图表资源均在本地。
+
+安装 EXE 会在安装时解压。日常使用启动的是安装目录中的 MDHelper.exe,不会每次解压整套 Qt 和 Pandoc。
+旧的 `dist/MDHelper.exe` 是历史单文件产物,脚本保留它但不再生成或更新它。
+
+## 首次构建
+
+1. 准备 64 位 Python 3.10 或以上。优先复用项目现有虚拟环境,包括 `mdhelper_env/mdhelper_env` 的嵌套布局。
+2. 缺少或不符合 `requirements.txt` 的依赖时,脚本会安装锁定版本;需要网络。
+3. 缺少 pytest 时自动安装,默认执行全部单元回归测试。
+4. 优先使用已安装的 Inno Setup。未找到时下载官方 Inno Setup 6.7.3,校验 Windows 数字签名和发布者,再按当前用户安装到 `pack/.tools/InnoSetup6`。首次需要网络,之后可复用缓存。
+5. 项目应保留 `vendor/pandoc/pandoc.exe` 及其许可证文件。Pandoc 随应用目录安装,只有导出 DOCX 时才运行。
+
+脚本不会启动安装后的 MDHelper,也不会替你执行生成的安装程序。
+构建工具的使用条件见 [Inno Setup 官网](https://jrsoftware.org/isinfo.php)。
+
+## 自动化和自定义
+
+```bat
+pack\_installer.cmd -NoPause
+pack\_installer.cmd -NoPause -SkipTests
+```
+
+`-SkipTests` 只用于明确需要跳过已验证测试的重复构建。默认仍会执行测试。
+也可设置 `MDHELPER_NO_PAUSE=1` 取消结束暂停。
+
+使用指定工具路径:
+
+```bat
+set "MDHELPER_PYTHON=C:\Path\To\python.exe"
+set "MDHELPER_ISCC=C:\Path\To\ISCC.exe"
+pack\_installer.cmd
+```
+
+如果指定的是系统 Python,脚本先在 `pack/.venv` 创建独立构建环境。
+离线构建前,请先准备好依赖、Pandoc 和 Inno Setup;工具缺失时脚本会明确报错。
+版本号读取 `mdhelper/__init__.py`,安装器定义在 `MDHelper.iss`,目录式打包定义在根目录 `MDHelper.spec`。
+
+安装器暂未配置代码签名证书,生成的 MDHelper 安装 EXE 为未签名文件。
diff --git a/pack/_installer.cmd b/pack/_installer.cmd
new file mode 100644
index 0000000..783b060
--- /dev/null
+++ b/pack/_installer.cmd
@@ -0,0 +1,12 @@
+@echo off
+setlocal
+title MDHelper Installer Builder
+powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0build_installer.ps1" %*
+set "BUILD_EXIT=%ERRORLEVEL%"
+echo.
+if not "%BUILD_EXIT%"=="0" echo Build failed. See the error above and pack\logs.
+if /I "%~1"=="-NoPause" goto done
+if "%MDHELPER_NO_PAUSE%"=="1" goto done
+pause
+:done
+exit /b %BUILD_EXIT%
diff --git a/pack/build_installer.ps1 b/pack/build_installer.ps1
new file mode 100644
index 0000000..0cb7b18
--- /dev/null
+++ b/pack/build_installer.ps1
@@ -0,0 +1,136 @@
+[CmdletBinding()]
+param([switch]$NoPause, [switch]$SkipTests)
+
+$ErrorActionPreference = 'Stop'
+$ProgressPreference = 'SilentlyContinue'
+# A .cmd launched from PowerShell 7 may inherit incompatible module paths.
+$env:PSModulePath = (Join-Path $PSHOME 'Modules') + ';' + (Join-Path $env:ProgramFiles 'WindowsPowerShell\Modules')
+$projectRoot = Split-Path -Parent $PSScriptRoot
+$logDir = Join-Path $PSScriptRoot 'logs'
+New-Item -ItemType Directory -Force -Path $logDir | Out-Null
+$logFile = Join-Path $logDir ('build-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.log')
+Start-Transcript -Path $logFile | Out-Null
+
+function Invoke-Checked([string]$Program, [string[]]$Arguments) {
+ & $Program @Arguments
+ if ($LASTEXITCODE -ne 0) { throw "$Program failed with exit code $LASTEXITCODE" }
+}
+
+function Test-PythonCode([string]$Python, [string]$Code) {
+ try {
+ & $Python -B -c $Code 2>$null | Out-Null
+ return $LASTEXITCODE -eq 0
+ } catch { return $false }
+}
+
+function Find-Python {
+ $candidates = @()
+ if ($env:MDHELPER_PYTHON) { $candidates += $env:MDHELPER_PYTHON }
+ $candidates += @(
+ (Join-Path $projectRoot 'mdhelper_env\Scripts\python.exe'),
+ (Join-Path $projectRoot 'mdhelper_env\mdhelper_env\Scripts\python.exe'),
+ (Join-Path $projectRoot '.venv\Scripts\python.exe'),
+ (Join-Path $PSScriptRoot '.venv\Scripts\python.exe')
+ )
+ $launcher = Get-Command py.exe -ErrorAction SilentlyContinue
+ if ($launcher) {
+ $detected = & $launcher.Source -3 -c 'import sys; print(sys.executable)' 2>$null
+ if ($LASTEXITCODE -eq 0) { $candidates += $detected }
+ }
+ $onPath = Get-Command python.exe -ErrorAction SilentlyContinue
+ if ($onPath) { $candidates += $onPath.Source }
+ foreach ($candidate in $candidates | Select-Object -Unique) {
+ if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { continue }
+ if (Test-PythonCode $candidate 'import sys, struct; sys.exit(0 if sys.version_info >= (3, 10) and struct.calcsize(chr(80)) == 8 else 1)') { return $candidate }
+ }
+ throw 'Python 3.10+ (64-bit) was not found. Install Python, or set MDHELPER_PYTHON to python.exe.'
+}
+
+function Find-InnoCompiler {
+ $candidates = @()
+ if ($env:MDHELPER_ISCC) { $candidates += $env:MDHELPER_ISCC }
+ $candidates += (Join-Path $PSScriptRoot '.tools\InnoSetup6\ISCC.exe')
+ $onPath = Get-Command ISCC.exe -ErrorAction SilentlyContinue
+ if ($onPath) { $candidates += $onPath.Source }
+ foreach ($base in @(${env:ProgramFiles(x86)}, $env:ProgramFiles, (Join-Path $env:LOCALAPPDATA 'Programs'))) {
+ if ($base) {
+ $candidates += (Join-Path $base 'Inno Setup 6\ISCC.exe')
+ $candidates += (Join-Path $base 'Inno Setup 7\ISCC.exe')
+ }
+ }
+ foreach ($candidate in $candidates) {
+ if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate }
+ }
+
+ Write-Host '[2/5] Downloading the official Inno Setup 6.7.3 compiler (first build only)...'
+ $toolsDir = Join-Path $PSScriptRoot '.tools'
+ New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null
+ $setupPath = Join-Path $toolsDir 'innosetup-6.7.3.exe'
+ if (-not (Test-Path -LiteralPath $setupPath)) {
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ Invoke-WebRequest -UseBasicParsing -Uri 'https://github.com/jrsoftware/issrc/releases/download/is-6_7_3/innosetup-6.7.3.exe' -OutFile ($setupPath + '.download')
+ Move-Item -LiteralPath ($setupPath + '.download') -Destination $setupPath -Force
+ }
+ $signature = Get-AuthenticodeSignature -LiteralPath $setupPath
+ if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Pyrsys B\.V\.') {
+ throw "Inno Setup publisher signature could not be verified. Remove $setupPath and retry, or set MDHELPER_ISCC to an installed compiler."
+ }
+ $innoDir = Join-Path $toolsDir 'InnoSetup6'
+ $arguments = @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-', '/CURRENTUSER', '/NOICONS', '/TASKS=', ('/DIR="' + $innoDir + '"'))
+ $process = Start-Process -FilePath $setupPath -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
+ if ($process.ExitCode -ne 0) { throw "Inno Setup installation failed: $($process.ExitCode)" }
+ $compiler = Join-Path $innoDir 'ISCC.exe'
+ if (-not (Test-Path -LiteralPath $compiler)) { throw 'Inno Setup compiler was not created.' }
+ return $compiler
+}
+
+try {
+ Push-Location $projectRoot
+ Write-Host '[1/5] Checking Python and build dependencies...'
+ $python = Find-Python
+ Write-Host "Python: $python"
+ # A system interpreter is used only to create an isolated build environment.
+ $isVenv = & $python -B -c 'import sys; print(int(sys.prefix != sys.base_prefix))'
+ if ($isVenv -ne '1') {
+ $venvRoot = Join-Path $PSScriptRoot '.venv'
+ Invoke-Checked $python @('-m', 'venv', $venvRoot)
+ $python = Join-Path $venvRoot 'Scripts\python.exe'
+ }
+ $probe = "import importlib.metadata as m, pathlib; lines=pathlib.Path('requirements.txt').read_text().splitlines(); assert all(m.version(n.strip()) == v.strip() for n,v in (s.split('==') for s in lines if '==' in s and not s.startswith('#')))"
+ if (-not (Test-PythonCode $python $probe)) {
+ Invoke-Checked $python @('-m', 'pip', 'install', '-r', 'requirements.txt')
+ }
+ if (-not (Test-Path -LiteralPath 'vendor\pandoc\pandoc.exe')) { throw 'Missing vendor\pandoc\pandoc.exe. Restore the bundled Pandoc before building.' }
+ $compiler = Find-InnoCompiler
+ Write-Host "Installer compiler: $compiler"
+
+ Write-Host '[3/5] Running regression tests...'
+ if (-not $SkipTests) {
+ if (-not (Test-PythonCode $python 'import pytest')) { Invoke-Checked $python @('-m', 'pip', 'install', 'pytest>=8,<10') }
+ Invoke-Checked $python @('-B', '-m', 'pytest', '-q', 'tests')
+ } else { Write-Host 'Tests explicitly skipped.' }
+
+ Write-Host '[4/5] Building the application directory...'
+ # Exclude unrelated tool runtimes from native DLL resolution.
+ $env:PATH = (($env:PATH -split ';') | Where-Object { $_ -notmatch '\\codex-runtimes\\' }) -join ';'
+ Invoke-Checked $python @('-m', 'PyInstaller', '--noconfirm', '--clean', 'MDHelper.spec')
+ $appPath = Join-Path $projectRoot 'dist\MDHelper\MDHelper.exe'
+ if (-not (Test-Path -LiteralPath $appPath)) { throw 'The application directory was not generated.' }
+
+ Write-Host '[5/5] Compiling the installer...'
+ $version = (& $python -B -c 'from mdhelper import __version__; print(__version__)').Trim()
+ if ($version -notmatch '^\d+\.\d+\.\d+([.-][A-Za-z0-9.]+)?$') { throw "Invalid application version: $version" }
+ Invoke-Checked $compiler @('/Qp', "/DAppVersion=$version", "/DSourceRoot=$projectRoot", (Join-Path $PSScriptRoot 'MDHelper.iss'))
+ $installer = Join-Path $PSScriptRoot "output\MDHelper-Setup-$version-x64.exe"
+ if (-not (Test-Path -LiteralPath $installer)) { throw 'The installer was not generated.' }
+ $hash = (Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash.ToLowerInvariant()
+ Set-Content -LiteralPath ($installer + '.sha256') -Value ($hash + ' ' + (Split-Path -Leaf $installer)) -Encoding ASCII
+ Write-Host "SUCCESS: $installer" -ForegroundColor Green
+ Write-Host "Build log: $logFile"
+} catch {
+ Write-Host "BUILD FAILED: $($_.Exception.Message)" -ForegroundColor Red
+ exit 1
+} finally {
+ Pop-Location
+ Stop-Transcript | Out-Null
+}
diff --git a/packaging/sample.md b/packaging/sample.md
new file mode 100644
index 0000000..4d40ef8
--- /dev/null
+++ b/packaging/sample.md
@@ -0,0 +1,14 @@
+# MDHelper
+
+欢迎使用 MDHelper。本程序用于阅读、搜索、编辑和导出本地 Markdown 与源码文档。
+
+
+
+## 快速开始
+
+1. 点击“打开文件夹”选择文档目录。
+2. 在左侧文档树中打开 Markdown 或源码文件。
+3. 使用 `Ctrl+F` 查找当前页面,使用 `Ctrl+Shift+F` 全文搜索。
+4. 使用“文件”菜单导出 PDF、HTML、DOCX 或 MHTML。
+
+完整说明请查看 [用户手册](docs/user_manual.md)。
diff --git a/requirements.txt b/requirements.txt
index 0c779b2..1b60c2e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,4 +4,5 @@ markdown-it-py==4.2.0
Pygments==2.20.0
Pillow==12.2.0
python-docx==1.2.0
+pypdf==6.14.2
PyInstaller==6.20.0
diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py
index a30b335..b45f229 100644
--- a/tests/gui_smoke.py
+++ b/tests/gui_smoke.py
@@ -4,6 +4,7 @@ import os
import sys
import traceback
import zipfile
+import tempfile
from pathlib import Path
@@ -21,10 +22,10 @@ os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))
-from PySide6.QtCore import QEventLoop, QSettings, QTimer, QUrl, Qt
+from PySide6.QtCore import QEventLoop, QPoint, QSettings, QTimer, QUrl, Qt
from PySide6.QtGui import QTextCursor
from PySide6.QtWebEngineCore import QWebEnginePage
-from PySide6.QtWidgets import QApplication, QMessageBox, QPushButton, QToolBar
+from PySide6.QtWidgets import QAbstractItemView, QApplication, QMessageBox, QPushButton, QToolBar
from mdhelper.main_window import MainWindow, ReaderPage, ReaderView, VideoPlayerWidget
from mdhelper.markdown_editor import MarkdownEditorDialog
@@ -33,15 +34,15 @@ from mdhelper.style_dialog import DocumentStyleEditorDialog
def main() -> int:
+ isolated_settings = tempfile.TemporaryDirectory(prefix="mdhelper-gui-smoke-")
+ QSettings.setDefaultFormat(QSettings.Format.IniFormat)
+ QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, isolated_settings.name)
project_root = PROJECT_ROOT
app = QApplication.instance() or QApplication([sys.argv[0]])
settings = QSettings("MDHelper", "MDHelper")
settings.setValue("reader/document_file_groups", '["markdown"]')
settings.setValue("reader/wheel_scroll_speed", 1.0)
- settings.setValue("reader/embedded_toc", True)
- settings.setValue("reader/external_toc", False)
- settings.setValue("reader/embedded_progress", True)
- window = MainWindow(project_root=project_root, initial_path=project_root / "sample.md")
+ window = MainWindow(project_root=project_root, initial_path=project_root / "sample.md", defer_startup=True)
window.show()
checks: list[str] = []
@@ -50,6 +51,8 @@ def main() -> int:
empty_window = MainWindow(project_root=None, app_root=project_root)
if empty_window.has_project or empty_window.entries:
checks.append("empty_start_project")
+ if empty_window.new_file_action.isEnabled():
+ checks.append("new_file_disabled_without_project")
if empty_window.tabs.count() != 1 or not bool(empty_window.tabs.currentWidget().property("is_welcome")):
checks.append("welcome_empty_start")
if empty_window.tree.topLevelItem(0).text(0) != "未选择文件夹":
@@ -58,12 +61,16 @@ def main() -> int:
if not empty_window.has_project or empty_window.project_root != project_root.resolve() or not empty_window.entries:
checks.append("set_project_root")
switch_root = project_root / "__gui_smoke_switch_root__"
+ nested_root = switch_root / "nested"
try:
- switch_root.mkdir(exist_ok=True)
+ nested_root.mkdir(parents=True, exist_ok=True)
(switch_root / "first.md").write_text("# First\n", encoding="utf-8")
+ (nested_root / "inside.md").write_text("# Inside\n", encoding="utf-8")
empty_window.open_document(project_root / "sample.md", add_history=False)
if not empty_window.set_project_root(switch_root, save=False):
checks.append("switch_project_root")
+ if not empty_window.new_file_action.isEnabled():
+ checks.append("new_file_enabled_with_project")
if empty_window.current_file is not None:
checks.append("switch_project_clears_current_file")
if empty_window.tabs.count() != 1 or not bool(empty_window.tabs.currentWidget().property("is_welcome")):
@@ -72,9 +79,159 @@ def main() -> int:
empty_window._poll_directory_changes()
if not any(entry.path == (switch_root / "second.md").resolve() for entry in empty_window.entries):
checks.append("directory_poll_refresh")
+ created_path = empty_window.create_new_markdown_file(empty_window.tree.topLevelItem(0))
+ if created_path is None or not created_path.exists() or created_path.suffix.lower() != ".md":
+ checks.append("new_markdown_file_created")
+ elif empty_window._new_file_rename_item is None:
+ checks.append("new_markdown_inline_rename")
+ else:
+ empty_window._new_file_rename_item.setText(0, "renamed-from-tree")
+ renamed_path = switch_root / "renamed-from-tree.md"
+ if created_path.exists() or not renamed_path.exists():
+ checks.append("new_markdown_tree_rename")
+ root_item = empty_window.tree.topLevelItem(0)
+ nested_item = next(
+ (
+ root_item.child(index)
+ for index in range(root_item.childCount())
+ if root_item.child(index).toolTip(0) == str(nested_root)
+ ),
+ None,
+ )
+ nested_created_path = empty_window.create_new_markdown_file(nested_item) if nested_item is not None else None
+ if nested_item is None or nested_created_path is None or nested_created_path.parent != nested_root.resolve():
+ checks.append("new_markdown_context_directory")
+ elif empty_window._new_file_rename_item is not None:
+ empty_window._new_file_rename_item.setText(0, "nested-note.md")
+ if not (nested_root / "nested-note.md").exists():
+ checks.append("new_markdown_nested_rename")
+ if empty_window.tree.selectionMode() != QAbstractItemView.SelectionMode.ExtendedSelection:
+ checks.append("tree_multi_selection_mode")
+ empty_window.tree.clearSelection()
+ blank_menu = empty_window._build_tree_context_menu(QPoint(-10, -10))
+ blank_actions = [action.text() for action in blank_menu.actions()]
+ if "删除" in blank_actions or "删除文件夹" in blank_actions or "重命名" in blank_actions:
+ checks.append("tree_blank_context_actions")
+
+ first_path = (switch_root / "first.md").resolve()
+ first_item = empty_window.path_to_item.get(first_path)
+ if first_item is None:
+ checks.append("tree_rename_item_visible")
+ else:
+ empty_window.tree.clearSelection()
+ first_item.setSelected(True)
+ first_menu = empty_window._build_tree_context_menu(
+ empty_window.tree.visualItemRect(first_item).center()
+ )
+ first_actions = [action.text() for action in first_menu.actions()]
+ if "重命名" not in first_actions or "删除" not in first_actions:
+ checks.append("tree_single_file_context_actions")
+ if not empty_window.rename_tree_file(first_item):
+ checks.append("tree_file_rename_start")
+ elif empty_window._new_file_rename_item is not None:
+ empty_window._new_file_rename_item.setText(0, "first-renamed.md")
+ if (switch_root / "first.md").exists() or not (switch_root / "first-renamed.md").exists():
+ checks.append("tree_file_rename_result")
+
+ delete_a = switch_root / "delete-a.md"
+ delete_b = switch_root / "delete-b.md"
+ delete_a.write_text("# Delete A\n", encoding="utf-8")
+ delete_b.write_text("# Delete B\n", encoding="utf-8")
+ empty_window._refresh_document_entries(force=True)
+ empty_window.tree.clearSelection()
+ delete_a_item = empty_window.path_to_item.get(delete_a.resolve())
+ delete_b_item = empty_window.path_to_item.get(delete_b.resolve())
+ if delete_a_item is None or delete_b_item is None:
+ checks.append("tree_delete_items_visible")
+ else:
+ delete_a_item.setSelected(True)
+ delete_b_item.setSelected(True)
+ selected_delete_paths = empty_window._selected_tree_file_paths()
+ if selected_delete_paths != sorted([delete_a.resolve(), delete_b.resolve()], key=lambda path: str(path).casefold()):
+ checks.append("tree_multi_delete_selection")
+ original_question = QMessageBox.question
+ original_move_to_trash = empty_window._move_file_to_trash
+ trashed_paths: list[Path] = []
+
+ def fake_move_to_trash(path: Path) -> bool:
+ trashed_paths.append(path)
+ path.unlink()
+ return True
+
+ QMessageBox.question = lambda *args, **kwargs: QMessageBox.StandardButton.Yes
+ empty_window._move_file_to_trash = fake_move_to_trash
+ try:
+ if not empty_window.delete_selected_tree_files():
+ checks.append("tree_multi_delete_result")
+ finally:
+ QMessageBox.question = original_question
+ empty_window._move_file_to_trash = original_move_to_trash
+ if delete_a.exists() or delete_b.exists() or set(trashed_paths) != {delete_a.resolve(), delete_b.resolve()}:
+ checks.append("tree_multi_delete_files")
+
+ folder_delete_root = switch_root / "folder-delete"
+ folder_delete_root.mkdir(exist_ok=True)
+ (folder_delete_root / "inside.md").write_text("# Delete Folder\n", encoding="utf-8")
+ empty_window._refresh_document_entries(force=True)
+ root_item = empty_window.tree.topLevelItem(0)
+ folder_delete_item = next(
+ (
+ root_item.child(index)
+ for index in range(root_item.childCount())
+ if root_item.child(index).toolTip(0) == str(folder_delete_root)
+ ),
+ None,
+ )
+ if folder_delete_item is None:
+ checks.append("tree_delete_folder_visible")
+ else:
+ folder_menu = empty_window._build_tree_context_menu(
+ empty_window.tree.visualItemRect(folder_delete_item).center()
+ )
+ folder_actions = [action.text() for action in folder_menu.actions()]
+ if "删除文件夹" not in folder_actions or "删除" in folder_actions or "重命名" in folder_actions:
+ checks.append("tree_folder_context_actions")
+ original_question = QMessageBox.question
+ original_move_to_trash = empty_window._move_file_to_trash
+
+ def fake_move_folder_to_trash(path: Path) -> bool:
+ (path / "inside.md").unlink()
+ path.rmdir()
+ return True
+
+ QMessageBox.question = lambda *args, **kwargs: QMessageBox.StandardButton.Yes
+ empty_window._move_file_to_trash = fake_move_folder_to_trash
+ try:
+ if not empty_window.delete_tree_folder(folder_delete_root):
+ checks.append("tree_delete_folder_result")
+ finally:
+ QMessageBox.question = original_question
+ empty_window._move_file_to_trash = original_move_to_trash
+ if folder_delete_root.exists():
+ checks.append("tree_delete_folder_removed")
finally:
- for cleanup_path in (switch_root / "first.md", switch_root / "second.md"):
+ for cleanup_path in (
+ switch_root / "first.md",
+ switch_root / "first-renamed.md",
+ switch_root / "second.md",
+ switch_root / "新建文件.md",
+ switch_root / "renamed-from-tree.md",
+ nested_root / "inside.md",
+ nested_root / "新建文件.md",
+ nested_root / "nested-note.md",
+ switch_root / "delete-a.md",
+ switch_root / "delete-b.md",
+ switch_root / "folder-delete" / "inside.md",
+ ):
cleanup_path.unlink(missing_ok=True)
+ try:
+ (switch_root / "folder-delete").rmdir()
+ except OSError:
+ pass
+ try:
+ nested_root.rmdir()
+ except OSError:
+ pass
try:
switch_root.rmdir()
except OSError:
@@ -209,10 +366,83 @@ def main() -> int:
checks.append("app_icon")
if not isinstance(window.tabs.currentWidget(), ReaderView):
checks.append("reader_view")
- if not window.reader_embedded_toc or window.reader_external_toc or not window.reader_embedded_progress:
- checks.append("reader_navigation_defaults")
- if window.toc_panel.isVisible() or window.reading_progress.isVisible():
- checks.append("reader_navigation_visibility")
+ math_view = ReaderView()
+ math_view.resize(640, 360)
+ math_html = window.renderer.render_source(
+ "正文基准\n\n$$\nx^2+y^2=z^2\n$$\n",
+ project_root / "__math_style_smoke.md",
+ document_font_size=18,
+ document_style_css=".reader p { font-size: 13px; }",
+ )
+ math_load_loop = QEventLoop()
+ math_view.loadFinished.connect(lambda ok: math_load_loop.quit())
+ math_view.setHtml(math_html, QUrl.fromLocalFile(str(project_root.resolve()) + os.sep))
+ math_view.show()
+ QTimer.singleShot(5000, math_load_loop.quit)
+ math_load_loop.exec()
+ math_size_result: dict[str, str] = {}
+ math_size_loop = QEventLoop()
+
+ def store_math_sizes(value: object) -> None:
+ math_size_result["value"] = str(value)
+ math_size_loop.quit()
+
+ math_view.page().runJavaScript(
+ "(() => {"
+ "const paragraph = document.querySelector('.reader > p');"
+ "const block = document.querySelector('.math-block');"
+ "const katex = block?.querySelector('.katex');"
+ "return [paragraph, block, katex].map(element => element ? getComputedStyle(element).fontSize : 'missing').join('|');"
+ "})()",
+ store_math_sizes,
+ )
+ QTimer.singleShot(2000, math_size_loop.quit)
+ math_size_loop.exec()
+ if math_size_result.get("value") != "13px|13px|13px":
+ checks.append(f"katex_font_size_follows_paragraph_style:{math_size_result}")
+
+ mathjax_html = window.renderer.render_source(
+ "正文基准\n\n$$\nx^2+y^2=z^2\n$$\n",
+ project_root / "__mathjax_style_smoke.md",
+ document_font_size=18,
+ document_style_css=".reader p { font-size: 13px; }",
+ math_engine="mathjax",
+ )
+ mathjax_load_loop = QEventLoop()
+ math_view.loadFinished.connect(lambda ok: mathjax_load_loop.quit())
+ math_view.setHtml(mathjax_html, QUrl.fromLocalFile(str(project_root.resolve()) + os.sep))
+ QTimer.singleShot(7000, mathjax_load_loop.quit)
+ mathjax_load_loop.exec()
+ mathjax_typeset_loop = QEventLoop()
+ QTimer.singleShot(1200, mathjax_typeset_loop.quit)
+ mathjax_typeset_loop.exec()
+ mathjax_size_result: dict[str, str] = {}
+ mathjax_size_loop = QEventLoop()
+
+ def store_mathjax_sizes(value: object) -> None:
+ mathjax_size_result["value"] = str(value)
+ mathjax_size_loop.quit()
+
+ math_view.page().runJavaScript(
+ "(() => {"
+ "const paragraph = document.querySelector('.reader > p');"
+ "const block = document.querySelector('.math-block');"
+ "const mathjax = block?.querySelector('mjx-container');"
+ "return [paragraph, block, mathjax].map(element => element ? getComputedStyle(element).fontSize : 'missing').join('|');"
+ "})()",
+ store_mathjax_sizes,
+ )
+ QTimer.singleShot(2000, mathjax_size_loop.quit)
+ mathjax_size_loop.exec()
+ math_view.close()
+ if mathjax_size_result.get("value") != "13px|13px|13px":
+ checks.append(f"mathjax_font_size_follows_paragraph_style:{mathjax_size_result}")
+ if window.navigation_tabs.count() != 2:
+ checks.append("navigation_tabs_count")
+ elif [window.navigation_tabs.tabText(index) for index in range(2)] != ["目录", "大纲"]:
+ checks.append("navigation_tabs_labels")
+ if hasattr(window, "toc_panel") or hasattr(window, "reading_progress"):
+ checks.append("obsolete_navigation_widgets")
if abs(window.wheel_scroll_speed - 1.0) > 0.01:
checks.append("wheel_scroll_speed_default")
window.wheel_scroll_speed = 1.7
@@ -266,9 +496,6 @@ def main() -> int:
font_scale=window.font_scale,
wheel_scroll_speed=1.4,
reader_width_scale=1.5,
- reader_embedded_toc=True,
- reader_external_toc=False,
- reader_embedded_progress=True,
auto_refresh=window.auto_refresh_enabled,
auto_refresh_mode=window.auto_refresh_mode,
auto_refresh_delay_ms=window.auto_refresh_delay_ms,
@@ -288,31 +515,6 @@ def main() -> int:
checks.append("settings_reader_width_scale")
if "fortran" not in prefs.document_file_groups:
checks.append("settings_fortran_file_group")
- if not prefs.reader_embedded_toc or prefs.reader_external_toc or not prefs.reader_embedded_progress:
- checks.append("settings_reader_navigation")
- external_settings_dialog = SettingsDialog(
- AppPreferences(
- theme=window.theme,
- theme_color=window.theme_color,
- theme_background=window.theme_background,
- font_scale=window.font_scale,
- wheel_scroll_speed=window.wheel_scroll_speed,
- reader_width_scale=window.reader_width_scale,
- reader_embedded_toc=False,
- reader_external_toc=True,
- reader_embedded_progress=True,
- auto_refresh=window.auto_refresh_enabled,
- auto_refresh_mode=window.auto_refresh_mode,
- auto_refresh_delay_ms=window.auto_refresh_delay_ms,
- non_preview_action=window.non_preview_action,
- document_file_groups=window.document_file_groups,
- ),
- window,
- )
- external_prefs = external_settings_dialog.preferences()
- if external_prefs.reader_embedded_toc or not external_prefs.reader_external_toc:
- checks.append("settings_external_toc_mode")
- external_settings_dialog.close()
settings_dialog.close()
if window.findChildren(QToolBar):
checks.append("main_toolbar_removed")
@@ -570,7 +772,11 @@ def main() -> int:
checks.append("tree_open_unopened_new_tab")
if window.current_file != (project_root / "docs" / "user_manual.md").resolve():
checks.append("tree_open_unopened_file")
- window._open_tree_item(sample_item)
+ refreshed_sample_item = window.path_to_item.get((project_root / "sample.md").resolve())
+ if refreshed_sample_item is None:
+ checks.append("tree_refreshed_sample_item")
+ else:
+ window._open_tree_item(refreshed_sample_item)
if window.tabs.count() != tree_tab_count + 1:
checks.append("tree_open_existing_no_duplicate")
if window.current_file != (project_root / "sample.md").resolve():
@@ -587,24 +793,19 @@ def main() -> int:
pass
pdf_test_path = project_root / "__gui_smoke_export.pdf"
try:
- pdf_result: dict[str, object] = {}
-
- def on_pdf_finished(file_path: str, success: bool) -> None:
- pdf_result["path"] = file_path
- pdf_result["success"] = success
- pdf_loop.quit()
-
pdf_loop = QEventLoop()
- try:
- window.web_view.page().pdfPrintingFinished.disconnect(window._on_pdf_printing_finished)
- except RuntimeError:
- pass
- window.web_view.page().pdfPrintingFinished.connect(on_pdf_finished)
window.export_pdf_to_path(pdf_test_path)
- QTimer.singleShot(8000, pdf_loop.quit)
+
+ def poll_pdf_export() -> None:
+ if pdf_test_path.exists() or getattr(window, "_pdf_export_page", None) is None:
+ pdf_loop.quit()
+ return
+ QTimer.singleShot(100, poll_pdf_export)
+
+ QTimer.singleShot(100, poll_pdf_export)
+ QTimer.singleShot(15000, pdf_loop.quit)
pdf_loop.exec()
- window.web_view.page().pdfPrintingFinished.connect(window._on_pdf_printing_finished)
- if not pdf_result.get("success") or not pdf_test_path.exists() or pdf_test_path.stat().st_size <= 0:
+ if not pdf_test_path.exists() or pdf_test_path.stat().st_size <= 0:
checks.append("export_pdf_write")
finally:
try:
@@ -781,15 +982,13 @@ def main() -> int:
preview_html = window.renderer.render_source(
dialog.source_text(),
editor_test_path,
- include_reader_toc=True,
- include_reader_progress=False,
)
- if 'class="reader-toc"' not in preview_html or 'data-reader-progress="0"' not in preview_html:
- checks.append("editor_preview_embedded_toc")
- dialog.preview_bridge.openHeading("source-target")
+ if "reader-toc" in preview_html or "reader-progress" in preview_html:
+ checks.append("editor_preview_navigation_chrome")
+ dialog.scroll_to_heading("source-target")
selected_block = dialog.editor.textCursor().block().text()
if "Source Target" not in selected_block:
- checks.append("editor_preview_toc_bridge")
+ checks.append("editor_outline_source_jump")
dialog.editor.setPlainText("alpha beta alpha")
dialog.editor_find_box.setText("alpha")
dialog.find_next_in_editor()
@@ -803,6 +1002,16 @@ def main() -> int:
dialog.insert_template("**{selection}**")
if not dialog.source_text().startswith("**"):
checks.append("editor_insert_template")
+ insert_action_labels = [action.text() for action in dialog.insert_toolbar.actions()]
+ if insert_action_labels[-3:] != ["Mermaid", "公式", "转换latex公式到md"]:
+ checks.append("editor_latex_converter_position")
+ dialog.editor.setPlainText("转换前\n\\[\nx + y\n\\]\n")
+ dialog.convert_latex_formula_action.trigger()
+ if dialog.source_text() != "转换前\n$$\nx + y\n$$\n":
+ checks.append("editor_latex_converter")
+ dialog.editor.undo()
+ if dialog.source_text() != "转换前\n\\[\nx + y\n\\]\n":
+ checks.append("editor_latex_converter_undo")
dialog.close()
window.open_document(editor_test_path, add_history=False)
editor_tab_count = window.tabs.count()
@@ -919,8 +1128,8 @@ def main() -> int:
checks.append("config_wheel_scroll_speed")
if snapshot.get("reader", {}).get("reader_width_scale") is None:
checks.append("config_reader_width_scale")
- if snapshot.get("reader", {}).get("reader_embedded_toc") is None:
- checks.append("config_reader_navigation")
+ if any(key in snapshot.get("reader", {}) for key in ("reader_embedded_toc", "reader_external_toc", "reader_embedded_progress")):
+ checks.append("config_obsolete_reader_navigation")
window._apply_configuration(
{
"reader": {
@@ -930,9 +1139,6 @@ def main() -> int:
"font_scale": 1.2,
"wheel_scroll_speed": 1.8,
"reader_width_scale": 1.75,
- "reader_embedded_toc": True,
- "reader_external_toc": True,
- "reader_embedded_progress": False,
"document_font_family": "Microsoft YaHei UI",
"document_font_size": 18,
"document_tree_label_mode": "filename",
@@ -955,10 +1161,6 @@ def main() -> int:
checks.append("config_apply_wheel_scroll_speed")
if abs(window.reader_width_scale - 1.75) > 0.01:
checks.append("config_apply_reader_width_scale")
- if not window.reader_embedded_toc or window.reader_external_toc or window.reader_embedded_progress:
- checks.append("config_apply_reader_navigation")
- if window.toc_panel.isVisible():
- checks.append("config_apply_external_toc_hidden")
if window.document_tree_label_mode != "filename":
checks.append("config_apply_tree_label_mode")
if window.ui_font_family != "Microsoft YaHei UI" or window.ui_font_point_size != 10:
diff --git a/tests/pdf_export_smoke.py b/tests/pdf_export_smoke.py
new file mode 100644
index 0000000..7ea0f94
--- /dev/null
+++ b/tests/pdf_export_smoke.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import os
+import sys
+import tempfile
+from pathlib import Path
+
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+os.environ.setdefault(
+ "QTWEBENGINE_CHROMIUM_FLAGS",
+ "--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --no-sandbox --log-level=3",
+)
+os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(PROJECT_ROOT))
+
+from PySide6.QtCore import QSettings, QTimer
+from PySide6.QtWidgets import QApplication, QMessageBox
+
+from mdhelper.main_window import MainWindow
+from mdhelper.pdf_export import PdfMargins
+
+
+def main() -> int:
+ isolated_settings = tempfile.TemporaryDirectory(prefix="mdhelper-pdf-smoke-")
+ QSettings.setDefaultFormat(QSettings.Format.IniFormat)
+ QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, isolated_settings.name)
+ output_path = Path(sys.argv[1] if len(sys.argv) > 1 else PROJECT_ROOT / "tmp" / "pdfs" / "pdf_export_smoke.pdf")
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ output_path.unlink(missing_ok=True)
+
+ app = QApplication.instance() or QApplication([sys.argv[0]])
+ settings = QSettings("MDHelper", "MDHelper-PdfExportSmoke")
+ settings.clear()
+ warnings: list[str] = []
+ original_warning = QMessageBox.warning
+ QMessageBox.warning = staticmethod(lambda _parent, _title, message, *_args: warnings.append(str(message)))
+
+ window = MainWindow(project_root=PROJECT_ROOT, initial_path=PROJECT_ROOT / "sample.md")
+ window.settings = settings
+ original_probe_handler = window._on_pdf_probe_ready
+
+ def capture_probe(pdf_data: object) -> None:
+ output_path.with_suffix(".probe.pdf").write_bytes(bytes(pdf_data))
+ original_probe_handler(pdf_data)
+
+ window._on_pdf_probe_ready = capture_probe
+ timeout_ticks = 0
+
+ def start_export() -> None:
+ window.export_pdf_to_path(output_path, PdfMargins(top=15, bottom=15, left=15, right=15))
+ poll_export()
+
+ def poll_export() -> None:
+ nonlocal timeout_ticks
+ timeout_ticks += 1
+ if output_path.exists() and output_path.stat().st_size > 0 and getattr(window, "_pdf_export_page", None) is None:
+ app.exit(0)
+ return
+ if warnings or timeout_ticks >= 300:
+ for warning in warnings:
+ print(warning, file=sys.stderr)
+ app.exit(1)
+ return
+ QTimer.singleShot(100, poll_export)
+
+ QTimer.singleShot(0, start_export)
+ exit_code = app.exec()
+ QMessageBox.warning = original_warning
+ window.close()
+ return exit_code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_app.py b/tests/test_app.py
index 4392fb7..0c2123e 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -1,12 +1,13 @@
from __future__ import annotations
import zipfile
-import shutil
from pathlib import Path
from mdhelper.app import parse_arguments, project_and_initial_path, resolve_launch_path
-from mdhelper.docx_exporter import export_markdown_to_docx
+from mdhelper.main_window import available_new_markdown_path
+from mdhelper.docx_exporter import export_markdown_to_docx, resolve_pandoc_executable
from mdhelper.logging_config import setup_logging
+from mdhelper.markdown_editor import convert_latex_display_delimiters
def test_parse_arguments_accepts_folder_alias() -> None:
@@ -45,6 +46,23 @@ def test_project_and_initial_path_uses_folder_directly(tmp_path: Path) -> None:
assert initial_path is None
+def test_convert_latex_display_delimiters_to_markdown() -> None:
+ source = "正文\n\\[\nx^2 + y^2 = z^2\n\\]\n行内公式 $x$ 保持不变\n"
+
+ converted, replacement_count = convert_latex_display_delimiters(source)
+
+ assert converted == "正文\n$$\nx^2 + y^2 = z^2\n$$\n行内公式 $x$ 保持不变\n"
+ assert replacement_count == 2
+
+
+def test_available_new_markdown_path_avoids_existing_names(tmp_path: Path) -> None:
+ assert available_new_markdown_path(tmp_path).name == "新建文件.md"
+ (tmp_path / "新建文件.md").write_text("", encoding="utf-8")
+ (tmp_path / "新建文件 (2).md").write_text("", encoding="utf-8")
+
+ assert available_new_markdown_path(tmp_path).name == "新建文件 (3).md"
+
+
def test_export_markdown_to_docx_writes_word_document(tmp_path: Path) -> None:
output_path = tmp_path / "guide.docx"
@@ -76,9 +94,15 @@ def test_export_markdown_to_docx_python_docx_engine(tmp_path: Path) -> None:
assert "标题" in document_xml
-def test_export_markdown_to_docx_pandoc_engine_when_available(tmp_path: Path) -> None:
- if shutil.which("pandoc") is None:
- return
+def test_resolve_pandoc_executable_uses_bundled_copy() -> None:
+ pandoc_path = resolve_pandoc_executable()
+
+ assert pandoc_path is not None
+ assert pandoc_path.name == "pandoc.exe"
+ assert pandoc_path.parent.name == "pandoc"
+
+
+def test_export_markdown_to_docx_pandoc_engine(tmp_path: Path) -> None:
output_path = tmp_path / "pandoc.docx"
source_path = tmp_path / "source.md"
source_path.write_text("# 标题\n\n正文\n", encoding="utf-8")
diff --git a/tests/test_renderer.py b/tests/test_renderer.py
index 4162a9b..c9377d3 100644
--- a/tests/test_renderer.py
+++ b/tests/test_renderer.py
@@ -1,6 +1,8 @@
from pathlib import Path
from tempfile import TemporaryDirectory
+from PySide6.QtGui import QPageLayout
+
from mdhelper.app import parse_arguments
from mdhelper import search as search_module
from mdhelper.doc_check import check_documents
@@ -10,6 +12,7 @@ from mdhelper.history import HistoryItem, NavigationHistory
from mdhelper.main_window import re_find_markdown_links
from mdhelper.markdown_utils import extract_headings
from mdhelper.markdown_renderer import MarkdownRenderer
+from mdhelper.pdf_export import PdfMargins, build_pdf_export_html, build_pdf_page_layout
from mdhelper.search import SearchIndex, search_entries
from mdhelper.style_dialog import build_document_style_css
@@ -69,11 +72,21 @@ def test_sample_media_and_code_rendering() -> None:
assert "data-math-engine=\"katex\"" in html
assert "data-wheel-scroll-speed=\"1.0\"" in html
assert "configuredWheelSpeed" in html
+ assert "VISUAL_SCROLL_INTERVAL" not in html
+ assert "scheduleScrollEndUpdate" not in html
+ assert "headingElements" not in html
+ assert "backdrop-filter" not in html
assert "--reader-font-family:" in html
assert "--reader-font-size:" in html
assert "--reader-paper-width: 794px;" in html
assert "katex.min.css" in html
assert "auto-render.min.js" in html
+ assert ".math-block .katex" in html
+ assert ".math-display mjx-container" in html
+ assert ".math-inline .katex" in html
+ assert ".math-inline mjx-container" in html
+ assert "--reader-math-font-size: var(--reader-font-size);" in html
+ assert "syncMathFontSize" in html
assert "window.mermaid" in html
assert "mermaid.min.js" in html
assert "qrc:///qtwebchannel/qwebchannel.js" in html
@@ -102,27 +115,120 @@ def test_sample_media_and_code_rendering() -> None:
assert ".reader { max-width: 720px; }" in custom_style_html
+def test_plain_document_omits_optional_runtime_assets(tmp_path: Path) -> None:
+ renderer = MarkdownRenderer(tmp_path)
+ rendered = renderer.render_source("# Plain\n\nNo formula or diagram.", tmp_path / "plain.md")
+ assert "mermaid.min.js" not in rendered
+ assert "katex.min.js" not in rendered
+ assert "tex-svg-full.js" not in rendered
-def test_reader_chrome_can_be_embedded_in_html() -> None:
+
+def test_formula_and_diagram_load_independently(tmp_path: Path) -> None:
+ renderer = MarkdownRenderer(tmp_path)
+ formula = renderer.render_source("Formula $x^2$.", tmp_path / "formula.md")
+ assert "katex.min.js" in formula
+ assert "mermaid.min.js" not in formula
+ diagram = renderer.render_source("```mermaid\ngraph LR\nA-->B\n```", tmp_path / "diagram.md")
+ assert "mermaid.min.js" in diagram
+ assert "katex.min.js" not in diagram
+ mathjax = renderer.render_source(r"Formula \(x^2\).", tmp_path / "math.md", math_engine="mathjax")
+ assert "tex-svg-full.js" in mathjax
+ assert "katex.min.js" not in mathjax
+
+
+def test_latex_math_is_protected_from_markdown_emphasis(tmp_path: Path) -> None:
+ renderer = MarkdownRenderer(tmp_path)
+ source = r"""普通强调 _仍然生效_,行内公式 $\widehat{\nabla_0W}^{(i)}_{0ij}$ 不应变成斜体。
+
+$$
+\mathbf g^{\mathrm{raw}}_{ij}
+=\nabla_{\boldsymbol\xi_i}W_{0ij}
+=-\nabla_{\boldsymbol\xi_{ij}}W(\boldsymbol\xi_{ij},h_s)
+\in\mathbb R^2.
+$$
+"""
+
+ rendered = renderer.markdown.render(source)
+
+ assert "仍然生效" in rendered
+ assert '$\\widehat{\\nabla_0W}^{(i)}_{0ij}$' in rendered
+ assert '$$' in rendered
+ assert "\\mathbf g^{\\mathrm{raw}}_{ij}" in rendered
+ assert "\\nabla_{\\boldsymbol\\xi_i}W_{0ij}" in rendered
+ assert "
{ij}" not in rendered
+ assert "{0ij}" not in rendered
+
+
+def test_parenthesized_latex_math_is_protected_from_markdown_escapes(tmp_path: Path) -> None:
+ renderer = MarkdownRenderer(tmp_path)
+
+ rendered = renderer.markdown.render(
+ r"""公式 \(\mathbf g^{c}_{0ij}\) 正常。
+
+\[
+\mathbf H_i=\sum_j \mathbf g^{\mathrm{raw}}_{ij}
+\]
+
+同一行展示公式 $$\mathbf L_i=\mathbf H_i^{-1}$$ 正常。
+"""
+ )
+
+ assert '\\(\\mathbf g^{c}_{0ij}\\)' in rendered
+ assert '\\[' in rendered
+ assert "\\mathbf H_i=\\sum_j \\mathbf g^{\\mathrm{raw}}_{ij}" in rendered
+ assert '$$\\mathbf L_i=\\mathbf H_i^{-1}$$' in rendered
+ assert "" not in rendered
+
+
+
+def test_reader_html_excludes_outline_and_progress_chrome() -> None:
project_root = Path(__file__).resolve().parent.parent
renderer = MarkdownRenderer(project_root)
- html = renderer.render_file(
- project_root / "sample.md",
- include_reader_toc=True,
- include_reader_progress=True,
- )
+ html = renderer.render_file(project_root / "sample.md")
+
+ assert 'class="reader-shell"' in html
+ assert 'id="mdhelper-reader"' in html
+ assert "reader-toc" not in html
+ assert "reader-progress" not in html
+ assert "data-reader-toc" not in html
+ assert "data-reader-progress" not in html
+ assert "reportScroll" not in html
+
+
+def test_pdf_page_layout_uses_configured_margins() -> None:
+ configured = PdfMargins(top=12.0, bottom=18.0, left=20.0, right=16.0)
+ layout = build_pdf_page_layout(configured)
+ margins = layout.margins(QPageLayout.Unit.Millimeter)
+
+ assert margins.left() == configured.left
+ assert margins.right() == configured.right
+ assert margins.top() == configured.top
+ assert margins.bottom() == configured.bottom
+
+
+def test_pdf_export_html_has_numbered_toc_white_background_and_page_break() -> None:
+ project_root = Path(__file__).resolve().parent.parent
+ renderer = MarkdownRenderer(project_root)
+ headings = extract_headings(project_root / "sample.md")
+ html = renderer.render_file(project_root / "sample.md")
+
+ exported = build_pdf_export_html(html, headings, {index: index + 2 for index in range(len(headings))})
+
+ assert 'class="pdf-toc' in exported
+ assert 'class="reader-toc"' not in exported
+ assert 'class="reader-progress"' not in exported
+ assert "break-after: page" in exported
+ assert "background: #ffffff !important" in exported
+ assert "MDHELPER_PDF_BODY_START_7A61" in exported
+ assert "MDHELPER_PDF_HEADING_0000" in exported
+ assert '2' in exported
+
+ final_export = build_pdf_export_html(html, headings, {0: 2}, include_page_markers=False)
+ assert "MDHELPER_PDF_BODY_START_7A61" not in final_export
+ assert "MDHELPER_PDF_HEADING_0000" not in final_export
+
- assert 'data-reader-toc="1"' in html
- assert 'data-reader-progress="1"' in html
- assert 'class="reader-toc"' in html
- assert 'class="reader-progress"' in html
- assert 'data-toc-target="2-表格示例"' in html
- assert "reader-toc__link" in html
- assert "grid-template-columns: minmax(0, var(--reader-paper-width)) minmax(190px, 240px);" in html
- assert ".reader-shell.has-reader-toc .reader" in html
- assert "grid-column: 1;" in html
- assert "grid-column: 2;" in html
def test_heading_extraction_matches_rendered_anchor() -> None:
project_root = Path(__file__).resolve().parent.parent
headings = extract_headings(project_root / "sample.md")
@@ -160,6 +266,7 @@ def test_document_style_builder_supports_word_like_paragraph_options() -> None:
)
assert ".reader p" in css
+ assert "--reader-math-font-size: 18px;" in css
assert 'font-family: "Times New Roman", "Microsoft YaHei UI"' in css
assert "font-size: 18px;" in css
assert "line-height: 1.7;" in css
diff --git a/tests/test_startup.py b/tests/test_startup.py
new file mode 100644
index 0000000..8edb33c
--- /dev/null
+++ b/tests/test_startup.py
@@ -0,0 +1,116 @@
+from __future__ import annotations
+
+import os
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+
+import threading
+import time
+from pathlib import Path
+
+import pytest
+from PySide6.QtCore import QSettings, QThreadPool
+from PySide6.QtWidgets import QApplication, QTextBrowser
+
+from mdhelper import main_window, startup_scan
+
+
+@pytest.fixture
+def gui(tmp_path, monkeypatch):
+ app = QApplication.instance() or QApplication([])
+ monkeypatch.setattr(main_window, "QSettings", lambda *_: QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat))
+ yield app
+ app.processEvents()
+
+
+def wait_until(app, condition, seconds=8):
+ deadline = time.monotonic() + seconds
+ while not condition() and time.monotonic() < deadline:
+ app.processEvents()
+ time.sleep(0.005)
+ assert condition(), "Timed out waiting for the background directory scan"
+
+
+def test_welcome_does_not_create_browser_process(gui, tmp_path, monkeypatch):
+ def unexpected_browser(_):
+ pytest.fail("Welcome page must not initialize WebEngine")
+ monkeypatch.setattr(main_window.MainWindow, "_create_reader_view", unexpected_browser)
+ window = main_window.MainWindow(None, app_root=tmp_path)
+ try:
+ assert isinstance(window.tabs.currentWidget(), QTextBrowser)
+ assert window.web_view is None
+ monkeypatch.setattr(window, "_welcome_html", lambda: "Updated welcome
")
+ window.refresh_all_tab_appearances()
+ assert "Updated welcome" in window.tabs.currentWidget().toPlainText()
+ finally:
+ window.close()
+
+
+def test_directory_scan_does_not_block_first_window(gui, tmp_path, monkeypatch):
+ (tmp_path / "guide.md").write_text("# Guide\n", encoding="utf-8")
+ entered, release = threading.Event(), threading.Event()
+ original = startup_scan.discover_documents
+ def slow_scan(*args):
+ entered.set()
+ if not release.wait(8):
+ raise TimeoutError("Test did not release scanner")
+ return original(*args)
+ monkeypatch.setattr(startup_scan, "discover_documents", slow_scan)
+ window = main_window.MainWindow(tmp_path, defer_startup=True)
+ try:
+ assert not entered.is_set()
+ assert window.entries == []
+ window.show()
+ wait_until(gui, entered.is_set)
+ assert window.isVisible()
+ assert window._startup_scan_pending
+ window.search_box.setText("Guide")
+ gui.processEvents()
+ release.set()
+ wait_until(gui, lambda: not window._startup_scan_pending)
+ assert [entry.title for entry in window.entries] == ["Guide"]
+ assert window.search_index.search("Guide")
+ finally:
+ release.set()
+ QThreadPool.globalInstance().waitForDone(10000)
+ window.close()
+
+
+def test_switching_projects_discards_old_scan(gui, tmp_path, monkeypatch):
+ old_root, new_root = tmp_path / "old", tmp_path / "new"
+ old_root.mkdir()
+ new_root.mkdir()
+ (old_root / "old.md").write_text("# Old\n", encoding="utf-8")
+ (new_root / "new.md").write_text("# New\n", encoding="utf-8")
+ entered, release = threading.Event(), threading.Event()
+ original = startup_scan.discover_documents
+ def slow_scan(*args):
+ entered.set()
+ release.wait(8)
+ return original(*args)
+ monkeypatch.setattr(startup_scan, "discover_documents", slow_scan)
+ window = main_window.MainWindow(old_root, defer_startup=True)
+ try:
+ wait_until(gui, entered.is_set)
+ window.set_project_root(new_root, save=False)
+ release.set()
+ QThreadPool.globalInstance().waitForDone(10000)
+ gui.processEvents()
+ assert window.project_root == new_root.resolve()
+ assert [entry.title for entry in window.entries] == ["New"]
+ finally:
+ release.set()
+ QThreadPool.globalInstance().waitForDone(10000)
+ window.close()
+
+
+def test_closing_project_cancels_queued_startup(gui, tmp_path):
+ initial = tmp_path / "guide.md"
+ initial.write_text("# Guide\n", encoding="utf-8")
+ window = main_window.MainWindow(tmp_path, initial_path=initial, defer_startup=True)
+ try:
+ window.close_project_folder()
+ gui.processEvents()
+ assert not window.has_project
+ assert window.current_file is None
+ finally:
+ window.close()
diff --git a/todo.md b/todo.md
index 27c8974..625e0c3 100644
--- a/todo.md
+++ b/todo.md
@@ -1,38 +1,32 @@
# MDHelper TODO
-## 0. 版本 0.2.0:阅读体验重构
+## 0. 阅读导航精简
-目标:减少阅读滚动时的 Qt 控件同步和 WebChannel 往返,把当前文档大纲和阅读进度逐步迁移到 HTML 阅读页内部,让阅读模式更接近浏览器打开网页的流畅度。
+目标:左侧在文件目录和文档大纲之间切换;删除阅读进度和网页内大纲,使正文滚动不再触发标题定位或界面同步。
文档与版本:
- [x] 将应用版本号更新为 `0.2.0`。
- [x] 更新 README,说明当前渲染路径、现有能力和 0.2.0 主线目标。
-- [x] 更新设计文档,明确当前 Qt 外部目录/进度方案和 0.2.0 网页内目录/进度方案。
+- [x] 更新设计文档,明确左侧目录/大纲切换和静态大纲方案。
- [x] 在 TODO 中建立 0.2.0 任务清单。
实现任务:
- [x] 梳理阅读模式和编辑模式中目录、进度、滚动位置保存的边界。
-- [x] 在 `MarkdownRenderer` 中输出标题元数据,减少主窗口和前端重复提取标题。
-- [x] 增加阅读页 HTML 外壳:正文区、网页内大纲、网页内阅读进度条。
-- [x] 在 `reader.css` 中实现网页内大纲和进度条样式,支持浅色、深色和彩色主题。
-- [x] 在 `reader.js` 中实现网页内目录点击跳转、滚动高亮和阅读进度更新。
-- [x] 阅读模式默认关闭或弱化外部 Qt 右侧目录树和状态栏进度条同步。
-- [x] WebChannel 滚动上报改为低频保存滚动位置,不参与每次视觉更新。
-- [x] 增加设置项:显示网页内大纲、显示外部目录栏、显示网页内进度条。
-- [x] 编辑模式保留源码目录定位;预览内目录点击通过离散事件回传到编辑器定位源码标题。
-- [x] 区分阅读 HTML 和导出 HTML,避免导出文档默认包含阅读进度条。
-- [x] 补充单元测试和 GUI smoke,覆盖网页内目录、进度条、主题切换、编辑模式定位。
+- [x] 删除状态栏和网页内阅读进度条。
+- [x] 删除网页内大纲及其 CSS、JS 和编辑预览桥接。
+- [x] 删除滚动时的进度计算、当前标题定位和 WebChannel 上报。
+- [x] 将文件目录和当前文档大纲合并为左侧两个切换页签。
+- [x] 大纲只在用户点击标题时执行跳转,不随滚动更新选中项。
+- [x] 保留低频滚动坐标保存,用于恢复阅读位置。
+- [x] 补充单元测试和 GUI smoke,覆盖左侧切换和无页面导航装饰的 HTML。
风险与注意事项:
-- [x] 网页内大纲会占用阅读宽度,窄窗口下需要自动折叠或隐藏。
-- [x] 大文档标题很多时,大纲 DOM 和滚动高亮要避免造成新的卡顿。
-- [x] 编辑模式不能丢失源码目录和标题定位能力,不能简单复用阅读模式目录逻辑。
-- [x] 导出 HTML/PDF/DOCX/MHTML 时需要明确是否包含目录,阅读进度条通常不应导出。
-- [x] WebEngine 滚动流畅度仍受页面复杂度影响,Mermaid、公式、大图片和超长代码块仍需单独优化。(已增加低频同步、网页内高亮、超长代码块降级、超长代码默认折叠、图片异步解码和重型块 content-visibility;后续如仍卡顿再做虚拟化专项。)
-- [x] 保留外部目录栏和网页内目录时,要避免两个目录高亮状态互相竞争。
+- [x] 编辑模式保留源码目录和标题定位能力。
+- [x] 大纲只在打开、切换或编辑内容变化时重建,不参与正文滚动。
+- [x] WebEngine 滚动流畅度仍受 Mermaid、公式、大图片和超长代码块影响,保留现有异步解码和重型块优化。
## 1. Markdown 编辑功能
diff --git a/vendor/pandoc/COPYING.rtf b/vendor/pandoc/COPYING.rtf
new file mode 100644
index 0000000..1b9532d
--- /dev/null
+++ b/vendor/pandoc/COPYING.rtf
@@ -0,0 +1,92 @@
+{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 \fmodern Courier;}}
+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
+\widowctrl\hyphauto
+
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 GNU GENERAL PUBLIC LICENSE\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Version 2, June 1991\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Copyright (C) 1989, 1991 Free Software Foundation, Inc. \line
+\line
+\line
+Everyone is permitted to copy and distribute verbatim copies\line
+of this license document, but changing it is not allowed.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 Preamble\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software\u8211-to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation\u8217's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Also, for each author\u8217's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors\u8217' reputations.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone\u8217's free use or not licensed at all.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 The precise terms and conditions for copying, distribution and modification follow.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 0.} This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The \u8220"Program\u8221", below, refers to any such program or work, and a \u8220"work based on the Program\u8221" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term \u8220"modification\u8221".) Each licensee is addressed as \u8220"you\u8221".\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 1.} You may copy and distribute verbatim copies of the Program\u8217's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 2.} You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b a)} You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b b)} You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b c)} If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 3.} You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b a)} Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b b)} Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b c)} Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 4.} You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 5.} You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 6.} Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients\u8217' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 7.} If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 8.} If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 9.} The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and \u8220"any later version\u8221", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 10.} If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b NO WARRANTY}\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 11.} BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \u8220"AS IS\u8221" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 {\b 12.} IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 END OF TERMS AND CONDITIONS\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel2 \b \fs28 How to Apply These Terms to Your New Programs\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the \u8220"copyright\u8221" line and a pointer to where the full notice is found.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \f1 one line to give the program's name and an idea of what it does.\line
+Copyright (C) yyyy name of author\line
+\line
+This program is free software; you can redistribute it and/or\line
+modify it under the terms of the GNU General Public License\line
+as published by the Free Software Foundation; either version 2\line
+of the License, or (at your option) any later version.\line
+\line
+This program is distributed in the hope that it will be useful,\line
+but WITHOUT ANY WARRANTY; without even the implied warranty of\line
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\line
+GNU General Public License for more details.\line
+\line
+You should have received a copy of the GNU General Public License along\line
+with this program; if not, see .\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 Also add information on how to contact you by electronic and paper mail.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 If the program is interactive, make it output a short notice like this when it starts in an interactive mode:\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Gnomovision version 69, Copyright (C) year name of author\line
+Gnomovision comes with ABSOLUTELY NO WARRANTY; for details\line
+type `show w'. This is free software, and you are welcome\line
+to redistribute it under certain conditions; type `show c' \line
+for details.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 The hypothetical commands `show w\u8217' and `show c\u8217' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w\u8217' and `show c\u8217'; they could even be mouse-clicks or menu items\u8211-whatever suits your program.\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 You should also get your employer (if you work as a programmer) or your school, if any, to sign a \u8220"copyright disclaimer\u8221" for the program, if necessary. Here is a sample; alter the names:\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Yoyodyne, Inc., hereby disclaims all copyright\line
+interest in the program `Gnomovision'\line
+(which makes passes at compilers) written \line
+by James Hacker.\line
+\line
+signature of Ty Coon, 1 April 1989\line
+Ty Coon, President of Vice\par}
+{\pard \ql \f0 \sa180 \li0 \fi0 This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the {\field{\*\fldinst{HYPERLINK "https://www.gnu.org/licenses/lgpl.html"}}{\fldrslt{\ul
+GNU Lesser General Public License
+}}}
+ instead of this License.\par}
+}
diff --git a/vendor/pandoc/COPYRIGHT.txt b/vendor/pandoc/COPYRIGHT.txt
new file mode 100644
index 0000000..2cff18a
--- /dev/null
+++ b/vendor/pandoc/COPYRIGHT.txt
@@ -0,0 +1,225 @@
+Pandoc
+Copyright (C) 2006-2024 John MacFarlane
+
+With the exceptions noted below, this code is released under the [GPL],
+version 2 or later:
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, see .
+
+The GNU General Public License is available in the file COPYING.md in
+the source distribution. On Debian systems, the complete text of the
+GPL can be found in `/usr/share/common-licenses/GPL`.
+
+[GPL]: https://www.gnu.org/copyleft/gpl.html
+
+The complete source code for pandoc version X.Y.Z is available at
+
+and at .
+
+Pandoc includes some code with different copyrights, or subject to different
+licenses. The copyright and license statements for these sources are included
+below. All are GPL-compatible licenses.
+
+----------------------------------------------------------------------
+The modules in the `pandoc-types` repository (Text.Pandoc.Definition,
+Text.Pandoc.Builder, Text.Pandoc.Generics, Text.Pandoc.JSON,
+Text.Pandoc.Walk) are licensed under the BSD 3-clause license:
+
+Copyright (c) 2006-2024, John MacFarlane
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of John MacFarlane nor the names of other
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+Pandoc's templates (in `data/templates`) are dual-licensed as either
+GPL (v2 or higher, same as pandoc) or (at your option) the BSD
+3-clause license.
+
+Copyright (c) 2014--2024, John MacFarlane
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Writers/Muse.hs
+Copyright (C) 2017-2020 Alexander Krotov
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Writers/Texinfo.hs
+Copyright (C) 2008-2024 John MacFarlane and Peter Wang
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Writers/OpenDocument.hs
+Copyright (C) 2008-2024 Andrea Rossato and John MacFarlane
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Writers/Org.hs
+Copyright (C) 2010-2024 Puneeth Chaganti, John MacFarlane, and
+ Albert Krewinkel
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Writers/ZimWiki.hs
+Copyright (C) 2017 Alex Ivkin
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/Docx.hs
+src/Text/Pandoc/Readers/Docx/*
+Copyright (C) 2014-2020 Jesse Rosenthal
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/Textile.hs
+Copyright (C) 2010-2024 Paul Rivier and John MacFarlane
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/TikiWiki.hs
+Copyright (C) 2017 Robin Lee Powell
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/JATS.hs
+Copyright (C) 2017-2018 Hamish Mackenzie
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/EPUB.hs
+Copyright (C) 2014-2024 Matthew Pickering and John MacFarlane
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/Org.hs
+src/Text/Pandoc/Readers/Org/*
+test/Tests/Readers/Org/*
+Copyright (C) 2014-2024 Albert Krewinkel
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+pandoc-lua-engine/src/Text/Pandoc/Lua.hs
+pandoc-lua-engine/src/Text/Pandoc/Lua/*
+pandoc-lua-engine/test/lua/*
+Copyright (C) 2017--2024 Albert Krewinkel and John MacFarlane
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/Jira.hs
+src/Text/Pandoc/Writers/Jira.hs
+test/Tests/Readers/Jira.hs
+Copyright (C) 2019--2024 Albert Krewinkel
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/FB2.hs
+Copyright (C) 2018--2019 Alexander Krotov
+
+Released under the GNU General Public License version 2 or later.
+
+----------------------------------------------------------------------
+The dzslides template contains JavaScript and CSS from Paul Rouget's
+dzslides template.
+https://github.com/paulrouget/dzslides
+
+Released under the Do What the Fuck You Want To Public License.
+
+------------------------------------------------------------------------
+Pandoc embeds a Lua interpreter (via hslua).
+
+Copyright © 1994--2023 Lua.org, PUC-Rio.
+
+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.
+
+------------------------------------------------------------------------
+Some of the code in wasm/pandoc.js and the patches in wasm/patches is
+from https://github.com/haskell-wasm/pandoc-wasm. It is released under
+this license:
+
+MIT License
+
+Copyright (c) Tweag I/O Limited.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/pandoc/README.md b/vendor/pandoc/README.md
new file mode 100644
index 0000000..69ec472
--- /dev/null
+++ b/vendor/pandoc/README.md
@@ -0,0 +1,8 @@
+# Bundled Pandoc
+
+MDHelper bundles Pandoc 3.9.0.2 for Windows x86-64 so DOCX export does not depend on a user-installed executable or `PATH` configuration.
+
+- Upstream: https://github.com/jgm/pandoc
+- Release archive: `pandoc-3.9.0.2-windows-x86_64.zip`
+- Release SHA-256: `c97542f2800f446e788d9f74237856d995421ad1bb3cc8324286840c5f272d3a`
+- Included license notices: `COPYING.rtf` and `COPYRIGHT.txt`
diff --git a/vendor/pandoc/pandoc.exe b/vendor/pandoc/pandoc.exe
new file mode 100644
index 0000000..106d1ed
--- /dev/null
+++ b/vendor/pandoc/pandoc.exe
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e83f8354c0f507222b5684797b9c5ae766f03889785995d14aac27816ec456ba
+size 231056136