from __future__ import annotations import os import sys import traceback import zipfile 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, QSettings, QTimer, QUrl, Qt from PySide6.QtGui import QTextCursor from PySide6.QtWebEngineCore import QWebEnginePage from PySide6.QtWidgets import QApplication, QMessageBox, QPushButton, QToolBar from mdhelper.main_window import MainWindow, ReaderPage, ReaderView, VideoPlayerWidget from mdhelper.markdown_editor import MarkdownEditorDialog from mdhelper.settings_dialog import AppPreferences, SettingsDialog from mdhelper.style_dialog import DocumentStyleEditorDialog def main() -> int: 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") 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") original_file_groups = empty_window.document_file_groups empty_window.document_file_groups = ("markdown", "python", "cpp") empty_window._refresh_document_entries(force=True) code_suffixes = {".py", ".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".hpp"} 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")): 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.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 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 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.tabs.currentWidget() if isinstance(current_reader, ReaderView) 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, 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.wheel_scroll_speed_spin.setValue(2.2) if abs(settings_dialog.preferences().wheel_scroll_speed - 2.2) > 0.01: checks.append("settings_wheel_scroll_speed_value") 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: 1120px" 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: 1120px" 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") toc_refresh_loop = QEventLoop() QTimer.singleShot(700, toc_refresh_loop.quit) toc_refresh_loop.exec() 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 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())) 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") window._open_tree_item(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, "