from __future__ import annotations import math from dataclasses import dataclass from pathlib import Path from PySide6.QtCore import QSize, QSignalBlocker, QSettings, QStandardPaths, Qt, QUrl from PySide6.QtGui import ( QAction, QColor, QDesktopServices, QDragEnterEvent, QDropEvent, QFont, QIcon, QIntValidator, QKeySequence, QPainter, QPen, QPixmap, ) from PySide6.QtPrintSupport import QPrintDialog, QPrinter from PySide6.QtWidgets import ( QCheckBox, QColorDialog, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFormLayout, QFileDialog, QFrame, QHBoxLayout, QInputDialog, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMainWindow, QMenu, QMessageBox, QPushButton, QSplitter, QSlider, QSpinBox, QStatusBar, QStyle, QTabWidget, QToolBar, QToolButton, QVBoxLayout, QWidget, ) from pdfreaderlite import __version__ from pdfreaderlite.core.file_association import ( register_pdf_association, unregister_pdf_association, ) from pdfreaderlite.core.document import AnnotationInfo, EncryptedPdfError, FormField, PdfDocument, SearchMatch from pdfreaderlite.resources import pdf_icon_path, software_icon_path from pdfreaderlite.ui.page_manager import PageManagerDialog from pdfreaderlite.ui.pdf_viewer import PdfViewer from pdfreaderlite.ui.right_tools import RightToolsPanel from pdfreaderlite.ui.sidebar import Sidebar from pdfreaderlite.ui.signature_dialog import SignatureDialog @dataclass class DocumentSession: document: PdfDocument viewer: PdfViewer sidebar: Sidebar widget: QWidget session_raster_objects: list[dict[str, object]] selected_annotation: AnnotationInfo | None = None selected_raster_id: int | None = None next_raster_id: int = 1 class MainWindow(QMainWindow): def __init__(self) -> None: super().__init__() self.settings = QSettings() self.recent_files: list[str] = self.settings.value("recentFiles", [], list) self.dark_mode = self.settings.value("darkMode", False, bool) self.annotation_color = QColor( self.settings.value("annotationStyle/color", "#1f6fd1", str) ) self.annotation_line_width = int(self.settings.value("annotationStyle/lineWidth", 2, int)) self.annotation_opacity = float(self.settings.value("annotationStyle/opacity", 1.0, float)) self.sessions: list[DocumentSession] = [] self.active_session_index = -1 self.tab_widget = QTabWidget() self.tab_widget.setDocumentMode(True) self.tab_widget.setTabsClosable(True) self.document = PdfDocument() self.viewer = PdfViewer() self.sidebar = Sidebar() self.search_box = QLineEdit() self.search_results = QListWidget() self.annotation_filter_combo = QComboBox() self.annotation_search_box = QLineEdit() self.right_annotation_list = QListWidget() self.mode_status_label = QLabel() self.right_tools = RightToolsPanel(self.search_box, self.search_results) self.main_splitter: QSplitter | None = None self._last_right_tools_width = 280 self.pending_placement: dict[str, object] | None = None self.selected_annotation: AnnotationInfo | None = None self.session_raster_objects: list[dict[str, object]] = [] self.selected_raster_id: int | None = None self.next_raster_id = 1 self._create_document_session("未打开") self._build_window() self._build_actions() self._build_toolbar() self._build_status_controls() self._connect_signals() self._apply_theme() self._restore_window_state() self._update_title() self._update_status() def closeEvent(self, event) -> None: if not self._confirm_close_all_sessions(): event.ignore() return self.settings.setValue("windowGeometry", self.saveGeometry()) self.settings.setValue("windowState", self.saveState()) super().closeEvent(event) def dragEnterEvent(self, event: QDragEnterEvent) -> None: if self._dragged_pdf_paths(event): event.acceptProposedAction() return event.ignore() def dropEvent(self, event: QDropEvent) -> None: paths = self._dragged_pdf_paths(event) if not paths: event.ignore() return for path in paths: self.open_file(path) event.acceptProposedAction() def _dragged_pdf_paths(self, event: QDragEnterEvent | QDropEvent) -> list[Path]: if not event.mimeData().hasUrls(): return [] paths: list[Path] = [] for url in event.mimeData().urls(): if not url.isLocalFile(): continue path = Path(url.toLocalFile()) if path.suffix.lower() == ".pdf" and path.exists(): paths.append(path) return paths def _create_document_session(self, title: str = "未打开") -> DocumentSession: document = PdfDocument() viewer = PdfViewer() sidebar = Sidebar() splitter = QSplitter() splitter.addWidget(sidebar) splitter.addWidget(viewer) splitter.setSizes([188, 872]) session = DocumentSession( document=document, viewer=viewer, sidebar=sidebar, widget=splitter, session_raster_objects=[], ) self.sessions.append(session) self.tab_widget.addTab(splitter, title) self._connect_session_signals(session) self._activate_session(len(self.sessions) - 1) return session def _connect_session_signals(self, session: DocumentSession) -> None: session.sidebar.page_selected.connect(session.viewer.go_to_page) session.viewer.page_changed.connect(session.sidebar.select_page) session.viewer.page_changed.connect(lambda _: self._update_status()) session.viewer.page_changed.connect(lambda _: self._refresh_session_raster_overlays()) session.viewer.zoom_changed.connect(lambda _: self._update_status()) session.viewer.zoom_changed.connect(lambda zoom, watched=session: self._sync_zoom_controls(zoom, watched)) session.viewer.ink_stroke_finished.connect(self.add_ink_stroke) session.viewer.placement_requested.connect(self.place_pending_object) session.viewer.object_select_requested.connect(self.select_object_at_point) session.viewer.object_rect_changed.connect(self.update_selected_object_rect) session.viewer.object_context_requested.connect(self.show_object_context_menu) def _persist_current_session_state(self) -> None: index = self.active_session_index if 0 <= index < len(self.sessions): session = self.sessions[index] session.selected_annotation = self.selected_annotation session.selected_raster_id = self.selected_raster_id session.next_raster_id = self.next_raster_id def _activate_session(self, index: int) -> None: if not (0 <= index < len(self.sessions)): return session = self.sessions[index] self.document = session.document self.viewer = session.viewer self.sidebar = session.sidebar self.session_raster_objects = session.session_raster_objects self.selected_annotation = session.selected_annotation self.selected_raster_id = session.selected_raster_id self.next_raster_id = session.next_raster_id self.active_session_index = index if self.tab_widget.currentIndex() != index: self.tab_widget.setCurrentIndex(index) self._refresh_session_raster_overlays() self._sync_zoom_controls(self.viewer.zoom) self._update_title() self._update_status() def _current_session(self) -> DocumentSession: index = self.tab_widget.currentIndex() return self.sessions[index] def _on_tab_changed(self, index: int) -> None: self._persist_current_session_state() self._activate_session(index) def _close_tab(self, index: int) -> None: if not (0 <= index < len(self.sessions)): return session = self.sessions[index] if not self._confirm_close_session(index): return session.document.close() self.tab_widget.removeTab(index) self.sessions.pop(index) if not self.sessions: self._create_document_session("未打开") else: self._activate_session(min(index, len(self.sessions) - 1)) def _update_current_tab_title(self) -> None: index = self.tab_widget.currentIndex() if 0 <= index < len(self.sessions): title = self.document.title if self.document.is_open else "未打开" if self._session_has_unsaved_changes(self.sessions[index]): title = f"*{title}" self.tab_widget.setTabText(index, title) def _session_has_unsaved_changes(self, session: DocumentSession) -> bool: return session.document.is_dirty or bool(session.session_raster_objects) def _confirm_close_session(self, index: int) -> bool: session = self.sessions[index] if not self._session_has_unsaved_changes(session): return True title = session.document.title if session.document.is_open else "未打开" reply = QMessageBox.question( self, "未保存的更改", f"{title} 有未保存的更改,是否保存?", QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard | QMessageBox.StandardButton.Cancel, ) if reply == QMessageBox.StandardButton.Cancel: return False if reply == QMessageBox.StandardButton.Discard: return True self._activate_session(index) return self.save_file() def _confirm_close_all_sessions(self) -> bool: for index in reversed(range(len(self.sessions))): if not self._confirm_close_session(index): return False return True def previous_page(self) -> None: self.viewer.previous_page() def next_page(self) -> None: self.viewer.next_page() def zoom_in(self) -> None: self.viewer.zoom_in() def zoom_out(self) -> None: self.viewer.zoom_out() def fit_width(self) -> None: self.viewer.fit_width() def fit_page(self) -> None: self.viewer.fit_page() def set_zoom_percent(self, value: int) -> None: if not self.document.is_open: self._sync_zoom_controls(self.viewer.zoom) return self.viewer.set_zoom(self._zoom_from_slider_value(value)) def _slider_value_from_zoom(self, zoom: float) -> int: min_zoom = 0.2 max_zoom = 3.0 clamped_zoom = max(min_zoom, min(max_zoom, zoom)) span = math.log10(max_zoom) - math.log10(min_zoom) return round(((math.log10(clamped_zoom) - math.log10(min_zoom)) / span) * 2000) def _zoom_from_slider_value(self, value: int) -> float: min_zoom = 0.2 max_zoom = 3.0 span = math.log10(max_zoom) - math.log10(min_zoom) exponent = math.log10(min_zoom) + (value / 2000) * span return 10**exponent def apply_zoom_percent_input(self) -> None: if not self.document.is_open: self._sync_zoom_controls(self.viewer.zoom) return text = self.zoom_percent_input.text().strip().removesuffix("%") try: percent = int(text) except ValueError: self._sync_zoom_controls(self.viewer.zoom) return if 20 <= percent <= 300: self.viewer.set_zoom(percent / 100) self._sync_zoom_controls(self.viewer.zoom) def _sync_zoom_controls( self, zoom: float, watched: DocumentSession | None = None, ) -> None: if not hasattr(self, "zoom_slider"): return if watched is not None and watched is not self._current_session(): return percent = max(20, min(300, round(zoom * 100))) with QSignalBlocker(self.zoom_slider), QSignalBlocker(self.zoom_percent_input): self.zoom_slider.setValue(self._slider_value_from_zoom(zoom)) self.zoom_percent_input.setText(str(percent)) def _sync_page_controls(self) -> None: if not hasattr(self, "page_number_input"): return if not self.document.is_open: with QSignalBlocker(self.page_number_input): self.page_number_input.setValidator(QIntValidator(1, 1, self.page_number_input)) self.page_number_input.setText("1") self.page_number_input.setEnabled(False) self.page_total_label.setText("/ 0 页") return with QSignalBlocker(self.page_number_input): self.page_number_input.setEnabled(True) self.page_number_input.setValidator(QIntValidator(1, self.document.page_count, self.page_number_input)) self.page_number_input.setText(str(self.viewer.page_index + 1)) self.page_total_label.setText(f"/ {self.document.page_count} 页") def apply_page_number_input(self) -> None: if not self.document.is_open: self._sync_page_controls() return try: page = int(self.page_number_input.text().strip()) except ValueError: self._sync_page_controls() return if 1 <= page <= self.document.page_count: self.viewer.go_to_page(page - 1) self._sync_page_controls() def offer_restore_last_file(self) -> None: last_file = self.settings.value("lastOpenFile", "", str) if not last_file or self.document.is_open or not Path(last_file).exists(): return reply = QMessageBox.question( self, "恢复上次文件", f"是否打开上次阅读的文件?\n\n{last_file}", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, ) if reply == QMessageBox.StandardButton.Yes: self.open_file(last_file) def open_file(self, path: str | Path | None = None) -> None: if path is None: selected, _ = QFileDialog.getOpenFileName( self, "打开 PDF", "", "PDF 文件 (*.pdf);;所有文件 (*.*)" ) if not selected: return path = selected if self.document.is_open: self._create_document_session(Path(path).name) try: self._clear_session_raster_objects() self.document.open(path) self.viewer.set_document(self.document) self.sidebar.load_document(self.document) self._remember_file(str(path)) self._update_current_tab_title() self._update_title() self._update_status() except EncryptedPdfError: password, ok = QInputDialog.getText( self, "输入密码", "该 PDF 需要打开密码:", QLineEdit.EchoMode.Password, ) if ok and password: try: self._clear_session_raster_objects() self.document.open(path, password) self.viewer.set_document(self.document) self.sidebar.load_document(self.document) self._remember_file(str(path)) self._update_current_tab_title() self._update_title() self._update_status() except Exception as exc: QMessageBox.critical(self, "打开失败", f"密码错误或无法打开 PDF:\n{exc}") except Exception as exc: QMessageBox.critical(self, "打开失败", f"无法打开 PDF:\n{exc}") def save_file(self) -> bool: if not self._ensure_document(): return False try: self._flush_session_raster_objects() self.document.save() self._update_current_tab_title() self.statusBar().showMessage("已保存", 3000) return True except Exception as exc: QMessageBox.critical(self, "保存失败", f"无法保存文件:\n{exc}") return False def save_as_file(self) -> bool: if not self._ensure_document(): return False selected, _ = QFileDialog.getSaveFileName( self, "另存为", self.document.title, "PDF 文件 (*.pdf)" ) if not selected: return False if not selected.lower().endswith(".pdf"): selected += ".pdf" try: self._flush_session_raster_objects() self.document.save_as(selected) self._remember_file(selected) self._update_current_tab_title() self._update_title() self.statusBar().showMessage("已另存为", 3000) return True except Exception as exc: QMessageBox.critical(self, "另存为失败", f"无法保存文件:\n{exc}") return False def save_encrypted_file(self) -> None: if not self._ensure_document(): return password, ok = QInputDialog.getText( self, "密码保护", "输入打开密码:", QLineEdit.EchoMode.Password, ) if not ok or not password: return permission_dialog = QDialog(self) permission_dialog.setWindowTitle("权限设置") permission_layout = QVBoxLayout(permission_dialog) allow_print = QCheckBox("允许打印") allow_copy = QCheckBox("允许复制") allow_modify = QCheckBox("允许修改") allow_print.setChecked(True) allow_copy.setChecked(True) permission_layout.addWidget(allow_print) permission_layout.addWidget(allow_copy) permission_layout.addWidget(allow_modify) permission_buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel ) permission_buttons.accepted.connect(permission_dialog.accept) permission_buttons.rejected.connect(permission_dialog.reject) permission_layout.addWidget(permission_buttons) if permission_dialog.exec() != QDialog.DialogCode.Accepted: return selected, _ = QFileDialog.getSaveFileName( self, "保存加密 PDF", self.document.title, "PDF 文件 (*.pdf)" ) if not selected: return if not selected.lower().endswith(".pdf"): selected += ".pdf" try: self._flush_session_raster_objects() self.document.save_encrypted( selected, password, allow_print=allow_print.isChecked(), allow_copy=allow_copy.isChecked(), allow_modify=allow_modify.isChecked(), ) self._remember_file(selected) self._update_current_tab_title() self.statusBar().showMessage("已保存加密 PDF", 3000) except Exception as exc: QMessageBox.critical(self, "保存失败", f"无法保存加密 PDF:\n{exc}") def remove_password_file(self) -> None: if not self._ensure_document(): return selected, _ = QFileDialog.getSaveFileName( self, "移除密码并另存为", self.document.title, "PDF 文件 (*.pdf)" ) if not selected: return if not selected.lower().endswith(".pdf"): selected += ".pdf" try: self._flush_session_raster_objects() self.document.save_as(selected) self._remember_file(selected) self._update_current_tab_title() self._update_title() self.statusBar().showMessage("已另存为无密码 PDF", 3000) except Exception as exc: QMessageBox.critical(self, "移除失败", f"无法移除密码:\n{exc}") def print_document(self) -> None: if not self._ensure_document(): return printer = QPrinter(QPrinter.PrinterMode.HighResolution) printer.setDocName(self.document.title) dialog = QPrintDialog(printer, self) if dialog.exec() != QDialog.DialogCode.Accepted: return painter = QPainter() if not painter.begin(printer): QMessageBox.critical(self, "打印失败", "无法启动打印任务。") return try: for page_index in range(self.document.page_count): if page_index > 0: printer.newPage() image = self.document.render_page(page_index, 2.0) page_rect = printer.pageRect(QPrinter.Unit.DevicePixel) scaled = image.scaled( page_rect.size().toSize(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation, ) x = int(page_rect.x() + (page_rect.width() - scaled.width()) / 2) y = int(page_rect.y() + (page_rect.height() - scaled.height()) / 2) painter.drawImage(x, y, scaled) finally: painter.end() self.statusBar().showMessage("打印任务已发送", 3000) def rotate_page(self) -> None: if not self._ensure_document(): return self._flush_session_raster_objects() self.document.rotate_page(self.viewer.page_index) self._refresh_document_view() self.statusBar().showMessage("页面已旋转,记得保存", 3000) def delete_page(self) -> None: if not self._ensure_document(): return if self.document.page_count <= 1: QMessageBox.information(self, "无法删除", "PDF 至少需要保留一页。") return reply = QMessageBox.question( self, "删除页面", f"确定删除第 {self.viewer.page_index + 1} 页吗?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, ) if reply != QMessageBox.StandardButton.Yes: return self._flush_session_raster_objects() self.document.delete_page(self.viewer.page_index) self.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) self._refresh_document_view() self.statusBar().showMessage("页面已删除,记得保存", 3000) def move_page_dialog(self) -> None: if not self._ensure_document(): return if self.document.page_count <= 1: QMessageBox.information(self, "移动页面", "当前 PDF 只有一页。") return source_page, ok = QInputDialog.getInt( self, "移动页面", "要移动的页码:", self.viewer.page_index + 1, 1, self.document.page_count, ) if not ok: return target_page, ok = QInputDialog.getInt( self, "移动页面", "移动到页码:", source_page, 1, self.document.page_count, ) if not ok: return self._flush_session_raster_objects() self.document.move_page(source_page - 1, target_page - 1) self.viewer.go_to_page(target_page - 1) self._refresh_document_view() self.statusBar().showMessage("页面已移动,记得保存", 3000) def open_page_manager(self) -> None: if not self._ensure_document(): return if self.document.page_count <= 1: QMessageBox.information(self, "页面管理", "当前 PDF 只有一页。") return dialog = PageManagerDialog(self.document, self) if dialog.exec() != QDialog.DialogCode.Accepted: return try: self._flush_session_raster_objects() self.document.reorder_pages(dialog.page_order()) self.viewer.page_index = 0 self._refresh_document_view() self.statusBar().showMessage("页面顺序已更新,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "页面管理失败", f"无法重排页面:\n{exc}") def undo(self) -> None: if not self._ensure_document(): return if self.document.undo(): self.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) self._refresh_document_view() self.statusBar().showMessage("已撤销", 3000) else: self.statusBar().showMessage("没有可撤销的操作", 3000) def redo(self) -> None: if not self._ensure_document(): return if self.document.redo(): self.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) self._refresh_document_view() self.statusBar().showMessage("已重做", 3000) else: self.statusBar().showMessage("没有可重做的操作", 3000) def insert_blank_page(self) -> None: if not self._ensure_document(): return self._flush_session_raster_objects() new_index = self.document.insert_blank_page(self.viewer.page_index) self.viewer.go_to_page(new_index) self._refresh_document_view() self.statusBar().showMessage("已插入空白页,记得保存", 3000) def insert_pdf(self) -> None: if not self._ensure_document(): return selected, _ = QFileDialog.getOpenFileName( self, "插入 PDF", "", "PDF 文件 (*.pdf);;所有文件 (*.*)" ) if not selected: return try: self._flush_session_raster_objects() count = self.document.insert_pdf(selected, self.viewer.page_index) self._refresh_document_view() self.statusBar().showMessage(f"已插入 {count} 页,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "插入失败", f"无法插入 PDF:\n{exc}") def extract_pages(self) -> None: if not self._ensure_document(): return text, ok = QInputDialog.getText( self, "提取页面", "输入页码,例如 1,3,5-8:", ) if not ok or not text.strip(): return try: page_numbers = self._parse_page_numbers(text) except ValueError as exc: QMessageBox.warning(self, "页码错误", str(exc)) return selected, _ = QFileDialog.getSaveFileName( self, "保存提取页面", "提取页面.pdf", "PDF 文件 (*.pdf)" ) if not selected: return if not selected.lower().endswith(".pdf"): selected += ".pdf" try: self.document.extract_pages(page_numbers, selected) self.statusBar().showMessage("页面已提取", 3000) except Exception as exc: QMessageBox.critical(self, "提取失败", f"无法提取页面:\n{exc}") def split_pdf(self) -> None: if not self._ensure_document(): return folder = QFileDialog.getExistingDirectory(self, "选择拆分保存文件夹") if not folder: return try: self.document.split_to_folder(folder) self.statusBar().showMessage("PDF 已按页拆分", 3000) except Exception as exc: QMessageBox.critical(self, "拆分失败", f"无法拆分 PDF:\n{exc}") def merge_pdfs(self) -> None: selected_files, _ = QFileDialog.getOpenFileNames( self, "选择要合并的 PDF", "", "PDF 文件 (*.pdf);;所有文件 (*.*)" ) if not selected_files: return target, _ = QFileDialog.getSaveFileName(self, "保存合并 PDF", "合并文件.pdf", "PDF 文件 (*.pdf)") if not target: return if not target.lower().endswith(".pdf"): target += ".pdf" try: PdfDocument.merge_pdfs(selected_files, target) self.statusBar().showMessage("PDF 已合并", 3000) except Exception as exc: QMessageBox.critical(self, "合并失败", f"无法合并 PDF:\n{exc}") def export_current_page_image(self) -> None: if not self._ensure_document(): return selected, _ = QFileDialog.getSaveFileName( self, "导出当前页为图片", f"第{self.viewer.page_index + 1}页.png", "PNG 图片 (*.png)" ) if not selected: return if not selected.lower().endswith(".png"): selected += ".png" try: self.document.export_page_image(self.viewer.page_index, selected) self.statusBar().showMessage("当前页已导出为图片", 3000) except Exception as exc: QMessageBox.critical(self, "导出失败", f"无法导出图片:\n{exc}") def export_pages_images(self) -> None: if not self._ensure_document(): return text, ok = QInputDialog.getText(self, "导出页面图片", "输入页码,例如 1,3,5-8:") if not ok or not text.strip(): return try: page_numbers = self._parse_page_numbers(text) except ValueError as exc: QMessageBox.warning(self, "页码错误", str(exc)) return folder = QFileDialog.getExistingDirectory(self, "选择图片保存文件夹") if not folder: return try: self.document.export_pages_images(page_numbers, folder) self.statusBar().showMessage("页面图片已导出", 3000) except Exception as exc: QMessageBox.critical(self, "导出失败", f"无法导出图片:\n{exc}") def images_to_pdf(self) -> None: selected_files, _ = QFileDialog.getOpenFileNames( self, "选择图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff);;所有文件 (*.*)", ) if not selected_files: return target, _ = QFileDialog.getSaveFileName(self, "保存 PDF", "图片合成.pdf", "PDF 文件 (*.pdf)") if not target: return if not target.lower().endswith(".pdf"): target += ".pdf" try: PdfDocument.images_to_pdf(selected_files, target) self.statusBar().showMessage("图片已转换为 PDF", 3000) except Exception as exc: QMessageBox.critical(self, "转换失败", f"无法生成 PDF:\n{exc}") def edit_metadata(self) -> None: if not self._ensure_document(): return metadata = self.document.metadata() dialog = QDialog(self) dialog.setWindowTitle("文档信息") layout = QFormLayout(dialog) title_edit = QLineEdit(metadata.get("title", "")) author_edit = QLineEdit(metadata.get("author", "")) subject_edit = QLineEdit(metadata.get("subject", "")) keywords_edit = QLineEdit(metadata.get("keywords", "")) layout.addRow("标题", title_edit) layout.addRow("作者", author_edit) layout.addRow("主题", subject_edit) layout.addRow("关键词", keywords_edit) layout.addRow("页数", QLabel(str(self.document.page_count))) if self.document.path: layout.addRow("路径", QLabel(str(self.document.path))) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel ) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) layout.addRow(buttons) if dialog.exec() != QDialog.DialogCode.Accepted: return self.document.update_metadata( title_edit.text(), author_edit.text(), subject_edit.text(), keywords_edit.text(), ) self.statusBar().showMessage("文档信息已更新,记得保存", 3000) def fill_form_field(self) -> None: if not self._ensure_document(): return fields = self.document.form_fields() if not fields: QMessageBox.information(self, "表单", "当前 PDF 没有可填写的表单字段。") return dialog = QDialog(self) dialog.setWindowTitle("填写表单") layout = QFormLayout(dialog) field_combo = QComboBox() value_edit = QLineEdit() for field in fields: label = f"{field.name}(第 {field.page_index + 1} 页,{field.field_type})" field_combo.addItem(label, field) layout.addRow("字段", field_combo) layout.addRow("值", value_edit) def load_field(index: int) -> None: field: FormField = field_combo.itemData(index) value_edit.setText(field.value) field_combo.currentIndexChanged.connect(load_field) load_field(0) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel ) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) layout.addRow(buttons) if dialog.exec() != QDialog.DialogCode.Accepted: return selected_field: FormField = field_combo.currentData() if self.document.update_form_field(selected_field.name, value_edit.text()): self.viewer.render() self.statusBar().showMessage("表单字段已更新,记得保存", 3000) else: QMessageBox.warning(self, "填写失败", "没有找到对应的表单字段。") def show_annotations(self) -> None: if not self._ensure_document(): return annotations = self.document.annotations() if not annotations: QMessageBox.information(self, "注释列表", "当前 PDF 没有注释。") return dialog = QDialog(self) dialog.setWindowTitle("注释列表") layout = QVBoxLayout(dialog) annotation_list = QListWidget() for annotation in annotations: content = annotation.content or annotation.annotation_type item = QListWidgetItem( f"第 {annotation.page_index + 1} 页 {annotation.annotation_type} {content}" ) item.setData(Qt.ItemDataRole.UserRole, annotation) annotation_list.addItem(item) layout.addWidget(annotation_list) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Close ) buttons.button(QDialogButtonBox.StandardButton.Ok).setText("跳转") delete_button = buttons.addButton("删除", QDialogButtonBox.ButtonRole.ActionRole) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) layout.addWidget(buttons) deleted = {"value": False} def delete_selected_annotation() -> None: item = annotation_list.currentItem() if not item: return annotation = item.data(Qt.ItemDataRole.UserRole) reply = QMessageBox.question( self, "删除注释", "确定删除选中的注释吗?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, ) if reply == QMessageBox.StandardButton.Yes: self.document.delete_annotation(annotation.page_index, annotation.xref) self.viewer.render() self.statusBar().showMessage("注释已删除,记得保存", 3000) self._refresh_annotation_panel() deleted["value"] = True dialog.accept() delete_button.clicked.connect(delete_selected_annotation) result = dialog.exec() if deleted["value"]: return item = annotation_list.currentItem() if not item: return annotation = item.data(Qt.ItemDataRole.UserRole) if result == QDialog.DialogCode.Accepted: self.viewer.go_to_page(annotation.page_index) def go_to_page_dialog(self) -> None: if not self._ensure_document(): return page, ok = QInputDialog.getInt( self, "跳转页码", "页码:", self.viewer.page_index + 1, 1, self.document.page_count, ) if ok: self.viewer.go_to_page(page - 1) def search(self) -> None: query = self.search_box.text().strip() self.search_results.clear() if not self._ensure_document() or not query: self.right_tools.set_search_results_visible(False) return matches = self.document.search(query) for match in matches: item = QListWidgetItem(f"第 {match.page_index + 1} 页 {match.text}") item.setData(Qt.ItemDataRole.UserRole, match) self.search_results.addItem(item) self.right_tools.set_search_results_visible(bool(matches)) self.statusBar().showMessage(f"找到 {len(matches)} 个页面匹配", 3000) def _build_window(self) -> None: self.setWindowTitle("PDFReaderLite") self.setWindowIcon(QIcon(software_icon_path().as_posix())) self.resize(1320, 860) self.setStatusBar(QStatusBar()) self.setAcceptDrops(True) self.search_box.setObjectName("searchBox") self.search_results.setObjectName("searchResults") self.annotation_filter_combo.setObjectName("annotationFilterCombo") self.annotation_search_box.setObjectName("annotationSearchBox") self.tab_widget.setObjectName("documentTabs") self.right_tools.setObjectName("rightToolsPanel") self.main_splitter = QSplitter() self.main_splitter.setObjectName("mainSplitter") self.main_splitter.addWidget(self.tab_widget) self.main_splitter.addWidget(self.right_tools) self.main_splitter.setSizes([1060, 280]) self.setCentralWidget(self.main_splitter) self.search_box.setPlaceholderText("搜索文本,按 Enter") self.search_results.setAlternatingRowColors(True) self.annotation_filter_combo.addItem("全部注释", "all") self.annotation_filter_combo.addItem("高亮", "highlight") self.annotation_filter_combo.addItem("文本标记", "text_markup") self.annotation_filter_combo.addItem("便签/批注", "note") self.annotation_filter_combo.addItem("图形", "shape") self.annotation_filter_combo.addItem("画笔", "ink") self.annotation_search_box.setPlaceholderText("搜索注释内容") self.setStyleSheet( """ QMainWindow { background: #ededed; } QToolBar { background: #f8f8f8; border-bottom: 1px solid #d2d2d2; spacing: 4px; } QToolButton { padding: 6px 8px; } QLineEdit { padding: 7px; border: 1px solid #b9b9b9; border-radius: 3px; } QListWidget { background: #ffffff; border: 1px solid #d0d0d0; } """ ) def _build_actions(self) -> None: self.open_action = QAction("打开", self) self.open_action.setShortcut(QKeySequence.StandardKey.Open) self.save_action = QAction("保存", self) self.save_action.setShortcut(QKeySequence.StandardKey.Save) self.save_as_action = QAction("另存为", self) self.save_as_action.setShortcut(QKeySequence.StandardKey.SaveAs) self.save_encrypted_action = QAction("密码另存为", self) self.remove_password_action = QAction("移除密码另存为", self) self.print_action = QAction("打印", self) self.print_action.setShortcut(QKeySequence.StandardKey.Print) self.clear_recent_action = QAction("清空最近文件", self) self.undo_action = QAction("撤销", self) self.undo_action.setShortcut(QKeySequence.StandardKey.Undo) self.redo_action = QAction("重做", self) self.redo_action.setShortcut(QKeySequence.StandardKey.Redo) self.previous_action = QAction("上一页", self) self.previous_action.setShortcut(QKeySequence(Qt.Key.Key_PageUp)) self.next_action = QAction("下一页", self) self.next_action.setShortcut(QKeySequence(Qt.Key.Key_PageDown)) self.zoom_out_action = QAction("缩小", self) self.zoom_out_action.setShortcut(QKeySequence.StandardKey.ZoomOut) self.zoom_in_action = QAction("放大", self) self.zoom_in_action.setShortcut(QKeySequence.StandardKey.ZoomIn) self.zoom_slider = QSlider(Qt.Orientation.Horizontal) self.zoom_slider.setRange(0, 2000) self.zoom_slider.setSingleStep(25) self.zoom_slider.setPageStep(100) self.zoom_slider.setFixedWidth(150) self.zoom_slider.setToolTip("缩放") self.zoom_percent_input = QLineEdit() self.zoom_percent_input.setValidator(QIntValidator(20, 300, self)) self.zoom_percent_input.setFixedWidth(64) self.zoom_percent_input.setToolTip("缩放百分比") self.page_number_input = QLineEdit() self.page_number_input.setValidator(QIntValidator(1, 1, self)) self.page_number_input.setFixedWidth(48) self.page_number_input.setToolTip("当前页码") self.page_number_input.setEnabled(False) self.page_total_label = QLabel("/ 0 页") self.page_total_label.setObjectName("statusPageTotal") self.fit_width_action = QAction("适应宽度", self) self.fit_page_action = QAction("适应页面", self) self.go_to_page_action = QAction("跳转", self) self.go_to_page_action.setShortcut(QKeySequence("Ctrl+G")) self.rotate_action = QAction("旋转", self) self.delete_action = QAction("删除页", self) self.move_page_action = QAction("移动页面", self) self.page_manager_action = QAction("页面管理", self) self.insert_blank_action = QAction("插入空白页", self) self.insert_pdf_action = QAction("插入 PDF", self) self.extract_pages_action = QAction("提取页面", self) self.split_pdf_action = QAction("拆分 PDF", self) self.merge_pdfs_action = QAction("合并 PDF", self) self.export_current_image_action = QAction("当前页导出图片", self) self.export_pages_images_action = QAction("批量导出图片", self) self.images_to_pdf_action = QAction("图片转 PDF", self) self.metadata_action = QAction("文档信息", self) self.metadata_action.setShortcut(QKeySequence("Ctrl+I")) self.form_fill_action = QAction("填写表单", self) self.annotation_list_action = QAction("注释列表", self) self.highlight_action = QAction("高亮", self) self.highlight_action.setShortcut(QKeySequence("Ctrl+H")) self.underline_action = QAction("下划线", self) self.strikeout_action = QAction("删除线", self) self.note_action = QAction("批注", self) self.annotation_style_action = QAction("注释样式", self) self.select_object_action = QAction("选择对象", self) self.select_object_action.setCheckable(True) self.select_object_action.setShortcut(QKeySequence("V")) self.freehand_action = QAction("自由画笔", self) self.freehand_action.setCheckable(True) self.add_text_action = QAction("添加文本", self) self.place_text_action = QAction("点击放置文本", self) self.insert_image_action = QAction("插入图片", self) self.place_image_action = QAction("点击放置图片", self) self.signature_action = QAction("图片签名", self) self.place_signature_action = QAction("点击放置签名", self) self.draw_signature_action = QAction("手写签名", self) self.rectangle_action = QAction("矩形", self) self.circle_action = QAction("圆形", self) self.line_action = QAction("线条", self) self.arrow_action = QAction("箭头", self) self.cover_action = QAction("遮盖", self) self.dark_mode_action = QAction("深色模式", self) self.dark_mode_action.setCheckable(True) self.dark_mode_action.setChecked(self.dark_mode) self.toggle_edit_pdf_action = QAction("编辑PDF", self) self.toggle_edit_pdf_action.setCheckable(True) self.toggle_pages_action = QAction("页面", self) self.toggle_pages_action.setCheckable(True) self.toggle_tools_action = QAction("工具", self) self.toggle_tools_action.setCheckable(True) self.toggle_tools_action.setChecked(True) self.toggle_annotations_action = QAction("注释", self) self.toggle_annotations_action.setCheckable(True) self.toggle_read_action = QAction("阅读", self) self.toggle_read_action.setCheckable(True) self._apply_action_icons() file_menu = self.menuBar().addMenu("文件") file_menu.addAction(self.open_action) file_menu.addAction(self.save_action) file_menu.addAction(self.save_as_action) file_menu.addAction(self.save_encrypted_action) file_menu.addAction(self.remove_password_action) file_menu.addAction(self.print_action) self.recent_menu = file_menu.addMenu("最近打开") self._refresh_recent_menu() view_menu = self.menuBar().addMenu("视图") view_menu.addAction(self.previous_action) view_menu.addAction(self.next_action) view_menu.addAction(self.zoom_out_action) view_menu.addAction(self.zoom_in_action) view_menu.addAction(self.fit_width_action) view_menu.addAction(self.fit_page_action) view_menu.addAction(self.dark_mode_action) page_menu = self.menuBar().addMenu("页面") page_menu.addAction(self.go_to_page_action) page_menu.addAction(self.rotate_action) page_menu.addAction(self.delete_action) page_menu.addAction(self.move_page_action) page_menu.addAction(self.page_manager_action) page_menu.addAction(self.insert_blank_action) page_menu.addAction(self.insert_pdf_action) page_menu.addAction(self.extract_pages_action) page_menu.addAction(self.split_pdf_action) page_menu.addAction(self.merge_pdfs_action) tools_menu = self.menuBar().addMenu("工具") tools_menu.addAction(self.export_current_image_action) tools_menu.addAction(self.export_pages_images_action) tools_menu.addAction(self.images_to_pdf_action) tools_menu.addAction(self.metadata_action) tools_menu.addAction(self.form_fill_action) tools_menu.addAction(self.annotation_list_action) settings_menu = self.menuBar().addMenu("设置") self.register_pdf_action = QAction("注册 PDF 文件关联", self) self.unregister_pdf_action = QAction("取消 PDF 文件关联注册", self) self.default_apps_action = QAction("打开系统默认应用设置", self) settings_menu.addAction(self.register_pdf_action) settings_menu.addAction(self.unregister_pdf_action) settings_menu.addAction(self.default_apps_action) edit_menu = self.menuBar().addMenu("编辑") edit_menu.addAction(self.undo_action) edit_menu.addAction(self.redo_action) edit_menu.addAction(self.highlight_action) edit_menu.addAction(self.underline_action) edit_menu.addAction(self.strikeout_action) edit_menu.addAction(self.note_action) edit_menu.addAction(self.select_object_action) edit_menu.addAction(self.freehand_action) edit_menu.addAction(self.add_text_action) edit_menu.addAction(self.place_text_action) edit_menu.addAction(self.insert_image_action) edit_menu.addAction(self.place_image_action) edit_menu.addAction(self.signature_action) edit_menu.addAction(self.place_signature_action) edit_menu.addAction(self.draw_signature_action) edit_menu.addAction(self.rectangle_action) edit_menu.addAction(self.circle_action) edit_menu.addAction(self.line_action) edit_menu.addAction(self.arrow_action) edit_menu.addAction(self.cover_action) help_menu = self.menuBar().addMenu("帮助") self.shortcuts_action = QAction("快捷键", self) self.open_log_dir_action = QAction("打开日志目录", self) self.about_action = QAction("关于", self) help_menu.addAction(self.shortcuts_action) help_menu.addAction(self.open_log_dir_action) help_menu.addAction(self.about_action) self._build_right_tools_panel() def _text_icon(self, text: str, color: QColor | None = None) -> QIcon: pixmap = QPixmap(24, 24) pixmap.fill(Qt.GlobalColor.transparent) painter = QPainter(pixmap) painter.setRenderHint(QPainter.RenderHint.Antialiasing) pen_color = color or QColor("#2d73c5") font = QFont() font.setBold(True) font.setPixelSize(18 if len(text) <= 1 else 13) painter.setFont(font) painter.setPen(pen_color) painter.drawText(pixmap.rect(), Qt.AlignmentFlag.AlignCenter, text) painter.end() return QIcon(pixmap) def _apply_action_icons(self) -> None: icon_map = { self.open_action: QStyle.StandardPixmap.SP_DialogOpenButton, self.save_action: QStyle.StandardPixmap.SP_DialogSaveButton, self.print_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.undo_action: QStyle.StandardPixmap.SP_ArrowBack, self.redo_action: QStyle.StandardPixmap.SP_ArrowForward, self.previous_action: QStyle.StandardPixmap.SP_ArrowUp, self.next_action: QStyle.StandardPixmap.SP_ArrowDown, self.fit_page_action: QStyle.StandardPixmap.SP_FileDialogContentsView, self.go_to_page_action: QStyle.StandardPixmap.SP_ArrowRight, self.rotate_action: QStyle.StandardPixmap.SP_BrowserReload, self.delete_action: QStyle.StandardPixmap.SP_TrashIcon, self.move_page_action: QStyle.StandardPixmap.SP_FileDialogListView, self.page_manager_action: QStyle.StandardPixmap.SP_FileDialogInfoView, self.insert_blank_action: QStyle.StandardPixmap.SP_FileIcon, self.insert_pdf_action: QStyle.StandardPixmap.SP_FileLinkIcon, self.extract_pages_action: QStyle.StandardPixmap.SP_DialogSaveButton, self.split_pdf_action: QStyle.StandardPixmap.SP_DialogResetButton, self.merge_pdfs_action: QStyle.StandardPixmap.SP_DirIcon, self.export_current_image_action: QStyle.StandardPixmap.SP_DialogSaveButton, self.export_pages_images_action: QStyle.StandardPixmap.SP_DirOpenIcon, self.images_to_pdf_action: QStyle.StandardPixmap.SP_FileIcon, self.metadata_action: QStyle.StandardPixmap.SP_MessageBoxInformation, self.form_fill_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.annotation_list_action: QStyle.StandardPixmap.SP_FileDialogListView, self.highlight_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.underline_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.strikeout_action: QStyle.StandardPixmap.SP_DialogCancelButton, self.note_action: QStyle.StandardPixmap.SP_MessageBoxInformation, self.annotation_style_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.select_object_action: QStyle.StandardPixmap.SP_ArrowRight, self.freehand_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.add_text_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.place_text_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.insert_image_action: QStyle.StandardPixmap.SP_FileIcon, self.place_image_action: QStyle.StandardPixmap.SP_FileIcon, self.signature_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.place_signature_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.draw_signature_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.rectangle_action: QStyle.StandardPixmap.SP_FileDialogContentsView, self.circle_action: QStyle.StandardPixmap.SP_FileDialogContentsView, self.line_action: QStyle.StandardPixmap.SP_ArrowRight, self.arrow_action: QStyle.StandardPixmap.SP_ArrowRight, self.cover_action: QStyle.StandardPixmap.SP_DialogCloseButton, self.dark_mode_action: QStyle.StandardPixmap.SP_ComputerIcon, self.toggle_edit_pdf_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.toggle_pages_action: QStyle.StandardPixmap.SP_FileDialogInfoView, self.toggle_tools_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.toggle_annotations_action: QStyle.StandardPixmap.SP_FileDialogListView, self.toggle_read_action: QStyle.StandardPixmap.SP_FileDialogContentsView, } for action, standard_icon in icon_map.items(): action.setIcon(self.style().standardIcon(standard_icon)) self.save_as_action.setIcon(self._text_icon("另", QColor("#365f91"))) self.zoom_out_action.setIcon(self._text_icon("-", QColor("#2f5f9f"))) self.zoom_in_action.setIcon(self._text_icon("+", QColor("#2f5f9f"))) self.fit_width_action.setIcon(self._text_icon("<>", QColor("#2f5f9f"))) def _build_right_tools_panel(self) -> None: self.right_tools.add_section( "编辑 PDF", [ self.add_text_action, self.place_text_action, self.insert_image_action, self.place_image_action, self.cover_action, self.undo_action, self.redo_action, ], section_id="edit", ) self.right_tools.add_section( "注释", [ self.highlight_action, self.underline_action, self.strikeout_action, self.note_action, self.annotation_style_action, self.select_object_action, self.freehand_action, self.rectangle_action, self.circle_action, self.line_action, self.arrow_action, ], section_id="annotations", ) self.right_tools.add_annotation_list( "注释列表", self.right_annotation_list, "annotation_list", controls=[self.annotation_filter_combo, self.annotation_search_box], ) self.right_tools.add_section( "页面", [ self.rotate_action, self.delete_action, self.move_page_action, self.page_manager_action, self.insert_blank_action, self.insert_pdf_action, self.extract_pages_action, self.split_pdf_action, self.merge_pdfs_action, ], section_id="pages", ) self.right_tools.add_section( "签名与表单", [ self.signature_action, self.place_signature_action, self.draw_signature_action, self.form_fill_action, ], section_id="sign", ) self.right_tools.add_section( "导出与安全", [ self.export_current_image_action, self.export_pages_images_action, self.images_to_pdf_action, self.metadata_action, self.save_encrypted_action, self.remove_password_action, ], section_id="export", ) self.right_tools.add_section( "设置", [ self.register_pdf_action, self.default_apps_action, self.open_log_dir_action, ], section_id="settings", ) self.right_tools.finish() self.right_tools.show_sections(["sign", "export", "settings"]) def _build_toolbar(self) -> None: toolbar = QToolBar("主工具栏") self.main_toolbar = toolbar self._toolbar_page_size_actions = [] toolbar.setObjectName("mainToolBar") toolbar.setMovable(False) toolbar.setFloatable(False) toolbar.setAllowedAreas(Qt.ToolBarArea.TopToolBarArea) toolbar.setIconSize(QSize(18, 18)) toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) self.addToolBar(Qt.ToolBarArea.TopToolBarArea, toolbar) for action in [ self.open_action, self.save_action, self.save_as_action, ]: toolbar.addAction(action) toolbar.addSeparator() for action in [ self.undo_action, self.redo_action, ]: toolbar.addAction(action) toolbar.addAction(self.toggle_edit_pdf_action) toolbar.addAction(self.toggle_pages_action) toolbar.addAction(self.toggle_tools_action) toolbar.addAction(self.toggle_annotations_action) toolbar.addAction(self.toggle_read_action) def _status_action_button(self, action: QAction, width: int = 64) -> QToolButton: button = QToolButton() button.setObjectName("statusToolButton") button.setDefaultAction(action) button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) button.setIconSize(QSize(20, 20)) button.setMinimumWidth(width) button.setMinimumHeight(24) button.setAutoRaise(True) return button def _status_separator(self) -> QFrame: separator = QFrame() separator.setObjectName("statusSeparator") separator.setFrameShape(QFrame.Shape.VLine) separator.setFrameShadow(QFrame.Shadow.Plain) separator.setFixedHeight(18) return separator def _build_status_controls(self) -> None: status = self.statusBar() toolbar = getattr(self, "main_toolbar", None) if toolbar: for action in [ self.zoom_out_action, self.zoom_in_action, self.fit_width_action, self.fit_page_action, self.go_to_page_action, ]: toolbar.removeAction(action) for action in getattr(self, "_toolbar_page_size_actions", []): toolbar.removeAction(action) page_label = QLabel("第") page_label.setObjectName("statusPageLabel") zoom_label = QLabel("缩放") zoom_label.setObjectName("statusZoomLabel") self.zoom_slider.setObjectName("statusZoomSlider") self.zoom_slider.setFixedWidth(162) self.zoom_percent_input.setObjectName("statusZoomPercent") self.zoom_percent_input.setFixedWidth(58) self.mode_status_label.setObjectName("statusModeLabel") self.mode_status_label.setMinimumWidth(86) self._sync_mode_status() controls = QWidget() controls.setObjectName("statusPageControls") controls_layout = QHBoxLayout(controls) controls_layout.setContentsMargins(0, 0, 0, 0) controls_layout.setSpacing(8) for widget in [ page_label, self.page_number_input, self.page_total_label, self._status_separator(), self._status_action_button(self.zoom_out_action, 64), self._status_action_button(self.zoom_in_action, 64), zoom_label, self.zoom_percent_input, self.zoom_slider, self._status_separator(), self._status_action_button(self.fit_width_action, 92), self._status_action_button(self.fit_page_action, 92), ]: controls_layout.addWidget(widget) widget.show() controls.setFixedWidth(800) status.addPermanentWidget(self.mode_status_label, 0) status.addPermanentWidget(controls, 0) def _connect_signals(self) -> None: self.open_action.triggered.connect(lambda: self.open_file()) self.save_action.triggered.connect(self.save_file) self.save_as_action.triggered.connect(self.save_as_file) self.save_encrypted_action.triggered.connect(self.save_encrypted_file) self.remove_password_action.triggered.connect(self.remove_password_file) self.print_action.triggered.connect(self.print_document) self.clear_recent_action.triggered.connect(self.clear_recent_files) self.shortcuts_action.triggered.connect(self.show_shortcuts) self.open_log_dir_action.triggered.connect(self.open_log_dir) self.about_action.triggered.connect(self.show_about) self.undo_action.triggered.connect(self.undo) self.redo_action.triggered.connect(self.redo) self.previous_action.triggered.connect(self.previous_page) self.next_action.triggered.connect(self.next_page) self.zoom_out_action.triggered.connect(self.zoom_out) self.zoom_in_action.triggered.connect(self.zoom_in) self.zoom_slider.valueChanged.connect(self.set_zoom_percent) self.zoom_percent_input.editingFinished.connect(self.apply_zoom_percent_input) self.page_number_input.editingFinished.connect(self.apply_page_number_input) self.fit_width_action.triggered.connect(self.fit_width) self.fit_page_action.triggered.connect(self.fit_page) self.go_to_page_action.triggered.connect(self.go_to_page_dialog) self.rotate_action.triggered.connect(self.rotate_page) self.delete_action.triggered.connect(self.delete_page) self.move_page_action.triggered.connect(self.move_page_dialog) self.page_manager_action.triggered.connect(self.open_page_manager) self.insert_blank_action.triggered.connect(self.insert_blank_page) self.insert_pdf_action.triggered.connect(self.insert_pdf) self.extract_pages_action.triggered.connect(self.extract_pages) self.split_pdf_action.triggered.connect(self.split_pdf) self.merge_pdfs_action.triggered.connect(self.merge_pdfs) self.export_current_image_action.triggered.connect(self.export_current_page_image) self.export_pages_images_action.triggered.connect(self.export_pages_images) self.images_to_pdf_action.triggered.connect(self.images_to_pdf) self.metadata_action.triggered.connect(self.edit_metadata) self.form_fill_action.triggered.connect(self.fill_form_field) self.annotation_list_action.triggered.connect(self.show_annotations) self.register_pdf_action.triggered.connect(self.register_pdf_file_association) self.unregister_pdf_action.triggered.connect(self.unregister_pdf_file_association) self.default_apps_action.triggered.connect(self.open_default_apps_settings) self.highlight_action.triggered.connect(self.highlight_current_page) self.underline_action.triggered.connect(self.underline_current_page) self.strikeout_action.triggered.connect(self.strikeout_current_page) self.note_action.triggered.connect(self.add_note) self.annotation_style_action.triggered.connect(self.configure_annotation_style) self.select_object_action.toggled.connect(self.toggle_object_selection) self.freehand_action.toggled.connect(self.toggle_freehand_drawing) self.add_text_action.triggered.connect(self.add_text) self.place_text_action.triggered.connect(self.prepare_place_text) self.insert_image_action.triggered.connect(self.insert_image) self.place_image_action.triggered.connect(self.prepare_place_image) self.signature_action.triggered.connect(self.add_signature) self.place_signature_action.triggered.connect(self.prepare_place_signature) self.draw_signature_action.triggered.connect(self.draw_signature) self.rectangle_action.triggered.connect(self.add_rectangle) self.circle_action.triggered.connect(self.add_circle) self.line_action.triggered.connect(self.add_line) self.arrow_action.triggered.connect(self.add_arrow) self.cover_action.triggered.connect(self.add_cover_area) self.dark_mode_action.triggered.connect(self.toggle_dark_mode) self.toggle_edit_pdf_action.toggled.connect(self.toggle_edit_pdf_panel) self.toggle_pages_action.toggled.connect(self.toggle_pages_panel) self.toggle_tools_action.toggled.connect(self.toggle_tools_panel) self.toggle_annotations_action.toggled.connect(self.toggle_annotations_panel) self.toggle_read_action.toggled.connect(self.toggle_read_mode) self.right_tools.collapse_requested.connect(self.close_right_tools_panel) self.tab_widget.currentChanged.connect(self._on_tab_changed) self.tab_widget.tabCloseRequested.connect(self._close_tab) self.search_box.returnPressed.connect(self.search) self.search_results.itemClicked.connect(self._go_to_search_match) self.annotation_filter_combo.currentIndexChanged.connect(self._refresh_annotation_panel) self.annotation_search_box.textChanged.connect(self._refresh_annotation_panel) self.right_annotation_list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.right_annotation_list.itemClicked.connect(self._go_to_annotation_item) self.right_annotation_list.itemDoubleClicked.connect(self.edit_annotation_from_panel_item) self.right_annotation_list.customContextMenuRequested.connect( self.show_annotation_list_context_menu ) def _go_to_search_match(self, item: QListWidgetItem) -> None: match: SearchMatch = item.data(Qt.ItemDataRole.UserRole) self.viewer.go_to_page(match.page_index) def _go_to_annotation_item(self, item: QListWidgetItem) -> None: annotation = item.data(Qt.ItemDataRole.UserRole) if isinstance(annotation, AnnotationInfo): self.viewer.go_to_page(annotation.page_index) self.selected_annotation = annotation self.viewer.set_selected_object_rect(annotation.rect) def show_annotation_list_context_menu(self, position) -> None: item = self.right_annotation_list.itemAt(position) if not item: return annotation = item.data(Qt.ItemDataRole.UserRole) if not isinstance(annotation, AnnotationInfo): return menu = QMenu(self) edit_action = menu.addAction("编辑内容") delete_action = menu.addAction("删除注释") chosen = menu.exec(self.right_annotation_list.mapToGlobal(position)) if chosen == edit_action: self.edit_annotation_from_panel(annotation) elif chosen == delete_action: self.delete_annotation_from_panel(annotation) def edit_annotation_from_panel_item(self, item: QListWidgetItem) -> None: annotation = item.data(Qt.ItemDataRole.UserRole) if isinstance(annotation, AnnotationInfo): self.edit_annotation_from_panel(annotation) def edit_annotation_from_panel(self, annotation: AnnotationInfo) -> None: text, ok = QInputDialog.getMultiLineText( self, "编辑注释内容", "注释内容:", annotation.content or "", ) if not ok: return try: if not self.document.update_annotation_content(annotation.page_index, annotation.xref, text): QMessageBox.warning(self, "编辑失败", "没有找到对应的注释。") return if self.selected_annotation and self.selected_annotation.xref == annotation.xref: self.selected_annotation = AnnotationInfo( page_index=annotation.page_index, xref=annotation.xref, annotation_type=annotation.annotation_type, content=text, rect=annotation.rect, ) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("注释内容已更新,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "编辑失败", f"无法更新注释内容:\n{exc}") def delete_annotation_from_panel(self, annotation: AnnotationInfo) -> None: reply = QMessageBox.question( self, "删除注释", "确定删除选中的注释吗?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, ) if reply != QMessageBox.StandardButton.Yes: return try: if not self.document.delete_annotation(annotation.page_index, annotation.xref): QMessageBox.warning(self, "删除失败", "没有找到对应的注释。") return if self.selected_annotation and self.selected_annotation.xref == annotation.xref: self.selected_annotation = None self.viewer.clear_object_selection() self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("注释已删除,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "删除失败", f"无法删除注释:\n{exc}") def _annotation_type_matches_filter(self, annotation: AnnotationInfo) -> bool: filter_key = self.annotation_filter_combo.currentData() if filter_key in (None, "all"): return True annotation_type = annotation.annotation_type.lower() type_groups = { "highlight": {"highlight"}, "text_markup": {"highlight", "underline", "strikeout", "squiggly"}, "note": {"text", "freetext", "caret"}, "shape": {"square", "circle", "line", "polygon", "polyline"}, "ink": {"ink"}, } return annotation_type in type_groups.get(str(filter_key), set()) def _annotation_matches_search(self, annotation: AnnotationInfo) -> bool: query = self.annotation_search_box.text().strip().lower() if not query: return True haystack = " ".join( [ str(annotation.page_index + 1), annotation.annotation_type, annotation.content or "", ] ).lower() return query in haystack def _refresh_annotation_panel(self) -> None: if not hasattr(self, "right_annotation_list"): return self.right_annotation_list.clear() if not self.document.is_open: item = QListWidgetItem("打开 PDF 后显示注释列表") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) return annotations = self.document.annotations() if not annotations: item = QListWidgetItem("当前 PDF 没有注释") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) return annotations = [ annotation for annotation in annotations if self._annotation_type_matches_filter(annotation) and self._annotation_matches_search(annotation) ] if not annotations: item = QListWidgetItem("?????????") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) return for annotation in annotations: content = annotation.content or annotation.annotation_type item = QListWidgetItem( f"第 {annotation.page_index + 1} 页 {annotation.annotation_type} {content}" ) item.setData(Qt.ItemDataRole.UserRole, annotation) self.right_annotation_list.addItem(item) def highlight_current_page(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("高亮"): return text, ok = QInputDialog.getText(self, "高亮", "输入要在当前页高亮的文本:") if not ok or not text.strip(): return count = self.document.highlight_text(self.viewer.page_index, text) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage(f"已高亮 {count} 处,记得保存", 3000) def underline_current_page(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("下划线"): return text, ok = QInputDialog.getText(self, "下划线", "输入要在当前页标记的文本:") if not ok or not text.strip(): return count = self.document.underline_text(self.viewer.page_index, text) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage(f"已添加下划线 {count} 处,记得保存", 3000) def strikeout_current_page(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("删除线"): return text, ok = QInputDialog.getText(self, "删除线", "输入要在当前页标记的文本:") if not ok or not text.strip(): return count = self.document.strikeout_text(self.viewer.page_index, text) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage(f"已添加删除线 {count} 处,记得保存", 3000) def add_note(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("批注"): return text, ok = QInputDialog.getMultiLineText(self, "批注", "批注内容:") if not ok or not text.strip(): return self.document.add_note(self.viewer.page_index, text) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("批注已添加,记得保存", 3000) def configure_annotation_style(self) -> None: dialog = QDialog(self) dialog.setWindowTitle("注释样式") layout = QFormLayout(dialog) selected_color = QColor(self.annotation_color) color_button = QPushButton(selected_color.name().upper()) color_button.setAutoFillBackground(True) def update_color_button() -> None: color_button.setText(selected_color.name().upper()) color_button.setStyleSheet( f"background: {selected_color.name()}; color: {'#ffffff' if selected_color.lightness() < 128 else '#202124'};" ) def choose_color() -> None: nonlocal selected_color color = QColorDialog.getColor(selected_color, self, "选择注释颜色") if color.isValid(): selected_color = color update_color_button() color_button.clicked.connect(choose_color) update_color_button() width_input = QSpinBox() width_input.setRange(1, 12) width_input.setValue(self.annotation_line_width) width_input.setSuffix(" px") opacity_input = QDoubleSpinBox() opacity_input.setRange(10, 100) opacity_input.setSingleStep(5) opacity_input.setDecimals(0) opacity_input.setValue(self.annotation_opacity * 100) opacity_input.setSuffix("%") layout.addRow("颜色", color_button) layout.addRow("线宽", width_input) layout.addRow("透明度", opacity_input) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel ) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) layout.addRow(buttons) if dialog.exec() != QDialog.DialogCode.Accepted: return self.annotation_color = selected_color self.annotation_line_width = width_input.value() self.annotation_opacity = opacity_input.value() / 100 self.settings.setValue("annotationStyle/color", self.annotation_color.name()) self.settings.setValue("annotationStyle/lineWidth", self.annotation_line_width) self.settings.setValue("annotationStyle/opacity", self.annotation_opacity) self.statusBar().showMessage("注释样式已更新", 3000) def _annotation_style(self) -> tuple[tuple[float, float, float], int, float]: color = self.annotation_color return ( (color.redF(), color.greenF(), color.blueF()), self.annotation_line_width, self.annotation_opacity, ) def toggle_object_selection(self, enabled: bool) -> None: if enabled and not self._ensure_document(): self.select_object_action.setChecked(False) return if enabled and not self._ensure_can_edit("选择对象"): with QSignalBlocker(self.select_object_action): self.select_object_action.setChecked(False) self.viewer.reset_interaction_mode() return if enabled: self.pending_placement = None self.freehand_action.setChecked(False) self.viewer.set_placement_enabled(False) else: self.selected_annotation = None self.selected_raster_id = None self.viewer.set_object_edit_enabled(enabled) if enabled: self.statusBar().showMessage("选择对象已启用:点击注释对象后可拖动或拖右下角缩放", 5000) else: self.statusBar().showMessage("选择对象已关闭", 3000) def select_object_at_point(self, page_index: int, point: tuple[float, float]) -> None: if self.toggle_read_action.isChecked(): self.viewer.reset_interaction_mode() return raster = self._session_raster_at_point(page_index, point) if raster: self.selected_raster_id = int(raster["id"]) self.selected_annotation = None self.viewer.set_selected_object_rect(raster["rect"]) self.statusBar().showMessage("已选中图片/签名,可拖动、缩放或按 Delete 删除", 5000) return annotation = self.document.annotation_at_point(page_index, point) self.selected_annotation = annotation self.selected_raster_id = None self.viewer.set_selected_object_rect(annotation.rect if annotation else None) if annotation: self.statusBar().showMessage("已选中对象,可拖动、缩放或按 Delete 删除", 5000) else: self.statusBar().showMessage("未选中对象", 3000) def update_selected_object_rect(self, page_index: int, rect: tuple[float, float, float, float]) -> None: if self.selected_raster_id is not None: raster = self._session_raster_by_id(self.selected_raster_id) if not raster or int(raster["page_index"]) != page_index: return raster["rect"] = rect self._refresh_session_raster_overlays() self.viewer.set_selected_object_rect(rect) self.statusBar().showMessage("图片/签名已调整,保存时会写入 PDF", 3000) return if not self.selected_annotation or self.selected_annotation.page_index != page_index: return try: if self.document.update_annotation_rect(page_index, self.selected_annotation.xref, rect): updated_rect = self.document.annotation_rect(page_index, self.selected_annotation.xref) self.selected_annotation = AnnotationInfo( page_index=page_index, xref=self.selected_annotation.xref, annotation_type=self.selected_annotation.annotation_type, content=self.selected_annotation.content, rect=updated_rect, ) self.viewer.render() self.viewer.set_selected_object_rect(updated_rect) self.statusBar().showMessage("对象已更新,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "对象更新失败", f"无法更新对象:\n{exc}") self.viewer.render() def delete_selected_object(self) -> None: if self.selected_raster_id is not None: raster_id = self.selected_raster_id self.session_raster_objects = [ item for item in self.session_raster_objects if int(item["id"]) != raster_id ] self.selected_raster_id = None self.viewer.clear_object_selection() self._refresh_session_raster_overlays() self.statusBar().showMessage("图片/签名已删除", 3000) return if not self.selected_annotation: self.statusBar().showMessage("没有选中的对象", 3000) return try: if self.document.delete_annotation(self.selected_annotation.page_index, self.selected_annotation.xref): self.selected_annotation = None self.viewer.clear_object_selection() self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("对象已删除,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "删除失败", f"无法删除对象:\n{exc}") def show_object_context_menu(self, page_index: int, point: tuple[float, float]) -> None: if self.toggle_read_action.isChecked() or not self.select_object_action.isChecked(): return raster = self._session_raster_at_point(page_index, point) if raster: self.selected_raster_id = int(raster["id"]) self.selected_annotation = None self.viewer.set_selected_object_rect(raster["rect"]) else: self.selected_raster_id = None annotation = self.document.annotation_at_point(page_index, point) if annotation: self.selected_annotation = annotation self.viewer.set_selected_object_rect(annotation.rect) menu = QMenu(self) delete_action = menu.addAction("删除对象") delete_action.setEnabled(self.selected_annotation is not None) chosen = menu.exec(self.cursor().pos()) if chosen == delete_action: self.delete_selected_object() def cancel_current_operation(self) -> bool: had_pending = self.pending_placement is not None had_selection = self.selected_annotation is not None or self.selected_raster_id is not None had_tool = self.select_object_action.isChecked() or self.freehand_action.isChecked() if not (had_pending or had_selection or had_tool): return False self.pending_placement = None self.selected_annotation = None self.selected_raster_id = None self.select_object_action.setChecked(False) self.freehand_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_drawing_enabled(False) self.viewer.set_object_edit_enabled(False) self.viewer.clear_object_selection() self.statusBar().showMessage("已取消当前操作", 3000) return True def keyPressEvent(self, event) -> None: if event.key() == Qt.Key.Key_Escape and self.cancel_current_operation(): event.accept() return if event.key() == Qt.Key.Key_Delete and (self.selected_annotation or self.selected_raster_id is not None): self.delete_selected_object() return if self.document.is_open and not isinstance(self.focusWidget(), QLineEdit): if event.key() == Qt.Key.Key_Left: self.previous_page() event.accept() return if event.key() == Qt.Key.Key_Right: self.next_page() event.accept() return if event.key() in {Qt.Key.Key_Up, Qt.Key.Key_Down}: bar = self.viewer.verticalScrollBar() direction = -1 if event.key() == Qt.Key.Key_Up else 1 step = max(48, bar.pageStep() // 5) bar.setValue(bar.value() + direction * step) event.accept() return super().keyPressEvent(event) def toggle_freehand_drawing(self, enabled: bool) -> None: if enabled and not self._ensure_document(): self.freehand_action.setChecked(False) return if enabled and not self._ensure_can_edit("自由画笔"): with QSignalBlocker(self.freehand_action): self.freehand_action.setChecked(False) self.viewer.reset_interaction_mode() return if enabled: self.pending_placement = None self.viewer.set_placement_enabled(False) self.select_object_action.setChecked(False) self.viewer.set_drawing_enabled(enabled) if enabled: self.statusBar().showMessage("自由画笔已启用:在页面上按住鼠标绘制", 5000) else: self.statusBar().showMessage("自由画笔已关闭", 3000) def add_ink_stroke(self, page_index: int, points: list[tuple[float, float]]) -> None: try: color, line_width, opacity = self._annotation_style() self.document.add_ink(page_index, points, color, line_width, opacity) self.viewer.render() self._refresh_annotation_panel() self.freehand_action.setChecked(False) self.statusBar().showMessage("画笔注释已添加,记得保存", 3000) except Exception as exc: self.freehand_action.setChecked(False) QMessageBox.critical(self, "画笔失败", f"无法添加画笔注释:\n{exc}") def add_text(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("添加文本"): return text, ok = QInputDialog.getMultiLineText(self, "添加文本", "文本内容:") if not ok or not text.strip(): return try: self.document.add_text(self.viewer.page_index, text) self.viewer.render() self.statusBar().showMessage("文本已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "添加失败", f"无法添加文本:\n{exc}") def prepare_place_text(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("点击放置文本"): return text, ok = QInputDialog.getMultiLineText(self, "点击放置文本", "文本内容:") if not ok or not text.strip(): return self._start_placement({"type": "text", "text": text}, "点击页面位置放置文本") def prepare_place_image(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("点击放置图片"): return selected, _ = QFileDialog.getOpenFileName( self, "点击放置图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)" ) if not selected: return self._start_placement({"type": "image", "path": selected}, "点击页面位置放置图片") def prepare_place_signature(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("点击放置签名"): return selected, _ = QFileDialog.getOpenFileName( self, "点击放置签名", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)", ) if not selected: return self._start_placement({"type": "signature", "path": selected}, "点击页面位置放置签名") def _add_session_raster_object( self, kind: str, page_index: int, image_path: str, point: tuple[float, float] | None = None, ) -> None: rect = ( self.document.signature_rect(page_index, point) if kind == "signature" else self.document.image_rect(page_index, point) ) item = { "id": self.next_raster_id, "type": kind, "page_index": page_index, "path": image_path, "rect": rect, } self.next_raster_id += 1 self.session_raster_objects.append(item) self.selected_raster_id = int(item["id"]) self.selected_annotation = None self.select_object_action.setChecked(True) self.viewer.set_selected_object_rect(rect) def _session_raster_by_id(self, raster_id: int) -> dict[str, object] | None: for item in self.session_raster_objects: if int(item["id"]) == raster_id: return item return None def _session_raster_at_point( self, page_index: int, point: tuple[float, float], ) -> dict[str, object] | None: x, y = point for item in reversed(self.session_raster_objects): if int(item["page_index"]) != page_index: continue x0, y0, x1, y1 = item["rect"] if float(x0) <= x <= float(x1) and float(y0) <= y <= float(y1): return item return None def _refresh_session_raster_overlays(self) -> None: self.viewer.set_overlay_images(self.session_raster_objects) self._update_current_tab_title() def _clear_session_raster_objects(self) -> None: self.session_raster_objects.clear() self.selected_raster_id = None self.selected_annotation = None self.viewer.set_overlay_images([]) self.viewer.clear_object_selection() def _flush_session_raster_objects(self) -> None: if not self.session_raster_objects: return for item in list(self.session_raster_objects): rect = item["rect"] if item["type"] == "signature": self.document.add_signature_rect(int(item["page_index"]), str(item["path"]), rect) else: self.document.insert_image_rect(int(item["page_index"]), str(item["path"]), rect) self._clear_session_raster_objects() self._update_current_tab_title() def _start_placement(self, payload: dict[str, object], message: str) -> None: if not self._ensure_can_edit("点击放置"): return self.pending_placement = payload self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.set_placement_enabled(True) self.statusBar().showMessage(message, 5000) def place_pending_object(self, page_index: int, point: tuple[float, float]) -> None: if not self.pending_placement: return payload = self.pending_placement self.pending_placement = None self.viewer.set_placement_enabled(False) try: kind = payload.get("type") if kind == "text": self.document.add_text(page_index, str(payload["text"]), point) elif kind == "image": self._add_session_raster_object("image", page_index, str(payload["path"]), point) elif kind == "signature": self._add_session_raster_object("signature", page_index, str(payload["path"]), point) else: raise ValueError("未知的放置类型") self.viewer.render() self._refresh_session_raster_overlays() self.statusBar().showMessage("已放置,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "放置失败", f"无法放置内容:\n{exc}") def insert_image(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("插入图片"): return selected, _ = QFileDialog.getOpenFileName( self, "插入图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)" ) if not selected: return try: self._add_session_raster_object("image", self.viewer.page_index, selected) self._refresh_session_raster_overlays() self.statusBar().showMessage("图片已插入,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "插入失败", f"无法插入图片:\n{exc}") def add_signature(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("图片签名"): return selected, _ = QFileDialog.getOpenFileName( self, "选择签名图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)", ) if not selected: return try: self._add_session_raster_object("signature", self.viewer.page_index, selected) self._refresh_session_raster_overlays() self.statusBar().showMessage("签名图片已放置,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "签名失败", f"无法添加签名:\n{exc}") def draw_signature(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("手写签名"): return dialog = SignatureDialog(self) if dialog.exec() != QDialog.DialogCode.Accepted: return signature_path = Path(self.settings.fileName()).parent / "last_signature.png" dialog.save_signature(signature_path) try: self._add_session_raster_object("signature", self.viewer.page_index, str(signature_path)) self._refresh_session_raster_overlays() self.statusBar().showMessage("手写签名已放置,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "签名失败", f"无法添加手写签名:\n{exc}") def add_rectangle(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("矩形"): return color, line_width, opacity = self._annotation_style() self.document.add_rectangle(self.viewer.page_index, color, line_width, opacity) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("矩形已添加,记得保存", 3000) def add_circle(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("圆形"): return color, line_width, opacity = self._annotation_style() self.document.add_circle(self.viewer.page_index, color, line_width, opacity) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("圆形已添加,记得保存", 3000) def add_line(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("线条"): return color, line_width, opacity = self._annotation_style() self.document.add_line(self.viewer.page_index, False, color, line_width, opacity) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("线条已添加,记得保存", 3000) def add_arrow(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("箭头"): return color, line_width, opacity = self._annotation_style() self.document.add_line(self.viewer.page_index, True, color, line_width, opacity) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("箭头已添加,记得保存", 3000) def add_cover_area(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("遮盖"): return self.document.add_cover_area(self.viewer.page_index) self.viewer.render() self._refresh_annotation_panel() self.statusBar().showMessage("遮盖区域已添加,记得保存", 3000) def _remember_file(self, path: str) -> None: files = [item for item in self.recent_files if item != path] files.insert(0, path) self.recent_files = files[:10] self.settings.setValue("lastOpenFile", path) self.settings.setValue("recentFiles", self.recent_files) self._refresh_recent_menu() def clear_recent_files(self) -> None: self.recent_files = [] self.settings.remove("recentFiles") self.settings.remove("lastOpenFile") self._refresh_recent_menu() self.statusBar().showMessage("最近文件已清空", 3000) def _refresh_recent_menu(self) -> None: if not hasattr(self, "recent_menu"): return self.recent_menu.clear() if not self.recent_files: empty_action = QAction("暂无", self) empty_action.setEnabled(False) self.recent_menu.addAction(empty_action) return for path in self.recent_files: action = QAction(Path(path).name, self) action.setToolTip(path) action.triggered.connect(lambda checked=False, file_path=path: self.open_file(file_path)) self.recent_menu.addAction(action) self.recent_menu.addSeparator() self.recent_menu.addAction(self.clear_recent_action) def _ensure_document(self) -> bool: if not self.document.is_open: QMessageBox.information(self, "未打开文件", "请先打开一个 PDF 文件。") return False return True def _ensure_can_edit(self, tool_name: str) -> bool: if not self.toggle_read_action.isChecked(): return True self.pending_placement = None self.selected_annotation = None self.selected_raster_id = None self.viewer.reset_interaction_mode() self.statusBar().showMessage(f"阅读模式下不能使用“{tool_name}”,请先切换到编辑或注释模式", 4000) return False def _refresh_document_view(self) -> None: self.viewer.render() self._refresh_session_raster_overlays() self.sidebar.load_document(self.document) self.sidebar.select_page(self.viewer.page_index) self._update_status() def _parse_page_numbers(self, text: str) -> list[int]: pages: set[int] = set() for part in text.replace(",", ",").split(","): part = part.strip() if not part: continue if "-" in part: start_text, end_text = part.split("-", 1) start = int(start_text.strip()) end = int(end_text.strip()) if start > end: raise ValueError("页码范围起始值不能大于结束值。") pages.update(range(start, end + 1)) else: pages.add(int(part)) if not pages: raise ValueError("请输入至少一个页码。") for page in pages: if page < 1 or page > self.document.page_count: raise ValueError(f"页码超出范围:{page}") return sorted(pages) def toggle_dark_mode(self, checked: bool) -> None: self.dark_mode = checked self.settings.setValue("darkMode", self.dark_mode) self._apply_theme() def toggle_edit_pdf_panel(self, checked: bool) -> None: if checked: self._show_right_panel_mode("edit") elif not self._any_right_mode_checked(): self.set_right_tools_visible(False) def toggle_pages_panel(self, checked: bool) -> None: if checked: self._show_right_panel_mode("pages") elif not self._any_right_mode_checked(): self.set_right_tools_visible(False) def toggle_tools_panel(self, checked: bool) -> None: if checked: self._show_right_panel_mode("tools") elif not self._any_right_mode_checked(): self.set_right_tools_visible(False) def toggle_annotations_panel(self, checked: bool) -> None: if checked: self._show_right_panel_mode("annotations") elif not self._any_right_mode_checked(): self.set_right_tools_visible(False) def toggle_read_mode(self, checked: bool) -> None: if checked: self._enter_read_mode() elif not self._any_right_mode_checked(): self.set_right_tools_visible(False) def _right_mode_actions(self) -> list[QAction]: return [ self.toggle_edit_pdf_action, self.toggle_pages_action, self.toggle_tools_action, self.toggle_annotations_action, self.toggle_read_action, ] def _any_right_mode_checked(self) -> bool: return any(action.isChecked() for action in self._right_mode_actions()) def _current_mode_text(self) -> str: if not hasattr(self, "toggle_tools_action"): return "模式:工具" if self.toggle_read_action.isChecked(): return "模式:阅读" if self.toggle_annotations_action.isChecked(): return "模式:注释" if self.toggle_edit_pdf_action.isChecked(): return "模式:编辑PDF" if self.toggle_pages_action.isChecked(): return "模式:页面" if self.toggle_tools_action.isChecked(): return "模式:工具" return "模式:无" def _sync_mode_status(self) -> None: if hasattr(self, "mode_status_label"): self.mode_status_label.setText(self._current_mode_text()) def _show_right_panel_mode(self, mode: str) -> None: with ( QSignalBlocker(self.toggle_edit_pdf_action), QSignalBlocker(self.toggle_pages_action), QSignalBlocker(self.toggle_tools_action), QSignalBlocker(self.toggle_annotations_action), QSignalBlocker(self.toggle_read_action), ): self.toggle_edit_pdf_action.setChecked(mode == "edit") self.toggle_pages_action.setChecked(mode == "pages") self.toggle_tools_action.setChecked(mode == "tools") self.toggle_annotations_action.setChecked(mode == "annotations") self.toggle_read_action.setChecked(False) if mode == "annotations": self.right_tools.set_title("注释") self.right_tools.show_sections(["annotations", "annotation_list"]) self._refresh_annotation_panel() elif mode == "edit": self.right_tools.set_title("编辑PDF") self.right_tools.show_sections(["edit"]) elif mode == "pages": self.right_tools.set_title("页面") self.right_tools.show_sections(["pages"]) else: self.right_tools.set_title("工具") self.right_tools.show_sections(["sign", "export", "settings"]) self.set_right_tools_visible(True) self._sync_mode_status() def _enter_read_mode(self) -> None: with ( QSignalBlocker(self.toggle_edit_pdf_action), QSignalBlocker(self.toggle_pages_action), QSignalBlocker(self.toggle_tools_action), QSignalBlocker(self.toggle_annotations_action), QSignalBlocker(self.toggle_read_action), ): self.toggle_edit_pdf_action.setChecked(False) self.toggle_pages_action.setChecked(False) self.toggle_tools_action.setChecked(False) self.toggle_annotations_action.setChecked(False) self.toggle_read_action.setChecked(True) self.pending_placement = None self.selected_annotation = None self.selected_raster_id = None self.select_object_action.setChecked(False) self.freehand_action.setChecked(False) self.viewer.reset_interaction_mode() self.set_right_tools_visible(False) self._sync_mode_status() self.statusBar().showMessage("阅读模式已开启", 3000) def close_right_tools_panel(self) -> None: with ( QSignalBlocker(self.toggle_edit_pdf_action), QSignalBlocker(self.toggle_pages_action), QSignalBlocker(self.toggle_tools_action), QSignalBlocker(self.toggle_annotations_action), QSignalBlocker(self.toggle_read_action), ): for action in self._right_mode_actions(): action.setChecked(False) self.set_right_tools_visible(False) self._sync_mode_status() def set_right_tools_visible(self, visible: bool) -> None: if not self.main_splitter: self.right_tools.setVisible(visible) return sizes = self.main_splitter.sizes() total_width = sum(sizes) or self.width() if visible: if self.right_tools.isVisible(): return right_width = self._clamp_right_tools_width(self._last_right_tools_width) self.right_tools.setVisible(True) self.main_splitter.setSizes([max(1, total_width - right_width), right_width]) return if self.right_tools.isVisible() and len(sizes) > 1 and sizes[1] > 0: self._last_right_tools_width = self._clamp_right_tools_width(sizes[1]) self.right_tools.setVisible(False) self.main_splitter.setSizes([total_width, 0]) def _clamp_right_tools_width(self, width: int) -> int: minimum = self.right_tools.minimumWidth() maximum = self.right_tools.maximumWidth() if maximum <= 0: maximum = 300 return max(minimum, min(int(width), maximum)) def _apply_theme(self) -> None: if self.dark_mode: self.setStyleSheet( """ QMainWindow { background: #242628; color: #f1f1f1; } QMenuBar, QMenu { background: #2f3235; color: #f1f1f1; border-color: #464a4f; } QMenuBar::item:selected, QMenu::item:selected { background: #3f6fb5; color: #ffffff; } QToolBar#mainToolBar { background: #303235; border-bottom: 1px solid #45494d; padding: 4px 8px; spacing: 2px; } QToolBar#mainToolBar::separator { background: #50545a; width: 1px; margin: 6px 8px; } QToolButton { color: #f1f1f1; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 5px 9px; } QToolButton:hover, QPushButton#rightToolButton:hover { background: #3c4045; border-color: #555a60; } QToolButton:checked, QPushButton#rightToolButton:checked { background: #244a78; border-color: #4f89c8; } QLabel#toolbarLabel { color: #cfd3d8; padding-left: 4px; } QLabel#statusZoomLabel { color: #cfd3d8; padding: 0 4px 0 10px; } QLabel#statusPageLabel, QLabel#statusPageTotal, QLabel#statusModeLabel { color: #cfd3d8; padding: 0 4px; } QFrame#statusSeparator { color: #555a60; background: #555a60; } QToolButton#statusToolButton { color: #f1f1f1; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 3px 7px; } QToolButton#statusToolButton:hover { background: #3c4045; border-color: #555a60; } QLineEdit, QSpinBox, QComboBox { padding: 6px 8px; background: #202225; color: #f1f1f1; border: 1px solid #555a60; border-radius: 4px; } QSlider::groove:horizontal { height: 4px; background: #555a60; border-radius: 2px; } QSlider::handle:horizontal { background: #5b9be3; width: 14px; margin: -5px 0; border-radius: 7px; } QTabWidget::pane { background: #26282b; border: 1px solid #45494d; } QTabBar::tab { background: #303235; color: #dfe3e7; border: 1px solid #45494d; padding: 7px 14px; margin-right: 2px; } QTabBar::tab:selected { background: #26282b; border-bottom-color: #26282b; } QSplitter::handle { background: #34373b; } QWidget#rightToolsPanel { background: #2b2e31; border-left: 1px solid #44484d; } QLabel#rightToolsTitle { color: #f1f1f1; font-weight: 600; padding-left: 4px; } QToolButton#rightToolsCollapseButton { color: #dfe3e7; background: transparent; border: 1px solid #555a60; border-radius: 4px; padding: 2px 7px; } QToolButton#rightToolsCollapseButton:hover { background: #3c4045; } QScrollArea#rightToolsScroll { background: transparent; border: none; } QFrame#toolSection { background: #313438; border: 1px solid #44484d; border-radius: 6px; } QToolButton#toolSectionTitle { color: #f1f1f1; font-weight: 600; text-align: left; padding: 6px 4px; border: none; background: transparent; } QLabel#toolSectionLabel { color: #f1f1f1; font-weight: 600; padding: 6px 4px; } QToolButton#toolSectionTitle:hover { background: #3c4045; border-radius: 4px; } QPushButton#rightToolButton { color: #f1f1f1; text-align: left; padding: 6px 8px 6px 14px; border: 1px solid transparent; border-radius: 4px; background: transparent; } QListWidget, QListWidget#searchResults, QListWidget#thumbnailList { background: #202225; color: #f1f1f1; border: 1px solid #45494d; border-radius: 4px; } QListWidget::item { padding: 6px; border-radius: 4px; border: 1px solid transparent; } QListWidget::item:selected { background: #27384d; color: #ffffff; border: 2px solid #4f89c8; } QListWidget#thumbnailList::item { margin: 3px 4px; padding: 4px; } QListWidget#thumbnailList::item:selected { background: #26384d; border: 2px solid #5b9be3; } QLabel#thumbnailPageLabel { color: #f1f1f1; } QScrollArea#pdfCanvas, QWidget#pdfContinuousContent { background: #181a1c; border: none; } QLabel#emptyPage { background: #2d3034; color: #cfd3d8; padding: 28px; border: 1px solid #464a4f; } QLabel#pdfPage { background: #ffffff; color: #202020; padding: 0; border: 1px solid #53575c; } QStatusBar { background: #303235; color: #dfe3e7; border-top: 1px solid #45494d; } """ ) else: self.setStyleSheet( """ QMainWindow { background: #e6e7e9; color: #202124; } QMenuBar, QMenu { background: #ffffff; color: #202124; border-color: #d6d8dc; } QMenuBar::item:selected, QMenu::item:selected { background: #dbeafe; color: #0f3f7a; } QToolBar#mainToolBar { background: #f7f8fa; border-bottom: 1px solid #cfd2d7; padding: 4px 8px; spacing: 2px; } QToolBar#mainToolBar::separator { background: #c7cad0; width: 1px; margin: 6px 8px; } QToolButton { color: #25272a; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 5px 9px; } QToolButton:hover, QPushButton#rightToolButton:hover { background: #eceff3; border-color: #c9cdd3; } QToolButton:pressed, QPushButton#rightToolButton:pressed { background: #dfe6f1; } QToolButton:checked, QPushButton#rightToolButton:checked { background: #dbeafe; border-color: #6aa3dc; color: #0f3f7a; } QLabel#toolbarLabel { color: #5b6067; padding-left: 4px; } QLabel#statusZoomLabel { color: #5b6067; padding: 0 4px 0 10px; } QLabel#statusPageLabel, QLabel#statusPageTotal, QLabel#statusModeLabel { color: #5b6067; padding: 0 4px; } QFrame#statusSeparator { color: #c9cdd3; background: #c9cdd3; } QToolButton#statusToolButton { color: #25272a; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 3px 7px; } QToolButton#statusToolButton:hover { background: #eceff3; border-color: #c9cdd3; } QLineEdit, QSpinBox, QComboBox { padding: 6px 8px; background: #ffffff; color: #202124; border: 1px solid #b9bec6; border-radius: 4px; } QLineEdit:focus, QSpinBox:focus, QComboBox:focus { border-color: #4f8bd3; } QSlider::groove:horizontal { height: 4px; background: #c6cbd2; border-radius: 2px; } QSlider::handle:horizontal { background: #2d73c5; width: 14px; margin: -5px 0; border-radius: 7px; } QTabWidget::pane { background: #f1f2f4; border: 1px solid #cfd2d7; } QTabBar::tab { background: #e8eaed; color: #303236; border: 1px solid #cfd2d7; padding: 7px 14px; margin-right: 2px; } QTabBar::tab:selected { background: #f8f9fb; border-bottom-color: #f8f9fb; } QSplitter::handle { background: #d2d5da; } QWidget#rightToolsPanel { background: #f4f5f7; border-left: 1px solid #cfd2d7; } QLabel#rightToolsTitle { color: #25272a; font-weight: 600; padding-left: 4px; } QToolButton#rightToolsCollapseButton { color: #4b5563; background: transparent; border: 1px solid #c9cdd3; border-radius: 4px; padding: 2px 7px; } QToolButton#rightToolsCollapseButton:hover { background: #eceff3; } QScrollArea#rightToolsScroll { background: transparent; border: none; } QFrame#toolSection { background: #ffffff; border: 1px solid #d8dbe0; border-radius: 6px; } QToolButton#toolSectionTitle { color: #25272a; font-weight: 600; text-align: left; padding: 6px 4px; border: none; background: transparent; } QLabel#toolSectionLabel { color: #25272a; font-weight: 600; padding: 6px 4px; } QToolButton#toolSectionTitle:hover { background: #f0f3f8; border-radius: 4px; } QPushButton#rightToolButton { color: #25272a; text-align: left; padding: 6px 8px 6px 14px; border: 1px solid transparent; border-radius: 4px; background: transparent; } QListWidget, QListWidget#searchResults, QListWidget#thumbnailList { background: #ffffff; color: #202124; border: 1px solid #cfd2d7; border-radius: 4px; } QListWidget::item { padding: 6px; border-radius: 4px; border: 1px solid transparent; } QListWidget::item:hover { background: #f0f3f8; } QListWidget::item:selected { background: #f8fbff; color: #0f3f7a; border: 2px solid #6aa3dc; } QListWidget#thumbnailList::item { margin: 3px 4px; padding: 4px; } QListWidget#thumbnailList::item:selected { background: #f8fbff; border: 2px solid #2d73c5; } QLabel#thumbnailPageLabel { color: #202124; } QScrollArea#pdfCanvas, QWidget#pdfContinuousContent { background: #bfc4cb; border: none; } QLabel#emptyPage { background: #f8f9fb; color: #5f6368; padding: 28px; border: 1px solid #d3d6dc; } QLabel#pdfPage { background: #ffffff; color: #202020; padding: 0; border: 1px solid #b7bbc2; } QStatusBar { background: #f7f8fa; color: #44484f; border-top: 1px solid #cfd2d7; } """ ) def _restore_window_state(self) -> None: geometry = self.settings.value("windowGeometry") window_state = self.settings.value("windowState") if geometry: self.restoreGeometry(geometry) if window_state: self.restoreState(window_state) def log_dir(self) -> Path: return Path(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)) def open_log_dir(self) -> None: log_dir = self.log_dir() log_dir.mkdir(parents=True, exist_ok=True) QDesktopServices.openUrl(QUrl.fromLocalFile(str(log_dir))) def register_pdf_file_association(self) -> None: try: register_pdf_association(pdf_icon_path()) QMessageBox.information( self, "PDF 文件关联", "已注册 PDFReaderLite 的 PDF 文件关联信息。\n\n" "Windows 可能仍需要你在系统默认应用设置中确认默认 PDF 应用。", ) self.open_default_apps_settings() except Exception as exc: QMessageBox.critical(self, "注册失败", f"无法注册 PDF 文件关联:\n{exc}") def unregister_pdf_file_association(self) -> None: try: unregister_pdf_association() QMessageBox.information( self, "PDF 文件关联", "已移除 PDFReaderLite 的 PDF 文件关联注册信息。\n\n" "如果系统默认应用仍显示 PDFReaderLite,请在 Windows 默认应用设置中重新选择。", ) except Exception as exc: QMessageBox.critical(self, "取消失败", f"无法取消 PDF 文件关联注册:\n{exc}") def open_default_apps_settings(self) -> None: QDesktopServices.openUrl(QUrl("ms-settings:defaultapps")) def show_shortcuts(self) -> None: QMessageBox.information( self, "快捷键", "打开:Ctrl+O\n" "保存:Ctrl+S\n" "另存为:Ctrl+Shift+S\n" "打印:Ctrl+P\n" "撤销:Ctrl+Z\n" "重做:Ctrl+Y\n" "上一页:Page Up\n" "下一页:Page Down\n" "放大:Ctrl++\n" "缩小:Ctrl+-\n" "跳转页码:Ctrl+G\n" "高亮:Ctrl+H\n" "文档信息:Ctrl+I", ) def show_about(self) -> None: QMessageBox.information( self, "关于 PDFReaderLite", "PDFReaderLite\n\n" f"版本:{__version__}\n" "定位:轻量 PDF 阅读与编辑工具\n\n" f"日志目录:{self.log_dir()}", ) def _update_title(self) -> None: self.setWindowTitle(f"{self.document.title} - PDFReaderLite") def _update_status(self) -> None: self._update_current_tab_title() self._sync_zoom_controls(self.viewer.zoom) self._sync_page_controls() self._refresh_annotation_panel() self._sync_mode_status() if not self.document.is_open: self.statusBar().showMessage("就绪") return self.statusBar().showMessage("就绪")