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 QEventLoop, QTimer, QUrl, Qt from PySide6.QtGui import QTextCursor from PySide6.QtWidgets import QApplication, QMessageBox from mdhelper.main_window import MainWindow, ReaderView from mdhelper.markdown_editor import MarkdownEditorDialog 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: 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.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) != "未选择文件夹": checks.append("empty_start_tree") empty_window.set_project_root(project_root, save=False) if not empty_window.has_project or empty_window.project_root != project_root.resolve() or not empty_window.entries: checks.append("set_project_root") supported_suffixes = {".md", ".markdown", ".html", ".htm", ".xhtml"} if any(entry.path.suffix.lower() not in supported_suffixes for entry in empty_window.entries): checks.append("project_supported_files_only") if not any(entry.path == (project_root / "sample.md").resolve() for entry in empty_window.entries): checks.append("project_markdown_files") if any(entry.path == (project_root / "requirements.txt").resolve() for entry in empty_window.entries): checks.append("project_hidden_unsupported_files") tree_root = empty_window.tree.topLevelItem(0) if tree_root is None or not tree_root.isExpanded(): checks.append("file_tree_root_expanded") if tree_root is None or tree_root.icon(0).isNull(): checks.append("file_tree_root_icon") folder_item = None file_item = None if tree_root is not None: pending = [tree_root.child(index) for index in range(tree_root.childCount())] while pending: candidate = pending.pop(0) data = candidate.data(0, Qt.ItemDataRole.UserRole) if data and file_item is None: file_item = candidate elif not data: if folder_item is None and candidate.childCount() > 0: folder_item = candidate pending.extend(candidate.child(index) for index in range(candidate.childCount())) if folder_item is None: checks.append("file_tree_folder_item") else: if folder_item.isExpanded(): checks.append("file_tree_subfolder_collapsed") if folder_item.icon(0).isNull(): checks.append("file_tree_folder_icon") if file_item is None: checks.append("file_tree_file_item") elif file_item.icon(0).isNull(): checks.append("file_tree_file_icon") if folder_item is not None and file_item is not None: folder_color = folder_item.foreground(0).color().name() file_color = file_item.foreground(0).color().name() if folder_color == file_color: checks.append("file_tree_item_colors") if tree_root is not None: root_children = [tree_root.child(index) for index in range(tree_root.childCount())] root_sort_keys = [ (bool(child.data(0, Qt.ItemDataRole.UserRole)), child.text(0).casefold()) for child in root_children ] if root_sort_keys != sorted(root_sort_keys): checks.append("file_tree_folder_first_sorted") empty_window.set_document_tree_label_mode("filename") sample_item = empty_window.path_to_item.get((project_root / "sample.md").resolve()) if sample_item is None or sample_item.text(0) != "sample.md": checks.append("tree_label_filename_mode") empty_window.set_document_tree_label_mode("title") sample_item = empty_window.path_to_item.get((project_root / "sample.md").resolve()) if sample_item is None or sample_item.text(0) == "sample.md": checks.append("tree_label_title_mode") empty_window._set_theme_color("black") empty_window._apply_navigation_style() theme_loop = QEventLoop() QTimer.singleShot(500, theme_loop.quit) theme_loop.exec() welcome_view = empty_window.tabs.currentWidget() if welcome_view is not None and bool(welcome_view.property("is_welcome")): result: dict[str, str] = {} def store_theme(value: object) -> None: result["theme"] = str(value) theme_loop.quit() welcome_view.page().runJavaScript("document.documentElement.dataset.theme", store_theme) QTimer.singleShot(1000, theme_loop.quit) theme_loop.exec() if result.get("theme") != "dark": checks.append("welcome_theme_refresh") empty_window.close() window.find_box.setText("斐波那契") window.find_next() if window.current_file != (project_root / "sample.md").resolve(): checks.append("current_file") if window.tabs.count() < 1: checks.append("tabs") if window._welcome_tab_index() >= 0: checks.append("welcome_closed_for_document") if window.windowIcon().isNull(): checks.append("window_icon") if app.windowIcon().isNull(): checks.append("app_icon") 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 hasattr(window, "theme_action"): checks.append("theme_toolbar_action") if hasattr(window, "home_action"): checks.append("home_toolbar_action") if window.back_action.icon().isNull() or window.forward_action.icon().isNull(): checks.append("navigation_toolbar_icons") if window.open_action.icon().isNull() or window.refresh_action.icon().isNull(): checks.append("file_toolbar_icons") if not hasattr(window, "document_font_box") or not hasattr(window, "document_font_size_box"): checks.append("toolbar_font_controls") else: previous_size = window.document_font_size window.set_document_font_size_from_toolbar("18") if window.document_font_size != 18: checks.append("toolbar_font_size") window.set_document_font_size_from_toolbar(str(previous_size)) if not hasattr(window, "theme_menu"): checks.append("theme_menu") background_values = { str(action.data()) for action in window.theme_background_group.actions() if action.data() is not None } expected_background_values = { "none", "chinese_knot", "cloud", "ruyi", "brush", "peony", "bamboo", "meander", } if background_values != expected_background_values: checks.append("theme_background_options") if window._normalized_theme_background("circuit") != "none": checks.append("legacy_theme_background_migration") window.theme_background = "peony" window._set_theme_color("black") window._update_theme_menu_state() if window.theme_background != "none": checks.append("background_requires_colorful") peony_action = next((action for action in window.theme_background_group.actions() if action.data() == "peony"), None) if peony_action is None or peony_action.isEnabled(): checks.append("background_disabled_for_non_colorful") window._set_theme_color("colorful") window.set_theme_background_from_action(peony_action) if window.theme_background != "peony": checks.append("background_enabled_for_colorful") if not hasattr(window, "manage_external_apps_action"): checks.append("manage_external_apps_action") if not window.edit_current_action.isEnabled(): checks.append("edit_current_action") toc_items = window.toc_tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive) toc_item = next((item for item in toc_items if item.data(0, Qt.ItemDataRole.UserRole)), None) if toc_item is None: checks.append("toc_items") else: target_slug = str(toc_item.data(0, Qt.ItemDataRole.UserRole)) window._open_toc_item(toc_item) if window.current_fragment != target_slug: checks.append("toc_click_fragment") second_toc_item = next( (item for item in toc_items if item is not toc_item and item.data(0, Qt.ItemDataRole.UserRole)), None, ) if second_toc_item is not None: second_slug = str(second_toc_item.data(0, Qt.ItemDataRole.UserRole)) window._open_toc_item(second_toc_item) toc_loop = QEventLoop() QTimer.singleShot(250, toc_loop.quit) toc_loop.exec() if window.current_fragment != second_slug: checks.append("toc_second_click_fragment") result: dict[str, float] = {} def store_scroll(value: object) -> None: try: result["scroll_y"] = float(value or 0) except (TypeError, ValueError): result["scroll_y"] = -1 toc_loop.quit() window.web_view.page().runJavaScript("Math.max(0, window.scrollY || document.documentElement.scrollTop || 0)", store_scroll) QTimer.singleShot(1000, toc_loop.quit) toc_loop.exec() if result.get("scroll_y", -1) < 0: checks.append("toc_second_click_scroll") if window.search_index.search("斐波那契") == []: checks.append("search_index") if not window._is_current_page_anchor_url(QUrl("#2-表格示例")): checks.append("plain_anchor_url") base_anchor = QUrl.fromLocalFile(str((project_root / "sample.md").resolve().parent)) base_anchor.setFragment("2-表格示例") if not window._is_current_page_anchor_url(base_anchor): checks.append("base_anchor_url") if window._is_current_page_anchor_url(QUrl("mailto:user@example.com#message")): checks.append("external_fragment_url") context_events: list[tuple[str, bool]] = [] try: window.web_view.open_link_requested.disconnect(window.open_link_url) except RuntimeError: pass try: window.web_view.open_link_requested.connect(lambda url, new_tab: context_events.append((url.toString(), new_tab))) manual_context_url = QUrl.fromLocalFile(str((project_root / "docs" / "user_manual.md").resolve())) if not window.web_view._handle_link_context_action(manual_context_url, False): checks.append("context_menu_current_action") if not window.web_view._handle_link_context_action(manual_context_url, True): checks.append("context_menu_new_action") if context_events[-2:] != [(manual_context_url.toString(), False), (manual_context_url.toString(), True)]: checks.append("context_menu_signals") finally: window.web_view.open_link_requested.connect(window.open_link_url) manual_url = QUrl.fromLocalFile(str((project_root / "docs" / "user_manual.md").resolve())) window._open_link_url_now(manual_url, False) if window.current_file != (project_root / "docs" / "user_manual.md").resolve(): checks.append("local_link_current_tab") tab_count = window.tabs.count() window._open_link_url_now(manual_url, True) if window.tabs.count() != tab_count + 1: checks.append("local_link_new_tab") if window.current_file != (project_root / "docs" / "user_manual.md").resolve(): checks.append("local_link_new_tab_file") window._close_tab(window.tabs.currentIndex()) if window.tabs.count() == 1 and bool(window.tabs.currentWidget().property("is_welcome")): checks.append("welcome_opened_with_other_doc") window.open_document(project_root / "sample.md", add_history=False) load_loop = QEventLoop() window.web_view.loadFinished.connect(load_loop.quit) QTimer.singleShot(5000, load_loop.quit) load_loop.exec() export_test_path = project_root / "__gui_smoke_export.html" try: window._write_exported_html(export_test_path, "Smoke") if not export_test_path.exists() or "Smoke" not in export_test_path.read_text(encoding="utf-8"): checks.append("export_html_write") finally: try: export_test_path.unlink(missing_ok=True) except OSError: 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) 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: checks.append("export_pdf_write") finally: try: pdf_test_path.unlink(missing_ok=True) except OSError: pass window._remember_external_application(project_root / "media" / "demo.mp4", str(project_root / "fake_player.exe")) if ".mp4" not in window.external_applications: checks.append("external_app_remember") window._forget_external_application(".mp4") if ".mp4" in window.external_applications: checks.append("external_app_forget") started: list[tuple[str, Path]] = [] original_start = window._start_external_application window._start_external_application = lambda program, path: started.append((program, Path(path))) or True try: if not window._open_with_application(project_root / "media" / "demo.mp4", str(project_root / "fake_player.exe")): checks.append("external_app_select") if not started or started[-1][1] != (project_root / "media" / "demo.mp4").resolve(): checks.append("external_app_select_target") finally: window._start_external_application = original_start window._forget_external_application(".mp4") editor_test_path = project_root / "__gui_smoke_editor__.md" try: editor_test_path.write_text("# Editor Smoke\n\n初始内容\n", encoding="utf-8") window.open_document(editor_test_path, add_history=False) window._save_editor_draft(editor_test_path, "# Draft\n\n草稿内容\n") if str(editor_test_path.resolve()) not in window.editor_drafts: checks.append("editor_draft_save") draft = window.editor_drafts.get(str(editor_test_path.resolve()), {}) if "saved_at" not in draft or "file_mtime_ns" not in draft or "file_size" not in draft: checks.append("editor_draft_metadata") if not window.save_markdown_source(editor_test_path, "# Editor Smoke Saved\n\n编辑保存命中\n"): checks.append("editor_save") if str(editor_test_path.resolve()) in window.editor_drafts: checks.append("editor_draft_clear") if window._read_markdown_source(editor_test_path) != "# Editor Smoke Saved\n\n编辑保存命中\n": checks.append("editor_readback") if window.search_index.search("编辑保存命中") == []: checks.append("editor_search_index") save_as_path = project_root / "__gui_smoke_editor_saved_as.md" if not window.save_markdown_source(save_as_path, "# Saved As\n\n另存为命中\n", original_path=editor_test_path): checks.append("editor_save_as") if not save_as_path.exists() or window.search_index.search("另存为命中") == []: checks.append("editor_save_as_index") conflict_path = project_root / "__gui_smoke_conflict.md" conflict_path.write_text("# Conflict\n\nold\n", encoding="utf-8") signature = window._file_signature(conflict_path) conflict_path.write_text("# Conflict\n\nexternal\n", encoding="utf-8") original_warning = QMessageBox.warning QMessageBox.warning = lambda *args, **kwargs: QMessageBox.StandardButton.Cancel try: if window.save_markdown_source(conflict_path, "# Conflict\n\noverwrite\n", expected_signature=signature): checks.append("editor_conflict_cancel") if "external" not in conflict_path.read_text(encoding="utf-8"): checks.append("editor_conflict_preserve") finally: QMessageBox.warning = original_warning dialog = MarkdownEditorDialog( path=editor_test_path, source="# Preview Smoke\n\n```mermaid\ngraph TD\n A --> B\n```", renderer=window.renderer, theme=window.theme, font_scale=window.font_scale, document_font_family=window.document_font_family, document_font_size=window.document_font_size, math_engine=window.math_engine, parent=window, ) dialog.view_mode_box.setCurrentIndex(2) if dialog.editor.isHidden() or dialog.preview.isHidden(): checks.append("editor_split_mode") dialog.editor.setPlainText("# Preview Smoke\n\n更新预览") dialog._refresh_preview_now() if dialog._preview_dirty: checks.append("editor_preview_refresh") dialog.editor.setPlainText("alpha beta alpha") dialog.editor_find_box.setText("alpha") dialog.find_next_in_editor() if dialog.find_status_label.text() != "1/2": checks.append("editor_find_count") dialog.editor_replace_box.setText("gamma") dialog.replace_current_in_editor() if "gamma" not in dialog.source_text(): checks.append("editor_replace") dialog.editor.selectAll() dialog.insert_template("**{selection}**") if not dialog.source_text().startswith("**"): checks.append("editor_insert_template") dialog.close() window.open_document(editor_test_path, add_history=False) editor_tab_count = window.tabs.count() window.edit_current_markdown() editor_widget = window.tabs.currentWidget() if window.tabs.count() != editor_tab_count or not isinstance(editor_widget, MarkdownEditorDialog): checks.append("editor_tab_open") else: if editor_widget.view_mode_box.currentData() != "split": checks.append("editor_tab_default_split") if editor_widget.path_label.isVisible(): checks.append("editor_path_label_visible") old_editor_point_size = editor_widget.editor.font().pointSize() window.set_document_font_size_from_toolbar("22") if editor_widget.document_font_size != 22 or editor_widget.editor.font().pointSize() <= old_editor_point_size: checks.append("editor_font_size_update") window.set_document_font_size_from_toolbar("16") if not hasattr(editor_widget, "undo_button") or not hasattr(editor_widget, "redo_button"): checks.append("editor_undo_redo_buttons") button_order = [ editor_widget.redo_button.text(), editor_widget.undo_button.text(), editor_widget.save_button.text(), editor_widget.save_as_button.text(), editor_widget.cancel_button.text(), ] if button_order != ["前进", "回退", "保存", "另存为", "取消"]: checks.append("editor_button_order") toc_items_after_edit = window.toc_tree.findItems( "*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive, ) if not toc_items_after_edit: checks.append("editor_toc_visible") else: target_slug = str(toc_items_after_edit[0].data(0, Qt.ItemDataRole.UserRole)) window._open_toc_item(toc_items_after_edit[0]) if window.current_fragment != target_slug: checks.append("editor_toc_click") second_edit_toc = next( ( item for item in toc_items_after_edit if item is not toc_items_after_edit[0] and item.data(0, Qt.ItemDataRole.UserRole) ), None, ) if second_edit_toc is not None: second_edit_slug = str(second_edit_toc.data(0, Qt.ItemDataRole.UserRole)) window._open_toc_item(second_edit_toc) if window.current_fragment != second_edit_slug: checks.append("editor_toc_second_click") editor_widget.editor.setPlainText("\n".join(f"line {index}" for index in range(160))) editor_widget.editor.verticalScrollBar().setValue(editor_widget.editor.verticalScrollBar().maximum()) editor_widget._sync_preview_to_editor_scroll(editor_widget.editor.verticalScrollBar().value()) if editor_widget._preview_scroll_ratio < 0.9: checks.append("editor_preview_scroll_sync") editor_widget.editor.setPlainText("undo baseline") cursor = editor_widget.editor.textCursor() cursor.movePosition(QTextCursor.MoveOperation.End) editor_widget.editor.setTextCursor(cursor) editor_widget.editor.insertPlainText(" changed") editor_widget.undo_button.click() if editor_widget.source_text() != "undo baseline": checks.append("editor_undo_button") editor_widget.redo_button.click() if editor_widget.source_text() != "undo baseline changed": checks.append("editor_redo_button") editor_widget.editor.setPlainText("# Editor Tab\n\n标签页编辑保存\n") editor_widget._emit_save_requested() if window.tabs.currentWidget() is not editor_widget: checks.append("editor_tab_stays_open") if "标签页编辑保存" not in editor_test_path.read_text(encoding="utf-8"): checks.append("editor_tab_save") tab_count_before_theme = window.tabs.count() window._set_theme_color("black") window.refresh_document() if window.tabs.count() != tab_count_before_theme: checks.append("editor_theme_new_tab") if editor_widget.theme != "dark": checks.append("editor_theme_update") window._set_theme_color("white") window.refresh_document() window._close_tab(window.tabs.currentIndex()) if window.tabs.count() == 0: checks.append("welcome_after_close") window.open_document(project_root / "sample.md", add_history=False) finally: for cleanup_path in ( editor_test_path, project_root / "__gui_smoke_editor_saved_as.md", project_root / "__gui_smoke_conflict.md", ): try: cleanup_path.unlink(missing_ok=True) except OSError: pass window.katex_action.trigger() if window.math_engine != "katex": checks.append("katex_action") window.mathjax_action.trigger() if window.math_engine != "mathjax": checks.append("mathjax_action") snapshot = window._configuration_snapshot() if snapshot.get("version") is None: checks.append("config_version") if "external_applications" not in snapshot: checks.append("config_external_applications") if snapshot.get("reader", {}).get("theme_background") is None: checks.append("config_theme_background") if snapshot.get("reader", {}).get("document_tree_label_mode") not in {"title", "filename"}: checks.append("config_tree_label_mode") window._apply_configuration( { "reader": { "theme_color": "dark_gray", "theme_background": "peony", "math_engine": "katex", "font_scale": 1.2, "document_font_family": "Microsoft YaHei UI", "document_font_size": 18, "document_tree_label_mode": "filename", "ui_font_family": "Microsoft YaHei UI", "ui_font_point_size": 10, }, "recent_files": [str(project_root / "sample.md")], "bookmarks": [{"path": str(project_root / "sample.md"), "fragment": "", "label": "sample"}], "scroll_positions": {str(project_root / "sample.md"): 42}, "external_applications": {".mp4": "C:/Tools/player.exe"}, } ) if window.theme != "dark" or window.theme_color != "dark_gray" or window.math_engine != "katex": checks.append("config_apply_reader") if window.theme_background != "none": checks.append("config_apply_theme_background") if window.document_font_size != 18 or window.document_font_family != "Microsoft YaHei UI": checks.append("config_apply_document_font") 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: checks.append("config_apply_ui_font") if ".mp4" not in window.external_applications: checks.append("config_apply_external_apps") 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())