From 395ea3335edea0d6e33c74bda7b87ab946fee2ed Mon Sep 17 00:00:00 2001 From: Jackson Harper Date: Thu, 2 Feb 2023 16:10:18 +0800 Subject: [PATCH] PDF highlight position info on iOS --- .../Sources/App/PDFSupport/PDFViewer.swift | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/apple/OmnivoreKit/Sources/App/PDFSupport/PDFViewer.swift b/apple/OmnivoreKit/Sources/App/PDFSupport/PDFViewer.swift index dc1091f7b..4958503ca 100644 --- a/apple/OmnivoreKit/Sources/App/PDFSupport/PDFViewer.swift +++ b/apple/OmnivoreKit/Sources/App/PDFSupport/PDFViewer.swift @@ -269,6 +269,34 @@ import Utils return result } + func heightBefore(pageIndex: PageIndex) -> Double { + var totalHeight = 0.0 + for idx in 0 ..< pageIndex { + if let page = document.pageInfoForPage(at: idx) { + totalHeight += page.size.height + } + } + return totalHeight + } + + func documentTotalHeight() -> Double { + var totalHeight = 0.0 + for idx in 0 ..< document.pageCount { + if let page = document.pageInfoForPage(at: idx) { + totalHeight += page.size.height + } + } + return totalHeight + } + + func highlightTop(pageView: PDFPageView, highlight: HighlightAnnotation) -> Double { + if let pageInfo = pageView.pageInfo { + return pageInfo.size.height - highlight.boundingBox.minY + } + + return 0.0 + } + // swiftlint:disable:next function_body_length func highlightSelection(pageView: PDFPageView, selectedText: String, dataService: DataService) -> String { let highlightID = UUID().uuidString.lowercased() @@ -290,6 +318,9 @@ import Utils let overlapping = overlappingHighlights(pageView: pageView, highlight: highlight) if let patchData = try? highlight.generateInstantJSON(), let patch = String(data: patchData, encoding: .utf8) { + let top = highlightTop(pageView: pageView, highlight: highlight) + let positionPercent = (heightBefore(pageIndex: pageView.pageIndex) + top) / documentTotalHeight() + if overlapping.isEmpty { viewModel.createHighlight( dataService: dataService, @@ -297,8 +328,7 @@ import Utils highlightID: highlightID, quote: quote, patch: patch, - // TODO - positionPercent: nil, + positionPercent: positionPercent, positionAnchorIndex: Int(pageView.pageIndex) ) } else { @@ -310,6 +340,9 @@ import Utils boundingBox: boundingBox, pageIndex: Int(pageView.pageIndex) ) { + let top = boundingBox.minY + let positionPercent = (heightBefore(pageIndex: pageView.pageIndex) + top) / documentTotalHeight() + mergedHighlight.customData = highlight.customData document.add(annotations: [mergedHighlight]) document.remove(annotations: overlapping + [highlight]) @@ -320,8 +353,7 @@ import Utils highlightID: highlightID, quote: quote, patch: patch, - // TODO: - positionPercent: nil, + positionPercent: positionPercent, positionAnchorIndex: Int(pageView.pageIndex), overlapHighlightIdList: highlightIds(overlapping) )