@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,430 @@
1
+ import CoreLocation
2
+ import CoreMotion
3
+ import Lynx
4
+ import UIKit
5
+
6
+ /// The native module behind the runtime's `LynxMotion`, which calls it as
7
+ /// `NativeModules.AngularLynxMotion` (from the background thread, where
8
+ /// NativeModules lives).
9
+ ///
10
+ /// `start(sensor, interval)` runs a sensor, sampling every `interval`
11
+ /// milliseconds, or changes how often; `stop(sensor)` stops it; and
12
+ /// `availability` calls back with which sensors the phone has. The sensors
13
+ /// are `acceleration` (the accelerometer, in m/s² with gravity), `rotation`
14
+ /// (Core Motion's device motion rotation rate, in rad/s), `orientation`
15
+ /// (device motion's attitude, as a rotation matrix), `heading`
16
+ /// (`CLLocationManager`'s heading, which asks for no location permission)
17
+ /// and `shake`, which this module hears from the accelerometer itself, so a
18
+ /// shake costs the runtime one event rather than 50 samples a second.
19
+ ///
20
+ /// The samples go to the runtime in the `angularLynxMotion` global event,
21
+ /// one object with a flat array of numbers for each sensor that sampled
22
+ /// (see `MotionBatch` in the runtime's motion.ts), at most once every 16 ms:
23
+ /// each event is work for Lynx's engine thread, where Angular runs. The
24
+ /// sensors stop while the app is in the background, and start again when it
25
+ /// comes back.
26
+ ///
27
+ /// The generator leaves this file out of an app whose angular.json doesn't
28
+ /// set `motion`, and LynxViewController registers the module by its
29
+ /// Objective-C name only when it's there, hence the `@objc` name.
30
+ @objc(AngularLynxMotionModule)
31
+ final class MotionModule: NSObject, LynxContextModule, CLLocationManagerDelegate {
32
+ static var name: String { "AngularLynxMotion" }
33
+
34
+ static var methodLookup: [String: String] {
35
+ [
36
+ "start": NSStringFromSelector(#selector(start(_:interval:))),
37
+ "stop": NSStringFromSelector(#selector(stop(_:))),
38
+ "availability": NSStringFromSelector(#selector(availability(_:))),
39
+ ]
40
+ }
41
+
42
+ static let event = "angularLynxMotion"
43
+ /// The least time between events, about a frame.
44
+ private static let flushInterval = 0.016
45
+ /// How often the accelerometer samples for shakes: the runtime's
46
+ /// `SHAKE.intervalMs`.
47
+ private static let shakeInterval = 0.02
48
+
49
+ private weak var context: LynxContext?
50
+ /// Everything below belongs to this queue, and the sensors' handlers run
51
+ /// on it. Lynx calls modules on threads of its own.
52
+ private let queue = DispatchQueue(label: "dev.angularlynx.motion")
53
+ private lazy var handlers: OperationQueue = {
54
+ let operations = OperationQueue()
55
+ operations.underlyingQueue = queue
56
+ operations.maxConcurrentOperationCount = 1
57
+ return operations
58
+ }()
59
+ private let manager = CMMotionManager()
60
+ /// Made, started and stopped on the main thread, which its delegate
61
+ /// methods are called on.
62
+ private var locationManager: CLLocationManager?
63
+ /// The interval each running sensor was started at, in seconds.
64
+ private var requested: [String: TimeInterval] = [:]
65
+ /// The intervals the hardware runs at now, to restart it only on a change.
66
+ private var accelerometerInterval: TimeInterval?
67
+ private var deviceMotionInterval: TimeInterval?
68
+ private var headingOn = false
69
+ /// When each sensor's last sample was kept, in milliseconds.
70
+ private var lastSample: [String: Double] = [:]
71
+ private var batch: [String: [Double]] = [:]
72
+ private var flushScheduled = false
73
+ private var lastFlush: TimeInterval = 0
74
+ private var inBackground = false
75
+ private var shakes = ShakeDetector()
76
+ /// Turns the uptime Core Motion stamps its samples with into milliseconds
77
+ /// since the epoch.
78
+ private let clock = MotionClock()
79
+ private var observers: [NSObjectProtocol] = []
80
+
81
+ override init() {
82
+ super.init()
83
+ }
84
+
85
+ // Swift can't import an optional initializer as optional, so Lynx's
86
+ // initWithParam: and initWithLynxContext:WithParam: are required here.
87
+ init(param: Any) {
88
+ super.init()
89
+ }
90
+
91
+ init(lynxContext context: LynxContext) {
92
+ self.context = context
93
+ super.init()
94
+ observeAppState()
95
+ }
96
+
97
+ init(lynxContext context: LynxContext, withParam param: Any) {
98
+ self.context = context
99
+ super.init()
100
+ observeAppState()
101
+ }
102
+
103
+ deinit {
104
+ observers.forEach { NotificationCenter.default.removeObserver($0) }
105
+ }
106
+
107
+ /// The LynxView is going: nothing should keep the sensors on for it.
108
+ func destroy() {
109
+ queue.async {
110
+ self.requested.removeAll()
111
+ self.apply()
112
+ }
113
+ }
114
+
115
+ @objc func start(_ sensor: String, interval: Double) {
116
+ queue.async {
117
+ // At least 5 ms, as the runtime asks: Core Motion's rates top out
118
+ // near 100 Hz on most iPhones anyway.
119
+ self.requested[sensor] = max(interval, 5) / 1000
120
+ self.apply()
121
+ }
122
+ }
123
+
124
+ @objc func stop(_ sensor: String) {
125
+ queue.async {
126
+ self.requested.removeValue(forKey: sensor)
127
+ self.lastSample.removeValue(forKey: sensor)
128
+ // Samples still waiting for the next event were for the watches that
129
+ // just stopped: a shake heard before a new listener came mustn't reach
130
+ // it.
131
+ self.batch.removeValue(forKey: sensor)
132
+ // A shake begun for the last listener can't be finished for the next.
133
+ if sensor == "shake" { self.shakes = ShakeDetector() }
134
+ self.apply()
135
+ }
136
+ }
137
+
138
+ /// Calls back with which sensors the phone has. The Simulator has none.
139
+ @objc func availability(_ callback: @escaping LynxCallbackBlock) {
140
+ callback([
141
+ "acceleration": manager.isAccelerometerAvailable,
142
+ "rotation": manager.isGyroAvailable && manager.isDeviceMotionAvailable,
143
+ "orientation": manager.isDeviceMotionAvailable,
144
+ "heading": CLLocationManager.headingAvailable(),
145
+ ])
146
+ }
147
+
148
+ /// Stops the sensors while the app is in the background, where Lynx
149
+ /// pauses the runtime and nobody sees what they'd measure.
150
+ private func observeAppState() {
151
+ let center = NotificationCenter.default
152
+ observers = [
153
+ center.addObserver(
154
+ forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil
155
+ ) { [weak self] _ in
156
+ self?.queue.async {
157
+ self?.inBackground = true
158
+ // Samples from before the app left aren't sent after it, and
159
+ // aren't half of a shake with one after it either.
160
+ self?.batch.removeAll()
161
+ self?.shakes = ShakeDetector()
162
+ self?.apply()
163
+ }
164
+ },
165
+ center.addObserver(
166
+ forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil
167
+ ) { [weak self] _ in
168
+ self?.queue.async {
169
+ self?.inBackground = false
170
+ self?.apply()
171
+ }
172
+ },
173
+ ]
174
+ }
175
+
176
+ /// Runs each piece of hardware at the shortest interval anything asks of
177
+ /// it, or stops it. On the queue.
178
+ private func apply() {
179
+ let wanted = inBackground ? [:] : requested
180
+
181
+ // The accelerometer serves the acceleration and the shakes.
182
+ var accelerometer = wanted["acceleration"]
183
+ if wanted["shake"] != nil {
184
+ accelerometer = min(accelerometer ?? Self.shakeInterval, Self.shakeInterval)
185
+ }
186
+ if accelerometer != accelerometerInterval {
187
+ manager.stopAccelerometerUpdates()
188
+ accelerometerInterval = accelerometer
189
+ if let interval = accelerometer, manager.isAccelerometerAvailable {
190
+ manager.accelerometerUpdateInterval = interval
191
+ manager.startAccelerometerUpdates(to: handlers) { [weak self] data, _ in
192
+ if let data { self?.accelerometer(data) }
193
+ }
194
+ }
195
+ }
196
+
197
+ // Device motion, which fuses the accelerometer and the gyroscope, serves
198
+ // the rotation rate (without the gyroscope's drift) and the attitude.
199
+ // Its yaw counts from where the phone faced when it started, without the
200
+ // magnetometer, as Android's game rotation vector does.
201
+ let motion = [wanted["rotation"], wanted["orientation"]].compactMap { $0 }.min()
202
+ if let interval = motion, deviceMotionInterval != nil, manager.isDeviceMotionActive {
203
+ // Already running: only the rate changes. A restart would take the
204
+ // phone's heading now as the new zero of .xArbitraryZVertical, and a
205
+ // watch of the orientation would see alpha jump when another watch
206
+ // starts or stops.
207
+ if interval != deviceMotionInterval {
208
+ manager.deviceMotionUpdateInterval = interval
209
+ deviceMotionInterval = interval
210
+ }
211
+ } else if motion != deviceMotionInterval {
212
+ manager.stopDeviceMotionUpdates()
213
+ deviceMotionInterval = motion
214
+ if let interval = motion, manager.isDeviceMotionAvailable {
215
+ manager.deviceMotionUpdateInterval = interval
216
+ manager.startDeviceMotionUpdates(using: .xArbitraryZVertical, to: handlers) {
217
+ [weak self] data, _ in
218
+ if let data { self?.deviceMotion(data) }
219
+ }
220
+ }
221
+ }
222
+
223
+ let heading = wanted["heading"] != nil
224
+ if heading != headingOn {
225
+ headingOn = heading
226
+ DispatchQueue.main.async { self.setHeading(on: heading) }
227
+ }
228
+ }
229
+
230
+ /// On the main thread, where CLLocationManager wants to be made and calls
231
+ /// its delegate.
232
+ private func setHeading(on: Bool) {
233
+ guard CLLocationManager.headingAvailable() else { return }
234
+ if on {
235
+ let manager = locationManager ?? CLLocationManager()
236
+ manager.delegate = self
237
+ // A new heading for each degree it turns: the runtime throttles to the
238
+ // watch's interval, and a phone held still reports nothing.
239
+ manager.headingFilter = 1
240
+ locationManager = manager
241
+ manager.startUpdatingHeading()
242
+ } else {
243
+ locationManager?.stopUpdatingHeading()
244
+ }
245
+ }
246
+
247
+ func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
248
+ // A negative accuracy means iOS has no heading at all, not one of
249
+ // unknown accuracy.
250
+ guard newHeading.headingAccuracy >= 0 else { return }
251
+ let t = clock.milliseconds(ProcessInfo.processInfo.systemUptime)
252
+ let magnetic = newHeading.magneticHeading
253
+ // Negative when iOS doesn't know: true north needs the location, which
254
+ // the app may not have access to.
255
+ let trueHeading = newHeading.trueHeading >= 0 ? newHeading.trueHeading : -1
256
+ let accuracy = newHeading.headingAccuracy
257
+ queue.async {
258
+ // One that came as the app went to the background, before the
259
+ // heading stopped.
260
+ guard !self.inBackground, self.keep("heading", at: t) else { return }
261
+ self.add("heading", [t, magnetic, trueHeading, accuracy])
262
+ }
263
+ }
264
+
265
+ private func accelerometer(_ data: CMAccelerometerData) {
266
+ // One Core Motion queued before the app went to the background and the
267
+ // accelerometer stopped, as the heading's delegate skips.
268
+ guard !inBackground else { return }
269
+ let t = clock.milliseconds(data.timestamp)
270
+ // Core Motion measures in g, and as the force on the phone: a phone
271
+ // lying face up reads z = -1. The web and Android give the acceleration
272
+ // in m/s² the other way round, z = 9.81, so the runtime gets the same on
273
+ // both.
274
+ let g = -9.80665
275
+ let (x, y, z) = (data.acceleration.x * g, data.acceleration.y * g, data.acceleration.z * g)
276
+ if requested["acceleration"] != nil, keep("acceleration", at: t) {
277
+ add("acceleration", [t, x, y, z])
278
+ }
279
+ if requested["shake"] != nil, shakes.add(t, x, y, z) {
280
+ add("shake", [t])
281
+ }
282
+ }
283
+
284
+ private func deviceMotion(_ data: CMDeviceMotion) {
285
+ guard !inBackground else { return }
286
+ let t = clock.milliseconds(data.timestamp)
287
+ if requested["rotation"] != nil, keep("rotation", at: t) {
288
+ let rate = data.rotationRate
289
+ add("rotation", [t, rate.x, rate.y, rate.z])
290
+ }
291
+ if requested["orientation"] != nil, keep("orientation", at: t) {
292
+ add("orientation", [t] + Self.deviceToEarth(data))
293
+ }
294
+ }
295
+
296
+ /// The attitude as the matrix the runtime reads: the one that turns a
297
+ /// vector in the phone's frame into the earth's, row by row, as Android's
298
+ /// `getRotationMatrixFromVector` makes it. Its last row is the earth's up
299
+ /// in the phone's frame, which is gravity turned around.
300
+ ///
301
+ /// Apple doesn't say which way `CMRotationMatrix` turns, so the matrix is
302
+ /// taken as it is or transposed, whichever's last row points up as gravity
303
+ /// says it should.
304
+ private static func deviceToEarth(_ data: CMDeviceMotion) -> [Double] {
305
+ let m = data.attitude.rotationMatrix
306
+ let up = (-data.gravity.x, -data.gravity.y, -data.gravity.z)
307
+ let asIs = [m.m11, m.m12, m.m13, m.m21, m.m22, m.m23, m.m31, m.m32, m.m33]
308
+ let transposed = [m.m11, m.m21, m.m31, m.m12, m.m22, m.m32, m.m13, m.m23, m.m33]
309
+ let dot = { (r: [Double]) in r[6] * up.0 + r[7] * up.1 + r[8] * up.2 }
310
+ return dot(transposed) >= dot(asIs) ? transposed : asIs
311
+ }
312
+
313
+ /// Whether a sensor's sample at `t` is due, by the interval it was started
314
+ /// at, allowing a little early for the sensor's jitter. Marks it kept.
315
+ private func keep(_ sensor: String, at t: Double) -> Bool {
316
+ guard let interval = requested[sensor] else { return false }
317
+ // The runtime's own rule (`due()` in motion.ts): a sample up to a quarter
318
+ // of the interval early, 4 ms at most, counts. A wider one here would
319
+ // pass samples the runtime then skips, halving a watch's rate.
320
+ let ms = interval * 1000
321
+ if let last = lastSample[sensor], t - last < ms - min(4, ms / 4) { return false }
322
+ lastSample[sensor] = t
323
+ return true
324
+ }
325
+
326
+ /// Adds a sample to the next event, which goes at most every 16 ms.
327
+ private func add(_ sensor: String, _ values: [Double]) {
328
+ batch[sensor, default: []].append(contentsOf: values)
329
+ guard !flushScheduled else { return }
330
+ flushScheduled = true
331
+ let wait = max(0, lastFlush + Self.flushInterval - ProcessInfo.processInfo.systemUptime)
332
+ queue.asyncAfter(deadline: .now() + wait) { self.flush() }
333
+ }
334
+
335
+ private func flush() {
336
+ flushScheduled = false
337
+ lastFlush = ProcessInfo.processInfo.systemUptime
338
+ guard !batch.isEmpty else { return }
339
+ let sent = batch
340
+ batch = [:]
341
+ context?.sendGlobalEvent(Self.event, withParams: [sent])
342
+ }
343
+ }
344
+
345
+ /// Stamps the samples in milliseconds since the epoch, as the runtime's
346
+ /// `Date.now()` counts, from the epoch time of the phone's start read once:
347
+ /// each time is counted from there, so the times only go forward, and
348
+ /// spacing and shakes go by them, even when the system's clock is changed.
349
+ ///
350
+ /// Core Motion stamps a sample with the uptime (`systemUptime`, Mach's
351
+ /// absolute time), which stops while the phone sleeps. Counted from the
352
+ /// start on that clock alone, every stamp would fall behind by all the time
353
+ /// the phone has ever slept (issue #1021), and `onShake()`, which notes
354
+ /// `Date.now()` as a handler starts, would skip each shake after the phone
355
+ /// woke. So the start is read on Mach's continuous time, which counts the
356
+ /// sleep, and each stamp adds the sleep so far to the sample's uptime, as
357
+ /// Android's `elapsedRealtimeNanos()` includes it. The sleep only changes
358
+ /// while the phone sleeps, and the app is in the background then, its
359
+ /// sensors stopped, so no sample measured before a sleep is stamped after.
360
+ struct MotionClock {
361
+ /// Seconds since the phone started, with the sleep and without it. They're
362
+ /// parameters only so a test can put the phone to sleep.
363
+ private let continuousTime: () -> TimeInterval
364
+ private let uptime: () -> TimeInterval
365
+ private let epochAtBoot: TimeInterval
366
+
367
+ init(
368
+ continuousTime: @escaping () -> TimeInterval = MotionClock.machContinuousTime,
369
+ uptime: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
370
+ ) {
371
+ self.continuousTime = continuousTime
372
+ self.uptime = uptime
373
+ epochAtBoot = Date().timeIntervalSince1970 - continuousTime()
374
+ }
375
+
376
+ /// An uptime, seconds the phone has been awake since it started, in
377
+ /// milliseconds since the epoch.
378
+ func milliseconds(_ uptime: TimeInterval) -> Double {
379
+ (epochAtBoot + slept() + uptime) * 1000
380
+ }
381
+
382
+ /// How long the phone has slept since it started, in seconds: the time
383
+ /// that counts sleep less the uptime, which doesn't.
384
+ private func slept() -> TimeInterval {
385
+ // The uptime first, so the nanoseconds between the two reads add to the
386
+ // sleep rather than taking it below zero.
387
+ let awake = uptime()
388
+ return continuousTime() - awake
389
+ }
390
+
391
+ /// Mach's continuous time, which goes on while the phone sleeps, in seconds.
392
+ /// Its ticks are 1 ns on Intel and 125/3 ns on Apple silicon.
393
+ static func machContinuousTime() -> TimeInterval {
394
+ Double(mach_continuous_time()) * Double(timebase.numer) / Double(timebase.denom)
395
+ / 1_000_000_000
396
+ }
397
+
398
+ private static let timebase: mach_timebase_info_data_t = {
399
+ var info = mach_timebase_info_data_t()
400
+ mach_timebase_info(&info)
401
+ return info
402
+ }()
403
+ }
404
+
405
+ /// Hears a shake in accelerometer samples: the runtime's `ShakeDetector`
406
+ /// (`motion/motion-math.ts`), after Square's Seismic. A sample accelerates
407
+ /// past 13 m/s², and the phone is shaking when three quarters of the samples
408
+ /// of the last half second do, over a quarter of a second or more.
409
+ private struct ShakeDetector {
410
+ private var samples: [(t: Double, accelerating: Bool)] = []
411
+ private var accelerating = 0
412
+ private var quietUntil = -Double.infinity
413
+
414
+ mutating func add(_ t: Double, _ x: Double, _ y: Double, _ z: Double) -> Bool {
415
+ let fast = x * x + y * y + z * z > 13 * 13
416
+ samples.append((t, fast))
417
+ if fast { accelerating += 1 }
418
+ while let first = samples.first, first.t < t - 500 {
419
+ if samples.removeFirst().accelerating { accelerating -= 1 }
420
+ }
421
+ if t < quietUntil { return false }
422
+ guard let first = samples.first, samples.count >= 4, t - first.t >= 250,
423
+ accelerating * 4 >= samples.count * 3
424
+ else { return false }
425
+ samples.removeAll()
426
+ accelerating = 0
427
+ quietUntil = t + 750
428
+ return true
429
+ }
430
+ }
@@ -0,0 +1,41 @@
1
+ import Foundation
2
+ import Network
3
+
4
+ /// Whether the phone has a connection to the internet, for LynxNetwork, which
5
+ /// LynxViewController sends in the `online` global prop. Lynx tells the app's
6
+ /// code nothing about the connection, and has no `navigator.onLine`, so the
7
+ /// shell watches it itself.
8
+ ///
9
+ /// Online while NWPathMonitor's path is `satisfied`: there's a route out,
10
+ /// over Wi-Fi, cellular or a wired link. It needs no permission and shows the
11
+ /// user nothing.
12
+ final class NetworkStatus {
13
+ private let monitor = NWPathMonitor()
14
+
15
+ /// Online until the monitor's first path arrives, which comes just after
16
+ /// it starts: the first global props go out before that, and an app
17
+ /// shouldn't flash an offline screen at every launch.
18
+ private(set) var online = true
19
+
20
+ /// - Parameter onChange: called on the main queue each time `online`
21
+ /// changes, and only then: a new path with the same answer (another
22
+ /// Wi-Fi, or a switch to cellular) would only make the app run its
23
+ /// change detection for nothing.
24
+ init(onChange: @escaping (Bool) -> Void) {
25
+ monitor.pathUpdateHandler = { [weak self] path in
26
+ let online = path.status == .satisfied
27
+ guard let self, self.online != online else { return }
28
+ self.online = online
29
+ onChange(online)
30
+ }
31
+ // The main queue, where the controller's LynxView takes its updates and
32
+ // `online` is read: no hop between threads, and nothing to lock.
33
+ monitor.start(queue: .main)
34
+ }
35
+
36
+ /// The monitor runs until it's canceled, so it stops with its controller,
37
+ /// which iOS can drop with its scene and build again.
38
+ deinit {
39
+ monitor.cancel()
40
+ }
41
+ }