457 lines
20 KiB
Swift
457 lines
20 KiB
Swift
import UIKit
|
|
|
|
/// 页面视图的宿主回调。选区/划线/注释的交互与菜单全部由 SDK 处理,
|
|
/// 宿主只负责数据持久化和打开业务界面(如注释编辑器)。
|
|
/// 与 EPUB 的 `RDEPUBTextContentViewDelegate` 职责边界一致。
|
|
public protocol RDPDFReaderPageViewDelegate: AnyObject {
|
|
/// 选区变化(`nil` 表示清除)。宿主可据此更新状态展示。
|
|
func pageView(_ pageView: RDPDFReaderPageView, didChangeSelection selection: RDPDFReaderImageTextSelection?)
|
|
|
|
/// SDK 已把文本写入系统剪贴板后回调,宿主无需再执行复制。
|
|
func pageView(_ pageView: RDPDFReaderPageView, didCopyText text: String)
|
|
|
|
/// 用户在选区菜单点击“划线”。宿主负责创建并持久化标注,
|
|
/// 完成后通过 `configureTextLayer` 刷新页面。
|
|
func pageView(_ pageView: RDPDFReaderPageView, didRequestHighlight selection: RDPDFReaderImageTextSelection, color: String)
|
|
|
|
/// 用户在选区菜单点击“注释”。宿主打开注释编辑器。
|
|
func pageView(_ pageView: RDPDFReaderPageView, didRequestAnnotation selection: RDPDFReaderImageTextSelection)
|
|
|
|
/// 用户点击了带笔记的标注圆点。宿主打开注释查看/编辑界面。
|
|
func pageView(_ pageView: RDPDFReaderPageView, didOpenAnnotation annotation: RDPDFReaderAnnotation)
|
|
|
|
/// 用户在已有划线的菜单上选择动作。`.copy` 时 SDK 已写入剪贴板;
|
|
/// 删除/注释等数据变更由宿主执行。
|
|
func pageView(
|
|
_ pageView: RDPDFReaderPageView,
|
|
didRequestHighlightMenuAction action: RDPDFReaderExistingHighlightMenuAction,
|
|
highlight: RDPDFReaderAnnotation
|
|
)
|
|
}
|
|
|
|
public extension RDPDFReaderPageViewDelegate {
|
|
func pageView(_ pageView: RDPDFReaderPageView, didChangeSelection selection: RDPDFReaderImageTextSelection?) {}
|
|
func pageView(_ pageView: RDPDFReaderPageView, didCopyText text: String) {}
|
|
}
|
|
|
|
/// PDF 页面视图:组合缩放画布、文字选择层和选区放大镜,
|
|
/// 并提供与 EPUB 一致的两套系统编辑菜单:
|
|
/// - 选区菜单:复制、划线、注释;
|
|
/// - 已有划线菜单:复制、注释/删除注释、删除划线。
|
|
public final class RDPDFReaderPageView: UIView, RDPDFReaderPageInteractable, UIGestureRecognizerDelegate {
|
|
|
|
/// 与 EPUB 相同的“一步划线”默认颜色。
|
|
public static let defaultHighlightColor = "#F8E16C"
|
|
|
|
public weak var delegate: RDPDFReaderPageViewDelegate?
|
|
|
|
public var image: UIImage? { didSet { zoomView.image = image } }
|
|
|
|
/// 当前页索引,来自 `configureTextLayer`。
|
|
public var pageIndex: Int { textLayer.pageIndex }
|
|
|
|
/// 内容区的无障碍标识。UI 自动化通过它读取缩放与偏移状态。
|
|
public var contentAccessibilityIdentifier: String = "epub.reader.content" {
|
|
didSet { contentAccessibilityView.accessibilityIdentifier = contentAccessibilityIdentifier }
|
|
}
|
|
|
|
private let zoomView = RDPDFZoomablePageView()
|
|
private let textLayer = RDPDFReaderImageTextLayerView()
|
|
private let drawingCanvas = RDPDFReaderDrawingCanvasView()
|
|
private let contentAccessibilityView = UIView()
|
|
private let selectionLoupe = RDPDFReaderSelectionLoupeView()
|
|
private var tappedHighlight: RDPDFReaderAnnotation?
|
|
|
|
/// 画笔层属于单个实际 PDF 页,而不是横屏双页容器;因此笔迹不能越过书脊。
|
|
/// 画笔面板已打开时,禁用文本选区以保证单指手势可以用于拖动画面。
|
|
public var isDrawingSessionActive = false {
|
|
didSet {
|
|
textLayer.isSelectionEnabled = !isDrawingSessionActive
|
|
if isDrawingSessionActive { textLayer.clearSelection() }
|
|
}
|
|
}
|
|
|
|
/// 仅在画笔或橡皮擦被选中时启用画布,单指手势才会被画布消费。
|
|
public var isDrawingMode = false {
|
|
didSet {
|
|
// 退出编辑只关闭触摸,不隐藏画布;否则已持久化的笔迹会和工具栏一起消失。
|
|
drawingCanvas.isHidden = false
|
|
drawingCanvas.isUserInteractionEnabled = isDrawingMode
|
|
zoomView.isDrawingMode = isDrawingMode
|
|
}
|
|
}
|
|
|
|
var drawingStrokeEventHandler: ((RDPDFReaderPageView, CGPoint, RDPDFReaderDrawingStrokePhase) -> Void)?
|
|
|
|
// MARK: - RDPDFReaderPageInteractable
|
|
|
|
public var readerContentTapHandler: ((CGPoint) -> Void)?
|
|
public var readerZoomStateChangedHandler: ((Bool) -> Void)?
|
|
public var readerSelectionStateChangedHandler: ((Bool) -> Void)?
|
|
|
|
public var readerIsZoomed: Bool { zoomView.isZoomed }
|
|
public var readerHasActiveTextSelection: Bool { textLayer.selectedSelection != nil }
|
|
|
|
public func readerSetInternalGesturesEnabled(_ enabled: Bool) { zoomView.setInternalGesturesEnabled(enabled) }
|
|
public func readerClearTextSelection() { textLayer.clearSelection() }
|
|
public func readerFinishActiveDrawingStroke() { drawingCanvas.finishCurrentStroke() }
|
|
public func readerBeginExternalPinch(at point: CGPoint) { zoomView.beginExternalPinch(at: convert(point, to: zoomView)) }
|
|
public func readerUpdateExternalPinch(scale: CGFloat, at point: CGPoint) {
|
|
zoomView.updateExternalPinch(scale: scale, at: convert(point, to: zoomView))
|
|
}
|
|
public func readerEndExternalPinch() { zoomView.endExternalPinch() }
|
|
public func readerBeginExternalPan() { zoomView.beginExternalPan() }
|
|
public func readerUpdateExternalPan(translation: CGPoint) { zoomView.updateExternalPan(translation: translation) }
|
|
public func readerEndExternalPan() { zoomView.endExternalPan() }
|
|
|
|
func setSpreadContentAlignment(_ alignment: RDPDFZoomSurfaceView.ContentAlignment) {
|
|
zoomView.contentAlignment = alignment
|
|
}
|
|
|
|
/// 手机横屏单页按安全区内的可用宽度显示;纵向超出的部分由阅读器的
|
|
/// collectionView 连续竖滑承接(cell 高度即纸张高度),页面内部不做
|
|
/// 兜底竖向拖动——嵌套的同向滚动会吞掉外层手势,导致无法滚到下一页。
|
|
func setPhoneLandscapeWidthFitting(_ enabled: Bool, safeAreaInsets: UIEdgeInsets) {
|
|
zoomView.pageFitMode = enabled ? .fitAvailableWidth : .aspectFit
|
|
zoomView.allowsBaselineVerticalPan = false
|
|
zoomView.contentHorizontalInsets = enabled
|
|
? UIEdgeInsets(top: 0, left: safeAreaInsets.left, bottom: 0, right: safeAreaInsets.right)
|
|
: .zero
|
|
}
|
|
|
|
/// 页面图片在当前适配比例下的实际纸张区域,用于把仿真翻页手势限制在书籍范围内。
|
|
func fittedPageFrame(in targetView: UIView) -> CGRect {
|
|
layoutIfNeeded()
|
|
zoomView.layoutIfNeeded()
|
|
return zoomView.contentView.convert(zoomView.contentView.bounds, to: targetView)
|
|
}
|
|
|
|
// MARK: - 配置
|
|
|
|
public func configureTextLayer(
|
|
pageIndex: Int,
|
|
textRuns: [RDPDFReaderTextRun],
|
|
textSource: RDPDFReaderAnnotationSource,
|
|
annotations: [RDPDFReaderAnnotation]
|
|
) {
|
|
textLayer.pageIndex = pageIndex
|
|
textLayer.textSource = textSource
|
|
// 无文字来源时长按空白进入区域框选;有文字时保持与 EPUB 一致只响应文本。
|
|
textLayer.allowsRegionSelection = textSource == .region
|
|
textLayer.textRuns = textRuns
|
|
textLayer.annotations = annotations
|
|
updateAccessibilityViewport()
|
|
}
|
|
|
|
/// Shows a non-persistent highlight while the speech engine reads text.
|
|
public func setSpeechHighlightRects(_ rects: [CGRect]) {
|
|
textLayer.speechHighlightRects = rects
|
|
}
|
|
|
|
public func configureDrawing(
|
|
pageIndex: Int,
|
|
document: RDPDFReaderDrawingDocument,
|
|
documentChanged: @escaping (RDPDFReaderDrawingDocument) -> Void
|
|
) {
|
|
drawingCanvas.currentPage = pageIndex
|
|
drawingCanvas.load(document: document)
|
|
drawingCanvas.pathsChangedHandler = { [weak drawingCanvas] _ in
|
|
guard let drawingCanvas else { return }
|
|
documentChanged(drawingCanvas.drawingDocument())
|
|
}
|
|
drawingCanvas.strokeEventHandler = { [weak self] point, phase in
|
|
guard let self else { return }
|
|
self.drawingStrokeEventHandler?(self, self.convert(point, from: self.drawingCanvas), phase)
|
|
}
|
|
}
|
|
|
|
public func setDrawingTool(_ tool: RDPDFReaderDrawingTool, color: UIColor? = nil, lineWidth: CGFloat? = nil) {
|
|
drawingCanvas.tool = tool
|
|
if let color { drawingCanvas.strokeColor = color }
|
|
if let lineWidth { drawingCanvas.lineWidth = lineWidth }
|
|
}
|
|
|
|
public func undoDrawing() { drawingCanvas.undo() }
|
|
public func redoDrawing() { drawingCanvas.redo() }
|
|
public func clearDrawing() { drawingCanvas.clearAll() }
|
|
public func drawingLayers() -> [RDPDFReaderDrawingLayer] { drawingCanvas.drawingLayers() }
|
|
public func selectedDrawingLayerID() -> UUID? { drawingCanvas.selectedDrawingLayerID() }
|
|
public func addDrawingLayer() { drawingCanvas.addLayer() }
|
|
public func selectDrawingLayer(id: UUID) { drawingCanvas.selectLayer(id: id) }
|
|
public func setDrawingLayerVisibility(id: UUID, isVisible: Bool) { drawingCanvas.setLayerVisibility(id: id, isVisible: isVisible) }
|
|
public func deleteDrawingLayer(id: UUID) { drawingCanvas.deleteLayer(id: id) }
|
|
|
|
func containsDrawingPoint(_ point: CGPoint, from sourceView: UIView) -> Bool {
|
|
drawingCanvas.bounds.contains(sourceView.convert(point, to: drawingCanvas))
|
|
}
|
|
|
|
func continueDrawingStroke(at point: CGPoint, from sourceView: UIView, phase: RDPDFReaderDrawingStrokePhase) {
|
|
let localPoint = sourceView.convert(point, to: drawingCanvas)
|
|
switch phase {
|
|
case .began: drawingCanvas.beginExternalStroke(at: localPoint)
|
|
case .moved: drawingCanvas.updateExternalStroke(at: localPoint)
|
|
case .ended: drawingCanvas.endExternalStroke(at: localPoint)
|
|
case .cancelled: drawingCanvas.endExternalStroke(at: localPoint)
|
|
}
|
|
}
|
|
|
|
/// 应用阅读主题。SDK 不依赖任何主题类型,宿主传入解析后的颜色。
|
|
public func applyTheme(contentBackgroundColor: UIColor, surroundingBackgroundColor: UIColor) {
|
|
backgroundColor = contentBackgroundColor
|
|
zoomView.backgroundColor = surroundingBackgroundColor
|
|
zoomView.contentView.backgroundColor = contentBackgroundColor
|
|
}
|
|
|
|
// MARK: - 初始化
|
|
|
|
public override init(frame: CGRect) {
|
|
super.init(frame: frame)
|
|
isAccessibilityElement = false
|
|
|
|
zoomView.frame = bounds
|
|
zoomView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
zoomView.zoomStateChanged = { [weak self] zoomed in
|
|
self?.readerZoomStateChangedHandler?(zoomed)
|
|
self?.updateAccessibilityViewport()
|
|
}
|
|
zoomView.viewportChanged = { [weak self] _, _ in self?.updateAccessibilityViewport() }
|
|
addSubview(zoomView)
|
|
|
|
textLayer.frame = zoomView.contentView.bounds
|
|
textLayer.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
textLayer.isAccessibilityElement = true
|
|
textLayer.onSelectionChanged = { [weak self] selection in
|
|
self?.handleSelectionChange(selection)
|
|
}
|
|
textLayer.onInteractionStateChanged = { [weak self] state in
|
|
self?.handleSelectionInteractionStateChange(state)
|
|
}
|
|
textLayer.onSelectionFocusChanged = { [weak self] focusPoint in
|
|
self?.updateSelectionLoupe(focusPoint)
|
|
}
|
|
zoomView.contentView.addSubview(textLayer)
|
|
|
|
drawingCanvas.frame = zoomView.contentView.bounds
|
|
drawingCanvas.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
drawingCanvas.clipsToBounds = true
|
|
drawingCanvas.isHidden = true
|
|
drawingCanvas.isUserInteractionEnabled = false
|
|
zoomView.contentView.addSubview(drawingCanvas)
|
|
|
|
contentAccessibilityView.frame = bounds
|
|
contentAccessibilityView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
contentAccessibilityView.backgroundColor = .clear
|
|
contentAccessibilityView.isUserInteractionEnabled = false
|
|
contentAccessibilityView.isAccessibilityElement = true
|
|
contentAccessibilityView.accessibilityIdentifier = contentAccessibilityIdentifier
|
|
contentAccessibilityView.accessibilityLabel = "PDF 阅读页面"
|
|
addSubview(contentAccessibilityView)
|
|
|
|
addSubview(selectionLoupe)
|
|
|
|
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
|
|
tap.delegate = self
|
|
tap.require(toFail: zoomView.doubleTapZoomGestureRecognizer)
|
|
tap.require(toFail: textLayer.longPressGestureRecognizer)
|
|
tap.require(toFail: textLayer.selectionHandlePanGestureRecognizer)
|
|
tap.cancelsTouchesInView = false
|
|
addGestureRecognizer(tap)
|
|
updateAccessibilityViewport()
|
|
}
|
|
|
|
public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
public override func layoutSubviews() {
|
|
super.layoutSubviews()
|
|
zoomView.layoutIfNeeded()
|
|
textLayer.frame = zoomView.contentView.bounds
|
|
drawingCanvas.frame = zoomView.contentView.bounds
|
|
}
|
|
|
|
// MARK: - 点击分发
|
|
|
|
@objc private func handleTap(_ gesture: UITapGestureRecognizer) {
|
|
if textLayer.selectedSelection != nil {
|
|
textLayer.clearSelection()
|
|
return
|
|
}
|
|
let textLayerPoint = gesture.location(in: textLayer)
|
|
if let highlight = highlightAt(textLayerPoint) {
|
|
showExistingHighlightMenu(for: highlight, at: gesture.location(in: self))
|
|
return
|
|
}
|
|
tappedHighlight = nil
|
|
readerContentTapHandler?(gesture.location(in: self))
|
|
}
|
|
|
|
private func highlightAt(_ point: CGPoint) -> RDPDFReaderAnnotation? {
|
|
guard bounds.width > 0, bounds.height > 0 else { return nil }
|
|
let normalizedPoint = CGPoint(
|
|
x: point.x / textLayer.bounds.width,
|
|
y: point.y / textLayer.bounds.height
|
|
)
|
|
for annotation in textLayer.annotations where annotation.pageIndex == textLayer.pageIndex {
|
|
for rect in annotation.normalizedRects where rect.contains(normalizedPoint) {
|
|
return annotation
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// MARK: - 菜单(与 EPUB 一致:锚定在选区/划线旁的系统编辑菜单)
|
|
|
|
public override var canBecomeFirstResponder: Bool { true }
|
|
|
|
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
|
if tappedHighlight != nil {
|
|
return action == #selector(rd_copyHighlight(_:))
|
|
|| action == #selector(rd_deleteHighlight(_:))
|
|
|| action == #selector(rd_annotateHighlight(_:))
|
|
|| action == #selector(rd_deleteAnnotation(_:))
|
|
}
|
|
guard let selection = textLayer.selectedSelection else { return false }
|
|
switch action {
|
|
case #selector(rd_copy(_:)):
|
|
return selection.canCopyText
|
|
case #selector(rd_highlight(_:)), #selector(rd_annotate(_:)):
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
private func handleSelectionChange(_ selection: RDPDFReaderImageTextSelection?) {
|
|
if selection == nil {
|
|
hideMenu()
|
|
}
|
|
readerSelectionStateChangedHandler?(selection != nil)
|
|
delegate?.pageView(self, didChangeSelection: selection)
|
|
}
|
|
|
|
private func handleSelectionInteractionStateChange(_ state: RDPDFReaderSelectionInteractionState) {
|
|
switch state {
|
|
case .selectionActive:
|
|
showSelectionMenu()
|
|
case .idle, .selecting, .adjustingHandle:
|
|
hideMenu()
|
|
}
|
|
}
|
|
|
|
private func showSelectionMenu() {
|
|
guard textLayer.selectedSelection != nil,
|
|
let anchorRect = textLayer.menuAnchorRect() else {
|
|
return
|
|
}
|
|
tappedHighlight = nil
|
|
becomeFirstResponder()
|
|
let menuController = UIMenuController.shared
|
|
menuController.menuItems = [
|
|
UIMenuItem(title: "复制", action: #selector(rd_copy(_:))),
|
|
UIMenuItem(title: "划线", action: #selector(rd_highlight(_:))),
|
|
UIMenuItem(title: "注释", action: #selector(rd_annotate(_:)))
|
|
]
|
|
menuController.setTargetRect(convert(anchorRect, from: textLayer), in: self)
|
|
menuController.setMenuVisible(true, animated: true)
|
|
}
|
|
|
|
private func showExistingHighlightMenu(for annotation: RDPDFReaderAnnotation, at point: CGPoint) {
|
|
tappedHighlight = annotation
|
|
becomeFirstResponder()
|
|
|
|
var menuItems = [UIMenuItem(title: "复制", action: #selector(rd_copyHighlight(_:)))]
|
|
if annotation.note?.isEmpty == false {
|
|
menuItems.append(UIMenuItem(title: "删除注释", action: #selector(rd_deleteAnnotation(_:))))
|
|
} else {
|
|
menuItems.append(UIMenuItem(title: "注释", action: #selector(rd_annotateHighlight(_:))))
|
|
}
|
|
menuItems.append(UIMenuItem(title: "删除划线", action: #selector(rd_deleteHighlight(_:))))
|
|
|
|
let menuController = UIMenuController.shared
|
|
menuController.menuItems = menuItems
|
|
menuController.setTargetRect(CGRect(x: point.x, y: point.y, width: 1, height: 1), in: self)
|
|
menuController.setMenuVisible(true, animated: true)
|
|
}
|
|
|
|
private func hideMenu() {
|
|
UIMenuController.shared.setMenuVisible(false, animated: true)
|
|
}
|
|
|
|
private func updateSelectionLoupe(_ focusPoint: CGPoint?) {
|
|
guard let focusPoint else {
|
|
selectionLoupe.dismiss()
|
|
return
|
|
}
|
|
selectionLoupe.present(
|
|
sourceView: zoomView.contentView,
|
|
focusPoint: textLayer.convert(focusPoint, to: zoomView.contentView),
|
|
hostBounds: bounds,
|
|
targetPoint: convert(focusPoint, from: textLayer)
|
|
)
|
|
}
|
|
|
|
// MARK: - 选区菜单动作
|
|
|
|
@objc private func rd_copy(_ sender: Any?) {
|
|
guard let selection = textLayer.selectedSelection,
|
|
selection.canCopyText,
|
|
let text = selection.text?.trimmingCharacters(in: .whitespacesAndNewlines),
|
|
!text.isEmpty else { return }
|
|
UIPasteboard.general.string = text
|
|
delegate?.pageView(self, didCopyText: text)
|
|
textLayer.clearSelection()
|
|
}
|
|
|
|
@objc private func rd_highlight(_ sender: Any?) {
|
|
guard let selection = textLayer.selectedSelection else { return }
|
|
delegate?.pageView(self, didRequestHighlight: selection, color: Self.defaultHighlightColor)
|
|
textLayer.clearSelection()
|
|
}
|
|
|
|
@objc private func rd_annotate(_ sender: Any?) {
|
|
guard let selection = textLayer.selectedSelection else { return }
|
|
delegate?.pageView(self, didRequestAnnotation: selection)
|
|
textLayer.clearSelection()
|
|
}
|
|
|
|
// MARK: - 已有划线菜单动作
|
|
|
|
@objc private func rd_copyHighlight(_ sender: Any?) {
|
|
guard let highlight = consumeTappedHighlight() else { return }
|
|
if let text = highlight.selectedText?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty {
|
|
UIPasteboard.general.string = text
|
|
delegate?.pageView(self, didCopyText: text)
|
|
}
|
|
delegate?.pageView(self, didRequestHighlightMenuAction: .copy, highlight: highlight)
|
|
}
|
|
|
|
@objc private func rd_annotateHighlight(_ sender: Any?) {
|
|
guard let highlight = consumeTappedHighlight() else { return }
|
|
delegate?.pageView(self, didRequestHighlightMenuAction: .annotate, highlight: highlight)
|
|
}
|
|
|
|
@objc private func rd_deleteAnnotation(_ sender: Any?) {
|
|
guard let highlight = consumeTappedHighlight() else { return }
|
|
delegate?.pageView(self, didRequestHighlightMenuAction: .deleteAnnotation, highlight: highlight)
|
|
}
|
|
|
|
@objc private func rd_deleteHighlight(_ sender: Any?) {
|
|
guard let highlight = consumeTappedHighlight() else { return }
|
|
delegate?.pageView(self, didRequestHighlightMenuAction: .deleteUnderline, highlight: highlight)
|
|
}
|
|
|
|
private func consumeTappedHighlight() -> RDPDFReaderAnnotation? {
|
|
defer { tappedHighlight = nil }
|
|
return tappedHighlight
|
|
}
|
|
|
|
private func updateAccessibilityViewport() {
|
|
let offset = zoomView.contentOffset
|
|
contentAccessibilityView.accessibilityValue = String(
|
|
format: "zoom=%.2f offset=%.0f,%.0f",
|
|
zoomView.zoomScale,
|
|
offset.x,
|
|
offset.y
|
|
)
|
|
}
|
|
}
|