@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
@@ -0,0 +1,1557 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.BlendMode
5
+ import android.graphics.Canvas
6
+ import android.graphics.Color
7
+ import android.graphics.DashPathEffect
8
+ import android.graphics.LinearGradient
9
+ import android.graphics.Matrix
10
+ import android.graphics.Paint
11
+ import android.graphics.Path
12
+ import android.graphics.PorterDuff
13
+ import android.graphics.PorterDuffXfermode
14
+ import android.graphics.RadialGradient
15
+ import android.graphics.Rect
16
+ import android.graphics.RectF
17
+ import android.graphics.Region
18
+ import android.graphics.Shader
19
+ import android.graphics.SweepGradient
20
+ import android.graphics.Typeface
21
+ import android.graphics.BitmapShader
22
+ import android.os.Build
23
+ import android.util.Log
24
+ import androidx.annotation.RequiresApi
25
+ import com.lynx.react.bridge.JavaOnlyArray
26
+ import com.lynx.react.bridge.ReadableArray
27
+ import com.lynx.react.bridge.ReadableMap
28
+ import com.lynx.react.bridge.ReadableType
29
+ import java.io.ByteArrayOutputStream
30
+ import java.nio.ByteBuffer
31
+ import java.nio.ByteOrder
32
+ import java.util.WeakHashMap
33
+ import kotlin.math.abs
34
+ import kotlin.math.ceil
35
+ import kotlin.math.floor
36
+ import kotlin.math.max
37
+ import kotlin.math.min
38
+ import kotlin.math.roundToInt
39
+
40
+ /**
41
+ * `<canvas>`'s 2D context for the AngularLynx runtime: the bitmap the
42
+ * runtime's CanvasRenderingContext2D (packages/runtime/src/lib/canvas/
43
+ * canvas-2d-context.ts) draws on, with `android.graphics.Canvas`, which is
44
+ * Skia, the engine Chrome's canvas draws with. The runtime sends its calls in
45
+ * batches, as the WebGL context does, through WebGLModule's `run2D`.
46
+ *
47
+ * The runtime keeps the state its getters answer and builds paths itself, in
48
+ * the canvas's pixels (arcs and rounded rectangles arrive as Bézier curves),
49
+ * so this side draws what it's told: a path filled or stroked with the
50
+ * current style, text, an image. Everything is drawn into one ARGB_8888
51
+ * bitmap the canvas's `width` by `height`, which is copied into the canvas's
52
+ * TextureView after each task that drew.
53
+ *
54
+ * What the canvas spec has that Android's canvas doesn't is made here:
55
+ * compositing that clears what the shape doesn't cover (source-in and the
56
+ * like) draws the shape in a layer the canvas's size first; shadows, whose
57
+ * offset and blur are the canvas's pixels whatever the transform, are
58
+ * undone through the transform where a shape is drawn under it; and a
59
+ * filter draws the shape in a layer whose pixels it then works on
60
+ * (CanvasFilter).
61
+ *
62
+ * Lynx calls `run` on its engine thread; the view's surface comes and goes
63
+ * on the UI thread, which shows the bitmap again then. The context's lock
64
+ * keeps the two apart.
65
+ */
66
+ class Canvas2DContext(
67
+ override val canvasId: String,
68
+ attributes: ReadableMap?,
69
+ /**
70
+ * The gradients and patterns of every 2D context in the LynxView, by the
71
+ * runtime's ids, so one context's can paint in another, as on the web.
72
+ * The module holds it.
73
+ */
74
+ private val objects: MutableMap<Int, Any>,
75
+ ) : CanvasContext {
76
+ private val alpha = !(attributes != null && attributes.hasKey("alpha") &&
77
+ attributes.getType("alpha") == ReadableType.Boolean && !attributes.getBoolean("alpha"))
78
+ private var width = 0
79
+ private var height = 0
80
+ private var bitmap: Bitmap? = null
81
+ private var canvas: Canvas? = null
82
+ private var state = State()
83
+ private val stack = ArrayList<State>()
84
+ private var destroyed = false
85
+
86
+ /** Shows the bitmap in the canvas's view. */
87
+ private val presenter = BitmapPresenter(TAG)
88
+
89
+ /** Decoded images as bitmaps, made the first time each is drawn. */
90
+ private val decodedBitmaps = WeakHashMap<DecodedImage, Bitmap>()
91
+
92
+ init {
93
+ val w = attributes.int("width", 300)
94
+ val h = attributes.int("height", 150)
95
+ allocate(w, h)
96
+ }
97
+
98
+ // --- State ---------------------------------------------------------------
99
+
100
+ /**
101
+ * A fill or stroke style: a color, a gradient (which crosses whole with
102
+ * the style), or a pattern's image by id, with its transform.
103
+ */
104
+ private class Style(
105
+ val kind: Int,
106
+ val color: Int,
107
+ val objectId: Int,
108
+ val gradient: Gradient? = null,
109
+ val transform: Matrix? = null,
110
+ ) {
111
+ companion object {
112
+ const val COLOR = 0
113
+ const val GRADIENT = 1
114
+ const val PATTERN = 2
115
+ val BLACK = Style(COLOR, Color.BLACK, 0)
116
+ }
117
+ }
118
+
119
+ /** What canvas `save()` keeps. The clip is the Android canvas's, saved with it. */
120
+ private data class State(
121
+ var transform: FloatArray = floatArrayOf(1f, 0f, 0f, 1f, 0f, 0f),
122
+ var globalAlpha: Float = 1f,
123
+ var composite: Int = 0,
124
+ var fill: Style = Style.BLACK,
125
+ var stroke: Style = Style.BLACK,
126
+ var lineWidth: Float = 1f,
127
+ var lineCap: Paint.Cap = Paint.Cap.BUTT,
128
+ var lineJoin: Paint.Join = Paint.Join.MITER,
129
+ var miterLimit: Float = 10f,
130
+ var lineDash: FloatArray = FloatArray(0),
131
+ var lineDashOffset: Float = 0f,
132
+ var shadowBlur: Float = 0f,
133
+ var shadowColor: Int = Color.TRANSPARENT,
134
+ var shadowOffsetX: Float = 0f,
135
+ var shadowOffsetY: Float = 0f,
136
+ var typeface: Typeface = Typeface.DEFAULT,
137
+ var fontSize: Float = 10f,
138
+ var textAlign: Int = 0,
139
+ var textBaseline: Int = 3,
140
+ var rtl: Boolean = false,
141
+ var letterSpacing: Float = 0f,
142
+ var smoothing: Boolean = true,
143
+ /** The filter, as its steps (see CanvasFilter). */
144
+ var filterSteps: DoubleArray = DoubleArray(0),
145
+ ) {
146
+ fun copyState(): State = copy(transform = transform.copyOf(), lineDash = lineDash.copyOf())
147
+ }
148
+
149
+ private class Gradient(val type: Int, val p: FloatArray) {
150
+ /** Offsets and colors, in order. */
151
+ val offsets = ArrayList<Float>()
152
+ val colors = ArrayList<Int>()
153
+
154
+ fun addStop(offset: Float, color: Int) {
155
+ // A stop goes after the stops at the same offset, as the spec
156
+ // has it, so two at one offset make a hard edge.
157
+ var index = offsets.size
158
+ while (index > 0 && offsets[index - 1] > offset) index--
159
+ offsets.add(index, offset)
160
+ colors.add(index, color)
161
+ }
162
+ }
163
+
164
+ private class Pattern(val bitmap: Bitmap, val repetition: Int)
165
+
166
+ // --- The bitmap ----------------------------------------------------------
167
+
168
+ /** A new bitmap, cleared, with the state reset, as a canvas has when it's resized or reset. */
169
+ private fun allocate(w: Int, h: Int) {
170
+ bitmap?.recycle()
171
+ bitmap = null
172
+ canvas = null
173
+ width = max(0, w)
174
+ height = max(0, h)
175
+ state = State()
176
+ stack.clear()
177
+ if (width == 0 || height == 0) return
178
+ val created = try {
179
+ Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
180
+ } catch (_: OutOfMemoryError) {
181
+ null
182
+ } catch (_: IllegalArgumentException) {
183
+ null
184
+ } ?: run {
185
+ // Too big to allocate: a canvas with no pixels, as a browser's
186
+ // that can't hold its size.
187
+ Log.w(TAG, "The canvas's ${width}x$height bitmap is too big to allocate")
188
+ width = 0
189
+ height = 0
190
+ return
191
+ }
192
+ bitmap = created
193
+ canvas = Canvas(created)
194
+ // A canvas with alpha: false is opaque black until drawn on.
195
+ if (!alpha) created.eraseColor(Color.BLACK)
196
+ }
197
+
198
+ @Synchronized
199
+ fun destroy() {
200
+ if (destroyed) return
201
+ destroyed = true
202
+ presenter.release()
203
+ bitmap?.recycle()
204
+ bitmap = null
205
+ canvas = null
206
+ }
207
+
208
+ // --- Showing the bitmap --------------------------------------------------
209
+
210
+ @Synchronized
211
+ override fun attachView(canvas: CanvasUI?) {
212
+ if (presenter.attach(canvas, !alpha)) surfaceChanged()
213
+ }
214
+
215
+ @Synchronized
216
+ override fun surfaceChanged() {
217
+ if (destroyed) return
218
+ if (presenter.surfaceChanged()) present()
219
+ }
220
+
221
+ /** Copies the bitmap into the view's surface, scaled to its size. */
222
+ private fun present() = presenter.present(bitmap)
223
+
224
+ @Synchronized
225
+ override fun snapshot(): DecodedImage? {
226
+ val source = bitmap ?: return null
227
+ val pixels = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.nativeOrder())
228
+ // ARGB_8888 is R, G, B, A in memory, premultiplied.
229
+ source.copyPixelsToBuffer(pixels)
230
+ pixels.rewind()
231
+ return DecodedImage(pixels, width, height, true)
232
+ }
233
+
234
+ /**
235
+ * After transferToImageBitmap() took the bitmap: transparent black, or
236
+ * opaque black without alpha. eraseColor ignores the clip, and the state
237
+ * stays.
238
+ */
239
+ @Synchronized
240
+ override fun clearForTransfer() {
241
+ val target = bitmap ?: return
242
+ target.eraseColor(if (alpha) Color.TRANSPARENT else Color.BLACK)
243
+ if (presenter.view != null) present()
244
+ }
245
+
246
+ /** The bitmap as a PNG or JPEG file, or null when it has no pixels. */
247
+ @Synchronized
248
+ fun encode(jpeg: Boolean, quality: Double): ByteArray? {
249
+ val source = bitmap ?: return null
250
+ var image = source
251
+ if (jpeg && alpha) {
252
+ // A JPEG has no transparency: transparent pixels come out black,
253
+ // as in browsers.
254
+ image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
255
+ image.eraseColor(Color.BLACK)
256
+ Canvas(image).drawBitmap(source, 0f, 0f, null)
257
+ }
258
+ try {
259
+ return ByteArrayOutputStream().use { output ->
260
+ val written = image.compress(
261
+ if (jpeg) Bitmap.CompressFormat.JPEG else Bitmap.CompressFormat.PNG,
262
+ (quality.coerceIn(0.0, 1.0) * 100).roundToInt(),
263
+ output,
264
+ )
265
+ if (written) output.toByteArray() else null
266
+ }
267
+ } finally {
268
+ if (image !== source) image.recycle()
269
+ }
270
+ }
271
+
272
+ // --- Running a batch -----------------------------------------------------
273
+
274
+ private class Reader(val items: ReadableArray) {
275
+ var index = 0
276
+ val size = items.size()
277
+ fun hasNext() = index < size
278
+ fun number(): Double {
279
+ if (index >= size) return 0.0
280
+ val i = index++
281
+ return when (items.getType(i)) {
282
+ ReadableType.Int, ReadableType.Long, ReadableType.Number -> items.getDouble(i)
283
+ ReadableType.Boolean -> if (items.getBoolean(i)) 1.0 else 0.0
284
+ else -> 0.0
285
+ }
286
+ }
287
+ fun int(): Int = number().toLong().toInt()
288
+ fun float(): Float = number().toFloat()
289
+ fun string(): String {
290
+ if (index >= size) return ""
291
+ val i = index++
292
+ return if (items.getType(i) == ReadableType.String) items.getString(i) else ""
293
+ }
294
+ fun array(): ReadableArray {
295
+ if (index >= size) return JavaOnlyArray()
296
+ val i = index++
297
+ return if (items.getType(i) == ReadableType.Array) items.getArray(i) else JavaOnlyArray()
298
+ }
299
+ fun map(): ReadableMap? {
300
+ if (index >= size) return null
301
+ val i = index++
302
+ return if (items.getType(i) == ReadableType.Map) items.getMap(i) else null
303
+ }
304
+ }
305
+
306
+ @Synchronized
307
+ fun run(commands: ReadableArray): JavaOnlyArray {
308
+ val results = JavaOnlyArray()
309
+ if (destroyed) return results
310
+ val reader = Reader(commands)
311
+ while (reader.hasNext()) {
312
+ val op = reader.int()
313
+ if (op >= 200) {
314
+ when (val result = query(op, reader)) {
315
+ is Boolean -> results.pushBoolean(result)
316
+ is JavaOnlyArray -> results.pushArray(result)
317
+ else -> results.pushNull()
318
+ }
319
+ } else {
320
+ command(op, reader)
321
+ }
322
+ }
323
+ return results
324
+ }
325
+
326
+ private fun color(r: Reader): Int {
327
+ val red = r.int()
328
+ val green = r.int()
329
+ val blue = r.int()
330
+ val a = (r.number() * 255).roundToInt().coerceIn(0, 255)
331
+ return Color.argb(a, red.coerceIn(0, 255), green.coerceIn(0, 255), blue.coerceIn(0, 255))
332
+ }
333
+
334
+ private fun command(op: Int, r: Reader) {
335
+ val s = state
336
+ when (op) {
337
+ Canvas2DOps.SAVE -> {
338
+ stack.add(s.copyState())
339
+ canvas?.save()
340
+ }
341
+ Canvas2DOps.RESTORE -> {
342
+ if (stack.isEmpty()) return
343
+ state = stack.removeAt(stack.size - 1)
344
+ canvas?.restore()
345
+ }
346
+ Canvas2DOps.RESET -> allocate(width, height)
347
+ Canvas2DOps.RESIZE -> {
348
+ val w = r.int()
349
+ val h = r.int()
350
+ allocate(w, h)
351
+ }
352
+ Canvas2DOps.PRESENT -> present()
353
+ Canvas2DOps.SET_TRANSFORM -> s.transform = FloatArray(6) { r.float() }
354
+ Canvas2DOps.SET_GLOBAL_ALPHA -> s.globalAlpha = r.float()
355
+ Canvas2DOps.SET_COMPOSITE_OPERATION -> s.composite = r.int().coerceIn(0, COMPOSITE_COUNT - 1)
356
+ Canvas2DOps.SET_FILL_COLOR -> s.fill = Style(Style.COLOR, color(r), 0)
357
+ Canvas2DOps.SET_FILL_GRADIENT -> s.fill = Style(Style.GRADIENT, 0, 0, gradientFrom(r))
358
+ Canvas2DOps.SET_FILL_PATTERN -> s.fill = patternStyle(r)
359
+ Canvas2DOps.SET_STROKE_COLOR -> s.stroke = Style(Style.COLOR, color(r), 0)
360
+ Canvas2DOps.SET_STROKE_GRADIENT -> s.stroke = Style(Style.GRADIENT, 0, 0, gradientFrom(r))
361
+ Canvas2DOps.SET_STROKE_PATTERN -> s.stroke = patternStyle(r)
362
+ Canvas2DOps.SET_LINE_WIDTH -> s.lineWidth = r.float()
363
+ Canvas2DOps.SET_LINE_CAP -> s.lineCap = when (r.int()) {
364
+ 1 -> Paint.Cap.ROUND
365
+ 2 -> Paint.Cap.SQUARE
366
+ else -> Paint.Cap.BUTT
367
+ }
368
+ Canvas2DOps.SET_LINE_JOIN -> s.lineJoin = when (r.int()) {
369
+ 1 -> Paint.Join.ROUND
370
+ 2 -> Paint.Join.BEVEL
371
+ else -> Paint.Join.MITER
372
+ }
373
+ Canvas2DOps.SET_MITER_LIMIT -> s.miterLimit = r.float()
374
+ Canvas2DOps.SET_LINE_DASH -> {
375
+ val dash = r.array()
376
+ s.lineDash = FloatArray(dash.size()) { dash.getDouble(it).toFloat() }
377
+ s.lineDashOffset = r.float()
378
+ }
379
+ Canvas2DOps.SET_SHADOW -> {
380
+ s.shadowBlur = r.float()
381
+ s.shadowColor = color(r)
382
+ s.shadowOffsetX = r.float()
383
+ s.shadowOffsetY = r.float()
384
+ }
385
+ Canvas2DOps.SET_FONT -> {
386
+ val italic = r.int() != 0
387
+ val weight = r.int()
388
+ val size = r.float()
389
+ val families = r.string()
390
+ s.typeface = typefaceFor(families, weight, italic)
391
+ s.fontSize = size
392
+ }
393
+ Canvas2DOps.SET_TEXT_ALIGN -> s.textAlign = r.int()
394
+ Canvas2DOps.SET_TEXT_BASELINE -> s.textBaseline = r.int()
395
+ Canvas2DOps.SET_DIRECTION -> s.rtl = r.int() == 1
396
+ Canvas2DOps.SET_LETTER_SPACING -> s.letterSpacing = r.float()
397
+ Canvas2DOps.SET_IMAGE_SMOOTHING -> {
398
+ s.smoothing = r.int() != 0
399
+ r.int()
400
+ }
401
+ Canvas2DOps.SET_FILTER -> {
402
+ // Only the steps: the layers are planned from their own
403
+ // reach (see planFor).
404
+ val steps = r.array()
405
+ s.filterSteps = DoubleArray(steps.size()) { steps.getDouble(it) }
406
+ }
407
+ Canvas2DOps.CREATE_PATTERN -> {
408
+ val id = r.int()
409
+ val source = r.map()
410
+ val repetition = r.int()
411
+ // A pattern is of the image as it is now: a copy, which a
412
+ // canvas drawing on doesn't change.
413
+ val image = source?.let { bitmapFrom(it) } ?: return
414
+ objects[id] = Pattern(image.copy(Bitmap.Config.ARGB_8888, false), repetition)
415
+ }
416
+ Canvas2DOps.RELEASE_OBJECT -> objects.remove(r.int())
417
+ Canvas2DOps.CLEAR_PATH -> clearPath(pathFrom(r.array()))
418
+ Canvas2DOps.FILL -> {
419
+ val path = pathFrom(r.array())
420
+ path.fillType = if (r.int() == 1) Path.FillType.EVEN_ODD else Path.FillType.WINDING
421
+ fillDevicePath(path, s.fill)
422
+ }
423
+ Canvas2DOps.STROKE -> strokeDevicePath(pathFrom(r.array()))
424
+ Canvas2DOps.CLIP -> {
425
+ val path = pathFrom(r.array())
426
+ path.fillType = if (r.int() == 1) Path.FillType.EVEN_ODD else Path.FillType.WINDING
427
+ val c = canvas ?: return
428
+ // An empty path clips everything away.
429
+ if (path.isEmpty) c.clipRect(0, 0, 0, 0) else c.clipPath(path)
430
+ }
431
+ Canvas2DOps.FILL_TEXT, Canvas2DOps.STROKE_TEXT -> {
432
+ val text = r.string()
433
+ val x = r.float()
434
+ val y = r.float()
435
+ val maxWidth = r.float()
436
+ drawText(text, x, y, maxWidth, op == Canvas2DOps.STROKE_TEXT)
437
+ }
438
+ Canvas2DOps.DRAW_IMAGE -> {
439
+ val source = r.map()
440
+ val src = RectF(r.float(), r.float(), 0f, 0f).also { it.right = it.left + r.float(); it.bottom = it.top + r.float() }
441
+ val dst = RectF(r.float(), r.float(), 0f, 0f).also { it.right = it.left + r.float(); it.bottom = it.top + r.float() }
442
+ val image = source?.let { bitmapFrom(it) } ?: return
443
+ drawImage(image, src, dst)
444
+ }
445
+ Canvas2DOps.PUT_IMAGE_DATA -> {
446
+ val bytes = bytesFromWords(r.array())
447
+ val w = r.int()
448
+ val h = r.int()
449
+ val x = r.int()
450
+ val y = r.int()
451
+ putPixels(bytes, w, h, x, y)
452
+ }
453
+ // An unknown command can't be skipped past: the rest of the
454
+ // batch would be read as the wrong arguments.
455
+ else -> r.index = r.size
456
+ }
457
+ }
458
+
459
+ /** A gradient as the runtime sends it: its type, six numbers, and its stops. */
460
+ private fun gradientFrom(r: Reader): Gradient {
461
+ val type = r.int()
462
+ val gradient = Gradient(type, FloatArray(6) { r.float() })
463
+ val stops = r.array()
464
+ var i = 0
465
+ while (i + 4 < stops.size()) {
466
+ val color = Color.argb(
467
+ (stops.getDouble(i + 4) * 255).roundToInt().coerceIn(0, 255),
468
+ stops.getDouble(i + 1).toInt().coerceIn(0, 255),
469
+ stops.getDouble(i + 2).toInt().coerceIn(0, 255),
470
+ stops.getDouble(i + 3).toInt().coerceIn(0, 255),
471
+ )
472
+ gradient.addStop(stops.getDouble(i).toFloat(), color)
473
+ i += 5
474
+ }
475
+ return gradient
476
+ }
477
+
478
+ /** A pattern's image, by id, with its transform. */
479
+ private fun patternStyle(r: Reader): Style {
480
+ val id = r.int()
481
+ val transform = matrixOf(FloatArray(6) { r.float() })
482
+ return Style(Style.PATTERN, 0, id, transform = transform)
483
+ }
484
+
485
+ private fun query(op: Int, r: Reader): Any? = when (op) {
486
+ Canvas2DOps.MEASURE_TEXT -> measureText(r.string())
487
+ Canvas2DOps.GET_IMAGE_DATA -> {
488
+ val x = r.int()
489
+ val y = r.int()
490
+ val w = r.int()
491
+ val h = r.int()
492
+ pixelsAt(x, y, w, h)
493
+ }
494
+ Canvas2DOps.IS_POINT_IN_PATH -> {
495
+ val path = pathFrom(r.array())
496
+ path.fillType = if (r.int() == 1) Path.FillType.EVEN_ODD else Path.FillType.WINDING
497
+ contains(path, r.float(), r.float())
498
+ }
499
+ Canvas2DOps.IS_POINT_IN_STROKE -> {
500
+ val outline = strokeOutline(pathFrom(r.array()))
501
+ val x = r.float()
502
+ val y = r.float()
503
+ outline != null && contains(outline, x, y)
504
+ }
505
+ else -> {
506
+ r.index = r.size
507
+ null
508
+ }
509
+ }
510
+
511
+ // --- Paths ---------------------------------------------------------------
512
+
513
+ /** A path from the runtime's segments (Canvas2DPathOps), in the canvas's pixels. */
514
+ private fun pathFrom(segments: ReadableArray): Path {
515
+ val path = Path()
516
+ val count = segments.size()
517
+ var i = 0
518
+ fun next(): Float = if (i < count) segments.getDouble(i++).toFloat() else 0f
519
+ var empty = true
520
+ while (i < count) {
521
+ when (segments.getDouble(i++).toInt()) {
522
+ Canvas2DPathOps.MOVE_TO -> {
523
+ path.moveTo(next(), next())
524
+ empty = false
525
+ }
526
+ Canvas2DPathOps.LINE_TO -> {
527
+ val x = next()
528
+ val y = next()
529
+ if (empty) path.moveTo(x, y) else path.lineTo(x, y)
530
+ empty = false
531
+ }
532
+ Canvas2DPathOps.QUAD_TO -> {
533
+ val cx = next(); val cy = next(); val x = next(); val y = next()
534
+ if (empty) path.moveTo(cx, cy)
535
+ path.quadTo(cx, cy, x, y)
536
+ empty = false
537
+ }
538
+ Canvas2DPathOps.CUBIC_TO -> {
539
+ val ax = next(); val ay = next(); val bx = next(); val by = next(); val x = next(); val y = next()
540
+ if (empty) path.moveTo(ax, ay)
541
+ path.cubicTo(ax, ay, bx, by, x, y)
542
+ empty = false
543
+ }
544
+ Canvas2DPathOps.CLOSE -> if (!empty) path.close()
545
+ else -> i = count
546
+ }
547
+ }
548
+ return path
549
+ }
550
+
551
+ private fun matrixOf(m: FloatArray): Matrix = Matrix().apply {
552
+ setValues(floatArrayOf(m[0], m[2], m[4], m[1], m[3], m[5], 0f, 0f, 1f))
553
+ }
554
+
555
+ private fun transformMatrix(): Matrix = matrixOf(state.transform)
556
+
557
+ private fun invertible(m: FloatArray): Boolean {
558
+ val det = m[0] * m[3] - m[1] * m[2]
559
+ return det != 0f && det.isFinite()
560
+ }
561
+
562
+ /**
563
+ * Whether the point is in the path, to a 64th of a pixel: Region works in
564
+ * whole pixels, so the path is moved to put the point at the origin and
565
+ * scaled up before it's tested. A point on the edge counts as in.
566
+ */
567
+ private fun contains(path: Path, x: Float, y: Float): Boolean {
568
+ val bounds = RectF()
569
+ @Suppress("DEPRECATION")
570
+ path.computeBounds(bounds, true)
571
+ if (x < bounds.left || x > bounds.right || y < bounds.top || y > bounds.bottom) return false
572
+ val scaled = Path(path)
573
+ scaled.transform(Matrix().apply {
574
+ setTranslate(-x, -y)
575
+ postScale(POINT_SCALE, POINT_SCALE)
576
+ })
577
+ val region = Region()
578
+ region.setPath(scaled, Region(-2, -2, 2, 2))
579
+ // The four pixels round the origin: one that covers the point.
580
+ return region.contains(0, 0) || region.contains(-1, 0) || region.contains(0, -1) || region.contains(-1, -1)
581
+ }
582
+
583
+ // --- Compositing ---------------------------------------------------------
584
+
585
+ private fun shadowVisible(): Boolean {
586
+ val s = state
587
+ return Color.alpha(s.shadowColor) > 0 && (s.shadowBlur > 0 || s.shadowOffsetX != 0f || s.shadowOffsetY != 0f)
588
+ }
589
+
590
+ private fun setBlend(paint: Paint, composite: Int) {
591
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
592
+ paint.blendMode = BlendModes.ALL[composite]
593
+ } else {
594
+ PORTER_DUFF_MODES[composite]?.let { paint.xfermode = PorterDuffXfermode(it) }
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Draws with the state's alpha, compositing and shadow, under `matrix`
600
+ * (the transform, for what's drawn in its space) or none (a path in the
601
+ * canvas's pixels).
602
+ *
603
+ * Android draws an operation like source-in only where the shape covers;
604
+ * the canvas spec composites the whole canvas. So for those the shape is
605
+ * drawn into a layer, which is composited with the operation.
606
+ *
607
+ * A shadow is cast from a layer too (compositeFiltered), never with the
608
+ * paint's setShadowLayer(). Android's shadow pass only swaps the paint's
609
+ * color for the shadow's, so it takes neither the shape's alpha (a
610
+ * see-through color, or globalAlpha) nor its shape's colors (an image,
611
+ * gradient or pattern casts a copy of itself), and the smallest blur it
612
+ * draws is half a pixel's deviation, so a shadowBlur of 0 isn't sharp.
613
+ * The spec casts the shadow from the alpha of the shape as drawn, which
614
+ * the layer has. It costs a canvas-sized layer per shadowed draw, as
615
+ * Core Graphics' transparency layer does on iOS.
616
+ */
617
+ private fun composite(paint: Paint, matrix: Matrix?, draw: (Canvas) -> Unit) {
618
+ val c = canvas ?: return
619
+ val s = state
620
+ if (s.filterSteps.isNotEmpty() || shadowVisible()) {
621
+ compositeFiltered(c, matrix, draw)
622
+ return
623
+ }
624
+ val unbounded = s.composite in UNBOUNDED
625
+ if (unbounded) {
626
+ val layer = Paint()
627
+ setBlend(layer, s.composite)
628
+ layer.alpha = (s.globalAlpha * 255).roundToInt()
629
+ c.saveLayer(null, layer)
630
+ } else {
631
+ setBlend(paint, s.composite)
632
+ paint.alpha = (paint.alpha * s.globalAlpha).roundToInt()
633
+ }
634
+ c.save()
635
+ if (matrix != null) c.concat(matrix)
636
+ draw(c)
637
+ c.restore()
638
+ if (unbounded) c.restore()
639
+ if (!alpha && s.composite in REDUCES_ALPHA) keepOpaque()
640
+ }
641
+
642
+ /**
643
+ * Draws with a filter, which works on pixels: the shape is drawn into a
644
+ * layer over the canvas (see [layers]), and the alpha and then the
645
+ * filter are applied to the layer's pixels (CanvasFilter). The layer is
646
+ * then drawn over the canvas with the operation and the shadow, inside
647
+ * the clip, in the canvas spec's order.
648
+ * Any draw with a shadow (and no filter) draws this way too, for the
649
+ * shadow cast from the shape's alpha (see composite).
650
+ */
651
+ private fun compositeFiltered(c: Canvas, matrix: Matrix?, draw: (Canvas) -> Unit) {
652
+ val s = state
653
+ // Parsed once, so the layers are planned and drawn from the same steps.
654
+ val steps = CanvasFilter.parse(s.filterSteps)
655
+ val layers = layers(steps)
656
+ // The shape's plan always has a layer at the canvas's resolution.
657
+ val shapeLayer = layers.shape.full ?: return
658
+ var layer: Bitmap? = null
659
+ var shadow: Bitmap? = null
660
+ try {
661
+ val pixels = rendered(layers.shape, steps, matrix, draw)
662
+ // The canvas shadow, cast from the filtered layer's alpha and
663
+ // drawn before it, as the spec has it. It's cast from the shape's
664
+ // layer, or from a layer of its own (see layers), which may be a
665
+ // smaller one, scaled up as it's drawn.
666
+ var sourceLayer = shapeLayer
667
+ if (shadowVisible()) {
668
+ val source = layers.shadow?.let { plan ->
669
+ sourceLayer = plan.full ?: plan.low ?: return
670
+ rendered(plan, steps, matrix, draw)
671
+ } ?: pixels
672
+ val color = s.shadowColor
673
+ val shadowBytes = CanvasFilter.shadowOf(
674
+ source, sourceLayer.width, sourceLayer.height, 0.0, 0.0, s.shadowBlur / 2.0 * sourceLayer.scale,
675
+ Color.red(color).toDouble(), Color.green(color).toDouble(), Color.blue(color).toDouble(),
676
+ Color.alpha(color) / 255.0,
677
+ )
678
+ shadow = bitmapOf(shadowBytes, sourceLayer)
679
+ }
680
+ layer = bitmapOf(pixels, shapeLayer)
681
+ val paint = Paint(Paint.FILTER_BITMAP_FLAG)
682
+ val unbounded = s.composite in UNBOUNDED
683
+ // The spec composites the shadow, then the shape, each over the
684
+ // whole clip with the operation (its drawing model's steps 6 and
685
+ // 7), so with copy or source-in the shape's composite clears the
686
+ // shadow round it. For those, each goes through a layer of its
687
+ // own, composited with the operation as it's restored: in one
688
+ // layer they'd meet source-over first, and the shadow would stay.
689
+ val layerPaint = Paint()
690
+ if (unbounded) setBlend(layerPaint, s.composite) else setBlend(paint, s.composite)
691
+ shadow?.let {
692
+ if (unbounded) c.saveLayer(null, layerPaint)
693
+ // Its offset is in the canvas's pixels, which the layers are in.
694
+ c.drawBitmap(it, null, sourceLayer.bounds(s.shadowOffsetX.toDouble(), s.shadowOffsetY.toDouble()), paint)
695
+ if (unbounded) c.restore()
696
+ }
697
+ if (unbounded) c.saveLayer(null, layerPaint)
698
+ c.drawBitmap(layer, shapeLayer.left.toFloat(), shapeLayer.top.toFloat(), paint)
699
+ if (unbounded) c.restore()
700
+ } catch (_: OutOfMemoryError) {
701
+ // A layer, its bytes or the filter's scratch copies didn't fit:
702
+ // this draw is left out, and the batch goes on, as a browser's
703
+ // canvas that can't hold its size draws nothing.
704
+ Log.w(TAG, "The filter's ${shapeLayer.width}x${shapeLayer.height} layer is too big to draw with")
705
+ return
706
+ } catch (_: IllegalArgumentException) {
707
+ Log.w(TAG, "The filter's ${shapeLayer.width}x${shapeLayer.height} layer is too big to allocate")
708
+ return
709
+ } finally {
710
+ layer?.recycle()
711
+ shadow?.recycle()
712
+ }
713
+ if (!alpha && s.composite in REDUCES_ALPHA) keepOpaque()
714
+ }
715
+
716
+ /**
717
+ * What `draw` draws into `layer`, through globalAlpha: the bytes as
718
+ * stored, premultiplied RGBA, which is what the filter works on.
719
+ * globalAlpha goes on first, as the canvas spec has it (since
720
+ * whatwg/html#10674), so a drop-shadow() shows through a see-through
721
+ * shape.
722
+ */
723
+ private fun drawn(layer: Layer, matrix: Matrix?, draw: (Canvas) -> Unit): ByteArray {
724
+ val bitmap = Bitmap.createBitmap(layer.width, layer.height, Bitmap.Config.ARGB_8888)
725
+ try {
726
+ val layerCanvas = Canvas(bitmap)
727
+ // The layer's place in the canvas's pixels, worked out in Doubles:
728
+ // a small layer's left can be far off the canvas.
729
+ layerCanvas.translate((-layer.left * layer.scale).toFloat(), (-layer.top * layer.scale).toFloat())
730
+ if (layer.scale != 1.0) layerCanvas.scale(layer.scale.toFloat(), layer.scale.toFloat())
731
+ if (matrix != null) layerCanvas.concat(matrix)
732
+ draw(layerCanvas)
733
+ val pixels = ByteBuffer.allocate(layer.width * layer.height * 4)
734
+ bitmap.copyPixelsToBuffer(pixels)
735
+ CanvasFilter.scaleAlpha(pixels.array(), state.globalAlpha.toDouble())
736
+ return pixels.array()
737
+ } finally {
738
+ bitmap.recycle()
739
+ }
740
+ }
741
+
742
+ /**
743
+ * What `draw` draws through the alpha and the filter's `steps`, as
744
+ * `plan` has it: the bytes over its [Plan.full] layer, or over its
745
+ * [Plan.low] one when it has only that.
746
+ *
747
+ * With both, the low layer is drawn too, and the steps whose deviation
748
+ * is wide enough there ([isWide]) are worked out in it and scaled up
749
+ * onto the full one ([CanvasFilter.resample]): a wide blur replaces the
750
+ * full layer (so the steps before it are worked out only in the low
751
+ * one), and a wide drop shadow's shadow goes under it. The other steps
752
+ * are applied in both. So whatever the wide steps bring onto the canvas
753
+ * from past the full layer's reach comes from the low one, which reaches
754
+ * as far as the steps do, and the rest keeps the full layer's resolution.
755
+ *
756
+ * A far drop shadow ([lastFar]) is cast from a layer of its own (see
757
+ * [farShadow]), so the plan is for the steps after the last one, and
758
+ * the steps up to it are worked out over each of the plan's layers in
759
+ * place of what `draw` draws there.
760
+ */
761
+ private fun rendered(plan: Plan, steps: List<CanvasFilter.Step>, matrix: Matrix?, draw: (Canvas) -> Unit): ByteArray {
762
+ val far = lastFar(steps)
763
+ val rest = steps.subList(far + 1, steps.size)
764
+ fun source(layer: Layer): ByteArray =
765
+ if (far < 0) drawn(layer, matrix, draw) else farShadow(layer, steps.subList(0, far + 1), matrix, draw)
766
+ val full = plan.full
767
+ val low = plan.low
768
+ if (full == null || low == null) {
769
+ // A plan has one layer at least (see planFor and layers).
770
+ val only = full ?: checkNotNull(low)
771
+ val bytes = source(only)
772
+ for (step in rest) CanvasFilter.applyStep(bytes, only.width, only.height, step, only.scale)
773
+ return bytes
774
+ }
775
+ val wide = rest.map { isWide(it, low.scale) }
776
+ val lastWide = wide.lastIndexOf(true)
777
+ val lastWideBlur = rest.indices.lastOrNull { wide[it] && rest[it].isBlur } ?: -1
778
+ val lowBytes = source(low)
779
+ var fullBytes = if (lastWideBlur < 0) source(full) else null
780
+ for ((i, step) in rest.withIndex()) {
781
+ when {
782
+ !wide[i] -> {
783
+ // The low layer is read only up to the last wide step.
784
+ if (i < lastWide) CanvasFilter.applyStep(lowBytes, low.width, low.height, step, low.scale)
785
+ fullBytes?.let { CanvasFilter.applyStep(it, full.width, full.height, step, full.scale) }
786
+ }
787
+ step.isBlur -> {
788
+ CanvasFilter.applyStep(lowBytes, low.width, low.height, step, low.scale)
789
+ if (i == lastWideBlur) fullBytes = resampled(lowBytes, low, full, 0.0, 0.0)
790
+ }
791
+ else -> {
792
+ // The shadow is cast unmoved, then moved as it's resampled
793
+ // onto each layer, so its offset needn't be whole pixels
794
+ // of the low one.
795
+ val v = step.values
796
+ val cast = CanvasFilter.shadowOf(lowBytes, low.width, low.height, 0.0, 0.0, v[2] * low.scale, v[3], v[4], v[5], v[6])
797
+ fullBytes?.let { CanvasFilter.under(it, resampled(cast, low, full, v[0], v[1])) }
798
+ if (i < lastWide) CanvasFilter.under(lowBytes, resampled(cast, low, low, v[0], v[1]))
799
+ }
800
+ }
801
+ }
802
+ // Drawn up front, or made from the low layer at the last wide blur.
803
+ return checkNotNull(fullBytes)
804
+ }
805
+
806
+ /**
807
+ * The index of the last far drop shadow in `steps`, or -1. When the
808
+ * steps reach past [MAX_REACH], a drop shadow moved by an offset is far
809
+ * (up to the filter's last few, [CanvasFilter.Step.castsAlone], as each
810
+ * doubles the draws): it's cast from a layer of its own ([farShadow]), so its offset
811
+ * doesn't count toward the reach the layers are planned for. Counted, an
812
+ * offset past the cap would leave out a shape that far off the canvas
813
+ * (issue #824), as the capped layer doesn't reach it, and it would lower
814
+ * the scale of the smaller layer a wide blur goes through, enough to
815
+ * keep a blur beside it at the canvas's resolution, cut short by the cap.
816
+ */
817
+ private fun lastFar(steps: List<CanvasFilter.Step>): Int =
818
+ if (steps.sumOf { it.reach } > MAX_REACH) steps.indexOfLast { it.castsAlone } else -1
819
+
820
+ /** The steps the layers are planned for: those after the last far drop shadow ([lastFar]). */
821
+ private fun planned(steps: List<CanvasFilter.Step>): List<CanvasFilter.Step> =
822
+ steps.subList(lastFar(steps) + 1, steps.size)
823
+
824
+ /**
825
+ * What `draw` draws through the alpha and `steps`, which end with a far
826
+ * drop shadow ([lastFar]), over `layer`: the steps before it, worked out
827
+ * over the layer, with the shadow under them, cast from those steps
828
+ * worked out over the layer moved back by the shadow's offset. That
829
+ * layer takes in the shape the shadow is cast from however far off the
830
+ * canvas it lies, and it's the size `layer` is, as the canvas shadow
831
+ * casts from a layer of its own (see [layers]).
832
+ *
833
+ * The shadow's own blur goes on there as a blur step after the others,
834
+ * so a wide one is worked out in a smaller layer as any blur is (see
835
+ * [planFor]), and the shadow is the alpha that leaves, in its color: a
836
+ * blur blurs each channel alike, so that's the alpha blurred, as
837
+ * [CanvasFilter.shadowOf] casts it. The offset isn't rounded: the
838
+ * moved layer needn't lie on whole pixels, as only its bytes are used,
839
+ * each landing on the pixel of `layer` it's moved onto, so a fractional
840
+ * offset draws the shape between pixels there, as it lands on the
841
+ * canvas. A wide shadow's offset, resampled from the smaller layer, kept
842
+ * its fraction before this too.
843
+ */
844
+ private fun farShadow(layer: Layer, steps: List<CanvasFilter.Step>, matrix: Matrix?, draw: (Canvas) -> Unit): ByteArray {
845
+ val before = steps.subList(0, steps.size - 1)
846
+ val v = steps.last().values
847
+ val shape = over(layer, before, matrix, draw)
848
+ // Past where a shadow's layer can lie, the canvas's pixels, which are
849
+ // floats, place no shape the shadow could be cast from.
850
+ if (abs(v[0]) > MAX_LAYER_OFFSET || abs(v[1]) > MAX_LAYER_OFFSET) return shape
851
+ val cast = over(layer.moved(-v[0], -v[1]), before + CanvasFilter.Step.blur(v[2]), matrix, draw)
852
+ val shadow = CanvasFilter.shadowOf(cast, layer.width, layer.height, 0.0, 0.0, 0.0, v[3], v[4], v[5], v[6])
853
+ CanvasFilter.under(shape, shadow)
854
+ return shape
855
+ }
856
+
857
+ /**
858
+ * What `draw` draws through the alpha and `steps` over `layer`, planned
859
+ * round it as any filtered draw is ([planFor]), and resampled down to
860
+ * it: the plan's full layer lies on its pixels, so that copies them.
861
+ */
862
+ private fun over(layer: Layer, steps: List<CanvasFilter.Step>, matrix: Matrix?, draw: (Canvas) -> Unit): ByteArray {
863
+ if (steps.isEmpty()) return drawn(layer, matrix, draw)
864
+ val plan = planFor(layer, steps, 0.0)
865
+ // planFor's plans always have a full layer.
866
+ val full = checkNotNull(plan.full)
867
+ val bytes = rendered(plan, steps, matrix, draw)
868
+ if (full.width == layer.width && full.height == layer.height) return bytes
869
+ return resampled(bytes, full, layer, 0.0, 0.0)
870
+ }
871
+
872
+ /** `bytes` of layer `from`, resampled onto layer `to`, moved by (dx, dy) canvas pixels. */
873
+ private fun resampled(bytes: ByteArray, from: Layer, to: Layer, dx: Double, dy: Double): ByteArray =
874
+ CanvasFilter.resample(
875
+ bytes, from.width, from.height, from.left, from.top, from.scale,
876
+ to.width, to.height, to.left, to.top, to.scale, dx, dy,
877
+ )
878
+
879
+ /**
880
+ * Whether a step blurs widely enough, in a layer at `scale`, to be
881
+ * worked out there and scaled up: its deviation there is at least
882
+ * [WIDE_SIGMA] of the layer's pixels, so the detail the smaller layer
883
+ * loses is blurred away. Skia scales a wide blur down the same way.
884
+ */
885
+ private fun isWide(step: CanvasFilter.Step, scale: Double): Boolean = step.sigma * scale >= WIDE_SIGMA
886
+
887
+ /** A layer's bytes, premultiplied RGBA, as a bitmap of the layer's size. */
888
+ private fun bitmapOf(bytes: ByteArray, layer: Layer): Bitmap {
889
+ val bitmap = Bitmap.createBitmap(layer.width, layer.height, Bitmap.Config.ARGB_8888)
890
+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(bytes))
891
+ return bitmap
892
+ }
893
+
894
+ /**
895
+ * A layer a draw goes into, over part of the canvas's pixels: from
896
+ * ([left], [top]), [width] by [height] of its pixels, [scale] of them to
897
+ * a canvas pixel. A layer at the canvas's resolution (scale 1) lies on
898
+ * whole pixels, so its pixels line up with the canvas's.
899
+ */
900
+ private class Layer(val left: Double, val top: Double, val width: Int, val height: Int, val scale: Double) {
901
+ constructor(rect: Rect) : this(rect.left.toDouble(), rect.top.toDouble(), rect.width(), rect.height(), 1.0)
902
+
903
+ /** Where a layer at the canvas's resolution lies, as a Rect. */
904
+ fun rect(): Rect = Rect(left.toInt(), top.toInt(), left.toInt() + width, top.toInt() + height)
905
+
906
+ /** It grown by `pixels` of its own on each side, which stay where they were. */
907
+ fun grown(pixels: Int): Layer =
908
+ Layer(left - pixels / scale, top - pixels / scale, width + 2 * pixels, height + 2 * pixels, scale)
909
+
910
+ /** It moved by (dx, dy) canvas pixels. */
911
+ fun moved(dx: Double, dy: Double): Layer = Layer(left + dx, top + dy, width, height, scale)
912
+
913
+ /** Where it lies in the canvas's pixels, moved by (dx, dy). */
914
+ fun bounds(dx: Double, dy: Double): RectF = RectF(
915
+ (left + dx).toFloat(),
916
+ (top + dy).toFloat(),
917
+ (left + dx + width / scale).toFloat(),
918
+ (top + dy + height / scale).toFloat(),
919
+ )
920
+ }
921
+
922
+ /**
923
+ * The layers one filtered draw (or the shadow cast from it) goes into:
924
+ * [full], at the canvas's resolution, and [low], a smaller one that
925
+ * reaches as far as the filter's wide blurs do (see [rendered]), or
926
+ * either alone. The shape's plan always has [full].
927
+ */
928
+ private class Plan(val full: Layer?, val low: Layer?)
929
+
930
+ /**
931
+ * Where a filter's layers lie: [shape] is the plan the shape is drawn
932
+ * into, and [shadow] a second one the shadow is cast from, or null.
933
+ */
934
+ private class Layers(val shape: Plan, val shadow: Plan?)
935
+
936
+ /** A rectangle's area, as a Long: a layer's sides multiplied can pass an Int. */
937
+ private fun area(rect: Rect): Long = rect.width().toLong() * rect.height()
938
+
939
+ /**
940
+ * The plan for a filtered draw that needs `base` (the canvas, the canvas
941
+ * moved back by the shadow's offset, or a layer a far drop shadow is
942
+ * worked out over) and the filter's reach round it, and `extra` more for
943
+ * the full layer (a shadow's blur, when the shadow is cast from it).
944
+ *
945
+ * The full layer is at `base`'s resolution, grown by the reach, capped at
946
+ * [MAX_REACH] of its pixels, so a huge blur makes no huge layer. Past the
947
+ * cap, when a step blurs widely ([isWide]), a low layer, scaled down by
948
+ * MAX_REACH over the reach, takes in the whole reach at about the size
949
+ * the capped layer was (issue #814), and the full layer needs to reach
950
+ * only as far as the steps after the last wide blur do.
951
+ *
952
+ * The reach is the steps' own, from those after the last far drop shadow
953
+ * ([planned]), which casts from a layer of its own. That's why the
954
+ * runtime sends only the steps: the whole filter's reach, which it once
955
+ * sent too, is too much for part of the filter and too little for a
956
+ * layer at another resolution.
957
+ */
958
+ private fun planFor(base: Layer, steps: List<CanvasFilter.Step>, extra: Double): Plan {
959
+ val rest = planned(steps)
960
+ val reach = rest.sumOf { it.reach }
961
+ fun fullLayer(margin: Double): Layer = base.grown(ceil(min(margin * base.scale, MAX_REACH)).toInt())
962
+ if (!(reach * base.scale > MAX_REACH) || !reach.isFinite()) return Plan(fullLayer(reach + extra), null)
963
+ val scale = MAX_REACH / reach
964
+ val wide = rest.map { isWide(it, scale) }
965
+ if (wide.none { it }) return Plan(fullLayer(reach + extra), null)
966
+ val lastWideBlur = rest.indices.lastOrNull { wide[it] && rest[it].isBlur } ?: -1
967
+ val after = rest.withIndex().filter { (i, _) -> i > lastWideBlur && !wide[i] }.sumOf { it.value.reach }
968
+ return Plan(fullLayer(after + extra), lowLayer(base, reach, scale))
969
+ }
970
+
971
+ /** A layer over `base` grown by `reach`, at `scale`, which keeps it about the size `base` grown by MAX_REACH is. */
972
+ private fun lowLayer(base: Layer, reach: Double, scale: Double): Layer = Layer(
973
+ base.left - reach,
974
+ base.top - reach,
975
+ // (side + 2 * reach) * scale, without multiplying a huge reach out.
976
+ ceil(base.width / base.scale * scale + 2 * reach * scale).toInt(),
977
+ ceil(base.height / base.scale * scale + 2 * reach * scale).toInt(),
978
+ scale,
979
+ )
980
+
981
+ /**
982
+ * The layers a filtered draw with `steps` goes into. The shape's is the canvas grown
983
+ * by the filter's reach, so a shape just off the canvas still blurs onto
984
+ * it (see [planFor]). With a shadow, the shadow needs the part of the
985
+ * shape that casts onto the canvas: the canvas moved back by the
986
+ * shadow's offset, grown by its blur (three of its deviations, which are
987
+ * half the blur) and the filter's reach.
988
+ *
989
+ * Within [MAX_REACH] of that, when one rectangle round both is no bigger
990
+ * than the two, the shape's layer grows to take that part in. Otherwise
991
+ * it's a second layer: one rectangle round both would grow with the
992
+ * offset, and a shadow cast from far off the canvas (shadowOffsetX =
993
+ * 10000 and a shape at x = -10000) would make a huge layer, or, capped,
994
+ * cut the shape away.
995
+ *
996
+ * Past MAX_REACH, the shadow's layer is a smaller one that takes in the
997
+ * whole reach (issue #814): a 1000 px shadowBlur reaches 1500 px, and a
998
+ * layer that far round the canvas would be thousands of pixels a side.
999
+ * When the shadow's blur is wide at that layer's scale ([WIDE_SIGMA]),
1000
+ * the shape is drawn, filtered and cast from in it, and the shadow is
1001
+ * scaled up as it's drawn, as Skia scales a wide blur down: the detail
1002
+ * the layer loses is blurred away. Otherwise the reach is the filter's,
1003
+ * and the shadow's layer is planned as the shape's is, grown by the
1004
+ * shadow's blur too.
1005
+ */
1006
+ private fun layers(steps: List<CanvasFilter.Step>): Layers {
1007
+ val s = state
1008
+ val canvasRect = Rect(0, 0, width, height)
1009
+ val shape = planFor(Layer(canvasRect), steps, 0.0)
1010
+ if (!shadowVisible()) return Layers(shape, null)
1011
+ val blurReach = ceil(s.shadowBlur * 1.5)
1012
+ // A Double, as a huge blur's reach doesn't fit an Int. A far drop
1013
+ // shadow casts from a layer of its own (see planFor).
1014
+ val fullReach = planned(steps).sumOf { it.reach } + blurReach
1015
+ val within = fullReach <= MAX_REACH
1016
+ val reach = if (within) fullReach else 0.0
1017
+ // Whole pixels, so the layer's pixels line up with the canvas's.
1018
+ val moved = listOf(
1019
+ floor(-s.shadowOffsetX.toDouble()),
1020
+ floor(-s.shadowOffsetY.toDouble()),
1021
+ ceil(width - s.shadowOffsetX.toDouble()),
1022
+ ceil(height - s.shadowOffsetY.toDouble()),
1023
+ )
1024
+ // An offset past what a Rect holds casts no shadow anywhere the
1025
+ // canvas's pixels, which are floats, can still place a shape. It's
1026
+ // the canvas moved back by the offset that's checked, not that grown
1027
+ // by the reach: the reach is at most MAX_REACH here, which a Rect
1028
+ // still holds past the limit, and the shadow of a shape the canvas's
1029
+ // floats can place stays, however much the filter reaches.
1030
+ if (moved.any { abs(it) > MAX_LAYER_OFFSET }) return Layers(shape, null)
1031
+ val (left, top) = moved.take(2).map { it - reach }
1032
+ val (right, bottom) = moved.drop(2).map { it + reach }
1033
+ val source = Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
1034
+ if (!within) {
1035
+ val scale = MAX_REACH / fullReach
1036
+ if (s.shadowBlur / 2.0 * scale >= WIDE_SIGMA && fullReach.isFinite()) {
1037
+ return Layers(shape, Plan(null, lowLayer(Layer(source), fullReach, scale)))
1038
+ }
1039
+ return Layers(shape, planFor(Layer(source), steps, blurReach))
1040
+ }
1041
+ // Within MAX_REACH, so is the filter's reach: the shape's layer is
1042
+ // at the canvas's resolution alone, on whole pixels.
1043
+ val shapeRect = shape.full?.rect() ?: return Layers(shape, Plan(Layer(source), null))
1044
+ val both = Rect(shapeRect).apply { union(source) }
1045
+ if (area(both) > area(shapeRect) + area(source)) return Layers(shape, Plan(Layer(source), null))
1046
+ return Layers(Plan(Layer(both), null), null)
1047
+ }
1048
+
1049
+ /**
1050
+ * An opaque canvas stays opaque: what an operation like copy or
1051
+ * destination-out left see-through is put over black, as a browser keeps
1052
+ * a canvas made with alpha: false. It's done on the bytes: drawing black
1053
+ * under them would be antialiased at the clip's edge, and leave those
1054
+ * pixels see-through.
1055
+ */
1056
+ private fun keepOpaque() {
1057
+ val target = bitmap ?: return
1058
+ // The stored bytes, premultiplied, which are the colors over black:
1059
+ // only the alpha changes.
1060
+ val pixels = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.nativeOrder())
1061
+ target.copyPixelsToBuffer(pixels)
1062
+ var changed = false
1063
+ for (i in 3 until pixels.capacity() step 4) {
1064
+ if (pixels.get(i) != 0xff.toByte()) {
1065
+ pixels.put(i, 0xff.toByte())
1066
+ changed = true
1067
+ }
1068
+ }
1069
+ if (!changed) return
1070
+ pixels.rewind()
1071
+ target.copyPixelsFromBuffer(pixels)
1072
+ }
1073
+
1074
+ // --- Shapes --------------------------------------------------------------
1075
+
1076
+ /** A paint for the style, with shaders in the space of `matrix`, or null when it paints nothing. */
1077
+ private fun paintFor(style: Style, matrix: Matrix?): Paint? {
1078
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)
1079
+ paint.isFilterBitmap = state.smoothing
1080
+ when (style.kind) {
1081
+ Style.COLOR -> paint.color = style.color
1082
+ Style.GRADIENT -> {
1083
+ val gradient = style.gradient ?: return null
1084
+ val shader = shaderFor(gradient) ?: return null
1085
+ // The shader's own matrix (a conic gradient's turn), then the
1086
+ // transform's.
1087
+ val local = Matrix()
1088
+ shader.getLocalMatrix(local)
1089
+ matrix?.let { local.postConcat(it) }
1090
+ shader.setLocalMatrix(local)
1091
+ paint.shader = shader
1092
+ }
1093
+ Style.PATTERN -> {
1094
+ val pattern = objects[style.objectId] as? Pattern ?: return null
1095
+ val shader = shaderFor(pattern)
1096
+ // The shader's own matrix (a padded image's offset), then the
1097
+ // pattern's transform, then the canvas's.
1098
+ val local = Matrix()
1099
+ shader.getLocalMatrix(local)
1100
+ style.transform?.let { local.postConcat(it) }
1101
+ matrix?.let { local.postConcat(it) }
1102
+ shader.setLocalMatrix(local)
1103
+ paint.shader = shader
1104
+ }
1105
+ }
1106
+ return paint
1107
+ }
1108
+
1109
+ private fun shaderFor(gradient: Gradient): Shader? {
1110
+ if (gradient.offsets.isEmpty()) return null
1111
+ val offsets = ArrayList(gradient.offsets)
1112
+ val colors = ArrayList(gradient.colors)
1113
+ if (offsets.first() > 0f) {
1114
+ offsets.add(0, 0f)
1115
+ colors.add(0, colors.first())
1116
+ }
1117
+ if (offsets.last() < 1f) {
1118
+ offsets.add(1f)
1119
+ colors.add(colors.last())
1120
+ }
1121
+ val positions = offsets.toFloatArray()
1122
+ val colorArray = colors.toIntArray()
1123
+ val p = gradient.p
1124
+ return when (gradient.type) {
1125
+ 0 -> {
1126
+ // A gradient of no length paints nothing.
1127
+ if (p[0] == p[2] && p[1] == p[3]) return null
1128
+ LinearGradient(p[0], p[1], p[2], p[3], colorArray, positions, Shader.TileMode.CLAMP)
1129
+ }
1130
+ 1 -> {
1131
+ if (p[0] == p[3] && p[1] == p[4] && p[2] == p[5]) return null
1132
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1133
+ RadialGradient(
1134
+ p[0], p[1], p[2], p[3], p[4], p[5],
1135
+ LongArray(colorArray.size) { Color.pack(colorArray[it]) },
1136
+ positions,
1137
+ Shader.TileMode.CLAMP,
1138
+ )
1139
+ } else {
1140
+ // Before Android 12 a radial gradient is one circle: the
1141
+ // bigger circle, with the smaller one's radius as the
1142
+ // first stop, which is right for circles with one center.
1143
+ // A gradient that shrinks runs its stops the other way.
1144
+ val shrinks = p[2] > p[5]
1145
+ val outer = max(max(p[2], p[5]), 0.0001f)
1146
+ val start = (min(p[2], p[5]) / outer).coerceIn(0f, 1f)
1147
+ val count = positions.size
1148
+ val stops = FloatArray(count) {
1149
+ val t = if (shrinks) 1 - positions[count - 1 - it] else positions[it]
1150
+ start + t * (1 - start)
1151
+ }
1152
+ val stopColors = IntArray(count) { colorArray[if (shrinks) count - 1 - it else it] }
1153
+ val cx = if (shrinks) p[0] else p[3]
1154
+ val cy = if (shrinks) p[1] else p[4]
1155
+ RadialGradient(cx, cy, outer, stopColors, stops, Shader.TileMode.CLAMP)
1156
+ }
1157
+ }
1158
+ else -> SweepGradient(p[1], p[2], colorArray, positions).apply {
1159
+ // Sweep gradients start at 3 o'clock, as conic ones do at
1160
+ // their start angle: it's turned by that.
1161
+ setLocalMatrix(Matrix().apply { setRotate(Math.toDegrees(p[0].toDouble()).toFloat(), p[1], p[2]) })
1162
+ }
1163
+ }
1164
+ }
1165
+
1166
+ private fun shaderFor(pattern: Pattern): Shader {
1167
+ val repeatX = pattern.repetition == 0 || pattern.repetition == 1
1168
+ val repeatY = pattern.repetition == 0 || pattern.repetition == 2
1169
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1170
+ return BitmapShader(
1171
+ pattern.bitmap,
1172
+ if (repeatX) Shader.TileMode.REPEAT else Shader.TileMode.DECAL,
1173
+ if (repeatY) Shader.TileMode.REPEAT else Shader.TileMode.DECAL,
1174
+ )
1175
+ }
1176
+ if (repeatX && repeatY) {
1177
+ return BitmapShader(pattern.bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
1178
+ }
1179
+ // Before Android 12 there's no tiling that draws nothing past the
1180
+ // edge: a transparent pixel round the image, clamped, draws nothing.
1181
+ val padX = if (repeatX) 0 else 1
1182
+ val padY = if (repeatY) 0 else 1
1183
+ val padded = Bitmap.createBitmap(pattern.bitmap.width + padX * 2, pattern.bitmap.height + padY * 2, Bitmap.Config.ARGB_8888)
1184
+ Canvas(padded).drawBitmap(pattern.bitmap, padX.toFloat(), padY.toFloat(), null)
1185
+ return BitmapShader(
1186
+ padded,
1187
+ if (repeatX) Shader.TileMode.REPEAT else Shader.TileMode.CLAMP,
1188
+ if (repeatY) Shader.TileMode.REPEAT else Shader.TileMode.CLAMP,
1189
+ ).apply { setLocalMatrix(Matrix().apply { setTranslate(-padX.toFloat(), -padY.toFloat()) }) }
1190
+ }
1191
+
1192
+ /** Fills a path in the canvas's pixels; the style is in the transform's space. */
1193
+ private fun fillDevicePath(path: Path, style: Style) {
1194
+ if (path.isEmpty) return
1195
+ val transform = transformMatrix()
1196
+ val paint = paintFor(style, transform) ?: return
1197
+ paint.style = Paint.Style.FILL
1198
+ composite(paint, null) { it.drawPath(path, paint) }
1199
+ }
1200
+
1201
+ private fun strokePaint(style: Style): Paint? {
1202
+ val s = state
1203
+ val paint = paintFor(style, null) ?: return null
1204
+ paint.style = Paint.Style.STROKE
1205
+ paint.strokeWidth = s.lineWidth
1206
+ paint.strokeCap = s.lineCap
1207
+ paint.strokeJoin = s.lineJoin
1208
+ paint.strokeMiter = s.miterLimit
1209
+ if (s.lineDash.isNotEmpty()) paint.pathEffect = DashPathEffect(s.lineDash, s.lineDashOffset)
1210
+ return paint
1211
+ }
1212
+
1213
+ /** The path in the transform's space, where its line's width and dashes are. */
1214
+ private fun userPath(devicePath: Path): Path? {
1215
+ if (!invertible(state.transform)) return null
1216
+ val inverse = Matrix()
1217
+ if (!transformMatrix().invert(inverse)) return null
1218
+ return Path(devicePath).apply { transform(inverse) }
1219
+ }
1220
+
1221
+ private fun strokeDevicePath(devicePath: Path) {
1222
+ if (devicePath.isEmpty) return
1223
+ val user = userPath(devicePath) ?: return
1224
+ val paint = strokePaint(state.stroke) ?: return
1225
+ composite(paint, transformMatrix()) { it.drawPath(user, paint) }
1226
+ }
1227
+
1228
+ /** The outline a stroke of the path fills, in the canvas's pixels. */
1229
+ private fun strokeOutline(devicePath: Path): Path? {
1230
+ val user = userPath(devicePath) ?: return null
1231
+ val paint = strokePaint(Style.BLACK) ?: return null
1232
+ val outline = Path()
1233
+ @Suppress("DEPRECATION")
1234
+ paint.getFillPath(user, outline)
1235
+ outline.transform(transformMatrix())
1236
+ return outline
1237
+ }
1238
+
1239
+ private fun clearPath(path: Path) {
1240
+ val c = canvas ?: return
1241
+ if (path.isEmpty) return
1242
+ // Not touched by alpha, compositing or shadows, as the spec has it;
1243
+ // the clip still applies.
1244
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)
1245
+ if (alpha) {
1246
+ paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
1247
+ } else {
1248
+ paint.color = Color.BLACK
1249
+ paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
1250
+ }
1251
+ c.drawPath(path, paint)
1252
+ }
1253
+
1254
+ // --- Images --------------------------------------------------------------
1255
+
1256
+ /**
1257
+ * An image source (see #imageSource in canvas-2d-context.ts): a decoded
1258
+ * image by id, or a canvas by its id, as it is now.
1259
+ */
1260
+ private fun bitmapFrom(source: ReadableMap): Bitmap? {
1261
+ if (source.hasKey("blank")) {
1262
+ // A canvas without a context: a transparent image of its size.
1263
+ val w = source.int("width", 0)
1264
+ val h = source.int("height", 0)
1265
+ if (w < 1 || h < 1) return null
1266
+ return try {
1267
+ Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
1268
+ } catch (_: OutOfMemoryError) {
1269
+ null
1270
+ }
1271
+ }
1272
+ if (source.hasKey("canvas") && source.getType("canvas") == ReadableType.String) {
1273
+ val id = source.getString("canvas")
1274
+ if (id == canvasId) return bitmap?.copy(Bitmap.Config.ARGB_8888, false)
1275
+ val image = CanvasRegistry.context(id)?.snapshot() ?: return null
1276
+ return bitmapOf(image)
1277
+ }
1278
+ if (!source.hasKey("image") || source.getType("image") !in NUMBER_TYPES) return null
1279
+ val image = DecodedImages.get(source.getDouble("image").toInt()) ?: return null
1280
+ return decodedBitmaps.getOrPut(image) { bitmapOf(image) }
1281
+ }
1282
+
1283
+ /**
1284
+ * drawImage: the source rectangle of the image drawn in the destination
1285
+ * rectangle, in the transform's space.
1286
+ */
1287
+ private fun drawImage(image: Bitmap, src: RectF, dst: RectF) {
1288
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)
1289
+ paint.isFilterBitmap = state.smoothing
1290
+ // The whole image, placed so the source lands on the destination, and
1291
+ // clipped to it, so a source between pixels is drawn where it falls.
1292
+ val scaleX = dst.width() / src.width()
1293
+ val scaleY = dst.height() / src.height()
1294
+ val whole = RectF(
1295
+ dst.left - src.left * scaleX,
1296
+ dst.top - src.top * scaleY,
1297
+ dst.left - src.left * scaleX + image.width * scaleX,
1298
+ dst.top - src.top * scaleY + image.height * scaleY,
1299
+ )
1300
+ // A source on whole pixels is drawn as itself, so a shadow falls
1301
+ // outside it; one between pixels is clipped, shadow and all.
1302
+ val integral = src.left == src.left.toInt().toFloat() && src.top == src.top.toInt().toFloat() &&
1303
+ src.right == src.right.toInt().toFloat() && src.bottom == src.bottom.toInt().toFloat()
1304
+ composite(paint, transformMatrix()) {
1305
+ if (integral) {
1306
+ val crop = Rect(src.left.toInt(), src.top.toInt(), src.right.toInt(), src.bottom.toInt())
1307
+ it.drawBitmap(image, crop, dst, paint)
1308
+ } else {
1309
+ it.clipRect(dst)
1310
+ it.drawBitmap(image, null, whole, paint)
1311
+ }
1312
+ }
1313
+ }
1314
+
1315
+ // --- Pixels --------------------------------------------------------------
1316
+
1317
+ /** getImageData: the rectangle's pixels, not premultiplied; transparent black outside the canvas. */
1318
+ private fun pixelsAt(x: Int, y: Int, w: Int, h: Int): JavaOnlyArray {
1319
+ val out = ByteBuffer.allocate(max(0, w) * max(0, h) * 4).order(ByteOrder.LITTLE_ENDIAN)
1320
+ val source = bitmap
1321
+ if (source != null && w > 0 && h > 0) {
1322
+ val left = max(0, x)
1323
+ val top = max(0, y)
1324
+ val right = min(width, x + w)
1325
+ val bottom = min(height, y + h)
1326
+ if (right > left && bottom > top) {
1327
+ val rowWidth = right - left
1328
+ val colors = IntArray(rowWidth)
1329
+ for (row in top until bottom) {
1330
+ // getPixels gives straight ARGB, whatever the bitmap holds.
1331
+ source.getPixels(colors, 0, rowWidth, left, row, rowWidth, 1)
1332
+ for (column in 0 until rowWidth) {
1333
+ val color = colors[column]
1334
+ val index = ((row - y) * w + (left - x + column)) * 4
1335
+ out.put(index, Color.red(color).toByte())
1336
+ out.put(index + 1, Color.green(color).toByte())
1337
+ out.put(index + 2, Color.blue(color).toByte())
1338
+ out.put(index + 3, (if (alpha) Color.alpha(color) else 255).toByte())
1339
+ }
1340
+ }
1341
+ }
1342
+ }
1343
+ return wordsFromBytes(out, out.capacity())
1344
+ }
1345
+
1346
+ /** putImageData: straight RGBA written as it is, whatever the transform, clip and compositing. */
1347
+ private fun putPixels(bytes: ByteBuffer, w: Int, h: Int, x: Int, y: Int) {
1348
+ val target = bitmap ?: return
1349
+ if (bytes.limit() < w * h * 4) return
1350
+ val left = max(0, x)
1351
+ val top = max(0, y)
1352
+ val right = min(width, x + w)
1353
+ val bottom = min(height, y + h)
1354
+ if (right <= left || bottom <= top) return
1355
+ val rowWidth = right - left
1356
+ val colors = IntArray(rowWidth)
1357
+ for (row in top until bottom) {
1358
+ for (column in 0 until rowWidth) {
1359
+ val index = ((row - y) * w + (left - x + column)) * 4
1360
+ val a = if (alpha) bytes.get(index + 3).toInt() and 0xff else 255
1361
+ colors[column] = Color.argb(
1362
+ a,
1363
+ bytes.get(index).toInt() and 0xff,
1364
+ bytes.get(index + 1).toInt() and 0xff,
1365
+ bytes.get(index + 2).toInt() and 0xff,
1366
+ )
1367
+ }
1368
+ // setPixels takes straight colors and writes them as they are.
1369
+ target.setPixels(colors, 0, rowWidth, left, row, rowWidth, 1)
1370
+ }
1371
+ }
1372
+
1373
+ // --- Text ----------------------------------------------------------------
1374
+
1375
+ private fun typefaceFor(families: String, weight: Int, italic: Boolean): Typeface {
1376
+ val style = when {
1377
+ weight >= 600 && italic -> Typeface.BOLD_ITALIC
1378
+ weight >= 600 -> Typeface.BOLD
1379
+ italic -> Typeface.ITALIC
1380
+ else -> Typeface.NORMAL
1381
+ }
1382
+ var base: Typeface? = null
1383
+ for (family in families.split('\n')) {
1384
+ val name = family.trim()
1385
+ if (name.isEmpty()) continue
1386
+ base = SystemFontFamilies.getTypeface(name, style)
1387
+ if (base != null) break
1388
+ }
1389
+ val found = base ?: Typeface.create(Typeface.DEFAULT, style)
1390
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1391
+ Typeface.create(found, weight.coerceIn(1, 1000), italic)
1392
+ } else {
1393
+ found
1394
+ }
1395
+ }
1396
+
1397
+ private fun textPaint(): Paint {
1398
+ val s = state
1399
+ return Paint(Paint.ANTI_ALIAS_FLAG).apply {
1400
+ typeface = s.typeface
1401
+ textSize = s.fontSize
1402
+ letterSpacing = if (s.fontSize > 0) s.letterSpacing / s.fontSize else 0f
1403
+ }
1404
+ }
1405
+
1406
+ private fun alignmentOffset(width: Float): Float {
1407
+ val rtl = state.rtl
1408
+ return when (state.textAlign) {
1409
+ 1 -> if (rtl) 0f else -width
1410
+ 2 -> 0f
1411
+ 3 -> -width
1412
+ 4 -> -width / 2
1413
+ else -> if (rtl) -width else 0f
1414
+ }
1415
+ }
1416
+
1417
+ /** How far above the alphabetic baseline the anchor is, for textBaseline, as Chrome works it out. */
1418
+ private fun baselineHeight(paint: Paint): Float {
1419
+ val metrics = paint.fontMetrics
1420
+ val ascent = -metrics.ascent
1421
+ val descent = metrics.descent
1422
+ return when (state.textBaseline) {
1423
+ 0 -> ascent
1424
+ 1 -> ascent * 0.8f
1425
+ 2 -> (ascent - descent) / 2
1426
+ 4, 5 -> -descent
1427
+ else -> 0f
1428
+ }
1429
+ }
1430
+
1431
+ private fun drawText(text: String, x: Float, y: Float, maxWidth: Float, stroke: Boolean) {
1432
+ if (canvas == null || text.isEmpty() || state.fontSize <= 0.01f) return
1433
+ val paint = textPaint()
1434
+ val width = paint.measureText(text)
1435
+ // Text wider than maxWidth is squeezed to fit, as the spec allows.
1436
+ val scaleX = if (maxWidth > 0 && width > maxWidth) maxWidth / width else 1f
1437
+ val originX = x + alignmentOffset(width) * scaleX
1438
+ val baseline = y + baselineHeight(paint)
1439
+ val place = Matrix().apply {
1440
+ setScale(scaleX, 1f)
1441
+ postTranslate(originX, baseline)
1442
+ }
1443
+ val style = if (stroke) state.stroke else state.fill
1444
+ if (!stroke && style.kind == Style.COLOR) {
1445
+ // Drawn as glyphs, so color glyphs (emoji) draw too.
1446
+ paint.color = style.color
1447
+ val matrix = transformMatrix().apply { preConcat(place) }
1448
+ composite(paint, matrix) {
1449
+ it.drawTextRun(text, 0, text.length, 0, text.length, 0f, 0f, state.rtl, paint)
1450
+ }
1451
+ return
1452
+ }
1453
+ // The glyphs' outlines, in the canvas's pixels, filled or stroked as
1454
+ // a path is.
1455
+ val glyphs = Path()
1456
+ paint.getTextPath(text, 0, text.length, 0f, 0f, glyphs)
1457
+ glyphs.transform(place)
1458
+ glyphs.transform(transformMatrix())
1459
+ if (stroke) strokeDevicePath(glyphs) else fillDevicePath(glyphs, style)
1460
+ }
1461
+
1462
+ /** measureText: TextMetrics' numbers, in order (see LynxTextMetrics), from the anchor. */
1463
+ private fun measureText(text: String): JavaOnlyArray {
1464
+ val paint = textPaint()
1465
+ val width = paint.measureText(text)
1466
+ val bounds = Rect()
1467
+ if (text.isNotEmpty()) paint.getTextBounds(text, 0, text.length, bounds)
1468
+ val metrics = paint.fontMetrics
1469
+ val ascent = -metrics.ascent
1470
+ val descent = metrics.descent
1471
+ val offset = alignmentOffset(width)
1472
+ val anchor = baselineHeight(paint)
1473
+ // Android's bounds are y down; TextMetrics' are y up from the baseline.
1474
+ val values = floatArrayOf(
1475
+ width,
1476
+ -(offset + bounds.left),
1477
+ offset + bounds.right,
1478
+ ascent - anchor,
1479
+ descent + anchor,
1480
+ -bounds.top - anchor,
1481
+ bounds.bottom + anchor,
1482
+ ascent - anchor,
1483
+ descent + anchor,
1484
+ ascent * 0.8f - anchor,
1485
+ -anchor,
1486
+ -descent - anchor,
1487
+ )
1488
+ return JavaOnlyArray().apply { for (value in values) pushDouble(value.toDouble()) }
1489
+ }
1490
+
1491
+ companion object {
1492
+ private const val TAG = "AngularLynxCanvas2D"
1493
+ private const val COMPOSITE_COUNT = 26
1494
+
1495
+ /**
1496
+ * How far off the canvas a shadow's layer can lie: 2^24 pixels, past
1497
+ * which a float, as the canvas's pixels are, no longer holds every
1498
+ * whole pixel, and well inside what a Rect's ints hold.
1499
+ */
1500
+ private const val MAX_LAYER_OFFSET = 16_777_216.0
1501
+
1502
+ /**
1503
+ * The most a layer at the canvas's resolution reaches past the part
1504
+ * of the canvas it's for, so a huge blur makes no huge layer. A blur
1505
+ * or shadow that reaches farther goes through a smaller layer too
1506
+ * (see layers), which this keeps about the capped layer's size.
1507
+ */
1508
+ private const val MAX_REACH = 256.0
1509
+
1510
+ /**
1511
+ * The deviation, in a smaller layer's pixels, from which a blur is
1512
+ * worked out there and scaled up (see isWide): a blur that wide has
1513
+ * no detail a pixel of that layer would lose.
1514
+ */
1515
+ private const val WIDE_SIGMA = 4.0
1516
+
1517
+ /** The operations that clear what the shape doesn't cover. */
1518
+ private val UNBOUNDED = setOf(1, 2, 5, 7, 9)
1519
+
1520
+ /**
1521
+ * The operations that can leave a pixel less opaque than it was:
1522
+ * source-in, source-out, destination-in, destination-out,
1523
+ * destination-atop, copy and xor.
1524
+ */
1525
+ private val REDUCES_ALPHA = setOf(1, 2, 5, 6, 7, 9, 10)
1526
+
1527
+ /** How finely isPointInPath() tests a point: a 64th of a pixel. */
1528
+ private const val POINT_SCALE = 64f
1529
+
1530
+
1531
+ /** Before Android 10, the operations PorterDuff has; the rest draw as source-over. */
1532
+ private val PORTER_DUFF_MODES: Array<PorterDuff.Mode?> = arrayOf(
1533
+ PorterDuff.Mode.SRC_OVER, PorterDuff.Mode.SRC_IN, PorterDuff.Mode.SRC_OUT, PorterDuff.Mode.SRC_ATOP,
1534
+ PorterDuff.Mode.DST_OVER, PorterDuff.Mode.DST_IN, PorterDuff.Mode.DST_OUT, PorterDuff.Mode.DST_ATOP,
1535
+ PorterDuff.Mode.ADD, PorterDuff.Mode.SRC, PorterDuff.Mode.XOR, PorterDuff.Mode.MULTIPLY,
1536
+ PorterDuff.Mode.SCREEN, PorterDuff.Mode.OVERLAY, PorterDuff.Mode.DARKEN, PorterDuff.Mode.LIGHTEN,
1537
+ null, null, null, null, null, null, null, null, null, null,
1538
+ )
1539
+ }
1540
+ }
1541
+
1542
+ /** The canvas's composite operations as Android 10's blend modes, in order. */
1543
+ @RequiresApi(Build.VERSION_CODES.Q)
1544
+ private object BlendModes {
1545
+ val ALL: Array<BlendMode> = arrayOf(
1546
+ BlendMode.SRC_OVER, BlendMode.SRC_IN, BlendMode.SRC_OUT, BlendMode.SRC_ATOP,
1547
+ BlendMode.DST_OVER, BlendMode.DST_IN, BlendMode.DST_OUT, BlendMode.DST_ATOP,
1548
+ BlendMode.PLUS, BlendMode.SRC, BlendMode.XOR, BlendMode.MULTIPLY,
1549
+ BlendMode.SCREEN, BlendMode.OVERLAY, BlendMode.DARKEN, BlendMode.LIGHTEN,
1550
+ BlendMode.COLOR_DODGE, BlendMode.COLOR_BURN, BlendMode.HARD_LIGHT, BlendMode.SOFT_LIGHT,
1551
+ BlendMode.DIFFERENCE, BlendMode.EXCLUSION, BlendMode.HUE, BlendMode.SATURATION,
1552
+ BlendMode.COLOR, BlendMode.LUMINOSITY,
1553
+ )
1554
+ }
1555
+
1556
+ private fun ReadableMap?.int(key: String, default: Int): Int =
1557
+ if (this != null && hasKey(key) && getType(key) in NUMBER_TYPES) getDouble(key).toInt() else default