from __future__ import annotations import json import math from dataclasses import dataclass from datetime import datetime from pathlib import Path from PySide6.QtCore import QRect, QSize, QSignalBlocker, QSettings, QStandardPaths, Qt, QUrl from PySide6.QtGui import ( QAction, QActionGroup, QColor, QDesktopServices, QDragEnterEvent, QDropEvent, QFont, QIcon, QImage, QIntValidator, QKeySequence, QCursor, QPainter, QPen, QPixmap, ) from PySide6.QtPrintSupport import QPrintDialog, QPrinter from PySide6.QtWidgets import ( QAbstractItemView, QApplication, 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, QTextEdit, QToolBar, QToolButton, QToolTip, 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.cover_color = QColor(self.settings.value("coverStyle/color", "#ffffff", str)) self.cover_opacity = float(self.settings.value("coverStyle/opacity", 1.0, float)) self.text_color = QColor(self.settings.value("textStyle/color", "#202124", str)) self.text_font_size = int(self.settings.value("textStyle/fontSize", 14, int)) 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_sort_combo = QComboBox() self.annotation_current_page_only = QCheckBox("仅当前页") self.annotation_export_button = QPushButton("导出注释") self.annotation_search_box = QLineEdit() self.right_annotation_list = QListWidget() self.right_object_list = QListWidget() self.annotation_properties_panel = QWidget() self.annotation_property_info_label = QLabel("未选择注释") self.annotation_property_content = QLineEdit() self.annotation_property_color = QColor(self.annotation_color) self.annotation_property_color_button = QPushButton() self.annotation_property_font_size = QSpinBox() self.annotation_property_width = QSpinBox() self.annotation_property_opacity = QDoubleSpinBox() self.annotation_property_apply_button = QPushButton("应用属性") 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.pending_area_markup: str | None = None self.pending_text_selection: dict[str, object] | None = None self.pending_shape_placement: str | None = None self.selected_annotation: AnnotationInfo | None = None self.session_raster_objects: list[dict[str, object]] = [] self.selected_raster_id: int | None = None self.selected_object_keys: list[tuple[str, int]] = [] self.next_raster_id = 1 self.copied_raster_object: dict[str, object] | None = None self.copied_annotation_object: AnnotationInfo | None = None 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.hand_action.setChecked(True) 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.page_changed.connect(lambda _: self._refresh_annotation_panel()) 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.area_selection_finished.connect(self.add_area_markup) session.viewer.text_selection_preview_changed.connect(self.preview_text_selection) session.viewer.text_selection_finished.connect(self.handle_text_selection) session.viewer.text_selection_click_requested.connect(self.select_existing_text_markup_at_point) session.viewer.text_selection_context_requested.connect(self.show_text_selection_context_menu) session.viewer.shape_placement_finished.connect(self.add_shape_from_points) 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) session.viewer.object_double_clicked.connect(self.edit_object_at_point) session.viewer.annotation_double_clicked.connect(self.edit_annotation_at_point) session.viewer.annotation_hover_requested.connect(self.show_annotation_tooltip) 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._restore_primary_pointer_or_hand() 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._restore_primary_pointer_or_hand() 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 page_index = self.viewer.page_index self._flush_session_raster_objects() page_index = max(0, min(page_index, self.document.page_count - 1)) self.document.rotate_page(page_index) self._refresh_document_view(page_index) 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() target_page = min(self.viewer.page_index, self.document.page_count - 2) self.document.delete_page(self.viewer.page_index) self._refresh_document_view(target_page) 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._refresh_document_view(target_page - 1) 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() original_page_count = self.document.page_count rotated_pages = [page for page, degrees in dialog.rotations.items() if degrees % 360] for page_index, degrees in dialog.rotations.items(): if degrees % 360: self.document.rotate_pages([page_index], degrees) page_plan = dialog.page_plan() current_page_before = self.viewer.page_index target_page = self._page_after_page_plan(current_page_before, page_plan) self.document.apply_page_plan(page_plan) self._refresh_document_view(target_page) kept_count = sum(1 for entry in page_plan if entry.get("source") == "current") external_count = sum(1 for entry in page_plan if entry.get("source") == "external") message = "页面管理已应用,记得保存" if rotated_pages: message += f";旋转 {len(rotated_pages)} 页" if kept_count != original_page_count: message += ";页面已删除" if external_count: message += f";插入 {external_count} 页" self.statusBar().showMessage(message, 4000) 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._refresh_document_view(min(self.viewer.page_index, self.document.page_count - 1)) self.statusBar().showMessage("已撤销", 3000) else: self.statusBar().showMessage("没有可撤销的操作", 3000) def redo(self) -> None: if not self._ensure_document(): return if self.document.redo(): self._refresh_document_view(min(self.viewer.page_index, self.document.page_count - 1)) 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._refresh_document_view(new_index) 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() insert_after = self.viewer.page_index count = self.document.insert_pdf(selected, self.viewer.page_index) self._refresh_document_view(insert_after + 1) 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._render_at_page(self.viewer.page_index) 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._render_at_page(self.viewer.page_index) 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() self.viewer.set_search_highlights(None) 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_sort_combo.setObjectName("annotationSortCombo") 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_sort_combo.addItem("按创建顺序", "created") self.annotation_sort_combo.addItem("按页码", "page") self.annotation_sort_combo.addItem("按类型", "type") 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.pointer_action = QAction("指针", self) self.pointer_action.setCheckable(True) self.pointer_action.setToolTip("选择文字") self.hand_action = QAction("手", self) self.hand_action.setCheckable(True) self.hand_action.setToolTip("拖拽移动页面") 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.text_selection_action = QAction("文本选择", self) self.text_selection_action.setCheckable(True) 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.text_stamp_action = QAction("文字图章", self) self.image_stamp_action = QAction("图片图章", self) self.select_object_action = QAction("选择对象", self) self.select_object_action.setCheckable(True) self.select_object_action.setShortcut(QKeySequence("V")) self.copy_object_action = QAction("复制对象", self) self.copy_object_action.setShortcut(QKeySequence.StandardKey.Copy) self.paste_object_action = QAction("粘贴对象", self) self.paste_object_action.setShortcut(QKeySequence.StandardKey.Paste) self.replace_image_action = QAction("替换图片", self) self.image_properties_action = QAction("图片属性", self) self.bring_to_front_action = QAction("置顶", self) self.send_to_back_action = QAction("置底", self) self.bring_forward_action = QAction("上移一层", self) self.send_backward_action = QAction("下移一层", self) self.align_left_action = QAction("左对齐", self) self.align_center_action = QAction("水平居中", self) self.align_right_action = QAction("右对齐", self) self.align_top_action = QAction("顶端对齐", self) self.align_middle_action = QAction("垂直居中", self) self.align_bottom_action = QAction("底端对齐", self) self.distribute_horizontal_action = QAction("水平分布", self) self.distribute_vertical_action = QAction("垂直分布", self) self.freehand_action = QAction("自由画笔", self) self.freehand_action.setCheckable(True) self.add_text_action = QAction("添加文本", self) self.place_text_action = QAction("添加文本", self) self.text_style_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.primary_tool_group = QActionGroup(self) self.primary_tool_group.setExclusive(True) self.primary_tool_group.addAction(self.pointer_action) self.primary_tool_group.addAction(self.hand_action) self.right_mode_group = QActionGroup(self) self.right_mode_group.setExclusive(True) for action in [ self.toggle_edit_pdf_action, self.toggle_pages_action, self.toggle_tools_action, self.toggle_annotations_action, self.toggle_read_action, ]: self.right_mode_group.addAction(action) 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.text_stamp_action) edit_menu.addAction(self.image_stamp_action) edit_menu.addAction(self.select_object_action) edit_menu.addAction(self.copy_object_action) edit_menu.addAction(self.paste_object_action) edit_menu.addAction(self.replace_image_action) edit_menu.addAction(self.image_properties_action) edit_menu.addAction(self.bring_to_front_action) edit_menu.addAction(self.send_to_back_action) edit_menu.addAction(self.bring_forward_action) edit_menu.addAction(self.send_backward_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.text_style_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.pointer_action: QStyle.StandardPixmap.SP_ArrowRight, self.hand_action: QStyle.StandardPixmap.SP_DialogOpenButton, 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.text_selection_action: QStyle.StandardPixmap.SP_FileDialogContentsView, 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.text_stamp_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.image_stamp_action: QStyle.StandardPixmap.SP_FileIcon, self.select_object_action: QStyle.StandardPixmap.SP_ArrowRight, self.image_properties_action: QStyle.StandardPixmap.SP_FileDialogInfoView, self.align_left_action: QStyle.StandardPixmap.SP_ArrowLeft, self.align_center_action: QStyle.StandardPixmap.SP_FileDialogContentsView, self.align_right_action: QStyle.StandardPixmap.SP_ArrowRight, self.align_top_action: QStyle.StandardPixmap.SP_ArrowUp, self.align_middle_action: QStyle.StandardPixmap.SP_FileDialogContentsView, self.align_bottom_action: QStyle.StandardPixmap.SP_ArrowDown, self.distribute_horizontal_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.distribute_vertical_action: QStyle.StandardPixmap.SP_FileDialogListView, self.freehand_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.add_text_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.place_text_action: QStyle.StandardPixmap.SP_FileDialogDetailedView, self.text_style_action: QStyle.StandardPixmap.SP_DialogApplyButton, 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.place_text_action, self.text_style_action, self.place_image_action, self.cover_action, self.replace_image_action, self.image_properties_action, self.bring_to_front_action, self.send_to_back_action, self.bring_forward_action, self.send_backward_action, self.align_left_action, self.align_center_action, self.align_right_action, self.align_top_action, self.align_middle_action, self.align_bottom_action, self.distribute_horizontal_action, self.distribute_vertical_action, ], section_id="edit", ) self.right_tools.add_annotation_list( "页面对象", self.right_object_list, "object_list", ) self.right_tools.add_section( "注释", [ self.highlight_action, self.underline_action, self.strikeout_action, self.note_action, self.annotation_style_action, self.text_stamp_action, self.image_stamp_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_sort_combo, self.annotation_current_page_only, self.annotation_search_box, self.annotation_export_button, ], ) self._build_annotation_properties_panel() self.right_tools.add_widget_section( "注释属性", self.annotation_properties_panel, "annotation_properties", ) 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_annotation_properties_panel(self) -> None: panel = self.annotation_properties_panel panel.setObjectName("annotationPropertiesPanel") layout = QFormLayout(panel) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(6) self.annotation_property_info_label.setObjectName("annotationPropertyInfo") self.annotation_property_content.setPlaceholderText("注释内容") self.annotation_property_width.setRange(0, 16) self.annotation_property_width.setValue(self.annotation_line_width) self.annotation_property_width.setSuffix(" px") self.annotation_property_font_size.setRange(8, 72) self.annotation_property_font_size.setValue(self.text_font_size) self.annotation_property_font_size.setSuffix(" pt") self.annotation_property_opacity.setRange(10, 100) self.annotation_property_opacity.setSingleStep(5) self.annotation_property_opacity.setDecimals(0) self.annotation_property_opacity.setSuffix("%") self.annotation_property_opacity.setValue(self.annotation_opacity * 100) self._update_annotation_property_color_button() self.annotation_property_color_button.clicked.connect(self.choose_annotation_property_color) self.annotation_property_apply_button.clicked.connect(self.apply_selected_annotation_properties) layout.addRow(self.annotation_property_info_label) layout.addRow("内容", self.annotation_property_content) layout.addRow("颜色", self.annotation_property_color_button) layout.addRow("字号", self.annotation_property_font_size) layout.addRow("线宽", self.annotation_property_width) layout.addRow("透明度", self.annotation_property_opacity) layout.addRow(self.annotation_property_apply_button) self._refresh_annotation_properties_panel() 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, self.pointer_action, self.hand_action, ]: toolbar.addAction(action) toolbar.addSeparator() 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.pointer_action.toggled.connect(self.toggle_pointer_selection) self.hand_action.toggled.connect(self.toggle_hand_pan) 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.text_selection_action.toggled.connect(self.toggle_text_selection) 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.text_stamp_action.triggered.connect(self.add_text_stamp) self.image_stamp_action.triggered.connect(self.prepare_place_image_stamp) self.select_object_action.toggled.connect(self.toggle_object_selection) self.copy_object_action.triggered.connect(self.copy_selected_object) self.paste_object_action.triggered.connect(self.paste_copied_object) self.replace_image_action.triggered.connect(self.replace_selected_image) self.image_properties_action.triggered.connect(self.edit_selected_image_properties) self.bring_to_front_action.triggered.connect(lambda: self.reorder_selected_raster("front")) self.send_to_back_action.triggered.connect(lambda: self.reorder_selected_raster("back")) self.bring_forward_action.triggered.connect(lambda: self.reorder_selected_raster("forward")) self.send_backward_action.triggered.connect(lambda: self.reorder_selected_raster("backward")) self.align_left_action.triggered.connect(lambda: self.align_selected_objects("left")) self.align_center_action.triggered.connect(lambda: self.align_selected_objects("center")) self.align_right_action.triggered.connect(lambda: self.align_selected_objects("right")) self.align_top_action.triggered.connect(lambda: self.align_selected_objects("top")) self.align_middle_action.triggered.connect(lambda: self.align_selected_objects("middle")) self.align_bottom_action.triggered.connect(lambda: self.align_selected_objects("bottom")) self.distribute_horizontal_action.triggered.connect(lambda: self.distribute_selected_objects("horizontal")) self.distribute_vertical_action.triggered.connect(lambda: self.distribute_selected_objects("vertical")) 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.text_style_action.triggered.connect(self.configure_text_style) 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_sort_combo.currentIndexChanged.connect(self._refresh_annotation_panel) self.annotation_current_page_only.stateChanged.connect(self._refresh_annotation_panel) self.annotation_export_button.clicked.connect(self.export_annotations) 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 ) self.right_object_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.right_object_list.itemClicked.connect(self.select_object_from_panel_item) self.right_object_list.itemSelectionChanged.connect(self.select_objects_from_panel_selection) def _go_to_search_match(self, item: QListWidgetItem) -> None: match: SearchMatch = item.data(Qt.ItemDataRole.UserRole) self.viewer.set_search_highlights(match.page_index, match.rects) 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.selected_raster_id = None self.viewer.set_selected_object_rect(annotation.rect) self._refresh_annotation_properties_panel() 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._render_at_page(annotation.page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_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._render_at_page(annotation.page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_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) self._refresh_page_object_list() return annotations = self.document.annotations() if not annotations: item = QListWidgetItem("当前 PDF 没有注释") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) self._refresh_page_object_list() return annotations = [ annotation for annotation in annotations if self._annotation_type_matches_filter(annotation) and self._annotation_matches_search(annotation) ] if self.annotation_current_page_only.isChecked(): annotations = [ annotation for annotation in annotations if annotation.page_index == self.viewer.page_index ] sort_key = self.annotation_sort_combo.currentData() if sort_key == "page": annotations.sort(key=lambda item: (item.page_index, item.xref)) elif sort_key == "type": annotations.sort(key=lambda item: (item.annotation_type.lower(), item.page_index, item.xref)) if not annotations: item = QListWidgetItem("没有符合条件的注释") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) self._refresh_page_object_list() 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) self._refresh_page_object_list() def export_annotations(self) -> None: if not self._ensure_document(): return annotations = self.document.annotations() if self.annotation_current_page_only.isChecked(): annotations = [ annotation for annotation in annotations if annotation.page_index == self.viewer.page_index ] annotations = [ annotation for annotation in annotations if self._annotation_type_matches_filter(annotation) and self._annotation_matches_search(annotation) ] if not annotations: self.statusBar().showMessage("没有可导出的注释", 3000) return target, selected_filter = QFileDialog.getSaveFileName( self, "导出注释", "PDFReaderLite_注释.json", "JSON 文件 (*.json);;文本文件 (*.txt)", ) if not target: return target_path = Path(target) records = [ { "page": annotation.page_index + 1, "type": annotation.annotation_type, "content": annotation.content or "", "rect": annotation.rect, } for annotation in annotations ] try: if selected_filter.startswith("文本") or target_path.suffix.lower() == ".txt": lines = [ f"导出时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", f"注释数量:{len(records)}", "", ] for record in records: lines.append( f"第 {record['page']} 页 {record['type']} {record['content']} {record['rect']}" ) target_path.write_text("\n".join(lines), encoding="utf-8") else: payload = { "exported_at": datetime.now().isoformat(timespec="seconds"), "document": str(self.document.path or ""), "annotations": records, } target_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") self.statusBar().showMessage(f"注释已导出:{target_path}", 4000) except Exception as exc: QMessageBox.critical(self, "导出失败", f"无法导出注释:\n{exc}") def _refresh_page_object_list(self) -> None: if not hasattr(self, "right_object_list"): return self.right_object_list.clear() if not self.document.is_open: item = QListWidgetItem("打开 PDF 后显示页面对象") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_object_list.addItem(item) return page_index = self.viewer.page_index count = 0 for raster in self.session_raster_objects: if int(raster["page_index"]) != page_index: continue label = {"image": "图片", "signature": "签名", "stamp": "图片图章"}.get( str(raster["type"]), str(raster["type"]), ) item = QListWidgetItem(f"{label} #{raster['id']}") item.setData(Qt.ItemDataRole.UserRole, ("raster", int(raster["id"]))) self.right_object_list.addItem(item) count += 1 for annotation in self.document.annotations(): if annotation.page_index != page_index: continue content = annotation.content or annotation.annotation_type item = QListWidgetItem(f"注释 {annotation.annotation_type} {content}") item.setData(Qt.ItemDataRole.UserRole, ("annotation", annotation)) self.right_object_list.addItem(item) count += 1 if count == 0: item = QListWidgetItem("当前页没有对象") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_object_list.addItem(item) def select_object_from_panel_item(self, item: QListWidgetItem) -> None: if len(self.right_object_list.selectedItems()) > 1: self.select_objects_from_panel_selection() return payload = item.data(Qt.ItemDataRole.UserRole) if not payload: return kind, value = payload self.select_object_action.setChecked(True) if kind == "raster": raster = self._session_raster_by_id(int(value)) if not raster: return self.viewer.go_to_page(int(raster["page_index"])) self.selected_raster_id = int(raster["id"]) self.selected_annotation = None self.selected_object_keys = [("raster", int(raster["id"]))] self.viewer.set_selected_object_rect(raster["rect"]) self._refresh_annotation_properties_panel() return if kind == "annotation" and isinstance(value, AnnotationInfo): self.viewer.go_to_page(value.page_index) self.selected_annotation = value self.selected_raster_id = None self.selected_object_keys = [("annotation", value.xref)] self.viewer.set_selected_object_rect(value.rect) self._refresh_annotation_properties_panel() def select_objects_from_panel_selection(self) -> None: records = self._selected_panel_object_records() if len(records) <= 1: return self.select_object_action.setChecked(True) self.selected_annotation = None self.selected_raster_id = None self.selected_object_keys = [record["key"] for record in records] self.viewer.go_to_page(int(records[0]["page_index"])) self.viewer.set_selected_object_rects([record["rect"] for record in records]) self._refresh_annotation_properties_panel() self.statusBar().showMessage(f"已选中 {len(records)} 个对象,可执行对齐或分布", 4000) def _selected_panel_object_records(self) -> list[dict[str, object]]: records: list[dict[str, object]] = [] for item in self.right_object_list.selectedItems(): record = self._object_record_from_item(item) if record: records.append(record) return records def _object_record_from_item(self, item: QListWidgetItem) -> dict[str, object] | None: payload = item.data(Qt.ItemDataRole.UserRole) if not payload: return None kind, value = payload if kind == "raster": raster = self._session_raster_by_id(int(value)) if not raster: return None return { "key": ("raster", int(raster["id"])), "kind": "raster", "id": int(raster["id"]), "page_index": int(raster["page_index"]), "rect": tuple(raster["rect"]), } if kind == "annotation" and isinstance(value, AnnotationInfo) and value.rect: return { "key": ("annotation", value.xref), "kind": "annotation", "id": value.xref, "page_index": value.page_index, "rect": tuple(value.rect), } return None def _object_record_from_key(self, key: tuple[str, int]) -> dict[str, object] | None: kind, object_id = key if kind == "raster": raster = self._session_raster_by_id(object_id) if not raster: return None return { "key": key, "kind": "raster", "id": object_id, "page_index": int(raster["page_index"]), "rect": tuple(raster["rect"]), } if kind == "annotation": for annotation in self.document.annotations(): if annotation.xref == object_id and annotation.rect: return { "key": key, "kind": "annotation", "id": object_id, "page_index": annotation.page_index, "rect": tuple(annotation.rect), } return None def toggle_text_selection(self, enabled: bool) -> None: if enabled and not self._ensure_document(): self.viewer.set_text_selection_enabled(False) with QSignalBlocker(self.pointer_action): self.pointer_action.setChecked(enabled) return if enabled: self.pending_placement = None self.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None with QSignalBlocker(self.hand_action): self.hand_action.setChecked(False) self.viewer.set_hand_pan_enabled(False) self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_drawing_enabled(False) self.viewer.set_shape_placement_enabled(False) self.viewer.set_text_selection_enabled(enabled) if not enabled: self.pending_text_selection = None self.viewer.clear_text_selection() with QSignalBlocker(self.pointer_action): self.pointer_action.setChecked(enabled) if enabled: self.statusBar().showMessage("文本选择已启用:拖拽选择文字后可高亮、下划线或删除线", 5000) else: self.statusBar().showMessage("文本选择已关闭", 3000) def toggle_pointer_selection(self, enabled: bool) -> None: if self.text_selection_action.isChecked() != enabled: self.text_selection_action.setChecked(enabled) else: self.toggle_text_selection(enabled) def toggle_hand_pan(self, enabled: bool) -> None: if enabled: self.pending_placement = None self.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None with QSignalBlocker(self.text_selection_action), QSignalBlocker(self.pointer_action): self.text_selection_action.setChecked(False) self.pointer_action.setChecked(False) self.viewer.clear_text_selection() self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_drawing_enabled(False) self.viewer.set_shape_placement_enabled(False) self.viewer.set_text_selection_enabled(False) self.viewer.clear_text_selection() self.viewer.set_hand_pan_enabled(enabled) if enabled: self.statusBar().showMessage("手形工具已启用:按住页面拖拽移动视图", 5000) else: self.statusBar().showMessage("手形工具已关闭", 3000) def _restore_primary_pointer_or_hand(self) -> None: if self.pointer_action.isChecked(): self.viewer.set_hand_pan_enabled(False) self.viewer.set_text_selection_enabled(self.document.is_open) elif self.hand_action.isChecked(): self.viewer.set_text_selection_enabled(False) self.viewer.set_hand_pan_enabled(True) def _suspend_text_selection_view(self) -> None: self.pending_text_selection = None self.viewer.set_text_selection_enabled(False) self.viewer.clear_text_selection() def handle_text_selection( self, page_index: int, rect: tuple[float, float, float, float], start: tuple[float, float] | None = None, end: tuple[float, float] | None = None, ) -> None: if not self.text_selection_action.isChecked(): return try: text, rects = self.document.text_selection(page_index, rect, start, end) except Exception as exc: QMessageBox.critical(self, "文本选择失败", f"无法读取选区文字:\n{exc}") return if not text.strip() or not rects: self.pending_text_selection = None self.viewer.clear_text_selection() self.statusBar().showMessage("选区内没有可识别的真实文字,可改用区域类注释", 5000) return self.pending_text_selection = {"page_index": page_index, "text": text, "rects": rects} self.viewer.set_text_selection_highlights(page_index, rects) self.statusBar().showMessage("已选中文字,可点击高亮、下划线、删除线,或右键复制文字", 5000) def preview_text_selection( self, page_index: int, rect: tuple[float, float, float, float], start: tuple[float, float] | None = None, end: tuple[float, float] | None = None, ) -> None: if not self.text_selection_action.isChecked(): return if abs(rect[2] - rect[0]) < 3 and abs(rect[3] - rect[1]) < 3: self.pending_text_selection = None self.viewer.clear_text_selection() return try: text, rects = self.document.text_selection(page_index, rect, start, end) except Exception: return if not text.strip() or not rects: self.pending_text_selection = None self.viewer.clear_text_selection() return self.pending_text_selection = {"page_index": page_index, "text": text, "rects": rects} self.viewer.set_text_selection_highlights(page_index, rects) def select_existing_text_markup_at_point(self, page_index: int, point: tuple[float, float]) -> bool: if not self.text_selection_action.isChecked() or not self._ensure_document(): return False try: annotation = self.document.annotation_at_point(page_index, point) if not annotation: return False selection = self.document.annotation_text_selection(page_index, annotation.xref, include_text=False) except Exception: return False if not selection: return False text, rects = selection if not rects: return False self.pending_text_selection = { "page_index": page_index, "text": text, "rects": rects, "source_annotation_xref": annotation.xref, "source_annotation_type": annotation.annotation_type.lower(), } self.selected_annotation = annotation self.viewer.set_text_selection_highlights(page_index, rects) self.viewer.clear_object_selection() self._refresh_annotation_properties_panel() return True def show_text_selection_context_menu(self, page_index: int, point: tuple[float, float]) -> None: if not self.text_selection_action.isChecked(): return if not ( self.pending_text_selection and int(self.pending_text_selection.get("page_index", -1)) == page_index ): self.select_existing_text_markup_at_point(page_index, point) menu = QMenu(self) has_selection = bool( self.pending_text_selection and int(self.pending_text_selection.get("page_index", -1)) == page_index ) if not has_selection: hint_action = menu.addAction("请先拖拽选中文字") hint_action.setEnabled(False) menu.exec(QCursor.pos()) return if self.toggle_read_action.isChecked(): copy_action = menu.addAction("复制文字") hint_action = menu.addAction("阅读模式下仅支持复制文字") hint_action.setEnabled(False) chosen = menu.exec(QCursor.pos()) if chosen == copy_action: QApplication.clipboard().setText(str(self.pending_text_selection["text"])) self.statusBar().showMessage("选区文字已复制", 3000) return highlight_menu = menu.addMenu("高亮显示") highlight_actions: dict[QAction, tuple[float, float, float]] = {} for label, color in self._highlight_color_options(): action = highlight_menu.addAction(label) action.setIcon(self._color_swatch_icon(color)) highlight_actions[action] = color note_action = menu.addAction("添加注释") menu.addSeparator() underline_action = menu.addAction("下划线") strikeout_action = menu.addAction("删除线") copy_action = menu.addAction("复制文字") chosen = menu.exec(QCursor.pos()) if not chosen: return if chosen in highlight_actions: self._add_text_selection_markup("highlight", highlight_actions[chosen]) elif chosen == underline_action: self._add_text_selection_markup("underline") elif chosen == strikeout_action: self._add_text_selection_markup("strikeout") elif chosen == copy_action: QApplication.clipboard().setText(str(self.pending_text_selection["text"])) self.statusBar().showMessage("选区文字已复制", 3000) elif chosen == note_action: self._add_text_selection_note_popup() def _highlight_color_options(self) -> list[tuple[str, tuple[float, float, float]]]: return [ ("橙色", (0.96, 0.55, 0.13)), ("黄色", (1.0, 0.90, 0.12)), ("绿色", (0.20, 0.74, 0.29)), ("浅蓝色", (0.28, 0.74, 0.92)), ("粉色", (0.93, 0.31, 0.56)), ("红色", (0.90, 0.08, 0.14)), ] def _color_swatch_icon(self, color: tuple[float, float, float]) -> QIcon: pixmap = QPixmap(18, 18) pixmap.fill(Qt.GlobalColor.transparent) painter = QPainter(pixmap) painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(QColor.fromRgbF(*color)) painter.drawEllipse(2, 2, 14, 14) painter.end() return QIcon(pixmap) def _add_text_selection_markup( self, markup: str, color: tuple[float, float, float] | None = None, ) -> None: if not self.pending_text_selection: return if not self._ensure_can_edit("文本标记"): return page_index = int(self.pending_text_selection["page_index"]) rects = list(self.pending_text_selection["rects"]) try: source_xref = self.pending_text_selection.get("source_annotation_xref") source_type = str(self.pending_text_selection.get("source_annotation_type", "")).lower() if source_xref is not None and source_type == markup and color is not None: annotation = self.document.update_text_markup_color( page_index, int(source_xref), color, ) else: annotation = self.document.add_text_markup(page_index, rects, markup, "", color=color) if not annotation: self.statusBar().showMessage("没有可写入的文本标记", 3000) return self._render_at_page(page_index) self.pending_text_selection = None self.viewer.clear_text_selection() self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("文本标记已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "文本标记失败", f"无法添加文本标记:\n{exc}") def _add_text_selection_note_popup(self) -> None: if not self.pending_text_selection: return if not self._ensure_can_edit("添加注释"): return page_index = int(self.pending_text_selection["page_index"]) rects = list(self.pending_text_selection["rects"]) selected_text = str(self.pending_text_selection["text"]) note_text = self._show_text_selection_note_editor(selected_text) if not note_text: return x0, _y0, _x1, y1 = rects[0] note_point = (max(0.0, float(x0) - 16.0), float(y1) + 4.0) try: highlight_annotation = None source_type = str(self.pending_text_selection.get("source_annotation_type", "")).lower() if source_type != "highlight": highlight_annotation = self.document.add_text_markup( page_index, rects, "highlight", "", color=(1.0, 0.90, 0.12), ) annotation = self.document.add_note(page_index, note_text, note_point) self._render_at_page(page_index) self.pending_text_selection = None self.viewer.clear_text_selection() self._select_annotation_object(annotation) if highlight_annotation: self.statusBar().showMessage("注释已添加,所选文字已高亮,记得保存", 3000) else: self.statusBar().showMessage("注释已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "添加注释失败", f"无法添加注释:\n{exc}") def _show_text_selection_note_editor(self, selected_text: str) -> str: dialog = QDialog(self, Qt.WindowType.Popup) dialog.setWindowTitle("添加注释") dialog.setMinimumSize(300, 180) layout = QVBoxLayout(dialog) layout.setContentsMargins(12, 12, 12, 10) layout.setSpacing(8) editor = QTextEdit(dialog) editor.setPlaceholderText("在此处输入评论...") editor.setAcceptRichText(False) editor.setMinimumHeight(115) layout.addWidget(editor) button_row = QHBoxLayout() quote_label = QLabel(selected_text.strip()[:80], dialog) quote_label.setToolTip(selected_text.strip()) button_row.addWidget(quote_label, 1) cancel_button = QPushButton("取消", dialog) confirm_button = QPushButton("确定", dialog) confirm_button.setDefault(True) button_row.addWidget(cancel_button) button_row.addWidget(confirm_button) layout.addLayout(button_row) cancel_button.clicked.connect(dialog.reject) confirm_button.clicked.connect(dialog.accept) cursor_pos = QCursor.pos() screen = QApplication.screenAt(cursor_pos) or QApplication.primaryScreen() dialog.adjustSize() target_x = cursor_pos.x() + 16 target_y = cursor_pos.y() - 24 if screen: available = screen.availableGeometry() target_x = min(max(available.left(), target_x), available.right() - dialog.width()) target_y = min(max(available.top(), target_y), available.bottom() - dialog.height()) dialog.move(target_x, target_y) if dialog.exec() != QDialog.DialogCode.Accepted: return "" return editor.toPlainText().strip() def _add_text_selection_note(self) -> None: if not self.pending_text_selection: return if not self._ensure_can_edit("批注"): return page_index = int(self.pending_text_selection["page_index"]) rects = list(self.pending_text_selection["rects"]) selected_text = str(self.pending_text_selection["text"]) note_text, ok = QInputDialog.getMultiLineText( self, "添加注释", "注释内容:", selected_text, ) if not ok or not note_text.strip(): return x0, y0, _x1, _y1 = rects[0] try: annotation = self.document.add_note(page_index, note_text.strip(), (float(x0), float(y0))) self._render_at_page(page_index) self.pending_text_selection = None self.viewer.clear_text_selection() self._select_annotation_object(annotation) self.statusBar().showMessage("注释已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "添加注释失败", f"无法添加注释:\n{exc}") def highlight_current_page(self) -> None: self._apply_or_prepare_text_markup("highlight") def underline_current_page(self) -> None: self._apply_or_prepare_text_markup("underline") def strikeout_current_page(self) -> None: self._apply_or_prepare_text_markup("strikeout") def _apply_or_prepare_text_markup(self, markup: str) -> None: if self.pending_text_selection: self._add_text_selection_markup(markup) return if not self._ensure_document(): return if not self.text_selection_action.isChecked(): self.pointer_action.setChecked(True) else: self.toggle_text_selection(True) self.statusBar().showMessage("请先用指针选中文字,再点击高亮、下划线或删除线", 5000) def _start_area_markup(self, markup: str, message: str) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("区域注释"): return self.pending_placement = None self.pending_area_markup = markup self.pending_text_selection = None self.pending_shape_placement = None self._suspend_text_selection_view() self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.clear_text_selection() self.viewer.set_shape_placement_enabled(False) self.viewer.set_area_selection_enabled(True) self.statusBar().showMessage(message, 5000) def add_area_markup(self, page_index: int, rect: tuple[float, float, float, float]) -> None: if not self.pending_area_markup: return markup = self.pending_area_markup self.pending_area_markup = None self.pending_text_selection = None self.viewer.set_area_selection_enabled(False) try: color, line_width, opacity = self._annotation_style() if markup == "highlight": annotation = self.document.add_area_highlight(page_index, rect, color, min(0.55, opacity)) elif markup == "underline": annotation = self.document.add_area_line_mark(page_index, rect, False, color, line_width, opacity) elif markup == "strikeout": annotation = self.document.add_area_line_mark(page_index, rect, True, color, line_width, opacity) else: return self._render_at_page(page_index) self._select_annotation_object(annotation) self._restore_primary_pointer_or_hand() self.statusBar().showMessage("区域注释已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "区域注释失败", f"无法添加区域注释:\n{exc}") 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 page_index = self.viewer.page_index annotation = self.document.add_note(page_index, text) self._render_at_page(page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("批注已添加,记得保存", 3000) def add_text_stamp(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("文字图章"): return presets = ["已阅", "批准", "草稿", "作废", "请修改"] text, ok = QInputDialog.getItem(self, "文字图章", "选择图章:", presets, 0, True) if not ok or not text.strip(): return try: page_index = self.viewer.page_index annotation = self.document.add_text_stamp(page_index, text.strip()) self._render_at_page(page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("文字图章已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "图章失败", f"无法添加文字图章:\n{exc}") def prepare_place_image_stamp(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_stamp", "path": selected}, "点击页面位置放置图片图章") 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 choose_annotation_property_color(self) -> None: color = QColorDialog.getColor(self.annotation_property_color, self, "选择注释颜色") if color.isValid(): self.annotation_property_color = color self._update_annotation_property_color_button() def _update_annotation_property_color_button(self) -> None: color = self.annotation_property_color self.annotation_property_color_button.setText(color.name().upper()) self.annotation_property_color_button.setStyleSheet( f"background: {color.name()}; color: {'#ffffff' if color.lightness() < 128 else '#202124'};" ) def _refresh_annotation_properties_panel(self) -> None: enabled = self.selected_annotation is not None widgets = [ self.annotation_property_content, self.annotation_property_color_button, self.annotation_property_font_size, self.annotation_property_width, self.annotation_property_opacity, self.annotation_property_apply_button, ] for widget in widgets: widget.setEnabled(enabled) if not self.selected_annotation: self.annotation_property_info_label.setText("未选择注释") self.annotation_property_content.clear() return annotation = self.selected_annotation is_freetext = annotation.annotation_type.lower() == "freetext" self.annotation_property_info_label.setText( f"第 {annotation.page_index + 1} 页 {annotation.annotation_type}" ) self.annotation_property_content.setText(annotation.content or "") self.annotation_property_font_size.setEnabled(is_freetext) self.annotation_property_width.setEnabled(not is_freetext) self.annotation_property_opacity.setEnabled(not is_freetext) def apply_selected_annotation_properties(self) -> None: if not self.selected_annotation: self.statusBar().showMessage("请先选择一个注释", 3000) return color = self.annotation_property_color try: if self.selected_annotation.annotation_type.lower() == "freetext": updated = self.document.update_freetext_annotation( self.selected_annotation.page_index, self.selected_annotation.xref, self.annotation_property_content.text(), self.annotation_property_font_size.value(), (color.redF(), color.greenF(), color.blueF()), ) else: updated = self.document.update_annotation_style( self.selected_annotation.page_index, self.selected_annotation.xref, (color.redF(), color.greenF(), color.blueF()), self.annotation_property_width.value(), self.annotation_property_opacity.value() / 100, self.annotation_property_content.text(), ) if not updated: QMessageBox.warning(self, "属性更新失败", "没有找到对应的注释。") return self.selected_annotation = updated self._render_at_page(updated.page_index) self.viewer.set_selected_object_rect(updated.rect) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("注释属性已更新,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "属性更新失败", f"无法更新注释属性:\n{exc}") def configure_text_style(self) -> None: dialog = QDialog(self) dialog.setWindowTitle("文本样式") layout = QFormLayout(dialog) selected_color = QColor(self.text_color) color_button = QPushButton(selected_color.name().upper()) 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() font_size_input = QSpinBox() font_size_input.setRange(8, 72) font_size_input.setValue(self.text_font_size) font_size_input.setSuffix(" pt") layout.addRow("颜色", color_button) layout.addRow("字号", font_size_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.text_color = selected_color self.text_font_size = font_size_input.value() self.settings.setValue("textStyle/color", self.text_color.name()) self.settings.setValue("textStyle/fontSize", self.text_font_size) self.statusBar().showMessage("文本样式已更新,新建文本会使用该样式", 3000) def _text_style(self) -> tuple[int, tuple[float, float, float]]: return ( self.text_font_size, (self.text_color.redF(), self.text_color.greenF(), self.text_color.blueF()), ) 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.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None self._suspend_text_selection_view() self.freehand_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_shape_placement_enabled(False) else: self.selected_annotation = None self.selected_raster_id = None self.selected_object_keys = [] self._refresh_annotation_properties_panel() 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.selected_object_keys = [("raster", int(raster["id"]))] self.viewer.set_selected_object_rect(raster["rect"]) self._refresh_annotation_properties_panel() 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.selected_object_keys = [("annotation", annotation.xref)] if annotation else [] self.viewer.set_selected_object_rect(annotation.rect if annotation else None) self._refresh_annotation_properties_panel() if annotation: self.statusBar().showMessage("已选中对象,可拖动、缩放或按 Delete 删除", 5000) else: self.selected_object_keys = [] with QSignalBlocker(self.select_object_action): self.select_object_action.setChecked(False) self.viewer.set_object_edit_enabled(False) self.statusBar().showMessage("未选中对象", 3000) def show_annotation_tooltip(self, page_index: int, point: tuple[float, float]) -> None: if not self.document.is_open: QToolTip.hideText() return if self.pending_placement or self.pending_area_markup or self.pending_shape_placement: QToolTip.hideText() return try: annotation = self.document.annotation_at_point(page_index, point) except Exception: annotation = None content = self._annotation_tooltip_content(annotation) if content: QToolTip.showText(QCursor.pos(), content, self.viewer) else: QToolTip.hideText() def _annotation_tooltip_content(self, annotation: AnnotationInfo | None) -> str: if not annotation: return "" annotation_type = annotation.annotation_type.lower() if annotation_type in {"highlight", "underline", "strikeout", "squiggly"}: return "" content = (annotation.content or "").strip() if content in {"区域高亮", "区域下划线", "区域删除线", "遮盖"}: return "" return content def _select_annotation_object(self, annotation: AnnotationInfo, navigate: bool = False) -> None: self.selected_annotation = annotation self.selected_raster_id = None self.selected_object_keys = [("annotation", annotation.xref)] self.select_object_action.setChecked(True) self.viewer.set_object_edit_enabled(True) if navigate: self.viewer.go_to_page(annotation.page_index) elif self.viewer.document and 0 <= annotation.page_index < self.viewer.document.page_count: self.viewer.page_index = annotation.page_index if self.viewer._page_labels: self.viewer.page_label = self.viewer._page_labels[annotation.page_index] self.viewer.set_selected_object_rect(annotation.rect) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() 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: updated = self.document.update_annotation_rect_info(page_index, self.selected_annotation.xref, rect) if updated: self.selected_annotation = AnnotationInfo( page_index=page_index, xref=updated.xref, annotation_type=updated.annotation_type, content=updated.content, rect=updated.rect, ) self._render_at_page(page_index) self.viewer.set_selected_object_rect(updated.rect) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("对象已更新,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "对象更新失败", f"无法更新对象:\n{exc}") self._render_at_page(page_index) def align_selected_objects(self, mode: str) -> None: records = self._objects_for_alignment() if not records: self.statusBar().showMessage("请先在右侧页面对象列表中选择对象", 3000) return page_indices = {int(record["page_index"]) for record in records} if len(page_indices) != 1: self.statusBar().showMessage("只能对同一页内的对象执行对齐", 3000) return if len(records) == 1: target_rect = self.document.page_rect(int(records[0]["page_index"])) else: target_rect = self._bounding_rect([record["rect"] for record in records]) updates = [] tx0, ty0, tx1, ty1 = target_rect target_cx = (tx0 + tx1) / 2 target_cy = (ty0 + ty1) / 2 for record in records: x0, y0, x1, y1 = record["rect"] width = x1 - x0 height = y1 - y0 if mode == "left": new_rect = (tx0, y0, tx0 + width, y1) elif mode == "center": new_rect = (target_cx - width / 2, y0, target_cx + width / 2, y1) elif mode == "right": new_rect = (tx1 - width, y0, tx1, y1) elif mode == "top": new_rect = (x0, ty0, x1, ty0 + height) elif mode == "middle": new_rect = (x0, target_cy - height / 2, x1, target_cy + height / 2) elif mode == "bottom": new_rect = (x0, ty1 - height, x1, ty1) else: return updates.append((record, new_rect)) self._apply_object_rect_updates(updates, "对象已对齐,记得保存") def distribute_selected_objects(self, direction: str) -> None: records = self._objects_for_alignment() if len(records) < 3: self.statusBar().showMessage("分布需要至少选择 3 个对象", 3000) return page_indices = {int(record["page_index"]) for record in records} if len(page_indices) != 1: self.statusBar().showMessage("只能对同一页内的对象执行分布", 3000) return horizontal = direction == "horizontal" records.sort(key=lambda record: self._rect_center(record["rect"])[0 if horizontal else 1]) first_center = self._rect_center(records[0]["rect"])[0 if horizontal else 1] last_center = self._rect_center(records[-1]["rect"])[0 if horizontal else 1] if first_center == last_center: self.statusBar().showMessage("对象中心重合,无法分布", 3000) return step = (last_center - first_center) / (len(records) - 1) updates = [] for index, record in enumerate(records): x0, y0, x1, y1 = record["rect"] width = x1 - x0 height = y1 - y0 center = first_center + step * index if horizontal: new_rect = (center - width / 2, y0, center + width / 2, y1) else: new_rect = (x0, center - height / 2, x1, center + height / 2) updates.append((record, new_rect)) self._apply_object_rect_updates(updates, "对象已分布,记得保存") def _objects_for_alignment(self) -> list[dict[str, object]]: records = self._selected_panel_object_records() if records: return records keyed_records = [ record for key in self.selected_object_keys if (record := self._object_record_from_key(key)) ] if keyed_records: return keyed_records page_index, rect = self._selected_object_rect() if page_index is None or rect is None: return [] if self.selected_raster_id is not None: return [ { "key": ("raster", self.selected_raster_id), "kind": "raster", "id": self.selected_raster_id, "page_index": page_index, "rect": rect, } ] if self.selected_annotation is not None: return [ { "key": ("annotation", self.selected_annotation.xref), "kind": "annotation", "id": self.selected_annotation.xref, "page_index": page_index, "rect": rect, } ] return [] def _apply_object_rect_updates( self, updates: list[tuple[dict[str, object], tuple[float, float, float, float]]], message: str, ) -> None: if not updates: return updated_records: list[dict[str, object]] = [] try: annotation_updates_by_page: dict[int, dict[int, tuple[float, float, float, float]]] = {} annotation_records: dict[tuple[int, int], dict[str, object]] = {} for record, rect in updates: if record["kind"] == "raster": raster = self._session_raster_by_id(int(record["id"])) if not raster: continue raster["rect"] = rect updated_records.append({**record, "rect": rect}) else: page_index = int(record["page_index"]) object_id = int(record["id"]) annotation_updates_by_page.setdefault(page_index, {})[object_id] = rect annotation_records[(page_index, object_id)] = record for page_index, rect_updates in annotation_updates_by_page.items(): updated_annotations = self.document.update_annotation_rects(page_index, rect_updates) for original_xref, annotation in updated_annotations.items(): source = annotation_records.get((page_index, original_xref)) if source and annotation.rect: updated_records.append( { **source, "id": annotation.xref, "key": ("annotation", annotation.xref), "rect": annotation.rect, } ) self._refresh_session_raster_overlays() if updated_records: self._render_at_page(int(updated_records[0]["page_index"])) self.selected_object_keys = [record["key"] for record in updated_records] self.viewer.set_selected_object_rects([record["rect"] for record in updated_records]) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage(message, 3000) except Exception as exc: QMessageBox.critical(self, "对象排列失败", f"无法排列对象:\n{exc}") self._refresh_document_view(self.viewer.page_index) @staticmethod def _bounding_rect(rects: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]: return ( min(rect[0] for rect in rects), min(rect[1] for rect in rects), max(rect[2] for rect in rects), max(rect[3] for rect in rects), ) @staticmethod def _rect_center(rect: tuple[float, float, float, float]) -> tuple[float, float]: x0, y0, x1, y1 = rect return ((x0 + x1) / 2, (y0 + y1) / 2) def nudge_selected_object(self, dx: float, dy: float) -> bool: page_index, rect = self._selected_object_rect() if page_index is None or rect is None: return False x0, y0, x1, y1 = rect self.update_selected_object_rect(page_index, (x0 + dx, y0 + dy, x1 + dx, y1 + dy)) return True def _selected_object_rect(self) -> tuple[int | None, 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 raster: return int(raster["page_index"]), tuple(raster["rect"]) return None, None if self.selected_annotation: rect = self.selected_annotation.rect or self.document.annotation_rect( self.selected_annotation.page_index, self.selected_annotation.xref, ) return self.selected_annotation.page_index, rect return None, None def copy_selected_object(self) -> None: if self.selected_raster_id is not None: raster = self._session_raster_by_id(self.selected_raster_id) if not raster: self.statusBar().showMessage("没有可复制的对象", 3000) return self.copied_raster_object = { "type": raster["type"], "path": raster["path"], "rect": tuple(raster["rect"]), "rotation": int(raster.get("rotation", 0)), "opacity": float(raster.get("opacity", 1.0)), "crop": dict(raster.get("crop", {})), } self.copied_annotation_object = None self.statusBar().showMessage("对象已复制", 3000) return if self.selected_annotation is not None: self.copied_annotation_object = self.selected_annotation self.copied_raster_object = None self.statusBar().showMessage("注释对象已复制", 3000) return self.statusBar().showMessage("没有可复制的对象", 3000) def _has_copied_object(self) -> bool: return self.copied_raster_object is not None or self.copied_annotation_object is not None def _offset_rect(self, rect: tuple[float, float, float, float], offset: float = 18) -> tuple[float, float, float, float]: x0, y0, x1, y1 = rect return (x0 + offset, y0 + offset, x1 + offset, y1 + offset) def _paste_copied_raster_object(self) -> None: if not self.copied_raster_object: return x0, y0, x1, y1 = self.copied_raster_object["rect"] item = { "id": self.next_raster_id, "type": self.copied_raster_object["type"], "page_index": self.viewer.page_index, "path": self.copied_raster_object["path"], "rect": self._offset_rect((x0, y0, x1, y1)), "rotation": int(self.copied_raster_object.get("rotation", 0)), "opacity": float(self.copied_raster_object.get("opacity", 1.0)), "crop": dict(self.copied_raster_object.get("crop", {})), } 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._refresh_session_raster_overlays() self.viewer.set_selected_object_rect(item["rect"]) def paste_copied_object(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("粘贴对象"): return if not self._has_copied_object(): self.statusBar().showMessage("没有可粘贴的对象", 3000) return if self.copied_raster_object: self._paste_copied_raster_object() self.statusBar().showMessage("对象已粘贴,保存时会写入 PDF", 3000) return if self.copied_annotation_object: annotation = self.document.duplicate_annotation_info( self.copied_annotation_object, self.viewer.page_index, ) if not annotation: self.statusBar().showMessage("该注释暂不支持复制粘贴", 3000) return self._render_at_page(annotation.page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("注释对象已粘贴,记得保存", 3000) def replace_selected_image(self) -> None: if self.selected_raster_id is None: self.statusBar().showMessage("请选择未保存的图片/签名/图章对象", 3000) return raster = self._session_raster_by_id(self.selected_raster_id) if not raster: return selected, _ = QFileDialog.getOpenFileName( self, "替换图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)", ) if not selected: return raster["path"] = selected self._refresh_session_raster_overlays() self.viewer.set_selected_object_rect(raster["rect"]) self.statusBar().showMessage("图片已替换,保存时会写入 PDF", 3000) def edit_selected_image_properties(self) -> None: if self.selected_raster_id is None: self.statusBar().showMessage("请选择未保存的图片/签名/图章对象", 3000) return raster = self._session_raster_by_id(self.selected_raster_id) if not raster: return dialog = QDialog(self) dialog.setWindowTitle("图片属性") layout = QFormLayout(dialog) rotation_input = QComboBox() for value in [0, 90, 180, 270]: rotation_input.addItem(f"{value}掳", value) rotation_index = rotation_input.findData(int(raster.get("rotation", 0)) % 360) rotation_input.setCurrentIndex(max(0, rotation_index)) opacity_input = QDoubleSpinBox() opacity_input.setRange(10, 100) opacity_input.setSingleStep(5) opacity_input.setDecimals(0) opacity_input.setSuffix("%") opacity_input.setValue(float(raster.get("opacity", 1.0)) * 100) crop = raster.get("crop") if isinstance(raster.get("crop"), dict) else {} crop_inputs: dict[str, QDoubleSpinBox] = {} for key, label in [ ("left", "左裁剪"), ("top", "上裁剪"), ("right", "右裁剪"), ("bottom", "下裁剪"), ]: input_box = QDoubleSpinBox() input_box.setRange(0, 80) input_box.setSingleStep(2) input_box.setDecimals(0) input_box.setSuffix("%") input_box.setValue(float(crop.get(key, 0)) * 100 if crop else 0) crop_inputs[key] = input_box layout.addRow(label, input_box) layout.insertRow(0, "旋转", rotation_input) layout.insertRow(1, "透明度", 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 new_crop = {key: value.value() / 100 for key, value in crop_inputs.items()} if new_crop["left"] + new_crop["right"] >= 0.95 or new_crop["top"] + new_crop["bottom"] >= 0.95: QMessageBox.warning(self, "裁剪过大", "左右或上下裁剪总量过大,请保留至少 5% 的图片内容。") return raster["rotation"] = int(rotation_input.currentData()) raster["opacity"] = opacity_input.value() / 100 raster["crop"] = new_crop self._refresh_session_raster_overlays() self.viewer.set_selected_object_rect(raster["rect"]) self.statusBar().showMessage("图片属性已更新,保存时会写入 PDF", 3000) def reorder_selected_raster(self, direction: str) -> None: if self.selected_raster_id is None: self.statusBar().showMessage("请选择未保存的图片/签名/图章对象", 3000) return index = next( ( idx for idx, item in enumerate(self.session_raster_objects) if int(item["id"]) == self.selected_raster_id ), None, ) if index is None: return item = self.session_raster_objects.pop(index) if direction == "front": new_index = len(self.session_raster_objects) elif direction == "back": new_index = 0 elif direction == "forward": new_index = min(len(self.session_raster_objects), index + 1) elif direction == "backward": new_index = max(0, index - 1) else: new_index = index self.session_raster_objects.insert(new_index, item) self._refresh_session_raster_overlays() self.viewer.set_selected_object_rect(item["rect"]) self.statusBar().showMessage("对象层级已调整,保存时会写入 PDF", 3000) 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.selected_object_keys = [] 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): page_index = self.selected_annotation.page_index self.selected_annotation = None self.selected_object_keys = [] self.viewer.clear_object_selection() self._render_at_page(page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_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) else: self.selected_annotation = None self.viewer.clear_object_selection() menu = QMenu(self) has_object = self.selected_annotation is not None or self.selected_raster_id is not None if has_object: delete_action = menu.addAction("删除对象") copy_action = menu.addAction("复制对象") else: delete_action = None copy_action = None paste_action = menu.addAction("粘贴对象") paste_action.setEnabled(self._has_copied_object()) if not has_object and not self._has_copied_object(): hint_action = menu.addAction("没有可操作的对象") hint_action.setEnabled(False) replace_action = None image_properties_action = None front_action = None back_action = None forward_action = None backward_action = None edit_action = None properties_action = None if self.selected_raster_id is not None: replace_action = menu.addAction("替换图片") image_properties_action = menu.addAction("图片属性") layer_menu = menu.addMenu("图层顺序") front_action = layer_menu.addAction("置顶") back_action = layer_menu.addAction("置底") forward_action = layer_menu.addAction("上移一层") backward_action = layer_menu.addAction("下移一层") properties_action = menu.addAction("属性") elif self.selected_annotation is not None: if self._selected_annotation_content_editable(): edit_action = menu.addAction("编辑内容") properties_action = menu.addAction("属性") chosen = menu.exec(self.cursor().pos()) if delete_action is not None and chosen == delete_action: self.delete_selected_object() elif copy_action is not None and chosen == copy_action: self.copy_selected_object() elif chosen == paste_action: self.paste_copied_object() elif replace_action is not None and chosen == replace_action: self.replace_selected_image() elif image_properties_action is not None and chosen == image_properties_action: self.edit_selected_image_properties() elif front_action is not None and chosen == front_action: self.reorder_selected_raster("front") elif back_action is not None and chosen == back_action: self.reorder_selected_raster("back") elif forward_action is not None and chosen == forward_action: self.reorder_selected_raster("forward") elif backward_action is not None and chosen == backward_action: self.reorder_selected_raster("backward") elif edit_action is not None and chosen == edit_action and self.selected_annotation: self.edit_annotation_from_panel(self.selected_annotation) elif properties_action is not None and chosen == properties_action: self.show_selected_object_properties() def edit_object_at_point(self, page_index: int, point: tuple[float, float]) -> None: if self.toggle_read_action.isChecked() or not self.select_object_action.isChecked(): return self.select_object_at_point(page_index, point) if self.selected_annotation and self._selected_annotation_content_editable(): self.edit_annotation_from_panel(self.selected_annotation) return if self.selected_raster_id is not None: self.statusBar().showMessage("图片/签名对象可通过右键查看属性或复制粘贴", 3000) return self.statusBar().showMessage("该对象暂不支持双击编辑内容", 3000) def edit_annotation_at_point(self, page_index: int, point: tuple[float, float]) -> None: if self.toggle_read_action.isChecked() or not self._ensure_document(): return try: annotation = self.document.annotation_at_point(page_index, point) except Exception: annotation = None if not annotation or annotation.annotation_type.lower() not in {"text", "freetext"}: return self.selected_annotation = annotation self.selected_raster_id = None self.selected_object_keys = [("annotation", annotation.xref)] self.viewer.set_selected_object_rect(annotation.rect) self._refresh_annotation_properties_panel() self.edit_annotation_from_panel(annotation) def _selected_annotation_content_editable(self) -> bool: if not self.selected_annotation: return False return self.selected_annotation.annotation_type.lower() in {"freetext", "text"} def show_selected_object_properties(self) -> None: if self.selected_raster_id is not None: raster = self._session_raster_by_id(self.selected_raster_id) if not raster: return x0, y0, x1, y1 = raster["rect"] message = ( f"类型:{raster['type']}\n" f"页码:第 {int(raster['page_index']) + 1} 页\n" f"位置:{x0:.1f}, {y0:.1f}, {x1:.1f}, {y1:.1f}\n" f"文件:{raster['path']}" ) QMessageBox.information(self, "对象属性", message) return if self.selected_annotation: rect = self.selected_annotation.rect or self.document.annotation_rect( self.selected_annotation.page_index, self.selected_annotation.xref, ) rect_text = "" if rect: rect_text = f"\n位置:{rect[0]:.1f}, {rect[1]:.1f}, {rect[2]:.1f}, {rect[3]:.1f}" message = ( f"类型:{self.selected_annotation.annotation_type}\n" f"页码:第 {self.selected_annotation.page_index + 1} 页\n" f"编号:{self.selected_annotation.xref}" f"{rect_text}\n" f"内容:{self.selected_annotation.content or '无'}" ) QMessageBox.information(self, "对象属性", message) def cancel_current_operation(self) -> bool: had_pending = self.pending_placement is not None had_area = self.pending_area_markup is not None had_text = self.text_selection_action.isChecked() or self.pending_text_selection is not None had_shape = self.pending_shape_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() or self.hand_action.isChecked() if not (had_pending or had_area or had_text or had_shape or had_selection or had_tool): return False self.pending_placement = None self.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None self.selected_annotation = None self.selected_raster_id = None self.selected_object_keys = [] self.select_object_action.setChecked(False) self.freehand_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_area_selection_enabled(False) self._suspend_text_selection_view() self.viewer.set_shape_placement_enabled(False) self.viewer.set_drawing_enabled(False) self.viewer.set_object_edit_enabled(False) self.viewer.clear_object_selection() self._restore_primary_pointer_or_hand() 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): has_movable_selection = self.selected_raster_id is not None or ( self.selected_annotation is not None and self.select_object_action.isChecked() ) if has_movable_selection: step = 10 if event.modifiers() & Qt.KeyboardModifier.ShiftModifier else 1 offsets = { Qt.Key.Key_Left: (-step, 0), Qt.Key.Key_Right: (step, 0), Qt.Key.Key_Up: (0, -step), Qt.Key.Key_Down: (0, step), } if event.key() in offsets: dx, dy = offsets[event.key()] if self.nudge_selected_object(dx, dy): event.accept() return 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.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None self._suspend_text_selection_view() self.viewer.set_placement_enabled(False) self.select_object_action.setChecked(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_shape_placement_enabled(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() annotation = self.document.add_ink(page_index, points, color, line_width, opacity) self._render_at_page(page_index) if annotation: self._select_annotation_object(annotation) else: 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: font_size, text_color = self._text_style() page_index = self.viewer.page_index annotation = self.document.add_text( page_index, text, font_size=font_size, text_color=text_color, ) self._render_at_page(page_index) self._select_annotation_object(annotation) 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, "rotation": 0, "opacity": 1.0, "crop": {"left": 0.0, "top": 0.0, "right": 0.0, "bottom": 0.0}, } self.next_raster_id += 1 self.session_raster_objects.append(item) self._select_raster_object(int(item["id"])) def _select_raster_object(self, raster_id: int, navigate: bool = False) -> None: raster = self._session_raster_by_id(raster_id) if not raster: return self.selected_raster_id = raster_id self.selected_annotation = None self.selected_object_keys = [("raster", raster_id)] self.select_object_action.setChecked(True) self.viewer.set_object_edit_enabled(True) page_index = int(raster["page_index"]) if navigate: self.viewer.go_to_page(page_index) elif self.viewer.document and 0 <= page_index < self.viewer.document.page_count: self.viewer.page_index = page_index if self.viewer._page_labels: self.viewer.page_label = self.viewer._page_labels[page_index] self.viewer.set_selected_object_rect(raster["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._refresh_page_object_list() 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 _prepared_raster_path(self, item: dict[str, object]) -> str: rotation = int(item.get("rotation", 0)) % 360 opacity = float(item.get("opacity", 1.0)) crop = item.get("crop") if isinstance(item.get("crop"), dict) else {} has_crop = bool(crop) and any(float(crop.get(key, 0)) > 0 for key in ["left", "top", "right", "bottom"]) if rotation == 0 and opacity >= 0.999 and not has_crop: return str(item["path"]) pixmap = QPixmap(str(item["path"])) if pixmap.isNull(): return str(item["path"]) left = max(0.0, min(0.8, float(crop.get("left", 0) if crop else 0))) top = max(0.0, min(0.8, float(crop.get("top", 0) if crop else 0))) right = max(0.0, min(0.8, float(crop.get("right", 0) if crop else 0))) bottom = max(0.0, min(0.8, float(crop.get("bottom", 0) if crop else 0))) if left + right >= 0.95: right = 0.95 - left if top + bottom >= 0.95: bottom = 0.95 - top crop_rect = QRect( int(pixmap.width() * left), int(pixmap.height() * top), max(1, int(pixmap.width() * (1 - left - right))), max(1, int(pixmap.height() * (1 - top - bottom))), ) source = pixmap.copy(crop_rect) if source.isNull(): return str(item["path"]) canvas_width = source.height() if rotation in {90, 270} else source.width() canvas_height = source.width() if rotation in {90, 270} else source.height() image = QImage(canvas_width, canvas_height, QImage.Format.Format_ARGB32) image.fill(Qt.GlobalColor.transparent) painter = QPainter(image) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) painter.setOpacity(max(0.1, min(1.0, opacity))) painter.translate(canvas_width / 2, canvas_height / 2) painter.rotate(rotation) painter.drawPixmap(int(-source.width() / 2), int(-source.height() / 2), source) painter.end() temp_dir = Path(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.TempLocation) or ".") temp_dir = temp_dir / "PDFReaderLite" temp_dir.mkdir(parents=True, exist_ok=True) temp_path = temp_dir / f"raster_{id(item)}_{rotation}.png" image.save(str(temp_path), "PNG") return str(temp_path) 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"] image_path = self._prepared_raster_path(item) if item["type"] == "signature": self.document.add_signature_rect(int(item["page_index"]), image_path, rect) else: self.document.insert_image_rect(int(item["page_index"]), image_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.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None self._suspend_text_selection_view() self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_shape_placement_enabled(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") raster_id: int | None = None if kind == "text": font_size, text_color = self._text_style() annotation = self.document.add_text( page_index, str(payload["text"]), point, font_size=font_size, text_color=text_color, ) elif kind == "image": self._add_session_raster_object("image", page_index, str(payload["path"]), point) raster_id = self.selected_raster_id annotation = None elif kind == "image_stamp": self._add_session_raster_object("stamp", page_index, str(payload["path"]), point) raster_id = self.selected_raster_id annotation = None elif kind == "signature": self._add_session_raster_object("signature", page_index, str(payload["path"]), point) raster_id = self.selected_raster_id annotation = None else: raise ValueError("未知的放置类型") if annotation: self._render_at_page(page_index) self._select_annotation_object(annotation) if raster_id is not None: self._refresh_session_raster_overlays() self._select_raster_object(raster_id) self._restore_primary_pointer_or_hand() 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: self._start_shape_placement("rectangle", "矩形:点击第一个角点,再点击第二个角点完成") def add_circle(self) -> None: self._start_shape_placement("circle", "圆形:点击外接框第一个角点,再点击第二个角点完成") def add_line(self) -> None: self._start_shape_placement("line", "线条:点击起点,再点击终点完成") def add_arrow(self) -> None: self._start_shape_placement("arrow", "箭头:点击起点,再点击箭头终点完成") def _start_shape_placement(self, kind: str, message: str) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("图形"): return self.pending_placement = None self.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = kind self._suspend_text_selection_view() self.freehand_action.setChecked(False) self.select_object_action.setChecked(False) self.viewer.set_placement_enabled(False) self.viewer.set_area_selection_enabled(False) self.viewer.set_shape_placement_enabled(True, kind) self.statusBar().showMessage(message, 5000) def add_shape_from_points( self, page_index: int, kind: str, start: tuple[float, float], end: tuple[float, float], ) -> None: if self.pending_shape_placement != kind: return self.pending_shape_placement = None self.viewer.set_shape_placement_enabled(False) color, line_width, opacity = self._annotation_style() try: if kind in {"rectangle", "circle"}: rect = (start[0], start[1], end[0], end[1]) if abs(rect[2] - rect[0]) < 8 or abs(rect[3] - rect[1]) < 8: self.statusBar().showMessage("图形尺寸太小,请重新放置", 3000) return if kind == "rectangle": annotation = self.document.add_rectangle(page_index, color, line_width, opacity, rect) else: annotation = self.document.add_circle(page_index, color, line_width, opacity, rect) else: if math.hypot(end[0] - start[0], end[1] - start[1]) < 8: self.statusBar().showMessage("线条太短,请重新放置", 3000) return annotation = self.document.add_line( page_index, kind == "arrow", color, line_width, opacity, start, end, ) self._render_at_page(page_index) self._select_annotation_object(annotation) self._restore_primary_pointer_or_hand() self.statusBar().showMessage("图形已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "图形添加失败", f"无法添加图形:\n{exc}") def add_cover_area(self) -> None: if not self._ensure_document(): return if not self._ensure_can_edit("遮盖"): return dialog = QDialog(self) dialog.setWindowTitle("遮盖") layout = QFormLayout(dialog) selected_color = QColor(self.cover_color) color_button = QPushButton(selected_color.name().upper()) 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() opacity_input = QDoubleSpinBox() opacity_input.setRange(10, 100) opacity_input.setSingleStep(5) opacity_input.setDecimals(0) opacity_input.setValue(self.cover_opacity * 100) opacity_input.setSuffix("%") text_input = QLineEdit() text_input.setPlaceholderText("可选") layout.addRow("颜色", color_button) layout.addRow("透明度", opacity_input) layout.addRow("文字", text_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.cover_color = selected_color self.cover_opacity = opacity_input.value() / 100 self.settings.setValue("coverStyle/color", self.cover_color.name()) self.settings.setValue("coverStyle/opacity", self.cover_opacity) try: page_index = self.viewer.page_index annotation = self.document.add_cover_area( page_index, (self.cover_color.redF(), self.cover_color.greenF(), self.cover_color.blueF()), self.cover_opacity, text_input.text(), ) self._render_at_page(page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("遮盖区域已添加,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "遮盖失败", f"无法添加遮盖区域:\n{exc}") 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.pending_area_markup = None self.pending_text_selection = None self.pending_shape_placement = None self.selected_annotation = None self.selected_raster_id = None self.viewer.reset_interaction_mode() self._restore_primary_pointer_or_hand() self.statusBar().showMessage(f"阅读模式下不能使用“{tool_name}”,请先切换到编辑或注释模式", 4000) return False def _refresh_document_view(self, page_index: int | None = None) -> None: if page_index is not None and self.document.is_open: self.viewer.page_index = max(0, min(page_index, self.document.page_count - 1)) 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() @staticmethod def _page_after_page_plan(current_page: int, page_plan: list[dict[str, object]]) -> int: for new_index, entry in enumerate(page_plan): if entry.get("source") == "current" and int(entry.get("page_index", -1)) == current_page: return new_index current_entries = [ new_index for new_index, entry in enumerate(page_plan) if entry.get("source") == "current" and int(entry.get("page_index", -1)) > current_page ] if current_entries: return min(current_entries) return max(0, min(current_page, len(page_plan) - 1)) def _render_at_page(self, page_index: int) -> None: if self.viewer._page_labels and 0 <= page_index < len(self.viewer._page_labels): self.viewer.refresh_page(page_index) return scroll_value = self.viewer.verticalScrollBar().value() self.viewer.render_preserving_scroll(page_index, scroll_value) 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", "annotation_properties"]) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() elif mode == "edit": self.right_tools.set_title("编辑PDF") self.right_tools.show_sections(["edit", "object_list"]) self._refresh_page_object_list() 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.pending_area_markup = None self.pending_text_selection = None self.pending_shape_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._restore_primary_pointer_or_hand() 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("就绪")