@blotch/angular-lynx-native 22.3.1 → 22.3.3

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 (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -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/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,557 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.content.BroadcastReceiver
6
+ import android.content.Context
7
+ import android.content.Intent
8
+ import android.content.IntentFilter
9
+ import android.content.pm.PackageManager
10
+ import android.location.Location
11
+ import android.location.LocationManager
12
+ import android.os.Build
13
+ import android.os.Handler
14
+ import android.os.HandlerThread
15
+ import android.os.Looper
16
+ import android.os.SystemClock
17
+ import android.util.Log
18
+ import androidx.core.content.ContextCompat
19
+ import androidx.core.location.LocationListenerCompat
20
+ import androidx.core.location.LocationManagerCompat
21
+ import androidx.core.location.LocationRequestCompat
22
+ import com.lynx.jsbridge.LynxContextModule
23
+ import com.lynx.jsbridge.LynxMethod
24
+ import com.lynx.react.bridge.Callback
25
+ import com.lynx.react.bridge.JavaOnlyArray
26
+ import com.lynx.react.bridge.JavaOnlyMap
27
+ import com.lynx.react.bridge.ReadableMap
28
+ import com.lynx.tasm.behavior.LynxContext
29
+ import java.util.concurrent.Executor
30
+ import java.util.concurrent.atomic.AtomicBoolean
31
+ import kotlin.math.ceil
32
+ import kotlin.math.min
33
+
34
+ /**
35
+ * The native module behind the runtime's `LynxGeolocation`, which calls it as
36
+ * `NativeModules.AngularLynxGeolocation` (from the background thread, where
37
+ * NativeModules lives): where the phone is, once or as it moves, while the
38
+ * app is in use, from Android's own `LocationManager`, so it needs no Google
39
+ * Play services.
40
+ *
41
+ * Only an app whose angular.json sets `permissions.location` has this file,
42
+ * and the location permissions its manifest declares: the generator deletes
43
+ * it from every other app, with MainActivity's lines that register it.
44
+ *
45
+ * Each method calls back once: with its result, or with `{ error, message }`,
46
+ * as the iOS module does. The rest arrives as `angularLynxGeolocation`
47
+ * global events, each an object with a `type`: the `state` changing, a
48
+ * watch's `position`s and a `watchStopped`, each with the `watch` id its
49
+ * startWatch was given.
50
+ *
51
+ * It asks for both location permissions, so Android 12 and later let the
52
+ * person choose precise or approximate in the prompt, and reports an app
53
+ * granted only the coarse one as `approximate` rather than refused.
54
+ */
55
+ // Lint's MissingPermission check wants every location call next to a
56
+ // permission check it can see. Here that check is whenPermitted(), which
57
+ // each method that finds the phone goes through first, and lint can't follow
58
+ // it through the callbacks. A permission revoked anyway surfaces as a
59
+ // SecurityException, which is answered `denied`.
60
+ @SuppressLint("MissingPermission")
61
+ class GeolocationModule : LynxContextModule {
62
+ // Lynx creates a module through whichever of its constructors it finds.
63
+ constructor(context: LynxContext) : super(context)
64
+ constructor(context: LynxContext, param: Any?) : super(context, param)
65
+
66
+ private val appContext: Context = mContext.applicationContext
67
+ private val manager: LocationManager? = appContext.getSystemService(LocationManager::class.java)
68
+
69
+ // Every field below is read and written on this one thread. The methods
70
+ // (which Lynx calls from its JavaScript thread), the location callbacks
71
+ // and the mode broadcast all post to it, so nothing needs a lock.
72
+ private val thread = HandlerThread(TAG).apply { start() }
73
+ private val location = Handler(thread.looper)
74
+ private val executor = Executor { location.post(it) }
75
+
76
+ // The activity's permission prompt runs on the UI thread.
77
+ private val main = Handler(Looper.getMainLooper())
78
+
79
+ // Set once Lynx destroys the module: nothing is posted or sent after it.
80
+ @Volatile
81
+ private var destroyed = false
82
+
83
+ // Whether the person refused when this app last asked. Android can't
84
+ // tell an app whether a permission it doesn't hold was ever asked for,
85
+ // so it's kept across launches: until the app has asked, the state is
86
+ // `unknown`, which tells it that asking may still work.
87
+ private val preferences = appContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
88
+ private var refused = preferences.getBoolean(REFUSED, false)
89
+
90
+ // Who's waiting for the permission prompt this module has open, so a
91
+ // second call joins it instead of opening another.
92
+ private val askers = mutableListOf<(Answer) -> Unit>()
93
+
94
+ // The state the app last heard, so a `state` event goes out only when it
95
+ // changes.
96
+ private var reportedState: String? = null
97
+
98
+ // The one-off requests running, which destroy() stops.
99
+ private val requests = mutableSetOf<LocationListenerCompat>()
100
+
101
+ // The watches running, by the id the runtime gave them.
102
+ private val watches = HashMap<Int, LocationListenerCompat>()
103
+
104
+ // Location being turned on or off for the whole phone, which arrives on
105
+ // the module's thread.
106
+ private val modeChanges = object : BroadcastReceiver() {
107
+ override fun onReceive(context: Context, intent: Intent) {
108
+ guarded {
109
+ stateChanged()
110
+ if (!enabled()) endWatches(Failure(OFF, OFF_MESSAGE))
111
+ }
112
+ }
113
+ }
114
+
115
+ init {
116
+ post {
117
+ reportedState = state()
118
+ // A broadcast only the system sends needs neither
119
+ // RECEIVER_EXPORTED nor RECEIVER_NOT_EXPORTED, which apps
120
+ // targeting Android 14 must otherwise choose between.
121
+ appContext.registerReceiver(
122
+ modeChanges,
123
+ IntentFilter(LocationManager.MODE_CHANGED_ACTION),
124
+ null,
125
+ location,
126
+ )
127
+ }
128
+ }
129
+
130
+ /** `{ state }`, without asking for anything. */
131
+ @LynxMethod
132
+ fun getState(callback: Callback) = serve(callback) { reply ->
133
+ stateChanged()
134
+ reply.ok(stateResult())
135
+ }
136
+
137
+ /**
138
+ * Asks for the location permissions, unless one is granted, and answers
139
+ * `{ state }` once the person has chosen.
140
+ */
141
+ @LynxMethod
142
+ fun requestPermission(callback: Callback) = serve(callback) { reply ->
143
+ if (manager == null || granted() != null) {
144
+ stateChanged()
145
+ return@serve reply.ok(stateResult())
146
+ }
147
+ ask(reply) { answer ->
148
+ when (answer) {
149
+ Answer.ANSWERED -> reply.ok(stateResult())
150
+ Answer.BUSY -> reply.fail(BUSY, PROMPT_OPEN)
151
+ Answer.CLOSED -> reply.fail(FAILED, PAGE_CLOSED)
152
+ }
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Finds the phone once: `options.accuracy` (`precise` or
158
+ * `approximate`), `options.timeout` in milliseconds, and
159
+ * `options.maximumAge`, the oldest position already known that answers
160
+ * at once. Calls back `{ position }`.
161
+ */
162
+ @LynxMethod
163
+ fun getCurrentPosition(options: ReadableMap?, callback: Callback) = serve(callback) { reply ->
164
+ val precise = options?.getString("accuracy", PRECISE) != APPROXIMATE
165
+ // A timeout under a millisecond is still one: rounded up, not to 0,
166
+ // which would read as none.
167
+ val timeout = options?.getDouble("timeout", 0.0)?.let { ceil(it).toLong() }?.takeIf { it > 0 }
168
+ ?: DEFAULT_TIMEOUT_MS
169
+ val maximumAge = options?.getDouble("maximumAge", 0.0)?.toLong() ?: 0L
170
+ whenPermitted(reply) { manager ->
171
+ // The oldest fix that answers, for a fix Android already has and
172
+ // one a provider hands over first alike: one from before the
173
+ // request only within maximumAge. Not getCurrentLocation(), which
174
+ // takes any fix from the last few seconds, older than a maximumAge
175
+ // of 0 allows.
176
+ // Capped first: a maximumAge of centuries would overflow a Long
177
+ // in nanoseconds. Any age past the phone's uptime takes any fix.
178
+ val oldest = SystemClock.elapsedRealtimeNanos() - min(maximumAge, Long.MAX_VALUE / 1_000_000) * 1_000_000
179
+ if (maximumAge > 0) {
180
+ lastKnown(manager)?.takeIf { it.elapsedRealtimeNanos >= oldest }?.let {
181
+ return@whenPermitted reply.ok(JavaOnlyMap().apply { putMap("position", position(it)) })
182
+ }
183
+ }
184
+ val provider = provider(manager, precise)
185
+ ?: return@whenPermitted reply.fail(OFF, OFF_MESSAGE)
186
+ lateinit var deadline: Runnable
187
+ val listener = object : LocationListenerCompat {
188
+ override fun onLocationChanged(found: Location) {
189
+ if (found.elapsedRealtimeNanos < oldest || !requests.remove(this)) return
190
+ location.removeCallbacks(deadline)
191
+ LocationManagerCompat.removeUpdates(manager, this)
192
+ reply.ok(JavaOnlyMap().apply { putMap("position", position(found)) })
193
+ }
194
+ }
195
+ deadline = Runnable {
196
+ if (!requests.remove(listener)) return@Runnable
197
+ LocationManagerCompat.removeUpdates(manager, listener)
198
+ reply.fail(TIMEOUT, "No position came in time.")
199
+ }
200
+ requests += listener
201
+ location.postDelayed(deadline, timeout)
202
+ val request = LocationRequestCompat.Builder(0L)
203
+ .setQuality(quality(precise))
204
+ .build()
205
+ try {
206
+ LocationManagerCompat.requestLocationUpdates(manager, provider, request, executor, listener)
207
+ } catch (error: RuntimeException) {
208
+ // A permission taken back meanwhile throws: nothing is left
209
+ // waiting for a deadline that answers nobody.
210
+ requests -= listener
211
+ location.removeCallbacks(deadline)
212
+ throw error
213
+ }
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Starts watch `options.watch`: a position each time the phone moves
219
+ * `options.distanceFilter` meters, at `options.accuracy`. Calls back
220
+ * `{}` once it's started; the positions arrive as `position` events.
221
+ */
222
+ @LynxMethod
223
+ fun startWatch(options: ReadableMap?, callback: Callback) = serve(callback) { reply ->
224
+ val id = options?.getDouble("watch", 0.0)?.toInt() ?: 0
225
+ val precise = options?.getString("accuracy", PRECISE) != APPROXIMATE
226
+ val distance = options?.getDouble("distanceFilter", 0.0)?.toFloat() ?: 0f
227
+ whenPermitted(reply) { manager ->
228
+ val provider = provider(manager, precise)
229
+ ?: return@whenPermitted reply.fail(OFF, OFF_MESSAGE)
230
+ val request = LocationRequestCompat.Builder(if (precise) PRECISE_INTERVAL_MS else APPROXIMATE_INTERVAL_MS)
231
+ .setQuality(quality(precise))
232
+ .setMinUpdateDistanceMeters(distance)
233
+ .build()
234
+ val listener = object : LocationListenerCompat {
235
+ override fun onLocationChanged(found: Location) {
236
+ if (watches[id] === this) {
237
+ emit("position") {
238
+ putInt("watch", id)
239
+ putMap("position", position(found))
240
+ }
241
+ }
242
+ }
243
+ }
244
+ // A start for an id the runtime already has running replaces it.
245
+ watches.remove(id)?.let { LocationManagerCompat.removeUpdates(manager, it) }
246
+ watches[id] = listener
247
+ LocationManagerCompat.requestLocationUpdates(manager, provider, request, executor, listener)
248
+ reply.ok()
249
+ }
250
+ }
251
+
252
+ @LynxMethod
253
+ fun stopWatch(id: Int, callback: Callback) = serve(callback) { reply ->
254
+ val listener = watches.remove(id)
255
+ if (listener != null) manager?.let { LocationManagerCompat.removeUpdates(it, listener) }
256
+ reply.ok()
257
+ }
258
+
259
+ // Lynx destroys the module with its page (and the debug build's reload):
260
+ // every request and watch stops, and the thread goes. Nobody's left to
261
+ // hear about it, so there are no events.
262
+ override fun destroy() {
263
+ destroyed = true
264
+ location.post {
265
+ guarded {
266
+ try {
267
+ appContext.unregisterReceiver(modeChanges)
268
+ } catch (_: IllegalArgumentException) {
269
+ // It wasn't registered: the module went before it started.
270
+ }
271
+ manager?.let { manager -> requests.forEach { LocationManagerCompat.removeUpdates(manager, it) } }
272
+ requests.clear()
273
+ manager?.let { manager -> watches.values.forEach { LocationManagerCompat.removeUpdates(manager, it) } }
274
+ watches.clear()
275
+ askers.toList().also { askers.clear() }.forEach { it(Answer.CLOSED) }
276
+ }
277
+ }
278
+ // Runs what's posted before it, the teardown above included.
279
+ thread.quitSafely()
280
+ super.destroy()
281
+ }
282
+
283
+ // State
284
+
285
+ private fun permitted(name: String) =
286
+ ContextCompat.checkSelfPermission(appContext, name) == PackageManager.PERMISSION_GRANTED
287
+
288
+ /** `precise` or `approximate` for the permission granted, or null for none. */
289
+ private fun granted(): String? = when {
290
+ permitted(Manifest.permission.ACCESS_FINE_LOCATION) -> PRECISE
291
+ permitted(Manifest.permission.ACCESS_COARSE_LOCATION) -> APPROXIMATE
292
+ else -> null
293
+ }
294
+
295
+ private fun enabled(): Boolean = manager?.let { LocationManagerCompat.isLocationEnabled(it) } ?: false
296
+
297
+ private fun state(): String {
298
+ if (manager == null) return "unsupported"
299
+ if (!enabled()) return OFF
300
+ return granted() ?: if (refused) DENIED else "unknown"
301
+ }
302
+
303
+ private fun stateResult() = JavaOnlyMap().apply { putString("state", state()) }
304
+
305
+ /** Sends a `state` event when the state isn't what the app last heard. */
306
+ private fun stateChanged() {
307
+ val state = state()
308
+ if (state == reportedState) return
309
+ reportedState = state
310
+ emit("state") { putString("state", state) }
311
+ }
312
+
313
+ /**
314
+ * Runs [action] once the app may find the phone: with Location on, and
315
+ * with a location permission granted (asked for first when neither is).
316
+ * Otherwise [reply] answers why not.
317
+ */
318
+ private fun whenPermitted(reply: Reply, action: (LocationManager) -> Unit) {
319
+ val manager = manager ?: return reply.fail(FAILED, "This device has no location service.")
320
+ if (!enabled()) return reply.fail(OFF, OFF_MESSAGE)
321
+ if (granted() == null) {
322
+ return ask(reply) { answer ->
323
+ when {
324
+ answer == Answer.BUSY -> reply.fail(BUSY, PROMPT_OPEN)
325
+ answer == Answer.CLOSED -> reply.fail(FAILED, PAGE_CLOSED)
326
+ granted() != null -> whenPermitted(reply, action)
327
+ else -> reply.fail(DENIED, DENIED_MESSAGE)
328
+ }
329
+ }
330
+ }
331
+ action(manager)
332
+ }
333
+
334
+ /**
335
+ * Shows Android's permission prompt through the activity, and calls
336
+ * [done] on the module's thread once it's answered. While this module's
337
+ * prompt is open, a second call waits for the same answer. [done] carries
338
+ * on the method [reply] answers, so it answers as [serve] would when
339
+ * [done] throws.
340
+ */
341
+ private fun ask(reply: Reply, done: (Answer) -> Unit) {
342
+ askers += { answer -> answering(reply) { done(answer) } }
343
+ if (askers.size > 1) return
344
+ val host = mParam as? PermissionHost
345
+ main.post {
346
+ // The page can close first, unregistering the activity's
347
+ // launcher, which then throws: destroy() has answered the calls
348
+ // waiting already.
349
+ if (destroyed) return@post
350
+ val asked = host?.requestPermissions(PERMISSIONS) { post { answered(Answer.ANSWERED) } } ?: false
351
+ // No host can't ask, which is as good as refused; another
352
+ // module's prompt being open is only for now.
353
+ if (!asked) post { answered(if (host == null) Answer.ANSWERED else Answer.BUSY) }
354
+ }
355
+ }
356
+
357
+ private fun answered(answer: Answer) {
358
+ if (answer == Answer.ANSWERED) {
359
+ refused = granted() == null
360
+ preferences.edit().putBoolean(REFUSED, refused).apply()
361
+ }
362
+ val waiting = askers.toList()
363
+ askers.clear()
364
+ stateChanged()
365
+ waiting.forEach { it(answer) }
366
+ }
367
+
368
+ // Finding the phone
369
+
370
+ /**
371
+ * The provider to ask: the fused one from Android 12, which mixes GPS,
372
+ * Wi-Fi and cell towers as the request's quality asks; before it GPS for
373
+ * a precise position, which only the fine permission allows, and the
374
+ * network otherwise. Null when none is on.
375
+ */
376
+ private fun provider(manager: LocationManager, precise: Boolean): String? {
377
+ val candidates = buildList {
378
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) add(LocationManager.FUSED_PROVIDER)
379
+ val fine = granted() == PRECISE
380
+ if (precise && fine) add(LocationManager.GPS_PROVIDER)
381
+ add(LocationManager.NETWORK_PROVIDER)
382
+ if (!precise && fine) add(LocationManager.GPS_PROVIDER)
383
+ }
384
+ return candidates.firstOrNull {
385
+ LocationManagerCompat.hasProvider(manager, it) && manager.isProviderEnabled(it)
386
+ }
387
+ }
388
+
389
+ private fun quality(precise: Boolean) =
390
+ if (precise) {
391
+ LocationRequestCompat.QUALITY_HIGH_ACCURACY
392
+ } else {
393
+ LocationRequestCompat.QUALITY_BALANCED_POWER_ACCURACY
394
+ }
395
+
396
+ /** The newest position any provider already has. */
397
+ private fun lastKnown(manager: LocationManager): Location? =
398
+ manager.getProviders(true)
399
+ .mapNotNull { manager.getLastKnownLocation(it) }
400
+ .maxByOrNull { it.elapsedRealtimeNanos }
401
+
402
+ /** Ends every watch, as Location turning off does. */
403
+ private fun endWatches(failure: Failure) {
404
+ val manager = manager ?: return
405
+ watches.toList().also { watches.clear() }.forEach { (id, listener) ->
406
+ LocationManagerCompat.removeUpdates(manager, listener)
407
+ emit("watchStopped") {
408
+ putInt("watch", id)
409
+ putString("error", failure.code)
410
+ putString("message", failure.message)
411
+ }
412
+ }
413
+ }
414
+
415
+ // Plumbing
416
+
417
+ private fun post(action: () -> Unit) {
418
+ if (!destroyed) location.post { guarded(action) }
419
+ }
420
+
421
+ private fun guarded(action: () -> Unit) {
422
+ try {
423
+ action()
424
+ } catch (error: RuntimeException) {
425
+ Log.w(TAG, "Location failed", error)
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Runs a method's [work] on the module's thread. A page that's gone
431
+ * answers `failed`, and anything [work] didn't expect answers `failed`
432
+ * (or `denied`, for a permission Android says is missing) rather than
433
+ * ending the app.
434
+ */
435
+ private fun serve(callback: Callback, work: (Reply) -> Unit) {
436
+ val reply = Reply(callback)
437
+ val posted = !destroyed && location.post { answering(reply) { work(reply) } }
438
+ if (!posted) reply.fail(FAILED, PAGE_CLOSED)
439
+ }
440
+
441
+ private fun answering(reply: Reply, work: () -> Unit) {
442
+ try {
443
+ work()
444
+ } catch (_: SecurityException) {
445
+ reply.fail(DENIED, DENIED_MESSAGE)
446
+ } catch (error: RuntimeException) {
447
+ Log.w(TAG, "Location failed", error)
448
+ reply.fail(FAILED, error.message ?: "Finding the location failed.")
449
+ }
450
+ }
451
+
452
+ private fun emit(type: String, fill: JavaOnlyMap.() -> Unit) {
453
+ if (destroyed) return
454
+ val payload = JavaOnlyMap().apply {
455
+ putString("type", type)
456
+ fill()
457
+ }
458
+ mLynxContext.sendGlobalEvent(EVENT, JavaOnlyArray().apply { pushMap(payload) })
459
+ }
460
+
461
+ /** A method's callback, which answers once: a second answer is dropped. */
462
+ private class Reply(private val callback: Callback) {
463
+ private val answered = AtomicBoolean(false)
464
+
465
+ fun ok(result: JavaOnlyMap = JavaOnlyMap()) {
466
+ if (answered.compareAndSet(false, true)) callback.invoke(result)
467
+ }
468
+
469
+ fun fail(code: String, message: String) {
470
+ if (answered.compareAndSet(false, true)) {
471
+ callback.invoke(
472
+ JavaOnlyMap().apply {
473
+ putString("error", code)
474
+ putString("message", message)
475
+ },
476
+ )
477
+ }
478
+ }
479
+ }
480
+
481
+ /** One of the contract's error codes, and a sentence for the person. */
482
+ private class Failure(val code: String, val message: String)
483
+
484
+ /** How a permission prompt ended. */
485
+ private enum class Answer {
486
+ /** The person chose (or Android chose for them). */
487
+ ANSWERED,
488
+
489
+ /** Another module's prompt is open. */
490
+ BUSY,
491
+
492
+ /** The module was destroyed first. */
493
+ CLOSED,
494
+ }
495
+
496
+ companion object {
497
+ const val NAME = "AngularLynxGeolocation"
498
+
499
+ private const val TAG = "AngularLynxGeolocation"
500
+
501
+ /** The one global event, whose payload's `type` says what happened. */
502
+ private const val EVENT = "angularLynxGeolocation"
503
+
504
+ private const val PREFERENCES = "angular_lynx_geolocation"
505
+ private const val REFUSED = "refused"
506
+
507
+ // Both, so Android 12 and later offer the person the choice.
508
+ private val PERMISSIONS = arrayOf(
509
+ Manifest.permission.ACCESS_FINE_LOCATION,
510
+ Manifest.permission.ACCESS_COARSE_LOCATION,
511
+ )
512
+
513
+ // The states and accuracies, as the runtime names them.
514
+ private const val PRECISE = "precise"
515
+ private const val APPROXIMATE = "approximate"
516
+
517
+ // The contract's error codes.
518
+ private const val DENIED = "denied"
519
+ private const val OFF = "off"
520
+ private const val TIMEOUT = "timeout"
521
+ private const val BUSY = "busy"
522
+ private const val FAILED = "failed"
523
+
524
+ private const val DENIED_MESSAGE = "The app isn't allowed to find the phone."
525
+ private const val OFF_MESSAGE = "Location is turned off for the phone."
526
+ private const val PROMPT_OPEN = "Another permission prompt is open."
527
+ private const val PAGE_CLOSED = "The page closed."
528
+
529
+ /** For a getCurrentPosition() without a timeout, which the runtime always gives. */
530
+ private const val DEFAULT_TIMEOUT_MS = 10_000L
531
+
532
+ // How often a watch asks for a position: about once a second for a
533
+ // precise one, as GPS gives them, and less for an approximate one,
534
+ // which barely changes.
535
+ private const val PRECISE_INTERVAL_MS = 1_000L
536
+ private const val APPROXIMATE_INTERVAL_MS = 10_000L
537
+
538
+ /**
539
+ * A position as the runtime reads it. What Android doesn't know is
540
+ * left out, and the runtime reads it as null.
541
+ */
542
+ private fun position(found: Location) = JavaOnlyMap().apply {
543
+ putDouble("latitude", found.latitude)
544
+ putDouble("longitude", found.longitude)
545
+ putDouble("accuracy", if (found.hasAccuracy()) found.accuracy.toDouble() else 0.0)
546
+ // Above the WGS 84 ellipsoid, as the web and the iOS module give
547
+ // it, not the sea level Android 14's mslAltitudeMeters measures.
548
+ if (found.hasAltitude()) putDouble("altitude", found.altitude)
549
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && found.hasVerticalAccuracy()) {
550
+ putDouble("altitudeAccuracy", found.verticalAccuracyMeters.toDouble())
551
+ }
552
+ if (found.hasBearing()) putDouble("heading", found.bearing.toDouble())
553
+ if (found.hasSpeed()) putDouble("speed", found.speed.toDouble())
554
+ putDouble("timestamp", found.time.toDouble())
555
+ }
556
+ }
557
+ }
@@ -0,0 +1,82 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.os.Build
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.view.HapticFeedbackConstants
9
+ import com.lynx.jsbridge.LynxMethod
10
+ import com.lynx.jsbridge.LynxModule
11
+ import com.lynx.react.bridge.Callback
12
+ import com.lynx.react.bridge.JavaOnlyMap
13
+
14
+ /**
15
+ * The native module behind the runtime's `LynxHaptics`, which calls it as
16
+ * `NativeModules.AngularLynxHaptics` (from the background thread, where
17
+ * NativeModules lives). MainActivity registers it with itself as the param:
18
+ * the feedback plays on its window.
19
+ *
20
+ * Each method plays the nearest of Android's `HapticFeedbackConstants` with
21
+ * `View.performHapticFeedback()`, as the system's own controls do, and calls
22
+ * back once with `{}`. Unlike `Vibrator`, that needs no VIBRATE permission,
23
+ * and it follows the person's touch feedback setting: Android plays nothing
24
+ * when they've turned it off.
25
+ */
26
+ class HapticsModule(context: Context, param: Any?) : LynxModule(context, param) {
27
+ private val activity = param as Activity
28
+ private val main = Handler(Looper.getMainLooper())
29
+
30
+ // Lynx calls modules off the main thread, and a view's feedback belongs
31
+ // to the UI thread.
32
+ private fun play(feedback: Int, callback: Callback) {
33
+ main.post {
34
+ activity.window?.decorView?.performHapticFeedback(feedback)
35
+ callback.invoke(JavaOnlyMap())
36
+ }
37
+ }
38
+
39
+ /**
40
+ * The runtime's HapticImpactStyle. Android has three weights of tap, so
41
+ * `soft` plays as `light` and `rigid` as `medium`; a name the runtime
42
+ * doesn't send plays as `medium`, as its default does.
43
+ */
44
+ @LynxMethod
45
+ fun impact(style: String, callback: Callback) {
46
+ val feedback =
47
+ when (style) {
48
+ "light", "soft" -> HapticFeedbackConstants.KEYBOARD_TAP
49
+ "heavy" -> HapticFeedbackConstants.LONG_PRESS
50
+ else -> HapticFeedbackConstants.VIRTUAL_KEY
51
+ }
52
+ play(feedback, callback)
53
+ }
54
+
55
+ /** A selection moving, as a picker's detent or a clock's hand ticks. */
56
+ @LynxMethod
57
+ fun selection(callback: Callback) {
58
+ play(HapticFeedbackConstants.CLOCK_TICK, callback)
59
+ }
60
+
61
+ /**
62
+ * The runtime's HapticNotificationType. Android 11 added a confirm and a
63
+ * reject feedback; before it, success plays as a key's tap and the
64
+ * others as a long press.
65
+ */
66
+ @LynxMethod
67
+ fun notification(type: String, callback: Callback) {
68
+ val modern = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
69
+ val feedback =
70
+ when {
71
+ type == "warning" || type == "error" ->
72
+ if (modern) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.LONG_PRESS
73
+ else ->
74
+ if (modern) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.VIRTUAL_KEY
75
+ }
76
+ play(feedback, callback)
77
+ }
78
+
79
+ companion object {
80
+ const val NAME = "AngularLynxHaptics"
81
+ }
82
+ }