Remember external applications and add GUI smoke test
This commit is contained in:
@@ -14,6 +14,7 @@ MDHelper 是一个用 Python 和 Markdown 文件组成的本地帮助文档阅
|
||||
- 支持多标签页阅读
|
||||
- 单击本地 `.md` 和网页文件链接会在 MDHelper 标签页内展示
|
||||
- 单击其他本地文件链接时,会先询问是否用本地默认软件打开
|
||||
- 默认软件打开失败时,可选择本地程序打开,并按扩展名记住该程序
|
||||
- 右键本地文件链接可选择“在本标签页打开”或“新建标签页打开”
|
||||
- 右侧显示当前文档标题目录
|
||||
- 滚动阅读时自动高亮当前章节目录
|
||||
@@ -76,6 +77,12 @@ MDHelper 是一个用 Python 和 Markdown 文件组成的本地帮助文档阅
|
||||
.\mdhelper_env\Scripts\python.exe -m mdhelper --check
|
||||
```
|
||||
|
||||
运行 GUI 烟雾测试:
|
||||
|
||||
```powershell
|
||||
.\mdhelper_env\Scripts\python.exe .\tests\gui_smoke.py
|
||||
```
|
||||
|
||||
## 依赖
|
||||
|
||||
核心依赖已写入 `requirements.txt`:
|
||||
|
||||
+61
-2
@@ -44,6 +44,7 @@ from .settings_dialog import AppPreferences, SettingsDialog
|
||||
|
||||
BOOKMARKS_SETTING_KEY = "bookmarks/items"
|
||||
SCROLL_POSITIONS_SETTING_KEY = "reader/scroll_positions"
|
||||
EXTERNAL_APPLICATIONS_SETTING_KEY = "external_apps/by_extension"
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -136,6 +137,7 @@ class MainWindow(QMainWindow):
|
||||
self.recent_files: list[Path] = []
|
||||
self.bookmarks: list[dict[str, str]] = []
|
||||
self.scroll_positions: dict[str, int] = {}
|
||||
self.external_applications: dict[str, str] = {}
|
||||
self.path_to_item: dict[Path, QTreeWidgetItem] = {}
|
||||
self.file_watcher = QFileSystemWatcher(self)
|
||||
self.file_watcher.fileChanged.connect(self._on_watched_file_changed)
|
||||
@@ -572,6 +574,9 @@ class MainWindow(QMainWindow):
|
||||
QMessageBox.information(self, "已阻止打开", f"此文件类型未在 MDHelper 内预览:\n{path}")
|
||||
return
|
||||
|
||||
if self._open_with_saved_application(path):
|
||||
return
|
||||
|
||||
if self.non_preview_action == "ask":
|
||||
answer = QMessageBox.question(
|
||||
self,
|
||||
@@ -599,7 +604,7 @@ class MainWindow(QMainWindow):
|
||||
message.setInformativeText(
|
||||
f"文件:\n{path}\n\n"
|
||||
f"系统错误:\n{error}\n\n"
|
||||
"你可以选择一个本地程序来打开此文件。"
|
||||
"你可以选择一个本地程序来打开此文件。选择成功后,MDHelper 会记住此扩展名对应的程序。"
|
||||
)
|
||||
choose_button = message.addButton("选择程序打开", QMessageBox.ButtonRole.AcceptRole)
|
||||
message.addButton("取消", QMessageBox.ButtonRole.RejectRole)
|
||||
@@ -620,13 +625,56 @@ class MainWindow(QMainWindow):
|
||||
return
|
||||
|
||||
LOGGER.info("Opening local file with selected application: %s -> %s", program, path)
|
||||
if not QProcess.startDetached(program, [str(path)]):
|
||||
if self._start_external_application(program, path):
|
||||
self._remember_external_application(path, program)
|
||||
self.status_label.setText(f"已记住 {path.suffix.lower()} 的打开程序")
|
||||
else:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"打开失败",
|
||||
f"无法启动所选程序:\n{program}\n\n要打开的文件:\n{path}",
|
||||
)
|
||||
|
||||
def _open_with_saved_application(self, path: Path) -> bool:
|
||||
extension = path.suffix.lower()
|
||||
program = self.external_applications.get(extension)
|
||||
if not extension or not program:
|
||||
return False
|
||||
|
||||
program_path = Path(program)
|
||||
if not program_path.exists():
|
||||
LOGGER.warning("Saved application no longer exists for %s: %s", extension, program)
|
||||
self._forget_external_application(extension)
|
||||
return False
|
||||
|
||||
LOGGER.info("Opening local file with saved application: %s -> %s", program, path)
|
||||
if self._start_external_application(program, path):
|
||||
return True
|
||||
|
||||
LOGGER.warning("Saved application failed for %s: %s", extension, program)
|
||||
self._forget_external_application(extension)
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"打开失败",
|
||||
f"已记住的程序无法启动,MDHelper 已清除此记录。\n\n程序:\n{program}\n\n文件:\n{path}",
|
||||
)
|
||||
return False
|
||||
|
||||
def _start_external_application(self, program: str, path: Path) -> bool:
|
||||
return QProcess.startDetached(program, [str(path)])
|
||||
|
||||
def _remember_external_application(self, path: Path, program: str) -> None:
|
||||
extension = path.suffix.lower()
|
||||
if not extension:
|
||||
return
|
||||
self.external_applications[extension] = str(Path(program).resolve())
|
||||
self._save_preferences()
|
||||
LOGGER.info("Remembered external application for %s: %s", extension, program)
|
||||
|
||||
def _forget_external_application(self, extension: str) -> None:
|
||||
self.external_applications.pop(extension.lower(), None)
|
||||
self._save_preferences()
|
||||
|
||||
def _open_webpage_file_now(self, path: Path, new_tab: bool = False) -> None:
|
||||
path = path.resolve()
|
||||
if not path.exists():
|
||||
@@ -1178,8 +1226,15 @@ class MainWindow(QMainWindow):
|
||||
self.recent_files = [Path(str(path)).resolve() for path in recent_paths if str(path)]
|
||||
bookmarks = self._load_json_setting(BOOKMARKS_SETTING_KEY, [])
|
||||
scroll_positions = self._load_json_setting(SCROLL_POSITIONS_SETTING_KEY, {})
|
||||
external_applications = self._load_json_setting(EXTERNAL_APPLICATIONS_SETTING_KEY, {})
|
||||
self.bookmarks = bookmarks if isinstance(bookmarks, list) else []
|
||||
self.scroll_positions = scroll_positions if isinstance(scroll_positions, dict) else {}
|
||||
if isinstance(external_applications, dict):
|
||||
self.external_applications = {
|
||||
str(extension).lower(): str(program)
|
||||
for extension, program in external_applications.items()
|
||||
if str(extension).startswith(".") and str(program)
|
||||
}
|
||||
|
||||
def _save_preferences(self) -> None:
|
||||
self.settings.setValue("reader/theme", self.theme)
|
||||
@@ -1189,6 +1244,10 @@ class MainWindow(QMainWindow):
|
||||
self.settings.setValue("recent/files", [str(path) for path in self.recent_files])
|
||||
self.settings.setValue(BOOKMARKS_SETTING_KEY, json.dumps(self.bookmarks, ensure_ascii=False))
|
||||
self.settings.setValue(SCROLL_POSITIONS_SETTING_KEY, json.dumps(self.scroll_positions, ensure_ascii=False))
|
||||
self.settings.setValue(
|
||||
EXTERNAL_APPLICATIONS_SETTING_KEY,
|
||||
json.dumps(self.external_applications, ensure_ascii=False),
|
||||
)
|
||||
if hasattr(self, "splitter"):
|
||||
self.settings.setValue("window/splitter", self.splitter.saveState())
|
||||
self.settings.setValue("window/geometry", self.saveGeometry())
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox")
|
||||
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 QTimer
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from mdhelper.main_window import MainWindow, ReaderView
|
||||
|
||||
|
||||
def main() -> int:
|
||||
project_root = PROJECT_ROOT
|
||||
app = QApplication.instance() or QApplication([sys.argv[0]])
|
||||
window = MainWindow(project_root=project_root, initial_path=project_root / "sample.md")
|
||||
window.show()
|
||||
|
||||
checks: list[str] = []
|
||||
|
||||
def verify() -> None:
|
||||
if window.current_file != (project_root / "sample.md").resolve():
|
||||
checks.append("current_file")
|
||||
if window.tabs.count() < 1:
|
||||
checks.append("tabs")
|
||||
if not isinstance(window.tabs.currentWidget(), ReaderView):
|
||||
checks.append("reader_view")
|
||||
if not window.export_pdf_action.isEnabled():
|
||||
checks.append("export_pdf_action")
|
||||
if not window.export_html_action.isEnabled():
|
||||
checks.append("export_html_action")
|
||||
if window.search_index.search("斐波那契") == []:
|
||||
checks.append("search_index")
|
||||
window.close()
|
||||
app.quit()
|
||||
|
||||
QTimer.singleShot(1600, verify)
|
||||
app.exec()
|
||||
|
||||
if checks:
|
||||
print("GUI smoke failed:", ", ".join(checks))
|
||||
return 1
|
||||
|
||||
print("GUI smoke ok")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user