@blotch/angular-lynx-native 22.3.0 → 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 +143 -2
  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 +37 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +70 -1
  35. package/templates/android/app/src/main/AndroidManifest.xml +24 -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,332 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.content.Context
6
+ import android.hardware.Sensor
7
+ import android.hardware.SensorEvent
8
+ import android.hardware.SensorEventListener
9
+ import android.hardware.SensorManager
10
+ import android.os.Bundle
11
+ import android.os.Handler
12
+ import android.os.HandlerThread
13
+ import android.os.SystemClock
14
+ import com.lynx.jsbridge.LynxContextModule
15
+ import com.lynx.jsbridge.LynxMethod
16
+ import com.lynx.react.bridge.Callback
17
+ import com.lynx.react.bridge.JavaOnlyArray
18
+ import com.lynx.react.bridge.JavaOnlyMap
19
+ import com.lynx.tasm.behavior.LynxContext
20
+
21
+ /**
22
+ * The native module behind the runtime's `LynxMotion`, which calls it as
23
+ * `NativeModules.AngularLynxMotion` (from the background thread, where
24
+ * NativeModules lives). MainActivity registers it with itself as the param,
25
+ * so the sensors stop while the activity is paused.
26
+ *
27
+ * `start(sensor, interval)` runs a sensor, sampling every `interval`
28
+ * milliseconds, or changes how often; `stop(sensor)` stops it; and
29
+ * `availability` calls back with which sensors the phone has. The sensors
30
+ * are `acceleration` (`TYPE_ACCELEROMETER`, in m/s² with gravity), `rotation`
31
+ * (`TYPE_GYROSCOPE`, in rad/s), `orientation` (`TYPE_GAME_ROTATION_VECTOR`,
32
+ * which leaves the magnetometer out, as a rotation matrix), `heading`
33
+ * (`TYPE_ROTATION_VECTOR`'s azimuth, which uses it) and `shake`, which this
34
+ * module hears from the accelerometer itself, so a shake costs the runtime
35
+ * one event rather than 50 samples a second. None needs a permission: the
36
+ * runtime asks for no more than 200 Hz, past which Android 12 wants
37
+ * HIGH_SAMPLING_RATE_SENSORS.
38
+ *
39
+ * The samples go to the runtime in the `angularLynxMotion` global event, one
40
+ * map with a flat array of numbers for each sensor that sampled (see
41
+ * `MotionBatch` in the runtime's motion.ts), at most once every 16 ms: each
42
+ * event is work for Lynx's engine thread, where Angular runs.
43
+ *
44
+ * The generator leaves this file, and the lines in MainActivity that
45
+ * register it, out of an app whose angular.json doesn't set `motion`.
46
+ */
47
+ class MotionModule : LynxContextModule {
48
+ // Lynx creates a module through whichever of its constructors it finds.
49
+ constructor(context: LynxContext) : super(context) {
50
+ activity = null
51
+ watchLifecycle()
52
+ }
53
+
54
+ constructor(context: LynxContext, param: Any?) : super(context, param) {
55
+ activity = param as? Activity
56
+ watchLifecycle()
57
+ }
58
+
59
+ private val activity: Activity?
60
+
61
+ /** Everything below belongs to this thread, where the sensors call back. */
62
+ private val thread = HandlerThread("AngularLynxMotion").apply { start() }
63
+ private val handler = Handler(thread.looper)
64
+ private val sensors = mLynxContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager
65
+
66
+ /** The interval each running sensor was started at, in microseconds. */
67
+ private val requested = HashMap<String, Int>()
68
+ /** The rate each piece of hardware was registered at, to change it only on a change. */
69
+ private val registered = HashMap<Int, Int>()
70
+ /** When each sensor's last sample was kept, in milliseconds. */
71
+ private val lastSample = HashMap<String, Double>()
72
+ private val batch = HashMap<String, MutableList<Double>>()
73
+ private var flushScheduled = false
74
+ private var lastFlush = 0L
75
+ private var paused = false
76
+ private var shakes = ShakeDetector()
77
+
78
+ /**
79
+ * The epoch time of the phone's start, read once: each sample's time is
80
+ * its elapsed realtime from there, so the times only go forward, and
81
+ * spacing and shakes go by them, even when the system's clock is changed.
82
+ * They stay milliseconds since the epoch, as the runtime's `Date.now()`.
83
+ */
84
+ private val epochAtBootMs = System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1_000_000.0
85
+ private val rotation = FloatArray(9)
86
+ private val angles = FloatArray(3)
87
+
88
+ private val listener =
89
+ object : SensorEventListener {
90
+ override fun onSensorChanged(event: SensorEvent) = sample(event)
91
+
92
+ override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit
93
+ }
94
+
95
+ private val lifecycle =
96
+ object : Application.ActivityLifecycleCallbacks {
97
+ override fun onActivityResumed(resumed: Activity) {
98
+ if (resumed === activity) handler.post { paused = false; apply() }
99
+ }
100
+
101
+ override fun onActivityPaused(paused: Activity) {
102
+ if (paused === activity) {
103
+ handler.post {
104
+ this@MotionModule.paused = true
105
+ // Samples from before the pause aren't sent after
106
+ // it, and aren't half of a shake with one after it
107
+ // either.
108
+ batch.clear()
109
+ shakes = ShakeDetector()
110
+ apply()
111
+ }
112
+ }
113
+ }
114
+
115
+ override fun onActivityCreated(created: Activity, state: Bundle?) = Unit
116
+
117
+ override fun onActivityStarted(started: Activity) = Unit
118
+
119
+ override fun onActivityStopped(stopped: Activity) = Unit
120
+
121
+ override fun onActivitySaveInstanceState(saved: Activity, state: Bundle) = Unit
122
+
123
+ override fun onActivityDestroyed(destroyed: Activity) = Unit
124
+ }
125
+
126
+ /**
127
+ * Stops the sensors while the activity is paused, where Lynx pauses the
128
+ * runtime and nobody sees what they'd measure, and the battery would pay
129
+ * for them.
130
+ */
131
+ private fun watchLifecycle() {
132
+ (mLynxContext.applicationContext as? Application)?.registerActivityLifecycleCallbacks(lifecycle)
133
+ }
134
+
135
+ @LynxMethod
136
+ fun start(sensor: String, interval: Double) {
137
+ handler.post {
138
+ requested[sensor] = (maxOf(interval, 5.0) * 1000).toInt()
139
+ apply()
140
+ }
141
+ }
142
+
143
+ @LynxMethod
144
+ fun stop(sensor: String) {
145
+ handler.post {
146
+ requested.remove(sensor)
147
+ lastSample.remove(sensor)
148
+ // Samples still waiting for the next event were for the watches
149
+ // that just stopped: a shake heard before a new listener came
150
+ // mustn't reach it.
151
+ batch.remove(sensor)
152
+ // A shake begun for the last listener can't be finished for the next.
153
+ if (sensor == "shake") shakes = ShakeDetector()
154
+ apply()
155
+ }
156
+ }
157
+
158
+ /** Calls back with which sensors the phone has. */
159
+ @LynxMethod
160
+ fun availability(callback: Callback) {
161
+ callback.invoke(
162
+ JavaOnlyMap().apply {
163
+ putBoolean("acceleration", sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null)
164
+ putBoolean("rotation", sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null)
165
+ putBoolean("orientation", sensors.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR) != null)
166
+ putBoolean("heading", sensors.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null)
167
+ },
168
+ )
169
+ }
170
+
171
+ override fun destroy() {
172
+ (mLynxContext.applicationContext as? Application)?.unregisterActivityLifecycleCallbacks(lifecycle)
173
+ handler.post {
174
+ requested.clear()
175
+ apply()
176
+ thread.quitSafely()
177
+ }
178
+ super.destroy()
179
+ }
180
+
181
+ /** Registers each sensor at the shortest interval anything asks of it, or not at all. */
182
+ private fun apply() {
183
+ val wanted = if (paused) emptyMap() else requested
184
+ // The accelerometer serves the acceleration and the shakes.
185
+ val accelerometer =
186
+ listOfNotNull(wanted["acceleration"], wanted["shake"]?.let { SHAKE_INTERVAL_US }).minOrNull()
187
+ set(Sensor.TYPE_ACCELEROMETER, accelerometer)
188
+ set(Sensor.TYPE_GYROSCOPE, wanted["rotation"])
189
+ set(Sensor.TYPE_GAME_ROTATION_VECTOR, wanted["orientation"])
190
+ set(Sensor.TYPE_ROTATION_VECTOR, wanted["heading"])
191
+ }
192
+
193
+ private fun set(type: Int, interval: Int?) {
194
+ if (registered[type] == interval) return
195
+ val sensor = sensors.getDefaultSensor(type) ?: return
196
+ val previous = registered.remove(type)
197
+ if (previous != null) sensors.unregisterListener(listener, sensor)
198
+ if (interval == null) return
199
+ // The interval is a hint: Android may sample faster, which keep()
200
+ // throttles. Recorded only when Android took it, so a later start()
201
+ // tries again rather than finding it already registered. If Android
202
+ // refuses the new rate, the watches that were running keep the old
203
+ // one rather than getting nothing.
204
+ if (sensors.registerListener(listener, sensor, interval, handler)) {
205
+ registered[type] = interval
206
+ } else if (previous != null && sensors.registerListener(listener, sensor, previous, handler)) {
207
+ registered[type] = previous
208
+ }
209
+ }
210
+
211
+ private fun sample(event: SensorEvent) {
212
+ val t = milliseconds(event.timestamp)
213
+ val v = event.values
214
+ when (event.sensor.type) {
215
+ Sensor.TYPE_ACCELEROMETER -> {
216
+ val (x, y, z) = Triple(v[0].toDouble(), v[1].toDouble(), v[2].toDouble())
217
+ if (keep("acceleration", t)) add("acceleration", t, x, y, z)
218
+ if (requested.containsKey("shake") && shakes.add(t, x, y, z)) add("shake", t)
219
+ }
220
+ Sensor.TYPE_GYROSCOPE ->
221
+ if (keep("rotation", t)) add("rotation", t, v[0].toDouble(), v[1].toDouble(), v[2].toDouble())
222
+ Sensor.TYPE_GAME_ROTATION_VECTOR ->
223
+ if (keep("orientation", t)) {
224
+ // Turns a vector in the phone's frame into the earth's,
225
+ // row by row: the matrix the runtime reads.
226
+ SensorManager.getRotationMatrixFromVector(rotation, v)
227
+ add("orientation", t, *rotation.map { it.toDouble() }.toDoubleArray())
228
+ }
229
+ Sensor.TYPE_ROTATION_VECTOR ->
230
+ if (keep("heading", t)) {
231
+ SensorManager.getRotationMatrixFromVector(rotation, v)
232
+ SensorManager.getOrientation(rotation, angles)
233
+ // The azimuth: where the top of the phone points, in
234
+ // radians clockwise from magnetic north (π/2 when it
235
+ // points east), from -π to π, as degrees from 0 to 360.
236
+ val heading = (Math.toDegrees(angles[0].toDouble()) + 360) % 360
237
+ // The estimated accuracy, in radians, where the sensor
238
+ // gives one, and -1 where it doesn't. Android has no true
239
+ // north without the phone's location, so that's -1.
240
+ val accuracy = if (v.size > 4 && v[4] >= 0) Math.toDegrees(v[4].toDouble()) else -1.0
241
+ add("heading", t, heading, -1.0, accuracy)
242
+ }
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Whether a sensor's sample at `t` is due, by the interval it was started
248
+ * at, allowing a little early for the sensor's jitter. Marks it kept.
249
+ */
250
+ private fun keep(sensor: String, t: Double): Boolean {
251
+ val interval = requested[sensor] ?: return false
252
+ val last = lastSample[sensor]
253
+ // The runtime's own rule (`due()` in motion.ts): a sample up to a
254
+ // quarter of the interval early, 4 ms at most, counts. A wider one
255
+ // here would pass samples the runtime then skips, halving a watch's
256
+ // rate.
257
+ val ms = interval / 1000.0
258
+ if (last != null && t - last < ms - minOf(4.0, ms / 4)) return false
259
+ lastSample[sensor] = t
260
+ return true
261
+ }
262
+
263
+ /** Adds a sample to the next event, which goes at most every 16 ms. */
264
+ private fun add(sensor: String, vararg values: Double) {
265
+ batch.getOrPut(sensor) { ArrayList() }.addAll(values.toList())
266
+ if (flushScheduled) return
267
+ flushScheduled = true
268
+ val wait = maxOf(0L, lastFlush + FLUSH_INTERVAL_MS - SystemClock.uptimeMillis())
269
+ handler.postDelayed({ flush() }, wait)
270
+ }
271
+
272
+ private fun flush() {
273
+ flushScheduled = false
274
+ lastFlush = SystemClock.uptimeMillis()
275
+ if (batch.isEmpty()) return
276
+ val map = JavaOnlyMap()
277
+ for ((sensor, values) in batch) {
278
+ map.putArray(sensor, JavaOnlyArray().apply { values.forEach { pushDouble(it) } })
279
+ }
280
+ batch.clear()
281
+ mLynxContext.sendGlobalEvent(EVENT, JavaOnlyArray().apply { pushMap(map) })
282
+ }
283
+
284
+ /**
285
+ * A sensor event's time (nanoseconds of elapsed realtime) in milliseconds
286
+ * since the epoch, as the runtime's `Date.now()` counts, from the epoch
287
+ * time of the phone's start read once (`epochAtBootMs`).
288
+ */
289
+ private fun milliseconds(timestamp: Long): Double = epochAtBootMs + timestamp / 1_000_000.0
290
+
291
+ companion object {
292
+ const val NAME = "AngularLynxMotion"
293
+ const val EVENT = "angularLynxMotion"
294
+
295
+ /** The least time between events, about a frame. */
296
+ private const val FLUSH_INTERVAL_MS = 16L
297
+
298
+ /** How often the accelerometer samples for shakes: the runtime's `SHAKE.intervalMs`. */
299
+ private const val SHAKE_INTERVAL_US = 20_000
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Hears a shake in accelerometer samples: the runtime's `ShakeDetector`
305
+ * (`motion/motion-math.ts`), after Square's Seismic. A sample accelerates
306
+ * past 13 m/s², and the phone is shaking when three quarters of the samples
307
+ * of the last half second do, over a quarter of a second or more.
308
+ */
309
+ private class ShakeDetector {
310
+ private val times = ArrayDeque<Double>()
311
+ private val fast = ArrayDeque<Boolean>()
312
+ private var accelerating = 0
313
+ private var quietUntil = Double.NEGATIVE_INFINITY
314
+
315
+ fun add(t: Double, x: Double, y: Double, z: Double): Boolean {
316
+ val accelerates = x * x + y * y + z * z > 13.0 * 13.0
317
+ times.addLast(t)
318
+ fast.addLast(accelerates)
319
+ if (accelerates) accelerating++
320
+ while (times.isNotEmpty() && times.first() < t - 500) {
321
+ times.removeFirst()
322
+ if (fast.removeFirst()) accelerating--
323
+ }
324
+ if (t < quietUntil) return false
325
+ if (times.size < 4 || t - times.first() < 250 || accelerating * 4 < times.size * 3) return false
326
+ times.clear()
327
+ fast.clear()
328
+ accelerating = 0
329
+ quietUntil = t + 750
330
+ return true
331
+ }
332
+ }
@@ -0,0 +1,274 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.nfc.FormatException
6
+ import android.nfc.NdefMessage
7
+ import android.nfc.NdefRecord
8
+ import android.nfc.NfcAdapter
9
+ import android.nfc.Tag
10
+ import android.nfc.tech.Ndef
11
+ import android.nfc.tech.NdefFormatable
12
+ import android.os.Handler
13
+ import android.os.Looper
14
+ import android.util.Base64
15
+ import com.lynx.jsbridge.LynxMethod
16
+ import com.lynx.jsbridge.LynxModule
17
+ import com.lynx.react.bridge.Callback
18
+ import com.lynx.react.bridge.JavaOnlyArray
19
+ import com.lynx.react.bridge.JavaOnlyMap
20
+ import com.lynx.react.bridge.ReadableMap
21
+ import com.lynx.react.bridge.ReadableType
22
+ import java.io.IOException
23
+
24
+ /**
25
+ * The native module behind the runtime's `LynxNfc`, which calls it as
26
+ * `NativeModules.AngularLynxNfc` (from the background thread, where
27
+ * NativeModules lives). MainActivity registers it with itself as the param,
28
+ * the activity reader mode runs in. iOS's shell has one of the same name and
29
+ * methods (NfcModule.swift), which say what each answers.
30
+ *
31
+ * A session is `NfcAdapter.enableReaderMode`, which hands each tag that comes
32
+ * near the phone to this module rather than to other apps, while the activity
33
+ * is in the foreground: Android pauses it with the activity and starts it
34
+ * again when the app comes back. There's no system sheet, so `alertMessage`
35
+ * and the messages `stop` takes are iOS's alone.
36
+ *
37
+ * The generator leaves this file and the lines in MainActivity that register
38
+ * it out of an app whose angular.json doesn't set `permissions.nfc`, which
39
+ * also declares the NFC permission and the (not required) NFC feature.
40
+ */
41
+ class NfcModule(context: Context, param: Any?) : LynxModule(context, param) {
42
+ private val activity = param as Activity
43
+ private val adapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(context)
44
+ private val main = Handler(Looper.getMainLooper())
45
+
46
+ /** A tag that couldn't be read or written, with the runtime's code. */
47
+ private class TagError(val code: String, message: String) : Exception(message)
48
+
49
+ // Guarded by `this`: Lynx calls the methods on a thread of its own, and
50
+ // reader mode hands over tags on a binder thread.
51
+ private var open = false
52
+ /**
53
+ * Counts the sessions, so a tag read during one that has since ended,
54
+ * and another started, isn't taken for the new one's.
55
+ */
56
+ private var session = 0
57
+ /** Whether a read or write (not a scan) has taken its one tag. */
58
+ private var claimed = false
59
+ private var multiple = false
60
+ private var message: NdefMessage? = null
61
+ private var waiting: Callback? = null
62
+ private val answers = ArrayDeque<JavaOnlyMap>()
63
+
64
+ @LynxMethod
65
+ fun state(callback: Callback) {
66
+ callback.invoke(JavaOnlyMap().apply { putString("state", currentState()) })
67
+ }
68
+
69
+ private fun currentState(): String = when {
70
+ adapter == null -> "unsupported"
71
+ !adapter.isEnabled -> "disabled"
72
+ else -> "ready"
73
+ }
74
+
75
+ @LynxMethod
76
+ fun start(options: ReadableMap, callback: Callback) {
77
+ when (currentState()) {
78
+ "unsupported" -> return callback.invoke(error("unsupported", "This phone has no NFC reader."))
79
+ "disabled" -> return callback.invoke(error("disabled", "NFC is turned off in the phone's settings."))
80
+ }
81
+ val records = if (options.hasKey("write") && options.getType("write") == ReadableType.Array) {
82
+ try {
83
+ NdefMessage(records(options.getArray("write")!!))
84
+ } catch (_: IllegalArgumentException) {
85
+ return callback.invoke(error("failed", "The records to write aren't valid NDEF records."))
86
+ }
87
+ } else {
88
+ null
89
+ }
90
+ synchronized(this) {
91
+ if (open) return callback.invoke(error("busy", "Another NFC read or write is still open."))
92
+ open = true
93
+ session++
94
+ claimed = false
95
+ multiple = options.hasKey("multiple") && options.getType("multiple") == ReadableType.Boolean &&
96
+ options.getBoolean("multiple")
97
+ message = records
98
+ answers.clear()
99
+ }
100
+ // Reader mode starts from the main thread, with the activity in the
101
+ // foreground.
102
+ main.post {
103
+ try {
104
+ adapter!!.enableReaderMode(activity, ::onTag, READER_FLAGS, null)
105
+ callback.invoke(JavaOnlyMap())
106
+ } catch (exception: IllegalStateException) {
107
+ synchronized(this) { open = false }
108
+ callback.invoke(error("failed", "NFC couldn't start: ${exception.message}"))
109
+ }
110
+ }
111
+ }
112
+
113
+ @LynxMethod
114
+ fun next(callback: Callback) {
115
+ synchronized(this) {
116
+ when {
117
+ answers.isNotEmpty() -> callback.invoke(answers.removeFirst())
118
+ !open -> callback.invoke(error("stopped", "The NFC session has ended."))
119
+ waiting != null -> callback.invoke(error("busy", "The module is already waiting for a tag."))
120
+ else -> waiting = callback
121
+ }
122
+ }
123
+ }
124
+
125
+ @LynxMethod
126
+ fun stop(@Suppress("UNUSED_PARAMETER") options: ReadableMap, callback: Callback) {
127
+ val waiter = synchronized(this) {
128
+ val wasOpen = open
129
+ open = false
130
+ val waiter = waiting
131
+ waiting = null
132
+ if (wasOpen) main.post { adapter?.disableReaderMode(activity) }
133
+ waiter
134
+ }
135
+ waiter?.invoke(error("stopped", "The NFC session has ended."))
136
+ callback.invoke(JavaOnlyMap())
137
+ }
138
+
139
+ /** Reader mode's callback, on a binder thread, for each tag it finds. */
140
+ private fun onTag(tag: Tag) {
141
+ // Reader mode keeps handing over tags until `stop`, so a read or a
142
+ // write claims the first before touching it: a second tag that comes
143
+ // near before the runtime stops the session is neither read nor
144
+ // written to.
145
+ val (write, token) = synchronized(this) {
146
+ if (!open || (!multiple && claimed)) return
147
+ if (!multiple) claimed = true
148
+ message to session
149
+ }
150
+ val answer = try {
151
+ JavaOnlyMap().apply { putMap("tag", if (write != null) write(write, tag) else read(tag)) }
152
+ } catch (exception: TagError) {
153
+ error(exception.code, exception.message ?: "")
154
+ } catch (exception: IOException) {
155
+ error("failed", "The tag moved away before it could be read: ${exception.message}")
156
+ } catch (exception: FormatException) {
157
+ error("failed", "The tag's NDEF message is damaged: ${exception.message}")
158
+ }
159
+ val waiter = synchronized(this) {
160
+ // A scan skips a tag it couldn't read; there's no sheet to say so,
161
+ // and the next tap tries again.
162
+ if (!open || token != session || (multiple && answer.hasKey("error"))) return
163
+ val waiter = waiting
164
+ waiting = null
165
+ if (waiter == null) answers.addLast(answer)
166
+ waiter
167
+ }
168
+ waiter?.invoke(answer)
169
+ }
170
+
171
+ private fun read(tag: Tag): JavaOnlyMap {
172
+ Ndef.get(tag)?.let { ndef ->
173
+ ndef.connect()
174
+ try {
175
+ // Null on a tag formatted for NDEF with no message yet.
176
+ val message = ndef.ndefMessage
177
+ return tagMap(message?.records ?: emptyArray(), ndef.isWritable, ndef.maxSize, tag)
178
+ } finally {
179
+ ndef.close()
180
+ }
181
+ }
182
+ // A blank tag that can take NDEF once it's formatted, which a write
183
+ // does.
184
+ if (NdefFormatable.get(tag) != null) return tagMap(emptyArray(), true, 0, tag)
185
+ throw TagError("tagNotNdef", "This tag doesn't hold NDEF records.")
186
+ }
187
+
188
+ private fun write(message: NdefMessage, tag: Tag): JavaOnlyMap {
189
+ Ndef.get(tag)?.let { ndef ->
190
+ ndef.connect()
191
+ try {
192
+ if (!ndef.isWritable) throw TagError("readOnly", "This tag is locked, so it can't be written to.")
193
+ if (message.byteArrayLength > ndef.maxSize) {
194
+ throw TagError(
195
+ "tooLarge",
196
+ "The records take ${message.byteArrayLength} bytes, and this tag holds ${ndef.maxSize}.",
197
+ )
198
+ }
199
+ ndef.writeNdefMessage(message)
200
+ return tagMap(message.records, true, ndef.maxSize, tag)
201
+ } finally {
202
+ ndef.close()
203
+ }
204
+ }
205
+ NdefFormatable.get(tag)?.let { blank ->
206
+ blank.connect()
207
+ try {
208
+ blank.format(message)
209
+ return tagMap(message.records, true, 0, tag)
210
+ } finally {
211
+ blank.close()
212
+ }
213
+ }
214
+ throw TagError("tagNotNdef", "This tag can't hold NDEF records.")
215
+ }
216
+
217
+ private fun tagMap(records: Array<NdefRecord>, writable: Boolean, capacity: Int, tag: Tag) =
218
+ JavaOnlyMap().apply {
219
+ putArray(
220
+ "records",
221
+ JavaOnlyArray().apply {
222
+ for (record in records) {
223
+ pushMap(
224
+ JavaOnlyMap().apply {
225
+ putInt("tnf", record.tnf.toInt())
226
+ putString("type", base64(record.type))
227
+ putString("id", base64(record.id))
228
+ putString("payload", base64(record.payload))
229
+ },
230
+ )
231
+ }
232
+ },
233
+ )
234
+ putBoolean("writable", writable)
235
+ putInt("capacity", capacity)
236
+ putString("id", tag.id.joinToString("") { "%02x".format(it) })
237
+ }
238
+
239
+ /** The runtime's records, which NdefRecord checks: it throws for a bad one. */
240
+ private fun records(list: com.lynx.react.bridge.ReadableArray): Array<NdefRecord> =
241
+ Array(list.size()) { index ->
242
+ val record = list.getMap(index) ?: throw IllegalArgumentException("Not a record")
243
+ if (record.getType("tnf") !in NUMBERS) throw IllegalArgumentException("No tnf")
244
+ NdefRecord(
245
+ record.getDouble("tnf").toInt().toShort(),
246
+ bytes(record, "type"),
247
+ bytes(record, "id"),
248
+ bytes(record, "payload"),
249
+ )
250
+ }
251
+
252
+ private fun bytes(record: ReadableMap, name: String): ByteArray =
253
+ if (record.hasKey(name) && record.getType(name) == ReadableType.String) {
254
+ Base64.decode(record.getString(name), Base64.DEFAULT)
255
+ } else {
256
+ ByteArray(0)
257
+ }
258
+
259
+ private fun base64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
260
+
261
+ private fun error(code: String, message: String) = JavaOnlyMap().apply {
262
+ putString("error", code)
263
+ putString("message", message)
264
+ }
265
+
266
+ companion object {
267
+ const val NAME = "AngularLynxNfc"
268
+ private val NUMBERS = setOf(ReadableType.Int, ReadableType.Long, ReadableType.Number)
269
+
270
+ /** Every kind of tag that can hold NDEF. */
271
+ private const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or NfcAdapter.FLAG_READER_NFC_B or
272
+ NfcAdapter.FLAG_READER_NFC_F or NfcAdapter.FLAG_READER_NFC_V
273
+ }
274
+ }
@@ -0,0 +1,25 @@
1
+ package dev.angularlynx.shell
2
+
3
+ /**
4
+ * Asks the person for runtime permissions on a native module's behalf.
5
+ *
6
+ * Android's permission prompt belongs to an activity, and an activity has to
7
+ * register for its result as it's created, before a module that wants it
8
+ * exists. So MainActivity registers once and lends the prompt to whichever
9
+ * module asks, which it hands this as its param. It's generic, so a module
10
+ * that needs a permission later reuses it rather than adding a launcher of
11
+ * its own.
12
+ */
13
+ interface PermissionHost {
14
+ /**
15
+ * Shows Android's prompt for [names] and calls [done] once, on the main
16
+ * thread, with whether each was granted. Must be called on the main
17
+ * thread. Returns false, without asking, while another request is open:
18
+ * the activity shows one prompt at a time.
19
+ *
20
+ * Android answers at once, without a prompt, for a permission the person
21
+ * already granted or refused for good, and for one the manifest doesn't
22
+ * declare (which counts as refused).
23
+ */
24
+ fun requestPermissions(names: Array<String>, done: (Map<String, Boolean>) -> Unit): Boolean
25
+ }