"""Real WebEngine, dialogs, cancellation and PDF integration checks.""" from __future__ import annotations import os os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3") import sys import tempfile import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from PySide6.QtCore import QMimeData, QSettings, QTimer from PySide6.QtGui import QColor, QFontDatabase, QImage, QTextCursor from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QPushButton, QSpinBox, QTableWidget from pypdf import PdfReader from mdhelper.main_window import MainWindow from mdhelper.markdown_editor import MarkdownEditorDialog from mdhelper.export_settings import PageSettings from mdhelper.pdf_export import PdfExportSettingsDialog from mdhelper.file_versions import VersionStore def main(): output = ROOT / "pack" / "output" / "improvements-qa" output.mkdir(parents=True, exist_ok=True) app = QApplication.instance() or QApplication([]) if not QFontDatabase.families(): QFontDatabase.addApplicationFont("C:/Windows/Fonts/msyh.ttc") app.setQuitOnLastWindowClosed(False) warnings = [] QMessageBox.warning = staticmethod(lambda parent, title, text, *args: warnings.append(str(text))) with tempfile.TemporaryDirectory(prefix="mdhelper-improvements-") as temporary: directory = Path(temporary) QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(directory / "settings")) os.environ["MDHELPER_HISTORY_DIR"] = str(directory / "history") path = directory / "报告.md" path.write_text("# OLD_DISK\n\n旧内容", encoding="utf-8") window = MainWindow(None, app_root=ROOT) window.prepare_reader_before_show(); window.resize(1380, 900); window.show() def wait(condition, seconds=30): end = time.monotonic() + seconds while not condition() and time.monotonic() < end: app.processEvents(); time.sleep(0.01) assert condition(), "Integration check timed out" def js(script): values = [] editor.preview.page().runJavaScript(script, values.append) wait(lambda: bool(values), 10) return values[0] window.open_document(path) window.edit_current_markdown() editor = window.tabs.currentWidget() assert isinstance(editor, MarkdownEditorDialog) source = "# 最新报告 FRESH_EDITOR\n\n**中文加粗。**紧接正文。\n\n" + "\n\n".join(f"## 章节 {n}\n\n" + "用于检查段落和字体。" * 12 for n in range(1, 10)) editor.replace_source_undoable(source) image = QImage(300, 900, QImage.Format.Format_RGB32); image.fill(QColor("#b8d6ef")) mime = QMimeData(); mime.setImageData(image) cursor = editor.editor.textCursor(); cursor.setPosition(source.index("## 章节 3")); editor.editor.setTextCursor(cursor) editor.editor.insertFromMimeData(mime) editor.editor.textCursor().insertText("\n\n") source = editor.source_text() assert ".assets" in source wait(lambda: not editor._preview_dirty) wait(lambda: js("document.querySelectorAll('[data-source-line]').length") > 10) cursor = editor.editor.textCursor(); cursor.movePosition(QTextCursor.MoveOperation.End) editor.editor.setTextCursor(cursor); editor.editor.ensureCursorVisible() wait(lambda: js("window.scrollY") > 200) editor.sync_scroll_checkbox.setChecked(False) before = js("window.scrollY") editor.editor.verticalScrollBar().setValue(0) end = time.monotonic() + .3 while time.monotonic() < end: app.processEvents(); time.sleep(.01) assert abs(js("window.scrollY") - before) < 2 editor.sync_scroll_checkbox.setChecked(True) editor._sync_preview_to_source_line() wait(lambda: js("window.scrollY") < 100) # Wait until programmatic suppression expires, then emulate a preview scroll. end = time.monotonic() + .25 while time.monotonic() < end: app.processEvents(); time.sleep(.01) js("document.dispatchEvent(new WheelEvent('wheel')); window.scrollTo(0, document.querySelectorAll('h2')[5].offsetTop)") wait(lambda: editor.editor.firstVisibleBlock().blockNumber() >= 15) window.grab().save(str(output / "editor.png")) # Exercise table dialog controls, clipboard import and undo through the toolbar. before_table = editor.source_text() def table_dialog(): dialog = QApplication.activeModalWidget() assert isinstance(dialog, QDialog) QApplication.clipboard().setText("项目\t数值\nA\t10\nB\t20") next(b for b in dialog.findChildren(QPushButton) if b.text() == "从 Excel 粘贴").click() next(b for b in dialog.findChildren(QPushButton) if b.text() == "插入列").click() assert dialog.findChild(QTableWidget).columnCount() == 3 dialog.grab().save(str(output / "table.png")); dialog.accept() QTimer.singleShot(100, table_dialog); editor._edit_table() assert "| 项目" in editor.source_text() editor.editor.undo(); assert editor.source_text() == before_table assert window.save_markdown_source(path, source, reload_current=False) assert VersionStore().versions(path)[0].read_text(encoding="utf-8") == "# OLD_DISK\n\n旧内容" def history_dialog(): dialog = QApplication.activeModalWidget() dialog.grab().save(str(output / "history.png")); dialog.accept() QTimer.singleShot(100, history_dialog); editor.show_history() assert "OLD_DISK" in editor.source_text() editor.editor.undo(); assert editor.source_text() == source # Current editor text must win over saved disk in the following export. editor.replace_source_undoable(source.replace("FRESH_EDITOR", "LATEST_UNSAVED")) settings = PageSettings(paper="A4", landscape=True, include_toc=True, toc_depth=2, header="测试报告 Header", footer="内部资料 Footer", page_numbers=True) dialog = PdfExportSettingsDialog(settings) dialog.show(); app.processEvents(); dialog.grab().save(str(output / "page-settings.png")); dialog.close() target = output / "landscape.pdf" target.write_bytes(b"old output") window.export_pdf_to_path(target, settings) window._pdf_controller.cancel() assert target.read_bytes() == b"old output" window.export_pdf_to_path(target, settings) # Switching tabs must not change the active PDF snapshot or resource directory. other = directory / "other.md"; other.write_text("# Other tab", encoding="utf-8") window.open_document(other, new_tab=True) wait(lambda: getattr(window, "_pdf_export_page", None) is None, 45) assert not warnings, warnings pdf = PdfReader(target) text = "\n".join(page.extract_text() for page in pdf.pages) assert "LATEST_UNSAVED" in text and "OLD_DISK" not in text assert "Header" in text and "Footer" in text assert float(pdf.pages[0].mediabox.width) > float(pdf.pages[0].mediabox.height) assert len(pdf.pages) >= 2 # Exercise background Word conversion and wait for the final atomic output. window.tabs.setCurrentWidget(editor) word = output / "report.docx" window.export_docx_to_path(word, "pandoc", background=True, page_settings=settings) wait(lambda: not window._export_jobs, 30) assert word.exists() and not warnings, warnings editor.mark_saved(path, editor.source_text(), window._file_signature(path)) window.close(); app.processEvents() print("Improvements integration passed: images, tables, history, bidirectional scroll, PDF cancel/retry/snapshot, page headers, background Word.") return 0 if __name__ == "__main__": raise SystemExit(main())