This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MGLMapView.mm
2950 lines (2485 loc) · 120 KB
/
MGLMapView.mm
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "MGLMapView_Private.h"
#import "MGLAttributionButton.h"
#import "MGLCompassCell.h"
#import "MGLOpenGLLayer.h"
#import "MGLStyle.h"
#import "MGLRendererFrontend.h"
#import "MGLRendererConfiguration.h"
#import "MGLAnnotationImage_Private.h"
#import "MGLAttributionInfo_Private.h"
#import "MGLFeature_Private.h"
#import "MGLFoundation_Private.h"
#import "MGLGeometry_Private.h"
#import "MGLMultiPoint_Private.h"
#import "MGLOfflineStorage_Private.h"
#import "MGLStyle_Private.h"
#import "MGLShape_Private.h"
#import "MGLAccountManager.h"
#import "MGLMapCamera.h"
#import "MGLPolygon.h"
#import "MGLPolyline.h"
#import "MGLAnnotationImage.h"
#import "MGLMapViewDelegate.h"
#import "MGLImageSource.h"
#import <mbgl/map/map.hpp>
#import <mbgl/style/style.hpp>
#import <mbgl/annotation/annotation.hpp>
#import <mbgl/map/camera.hpp>
#import <mbgl/storage/reachability.h>
#import <mbgl/util/default_thread_pool.hpp>
#import <mbgl/style/image.hpp>
#import <mbgl/renderer/renderer.hpp>
#import <mbgl/renderer/renderer_backend.hpp>
#import <mbgl/renderer/backend_scope.hpp>
#import <mbgl/storage/default_file_source.hpp>
#import <mbgl/storage/network_status.hpp>
#import <mbgl/math/wrap.hpp>
#import <mbgl/util/constants.hpp>
#import <mbgl/util/chrono.hpp>
#import <mbgl/util/exception.hpp>
#import <mbgl/util/run_loop.hpp>
#import <mbgl/util/shared_thread_pool.hpp>
#import <mbgl/util/string.hpp>
#import <mbgl/util/projection.hpp>
#import <map>
#import <unordered_map>
#import <unordered_set>
#import "NSBundle+MGLAdditions.h"
#import "NSDate+MGLAdditions.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "NSException+MGLAdditions.h"
#import "NSString+MGLAdditions.h"
#import "NSURL+MGLAdditions.h"
#import "NSColor+MGLAdditions.h"
#import "NSImage+MGLAdditions.h"
#import "NSPredicate+MGLAdditions.h"
#import <QuartzCore/QuartzCore.h>
#import <OpenGL/gl.h>
class MGLMapViewImpl;
class MGLAnnotationContext;
/// Distance from the edge of the view to ornament views (logo, attribution, etc.).
const CGFloat MGLOrnamentPadding = 12;
/// Alpha value of the ornament views (logo, attribution, etc.).
const CGFloat MGLOrnamentOpacity = 0.9;
/// Default duration for programmatic animations.
const NSTimeInterval MGLAnimationDuration = 0.3;
/// Distance in points that a single press of the panning keyboard shortcut pans the map by.
const CGFloat MGLKeyPanningIncrement = 150;
/// Degrees that a single press of the rotation keyboard shortcut rotates the map by.
const CLLocationDegrees MGLKeyRotationIncrement = 25;
/// Key for the user default that, when true, causes the map view to zoom in and out on scroll wheel events.
NSString * const MGLScrollWheelZoomsMapViewDefaultKey = @"MGLScrollWheelZoomsMapView";
/// Reuse identifier and file name of the default point annotation image.
static NSString * const MGLDefaultStyleMarkerSymbolName = @"default_marker";
/// Prefix that denotes a sprite installed by MGLMapView, to avoid collisions
/// with style-defined sprites.
static NSString * const MGLAnnotationSpritePrefix = @"com.mapbox.sprites.";
/// Slop area around the hit testing point, allowing for imprecise annotation selection.
const CGFloat MGLAnnotationImagePaddingForHitTest = 4;
/// Distance from the callout’s anchor point to the annotation it points to.
const CGFloat MGLAnnotationImagePaddingForCallout = 4;
/// Unique identifier representing a single annotation in mbgl.
typedef uint32_t MGLAnnotationTag;
/// An indication that the requested annotation was not found or is nonexistent.
enum { MGLAnnotationTagNotFound = UINT32_MAX };
/// Mapping from an annotation tag to metadata about that annotation, including
/// the annotation itself.
typedef std::unordered_map<MGLAnnotationTag, MGLAnnotationContext> MGLAnnotationTagContextMap;
/// Mapping from an annotation object to an annotation tag.
typedef std::map<id<MGLAnnotation>, MGLAnnotationTag> MGLAnnotationObjectTagMap;
/// Returns an NSImage for the default marker image.
NSImage *MGLDefaultMarkerImage() {
NSString *path = [[NSBundle mgl_frameworkBundle] pathForResource:MGLDefaultStyleMarkerSymbolName
ofType:@"pdf"];
return [[NSImage alloc] initWithContentsOfFile:path];
}
/// Converts a media timing function into a unit bezier object usable in mbgl.
mbgl::util::UnitBezier MGLUnitBezierForMediaTimingFunction(CAMediaTimingFunction *function) {
if (!function) {
function = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
}
float p1[2], p2[2];
[function getControlPointAtIndex:0 values:p1];
[function getControlPointAtIndex:1 values:p2];
return { p1[0], p1[1], p2[0], p2[1] };
}
/// Lightweight container for metadata about an annotation, including the annotation itself.
class MGLAnnotationContext {
public:
id <MGLAnnotation> annotation;
/// The annotation’s image’s reuse identifier.
NSString *imageReuseIdentifier;
};
@interface MGLMapView () <NSPopoverDelegate, MGLMultiPointDelegate, NSGestureRecognizerDelegate>
@property (nonatomic, readwrite) NSSegmentedControl *zoomControls;
@property (nonatomic, readwrite) NSSlider *compass;
@property (nonatomic, readwrite) NSImageView *logoView;
@property (nonatomic, readwrite) NSView *attributionView;
@property (nonatomic, readwrite) MGLStyle *style;
/// Mapping from reusable identifiers to annotation images.
@property (nonatomic) NS_MUTABLE_DICTIONARY_OF(NSString *, MGLAnnotationImage *) *annotationImagesByIdentifier;
/// Currently shown popover representing the selected annotation.
@property (nonatomic) NSPopover *calloutForSelectedAnnotation;
@property (nonatomic, readwrite, getter=isDormant) BOOL dormant;
@end
@implementation MGLMapView {
/// Cross-platform map view controller.
mbgl::Map *_mbglMap;
MGLMapViewImpl *_mbglView;
std::unique_ptr<MGLRenderFrontend> _rendererFrontend;
std::shared_ptr<mbgl::ThreadPool> _mbglThreadPool;
NSPanGestureRecognizer *_panGestureRecognizer;
NSMagnificationGestureRecognizer *_magnificationGestureRecognizer;
NSRotationGestureRecognizer *_rotationGestureRecognizer;
NSClickGestureRecognizer *_singleClickRecognizer;
double _zoomAtBeginningOfGesture;
CLLocationDirection _directionAtBeginningOfGesture;
CGFloat _pitchAtBeginningOfGesture;
BOOL _didHideCursorDuringGesture;
MGLAnnotationTagContextMap _annotationContextsByAnnotationTag;
MGLAnnotationObjectTagMap _annotationTagsByAnnotation;
MGLAnnotationTag _selectedAnnotationTag;
MGLAnnotationTag _lastSelectedAnnotationTag;
/// Size of the rectangle formed by unioning the maximum slop area around every annotation image.
NSSize _unionedAnnotationImageSize;
std::vector<MGLAnnotationTag> _annotationsNearbyLastClick;
/// True if any annotations that have tooltips have been installed.
BOOL _wantsToolTipRects;
/// True if any annotation images that have custom cursors have been installed.
BOOL _wantsCursorRects;
/// True if a willChange notification has been issued for shape annotation layers and a didChange notification is pending.
BOOL _isChangingAnnotationLayers;
// Cached checks for delegate method implementations that may be called from
// MGLMultiPointDelegate methods.
BOOL _delegateHasAlphasForShapeAnnotations;
BOOL _delegateHasStrokeColorsForShapeAnnotations;
BOOL _delegateHasFillColorsForShapeAnnotations;
BOOL _delegateHasLineWidthsForShapeAnnotations;
/// True if the current process is the Interface Builder designable
/// renderer. When drawing the designable, the map is paused, so any call to
/// it may hang the process.
BOOL _isTargetingInterfaceBuilder;
CLLocationDegrees _pendingLatitude;
CLLocationDegrees _pendingLongitude;
/// True if the view is currently printing itself.
BOOL _isPrinting;
/// reachability instance
MGLReachability *_reachability;
}
#pragma mark Lifecycle
+ (void)initialize {
if (self == [MGLMapView class]) {
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
MGLScrollWheelZoomsMapViewDefaultKey: @NO,
}];
}
}
- (instancetype)initWithFrame:(NSRect)frameRect {
if (self = [super initWithFrame:frameRect]) {
[self commonInit];
self.styleURL = nil;
}
return self;
}
- (instancetype)initWithFrame:(NSRect)frame styleURL:(nullable NSURL *)styleURL {
if (self = [super initWithFrame:frame]) {
[self commonInit];
self.styleURL = styleURL;
}
return self;
}
- (instancetype)initWithCoder:(nonnull NSCoder *)decoder {
if (self = [super initWithCoder:decoder]) {
[self commonInit];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
// If the Style URL inspectable was not set, make sure to go through
// -setStyleURL: to load the default style.
if (_mbglMap->getStyle().getURL().empty()) {
self.styleURL = nil;
}
}
+ (NSArray *)restorableStateKeyPaths {
return @[@"camera", @"debugMask"];
}
- (void)commonInit {
_isTargetingInterfaceBuilder = NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent;
// Set up cross-platform controllers and resources.
_mbglView = new MGLMapViewImpl(self);
// Delete the pre-offline ambient cache at
// ~/Library/Caches/com.mapbox.sdk.ios/cache.db.
NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];
cachesDirectoryURL = [cachesDirectoryURL URLByAppendingPathComponent:
[NSBundle mgl_frameworkBundle].bundleIdentifier];
NSURL *legacyCacheURL = [cachesDirectoryURL URLByAppendingPathComponent:@"cache.db"];
[[NSFileManager defaultManager] removeItemAtURL:legacyCacheURL error:NULL];
_mbglThreadPool = mbgl::sharedThreadPool();
MGLRendererConfiguration *config = [MGLRendererConfiguration currentConfiguration];
auto renderer = std::make_unique<mbgl::Renderer>(*_mbglView, config.scaleFactor, *config.fileSource, *_mbglThreadPool, config.contextMode, config.cacheDir, config.localFontFamilyName);
_rendererFrontend = std::make_unique<MGLRenderFrontend>(std::move(renderer), self, *_mbglView, true);
_mbglMap = new mbgl::Map(*_rendererFrontend, *_mbglView, self.size, config.scaleFactor, *config.fileSource, *_mbglThreadPool, mbgl::MapMode::Continuous, mbgl::ConstrainMode::None, mbgl::ViewportMode::Default);
// Install the OpenGL layer. Interface Builder’s synchronous drawing means
// we can’t display a map, so don’t even bother to have a map layer.
self.layer = _isTargetingInterfaceBuilder ? [CALayer layer] : [MGLOpenGLLayer layer];
// Notify map object when network reachability status changes.
_reachability = [MGLReachability reachabilityForInternetConnection];
_reachability.reachableBlock = ^(MGLReachability *) {
mbgl::NetworkStatus::Reachable();
};
[_reachability startNotifier];
// Install ornaments and gesture recognizers.
[self installZoomControls];
[self installCompass];
[self installLogoView];
[self installAttributionView];
[self installGestureRecognizers];
// Set up annotation management and selection state.
_annotationImagesByIdentifier = [NSMutableDictionary dictionary];
_annotationContextsByAnnotationTag = {};
_annotationTagsByAnnotation = {};
_selectedAnnotationTag = MGLAnnotationTagNotFound;
_lastSelectedAnnotationTag = MGLAnnotationTagNotFound;
_annotationsNearbyLastClick = {};
// Jump to Null Island initially.
self.automaticallyAdjustsContentInsets = YES;
mbgl::CameraOptions options;
options.center = mbgl::LatLng(0, 0);
options.padding = MGLEdgeInsetsFromNSEdgeInsets(self.contentInsets);
options.zoom = _mbglMap->getMinZoom();
_mbglMap->jumpTo(options);
_pendingLatitude = NAN;
_pendingLongitude = NAN;
}
- (mbgl::Size)size {
// check for minimum texture size supported by OpenGL ES 2.0
//
CGSize size = CGSizeMake(MAX(self.bounds.size.width, 64), MAX(self.bounds.size.height, 64));
return { static_cast<uint32_t>(size.width),
static_cast<uint32_t>(size.height) };
}
- (mbgl::Size)framebufferSize {
NSRect bounds = [self convertRectToBacking:self.bounds];
return { static_cast<uint32_t>(bounds.size.width), static_cast<uint32_t>(bounds.size.height) };
}
/// Adds zoom controls to the lower-right corner.
- (void)installZoomControls {
_zoomControls = [[NSSegmentedControl alloc] initWithFrame:NSZeroRect];
_zoomControls.wantsLayer = YES;
_zoomControls.layer.opacity = MGLOrnamentOpacity;
[(NSSegmentedCell *)_zoomControls.cell setTrackingMode:NSSegmentSwitchTrackingMomentary];
_zoomControls.continuous = YES;
_zoomControls.segmentCount = 2;
[_zoomControls setLabel:NSLocalizedStringWithDefaultValue(@"ZOOM_OUT_LABEL", nil, nil, @"−", @"Label of Zoom Out button; U+2212 MINUS SIGN") forSegment:0];
[(NSSegmentedCell *)_zoomControls.cell setTag:0 forSegment:0];
[(NSSegmentedCell *)_zoomControls.cell setToolTip:NSLocalizedStringWithDefaultValue(@"ZOOM_OUT_TOOLTIP", nil, nil, @"Zoom Out", @"Tooltip of Zoom Out button") forSegment:0];
[_zoomControls setLabel:NSLocalizedStringWithDefaultValue(@"ZOOM_IN_LABEL", nil, nil, @"+", @"Label of Zoom In button") forSegment:1];
[(NSSegmentedCell *)_zoomControls.cell setTag:1 forSegment:1];
[(NSSegmentedCell *)_zoomControls.cell setToolTip:NSLocalizedStringWithDefaultValue(@"ZOOM_IN_TOOLTIP", nil, nil, @"Zoom In", @"Tooltip of Zoom In button") forSegment:1];
_zoomControls.target = self;
_zoomControls.action = @selector(zoomInOrOut:);
_zoomControls.controlSize = NSRegularControlSize;
[_zoomControls sizeToFit];
_zoomControls.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_zoomControls];
}
/// Adds a rudimentary compass control to the lower-right corner.
- (void)installCompass {
_compass = [[NSSlider alloc] initWithFrame:NSZeroRect];
_compass.wantsLayer = YES;
_compass.layer.opacity = MGLOrnamentOpacity;
_compass.cell = [[MGLCompassCell alloc] init];
_compass.continuous = YES;
_compass.target = self;
_compass.action = @selector(rotate:);
[_compass sizeToFit];
_compass.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_compass];
}
/// Adds a Mapbox logo to the lower-left corner.
- (void)installLogoView {
_logoView = [[NSImageView alloc] initWithFrame:NSZeroRect];
_logoView.wantsLayer = YES;
NSImage *logoImage = [[NSImage alloc] initWithContentsOfFile:
[[NSBundle mgl_frameworkBundle] pathForResource:@"mapbox" ofType:@"pdf"]];
// Account for the image’s built-in padding when aligning other controls to the logo.
logoImage.alignmentRect = NSOffsetRect(logoImage.alignmentRect, 0, 3);
_logoView.image = logoImage;
_logoView.translatesAutoresizingMaskIntoConstraints = NO;
_logoView.accessibilityTitle = NSLocalizedStringWithDefaultValue(@"MAP_A11Y_TITLE", nil, nil, @"Mapbox", @"Accessibility title");
[self addSubview:_logoView];
}
/// Adds legally required map attribution to the lower-left corner.
- (void)installAttributionView {
[_attributionView removeFromSuperview];
_attributionView = [[NSView alloc] initWithFrame:NSZeroRect];
_attributionView.wantsLayer = YES;
// Make the background and foreground translucent to be unobtrusive.
_attributionView.layer.opacity = 0.6;
// Blur the background to prevent text underneath the view from running into
// the text in the view, rendering it illegible.
CIFilter *attributionBlurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
[attributionBlurFilter setDefaults];
// Brighten the background. This is similar to applying a translucent white
// background on the view, but the effect is a bit more subtle and works
// well with the blur above.
CIFilter *attributionColorFilter = [CIFilter filterWithName:@"CIColorControls"];
[attributionColorFilter setDefaults];
[attributionColorFilter setValue:@(0.1) forKey:kCIInputBrightnessKey];
// Apply the background effects and a standard button corner radius.
_attributionView.backgroundFilters = @[attributionColorFilter, attributionBlurFilter];
_attributionView.layer.cornerRadius = 4;
_attributionView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_attributionView];
[self updateAttributionView];
}
/// Adds gesture recognizers for manipulating the viewport and selecting annotations.
- (void)installGestureRecognizers {
_scrollEnabled = YES;
_zoomEnabled = YES;
_rotateEnabled = YES;
_pitchEnabled = YES;
_panGestureRecognizer = [[NSPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
_panGestureRecognizer.delaysKeyEvents = YES;
[self addGestureRecognizer:_panGestureRecognizer];
_singleClickRecognizer = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(handleClickGesture:)];
_singleClickRecognizer.delaysPrimaryMouseButtonEvents = NO;
_singleClickRecognizer.delegate = self;
[self addGestureRecognizer:_singleClickRecognizer];
NSClickGestureRecognizer *rightClickGestureRecognizer = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(handleRightClickGesture:)];
rightClickGestureRecognizer.buttonMask = 0x2;
[self addGestureRecognizer:rightClickGestureRecognizer];
NSClickGestureRecognizer *doubleClickGestureRecognizer = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleClickGesture:)];
doubleClickGestureRecognizer.numberOfClicksRequired = 2;
doubleClickGestureRecognizer.delaysPrimaryMouseButtonEvents = NO;
[self addGestureRecognizer:doubleClickGestureRecognizer];
_magnificationGestureRecognizer = [[NSMagnificationGestureRecognizer alloc] initWithTarget:self action:@selector(handleMagnificationGesture:)];
[self addGestureRecognizer:_magnificationGestureRecognizer];
_rotationGestureRecognizer = [[NSRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotationGesture:)];
[self addGestureRecognizer:_rotationGestureRecognizer];
}
/// Updates the attribution view to reflect the sources used. For now, this is
/// hard-coded to the standard Mapbox and OpenStreetMap attribution.
- (void)updateAttributionView {
NSView *attributionView = self.attributionView;
for (NSView *button in attributionView.subviews) {
[button removeConstraints:button.constraints];
}
attributionView.subviews = @[];
[attributionView removeConstraints:attributionView.constraints];
// Make the whole string mini by default.
// Force links to be black, because the default blue is distracting.
CGFloat miniSize = [NSFont systemFontSizeForControlSize:NSMiniControlSize];
NSArray *attributionInfos = [self.style attributionInfosWithFontSize:miniSize linkColor:[NSColor blackColor]];
for (MGLAttributionInfo *info in attributionInfos) {
// Feedback links are added to the Help menu.
if (info.feedbackLink) {
continue;
}
// For each attribution, add a borderless button that responds to clicks
// and feels like a hyperlink.
NSButton *button = [[MGLAttributionButton alloc] initWithAttributionInfo:info];
button.controlSize = NSMiniControlSize;
button.translatesAutoresizingMaskIntoConstraints = NO;
// Set the new button flush with the buttom of the container and to the
// right of the previous button, with standard spacing. If there is no
// previous button, align to the container instead.
NSView *previousView = attributionView.subviews.lastObject;
[attributionView addSubview:button];
[attributionView addConstraint:
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:attributionView
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
[attributionView addConstraint:
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:previousView ? previousView : attributionView
attribute:previousView ? NSLayoutAttributeTrailing : NSLayoutAttributeLeading
multiplier:1
constant:8]];
[attributionView addConstraint:
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:attributionView
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
}
if (attributionInfos.count) {
[attributionView addConstraint:
[NSLayoutConstraint constraintWithItem:attributionView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:attributionView.subviews.lastObject
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:8]];
}
}
- (void)dealloc {
[_reachability stopNotifier];
[self.window removeObserver:self forKeyPath:@"contentLayoutRect"];
[self.window removeObserver:self forKeyPath:@"titlebarAppearsTransparent"];
// Close any annotation callout immediately.
[self.calloutForSelectedAnnotation close];
self.calloutForSelectedAnnotation = nil;
// Removing the annotations unregisters any outstanding KVO observers.
[self removeAnnotations:self.annotations];
if (_mbglMap) {
delete _mbglMap;
_mbglMap = nullptr;
}
if (_mbglView) {
delete _mbglView;
_mbglView = nullptr;
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__unused NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentLayoutRect"] ||
[keyPath isEqualToString:@"titlebarAppearsTransparent"]) {
[self adjustContentInsets];
} else if ([keyPath isEqualToString:@"coordinate"] &&
[object conformsToProtocol:@protocol(MGLAnnotation)] &&
![object isKindOfClass:[MGLMultiPoint class]]) {
id <MGLAnnotation> annotation = object;
MGLAnnotationTag annotationTag = (MGLAnnotationTag)(NSUInteger)context;
// We can get here because a subclass registered itself as an observer
// of the coordinate key path of a non-multipoint annotation but failed
// to handle the change. This check deters us from treating the
// subclass’s context as an annotation tag. If the context happens to
// match a valid annotation tag, the annotation will be unnecessarily
// but safely updated.
if (annotation == [self annotationWithTag:annotationTag]) {
const mbgl::Point<double> point = MGLPointFromLocationCoordinate2D(annotation.coordinate);
MGLAnnotationImage *annotationImage = [self imageOfAnnotationWithTag:annotationTag];
_mbglMap->updateAnnotation(annotationTag, mbgl::SymbolAnnotation { point, annotationImage.styleIconIdentifier.UTF8String ?: "" });
[self updateAnnotationCallouts];
}
} else if ([keyPath isEqualToString:@"coordinates"] &&
[object isKindOfClass:[MGLMultiPoint class]]) {
MGLMultiPoint *annotation = object;
MGLAnnotationTag annotationTag = (MGLAnnotationTag)(NSUInteger)context;
// We can get here because a subclass registered itself as an observer
// of the coordinates key path of a multipoint annotation but failed
// to handle the change. This check deters us from treating the
// subclass’s context as an annotation tag. If the context happens to
// match a valid annotation tag, the annotation will be unnecessarily
// but safely updated.
if (annotation == [self annotationWithTag:annotationTag]) {
_mbglMap->updateAnnotation(annotationTag, [annotation annotationObjectWithDelegate:self]);
[self updateAnnotationCallouts];
}
}
}
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
return [key isEqualToString:@"annotations"] ? YES : [super automaticallyNotifiesObserversForKey:key];
}
- (void)setDelegate:(id<MGLMapViewDelegate>)delegate {
_delegate = delegate;
// Cache checks for delegate method implementations that may be called in a
// hot loop, namely the annotation style methods.
_delegateHasAlphasForShapeAnnotations = [_delegate respondsToSelector:@selector(mapView:alphaForShapeAnnotation:)];
_delegateHasStrokeColorsForShapeAnnotations = [_delegate respondsToSelector:@selector(mapView:strokeColorForShapeAnnotation:)];
_delegateHasFillColorsForShapeAnnotations = [_delegate respondsToSelector:@selector(mapView:fillColorForPolygonAnnotation:)];
_delegateHasLineWidthsForShapeAnnotations = [_delegate respondsToSelector:@selector(mapView:lineWidthForPolylineAnnotation:)];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
if ([self.delegate respondsToSelector:@selector(mapView:regionWillChangeAnimated:)]) {
NSLog(@"-mapView:regionWillChangeAnimated: is not supported by the macOS SDK, but %@ implements it anyways. "
@"Please implement -[%@ mapView:cameraWillChangeAnimated:] instead.",
NSStringFromClass([delegate class]), NSStringFromClass([delegate class]));
}
if ([self.delegate respondsToSelector:@selector(mapViewRegionIsChanging:)]) {
NSLog(@"-mapViewRegionIsChanging: is not supported by the macOS SDK, but %@ implements it anyways. "
@"Please implement -[%@ mapViewCameraIsChanging:] instead.",
NSStringFromClass([delegate class]), NSStringFromClass([delegate class]));
}
if ([self.delegate respondsToSelector:@selector(mapView:regionDidChangeAnimated:)]) {
NSLog(@"-mapView:regionDidChangeAnimated: is not supported by the macOS SDK, but %@ implements it anyways. "
@"Please implement -[%@ mapView:cameraDidChangeAnimated:] instead.",
NSStringFromClass([delegate class]), NSStringFromClass([delegate class]));
}
#pragma clang diagnostic pop
}
#pragma mark Style
+ (NS_SET_OF(NSString *) *)keyPathsForValuesAffectingStyle {
return [NSSet setWithObject:@"styleURL"];
}
- (nonnull NSURL *)styleURL {
NSString *styleURLString = @(_mbglMap->getStyle().getURL().c_str()).mgl_stringOrNilIfEmpty;
return styleURLString ? [NSURL URLWithString:styleURLString] : [MGLStyle streetsStyleURLWithVersion:MGLStyleDefaultVersion];
}
- (void)setStyleURL:(nullable NSURL *)styleURL {
if (_isTargetingInterfaceBuilder) {
return;
}
// Default to Streets.
if (!styleURL) {
styleURL = [MGLStyle streetsStyleURLWithVersion:MGLStyleDefaultVersion];
}
// An access token is required to load any default style, including Streets.
if (![MGLAccountManager accessToken] && [styleURL.scheme isEqualToString:@"mapbox"]) {
NSLog(@"Cannot set the style URL to %@ because no access token has been specified.", styleURL);
return;
}
styleURL = styleURL.mgl_URLByStandardizingScheme;
self.style = nil;
_mbglMap->getStyle().loadURL(styleURL.absoluteString.UTF8String);
}
- (IBAction)reloadStyle:(__unused id)sender {
NSURL *styleURL = self.styleURL;
_mbglMap->getStyle().loadURL("");
self.styleURL = styleURL;
}
- (mbgl::Map *)mbglMap {
return _mbglMap;
}
- (mbgl::Renderer *)renderer {
return _rendererFrontend->getRenderer();
}
#pragma mark View hierarchy and drawing
- (void)viewWillMoveToWindow:(NSWindow *)newWindow {
[self deselectAnnotation:self.selectedAnnotation];
if (!self.dormant && !newWindow) {
self.dormant = YES;
}
[self.window removeObserver:self forKeyPath:@"contentLayoutRect"];
[self.window removeObserver:self forKeyPath:@"titlebarAppearsTransparent"];
}
- (void)viewDidMoveToWindow {
NSWindow *window = self.window;
if (self.dormant && window) {
self.dormant = NO;
}
if (window && _mbglMap->getConstrainMode() == mbgl::ConstrainMode::None) {
_mbglMap->setConstrainMode(mbgl::ConstrainMode::HeightOnly);
}
[window addObserver:self
forKeyPath:@"contentLayoutRect"
options:NSKeyValueObservingOptionInitial
context:NULL];
[window addObserver:self
forKeyPath:@"titlebarAppearsTransparent"
options:NSKeyValueObservingOptionInitial
context:NULL];
}
- (BOOL)wantsLayer {
return YES;
}
- (BOOL)wantsBestResolutionOpenGLSurface {
// Use an OpenGL layer, except when drawing the designable, which is just
// ordinary Cocoa.
return !_isTargetingInterfaceBuilder;
}
- (void)setFrame:(NSRect)frame {
super.frame = frame;
if (!_isTargetingInterfaceBuilder) {
_mbglMap->setSize(self.size);
}
}
- (void)updateConstraints {
// Place the zoom controls at the lower-right corner of the view.
[self addConstraint:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_zoomControls
attribute:NSLayoutAttributeBottom
multiplier:1
constant:MGLOrnamentPadding]];
[self addConstraint:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_zoomControls
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:MGLOrnamentPadding]];
// Center the compass above the zoom controls, assuming that the compass is
// narrower than the zoom controls.
[self addConstraint:
[NSLayoutConstraint constraintWithItem:_compass
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:_zoomControls
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
[self addConstraint:
[NSLayoutConstraint constraintWithItem:_zoomControls
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_compass
attribute:NSLayoutAttributeBottom
multiplier:1
constant:8]];
// Place the logo view in the lower-left corner of the view, accounting for
// the logo’s alignment rect.
[self addConstraint:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_logoView
attribute:NSLayoutAttributeBottom
multiplier:1
constant:MGLOrnamentPadding - _logoView.image.alignmentRect.origin.y]];
[self addConstraint:
[NSLayoutConstraint constraintWithItem:_logoView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading
multiplier:1
constant:MGLOrnamentPadding - _logoView.image.alignmentRect.origin.x]];
// Place the attribution view to the right of the logo view and size it to
// fit the buttons inside.
[self addConstraint:[NSLayoutConstraint constraintWithItem:_logoView
attribute:NSLayoutAttributeBaseline
relatedBy:NSLayoutRelationEqual
toItem:_attributionView
attribute:NSLayoutAttributeBaseline
multiplier:1
constant:_logoView.image.alignmentRect.origin.y]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:_attributionView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:_logoView
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:8]];
[super updateConstraints];
}
- (void)renderSync {
if (!self.dormant && _rendererFrontend) {
_rendererFrontend->render();
if (_isPrinting) {
_isPrinting = NO;
NSImage *image = [[NSImage alloc] initWithMGLPremultipliedImage:_mbglView->readStillImage()];
[self performSelector:@selector(printWithImage:) withObject:image afterDelay:0];
}
// [self updateUserLocationAnnotationView];
}
}
- (void)setNeedsGLDisplay {
MGLAssertIsMainThread();
[self.layer setNeedsDisplay];
}
- (void)cameraWillChangeAnimated:(BOOL)animated {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapView:cameraWillChangeAnimated:)]) {
[self.delegate mapView:self cameraWillChangeAnimated:animated];
}
}
- (void)cameraIsChanging {
if (!_mbglMap) {
return;
}
// Update a minimum of UI that needs to stay attached to the map
// while animating.
[self updateCompass];
[self updateAnnotationCallouts];
if ([self.delegate respondsToSelector:@selector(mapViewCameraIsChanging:)]) {
[self.delegate mapViewCameraIsChanging:self];
}
}
- (void)cameraDidChangeAnimated:(BOOL)animated {
if (!_mbglMap) {
return;
}
// Update all UI at the end of an animation or atomic change to the
// viewport. More expensive updates can happen here, but care should
// still be taken to minimize the work done here because scroll
// gesture recognition and momentum scrolling is performed as a
// series of atomic changes, not an animation.
[self updateZoomControls];
[self updateCompass];
[self updateAnnotationCallouts];
[self updateAnnotationTrackingAreas];
if ([self.delegate respondsToSelector:@selector(mapView:cameraDidChangeAnimated:)]) {
[self.delegate mapView:self cameraDidChangeAnimated:animated];
}
}
- (void)mapViewWillStartLoadingMap {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapViewWillStartLoadingMap:)]) {
[self.delegate mapViewWillStartLoadingMap:self];
}
}
- (void)mapViewDidFinishLoadingMap {
if (!_mbglMap) {
return;
}
[self.style willChangeValueForKey:@"sources"];
[self.style didChangeValueForKey:@"sources"];
[self.style willChangeValueForKey:@"layers"];
[self.style didChangeValueForKey:@"layers"];
if ([self.delegate respondsToSelector:@selector(mapViewDidFinishLoadingMap:)]) {
[self.delegate mapViewDidFinishLoadingMap:self];
}
}
- (void)mapViewDidFailLoadingMapWithError:(NSError *)error {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapViewDidFailLoadingMap:withError:)]) {
[self.delegate mapViewDidFailLoadingMap:self withError:error];
}
}
- (void)mapViewWillStartRenderingFrame {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapViewWillStartRenderingFrame:)]) {
[self.delegate mapViewWillStartRenderingFrame:self];
}
}
- (void)mapViewDidFinishRenderingFrameFullyRendered:(BOOL)fullyRendered {
if (!_mbglMap) {
return;
}
if (_isChangingAnnotationLayers) {
_isChangingAnnotationLayers = NO;
[self.style didChangeValueForKey:@"layers"];
}
if ([self.delegate respondsToSelector:@selector(mapViewDidFinishRenderingFrame:fullyRendered:)]) {
[self.delegate mapViewDidFinishRenderingFrame:self fullyRendered:fullyRendered];
}
}
- (void)mapViewWillStartRenderingMap {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapViewWillStartRenderingMap:)]) {
[self.delegate mapViewWillStartRenderingMap:self];
}
}
- (void)mapViewDidFinishRenderingMapFullyRendered:(BOOL)fullyRendered {
if (!_mbglMap) {
return;
}
if ([self.delegate respondsToSelector:@selector(mapViewDidFinishRenderingMap:fullyRendered:)]) {
[self.delegate mapViewDidFinishRenderingMap:self fullyRendered:fullyRendered];
}
}
- (void)mapViewDidFinishLoadingStyle {
if (!_mbglMap) {
return;
}
self.style = [[MGLStyle alloc] initWithRawStyle:&_mbglMap->getStyle() mapView:self];
if ([self.delegate respondsToSelector:@selector(mapView:didFinishLoadingStyle:)])
{
[self.delegate mapView:self didFinishLoadingStyle:self.style];
}
}
- (void)sourceDidChange:(MGLSource *)source {
if (!_mbglMap) {
return;
}
// Attribution only applies to tiled sources
if ([source isKindOfClass:[MGLTileSource class]]) {
[self installAttributionView];
}
self.needsUpdateConstraints = YES;
self.needsDisplay = YES;
}
#pragma mark Printing
- (void)print:(__unused id)sender {
_isPrinting = YES;
[self setNeedsGLDisplay];
}
- (void)printWithImage:(NSImage *)image {
NSImageView *imageView = [[NSImageView alloc] initWithFrame:self.bounds];
imageView.image = image;
NSPrintOperation *op = [NSPrintOperation printOperationWithView:imageView];
[op runOperation];
}
#pragma mark Viewport
+ (NS_SET_OF(NSString *) *)keyPathsForValuesAffectingCenterCoordinate {
return [NSSet setWithObjects:@"latitude", @"longitude", @"camera", nil];
}
- (CLLocationCoordinate2D)centerCoordinate {
mbgl::EdgeInsets padding = MGLEdgeInsetsFromNSEdgeInsets(self.contentInsets);
return MGLLocationCoordinate2DFromLatLng(_mbglMap->getLatLng(padding));
}
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate {
[self setCenterCoordinate:centerCoordinate animated:NO];
}
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate animated:(BOOL)animated {
[self willChangeValueForKey:@"centerCoordinate"];
_mbglMap->setLatLng(MGLLatLngFromLocationCoordinate2D(centerCoordinate),
MGLEdgeInsetsFromNSEdgeInsets(self.contentInsets),
MGLDurationFromTimeInterval(animated ? MGLAnimationDuration : 0));
[self didChangeValueForKey:@"centerCoordinate"];
}
- (void)offsetCenterCoordinateBy:(NSPoint)delta animated:(BOOL)animated {
[self willChangeValueForKey:@"centerCoordinate"];
_mbglMap->cancelTransitions();
MGLMapCamera *oldCamera = self.camera;
_mbglMap->moveBy({ delta.x, delta.y },
MGLDurationFromTimeInterval(animated ? MGLAnimationDuration : 0));
if ([self.delegate respondsToSelector:@selector(mapView:shouldChangeFromCamera:toCamera:)]
&& ![self.delegate mapView:self shouldChangeFromCamera:oldCamera toCamera:self.camera]) {
self.camera = oldCamera;
}
[self didChangeValueForKey:@"centerCoordinate"];
}
- (CLLocationDegrees)pendingLatitude {
return _pendingLatitude;