from __future__ import annotations import os import shutil import sys import tempfile from pathlib import Path os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import fitz from PySide6.QtCore import QEventLoop, QSettings, QThread, QTimer from PySide6.QtWidgets import QApplication PROJECT_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PROJECT_ROOT)) from pdfreaderlite.core.document import PdfDocument from pdfreaderlite.ui.main_window import MainWindow, OpenPdfWorker from pdfreaderlite.ui.page_manager import PageManagerDialog def create_multi_page_pdf(path: Path, page_count: int = 5) -> None: doc = fitz.open() try: for page_index in range(page_count): page = doc.new_page(width=420, height=560) page.insert_text((72, 72), f"Page {page_index + 1}") page.insert_text((72, 120), "left column alpha beta gamma") page.insert_text((250, 120), "right column delta epsilon zeta") doc.save(path) finally: doc.close() def create_line_number_pdf(path: Path) -> None: doc = fitz.open() try: page = doc.new_page(width=420, height=560) for line in range(1, 8): y = 72 + line * 22 page.insert_text((18, y), str(line)) page.insert_text((64, y), f"body text line {line} selectable content") page.insert_text((150, 260), "WATERMARK") doc.save(path) finally: doc.close() def assert_save_failure_keeps_document_open(path: Path, temp_dir: Path) -> None: document = PdfDocument() document.open(path) document.add_note(0, "dirty note") assert document.is_dirty invalid_target = temp_dir / "target_is_directory" invalid_target.mkdir() try: document.save_as(invalid_target) except Exception: pass else: raise AssertionError("save_as should fail when target is a directory") assert document.is_open assert document.is_dirty assert document.render_page(0, 0.5).width() > 0 document.save_as(temp_dir / "recovered.pdf") assert not document.is_dirty document.close() def assert_repeated_save_keeps_file_unlocked(path: Path) -> None: document = PdfDocument() document.open(path) document.add_note(0, "first") document.save() document.add_note(0, "second") document.save() assert document.is_open assert not document.is_dirty document.close() def assert_render_cache_respects_memory_limit(path: Path) -> None: document = PdfDocument() document.open(path) original_limit = document._MAX_RENDER_CACHE_BYTES try: document._MAX_RENDER_CACHE_BYTES = 1 image = document.render_page(0, 1.0) assert image.width() > 0 assert document._render_cache_bytes <= document._MAX_RENDER_CACHE_BYTES assert len(document._render_cache) == 0 finally: document._MAX_RENDER_CACHE_BYTES = original_limit document.close() def assert_large_snapshot_is_skipped(path: Path) -> None: document = PdfDocument() document.open(path) original_limit = document._MAX_SNAPSHOT_BYTES try: document._MAX_SNAPSHOT_BYTES = 1 document.add_note(0, "large snapshot skip") assert not document.can_undo() finally: document._MAX_SNAPSHOT_BYTES = original_limit document.close() def assert_save_avoids_memory_backup(path: Path, temp_dir: Path) -> None: document = PdfDocument() document.open(path) document.add_note(0, "no memory backup") document.to_bytes = lambda: (_ for _ in ()).throw( AssertionError("save_as should not require an in-memory recovery copy") ) document.save_as(temp_dir / "saved_without_memory_backup.pdf") assert document.is_open assert not document.is_dirty document.close() def assert_text_selection_stays_in_column(path: Path) -> None: document = PdfDocument() document.open(path) text, _rects = document.text_selection(0, (60, 105, 220, 145), (70, 115), (210, 135)) assert "left column" in text assert "right column" not in text document.close() def assert_line_numbers_are_filtered(path: Path) -> None: document = PdfDocument() document.open(path) text, _rects = document.text_selection(0, (10, 80, 330, 160), (12, 80), (330, 160)) assert "body text line" in text assert "\n1\n" not in f"\n{text}\n" assert "WATERMARK" not in text document.close() def assert_annotation_editing_is_stable(path: Path) -> None: document = PdfDocument() document.open(path) text, rects = document.text_selection(0, (60, 105, 220, 145), (70, 115), (210, 135)) assert text and rects markup = document.add_text_markup(0, rects, "highlight", content="review") assert markup is not None recolored = document.update_text_markup_color(0, markup.xref, (1.0, 0.45, 0.0)) assert recolored is not None freetext = document.add_text(0, "old") edited = document.update_freetext_annotation(0, freetext.xref, "new", 16, (0.1, 0.2, 0.3)) assert edited is not None and edited.content == "new" document.save() document.close() reopened = PdfDocument() reopened.open(path) annotations = reopened.annotations() assert any(item.content == "review" for item in annotations) assert any(item.content == "new" for item in annotations) reopened.close() def assert_open_bytes_and_annotation_cache_are_stable(path: Path) -> None: document = PdfDocument() document.open_bytes(path.read_bytes(), path) first = document.annotations() second = document.annotations() assert first == second document.add_note(0, "cache invalidation") updated = document.annotations() assert len(updated) >= len(first) + 1 assert any(item.content == "cache invalidation" for item in updated) document.close() def assert_page_operations_keep_view(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) window = MainWindow() try: window.open_file(path) window.viewer.go_to_page(2) app.processEvents() window.viewer.set_zoom(1.6) app.processEvents() assert window.viewer.page_index == 2 window.rotate_page() app.processEvents() assert window.viewer.page_index == 2 window.insert_blank_page() app.processEvents() assert window.viewer.page_index == 3 finally: for session in list(window.sessions): session.document.close() window.close() def assert_async_viewer_render_finishes(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) window = MainWindow() try: window.open_file(path) for _ in range(160): if window.viewer._rendered_pages: break loop = QEventLoop() QTimer.singleShot(10, loop.quit) loop.exec() app.processEvents() assert window.viewer._rendered_pages finally: window.viewer.stop_async_render() for session in list(window.sessions): session.document.close() window.close() def assert_background_open_large_pdf(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) window = MainWindow() thread = QThread() worker = OpenPdfWorker(1, path) result: dict[str, object] = {} try: worker.moveToThread(thread) def finish_open(job_id: int, data: bytes, file_path: str, password: str) -> None: result["data"] = data result["file_path"] = file_path result["password"] = password thread.quit() def fail_open(_job_id: int, message: str) -> None: result["error"] = message thread.quit() thread.started.connect(worker.run) worker.finished.connect(finish_open) worker.failed.connect(fail_open) worker.encrypted.connect(lambda _job_id: result.setdefault("encrypted", True)) worker.encrypted.connect(thread.quit) thread.start() for _ in range(200): if not thread.isRunning(): break loop = QEventLoop() QTimer.singleShot(10, loop.quit) loop.exec() app.processEvents() assert not thread.isRunning() assert "error" not in result assert not result.get("encrypted") data = result.get("data") assert isinstance(data, bytes) and data window._apply_opened_pdf( window.sessions[window.active_session_index], data, Path(str(result["file_path"])), str(result.get("password") or "") or None, ) assert window.document.is_open assert window.document.page_count > 0 app.processEvents() finally: if thread.isRunning(): thread.quit() thread.wait(1000) worker.deleteLater() thread.deleteLater() for session in list(window.sessions): session.viewer.stop_async_render() session.document.close() window.close() def assert_missing_raster_fails_before_mutation(path: Path) -> None: document = PdfDocument() document.open(path) try: document.insert_image_rect(0, path.parent / "missing.png", (72, 72, 140, 120)) except FileNotFoundError: pass else: raise AssertionError("missing image should fail before mutating the PDF") assert not document.can_undo() document.save() document.close() def assert_background_search_returns_results(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) window = MainWindow() try: window.open_file(path) window._TRANSACTION_MEMORY_LIMIT = 1 window.search_box.setText("left column") window.search() for _ in range(100): if window._search_worker is None: break loop = QEventLoop() QTimer.singleShot(10, loop.quit) loop.exec() app.processEvents() assert window._search_worker is None assert window.search_results.count() > 0 finally: for session in list(window.sessions): session.document.close() window.close() def assert_consecutive_searches_do_not_keep_stale_worker(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) window = MainWindow() try: window.open_file(path) window.search_box.setText("left column") window.search() window.search_box.setText("right column") window.search() for _ in range(160): if window._search_worker is None: break loop = QEventLoop() QTimer.singleShot(10, loop.quit) loop.exec() app.processEvents() assert window._search_worker is None assert window._search_thread is None assert window.search_results.count() > 0 finally: window._stop_search_worker(wait_ms=1000) for session in list(window.sessions): session.document.close() window.close() def assert_page_manager_external_thumbnails_are_queued(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) document = PdfDocument() document.open(path) dialog = PageManagerDialog(document) try: before = dialog.grid.count() dialog.insert_external_pdfs([str(path)], before) assert dialog.grid.count() == before + document.page_count loop = QEventLoop() QTimer.singleShot(250, loop.quit) loop.exec() app.processEvents() assert not dialog.grid.item(before).icon().isNull() finally: dialog.close() document.close() def assert_page_manager_close_clears_thumbnail_queue(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) document = PdfDocument() document.open(path) dialog = PageManagerDialog(document) try: dialog.insert_external_pdfs([str(path)], dialog.grid.count()) assert dialog._thumbnail_queue dialog.done(0) app.processEvents() assert not dialog._thumbnail_timer.isActive() assert not dialog._thumbnail_queue assert not dialog._external_thumbnail_docs finally: document.close() def assert_large_transaction_uses_file_checkpoint(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) window = MainWindow() try: window.open_file(path) original_limit = window._TRANSACTION_PAGE_LIMIT window._TRANSACTION_PAGE_LIMIT = 1 checkpoint = window._make_document_transaction_checkpoint() try: assert checkpoint["type"] == "file" assert Path(str(checkpoint["path"])).exists() finally: window._cleanup_document_transaction_checkpoint(checkpoint) window._TRANSACTION_PAGE_LIMIT = original_limit finally: for session in list(window.sessions): session.document.close() window.close() def assert_multi_tab_delayed_signal_is_ignored(path: Path, settings_dir: Path) -> None: QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(settings_dir)) app = QApplication.instance() or QApplication([]) second = path.parent / "second.pdf" shutil.copy2(path, second) window = MainWindow() try: window.open_file(path) window.open_file(second) assert len(window.sessions) >= 2 window.tab_widget.setCurrentIndex(1) app.processEvents() current_page = window.viewer.page_index hidden_viewer = window.sessions[0].viewer hidden_viewer.page_changed.emit(3) app.processEvents() assert window.viewer is window.sessions[1].viewer assert window.viewer.page_index == current_page finally: for session in list(window.sessions): session.document.close() window.close() def assert_undo_history_is_limited(path: Path) -> None: document = PdfDocument() document.open(path) for index in range(30): document.add_note(0, f"note {index}", (72, 72 + index)) assert len(document._undo_stack) <= document._MAX_HISTORY_ITEMS assert document._undo_stack_bytes <= document._MAX_HISTORY_BYTES document.close() def main() -> int: temp_dir = Path(tempfile.mkdtemp(prefix="pdfreaderlite_stability_")) try: settings_dir = temp_dir / "settings" settings_dir.mkdir() pdf_path = temp_dir / "source.pdf" editable_pdf = temp_dir / "editable.pdf" line_number_pdf = temp_dir / "line_numbers.pdf" create_multi_page_pdf(pdf_path) create_line_number_pdf(line_number_pdf) shutil.copy2(pdf_path, editable_pdf) assert_save_failure_keeps_document_open(pdf_path, temp_dir) assert_repeated_save_keeps_file_unlocked(pdf_path) assert_render_cache_respects_memory_limit(pdf_path) assert_large_snapshot_is_skipped(pdf_path) assert_save_avoids_memory_backup(pdf_path, temp_dir) assert_text_selection_stays_in_column(pdf_path) assert_line_numbers_are_filtered(line_number_pdf) assert_annotation_editing_is_stable(editable_pdf) assert_open_bytes_and_annotation_cache_are_stable(pdf_path) assert_page_operations_keep_view(pdf_path, settings_dir) assert_async_viewer_render_finishes(pdf_path, settings_dir) assert_background_open_large_pdf(pdf_path, settings_dir) assert_background_search_returns_results(pdf_path, settings_dir) assert_consecutive_searches_do_not_keep_stale_worker(pdf_path, settings_dir) assert_page_manager_external_thumbnails_are_queued(pdf_path, settings_dir) assert_page_manager_close_clears_thumbnail_queue(pdf_path, settings_dir) assert_large_transaction_uses_file_checkpoint(pdf_path, settings_dir) assert_missing_raster_fails_before_mutation(pdf_path) assert_multi_tab_delayed_signal_is_ignored(pdf_path, settings_dir) assert_undo_history_is_limited(pdf_path) print("PDFReaderLite stability regression test passed.") return 0 finally: shutil.rmtree(temp_dir, ignore_errors=True) if __name__ == "__main__": raise SystemExit(main())