Add unsaved changes prompts
This commit is contained in:
@@ -65,6 +65,7 @@ PDFReaderLite 是一个面向 Windows 的轻量 PDF 阅读与编辑工具,目
|
|||||||
- Acrobat 风格右侧工具面板
|
- Acrobat 风格右侧工具面板
|
||||||
- 图片签名
|
- 图片签名
|
||||||
- 多标签页打开、切换、关闭 PDF
|
- 多标签页打开、切换、关闭 PDF
|
||||||
|
- 未保存更改星号提示,关闭标签/窗口时保存确认
|
||||||
- 深色模式
|
- 深色模式
|
||||||
- 常用快捷键
|
- 常用快捷键
|
||||||
|
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
|
|||||||
- 后台渲染(已完成缩略图分批加载)
|
- 后台渲染(已完成缩略图分批加载)
|
||||||
- 快捷键(已完成常用快捷键与说明)
|
- 快捷键(已完成常用快捷键与说明)
|
||||||
- 配置保存(已完成窗口状态、主题、最近文件)
|
- 配置保存(已完成窗口状态、主题、最近文件)
|
||||||
|
- 未保存更改保护(已完成标签星号提示与关闭标签/窗口确认)
|
||||||
- 异常恢复(已完成异常日志、日志目录入口与上次文件恢复提示)
|
- 异常恢复(已完成异常日志、日志目录入口与上次文件恢复提示)
|
||||||
- PyInstaller 打包(已完成)
|
- PyInstaller 打包(已完成)
|
||||||
- 单文件 exe(已完成)
|
- 单文件 exe(已完成)
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ class PdfDocument:
|
|||||||
self.path: Path | None = None
|
self.path: Path | None = None
|
||||||
self._doc: fitz.Document | None = None
|
self._doc: fitz.Document | None = None
|
||||||
self._revision = 0
|
self._revision = 0
|
||||||
|
self._dirty = False
|
||||||
self._undo_stack: list[bytes] = []
|
self._undo_stack: list[bytes] = []
|
||||||
self._redo_stack: list[bytes] = []
|
self._redo_stack: list[bytes] = []
|
||||||
self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict()
|
self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict()
|
||||||
@@ -60,6 +61,10 @@ class PdfDocument:
|
|||||||
return "未打开文档"
|
return "未打开文档"
|
||||||
return self.path.name
|
return self.path.name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_dirty(self) -> bool:
|
||||||
|
return self._dirty
|
||||||
|
|
||||||
def open(self, path: str | Path, password: str | None = None) -> None:
|
def open(self, path: str | Path, password: str | None = None) -> None:
|
||||||
self.close()
|
self.close()
|
||||||
self.path = Path(path)
|
self.path = Path(path)
|
||||||
@@ -68,6 +73,7 @@ class PdfDocument:
|
|||||||
if not password or not self._doc.authenticate(password):
|
if not password or not self._doc.authenticate(password):
|
||||||
self.close()
|
self.close()
|
||||||
raise EncryptedPdfError("该 PDF 需要密码。")
|
raise EncryptedPdfError("该 PDF 需要密码。")
|
||||||
|
self._dirty = False
|
||||||
self.clear_history()
|
self.clear_history()
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
@@ -75,6 +81,7 @@ class PdfDocument:
|
|||||||
self._doc.close()
|
self._doc.close()
|
||||||
self._doc = None
|
self._doc = None
|
||||||
self.path = None
|
self.path = None
|
||||||
|
self._dirty = False
|
||||||
self.clear_history()
|
self.clear_history()
|
||||||
self.clear_cache()
|
self.clear_cache()
|
||||||
|
|
||||||
@@ -653,7 +660,7 @@ class PdfDocument:
|
|||||||
self._doc.close()
|
self._doc.close()
|
||||||
self.path = target
|
self.path = target
|
||||||
self._doc = fitz.open(target)
|
self._doc = fitz.open(target)
|
||||||
self.mark_changed()
|
self.mark_saved()
|
||||||
return
|
return
|
||||||
|
|
||||||
with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp:
|
with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp:
|
||||||
@@ -666,7 +673,7 @@ class PdfDocument:
|
|||||||
if self._doc:
|
if self._doc:
|
||||||
self._doc.close()
|
self._doc.close()
|
||||||
self._doc = fitz.open(target)
|
self._doc = fitz.open(target)
|
||||||
self.mark_changed()
|
self.mark_saved()
|
||||||
finally:
|
finally:
|
||||||
if temp_path.exists():
|
if temp_path.exists():
|
||||||
temp_path.unlink()
|
temp_path.unlink()
|
||||||
@@ -721,6 +728,12 @@ class PdfDocument:
|
|||||||
|
|
||||||
def mark_changed(self) -> None:
|
def mark_changed(self) -> None:
|
||||||
self._revision += 1
|
self._revision += 1
|
||||||
|
self._dirty = True
|
||||||
|
self.clear_cache()
|
||||||
|
|
||||||
|
def mark_saved(self) -> None:
|
||||||
|
self._revision += 1
|
||||||
|
self._dirty = False
|
||||||
self.clear_cache()
|
self.clear_cache()
|
||||||
|
|
||||||
def snapshot(self) -> None:
|
def snapshot(self) -> None:
|
||||||
|
|||||||
@@ -90,6 +90,9 @@ class MainWindow(QMainWindow):
|
|||||||
self._update_status()
|
self._update_status()
|
||||||
|
|
||||||
def closeEvent(self, event) -> None:
|
def closeEvent(self, event) -> None:
|
||||||
|
if not self._confirm_close_all_sessions():
|
||||||
|
event.ignore()
|
||||||
|
return
|
||||||
self.settings.setValue("windowGeometry", self.saveGeometry())
|
self.settings.setValue("windowGeometry", self.saveGeometry())
|
||||||
self.settings.setValue("windowState", self.saveState())
|
self.settings.setValue("windowState", self.saveState())
|
||||||
super().closeEvent(event)
|
super().closeEvent(event)
|
||||||
@@ -166,6 +169,8 @@ class MainWindow(QMainWindow):
|
|||||||
if not (0 <= index < len(self.sessions)):
|
if not (0 <= index < len(self.sessions)):
|
||||||
return
|
return
|
||||||
session = self.sessions[index]
|
session = self.sessions[index]
|
||||||
|
if not self._confirm_close_session(index):
|
||||||
|
return
|
||||||
session.document.close()
|
session.document.close()
|
||||||
self.tab_widget.removeTab(index)
|
self.tab_widget.removeTab(index)
|
||||||
self.sessions.pop(index)
|
self.sessions.pop(index)
|
||||||
@@ -178,8 +183,39 @@ class MainWindow(QMainWindow):
|
|||||||
index = self.tab_widget.currentIndex()
|
index = self.tab_widget.currentIndex()
|
||||||
if 0 <= index < len(self.sessions):
|
if 0 <= index < len(self.sessions):
|
||||||
title = self.document.title if self.document.is_open else "未打开"
|
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)
|
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 offer_restore_last_file(self) -> None:
|
def offer_restore_last_file(self) -> None:
|
||||||
last_file = self.settings.value("lastOpenFile", "", str)
|
last_file = self.settings.value("lastOpenFile", "", str)
|
||||||
if not last_file or self.document.is_open or not Path(last_file).exists():
|
if not last_file or self.document.is_open or not Path(last_file).exists():
|
||||||
@@ -235,25 +271,27 @@ class MainWindow(QMainWindow):
|
|||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
QMessageBox.critical(self, "打开失败", f"无法打开 PDF:\n{exc}")
|
QMessageBox.critical(self, "打开失败", f"无法打开 PDF:\n{exc}")
|
||||||
|
|
||||||
def save_file(self) -> None:
|
def save_file(self) -> bool:
|
||||||
if not self._ensure_document():
|
if not self._ensure_document():
|
||||||
return
|
return False
|
||||||
try:
|
try:
|
||||||
self._flush_session_raster_objects()
|
self._flush_session_raster_objects()
|
||||||
self.document.save()
|
self.document.save()
|
||||||
self._update_current_tab_title()
|
self._update_current_tab_title()
|
||||||
self.statusBar().showMessage("已保存", 3000)
|
self.statusBar().showMessage("已保存", 3000)
|
||||||
|
return True
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
QMessageBox.critical(self, "保存失败", f"无法保存文件:\n{exc}")
|
QMessageBox.critical(self, "保存失败", f"无法保存文件:\n{exc}")
|
||||||
|
return False
|
||||||
|
|
||||||
def save_as_file(self) -> None:
|
def save_as_file(self) -> bool:
|
||||||
if not self._ensure_document():
|
if not self._ensure_document():
|
||||||
return
|
return False
|
||||||
selected, _ = QFileDialog.getSaveFileName(
|
selected, _ = QFileDialog.getSaveFileName(
|
||||||
self, "另存为", self.document.title, "PDF 文件 (*.pdf)"
|
self, "另存为", self.document.title, "PDF 文件 (*.pdf)"
|
||||||
)
|
)
|
||||||
if not selected:
|
if not selected:
|
||||||
return
|
return False
|
||||||
if not selected.lower().endswith(".pdf"):
|
if not selected.lower().endswith(".pdf"):
|
||||||
selected += ".pdf"
|
selected += ".pdf"
|
||||||
try:
|
try:
|
||||||
@@ -263,8 +301,10 @@ class MainWindow(QMainWindow):
|
|||||||
self._update_current_tab_title()
|
self._update_current_tab_title()
|
||||||
self._update_title()
|
self._update_title()
|
||||||
self.statusBar().showMessage("已另存为", 3000)
|
self.statusBar().showMessage("已另存为", 3000)
|
||||||
|
return True
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
QMessageBox.critical(self, "另存为失败", f"无法保存文件:\n{exc}")
|
QMessageBox.critical(self, "另存为失败", f"无法保存文件:\n{exc}")
|
||||||
|
return False
|
||||||
|
|
||||||
def save_encrypted_file(self) -> None:
|
def save_encrypted_file(self) -> None:
|
||||||
if not self._ensure_document():
|
if not self._ensure_document():
|
||||||
@@ -1391,6 +1431,7 @@ class MainWindow(QMainWindow):
|
|||||||
|
|
||||||
def _refresh_session_raster_overlays(self) -> None:
|
def _refresh_session_raster_overlays(self) -> None:
|
||||||
self.viewer.set_overlay_images(self.session_raster_objects)
|
self.viewer.set_overlay_images(self.session_raster_objects)
|
||||||
|
self._update_current_tab_title()
|
||||||
|
|
||||||
def _clear_session_raster_objects(self) -> None:
|
def _clear_session_raster_objects(self) -> None:
|
||||||
self.session_raster_objects.clear()
|
self.session_raster_objects.clear()
|
||||||
@@ -1409,6 +1450,7 @@ class MainWindow(QMainWindow):
|
|||||||
else:
|
else:
|
||||||
self.document.insert_image_rect(int(item["page_index"]), str(item["path"]), rect)
|
self.document.insert_image_rect(int(item["page_index"]), str(item["path"]), rect)
|
||||||
self._clear_session_raster_objects()
|
self._clear_session_raster_objects()
|
||||||
|
self._update_current_tab_title()
|
||||||
|
|
||||||
def _start_placement(self, payload: dict[str, object], message: str) -> None:
|
def _start_placement(self, payload: dict[str, object], message: str) -> None:
|
||||||
self.pending_placement = payload
|
self.pending_placement = payload
|
||||||
@@ -1701,6 +1743,7 @@ class MainWindow(QMainWindow):
|
|||||||
self.setWindowTitle(f"{self.document.title} - PDFReaderLite")
|
self.setWindowTitle(f"{self.document.title} - PDFReaderLite")
|
||||||
|
|
||||||
def _update_status(self) -> None:
|
def _update_status(self) -> None:
|
||||||
|
self._update_current_tab_title()
|
||||||
if not self.document.is_open:
|
if not self.document.is_open:
|
||||||
self.statusBar().showMessage("就绪")
|
self.statusBar().showMessage("就绪")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ def main() -> int:
|
|||||||
|
|
||||||
document = PdfDocument()
|
document = PdfDocument()
|
||||||
document.open(source_pdf)
|
document.open(source_pdf)
|
||||||
|
assert not document.is_dirty
|
||||||
assert document.render_page(0, 1.0).width() > 0
|
assert document.render_page(0, 1.0).width() > 0
|
||||||
assert document.render_page(0, 1.0).width() > 0
|
assert document.render_page(0, 1.0).width() > 0
|
||||||
assert document.search("feature")
|
assert document.search("feature")
|
||||||
@@ -74,6 +75,7 @@ def main() -> int:
|
|||||||
assert document.strikeout_text(0, "feature") == 1
|
assert document.strikeout_text(0, "feature") == 1
|
||||||
|
|
||||||
document.add_note(0, "note")
|
document.add_note(0, "note")
|
||||||
|
assert document.is_dirty
|
||||||
annotations = document.annotations()
|
annotations = document.annotations()
|
||||||
assert annotations
|
assert annotations
|
||||||
assert document.delete_annotation(annotations[0].page_index, annotations[0].xref)
|
assert document.delete_annotation(annotations[0].page_index, annotations[0].xref)
|
||||||
@@ -118,6 +120,7 @@ def main() -> int:
|
|||||||
allow_modify=False,
|
allow_modify=False,
|
||||||
)
|
)
|
||||||
document.save()
|
document.save()
|
||||||
|
assert not document.is_dirty
|
||||||
document.close()
|
document.close()
|
||||||
|
|
||||||
encrypted_document = PdfDocument()
|
encrypted_document = PdfDocument()
|
||||||
|
|||||||
Reference in New Issue
Block a user