@tobyt/expo-pdf-markup 0.0.0-next.20261121170125

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 (113) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/LICENSE +21 -0
  3. package/README.md +238 -0
  4. package/android/.editorconfig +2 -0
  5. package/android/build.gradle +33 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationGeometry.kt +85 -0
  8. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationHitTester.kt +76 -0
  9. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationModel.kt +41 -0
  10. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationRenderer.kt +254 -0
  11. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationSerializer.kt +239 -0
  12. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationsChangeEmitter.kt +31 -0
  13. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookPager.kt +66 -0
  14. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookTurnPolicy.kt +117 -0
  15. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ContinuousPdfView.kt +1107 -0
  16. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +116 -0
  17. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +317 -0
  18. package/android/src/main/java/dev/terhoeven/expopdfmarkup/TouchInterceptPolicy.kt +20 -0
  19. package/build/ExpoPdfMarkup.types.d.ts +193 -0
  20. package/build/ExpoPdfMarkup.types.d.ts.map +1 -0
  21. package/build/ExpoPdfMarkup.types.js +2 -0
  22. package/build/ExpoPdfMarkup.types.js.map +1 -0
  23. package/build/ExpoPdfMarkupModule.d.ts +2 -0
  24. package/build/ExpoPdfMarkupModule.d.ts.map +1 -0
  25. package/build/ExpoPdfMarkupModule.js +4 -0
  26. package/build/ExpoPdfMarkupModule.js.map +1 -0
  27. package/build/ExpoPdfMarkupModule.web.d.ts +2 -0
  28. package/build/ExpoPdfMarkupModule.web.d.ts.map +1 -0
  29. package/build/ExpoPdfMarkupModule.web.js +4 -0
  30. package/build/ExpoPdfMarkupModule.web.js.map +1 -0
  31. package/build/ExpoPdfMarkupView.d.ts +4 -0
  32. package/build/ExpoPdfMarkupView.d.ts.map +1 -0
  33. package/build/ExpoPdfMarkupView.js +20 -0
  34. package/build/ExpoPdfMarkupView.js.map +1 -0
  35. package/build/ExpoPdfMarkupView.web.d.ts +8 -0
  36. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -0
  37. package/build/ExpoPdfMarkupView.web.js +953 -0
  38. package/build/ExpoPdfMarkupView.web.js.map +1 -0
  39. package/build/index.d.ts +5 -0
  40. package/build/index.d.ts.map +1 -0
  41. package/build/index.js +5 -0
  42. package/build/index.js.map +1 -0
  43. package/build/parseAnnotations.d.ts +11 -0
  44. package/build/parseAnnotations.d.ts.map +1 -0
  45. package/build/parseAnnotations.js +49 -0
  46. package/build/parseAnnotations.js.map +1 -0
  47. package/build/pdfjs.d.ts +3 -0
  48. package/build/pdfjs.d.ts.map +1 -0
  49. package/build/pdfjs.js +8 -0
  50. package/build/pdfjs.js.map +1 -0
  51. package/build/pdfjs.web.d.ts +2 -0
  52. package/build/pdfjs.web.d.ts.map +1 -0
  53. package/build/pdfjs.web.js +2 -0
  54. package/build/pdfjs.web.js.map +1 -0
  55. package/build/web/annotationUtils.d.ts +54 -0
  56. package/build/web/annotationUtils.d.ts.map +1 -0
  57. package/build/web/annotationUtils.js +363 -0
  58. package/build/web/annotationUtils.js.map +1 -0
  59. package/build/web/bookMode.d.ts +77 -0
  60. package/build/web/bookMode.d.ts.map +1 -0
  61. package/build/web/bookMode.js +169 -0
  62. package/build/web/bookMode.js.map +1 -0
  63. package/build/web/layout.d.ts +8 -0
  64. package/build/web/layout.d.ts.map +1 -0
  65. package/build/web/layout.js +22 -0
  66. package/build/web/layout.js.map +1 -0
  67. package/build/web/types.d.ts +15 -0
  68. package/build/web/types.d.ts.map +1 -0
  69. package/build/web/types.js +2 -0
  70. package/build/web/types.js.map +1 -0
  71. package/expo-module.config.json +9 -0
  72. package/fixtures/annotations-v1-array.json +124 -0
  73. package/fixtures/annotations-v1.json +130 -0
  74. package/fixtures/ink-cleanup-expected-array.json +95 -0
  75. package/fixtures/ink-cleanup-expected-object.json +95 -0
  76. package/fixtures/ink-cleanup-input.json +99 -0
  77. package/ios/AnnotationModels.swift +417 -0
  78. package/ios/AnnotationSerializer.swift +407 -0
  79. package/ios/ExpoPdfMarkup.podspec +28 -0
  80. package/ios/ExpoPdfMarkupModule.swift +70 -0
  81. package/ios/ExpoPdfMarkupView+Book.swift +455 -0
  82. package/ios/ExpoPdfMarkupView+Ink.swift +168 -0
  83. package/ios/ExpoPdfMarkupView+Markup.swift +151 -0
  84. package/ios/ExpoPdfMarkupView+Move.swift +277 -0
  85. package/ios/ExpoPdfMarkupView.swift +385 -0
  86. package/ios/StampPDFAnnotation.swift +118 -0
  87. package/ios/Tests/AnnotationCoordinateTests.swift +424 -0
  88. package/ios/Tests/AnnotationModelTests.swift +178 -0
  89. package/ios/Tests/AnnotationSerializerTests.swift +486 -0
  90. package/ios/Tests/AreaMarkupTests.swift +279 -0
  91. package/ios/Tests/BookModeTests.swift +538 -0
  92. package/ios/Tests/ExpoPdfMarkupViewTests.swift +318 -0
  93. package/ios/Tests/RotatedAnnotationRenderingTests.swift +411 -0
  94. package/ios/Tests/StampPDFAnnotationTests.swift +128 -0
  95. package/ios/Tests/book-sample.pdf +207 -0
  96. package/ios/Tests/single-page.pdf +52 -0
  97. package/ios/Tests/test.pdf +0 -0
  98. package/metro.d.ts +5 -0
  99. package/metro.js +133 -0
  100. package/package.json +95 -0
  101. package/src/ExpoPdfMarkup.types.ts +185 -0
  102. package/src/ExpoPdfMarkupModule.ts +2 -0
  103. package/src/ExpoPdfMarkupModule.web.ts +2 -0
  104. package/src/ExpoPdfMarkupView.tsx +43 -0
  105. package/src/ExpoPdfMarkupView.web.tsx +1197 -0
  106. package/src/index.ts +4 -0
  107. package/src/parseAnnotations.ts +52 -0
  108. package/src/pdfjs.ts +8 -0
  109. package/src/pdfjs.web.ts +1 -0
  110. package/src/web/annotationUtils.ts +452 -0
  111. package/src/web/bookMode.ts +186 -0
  112. package/src/web/layout.ts +30 -0
  113. package/src/web/types.ts +15 -0
@@ -0,0 +1,254 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ import android.content.Context
4
+ import android.content.res.AssetManager
5
+ import android.graphics.Canvas
6
+ import android.graphics.DashPathEffect
7
+ import android.graphics.Paint
8
+ import android.graphics.Path
9
+ import android.graphics.RectF
10
+ import android.graphics.Typeface
11
+
12
+ object AnnotationRenderer {
13
+
14
+ fun drawAnnotations(
15
+ canvas: Canvas,
16
+ annotations: List<AnnotationModel>,
17
+ pageIndex: Int,
18
+ pageYOffset: Float,
19
+ renderScale: Float,
20
+ pageHeight: Int,
21
+ context: Context
22
+ ) {
23
+ for (annotation in annotations) {
24
+ if (annotation.page != pageIndex) continue
25
+ when (annotation.type) {
26
+ "ink" -> drawInk(canvas, annotation, pageYOffset, renderScale, pageHeight)
27
+
28
+ "highlight" -> drawHighlight(
29
+ canvas,
30
+ annotation,
31
+ pageYOffset,
32
+ renderScale,
33
+ pageHeight
34
+ )
35
+
36
+ "underline" -> drawUnderline(
37
+ canvas,
38
+ annotation,
39
+ pageYOffset,
40
+ renderScale,
41
+ pageHeight
42
+ )
43
+
44
+ "freeText", "text" -> drawFreeText(
45
+ canvas,
46
+ annotation,
47
+ pageYOffset,
48
+ renderScale,
49
+ pageHeight,
50
+ context
51
+ )
52
+
53
+ "stamp" -> drawStamp(
54
+ canvas,
55
+ annotation,
56
+ pageYOffset,
57
+ renderScale,
58
+ pageHeight
59
+ )
60
+ }
61
+ }
62
+ }
63
+
64
+ fun drawEditingAffordances(
65
+ canvas: Canvas,
66
+ annotations: List<AnnotationModel>,
67
+ pageIndex: Int,
68
+ pageYOffset: Float,
69
+ renderScale: Float,
70
+ pageHeight: Int,
71
+ currentScale: Float
72
+ ) {
73
+ val paint = Paint().apply {
74
+ color = 0xFF0A84FF.toInt()
75
+ strokeWidth = 2f / currentScale
76
+ style = Paint.Style.STROKE
77
+ isAntiAlias = true
78
+ pathEffect = DashPathEffect(floatArrayOf(10f / currentScale, 6f / currentScale), 0f)
79
+ }
80
+
81
+ for (annotation in annotations) {
82
+ if (annotation.page != pageIndex) continue
83
+ val bounds = AnnotationGeometry.outlineBounds(annotation) ?: continue
84
+ val left = bounds.x * renderScale
85
+ val top = (pageHeight - bounds.y - bounds.height) * renderScale + pageYOffset
86
+ val right = left + bounds.width * renderScale
87
+ val bottom = top + bounds.height * renderScale
88
+ canvas.drawRect(left, top, right, bottom, paint)
89
+ }
90
+ }
91
+
92
+ private fun drawInk(
93
+ canvas: Canvas,
94
+ annotation: AnnotationModel,
95
+ pageYOffset: Float,
96
+ renderScale: Float,
97
+ pageHeight: Int
98
+ ) {
99
+ val paths = annotation.paths ?: return
100
+ val paint = Paint().apply {
101
+ color = AnnotationSerializer.colorFromHex(annotation.color)
102
+ strokeWidth = (annotation.lineWidth ?: 2f) * renderScale
103
+ style = Paint.Style.STROKE
104
+ isAntiAlias = true
105
+ strokeCap = Paint.Cap.ROUND
106
+ strokeJoin = Paint.Join.ROUND
107
+ }
108
+ for (stroke in paths) {
109
+ if (stroke.isEmpty()) continue
110
+ val path = Path()
111
+ for ((i, pt) in stroke.withIndex()) {
112
+ val cx = pt.x * renderScale
113
+ val cy = (pageHeight - pt.y) * renderScale + pageYOffset
114
+ if (i == 0) path.moveTo(cx, cy) else path.lineTo(cx, cy)
115
+ }
116
+ canvas.drawPath(path, paint)
117
+ }
118
+ }
119
+
120
+ private fun drawHighlight(
121
+ canvas: Canvas,
122
+ annotation: AnnotationModel,
123
+ pageYOffset: Float,
124
+ renderScale: Float,
125
+ pageHeight: Int
126
+ ) {
127
+ val bounds = annotation.bounds ?: return
128
+ val alpha = annotation.alpha ?: 0.5f
129
+ val color = AnnotationSerializer.colorFromHex(annotation.color)
130
+ val paint = Paint().apply {
131
+ this.color = color
132
+ this.alpha = (alpha * 255).toInt()
133
+ style = Paint.Style.FILL
134
+ isAntiAlias = true
135
+ }
136
+ val left = bounds.x * renderScale
137
+ val top = (pageHeight - bounds.y - bounds.height) * renderScale + pageYOffset
138
+ val right = left + bounds.width * renderScale
139
+ val bottom = top + bounds.height * renderScale
140
+ canvas.drawRect(left, top, right, bottom, paint)
141
+ }
142
+
143
+ private fun drawUnderline(
144
+ canvas: Canvas,
145
+ annotation: AnnotationModel,
146
+ pageYOffset: Float,
147
+ renderScale: Float,
148
+ pageHeight: Int
149
+ ) {
150
+ val bounds = annotation.bounds ?: return
151
+ val paint = Paint().apply {
152
+ color = AnnotationSerializer.colorFromHex(annotation.color)
153
+ strokeWidth = 1f * renderScale
154
+ style = Paint.Style.STROKE
155
+ isAntiAlias = true
156
+ }
157
+ val left = bounds.x * renderScale
158
+ val bottom = (pageHeight - bounds.y) * renderScale + pageYOffset
159
+ val right = left + bounds.width * renderScale
160
+ canvas.drawLine(left, bottom, right, bottom, paint)
161
+ }
162
+
163
+ private fun drawFreeText(
164
+ canvas: Canvas,
165
+ annotation: AnnotationModel,
166
+ pageYOffset: Float,
167
+ renderScale: Float,
168
+ pageHeight: Int,
169
+ context: Context
170
+ ) {
171
+ val bounds = annotation.bounds ?: return
172
+ val text = annotation.contents ?: return
173
+ val paint = Paint().apply {
174
+ color = AnnotationSerializer.colorFromHex(annotation.color)
175
+ textSize = (annotation.fontSize ?: 16f) * renderScale
176
+ typeface = resolveTypeface(context, annotation.fontFamily)
177
+ isAntiAlias = true
178
+ }
179
+ val left = bounds.x * renderScale
180
+ val top = (pageHeight - bounds.y - bounds.height) * renderScale + pageYOffset
181
+ canvas.drawText(text, left, top + paint.textSize, paint)
182
+ }
183
+
184
+ private fun drawStamp(
185
+ canvas: Canvas,
186
+ annotation: AnnotationModel,
187
+ pageYOffset: Float,
188
+ renderScale: Float,
189
+ pageHeight: Int
190
+ ) {
191
+ val bounds = annotation.bounds ?: return
192
+ val text = annotation.text ?: return
193
+ val left = bounds.x * renderScale
194
+ val top = (pageHeight - bounds.y - bounds.height) * renderScale + pageYOffset
195
+ val right = left + bounds.width * renderScale
196
+ val bottom = top + bounds.height * renderScale
197
+ val rect = RectF(left, top, right, bottom)
198
+
199
+ val paint = Paint().apply {
200
+ color = AnnotationSerializer.colorFromHex(annotation.color)
201
+ textSize = rect.height() * 0.7f
202
+ textAlign = Paint.Align.CENTER
203
+ isAntiAlias = true
204
+ }
205
+ // Paint has no built-in middle-baseline; offset by (ascent + descent) / 2 to
206
+ // vertically center the glyph within rect.
207
+ val baselineY = rect.centerY() - (paint.descent() + paint.ascent()) / 2f
208
+ canvas.drawText(text, rect.centerX(), baselineY, paint)
209
+ }
210
+
211
+ /** Resolve a typeface the same way React Native text does when available, so
212
+ * expo-font loaded families are measured and rendered consistently with the
213
+ * rest of the app. */
214
+ fun resolveTypeface(context: Context, fontFamily: String?): Typeface {
215
+ if (fontFamily == null) return Typeface.DEFAULT
216
+ return resolveReactTypeface(fontFamily, context.assets)
217
+ ?: try {
218
+ Typeface.createFromAsset(context.assets, "fonts/$fontFamily.ttf")
219
+ } catch (_: Exception) {
220
+ Typeface.create(fontFamily, Typeface.NORMAL)
221
+ }
222
+ }
223
+
224
+ private fun resolveReactTypeface(fontFamily: String, assetManager: AssetManager): Typeface? {
225
+ val managerClasses = listOf(
226
+ "com.facebook.react.common.assets.ReactFontManager",
227
+ "com.facebook.react.views.text.ReactFontManager"
228
+ )
229
+
230
+ for (className in managerClasses) {
231
+ try {
232
+ val managerClass = Class.forName(className)
233
+ val getInstance = managerClass.getMethod("getInstance")
234
+ val manager = getInstance.invoke(null)
235
+ val getTypeface = managerClass.getMethod(
236
+ "getTypeface",
237
+ String::class.java,
238
+ Int::class.javaPrimitiveType,
239
+ AssetManager::class.java
240
+ )
241
+ return getTypeface.invoke(
242
+ manager,
243
+ fontFamily,
244
+ Typeface.NORMAL,
245
+ assetManager
246
+ ) as? Typeface
247
+ } catch (_: Exception) {
248
+ continue
249
+ }
250
+ }
251
+
252
+ return null
253
+ }
254
+ }
@@ -0,0 +1,239 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+
6
+ object AnnotationSerializer {
7
+
8
+ fun deserialize(json: String): AnnotationsData? {
9
+ return try {
10
+ val obj = JSONObject(json)
11
+ val version = obj.optInt("version", 1)
12
+ val arr = obj.optJSONArray("annotations") ?: return AnnotationsData(version)
13
+ val annotations = mutableListOf<AnnotationModel>()
14
+ for (i in 0 until arr.length()) {
15
+ parseAnnotation(arr.getJSONObject(i))?.let { annotations.add(it) }
16
+ }
17
+ AnnotationsData(version, annotations)
18
+ } catch (_: Exception) {
19
+ null
20
+ }
21
+ }
22
+
23
+ fun serialize(
24
+ data: AnnotationsData,
25
+ inkPointFormat: InkPointFormat = InkPointFormat.OBJECT
26
+ ): String {
27
+ val obj = JSONObject()
28
+ obj.put("version", data.version)
29
+ val arr = JSONArray()
30
+ for (annotation in data.annotations) {
31
+ arr.put(annotationToJson(annotation, inkPointFormat))
32
+ }
33
+ obj.put("annotations", arr)
34
+ return obj.toString()
35
+ }
36
+
37
+ fun colorFromHex(hex: String): Int {
38
+ val cleaned = hex.removePrefix("#")
39
+ return when (cleaned.length) {
40
+ 6 -> {
41
+ val rgb = cleaned.toLong(16).toInt()
42
+ (0xFF shl 24) or rgb
43
+ }
44
+
45
+ 8 -> {
46
+ val r = cleaned.substring(0, 2).toInt(16)
47
+ val g = cleaned.substring(2, 4).toInt(16)
48
+ val b = cleaned.substring(4, 6).toInt(16)
49
+ val a = cleaned.substring(6, 8).toInt(16)
50
+ (a shl 24) or (r shl 16) or (g shl 8) or b
51
+ }
52
+
53
+ else -> (0xFF shl 24) // fallback to opaque black
54
+ }
55
+ }
56
+
57
+ fun hexFromColor(color: Int): String {
58
+ val r = (color shr 16) and 0xFF
59
+ val g = (color shr 8) and 0xFF
60
+ val b = color and 0xFF
61
+ return "#%02X%02X%02X".format(r, g, b)
62
+ }
63
+
64
+ private fun parseAnnotation(obj: JSONObject): AnnotationModel? {
65
+ val id = obj.optString("id", "").ifEmpty { return null }
66
+ val type = obj.optString("type", "").ifEmpty { return null }
67
+ val page = obj.optInt("page", -1)
68
+ if (page < 0) return null
69
+ val color = obj.optString("color", "#000000")
70
+
71
+ return AnnotationModel(
72
+ id = id,
73
+ type = type,
74
+ page = page,
75
+ color = color,
76
+ lineWidth = optFloat(obj, "lineWidth"),
77
+ alpha = optFloat(obj, "alpha"),
78
+ paths = parsePaths(obj.optJSONArray("paths")),
79
+ bounds = parseBounds(obj.optJSONObject("bounds")),
80
+ contents = if (obj.has("contents")) obj.getString("contents") else null,
81
+ fontSize = optFloat(obj, "fontSize"),
82
+ fontFamily = if (obj.has("fontFamily")) obj.getString("fontFamily") else null,
83
+ createdAt = if (obj.has("createdAt")) obj.optDouble("createdAt") else null,
84
+ text = if (obj.has("text")) obj.getString("text") else null
85
+ )
86
+ }
87
+
88
+ private fun optFloat(obj: JSONObject, key: String): Float? =
89
+ if (obj.has(key)) obj.optDouble(key).toFloat() else null
90
+
91
+ private fun parsePaths(arr: JSONArray?): List<List<AnnotationPoint>>? {
92
+ arr ?: return null
93
+ val paths = mutableListOf<List<AnnotationPoint>>()
94
+ for (i in 0 until arr.length()) {
95
+ // A stroke that isn't an array is malformed and skipped; the rest still loads.
96
+ val stroke = arr.optJSONArray(i) ?: continue
97
+ val points = mutableListOf<AnnotationPoint>()
98
+ for (j in 0 until stroke.length()) {
99
+ readInkPoint(stroke.opt(j))?.let { points.add(it) }
100
+ }
101
+ paths.add(points)
102
+ }
103
+ return paths
104
+ }
105
+
106
+ /**
107
+ * Reads one ink point in object form (`{"x": …, "y": …}`) or array form (`[x, y]`).
108
+ * Anything else is malformed and returns null, so the caller skips just that point.
109
+ */
110
+ private fun readInkPoint(value: Any?): AnnotationPoint? {
111
+ val (x, y) = when (value) {
112
+ is JSONObject -> value.opt("x") to value.opt("y")
113
+ is JSONArray -> if (value.length() == 2) value.opt(0) to value.opt(1) else return null
114
+ else -> return null
115
+ }
116
+ val xd = finiteNumber(x) ?: return null
117
+ val yd = finiteNumber(y) ?: return null
118
+ return AnnotationPoint(xd.toFloat(), yd.toFloat())
119
+ }
120
+
121
+ private fun finiteNumber(value: Any?): Double? =
122
+ (value as? Number)?.toDouble()?.takeIf { it.isFinite() }
123
+
124
+ private fun parseBounds(obj: JSONObject?): AnnotationBounds? {
125
+ obj ?: return null
126
+ return AnnotationBounds(
127
+ x = obj.getDouble("x").toFloat(),
128
+ y = obj.getDouble("y").toFloat(),
129
+ width = obj.getDouble("width").toFloat(),
130
+ height = obj.getDouble("height").toFloat()
131
+ )
132
+ }
133
+
134
+ private fun annotationToJson(
135
+ model: AnnotationModel,
136
+ inkPointFormat: InkPointFormat
137
+ ): JSONObject {
138
+ val obj = JSONObject()
139
+ obj.put("id", model.id)
140
+ obj.put("type", model.type)
141
+ obj.put("page", model.page)
142
+ obj.put("color", model.color)
143
+ model.lineWidth?.let { obj.put("lineWidth", it.toDouble()) }
144
+ model.alpha?.let { obj.put("alpha", it.toDouble()) }
145
+ // Ink annotations always carry `paths`, even when empty: the JS `Annotation` type
146
+ // declares it non-optional, so omitting the key crashes consumers that dereference it.
147
+ // Only ink points are cleaned up and follow the ink point format; any other paths are
148
+ // written as they always were.
149
+ if (model.type == "ink") {
150
+ obj.put("paths", inkPathsToJson(model.paths ?: emptyList(), inkPointFormat))
151
+ } else {
152
+ model.paths?.let { obj.put("paths", rawPathsToJson(it)) }
153
+ }
154
+ model.bounds?.let { obj.put("bounds", boundsToJson(it)) }
155
+ model.contents?.let { obj.put("contents", it) }
156
+ model.fontSize?.let { obj.put("fontSize", it.toDouble()) }
157
+ model.fontFamily?.let { obj.put("fontFamily", it) }
158
+ model.createdAt?.let { obj.put("createdAt", it) }
159
+ model.text?.let { obj.put("text", it) }
160
+ return obj
161
+ }
162
+
163
+ /**
164
+ * Writes ink strokes cleaned up: every coordinate rounded to 0.1 pt, consecutive duplicate
165
+ * points (after rounding) dropped, and a stroke that collapses from 2+ points to one kept
166
+ * as two identical points so it still draws as a dot. In-memory points are untouched.
167
+ * Each point is written in object form (`{"x": …, "y": …}`) or array form (`[x, y]`).
168
+ */
169
+ private fun inkPathsToJson(
170
+ paths: List<List<AnnotationPoint>>,
171
+ inkPointFormat: InkPointFormat
172
+ ): JSONArray {
173
+ val writePoint: (Long, Long) -> Any = when (inkPointFormat) {
174
+ InkPointFormat.OBJECT -> { x, y ->
175
+ JSONObject().put("x", tenthsToJsonNumber(x)).put("y", tenthsToJsonNumber(y))
176
+ }
177
+
178
+ InkPointFormat.ARRAY -> { x, y ->
179
+ JSONArray().put(tenthsToJsonNumber(x)).put(tenthsToJsonNumber(y))
180
+ }
181
+ }
182
+ val arr = JSONArray()
183
+ for (stroke in paths) {
184
+ val strokeArr = JSONArray()
185
+ for ((x, y) in cleanUpStroke(stroke)) strokeArr.put(writePoint(x, y))
186
+ arr.put(strokeArr)
187
+ }
188
+ return arr
189
+ }
190
+
191
+ /** Writes paths of a non-ink annotation unchanged, each point in object form. */
192
+ private fun rawPathsToJson(paths: List<List<AnnotationPoint>>): JSONArray {
193
+ val arr = JSONArray()
194
+ for (stroke in paths) {
195
+ val strokeArr = JSONArray()
196
+ for (pt in stroke) {
197
+ strokeArr.put(JSONObject().put("x", pt.x.toDouble()).put("y", pt.y.toDouble()))
198
+ }
199
+ arr.put(strokeArr)
200
+ }
201
+ return arr
202
+ }
203
+
204
+ /** Rounds a stroke to whole tenths of a point and drops consecutive duplicates. */
205
+ private fun cleanUpStroke(stroke: List<AnnotationPoint>): List<Pair<Long, Long>> {
206
+ val kept = mutableListOf<Pair<Long, Long>>()
207
+ for (pt in stroke) {
208
+ val rounded = toTenths(pt.x) to toTenths(pt.y)
209
+ if (kept.lastOrNull() != rounded) kept.add(rounded)
210
+ }
211
+ if (stroke.size >= 2 && kept.size == 1) kept.add(kept[0])
212
+ return kept
213
+ }
214
+
215
+ /**
216
+ * Nearest whole number of tenths, rounding the Double product with ties away from zero.
217
+ * The Float is widened to Double first; `kotlin.math.round` is half-even, so it isn't used.
218
+ */
219
+ private fun toTenths(value: Float): Long {
220
+ val scaled = value.toDouble() * 10
221
+ return (Math.signum(scaled) * Math.round(Math.abs(scaled))).toLong()
222
+ }
223
+
224
+ /**
225
+ * Whole numbers go in as Long so they print without `.0` (and negative zero as `0`);
226
+ * anything else is n / 10.0, whose shortest decimal has a single digit after the point.
227
+ */
228
+ private fun tenthsToJsonNumber(tenths: Long): Number =
229
+ if (tenths % 10 == 0L) tenths / 10 else tenths / 10.0
230
+
231
+ private fun boundsToJson(bounds: AnnotationBounds): JSONObject {
232
+ val obj = JSONObject()
233
+ obj.put("x", bounds.x.toDouble())
234
+ obj.put("y", bounds.y.toDouble())
235
+ obj.put("width", bounds.width.toDouble())
236
+ obj.put("height", bounds.height.toDouble())
237
+ return obj
238
+ }
239
+ }
@@ -0,0 +1,31 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ /**
4
+ * Reads the view's annotation set when it is loaded, and writes it after an edit, handing the
5
+ * JSON to [emit] (the view's `onAnnotationsChanged`). Loading never emits.
6
+ */
7
+ class AnnotationsChangeEmitter(private val emit: (String) -> Unit) {
8
+ /** Applies from the next write; setting it writes nothing by itself. */
9
+ var inkPointFormat: InkPointFormat = InkPointFormat.OBJECT
10
+
11
+ fun annotationsChanged(annotations: List<AnnotationModel>) {
12
+ emit(
13
+ AnnotationSerializer.serialize(
14
+ AnnotationsData(version = 1, annotations = annotations),
15
+ inkPointFormat
16
+ )
17
+ )
18
+ }
19
+
20
+ /**
21
+ * Reads an annotation set given to the view, keeping the last annotation with each id.
22
+ * Returns an empty list for no set, or null when [json] can't be read (keep what is shown).
23
+ * Writes nothing.
24
+ */
25
+ fun annotationsLoaded(json: String?): List<AnnotationModel>? {
26
+ if (json.isNullOrEmpty()) return emptyList()
27
+ val data = AnnotationSerializer.deserialize(json) ?: return null
28
+ val seen = mutableSetOf<String>()
29
+ return data.annotations.reversed().filter { seen.add(it.id) }.reversed()
30
+ }
31
+ }
@@ -0,0 +1,66 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ /**
4
+ * Which page book mode shows, and how a turn moves between pages. Pure Kotlin
5
+ * so the turn rules can be tested in the JVM; the view animates whatever
6
+ * [turn] returns and calls [finishSlide] when the slide has landed.
7
+ */
8
+ class BookPager(private val onPageChanged: (page: Int) -> Unit) {
9
+ sealed interface Turn {
10
+ data class Slide(val from: Int, val to: Int, val direction: BookTurnPolicy.Direction) : Turn
11
+
12
+ /** No page that way: nudge towards [direction] and spring back. Nothing wraps round. */
13
+ data class Bounce(val direction: BookTurnPolicy.Direction) : Turn
14
+ }
15
+
16
+ var pageCount = 0
17
+ private set
18
+ var currentPage = 0
19
+ private set
20
+
21
+ private var inFlight: Turn.Slide? = null
22
+
23
+ /** True while a slide has started but not landed. */
24
+ val isSliding: Boolean get() = inFlight != null
25
+
26
+ /**
27
+ * Sets the document and page without reporting a change, clamping [page]
28
+ * into the document. Used on load, mode switch, rotation and resize.
29
+ */
30
+ fun reset(pageCount: Int, page: Int) {
31
+ inFlight = null
32
+ this.pageCount = maxOf(0, pageCount)
33
+ currentPage = page.coerceIn(0, maxOf(0, this.pageCount - 1))
34
+ }
35
+
36
+ /**
37
+ * Starts a turn. A slide already in flight lands first, so rapid turns
38
+ * each count and each report once. Returns [Turn.Bounce] at either end.
39
+ */
40
+ fun turn(direction: BookTurnPolicy.Direction): Turn {
41
+ finishSlide()
42
+ val target = currentPage + direction.delta
43
+ if (target !in 0 until pageCount) return Turn.Bounce(direction)
44
+ val slide = Turn.Slide(currentPage, target, direction)
45
+ inFlight = slide
46
+ return slide
47
+ }
48
+
49
+ /** Shows [page] straight away (the `page` prop), cancelling any slide. */
50
+ fun jumpTo(page: Int): Boolean {
51
+ if (page !in 0 until pageCount) return false
52
+ inFlight = null
53
+ if (page == currentPage) return false
54
+ currentPage = page
55
+ onPageChanged(page)
56
+ return true
57
+ }
58
+
59
+ /** Lands the slide in flight, if any, and reports the new page. */
60
+ fun finishSlide() {
61
+ val slide = inFlight ?: return
62
+ inFlight = null
63
+ currentPage = slide.to
64
+ onPageChanged(currentPage)
65
+ }
66
+ }