@blotch/angular-lynx-native 22.3.1 → 22.3.2

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 (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +140 -1
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +35 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +51 -2
  35. package/templates/android/app/src/main/AndroidManifest.xml +14 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -11,11 +11,13 @@ import com.lynx.react.bridge.JavaOnlyMap
11
11
  import com.lynx.react.bridge.ReadableArray
12
12
  import com.lynx.react.bridge.ReadableMap
13
13
  import com.lynx.react.bridge.ReadableType
14
- import java.io.ByteArrayOutputStream
15
14
  import java.lang.ref.WeakReference
16
15
  import java.nio.ByteBuffer
17
16
  import java.nio.ByteOrder
17
+ // angular-lynx:webgl
18
+ import java.io.ByteArrayOutputStream
18
19
  import kotlin.math.roundToInt
20
+ // /angular-lynx:webgl
19
21
 
20
22
  /**
21
23
  * `<canvas>` with WebGL2 for the AngularLynx runtime: the `AngularLynxWebGL`
@@ -32,8 +34,20 @@ import kotlin.math.roundToInt
32
34
  * thread's JavaScript runs, which the shell runs off the UI thread.
33
35
  */
34
36
  class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
37
+ // The WebGL2 context's lines, between the `angular-lynx:webgl` markers,
38
+ // go with WebGLContext.kt and WebGLOps.kt from an app that draws on a
39
+ // canvas only in 2D (@blotch/angular-lynx-native's features.ts): the
40
+ // runtime then has no WebGL2 context to call them (issue #847).
41
+ // angular-lynx:webgl
35
42
  private val contexts = HashMap<Int, WebGLContext>()
43
+ // /angular-lynx:webgl
44
+ private val contexts2D = HashMap<Int, Canvas2DContext>()
45
+ private val bitmapRenderers = HashMap<Int, BitmapRendererContext>()
46
+
47
+ /** The 2D contexts' gradients and patterns, which any of them can paint with. */
48
+ private val canvas2DObjects = HashMap<Int, Any>()
36
49
 
50
+ // angular-lynx:webgl
37
51
  @LynxMethod
38
52
  fun create(contextId: Int, canvasId: String, attributes: ReadableMap?): JavaOnlyMap {
39
53
  contexts.remove(contextId)?.destroy()
@@ -60,13 +74,42 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
60
74
  context.destroy()
61
75
  return true
62
76
  }
77
+ // /angular-lynx:webgl
78
+
79
+ /**
80
+ * The size of the frame a `<video>` shows (VideoUI), by its `video-id`:
81
+ * the runtime's videoWidth and videoHeight, and the size a canvas reads
82
+ * it at. 0 by 0 before its first frame.
83
+ */
84
+ @LynxMethod
85
+ fun videoSize(videoId: String?): JavaOnlyMap {
86
+ val video = videoId?.let { CanvasRegistry.context(it) } as? VideoUI
87
+ val (width, height) = video?.frameSize() ?: (0 to 0)
88
+ return JavaOnlyMap.from(mapOf("width" to width, "height" to height))
89
+ }
63
90
 
64
91
  @LynxMethod
65
92
  fun decodeImage(imageId: Int, bytes: ReadableArray?, options: ReadableMap?): JavaOnlyMap {
66
- val image = bytes?.let { decode(bytesFromWords(it), options) }
67
- ?: return JavaOnlyMap.from(mapOf("width" to 0, "height" to 0, "error" to "The data is not an image Android can decode"))
68
- DecodedImages.put(imageId, image)
69
- return JavaOnlyMap.from(mapOf("width" to image.width, "height" to image.height))
93
+ return try {
94
+ val image = bytes?.let {
95
+ if (hasCrop(options)) {
96
+ // Cropped before it's resized or flipped, as the HTML
97
+ // spec orders it: the file is decoded as it is, with the
98
+ // alpha the bitmap asks for, so the copy needn't convert
99
+ // it, and then cut.
100
+ val premultiply = options?.optString("premultiplyAlpha") == "premultiply"
101
+ decode(bytesFromWords(it), null, premultiply)?.let { decoded -> pixelsOfSnapshot(decoded, options) }
102
+ } else {
103
+ decode(bytesFromWords(it), options)
104
+ }
105
+ } ?: return imageFailed("The data is not an image Android can decode")
106
+ keptImage(imageId, image, options)
107
+ } catch (_: OutOfMemoryError) {
108
+ imageFailed("The image is too large to decode")
109
+ } catch (_: IllegalArgumentException) {
110
+ // A crop or a resize larger than a Bitmap or a buffer can hold.
111
+ imageFailed("The image is too large to decode")
112
+ }
70
113
  }
71
114
 
72
115
  @LynxMethod
@@ -75,6 +118,185 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
75
118
  return true
76
119
  }
77
120
 
121
+ /**
122
+ * An ImageBitmap of a canvas, for createImageBitmap() and
123
+ * OffscreenCanvas.transferToImageBitmap(): a copy of the canvas's pixels
124
+ * now, kept under [imageId] as a decoded image is, so texture uploads and
125
+ * drawImage read it as they read one. The pixels never cross the bridge.
126
+ * [options] holds createImageBitmap's options, the canvas's size (a
127
+ * canvas with no context is transparent black, as in a browser) and
128
+ * `transfer`, which clears the canvas after it's read. `{ width, height }`,
129
+ * or `{ error }`.
130
+ */
131
+ @LynxMethod
132
+ fun imageFromCanvas(imageId: Int, canvasId: String?, options: ReadableMap?): JavaOnlyMap {
133
+ val context = canvasId?.let { CanvasRegistry.context(it) }
134
+ return try {
135
+ val snapshot = if (context != null) {
136
+ // A context that has pixels but couldn't read them is a
137
+ // failure, not a blank canvas.
138
+ context.snapshot() ?: return imageFailed("The canvas's pixels could not be read")
139
+ } else {
140
+ val width = options?.optInt("width") ?: 0
141
+ val height = options?.optInt("height") ?: 0
142
+ if (width <= 0 || height <= 0) return imageFailed("The canvas has no pixels")
143
+ val bytes = rgbaByteCount(width, height) ?: return imageFailed("The canvas is too large to copy")
144
+ DecodedImage(ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()), width, height, true)
145
+ }
146
+ if (options?.optBool("transfer") == true) context?.clearForTransfer()
147
+ keptImage(imageId, pixelsOfSnapshot(snapshot, options), options)
148
+ } catch (_: OutOfMemoryError) {
149
+ imageFailed("The canvas is too large to copy")
150
+ } catch (_: IllegalArgumentException) {
151
+ // A crop or a resize larger than a Bitmap or a buffer can hold.
152
+ imageFailed("The canvas is too large to copy")
153
+ }
154
+ }
155
+
156
+ /**
157
+ * An ImageBitmap of an image the module keeps (an ImageBitmap's, or an
158
+ * `<img>`'s), for createImageBitmap(): a copy of its pixels with
159
+ * createImageBitmap's options, so neither the pixels nor the file cross
160
+ * the bridge again. `{ width, height, cropped }`, or `{ error }`.
161
+ */
162
+ @LynxMethod
163
+ fun imageFromImage(imageId: Int, sourceId: Int, options: ReadableMap?): JavaOnlyMap {
164
+ val source = DecodedImages.get(sourceId) ?: return imageFailed("The image is gone")
165
+ return try {
166
+ // pixelsOfSnapshot works on the pixels it's given, and these are
167
+ // the source's own, which stay as they are. A crop copies them
168
+ // first, so only the part it keeps is read.
169
+ keptImage(imageId, pixelsOfSnapshot(if (hasCrop(options)) source else source.copy(), options), options)
170
+ } catch (_: OutOfMemoryError) {
171
+ imageFailed("The image is too large to copy")
172
+ } catch (_: IllegalArgumentException) {
173
+ imageFailed("The image is too large to copy")
174
+ }
175
+ }
176
+
177
+ /**
178
+ * An ImageBitmap of an ImageData, for createImageBitmap(): its RGBA
179
+ * bytes, straight, rows top to bottom, sent as words (see
180
+ * [bytesFromWords]), with its size in [options], and createImageBitmap's
181
+ * options applied. `{ width, height, cropped }`, or `{ error }`.
182
+ */
183
+ @LynxMethod
184
+ fun imageFromPixels(imageId: Int, bytes: ReadableArray?, options: ReadableMap?): JavaOnlyMap {
185
+ val width = options?.optInt("width") ?: 0
186
+ val height = options?.optInt("height") ?: 0
187
+ return try {
188
+ val pixels = bytes?.let { bytesFromWords(it) }
189
+ if (pixels == null || width <= 0 || height <= 0 || rgbaByteCount(width, height) != pixels.remaining()) {
190
+ return imageFailed("The pixels don't fill the image")
191
+ }
192
+ keptImage(imageId, pixelsOfSnapshot(DecodedImage(pixels, width, height, false), options), options)
193
+ } catch (_: OutOfMemoryError) {
194
+ imageFailed("The image is too large to copy")
195
+ } catch (_: IllegalArgumentException) {
196
+ imageFailed("The image is too large to copy")
197
+ }
198
+ }
199
+
200
+ private fun imageFailed(message: String) =
201
+ JavaOnlyMap.from(mapOf("width" to 0, "height" to 0, "error" to message))
202
+
203
+ /**
204
+ * Keeps a new ImageBitmap's pixels under the id the runtime gave it, and
205
+ * answers its size and, when it was asked for, that the crop was
206
+ * applied: a shell from before cropping leaves `cropped` out, so the
207
+ * runtime can tell it would get all of the source.
208
+ */
209
+ private fun keptImage(imageId: Int, image: DecodedImage, options: ReadableMap?): JavaOnlyMap {
210
+ DecodedImages.put(imageId, image)
211
+ return JavaOnlyMap.from(mapOf("width" to image.width, "height" to image.height, "cropped" to hasCrop(options)))
212
+ }
213
+
214
+ /**
215
+ * Whether createImageBitmap() asked for part of the source (its `sx, sy,
216
+ * sw, sh`), which the runtime sends as cropX, cropY, cropWidth and
217
+ * cropHeight, the sizes made positive.
218
+ */
219
+ private fun hasCrop(options: ReadableMap?): Boolean =
220
+ options != null && options.optLong("cropWidth") > 0 && options.optLong("cropHeight") > 0
221
+
222
+ /**
223
+ * The part of [image] createImageBitmap()'s crop rectangle covers, the
224
+ * rectangle's size: what it covers outside the image is transparent
225
+ * black, as the HTML spec has it, and the rest keeps its alpha as it
226
+ * was. The rows are copied into a new buffer; the image is only read.
227
+ */
228
+ private fun cropped(image: DecodedImage, options: ReadableMap): DecodedImage {
229
+ // In Long: a corner near a Web IDL long's end, plus a side, passes an Int's.
230
+ val x = options.optLong("cropX")
231
+ val y = options.optLong("cropY")
232
+ val width = options.optLong("cropWidth").toInt()
233
+ val height = options.optLong("cropHeight").toInt()
234
+ val bytes = rgbaByteCount(width, height) ?: throw IllegalArgumentException("The crop rectangle is too large")
235
+ val out = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder())
236
+ // The columns and rows the rectangle shares with the image.
237
+ val left = maxOf(x, 0L)
238
+ val right = minOf(x + width, image.width.toLong())
239
+ val top = maxOf(y, 0L)
240
+ val bottom = minOf(y + height, image.height.toLong())
241
+ if (left < right && top < bottom) {
242
+ // A view of its own, so the image's buffer keeps its position.
243
+ val from = image.pixels.duplicate()
244
+ val row = ByteArray(((right - left) * 4).toInt())
245
+ for (r in top until bottom) {
246
+ from.position(((r * image.width + left) * 4).toInt())
247
+ from.get(row)
248
+ out.position((((r - y) * width + (left - x)) * 4).toInt())
249
+ out.put(row)
250
+ }
251
+ }
252
+ out.rewind()
253
+ return DecodedImage(out, width, height, image.premultiplied)
254
+ }
255
+
256
+ /**
257
+ * Pixels of the shell's own (a canvas's snapshot, a copy of an image it
258
+ * keeps, an ImageData's) as createImageBitmap's options ask, for a new
259
+ * ImageBitmap: cropped first, as the HTML spec orders it, so a resize and
260
+ * a flip apply to the part the crop rectangle names. Without a resize, the
261
+ * bytes are flipped and premultiplied or divided as asked, exactly, in
262
+ * place; a resize scales them, as a decode does.
263
+ */
264
+ private fun pixelsOfSnapshot(source: DecodedImage, options: ReadableMap?): DecodedImage {
265
+ // hasCrop() is false without options; the check is for the compiler.
266
+ val snapshot = if (options != null && hasCrop(options)) cropped(source, options) else source
267
+ val premultiply = options?.optString("premultiplyAlpha") == "premultiply"
268
+ val resizeWidth = options?.optInt("resizeWidth") ?: 0
269
+ val resizeHeight = options?.optInt("resizeHeight") ?: 0
270
+ var pixels = snapshot.pixels
271
+ var width = snapshot.width
272
+ var height = snapshot.height
273
+ pixels.rewind()
274
+ if (resizeWidth > 0 || resizeHeight > 0) {
275
+ // Scaling draws, which Android only does on premultiplied bitmaps.
276
+ if (!snapshot.premultiplied) premultiply(pixels)
277
+ val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
278
+ // ARGB_8888 is R, G, B, A in memory, premultiplied.
279
+ bitmap.copyPixelsFromBuffer(pixels)
280
+ width = resizedSide(resizeWidth, snapshot.width, resizeHeight, snapshot.height)
281
+ height = resizedSide(resizeHeight, snapshot.height, resizeWidth, snapshot.width)
282
+ val bytes = rgbaByteCount(width, height) ?: throw IllegalArgumentException("The resize is too large")
283
+ val scaled = Bitmap.createScaledBitmap(bitmap, width, height, true)
284
+ pixels = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder())
285
+ scaled.copyPixelsToBuffer(pixels)
286
+ pixels.rewind()
287
+ if (scaled !== bitmap) scaled.recycle()
288
+ bitmap.recycle()
289
+ if (!premultiply) unpremultiply(pixels)
290
+ } else if (premultiply && !snapshot.premultiplied) {
291
+ premultiply(pixels)
292
+ } else if (!premultiply && snapshot.premultiplied) {
293
+ unpremultiply(pixels)
294
+ }
295
+ if (options?.optString("imageOrientation") == "flipY") flipRows(pixels, width * 4, height)
296
+ return DecodedImage(pixels, width, height, premultiply)
297
+ }
298
+
299
+ // angular-lynx:webgl
78
300
  /**
79
301
  * The drawing buffer as an image file, for canvas.toBlob() and
80
302
  * toDataURL(): `{ base64, type }`, or `{ error }`. [options] holds the
@@ -115,8 +337,6 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
115
337
  }
116
338
  }
117
339
 
118
- private fun encodeFailed(message: String) = JavaOnlyMap.from(mapOf("error" to message))
119
-
120
340
  /**
121
341
  * Encodes RGBA pixels, rows bottom to top, as a PNG or JPEG file.
122
342
  */
@@ -163,22 +383,169 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
163
383
  bitmap.recycle()
164
384
  }
165
385
  }
386
+ // /angular-lynx:webgl
387
+
388
+ private fun encodeFailed(message: String) = JavaOnlyMap.from(mapOf("error" to message))
389
+
390
+ /** A 2D context for the canvas (see Canvas2DContext): `{ ok }`, or `{ ok: false, error }`. */
391
+ @LynxMethod
392
+ fun create2D(contextId: Int, canvasId: String, attributes: ReadableMap?): JavaOnlyMap {
393
+ destroy2D(contextId)
394
+ return try {
395
+ val context = Canvas2DContext(canvasId, attributes, canvas2DObjects)
396
+ contexts2D[contextId] = context
397
+ CanvasRegistry.setContext(canvasId, context)
398
+ JavaOnlyMap.from(mapOf("ok" to true))
399
+ } catch (_: OutOfMemoryError) {
400
+ JavaOnlyMap.from(mapOf("ok" to false, "error" to "The canvas is too large for its bitmap"))
401
+ }
402
+ }
403
+
404
+ @LynxMethod
405
+ fun run2D(contextId: Int, commands: ReadableArray?): JavaOnlyArray {
406
+ val context = contexts2D[contextId] ?: return JavaOnlyArray()
407
+ return context.run(commands ?: return JavaOnlyArray())
408
+ }
409
+
410
+ @LynxMethod
411
+ fun destroy2D(contextId: Int): Boolean {
412
+ val context = contexts2D.remove(contextId) ?: return true
413
+ if (CanvasRegistry.context(context.canvasId) === context) CanvasRegistry.setContext(context.canvasId, null)
414
+ context.destroy()
415
+ return true
416
+ }
417
+
418
+ /**
419
+ * Frees a gradient or pattern, which every 2D context in the LynxView
420
+ * shares, whether or not the context that made it is still there.
421
+ */
422
+ @LynxMethod
423
+ fun release2D(objectId: Int): Boolean {
424
+ canvas2DObjects.remove(objectId)
425
+ return true
426
+ }
427
+
428
+ /** The bitmap as an image file, for canvas.toBlob() and toDataURL(). */
429
+ @LynxMethod
430
+ fun encode2D(contextId: Int, options: ReadableMap?): JavaOnlyMap {
431
+ val context = contexts2D[contextId] ?: return encodeFailed("The canvas has no 2D context")
432
+ val jpeg = options?.optString("type") == "image/jpeg"
433
+ val quality = if (options != null && options.hasKey("quality") && options.getType("quality") in NUMBER_TYPES) {
434
+ options.getDouble("quality")
435
+ } else {
436
+ 0.92
437
+ }
438
+ return try {
439
+ val file = context.encode(jpeg, quality) ?: return encodeFailed("The canvas couldn't be encoded")
440
+ JavaOnlyMap.from(
441
+ mapOf(
442
+ "base64" to Base64.encodeToString(file, Base64.NO_WRAP),
443
+ "type" to if (jpeg) "image/jpeg" else "image/png",
444
+ ),
445
+ )
446
+ } catch (_: OutOfMemoryError) {
447
+ encodeFailed("The canvas is too large to encode")
448
+ }
449
+ }
450
+
451
+ /**
452
+ * A bitmaprenderer context for the canvas (see BitmapRendererContext),
453
+ * showing a blank canvas of the `width` and `height` in [attributes]:
454
+ * `{ ok }`.
455
+ */
456
+ @LynxMethod
457
+ fun createBitmapRenderer(contextId: Int, canvasId: String, attributes: ReadableMap?): JavaOnlyMap {
458
+ destroyBitmapRenderer(contextId)
459
+ val context = BitmapRendererContext(canvasId, attributes)
460
+ bitmapRenderers[contextId] = context
461
+ CanvasRegistry.setContext(canvasId, context)
462
+ return JavaOnlyMap.from(mapOf("ok" to true))
463
+ }
464
+
465
+ /**
466
+ * transferFromImageBitmap(): shows the decoded image [imageId] in the
467
+ * canvas, which owns it from then on, or a blank canvas of [width] by
468
+ * [height] for an id of 0. The image leaves DecodedImages even when the
469
+ * context has gone, as the runtime's bitmap is detached either way and
470
+ * nothing else would free it. `{ ok }`, or `{ ok: false, error }`.
471
+ */
472
+ @LynxMethod
473
+ fun transferToBitmapRenderer(contextId: Int, imageId: Int, width: Int, height: Int): JavaOnlyMap {
474
+ val image = if (imageId != 0) {
475
+ val taken = DecodedImages.get(imageId)
476
+ DecodedImages.remove(imageId)
477
+ taken ?: return transferFailed("The ImageBitmap's pixels are gone")
478
+ } else {
479
+ null
480
+ }
481
+ val context = bitmapRenderers[contextId] ?: return transferFailed("The canvas has no bitmaprenderer context")
482
+ return try {
483
+ if (image != null) context.show(image) else context.showBlank(width, height)
484
+ JavaOnlyMap.from(mapOf("ok" to true))
485
+ } catch (_: OutOfMemoryError) {
486
+ transferFailed("The ImageBitmap is too large to show")
487
+ }
488
+ }
489
+
490
+ private fun transferFailed(message: String) = JavaOnlyMap.from(mapOf("ok" to false, "error" to message))
491
+
492
+ @LynxMethod
493
+ fun destroyBitmapRenderer(contextId: Int): Boolean {
494
+ val context = bitmapRenderers.remove(contextId) ?: return true
495
+ if (CanvasRegistry.context(context.canvasId) === context) CanvasRegistry.setContext(context.canvasId, null)
496
+ context.destroy()
497
+ return true
498
+ }
499
+
500
+ /** What the canvas shows as an image file, for canvas.toBlob() and toDataURL(). */
501
+ @LynxMethod
502
+ fun encodeBitmapRenderer(contextId: Int, options: ReadableMap?): JavaOnlyMap {
503
+ val context = bitmapRenderers[contextId] ?: return encodeFailed("The canvas has no bitmaprenderer context")
504
+ val jpeg = options?.optString("type") == "image/jpeg"
505
+ val quality = if (options != null && options.hasKey("quality") && options.getType("quality") in NUMBER_TYPES) {
506
+ options.getDouble("quality")
507
+ } else {
508
+ 0.92
509
+ }
510
+ return try {
511
+ val file = context.encode(jpeg, quality) ?: return encodeFailed("The canvas couldn't be encoded")
512
+ JavaOnlyMap.from(
513
+ mapOf(
514
+ "base64" to Base64.encodeToString(file, Base64.NO_WRAP),
515
+ "type" to if (jpeg) "image/jpeg" else "image/png",
516
+ ),
517
+ )
518
+ } catch (_: OutOfMemoryError) {
519
+ encodeFailed("The canvas is too large to encode")
520
+ }
521
+ }
166
522
 
167
523
  override fun destroy() {
524
+ // angular-lynx:webgl
168
525
  for (context in contexts.values) context.destroy()
169
526
  contexts.clear()
527
+ // /angular-lynx:webgl
528
+ for (context in contexts2D.values) context.destroy()
529
+ contexts2D.clear()
530
+ for (context in bitmapRenderers.values) context.destroy()
531
+ bitmapRenderers.clear()
532
+ canvas2DObjects.clear()
170
533
  super.destroy()
171
534
  }
172
535
 
173
536
  /**
174
537
  * Decodes an image file to RGBA bytes, as createImageBitmap's options ask:
175
538
  * `imageOrientation: 'flipY'` flips it, `premultiplyAlpha: 'premultiply'`
176
- * premultiplies it (otherwise it's kept straight), and
539
+ * premultiplies it (otherwise it's kept straight; [premultiply] says so
540
+ * instead, for a file decoded to be cropped), and
177
541
  * `resizeWidth`/`resizeHeight` scale it.
178
542
  */
179
- private fun decode(bytes: ByteBuffer, options: ReadableMap?): DecodedImage? {
543
+ private fun decode(
544
+ bytes: ByteBuffer,
545
+ options: ReadableMap?,
546
+ premultiply: Boolean = options?.optString("premultiplyAlpha") == "premultiply",
547
+ ): DecodedImage? {
180
548
  val array = ByteArray(bytes.remaining()).also { bytes.get(it) }
181
- val premultiply = options?.optString("premultiplyAlpha") == "premultiply"
182
549
  val resizeWidth = options?.optInt("resizeWidth") ?: 0
183
550
  val resizeHeight = options?.optInt("resizeHeight") ?: 0
184
551
  val resize = resizeWidth > 0 || resizeHeight > 0
@@ -190,8 +557,8 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
190
557
  }
191
558
  var bitmap = BitmapFactory.decodeByteArray(array, 0, array.size, decodeOptions) ?: return null
192
559
  if (resize) {
193
- val width = if (resizeWidth > 0) resizeWidth else maxOf(1, bitmap.width * resizeHeight / bitmap.height)
194
- val height = if (resizeHeight > 0) resizeHeight else maxOf(1, bitmap.height * resizeWidth / bitmap.width)
560
+ val width = resizedSide(resizeWidth, bitmap.width, resizeHeight, bitmap.height)
561
+ val height = resizedSide(resizeHeight, bitmap.height, resizeWidth, bitmap.width)
195
562
  bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true)
196
563
  }
197
564
  if (bitmap.config != Bitmap.Config.ARGB_8888) bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false)
@@ -210,6 +577,12 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
210
577
  private fun ReadableMap.optInt(key: String): Int =
211
578
  if (hasKey(key) && getType(key) in NUMBER_TYPES) getDouble(key).toInt() else 0
212
579
 
580
+ private fun ReadableMap.optLong(key: String): Long =
581
+ if (hasKey(key) && getType(key) in NUMBER_TYPES) getDouble(key).toLong() else 0L
582
+
583
+ private fun ReadableMap.optBool(key: String): Boolean =
584
+ hasKey(key) && getType(key) == ReadableType.Boolean && getBoolean(key)
585
+
213
586
  companion object {
214
587
  const val NAME = "AngularLynxWebGL"
215
588
  }
@@ -217,11 +590,71 @@ class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
217
590
 
218
591
  internal val NUMBER_TYPES = setOf(ReadableType.Int, ReadableType.Long, ReadableType.Number)
219
592
 
593
+ // angular-lynx:webgl
220
594
  /** The drawing buffer's pixels: RGBA, rows bottom to top, and whether the canvas has alpha. */
221
595
  class DrawingBufferPixels(val rgba: ByteBuffer, val width: Int, val height: Int, val alpha: Boolean)
596
+ // /angular-lynx:webgl
222
597
 
223
598
  /** Pixels the module decoded, which texture uploads read by id: RGBA, rows top to bottom. */
224
- internal class DecodedImage(val pixels: ByteBuffer, val width: Int, val height: Int, val premultiplied: Boolean)
599
+ class DecodedImage(val pixels: ByteBuffer, val width: Int, val height: Int, val premultiplied: Boolean) {
600
+ /** A copy, in a buffer of its own, for work done on the pixels in place. */
601
+ fun copy(): DecodedImage {
602
+ val from = pixels.duplicate()
603
+ from.rewind()
604
+ val to = ByteBuffer.allocateDirect(from.remaining()).order(ByteOrder.nativeOrder())
605
+ to.put(from)
606
+ to.rewind()
607
+ return DecodedImage(to, width, height, premultiplied)
608
+ }
609
+ }
610
+
611
+ /**
612
+ * A canvas's context, of either kind: what the registry pairs with the
613
+ * canvas's view, and what another context reads the canvas through (as a
614
+ * texture, or drawn on a 2D canvas).
615
+ */
616
+ interface CanvasContext {
617
+ val canvasId: String
618
+
619
+ /** Shows frames in this canvas's view, or nowhere while it's null. */
620
+ fun attachView(canvas: CanvasUI?)
621
+
622
+ /** The view's surface came, went or changed size. */
623
+ fun surfaceChanged()
624
+
625
+ /** The canvas's pixels now, rows top to bottom, or null when it has none. */
626
+ fun snapshot(): DecodedImage?
627
+
628
+ /**
629
+ * After `OffscreenCanvas.transferToImageBitmap()` took the pixels: a 2D
630
+ * bitmap is cleared to transparent black (opaque black without alpha),
631
+ * and a WebGL drawing buffer too, even with preserveDrawingBuffer, which
632
+ * the HTML spec says has no effect on a transfer. The context's state
633
+ * stays.
634
+ */
635
+ fun clearForTransfer()
636
+ }
637
+
638
+ /** Pixels as a bitmap, premultiplied, as Android's canvas draws only those. */
639
+ internal fun bitmapOf(image: DecodedImage): Bitmap {
640
+ val pixels = image.pixels.duplicate().order(ByteOrder.nativeOrder())
641
+ pixels.rewind()
642
+ val bytes = if (image.premultiplied) {
643
+ pixels
644
+ } else {
645
+ val copy = ByteBuffer.allocateDirect(image.width * image.height * 4).order(ByteOrder.nativeOrder())
646
+ for (i in 0 until image.width * image.height * 4 step 4) {
647
+ val a = pixels.get(i + 3).toInt() and 0xff
648
+ for (c in 0 until 3) copy.put(i + c, (((pixels.get(i + c).toInt() and 0xff) * a + 127) / 255).toByte())
649
+ copy.put(i + 3, a.toByte())
650
+ }
651
+ copy
652
+ }
653
+ bytes.rewind()
654
+ return Bitmap.createBitmap(image.width, image.height, Bitmap.Config.ARGB_8888).apply {
655
+ copyPixelsFromBuffer(bytes)
656
+ }
657
+ }
225
658
 
226
659
  internal object DecodedImages {
227
660
  private val images = HashMap<Int, DecodedImage>()
@@ -235,81 +668,76 @@ internal object DecodedImages {
235
668
  * runtime may make the context before Lynx has made the element's view.
236
669
  *
237
670
  * Views come and go on the UI thread, contexts on Lynx's engine thread, so
238
- * it's locked. It takes a context's lock inside its own, and a context never
239
- * calls it, so the two can't wait on each other.
671
+ * it's locked. A context looks a canvas up here while it holds its own lock
672
+ * (drawing another canvas, or uploading it as a texture), so the registry
673
+ * never calls a context while it holds its lock: it finds the context, lets
674
+ * go, then attaches the view.
240
675
  */
241
676
  internal object CanvasRegistry {
242
677
  private val views = HashMap<String, WeakReference<CanvasUI>>()
243
- private val contexts = HashMap<String, WeakReference<WebGLContext>>()
678
+ private val contexts = HashMap<String, WeakReference<CanvasContext>>()
244
679
 
245
- @Synchronized
246
680
  fun setView(canvasId: String, view: CanvasUI?) {
247
- if (view == null) views.remove(canvasId) else views[canvasId] = WeakReference(view)
248
- contexts[canvasId]?.get()?.attachView(view)
681
+ val context = synchronized(this) {
682
+ if (view == null) views.remove(canvasId) else views[canvasId] = WeakReference(view)
683
+ contexts[canvasId]?.get()
684
+ }
685
+ context?.attachView(view)
249
686
  }
250
687
 
251
688
  @Synchronized
252
689
  fun view(canvasId: String): CanvasUI? = views[canvasId]?.get()
253
690
 
254
- @Synchronized
255
- fun setContext(canvasId: String, context: WebGLContext?) {
256
- if (context == null) {
257
- contexts.remove(canvasId)
258
- } else {
259
- contexts[canvasId] = WeakReference(context)
260
- context.attachView(views[canvasId]?.get())
691
+ fun setContext(canvasId: String, context: CanvasContext?) {
692
+ val view = synchronized(this) {
693
+ if (context == null) {
694
+ contexts.remove(canvasId)
695
+ null
696
+ } else {
697
+ contexts[canvasId] = WeakReference(context)
698
+ views[canvasId]?.get()
699
+ }
261
700
  }
701
+ context?.attachView(view)
262
702
  }
263
703
 
264
704
  @Synchronized
265
- fun context(canvasId: String): WebGLContext? = contexts[canvasId]?.get()
705
+ fun context(canvasId: String): CanvasContext? = contexts[canvasId]?.get()
266
706
  }
267
707
 
268
708
  /**
269
- * The bytes the runtime sends as 32-bit words, with the byte count last (see
270
- * toWords in webgl-bridge.ts). Android runs little-endian, so the words land
271
- * in memory as the bytes were.
709
+ * The bytes of a [width] by [height] RGBA image, or null when a buffer can't
710
+ * hold that many. The pixel count of two Ints fits in a Long, and is checked
711
+ * before it's multiplied by 4: a canvas of 32768 by 32768 has 2^32 bytes,
712
+ * which an Int wraps round to 0, and one of Int.MAX_VALUE by Int.MAX_VALUE
713
+ * more than a Long holds.
272
714
  */
273
- internal fun bytesFromWords(words: ReadableArray): ByteBuffer {
274
- val count = words.size()
275
- if (count == 0) return ByteBuffer.allocateDirect(0)
276
- val byteLength = words.getDouble(count - 1).toLong().toInt()
277
- val buffer = ByteBuffer.allocateDirect((count - 1) * 4).order(ByteOrder.LITTLE_ENDIAN)
278
- for (i in 0 until count - 1) buffer.putInt(words.getDouble(i).toLong().toInt())
279
- buffer.rewind()
280
- buffer.limit(minOf(byteLength, (count - 1) * 4))
281
- return buffer
715
+ internal fun rgbaByteCount(width: Int, height: Int): Int? {
716
+ val pixels = width.toLong() * height
717
+ return if (pixels in 0..(Int.MAX_VALUE / 4).toLong()) (pixels * 4).toInt() else null
282
718
  }
283
719
 
284
- /** Bytes as words for the trip back, the byte count last. */
285
- internal fun wordsFromBytes(bytes: ByteBuffer, length: Int): JavaOnlyArray {
286
- val words = JavaOnlyArray()
287
- val source = bytes.duplicate().order(ByteOrder.LITTLE_ENDIAN)
288
- source.rewind()
289
- val wordCount = (length + 3) / 4
290
- for (i in 0 until wordCount) {
291
- var word = 0L
292
- for (b in 0 until 4) {
293
- val index = i * 4 + b
294
- if (index < length) word = word or ((source.get(index).toLong() and 0xff) shl (8 * b))
295
- }
296
- words.pushDouble(word.toDouble())
297
- }
298
- words.pushInt(length)
299
- return words
720
+ /**
721
+ * One side of the size createImageBitmap's resize asks for: [resize] when
722
+ * it's given, otherwise the side scaled by the other side's resize, keeping
723
+ * the aspect ratio, rounded up, as the HTML spec has it. In Long, so a big
724
+ * image can't wrap round.
725
+ */
726
+ internal fun resizedSide(resize: Int, side: Int, otherResize: Int, otherSide: Int): Int {
727
+ if (resize > 0) return resize
728
+ val scaled = (side.toLong() * otherResize + otherSide - 1) / otherSide
729
+ return scaled.coerceIn(1L, Int.MAX_VALUE.toLong()).toInt()
300
730
  }
301
731
 
302
- internal fun flipRows(pixels: ByteBuffer, stride: Int, height: Int) {
303
- val top = ByteArray(stride)
304
- val bottom = ByteArray(stride)
305
- for (row in 0 until height / 2) {
306
- val other = height - 1 - row
307
- pixels.position(row * stride); pixels.get(top)
308
- pixels.position(other * stride); pixels.get(bottom)
309
- pixels.position(row * stride); pixels.put(bottom)
310
- pixels.position(other * stride); pixels.put(top)
732
+ internal fun premultiply(pixels: ByteBuffer) {
733
+ for (i in 0 until pixels.limit() step 4) {
734
+ val alpha = pixels.get(i + 3).toInt() and 0xff
735
+ if (alpha == 255) continue
736
+ for (c in 0 until 3) {
737
+ val value = pixels.get(i + c).toInt() and 0xff
738
+ pixels.put(i + c, ((value * alpha + 127) / 255).toByte())
739
+ }
311
740
  }
312
- pixels.rewind()
313
741
  }
314
742
 
315
743
  internal fun unpremultiply(pixels: ByteBuffer) {