react-native-pdf-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/PdfSdk.podspec +32 -0
  4. package/README.md +270 -2
  5. package/android/CMakeLists.txt +24 -0
  6. package/android/build.gradle +132 -0
  7. package/android/gradle.properties +4 -0
  8. package/android/src/main/AndroidManifest.xml +1 -0
  9. package/android/src/main/cpp/cpp-adapter.cpp +9 -0
  10. package/android/src/main/java/com/margelo/nitro/pdfsdk/HybridPdfDocument.kt +72 -0
  11. package/android/src/main/java/com/margelo/nitro/pdfsdk/HybridPdfSdk.kt +17 -0
  12. package/android/src/main/java/com/margelo/nitro/pdfsdk/HybridPdfView.kt +194 -0
  13. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfDocumentLayout.kt +109 -0
  14. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfFailure.kt +36 -0
  15. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfPageSource.kt +141 -0
  16. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfSdkPackage.kt +35 -0
  17. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfSourceLoader.kt +117 -0
  18. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfSurface.kt +839 -0
  19. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfTileStore.kt +210 -0
  20. package/android/src/main/java/com/margelo/nitro/pdfsdk/PdfViewport.kt +255 -0
  21. package/android/src/main/java/com/margelo/nitro/pdfsdk/TileGrid.kt +276 -0
  22. package/ios/HybridPdfDocument.swift +71 -0
  23. package/ios/HybridPdfSdk.swift +10 -0
  24. package/ios/HybridPdfView.swift +202 -0
  25. package/ios/PdfDocumentLayout.swift +174 -0
  26. package/ios/PdfFailure.swift +46 -0
  27. package/ios/PdfImageCache.swift +83 -0
  28. package/ios/PdfPageSource.swift +221 -0
  29. package/ios/PdfScrollPlan.swift +108 -0
  30. package/ios/PdfSourceLoader.swift +120 -0
  31. package/ios/PdfSurface.swift +711 -0
  32. package/ios/PdfTileCanvas.swift +148 -0
  33. package/ios/PdfTileGrid.swift +518 -0
  34. package/ios/PdfTileStore.swift +346 -0
  35. package/ios/PdfViewport.swift +200 -0
  36. package/lib/commonjs/PdfView.js +149 -0
  37. package/lib/commonjs/PdfView.js.map +1 -0
  38. package/lib/commonjs/document.js +38 -0
  39. package/lib/commonjs/document.js.map +1 -0
  40. package/lib/commonjs/index.js +26 -0
  41. package/lib/commonjs/index.js.map +1 -0
  42. package/lib/commonjs/package.json +1 -0
  43. package/lib/commonjs/specs/PdfSdk.nitro.js +6 -0
  44. package/lib/commonjs/specs/PdfSdk.nitro.js.map +1 -0
  45. package/lib/commonjs/specs/PdfView.nitro.js +6 -0
  46. package/lib/commonjs/specs/PdfView.nitro.js.map +1 -0
  47. package/lib/module/PdfView.js +143 -0
  48. package/lib/module/PdfView.js.map +1 -0
  49. package/lib/module/document.js +34 -0
  50. package/lib/module/document.js.map +1 -0
  51. package/lib/module/index.js +5 -0
  52. package/lib/module/index.js.map +1 -0
  53. package/lib/module/specs/PdfSdk.nitro.js +4 -0
  54. package/lib/module/specs/PdfSdk.nitro.js.map +1 -0
  55. package/lib/module/specs/PdfView.nitro.js +4 -0
  56. package/lib/module/specs/PdfView.nitro.js.map +1 -0
  57. package/lib/typescript/src/PdfView.d.ts +65 -0
  58. package/lib/typescript/src/PdfView.d.ts.map +1 -0
  59. package/lib/typescript/src/document.d.ts +22 -0
  60. package/lib/typescript/src/document.d.ts.map +1 -0
  61. package/lib/typescript/src/index.d.ts +6 -0
  62. package/lib/typescript/src/index.d.ts.map +1 -0
  63. package/lib/typescript/src/specs/PdfSdk.nitro.d.ts +60 -0
  64. package/lib/typescript/src/specs/PdfSdk.nitro.d.ts.map +1 -0
  65. package/lib/typescript/src/specs/PdfView.nitro.d.ts +131 -0
  66. package/lib/typescript/src/specs/PdfView.nitro.d.ts.map +1 -0
  67. package/nitro.json +40 -0
  68. package/nitrogen/generated/.gitattributes +1 -0
  69. package/nitrogen/generated/android/PdfSdk+autolinking.cmake +87 -0
  70. package/nitrogen/generated/android/PdfSdk+autolinking.gradle +27 -0
  71. package/nitrogen/generated/android/PdfSdkOnLoad.cpp +84 -0
  72. package/nitrogen/generated/android/PdfSdkOnLoad.hpp +34 -0
  73. package/nitrogen/generated/android/c++/JFunc_void_PdfErrorEvent.hpp +80 -0
  74. package/nitrogen/generated/android/c++/JFunc_void_PdfLoadEvent.hpp +77 -0
  75. package/nitrogen/generated/android/c++/JFunc_void_PdfPageEvent.hpp +77 -0
  76. package/nitrogen/generated/android/c++/JFunc_void_PdfTapEvent.hpp +77 -0
  77. package/nitrogen/generated/android/c++/JFunc_void_PdfZoomEvent.hpp +77 -0
  78. package/nitrogen/generated/android/c++/JHybridNativePdfViewSpec.cpp +266 -0
  79. package/nitrogen/generated/android/c++/JHybridNativePdfViewSpec.hpp +92 -0
  80. package/nitrogen/generated/android/c++/JHybridPdfDocumentSpec.cpp +87 -0
  81. package/nitrogen/generated/android/c++/JHybridPdfDocumentSpec.hpp +65 -0
  82. package/nitrogen/generated/android/c++/JHybridPdfSdkSpec.cpp +58 -0
  83. package/nitrogen/generated/android/c++/JHybridPdfSdkSpec.hpp +63 -0
  84. package/nitrogen/generated/android/c++/JPdfErrorCode.hpp +67 -0
  85. package/nitrogen/generated/android/c++/JPdfErrorEvent.hpp +63 -0
  86. package/nitrogen/generated/android/c++/JPdfFit.hpp +64 -0
  87. package/nitrogen/generated/android/c++/JPdfLoadEvent.hpp +65 -0
  88. package/nitrogen/generated/android/c++/JPdfPageEvent.hpp +61 -0
  89. package/nitrogen/generated/android/c++/JPdfPageSize.hpp +61 -0
  90. package/nitrogen/generated/android/c++/JPdfRenderRequest.hpp +86 -0
  91. package/nitrogen/generated/android/c++/JPdfTapEvent.hpp +65 -0
  92. package/nitrogen/generated/android/c++/JPdfViewSource.hpp +84 -0
  93. package/nitrogen/generated/android/c++/JPdfZoomEvent.hpp +61 -0
  94. package/nitrogen/generated/android/c++/views/JHybridNativePdfViewStateUpdater.cpp +108 -0
  95. package/nitrogen/generated/android/c++/views/JHybridNativePdfViewStateUpdater.hpp +49 -0
  96. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/Func_void_PdfErrorEvent.kt +80 -0
  97. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/Func_void_PdfLoadEvent.kt +80 -0
  98. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/Func_void_PdfPageEvent.kt +80 -0
  99. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/Func_void_PdfTapEvent.kt +80 -0
  100. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/Func_void_PdfZoomEvent.kt +80 -0
  101. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/HybridNativePdfViewSpec.kt +185 -0
  102. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/HybridPdfDocumentSpec.kt +65 -0
  103. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/HybridPdfSdkSpec.kt +54 -0
  104. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfErrorCode.kt +26 -0
  105. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfErrorEvent.kt +56 -0
  106. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfFit.kt +25 -0
  107. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfLoadEvent.kt +61 -0
  108. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfPageEvent.kt +56 -0
  109. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfPageSize.kt +56 -0
  110. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfRenderRequest.kt +86 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfSdkOnLoad.kt +35 -0
  112. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfTapEvent.kt +61 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfViewSource.kt +66 -0
  114. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/PdfZoomEvent.kt +56 -0
  115. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/views/HybridNativePdfViewManager.kt +80 -0
  116. package/nitrogen/generated/android/kotlin/com/margelo/nitro/pdfsdk/views/HybridNativePdfViewStateUpdater.kt +23 -0
  117. package/nitrogen/generated/ios/PdfSdk+autolinking.rb +62 -0
  118. package/nitrogen/generated/ios/PdfSdk-Swift-Cxx-Bridge.cpp +123 -0
  119. package/nitrogen/generated/ios/PdfSdk-Swift-Cxx-Bridge.hpp +474 -0
  120. package/nitrogen/generated/ios/PdfSdk-Swift-Cxx-Umbrella.hpp +88 -0
  121. package/nitrogen/generated/ios/PdfSdkAutolinking.mm +41 -0
  122. package/nitrogen/generated/ios/PdfSdkAutolinking.swift +38 -0
  123. package/nitrogen/generated/ios/c++/HybridNativePdfViewSpecSwift.cpp +11 -0
  124. package/nitrogen/generated/ios/c++/HybridNativePdfViewSpecSwift.hpp +209 -0
  125. package/nitrogen/generated/ios/c++/HybridPdfDocumentSpecSwift.cpp +11 -0
  126. package/nitrogen/generated/ios/c++/HybridPdfDocumentSpecSwift.hpp +105 -0
  127. package/nitrogen/generated/ios/c++/HybridPdfSdkSpecSwift.cpp +11 -0
  128. package/nitrogen/generated/ios/c++/HybridPdfSdkSpecSwift.hpp +86 -0
  129. package/nitrogen/generated/ios/c++/views/HybridNativePdfViewComponent.mm +187 -0
  130. package/nitrogen/generated/ios/swift/Func_void_PdfErrorEvent.swift +46 -0
  131. package/nitrogen/generated/ios/swift/Func_void_PdfLoadEvent.swift +46 -0
  132. package/nitrogen/generated/ios/swift/Func_void_PdfPageEvent.swift +46 -0
  133. package/nitrogen/generated/ios/swift/Func_void_PdfTapEvent.swift +46 -0
  134. package/nitrogen/generated/ios/swift/Func_void_PdfZoomEvent.swift +46 -0
  135. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  136. package/nitrogen/generated/ios/swift/Func_void_std__string.swift +46 -0
  137. package/nitrogen/generated/ios/swift/HybridNativePdfViewSpec.swift +70 -0
  138. package/nitrogen/generated/ios/swift/HybridNativePdfViewSpec_cxx.swift +438 -0
  139. package/nitrogen/generated/ios/swift/HybridPdfDocumentSpec.swift +57 -0
  140. package/nitrogen/generated/ios/swift/HybridPdfDocumentSpec_cxx.swift +173 -0
  141. package/nitrogen/generated/ios/swift/HybridPdfSdkSpec.swift +55 -0
  142. package/nitrogen/generated/ios/swift/HybridPdfSdkSpec_cxx.swift +148 -0
  143. package/nitrogen/generated/ios/swift/PdfErrorCode.swift +52 -0
  144. package/nitrogen/generated/ios/swift/PdfErrorEvent.swift +34 -0
  145. package/nitrogen/generated/ios/swift/PdfFit.swift +48 -0
  146. package/nitrogen/generated/ios/swift/PdfLoadEvent.swift +39 -0
  147. package/nitrogen/generated/ios/swift/PdfPageEvent.swift +34 -0
  148. package/nitrogen/generated/ios/swift/PdfPageSize.swift +34 -0
  149. package/nitrogen/generated/ios/swift/PdfRenderRequest.swift +129 -0
  150. package/nitrogen/generated/ios/swift/PdfTapEvent.swift +39 -0
  151. package/nitrogen/generated/ios/swift/PdfViewSource.swift +97 -0
  152. package/nitrogen/generated/ios/swift/PdfZoomEvent.swift +34 -0
  153. package/nitrogen/generated/shared/c++/HybridNativePdfViewSpec.cpp +51 -0
  154. package/nitrogen/generated/shared/c++/HybridNativePdfViewSpec.hpp +112 -0
  155. package/nitrogen/generated/shared/c++/HybridPdfDocumentSpec.cpp +24 -0
  156. package/nitrogen/generated/shared/c++/HybridPdfDocumentSpec.hpp +70 -0
  157. package/nitrogen/generated/shared/c++/HybridPdfSdkSpec.cpp +21 -0
  158. package/nitrogen/generated/shared/c++/HybridPdfSdkSpec.hpp +66 -0
  159. package/nitrogen/generated/shared/c++/PdfErrorCode.hpp +88 -0
  160. package/nitrogen/generated/shared/c++/PdfErrorEvent.hpp +89 -0
  161. package/nitrogen/generated/shared/c++/PdfFit.hpp +84 -0
  162. package/nitrogen/generated/shared/c++/PdfLoadEvent.hpp +91 -0
  163. package/nitrogen/generated/shared/c++/PdfPageEvent.hpp +87 -0
  164. package/nitrogen/generated/shared/c++/PdfPageSize.hpp +87 -0
  165. package/nitrogen/generated/shared/c++/PdfRenderRequest.hpp +112 -0
  166. package/nitrogen/generated/shared/c++/PdfTapEvent.hpp +91 -0
  167. package/nitrogen/generated/shared/c++/PdfViewSource.hpp +97 -0
  168. package/nitrogen/generated/shared/c++/PdfZoomEvent.hpp +87 -0
  169. package/nitrogen/generated/shared/c++/views/HybridNativePdfViewComponent.cpp +226 -0
  170. package/nitrogen/generated/shared/c++/views/HybridNativePdfViewComponent.hpp +130 -0
  171. package/nitrogen/generated/shared/json/NativePdfViewConfig.json +23 -0
  172. package/package.json +80 -4
  173. package/react-native.config.js +10 -0
  174. package/src/PdfView.tsx +221 -0
  175. package/src/document.ts +34 -0
  176. package/src/index.ts +16 -0
  177. package/src/specs/PdfSdk.nitro.ts +60 -0
  178. package/src/specs/PdfView.nitro.ts +149 -0
@@ -0,0 +1,174 @@
1
+ import CoreGraphics
2
+
3
+ /// A page's size in PDF points, a point being a 72nd of an inch.
4
+ struct PageSize: Equatable {
5
+ let width: CGFloat
6
+ let height: CGFloat
7
+
8
+ init(width: CGFloat, height: CGFloat) {
9
+ self.width = width
10
+ self.height = height
11
+ }
12
+ }
13
+
14
+ /// A rectangle of the document, in points.
15
+ struct PageRect: Equatable {
16
+ let x: CGFloat
17
+ let y: CGFloat
18
+ let width: CGFloat
19
+ let height: CGFloat
20
+
21
+ var right: CGFloat { x + width }
22
+ var bottom: CGFloat { y + height }
23
+
24
+ init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
25
+ self.x = x
26
+ self.y = y
27
+ self.width = width
28
+ self.height = height
29
+ }
30
+ }
31
+
32
+ /// Where a page sits in the document, in document points.
33
+ struct PageBox: Equatable {
34
+ let index: Int
35
+ let x: CGFloat
36
+ let y: CGFloat
37
+ let width: CGFloat
38
+ let height: CGFloat
39
+
40
+ var right: CGFloat { x + width }
41
+ var bottom: CGFloat { y + height }
42
+ var rect: PageRect { PageRect(x: x, y: y, width: width, height: height) }
43
+ }
44
+
45
+ /**
46
+ * The pages of a document, laid out one under another.
47
+ *
48
+ * A reader scrolls through a document; they do not press a button to turn a
49
+ * page. So the pages are placed in one coordinate space, with a gap between
50
+ * them, and everything above this works on that space rather than on a page.
51
+ * The gap is in points and therefore grows with the zoom, which is what keeps
52
+ * it looking like the same gap at every size.
53
+ *
54
+ * Pages narrower than the widest one are centred, the way every viewer draws a
55
+ * document whose pages are not all the same shape.
56
+ *
57
+ * The Kotlin twin of this file is `PdfDocumentLayout.kt`. The two are kept the
58
+ * same deliberately: the viewer should not open a document differently
59
+ * depending on the phone it is opened on, and a difference between the two is a
60
+ * bug in one of them.
61
+ */
62
+ final class PdfDocumentLayout {
63
+
64
+ let pages: [PageBox]
65
+ let width: CGFloat
66
+ let height: CGFloat
67
+ private let gap: CGFloat
68
+
69
+ init(_ sizes: [PageSize], gap: CGFloat = PdfDocumentLayout.defaultGap) {
70
+ self.gap = gap
71
+
72
+ let widest = sizes.map(\.width).max() ?? 0
73
+ var top: CGFloat = 0
74
+ var boxes: [PageBox] = []
75
+ boxes.reserveCapacity(sizes.count)
76
+
77
+ for (index, size) in sizes.enumerated() {
78
+ boxes.append(
79
+ PageBox(
80
+ index: index,
81
+ x: (widest - size.width) / 2,
82
+ y: top,
83
+ width: size.width,
84
+ height: size.height
85
+ )
86
+ )
87
+ top += size.height + gap
88
+ }
89
+
90
+ pages = boxes
91
+ width = widest
92
+ height = max(0, top - gap)
93
+ }
94
+
95
+ var pageCount: Int { pages.count }
96
+
97
+ var firstPage: PageSize {
98
+ guard let first = pages.first else { return PageSize(width: 0, height: 0) }
99
+ return PageSize(width: first.width, height: first.height)
100
+ }
101
+
102
+ /**
103
+ * The pages that any part of the given band of the document falls on.
104
+ *
105
+ * Found rather than filtered for: this is asked several times a frame, once
106
+ * per level drawn, and a document of five hundred pages should not be walked
107
+ * end to end each time. The pages are in order down the document, so the
108
+ * first one in the band can be looked up.
109
+ */
110
+ func pagesIn(top: CGFloat, bottom: CGFloat) -> [PageBox] {
111
+ guard !pages.isEmpty, bottom >= top else { return [] }
112
+
113
+ var low = 0
114
+ var high = pages.count
115
+ while low < high {
116
+ let middle = (low + high) / 2
117
+ if pages[middle].bottom < top { low = middle + 1 } else { high = middle }
118
+ }
119
+
120
+ var band: [PageBox] = []
121
+ var index = low
122
+ while index < pages.count, pages[index].y <= bottom {
123
+ band.append(pages[index])
124
+ index += 1
125
+ }
126
+ return band
127
+ }
128
+
129
+ /**
130
+ * The page a reader would say they are on: the one holding the middle of what
131
+ * is on screen, or the nearest one when the middle falls in a gap.
132
+ */
133
+ func pageAt(_ y: CGFloat) -> Int {
134
+ guard let last = pages.last else { return 0 }
135
+ for page in pages {
136
+ if y <= page.bottom { return page.index }
137
+ guard page.index + 1 < pages.count else { return page.index }
138
+ let next = pages[page.index + 1]
139
+ // In the gap between two pages, whichever edge is nearer.
140
+ if y < next.y {
141
+ return y - page.bottom <= next.y - y ? page.index : next.index
142
+ }
143
+ }
144
+ return last.index
145
+ }
146
+
147
+ /// The same document with one page's real size in place of the assumed one.
148
+ func withPageSize(_ index: Int, _ size: PageSize) -> PdfDocumentLayout {
149
+ var sizes = self.sizes()
150
+ guard sizes.indices.contains(index) else { return self }
151
+ guard sizes[index] != size else { return self }
152
+ sizes[index] = size
153
+ return PdfDocumentLayout(sizes, gap: gap)
154
+ }
155
+
156
+ func sizes() -> [PageSize] {
157
+ pages.map { PageSize(width: $0.width, height: $0.height) }
158
+ }
159
+
160
+ /**
161
+ * The gap between two pages, in points: about a fifth of an inch, which is
162
+ * enough to read as a break between sheets without wasting the screen.
163
+ */
164
+ static let defaultGap: CGFloat = 14
165
+
166
+ /// A document of one page, for the moment before the rest have been measured.
167
+ static func of(
168
+ _ size: PageSize,
169
+ pageCount: Int,
170
+ gap: CGFloat = PdfDocumentLayout.defaultGap
171
+ ) -> PdfDocumentLayout {
172
+ PdfDocumentLayout(Array(repeating: size, count: max(1, pageCount)), gap: gap)
173
+ }
174
+ }
@@ -0,0 +1,46 @@
1
+ import Foundation
2
+
3
+ /// Why a document could not be shown, in terms a caller can branch on.
4
+ enum PdfFailureCode {
5
+ case notFound
6
+ case password
7
+ case unsupported
8
+ case network
9
+ case unknown
10
+ }
11
+
12
+ struct PdfFailure: LocalizedError {
13
+ let code: PdfFailureCode
14
+ let message: String
15
+
16
+ var errorDescription: String? { message }
17
+
18
+ static func notFound(_ what: String) -> PdfFailure {
19
+ PdfFailure(code: .notFound, message: "There is no PDF at \(what)")
20
+ }
21
+
22
+ static func unsupported(_ what: String) -> PdfFailure {
23
+ PdfFailure(code: .unsupported, message: what)
24
+ }
25
+
26
+ static func password(_ what: String) -> PdfFailure {
27
+ PdfFailure(code: .password, message: what)
28
+ }
29
+
30
+ static func network(_ what: String) -> PdfFailure {
31
+ PdfFailure(code: .network, message: what)
32
+ }
33
+
34
+ static func unknown(_ what: String) -> PdfFailure {
35
+ PdfFailure(code: .unknown, message: what)
36
+ }
37
+
38
+ /// Whatever came back from somewhere else, as one of ours.
39
+ static func from(_ error: Error) -> PdfFailure {
40
+ if let failure = error as? PdfFailure { return failure }
41
+ return PdfFailure(
42
+ code: .unknown,
43
+ message: (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
44
+ )
45
+ }
46
+ }
@@ -0,0 +1,83 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+
4
+ /**
5
+ * The drawn tiles, kept until the room runs out, oldest use first.
6
+ *
7
+ * `NSCache` was here and had to go: it evicts what it likes, and what it liked
8
+ * was sometimes a tile being drawn on the screen every frame, which was then
9
+ * asked for again, drawn again and evicted again. Least recently used is the
10
+ * rule that suits a viewer, because every tile on screen is read on every
11
+ * frame and so can never be the least recently used one.
12
+ *
13
+ * The same rule as Android's `LruCache`, which is what the Kotlin twin uses.
14
+ */
15
+ final class PdfImageCache<Key: Hashable> {
16
+
17
+ private struct Held {
18
+ let image: CGImage
19
+ let bytes: Int
20
+ var used: UInt64
21
+ }
22
+
23
+ private let limit: Int
24
+ private let lock = NSLock()
25
+ private var held: [Key: Held] = [:]
26
+ private var used: UInt64 = 0
27
+ private(set) var bytes = 0
28
+
29
+ init(limit: Int) {
30
+ self.limit = max(1, limit)
31
+ }
32
+
33
+ func image(_ key: Key) -> CGImage? {
34
+ lock.lock()
35
+ defer { lock.unlock() }
36
+ guard var entry = held[key] else { return nil }
37
+ used += 1
38
+ entry.used = used
39
+ held[key] = entry
40
+ return entry.image
41
+ }
42
+
43
+ func put(_ image: CGImage, for key: Key) {
44
+ lock.lock()
45
+ defer { lock.unlock() }
46
+
47
+ let size = max(1, image.bytesPerRow * image.height)
48
+ if let existing = held[key] { bytes -= existing.bytes }
49
+ used += 1
50
+ held[key] = Held(image: image, bytes: size, used: used)
51
+ bytes += size
52
+ evict(to: limit)
53
+ }
54
+
55
+ func removeAll() {
56
+ lock.lock()
57
+ defer { lock.unlock() }
58
+ held.removeAll()
59
+ bytes = 0
60
+ }
61
+
62
+ /// Under memory pressure, back down to a share of what is allowed.
63
+ func trim(toShare share: Double) {
64
+ lock.lock()
65
+ defer { lock.unlock() }
66
+ evict(to: Int(Double(limit) * share))
67
+ }
68
+
69
+ /// Called with the lock held. Few enough tiles that the oldest is found by
70
+ /// looking, rather than by keeping a second structure in step.
71
+ private func evict(to allowed: Int) {
72
+ while bytes > allowed, held.count > 1 {
73
+ var oldest: Key?
74
+ var oldestUse = UInt64.max
75
+ for (key, entry) in held where entry.used < oldestUse {
76
+ oldestUse = entry.used
77
+ oldest = key
78
+ }
79
+ guard let oldest, let gone = held.removeValue(forKey: oldest) else { return }
80
+ bytes -= gone.bytes
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,221 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+ import ImageIO
4
+ #if canImport(UniformTypeIdentifiers)
5
+ import UniformTypeIdentifiers
6
+ #endif
7
+
8
+ /**
9
+ * Where a page's own coordinates are, and which way up it is.
10
+ *
11
+ * A PDF page is not a rectangle starting at zero: it has a box that may start
12
+ * anywhere, and a rotation the reader is meant to see it through. Both have to
13
+ * be undone before a part of the page can be asked for in the plain top left
14
+ * coordinates the rest of this package works in.
15
+ *
16
+ * Kept as a value with no renderer in it so the arithmetic can be tested.
17
+ */
18
+ struct PdfPageGeometry {
19
+ /// The page's box, in its own coordinates, y upwards.
20
+ let box: CGRect
21
+ /// A quarter turn clockwise each, as the file asks for: 0, 90, 180 or 270.
22
+ let rotation: Int
23
+
24
+ init(box: CGRect, rotation: Int) {
25
+ self.box = box.standardized
26
+ var turns = rotation % 360
27
+ if turns < 0 { turns += 360 }
28
+ self.rotation = (turns / 90) * 90
29
+ }
30
+
31
+ /// The size the reader sees, which is the box with the rotation applied.
32
+ var size: PageSize {
33
+ let turned = rotation == 90 || rotation == 270
34
+ return PageSize(
35
+ width: turned ? box.height : box.width,
36
+ height: turned ? box.width : box.height
37
+ )
38
+ }
39
+
40
+ /**
41
+ * Maps the page's own coordinates onto `(0, 0, size.width, size.height)`,
42
+ * y still upwards, with the rotation applied.
43
+ */
44
+ var transform: CGAffineTransform {
45
+ let localise = CGAffineTransform(translationX: -box.minX, y: -box.minY)
46
+ let width = box.width
47
+ let height = box.height
48
+ let turn: CGAffineTransform
49
+ switch rotation {
50
+ case 90:
51
+ turn = CGAffineTransform(a: 0, b: -1, c: 1, d: 0, tx: 0, ty: width)
52
+ case 180:
53
+ turn = CGAffineTransform(a: -1, b: 0, c: 0, d: -1, tx: width, ty: height)
54
+ case 270:
55
+ turn = CGAffineTransform(a: 0, b: 1, c: -1, d: 0, tx: height, ty: 0)
56
+ default:
57
+ turn = .identity
58
+ }
59
+ return localise.concatenating(turn)
60
+ }
61
+ }
62
+
63
+ /**
64
+ * A PDF file, open, drawn from one part of one page at a time.
65
+ *
66
+ * `CGPDFDocument` is not safe across threads, hence the lock. It also keeps
67
+ * nothing between draws: a page's content is read again on every call, which on
68
+ * a structural drawing is a tenth of a second whatever size is asked for, and
69
+ * is why the store above opens several of these and draws through them at once.
70
+ */
71
+ final class PdfPageSource: @unchecked Sendable {
72
+
73
+ private let lock = NSLock()
74
+ private let document: CGPDFDocument
75
+
76
+ private var geometries: [Int: PdfPageGeometry] = [:]
77
+ private var closed = false
78
+
79
+ init(path: String, password: String? = nil) throws {
80
+ let clean = path.hasPrefix("file://")
81
+ ? (URL(string: path)?.path ?? path)
82
+ : path
83
+
84
+ guard FileManager.default.fileExists(atPath: clean) else {
85
+ throw PdfFailure.notFound(clean)
86
+ }
87
+ guard let opened = CGPDFDocument(URL(fileURLWithPath: clean) as CFURL) else {
88
+ throw PdfFailure.unsupported("The file at \(clean) is not a PDF this device can read")
89
+ }
90
+
91
+ // An owner password alone is opened with an empty one, which is most of the
92
+ // documents that call themselves encrypted. A reader's password is not.
93
+ if opened.isEncrypted, !opened.isUnlocked {
94
+ let unlocked = password.map { word in
95
+ word.withCString { opened.unlockWithPassword($0) }
96
+ } ?? false
97
+ guard unlocked else {
98
+ throw PdfFailure.password(
99
+ password == nil
100
+ ? "This document is encrypted and needs a password"
101
+ : "That password does not open this document"
102
+ )
103
+ }
104
+ }
105
+ guard opened.numberOfPages > 0 else {
106
+ throw PdfFailure.unsupported("This document has no pages")
107
+ }
108
+ document = opened
109
+ }
110
+
111
+ var pageCount: Int { document.numberOfPages }
112
+
113
+ /// The page's size in points, a point being a 72nd of an inch.
114
+ func pageSize(_ index: Int) throws -> PageSize {
115
+ lock.lock()
116
+ defer { lock.unlock() }
117
+ return try geometry(index).size
118
+ }
119
+
120
+ /**
121
+ * Draws one part of one page, at the size asked for.
122
+ *
123
+ * `rect` is in the page's points with the origin at its top left corner,
124
+ * which is how the layout above thinks; the page itself is drawn upwards from
125
+ * its bottom left, which is what the flip below is for.
126
+ */
127
+ func image(page index: Int, rect: PageRect, pixelWidth: Int, pixelHeight: Int) throws -> CGImage {
128
+ lock.lock()
129
+ defer { lock.unlock() }
130
+
131
+ guard !closed else { throw PdfFailure.unknown("This document has been closed") }
132
+ let geometry = try self.geometry(index)
133
+ guard let page = document.page(at: index + 1) else {
134
+ throw PdfFailure.unknown("There is no page \(index) in a document of \(document.numberOfPages)")
135
+ }
136
+ guard rect.width > 0, rect.height > 0, pixelWidth > 0, pixelHeight > 0 else {
137
+ throw PdfFailure.unknown("A page cannot be drawn into nothing")
138
+ }
139
+
140
+ guard
141
+ let context = CGContext(
142
+ data: nil,
143
+ width: pixelWidth,
144
+ height: pixelHeight,
145
+ bitsPerComponent: 8,
146
+ bytesPerRow: 0,
147
+ space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(),
148
+ bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
149
+ | CGBitmapInfo.byteOrder32Little.rawValue
150
+ )
151
+ else {
152
+ throw PdfFailure.unknown("The page could not be drawn")
153
+ }
154
+
155
+ // Paper, not transparency: a PDF paints only what is on the page.
156
+ context.setFillColor(gray: 1, alpha: 1)
157
+ context.fill(CGRect(x: 0, y: 0, width: pixelWidth, height: pixelHeight))
158
+
159
+ context.interpolationQuality = .high
160
+ context.setShouldAntialias(true)
161
+
162
+ // A bitmap context counts upwards from the bottom, as a page does, so the
163
+ // region's distance from the bottom is what puts it at the origin.
164
+ let fromBottom = geometry.size.height - (rect.y + rect.height)
165
+ context.scaleBy(x: CGFloat(pixelWidth) / rect.width, y: CGFloat(pixelHeight) / rect.height)
166
+ context.translateBy(x: -rect.x, y: -fromBottom)
167
+ context.concatenate(geometry.transform)
168
+ context.drawPDFPage(page)
169
+
170
+ guard let image = context.makeImage() else {
171
+ throw PdfFailure.unknown("The page could not be drawn")
172
+ }
173
+ return image
174
+ }
175
+
176
+ func close() {
177
+ lock.lock()
178
+ defer { lock.unlock() }
179
+ closed = true
180
+ geometries.removeAll()
181
+ }
182
+
183
+ /// Writes an image out as a PNG, for the pictures the document object takes.
184
+ static func writePNG(_ image: CGImage, to path: String) throws {
185
+ let url = URL(fileURLWithPath: path)
186
+ try? FileManager.default.createDirectory(
187
+ at: url.deletingLastPathComponent(),
188
+ withIntermediateDirectories: true
189
+ )
190
+ guard
191
+ let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil)
192
+ else {
193
+ throw PdfFailure.unknown("Nothing could be written to \(path)")
194
+ }
195
+ CGImageDestinationAddImage(destination, image, nil)
196
+ guard CGImageDestinationFinalize(destination) else {
197
+ throw PdfFailure.unknown("The image could not be written to \(path)")
198
+ }
199
+ }
200
+
201
+ private func geometry(_ index: Int) throws -> PdfPageGeometry {
202
+ if let held = geometries[index] { return held }
203
+ guard index >= 0, index < document.numberOfPages, let page = document.page(at: index + 1) else {
204
+ throw PdfFailure.unknown(
205
+ "There is no page \(index) in a document of \(document.numberOfPages)"
206
+ )
207
+ }
208
+
209
+ var box = page.getBoxRect(.cropBox)
210
+ if box.isEmpty || box.isNull || box.isInfinite {
211
+ box = page.getBoxRect(.mediaBox)
212
+ }
213
+ if box.isEmpty || box.isNull || box.isInfinite {
214
+ throw PdfFailure.unsupported("Page \(index) has no size this viewer can read")
215
+ }
216
+
217
+ let geometry = PdfPageGeometry(box: box, rotation: Int(page.rotationAngle))
218
+ geometries[index] = geometry
219
+ return geometry
220
+ }
221
+ }
@@ -0,0 +1,108 @@
1
+ import CoreGraphics
2
+
3
+ /**
4
+ * The document as a scroll view has to be told about it.
5
+ *
6
+ * On iOS the reader's fingers are Apple's business: a `UIScrollView` carries
7
+ * the pan, the momentum, the rubber band at the edges and the pinch, all of
8
+ * which are better than anything written here would be, and all of which it
9
+ * does in terms of a content size, a zoom scale and a content offset. This
10
+ * turns a document and a screen into those three numbers, and back again.
11
+ *
12
+ * It is a separate, UIKit-free type because it is where a viewer drifts: a
13
+ * document that opens half off the screen, a page that cannot be zoomed as far
14
+ * as it should, a jump when a double tap lands. Those are all arithmetic, and
15
+ * `PdfSdkTests.swift` asks about them without a simulator.
16
+ *
17
+ * The document opens at zoom 1, whatever that is in points: the scroll view's
18
+ * scale is a multiple of how the document came up, not of its printed size.
19
+ */
20
+ struct PdfScrollPlan {
21
+
22
+ /// The document's bounding box, in its own points.
23
+ let documentSize: CGSize
24
+ let viewSize: CGSize
25
+
26
+ /// Document points to screen points at zoom 1.
27
+ let baseScale: CGFloat
28
+ let minimumZoomScale: CGFloat
29
+ let maximumZoomScale: CGFloat
30
+
31
+ init(viewport: PdfViewport) {
32
+ documentSize = CGSize(width: viewport.contentWidth, height: viewport.contentHeight)
33
+ viewSize = CGSize(width: viewport.viewWidth, height: viewport.viewHeight)
34
+
35
+ let floor = viewport.minScale()
36
+ let ceiling = viewport.maxScale()
37
+ // A page ten points tall would open at a zoom past the ceiling, so the
38
+ // ceiling wins: zoom 1 has to be inside the range the scroll view allows.
39
+ baseScale = min(max(viewport.restScale(), floor), ceiling)
40
+ minimumZoomScale = min(1, floor / baseScale)
41
+ maximumZoomScale = max(1, ceiling / baseScale)
42
+ }
43
+
44
+ /// The size of the content at zoom 1, which is what the scroll view is given.
45
+ var contentSize: CGSize {
46
+ CGSize(width: documentSize.width * baseScale, height: documentSize.height * baseScale)
47
+ }
48
+
49
+ func scale(atZoom zoom: CGFloat) -> CGFloat { baseScale * zoom }
50
+
51
+ /// The zoom that reaches a given scale, as far as the range allows.
52
+ func zoom(forScale scale: CGFloat) -> CGFloat {
53
+ min(max(scale / baseScale, minimumZoomScale), maximumZoomScale)
54
+ }
55
+
56
+ /**
57
+ * The space around a document smaller than the view, so that it sits in the
58
+ * middle of it rather than against the top left corner.
59
+ */
60
+ func margin(atZoom zoom: CGFloat) -> CGSize {
61
+ let scale = self.scale(atZoom: zoom)
62
+ return CGSize(
63
+ width: max(0, (viewSize.width - documentSize.width * scale) / 2),
64
+ height: max(0, (viewSize.height - documentSize.height * scale) / 2)
65
+ )
66
+ }
67
+
68
+ /**
69
+ * Where the document sits when it opens: at the top, at its left edge when it
70
+ * is wider than the screen, and in the middle of whichever direction it is
71
+ * smaller than the screen in.
72
+ */
73
+ var initialOffset: CGPoint {
74
+ let margin = self.margin(atZoom: 1)
75
+ return CGPoint(x: -margin.width, y: -margin.height)
76
+ }
77
+
78
+ /// Holds an offset inside what the scroll view would allow at that zoom.
79
+ func clamp(_ offset: CGPoint, atZoom zoom: CGFloat) -> CGPoint {
80
+ let margin = self.margin(atZoom: zoom)
81
+ let scale = self.scale(atZoom: zoom)
82
+ let furthestX = max(-margin.width, documentSize.width * scale - viewSize.width + margin.width)
83
+ let furthestY = max(-margin.height, documentSize.height * scale - viewSize.height + margin.height)
84
+ return CGPoint(
85
+ x: min(max(offset.x, -margin.width), furthestX),
86
+ y: min(max(offset.y, -margin.height), furthestY)
87
+ )
88
+ }
89
+
90
+ /// The offset that puts a point of the document in the middle of the view.
91
+ func offset(atZoom zoom: CGFloat, centredOn point: CGPoint) -> CGPoint {
92
+ let scale = self.scale(atZoom: zoom)
93
+ return clamp(
94
+ CGPoint(x: point.x * scale - viewSize.width / 2, y: point.y * scale - viewSize.height / 2),
95
+ atZoom: zoom
96
+ )
97
+ }
98
+
99
+ /// The offset that puts the top of a page at the top of the view.
100
+ func offset(atZoom zoom: CGFloat, pageTop top: CGFloat, keepingX x: CGFloat) -> CGPoint {
101
+ clamp(CGPoint(x: x, y: top * scale(atZoom: zoom)), atZoom: zoom)
102
+ }
103
+
104
+ /// What the viewport is looking at, given where the scroll view has arrived.
105
+ func place(_ viewport: PdfViewport, offset: CGPoint, zoom: CGFloat) {
106
+ viewport.place(scale: scale(atZoom: zoom), offsetX: -offset.x, offsetY: -offset.y)
107
+ }
108
+ }