from __future__ import annotations import os import sys import traceback import zipfile 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( "QT_LOGGING_RULES", "qt.multimedia.ffmpeg.*=false;qt.multimedia.*.debug=false;qt.multimedia.*.info=false", ) 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, QPoint, QSettings, QTimer, QUrl, Qt from PySide6.QtGui import QTextCursor from PySide6.QtWebEngineCore import QWebEnginePage from PySide6.QtWidgets import QAbstractItemView, QApplication, QMessageBox, QPushButton, QToolBar from mdhelper.main_window import MainWindow, ReaderPage, ReaderTabHost, ReaderView, VideoPlayerWidget from mdhelper.markdown_editor import MarkdownEditorDialog from mdhelper.settings_dialog import AppPreferences, SettingsDialog from mdhelper.style_dialog import DocumentStyleEditorDialog def wait_until(condition, timeout_ms=15000) -> bool: """Wait for completion, not a fixed rendering speed on the test machine.""" if condition(): return True loop = QEventLoop() poll = QTimer() poll.setInterval(20) poll.timeout.connect(lambda: loop.quit() if condition() else None) deadline = QTimer() deadline.setSingleShot(True) deadline.timeout.connect(loop.quit) poll.start() deadline.start(timeout_ms) loop.exec() poll.stop() deadline.stop() return bool(condition()) 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) window = MainWindow(project_root=project_root, initial_path=project_root / "sample.md", defer_startup=True) window.prepare_reader_before_show() window.show() checks: list[str] = [] def verify() -> None: empty_window = MainWindow(project_root=None, app_root=project_root) empty_window.prepare_reader_before_show() fixed_reader_host = empty_window.tabs.currentWidget() empty_window.show() if not isinstance(fixed_reader_host, ReaderTabHost) or fixed_reader_host.reader_view is None: checks.append("reader_pre_show_preparation") 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) != "未选择文件夹": 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") switch_root = project_root / "__gui_smoke_switch_root__" nested_root = switch_root / "nested" try: 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") first_reader = empty_window._reader_from_tab(fixed_reader_host) empty_window.open_document(project_root / "sample.md", add_history=False) wait_until( lambda: first_reader is not None and fixed_reader_host.stack.currentWidget() is first_reader, timeout_ms=30000, ) if empty_window.tabs.currentWidget() is not fixed_reader_host: checks.append("first_open_fixed_tab_host") if first_reader is None or fixed_reader_host.stack.currentWidget() is not first_reader: checks.append("first_open_reader_switch") 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")): checks.append("switch_project_closes_tabs") (switch_root / "second.md").write_text("# Second\n", encoding="utf-8") 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 / "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: pass empty_window.set_project_root(project_root, save=False) 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") original_file_groups = empty_window.document_file_groups empty_window.document_file_groups = ("markdown", "python", "cpp", "fortran") empty_window._refresh_document_entries(force=True) code_suffixes = {".py", ".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".hpp", ".f", ".for", ".f90", ".f95"} if not any(entry.path.suffix.lower() in code_suffixes for entry in empty_window.entries): checks.append("project_optional_code_files") empty_window.open_document(project_root / "sample.md", add_history=False) empty_window.document_file_groups = ("python",) empty_window._refresh_document_entries(force=True) if any(entry.path.suffix.lower() in {".md", ".markdown"} for entry in empty_window.entries): checks.append("project_file_type_filter_entries") if (project_root / "sample.md").resolve() in empty_window.path_to_item: checks.append("project_file_type_filter_tree") empty_window.document_file_groups = original_file_groups empty_window._refresh_document_entries(force=True) 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")): welcome_text = welcome_view.welcome_view if isinstance(welcome_view, ReaderTabHost) else welcome_view if "#17191f" not in welcome_text.styleSheet(): checks.append("welcome_theme_refresh") empty_window.close() window.search_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 not window.tabs.isMovable(): checks.append("tabs_movable") tab_bar = window.tabs.tabBar() if tab_bar.expanding(): checks.append("tabs_non_expanding") if hasattr(tab_bar, "changeCurrentOnDrag") and tab_bar.changeCurrentOnDrag(): checks.append("tabs_no_drag_switch") if tab_bar.contextMenuPolicy() != Qt.ContextMenuPolicy.CustomContextMenu: checks.append("tabs_context_menu_policy") if window._welcome_tab_index() >= 0: checks.append("welcome_closed_for_document") window.open_document(project_root / "docs" / "user_manual.md", new_tab=True, add_history=False) user_manual_index = window.tabs.currentIndex() if sum(1 for index in range(window.tabs.count()) if window._is_content_tab_index(index)) < 2: checks.append("tab_context_multiple_tabs") if not window._close_other_tabs(user_manual_index): checks.append("tab_context_close_others") if window.tabs.count() != 1 or window.current_file != (project_root / "docs" / "user_manual.md").resolve(): checks.append("tab_context_close_others_result") window.open_document(project_root / "sample.md", new_tab=True, add_history=False) if not window._close_tab_indexes(list(range(window.tabs.count()))): checks.append("tab_context_close_all") if window.tabs.count() != 1 or not bool(window.tabs.currentWidget().property("is_welcome")): checks.append("tab_context_close_all_result") window.open_document(project_root / "sample.md", add_history=False) if window.windowIcon().isNull(): checks.append("window_icon") if app.windowIcon().isNull(): checks.append("app_icon") if window._reader_from_tab(window.tabs.currentWidget()) is None: checks.append("reader_view") 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 window._apply_wheel_scroll_speed_to_tabs() current_reader = window._reader_from_tab(window.tabs.currentWidget()) if current_reader is not None and abs(float(current_reader.property("wheel_scroll_speed") or 0) - 1.7) > 0.01: checks.append("wheel_scroll_speed_tab_property") if window.status_label.objectName() != "statusPathLabel": checks.append("status_label_theme_name") if hasattr(window, "find_box"): checks.append("toolbar_find_box_visible") if not all( hasattr(window, name) for name in ( "panel_open_folder_button", "panel_refresh_button", "find_current_button", "find_previous_button", "find_next_button", ) ): checks.append("panel_find_buttons") elif window.panel_open_folder_button.icon().isNull() or window.panel_refresh_button.icon().isNull(): checks.append("panel_icon_buttons") elif any( button.text() for button in ( window.find_current_button, window.find_previous_button, window.find_next_button, ) ): checks.append("panel_find_button_text") elif any( button.icon().isNull() for button in ( window.find_current_button, window.find_previous_button, window.find_next_button, ) ): checks.append("panel_find_button_icons") expected_search_height = max(22, round(window.fontMetrics().height() * 1.5)) if abs(window.search_box.height() - expected_search_height) > 4: checks.append("panel_search_box_height") 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=1.4, reader_width_scale=1.5, 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, ) if abs(settings_dialog.wheel_scroll_speed_spin.value() - 1.4) > 0.01: checks.append("settings_wheel_scroll_speed") settings_dialog.fortran_files_check.setChecked(True) settings_dialog.wheel_scroll_speed_spin.setValue(2.2) prefs = settings_dialog.preferences() if abs(prefs.wheel_scroll_speed - 2.2) > 0.01: checks.append("settings_wheel_scroll_speed_value") if abs(prefs.reader_width_scale - 1.5) > 0.01: checks.append("settings_reader_width_scale") if "fortran" not in prefs.document_file_groups: checks.append("settings_fortran_file_group") settings_dialog.close() if window.findChildren(QToolBar): checks.append("main_toolbar_removed") if hasattr(window, "toolbar_font_label") or hasattr(window, "toolbar_font_size_label"): checks.append("toolbar_font_labels_removed") 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 not window.export_docx_action.isEnabled(): checks.append("export_docx_action") if not window.export_mhtml_action.isEnabled(): checks.append("export_mhtml_action") if hasattr(window, "theme_action"): checks.append("theme_toolbar_action") if hasattr(window, "home_action"): checks.append("home_toolbar_action") if hasattr(window, "document_font_box") or hasattr(window, "document_font_size_box"): checks.append("toolbar_font_controls_removed") previous_size = window.document_font_size window.set_document_font_size_from_toolbar("18") if window.document_font_size != 18: checks.append("font_size_helper") window.set_document_font_size_from_toolbar(str(previous_size)) if not hasattr(window, "theme_menu"): checks.append("theme_menu") menu_titles = [action.text() for action in window.menuBar().actions()] if "样式" not in menu_titles or not hasattr(window, "style_menu"): checks.append("style_menu") style_values = { str(action.data()) for action in window.document_style_group.actions() if action.data() is not None } if not {"default", "compact", "serif", "wide", "focus"}.issubset(style_values): checks.append("style_builtin_options") style_dialog = DocumentStyleEditorDialog( { "name": "图形样式", "rules": { "paragraph": { "font_size": 18, "line_height_value": 1.6, "line_height_unit": "multiple", "first_line_indent_chars": 2, "space_after_value": 6, "space_after_unit": "pt", } }, "extra_css": ".reader strong { color: #0057b8; }", }, parent=window, ) style_dialog.apply_theme(window.theme_color) style_payload = style_dialog.style_payload() if ( "font-size: 18px" not in str(style_payload.get("css")) or "text-indent: 2em" not in str(style_payload.get("css")) or "margin-bottom: 6pt" not in str(style_payload.get("css")) ): checks.append("style_editor_payload") if hasattr(style_dialog, "use_chinese_font_checkbox") or hasattr(style_dialog, "use_english_font_checkbox"): checks.append("style_font_checkboxes_removed") if style_dialog.chinese_font_combo.maximumWidth() > 315 or style_dialog.english_font_combo.maximumWidth() > 315: checks.append("style_font_combo_width") if style_dialog.findChild(QPushButton, "styleResetButton").maximumWidth() > 128: checks.append("style_reset_button_width") if "QTabWidget::pane" not in style_dialog.styleSheet() or "border: 1px solid" not in style_dialog.styleSheet(): checks.append("style_dialog_theme") style_dialog.close() previous_style = window.document_style_id window._set_document_style("compact") if window.document_style_id != "compact" or "max-width: var(--reader-paper-width)" not in window._document_style_css(): checks.append("style_apply_builtin") if window.delete_custom_style_action.isEnabled(): checks.append("style_delete_builtin_enabled") style_test_path = project_root / "style_smoke.mdhelper-style" try: window._write_document_style_file(style_test_path, "compact") imported_style_id = window._import_document_style_file(style_test_path) if imported_style_id not in window.custom_document_styles: checks.append("style_import_file") window.document_style_id = imported_style_id window._build_style_menu() if not window.delete_custom_style_action.isEnabled(): checks.append("style_delete_custom_disabled") exported_payload = window._style_payload_for_id(imported_style_id) if exported_payload.get("name") != "紧凑参考" or "max-width: var(--reader-paper-width)" not in str(exported_payload.get("css")): checks.append("style_payload") original_question = QMessageBox.question QMessageBox.question = lambda *args, **kwargs: QMessageBox.StandardButton.Yes try: window.delete_current_custom_document_style() finally: QMessageBox.question = original_question if imported_style_id in window.custom_document_styles or window.document_style_id != "default": checks.append("style_delete_custom") finally: style_test_path.unlink(missing_ok=True) window.document_style_id = previous_style window._build_style_menu() if "关于" not in menu_titles or menu_titles.index("关于") <= menu_titles.index("主题"): checks.append("about_menu_position") if window.about_action not in window.about_menu.actions(): checks.append("about_menu_action") if window.about_action in window.tools_menu.actions(): checks.append("about_still_in_tools") if not hasattr(window, "close_folder_action") or not hasattr(window, "exit_action"): checks.append("file_close_exit_actions") 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") wait_until(lambda: not window.web_view.page().isLoading(), timeout_ms=30000) if not hasattr(window, "manage_external_apps_action"): checks.append("manage_external_apps_action") close_window = MainWindow(project_root=project_root) close_window.close_project_folder() if close_window.has_project or close_window.entries: checks.append("close_folder_state") if close_window.tabs.count() != 1 or not bool(close_window.tabs.currentWidget().property("is_welcome")): checks.append("close_folder_welcome") close_window.close() 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 window.web_view.page().runJavaScript("Math.max(0, window.scrollY || document.documentElement.scrollTop || 0)", store_scroll) wait_until(lambda: "scroll_y" in result, timeout_ms=30000) 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())) page_for_left_click = ReaderPage() left_click_events: list[tuple[str, bool]] = [] page_for_left_click.local_link_requested.connect(lambda url, new_tab: left_click_events.append((url.toString(), new_tab))) accepted = page_for_left_click.acceptNavigationRequest( manual_url, QWebEnginePage.NavigationType.NavigationTypeLinkClicked, True, ) if accepted or left_click_events[-1:] != [(manual_url.toString(), True)]: checks.append("local_link_left_click_new_tab_default") 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() sample_item = window.path_to_item.get((project_root / "sample.md").resolve()) manual_item = window.path_to_item.get((project_root / "docs" / "user_manual.md").resolve()) if sample_item is None or manual_item is None: checks.append("tree_open_items") else: tree_tab_count = window.tabs.count() window._open_tree_item(manual_item) tree_loop = QEventLoop() QTimer.singleShot(700, tree_loop.quit) tree_loop.exec() if window.tabs.count() != tree_tab_count + 1: checks.append("tree_open_unopened_new_tab") if window.current_file != (project_root / "docs" / "user_manual.md").resolve(): checks.append("tree_open_unopened_file") 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(): checks.append("tree_open_existing_switch") export_test_path = project_root / "__gui_smoke_export.html" try: window._write_exported_html(export_test_path, "