fix: restore only the directory at startup and load tabs on request

This commit is contained in:
2026-11-05 14:59:37 +08:00
parent 750f11cf2c
commit a3bef33988
5 changed files with 144 additions and 61 deletions
+1 -1
View File
@@ -75,7 +75,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构
## 项目设置与批量导出
- 工作现场在正常退出或切换项目时保存;未保存内容仍由原有草稿恢复流程保护。指定启动文件时优先打开该文件。
- 普通启动只恢复上次的目录,不自动打开文件或历史文档标签。工作现场在有文档打开时保存,可通过“文件 → 恢复上次打开的标签”手动恢复;未保存内容仍由原有草稿恢复流程保护。明确指定启动文件时打开该文件。
- 启用“以当前设置启用项目默认”后,字体、段落和页面修改自动保存在当前项目;未启用的项目使用全局默认。模板是独立副本,修改一个项目不会改动其他项目。
- 样式预设 JSON 包含字体、核心样式/高级 CSS 和页面设置,不包含项目路径、书签或草稿。高级 CSS 在 Word 中仍受其排版能力限制,导出前会提示不支持的效果。
- 批量导出使用当前编辑内容;分别导出时文件名带顺序编号。全部转换成功后才发布输出,目标文件在导出期间发生变化会停止替换。
+1 -1
View File
@@ -335,7 +335,7 @@ MDHelper 会保存:
# 0.4 新增工作流
- **恢复工作现场**:正常退出后,再次打开同一文件夹会恢复标签顺序、当前文档、编辑模式和分屏状态。后台标签在点击时加载;可在“文件 → 启动时恢复工作现场”中关闭。未保存草稿仍按原有方式提示恢复。
- **启动与历史标签**:普通启动只恢复上次打开的文件夹,不自动打开其中的文件,也不恢复文档标签。需要历史标签时,可在没有打开文档的情况下选择“文件 → 恢复上次打开的标签”,手动恢复标签顺序、当前文档、编辑模式和分屏状态;后台标签在点击时加载。只打开文件夹后退出不会清除历史标签。未保存草稿仍按原有方式提示恢复;通过文件关联或启动参数明确指定的文件仍会正常打开。
- **文档检查**:在“工具 → 检查文档链接与图片”中扫描当前项目,检查本地链接、图片和章节锚点。检查使用当前编辑内容,双击结果可定位 Markdown 编辑行或查看 HTML 源码。
- **安全重命名**:在文件树重命名时,若存在需要同步修改的引用,会显示差异预览。确认后统一保存这些修改,并更新标签、最近文件和书签。备份位于本地应用数据目录的 `MDHelper/rename-backups`。
+44 -46
View File
@@ -143,7 +143,6 @@ class MainWindow(QMainWindow):
self._startup_prompt = prompt_for_project
self.settings = QSettings("MDHelper", "MDHelper")
self.workspaces = WorkspaceStore(self.settings)
self._workspace_restored = False
self._restoring_workspace = False
self.configurations = ConfigurationStore(self.settings)
self.documents = DocumentStore()
@@ -401,10 +400,8 @@ class MainWindow(QMainWindow):
file_menu.addSeparator()
file_menu.addAction(self.clear_recent_action)
self.restore_workspace_action = QAction("启动时恢复工作现场", self)
self.restore_workspace_action.setCheckable(True)
self.restore_workspace_action.setChecked(self.settings.value("workspace/restore", True, type=bool))
self.restore_workspace_action.toggled.connect(lambda enabled: self.settings.setValue("workspace/restore", enabled))
self.restore_workspace_action = QAction("恢复上次打开的标签", self)
self.restore_workspace_action.triggered.connect(self._restore_workspace)
file_menu.addAction(self.restore_workspace_action)
self.exit_action = QAction("退出", self)
@@ -844,19 +841,9 @@ class MainWindow(QMainWindow):
LOGGER.debug("Reader prewarm requested")
def prepare_reader_before_show(self, timeout_ms: int = 8000) -> None:
# Preparing a fixed reader host prevents startup flicker; it must not
# open historical documents. Tab restoration is an explicit menu action.
self._prepare_reader_before_show(timeout_ms)
if not self.isVisible() and not self._workspace_restored and self._startup_initial_path is None:
self._restore_workspace()
editor = self.tabs.currentWidget()
if isinstance(editor, RichMarkdownEditorDialog) and editor.preview.page().isLoading():
loop, deadline = QEventLoop(self), QTimer(self)
deadline.setSingleShot(True)
deadline.timeout.connect(loop.quit)
editor.preview.loadFinished.connect(loop.quit)
deadline.start(timeout_ms)
loop.exec()
deadline.stop()
editor.preview.loadFinished.disconnect(loop.quit)
def _prepare_reader_before_show(self, timeout_ms: int = 8000) -> None:
if self.isVisible():
@@ -1955,7 +1942,7 @@ class MainWindow(QMainWindow):
if not self._close_all_tabs(show_welcome=False):
return
if self.has_project:
if self.has_project and snapshot[0]:
self.workspaces.save(self.project_root, *snapshot)
self._save_preferences()
@@ -2014,7 +2001,7 @@ class MainWindow(QMainWindow):
snapshot = self._workspace_snapshot() if root_changed else None
if root_changed and not self._close_all_tabs(show_welcome=False):
return False
if snapshot is not None:
if snapshot is not None and snapshot[0]:
self.workspaces.save(self.project_root, *snapshot)
if root_changed or not self.has_project:
@@ -4002,6 +3989,7 @@ class MainWindow(QMainWindow):
editor.setFocus()
def _update_actions(self) -> None:
self.restore_workspace_action.setEnabled(self.has_project and not self._has_open_content_tabs())
history = self._current_history()
self.back_action.setEnabled(history.can_go_back)
self.forward_action.setEnabled(history.can_go_forward)
@@ -4450,7 +4438,9 @@ class MainWindow(QMainWindow):
event.ignore()
return
if self.has_project and not self._restoring_workspace:
self.workspaces.save(self.project_root, *self._workspace_snapshot())
snapshot = self._workspace_snapshot()
# Simply opening a directory must not erase its saved tab history.
if snapshot[0]: self.workspaces.save(self.project_root, *snapshot)
self.exports.cancel_all()
batch_dialog = getattr(self, "_batch_export_dialog", None)
if batch_dialog is not None:
@@ -4500,11 +4490,13 @@ class MainWindow(QMainWindow):
return states, active
def _restore_workspace(self) -> bool:
self._workspace_restored = True
if not self.has_project or not self.settings.value("workspace/restore", True, type=bool):
if not self.has_project:
return False
states, active = self.workspaces.load(self.project_root)
if not states or self._has_open_content_tabs():
if self._has_open_content_tabs():
return False
if not states:
self.status_label.setText("此文件夹没有可恢复的历史标签")
return False
seed = self.tabs.currentWidget()
if not isinstance(seed, ReaderTabHost):
@@ -4534,29 +4526,35 @@ class MainWindow(QMainWindow):
if not path.is_file():
host.welcome_view.setPlainText(f"文件已不存在:\n{path}")
return
host.workspace_state = None
if host.reader_view is None:
host.set_reader_view(self._create_reader_view())
self._standby_reader_view = None
host.reader_view.setProperty("is_reader_standby", False)
self.current_file = path
if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path):
self.open_document(path, add_history=False, scroll_y=state.scroll)
elif path.suffix.lower() in {".html", ".htm", ".xhtml"}:
self._open_webpage_file_now(path)
else:
self._open_preview_file_now(path)
if state.editing:
self.edit_current_markdown()
editor = self.tabs.currentWidget()
if isinstance(editor, RichMarkdownEditorDialog):
editor.sync_scroll_checkbox.setChecked(state.sync)
editor.view_mode_box.setCurrentIndex(editor.view_mode_box.findData(state.view))
editor.splitter.setSizes(state.sizes)
cursor = editor.editor.textCursor()
cursor.setPosition(min(state.cursor, editor.editor.document().characterCount() - 1))
editor.editor.setTextCursor(cursor)
QTimer.singleShot(0, editor, lambda: editor.editor.verticalScrollBar().setValue(state.source_scroll))
# Replacing a restored reader with its editor must not activate and
# load the neighbouring background tab during the intermediate removal.
with QSignalBlocker(self.tabs):
host.workspace_state = None
if host.reader_view is None:
host.set_reader_view(self._create_reader_view())
self._standby_reader_view = None
host.reader_view.setProperty("is_reader_standby", False)
host.begin_reader_load()
self.current_file = path
if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path):
self.open_document(path, add_history=False, scroll_y=state.scroll)
elif path.suffix.lower() in {".html", ".htm", ".xhtml"}:
self._open_webpage_file_now(path)
else:
self._open_preview_file_now(path)
if state.editing:
self.edit_current_markdown()
editor = self.tabs.currentWidget()
if isinstance(editor, RichMarkdownEditorDialog):
editor.sync_scroll_checkbox.setChecked(state.sync)
editor.view_mode_box.setCurrentIndex(editor.view_mode_box.findData(state.view))
editor.splitter.setSizes(state.sizes)
cursor = editor.editor.textCursor()
cursor.setPosition(min(state.cursor, editor.editor.document().characterCount() - 1))
editor.editor.setTextCursor(cursor)
QTimer.singleShot(0, editor, lambda: editor.editor.verticalScrollBar().setValue(state.source_scroll))
self._on_tab_changed(self.tabs.currentIndex())
@property
def editor_drafts(self) -> dict:
+18 -9
View File
@@ -82,12 +82,12 @@ def main():
finally:
window.close()
app.processEvents()
# Restore an editor and a project preset before showing the native window.
# Restore only the directory/preset, even when old settings saved an editor.
from mdhelper.workspace_state import WorkspaceStore, TabState
from mdhelper.project_presets import ProjectPresetStore, capture_preset
from mdhelper.preferences import ReaderPreferences
from mdhelper.export_settings import PageSettings
from mdhelper.markdown_editor import MarkdownEditorDialog
settings.setValue('workspace/restore', True)
WorkspaceStore(settings).save(root, [TabState(str(note), editing=True)], 0)
ProjectPresetStore(settings).bind(root, capture_preset('Startup preset',
ReaderPreferences(document_font_size=22, font_scale=22/16), PageSettings(header='Project header')))
@@ -95,19 +95,28 @@ def main():
restored.prepare_reader_before_show()
events = WindowEvents(restored)
try:
editor = restored.tabs.currentWidget()
assert isinstance(editor, MarkdownEditorDialog)
parent = editor.preview.parent()
host = restored.tabs.currentWidget()
reader = host.reader_view
assert restored.current_file is None and host.property('is_welcome')
assert getattr(host,'workspace_state',None) is None
parent = reader.parent()
restored.show()
native_id = int(restored.winId())
settled = []
QTimer.singleShot(1500, lambda: settled.append(True))
wait(lambda: bool(settled))
wait(lambda: bool(settled) and not restored._startup_scan_pending)
assert restored.document_font_size == 22 and restored._saved_page_settings().header == 'Project header'
assert int(restored.winId()) == native_id and restored.tabs.currentWidget() is editor
assert editor.preview.parent() is parent
assert restored.current_file is None and restored.tabs.count()==1
assert int(restored.winId()) == native_id and restored.tabs.currentWidget() is host
assert reader.parent() is parent and host.stack.currentWidget() is host.welcome_view
assert events.events.count(QEvent.Type.Show) == 1 and QEvent.Type.Hide not in events.events, events.events
print('Restored editor and project preset passed: one show, no hide, stable native window and preview parent.')
startup_events = list(events.events)
loaded=[];reader.loadFinished.connect(loaded.append)
restored.open_document(note)
wait(lambda:bool(loaded) and loaded[-1])
assert restored.tabs.currentWidget() is host and host.stack.currentWidget() is reader
assert int(restored.winId())==native_id and events.events==startup_events
print('Directory-only restore and manual file open passed: no document tabs at startup, one show, no hide, stable reader host.')
finally:
restored.close()
app.processEvents()
+80 -4
View File
@@ -1,4 +1,6 @@
from pathlib import Path
import time
import pytest
from PySide6.QtCore import QSettings
from mdhelper import main_window
from mdhelper.markdown_editor import MarkdownEditorDialog
@@ -6,6 +8,70 @@ from mdhelper.tab_controller import document_path
from mdhelper.workspace_state import TabState, WorkspaceStore
def wait_until(app, condition):
deadline=time.monotonic()+10
while not condition() and time.monotonic()<deadline:
app.processEvents();time.sleep(.01)
assert condition()
@pytest.mark.parametrize('legacy_restore', [None, True, False])
@pytest.mark.parametrize('deferred', [False, True])
def test_startup_restores_directory_without_any_document_tabs(qt_application,tmp_path,monkeypatch,legacy_restore,deferred):
settings=QSettings(str(tmp_path/'settings.ini'),QSettings.Format.IniFormat)
monkeypatch.setattr(main_window,'QSettings',lambda *_:settings)
note=tmp_path/'history.md';note.write_text('# History\n\nSaved document text',encoding='utf8')
settings.setValue('project/last_root',str(tmp_path))
if legacy_restore is not None:settings.setValue('workspace/restore',legacy_restore)
store=WorkspaceStore(settings)
store.save(tmp_path,[TabState(str(note),editing=True)],0)
window=main_window.MainWindow(tmp_path,defer_startup=deferred)
try:
window.prepare_reader_before_show()
host=window.tabs.currentWidget()
reader=host.reader_view
window.show()
wait_until(qt_application,lambda:not window._startup_scan_pending)
assert window.has_project and window.project_root==tmp_path.resolve()
assert [entry.path for entry in window.entries]==[note]
assert window.current_file is None and window.windowTitle()=='MDHelper'
assert window.tabs.count()==1 and window.tabs.currentWidget() is host
assert host.property('is_welcome') and document_path(host) is None
assert getattr(host,'workspace_state',None) is None
assert host.stack.currentWidget() is host.welcome_view
assert not window.restore_workspace_action.isCheckable()
assert settings.value('project/last_root')==str(tmp_path)
# A manual open uses the prepared host and displays content immediately
# after loading; it does not need the user to close a placeholder tab.
loaded=[];reader.loadFinished.connect(loaded.append)
window.open_document(note)
wait_until(qt_application,lambda:bool(loaded) and loaded[-1])
assert window.tabs.count()==1 and window.tabs.currentWidget() is host
assert host.reader_view is reader and host.stack.currentWidget() is reader
text=[];reader.page().toPlainText(text.append)
wait_until(qt_application,lambda:bool(text))
assert 'Saved document text' in text[0]
assert not window.restore_workspace_action.isEnabled()
finally:window.close()
def test_directory_only_session_preserves_manual_restore_history(qt_application,tmp_path,monkeypatch):
settings=QSettings(str(tmp_path/'settings.ini'),QSettings.Format.IniFormat)
monkeypatch.setattr(main_window,'QSettings',lambda *_:settings)
note=tmp_path/'history.md';note.write_text('# History',encoding='utf8')
store=WorkspaceStore(settings);store.save(tmp_path,[TabState(str(note))],0)
saved=settings.value(store.key(tmp_path))
window=main_window.MainWindow(tmp_path)
window.prepare_reader_before_show()
window.close()
assert settings.value(store.key(tmp_path))==saved
window=main_window.MainWindow(tmp_path)
try:
window.close_project_folder()
assert settings.value(store.key(tmp_path))==saved
finally:window.close()
def test_workspace_validation_filters_deleted_and_outside_files(tmp_path):
settings = QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat)
root = tmp_path / 'project'; root.mkdir()
@@ -19,20 +85,30 @@ def test_workspace_validation_filters_deleted_and_outside_files(tmp_path):
assert store.load(root) == ([], 0)
def test_restore_tab_order_editor_mode_and_lazy_background(qt_application, tmp_path, monkeypatch):
@pytest.mark.parametrize('active', [0, 1, 2])
def test_restore_tab_order_editor_mode_and_lazy_background(qt_application, tmp_path, monkeypatch, active):
settings = QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat)
monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings)
paths = [tmp_path / f'{n}.md' for n in range(3)]
for path in paths: path.write_text('# Example\n\nText', encoding='utf-8')
WorkspaceStore(settings).save(tmp_path, [TabState(str(paths[0]), True, 'source', False, 4),
TabState(str(paths[1])), TabState(str(paths[2]))], 1)
TabState(str(paths[1])), TabState(str(paths[2]))], active)
window = main_window.MainWindow(tmp_path, defer_startup=True)
try:
seed = window.tabs.currentWidget()
window.prepare_reader_before_show()
assert window.tabs.currentIndex() == 1 and window.tabs.widget(1) is seed
assert window.tabs.count()==1 and window.current_file is None
window.restore_workspace_action.trigger()
assert window.tabs.currentIndex() == active
assert [document_path(window.tabs.widget(i)) for i in range(3)] == paths
assert window.tabs.widget(0).reader_view is None and window.tabs.widget(2).reader_view is None
for index in range(3):
if index != active:assert window.tabs.widget(index).reader_view is None
if active != 0:
assert window.tabs.widget(active) is seed
wait_until(qt_application,lambda:seed.stack.currentWidget() is seed.reader_view)
text=[];seed.reader_view.page().toPlainText(text.append)
wait_until(qt_application,lambda:bool(text))
assert 'Example' in text[0]
window.tabs.setCurrentIndex(0)
editor = window.tabs.currentWidget()
assert isinstance(editor, MarkdownEditorDialog)