@capgo/capacitor-document-scanner 8.3.17 → 8.3.22

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.
@@ -1,13 +1,153 @@
1
+ // swiftlint:disable file_length type_body_length identifier_name type_name function_body_length
2
+ import CoreImage
3
+ import ObjectiveC.runtime
1
4
  import UIKit
2
5
  import VisionKit
3
6
 
4
- /// Global storage for maxNumDocuments limit (used by swizzled method)
7
+ private final class WeakDocumentCameraController {
8
+ weak var value: VNDocumentCameraViewController?
9
+ }
10
+
11
+ private let activeDocumentCameraController = WeakDocumentCameraController()
5
12
  private var documentScanLimit: Int?
13
+ private var documentScanShouldPresentPreviewAfterCapture = false
14
+ private var documentScanLastPreviewedAcceptedCount = 0
15
+ private var documentScanPreviewPresentationRequested = false
16
+ private var documentScanPreviewPresentationGeneration = 0
17
+ private var documentScanShouldCustomizePreviewNavigation = false
18
+ private var documentScanPreviewNavigationCustomized = false
19
+ private var documentScanModalSuppressionGeneration = 0
20
+
21
+ private protocol SimulatorDocumentScannerViewControllerDelegate: AnyObject {
22
+ func simulatorDocumentScannerViewControllerDidCancel(_ controller: SimulatorDocumentScannerViewController)
23
+ func simulatorDocumentScannerViewController(
24
+ _ controller: SimulatorDocumentScannerViewController,
25
+ didFinishWith images: [UIImage]
26
+ )
27
+ }
28
+
29
+ private final class SimulatorDocumentScannerViewController: UIViewController {
30
+ private let sampleImages: [UIImage]
31
+ private weak var delegate: SimulatorDocumentScannerViewControllerDelegate?
32
+
33
+ init(sampleImages: [UIImage], delegate: SimulatorDocumentScannerViewControllerDelegate) {
34
+ self.sampleImages = sampleImages
35
+ self.delegate = delegate
36
+ super.init(nibName: nil, bundle: nil)
37
+ }
38
+
39
+ @available(*, unavailable)
40
+ required init?(coder: NSCoder) {
41
+ fatalError("init(coder:) has not been implemented")
42
+ }
43
+
44
+ override func viewDidLoad() {
45
+ super.viewDidLoad()
46
+ view.backgroundColor = .systemBackground
47
+
48
+ let titleLabel = UILabel()
49
+ titleLabel.translatesAutoresizingMaskIntoConstraints = false
50
+ titleLabel.text = "Simulator VisionKit Scanner"
51
+ titleLabel.font = .systemFont(ofSize: 28, weight: .bold)
52
+ titleLabel.textAlignment = .center
53
+ titleLabel.accessibilityIdentifier = "simulator-scanner-title"
54
+
55
+ let subtitleLabel = UILabel()
56
+ subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
57
+ subtitleLabel.text = "Deterministic native harness for Maestro. Devices still use VisionKit."
58
+ subtitleLabel.font = .systemFont(ofSize: 15, weight: .medium)
59
+ subtitleLabel.textColor = .secondaryLabel
60
+ subtitleLabel.textAlignment = .center
61
+ subtitleLabel.numberOfLines = 0
62
+
63
+ let previewImageView = UIImageView(image: sampleImages.first)
64
+ previewImageView.translatesAutoresizingMaskIntoConstraints = false
65
+ previewImageView.contentMode = .scaleAspectFit
66
+ previewImageView.layer.cornerRadius = 20
67
+ previewImageView.layer.masksToBounds = true
68
+ previewImageView.layer.borderWidth = 1
69
+ previewImageView.layer.borderColor = UIColor.separator.cgColor
70
+ previewImageView.backgroundColor = UIColor.secondarySystemBackground
71
+
72
+ let summaryLabel = UILabel()
73
+ summaryLabel.translatesAutoresizingMaskIntoConstraints = false
74
+ summaryLabel.text = "\(sampleImages.count) sample page\(sampleImages.count == 1 ? "" : "s") ready"
75
+ summaryLabel.font = .monospacedSystemFont(ofSize: 14, weight: .semibold)
76
+ summaryLabel.textColor = .secondaryLabel
77
+ summaryLabel.textAlignment = .center
78
+
79
+ let cancelButton = UIButton(type: .system)
80
+ cancelButton.translatesAutoresizingMaskIntoConstraints = false
81
+ cancelButton.setTitle("Cancel Scan", for: .normal)
82
+ cancelButton.accessibilityIdentifier = "simulator-scanner-cancel-button"
83
+ cancelButton.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold)
84
+ cancelButton.backgroundColor = .secondarySystemBackground
85
+ cancelButton.layer.cornerRadius = 16
86
+ cancelButton.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
87
+
88
+ let useSampleButton = UIButton(type: .system)
89
+ useSampleButton.translatesAutoresizingMaskIntoConstraints = false
90
+ useSampleButton.setTitle("Use Sample Scan", for: .normal)
91
+ useSampleButton.accessibilityIdentifier = "simulator-scanner-use-sample-button"
92
+ useSampleButton.titleLabel?.font = .systemFont(ofSize: 17, weight: .bold)
93
+ useSampleButton.setTitleColor(.white, for: .normal)
94
+ useSampleButton.backgroundColor = .systemBlue
95
+ useSampleButton.layer.cornerRadius = 16
96
+ useSampleButton.addTarget(self, action: #selector(useSampleTapped), for: .touchUpInside)
97
+
98
+ let buttonStack = UIStackView(arrangedSubviews: [cancelButton, useSampleButton])
99
+ buttonStack.translatesAutoresizingMaskIntoConstraints = false
100
+ buttonStack.axis = .vertical
101
+ buttonStack.spacing = 12
102
+ buttonStack.distribution = .fillEqually
103
+
104
+ view.addSubview(titleLabel)
105
+ view.addSubview(subtitleLabel)
106
+ view.addSubview(previewImageView)
107
+ view.addSubview(summaryLabel)
108
+ view.addSubview(buttonStack)
109
+
110
+ NSLayoutConstraint.activate([
111
+ titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 32),
112
+ titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
113
+ titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
114
+
115
+ subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 12),
116
+ subtitleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
117
+ subtitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
118
+
119
+ previewImageView.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 28),
120
+ previewImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
121
+ previewImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
122
+ previewImageView.heightAnchor.constraint(equalTo: previewImageView.widthAnchor, multiplier: 1.35),
123
+
124
+ summaryLabel.topAnchor.constraint(equalTo: previewImageView.bottomAnchor, constant: 16),
125
+ summaryLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
126
+ summaryLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
127
+
128
+ buttonStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
129
+ buttonStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
130
+ buttonStack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -24),
131
+ buttonStack.heightAnchor.constraint(equalToConstant: 116),
132
+
133
+ cancelButton.heightAnchor.constraint(equalToConstant: 52),
134
+ useSampleButton.heightAnchor.constraint(equalToConstant: 52)
135
+ ])
136
+ }
137
+
138
+ @objc private func cancelTapped() {
139
+ delegate?.simulatorDocumentScannerViewControllerDidCancel(self)
140
+ }
141
+
142
+ @objc private func useSampleTapped() {
143
+ delegate?.simulatorDocumentScannerViewController(self, didFinishWith: sampleImages)
144
+ }
145
+ }
6
146
 
7
147
  /**
8
148
  Handles presenting the VisionKit document scanner and returning results.
9
149
  */
10
- class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
150
+ class DocScanner: NSObject {
11
151
  private weak var viewController: UIViewController?
12
152
  private var successHandler: ([String]) -> Void
13
153
  private var errorHandler: (String) -> Void
@@ -17,6 +157,9 @@ class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
17
157
  private var brightness: Float
18
158
  private var contrast: Float
19
159
  private var maxNumDocuments: Int?
160
+ private var letUserAdjustCrop: Bool
161
+ private var reviewCapturedDocument: Bool
162
+ private let ciContext = CIContext()
20
163
 
21
164
  private static var swizzled = false
22
165
 
@@ -29,7 +172,9 @@ class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
29
172
  croppedImageQuality: Int = 100,
30
173
  brightness: Float = 0.0,
31
174
  contrast: Float = 1.0,
32
- maxNumDocuments: Int? = nil
175
+ maxNumDocuments: Int? = nil,
176
+ letUserAdjustCrop: Bool = true,
177
+ reviewCapturedDocument: Bool = false
33
178
  ) {
34
179
  self.viewController = viewController
35
180
  self.successHandler = successHandler
@@ -40,79 +185,47 @@ class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
40
185
  self.brightness = brightness
41
186
  self.contrast = contrast
42
187
  self.maxNumDocuments = maxNumDocuments
188
+ self.letUserAdjustCrop = letUserAdjustCrop
189
+ self.reviewCapturedDocument = reviewCapturedDocument
43
190
  }
44
191
 
45
192
  override convenience init() {
46
193
  self.init(nil)
47
194
  }
48
195
 
49
- /// Swizzle the internal canAddImages method to enforce document limits
50
- private static func setupSwizzling() {
51
- guard !swizzled else { return }
52
- swizzled = true
53
-
54
- // Find the internal VNDocumentCameraViewController_InProcess class
55
- guard let inProcessClass = NSClassFromString("VNDocumentCameraViewController_InProcess") else {
56
- return
57
- }
58
-
59
- // Selector for the internal delegate method: documentCameraController:canAddImages:
60
- let originalSelector = NSSelectorFromString("documentCameraController:canAddImages:")
61
- let swizzledSelector = #selector(DocScanner.swizzled_documentCameraController(_:canAddImages:))
62
-
63
- guard let originalMethod = class_getInstanceMethod(inProcessClass, originalSelector),
64
- let swizzledMethod = class_getInstanceMethod(DocScanner.self, swizzledSelector) else {
196
+ func startScan() {
197
+ guard let viewController else {
198
+ errorHandler("Bridge view controller unavailable.")
65
199
  return
66
200
  }
67
201
 
68
- // Add the swizzled method to the target class
69
- let didAdd = class_addMethod(
70
- inProcessClass,
71
- swizzledSelector,
72
- method_getImplementation(swizzledMethod),
73
- method_getTypeEncoding(swizzledMethod)
74
- )
75
-
76
- if didAdd {
77
- guard let newSwizzledMethod = class_getInstanceMethod(inProcessClass, swizzledSelector) else {
78
- return
202
+ if shouldUseSimulatorHarness {
203
+ let simulatorController = SimulatorDocumentScannerViewController(
204
+ sampleImages: makeSimulatorSampleImages(),
205
+ delegate: self
206
+ )
207
+ simulatorController.modalPresentationStyle = .fullScreen
208
+ DispatchQueue.main.async {
209
+ viewController.present(simulatorController, animated: true)
79
210
  }
80
- method_exchangeImplementations(originalMethod, newSwizzledMethod)
81
- } else {
82
- method_exchangeImplementations(originalMethod, swizzledMethod)
83
- }
84
- }
85
-
86
- /// Swizzled implementation that enforces document limits
87
- @objc dynamic func swizzled_documentCameraController(_ controller: AnyObject, canAddImages count: UInt64) -> Bool {
88
- // Check if we have a limit set
89
- // count represents the total number of pages that would exist after adding
90
- // Allow adding if count would not exceed the limit
91
- if let limit = documentScanLimit, count > UInt64(limit) {
92
- return false
211
+ return
93
212
  }
94
- // Call the original implementation (swizzled, so this calls original)
95
- return swizzled_documentCameraController(controller, canAddImages: count)
96
- }
97
213
 
98
- func startScan() {
99
214
  guard VNDocumentCameraViewController.isSupported else {
100
- errorHandler("Document scanning is not supported on this device.")
215
+ errorHandler("VisionKit document scanning is not supported on this device.")
101
216
  return
102
217
  }
103
218
 
104
- // Set the global limit and setup swizzling if we have a limit
105
- if let limit = maxNumDocuments, limit > 0 {
106
- documentScanLimit = limit
107
- DocScanner.setupSwizzling()
108
- } else {
109
- documentScanLimit = nil
110
- }
219
+ DocScanner.configureVisionKitHackState(
220
+ limit: maxNumDocuments,
221
+ presentPreviewAfterCapture: reviewCapturedDocument || letUserAdjustCrop
222
+ )
111
223
 
112
224
  DispatchQueue.main.async {
113
225
  let documentCameraViewController = VNDocumentCameraViewController()
114
226
  documentCameraViewController.delegate = self
115
- self.viewController?.present(documentCameraViewController, animated: true)
227
+ activeDocumentCameraController.value = documentCameraViewController
228
+ viewController.present(documentCameraViewController, animated: true)
116
229
  }
117
230
  }
118
231
 
@@ -125,7 +238,9 @@ class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
125
238
  croppedImageQuality: Int? = 100,
126
239
  brightness: Float? = 0.0,
127
240
  contrast: Float? = 1.0,
128
- maxNumDocuments: Int? = nil
241
+ maxNumDocuments: Int? = nil,
242
+ letUserAdjustCrop: Bool = true,
243
+ reviewCapturedDocument: Bool = false
129
244
  ) {
130
245
  self.viewController = viewController
131
246
  self.successHandler = successHandler
@@ -136,115 +251,776 @@ class DocScanner: NSObject, VNDocumentCameraViewControllerDelegate {
136
251
  self.brightness = brightness ?? 0.0
137
252
  self.contrast = contrast ?? 1.0
138
253
  self.maxNumDocuments = maxNumDocuments
254
+ self.letUserAdjustCrop = letUserAdjustCrop
255
+ self.reviewCapturedDocument = reviewCapturedDocument
139
256
 
140
257
  startScan()
141
258
  }
142
259
 
143
- func documentCameraViewController(
144
- _ controller: VNDocumentCameraViewController,
145
- didFinishWith scan: VNDocumentCameraScan
146
- ) {
147
- var results: [String] = []
260
+ private static func configureVisionKitHackState(limit: Int?, presentPreviewAfterCapture: Bool) {
261
+ documentScanLimit = limit
262
+ documentScanShouldPresentPreviewAfterCapture = presentPreviewAfterCapture
263
+ documentScanLastPreviewedAcceptedCount = 0
264
+ documentScanPreviewPresentationRequested = false
265
+ documentScanPreviewPresentationGeneration += 1
266
+ documentScanShouldCustomizePreviewNavigation = false
267
+ documentScanPreviewNavigationCustomized = false
268
+ documentScanModalSuppressionGeneration += 1
269
+
270
+ guard limit != nil || presentPreviewAfterCapture else {
271
+ return
272
+ }
273
+
274
+ setupSwizzling()
275
+ }
276
+
277
+ private static func resetVisionKitHackState() {
278
+ documentScanLimit = nil
279
+ documentScanShouldPresentPreviewAfterCapture = false
280
+ documentScanLastPreviewedAcceptedCount = 0
281
+ documentScanPreviewPresentationRequested = false
282
+ documentScanPreviewPresentationGeneration += 1
283
+ documentScanShouldCustomizePreviewNavigation = false
284
+ documentScanPreviewNavigationCustomized = false
285
+ documentScanModalSuppressionGeneration += 1
286
+ activeDocumentCameraController.value = nil
287
+ }
288
+
289
+ private static func setupSwizzling() {
290
+ guard !swizzled else {
291
+ return
292
+ }
293
+
294
+ guard let inProcessClass = NSClassFromString("VNDocumentCameraViewController_InProcess") else {
295
+ return
296
+ }
148
297
 
149
- // Limit pages to maxNumDocuments if specified
150
- let pageLimit = maxNumDocuments != nil ? min(scan.pageCount, maxNumDocuments!) : scan.pageCount
298
+ let originalSelector = NSSelectorFromString("documentCameraController:canAddImages:")
299
+ let swizzledSelector = #selector(DocScanner.swizzled_documentCameraController(_:canAddImages:))
151
300
 
152
- for pageNumber in 0 ..< pageLimit {
153
- var processedImage = scan.imageOfPage(at: pageNumber)
301
+ guard
302
+ let originalMethod = class_getInstanceMethod(inProcessClass, originalSelector),
303
+ let swizzledMethod = class_getInstanceMethod(DocScanner.self, swizzledSelector)
304
+ else {
305
+ return
306
+ }
307
+
308
+ swizzled = true
309
+ let didAddMethod = class_addMethod(
310
+ inProcessClass,
311
+ swizzledSelector,
312
+ method_getImplementation(swizzledMethod),
313
+ method_getTypeEncoding(swizzledMethod)
314
+ )
315
+
316
+ if didAddMethod,
317
+ let installedSwizzledMethod = class_getInstanceMethod(inProcessClass, swizzledSelector) {
318
+ method_exchangeImplementations(originalMethod, installedSwizzledMethod)
319
+ return
320
+ }
154
321
 
155
- // Apply brightness and contrast adjustments if needed
156
- if brightness != 0.0 || contrast != 1.0 {
157
- processedImage = applyBrightnessContrast(to: processedImage, brightness: brightness, contrast: contrast)
322
+ method_exchangeImplementations(originalMethod, swizzledMethod)
323
+ }
324
+
325
+ @objc dynamic func swizzled_documentCameraController(_ controller: AnyObject, canAddImages count: UInt64) -> Bool {
326
+ let originalAllowsMoreImages = swizzled_documentCameraController(controller, canAddImages: count)
327
+ let acceptedCount = max(0, Int(count) - 1)
328
+ let reachedConfiguredLimit = documentScanLimit.map { Int(count) > $0 } ?? false
329
+ var previewWasRequested = false
330
+
331
+ if documentScanShouldPresentPreviewAfterCapture,
332
+ acceptedCount > 0,
333
+ acceptedCount > documentScanLastPreviewedAcceptedCount {
334
+ documentScanLastPreviewedAcceptedCount = acceptedCount
335
+ previewWasRequested = true
336
+ DocScanner.requestPreviewPresentationIfNeeded(
337
+ forceNewCycle: true,
338
+ customizeForCompletion: reachedConfiguredLimit
339
+ )
340
+ }
341
+
342
+ if reachedConfiguredLimit {
343
+ if !previewWasRequested {
344
+ DocScanner.requestPreviewPresentationIfNeeded(
345
+ forceNewCycle: true,
346
+ customizeForCompletion: true
347
+ )
348
+ }
349
+ DocScanner.suppressLimitModalIfNeeded()
350
+ return false
351
+ }
352
+
353
+ return originalAllowsMoreImages
354
+ }
355
+
356
+ private var shouldUseSimulatorHarness: Bool {
357
+ #if targetEnvironment(simulator)
358
+ return true
359
+ #else
360
+ return false
361
+ #endif
362
+ }
363
+
364
+ private static func resolvedView(for controller: UIViewController) -> UIView? {
365
+ controller.viewIfLoaded ?? controller.view
366
+ }
367
+
368
+ private static func requestPreviewPresentationIfNeeded(forceNewCycle: Bool, customizeForCompletion: Bool) {
369
+ DispatchQueue.main.async {
370
+ guard let documentCameraViewController = activeDocumentCameraController.value else {
371
+ return
372
+ }
373
+
374
+ if forceNewCycle {
375
+ documentScanPreviewPresentationRequested = false
376
+ documentScanPreviewNavigationCustomized = false
377
+ }
378
+
379
+ documentScanShouldCustomizePreviewNavigation =
380
+ documentScanShouldCustomizePreviewNavigation || customizeForCompletion
381
+
382
+ guard !documentScanPreviewPresentationRequested else {
383
+ if documentScanShouldCustomizePreviewNavigation {
384
+ _ = customizePreviewNavigationIfNeeded(around: documentCameraViewController)
385
+ }
386
+ return
158
387
  }
159
388
 
389
+ documentScanPreviewPresentationRequested = true
390
+ let generation = documentScanPreviewPresentationGeneration + 1
391
+ documentScanPreviewPresentationGeneration = generation
392
+ attemptPreviewPresentation(generation: generation, remainingAttempts: 12)
393
+ }
394
+ }
395
+
396
+ private static func attemptPreviewPresentation(generation: Int, remainingAttempts: Int) {
397
+ DispatchQueue.main.async {
160
398
  guard
161
- let scannedImageData = processedImage
162
- .jpegData(compressionQuality: CGFloat(croppedImageQuality) / CGFloat(100))
399
+ generation == documentScanPreviewPresentationGeneration,
400
+ let documentCameraViewController = activeDocumentCameraController.value
163
401
  else {
164
- goBackToPreviousView(controller)
165
- errorHandler("Unable to get scanned document in jpeg format.")
166
402
  return
167
403
  }
168
404
 
169
- switch responseType {
170
- case ResponseType.base64:
171
- results.append(scannedImageData.base64EncodedString())
172
- case ResponseType.imageFilePath:
173
- do {
174
- let imagePath = FileUtil().createImageFile(pageNumber)
175
- try scannedImageData.write(to: imagePath)
176
- results.append(imagePath.absoluteString)
177
- } catch {
178
- goBackToPreviousView(controller)
179
- errorHandler("Unable to save scanned image: \(error.localizedDescription)")
180
- return
405
+ if findVisiblePreviewOrEditorController(around: documentCameraViewController) != nil {
406
+ if documentScanShouldCustomizePreviewNavigation {
407
+ _ = customizePreviewNavigationIfNeeded(around: documentCameraViewController)
181
408
  }
182
- default:
183
- errorHandler(
184
- "responseType must be \(ResponseType.base64) or \(ResponseType.imageFilePath)"
409
+ return
410
+ }
411
+
412
+ guard let rootView = resolvedView(for: documentCameraViewController) else {
413
+ return
414
+ }
415
+
416
+ let previewWasTriggered: Bool
417
+ if let previewView = findFirstView(namedLike: ["ICDocCamThumbnailContainerView"], in: rootView) {
418
+ previewWasTriggered = triggerInteraction(around: previewView, in: rootView)
419
+ } else {
420
+ let previewPoint = CGPoint(
421
+ x: previewHotspotFrame(in: rootView).midX,
422
+ y: previewHotspotFrame(in: rootView).midY
185
423
  )
424
+ previewWasTriggered = triggerInteraction(at: previewPoint, in: rootView)
425
+ }
426
+
427
+ if !previewWasTriggered && remainingAttempts <= 0 {
428
+ documentScanPreviewPresentationRequested = false
186
429
  return
187
430
  }
431
+
432
+ guard remainingAttempts > 0 else {
433
+ return
434
+ }
435
+
436
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
437
+ attemptPreviewPresentation(generation: generation, remainingAttempts: remainingAttempts - 1)
438
+ }
188
439
  }
440
+ }
189
441
 
190
- // Clear the global limit before dismissing to avoid race conditions
191
- documentScanLimit = nil
192
- goBackToPreviousView(controller)
193
- successHandler(results)
442
+ @discardableResult
443
+ private static func customizePreviewNavigationIfNeeded(around scannerController: UIViewController) -> Bool {
444
+ guard documentScanShouldCustomizePreviewNavigation else {
445
+ return false
446
+ }
447
+
448
+ guard let previewController = findVisiblePreviewOrEditorController(around: scannerController) else {
449
+ return false
450
+ }
451
+
452
+ guard !documentScanPreviewNavigationCustomized else {
453
+ return true
454
+ }
455
+
456
+ let completionButton = findCompletionButton(in: scannerController)
457
+ let completionTitle = completionButton?.title ?? "Done"
458
+ let completionStyle = completionButton?.style == .plain ? UIBarButtonItem.Style.plain : .done
459
+
460
+ previewController.navigationItem.hidesBackButton = true
461
+ previewController.navigationItem.setHidesBackButton(true, animated: false)
462
+ previewController.navigationItem.leftItemsSupplementBackButton = false
463
+
464
+ if let completionAction = completionButton?.action {
465
+ previewController.navigationItem.leftBarButtonItem = UIBarButtonItem(
466
+ title: completionTitle,
467
+ style: completionStyle,
468
+ target: completionButton?.target,
469
+ action: completionAction
470
+ )
471
+ }
472
+
473
+ documentScanPreviewNavigationCustomized = true
474
+ return true
194
475
  }
195
476
 
196
- func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
197
- // Clear the global limit before dismissing to avoid race conditions
198
- documentScanLimit = nil
199
- goBackToPreviousView(controller)
200
- cancelHandler()
477
+ private static func triggerInteraction(around view: UIView, in rootView: UIView) -> Bool {
478
+ var currentView: UIView? = view
479
+
480
+ while let candidate = currentView {
481
+ if triggerInteraction(on: candidate) {
482
+ return true
483
+ }
484
+ currentView = candidate.superview
485
+ }
486
+
487
+ let targetPoint = view.convert(CGPoint(x: view.bounds.midX, y: view.bounds.midY), to: rootView)
488
+ return triggerInteraction(at: targetPoint, in: rootView)
201
489
  }
202
490
 
203
- func documentCameraViewController(
204
- _ controller: VNDocumentCameraViewController,
205
- didFailWithError error: Error
206
- ) {
207
- // Clear the global limit before dismissing to avoid race conditions
208
- documentScanLimit = nil
209
- goBackToPreviousView(controller)
210
- errorHandler(error.localizedDescription)
491
+ private static func triggerInteraction(at point: CGPoint, in rootView: UIView) -> Bool {
492
+ guard let hitView = rootView.hitTest(point, with: nil) else {
493
+ return false
494
+ }
495
+
496
+ var currentView: UIView? = hitView
497
+ while let candidate = currentView {
498
+ if triggerInteraction(on: candidate) {
499
+ return true
500
+ }
501
+ currentView = candidate.superview
502
+ }
503
+
504
+ return false
505
+ }
506
+
507
+ private static func triggerInteraction(on view: UIView) -> Bool {
508
+ if let control = view as? UIControl {
509
+ triggerBestPrimaryAction(for: control)
510
+ return true
511
+ }
512
+
513
+ return triggerGestureRecognizers(on: view)
514
+ }
515
+
516
+ private static func triggerGestureRecognizers(on view: UIView) -> Bool {
517
+ guard let gestureRecognizers = view.gestureRecognizers, !gestureRecognizers.isEmpty else {
518
+ return false
519
+ }
520
+
521
+ for gestureRecognizer in gestureRecognizers where gestureRecognizer.isEnabled {
522
+ guard let internalTargets = gestureRecognizer.value(forKey: "_targets") as? [NSObject] else {
523
+ continue
524
+ }
525
+
526
+ for internalTarget in internalTargets {
527
+ guard let invocation = gestureRecognizerInvocation(from: internalTarget) else {
528
+ continue
529
+ }
530
+
531
+ UIApplication.shared.sendAction(
532
+ invocation.selector,
533
+ to: invocation.target,
534
+ from: gestureRecognizer,
535
+ for: nil
536
+ )
537
+ return true
538
+ }
539
+ }
540
+
541
+ return false
542
+ }
543
+
544
+ private static func gestureRecognizerInvocation(from internalTarget: NSObject) -> (target: AnyObject, selector: Selector)? {
545
+ guard
546
+ let targetClass: AnyClass = object_getClass(internalTarget),
547
+ let targetIvar = class_getInstanceVariable(targetClass, "_target"),
548
+ let actionIvar = class_getInstanceVariable(targetClass, "_action"),
549
+ let target = object_getIvar(internalTarget, targetIvar) as AnyObject?
550
+ else {
551
+ return nil
552
+ }
553
+
554
+ let actionOffset = ivar_getOffset(actionIvar)
555
+ let actionPointer = Unmanaged.passUnretained(internalTarget).toOpaque().advanced(by: actionOffset)
556
+ let selector = actionPointer.load(as: Selector.self)
557
+
558
+ guard let responder = target as? NSObject,
559
+ responder.responds(to: selector) else {
560
+ return nil
561
+ }
562
+
563
+ return (target, selector)
564
+ }
565
+
566
+ private static func triggerBestPrimaryAction(for control: UIControl) {
567
+ let supportedEvents: [UIControl.Event] = [.primaryActionTriggered, .touchUpInside, .valueChanged]
568
+
569
+ for event in supportedEvents {
570
+ for target in control.allTargets {
571
+ if let actions = control.actions(forTarget: target, forControlEvent: event),
572
+ !actions.isEmpty {
573
+ control.sendActions(for: event)
574
+ return
575
+ }
576
+ }
577
+ }
578
+
579
+ control.sendActions(for: .touchUpInside)
580
+ }
581
+
582
+ private static func findFirstView(namedLike classNameFragments: [String], in rootView: UIView) -> UIView? {
583
+ findFirstView(namedLike: classNameFragments, in: rootView, rootView: rootView)
584
+ }
585
+
586
+ private static func findFirstView(
587
+ namedLike classNameFragments: [String],
588
+ in view: UIView,
589
+ rootView: UIView
590
+ ) -> UIView? {
591
+ guard !view.isHidden, view.alpha > 0.01 else {
592
+ return nil
593
+ }
594
+
595
+ let className = NSStringFromClass(type(of: view))
596
+ if classNameFragments.contains(where: { className.contains($0) }) {
597
+ return view
598
+ }
599
+
600
+ for subview in view.subviews {
601
+ if let matchingSubview = findFirstView(namedLike: classNameFragments, in: subview, rootView: rootView) {
602
+ return matchingSubview
603
+ }
604
+ }
605
+
606
+ return nil
607
+ }
608
+
609
+ private static func findVisiblePreviewOrEditorController(around scannerController: UIViewController) -> UIViewController? {
610
+ var controllersToVisit: [UIViewController] = []
611
+ var visitedControllers = Set<ObjectIdentifier>()
612
+
613
+ if let navigationController = scannerController.navigationController {
614
+ if let topViewController = navigationController.topViewController,
615
+ topViewController !== scannerController,
616
+ topViewController.isViewLoaded,
617
+ topViewController.view.window != nil {
618
+ return topViewController
619
+ }
620
+ controllersToVisit.append(navigationController)
621
+ }
622
+
623
+ controllersToVisit.append(contentsOf: scannerController.children)
624
+
625
+ if let presentedViewController = scannerController.presentedViewController {
626
+ controllersToVisit.append(presentedViewController)
627
+ }
628
+
629
+ while !controllersToVisit.isEmpty {
630
+ let currentController = controllersToVisit.removeFirst()
631
+ let identifier = ObjectIdentifier(currentController)
632
+
633
+ guard visitedControllers.insert(identifier).inserted else {
634
+ continue
635
+ }
636
+
637
+ if currentController !== scannerController,
638
+ currentController.isViewLoaded,
639
+ currentController.view.window != nil,
640
+ looksLikePreviewOrEditorController(currentController) {
641
+ return currentController
642
+ }
643
+
644
+ if let navigationController = currentController as? UINavigationController {
645
+ if let topViewController = navigationController.topViewController,
646
+ topViewController !== scannerController,
647
+ topViewController.isViewLoaded,
648
+ topViewController.view.window != nil {
649
+ return topViewController
650
+ }
651
+ controllersToVisit.append(contentsOf: navigationController.viewControllers)
652
+ }
653
+
654
+ controllersToVisit.append(contentsOf: currentController.children)
655
+
656
+ if let presentedViewController = currentController.presentedViewController {
657
+ controllersToVisit.append(presentedViewController)
658
+ }
659
+ }
660
+
661
+ return nil
662
+ }
663
+
664
+ private static func looksLikePreviewOrEditorController(_ viewController: UIViewController) -> Bool {
665
+ let className = NSStringFromClass(type(of: viewController)).lowercased()
666
+ let previewKeywords = ["preview", "review", "edit", "editor", "filter", "rotate", "crop"]
667
+ return previewKeywords.contains { className.contains($0) }
668
+ }
669
+
670
+ private static func findCompletionButton(in rootViewController: UIViewController) -> UIBarButtonItem? {
671
+ var controllersToVisit: [UIViewController] = [rootViewController]
672
+ var visitedControllers = Set<ObjectIdentifier>()
673
+ var fallbackButton: UIBarButtonItem?
674
+
675
+ while !controllersToVisit.isEmpty {
676
+ let currentController = controllersToVisit.removeFirst()
677
+ let identifier = ObjectIdentifier(currentController)
678
+
679
+ guard visitedControllers.insert(identifier).inserted else {
680
+ continue
681
+ }
682
+
683
+ let rightBarButtonItems = currentController.navigationItem.rightBarButtonItems ?? []
684
+ for barButtonItem in rightBarButtonItems where barButtonItem.isEnabled && barButtonItem.action != nil {
685
+ if isCompletionButton(barButtonItem) {
686
+ return barButtonItem
687
+ }
688
+ fallbackButton = fallbackButton ?? barButtonItem
689
+ }
690
+
691
+ if let rightBarButtonItem = currentController.navigationItem.rightBarButtonItem,
692
+ rightBarButtonItem.isEnabled,
693
+ rightBarButtonItem.action != nil {
694
+ if isCompletionButton(rightBarButtonItem) {
695
+ return rightBarButtonItem
696
+ }
697
+ fallbackButton = fallbackButton ?? rightBarButtonItem
698
+ }
699
+
700
+ if let navigationController = currentController as? UINavigationController {
701
+ controllersToVisit.append(contentsOf: navigationController.viewControllers)
702
+ }
703
+
704
+ controllersToVisit.append(contentsOf: currentController.children)
705
+
706
+ if let parentController = currentController.parent {
707
+ controllersToVisit.append(parentController)
708
+ }
709
+
710
+ if let presentedViewController = currentController.presentedViewController {
711
+ controllersToVisit.append(presentedViewController)
712
+ }
713
+ }
714
+
715
+ return fallbackButton
716
+ }
717
+
718
+ private static func isCompletionButton(_ barButtonItem: UIBarButtonItem) -> Bool {
719
+ if barButtonItem.style == .done {
720
+ return true
721
+ }
722
+
723
+ let normalizedTitle = normalizeActionText(barButtonItem.title)
724
+ return normalizedTitle == "done" || normalizedTitle == "save" || normalizedTitle == "done scanning"
725
+ }
726
+
727
+ private static func normalizeActionText(_ text: String?) -> String {
728
+ text?
729
+ .trimmingCharacters(in: .whitespacesAndNewlines)
730
+ .folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
731
+ .lowercased() ?? ""
732
+ }
733
+
734
+ private static func previewHotspotFrame(in rootView: UIView) -> CGRect {
735
+ CGRect(
736
+ x: 0,
737
+ y: rootView.bounds.height * 0.56,
738
+ width: rootView.bounds.width * 0.42,
739
+ height: rootView.bounds.height * 0.44
740
+ )
741
+ }
742
+
743
+ private static func suppressLimitModalIfNeeded() {
744
+ let generation = documentScanModalSuppressionGeneration + 1
745
+ documentScanModalSuppressionGeneration = generation
746
+ suppressLimitModalIfNeeded(generation: generation, remainingAttempts: 12)
211
747
  }
212
748
 
213
- private func goBackToPreviousView(_ controller: VNDocumentCameraViewController) {
749
+ private static func suppressLimitModalIfNeeded(generation: Int, remainingAttempts: Int) {
214
750
  DispatchQueue.main.async {
215
- controller.dismiss(animated: true)
751
+ guard generation == documentScanModalSuppressionGeneration else {
752
+ return
753
+ }
754
+
755
+ dismissVisibleLimitModalIfNeeded()
756
+
757
+ guard remainingAttempts > 0 else {
758
+ return
759
+ }
760
+
761
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
762
+ suppressLimitModalIfNeeded(generation: generation, remainingAttempts: remainingAttempts - 1)
763
+ }
216
764
  }
217
765
  }
218
766
 
219
- /**
220
- Applies brightness and contrast adjustments to a UIImage using CIFilter.
221
- - Parameter image: The source image
222
- - Parameter brightness: Brightness adjustment (-255 to 255, 0 = no change)
223
- - Parameter contrast: Contrast adjustment (0.0 to 10.0, 1.0 = no change)
224
- - Returns: A new UIImage with adjustments applied
225
- */
226
- private func applyBrightnessContrast(to image: UIImage, brightness: Float, contrast: Float) -> UIImage {
227
- guard let ciImage = CIImage(image: image) else {
767
+ private static func dismissVisibleLimitModalIfNeeded() {
768
+ guard let documentCameraViewController = activeDocumentCameraController.value else {
769
+ return
770
+ }
771
+
772
+ let modalsToDismiss = findPresentedModals(around: documentCameraViewController)
773
+ for modal in modalsToDismiss {
774
+ modal.view.alpha = 0
775
+ modal.view.isHidden = true
776
+ modal.dismiss(animated: false)
777
+ }
778
+ }
779
+
780
+ private static func findPresentedModals(around rootViewController: UIViewController) -> [UIViewController] {
781
+ var results: [UIViewController] = []
782
+ var controllersToVisit: [UIViewController] = [rootViewController]
783
+ var visitedControllers = Set<ObjectIdentifier>()
784
+ var seenResults = Set<ObjectIdentifier>()
785
+
786
+ while !controllersToVisit.isEmpty {
787
+ let currentController = controllersToVisit.removeFirst()
788
+ let identifier = ObjectIdentifier(currentController)
789
+
790
+ guard visitedControllers.insert(identifier).inserted else {
791
+ continue
792
+ }
793
+
794
+ if let presentedViewController = currentController.presentedViewController,
795
+ shouldSuppressModal(presentedViewController, scannerRoot: rootViewController),
796
+ seenResults.insert(ObjectIdentifier(presentedViewController)).inserted {
797
+ results.append(presentedViewController)
798
+ }
799
+
800
+ if let navigationController = currentController as? UINavigationController {
801
+ controllersToVisit.append(contentsOf: navigationController.viewControllers)
802
+ }
803
+
804
+ controllersToVisit.append(contentsOf: currentController.children)
805
+ }
806
+
807
+ if let windowScene = rootViewController.view.window?.windowScene {
808
+ for window in windowScene.windows {
809
+ guard let windowRootViewController = window.rootViewController else {
810
+ continue
811
+ }
812
+
813
+ if let modal = topPresentedViewController(from: windowRootViewController),
814
+ shouldSuppressModal(modal, scannerRoot: rootViewController),
815
+ seenResults.insert(ObjectIdentifier(modal)).inserted {
816
+ results.append(modal)
817
+ }
818
+ }
819
+ }
820
+
821
+ return results
822
+ }
823
+
824
+ private static func topPresentedViewController(from rootViewController: UIViewController) -> UIViewController? {
825
+ var currentViewController: UIViewController? = rootViewController
826
+ var lastPresentedViewController: UIViewController?
827
+
828
+ while let presentedViewController = currentViewController?.presentedViewController {
829
+ lastPresentedViewController = presentedViewController
830
+ currentViewController = presentedViewController
831
+ }
832
+
833
+ return lastPresentedViewController
834
+ }
835
+
836
+ private static func shouldSuppressModal(_ viewController: UIViewController, scannerRoot: UIViewController) -> Bool {
837
+ guard viewController !== scannerRoot else {
838
+ return false
839
+ }
840
+
841
+ if viewController is UIAlertController {
842
+ return true
843
+ }
844
+
845
+ let className = NSStringFromClass(type(of: viewController)).lowercased()
846
+ return className.contains("alert") || className.contains("sheet") || className.contains("prompt")
847
+ }
848
+
849
+ private func finishScan(with images: [UIImage]) {
850
+ DispatchQueue.global(qos: .userInitiated).async {
851
+ do {
852
+ let limitedImages = self.limit(images: images)
853
+ let results = try limitedImages.enumerated().map { index, image in
854
+ let adjustedImage = self.applyBrightnessContrastIfNeeded(to: image)
855
+ guard
856
+ let imageData = adjustedImage.jpegData(
857
+ compressionQuality: CGFloat(self.croppedImageQuality) / 100.0
858
+ )
859
+ else {
860
+ throw RuntimeError.message("Unable to get scanned document in jpeg format.")
861
+ }
862
+
863
+ switch self.responseType {
864
+ case ResponseType.base64:
865
+ return imageData.base64EncodedString()
866
+ case ResponseType.imageFilePath:
867
+ let imagePath = FileUtil().createImageFile(index)
868
+ try imageData.write(to: imagePath)
869
+ return imagePath.absoluteString
870
+ default:
871
+ throw RuntimeError.message(
872
+ "responseType must be \(ResponseType.base64) or \(ResponseType.imageFilePath)"
873
+ )
874
+ }
875
+ }
876
+
877
+ DispatchQueue.main.async {
878
+ self.successHandler(results)
879
+ }
880
+ } catch RuntimeError.message(let message) {
881
+ DispatchQueue.main.async {
882
+ self.errorHandler(message)
883
+ }
884
+ } catch {
885
+ DispatchQueue.main.async {
886
+ self.errorHandler("Unable to save scanned image: \(error.localizedDescription)")
887
+ }
888
+ }
889
+ }
890
+ }
891
+
892
+ private func limit(images: [UIImage]) -> [UIImage] {
893
+ guard let maxNumDocuments else {
894
+ return images
895
+ }
896
+ return Array(images.prefix(maxNumDocuments))
897
+ }
898
+
899
+ private func applyBrightnessContrastIfNeeded(to image: UIImage) -> UIImage {
900
+ guard brightness != 0.0 || contrast != 1.0 else {
228
901
  return image
229
902
  }
230
903
 
231
- // Normalize brightness from (-255, 255) to (-1, 1) for CIColorControls
232
- let normalizedBrightness = brightness / 255.0
904
+ guard let ciImage = CIImage(image: image) else {
905
+ return image
906
+ }
233
907
 
234
908
  let filter = CIFilter(name: "CIColorControls")
235
909
  filter?.setValue(ciImage, forKey: kCIInputImageKey)
236
- filter?.setValue(normalizedBrightness, forKey: kCIInputBrightnessKey)
910
+ filter?.setValue(brightness / 255.0, forKey: kCIInputBrightnessKey)
237
911
  filter?.setValue(contrast, forKey: kCIInputContrastKey)
238
912
 
239
- guard let outputImage = filter?.outputImage else {
913
+ guard let outputImage = filter?.outputImage,
914
+ let cgImage = ciContext.createCGImage(outputImage, from: outputImage.extent)
915
+ else {
240
916
  return image
241
917
  }
242
918
 
243
- let context = CIContext()
244
- guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else {
245
- return image
919
+ return UIImage(cgImage: cgImage, scale: image.scale, orientation: .up)
920
+ }
921
+
922
+ private func dismiss(_ controller: UIViewController, completion: @escaping () -> Void) {
923
+ DispatchQueue.main.async {
924
+ controller.dismiss(animated: true, completion: completion)
246
925
  }
926
+ }
927
+
928
+ private func makeSimulatorSampleImages() -> [UIImage] {
929
+ let sampleCount = maxNumDocuments.map { max(1, min($0, 2)) } ?? 2
930
+ return (1 ... sampleCount).map(makeSimulatorSampleImage(pageNumber:))
931
+ }
932
+
933
+ private func makeSimulatorSampleImage(pageNumber: Int) -> UIImage {
934
+ let size = CGSize(width: 1240, height: 1754)
935
+ let renderer = UIGraphicsImageRenderer(size: size)
936
+ return renderer.image { context in
937
+ let bounds = CGRect(origin: .zero, size: size)
938
+ UIColor(red: 0.92, green: 0.95, blue: 1.0, alpha: 1).setFill()
939
+ context.fill(bounds)
247
940
 
248
- return UIImage(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation)
941
+ let paperRect = bounds.insetBy(dx: 90, dy: 110)
942
+ let paperPath = UIBezierPath(roundedRect: paperRect, cornerRadius: 28)
943
+ UIColor.white.setFill()
944
+ paperPath.fill()
945
+
946
+ UIColor.black.withAlphaComponent(0.08).setStroke()
947
+ paperPath.lineWidth = 3
948
+ paperPath.stroke()
949
+
950
+ let header = "MAESTRO TEST DOCUMENT \(pageNumber)"
951
+ let headerAttributes: [NSAttributedString.Key: Any] = [
952
+ .font: UIFont.systemFont(ofSize: 46, weight: .bold),
953
+ .foregroundColor: UIColor.black
954
+ ]
955
+ header.draw(at: CGPoint(x: paperRect.minX + 70, y: paperRect.minY + 80), withAttributes: headerAttributes)
956
+
957
+ let subheader = reviewCapturedDocument
958
+ ? "VisionKit device path, simulator review harness"
959
+ : "VisionKit device path, simulator deterministic harness"
960
+ let subheaderAttributes: [NSAttributedString.Key: Any] = [
961
+ .font: UIFont.systemFont(ofSize: 28, weight: .medium),
962
+ .foregroundColor: UIColor.darkGray
963
+ ]
964
+ subheader.draw(
965
+ at: CGPoint(x: paperRect.minX + 70, y: paperRect.minY + 150),
966
+ withAttributes: subheaderAttributes
967
+ )
968
+
969
+ UIColor.systemBlue.setStroke()
970
+ for index in 0 ..< 18 {
971
+ let lineY = paperRect.minY + 260 + CGFloat(index * 62)
972
+ let lineRect = CGRect(x: paperRect.minX + 70, y: lineY, width: paperRect.width - 140, height: 6)
973
+ let linePath = UIBezierPath(roundedRect: lineRect, cornerRadius: 3)
974
+ linePath.lineWidth = 1
975
+ linePath.stroke()
976
+ }
977
+ }
978
+ }
979
+ }
980
+
981
+ extension DocScanner: VNDocumentCameraViewControllerDelegate {
982
+ func documentCameraViewController(
983
+ _ controller: VNDocumentCameraViewController,
984
+ didFinishWith scan: VNDocumentCameraScan
985
+ ) {
986
+ let images = (0 ..< scan.pageCount).map(scan.imageOfPage(at:))
987
+ DocScanner.resetVisionKitHackState()
988
+ dismiss(controller) {
989
+ self.finishScan(with: images)
990
+ }
991
+ }
992
+
993
+ func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
994
+ DocScanner.resetVisionKitHackState()
995
+ dismiss(controller) {
996
+ self.cancelHandler()
997
+ }
998
+ }
999
+
1000
+ func documentCameraViewController(
1001
+ _ controller: VNDocumentCameraViewController,
1002
+ didFailWithError error: Error
1003
+ ) {
1004
+ DocScanner.resetVisionKitHackState()
1005
+ dismiss(controller) {
1006
+ self.errorHandler(error.localizedDescription)
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ extension DocScanner: SimulatorDocumentScannerViewControllerDelegate {
1012
+ fileprivate func simulatorDocumentScannerViewControllerDidCancel(_ controller: SimulatorDocumentScannerViewController) {
1013
+ dismiss(controller) {
1014
+ self.cancelHandler()
1015
+ }
1016
+ }
1017
+
1018
+ fileprivate func simulatorDocumentScannerViewController(
1019
+ _ controller: SimulatorDocumentScannerViewController,
1020
+ didFinishWith images: [UIImage]
1021
+ ) {
1022
+ dismiss(controller) {
1023
+ self.finishScan(with: images)
1024
+ }
249
1025
  }
250
1026
  }