@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,455 @@
1
+ import CoreLocation
2
+ import Foundation
3
+ import Lynx
4
+
5
+ /// The native module behind the runtime's `LynxGeolocation`, which calls it
6
+ /// as `NativeModules.AngularLynxGeolocation` (from the background thread,
7
+ /// where NativeModules lives): where the phone is, once or as it moves,
8
+ /// while the app is in use, with Core Location.
9
+ ///
10
+ /// Only an app whose angular.json sets `permissions.location` has this file.
11
+ /// App Store Connect flags an app whose code uses Core Location without
12
+ /// `NSLocationWhenInUseUsageDescription` (ITMS-90683), which the generator
13
+ /// writes only then, so it leaves the file out otherwise, and the shell
14
+ /// registers the class by its Objective-C name instead of naming it.
15
+ ///
16
+ /// Every method calls back once, with its result or `{ error, message }`.
17
+ /// What the app didn't ask for at that moment arrives as the
18
+ /// `angularLynxGeolocation` global event, an object with a `type`: the
19
+ /// `state` changing, a watch's `position`s and a `watchStopped`, each with
20
+ /// the `watch` id its `startWatch` was given.
21
+ ///
22
+ /// A CLLocationManager calls its delegate on the run loop of the thread it
23
+ /// was made on, so every manager is made on the main thread, and everything
24
+ /// here (the methods Lynx calls on its JavaScript thread and the delegate's
25
+ /// callbacks alike) runs there, and the state needs no lock. Only
26
+ /// `locationServicesEnabled()`, which iOS warns may block the main thread,
27
+ /// is read on another queue (see `withServices`).
28
+ @objc(AngularLynxGeolocationModule)
29
+ final class GeolocationModule: NSObject, LynxContextModule, CLLocationManagerDelegate {
30
+ static var name: String { "AngularLynxGeolocation" }
31
+
32
+ static var methodLookup: [String: String] {
33
+ [
34
+ "getState": NSStringFromSelector(#selector(getState(_:))),
35
+ "requestPermission": NSStringFromSelector(#selector(requestPermission(_:))),
36
+ "getCurrentPosition": NSStringFromSelector(#selector(getCurrentPosition(_:callback:))),
37
+ "startWatch": NSStringFromSelector(#selector(startWatch(_:callback:))),
38
+ "stopWatch": NSStringFromSelector(#selector(stopWatch(_:callback:))),
39
+ ]
40
+ }
41
+
42
+ private static let eventName = "angularLynxGeolocation"
43
+
44
+ /// A one-off request for the position: its own manager, so its accuracy
45
+ /// doesn't change a watch's, the oldest fix that answers it, and the
46
+ /// deadline that answers `timeout`.
47
+ private final class Request {
48
+ let manager: CLLocationManager
49
+ let callback: LynxCallbackBlock
50
+ let oldest: Date
51
+ var deadline: DispatchWorkItem?
52
+
53
+ init(manager: CLLocationManager, callback: @escaping LynxCallbackBlock, oldest: Date) {
54
+ self.manager = manager
55
+ self.callback = callback
56
+ self.oldest = oldest
57
+ }
58
+ }
59
+
60
+ /// A watch's manager, its distance filter, and the last fix it sent.
61
+ private final class Watch {
62
+ let manager: CLLocationManager
63
+ let distance: CLLocationDistance
64
+ var last: CLLocation?
65
+
66
+ init(manager: CLLocationManager, distance: CLLocationDistance) {
67
+ self.manager = manager
68
+ self.distance = distance
69
+ }
70
+ }
71
+
72
+ private weak var context: LynxContext?
73
+
74
+ /// Where `withServices` reads whether Location is on (see there).
75
+ private let servicesQueue = DispatchQueue(
76
+ label: "dev.angularlynx.geolocation.services", qos: .userInitiated)
77
+
78
+ /// Reads and asks for the app's authorization. Making it shows nothing:
79
+ /// only `requestWhenInUseAuthorization()` shows iOS's prompt. Made on the
80
+ /// main thread on first use, since it calls its delegate there.
81
+ private var authorization: CLLocationManager?
82
+ private var destroyed = false
83
+
84
+ /// Calls that wait for the person to answer the prompt.
85
+ private var permissionWaiters: [() -> Void] = []
86
+
87
+ /// The one-off requests running, by their manager.
88
+ private var requests: [ObjectIdentifier: Request] = [:]
89
+
90
+ /// The watches running, by the id the runtime gave them, and each one's
91
+ /// manager's id back to it.
92
+ private var watches: [Int: Watch] = [:]
93
+ private var watchIDs: [ObjectIdentifier: Int] = [:]
94
+
95
+ /// The state the app last heard, so a `state` event goes out only when it
96
+ /// changes.
97
+ private var reportedState: String?
98
+
99
+ override init() {
100
+ super.init()
101
+ }
102
+
103
+ // Swift can't import an optional initializer as optional, so Lynx's
104
+ // initWithParam: and initWithLynxContext:WithParam: are required here.
105
+ init(param: Any) {
106
+ super.init()
107
+ }
108
+
109
+ init(lynxContext context: LynxContext) {
110
+ self.context = context
111
+ super.init()
112
+ }
113
+
114
+ init(lynxContext context: LynxContext, withParam param: Any) {
115
+ self.context = context
116
+ super.init()
117
+ }
118
+
119
+ /// Stops every request and watch, since Core Location would otherwise keep
120
+ /// finding the phone for a page that's gone. The calls still waiting
121
+ /// aren't answered: there's no page left to answer.
122
+ func destroy() {
123
+ DispatchQueue.main.async {
124
+ self.destroyed = true
125
+ self.permissionWaiters.removeAll()
126
+ for request in self.requests.values {
127
+ request.deadline?.cancel()
128
+ request.manager.stopUpdatingLocation()
129
+ request.manager.delegate = nil
130
+ }
131
+ self.requests.removeAll()
132
+ for watch in self.watches.values {
133
+ watch.manager.stopUpdatingLocation()
134
+ watch.manager.delegate = nil
135
+ }
136
+ self.watches.removeAll()
137
+ self.watchIDs.removeAll()
138
+ self.authorization?.delegate = nil
139
+ self.authorization = nil
140
+ }
141
+ }
142
+
143
+ // MARK: - Methods
144
+
145
+ /// `{ state }`, without asking the person.
146
+ @objc func getState(_ callback: @escaping LynxCallbackBlock) {
147
+ withServices { on in
148
+ callback(["state": self.state(servicesOn: on)])
149
+ }
150
+ }
151
+
152
+ /// `{ state }` once the person has answered iOS's prompt, which this shows
153
+ /// if they haven't been asked. With Location off for the whole phone it
154
+ /// answers `off` at once: iOS shows no prompt then, and the authorization
155
+ /// would never change.
156
+ @objc func requestPermission(_ callback: @escaping LynxCallbackBlock) {
157
+ withServices { on in
158
+ guard on else {
159
+ callback(["state": self.state(servicesOn: false)])
160
+ return
161
+ }
162
+ self.whenAnswered {
163
+ callback(["state": self.state(servicesOn: true)])
164
+ }
165
+ }
166
+ }
167
+
168
+ /// Finds the phone once: `options.accuracy` (`precise` or `approximate`),
169
+ /// `options.timeout` in milliseconds, and `options.maximumAge`, the oldest
170
+ /// position already known that answers at once. Calls back `{ position }`.
171
+ @objc func getCurrentPosition(_ options: [String: Any]?, callback: @escaping LynxCallbackBlock)
172
+ {
173
+ let precise = (options?["accuracy"] as? String) != "approximate"
174
+ let timeout = (options?["timeout"] as? NSNumber)?.doubleValue ?? 10_000
175
+ let maximumAge = (options?["maximumAge"] as? NSNumber)?.doubleValue ?? 0
176
+ whenPermitted(callback) {
177
+ if maximumAge > 0, let known = self.authorization?.location,
178
+ known.horizontalAccuracy >= 0,
179
+ -known.timestamp.timeIntervalSinceNow * 1000 <= maximumAge
180
+ {
181
+ callback(["position": Self.position(known)])
182
+ return
183
+ }
184
+ let manager = self.makeManager(precise: precise)
185
+ // A fix from before the request, which Core Location hands over first
186
+ // when it has one, answers only within maximumAge: 0, as the web's
187
+ // default, asks for a fix found afresh.
188
+ let request = Request(
189
+ manager: manager, callback: callback,
190
+ oldest: Date(timeIntervalSinceNow: -maximumAge / 1000))
191
+ let key = ObjectIdentifier(manager)
192
+ self.requests[key] = request
193
+ // finish() does nothing for a request that has answered already.
194
+ let deadline = DispatchWorkItem {
195
+ self.finish(key, ["error": "timeout", "message": "No position came in time."])
196
+ }
197
+ request.deadline = deadline
198
+ DispatchQueue.main.asyncAfter(deadline: .now() + timeout / 1000, execute: deadline)
199
+ // Updates rather than requestLocation(), which answers once, possibly
200
+ // with a fix older than maximumAge allows: finish() stops them at the
201
+ // first fresh one.
202
+ manager.startUpdatingLocation()
203
+ }
204
+ }
205
+
206
+ /// Starts watch `options.watch`: a position each time the phone moves
207
+ /// `options.distanceFilter` meters, at `options.accuracy`. Calls back `{}`
208
+ /// once it's started; the positions arrive as `position` events.
209
+ @objc func startWatch(_ options: [String: Any]?, callback: @escaping LynxCallbackBlock) {
210
+ let id = (options?["watch"] as? NSNumber)?.intValue ?? 0
211
+ let precise = (options?["accuracy"] as? String) != "approximate"
212
+ let distance = (options?["distanceFilter"] as? NSNumber)?.doubleValue ?? 0
213
+ whenPermitted(callback) {
214
+ let manager = self.makeManager(precise: precise)
215
+ // Every fix, filtered by distance from the last one sent in
216
+ // didUpdateLocations: Core Location's own filter measures from the
217
+ // last fix it delivered, which includes the ones the module dropped,
218
+ // so the two together could withhold a move past the filter.
219
+ manager.distanceFilter = kCLDistanceFilterNone
220
+ // A watch runs while the app is in use only: the app has no
221
+ // background location mode, so iOS pauses it in the background.
222
+ manager.pausesLocationUpdatesAutomatically = false
223
+ self.watches[id] = Watch(manager: manager, distance: distance)
224
+ self.watchIDs[ObjectIdentifier(manager)] = id
225
+ manager.startUpdatingLocation()
226
+ callback([:])
227
+ }
228
+ }
229
+
230
+ @objc func stopWatch(_ id: Double, callback: @escaping LynxCallbackBlock) {
231
+ DispatchQueue.main.async {
232
+ self.endWatch(Int(id))
233
+ callback([:])
234
+ }
235
+ }
236
+
237
+ // MARK: - CLLocationManagerDelegate
238
+
239
+ func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
240
+ guard manager === authorization, !destroyed else { return }
241
+ // It's called once as the manager is made, too, before anyone answered.
242
+ if manager.authorizationStatus != .notDetermined {
243
+ let waiting = permissionWaiters
244
+ permissionWaiters.removeAll()
245
+ waiting.forEach { $0() }
246
+ }
247
+ // The watches running now: one started after the services read below
248
+ // began started with the newer answer, so this one mustn't end it.
249
+ let running = Array(watches.keys)
250
+ withServices { on in
251
+ let state = self.state(servicesOn: on)
252
+ // The watches can't go on once the app may not find the phone,
253
+ // including when an Allow Once grant expires and iOS goes back to
254
+ // not determined. The runtime asks again if the app starts another.
255
+ if state == "denied" || state == "off" || state == "unknown" {
256
+ for id in running where self.watches[id] != nil {
257
+ self.endWatch(id)
258
+ self.send([
259
+ "type": "watchStopped", "watch": id, "error": state == "off" ? "off" : "denied",
260
+ "message": Self.message(for: state),
261
+ ])
262
+ }
263
+ }
264
+ guard state != self.reportedState else { return }
265
+ self.reportedState = state
266
+ self.send(["type": "state", "state": state])
267
+ }
268
+ }
269
+
270
+ func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
271
+ let key = ObjectIdentifier(manager)
272
+ // A location without a horizontal accuracy isn't valid.
273
+ let valid = locations.filter { $0.horizontalAccuracy >= 0 }
274
+ if let request = requests[key] {
275
+ guard let fresh = valid.last(where: { $0.timestamp >= request.oldest }) else { return }
276
+ finish(key, ["position": Self.position(fresh)])
277
+ } else if let id = watchIDs[key], let watch = watches[id] {
278
+ for location in valid {
279
+ // The watch's distance filter, from the last fix sent, as on Android
280
+ // and the web (Core Location's own is off: see startWatch).
281
+ if watch.distance > 0, let last = watch.last,
282
+ location.distance(from: last) < watch.distance
283
+ {
284
+ continue
285
+ }
286
+ watch.last = location
287
+ send(["type": "position", "watch": id, "position": Self.position(location)])
288
+ }
289
+ }
290
+ }
291
+
292
+ func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
293
+ let key = ObjectIdentifier(manager)
294
+ let code = (error as? CLError)?.code
295
+ if requests[key] != nil {
296
+ // locationUnknown is for now: Core Location keeps trying until the
297
+ // deadline.
298
+ if code == .locationUnknown { return }
299
+ if code == .denied {
300
+ finish(key, ["error": "denied", "message": Self.message(for: "denied")])
301
+ } else {
302
+ finish(key, ["error": "failed", "message": "No position: \(error.localizedDescription)"])
303
+ }
304
+ } else if let id = watchIDs[key] {
305
+ // locationUnknown is for now: Core Location keeps trying. A refusal
306
+ // also changes the authorization, which ends every watch, so only
307
+ // what's left ends this one.
308
+ guard code != .locationUnknown, code != .denied else { return }
309
+ endWatch(id)
310
+ send([
311
+ "type": "watchStopped", "watch": id, "error": "failed",
312
+ "message": "The location failed: \(error.localizedDescription)",
313
+ ])
314
+ }
315
+ }
316
+
317
+ // MARK: - Helpers
318
+
319
+ /// The runtime's name for the app's authorization, with Location turned
320
+ /// off for the whole phone first: iOS then reports every app as denied.
321
+ private func state(servicesOn: Bool) -> String {
322
+ guard let manager = authorization else { return "unknown" }
323
+ switch manager.authorizationStatus {
324
+ case .notDetermined: return servicesOn ? "unknown" : "off"
325
+ case .denied: return servicesOn ? "denied" : "off"
326
+ case .restricted: return "denied"
327
+ case .authorizedWhenInUse, .authorizedAlways:
328
+ if !servicesOn { return "off" }
329
+ return manager.accuracyAuthorization == .fullAccuracy ? "precise" : "approximate"
330
+ @unknown default: return "denied"
331
+ }
332
+ }
333
+
334
+ /// Runs `body` on the main thread with whether Location is on for the
335
+ /// phone, read on `servicesQueue`: iOS warns that reading it on the main
336
+ /// thread can block the UI. Makes the authorization manager first.
337
+ ///
338
+ /// The queue is serial, so the reads happen in the order they're asked
339
+ /// for, and each hands its answer to the main queue after the one before:
340
+ /// a body never runs with an answer older than one a body already used,
341
+ /// which could send `off`, and end the watches, after Location came back
342
+ /// on.
343
+ private func withServices(_ body: @escaping (Bool) -> Void) {
344
+ DispatchQueue.main.async {
345
+ self.makeAuthorization()
346
+ self.servicesQueue.async {
347
+ let on = CLLocationManager.locationServicesEnabled()
348
+ DispatchQueue.main.async {
349
+ guard !self.destroyed else { return }
350
+ body(on)
351
+ }
352
+ }
353
+ }
354
+ }
355
+
356
+ private func makeAuthorization() {
357
+ guard authorization == nil, !destroyed else { return }
358
+ let manager = CLLocationManager()
359
+ manager.delegate = self
360
+ authorization = manager
361
+ }
362
+
363
+ /// Runs `body` once the person has answered the prompt, showing it if
364
+ /// they haven't been asked. Must be called on the main thread.
365
+ private func whenAnswered(_ body: @escaping () -> Void) {
366
+ makeAuthorization()
367
+ guard let manager = authorization else { return }
368
+ guard manager.authorizationStatus == .notDetermined else {
369
+ body()
370
+ return
371
+ }
372
+ permissionWaiters.append(body)
373
+ if permissionWaiters.count == 1 {
374
+ manager.requestWhenInUseAuthorization()
375
+ }
376
+ }
377
+
378
+ /// Runs `action` on the main thread once the app may find the phone,
379
+ /// asking first if the person hasn't been asked. Otherwise `callback`
380
+ /// answers why not.
381
+ private func whenPermitted(
382
+ _ callback: @escaping LynxCallbackBlock, _ action: @escaping () -> Void
383
+ ) {
384
+ withServices { on in
385
+ guard on else {
386
+ callback(["error": "off", "message": Self.message(for: "off")])
387
+ return
388
+ }
389
+ self.whenAnswered {
390
+ switch self.state(servicesOn: true) {
391
+ case "precise", "approximate": action()
392
+ default: callback(["error": "denied", "message": Self.message(for: "denied")])
393
+ }
394
+ }
395
+ }
396
+ }
397
+
398
+ private func makeManager(precise: Bool) -> CLLocationManager {
399
+ let manager = CLLocationManager()
400
+ manager.delegate = self
401
+ // Reduced accuracy is a few kilometers, from Wi-Fi and cell towers,
402
+ // which is quicker and cheaper than GPS.
403
+ manager.desiredAccuracy = precise ? kCLLocationAccuracyBest : kCLLocationAccuracyReduced
404
+ return manager
405
+ }
406
+
407
+ /// Answers a one-off request, once, and lets its manager go.
408
+ private func finish(_ key: ObjectIdentifier, _ result: [String: Any]) {
409
+ guard let request = requests.removeValue(forKey: key) else { return }
410
+ request.deadline?.cancel()
411
+ request.manager.stopUpdatingLocation()
412
+ request.manager.delegate = nil
413
+ request.callback(result)
414
+ }
415
+
416
+ private func endWatch(_ id: Int) {
417
+ guard let manager = watches.removeValue(forKey: id)?.manager else { return }
418
+ watchIDs.removeValue(forKey: ObjectIdentifier(manager))
419
+ manager.stopUpdatingLocation()
420
+ manager.delegate = nil
421
+ }
422
+
423
+ private func send(_ payload: [String: Any]) {
424
+ guard !destroyed else { return }
425
+ context?.sendGlobalEvent(Self.eventName, withParams: [payload])
426
+ }
427
+
428
+ private static func message(for code: String) -> String {
429
+ code == "off"
430
+ ? "Location is turned off for the phone."
431
+ : "The app isn't allowed to find the phone."
432
+ }
433
+
434
+ /// A location as the runtime reads it. What iOS doesn't know (a negative
435
+ /// accuracy, course or speed) is left out, and the runtime reads it as
436
+ /// null.
437
+ private static func position(_ location: CLLocation) -> [String: Any] {
438
+ var position: [String: Any] = [
439
+ "latitude": location.coordinate.latitude,
440
+ "longitude": location.coordinate.longitude,
441
+ "accuracy": location.horizontalAccuracy,
442
+ "timestamp": (location.timestamp.timeIntervalSince1970 * 1000).rounded(),
443
+ ]
444
+ // Above the WGS 84 ellipsoid, as the web and Android give it:
445
+ // `altitude` is above sea level.
446
+ // Core Location's altitude is invalid when its accuracy isn't positive.
447
+ if location.verticalAccuracy > 0 {
448
+ position["altitude"] = location.ellipsoidalAltitude
449
+ position["altitudeAccuracy"] = location.verticalAccuracy
450
+ }
451
+ if location.course >= 0 { position["heading"] = location.course }
452
+ if location.speed >= 0 { position["speed"] = location.speed }
453
+ return position
454
+ }
455
+ }
@@ -0,0 +1,90 @@
1
+ import Lynx
2
+ import UIKit
3
+
4
+ /// The native module behind the runtime's `LynxHaptics`, which calls it as
5
+ /// `NativeModules.AngularLynxHaptics` (from the background thread, where
6
+ /// NativeModules lives).
7
+ ///
8
+ /// Each method plays its feedback on the haptic engine and calls back once
9
+ /// with `{}`. iOS plays nothing where the person turned System Haptics off,
10
+ /// and on a device without a haptic engine.
11
+ final class HapticsModule: NSObject, LynxModule {
12
+ static var name: String { "AngularLynxHaptics" }
13
+
14
+ static var methodLookup: [String: String] {
15
+ [
16
+ "impact": NSStringFromSelector(#selector(impact(_:callback:))),
17
+ "selection": NSStringFromSelector(#selector(selection(_:))),
18
+ "notification": NSStringFromSelector(#selector(notification(_:callback:))),
19
+ ]
20
+ }
21
+
22
+ // The generators, made on first use and kept: a generator that's
23
+ // prepared plays without the haptic engine's warm-up, which matters for
24
+ // a slider ticking through its steps. Only touched on the main thread.
25
+ private var impacts: [UIImpactFeedbackGenerator.FeedbackStyle: UIImpactFeedbackGenerator] = [:]
26
+ private lazy var selectionGenerator = UISelectionFeedbackGenerator()
27
+ private lazy var notificationGenerator = UINotificationFeedbackGenerator()
28
+
29
+ override init() {
30
+ super.init()
31
+ }
32
+
33
+ // Swift can't import an optional initializer as optional, so Lynx's
34
+ // initWithParam: is required here. Registered without a param, the module
35
+ // ignores it.
36
+ init(param: Any) {
37
+ super.init()
38
+ }
39
+
40
+ // Lynx calls modules off the main thread, and the generators are UIKit's.
41
+ // Each is prepared again after it plays, so the next feedback in the
42
+ // next few seconds, such as a slider's next step, plays at once.
43
+ @objc func impact(_ style: String, callback: @escaping LynxCallbackBlock) {
44
+ DispatchQueue.main.async {
45
+ let style = Self.impactStyle(style)
46
+ let generator = self.impacts[style] ?? UIImpactFeedbackGenerator(style: style)
47
+ self.impacts[style] = generator
48
+ generator.impactOccurred()
49
+ generator.prepare()
50
+ callback([:])
51
+ }
52
+ }
53
+
54
+ @objc func selection(_ callback: @escaping LynxCallbackBlock) {
55
+ DispatchQueue.main.async {
56
+ self.selectionGenerator.selectionChanged()
57
+ self.selectionGenerator.prepare()
58
+ callback([:])
59
+ }
60
+ }
61
+
62
+ @objc func notification(_ type: String, callback: @escaping LynxCallbackBlock) {
63
+ DispatchQueue.main.async {
64
+ self.notificationGenerator.notificationOccurred(Self.notificationType(type))
65
+ self.notificationGenerator.prepare()
66
+ callback([:])
67
+ }
68
+ }
69
+
70
+ /// The runtime's HapticImpactStyle. A name it doesn't send taps medium,
71
+ /// as the runtime's default does.
72
+ private static func impactStyle(_ name: String) -> UIImpactFeedbackGenerator.FeedbackStyle {
73
+ switch name {
74
+ case "light": return .light
75
+ case "heavy": return .heavy
76
+ case "soft": return .soft
77
+ case "rigid": return .rigid
78
+ default: return .medium
79
+ }
80
+ }
81
+
82
+ /// The runtime's HapticNotificationType, success unless it's another.
83
+ private static func notificationType(_ name: String) -> UINotificationFeedbackGenerator.FeedbackType {
84
+ switch name {
85
+ case "warning": return .warning
86
+ case "error": return .error
87
+ default: return .success
88
+ }
89
+ }
90
+ }