diff --git a/README.md b/README.md index 7568520..b37ca57 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,27 @@ PDFReaderLite 是一个面向 Windows 的轻量 PDF 阅读与覆盖式编辑工具,目标是提供 Adobe Acrobat 常用功能的轻量替代版。 -当前稳定版本:`0.2.1` +当前稳定版本:`0.2.2` ## 当前能力 - 多标签打开 PDF。 - 连续阅读、缩放、适应宽度、适应页面、页码跳转。 - 左侧自适应缩略图。 -- 阅读、编辑PDF、页面、工具、注释模式切换。 -- 文本搜索。 +- 指针/手形工具切换,阅读、编辑PDF、页面、工具、注释模式切换。 +- 文本搜索,搜索结果跳转并临时高亮。 +- PDF 自带目录/书签显示与跳转。 +- 真实文本选择,支持复制、右键高亮、添加注释。 - 高亮、下划线、删除线、批注、自由画笔、矩形、圆形、线条、箭头。 -- 注释列表、注释跳转、注释删除。 -- 添加文本、放置文本、插入图片、放置图片、遮盖区域。 +- 高亮颜色支持橙色、黄色、绿色、浅蓝色、粉色、红色。 +- 注释列表、注释筛选、搜索、排序、仅当前页、导出、跳转、删除。 +- 注释属性修改,支持内容、颜色、字号、线宽、透明度等常见属性。 +- 鼠标悬停注释符号显示注释内容,双击注释符号可修改注释。 +- 添加文本、插入图片、遮盖区域。 - 图片签名、放置签名、手写签名。 +- 对象选择、移动、缩放、删除、复制粘贴、图层顺序、对齐与分布。 - 页面旋转、删除、移动、插入、提取、拆分、合并。 +- 页面管理支持网格缩略图、多选、批量删除、批量旋转、批量提取、拖入 PDF 插入页面。 - 基础表单填写。 - 导出页面图片、批量导出图片、图片合成 PDF。 - 保存、另存为、加密另存为、移除密码另存为。 @@ -23,26 +30,26 @@ PDFReaderLite 是一个面向 Windows 的轻量 PDF 阅读与覆盖式编辑工 - 深色模式、窗口状态记忆、异常日志。 - 单文件 exe 打包。 -## 第二版计划 +## 当前版本重点 -第二版重点提升注释和编辑能力: +`0.2.2` 在 `0.2.1` 的阅读、页面管理和基础编辑能力上,重点完善 Acrobat 风格的常用审阅流程: -- 第二版先支持框选区域高亮、下划线、删除线;真实文本选区标注留到第三版。 -- 注释属性面板。 -- 注释列表筛选和搜索。 -- 图章工具。 -- 文本框二次编辑,以及新建文本默认字号、颜色。 -- 未保存图片、签名、图章对象支持旋转、透明度、裁剪。 -- 文本、图片、签名、遮盖、图形注释统一对象选择,常见注释支持复制粘贴。 -- 右键菜单、Esc 取消、Delete 删除、方向键微调。 -- 未保存状态进一步完善。 +- 指针模式下可选择 PDF 真实文本,支持逐字/逐字母选取。 +- 双栏文档选择文字时优先按左栏、右栏阅读顺序处理。 +- 选择文字后的右键菜单支持多色高亮、复制、添加注释。 +- 添加注释后自动高亮所选文字,并保留注释符号和悬停提示。 +- 注释模式下可捕捉已有注释,进行属性修改、删除和内容编辑。 +- Ctrl+滚轮缩放、页面旋转等操作尽量保持当前页和视图位置。 文档入口: - [开发计划](docs/development_plan.md) - [V2 注释与编辑专项计划](docs/v2_annotation_edit_plan.md) - [V2 需求清单](docs/v2_requirements_checklist.md) -- [V1 发布说明](docs/release_v0.2.1.md) +- [V3 Acrobat 工作流增强计划](docs/v3_acrobat_workflow_plan.md) +- [V4 可选高级能力探索计划](docs/v4_optional_advanced_plan.md) +- [V0.2.2 发布说明](docs/release_v0.2.2.md) +- [V0.2.1 发布说明](docs/release_v0.2.1.md) V2 验收: diff --git a/dist/PDFReaderLite.exe b/dist/PDFReaderLite.exe index d990b96..a5578c8 100644 Binary files a/dist/PDFReaderLite.exe and b/dist/PDFReaderLite.exe differ diff --git a/docs/development_plan.md b/docs/development_plan.md index c42f35e..e7ecffa 100644 --- a/docs/development_plan.md +++ b/docs/development_plan.md @@ -7,7 +7,8 @@ PDFReaderLite 是面向 Windows 的轻量 PDF 阅读与覆盖式编辑工具, 核心边界: - 重点做阅读、注释、覆盖式编辑、页面管理、基础表单、视觉签名、导出、密码保护。 -- 不做复杂 OCR、PDF 原文重排编辑、数字证书签名、真正永久擦除敏感信息。 +- V3 已完成,当前稳定版本为 `v0.2.2`,重点做更像 Acrobat 的常用审阅和编辑流程。 +- V4 可重新评估 OCR、导出文本/图片、遮盖标记、签名记录等可选增强,但仍保持轻量边界。 - 打包形态以单文件 exe 为主。 ## V1:稳定可用版 @@ -44,9 +45,9 @@ V1 已发布为 `v0.2.1`,发布产物为 `dist/PDFReaderLite.exe`。 ## V2:注释与编辑增强版 -V2 目标是把“能用”提升为“顺手”,重点参考 Acrobat 的注释审阅和覆盖式编辑工作流。 +V2 已并入当前 `v0.2.2` 代码。目标是把“能用”提升为“顺手”,重点参考 Acrobat 的注释审阅和覆盖式编辑工作流。 -主线: +已完成主线: - 注释主线:文本选择标注、注释属性、注释列表筛选搜索、图章。 - 编辑主线:文本框二次编辑、对象属性、统一对象选择、复制删除移动缩放。 @@ -54,18 +55,46 @@ V2 目标是把“能用”提升为“顺手”,重点参考 Acrobat 的注 优先功能包见 [V2 注释与编辑专项计划](v2_annotation_edit_plan.md)。 -## V3:实用工具增强版 +## V3:Acrobat 常用审阅与编辑流程增强版 -候选方向: +V3 已并入当前 `v0.2.2` 代码。目标是让高频工作流更接近 Acrobat,但继续坚持“简单、实用、轻量”的原则。 -- 水印工具:文字水印、图片水印,支持全部页/指定页。 -- 图像编辑增强:裁剪、替换、透明度、旋转。 -- 页面对象列表:显示当前页新增对象,点击选中。 -- 注释导出:导出为 txt/html/json。 -- 简单测量工具:两点距离、线段长度。 -- 更完整的表单支持。 +已完成主线: -## 长期不纳入范围 +- 真实文本选择:选中 PDF 真实文本后直接高亮、下划线、删除线。 +- 选区右键菜单:选中文本后弹出多色高亮、复制、添加注释等常用动作。 +- 文本框样式:已有 FreeText 文本框支持修改内容、字号和文字颜色。 +- 注释列表增强:按页码、类型、创建顺序排序,只看当前页注释,导出 txt/json。 +- 页面管理增强:页面管理视图支持多选、批量删除、批量旋转、批量提取。 +- 搜索与导航:搜索结果显示上下文,点击跳转并临时高亮;支持 PDF 自带目录/书签面板。 +- 对象操作增强:对象复制粘贴尽量保留样式,支持简单对齐和分布。 + +缺陷修复与体验改进: + +- 指针和手形工具互斥,右侧模式按钮互斥,两组状态互不干扰。 +- 软件启动默认手形工具,指针工具用于文字选择和复制。 +- Ctrl+鼠标滚轮缩放、页面旋转、页面操作后尽量保留当前页和视图位置。 +- 双栏文档文字选择优先按栏位处理,降低跨栏误选。 +- 对水印、行号、页边元素进行选择过滤,降低误选概率。 +- 鼠标悬停注释符号时显示注释内容;双击注释符号可编辑注释。 +- 已有文本高亮支持重新选中并修改颜色。 + +专项计划见 [V3 Acrobat 工作流增强计划](v3_acrobat_workflow_plan.md)。 + +## V4:可选高级能力探索版 + +V4 允许重新讨论部分之前不做的功能,但必须保持明确边界,不承诺 Acrobat Pro 级完整能力。 + +可选方向: + +- OCR:可做外部 OCR 插件或可选安装,不内置到单 exe。 +- PDF 导出:可做导出文本、导出图片,不承诺 PDF 转 Word 并保持原排版。 +- 敏感信息处理:可做遮盖标记和风险提示,不宣称真正永久擦除。 +- 签名:可做签名图片和签名记录,不做数字证书级签名。 + +专项计划见 [V4 可选高级能力探索计划](v4_optional_advanced_plan.md)。 + +## 长期保持谨慎的范围 - PDF 转 Word 并保持原排版。 - PDF 转 Excel 并保持表格结构。 diff --git a/docs/release_v0.2.2.md b/docs/release_v0.2.2.md new file mode 100644 index 0000000..75216c9 --- /dev/null +++ b/docs/release_v0.2.2.md @@ -0,0 +1,54 @@ +# PDFReaderLite v0.2.2 发布说明 + +发布日期:2026-07-01 + +## 发布产物 + +当前为源码版本升级。打包后产物仍为: + +```text +dist\PDFReaderLite.exe +``` + +版本信息: + +- 应用版本:`0.2.2` +- exe 版本:`0.2.2` +- 文件大小:`49,463,139 bytes` +- SHA256:`0A7701E9F10D23009CF22C8188A094DA1DDBCAF8C2455D352546EB65A9B74CBA` +- Git 标签:待发布后填写 + +## 本版定位 + +`0.2.2` 是第三版审阅与编辑流程增强后的稳定版本,重点完善 Acrobat 风格的文本选择、注释、页面管理和视图保持体验。 + +## 主要新增与完善 + +- 指针模式支持选择 PDF 真实文本,并支持逐字、逐字母选择。 +- 选中文本后右键菜单支持复制、多色高亮、下划线、删除线、添加注释。 +- 高亮颜色支持橙色、黄色、绿色、浅蓝色、粉色、红色。 +- 添加注释时可自动高亮所选文字,并在页面上保留注释符号。 +- 鼠标悬停注释符号显示注释内容;双击注释符号可修改注释内容。 +- 注释模式下可捕捉已有注释,进行属性修改和删除。 +- 已有文本高亮可重新选中并修改颜色。 +- 双栏文档文字选择按栏位优化,降低左栏、右栏混选。 +- 带水印、行号文档的文字选择增加过滤,降低误选页边内容。 +- 左侧目录页签支持读取 PDF 自带书签并跳转。 +- 注释列表支持类型筛选、关键字搜索、仅当前页、排序和导出 JSON/TXT。 +- 页面管理支持多选、批量删除、批量旋转、批量提取,以及拖入 PDF 插入页面。 +- 对象操作支持多选后的对齐和分布。 +- Ctrl+鼠标滚轮缩放、页面旋转、页面操作后尽量保留当前页和视图位置。 +- 指针/手形工具互斥,右侧阅读、编辑PDF、页面、工具、注释模式互斥,两组状态互不干扰。 + +## 已验证 + +- 源码冒烟测试通过。 +- Python 编译检查通过。 +- 版本号已同步到应用、包元数据和 Windows exe 版本资源。 + +## 已知边界 + +- 当前编辑仍属于覆盖式编辑,不是 PDF 原文段落级重排编辑。 +- 遮盖区域是视觉遮盖,不是敏感信息永久擦除。 +- 选区快捷操作当前采用右键菜单,悬浮迷你工具条保留为后续可选优化。 +- OCR、数字证书签名、自动更新不在当前版本范围。 diff --git a/docs/v2_annotation_edit_plan.md b/docs/v2_annotation_edit_plan.md index 8f2cfc1..a7a51a9 100644 --- a/docs/v2_annotation_edit_plan.md +++ b/docs/v2_annotation_edit_plan.md @@ -1,5 +1,11 @@ # V2 注释与编辑专项计划 +## 当前状态 + +V2 已并入当前 `v0.2.2` 代码。原 V2 目标中的框选区域标注、注释属性、注释列表、图章、文本框二次编辑、统一对象选择、右键菜单、键盘操作和未保存提示均已完成。 + +后续 V3 已继续补齐真实文本选择、多色高亮、选区添加注释、目录面板、页面管理批处理、注释导出和对象对齐分布等能力。本文档保留为 V2 需求来源和验收记录。 + ## 目标 V2 重点提升注释和编辑体验,让 PDFReaderLite 从“功能可用”进入“审阅和覆盖式编辑顺手”的阶段。 @@ -20,19 +26,19 @@ V2 重点提升注释和编辑体验,让 PDFReaderLite 从“功能可用” 第二版实施边界: - 第二版先做框选区域标注,可用于普通文本 PDF 和扫描/图片型 PDF。 -- 真正识别 PDF 文本选区、选中文本后的迷你工具条,延期到第三版。 +- 真正识别 PDF 文本选区、选中文本后的快捷操作已在 V3 / `v0.2.2` 中完成,当前以右键菜单形式提供。 目标: - 鼠标选中页面文字后,可直接执行高亮、下划线、删除线。 -- 选中文本后可出现迷你工具条,提供高亮、下划线、删除线、复制、添加批注。 +- 选中文本后可通过右键菜单执行高亮、下划线、删除线、复制、添加批注;悬浮迷你工具条作为后续可选优化。 - 对无法识别文本的扫描页,保留现有输入文字标注方式。 验收标准: - 可在普通文本 PDF 中选中一段文字并直接添加标注。 - 标注后注释列表自动刷新。 -- Esc 可取消当前选区或迷你工具条。 +- Esc 可取消当前选区或快捷菜单相关状态。 ### 2. 注释属性面板 @@ -77,7 +83,7 @@ V2 重点提升注释和编辑体验,让 PDFReaderLite 从“功能可用” - 支持拖动、缩放、删除。 - 双击文本框可修改内容。 - 第二版支持设置新建文本框的默认字号、颜色。 -- 已有文本框样式编辑和中文文本加粗延期到第三版。 +- 已有文本框内容、字号、文字颜色编辑已完成;中文文本加粗暂不作为当前承诺能力。 验收标准: @@ -97,7 +103,7 @@ V2 重点提升注释和编辑体验,让 PDFReaderLite 从“功能可用” - 文本、图片、签名、遮盖、图形注释使用统一选择框和控制点。 - 右键菜单支持删除、复制、属性。 -- 第二版支持常见注释对象复制粘贴;复杂 PDF 原生对象复制延期到第三版。 +- 当前支持常见注释对象复制粘贴并尽量保留样式;复杂 PDF 原生对象仍不承诺完整编辑。 - 键盘 Delete 删除,Esc 取消选择。 - 方向键微调位置,Shift+方向键大步移动。 diff --git a/docs/v2_requirements_checklist.md b/docs/v2_requirements_checklist.md index 779c9e9..4ebc3c9 100644 --- a/docs/v2_requirements_checklist.md +++ b/docs/v2_requirements_checklist.md @@ -1,12 +1,14 @@ # V2 需求清单 +当前状态:V2 已完成并并入 `v0.2.2`;V3 又补齐了真实文本选择、选区右键菜单、注释导出、目录面板和页面管理批处理等增强能力。 + ## 注释:新增功能 - [x] 框选区域后直接高亮。 - [x] 框选区域后直接下划线。 - [x] 框选区域后直接删除线。 -- [ ] 鼠标选择真实文本后直接高亮、下划线、删除线。(V3) -- [ ] 选中文本后的迷你工具条。(V3) +- [x] 鼠标选择真实文本后直接高亮、下划线、删除线。(V3 / 0.2.2) +- [x] 选中文本后的快捷操作菜单。(V3 / 0.2.2,当前为右键菜单;悬浮迷你工具条保留为后续可选优化) - [x] 注释属性面板。 - [x] 注释颜色设置。 - [x] 注释线宽设置。 @@ -35,7 +37,7 @@ - [x] 文本框双击编辑内容。 - [x] 新建文本框默认字号设置。 - [x] 新建文本框默认颜色设置。 -- [ ] 文本框加粗设置。(V3,需确认中文 FreeText 加粗方案) +- [ ] 文本框加粗设置。(暂不承诺,需确认中文 FreeText 加粗方案) - [x] 添加文本后自动选中新对象。 - [x] 图片替换。 - [x] 未保存图片/签名/图章对象旋转。 @@ -78,7 +80,10 @@ ## 验收测试建议 - [x] 普通文本 PDF:框选区域后高亮、下划线、删除线。 -- [ ] 普通文本 PDF:选择真实文字后高亮、下划线、删除线。(V3) +- [x] 普通文本 PDF:选择真实文字后高亮、下划线、删除线。(V3 / 0.2.2) +- [x] 普通文本 PDF:选择文字后右键多色高亮、复制、添加注释。 +- [x] 双栏文本 PDF:选择文字时优先按栏位处理,降低跨栏误选。 +- [x] 带水印、行号 PDF:选择文字时过滤常见页边和水印干扰。 - [x] 扫描/图片型 PDF:区域高亮、图章、画笔仍可使用。 - [x] 多页 PDF:注释列表筛选、搜索、跳转、属性编辑正确。 - [x] 多标签 PDF:每个标签的未保存状态独立。 diff --git a/docs/v3_acrobat_workflow_plan.md b/docs/v3_acrobat_workflow_plan.md new file mode 100644 index 0000000..463d99a --- /dev/null +++ b/docs/v3_acrobat_workflow_plan.md @@ -0,0 +1,182 @@ +# V3 Acrobat 工作流增强计划 + +## 当前实现进度 + +- 当前 V3 能力已并入 `v0.2.2`。 +- 已完成:真实文本框选识别、选区高亮、下划线、删除线、复制文字、选区批注。 +- 已完成:选区快捷操作以轻量右键菜单实现;后续如需要,可再升级为悬浮迷你工具条。 +- 已完成:右键高亮颜色支持橙色、黄色、绿色、浅蓝色、粉色、红色。 +- 已完成:添加注释时自动高亮所选文字,并保留注释符号和悬停提示。 +- 已完成:选中注释符号后双击可编辑注释内容。 +- 已完成:已有 FreeText 文本框可在右侧属性中修改内容、字号和文字颜色。 +- 已完成:注释列表支持类型筛选、关键字搜索、仅当前页、排序、导出 JSON/TXT。 +- 已完成:搜索结果点击后在页面上临时高亮命中区域。 +- 已完成:左侧新增目录页签,可读取 PDF 自带书签并跳转。 +- 已完成:页面管理支持多选、批量删除、批量左旋/右旋、提取所选页面。 +- 已完成:常见注释复制粘贴时尽量保留颜色、填充色、线宽、透明度和内容。 +- 已完成:页面对象支持多选后的左/中/右、顶/中/底对齐,以及水平/垂直分布。 +- 已完成:页面管理支持从资源管理器拖入 PDF,并按释放位置插入外部 PDF 页面。 +- 已完成:Ctrl+滚轮缩放、旋转页面、页面操作后尽量保持当前页和视图位置。 +- 已完成:双栏文档文字选择按栏位优化,带水印和行号文档选择时过滤常见干扰。 +- 当前 V3 计划项已完成,后续进入打包、人工验收和缺陷修复。 + +## 目标 + +V3 目标是让 PDFReaderLite 的高频审阅和覆盖式编辑流程更接近 Adobe Acrobat 常用操作,但继续保持轻量、中文、Windows 单机使用优先。 + +核心原则: + +- 优先做简单实用的常用功能。 +- 真实文本选择和注释快捷操作优先于复杂格式转换。 +- 继续保留扫描件/图片型 PDF 的框选区域标注作为兜底方案。 +- 不做 PDF 原文段落级重排编辑。 +- 所有新增功能都要能保存、撤销或明确提示不可撤销边界。 + +## 第一优先级 + +### 1. 真实文本选择与快捷标注 + +目标: + +- 鼠标拖选 PDF 真实文本后,可直接高亮、下划线、删除线。 +- 支持复制选中文本。 +- 支持对选中文本添加批注。 +- 扫描件或无法识别文本时,继续使用 V2 的框选区域标注。 + +建议实现: + +- 在页面视图中维护文本选区。 +- 使用 PyMuPDF 的文本块/词坐标识别选中区域对应文字。 +- 对真实文本使用 PDF 原生 highlight/underline/strikeout 注释。 +- 选区取消支持 Esc、点击空白处、切换模式。 + +验收标准: + +- 普通文本 PDF 可拖选一段文字并添加三种标注。 +- 标注后右侧注释列表和属性面板自动刷新。 +- 扫描件上不崩溃,并能继续使用区域标注。 + +### 2. 选中文本后的快捷操作 + +目标: + +- 选中文本后提供快捷操作。 +- 快捷操作包含:多色高亮、下划线、删除线、复制、批注。 +- Esc、点击空白处或切换操作后取消选区。 + +建议实现: + +- 当前实现为右键菜单,稳定后可再评估是否升级为悬浮迷你工具条。 +- 注释操作需在可编辑模式下执行;阅读模式仍保留文本选择和复制能力。 + +验收标准: + +- 菜单不会遮挡主要阅读流程。 +- 菜单动作与右侧注释列表同步。 +- 切换页码、缩放、滚动后选区状态保持可控。 + +### 3. 已有文本框样式编辑 + +目标: + +- 已写入 PDF 的 FreeText 文本框可编辑字号、颜色、加粗、对齐方式。 +- 新建文本框继续使用默认文本样式。 + +边界: + +- 中文加粗需要优先验证 PyMuPDF FreeText 的稳定方案。 +- 如果中文加粗不稳定,可采用“仅新建文本支持样式预设,已有文本暂不强制加粗”的降级方案。 + +验收标准: + +- 双击文本框可修改内容。 +- 选中文本框后右侧属性可修改字号、颜色。 +- 保存重开后样式存在。 + +## 第二优先级 + +### 4. 注释列表增强 + +目标: + +- 支持按页码、类型、创建顺序排序。 +- 支持只显示当前页注释。 +- 支持导出注释为 txt/json。 + +建议导出内容: + +- 页码。 +- 注释类型。 +- 注释内容。 +- 矩形坐标。 +- 导出时间。 + +验收标准: + +- 多页 PDF 中筛选、排序、搜索组合使用正确。 +- 导出文件中文正常。 + +### 5. 页面管理多选与批处理 + +目标: + +- 页面管理视图支持多选。 +- 支持批量删除、批量旋转、批量提取。 +- 拖拽重排时显示插入位置。 +- 支持从资源管理器拖入 PDF 到页面管理视图并插入。 + +验收标准: + +- 多选页面批处理后页码顺序正确。 +- 保存重开后页面顺序和内容正确。 +- 操作前有明确确认,避免误删。 + +### 6. 搜索结果上下文与目录面板 + +目标: + +- 搜索结果显示命中页码和前后上下文。 +- 点击搜索结果跳转并临时高亮命中区域。 +- 如果 PDF 自带目录/书签,则显示目录面板。 + +验收标准: + +- 多页搜索结果定位准确。 +- 没有目录的 PDF 不显示空白噪音。 + +## 第三优先级 + +### 7. 对象对齐与分布 + +目标: + +- 多对象选择后支持左对齐、居中、右对齐。 +- 支持水平/垂直分布。 + +边界: + +- V3 可先支持当前会话对象和常见注释对象。 +- 复杂 PDF 原生对象仍不承诺完整编辑。 + +### 8. 复制粘贴保留样式 + +目标: + +- 注释对象复制粘贴时尽量保留颜色、线宽、透明度、内容。 +- 文本框复制粘贴尽量保留字号、颜色。 + +验收标准: + +- 常见注释复制后视觉效果接近原对象。 +- 不支持的对象类型给出提示,不静默失败。 + +## 建议实施顺序 + +1. 真实文本选择基础能力。 +2. 真实文本高亮、下划线、删除线。 +3. 选区右键快捷菜单。 +4. 已有文本框样式编辑。 +5. 注释列表排序、当前页过滤、导出。 +6. 页面管理多选和批处理。 +7. 搜索上下文和目录面板。 +8. 对象对齐、样式复制等增强。 diff --git a/docs/v4_optional_advanced_plan.md b/docs/v4_optional_advanced_plan.md new file mode 100644 index 0000000..d3b3e68 --- /dev/null +++ b/docs/v4_optional_advanced_plan.md @@ -0,0 +1,116 @@ +# V4 可选高级能力探索计划 + +## 目标 + +V4 用于探索部分更高级但仍保持轻量边界的功能。V4 不追求完整替代 Acrobat Pro,也不承诺复杂版面重建、证书签名或真正永久擦除。 + +核心原则: + +- 高风险能力采用可选安装、外部工具或明确降级方案。 +- 不把大型 OCR 引擎内置进单文件 exe。 +- 对用户可能误解的安全能力必须给出明确提示。 +- 优先提供“可用、可解释、不会误导”的轻量能力。 + +## 可选方向 + +### 1. OCR 外部插件或可选安装 + +目标: + +- 支持调用外部 OCR 工具识别当前页或指定页。 +- 可选生成简单文本层或导出 OCR 文本。 + +边界: + +- 不内置完整 OCR 到单 exe。 +- 不承诺高质量可搜索 PDF。 +- 不承诺扫描件自动版面分析。 + +建议方案: + +- 软件设置中配置外部 OCR 程序路径。 +- 支持按页导出图片后交给外部 OCR。 +- OCR 结果先以 txt 或侧边栏文本方式展示。 + +验收标准: + +- 未配置外部 OCR 时界面给出清晰提示。 +- OCR 失败不影响原 PDF。 + +### 2. PDF 导出文本/图片 + +目标: + +- 支持导出当前页或全部页文本。 +- 支持导出当前页或全部页图片。 +- 可选将导出的文本按页分段保存。 + +边界: + +- 不承诺 PDF 转 Word 并保持原排版。 +- 不承诺 PDF 转 Excel 并保持表格结构。 +- 表格导出仅作为后续探索,不放入 V4 必做项。 + +验收标准: + +- 普通文本 PDF 能导出可读 txt。 +- 扫描件无文本时给出提示。 +- 图片导出沿用已有页面图片导出能力,不重复造复杂流程。 + +### 3. 敏感信息遮盖标记 + +目标: + +- 在遮盖工具基础上增加“敏感信息遮盖标记”模式。 +- 遮盖对象有特殊名称或列表标识,便于检查。 +- 保存前提示:这是视觉遮盖,不是真正永久擦除。 + +边界: + +- 不宣称真正永久擦除敏感信息。 +- 不自动删除 PDF 内部文本、对象、元数据。 +- 如果未来做真正擦除,需要单独设计和专项验证。 + +验收标准: + +- 用户能区分普通遮盖和敏感信息遮盖标记。 +- 导出或保存前有明确风险提示。 + +### 4. 签名图片与签名记录 + +目标: + +- 在现有图片签名、点击放置签名、手写签名基础上增加签名记录。 +- 记录签名时间、页码、位置、签名图片名称或摘要。 +- 可导出签名记录 txt/json。 + +边界: + +- 不做数字证书级签名。 +- 不做法律意义上的签名验证。 +- 不承诺防篡改。 + +验收标准: + +- 添加签名后可在签名记录列表中看到记录。 +- 保存重开后签名图片仍在 PDF 中。 +- 签名记录导出中文正常。 + +## 暂不纳入 V4 必做项 + +- PDF 转 Word 并保持原排版。 +- PDF 转 Excel 并保持表格结构。 +- OCR 生成高质量可搜索 PDF。 +- 扫描件自动版面分析。 +- 数字证书签名。 +- 敏感信息真正永久擦除。 +- 自动更新。 +- 单 exe 内置完整 OCR。 + +## 建议实施顺序 + +1. 导出文本能力。 +2. 敏感信息遮盖标记和风险提示。 +3. 签名记录列表与导出。 +4. 外部 OCR 配置和单页 OCR 文本导出。 + diff --git a/packaging/version_info.txt b/packaging/version_info.txt index 31cbd1c..9b10f90 100644 --- a/packaging/version_info.txt +++ b/packaging/version_info.txt @@ -1,8 +1,8 @@ # UTF-8 VSVersionInfo( ffi=FixedFileInfo( - filevers=(0, 2, 1, 0), - prodvers=(0, 2, 1, 0), + filevers=(0, 2, 2, 0), + prodvers=(0, 2, 2, 0), mask=0x3f, flags=0x0, OS=0x40004, @@ -17,11 +17,11 @@ VSVersionInfo( [ StringStruct("CompanyName", "PDFReaderLite"), StringStruct("FileDescription", "PDFReaderLite"), - StringStruct("FileVersion", "0.2.1"), + StringStruct("FileVersion", "0.2.2"), StringStruct("InternalName", "PDFReaderLite"), StringStruct("OriginalFilename", "PDFReaderLite.exe"), StringStruct("ProductName", "PDFReaderLite"), - StringStruct("ProductVersion", "0.2.1"), + StringStruct("ProductVersion", "0.2.2"), ], ) ]), diff --git a/pdfreaderlite/__init__.py b/pdfreaderlite/__init__.py index 3ced358..b5fdc75 100644 --- a/pdfreaderlite/__init__.py +++ b/pdfreaderlite/__init__.py @@ -1 +1 @@ -__version__ = "0.2.1" +__version__ = "0.2.2" diff --git a/pdfreaderlite/core/document.py b/pdfreaderlite/core/document.py index 131855d..5d1b40d 100644 --- a/pdfreaderlite/core/document.py +++ b/pdfreaderlite/core/document.py @@ -13,6 +13,14 @@ from PySide6.QtGui import QImage class SearchMatch: page_index: int text: str + rects: list[tuple[float, float, float, float]] + + +@dataclass(frozen=True) +class Bookmark: + level: int + title: str + page_index: int @dataclass(frozen=True) @@ -37,6 +45,8 @@ class EncryptedPdfError(RuntimeError): class PdfDocument: + _TEXT_MARKUP_TYPES = {"highlight", "underline", "strikeout", "squiggly"} + def __init__(self) -> None: self.path: Path | None = None self._doc: fitz.Document | None = None @@ -130,6 +140,9 @@ class PdfDocument: self._remember_cache_item(self._thumbnail_cache, cache_key, thumbnail, max_items=80) return thumbnail.copy() + def page_rect(self, page_index: int) -> tuple[float, float, float, float]: + return self._rect_tuple(self._page(page_index).rect) + def search(self, text: str, limit: int = 200) -> list[SearchMatch]: if not self._doc or not text.strip(): return [] @@ -137,7 +150,8 @@ class PdfDocument: matches: list[SearchMatch] = [] query = text.strip() for page_index, page in enumerate(self._doc): - if page.search_for(query): + rects = page.search_for(query) + if rects: page_text = page.get_text("text").replace("\n", " ") snippet_index = page_text.lower().find(query.lower()) if snippet_index >= 0: @@ -146,17 +160,51 @@ class PdfDocument: snippet = page_text[start:end].strip() else: snippet = f"第 {page_index + 1} 页匹配" - matches.append(SearchMatch(page_index=page_index, text=snippet)) + matches.append( + SearchMatch( + page_index=page_index, + text=snippet, + rects=[self._rect_tuple(rect) for rect in rects], + ) + ) if len(matches) >= limit: break return matches + def bookmarks(self) -> list[Bookmark]: + if not self._doc: + raise RuntimeError("没有打开 PDF") + items: list[Bookmark] = [] + for entry in self._doc.get_toc(simple=True): + if len(entry) < 3: + continue + level, title, page_number = entry[:3] + page_index = int(page_number) - 1 + if 0 <= page_index < self.page_count: + items.append(Bookmark(level=max(1, int(level)), title=str(title), page_index=page_index)) + return items + def rotate_page(self, page_index: int, degrees: int = 90) -> None: self.snapshot() page = self._page(page_index) page.set_rotation((page.rotation + degrees) % 360) self.mark_changed() + def rotate_pages(self, page_indices: list[int], degrees: int = 90) -> None: + if not self._doc: + raise RuntimeError("没有打开 PDF") + unique_pages = sorted(set(page_indices)) + if not unique_pages: + return + for page_index in unique_pages: + if page_index < 0 or page_index >= self.page_count: + raise IndexError("页码超出范围") + self.snapshot() + for page_index in unique_pages: + 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) rects = page.search_for(text.strip()) @@ -193,11 +241,449 @@ class PdfDocument: self.mark_changed() return len(rects) - def add_note(self, page_index: int, text: str) -> AnnotationInfo: + def text_selection( + self, + page_index: int, + rect: tuple[float, float, float, float], + start: tuple[float, float] | None = None, + end: tuple[float, float] | None = None, + ) -> tuple[str, list[tuple[float, float, float, float]]]: + page = self._page(page_index) + selection = self._normalized_rect(rect) + all_chars = self._page_text_chars(page) + selectable_chars = all_chars + if start is not None: + column_split = self._detect_text_char_column_split(all_chars, float(page.rect.width)) + if column_split is not None: + start_column = 0 if float(start[0]) < column_split else 1 + column_chars = [ + char_item + for char_item in all_chars + if self._char_belongs_to_column(char_item, column_split, start_column) + ] + if column_chars: + selectable_chars = column_chars + + selected_chars: list[tuple[int, int, int, str, fitz.Rect]] = [] + if start is not None and end is not None and selectable_chars: + start_index = self._text_char_index_for_point(selectable_chars, start) + end_index = self._text_char_index_for_point(selectable_chars, end) + if start_index is not None and end_index is not None: + first = min(start_index, end_index) + last = max(start_index, end_index) + selected_chars = selectable_chars[first : last + 1] + + if not selected_chars: + for char_item in selectable_chars: + char_rect = char_item[4] + if not selection.intersects(char_rect): + continue + selected_chars.append(char_item) + + if not selected_chars: + return "", [] + if start is not None: + selected_chars = self._filter_chars_to_start_cluster( + selected_chars, + start, + float(page.rect.width), + ) + if not selected_chars: + return "", [] + + lines: list[str] = [] + current_key: tuple[int, int] | None = None + current_chars: list[str] = [] + rects: list[tuple[float, float, float, float]] = [] + for block, line, _char_index, text, char_rect in selected_chars: + key = (block, line) + if current_key is not None and key != current_key: + lines.append("".join(current_chars)) + current_chars = [] + current_key = key + current_chars.append(text) + rects.append(self._rect_tuple(char_rect)) + if current_chars: + lines.append("".join(current_chars)) + return "\n".join(lines), rects + + @staticmethod + def _page_text_chars(page: fitz.Page) -> list[tuple[int, int, int, str, fitz.Rect]]: + raw = page.get_text("rawdict") + lines: list[dict[str, object]] = [] + page_width = float(page.rect.width) + for block_index, block in enumerate(raw.get("blocks", [])): + for line_index, line in enumerate(block.get("lines", [])): + direction = line.get("dir", (1, 0)) + if not PdfDocument._is_selectable_text_direction(direction): + continue + line_chars: list[tuple[int, int, str, fitz.Rect]] = [] + for span in line.get("spans", []): + for char in span.get("chars", []): + text = str(char.get("c", "")) + bbox = char.get("bbox") + if not text or not bbox: + continue + line_chars.append((block_index, line_index, text, fitz.Rect(bbox))) + if not line_chars: + continue + line_rect = PdfDocument._union_rect([item[3] for item in line_chars]) + line_text = "".join(item[2] for item in line_chars).strip() + if not line_text: + continue + lines.append( + { + "chars": line_chars, + "rect": line_rect, + "text": line_text, + } + ) + + body_left = PdfDocument._estimate_body_left(lines, page_width) + selectable_lines: list[dict[str, object]] = [] + for line in lines: + line_rect = line["rect"] + line_text = str(line["text"]) + if isinstance(line_rect, fitz.Rect) and PdfDocument._is_margin_artifact_line( + line_text, + line_rect, + body_left, + ): + continue + selectable_lines.append(line) + + ordered_lines = PdfDocument._sort_text_lines_reading_order(selectable_lines, page_width) + chars: list[tuple[int, int, int, str, fitz.Rect]] = [] + char_index = 0 + for reading_line_index, line in enumerate(ordered_lines): + for _block_index, _line_index, text, rect in line["chars"]: + chars.append((0, reading_line_index, char_index, text, rect)) + char_index += 1 + return chars + + @staticmethod + def _is_selectable_text_direction(direction: object) -> bool: + try: + dx, dy = direction + return abs(float(dy)) <= 0.12 and abs(float(dx)) >= 0.85 + except Exception: + return True + + @staticmethod + def _union_rect(rects: list[fitz.Rect]) -> fitz.Rect: + rect = fitz.Rect(rects[0]) + for item in rects[1:]: + rect |= item + return rect + + @staticmethod + def _estimate_body_left(lines: list[dict[str, object]], page_width: float) -> float: + candidates: list[float] = [] + for line in lines: + rect = line["rect"] + text = str(line["text"]) + if not isinstance(rect, fitz.Rect): + continue + if rect.width < page_width * 0.16: + continue + if len(text) < 12: + continue + if not any(char.isalpha() or "\u4e00" <= char <= "\u9fff" for char in text): + continue + candidates.append(float(rect.x0)) + if not candidates: + return page_width * 0.08 + candidates.sort() + return candidates[min(len(candidates) - 1, max(0, len(candidates) // 10))] + + @staticmethod + def _is_margin_artifact_line(text: str, rect: fitz.Rect, body_left: float) -> bool: + stripped = text.strip() + if not stripped: + return True + if rect.x1 >= body_left - 5: + return False + compact = stripped.replace(" ", "") + if compact.isdigit(): + return True + if len(compact) <= 3 and rect.width <= 28: + return True + return False + + @staticmethod + def _sort_text_lines_reading_order( + lines: list[dict[str, object]], + page_width: float, + ) -> list[dict[str, object]]: + if len(lines) < 6: + return sorted(lines, key=PdfDocument._line_yx_sort_key) + + body_lines = [ + line + for line in lines + if isinstance(line.get("rect"), fitz.Rect) + and fitz.Rect(line["rect"]).width < page_width * 0.62 + and len(str(line.get("text", "")).strip()) >= 6 + ] + split = PdfDocument._detect_column_split(body_lines, page_width) + if split is None: + return sorted(lines, key=PdfDocument._line_yx_sort_key) + + column_lines = [ + line + for line in lines + if isinstance(line.get("rect"), fitz.Rect) + and not PdfDocument._line_spans_column_split(fitz.Rect(line["rect"]), split, page_width) + ] + if not column_lines: + return sorted(lines, key=PdfDocument._line_yx_sort_key) + top_y = min(fitz.Rect(line["rect"]).y0 for line in column_lines) + bottom_y = max(fitz.Rect(line["rect"]).y1 for line in column_lines) + + def sort_key(line: dict[str, object]) -> tuple[int, int, float, float]: + rect = fitz.Rect(line["rect"]) + if PdfDocument._line_spans_column_split(rect, split, page_width): + if rect.y1 < top_y - 2: + return (0, 0, rect.y0, rect.x0) + if rect.y0 > bottom_y + 2: + return (3, 0, rect.y0, rect.x0) + return (2, 0, rect.y0, rect.x0) + column = 0 if rect.x0 < split else 1 + return (1, column, rect.y0, rect.x0) + + return sorted(lines, key=sort_key) + + @staticmethod + def _detect_column_split(lines: list[dict[str, object]], page_width: float) -> float | None: + centers = sorted(float((fitz.Rect(line["rect"]).x0 + fitz.Rect(line["rect"]).x1) / 2) for line in lines) + if len(centers) < 6: + return None + best_gap = 0.0 + best_index = -1 + for index in range(len(centers) - 1): + gap = centers[index + 1] - centers[index] + if gap > best_gap: + best_gap = gap + best_index = index + if best_index < 0 or best_gap < page_width * 0.12: + return None + left_count = best_index + 1 + right_count = len(centers) - left_count + if left_count < 3 or right_count < 3: + return None + split = (centers[best_index] + centers[best_index + 1]) / 2 + if split < page_width * 0.25 or split > page_width * 0.75: + return None + return split + + @staticmethod + def _line_spans_column_split(rect: fitz.Rect, split: float, page_width: float) -> bool: + margin = max(10.0, page_width * 0.025) + return rect.x0 < split - margin and rect.x1 > split + margin + + @staticmethod + def _line_yx_sort_key(line: dict[str, object]) -> tuple[float, float]: + rect = fitz.Rect(line["rect"]) + return (rect.y0, rect.x0) + + @staticmethod + def _text_char_index_for_point( + chars: list[tuple[int, int, int, str, fitz.Rect]], + point: tuple[float, float], + ) -> int | None: + if not chars: + return None + px, py = point + line_groups: dict[tuple[int, int], list[tuple[int, tuple[int, int, int, str, fitz.Rect]]]] = {} + for index, char in enumerate(chars): + line_groups.setdefault((char[0], char[1]), []).append((index, char)) + + best_line: list[tuple[int, tuple[int, int, int, str, fitz.Rect]]] | None = None + best_distance: tuple[float, float] | None = None + for line_chars in line_groups.values(): + y0 = min(item[1][4].y0 for item in line_chars) + y1 = max(item[1][4].y1 for item in line_chars) + x0 = min(item[1][4].x0 for item in line_chars) + x1 = max(item[1][4].x1 for item in line_chars) + if y0 <= py <= y1: + y_distance = 0.0 + else: + y_distance = min(abs(py - y0), abs(py - y1)) + if x0 <= px <= x1: + x_distance = 0.0 + else: + x_distance = min(abs(px - x0), abs(px - x1)) + distance = (y_distance, x_distance) + if best_distance is None or distance < best_distance: + best_distance = distance + best_line = line_chars + if not best_line: + return None + + best_index = best_line[0][0] + best_x_distance: float | None = None + for index, char in best_line: + rect = char[4] + if rect.x0 <= px <= rect.x1: + return index + distance = min(abs(px - rect.x0), abs(px - rect.x1)) + if best_x_distance is None or distance < best_x_distance: + best_x_distance = distance + best_index = index + return best_index + + @staticmethod + def _detect_text_char_column_split( + chars: list[tuple[int, int, int, str, fitz.Rect]], + page_width: float, + ) -> float | None: + if len(chars) < 80: + return None + line_groups: dict[int, list[tuple[int, int, int, str, fitz.Rect]]] = {} + for char_item in chars: + line_groups.setdefault(char_item[1], []).append(char_item) + + lines: list[dict[str, object]] = [] + for line_chars in line_groups.values(): + rect = PdfDocument._union_rect([char_item[4] for char_item in line_chars]) + text = "".join(char_item[3] for char_item in line_chars).strip() + if len(text) < 6: + continue + lines.append({"rect": rect, "text": text}) + split = PdfDocument._detect_column_split(lines, page_width) + if split is not None: + return split + + centers = sorted((char_item[4].x0 + char_item[4].x1) / 2 for char_item in chars) + if len(centers) < 80: + return None + best_gap = 0.0 + best_index = -1 + for index in range(len(centers) - 1): + gap = centers[index + 1] - centers[index] + if gap > best_gap: + best_gap = gap + best_index = index + if best_index < 0 or best_gap < page_width * 0.035: + return None + left_count = best_index + 1 + right_count = len(centers) - left_count + if left_count < 20 or right_count < 20: + return None + split = (centers[best_index] + centers[best_index + 1]) / 2 + if split < page_width * 0.25 or split > page_width * 0.75: + return None + return split + + @staticmethod + def _filter_chars_to_start_cluster( + chars: list[tuple[int, int, int, str, fitz.Rect]], + start: tuple[float, float], + page_width: float, + ) -> list[tuple[int, int, int, str, fitz.Rect]]: + if len(chars) < 24: + return chars + centers = sorted((char_item[4].x0 + char_item[4].x1) / 2 for char_item in chars) + best_gap = 0.0 + best_index = -1 + for index in range(len(centers) - 1): + gap = centers[index + 1] - centers[index] + if gap > best_gap: + best_gap = gap + best_index = index + if best_index < 0 or best_gap < max(14.0, page_width * 0.025): + return chars + left_count = best_index + 1 + right_count = len(centers) - left_count + if left_count < 8 or right_count < 8: + return chars + split = (centers[best_index] + centers[best_index + 1]) / 2 + if split < page_width * 0.25 or split > page_width * 0.75: + return chars + start_column = 0 if float(start[0]) < split else 1 + return [ + char_item + for char_item in chars + if PdfDocument._char_belongs_to_column(char_item, split, start_column) + ] + + @staticmethod + def _char_belongs_to_column( + char_item: tuple[int, int, int, str, fitz.Rect], + split: float, + column: int, + ) -> bool: + rect = char_item[4] + center_x = (rect.x0 + rect.x1) / 2 + return center_x < split if column == 0 else center_x >= split + + @staticmethod + def _point_on_spanning_text_line( + chars: list[tuple[int, int, int, str, fitz.Rect]], + point: tuple[float, float], + split: float, + page_width: float, + ) -> bool: + px, py = point + line_groups: dict[int, list[tuple[int, int, int, str, fitz.Rect]]] = {} + for char_item in chars: + line_groups.setdefault(char_item[1], []).append(char_item) + for line_chars in line_groups.values(): + rect = PdfDocument._union_rect([char_item[4] for char_item in line_chars]) + if rect.y0 <= py <= rect.y1 and rect.x0 - 2 <= px <= rect.x1 + 2: + return PdfDocument._line_spans_column_split(rect, split, page_width) + return False + + def add_text_markup( + self, + page_index: int, + rects: list[tuple[float, float, float, float]], + markup: str, + content: str = "", + color: tuple[float, float, float] | None = None, + ) -> AnnotationInfo | None: + if not rects: + return None self.snapshot() page = self._page(page_index) - point = fitz.Point(72, 72) - annot = page.add_text_annot(point, text) + fitz_rects = self._merge_markup_rects_for_selection( + [self._normalized_rect(rect) for rect in rects], + float(page.rect.width), + ) + if not fitz_rects: + return None + if markup == "highlight": + annot = page.add_highlight_annot(fitz_rects) + elif markup == "underline": + annot = page.add_underline_annot(fitz_rects) + elif markup == "strikeout": + annot = page.add_strikeout_annot(fitz_rects) + else: + raise ValueError("未知的文本标记类型") + if color: + annot.set_colors(stroke=color) + if content: + annot.set_info(content=content) + annot.update() + self.mark_changed() + return AnnotationInfo( + page_index=page_index, + xref=annot.xref, + annotation_type=annot.type[1], + content=annot.info.get("content", "") if annot.info else "", + rect=self._rect_tuple(annot.rect), + ) + + def add_note( + self, + page_index: int, + text: str, + point: tuple[float, float] | None = None, + ) -> AnnotationInfo: + self.snapshot() + page = self._page(page_index) + x, y = point or (72, 72) + annot = page.add_text_annot(fitz.Point(x, y), text) annot.set_info(content=text) annot.update() self.mark_changed() @@ -404,11 +890,12 @@ class PdfDocument: stroke_color: tuple[float, float, float] = (0.9, 0.1, 0.1), border_width: float = 2, opacity: float = 1.0, + rect: tuple[float, float, float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) - rect = self._default_rect(page) - annot = page.add_rect_annot(rect) + target_rect = self._normalized_rect(rect) if rect else self._default_rect(page) + annot = page.add_rect_annot(target_rect) self._apply_annotation_style(annot, stroke_color, border_width, opacity) annot.update() self.mark_changed() @@ -426,11 +913,12 @@ class PdfDocument: stroke_color: tuple[float, float, float] = (0.1, 0.3, 0.9), border_width: float = 2, opacity: float = 1.0, + rect: tuple[float, float, float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) - rect = self._default_rect(page) - annot = page.add_circle_annot(rect) + target_rect = self._normalized_rect(rect) if rect else self._default_rect(page) + annot = page.add_circle_annot(target_rect) self._apply_annotation_style(annot, stroke_color, border_width, opacity) annot.update() self.mark_changed() @@ -449,12 +937,18 @@ class PdfDocument: stroke_color: tuple[float, float, float] = (0.1, 0.1, 0.1), border_width: float = 2, opacity: float = 1.0, + start_point: tuple[float, float] | None = None, + end_point: tuple[float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) - rect = self._default_rect(page) - start = fitz.Point(rect.x0, rect.y0) - end = fitz.Point(rect.x1, rect.y1) + if start_point and end_point: + start = fitz.Point(float(start_point[0]), float(start_point[1])) + end = fitz.Point(float(end_point[0]), float(end_point[1])) + else: + rect = self._default_rect(page) + start = fitz.Point(rect.x0, rect.y0) + end = fitz.Point(rect.x1, rect.y1) annot = page.add_line_annot(start, end) self._apply_annotation_style(annot, stroke_color, border_width, opacity) if arrow: @@ -701,7 +1195,12 @@ class PdfDocument: matches: list[AnnotationInfo] = [] annot = page.first_annot while annot: - if annot.rect.contains(hit): + annot_type = annot.type[1].lower() + if annot_type in self._TEXT_MARKUP_TYPES: + hit_annotation = any(rect.contains(hit) for rect in self._annotation_markup_rects(annot, inflate=2.5)) + else: + hit_annotation = annot.rect.contains(hit) + if hit_annotation: content = annot.info.get("content", "") if annot.info else "" matches.append( AnnotationInfo( @@ -715,9 +1214,103 @@ class PdfDocument: annot = annot.next return matches[-1] if matches else None - def annotation_rect(self, page_index: int, xref: int) -> tuple[float, float, float, float] | None: + def annotation_text_selection( + self, + page_index: int, + xref: int, + include_text: bool = True, + ) -> tuple[str, list[tuple[float, float, float, float]]] | None: + page = self._page(page_index) annot = self._annotation(page_index, xref) - return self._rect_tuple(annot.rect) if annot else None + if not annot or annot.type[1].lower() not in self._TEXT_MARKUP_TYPES: + return None + + rects = self._merge_markup_rects_for_selection(self._annotation_markup_rects(annot), float(page.rect.width)) + if not rects: + return None + + if not include_text: + return "", [self._rect_tuple(rect) for rect in rects] + + fallback_lines = [page.get_textbox(rect + (-1, -1, 1, 1)).strip() for rect in rects] + fallback_text = "\n".join(line for line in fallback_lines if line) + return fallback_text, [self._rect_tuple(rect) for rect in rects] + + @staticmethod + def _annotation_markup_rects(annot, inflate: float = 0.0) -> list[fitz.Rect]: + vertices = getattr(annot, "vertices", None) or [] + rects: list[fitz.Rect] = [] + for index in range(0, len(vertices), 4): + quad_points = vertices[index : index + 4] + if len(quad_points) < 4: + continue + xs: list[float] = [] + ys: list[float] = [] + for point in quad_points: + try: + xs.append(float(point.x)) + ys.append(float(point.y)) + except AttributeError: + xs.append(float(point[0])) + ys.append(float(point[1])) + rect = fitz.Rect(min(xs), min(ys), max(xs), max(ys)) + if rect.width > 0 and rect.height > 0: + if inflate: + rect = rect + (-inflate, -inflate, inflate, inflate) + rects.append(rect) + if rects: + return rects + rect = fitz.Rect(annot.rect) if annot.rect else None + if rect and inflate: + rect = rect + (-inflate, -inflate, inflate, inflate) + return [rect] if rect else [] + + @staticmethod + def _merge_markup_rects_for_selection(rects: list[fitz.Rect], page_width: float) -> list[fitz.Rect]: + if not rects: + return [] + sorted_rects = sorted(rects, key=lambda rect: (round(rect.y0, 1), rect.x0)) + lines: list[list[fitz.Rect]] = [] + for rect in sorted_rects: + placed = False + center_y = (rect.y0 + rect.y1) / 2 + for line in lines: + line_rect = PdfDocument._union_rect(line) + line_center_y = (line_rect.y0 + line_rect.y1) / 2 + tolerance = max(3.0, min(rect.height, line_rect.height) * 0.65) + if abs(center_y - line_center_y) <= tolerance: + line.append(rect) + placed = True + break + if not placed: + lines.append([rect]) + + merged: list[fitz.Rect] = [] + max_gap = max(8.0, page_width * 0.035) + for line in lines: + current: fitz.Rect | None = None + for rect in sorted(line, key=lambda item: item.x0): + if current is None: + current = fitz.Rect(rect) + continue + gap = rect.x0 - current.x1 + if gap <= max_gap: + current |= rect + else: + merged.append(current) + current = fitz.Rect(rect) + if current is not None: + merged.append(current) + return merged + + def annotation_rect(self, page_index: int, xref: int) -> tuple[float, float, float, float] | None: + page = self._page(page_index) + annot = page.first_annot + while annot: + if annot.xref == xref: + return self._rect_tuple(annot.rect) + annot = annot.next + return None def update_annotation_rect( self, @@ -725,17 +1318,103 @@ class PdfDocument: xref: int, rect: tuple[float, float, float, float], ) -> bool: - annot = self._annotation(page_index, xref) + return self.update_annotation_rect_info(page_index, xref, rect) is not None + + def update_annotation_rect_info( + self, + page_index: int, + xref: int, + rect: tuple[float, float, float, float], + ) -> AnnotationInfo | None: + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next if not annot: - return False + return None x0, y0, x1, y1 = rect - if x1 - x0 < 12 or y1 - y0 < 12: - return False + annot_type = annot.type[1].lower() + min_size = 2 if annot_type in self._TEXT_MARKUP_TYPES else 12 + if x1 - x0 < min_size or y1 - y0 < min_size: + return None + content = annot.info.get("content", "") if annot.info else "" + style = self._annotation_visual_style_from_annot(annot) self.snapshot() - annot.set_rect(fitz.Rect(x0, y0, x1, y1)) - annot.update() + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot: + return None + target_rect = fitz.Rect(x0, y0, x1, y1) + if annot_type in self._TEXT_MARKUP_TYPES: + new_annot = self._replace_text_markup_annotation(page, annot, annot_type, target_rect, content, style) + if not new_annot: + return None + annot = new_annot + else: + annot.set_rect(target_rect) + annot.update() self.mark_changed() - return True + return AnnotationInfo( + page_index=page_index, + xref=annot.xref, + annotation_type=annot.type[1], + content=annot.info.get("content", "") if annot.info else "", + rect=self._rect_tuple(annot.rect), + ) + + def update_annotation_rects( + self, + page_index: int, + rect_updates: dict[int, tuple[float, float, float, float]], + ) -> dict[int, AnnotationInfo]: + if not rect_updates: + return {} + normalized_updates: dict[int, fitz.Rect] = {} + for xref, rect in rect_updates.items(): + x0, y0, x1, y1 = rect + if x1 - x0 < 2 or y1 - y0 < 2: + continue + normalized_updates[int(xref)] = fitz.Rect(x0, y0, x1, y1) + if not normalized_updates: + return {} + + self.snapshot() + page = self._page(page_index) + targets = [] + annot = page.first_annot + while annot: + if annot.xref in normalized_updates: + targets.append((annot.xref, annot, normalized_updates[annot.xref])) + annot = annot.next + if not targets: + return {} + + updated: dict[int, AnnotationInfo] = {} + for original_xref, annot, rect in targets: + annot_type = annot.type[1].lower() + content = annot.info.get("content", "") if annot.info else "" + if annot_type not in self._TEXT_MARKUP_TYPES and (rect.width < 12 or rect.height < 12): + continue + if annot_type in self._TEXT_MARKUP_TYPES: + style = self._annotation_visual_style_from_annot(annot) + new_annot = self._replace_text_markup_annotation(page, annot, annot_type, rect, content, style) + if not new_annot: + continue + annot = new_annot + else: + annot.set_rect(rect) + annot.update() + updated[original_xref] = AnnotationInfo( + page_index=page_index, + xref=annot.xref, + annotation_type=annot.type[1], + content=annot.info.get("content", "") if annot.info else "", + rect=self._rect_tuple(annot.rect), + ) + self.mark_changed() + return updated def move_annotation(self, page_index: int, xref: int, dx: float, dy: float) -> bool: annot = self._annotation(page_index, xref) @@ -814,6 +1493,102 @@ class PdfDocument: rect=self._rect_tuple(annot.rect), ) + def update_text_markup_color( + self, + page_index: int, + xref: int, + color: tuple[float, float, float], + ) -> AnnotationInfo | None: + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot: + return None + annot_type = annot.type[1].lower() + if annot_type not in self._TEXT_MARKUP_TYPES: + return None + content = annot.info.get("content", "") if annot.info else "" + rects = self._merge_markup_rects_for_selection( + self._annotation_markup_rects(annot), + float(page.rect.width), + ) + if not rects: + return None + + self.snapshot() + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot: + return None + page.delete_annot(annot) + if annot_type == "highlight": + new_annot = page.add_highlight_annot(rects) + elif annot_type == "underline": + new_annot = page.add_underline_annot(rects) + elif annot_type == "strikeout": + new_annot = page.add_strikeout_annot(rects) + elif annot_type == "squiggly": + new_annot = page.add_squiggly_annot(rects) + else: + return None + new_annot.set_colors(stroke=color) + if content: + new_annot.set_info(content=content) + new_annot.update() + self.mark_changed() + return AnnotationInfo( + page_index=page_index, + xref=new_annot.xref, + annotation_type=new_annot.type[1], + content=new_annot.info.get("content", "") if new_annot.info else "", + rect=self._rect_tuple(new_annot.rect), + ) + + def update_freetext_annotation( + self, + page_index: int, + xref: int, + content: str, + font_size: int, + text_color: tuple[float, float, float], + ) -> AnnotationInfo | None: + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot or annot.type[1].lower() != "freetext": + return None + rect = self._rect_tuple(annot.rect) + self.snapshot() + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot: + return None + page.delete_annot(annot) + new_annot = page.add_freetext_annot( + fitz.Rect(*rect), + content, + fontsize=max(8, min(72, int(font_size))), + fontname="china-s", + text_color=text_color, + border_width=0, + ) + new_annot.set_info(content=content) + new_annot.update() + self.mark_changed() + return AnnotationInfo( + page_index=page_index, + xref=new_annot.xref, + annotation_type=new_annot.type[1], + content=content, + rect=self._rect_tuple(new_annot.rect), + ) + def duplicate_annotation_info( self, annotation: AnnotationInfo, @@ -826,6 +1601,7 @@ class PdfDocument: rect = fitz.Rect(*annotation.rect) + (dx, dy, dx, dy) content = annotation.content or "" annot_type = annotation.annotation_type.lower() + source_style = self._annotation_visual_style(annotation.page_index, annotation.xref) self.snapshot() page = self._page(target_page_index) @@ -842,21 +1618,22 @@ class PdfDocument: duplicate = page.add_text_annot(rect.tl, content) elif annot_type in {"square", "rect"}: duplicate = page.add_rect_annot(rect) - duplicate.set_colors(stroke=(0.1, 0.35, 0.85)) - duplicate.set_border(width=2) elif annot_type in {"circle", "ellipse"}: duplicate = page.add_circle_annot(rect) - duplicate.set_colors(stroke=(0.1, 0.35, 0.85)) - duplicate.set_border(width=2) elif annot_type == "line": start = fitz.Point(rect.x0, rect.y0 + rect.height / 2) end = fitz.Point(rect.x1, rect.y0 + rect.height / 2) duplicate = page.add_line_annot(start, end) - duplicate.set_colors(stroke=(0.1, 0.35, 0.85)) - duplicate.set_border(width=2) + elif annot_type == "highlight": + duplicate = page.add_highlight_annot(rect) + elif annot_type == "underline": + duplicate = page.add_underline_annot(rect) + elif annot_type == "strikeout": + duplicate = page.add_strikeout_annot(rect) else: return None + self._apply_annotation_visual_style_snapshot(duplicate, source_style) if content: duplicate.set_info(content=content) duplicate.update() @@ -869,6 +1646,78 @@ class PdfDocument: rect=self._rect_tuple(duplicate.rect), ) + def _annotation_visual_style(self, page_index: int, xref: int) -> dict[str, object]: + page = self._page(page_index) + annot = page.first_annot + while annot and annot.xref != xref: + annot = annot.next + if not annot: + return {} + return self._annotation_visual_style_from_annot(annot) + + @staticmethod + def _annotation_visual_style_from_annot(annot) -> dict[str, object]: + colors = annot.colors or {} + border = annot.border or {} + style: dict[str, object] = { + "stroke": colors.get("stroke"), + "fill": colors.get("fill"), + "border_width": border.get("width"), + } + try: + style["opacity"] = annot.opacity + except Exception: + style["opacity"] = None + return style + + def _replace_text_markup_annotation( + self, + page: fitz.Page, + annot, + annot_type: str, + rect: fitz.Rect, + content: str, + style: dict[str, object], + ): + page.delete_annot(annot) + if annot_type == "highlight": + new_annot = page.add_highlight_annot(rect) + elif annot_type == "underline": + new_annot = page.add_underline_annot(rect) + elif annot_type == "strikeout": + new_annot = page.add_strikeout_annot(rect) + elif annot_type == "squiggly": + new_annot = page.add_squiggly_annot(rect) + else: + return None + if content: + new_annot.set_info(content=content) + self._apply_annotation_visual_style_snapshot(new_annot, style) + new_annot.update() + return new_annot + + def _apply_annotation_visual_style_snapshot(self, annot, style: dict[str, object]) -> None: + stroke = style.get("stroke") + fill = style.get("fill") + if stroke is not None or fill is not None: + try: + annot.set_colors(stroke=stroke, fill=fill) + except Exception: + if stroke is not None: + annot.set_colors(stroke=stroke) + border_width = style.get("border_width") + if border_width is not None: + try: + annot.set_border(width=max(0, float(border_width))) + except Exception: + pass + opacity = style.get("opacity") + if opacity is not None: + try: + annot.set_opacity(max(0.1, min(1.0, float(opacity)))) + except Exception: + pass + def delete_annotation(self, page_index: int, xref: int) -> bool: page = self._page(page_index) annot = page.first_annot @@ -938,8 +1787,12 @@ class PdfDocument: def reorder_pages(self, page_order: list[int]) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") - if sorted(page_order) != list(range(self.page_count)): - raise ValueError("页面顺序必须包含所有页面且不能重复") + if not page_order: + raise ValueError("页面顺序不能为空") + if len(set(page_order)) != len(page_order): + raise ValueError("页面顺序不能包含重复页面") + if any(page_index < 0 or page_index >= self.page_count for page_index in page_order): + raise ValueError("页面顺序包含超出范围的页面") if page_order == list(range(self.page_count)): return @@ -953,6 +1806,49 @@ class PdfDocument: reordered.close() self._replace_with_bytes(data) + def apply_page_plan(self, page_plan: list[dict[str, object]]) -> None: + if not self._doc: + raise RuntimeError("没有打开 PDF") + if not page_plan: + raise ValueError("页面计划不能为空") + current_order = [ + int(entry["page_index"]) + for entry in page_plan + if entry.get("source") == "current" + ] + has_external = any(entry.get("source") == "external" for entry in page_plan) + if not has_external and current_order == list(range(self.page_count)): + return + + self.snapshot() + rebuilt = fitz.open() + external_docs: dict[str, fitz.Document] = {} + try: + for entry in page_plan: + source = entry.get("source") + page_index = int(entry["page_index"]) + if source == "current": + if page_index < 0 or page_index >= self.page_count: + raise ValueError("页面计划包含超出范围的当前 PDF 页面") + rebuilt.insert_pdf(self._doc, from_page=page_index, to_page=page_index) + elif source == "external": + path = str(entry["path"]) + source_doc = external_docs.get(path) + if source_doc is None: + source_doc = fitz.open(path) + external_docs[path] = source_doc + if page_index < 0 or page_index >= source_doc.page_count: + raise ValueError("页面计划包含超出范围的外部 PDF 页面") + rebuilt.insert_pdf(source_doc, from_page=page_index, to_page=page_index) + else: + raise ValueError("未知页面来源") + data = rebuilt.tobytes(garbage=4, deflate=True) + finally: + rebuilt.close() + for source_doc in external_docs.values(): + source_doc.close() + self._replace_with_bytes(data) + def save(self) -> None: if not self.path: raise RuntimeError("没有原始文件路径") diff --git a/pdfreaderlite/ui/main_window.py b/pdfreaderlite/ui/main_window.py index 991f021..e62f309 100644 --- a/pdfreaderlite/ui/main_window.py +++ b/pdfreaderlite/ui/main_window.py @@ -1,12 +1,15 @@ 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, @@ -16,12 +19,15 @@ from PySide6.QtGui import ( QImage, QIntValidator, QKeySequence, + QCursor, QPainter, QPen, QPixmap, ) from PySide6.QtPrintSupport import QPrintDialog, QPrinter from PySide6.QtWidgets import ( + QAbstractItemView, + QApplication, QCheckBox, QColorDialog, QComboBox, @@ -47,8 +53,10 @@ from PySide6.QtWidgets import ( QStatusBar, QStyle, QTabWidget, + QTextEdit, QToolBar, QToolButton, + QToolTip, QVBoxLayout, QWidget, ) @@ -106,6 +114,9 @@ class MainWindow(QMainWindow): 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() @@ -114,6 +125,7 @@ class MainWindow(QMainWindow): 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("应用属性") @@ -123,9 +135,12 @@ class MainWindow(QMainWindow): 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 @@ -138,6 +153,7 @@ class MainWindow(QMainWindow): self._connect_signals() self._apply_theme() self._restore_window_state() + self.hand_action.setChecked(True) self._update_title() self._update_status() @@ -203,15 +219,23 @@ class MainWindow(QMainWindow): 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 @@ -422,6 +446,7 @@ class MainWindow(QMainWindow): 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() @@ -439,6 +464,7 @@ class MainWindow(QMainWindow): 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() @@ -590,9 +616,11 @@ class MainWindow(QMainWindow): def rotate_page(self) -> None: if not self._ensure_document(): return + page_index = self.viewer.page_index self._flush_session_raster_objects() - self.document.rotate_page(self.viewer.page_index) - self._refresh_document_view() + 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: @@ -610,9 +638,9 @@ class MainWindow(QMainWindow): 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.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) - self._refresh_document_view() + self._refresh_document_view(target_page) self.statusBar().showMessage("页面已删除,记得保存", 3000) def move_page_dialog(self) -> None: @@ -643,8 +671,7 @@ class MainWindow(QMainWindow): return self._flush_session_raster_objects() self.document.move_page(source_page - 1, target_page - 1) - self.viewer.go_to_page(target_page - 1) - self._refresh_document_view() + self._refresh_document_view(target_page - 1) self.statusBar().showMessage("页面已移动,记得保存", 3000) def open_page_manager(self) -> None: @@ -658,10 +685,26 @@ class MainWindow(QMainWindow): return try: self._flush_session_raster_objects() - self.document.reorder_pages(dialog.page_order()) - self.viewer.page_index = 0 - self._refresh_document_view() - self.statusBar().showMessage("页面顺序已更新,记得保存", 3000) + 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}") @@ -669,8 +712,7 @@ class MainWindow(QMainWindow): if not self._ensure_document(): return if self.document.undo(): - self.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) - self._refresh_document_view() + self._refresh_document_view(min(self.viewer.page_index, self.document.page_count - 1)) self.statusBar().showMessage("已撤销", 3000) else: self.statusBar().showMessage("没有可撤销的操作", 3000) @@ -679,8 +721,7 @@ class MainWindow(QMainWindow): if not self._ensure_document(): return if self.document.redo(): - self.viewer.page_index = min(self.viewer.page_index, self.document.page_count - 1) - self._refresh_document_view() + self._refresh_document_view(min(self.viewer.page_index, self.document.page_count - 1)) self.statusBar().showMessage("已重做", 3000) else: self.statusBar().showMessage("没有可重做的操作", 3000) @@ -690,8 +731,7 @@ class MainWindow(QMainWindow): return self._flush_session_raster_objects() new_index = self.document.insert_blank_page(self.viewer.page_index) - self.viewer.go_to_page(new_index) - self._refresh_document_view() + self._refresh_document_view(new_index) self.statusBar().showMessage("已插入空白页,记得保存", 3000) def insert_pdf(self) -> None: @@ -704,8 +744,9 @@ class MainWindow(QMainWindow): 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() + self._refresh_document_view(insert_after + 1) self.statusBar().showMessage(f"已插入 {count} 页,记得保存", 3000) except Exception as exc: QMessageBox.critical(self, "插入失败", f"无法插入 PDF:\n{exc}") @@ -892,7 +933,7 @@ class MainWindow(QMainWindow): return selected_field: FormField = field_combo.currentData() if self.document.update_form_field(selected_field.name, value_edit.text()): - self.viewer.render() + self._render_at_page(self.viewer.page_index) self.statusBar().showMessage("表单字段已更新,记得保存", 3000) else: QMessageBox.warning(self, "填写失败", "没有找到对应的表单字段。") @@ -942,7 +983,7 @@ class MainWindow(QMainWindow): ) if reply == QMessageBox.StandardButton.Yes: self.document.delete_annotation(annotation.page_index, annotation.xref) - self.viewer.render() + self._render_at_page(self.viewer.page_index) self.statusBar().showMessage("注释已删除,记得保存", 3000) self._refresh_annotation_panel() deleted["value"] = True @@ -977,6 +1018,7 @@ class MainWindow(QMainWindow): 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 @@ -997,6 +1039,7 @@ class MainWindow(QMainWindow): 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") @@ -1016,6 +1059,9 @@ class MainWindow(QMainWindow): 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( """ @@ -1045,6 +1091,12 @@ class MainWindow(QMainWindow): 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)) @@ -1091,6 +1143,8 @@ class MainWindow(QMainWindow): 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) @@ -1112,13 +1166,20 @@ class MainWindow(QMainWindow): 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.place_text_action = QAction("添加文本", self) self.text_style_action = QAction("文本样式", self) - self.insert_image_action = QAction("插入图片", self) - self.place_image_action = QAction("点击放置图片", self) + self.place_image_action = QAction("插入图片", self) self.signature_action = QAction("图片签名", self) self.place_signature_action = QAction("点击放置签名", self) self.draw_signature_action = QAction("手写签名", self) @@ -1141,6 +1202,20 @@ class MainWindow(QMainWindow): 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("文件") @@ -1212,7 +1287,6 @@ class MainWindow(QMainWindow): 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.insert_image_action) edit_menu.addAction(self.place_image_action) edit_menu.addAction(self.signature_action) edit_menu.addAction(self.place_signature_action) @@ -1254,6 +1328,8 @@ class MainWindow(QMainWindow): 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, @@ -1273,6 +1349,7 @@ class MainWindow(QMainWindow): 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, @@ -1282,11 +1359,18 @@ class MainWindow(QMainWindow): 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.insert_image_action: QStyle.StandardPixmap.SP_FileIcon, self.place_image_action: QStyle.StandardPixmap.SP_FileIcon, self.signature_action: QStyle.StandardPixmap.SP_DialogApplyButton, self.place_signature_action: QStyle.StandardPixmap.SP_DialogApplyButton, @@ -1314,22 +1398,24 @@ class MainWindow(QMainWindow): self.right_tools.add_section( "编辑 PDF", [ - self.add_text_action, self.place_text_action, self.text_style_action, - self.insert_image_action, self.place_image_action, self.cover_action, - self.copy_object_action, - self.paste_object_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.undo_action, - self.redo_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", ) @@ -1348,7 +1434,6 @@ class MainWindow(QMainWindow): self.annotation_style_action, self.text_stamp_action, self.image_stamp_action, - self.select_object_action, self.freehand_action, self.rectangle_action, self.circle_action, @@ -1361,7 +1446,13 @@ class MainWindow(QMainWindow): "注释列表", self.right_annotation_list, "annotation_list", - controls=[self.annotation_filter_combo, self.annotation_search_box], + 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( @@ -1432,6 +1523,10 @@ class MainWindow(QMainWindow): 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) @@ -1445,6 +1540,7 @@ class MainWindow(QMainWindow): 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) @@ -1472,8 +1568,11 @@ class MainWindow(QMainWindow): 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) @@ -1564,6 +1663,8 @@ class MainWindow(QMainWindow): 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) @@ -1592,6 +1693,7 @@ class MainWindow(QMainWindow): 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) @@ -1608,11 +1710,18 @@ class MainWindow(QMainWindow): 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.insert_image_action.triggered.connect(self.insert_image) self.place_image_action.triggered.connect(self.prepare_place_image) self.signature_action.triggered.connect(self.add_signature) self.place_signature_action.triggered.connect(self.prepare_place_signature) @@ -1635,6 +1744,9 @@ class MainWindow(QMainWindow): 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) @@ -1642,10 +1754,13 @@ class MainWindow(QMainWindow): 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: @@ -1700,7 +1815,7 @@ class MainWindow(QMainWindow): content=text, rect=annotation.rect, ) - self.viewer.render() + self._render_at_page(annotation.page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("注释内容已更新,记得保存", 3000) @@ -1723,7 +1838,7 @@ class MainWindow(QMainWindow): if self.selected_annotation and self.selected_annotation.xref == annotation.xref: self.selected_annotation = None self.viewer.clear_object_selection() - self.viewer.render() + self._render_at_page(annotation.page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("注释已删除,记得保存", 3000) @@ -1783,8 +1898,17 @@ class MainWindow(QMainWindow): 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 = QListWidgetItem("没有符合条件的注释") item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.right_annotation_list.addItem(item) self._refresh_page_object_list() @@ -1799,6 +1923,64 @@ class MainWindow(QMainWindow): 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 @@ -1838,6 +2020,9 @@ class MainWindow(QMainWindow): 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 @@ -1850,6 +2035,7 @@ class MainWindow(QMainWindow): 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 @@ -1857,17 +2043,466 @@ class MainWindow(QMainWindow): 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._start_area_markup("highlight", "拖拽框选要高亮的区域") + self._apply_or_prepare_text_markup("highlight") def underline_current_page(self) -> None: - self._start_area_markup("underline", "拖拽框选要添加下划线的区域") + self._apply_or_prepare_text_markup("underline") def strikeout_current_page(self) -> None: - self._start_area_markup("strikeout", "拖拽框选要添加删除线的区域") + 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(): @@ -1876,8 +2511,13 @@ class MainWindow(QMainWindow): 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) @@ -1886,6 +2526,7 @@ class MainWindow(QMainWindow): 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() @@ -1897,8 +2538,9 @@ class MainWindow(QMainWindow): annotation = self.document.add_area_line_mark(page_index, rect, True, color, line_width, opacity) else: return - self.viewer.render() + 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}") @@ -1911,8 +2553,9 @@ class MainWindow(QMainWindow): text, ok = QInputDialog.getMultiLineText(self, "批注", "批注内容:") if not ok or not text.strip(): return - annotation = self.document.add_note(self.viewer.page_index, text) - self.viewer.render() + 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) @@ -1926,8 +2569,9 @@ class MainWindow(QMainWindow): if not ok or not text.strip(): return try: - annotation = self.document.add_text_stamp(self.viewer.page_index, text.strip()) - self.viewer.render() + 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: @@ -2032,6 +2676,7 @@ class MainWindow(QMainWindow): 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, @@ -2043,10 +2688,14 @@ class MainWindow(QMainWindow): 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: @@ -2054,19 +2703,28 @@ class MainWindow(QMainWindow): return color = self.annotation_property_color try: - 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 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.viewer.render() + self._render_at_page(updated.page_index) self.viewer.set_selected_object_rect(updated.rect) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() @@ -2139,12 +2797,17 @@ class MainWindow(QMainWindow): 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: @@ -2160,6 +2823,7 @@ class MainWindow(QMainWindow): 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) @@ -2167,18 +2831,58 @@ class MainWindow(QMainWindow): 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 _select_annotation_object(self, annotation: AnnotationInfo) -> None: + 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.go_to_page(annotation.page_index) + 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() @@ -2196,22 +2900,187 @@ class MainWindow(QMainWindow): if not self.selected_annotation or self.selected_annotation.page_index != page_index: return try: - if self.document.update_annotation_rect(page_index, self.selected_annotation.xref, rect): - updated_rect = self.document.annotation_rect(page_index, self.selected_annotation.xref) + 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=self.selected_annotation.xref, - annotation_type=self.selected_annotation.annotation_type, - content=self.selected_annotation.content, - rect=updated_rect, + xref=updated.xref, + annotation_type=updated.annotation_type, + content=updated.content, + rect=updated.rect, ) - self.viewer.render() - self.viewer.set_selected_object_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.viewer.render() + 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() @@ -2308,7 +3177,7 @@ class MainWindow(QMainWindow): if not annotation: self.statusBar().showMessage("该注释暂不支持复制粘贴", 3000) return - self.viewer.render() + self._render_at_page(annotation.page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("注释对象已粘贴,记得保存", 3000) @@ -2345,7 +3214,7 @@ class MainWindow(QMainWindow): rotation_input = QComboBox() for value in [0, 90, 180, 270]: - rotation_input.addItem(f"{value}°", value) + rotation_input.addItem(f"{value}掳", value) rotation_index = rotation_input.findData(int(raster.get("rotation", 0)) % 360) rotation_input.setCurrentIndex(max(0, rotation_index)) @@ -2433,6 +3302,7 @@ class MainWindow(QMainWindow): 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) @@ -2442,9 +3312,11 @@ class MainWindow(QMainWindow): 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.viewer.render() + self._render_at_page(page_index) self._refresh_annotation_panel() self._refresh_annotation_properties_panel() self.statusBar().showMessage("对象已删除,记得保存", 3000) @@ -2465,49 +3337,68 @@ class MainWindow(QMainWindow): 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) - delete_action = menu.addAction("删除对象") - copy_action = menu.addAction("复制对象") + 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("粘贴对象") - 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("下移一层") - edit_action = menu.addAction("编辑内容") - properties_action = menu.addAction("属性") - delete_action.setEnabled(self.selected_annotation is not None or self.selected_raster_id is not None) - copy_action.setEnabled(self.selected_annotation is not None or self.selected_raster_id is not None) paste_action.setEnabled(self._has_copied_object()) - replace_action.setEnabled(self.selected_raster_id is not None) - image_properties_action.setEnabled(self.selected_raster_id is not None) - layer_menu.setEnabled(self.selected_raster_id is not None) - edit_action.setEnabled(self._selected_annotation_content_editable()) - properties_action.setEnabled(self.selected_annotation is not None or self.selected_raster_id is not None) + 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 chosen == delete_action: + if delete_action is not None and chosen == delete_action: self.delete_selected_object() - elif chosen == copy_action: + elif copy_action is not None and chosen == copy_action: self.copy_selected_object() elif chosen == paste_action: self.paste_copied_object() - elif chosen == replace_action: + elif replace_action is not None and chosen == replace_action: self.replace_selected_image() - elif chosen == image_properties_action: + elif image_properties_action is not None and chosen == image_properties_action: self.edit_selected_image_properties() - elif chosen == front_action: + elif front_action is not None and chosen == front_action: self.reorder_selected_raster("front") - elif chosen == back_action: + elif back_action is not None and chosen == back_action: self.reorder_selected_raster("back") - elif chosen == forward_action: + elif forward_action is not None and chosen == forward_action: self.reorder_selected_raster("forward") - elif chosen == backward_action: + elif backward_action is not None and chosen == backward_action: self.reorder_selected_raster("backward") - elif chosen == edit_action and self.selected_annotation: + elif edit_action is not None and chosen == edit_action and self.selected_annotation: self.edit_annotation_from_panel(self.selected_annotation) - elif chosen == properties_action: + 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: @@ -2522,6 +3413,22 @@ class MainWindow(QMainWindow): 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 @@ -2561,22 +3468,30 @@ class MainWindow(QMainWindow): 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() - if not (had_pending or had_area or had_selection or had_tool): + 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 @@ -2633,9 +3548,13 @@ class MainWindow(QMainWindow): 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) @@ -2646,7 +3565,7 @@ class MainWindow(QMainWindow): try: color, line_width, opacity = self._annotation_style() annotation = self.document.add_ink(page_index, points, color, line_width, opacity) - self.viewer.render() + self._render_at_page(page_index) if annotation: self._select_annotation_object(annotation) else: @@ -2667,13 +3586,14 @@ class MainWindow(QMainWindow): return try: font_size, text_color = self._text_style() + page_index = self.viewer.page_index annotation = self.document.add_text( - self.viewer.page_index, + page_index, text, font_size=font_size, text_color=text_color, ) - self.viewer.render() + self._render_at_page(page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("文本已添加,记得保存", 3000) except Exception as exc: @@ -2692,14 +3612,14 @@ class MainWindow(QMainWindow): def prepare_place_image(self) -> None: if not self._ensure_document(): return - if not self._ensure_can_edit("点击放置图片"): + if not self._ensure_can_edit("插入图片"): return selected, _ = QFileDialog.getOpenFileName( - self, "点击放置图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)" + self, "插入图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)" ) if not selected: return - self._start_placement({"type": "image", "path": selected}, "点击页面位置放置图片") + self._start_placement({"type": "image", "path": selected}, "点击页面位置插入图片") def prepare_place_signature(self) -> None: if not self._ensure_document(): @@ -2740,10 +3660,25 @@ class MainWindow(QMainWindow): } self.next_raster_id += 1 self.session_raster_objects.append(item) - self.selected_raster_id = int(item["id"]) + 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_selected_object_rect(rect) + 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: @@ -2845,9 +3780,13 @@ class MainWindow(QMainWindow): 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) @@ -2859,6 +3798,7 @@ class MainWindow(QMainWindow): 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( @@ -2870,19 +3810,25 @@ class MainWindow(QMainWindow): ) 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("未知的放置类型") - self.viewer.render() if annotation: + self._render_at_page(page_index) self._select_annotation_object(annotation) - self._refresh_session_raster_overlays() + 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}") @@ -2942,48 +3888,75 @@ class MainWindow(QMainWindow): QMessageBox.critical(self, "签名失败", f"无法添加手写签名:\n{exc}") def add_rectangle(self) -> None: - if not self._ensure_document(): - return - if not self._ensure_can_edit("矩形"): - return - color, line_width, opacity = self._annotation_style() - annotation = self.document.add_rectangle(self.viewer.page_index, color, line_width, opacity) - self.viewer.render() - self._select_annotation_object(annotation) - self.statusBar().showMessage("矩形已添加,记得保存", 3000) + self._start_shape_placement("rectangle", "矩形:点击第一个角点,再点击第二个角点完成") def add_circle(self) -> None: - if not self._ensure_document(): - return - if not self._ensure_can_edit("圆形"): - return - color, line_width, opacity = self._annotation_style() - annotation = self.document.add_circle(self.viewer.page_index, color, line_width, opacity) - self.viewer.render() - self._select_annotation_object(annotation) - self.statusBar().showMessage("圆形已添加,记得保存", 3000) + self._start_shape_placement("circle", "圆形:点击外接框第一个角点,再点击第二个角点完成") def add_line(self) -> None: - if not self._ensure_document(): - return - if not self._ensure_can_edit("线条"): - return - color, line_width, opacity = self._annotation_style() - annotation = self.document.add_line(self.viewer.page_index, False, color, line_width, opacity) - self.viewer.render() - self._select_annotation_object(annotation) - self.statusBar().showMessage("线条已添加,记得保存", 3000) + 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("箭头"): + 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() - annotation = self.document.add_line(self.viewer.page_index, True, color, line_width, opacity) - self.viewer.render() - self._select_annotation_object(annotation) - self.statusBar().showMessage("箭头已添加,记得保存", 3000) + 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(): @@ -3041,13 +4014,14 @@ class MainWindow(QMainWindow): 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( - self.viewer.page_index, + page_index, (self.cover_color.redF(), self.cover_color.greenF(), self.cover_color.blueF()), self.cover_opacity, text_input.text(), ) - self.viewer.render() + self._render_at_page(page_index) self._select_annotation_object(annotation) self.statusBar().showMessage("遮盖区域已添加,记得保存", 3000) except Exception as exc: @@ -3096,19 +4070,45 @@ class MainWindow(QMainWindow): 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) -> None: + 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(","): @@ -3244,11 +4244,15 @@ class MainWindow(QMainWindow): 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) diff --git a/pdfreaderlite/ui/page_manager.py b/pdfreaderlite/ui/page_manager.py index ccfb75b..84bb518 100644 --- a/pdfreaderlite/ui/page_manager.py +++ b/pdfreaderlite/ui/page_manager.py @@ -1,14 +1,21 @@ from __future__ import annotations -from PySide6.QtCore import QSize, Qt -from PySide6.QtGui import QDragEnterEvent, QDropEvent, QIcon, QPixmap +from pathlib import Path + +import fitz +from PySide6.QtCore import QSize, Qt, Signal +from PySide6.QtGui import QDragEnterEvent, QDropEvent, QIcon, QImage, QPixmap from PySide6.QtWidgets import ( QAbstractItemView, QDialog, QDialogButtonBox, + QFileDialog, + QHBoxLayout, QLabel, QListWidget, QListWidgetItem, + QMessageBox, + QPushButton, QVBoxLayout, ) @@ -16,6 +23,8 @@ from pdfreaderlite.core.document import PdfDocument class PageGrid(QListWidget): + pdf_files_dropped = Signal(list, int) + def __init__(self) -> None: super().__init__() self.setViewMode(QListWidget.ViewMode.IconMode) @@ -28,32 +37,82 @@ class PageGrid(QListWidget): self.setGridSize(QSize(178, 230)) self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) self.setDefaultDropAction(Qt.DropAction.MoveAction) - self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) def dropEvent(self, event: QDropEvent) -> None: + paths = self._dropped_pdf_paths(event) + if paths: + row = self.indexAt(event.position().toPoint()).row() + self.pdf_files_dropped.emit(paths, row if row >= 0 else self.count()) + event.acceptProposedAction() + return super().dropEvent(event) self._renumber_items() def dragEnterEvent(self, event: QDragEnterEvent) -> None: + if self._dropped_pdf_paths(event): + event.acceptProposedAction() + return event.acceptProposedAction() + def dragMoveEvent(self, event) -> None: + if self._dropped_pdf_paths(event): + event.acceptProposedAction() + return + super().dragMoveEvent(event) + + def _dropped_pdf_paths(self, event: QDragEnterEvent | QDropEvent) -> list[str]: + if not event.mimeData().hasUrls(): + return [] + paths: list[str] = [] + for url in event.mimeData().urls(): + if not url.isLocalFile(): + continue + path = Path(url.toLocalFile()) + if path.suffix.lower() == ".pdf": + paths.append(str(path)) + return paths + def _renumber_items(self) -> None: for row in range(self.count()): item = self.item(row) - original_page = item.data(Qt.ItemDataRole.UserRole) + 1 - item.setText(f"位置 {row + 1}\n原第 {original_page} 页") + entry = item.data(Qt.ItemDataRole.UserRole) + if isinstance(entry, dict) and entry.get("source") == "external": + item.setText( + f"位置 {row + 1}\n插入 {Path(str(entry['path'])).name}\n第 {int(entry['page_index']) + 1} 页" + ) + else: + original_page = int(entry) + 1 + item.setText(f"位置 {row + 1}\n原第 {original_page} 页") class PageManagerDialog(QDialog): def __init__(self, document: PdfDocument, parent=None) -> None: super().__init__(parent) self.document = document + self.rotations: dict[int, int] = {} self.setWindowTitle("页面管理") self.resize(920, 680) self.grid = PageGrid() - hint = QLabel("拖拽缩略图调整页面顺序,点击“应用”后写入当前 PDF。") + self.grid.pdf_files_dropped.connect(self.insert_external_pdfs) + hint = QLabel("拖拽缩略图调整页面顺序,可多选后批量删除、旋转或提取,点击“应用”后写入当前 PDF。") hint.setWordWrap(True) + delete_button = QPushButton("删除所选") + rotate_left_button = QPushButton("左旋所选") + rotate_right_button = QPushButton("右旋所选") + extract_button = QPushButton("提取所选") + delete_button.clicked.connect(self.delete_selected_pages) + rotate_left_button.clicked.connect(lambda: self.rotate_selected_pages(-90)) + rotate_right_button.clicked.connect(lambda: self.rotate_selected_pages(90)) + extract_button.clicked.connect(self.extract_selected_pages) + + action_layout = QHBoxLayout() + action_layout.addWidget(delete_button) + action_layout.addWidget(rotate_left_button) + action_layout.addWidget(rotate_right_button) + action_layout.addWidget(extract_button) + action_layout.addStretch(1) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Apply | QDialogButtonBox.StandardButton.Cancel @@ -64,6 +123,7 @@ class PageManagerDialog(QDialog): layout = QVBoxLayout(self) layout.addWidget(hint) + layout.addLayout(action_layout) layout.addWidget(self.grid, 1) layout.addWidget(buttons) @@ -73,8 +133,98 @@ class PageManagerDialog(QDialog): return [ self.grid.item(row).data(Qt.ItemDataRole.UserRole) for row in range(self.grid.count()) + if isinstance(self.grid.item(row).data(Qt.ItemDataRole.UserRole), int) ] + def page_plan(self) -> list[dict[str, object]]: + plan: list[dict[str, object]] = [] + for row in range(self.grid.count()): + entry = self.grid.item(row).data(Qt.ItemDataRole.UserRole) + if isinstance(entry, dict): + plan.append(entry) + else: + plan.append({"source": "current", "page_index": int(entry)}) + return plan + + def selected_pages(self) -> list[int]: + pages = [ + item.data(Qt.ItemDataRole.UserRole) + for item in self.grid.selectedItems() + if isinstance(item.data(Qt.ItemDataRole.UserRole), int) + ] + return sorted(set(pages)) + + def delete_selected_pages(self) -> None: + selected_items = self.grid.selectedItems() + if not selected_items: + return + if self.grid.count() - len(selected_items) <= 0: + QMessageBox.information(self, "删除页面", "PDF 至少需要保留一页。") + return + reply = QMessageBox.question( + self, + "删除页面", + f"确定从当前页面管理列表中删除 {len(selected_items)} 页吗?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + ) + if reply != QMessageBox.StandardButton.Yes: + return + for item in selected_items: + self.grid.takeItem(self.grid.row(item)) + self.grid._renumber_items() + + def insert_external_pdfs(self, paths: list[str], insert_row: int) -> None: + row = max(0, min(insert_row, self.grid.count())) + inserted = 0 + for path in paths: + try: + with fitz.open(path) as source: + for page_index in range(source.page_count): + item = self._external_page_item(path, source, page_index) + self.grid.insertItem(row + inserted, item) + inserted += 1 + except Exception as exc: + QMessageBox.warning(self, "插入 PDF", f"无法读取外部 PDF:\n{path}\n\n{exc}") + if inserted: + self.grid._renumber_items() + + def rotate_selected_pages(self, degrees: int) -> None: + pages = self.selected_pages() + if not pages: + return + for page_index in pages: + self.rotations[page_index] = (self.rotations.get(page_index, 0) + degrees) % 360 + self._renumber_with_rotation() + + def extract_selected_pages(self) -> None: + pages = self.selected_pages() + if not pages: + return + target, _ = QFileDialog.getSaveFileName( + self, + "提取所选页面", + "PDFReaderLite_提取页面.pdf", + "PDF 文件 (*.pdf)", + ) + if not target: + return + try: + self.document.extract_pages([page + 1 for page in pages], target) + QMessageBox.information(self, "提取页面", "所选页面已提取为新 PDF。") + except Exception as exc: + QMessageBox.critical(self, "提取失败", f"无法提取所选页面:\n{exc}") + + def _renumber_with_rotation(self) -> None: + self.grid._renumber_items() + for row in range(self.grid.count()): + item = self.grid.item(row) + original_page = item.data(Qt.ItemDataRole.UserRole) + if not isinstance(original_page, int): + continue + rotation = self.rotations.get(original_page, 0) + if rotation: + item.setText(f"{item.text()}\n旋转 {rotation}°") + def _load_pages(self) -> None: for page_index in range(self.document.page_count): image = self.document.render_thumbnail(page_index, width=150) @@ -85,3 +235,25 @@ class PageManagerDialog(QDialog): item.setData(Qt.ItemDataRole.UserRole, page_index) item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) self.grid.addItem(item) + + def _external_page_item(self, path: str, source: fitz.Document, page_index: int) -> QListWidgetItem: + page = source.load_page(page_index) + zoom = 150 / page.rect.width + pixmap = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False) + image = QImage( + pixmap.samples, + pixmap.width, + pixmap.height, + pixmap.stride, + QImage.Format.Format_RGB888, + ).copy() + item = QListWidgetItem( + QIcon(QPixmap.fromImage(image)), + f"插入 {Path(path).name}\n第 {page_index + 1} 页", + ) + item.setData( + Qt.ItemDataRole.UserRole, + {"source": "external", "path": path, "page_index": page_index}, + ) + item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + return item diff --git a/pdfreaderlite/ui/pdf_viewer.py b/pdfreaderlite/ui/pdf_viewer.py index 3c61dbc..d06c59e 100644 --- a/pdfreaderlite/ui/pdf_viewer.py +++ b/pdfreaderlite/ui/pdf_viewer.py @@ -1,6 +1,6 @@ from __future__ import annotations -from PySide6.QtCore import QPoint, QPointF, QRectF, Qt, Signal +from PySide6.QtCore import QPoint, QPointF, QRectF, Qt, QTimer, Signal from PySide6.QtGui import QColor, QContextMenuEvent, QMouseEvent, QPainter, QPen, QPixmap, QWheelEvent from PySide6.QtWidgets import QGraphicsDropShadowEffect, QLabel, QScrollArea, QSizePolicy, QVBoxLayout, QWidget @@ -10,31 +10,57 @@ from pdfreaderlite.core.document import PdfDocument class PageLabel(QLabel): stroke_finished = Signal(list) placement_requested = Signal(QPointF) + hand_pan_delta = Signal(QPointF) area_selection_finished = Signal(QRectF) + text_selection_preview_changed = Signal(QRectF, QPointF, QPointF) + text_selection_finished = Signal(QRectF, QPointF, QPointF) + text_selection_click_requested = Signal(QPointF) + text_selection_context_requested = Signal(QPointF) + shape_placement_finished = Signal(str, QPointF, QPointF) object_select_requested = Signal(QPointF) object_rect_changed = Signal(QRectF) object_context_requested = Signal(QPointF) object_double_clicked = Signal(QPointF) + annotation_double_clicked = Signal(QPointF) + annotation_hover_requested = Signal(QPointF) def __init__(self, text: str = "") -> None: super().__init__(text) self.drawing_enabled = False self.placement_enabled = False self.area_selection_enabled = False + self.text_selection_enabled = False + self.shape_placement_enabled = False + self.shape_placement_kind = "" + self.hand_pan_enabled = False self.object_edit_enabled = False self.selected_rect: QRectF | None = None + self.selected_rects: list[QRectF] = [] self.overlay_images: list[dict[str, object]] = [] + self.search_highlights: list[tuple[float, float, float, float]] = [] + self.text_selection_highlights: list[tuple[float, float, float, float]] = [] self._drawing = False self._selecting_area = False + self._selecting_text = False + self._placing_shape = False + self._hand_panning = False self._stroke: list[QPointF] = [] self._area_start = QPointF() self._area_rect = QRectF() + self._shape_start = QPointF() + self._shape_end = QPointF() self._dragging_object = False self._resizing_object = False self._drag_start = QPointF() self._drag_origin_rect = QRectF() + self._hand_last_pos = QPointF() def mousePressEvent(self, event: QMouseEvent) -> None: + if self.hand_pan_enabled and event.button() == Qt.MouseButton.LeftButton: + self._hand_panning = True + self._hand_last_pos = event.position() + self.setCursor(Qt.CursorShape.ClosedHandCursor) + return if self.placement_enabled and event.button() == Qt.MouseButton.LeftButton: self.placement_requested.emit(event.position()) return @@ -44,6 +70,30 @@ class PageLabel(QLabel): self._area_rect = QRectF(self._area_start, self._area_start) self.update() return + if self.text_selection_enabled and event.button() == Qt.MouseButton.LeftButton: + self._selecting_text = True + self._area_start = event.position() + self._area_rect = QRectF(self._area_start, self._area_start) + self.text_selection_preview_changed.emit(self._area_rect, self._area_start, event.position()) + self.update() + return + if self.shape_placement_enabled and event.button() == Qt.MouseButton.LeftButton: + if not self._placing_shape: + self._placing_shape = True + self._shape_start = event.position() + self._shape_end = event.position() + self.update() + return + self._placing_shape = False + self._shape_end = event.position() + self.update() + if (self._shape_end - self._shape_start).manhattanLength() >= 8: + self.shape_placement_finished.emit( + self.shape_placement_kind, + self._shape_start, + self._shape_end, + ) + return if self.object_edit_enabled and event.button() == Qt.MouseButton.LeftButton: if self.selected_rect and self._resize_handle_rect().contains(event.position()): self._resizing_object = True @@ -68,9 +118,17 @@ class PageLabel(QLabel): if self.object_edit_enabled and event.button() == Qt.MouseButton.LeftButton: self.object_double_clicked.emit(event.position()) return + if event.button() == Qt.MouseButton.LeftButton: + self.annotation_double_clicked.emit(event.position()) + return super().mouseDoubleClickEvent(event) def mouseMoveEvent(self, event: QMouseEvent) -> None: + if self._hand_panning: + delta = event.position() - self._hand_last_pos + self._hand_last_pos = event.position() + self.hand_pan_delta.emit(delta) + return if self._dragging_object and self.selected_rect: delta = event.position() - self._drag_start self.selected_rect = self._drag_origin_rect.translated(delta) @@ -92,9 +150,24 @@ class PageLabel(QLabel): self._area_rect = QRectF(self._area_start, event.position()).normalized() self.update() return + if self._selecting_text: + self._area_rect = QRectF(self._area_start, event.position()).normalized() + self.text_selection_preview_changed.emit(self._area_rect, self._area_start, event.position()) + self.update() + return + if self._placing_shape: + self._shape_end = event.position() + self.update() + return + self.annotation_hover_requested.emit(event.position()) super().mouseMoveEvent(event) def mouseReleaseEvent(self, event: QMouseEvent) -> None: + if self._hand_panning and event.button() == Qt.MouseButton.LeftButton: + self._hand_panning = False + if self.hand_pan_enabled: + self.setCursor(Qt.CursorShape.OpenHandCursor) + return if self._dragging_object and event.button() == Qt.MouseButton.LeftButton: self._dragging_object = False if self.selected_rect: @@ -120,9 +193,22 @@ class PageLabel(QLabel): if rect.width() >= 8 and rect.height() >= 8: self.area_selection_finished.emit(rect) return + if self._selecting_text and event.button() == Qt.MouseButton.LeftButton: + self._selecting_text = False + rect = self._area_rect.normalized() + self._area_rect = QRectF() + self.update() + if rect.width() >= 8 and rect.height() >= 8: + self.text_selection_finished.emit(rect, self._area_start, event.position()) + else: + self.text_selection_click_requested.emit(event.position()) + return super().mouseReleaseEvent(event) def contextMenuEvent(self, event: QContextMenuEvent) -> None: + if self.text_selection_enabled: + self.text_selection_context_requested.emit(QPointF(event.pos())) + return if self.object_edit_enabled: self.object_context_requested.emit(QPointF(event.pos())) return @@ -151,14 +237,35 @@ class PageLabel(QLabel): painter.setPen(QPen(Qt.GlobalColor.blue, 2, Qt.PenStyle.DashLine)) painter.drawRect(self.selected_rect) painter.fillRect(self._resize_handle_rect(), Qt.GlobalColor.blue) + for rect in self.selected_rects: + painter.setPen(QPen(QColor("#1f6fd1"), 2, Qt.PenStyle.DashLine)) + painter.drawRect(rect) + for x0, y0, x1, y1 in self.search_highlights: + highlight_rect = QRectF(x0, y0, x1 - x0, y1 - y0) + painter.setPen(QPen(QColor("#d18b00"), 1, Qt.PenStyle.SolidLine)) + painter.fillRect(highlight_rect, QColor(255, 214, 72, 95)) + painter.drawRect(highlight_rect) + for x0, y0, x1, y1 in self.text_selection_highlights: + selection_rect = QRectF(x0, y0, x1 - x0, y1 - y0) + painter.setPen(Qt.PenStyle.NoPen) + painter.fillRect(selection_rect, QColor(43, 120, 215, 118)) if self._stroke: painter.setPen(QPen(Qt.GlobalColor.black, 2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)) for index in range(1, len(self._stroke)): painter.drawLine(self._stroke[index - 1], self._stroke[index]) - if not self._area_rect.isNull(): + if not self._area_rect.isNull() and not self._selecting_text: painter.setPen(QPen(QColor("#2d73c5"), 2, Qt.PenStyle.DashLine)) painter.fillRect(self._area_rect, QColor(45, 115, 197, 38)) painter.drawRect(self._area_rect) + if self._placing_shape: + painter.setPen(QPen(QColor("#2d73c5"), 2, Qt.PenStyle.DashLine)) + rect = QRectF(self._shape_start, self._shape_end).normalized() + if self.shape_placement_kind == "circle": + painter.drawEllipse(rect) + elif self.shape_placement_kind in {"line", "arrow"}: + painter.drawLine(self._shape_start, self._shape_end) + else: + painter.drawRect(rect) def _resize_handle_rect(self) -> QRectF: if not self.selected_rect: @@ -205,10 +312,17 @@ class PdfViewer(QScrollArea): ink_stroke_finished = Signal(int, list) placement_requested = Signal(int, tuple) area_selection_finished = Signal(int, tuple) + text_selection_preview_changed = Signal(int, tuple, tuple, tuple) + text_selection_finished = Signal(int, tuple, tuple, tuple) + text_selection_click_requested = Signal(int, tuple) + text_selection_context_requested = Signal(int, tuple) + shape_placement_finished = Signal(int, str, tuple, tuple) object_select_requested = Signal(int, tuple) object_rect_changed = Signal(int, tuple) object_context_requested = Signal(int, tuple) object_double_clicked = Signal(int, tuple) + annotation_double_clicked = Signal(int, tuple) + annotation_hover_requested = Signal(int, tuple) def __init__(self) -> None: super().__init__() @@ -217,7 +331,10 @@ class PdfViewer(QScrollArea): self.zoom = 1.2 self._page_labels: list[PageLabel] = [] self._overlay_images: list[dict[str, object]] = [] + self._search_highlights: dict[int, list[tuple[float, float, float, float]]] = {} + self._text_selection_highlights: dict[int, list[tuple[float, float, float, float]]] = {} self._selected_object_rect: tuple[float, float, float, float] | None = None + self._selected_object_rects: list[tuple[float, float, float, float]] = [] self._selected_object_page_index: int | None = None self._updating_scroll_page = False @@ -242,7 +359,7 @@ class PdfViewer(QScrollArea): self.page_index = 0 self.render() - def render(self) -> None: + def render(self, scroll_to_page: bool = True) -> None: if not self.document or not self.document.is_open: self._clear_page_labels() self.page_label = self._make_empty_label() @@ -250,6 +367,7 @@ class PdfViewer(QScrollArea): return previous_page = min(self.page_index, self.document.page_count - 1) + self._updating_scroll_page = True self._clear_page_labels() for page_index in range(self.document.page_count): label = self._make_page_label(page_index) @@ -264,11 +382,51 @@ class PdfViewer(QScrollArea): self.content_layout.activate() self.content_widget.adjustSize() self._refresh_overlay_zoom() + self._refresh_search_highlights() + self._refresh_text_selection_highlights() self._apply_object_selection_to_labels() - self._scroll_to_page(self.page_index) + if scroll_to_page: + self._scroll_to_page(self.page_index) + else: + QTimer.singleShot(0, self._finish_programmatic_scroll) self.page_changed.emit(self.page_index) self.zoom_changed.emit(self.zoom) + def render_preserving_scroll(self, page_index: int, scroll_value: int) -> None: + if self.document and 0 <= page_index < self.document.page_count: + self.page_index = page_index + self.render() + self._updating_scroll_page = True + bar = self.verticalScrollBar() + bar.setValue(max(bar.minimum(), min(bar.maximum(), scroll_value))) + if self._page_labels and 0 <= self.page_index < len(self._page_labels): + self.page_label = self._page_labels[self.page_index] + QTimer.singleShot(0, self._finish_programmatic_scroll) + + def refresh_page(self, page_index: int) -> None: + if ( + not self.document + or not self.document.is_open + or page_index < 0 + or page_index >= len(self._page_labels) + ): + return + self._updating_scroll_page = True + label = self._page_labels[page_index] + image = self.document.render_page(page_index, self.zoom) + label.setPixmap(QPixmap.fromImage(image)) + label.adjustSize() + self.page_index = page_index + self.page_label = label + self.content_layout.activate() + self._refresh_overlay_zoom() + self._refresh_search_highlights() + self._refresh_text_selection_highlights() + self._apply_object_selection_to_labels() + self.page_changed.emit(self.page_index) + self.zoom_changed.emit(self.zoom) + QTimer.singleShot(0, self._finish_programmatic_scroll) + def next_page(self) -> None: if self.document and self.page_index < self.document.page_count - 1: self.go_to_page(self.page_index + 1) @@ -291,8 +449,23 @@ class PdfViewer(QScrollArea): self.set_zoom(max(0.2, self.zoom - 0.15)) def set_zoom(self, zoom: float) -> None: - self.zoom = max(0.2, min(3.0, zoom)) - self.render() + new_zoom = max(0.2, min(3.0, zoom)) + if abs(new_zoom - self.zoom) < 0.001: + return + if not self.document or not self.document.is_open: + self.zoom = new_zoom + self.render() + return + + anchor = self._viewport_pdf_anchor() + if anchor is not None: + self.page_index = anchor[0] + + self.zoom = new_zoom + self.render(scroll_to_page=False) + if anchor is not None: + self._restore_pdf_anchor(anchor) + QTimer.singleShot(0, lambda saved_anchor=anchor: self._restore_pdf_anchor(saved_anchor)) def wheelEvent(self, event: QWheelEvent) -> None: if event.modifiers() & Qt.KeyboardModifier.ControlModifier: @@ -304,10 +477,57 @@ class PdfViewer(QScrollArea): return super().wheelEvent(event) + def _viewport_pdf_anchor(self) -> tuple[int, float, float] | None: + if not self._page_labels or self.zoom <= 0: + return None + viewport_center = QPoint(self.viewport().width() // 2, self.viewport().height() // 2) + content_point = self.content_widget.mapFromGlobal(self.viewport().mapToGlobal(viewport_center)) + + best_index = self.page_index + best_distance: int | None = None + for index, label in enumerate(self._page_labels): + geometry = label.geometry() + if geometry.contains(content_point): + local_x = content_point.x() - geometry.x() + local_y = content_point.y() - geometry.y() + return index, local_x / self.zoom, local_y / self.zoom + distance = abs(geometry.center().y() - content_point.y()) + if best_distance is None or distance < best_distance: + best_distance = distance + best_index = index + + if 0 <= best_index < len(self._page_labels): + geometry = self._page_labels[best_index].geometry() + local_x = min(max(content_point.x() - geometry.x(), 0), geometry.width()) + local_y = min(max(content_point.y() - geometry.y(), 0), geometry.height()) + return best_index, local_x / self.zoom, local_y / self.zoom + return None + + def _restore_pdf_anchor(self, anchor: tuple[int, float, float]) -> None: + page_index, pdf_x, pdf_y = anchor + if not (0 <= page_index < len(self._page_labels)): + self._finish_programmatic_scroll() + return + self._updating_scroll_page = True + self.page_index = page_index + self.page_label = self._page_labels[page_index] + geometry = self.page_label.geometry() + target_x = geometry.x() + pdf_x * self.zoom - self.viewport().width() / 2 + target_y = geometry.y() + pdf_y * self.zoom - self.viewport().height() / 2 + hbar = self.horizontalScrollBar() + vbar = self.verticalScrollBar() + hbar.setValue(max(hbar.minimum(), min(hbar.maximum(), int(target_x)))) + vbar.setValue(max(vbar.minimum(), min(vbar.maximum(), int(target_y)))) + self.page_changed.emit(self.page_index) + QTimer.singleShot(0, self._finish_programmatic_scroll) + def set_drawing_enabled(self, enabled: bool) -> None: if enabled: self.set_placement_enabled(False) self.set_area_selection_enabled(False) + self.set_text_selection_enabled(False) + self.set_shape_placement_enabled(False) + self.set_hand_pan_enabled(False) for label in self._labels(): label.drawing_enabled = enabled label.setCursor(Qt.CursorShape.CrossCursor if enabled else Qt.CursorShape.ArrowCursor) @@ -315,9 +535,12 @@ class PdfViewer(QScrollArea): def set_placement_enabled(self, enabled: bool) -> None: if enabled: + self.set_shape_placement_enabled(False) + self.set_hand_pan_enabled(False) for label in self._labels(): label.drawing_enabled = False label.area_selection_enabled = False + label.text_selection_enabled = False self.set_object_edit_enabled(False) for label in self._labels(): label.placement_enabled = enabled @@ -326,9 +549,12 @@ class PdfViewer(QScrollArea): def set_area_selection_enabled(self, enabled: bool) -> None: if enabled: + self.set_shape_placement_enabled(False) + self.set_hand_pan_enabled(False) for label in self._labels(): label.drawing_enabled = False label.placement_enabled = False + label.text_selection_enabled = False self.set_object_edit_enabled(False) for label in self._labels(): label.area_selection_enabled = enabled @@ -339,12 +565,69 @@ class PdfViewer(QScrollArea): label.setCursor(Qt.CursorShape.CrossCursor if enabled else Qt.CursorShape.ArrowCursor) self.viewport().setCursor(Qt.CursorShape.CrossCursor if enabled else Qt.CursorShape.ArrowCursor) - def set_object_edit_enabled(self, enabled: bool) -> None: + def set_text_selection_enabled(self, enabled: bool) -> None: + if enabled: + self.set_shape_placement_enabled(False) + self.set_hand_pan_enabled(False) + for label in self._labels(): + label.drawing_enabled = False + label.placement_enabled = False + label.area_selection_enabled = False + self.set_object_edit_enabled(False) + for label in self._labels(): + label.text_selection_enabled = enabled + if not enabled: + label._selecting_text = False + label._area_rect = QRectF() + label.update() + label.setCursor(Qt.CursorShape.IBeamCursor if enabled else Qt.CursorShape.ArrowCursor) + self.viewport().setCursor(Qt.CursorShape.IBeamCursor if enabled else Qt.CursorShape.ArrowCursor) + + def set_shape_placement_enabled(self, enabled: bool, kind: str = "") -> None: + if enabled: + self.set_hand_pan_enabled(False) + for label in self._labels(): + label.drawing_enabled = False + label.placement_enabled = False + label.area_selection_enabled = False + label.text_selection_enabled = False + self.set_object_edit_enabled(False) + for label in self._labels(): + label.shape_placement_enabled = enabled + label.shape_placement_kind = kind if enabled else "" + if not enabled: + label._placing_shape = False + label._shape_start = QPointF() + label._shape_end = QPointF() + label.update() + label.setCursor(Qt.CursorShape.CrossCursor if enabled else Qt.CursorShape.ArrowCursor) + self.viewport().setCursor(Qt.CursorShape.CrossCursor if enabled else Qt.CursorShape.ArrowCursor) + + def set_hand_pan_enabled(self, enabled: bool) -> None: if enabled: for label in self._labels(): label.drawing_enabled = False label.placement_enabled = False label.area_selection_enabled = False + label.text_selection_enabled = False + label.shape_placement_enabled = False + self.set_object_edit_enabled(False) + for label in self._labels(): + label.hand_pan_enabled = enabled + if not enabled: + label._hand_panning = False + label.setCursor(Qt.CursorShape.OpenHandCursor if enabled else Qt.CursorShape.ArrowCursor) + self.viewport().setCursor(Qt.CursorShape.OpenHandCursor if enabled else Qt.CursorShape.ArrowCursor) + + def set_object_edit_enabled(self, enabled: bool) -> None: + if enabled: + self.set_shape_placement_enabled(False) + self.set_hand_pan_enabled(False) + for label in self._labels(): + label.drawing_enabled = False + label.placement_enabled = False + label.area_selection_enabled = False + label.text_selection_enabled = False else: self.clear_object_selection() for label in self._labels(): @@ -357,30 +640,70 @@ class PdfViewer(QScrollArea): label.drawing_enabled = False label.placement_enabled = False label.area_selection_enabled = False + label.text_selection_enabled = False + label.shape_placement_enabled = False + label.shape_placement_kind = "" + label.hand_pan_enabled = False + label._hand_panning = False label.object_edit_enabled = False + label._placing_shape = False label.setCursor(Qt.CursorShape.ArrowCursor) self.viewport().setCursor(Qt.CursorShape.ArrowCursor) self.clear_object_selection() + self.clear_text_selection() def set_selected_object_rect(self, rect: tuple[float, float, float, float] | None) -> None: if not rect: self.clear_object_selection() return self._selected_object_rect = rect + self._selected_object_rects = [] self._selected_object_page_index = self.page_index self._apply_object_selection_to_labels() + def set_selected_object_rects(self, rects: list[tuple[float, float, float, float]]) -> None: + self._selected_object_rect = None + self._selected_object_rects = rects + self._selected_object_page_index = self.page_index if rects else None + self._apply_object_selection_to_labels() + def set_overlay_images(self, overlays: list[dict[str, object]]) -> None: self._overlay_images = overlays self._refresh_overlay_zoom() + def set_search_highlights( + self, + page_index: int | None, + rects: list[tuple[float, float, float, float]] | None = None, + ) -> None: + self._search_highlights.clear() + if page_index is not None and rects: + self._search_highlights[page_index] = rects + self._refresh_search_highlights() + + def set_text_selection_highlights( + self, + page_index: int | None, + rects: list[tuple[float, float, float, float]] | None = None, + ) -> None: + self._text_selection_highlights.clear() + if page_index is not None and rects: + self._text_selection_highlights[page_index] = rects + self._refresh_text_selection_highlights() + def clear_object_selection(self) -> None: self._selected_object_rect = None + self._selected_object_rects = [] self._selected_object_page_index = None for label in self._labels(): label.selected_rect = None + label.selected_rects = [] label.update() + def clear_text_selection(self) -> None: + self._text_selection_highlights.clear() + self._refresh_text_selection_highlights() + def fit_width(self) -> None: if not self.document or not self.document.is_open: return @@ -423,12 +746,25 @@ class PdfViewer(QScrollArea): def _connect_page_label(self, label: PageLabel, page_index: int) -> None: label.stroke_finished.connect(lambda stroke, index=page_index: self._emit_ink_stroke_for_page(index, stroke)) + label.hand_pan_delta.connect(self._pan_by_delta) label.placement_requested.connect(lambda point, index=page_index: self._emit_placement_for_page(index, point)) label.area_selection_finished.connect(lambda rect, index=page_index: self._emit_area_selection_for_page(index, rect)) + label.text_selection_preview_changed.connect( + lambda rect, start, end, index=page_index: self._emit_text_selection_preview_for_page(index, rect, start, end) + ) + label.text_selection_finished.connect( + lambda rect, start, end, index=page_index: self._emit_text_selection_for_page(index, rect, start, end) + ) + label.text_selection_click_requested.connect(lambda point, index=page_index: self._emit_text_selection_click_for_page(index, point)) + label.text_selection_context_requested.connect(lambda point, index=page_index: self._emit_text_selection_context_for_page(index, point)) + label.shape_placement_finished.connect(lambda kind, start, end, index=page_index: self._emit_shape_placement_for_page(index, kind, start, end)) label.object_select_requested.connect(lambda point, index=page_index: self._emit_object_select_for_page(index, point)) label.object_rect_changed.connect(lambda rect, index=page_index: self._emit_object_rect_changed_for_page(index, rect)) label.object_context_requested.connect(lambda point, index=page_index: self._emit_object_context_for_page(index, point)) label.object_double_clicked.connect(lambda point, index=page_index: self._emit_object_double_clicked_for_page(index, point)) + label.annotation_double_clicked.connect(lambda point, index=page_index: self._emit_annotation_double_clicked_for_page(index, point)) + label.annotation_hover_requested.connect(lambda point, index=page_index: self._emit_annotation_hover_for_page(index, point)) + label.setMouseTracking(True) def _labels(self) -> list[PageLabel]: return self._page_labels or [self.page_label] @@ -445,7 +781,25 @@ class PdfViewer(QScrollArea): if not self._page_labels or page_index < 0 or page_index >= len(self._page_labels): return self._updating_scroll_page = True - self.ensureWidgetVisible(self._page_labels[page_index], 0, 0) + self.page_index = page_index + self.page_label = self._page_labels[page_index] + self._apply_scroll_to_page(page_index, attempts=3) + + def _apply_scroll_to_page(self, page_index: int, attempts: int = 0) -> None: + if not self._page_labels or page_index < 0 or page_index >= len(self._page_labels): + self._finish_programmatic_scroll() + return + self.content_layout.activate() + self.content_widget.adjustSize() + target_y = self._page_labels[page_index].geometry().top() + bar = self.verticalScrollBar() + bar.setValue(max(bar.minimum(), min(bar.maximum(), target_y))) + if attempts > 0: + QTimer.singleShot(0, lambda: self._apply_scroll_to_page(page_index, attempts - 1)) + else: + QTimer.singleShot(0, self._finish_programmatic_scroll) + + def _finish_programmatic_scroll(self) -> None: self._updating_scroll_page = False def _update_current_page_from_scroll(self) -> None: @@ -474,6 +828,32 @@ class PdfViewer(QScrollArea): ] label.update() + def _refresh_search_highlights(self) -> None: + for page_index, label in enumerate(self._labels()): + label.search_highlights = [ + ( + float(x0) * self.zoom, + float(y0) * self.zoom, + float(x1) * self.zoom, + float(y1) * self.zoom, + ) + for x0, y0, x1, y1 in self._search_highlights.get(page_index, []) + ] + label.update() + + def _refresh_text_selection_highlights(self) -> None: + for page_index, label in enumerate(self._labels()): + label.text_selection_highlights = [ + ( + float(x0) * self.zoom, + float(y0) * self.zoom, + float(x1) * self.zoom, + float(y1) * self.zoom, + ) + for x0, y0, x1, y1 in self._text_selection_highlights.get(page_index, []) + ] + label.update() + def _apply_object_selection_to_labels(self) -> None: for index, label in enumerate(self._labels()): if self._selected_object_rect and self._selected_object_page_index == index: @@ -486,6 +866,18 @@ class PdfViewer(QScrollArea): ) else: label.selected_rect = None + if self._selected_object_rects and self._selected_object_page_index == index: + label.selected_rects = [ + QRectF( + x0 * self.zoom, + y0 * self.zoom, + (x1 - x0) * self.zoom, + (y1 - y0) * self.zoom, + ) + for x0, y0, x1, y1 in self._selected_object_rects + ] + else: + label.selected_rects = [] label.update() def _set_current_page_from_interaction(self, page_index: int) -> None: @@ -500,6 +892,10 @@ class PdfViewer(QScrollArea): points = [(point.x() / self.zoom, point.y() / self.zoom) for point in stroke] self.ink_stroke_finished.emit(page_index, points) + def _pan_by_delta(self, delta: QPointF) -> None: + self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - int(delta.x())) + self.verticalScrollBar().setValue(self.verticalScrollBar().value() - int(delta.y())) + def _emit_placement_for_page(self, page_index: int, point: QPointF) -> None: self._set_current_page_from_interaction(page_index) self.placement_requested.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) @@ -516,6 +912,69 @@ class PdfViewer(QScrollArea): ), ) + def _emit_text_selection_for_page( + self, + page_index: int, + rect: QRectF, + start: QPointF, + end: QPointF, + ) -> None: + self._set_current_page_from_interaction(page_index) + self.text_selection_finished.emit( + page_index, + ( + rect.left() / self.zoom, + rect.top() / self.zoom, + rect.right() / self.zoom, + rect.bottom() / self.zoom, + ), + (start.x() / self.zoom, start.y() / self.zoom), + (end.x() / self.zoom, end.y() / self.zoom), + ) + + def _emit_text_selection_preview_for_page( + self, + page_index: int, + rect: QRectF, + start: QPointF, + end: QPointF, + ) -> None: + self._set_current_page_from_interaction(page_index) + self.text_selection_preview_changed.emit( + page_index, + ( + rect.left() / self.zoom, + rect.top() / self.zoom, + rect.right() / self.zoom, + rect.bottom() / self.zoom, + ), + (start.x() / self.zoom, start.y() / self.zoom), + (end.x() / self.zoom, end.y() / self.zoom), + ) + + def _emit_text_selection_context_for_page(self, page_index: int, point: QPointF) -> None: + self._set_current_page_from_interaction(page_index) + self.text_selection_context_requested.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) + + def _emit_text_selection_click_for_page(self, page_index: int, point: QPointF) -> None: + self._set_current_page_from_interaction(page_index) + self.text_selection_click_requested.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) + + def _emit_shape_placement_for_page( + self, + page_index: int, + kind: str, + start: QPointF, + end: QPointF, + ) -> None: + self._set_current_page_from_interaction(page_index) + self.shape_placement_finished.emit( + page_index, + kind, + (start.x() / self.zoom, start.y() / self.zoom), + (end.x() / self.zoom, end.y() / self.zoom), + ) + def _emit_object_select_for_page(self, page_index: int, point: QPointF) -> None: self._set_current_page_from_interaction(page_index) self.object_select_requested.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) @@ -539,3 +998,10 @@ class PdfViewer(QScrollArea): def _emit_object_double_clicked_for_page(self, page_index: int, point: QPointF) -> None: self._set_current_page_from_interaction(page_index) self.object_double_clicked.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) + + def _emit_annotation_double_clicked_for_page(self, page_index: int, point: QPointF) -> None: + self._set_current_page_from_interaction(page_index) + self.annotation_double_clicked.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) + + def _emit_annotation_hover_for_page(self, page_index: int, point: QPointF) -> None: + self.annotation_hover_requested.emit(page_index, (point.x() / self.zoom, point.y() / self.zoom)) diff --git a/pdfreaderlite/ui/sidebar.py b/pdfreaderlite/ui/sidebar.py index 8eb7746..191fdf2 100644 --- a/pdfreaderlite/ui/sidebar.py +++ b/pdfreaderlite/ui/sidebar.py @@ -6,7 +6,7 @@ from PySide6.QtCore import QSize, Qt, QTimer, Signal from PySide6.QtGui import QPixmap from PySide6.QtWidgets import QLabel, QListWidget, QListWidgetItem, QTabWidget, QWidget, QVBoxLayout -from pdfreaderlite.core.document import PdfDocument +from pdfreaderlite.core.document import Bookmark, PdfDocument class ThumbnailItemWidget(QWidget): @@ -187,7 +187,10 @@ class Sidebar(QTabWidget): super().__init__() self.setObjectName("leftSidebar") self.thumbnails = ThumbnailList() + self.bookmarks = QListWidget() + self.bookmarks.setObjectName("bookmarkList") self.thumbnails.page_selected.connect(self.page_selected.emit) + self.bookmarks.itemClicked.connect(self._emit_bookmark_page) thumb_page = QWidget() layout = QVBoxLayout(thumb_page) @@ -195,11 +198,41 @@ class Sidebar(QTabWidget): layout.addWidget(self.thumbnails) self.addTab(thumb_page, "缩略图") + self.addTab(self.bookmarks, "目录") self.setMinimumWidth(150) self.setMaximumWidth(330) def load_document(self, document: PdfDocument) -> None: self.thumbnails.load_document(document) + self._load_bookmarks(document) def select_page(self, page_index: int) -> None: self.thumbnails.select_page(page_index) + + def _load_bookmarks(self, document: PdfDocument) -> None: + self.bookmarks.clear() + if not document.is_open: + self._add_empty_bookmark_item("打开 PDF 后显示目录") + return + bookmarks = document.bookmarks() + if not bookmarks: + self._add_empty_bookmark_item("当前 PDF 没有目录") + return + for bookmark in bookmarks: + item = QListWidgetItem(self._bookmark_text(bookmark)) + item.setData(Qt.ItemDataRole.UserRole, bookmark.page_index) + self.bookmarks.addItem(item) + + def _add_empty_bookmark_item(self, text: str) -> None: + item = QListWidgetItem(text) + item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) + self.bookmarks.addItem(item) + + def _bookmark_text(self, bookmark: Bookmark) -> str: + prefix = " " * max(0, bookmark.level - 1) + return f"{prefix}{bookmark.title} 第 {bookmark.page_index + 1} 页" + + def _emit_bookmark_page(self, item: QListWidgetItem) -> None: + page_index = item.data(Qt.ItemDataRole.UserRole) + if isinstance(page_index, int): + self.page_selected.emit(page_index) diff --git a/pyproject.toml b/pyproject.toml index 750dc77..4fe60de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "PDFReaderLite" -version = "0.1.0" +version = "0.2.2" description = "A lightweight Windows PDF reader and editor inspired by common Adobe Acrobat workflows." requires-python = ">=3.10" dependencies = [