Add caching logging packaging and annotation management
This commit is contained in:
@@ -1 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.2.0"
|
||||
|
||||
+33
-1
@@ -1,19 +1,51 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QStandardPaths
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
|
||||
from pdfreaderlite import __version__
|
||||
from pdfreaderlite.resources import software_icon_path
|
||||
from pdfreaderlite.ui.main_window import MainWindow
|
||||
|
||||
|
||||
def configure_logging() -> Path:
|
||||
log_dir = Path(
|
||||
QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
|
||||
)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_path = log_dir / "PDFReaderLite.log"
|
||||
logging.basicConfig(
|
||||
filename=log_path,
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
encoding="utf-8",
|
||||
)
|
||||
logging.info("PDFReaderLite %s started", __version__)
|
||||
return log_path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName("PDFReaderLite")
|
||||
app.setOrganizationName("PDFReaderLite")
|
||||
app.setApplicationVersion(__version__)
|
||||
app.setWindowIcon(QIcon(software_icon_path().as_posix()))
|
||||
log_path = configure_logging()
|
||||
|
||||
def handle_exception(exc_type, exc_value, exc_traceback) -> None:
|
||||
logging.exception("Unhandled exception", exc_info=(exc_type, exc_value, exc_traceback))
|
||||
QMessageBox.critical(
|
||||
None,
|
||||
"程序错误",
|
||||
f"PDFReaderLite 遇到未处理错误。\n\n日志位置:{log_path}",
|
||||
)
|
||||
|
||||
sys.excepthook = handle_exception
|
||||
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
@@ -22,6 +23,14 @@ class FormField:
|
||||
value: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AnnotationInfo:
|
||||
page_index: int
|
||||
xref: int
|
||||
annotation_type: str
|
||||
content: str
|
||||
|
||||
|
||||
class EncryptedPdfError(RuntimeError):
|
||||
pass
|
||||
|
||||
@@ -30,6 +39,9 @@ class PdfDocument:
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self._doc: fitz.Document | None = None
|
||||
self._revision = 0
|
||||
self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict()
|
||||
self._thumbnail_cache: OrderedDict[tuple[int, int, int], QImage] = OrderedDict()
|
||||
|
||||
@property
|
||||
def is_open(self) -> bool:
|
||||
@@ -59,8 +71,14 @@ class PdfDocument:
|
||||
self._doc.close()
|
||||
self._doc = None
|
||||
self.path = None
|
||||
self.clear_cache()
|
||||
|
||||
def render_page(self, page_index: int, zoom: float) -> QImage:
|
||||
cache_key = (self._revision, page_index, round(zoom, 3))
|
||||
if cache_key in self._render_cache:
|
||||
self._render_cache.move_to_end(cache_key)
|
||||
return self._render_cache[cache_key].copy()
|
||||
|
||||
page = self._page(page_index)
|
||||
matrix = fitz.Matrix(zoom, zoom)
|
||||
pixmap = page.get_pixmap(matrix=matrix, alpha=False)
|
||||
@@ -71,13 +89,22 @@ class PdfDocument:
|
||||
pixmap.stride,
|
||||
QImage.Format.Format_RGB888,
|
||||
)
|
||||
return image.copy()
|
||||
cached = image.copy()
|
||||
self._remember_cache_item(self._render_cache, cache_key, cached, max_items=16)
|
||||
return cached.copy()
|
||||
|
||||
def render_thumbnail(self, page_index: int, width: int = 150) -> QImage:
|
||||
cache_key = (self._revision, page_index, width)
|
||||
if cache_key in self._thumbnail_cache:
|
||||
self._thumbnail_cache.move_to_end(cache_key)
|
||||
return self._thumbnail_cache[cache_key].copy()
|
||||
|
||||
page = self._page(page_index)
|
||||
rect = page.rect
|
||||
zoom = width / rect.width
|
||||
return self.render_page(page_index, zoom)
|
||||
thumbnail = self.render_page(page_index, zoom)
|
||||
self._remember_cache_item(self._thumbnail_cache, cache_key, thumbnail, max_items=80)
|
||||
return thumbnail.copy()
|
||||
|
||||
def search(self, text: str, limit: int = 200) -> list[SearchMatch]:
|
||||
if not self._doc or not text.strip():
|
||||
@@ -103,6 +130,7 @@ class PdfDocument:
|
||||
def rotate_page(self, page_index: int, degrees: int = 90) -> None:
|
||||
page = self._page(page_index)
|
||||
page.set_rotation((page.rotation + degrees) % 360)
|
||||
self.mark_changed()
|
||||
|
||||
def highlight_text(self, page_index: int, text: str) -> int:
|
||||
page = self._page(page_index)
|
||||
@@ -110,6 +138,8 @@ class PdfDocument:
|
||||
for rect in rects:
|
||||
annot = page.add_highlight_annot(rect)
|
||||
annot.update()
|
||||
if rects:
|
||||
self.mark_changed()
|
||||
return len(rects)
|
||||
|
||||
def underline_text(self, page_index: int, text: str) -> int:
|
||||
@@ -118,6 +148,8 @@ class PdfDocument:
|
||||
for rect in rects:
|
||||
annot = page.add_underline_annot(rect)
|
||||
annot.update()
|
||||
if rects:
|
||||
self.mark_changed()
|
||||
return len(rects)
|
||||
|
||||
def strikeout_text(self, page_index: int, text: str) -> int:
|
||||
@@ -126,6 +158,8 @@ class PdfDocument:
|
||||
for rect in rects:
|
||||
annot = page.add_strikeout_annot(rect)
|
||||
annot.update()
|
||||
if rects:
|
||||
self.mark_changed()
|
||||
return len(rects)
|
||||
|
||||
def add_note(self, page_index: int, text: str) -> None:
|
||||
@@ -133,11 +167,13 @@ class PdfDocument:
|
||||
point = fitz.Point(72, 72)
|
||||
annot = page.add_text_annot(point, text)
|
||||
annot.update()
|
||||
self.mark_changed()
|
||||
|
||||
def add_text(self, page_index: int, text: str) -> None:
|
||||
page = self._page(page_index)
|
||||
point = fitz.Point(72, 96)
|
||||
page.insert_text(point, text, fontsize=14, fontname="china-s", color=(0, 0, 0))
|
||||
self.mark_changed()
|
||||
|
||||
def insert_image(self, page_index: int, image_path: str | Path) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -146,6 +182,7 @@ class PdfDocument:
|
||||
height = width * 0.75
|
||||
rect = fitz.Rect(72, 120, 72 + width, 120 + height)
|
||||
page.insert_image(rect, filename=str(image_path), keep_proportion=True)
|
||||
self.mark_changed()
|
||||
|
||||
def add_signature(self, page_index: int, image_path: str | Path) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -160,6 +197,7 @@ class PdfDocument:
|
||||
page_rect.height - margin,
|
||||
)
|
||||
page.insert_image(rect, filename=str(image_path), keep_proportion=True)
|
||||
self.mark_changed()
|
||||
|
||||
def add_rectangle(self, page_index: int) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -168,6 +206,7 @@ class PdfDocument:
|
||||
annot.set_colors(stroke=(0.9, 0.1, 0.1))
|
||||
annot.set_border(width=2)
|
||||
annot.update()
|
||||
self.mark_changed()
|
||||
|
||||
def add_circle(self, page_index: int) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -176,6 +215,7 @@ class PdfDocument:
|
||||
annot.set_colors(stroke=(0.1, 0.3, 0.9))
|
||||
annot.set_border(width=2)
|
||||
annot.update()
|
||||
self.mark_changed()
|
||||
|
||||
def add_line(self, page_index: int, arrow: bool = False) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -188,6 +228,7 @@ class PdfDocument:
|
||||
if arrow:
|
||||
annot.set_line_ends(fitz.PDF_ANNOT_LE_NONE, fitz.PDF_ANNOT_LE_CLOSED_ARROW)
|
||||
annot.update()
|
||||
self.mark_changed()
|
||||
|
||||
def add_cover_area(self, page_index: int) -> None:
|
||||
page = self._page(page_index)
|
||||
@@ -196,6 +237,7 @@ class PdfDocument:
|
||||
annot.set_colors(stroke=(1, 1, 1), fill=(1, 1, 1))
|
||||
annot.set_border(width=0)
|
||||
annot.update()
|
||||
self.mark_changed()
|
||||
|
||||
def insert_blank_page(self, after_page_index: int | None = None) -> int:
|
||||
if not self._doc:
|
||||
@@ -209,6 +251,7 @@ class PdfDocument:
|
||||
height = 842
|
||||
insert_at = self.page_count if after_page_index is None else after_page_index + 1
|
||||
self._doc.new_page(pno=insert_at, width=width, height=height)
|
||||
self.mark_changed()
|
||||
return insert_at
|
||||
|
||||
def insert_pdf(self, source_path: str | Path, after_page_index: int | None = None) -> int:
|
||||
@@ -218,6 +261,7 @@ class PdfDocument:
|
||||
with fitz.open(source_path) as source:
|
||||
count = source.page_count
|
||||
self._doc.insert_pdf(source, start_at=insert_at)
|
||||
self.mark_changed()
|
||||
return count
|
||||
|
||||
def extract_pages(self, page_numbers: list[int], target_path: str | Path) -> None:
|
||||
@@ -328,6 +372,38 @@ class PdfDocument:
|
||||
}
|
||||
)
|
||||
self._doc.set_metadata(metadata)
|
||||
self.mark_changed()
|
||||
|
||||
def annotations(self) -> list[AnnotationInfo]:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
items: list[AnnotationInfo] = []
|
||||
for page_index in range(self.page_count):
|
||||
page = self._page(page_index)
|
||||
annot = page.first_annot
|
||||
while annot:
|
||||
content = annot.info.get("content", "") if annot.info else ""
|
||||
items.append(
|
||||
AnnotationInfo(
|
||||
page_index=page_index,
|
||||
xref=annot.xref,
|
||||
annotation_type=annot.type[1],
|
||||
content=content,
|
||||
)
|
||||
)
|
||||
annot = annot.next
|
||||
return items
|
||||
|
||||
def delete_annotation(self, page_index: int, xref: int) -> bool:
|
||||
page = self._page(page_index)
|
||||
annot = page.first_annot
|
||||
while annot:
|
||||
if annot.xref == xref:
|
||||
page.delete_annot(annot)
|
||||
self.mark_changed()
|
||||
return True
|
||||
annot = annot.next
|
||||
return False
|
||||
|
||||
def form_fields(self) -> list[FormField]:
|
||||
if not self._doc:
|
||||
@@ -358,6 +434,7 @@ class PdfDocument:
|
||||
if widget.field_name == field_name:
|
||||
widget.field_value = value
|
||||
widget.update()
|
||||
self.mark_changed()
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -365,6 +442,7 @@ class PdfDocument:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
self._doc.delete_page(page_index)
|
||||
self.mark_changed()
|
||||
|
||||
def save(self) -> None:
|
||||
if not self.path:
|
||||
@@ -378,20 +456,25 @@ class PdfDocument:
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
original_path = self.path
|
||||
if original_path and target.resolve() == original_path.resolve():
|
||||
self._doc.saveIncr()
|
||||
self._doc.close()
|
||||
self.path = target
|
||||
self._doc = fitz.open(target)
|
||||
self.mark_changed()
|
||||
return
|
||||
|
||||
with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp:
|
||||
temp_path = Path(tmp.name)
|
||||
|
||||
try:
|
||||
self._doc.save(temp_path, garbage=4, deflate=True)
|
||||
if original_path and target.resolve() == original_path.resolve():
|
||||
self._doc.close()
|
||||
self._doc = None
|
||||
temp_path.replace(target)
|
||||
self.path = target
|
||||
if self._doc:
|
||||
self._doc.close()
|
||||
self._doc = fitz.open(target)
|
||||
self.mark_changed()
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink()
|
||||
@@ -421,6 +504,26 @@ class PdfDocument:
|
||||
raise IndexError("页码超出范围")
|
||||
return self._doc.load_page(page_index)
|
||||
|
||||
def mark_changed(self) -> None:
|
||||
self._revision += 1
|
||||
self.clear_cache()
|
||||
|
||||
def clear_cache(self) -> None:
|
||||
self._render_cache.clear()
|
||||
self._thumbnail_cache.clear()
|
||||
|
||||
@staticmethod
|
||||
def _remember_cache_item(
|
||||
cache: OrderedDict,
|
||||
key: tuple,
|
||||
image: QImage,
|
||||
max_items: int,
|
||||
) -> None:
|
||||
cache[key] = image
|
||||
cache.move_to_end(key)
|
||||
while len(cache) > max_items:
|
||||
cache.popitem(last=False)
|
||||
|
||||
@staticmethod
|
||||
def _default_rect(page: fitz.Page) -> fitz.Rect:
|
||||
width = min(220, page.rect.width * 0.45)
|
||||
|
||||
@@ -422,6 +422,68 @@ class MainWindow(QMainWindow):
|
||||
else:
|
||||
QMessageBox.warning(self, "填写失败", "没有找到对应的表单字段。")
|
||||
|
||||
def show_annotations(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
annotations = self.document.annotations()
|
||||
if not annotations:
|
||||
QMessageBox.information(self, "注释列表", "当前 PDF 没有注释。")
|
||||
return
|
||||
|
||||
dialog = QDialog(self)
|
||||
dialog.setWindowTitle("注释列表")
|
||||
layout = QVBoxLayout(dialog)
|
||||
annotation_list = QListWidget()
|
||||
for annotation in annotations:
|
||||
content = annotation.content or annotation.annotation_type
|
||||
item = QListWidgetItem(
|
||||
f"第 {annotation.page_index + 1} 页 {annotation.annotation_type} {content}"
|
||||
)
|
||||
item.setData(Qt.ItemDataRole.UserRole, annotation)
|
||||
annotation_list.addItem(item)
|
||||
layout.addWidget(annotation_list)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Close
|
||||
)
|
||||
buttons.button(QDialogButtonBox.StandardButton.Ok).setText("跳转")
|
||||
delete_button = buttons.addButton("删除", QDialogButtonBox.ButtonRole.ActionRole)
|
||||
buttons.accepted.connect(dialog.accept)
|
||||
buttons.rejected.connect(dialog.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
deleted = {"value": False}
|
||||
|
||||
def delete_selected_annotation() -> None:
|
||||
item = annotation_list.currentItem()
|
||||
if not item:
|
||||
return
|
||||
annotation = item.data(Qt.ItemDataRole.UserRole)
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"删除注释",
|
||||
"确定删除选中的注释吗?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
)
|
||||
if reply == QMessageBox.StandardButton.Yes:
|
||||
self.document.delete_annotation(annotation.page_index, annotation.xref)
|
||||
self.viewer.render()
|
||||
self.statusBar().showMessage("注释已删除,记得保存", 3000)
|
||||
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
|
||||
@@ -519,6 +581,7 @@ class MainWindow(QMainWindow):
|
||||
self.metadata_action = QAction("文档信息", self)
|
||||
self.metadata_action.setShortcut(QKeySequence("Ctrl+I"))
|
||||
self.form_fill_action = QAction("填写表单", self)
|
||||
self.annotation_list_action = QAction("注释列表", self)
|
||||
self.highlight_action = QAction("高亮", self)
|
||||
self.highlight_action.setShortcut(QKeySequence("Ctrl+H"))
|
||||
self.underline_action = QAction("下划线", self)
|
||||
@@ -571,6 +634,7 @@ class MainWindow(QMainWindow):
|
||||
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)
|
||||
|
||||
edit_menu = self.menuBar().addMenu("编辑")
|
||||
edit_menu.addAction(self.highlight_action)
|
||||
@@ -647,6 +711,7 @@ class MainWindow(QMainWindow):
|
||||
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.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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtCore import QSize, Qt, Signal
|
||||
from PySide6.QtCore import QSize, Qt, QTimer, Signal
|
||||
from PySide6.QtGui import QIcon, QPixmap
|
||||
from PySide6.QtWidgets import QListWidget, QListWidgetItem, QTabWidget, QWidget, QVBoxLayout
|
||||
|
||||
@@ -12,18 +12,25 @@ class ThumbnailList(QListWidget):
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.document: PdfDocument | None = None
|
||||
self._next_thumbnail_index = 0
|
||||
self._thumbnail_timer = QTimer(self)
|
||||
self._thumbnail_timer.timeout.connect(self._render_next_thumbnail)
|
||||
self.setIconSize(QSize(132, 176))
|
||||
self.setViewMode(QListWidget.ViewMode.ListMode)
|
||||
self.setSpacing(8)
|
||||
self.itemClicked.connect(self._emit_page)
|
||||
|
||||
def load_document(self, document: PdfDocument) -> None:
|
||||
self._thumbnail_timer.stop()
|
||||
self.document = document
|
||||
self._next_thumbnail_index = 0
|
||||
self.clear()
|
||||
for page_index in range(document.page_count):
|
||||
image = document.render_thumbnail(page_index)
|
||||
item = QListWidgetItem(QIcon(QPixmap.fromImage(image)), f"第 {page_index + 1} 页")
|
||||
item = QListWidgetItem(f"第 {page_index + 1} 页")
|
||||
item.setData(Qt.ItemDataRole.UserRole, page_index)
|
||||
self.addItem(item)
|
||||
self._thumbnail_timer.start(1)
|
||||
|
||||
def select_page(self, page_index: int) -> None:
|
||||
if 0 <= page_index < self.count():
|
||||
@@ -33,6 +40,16 @@ class ThumbnailList(QListWidget):
|
||||
page_index = item.data(Qt.ItemDataRole.UserRole)
|
||||
self.page_selected.emit(page_index)
|
||||
|
||||
def _render_next_thumbnail(self) -> None:
|
||||
if not self.document or self._next_thumbnail_index >= self.count():
|
||||
self._thumbnail_timer.stop()
|
||||
return
|
||||
page_index = self._next_thumbnail_index
|
||||
item = self.item(page_index)
|
||||
image = self.document.render_thumbnail(page_index)
|
||||
item.setIcon(QIcon(QPixmap.fromImage(image)))
|
||||
self._next_thumbnail_index += 1
|
||||
|
||||
|
||||
class Sidebar(QTabWidget):
|
||||
page_selected = Signal(int)
|
||||
|
||||
Reference in New Issue
Block a user