-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
866 lines (829 loc) · 28.5 KB
/
Copy pathAppDelegate.swift
File metadata and controls
866 lines (829 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
import BackgroundTasks
import CoreHaptics
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
private var customHapticEngine: CHHapticEngine?
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FreshInstallKeychainCleaner.runIfNeeded()
// `batteryState` reports `.unknown` until monitoring is on, and the
// background Tor gate reads that state to decide whether this device can
// afford a Tor pass. Enable it here, on the main thread, before any task
// handler can run — a background task launch reaches this method first, so
// the gate finds a real state instead of deferring on `.unknown`.
UIDevice.current.isBatteryMonitoringEnabled = true
BackgroundMigrationManager.shared.registerBackgroundTask()
if #available(iOS 26.0, *) {
// One-release tombstone for requests submitted by the removed general
// background-sync feature. Do not register a handler for this identifier.
BGTaskScheduler.shared.cancel(
taskRequestWithIdentifier: "com.keplr.vizor.sync"
)
// A BGTask cold-launches the app with a background application state.
// Cancelling here unconditionally removes the very request iOS is
// launching us to service. Only a user-driven foreground launch should
// discard a stale pending preparation request.
if application.applicationState != .background {
BackgroundMigrationPreparationManager.shared
.handoffPendingRequestForForegroundLaunch()
}
BackgroundMigrationPreparationManager.shared.registerBackgroundTask()
BGTaskScheduler.shared.cancel(
taskRequestWithIdentifier: "com.keplr.vizor.txtrack"
)
}
if application.applicationState != .background {
IronwoodMigrationNotificationGate.shared.enforceOnForeground()
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func applicationWillEnterForeground(_ application: UIApplication) {
IronwoodMigrationNotificationGate.shared.enforceOnForeground()
if #available(iOS 26.0, *) {
BackgroundMigrationManager.shared.handoffToForeground()
}
super.applicationWillEnterForeground(application)
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
let messenger = engineBridge.applicationRegistrar.messenger()
let keychainAccessibilityMigrationHandler =
KeychainAccessibilityMigrationChannel()
let keychainAccessibilityMigrationChannel = FlutterMethodChannel(
name: keychainAccessibilityMigrationChannelName,
binaryMessenger: messenger
)
keychainAccessibilityMigrationChannel.setMethodCallHandler { call, result in
keychainAccessibilityMigrationHandler.handle(call, result: result)
}
let backgroundMigrationChannel = FlutterMethodChannel(
name: "com.zcash.wallet/background_migration",
binaryMessenger: messenger
)
backgroundMigrationChannel.setMethodCallHandler { call, result in
switch call.method {
case "getNotificationAuthorizationStatus":
IronwoodMigrationNotificationGate.shared.status { status in
DispatchQueue.main.async { result(status.rawValue) }
}
case "requestNotificationAuthorization":
IronwoodMigrationNotificationGate.shared.requestAuthorization {
status in
if !status.allowsBackgroundMigration {
IronwoodMigrationNotificationGate.shared.hardDisable()
}
DispatchQueue.main.async { result(status.rawValue) }
}
case "openNotificationSettings":
IronwoodMigrationNotificationGate.shared.openSettings {
opened in result(opened)
}
case "schedule":
BackgroundMigrationManager.shared.schedule { scheduled in
DispatchQueue.main.async { result(scheduled) }
}
case "startPreparation":
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared.start {
success in DispatchQueue.main.async { result(success) }
}
} else {
result(false)
}
case "supportsPreparationTracking":
// Denomination-preparation confirmation tracking is a
// BGContinuedProcessingTask, an iOS 26 API, while the Runner target
// deploys to iOS 15. On an older build there is no task to submit and
// no runtime state to report, so `getPreparationRuntimeState` answers
// `idle` — indistinguishable from "supported but nothing armed yet".
// Dart therefore asks for the capability separately instead of
// inferring it from an idle state.
//
// This reports the availability of the code path, not a guarantee that
// a submission will succeed. A submission can still be refused at
// runtime; that shows up as `startPreparation` returning false, which
// already leaves the run in its foreground-only presentation.
if #available(iOS 26.0, *) {
result(true)
} else {
result(false)
}
case "getPreparationRuntimeState":
guard
let arguments = call.arguments as? [String: Any],
let network = arguments["network"] as? String,
let accountUuid = arguments["accountUuid"] as? String,
let runId = arguments["runId"] as? String
else {
result(
FlutterError(
code: "invalid_arguments",
message: "Missing Ironwood preparation scope.",
details: nil
)
)
return
}
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared.runtimeState(
network: network,
accountUuid: accountUuid,
runId: runId
) { state in
DispatchQueue.main.async { result(state.rawValue) }
}
} else {
// No continued-processing task exists below iOS 26, so there is
// genuinely nothing running. Dart must not read this `idle` as
// "background tracking is possible but not armed" — see
// `supportsPreparationTracking`.
result(BackgroundMigrationPreparationRuntimeState.idle.rawValue)
}
case "ackPreparationForegroundContinuation":
guard
let arguments = call.arguments as? [String: Any],
let network = arguments["network"] as? String,
let accountUuid = arguments["accountUuid"] as? String,
let runId = arguments["runId"] as? String
else {
result(
FlutterError(
code: "invalid_arguments",
message: "Missing Ironwood preparation scope.",
details: nil
)
)
return
}
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared
.acknowledgeForegroundContinuation(
network: network,
accountUuid: accountUuid,
runId: runId
)
}
result(true)
case "stageOutboxBatch":
do {
result(try BackgroundMigrationOutboxChannel.stageBatch(arguments: call.arguments))
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "armOutboxBatch":
do {
try BackgroundMigrationOutboxChannel.armBatch(arguments: call.arguments)
self.completeOutboxArmWithBackgroundSchedule(result: result)
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "recoverOutboxBatch":
do {
let recovered = try BackgroundMigrationOutboxChannel.recoverBatch(
arguments: call.arguments
)
if recovered {
self.completeOutboxArmWithBackgroundSchedule(result: result)
} else {
result(false)
}
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "discardOutboxBatch":
do {
// Re-staging follows immediately and arms its own schedule, and
// discarding can only remove work, so no scheduling change is needed
// here. The batch id is reused, so notification bookkeeping stays
// keyed to the same record.
result(
try BackgroundMigrationOutboxChannel.discardBatch(
arguments: call.arguments
)
)
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "hasOutboxBatch":
do {
result(try BackgroundMigrationOutboxChannel.hasBatch(arguments: call.arguments))
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "recordVerifiedProofReadiness":
do {
let shouldSchedule =
try BackgroundMigrationOutboxChannel.recordVerifiedProofReadiness(
arguments: call.arguments
)
guard shouldSchedule else {
result(false)
return
}
// Persist first, then request a wake. If submission fails, the
// pending marker survives and the next foreground status check
// retries scheduling without announcing readiness twice.
BackgroundMigrationManager.shared.schedule { _ in
DispatchQueue.main.async { result(true) }
}
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "listOutboxReceipts":
do {
result(try BackgroundMigrationOutboxChannel.listReceipts())
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "listOutboxAttemptedTxids":
do {
result(
try BackgroundMigrationOutboxChannel.listAttemptedTxids(
arguments: call.arguments
)
)
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "ackOutboxReceipts":
do {
try BackgroundMigrationOutboxChannel.acknowledgeReceipts(arguments: call.arguments)
result(true)
} catch {
result(self.backgroundMigrationFlutterError(error))
}
case "runOutboxOnceNow":
DispatchQueue.global(qos: .utility).async {
let outcome = BackgroundMigrationOutboxChannel.runOnceNow()
DispatchQueue.main.async { result(self.backgroundOutboxResult(outcome)) }
}
case "cancel":
BackgroundMigrationManager.shared.cancelIfNoRunnableWork()
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared
.cancelIfNoActivePreparation()
}
result(true)
case "quiesce":
BackgroundMigrationManager.shared.quiesce {
outboxSuccess in
guard outboxSuccess else {
result(false)
return
}
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared.quiesce {
preparationSuccess in result(preparationSuccess)
}
} else {
result(true)
}
}
case "resume":
BackgroundMigrationManager.shared.resumeAfterFailedMutation {
resumed in
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared.resumeAfterMutation()
}
DispatchQueue.main.async { result(resumed) }
}
case "revokeAccount":
guard let arguments = call.arguments as? [String: Any],
let network = arguments["network"] as? String,
let accountUuid = arguments["accountUuid"] as? String
else {
result(
FlutterError(
code: "invalid_arguments",
message: "Missing Ironwood migration account scope.",
details: nil
)
)
return
}
BackgroundMigrationManager.shared.revokeAccount(
network: network,
accountUuid: accountUuid,
completion: { success in
if success {
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared
.cancelIfNoActivePreparation()
}
}
result(success)
}
)
case "revokeAll":
BackgroundMigrationManager.shared.revokeAll {
success in
if success {
if #available(iOS 26.0, *) {
BackgroundMigrationPreparationManager.shared
.cancelIfNoActivePreparation()
}
}
result(success)
}
#if DEBUG || targetEnvironment(simulator)
case "runOnceForTesting":
DispatchQueue.global(qos: .utility).async {
let outcome = BackgroundMigrationManager.shared.runOnceForTesting()
DispatchQueue.main.async {
result(self.backgroundOutboxResult(outcome))
}
}
case "resumeWithoutSchedulingForTesting":
result(
BackgroundMigrationManager.shared
.resumeWithoutSchedulingForTesting()
)
#endif
default:
result(FlutterMethodNotImplemented)
}
}
let networkPrivacyChannel = FlutterMethodChannel(
name: "com.zcash.wallet/network_privacy",
binaryMessenger: messenger
)
networkPrivacyChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "excludeFromBackup":
// Arti's directory records this wallet's guard choice. Restoring it
// onto another device would carry that choice across, so it is kept
// out of iCloud and finder backups; a restored install picks fresh
// guards at the cost of one bootstrap.
guard
let arguments = call.arguments as? [String: Any],
let path = arguments["path"] as? String,
!path.isEmpty
else {
result(
FlutterError(
code: "invalid_arguments",
message: "excludeFromBackup requires a path.",
details: nil
)
)
return
}
var url = URL(fileURLWithPath: path)
guard FileManager.default.fileExists(atPath: path) else {
// Tor was never enabled far enough to create it; nothing to mark.
result(false)
return
}
do {
var values = URLResourceValues()
values.isExcludedFromBackup = true
try url.setResourceValues(values)
result(true)
} catch {
result(
FlutterError(
code: "exclude_failed",
message: error.localizedDescription,
details: nil
)
)
}
default:
result(FlutterMethodNotImplemented)
}
}
let hapticsChannel = FlutterMethodChannel(
name: "com.zcash.wallet/haptics",
binaryMessenger: messenger
)
hapticsChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "error":
// The system's error notification haptic — the triple knock
// users know from failed Face ID / wrong system passcode.
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
result(true)
case "sendSuccess":
result(self.performSendSuccessHaptic())
case "sendFailure":
result(self.performSendFailureHaptic())
default:
result(FlutterMethodNotImplemented)
}
}
let sensitiveClipboardChannel = FlutterMethodChannel(
name: "com.zcash.wallet/sensitive_clipboard",
binaryMessenger: messenger
)
sensitiveClipboardChannel.setMethodCallHandler { (call, result) in
SensitiveClipboardHandler.handle(call, result: result)
}
let biometricUnlockChannel = FlutterMethodChannel(
name: "com.zcash.wallet/biometric_unlock",
binaryMessenger: messenger
)
biometricUnlockChannel.setMethodCallHandler { (call, result) in
BiometricUnlockHandler.shared.handle(call, result: result)
}
let deviceOwnerAuthChannel = FlutterMethodChannel(
name: "com.zcash.wallet/device_owner_auth",
binaryMessenger: messenger
)
deviceOwnerAuthChannel.setMethodCallHandler { (call, result) in
DeviceOwnerAuthHandler.shared.handle(call, result: result)
}
let datePickerChannel = FlutterMethodChannel(
name: "com.zcash.wallet/date_picker",
binaryMessenger: messenger
)
datePickerChannel.setMethodCallHandler { (call, result) in
DatePickerHandler.shared.handle(call, result: result)
}
let windowAppearanceChannel = FlutterMethodChannel(
name: "com.zcash.wallet/window_appearance",
binaryMessenger: messenger
)
windowAppearanceChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "setBrightness":
guard
let args = call.arguments as? [String: Any],
let brightness = args["brightness"] as? String
else {
result(
FlutterError(
code: "bad_args",
message: "Expected brightness argument.",
details: nil
)
)
return
}
WindowAppearanceHandler.setBrightness(brightness)
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
let screenAwakeChannel = FlutterMethodChannel(
name: "com.zcash.wallet/screen_awake",
binaryMessenger: messenger
)
screenAwakeChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "setEnabled":
guard
let args = call.arguments as? [String: Any],
let enabled = args["enabled"] as? Bool
else {
result(
FlutterError(
code: "bad_args",
message: "Expected enabled argument.",
details: nil
)
)
return
}
UIApplication.shared.isIdleTimerDisabled = enabled
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
let cameraPermissionChannel = FlutterMethodChannel(
name: "com.zcash.wallet/camera_permission",
binaryMessenger: messenger
)
cameraPermissionChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "openSettings":
guard let url = URL(string: UIApplication.openSettingsURLString) else {
result(false)
return
}
UIApplication.shared.open(url, options: [:]) { success in
result(success)
}
default:
result(FlutterMethodNotImplemented)
}
}
// EventChannel for screenshot detection — sensitive screens (secret
// passphrase) warn when the user captures them.
let screenshotChannel = FlutterEventChannel(
name: "com.zcash.wallet/screenshots",
binaryMessenger: messenger
)
screenshotChannel.setStreamHandler(ScreenshotStreamHandler())
}
private func completeOutboxArmWithBackgroundSchedule(
result: @escaping FlutterResult
) {
IronwoodMigrationNotificationGate.shared.status { status in
guard status.allowsBackgroundMigration else {
// The durable outbox remains intentionally usable from the foreground
// when the user declines notifications. Only the background lane is
// disabled in this mode.
IronwoodMigrationNotificationGate.shared.hardDisable()
let success = IronwoodMigrationOutboxArmSchedulePolicy.reportsSuccess(
authorization: status,
submitted: false
)
DispatchQueue.main.async { result(success) }
return
}
BackgroundMigrationManager.shared.schedule { submitted in
// With authorization granted, a scheduler submission failure must be
// surfaced so Dart does not mistake an unscheduled outbox for a
// background-tracked one.
let success = IronwoodMigrationOutboxArmSchedulePolicy.reportsSuccess(
authorization: status,
submitted: submitted
)
DispatchQueue.main.async { result(success) }
}
}
}
private func backgroundMigrationFlutterError(_ error: Error) -> FlutterError {
// A conflicting batch is a repairable state, not a generic failure: a batch
// record exists for this run but cannot deliver its scheduled
// transactions. Dart distinguishes it by code so recovery can restage the
// missing items instead of aborting on the inspection call.
if let outboxError = error as? BackgroundMigrationOutboxError,
outboxError == .conflictingBatch
{
return FlutterError(
code: "ironwood_outbox_conflicting_batch",
message: String(describing: error),
details: nil
)
}
return FlutterError(
code: "ironwood_outbox_error",
message: String(describing: error),
details: nil
)
}
private func backgroundOutboxResult(
_ runResult: BackgroundMigrationOutboxRunResult
) -> [String: Any?] {
let transport = backgroundTransportResult(runResult.transport)
var result = transport
result["transport"] = transport
result["accountUuid"] = runResult.transportAccountUuid
if let proofReady = runResult.proofReady {
result["proofReady"] = [
"batchId": proofReady.batchId,
"observedHeight": proofReady.observedHeight,
]
} else {
result["proofReady"] = NSNull()
}
return result
}
private func backgroundTransportResult(
_ outcome: BackgroundMigrationTransportOutcome
) -> [String: Any?] {
switch outcome {
case .noWork:
return ["outcome": "noWork"]
case .waiting(let nextHeight, let observedHeight, let delay):
return [
"outcome": "waiting",
"nextHeight": nextHeight,
"observedHeight": observedHeight,
"delaySeconds": delay,
]
case .accepted(let nextHeight, let observedHeight, let delay):
return [
"outcome": "accepted",
"nextHeight": nextHeight,
"observedHeight": observedHeight,
"delaySeconds": delay,
]
case .needsUserAction:
return ["outcome": "needsUserAction"]
case .temporarilyUnavailable:
return ["outcome": "temporarilyUnavailable"]
case .cancelled:
return ["outcome": "cancelled"]
}
}
private func performSendSuccessHaptic() -> Bool {
#if targetEnvironment(simulator)
return false
#else
guard #available(iOS 13.0, *) else {
return false
}
guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {
return false
}
do {
let engine: CHHapticEngine
if let existingEngine = customHapticEngine {
engine = existingEngine
} else {
engine = try CHHapticEngine()
customHapticEngine = engine
engine.stoppedHandler = { [weak self] _ in
self?.customHapticEngine = nil
}
engine.resetHandler = { [weak self] in
try? self?.customHapticEngine?.start()
}
}
try engine.start()
let pattern = try CHHapticPattern(
events: [
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [],
relativeTime: 0,
duration: 0.03
),
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [
CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.00)
],
relativeTime: 0.06,
duration: 0.04
),
],
parameters: []
)
let player = try engine.makePlayer(with: pattern)
try player.start(atTime: 0)
return true
} catch {
return false
}
#endif
}
private func performSendFailureHaptic() -> Bool {
#if targetEnvironment(simulator)
return false
#else
guard #available(iOS 13.0, *) else {
return false
}
guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {
return false
}
do {
let engine: CHHapticEngine
if let existingEngine = customHapticEngine {
engine = existingEngine
} else {
engine = try CHHapticEngine()
customHapticEngine = engine
engine.stoppedHandler = { [weak self] _ in
self?.customHapticEngine = nil
}
engine.resetHandler = { [weak self] in
try? self?.customHapticEngine?.start()
}
}
try engine.start()
let pattern = try CHHapticPattern(
events: [
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [
CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.70)
],
relativeTime: 0,
duration: 0.04
),
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [
CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.70)
],
relativeTime: 0.08,
duration: 0.04
),
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [
CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.90)
],
relativeTime: 0.16,
duration: 0.04
),
CHHapticEvent(
eventType: .hapticContinuous,
parameters: [
CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.60)
],
relativeTime: 0.24,
duration: 0.05
),
],
parameters: []
)
let player = try engine.makePlayer(with: pattern)
try player.start(atTime: 0)
return true
} catch {
return false
}
#endif
}
}
private enum SensitiveClipboardHandler {
private static let plainTextType = "public.utf8-plain-text"
static func handle(_ call: FlutterMethodCall, result: FlutterResult) {
switch call.method {
case "copyText":
guard
let args = call.arguments as? [String: Any],
let text = args["text"] as? String
else {
result(
FlutterError(
code: "bad_args",
message: "Expected text argument.",
details: nil
)
)
return
}
let expirationSeconds = max(1, seconds(from: args["expirationSeconds"]) ?? 60)
UIPasteboard.general.setItems(
[[plainTextType: text]],
options: [
.expirationDate: Date().addingTimeInterval(expirationSeconds),
.localOnly: true,
]
)
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
private static func seconds(from value: Any?) -> TimeInterval? {
if let number = value as? NSNumber {
return number.doubleValue
}
if let int = value as? Int {
return TimeInterval(int)
}
if let double = value as? Double {
return double
}
return nil
}
}
private enum WindowAppearanceHandler {
static func setBrightness(_ brightness: String) {
let style: UIUserInterfaceStyle
switch brightness {
case "dark":
style = .dark
case "system":
style = .unspecified
default:
style = .light
}
let windows = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
for window in windows {
window.overrideUserInterfaceStyle = style
window.rootViewController?.overrideUserInterfaceStyle = style
}
}
}
/// Streams a tick to Dart whenever iOS reports a user screenshot.
/// Lives in this file so it doesn't need a project.pbxproj entry.
class ScreenshotStreamHandler: NSObject, FlutterStreamHandler {
private var observer: NSObjectProtocol?
func onListen(
withArguments arguments: Any?,
eventSink events: @escaping FlutterEventSink
) -> FlutterError? {
observer = NotificationCenter.default.addObserver(
forName: UIApplication.userDidTakeScreenshotNotification,
object: nil,
queue: .main
) { _ in
events(true)
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
self.observer = nil
}
return nil
}
}