-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnotationView.swift
More file actions
770 lines (707 loc) · 35 KB
/
Copy pathAnnotationView.swift
File metadata and controls
770 lines (707 loc) · 35 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
//
// AnnotationView.swift
// IOSAccessAssessment
//
// Created by Himanshu on 11/10/25.
//
import SwiftUI
import TipKit
import CoreLocation
import simd
import PointNMapShared
enum AnnotationViewConstants {
enum Texts {
static let annotationViewTitle = "Annotation"
static let currentClassPrefixText = "Selected class"
static let finishText = "Finish"
static let nextText = "Next"
static let selectObjectText = "Select an object"
static let loadingPageText = "Loading. Please wait..."
/// Feature Detail View Text
static let featureDetailViewTitle = "Feature Details"
static let featureDetailViewIdKey = "ID"
static let featureDetailViewLocationKey = "Location"
static let featureDetailNotAvailableText = "Not Available"
/// Alert texts
static let managerStatusAlertTitleKey = "Error"
static let managerStatusAlertDismissButtonKey = "OK"
static let managerStatusAlertMessageDismissScreenSuffixKey = "Press OK to close this screen."
static let managerStatusAlertMessageDismissAlertSuffixKey = "Press OK to dismiss this alert."
static let apiChangesetUploadStatusAlertTitleKey = "Upload Error"
static let apiChangesetUploadStatusAlertDismissButtonKey = "OK"
static let apiChangesetUploadStatusAlertGenericMessageKey = "Failed to upload features. Press OK to dismiss this alert."
static let apiChangesetUploadStatusAlertMessageSuffixKey = " feature(s) failed to upload. Press OK to dismiss this alert."
/// SelectObjectInfoTip
static let selectFeatureInfoTipTitle = "Select a Feature"
static let selectFeatureInfoTipMessage = "Please select the individual feature that you want to annotate"
static let selectFeatureInfoTipLearnMoreButtonTitle = "Learn More"
/// SelectObjectInfoLearnMoreSheetView
static let selectFeatureInfoLearnMoreSheetTitle = "Annotating an Individual Feature"
static let selectFeatureInfoLearnMoreSheetMessage = """
For each type of accessibility feature, the app can identify multiple feature instances within the same image.
**Select All**: Default option. You can annotate all features of a particular type together.
**Individual**: You can select a particular feature from the dropdown menu if you wish to provide specific annotations for an individual feature.
**Ellipsis [...]**: For each feature, you can also view its details by tapping the ellipsis button next to the dropdown menu.
"""
}
enum Images {
static let checkIcon = "checkmark"
static let ellipsisIcon = "ellipsis"
static let infoIcon = "info.circle"
static let closeIcon = "xmark"
static let errorIcon = "exclamationmark.triangle"
}
}
enum AnnotationViewError: Error, LocalizedError {
case classIndexOutofBounds
case instanceIndexOutofBounds
case invalidCaptureDataRecord
case managerConfigurationFailed
case authenticationError
case workspaceConfigurationFailed
case attributeEstimationFailed(Error)
case uploadFailed
case apiChangesetUploadFailed(APIChangesetUploadResults)
var errorDescription: String? {
switch self {
case .classIndexOutofBounds:
return "The Current Class is not in the list."
case .instanceIndexOutofBounds:
return "Exceeded the number of instances for the current class."
case .invalidCaptureDataRecord:
return "The Current Capture is invalid."
case .managerConfigurationFailed:
return "Annotation Configuration failed"
case .authenticationError:
return "Authentication error. Please log in again."
case .workspaceConfigurationFailed:
return "Workspace configuration failed. Please check your workspace settings."
case .attributeEstimationFailed(let error):
return "Some Attribute Estimation calculations failed. They may be ignored. \nError: \(error.localizedDescription)"
case .uploadFailed:
return "Failed to upload annotations."
case .apiChangesetUploadFailed(let results):
return "API Transmission failed with \(results.failedFeatureUploads) failed uploads."
}
}
}
struct SelectFeatureInfoTip: Tip {
var title: Text {
Text(AnnotationViewConstants.Texts.selectFeatureInfoTipTitle)
}
var message: Text? {
Text(AnnotationViewConstants.Texts.selectFeatureInfoTipMessage)
}
var image: Image? {
Image(systemName: AnnotationViewConstants.Images.infoIcon)
.resizable()
}
var actions: [Action] {
// Define a learn more button.
Action(
id: AnnotationViewConstants.Texts.selectFeatureInfoTipLearnMoreButtonTitle,
title: AnnotationViewConstants.Texts.selectFeatureInfoTipLearnMoreButtonTitle
)
}
}
class AnnotationFeatureClassSelectionViewModel: ObservableObject {
@Published var currentIndex: Int? = nil
@Published var currentClass: AccessibilityFeatureClass? = nil
@Published var selectedAnnotationOption: AnnotationOption = .classOption(.default)
func setCurrent(index: Int, classes: [AccessibilityFeatureClass]) throws {
guard index < classes.count else {
throw AnnotationViewError.classIndexOutofBounds
}
self.currentIndex = index
self.currentClass = classes[index]
}
func setOption(option: AnnotationOption) {
self.selectedAnnotationOption = option
}
}
class AnnotationFeatureSelectionViewModel: ObservableObject {
@Published var instances: [MappedEditableAccessibilityFeature] = []
@Published var currentIndex: Int? = nil
@Published var currentFeature: MappedEditableAccessibilityFeature? = nil
func setInstances(_ instances: [MappedEditableAccessibilityFeature], currentClass: AccessibilityFeatureClass) throws {
self.instances = instances
/// If the class is sidewalk, we always select the first instance, as there should be only one sidewalk instance.
if (currentClass.kind.oswPolicy.oswElementClass == .Sidewalk) {
try setIndex(index: 0)
} else {
try setIndex(index: nil)
}
}
func setIndex(index: Int?) throws {
guard let index = index else {
self.currentIndex = nil
self.currentFeature = nil
return
}
guard index < instances.count else {
throw AnnotationViewError.instanceIndexOutofBounds
}
self.currentIndex = index
self.currentFeature = instances[index]
}
func setCurrent(index: Int?, instances: [MappedEditableAccessibilityFeature], currentClass: AccessibilityFeatureClass) throws {
try setInstances(instances, currentClass: currentClass)
try setIndex(index: index)
}
func setOptionOnFeature(option: AnnotationOption) {
if let currentFeature = self.currentFeature {
objectWillChange.send()
currentFeature.setAnnotationOption(option)
}
}
}
class AnnotationViewStatusViewModel: ObservableObject {
@Published var isFailed: Bool = false
@Published var errorMessage: String = ""
@Published var shouldDismiss: Bool = true
func update(isFailed: Bool, errorMessage: String, shouldDismiss: Bool = true) {
self.isFailed = isFailed
self.errorMessage = errorMessage
self.shouldDismiss = shouldDismiss
}
func update(isFailed: Bool, error: Error, shouldDismiss: Bool = true) {
self.isFailed = isFailed
let dismissKey = shouldDismiss ?
AnnotationViewConstants.Texts.managerStatusAlertMessageDismissScreenSuffixKey :
AnnotationViewConstants.Texts.managerStatusAlertMessageDismissAlertSuffixKey
self.errorMessage = "\(error.localizedDescription) \(dismissKey)"
self.shouldDismiss = shouldDismiss
}
}
class APIChangesetUploadStatusViewModel: ObservableObject {
@Published var isFailed: Bool = false
@Published var errorMessage: String = ""
func update(isFailed: Bool, errorMessage: String) {
self.isFailed = isFailed
self.errorMessage = errorMessage
}
func update(apiChangesetUploadResults: APIChangesetUploadResults) {
let failedFeatureUploads = apiChangesetUploadResults.failedFeatureUploads
if failedFeatureUploads == 0 {
self.isFailed = true
self.errorMessage = "Unknown Error Occurred."
} else {
self.isFailed = true
self.errorMessage = "\(failedFeatureUploads) \(AnnotationViewConstants.Texts.apiChangesetUploadStatusAlertMessageSuffixKey)"
}
}
}
struct AnnotationView: View {
let selectedClasses: [AccessibilityFeatureClass]
let selectedAttributesByClass: [AccessibilityFeatureClass: Set<AccessibilityFeatureAttribute>]
let captureLocation: CLLocationCoordinate2D
let apiChangesetUploadController: APIChangesetUploadController
@EnvironmentObject var userStateViewModel: UserStateViewModel
@EnvironmentObject var workspaceViewModel: WorkspaceViewModel
@EnvironmentObject var sharedAppData: SharedAppData
@Environment(\.dismiss) var dismiss
@StateObject var manager: AnnotationImageManager = AnnotationImageManager<MappedEditableAccessibilityFeature>()
@StateObject var segmentationAnnontationPipeline: SegmentationAnnotationPipeline = SegmentationAnnotationPipeline()
@StateObject var attributeEstimationPipeline: AttributeEstimationPipeline = AttributeEstimationPipeline()
@StateObject private var managerStatusViewModel = AnnotationViewStatusViewModel()
@StateObject private var apiChangesetUploadStatusViewModel = APIChangesetUploadStatusViewModel()
@State private var interfaceOrientation: UIInterfaceOrientation = .portrait // To bind one-way with manager's orientation
@StateObject var featureClassSelectionViewModel = AnnotationFeatureClassSelectionViewModel()
@StateObject var featureSelectionViewModel = AnnotationFeatureSelectionViewModel()
@State private var isShowingAnnotationFeatureDetailView: Bool = false
// var selectFeatureInfoTip = SelectFeatureInfoTip()
@State private var showSelectFeatureLearnMoreSheet = false
var body: some View {
VStack {
HStack {
Spacer()
Text(AnnotationViewConstants.Texts.annotationViewTitle)
.font(.headline)
.padding()
Spacer()
}
.overlay(
HStack {
Spacer()
Button(action: {
dismiss()
}) {
Image(systemName: AnnotationViewConstants.Images.closeIcon)
.resizable()
.frame(width: 20, height: 20)
}
.padding()
}
)
if let currentClass = featureClassSelectionViewModel.currentClass {
mainContent(currentClass: currentClass)
} else {
loadingPageView()
}
}
.task {
await handleOnAppear()
}
.onChange(of: featureClassSelectionViewModel.currentClass) { oldClass, newClass in
handleOnClassChange()
}
/// We are using index to track change in instance, instead of the instance itself, because we want to use the index for naming the instance in the picker.
/// To use the instance directly would require AccessibilityFeature to conform to Hashable, which is possible, by just using id.
/// But while rendering the picker, we would need to create a new Array of enumerated instances, which would be less efficient.
.onChange(of: featureSelectionViewModel.currentIndex) { oldIndex, newIndex in
handleOnInstanceChange(oldIndex: oldIndex, newIndex: newIndex)
}
.sheet(isPresented: $isShowingAnnotationFeatureDetailView) {
if let currentFeature = featureSelectionViewModel.currentFeature,
let currentFeatureIndex = featureSelectionViewModel.currentIndex
{
AnnotationFeatureDetailView(
accessibilityFeature: currentFeature,
title: "\(currentFeature.accessibilityFeatureClass.name.capitalized): \(currentFeatureIndex)"
)
.presentationDetents([.medium, .large])
} else {
Text(AnnotationViewConstants.Texts.featureDetailNotAvailableText)
.presentationDetents([.medium, .large])
}
}
.sheet(isPresented: $showSelectFeatureLearnMoreSheet) {
SelectFeatureLearnMoreSheetView()
.presentationDetents([.medium, .large])
}
.alert(AnnotationViewConstants.Texts.managerStatusAlertTitleKey, isPresented: $managerStatusViewModel.isFailed, actions: {
Button(AnnotationViewConstants.Texts.managerStatusAlertDismissButtonKey) {
let shouldDismiss = managerStatusViewModel.shouldDismiss
managerStatusViewModel.update(isFailed: false, errorMessage: "")
if shouldDismiss {
dismiss()
}
}
}, message: {
Text(managerStatusViewModel.errorMessage)
})
.alert(AnnotationViewConstants.Texts.apiChangesetUploadStatusAlertTitleKey,
isPresented: $apiChangesetUploadStatusViewModel.isFailed, actions: {
Button(AnnotationViewConstants.Texts.managerStatusAlertDismissButtonKey) {
apiChangesetUploadStatusViewModel.update(isFailed: false, errorMessage: "")
do {
try moveToNextClass()
} catch {
managerStatusViewModel.update(isFailed: true, error: error)
}
}
}, message: {
Text(apiChangesetUploadStatusViewModel.errorMessage)
})
}
private func loadingPageView() -> some View {
VStack {
Spacer()
Text(AnnotationViewConstants.Texts.loadingPageText)
SpinnerView()
Spacer()
}
}
@ViewBuilder
private func orientationStack<Content: View>(@ViewBuilder content: () -> Content) -> some View {
manager.interfaceOrientation.isLandscape ?
AnyLayout(HStackLayout())(content) :
AnyLayout(VStackLayout())(content)
}
@ViewBuilder
private func mainContent(currentClass: AccessibilityFeatureClass) -> some View {
let isDisabledFeatureDetailButton = featureSelectionViewModel.currentFeature == nil
orientationStack {
HostedAnnotationImageViewController<MappedEditableAccessibilityFeature>(annotationImageManager: manager)
VStack {
HStack {
Spacer()
Text("\(AnnotationViewConstants.Texts.currentClassPrefixText): \(currentClass.name)")
Spacer()
}
HStack {
Spacer()
CustomPicker (
label: AnnotationViewConstants.Texts.selectObjectText,
selection: $featureSelectionViewModel.currentIndex,
isContainsAll: currentClass.kind.oswPolicy.oswElementClass != .Sidewalk
) {
ForEach(featureSelectionViewModel.instances.indices, id: \.self) { featureIndex in
Text("\(currentClass.name.capitalized): \(featureIndex)")
.tag(featureIndex as Int?)
}
}
Button(action: {
isShowingAnnotationFeatureDetailView = true
}) {
Image(systemName: AnnotationViewConstants.Images.ellipsisIcon)
}
.buttonStyle(.bordered)
.padding(.horizontal, 5)
.disabled(isDisabledFeatureDetailButton)
Spacer()
}
.frame(maxWidth: .infinity)
.padding(.horizontal, 30)
.overlay(
HStack {
Spacer()
Button(action: {
showSelectFeatureLearnMoreSheet = true
}) {
Image(systemName: AnnotationViewConstants.Images.infoIcon)
.resizable()
.frame(width: 20, height: 20)
}
.padding(.trailing, 10)
}
)
ProgressBar(value: 0)
HStack {
Spacer()
annotationOptionsView(currentClass: currentClass)
Spacer()
}
.padding()
Button(action: {
confirmAnnotation()
}) {
Text(isCurrentIndexLast() ? AnnotationViewConstants.Texts.finishText : AnnotationViewConstants.Texts.nextText)
.padding()
}
}
}
}
private func annotationOptionsView(currentClass: AccessibilityFeatureClass) -> some View {
if let currentFeature = featureSelectionViewModel.currentFeature {
let annotationOptions: [AnnotationOption] = AnnotationOptionFeature.allCases.map { .individualOption($0) }
return VStack(spacing: 10) {
ForEach(annotationOptions, id: \.self) { option in
Button(action: {
featureSelectionViewModel.setOptionOnFeature(option: option)
}) {
Text(option.rawValue)
.font(.subheadline)
.frame(maxWidth: .infinity)
.padding()
.background(currentFeature.selectedAnnotationOption == option ? Color.blue : Color.gray)
.foregroundStyle(.white)
.cornerRadius(10)
}
}
}
} else {
let annotationOptions: [AnnotationOption] = AnnotationOptionFeatureClass.allCases.map { .classOption($0) }
return VStack(spacing: 10) {
ForEach(annotationOptions, id: \.self) { option in
Button(action: {
featureClassSelectionViewModel.setOption(option: option)
}) {
Text(option.rawValue)
.font(.subheadline)
.frame(maxWidth: .infinity)
.padding()
.background(featureClassSelectionViewModel.selectedAnnotationOption == option ? Color.blue : Color.gray)
.foregroundStyle(.white)
.cornerRadius(10)
}
}
}
}
}
private func isCurrentIndexValid() -> Bool {
guard let currentCaptureDataRecord = sharedAppData.currentCaptureDataRecord,
let currentClassIndex = featureClassSelectionViewModel.currentIndex else {
return false
}
let segmentedClasses = currentCaptureDataRecord.imageData.captureImageDataResults.segmentedClasses
return (currentClassIndex >= 0 && currentClassIndex < segmentedClasses.count)
}
private func isCurrentIndexLast() -> Bool {
guard let currentCaptureDataRecord = sharedAppData.currentCaptureDataRecord,
let currentClassIndex = featureClassSelectionViewModel.currentIndex else {
return false
}
let segmentedClasses = currentCaptureDataRecord.imageData.captureImageDataResults.segmentedClasses
return currentClassIndex == segmentedClasses.count - 1
}
private func handleOnAppear() async {
do {
guard let currentCaptureDataRecord = sharedAppData.currentCaptureDataRecord else {
throw AnnotationViewError.invalidCaptureDataRecord
}
var captureMeshData: (any CaptureMeshDataProtocol)? = nil
if userStateViewModel.isEnhancedAnalysisEnabled {
guard let captureMeshDataResults = currentCaptureDataRecord.meshData?.captureMeshDataResults else {
throw AnnotationViewError.invalidCaptureDataRecord
}
captureMeshData = CaptureImageAndMeshData(
captureImageData: CaptureImageData(currentCaptureDataRecord.imageData),
captureMeshDataResults: captureMeshDataResults
)
}
let segmentedClasses = currentCaptureDataRecord.imageData.captureImageDataResults.segmentedClasses
try segmentationAnnontationPipeline.configure()
try attributeEstimationPipeline.configure(
captureImageData: currentCaptureDataRecord.imageData,
/// TODO: MESH PROCESSING: Enable mesh data processing
captureMeshData: captureMeshData
)
try manager.configure(
selectedClasses: selectedClasses, segmentationAnnotationPipeline: segmentationAnnontationPipeline,
captureImageData: currentCaptureDataRecord.imageData,
captureMeshData: captureMeshData,
isEnhancedAnalysisEnabled: userStateViewModel.isEnhancedAnalysisEnabled
)
let captureDataHistory = Array(await sharedAppData.captureDataQueue.snapshot())
manager.setupAlignedSegmentationLabelImages(captureDataHistory: captureDataHistory)
try featureClassSelectionViewModel.setCurrent(index: 0, classes: segmentedClasses)
} catch {
managerStatusViewModel.update(isFailed: true, error: error)
}
}
private func handleOnClassChange() {
do {
guard let currentClass = featureClassSelectionViewModel.currentClass else {
throw AnnotationViewError.invalidCaptureDataRecord
}
let accessibilityFeatures = try manager.updateFeatureClass(accessibilityFeatureClass: currentClass)
var lastEstimationError: Error? = nil
accessibilityFeatures.forEach { accessibilityFeature in
do {
// try attributeEstimationPipeline.setPrerequisites(accessibilityFeature: accessibilityFeature)
try attributeEstimationPipeline.processLocationRequest(
deviceLocation: captureLocation,
accessibilityFeature: accessibilityFeature
)
attributeEstimationPipeline.processIsExistingRequest(
deviceLocation: captureLocation,
mappingData: sharedAppData.currentMappingData, accessibilityFeature: accessibilityFeature
)
try attributeEstimationPipeline.processAttributeRequest(
accessibilityFeature: accessibilityFeature,
attributes: selectedAttributesByClass[currentClass] ?? []
)
attributeEstimationPipeline.clearPrerequisites()
} catch {
lastEstimationError = error
}
}
featureClassSelectionViewModel.setOption(option: .classOption(.default))
try featureSelectionViewModel.setInstances(accessibilityFeatures, currentClass: currentClass)
if let lastEstimationError {
throw AnnotationViewError.attributeEstimationFailed(lastEstimationError)
}
} catch AnnotationViewError.attributeEstimationFailed(let error) {
managerStatusViewModel.update(
isFailed: true, error: AnnotationViewError.attributeEstimationFailed(error), shouldDismiss: false
)
} catch {
managerStatusViewModel.update(isFailed: true, error: error, shouldDismiss: false)
}
}
private func handleOnInstanceChange(oldIndex: Int?, newIndex: Int?) {
do {
try featureSelectionViewModel.setIndex(index: featureSelectionViewModel.currentIndex)
} catch {
managerStatusViewModel.update(isFailed: true, error: error)
}
do {
guard let currentClass = featureClassSelectionViewModel.currentClass else {
throw AnnotationViewError.invalidCaptureDataRecord
}
var accessibilityFeatures: [MappedEditableAccessibilityFeature]
var featureSelectedStatus: [UUID: Bool] = [:]
var updateFeatureResults: AnnotationImageFeatureUpdateResults? = nil
if let currentFeature = featureSelectionViewModel.currentFeature {
accessibilityFeatures = [currentFeature]
featureSelectedStatus[currentFeature.id] = true /// Selected and highlighted
if let oldIndex = oldIndex, oldIndex != featureSelectionViewModel.currentIndex,
oldIndex >= 0, oldIndex < featureSelectionViewModel.instances.count {
let oldFeature = featureSelectionViewModel.instances[oldIndex]
accessibilityFeatures.append(oldFeature)
featureSelectedStatus[oldFeature.id] = false /// Selected, but not highlighted
}
/// MARK: Temporary code for visualization. Incurs significant performance overhead.
/// TODO: Check what happens when we use the cache-based methods instead
if currentClass.kind.attributes.contains(where: {
$0 == .width || $0 == .runningSlope || $0 == .crossSlope || $0 == .surfaceIntegrity
}) {
let worldPoints = try attributeEstimationPipeline.getWorldPoints(accessibilityFeature: currentFeature)
let plane = try attributeEstimationPipeline.calculateAlignedPlane(
accessibilityFeature: currentFeature, worldPoints: worldPoints
)
let projectedPlane = try attributeEstimationPipeline.calculateProjectedPlane(
accessibilityFeature: currentFeature, plane: plane
)
let damageDetectionResults = try attributeEstimationPipeline.getDamageDetectionResults(
accessibilityFeature: currentFeature
)
updateFeatureResults = AnnotationImageFeatureUpdateResults(
plane: plane, projectedPlane: projectedPlane,
damageDetectionResults: damageDetectionResults
)
}
} else {
accessibilityFeatures = featureSelectionViewModel.instances
featureSelectedStatus = featureSelectionViewModel.instances.reduce(into: [:]) { dict, feature in
dict[feature.id] = false /// Selected, but not highlighted
}
}
// let isSelected = featureSelectionViewModel.currentFeature != nil
try manager.updateFeature(
accessibilityFeatureClass: currentClass,
accessibilityFeatures: accessibilityFeatures,
featureSelectedStatus: featureSelectedStatus,
updateFeatureResults: updateFeatureResults
)
} catch {
managerStatusViewModel.update(isFailed: true, error: error, shouldDismiss: false)
}
}
private func confirmAnnotation() {
Task {
do {
let apiChangesetUploadResults = try await uploadFeatures()
if let apiChangesetUploadResults, apiChangesetUploadResults.failedFeatureUploads > 0 {
throw AnnotationViewError.apiChangesetUploadFailed(apiChangesetUploadResults)
}
try moveToNextClass()
} catch AnnotationViewError.classIndexOutofBounds {
managerStatusViewModel.update(isFailed: true, error: AnnotationViewError.classIndexOutofBounds)
} catch AnnotationViewError.apiChangesetUploadFailed(let results) {
apiChangesetUploadStatusViewModel.update(apiChangesetUploadResults: results)
} catch {
apiChangesetUploadStatusViewModel.update(
isFailed: true,
errorMessage: AnnotationViewConstants.Texts.apiChangesetUploadStatusAlertGenericMessageKey
)
}
}
}
/// Fetches the latest map data for the current location and workspace, and updates the sharedAppData's currentMappingData.
/// This ensures that the most up-to-date map data is used for the next class's annotation, in case there were any changes from the previous upload.
/// May be used as a fail-safe if API changeset upload fails, to ensure that the user is working with the latest map data. If the upload is successful, the map data is already updated in the sharedAppData within the uploadFeatures function, so this would just be an extra fetch that may not be necessary.
private func refreshMap() async throws {
guard let workspaceId = workspaceViewModel.workspaceId else {
throw ARCameraViewError.workspaceConfigurationFailed
}
guard let accessToken = userStateViewModel.getAccessToken() else {
throw ARCameraViewError.authenticationError
}
let mapData = try await WorkspaceService.shared.fetchMapData(
workspaceId: workspaceId,
location: captureLocation,
radius: SharedAppConstants.WorkspaceConstants.fetchRadiusInMeters,
accessToken: accessToken,
environment: userStateViewModel.selectedEnvironment
)
sharedAppData.currentMappingData.replace(
osmMapDataResponse: mapData,
accessibilityFeatureClasses: selectedClasses
)
}
private func moveToNextClass() throws {
if isCurrentIndexLast() {
self.dismiss()
return
}
/// Move to next class
guard let currentCaptureDataRecord = sharedAppData.currentCaptureDataRecord,
let currentClassIndex = featureClassSelectionViewModel.currentIndex else {
throw AnnotationViewError.invalidCaptureDataRecord
}
let segmentedClasses = currentCaptureDataRecord.imageData.captureImageDataResults.segmentedClasses
try featureClassSelectionViewModel.setCurrent(index: currentClassIndex + 1, classes: segmentedClasses)
}
private func uploadFeatures() async throws -> APIChangesetUploadResults? {
guard let currentCaptureDataRecord = sharedAppData.currentCaptureDataRecord else {
throw AnnotationViewError.invalidCaptureDataRecord
}
guard let workspaceId = workspaceViewModel.workspaceId,
let changesetId = workspaceViewModel.changesetId else {
throw AnnotationViewError.workspaceConfigurationFailed
}
guard let accessToken = userStateViewModel.getAccessToken() else {
throw AnnotationViewError.authenticationError
}
guard let accessibilityFeatureClass = featureClassSelectionViewModel.currentClass else {
throw AnnotationViewError.classIndexOutofBounds
}
guard featureClassSelectionViewModel.selectedAnnotationOption != .classOption(.discard) else {
return nil
}
let featuresToUpload: [MappedEditableAccessibilityFeature] = featureSelectionViewModel.instances.filter { feature in
feature.selectedAnnotationOption != .individualOption(.discard) &&
feature.accessibilityFeatureClass == accessibilityFeatureClass
}
guard !featuresToUpload.isEmpty else {
return nil
}
let apiChangesetUploadInputs = APIChangesetUploadInputs(
workspaceId: workspaceId,
changesetId: changesetId,
accessibilityFeatureClass: accessibilityFeatureClass,
captureData: currentCaptureDataRecord,
captureLocation: captureLocation,
accessToken: accessToken,
environment: userStateViewModel.selectedEnvironment
)
let apiChangesetUploadResults = try await apiChangesetUploadController.uploadFeatures(
accessibilityFeatures: featuresToUpload,
currentMappedFeaturesData: sharedAppData.currentMappedFeaturesData,
inputs: apiChangesetUploadInputs
)
guard let mappedAccessibilityFeatures = apiChangesetUploadResults.accessibilityFeatures,
let mappedElements = apiChangesetUploadResults.oswElements else {
throw AnnotationViewError.apiChangesetUploadFailed(apiChangesetUploadResults)
}
sharedAppData.currentMappedFeaturesData.updateFeatures(mappedAccessibilityFeatures, for: accessibilityFeatureClass)
sharedAppData.currentMappingData.updateFeatures(mappedElements, for: accessibilityFeatureClass)
addFeaturesToCurrentDataset(
captureImageData: currentCaptureDataRecord.imageData,
featuresToUpload: featuresToUpload, mappedAccessibilityFeatures: mappedAccessibilityFeatures
)
sharedAppData.isUploadReady = true
return apiChangesetUploadResults
}
private func addFeaturesToCurrentDataset(
captureImageData: any CaptureImageDataProtocol,
featuresToUpload: [any AccessibilityFeatureProtocol],
mappedAccessibilityFeatures: [any AccessibilityFeatureProtocol]
) {
Task {
do {
try sharedAppData.currentDatasetEncoder?.addFeatures(
features: featuresToUpload, frameNumber: captureImageData.id, timestamp: captureImageData.timestamp
)
try sharedAppData.currentDatasetEncoder?.addFeatures(
features: mappedAccessibilityFeatures, frameNumber: captureImageData.id, timestamp: captureImageData.timestamp
)
} catch {
print("Error adding feature data to dataset encoder: \(error)")
}
}
}
}
struct SelectFeatureLearnMoreSheetView: View {
@Environment(\.dismiss)
var dismiss
var body: some View {
VStack(spacing: 20) {
// Image(systemName: "number")
// .resizable()
// .scaledToFit()
// .frame(width: 160)
// .foregroundStyle(.accentColor)
Text(AnnotationViewConstants.Texts.selectFeatureInfoLearnMoreSheetTitle)
.font(.headline)
Text(AnnotationViewConstants.Texts.selectFeatureInfoLearnMoreSheetMessage)
.foregroundStyle(.secondary)
Button("Dismiss") {
dismiss()
}
}
.padding(.horizontal, 40)
}
}