summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitmodules4
-rw-r--r--LICENSE.md31
-rw-r--r--Makefile13
-rw-r--r--README.md2
-rw-r--r--android/cpp/jni.cpp2
-rw-r--r--gyp/platform-ios.gypi23
-rw-r--r--gyp/platform-osx.gypi2
-rw-r--r--include/mbgl/ios/MGLMapView.h139
-rw-r--r--include/mbgl/ios/MGLMapboxEvents.h60
-rw-r--r--include/mbgl/ios/MGLMetricsLocationManager.h21
-rw-r--r--include/mbgl/ios/MGLStyleFunctionValue.h23
-rw-r--r--include/mbgl/ios/MGLTypes.h22
-rw-r--r--include/mbgl/ios/MGLUserLocation.h26
-rw-r--r--include/mbgl/ios/MapboxGL.h5
-rw-r--r--include/mbgl/ios/NSArray+MGLAdditions.h7
-rw-r--r--include/mbgl/ios/NSDictionary+MGLAdditions.h7
-rw-r--r--include/mbgl/ios/UIColor+MGLAdditions.h11
-rw-r--r--include/mbgl/map/map.hpp18
-rw-r--r--include/mbgl/map/view.hpp17
-rw-r--r--include/mbgl/platform/darwin/settings_nsuserdefaults.hpp5
-rw-r--r--ios/MapboxGL.podspec2
-rw-r--r--ios/app/MBXViewController.mm78
-rw-r--r--ios/app/mapboxgl-app.gyp4
-rw-r--r--platform/darwin/settings_nsuserdefaults.mm36
-rw-r--r--platform/ios/MGLMapView.mm1399
-rw-r--r--platform/ios/MGLMapboxEvents.m658
-rw-r--r--platform/ios/MGLMetricsLocationManager.m84
-rw-r--r--platform/ios/MGLStyleFunctionValue.m190
-rw-r--r--platform/ios/MGLTypes.m24
-rw-r--r--platform/ios/MGLUserLocation.m57
-rw-r--r--platform/ios/MGLUserLocationAnnotationView.h18
-rw-r--r--platform/ios/MGLUserLocationAnnotationView.m197
-rw-r--r--platform/ios/MGLUserLocation_Private.h9
-rw-r--r--platform/ios/NSArray+MGLAdditions.m10
-rw-r--r--platform/ios/NSDictionary+MGLAdditions.m10
-rw-r--r--platform/ios/UIColor+MGLAdditions.m167
-rw-r--r--platform/ios/resources/mapbox.pngbin5947 -> 1958 bytes
-rw-r--r--platform/ios/resources/mapbox@2x.pngbin10713 -> 4492 bytes
-rw-r--r--platform/ios/resources/mapbox@3x.pngbin14888 -> 7059 bytes
m---------platform/ios/vendor/SMCalloutView0
-rw-r--r--src/mbgl/geometry/line_atlas.cpp29
-rw-r--r--src/mbgl/geometry/line_atlas.hpp2
-rw-r--r--src/mbgl/geometry/sprite_atlas.cpp32
-rw-r--r--src/mbgl/geometry/static_vertex_buffer.cpp2
-rw-r--r--src/mbgl/map/map.cpp136
-rw-r--r--src/mbgl/map/source.cpp24
-rw-r--r--src/mbgl/map/tile_data.hpp14
-rw-r--r--src/mbgl/map/tile_parser.cpp142
-rw-r--r--src/mbgl/map/tile_parser.hpp3
-rw-r--r--src/mbgl/map/vector_tile.cpp48
-rw-r--r--src/mbgl/map/vector_tile.hpp2
-rw-r--r--src/mbgl/renderer/debug_bucket.cpp2
-rw-r--r--src/mbgl/renderer/fill_bucket.cpp13
-rw-r--r--src/mbgl/renderer/fill_bucket.hpp6
-rw-r--r--src/mbgl/renderer/line_bucket.cpp14
-rw-r--r--src/mbgl/renderer/line_bucket.hpp7
-rw-r--r--src/mbgl/renderer/painter.cpp33
-rw-r--r--src/mbgl/renderer/painter.hpp2
-rw-r--r--src/mbgl/renderer/painter_clipping.cpp2
-rw-r--r--src/mbgl/renderer/painter_debug.cpp2
-rw-r--r--src/mbgl/renderer/painter_line.cpp2
-rw-r--r--src/mbgl/renderer/painter_raster.cpp1
-rw-r--r--src/mbgl/renderer/painter_symbol.cpp2
-rw-r--r--src/mbgl/renderer/symbol_bucket.cpp16
-rw-r--r--src/mbgl/renderer/symbol_bucket.hpp6
-rw-r--r--src/mbgl/style/style.cpp33
-rw-r--r--src/mbgl/style/style.hpp21
-rw-r--r--src/mbgl/style/style_layer.cpp11
-rw-r--r--src/mbgl/style/style_layer.hpp4
-rw-r--r--src/mbgl/style/style_layer_group.cpp34
-rw-r--r--src/mbgl/style/style_layer_group.hpp24
-rw-r--r--src/mbgl/style/style_parser.cpp96
-rw-r--r--src/mbgl/style/style_parser.hpp14
-rw-r--r--src/mbgl/text/collision.cpp12
-rw-r--r--src/mbgl/text/collision.hpp1
-rw-r--r--src/mbgl/text/glyph_store.cpp6
-rw-r--r--src/mbgl/text/placement.cpp8
-rw-r--r--src/mbgl/text/rotation_range.cpp2
-rw-r--r--src/mbgl/util/clip_ids.cpp6
-rw-r--r--src/mbgl/util/mapbox.cpp18
-rw-r--r--src/mbgl/util/mapbox.hpp1
-rw-r--r--src/mbgl/util/merge_lines.cpp46
-rw-r--r--src/mbgl/util/scaling.cpp27
-rw-r--r--src/mbgl/util/scaling.hpp2
-rw-r--r--test/fixtures/fixture_log_observer.cpp6
-rw-r--r--test/fixtures/sprites/atlas_reference.binbin8137 -> 8158 bytes
-rw-r--r--test/fixtures/sprites/atlas_reference.pngbin9109 -> 9101 bytes
-rw-r--r--test/miscellaneous/bilinear.cpp22
-rw-r--r--test/miscellaneous/mapbox.cpp5
89 files changed, 2343 insertions, 1979 deletions
diff --git a/.gitmodules b/.gitmodules
index 19de5b6f78..9e5265a6a1 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -13,3 +13,7 @@
[submodule "test/ios/KIF"]
path = test/ios/KIF
url = https://github.com/mapbox/KIF.git
+
+[submodule "platform/ios/vendor/SMCalloutView"]
+ path = platform/ios/vendor/SMCalloutView
+ url = https://github.com/nfarina/calloutview.git
diff --git a/LICENSE.md b/LICENSE.md
index 845f311695..e5ed29c9ae 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -22,3 +22,34 @@ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+===========================================================================
+
+Mapbox GL uses portions of the Mapbox iOS SDK, which was derived from the
+Route-Me open source project, including the Alpstein fork of it.
+
+The Route-Me license appears below.
+
+Copyright (c) 2008-2013, Route-Me Contributors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/Makefile b/Makefile
index 33135ae96e..4c830fd83f 100644
--- a/Makefile
+++ b/Makefile
@@ -25,10 +25,13 @@ config/%.gypi: configure
styles/styles:
git submodule update --init styles
+SMCalloutView:
+ git submodule update --init platform/ios/vendor/SMCalloutView
+
#### Library builds ############################################################
.PRECIOUS: Makefile/mbgl
-Makefile/mbgl: config/$(HOST).gypi styles/styles
+Makefile/mbgl: config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make
mbgl: Makefile/mbgl
@@ -41,13 +44,13 @@ install: Makefile/mbgl
LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) install
.PRECIOUS: Xcode/mbgl
-Xcode/mbgl: config/$(HOST).gypi styles/styles
+Xcode/mbgl: config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f xcode
##### Test builds ##############################################################
.PRECIOUS: Makefile/test
-Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles
+Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp test/test.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make
test: Makefile/test
@@ -58,7 +61,7 @@ test-%: test
.PRECIOUS: Xcode/test
-Xcode/test: test/test.gyp config/osx.gypi styles/styles
+Xcode/test: test/test.gyp config/osx.gypi styles/styles SMCalloutView
deps/run_gyp test/test.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f xcode
.PHONY: lproj lbuild run-xlinux
@@ -108,7 +111,7 @@ xproj: xosx-proj
#### iOS application builds ####################################################
.PRECIOUS: Xcode/ios
-Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles
+Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles SMCalloutView
deps/run_gyp ios/app/mapboxgl-app.gyp $(CONFIG_ios) $(LIBS_ios) --generator-output=./build/ios -f xcode
.PHONY: ios-proj ios run-ios
diff --git a/README.md b/README.md
index 09759d84ef..f48a72b994 100644
--- a/README.md
+++ b/README.md
@@ -55,9 +55,11 @@ If you merely want to install the library for iOS and try it out as an Objective
- `MapboxGL.bundle` is in your target's *Copy Bundle Resources* build phase.
- `libMapboxGL.a` is in your target's *Link Binary With Libraries* build phase.
3. Add the following Cocoa framework dependencies to your target's *Link Binary With Libraries* build phase:
+ - `CoreTelephony.framework`
- `GLKit.framework`
- `ImageIO.framework`
- `MobileCoreServices.framework`
+ - `QuartzCore.framework`
- `SystemConfiguration.framework`
- `libc++.dylib`
- `libsqlite3.dylib`
diff --git a/android/cpp/jni.cpp b/android/cpp/jni.cpp
index 9cde5d385d..ce61a01bf9 100644
--- a/android/cpp/jni.cpp
+++ b/android/cpp/jni.cpp
@@ -160,7 +160,7 @@ jobject std_vector_string_to_jobject(JNIEnv *env, std::vector<std::string> vecto
return nullptr;
}
- for (std::string str : vector) {
+ for (const auto& str : vector) {
env->CallBooleanMethod(jlist, arrayListAddId, std_string_to_jstring(env, str));
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi
index 73f611a8e7..9965db57ac 100644
--- a/gyp/platform-ios.gypi
+++ b/gyp/platform-ios.gypi
@@ -22,18 +22,16 @@
'../include/mbgl/ios/MGLMapView.h',
'../platform/ios/MGLMapView.mm',
'../include/mbgl/ios/MGLAnnotation.h',
+ '../include/mbgl/ios/MGLUserLocation.h',
+ '../platform/ios/MGLUserLocation_Private.h',
+ '../platform/ios/MGLUserLocation.m',
+ '../platform/ios/MGLUserLocationAnnotationView.h',
+ '../platform/ios/MGLUserLocationAnnotationView.m',
'../include/mbgl/ios/MGLMetricsLocationManager.h',
'../platform/ios/MGLMetricsLocationManager.m',
- '../include/mbgl/ios/MGLStyleFunctionValue.h',
- '../platform/ios/MGLStyleFunctionValue.m',
'../include/mbgl/ios/MGLTypes.h',
- '../platform/ios/MGLTypes.m',
- '../include/mbgl/ios/NSArray+MGLAdditions.h',
- '../platform/ios/NSArray+MGLAdditions.m',
- '../include/mbgl/ios/NSDictionary+MGLAdditions.h',
- '../platform/ios/NSDictionary+MGLAdditions.m',
- '../include/mbgl/ios/UIColor+MGLAdditions.h',
- '../platform/ios/UIColor+MGLAdditions.m',
+ '../platform/ios/vendor/SMCalloutView/SMCalloutView.h',
+ '../platform/ios/vendor/SMCalloutView/SMCalloutView.m',
],
'variables': {
@@ -45,15 +43,13 @@
'<@(uv_static_libs)',
],
'ldflags': [
- '-framework CoreGraphics',
'-framework CoreLocation',
'-framework CoreTelephony',
- '-framework ImageIO',
'-framework GLKit',
+ '-framework ImageIO',
'-framework MobileCoreServices',
- '-framework OpenGLES',
+ '-framework QuartzCore',
'-framework SystemConfiguration',
- '-framework UIKit',
],
},
@@ -64,6 +60,7 @@
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ],
'CLANG_ENABLE_OBJC_ARC': 'YES',
+ 'CLANG_ENABLE_MODULES': 'YES',
},
'link_settings': {
diff --git a/gyp/platform-osx.gypi b/gyp/platform-osx.gypi
index 39e18bb839..aecb058595 100644
--- a/gyp/platform-osx.gypi
+++ b/gyp/platform-osx.gypi
@@ -26,7 +26,6 @@
'<@(uv_static_libs)',
],
'ldflags': [
- '-framework Foundation',
'-framework ImageIO',
'-framework CoreServices',
'-framework OpenGL',
@@ -42,6 +41,7 @@
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ],
'CLANG_ENABLE_OBJC_ARC': 'YES',
+ 'CLANG_ENABLE_MODULES': 'YES',
},
'link_settings': {
diff --git a/include/mbgl/ios/MGLMapView.h b/include/mbgl/ios/MGLMapView.h
index 3a6e622e12..bacef9d33d 100644
--- a/include/mbgl/ios/MGLMapView.h
+++ b/include/mbgl/ios/MGLMapView.h
@@ -1,6 +1,10 @@
+#import "MGLTypes.h"
+
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
+@class MGLUserLocation;
+
@protocol MGLMapViewDelegate;
@protocol MGLAnnotation;
@@ -29,6 +33,13 @@
* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken bundledStyleNamed:(NSString *)styleName;
+/** Initialize a map view with a given frame, style URL, and access token.
+* @param frame The frame with which to initialize the map view.
+* @param accessToken A Mapbox API access token.
+* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://<user.style>`).
+* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
+- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL;
+
/** Initialize a map view with a given frame, the default style, and an access token.
* @param frame The frame with which to initialize the map view.
* @param accessToken A Mapbox API access token.
@@ -185,6 +196,10 @@
* @param styleName The map style name to use. */
- (void)useBundledStyleNamed:(NSString *)styleName;
+/** Sets the map style URL to use.
+* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://<user.style>`). */
+- (void)setStyleURL:(NSURL *)styleURL;
+
#pragma mark - Annotating the Map
/** @name Annotating the Map */
@@ -234,6 +249,30 @@
* @param animated If `YES`, the callout view is animated offscreen. */
- (void)deselectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated;
+#pragma mark - Displaying the User's Location
+
+/** A Boolean value indicating whether the map may display the user location.
+
+ This property does not indicate whether the user’s position is actually visible on the map, only whether the map view is allowed to display it. To determine whether the user’s position is visible, use the userLocationVisible property. The default value of this property is `NO`.
+
+ Setting this property to `YES` causes the map view to use the Core Location framework to find the current location. As long as this property is `YES`, the map view continues to track the user’s location and update it periodically.
+
+ On iOS 8 and above, your app must specify a value for `NSLocationWhenInUseUsageDescription` in its `Info.plist` to satisfy the requirements of the underlying Core Location framework when enabling this property.
+ */
+@property (nonatomic, assign) BOOL showsUserLocation;
+
+/// Returns a Boolean value indicating whether the user currently sees the user location annotation.
+@property (nonatomic, assign, readonly, getter=isUserLocationVisible) BOOL userLocationVisible;
+
+/// Returns the annotation object indicating the user’s current location.
+@property (nonatomic, readonly) MGLUserLocation *userLocation;
+
+/** The mode used to track the user location. */
+@property (nonatomic, assign) MGLUserTrackingMode userTrackingMode;
+
+/** Whether the map view should display a heading calibration alert when necessary. The default value is `YES`. */
+@property (nonatomic, assign) BOOL displayHeadingCalibration;
+
#pragma mark - Debugging
/** @name Debugging */
@@ -251,11 +290,15 @@
@end
+#pragma mark - MGLMapViewDelegate
+
/** The MGLMapViewDelegate protocol defines a set of optional methods that you can use to receive map-related update messages. Because many map operations require the MGLMapView class to load data asynchronously, the map view calls these methods to notify your application when specific operations complete. The map view also uses these methods to request annotation marker symbology and to manage interactions with those markers. */
@protocol MGLMapViewDelegate <NSObject>
@optional
+#pragma mark - Managing the Display of Annotations
+
/** @name Managing the Display of Annotations */
/** Returns the style's symbol name to use for the marker for the specified point annotation object.
@@ -264,14 +307,54 @@
* @return The marker symbol to display for the specified annotation or `nil` if you want to display the default symbol. */
- (NSString *)mapView:(MGLMapView *)mapView symbolNameForAnnotation:(id <MGLAnnotation>)annotation;
+/** Returns a Boolean value indicating whether the annotation is able to display extra information in a callout bubble.
+*
+* If the value returned is `YES`, a standard callout bubble is shown when the user taps a selected annotation. The callout uses the title and subtitle text from the associated annotation object. If there is no title text, though, the annotation will not show a callout. The callout also displays any custom callout views returned by the delegate for the left and right callout accessory views.
+*
+* If the value returned is `NO`, the value of the title and subtitle strings are ignored.
+*
+* @param mapView The map view that requested the annotation callout ability.
+* @param annotation The object representing the annotation.
+* @return A Boolean indicating whether the annotation should show a callout. */
+- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation;
+
+/** Return the view to display on the left side of the standard callout bubble.
+*
+* The default value is treated as if `nil`. The left callout view is typically used to display information about the annotation or to link to custom information provided by your application.
+*
+* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds.
+*
+* @param mapView The map view presenting the annotation callout.
+* @param annotation The object representing the annotation with the callout.
+* @return The accessory view to display. */
+- (UIView *)mapView:(MGLMapView *)mapView leftCalloutAccessoryViewForAnnotation:(id <MGLAnnotation>)annotation;
+
+/** Return the view to display on the right side of the standard callout bubble.
+*
+* The default value is treated is if `nil`. The right callout view is typically used to link to more detailed information about the annotation. A common view to specify for this property is `UIButton` object whose type is set to `UIButtonTypeDetailDisclosure`.
+*
+* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds.
+*
+* @param mapView The map view presenting the annotation callout.
+* @param annotation The object representing the annotation with the callout.
+* @return The accessory view to display. */
+- (UIView *)mapView:(MGLMapView *)mapView rightCalloutAccessoryViewForAnnotation:(id <MGLAnnotation>)annotation;
+
+#pragma mark - Responding to Map Position Changes
+
// Responding to Map Position Changes
// TODO
- (void)mapView:(MGLMapView *)mapView regionWillChangeAnimated:(BOOL)animated;
// TODO
+- (void)mapViewRegionIsChanging:(MGLMapView *)mapView;
+
+// TODO
- (void)mapView:(MGLMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
+#pragma mark - Loading the Map Data
+
// Loading the Map Data
// TODO
@@ -289,4 +372,60 @@
// TODO
- (void)mapViewDidFinishRenderingMap:(MGLMapView *)mapView fullyRendered:(BOOL)fullyRendered;
+#pragma mark - Tracking the User Location
+
+/// Tells the delegate that the map view will begin tracking the user’s location.
+- (void)mapViewWillStartLocatingUser:(MGLMapView *)mapView;
+
+/// Tells the delegate that the map view has stopped tracking the user’s location.
+- (void)mapViewDidStopLocatingUser:(MGLMapView *)mapView;
+
+/// Tells the delegate that the map view has updated the user’s location to the given location.
+- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation;
+
+/// Tells the delegate that the map view has failed to locate the user.
+- (void)mapView:(MGLMapView *)mapView didFailToLocateUserWithError:(NSError *)error;
+
+/**
+ Tells the delegate that the map view’s user tracking mode has changed.
+
+ This method is called after the map view asynchronously changes to reflect the new user tracking mode, for example by beginning to zoom or rotate.
+ */
+- (void)mapView:(MGLMapView *)mapView didChangeUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated;
+
+#pragma mark - Managing Annotations
+
+/** @name Managing Annotations */
+
+/* Tells the delegate that the user tapped one of the annotation's accessory buttons.
+*
+* Accessory views contain custom content and are positioned on either side of the annotation title text. If a view you specify is a descendant of the `UIControl` class, the map view calls this method as a convenience whenever the user taps your view. You can use this method to respond to taps and perform any actions associated with that control. For example, if your control displayed additional information about the annotation, you could use this method to present a modal panel with that information.
+*
+* If your custom accessory views are not descendants of the `UIControl` class, the map view does not call this method.
+*
+* @param mapView The map view containing the specified annotation.
+* @param annotation The annotation whose button was tapped.
+* @param control The control that was tapped. */
+- (void)mapView:(MGLMapView *)mapView annotation:(id <MGLAnnotation>)annotation calloutAccessoryControlTapped:(UIControl *)control;
+
+#pragma mark - Selecting Annotations
+
+/** @name Selecting Annotations */
+
+/* Tells the delegate that one of its annotations was selected.
+*
+* You can use this method to track changes in the selection state of annotations.
+*
+* @param mapView The map view containing the annotation.
+* @param annotation The annotation that was selected. */
+- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id <MGLAnnotation>)annotation;
+
+/* Tells the delegate that one of its annotations was deselected.
+*
+* You can use this method to track changes in the selection state of annotations.
+*
+* @param mapView The map view containing the annotation.
+* @param annotation The annotation that was deselected. */
+- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id <MGLAnnotation>)annotation;
+
@end
diff --git a/include/mbgl/ios/MGLMapboxEvents.h b/include/mbgl/ios/MGLMapboxEvents.h
index bb28ec26c5..ea37edbb8e 100644
--- a/include/mbgl/ios/MGLMapboxEvents.h
+++ b/include/mbgl/ios/MGLMapboxEvents.h
@@ -1,26 +1,50 @@
-//
-// MapboxEvents.h
-// MapboxEvents
-//
-// Created by Brad Leege on 3/5/15.
-// Copyright (c) 2015 Mapbox. All rights reserved.
-//
-
#import <Foundation/Foundation.h>
+extern NSString *const MGLEventTypeMapLoad;
+extern NSString *const MGLEventTypeMapTap;
+extern NSString *const MGLEventTypeMapDragEnd;
+extern NSString *const MGLEventTypeLocation;
+
+extern NSString *const MGLEventKeyLatitude;
+extern NSString *const MGLEventKeyLongitude;
+extern NSString *const MGLEventKeyZoomLevel;
+extern NSString *const MGLEventKeyPushEnabled;
+extern NSString *const MGLEventKeyEmailEnabled;
+extern NSString *const MGLEventKeyGestureID;
+
+extern NSString *const MGLEventGestureSingleTap;
+extern NSString *const MGLEventGestureDoubleTap;
+extern NSString *const MGLEventGestureTwoFingerSingleTap;
+extern NSString *const MGLEventGestureQuickZoom;
+extern NSString *const MGLEventGesturePanStart;
+extern NSString *const MGLEventGesturePinchStart;
+extern NSString *const MGLEventGestureRotateStart;
+
@interface MGLMapboxEvents : NSObject
-@property (atomic) NSInteger flushAt;
-@property (atomic) NSInteger flushAfter;
-@property (atomic) NSString *api;
-@property (atomic) NSString *token;
-@property (atomic) NSString *appName;
-@property (atomic) NSString *appVersion;
+// You must call these methods from the main thread.
+//
++ (void) setToken:(NSString *)token;
++ (void) setAppName:(NSString *)appName;
++ (void) setAppVersion:(NSString *)appVersion;
-+ (id)sharedManager;
+// You can call this method from any thread. Significant work will
+// be dispatched to a low-priority background queue and all
+// resulting calls are guaranteed threadsafe.
+//
+// Events or attributes passed could be accessed on non-main threads,
+// so you must not reference UI elements from within any arguments.
+// Copy any values needed first or create dedicated methods in this
+// class for threadsafe access to UIKit classes.
+//
++ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary;
-- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary;
+// You can call these methods from any thread.
+//
++ (BOOL) checkPushEnabled;
-- (void) flush;
+// You can call this method from any thread.
+//
++ (void) flush;
-@end \ No newline at end of file
+@end
diff --git a/include/mbgl/ios/MGLMetricsLocationManager.h b/include/mbgl/ios/MGLMetricsLocationManager.h
index ce04ae9ef6..7281d05010 100644
--- a/include/mbgl/ios/MGLMetricsLocationManager.h
+++ b/include/mbgl/ios/MGLMetricsLocationManager.h
@@ -1,22 +1,9 @@
-//
-// MBLocationManager.h
-// Hermes
-//
-// Created by Brad Leege on 3/8/15.
-// Copyright (c) 2015 Mapbox. All rights reserved.
-//
-
#import <Foundation/Foundation.h>
-#import "CoreLocation/CoreLocation.h"
-@interface MGLMetricsLocationManager : NSObject <CLLocationManagerDelegate>
+@interface MGLMetricsLocationManager : NSObject
-+ (id)sharedManager;
-
-- (BOOL) isAuthorizedStatusDetermined;
-- (void) requestAlwaysAuthorization;
-
-- (void) startUpdatingLocation;
-- (void) stopUpdatingLocation;
+// This method can be called from any thread.
+//
++ (instancetype)sharedManager;
@end
diff --git a/include/mbgl/ios/MGLStyleFunctionValue.h b/include/mbgl/ios/MGLStyleFunctionValue.h
deleted file mode 100644
index 27a867548b..0000000000
--- a/include/mbgl/ios/MGLStyleFunctionValue.h
+++ /dev/null
@@ -1,23 +0,0 @@
-#import <UIKit/UIKit.h>
-
-@interface MGLStyleFunctionValue : NSObject
-
-+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase
- initialValue:(CGFloat)val
- slope:(CGFloat)slope
- minimumValue:(CGFloat)min
- maximumValue:(CGFloat)max;
-
-+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase
- initialValue:(CGFloat)val
- slope:(CGFloat)slope
- minimumValue:(CGFloat)min
- maximumValue:(CGFloat)max;
-
-+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom;
-
-+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom;
-
-+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ... NS_REQUIRES_NIL_TERMINATION;
-
-@end
diff --git a/include/mbgl/ios/MGLTypes.h b/include/mbgl/ios/MGLTypes.h
index 7a17445770..4c2e58b24b 100644
--- a/include/mbgl/ios/MGLTypes.h
+++ b/include/mbgl/ios/MGLTypes.h
@@ -1,17 +1,9 @@
#import <Foundation/Foundation.h>
-// style property value types
-//
-extern NSString *const MGLStyleValueTypeBoolean;
-extern NSString *const MGLStyleValueTypeNumber;
-extern NSString *const MGLStyleValueTypeNumberPair;
-extern NSString *const MGLStyleValueTypeColor;
-extern NSString *const MGLStyleValueTypeString;
-
-// style property function types
-//
-extern NSString *const MGLStyleValueTypeFunctionMinimumZoom;
-extern NSString *const MGLStyleValueTypeFunctionMaximumZoom;
-extern NSString *const MGLStyleValueTypeFunctionLinear;
-extern NSString *const MGLStyleValueTypeFunctionExponential;
-extern NSString *const MGLStyleValueTypeFunctionStops;
+/// The degree to which the map view tracks the user’s location.
+typedef NS_ENUM(NSUInteger, MGLUserTrackingMode)
+{
+ MGLUserTrackingModeNone = 0, ///< does not track the user’s location or heading
+ MGLUserTrackingModeFollow = 1, ///< tracks the user’s location
+ MGLUserTrackingModeFollowWithHeading = 2, ///< tracks the user’s location and heading
+};
diff --git a/include/mbgl/ios/MGLUserLocation.h b/include/mbgl/ios/MGLUserLocation.h
new file mode 100644
index 0000000000..fee3368889
--- /dev/null
+++ b/include/mbgl/ios/MGLUserLocation.h
@@ -0,0 +1,26 @@
+#import "MGLAnnotation.h"
+
+@interface MGLUserLocation : NSObject <MGLAnnotation>
+
+@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
+
+/** @name Determining the User’s Position */
+
+/** The current location of the device. (read-only)
+*
+* This property contains `nil` if the map view is not currently showing the user location or if the user’s location has not yet been determined. */
+@property (nonatomic, readonly) CLLocation *location;
+
+/** A Boolean value indicating whether the user’s location is currently being updated. (read-only) */
+@property (nonatomic, readonly, getter=isUpdating) BOOL updating; // FIXME
+
+/** The heading of the user location. (read-only)
+*
+* This property is `nil` if the user location tracking mode is not `RMUserTrackingModeFollowWithHeading`. */
+@property (nonatomic, readonly) CLHeading *heading;
+
+@property (nonatomic, copy) NSString *title;
+
+@property (nonatomic, copy) NSString *subtitle;
+
+@end
diff --git a/include/mbgl/ios/MapboxGL.h b/include/mbgl/ios/MapboxGL.h
index 237d493f31..c32915bc76 100644
--- a/include/mbgl/ios/MapboxGL.h
+++ b/include/mbgl/ios/MapboxGL.h
@@ -1,7 +1,4 @@
#import "MGLAnnotation.h"
#import "MGLMapView.h"
-#import "MGLStyleFunctionValue.h"
#import "MGLTypes.h"
-#import "NSArray+MGLAdditions.h"
-#import "NSDictionary+MGLAdditions.h"
-#import "UIColor+MGLAdditions.h"
+#import "MGLUserLocation.h"
diff --git a/include/mbgl/ios/NSArray+MGLAdditions.h b/include/mbgl/ios/NSArray+MGLAdditions.h
deleted file mode 100644
index 4b87614330..0000000000
--- a/include/mbgl/ios/NSArray+MGLAdditions.h
+++ /dev/null
@@ -1,7 +0,0 @@
-#import <Foundation/Foundation.h>
-
-@interface NSArray (MGLAdditions)
-
-- (NSMutableArray *)deepMutableCopy;
-
-@end
diff --git a/include/mbgl/ios/NSDictionary+MGLAdditions.h b/include/mbgl/ios/NSDictionary+MGLAdditions.h
deleted file mode 100644
index 04c3396d41..0000000000
--- a/include/mbgl/ios/NSDictionary+MGLAdditions.h
+++ /dev/null
@@ -1,7 +0,0 @@
-#import <Foundation/Foundation.h>
-
-@interface NSDictionary (MGLAdditions)
-
-- (NSMutableDictionary *)deepMutableCopy;
-
-@end
diff --git a/include/mbgl/ios/UIColor+MGLAdditions.h b/include/mbgl/ios/UIColor+MGLAdditions.h
deleted file mode 100644
index 3758c04eef..0000000000
--- a/include/mbgl/ios/UIColor+MGLAdditions.h
+++ /dev/null
@@ -1,11 +0,0 @@
-#import <UIKit/UIKit.h>
-
-@interface UIColor (MGLAdditions)
-
-+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString;
-- (NSString *)rgbaStringFromColor;
-
-+ (UIColor *)colorWithHexString:(NSString *)hexString;
-- (NSString *)hexStringFromColor;
-
-@end
diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp
index 0fb2065cca..cd280d0247 100644
--- a/include/mbgl/map/map.hpp
+++ b/include/mbgl/map/map.hpp
@@ -15,6 +15,7 @@
#include <iosfwd>
#include <set>
#include <vector>
+#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
@@ -28,7 +29,6 @@ class LayerDescription;
class Sprite;
class Style;
class StyleLayer;
-class StyleLayerGroup;
class StyleSource;
class TexturePool;
class FileSource;
@@ -153,13 +153,14 @@ public:
// Annotations
void setDefaultPointAnnotationSymbol(const std::string&);
+ double getTopOffsetPixelsForAnnotationSymbol(const std::string&);
uint32_t addPointAnnotation(const LatLng&, const std::string& symbol);
std::vector<uint32_t> addPointAnnotations(const std::vector<LatLng>&,
const std::vector<std::string>& symbols);
void removeAnnotation(uint32_t);
void removeAnnotations(const std::vector<uint32_t>&);
- std::vector<uint32_t> getAnnotationsInBounds(const LatLngBounds&) const;
- LatLngBounds getBoundsForAnnotations(const std::vector<uint32_t>&) const;
+ std::vector<uint32_t> getAnnotationsInBounds(const LatLngBounds&);
+ LatLngBounds getBoundsForAnnotations(const std::vector<uint32_t>&);
// Debug
void setDebug(bool value);
@@ -186,7 +187,6 @@ private:
void updateTiles();
void updateSources();
- void updateSources(const util::ptr<StyleLayerGroup> &group);
// Triggered by triggerUpdate();
void update();
@@ -199,6 +199,12 @@ private:
// the stylesheet.
void prepare();
+ // Runs the function in the map thread.
+ void invokeTask(std::function<void()>&&);
+ template <typename Fn> auto invokeSyncTask(const Fn& fn) -> decltype(fn());
+
+ void processTasks();
+
void updateAnnotationTiles(const std::vector<Tile::ID>&);
enum class Mode : uint8_t {
@@ -218,6 +224,7 @@ private:
std::thread thread;
std::unique_ptr<uv::async> asyncTerminate;
std::unique_ptr<uv::async> asyncUpdate;
+ std::unique_ptr<uv::async> asyncInvoke;
std::unique_ptr<uv::async> asyncRender;
bool terminating = false;
@@ -256,6 +263,9 @@ private:
std::set<util::ptr<StyleSource>> activeSources;
std::atomic<UpdateType> updated;
+
+ std::mutex mutexTask;
+ std::queue<std::function<void()>> tasks;
};
}
diff --git a/include/mbgl/map/view.hpp b/include/mbgl/map/view.hpp
index 1ee9d300c5..bcfeb62cfc 100644
--- a/include/mbgl/map/view.hpp
+++ b/include/mbgl/map/view.hpp
@@ -10,14 +10,15 @@ class Map;
enum MapChange : uint8_t {
MapChangeRegionWillChange = 0,
MapChangeRegionWillChangeAnimated = 1,
- MapChangeRegionDidChange = 2,
- MapChangeRegionDidChangeAnimated = 3,
- MapChangeWillStartLoadingMap = 4,
- MapChangeDidFinishLoadingMap = 5,
- MapChangeDidFailLoadingMap = 6,
- MapChangeWillStartRenderingMap = 7,
- MapChangeDidFinishRenderingMap = 8,
- MapChangeDidFinishRenderingMapFullyRendered = 9
+ MapChangeRegionIsChanging = 2,
+ MapChangeRegionDidChange = 3,
+ MapChangeRegionDidChangeAnimated = 4,
+ MapChangeWillStartLoadingMap = 5,
+ MapChangeDidFinishLoadingMap = 6,
+ MapChangeDidFailLoadingMap = 7,
+ MapChangeWillStartRenderingMap = 8,
+ MapChangeDidFinishRenderingMap = 9,
+ MapChangeDidFinishRenderingMapFullyRendered = 10
};
class View {
diff --git a/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp b/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp
index 3533e3da35..6c91fd3029 100644
--- a/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp
+++ b/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp
@@ -1,6 +1,8 @@
#ifndef MBGL_COMMON_SETTINGS_NSUSERDEFAULTS
#define MBGL_COMMON_SETTINGS_NSUSERDEFAULTS
+#import <mbgl/ios/MGLTypes.h>
+
namespace mbgl {
class Settings_NSUserDefaults {
@@ -16,6 +18,9 @@ public:
double zoom = 0;
double bearing = 0;
+ MGLUserTrackingMode userTrackingMode = MGLUserTrackingModeNone;
+ bool showsUserLocation = false;
+
bool debug = false;
};
diff --git a/ios/MapboxGL.podspec b/ios/MapboxGL.podspec
index 6179667444..b474f7c9e7 100644
--- a/ios/MapboxGL.podspec
+++ b/ios/MapboxGL.podspec
@@ -22,7 +22,7 @@ Pod::Spec.new do |m|
m.resource_bundle = { 'MapboxGL' => 'MapboxGL.bundle/*' }
- m.frameworks = 'CoreLocation', 'GLKit', 'ImageIO', 'MobileCoreServices', 'SystemConfiguration'
+ m.frameworks = 'CoreLocation', 'CoreTelephony', 'GLKit', 'ImageIO', 'MobileCoreServices', 'QuartzCore', 'SystemConfiguration'
m.libraries = 'c++', 'sqlite3', 'z'
diff --git a/ios/app/MBXViewController.mm b/ios/app/MBXViewController.mm
index 6d1175e4f1..c9973bcb7d 100644
--- a/ios/app/MBXViewController.mm
+++ b/ios/app/MBXViewController.mm
@@ -21,10 +21,9 @@ static NSArray *const kStyleNames = @[
static NSString *const kStyleVersion = @"v7";
-@interface MBXViewController () <UIActionSheetDelegate, CLLocationManagerDelegate>
+@interface MBXViewController () <UIActionSheetDelegate, MGLMapViewDelegate>
@property (nonatomic) MGLMapView *mapView;
-@property (nonatomic) CLLocationManager *locationManager;
@end
@@ -66,9 +65,10 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
self.mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds accessToken:accessToken];
self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
- [self.view addSubview:self.mapView];
-
self.mapView.viewControllerForLayoutGuides = self;
+ self.mapView.showsUserLocation = YES;
+ self.mapView.delegate = self;
+ [self.view addSubview:self.mapView];
self.view.tintColor = kTintColor;
self.navigationController.navigationBar.tintColor = kTintColor;
@@ -107,6 +107,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
settings->zoom = self.mapView.zoomLevel;
settings->bearing = self.mapView.direction;
settings->debug = self.mapView.isDebugActive;
+ settings->userTrackingMode = self.mapView.userTrackingMode;
+ settings->showsUserLocation = self.mapView.showsUserLocation;
settings->save();
}
}
@@ -117,6 +119,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
settings->load();
[self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(settings->latitude, settings->longitude) zoomLevel:settings->zoom animated:NO];
self.mapView.direction = settings->bearing;
+ self.mapView.userTrackingMode = settings->userTrackingMode;
+ self.mapView.showsUserLocation = settings->showsUserLocation;
[self.mapView setDebugActive:settings->debug];
}
}
@@ -252,40 +256,17 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
- (void)locateUser
{
- if ( ! self.locationManager)
+ if (self.mapView.userTrackingMode == MGLUserTrackingModeNone)
{
- self.locationManager = [CLLocationManager new];
- self.locationManager.delegate = self;
+ self.mapView.userTrackingMode = MGLUserTrackingModeFollow;
}
-
- if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
+ else if (self.mapView.userTrackingMode == MGLUserTrackingModeFollow)
{
- [[[UIAlertView alloc] initWithTitle:@"Authorization Denied"
- message:@"Please enable location services for this app in Privacy settings."
- delegate:nil
- cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
+ self.mapView.userTrackingMode = MGLUserTrackingModeFollowWithHeading;
}
else
{
-#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
- if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)])
- {
- if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
- {
- [self.locationManager startUpdatingLocation];
- }
- else
- {
- [_locationManager requestWhenInUseAuthorization];
- }
- }
- else
- {
- [self.locationManager startUpdatingLocation];
- }
-#else
- [self.locationManager startUpdatingLocation];
-#endif
+ self.mapView.userTrackingMode = MGLUserTrackingModeNone;
}
}
@@ -303,39 +284,14 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
}
}
-#pragma mark - CLLocationManagerDelegate
-
-- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
-{
- switch (status)
- {
- case kCLAuthorizationStatusAuthorizedAlways:
-#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
- case kCLAuthorizationStatusAuthorizedWhenInUse:
-#endif
- {
- [manager startUpdatingLocation];
- break;
- }
- default:
- {
- }
- }
-}
-
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
-- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
-{
- CLLocation *latestLocation = locations.lastObject;
-
- if ([latestLocation distanceFromLocation:[[CLLocation alloc] initWithLatitude:self.mapView.centerCoordinate.latitude longitude:self.mapView.centerCoordinate.longitude]] > 100)
- {
- [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latestLocation.coordinate.latitude, latestLocation.coordinate.longitude) zoomLevel:17 animated:YES];
- }
+#pragma mark - MGLMapViewDelegate
- [self.locationManager stopUpdatingLocation];
+- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation
+{
+ return YES;
}
#pragma clang diagnostic pop
diff --git a/ios/app/mapboxgl-app.gyp b/ios/app/mapboxgl-app.gyp
index 793ba6bce4..0e093a1d8d 100644
--- a/ios/app/mapboxgl-app.gyp
+++ b/ios/app/mapboxgl-app.gyp
@@ -10,7 +10,8 @@
'mac_bundle': 1,
'mac_bundle_resources': [
'<!@(find ./img -type f)',
- './features.geojson'
+ './features.geojson',
+ './Settings.bundle/'
],
'dependencies': [
@@ -41,6 +42,7 @@
'TARGETED_DEVICE_FAMILY': '1,2',
'COMBINE_HIDPI_IMAGES': 'NO', # don't merge @2x.png images into .tiff files
'CLANG_ENABLE_OBJC_ARC': 'YES',
+ 'CLANG_ENABLE_MODULES': 'YES',
},
'configurations': {
diff --git a/platform/darwin/settings_nsuserdefaults.mm b/platform/darwin/settings_nsuserdefaults.mm
index b9b0e134bf..168cba172d 100644
--- a/platform/darwin/settings_nsuserdefaults.mm
+++ b/platform/darwin/settings_nsuserdefaults.mm
@@ -6,11 +6,15 @@ using namespace mbgl;
Settings_NSUserDefaults::Settings_NSUserDefaults()
{
- [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"longitude" : @(longitude),
- @"latitude" : @(latitude),
- @"zoom" : @(zoom),
- @"bearing" : @(bearing),
- @"debug" : @(debug) }];
+ [[NSUserDefaults standardUserDefaults] registerDefaults:@{
+ @"longitude" : @(longitude),
+ @"latitude" : @(latitude),
+ @"zoom" : @(zoom),
+ @"bearing" : @(bearing),
+ @"userTrackingMode" : @(userTrackingMode),
+ @"showsUserLocation" : @(showsUserLocation),
+ @"debug" : @(debug),
+ }];
load();
}
@@ -23,15 +27,27 @@ void Settings_NSUserDefaults::load()
zoom = [settings[@"zoom"] doubleValue];
bearing = [settings[@"bearing"] doubleValue];
debug = [settings[@"debug"] boolValue];
+
+ unsigned uncheckedTrackingMode = [settings[@"trackingMode"] unsignedIntValue];
+ if (uncheckedTrackingMode > MGLUserTrackingModeNone &&
+ uncheckedTrackingMode <= MGLUserTrackingModeFollowWithHeading)
+ {
+ userTrackingMode = (MGLUserTrackingMode)uncheckedTrackingMode;
+ }
+ showsUserLocation = [settings[@"showsUserLocation"] boolValue];
}
void Settings_NSUserDefaults::save()
{
- [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{ @"longitude" : @(longitude),
- @"latitude" : @(latitude),
- @"zoom" : @(zoom),
- @"bearing" : @(bearing),
- @"debug" : @(debug) }];
+ [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{
+ @"longitude" : @(longitude),
+ @"latitude" : @(latitude),
+ @"zoom" : @(zoom),
+ @"bearing" : @(bearing),
+ @"userTrackingMode" : @(userTrackingMode),
+ @"showsUserLocation" : @(showsUserLocation),
+ @"debug" : @(debug),
+ }];
[[NSUserDefaults standardUserDefaults] synchronize];
}
diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm
index ce5997e0a9..4a55ada173 100644
--- a/platform/ios/MGLMapView.mm
+++ b/platform/ios/MGLMapView.mm
@@ -15,16 +15,15 @@
#include <mbgl/util/geo.hpp>
#import "MGLTypes.h"
-#import "MGLStyleFunctionValue.h"
#import "MGLAnnotation.h"
+#import "MGLUserLocationAnnotationView.h"
+#import "MGLUserLocation_Private.h"
-#import "UIColor+MGLAdditions.h"
-#import "NSArray+MGLAdditions.h"
-#import "NSDictionary+MGLAdditions.h"
+#import "SMCalloutView.h"
-#import <algorithm>
#import "MGLMapboxEvents.h"
-#import "MGLMetricsLocationManager.h"
+
+#import <algorithm>
// Returns the path to the default cache database on this system.
const std::string &defaultCacheDatabase() {
@@ -47,24 +46,14 @@ NSString *const MGLDefaultStyleName = @"Emerald";
NSString *const MGLStyleVersion = @"v7";
NSString *const MGLDefaultStyleMarkerSymbolName = @"default_marker";
-extern NSString *const MGLStyleKeyGeneric;
-extern NSString *const MGLStyleKeyFill;
-extern NSString *const MGLStyleKeyLine;
-extern NSString *const MGLStyleKeyIcon;
-extern NSString *const MGLStyleKeyText;
-extern NSString *const MGLStyleKeyRaster;
-extern NSString *const MGLStyleKeyComposite;
-extern NSString *const MGLStyleKeyBackground;
-
-extern NSString *const MGLStyleValueFunctionAllowed;
-
NSTimeInterval const MGLAnimationDuration = 0.3;
+const CGSize MGLAnnotationUpdateViewportOutset = {150, 150};
NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey";
#pragma mark - Private -
-@interface MGLMapView () <UIGestureRecognizerDelegate, GLKViewDelegate>
+@interface MGLMapView () <UIGestureRecognizerDelegate, GLKViewDelegate, CLLocationManagerDelegate>
@property (nonatomic) EAGLContext *context;
@property (nonatomic) GLKView *glView;
@@ -77,10 +66,12 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey";
@property (nonatomic) UIRotationGestureRecognizer *rotate;
@property (nonatomic) UILongPressGestureRecognizer *quickZoom;
@property (nonatomic) NSMutableArray *bundledStyleNames;
-@property (nonatomic) NSMapTable *annotationsStore;
+@property (nonatomic) NSMapTable *annotationIDsByAnnotation;
@property (nonatomic) std::vector<uint32_t> annotationsNearbyLastTap;
@property (nonatomic, weak) id <MGLAnnotation> selectedAnnotation;
-@property (nonatomic, readonly) NSDictionary *allowedStyleTypes;
+@property (nonatomic) SMCalloutView *selectedAnnotationCalloutView;
+@property (nonatomic) MGLUserLocationAnnotationView *userLocationAnnotationView;
+@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) CGPoint centerPoint;
@property (nonatomic) CGFloat scale;
@property (nonatomic) CGFloat angle;
@@ -90,26 +81,8 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey";
@end
-@interface MGLStyleFunctionValue (MGLMapViewFriend)
-
-@property (nonatomic) NSString *functionType;
-@property (nonatomic) NSDictionary *stops;
-@property (nonatomic) CGFloat zBase;
-@property (nonatomic) CGFloat val;
-@property (nonatomic) CGFloat slope;
-@property (nonatomic) CGFloat min;
-@property (nonatomic) CGFloat max;
-@property (nonatomic) CGFloat minimumZoom;
-@property (nonatomic) CGFloat maximumZoom;
-
-- (id)rawStyle;
-
-@end
-
@implementation MGLMapView
-@synthesize bundledStyleNames=_bundledStyleNames;
-
#pragma mark - Setup & Teardown -
@dynamic debugActive;
@@ -159,6 +132,19 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
return self;
}
+- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL
+{
+ self = [super initWithFrame:frame];
+
+ if (self && [self commonInit])
+ {
+ if (accessToken) [self setAccessToken:accessToken];
+ if (styleURL) [self setStyleURL:styleURL];
+ }
+
+ return self;
+}
+
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken
{
return [self initWithFrame:frame accessToken:accessToken styleJSON:nil];
@@ -180,8 +166,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
{
if (accessToken)
{
- mbglMap->setAccessToken((std::string)[accessToken cStringUsingEncoding:[NSString defaultCStringEncoding]]);
- [[MGLMapboxEvents sharedManager] setToken:accessToken];
+ mbglMap->setAccessToken((std::string)[accessToken UTF8String]);
+ [MGLMapboxEvents setToken:accessToken];
}
}
@@ -195,13 +181,22 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
}
else
{
- mbglMap->setStyleJSON((std::string)[styleJSON cStringUsingEncoding:[NSString defaultCStringEncoding]]);
+ mbglMap->setStyleJSON((std::string)[styleJSON UTF8String]);
}
}
-- (void)setStyleURL:(NSString *)filePathURL
+- (void)setStyleURL:(NSURL *)styleURL
{
- mbglMap->setStyleURL(std::string("asset://") + [filePathURL UTF8String]);
+ std::string styleURLString([[styleURL absoluteString] UTF8String]);
+
+ if ( ! [styleURL scheme])
+ {
+ mbglMap->setStyleURL(std::string("asset://") + styleURLString);
+ }
+ else
+ {
+ mbglMap->setStyleURL(styleURLString);
+ }
}
- (BOOL)commonInit
@@ -221,16 +216,11 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
//
self.accessibilityLabel = @"Map";
- // setup Metrics
- MGLMapboxEvents *events = [MGLMapboxEvents sharedManager];
+ // metrics: initial setup
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
- if (appName != nil) {
- events.appName = appName;
- }
- if (appVersion != nil) {
- events.appVersion = appVersion;
- }
+ if (appName != nil) [MGLMapboxEvents setAppName:appName];
+ if (appVersion != nil) [MGLMapboxEvents setAppVersion:appVersion];
// create GL view
//
@@ -244,7 +234,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
}
_glView.delegate = self;
[_glView bindDrawable];
- [self addSubview:_glView];
+ [self insertSubview:_glView atIndex:0];
_glView.contentMode = UIViewContentModeCenter;
[self setBackgroundColor:[UIColor clearColor]];
@@ -291,8 +281,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
// setup annotations
//
- _annotationsStore = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory];
- std::string defaultSymbolName([MGLDefaultStyleMarkerSymbolName cStringUsingEncoding:[NSString defaultCStringEncoding]]);
+ _annotationIDsByAnnotation = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory];
+ std::string defaultSymbolName([MGLDefaultStyleMarkerSymbolName UTF8String]);
mbglMap->setDefaultPointAnnotationSymbol(defaultSymbolName);
// setup logo bug
@@ -371,9 +361,6 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
- // Setup MBLocationManager for metrics
- [MGLMetricsLocationManager sharedManager];
-
// set initial position
//
mbglMap->setLatLngZoom(mbgl::LatLng(0, 0), mbglMap->getMinZoom());
@@ -386,28 +373,17 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
// start the main loop
mbglMap->start();
-
- // Fire map.load on a background thread
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
- NSMutableDictionary *evt = [[NSMutableDictionary alloc] init];
- [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getLatLng().latitude] forKey:@"lat"];
- [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getLatLng().longitude] forKey:@"lng"];
- [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getZoom()] forKey:@"zoom"];
- [[MGLMapboxEvents sharedManager] pushEvent:@"map.load" withAttributes:evt];
-
- [evt setValue:[[NSNumber alloc] initWithBool:[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]] forKey:@"enabled.push"];
-
- NSString *email = @"Unknown";
- Class MFMailComposeViewController = NSClassFromString(@"MFMailComposeViewController");
- if (MFMailComposeViewController) {
- SEL canSendMail = NSSelectorFromString(@"canSendMail");
- BOOL sendMail = ((BOOL (*)(id, SEL))[MFMailComposeViewController methodForSelector:canSendMail])(MFMailComposeViewController, canSendMail);
- email = [NSString stringWithFormat:@"%i", sendMail];
- }
- [evt setValue:email forKey:@"enabled.email"];
- });
-
+ // metrics: map load event
+ const mbgl::LatLng latLng = mbglMap->getLatLng();
+ const double zoom = mbglMap->getZoom();
+
+ [MGLMapboxEvents pushEvent:MGLEventTypeMapLoad withAttributes:@{
+ MGLEventKeyLatitude: @(latLng.latitude),
+ MGLEventKeyLongitude: @(latLng.longitude),
+ MGLEventKeyZoomLevel: @(zoom),
+ MGLEventKeyPushEnabled: @([MGLMapboxEvents checkPushEnabled])
+ }];
+
return YES;
}
@@ -449,6 +425,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
}
}
+- (void)setDelegate:(id<MGLMapViewDelegate>)delegate
+{
+ if (_delegate == delegate) return;
+
+ _delegate = delegate;
+}
+
#pragma mark - Layout -
- (void)setFrame:(CGRect)frame
@@ -585,8 +568,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)appDidBackground:(NSNotification *)notification
{
- // Flush Any Events Still In Queue
- [[MGLMapboxEvents sharedManager] flush];
+ [MGLMapboxEvents flush];
mbglMap->stop();
@@ -602,13 +584,14 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)tintColorDidChange
{
- for (UIView *subview in self.subviews)
- {
- if ([subview respondsToSelector:@selector(setTintColor:)])
- {
- subview.tintColor = self.tintColor;
- }
- }
+ for (UIView *subview in self.subviews) [self updateTintColorForView:subview];
+}
+
+- (void)updateTintColorForView:(UIView *)view
+{
+ if ([view respondsToSelector:@selector(setTintColor:)]) view.tintColor = self.tintColor;
+
+ for (UIView *subview in view.subviews) [self updateTintColorForView:subview];
}
#pragma mark - Gestures -
@@ -616,21 +599,25 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)handleCompassTapGesture:(id)sender
{
[self resetNorthAnimated:YES];
+
+ if (self.userTrackingMode == MGLUserTrackingModeFollowWithHeading) self.userTrackingMode = MGLUserTrackingModeFollow;
}
#pragma clang diagnostic pop
- (void)handlePanGesture:(UIPanGestureRecognizer *)pan
{
- [self trackGestureEvent:@"Pan" forRecognizer:pan];
-
if ( ! self.isScrollEnabled) return;
mbglMap->cancelTransitions();
if (pan.state == UIGestureRecognizerStateBegan)
{
+ [self trackGestureEvent:MGLEventGesturePanStart forRecognizer:pan];
+
self.centerPoint = CGPointMake(0, 0);
+
+ self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (pan.state == UIGestureRecognizerStateChanged)
{
@@ -640,6 +627,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
mbglMap->moveBy(delta.x, delta.y);
self.centerPoint = CGPointMake(self.centerPoint.x + delta.x, self.centerPoint.y + delta.y);
+
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)];
}
else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled)
{
@@ -675,23 +664,26 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
[weakSelf notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)];
}];
}
-
- // Send Map Drag End Event
- CGPoint ptInView = CGPointMake([pan locationInView:pan.view].x, [pan locationInView:pan.view].y);
- CLLocationCoordinate2D coord = [self convertPoint:ptInView toCoordinateFromView:pan.view];
- NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
- [dict setValue:[[NSNumber alloc] initWithDouble:coord.latitude] forKey:@"lat"];
- [dict setValue:[[NSNumber alloc] initWithDouble:coord.longitude] forKey:@"lng"];
- [dict setValue:[[NSNumber alloc] initWithDouble:[self zoomLevel]] forKey:@"zoom"];
-
- [[MGLMapboxEvents sharedManager] pushEvent:@"map.dragend" withAttributes:dict];
+ else
+ {
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)];
+ }
+
+ // metrics: pan end
+ CGPoint pointInView = CGPointMake([pan locationInView:pan.view].x, [pan locationInView:pan.view].y);
+ CLLocationCoordinate2D panCoordinate = [self convertPoint:pointInView toCoordinateFromView:pan.view];
+ double zoom = [self zoomLevel];
+
+ [MGLMapboxEvents pushEvent:MGLEventTypeMapDragEnd withAttributes:@{
+ MGLEventKeyLatitude: @(panCoordinate.latitude),
+ MGLEventKeyLongitude: @(panCoordinate.longitude),
+ MGLEventKeyZoomLevel: @(zoom)
+ }];
}
}
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)pinch
{
- [self trackGestureEvent:@"Pinch" forRecognizer:pinch];
-
if ( ! self.isZoomEnabled) return;
if (mbglMap->getZoom() <= mbglMap->getMinZoom() && pinch.scale < 1) return;
@@ -700,9 +692,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
if (pinch.state == UIGestureRecognizerStateBegan)
{
+ [self trackGestureEvent:MGLEventGesturePinchStart forRecognizer:pinch];
+
mbglMap->startScaling();
self.scale = mbglMap->getScale();
+
+ self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (pinch.state == UIGestureRecognizerStateChanged)
{
@@ -720,23 +716,25 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
[self unrotateIfNeededAnimated:YES];
- [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)];
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)];
}
}
- (void)handleRotateGesture:(UIRotationGestureRecognizer *)rotate
{
- [self trackGestureEvent:@"Rotation" forRecognizer:rotate];
-
if ( ! self.isRotateEnabled) return;
mbglMap->cancelTransitions();
if (rotate.state == UIGestureRecognizerStateBegan)
{
+ [self trackGestureEvent:MGLEventGestureRotateStart forRecognizer:rotate];
+
mbglMap->startRotating();
self.angle = [MGLMapView degreesToRadians:mbglMap->getBearing()] * -1;
+
+ self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (rotate.state == UIGestureRecognizerStateChanged)
{
@@ -760,135 +758,169 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
[self unrotateIfNeededAnimated:YES];
- [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)];
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)];
}
}
- (void)handleSingleTapGesture:(UITapGestureRecognizer *)singleTap
{
- [self trackGestureEvent:@"SingleTap" forRecognizer:singleTap];
-
- CGPoint tapPoint = [singleTap locationInView:self];
-
- // tolerances based on touch size & typical marker aspect ratio
- CGFloat toleranceWidth = 50;
- CGFloat toleranceHeight = 75;
+ if (singleTap.state == UIGestureRecognizerStateEnded)
+ {
+ [self trackGestureEvent:MGLEventGestureSingleTap forRecognizer:singleTap];
+
+ CGPoint tapPoint = [singleTap locationInView:self];
+
+ if (self.userLocationVisible && ! [self.selectedAnnotation isEqual:self.userLocation])
+ {
+ CGRect userLocationRect = CGRectMake(tapPoint.x - 15, tapPoint.y - 15, 30, 30);
+
+ if (CGRectContainsPoint(userLocationRect, [self convertCoordinate:self.userLocation.coordinate toPointToView:self]))
+ {
+ [self selectAnnotation:self.userLocation animated:YES];
+ return;
+ }
+ }
- // setup a recognition area weighted 2/3 of the way above the point to account for average marker imagery
- CGRect tapRect = CGRectMake(tapPoint.x - toleranceWidth / 2, tapPoint.y - 2 * toleranceHeight / 3, toleranceWidth, toleranceHeight);
- CGPoint tapRectLowerLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y + tapRect.size.height);
- CGPoint tapRectUpperLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y);
- CGPoint tapRectUpperRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y);
- CGPoint tapRectLowerRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y + tapRect.size.height);
+ // tolerances based on touch size & typical marker aspect ratio
+ CGFloat toleranceWidth = 40;
+ CGFloat toleranceHeight = 60;
- // figure out what that means in coordinate space
- CLLocationCoordinate2D coordinate;
- mbgl::LatLngBounds tapBounds;
+ // setup a recognition area weighted 2/3 of the way above the point to account for average marker imagery
+ CGRect tapRect = CGRectMake(tapPoint.x - toleranceWidth / 2, tapPoint.y - 2 * toleranceHeight / 3, toleranceWidth, toleranceHeight);
+ CGPoint tapRectLowerLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y + tapRect.size.height);
+ CGPoint tapRectUpperLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y);
+ CGPoint tapRectUpperRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y);
+ CGPoint tapRectLowerRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y + tapRect.size.height);
- coordinate = [self convertPoint:tapRectLowerLeft toCoordinateFromView:self];
- tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude));
+ // figure out what that means in coordinate space
+ CLLocationCoordinate2D coordinate;
+ mbgl::LatLngBounds tapBounds;
- coordinate = [self convertPoint:tapRectUpperLeft toCoordinateFromView:self];
- tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude));
+ coordinate = [self convertPoint:tapRectLowerLeft toCoordinateFromView:self];
+ tapBounds.extend(coordinateToLatLng(coordinate));
- coordinate = [self convertPoint:tapRectUpperRight toCoordinateFromView:self];
- tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude));
+ coordinate = [self convertPoint:tapRectUpperLeft toCoordinateFromView:self];
+ tapBounds.extend(coordinateToLatLng(coordinate));
- coordinate = [self convertPoint:tapRectLowerRight toCoordinateFromView:self];
- tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude));
+ coordinate = [self convertPoint:tapRectUpperRight toCoordinateFromView:self];
+ tapBounds.extend(coordinateToLatLng(coordinate));
- // query for nearby annotations
- std::vector<uint32_t> nearbyAnnotations = mbglMap->getAnnotationsInBounds(tapBounds);
+ coordinate = [self convertPoint:tapRectLowerRight toCoordinateFromView:self];
+ tapBounds.extend(coordinateToLatLng(coordinate));
- int32_t newSelectedAnnotationID = -1;
+ // query for nearby annotations
+ std::vector<uint32_t> nearbyAnnotations = mbglMap->getAnnotationsInBounds(tapBounds);
- if (nearbyAnnotations.size())
- {
- // there is at least one nearby annotation; select one
- //
- // first, sort for comparison and iteration
- std::sort(nearbyAnnotations.begin(), nearbyAnnotations.end());
+ int32_t newSelectedAnnotationID = -1;
- if (nearbyAnnotations == self.annotationsNearbyLastTap)
+ if (nearbyAnnotations.size())
{
- // the selection candidates haven't changed; cycle through them
- if (self.selectedAnnotation &&
- [[[self.annotationsStore objectForKey:self.selectedAnnotation]
- objectForKey:MGLAnnotationIDKey] unsignedIntValue] == self.annotationsNearbyLastTap.back())
- {
- // the selected annotation is the last in the set; cycle back to the first
- // note: this could be the selected annotation if only one in set
- newSelectedAnnotationID = self.annotationsNearbyLastTap.front();
- }
- else if (self.selectedAnnotation)
+ // there is at least one nearby annotation; select one
+ //
+ // first, sort for comparison and iteration
+ std::sort(nearbyAnnotations.begin(), nearbyAnnotations.end());
+
+ if (nearbyAnnotations == self.annotationsNearbyLastTap)
{
- // otherwise increment the selection through the candidates
- uint32_t currentID = [[[self.annotationsStore objectForKey:self.selectedAnnotation] objectForKey:MGLAnnotationIDKey] unsignedIntValue];
- auto result = std::find(self.annotationsNearbyLastTap.begin(), self.annotationsNearbyLastTap.end(), currentID);
- auto distance = std::distance(self.annotationsNearbyLastTap.begin(), result);
- newSelectedAnnotationID = self.annotationsNearbyLastTap[distance + 1];
+ // the selection candidates haven't changed; cycle through them
+ if (self.selectedAnnotation &&
+ [[[self.annotationIDsByAnnotation objectForKey:self.selectedAnnotation]
+ objectForKey:MGLAnnotationIDKey] unsignedIntValue] == self.annotationsNearbyLastTap.back())
+ {
+ // the selected annotation is the last in the set; cycle back to the first
+ // note: this could be the selected annotation if only one in set
+ newSelectedAnnotationID = self.annotationsNearbyLastTap.front();
+ }
+ else if (self.selectedAnnotation)
+ {
+ // otherwise increment the selection through the candidates
+ uint32_t currentID = [[[self.annotationIDsByAnnotation objectForKey:self.selectedAnnotation] objectForKey:MGLAnnotationIDKey] unsignedIntValue];
+ auto result = std::find(self.annotationsNearbyLastTap.begin(), self.annotationsNearbyLastTap.end(), currentID);
+ auto distance = std::distance(self.annotationsNearbyLastTap.begin(), result);
+ newSelectedAnnotationID = self.annotationsNearbyLastTap[distance + 1];
+ }
+ else
+ {
+ // no current selection; select the first one
+ newSelectedAnnotationID = self.annotationsNearbyLastTap.front();
+ }
}
else
{
- // no current selection; select the first one
+ // start tracking a new set of nearby annotations
+ self.annotationsNearbyLastTap = nearbyAnnotations;
+
+ // select the first one
newSelectedAnnotationID = self.annotationsNearbyLastTap.front();
}
}
else
{
- // start tracking a new set of nearby annotations
- self.annotationsNearbyLastTap = nearbyAnnotations;
-
- // select the first one
- newSelectedAnnotationID = self.annotationsNearbyLastTap.front();
+ // there are no nearby annotations; deselect if necessary
+ newSelectedAnnotationID = -1;
}
- }
- else
- {
- // there are no nearby annotations; deselect if necessary
- newSelectedAnnotationID = -1;
- }
- if (newSelectedAnnotationID >= 0)
- {
- // find & select model object for selection
- NSEnumerator *enumerator = self.annotationsStore.keyEnumerator;
-
- while (id <MGLAnnotation> annotation = enumerator.nextObject)
+ if (newSelectedAnnotationID >= 0)
{
- if ([[[self.annotationsStore objectForKey:annotation] objectForKey:MGLAnnotationIDKey] integerValue] == newSelectedAnnotationID)
+ // find & select model object for selection
+ NSEnumerator *enumerator = self.annotationIDsByAnnotation.keyEnumerator;
+
+ while (id <MGLAnnotation> annotation = enumerator.nextObject)
{
- // only change selection status if not the currently selected annotation
- if ( ! [annotation isEqual:self.selectedAnnotation])
+ if ([[[self.annotationIDsByAnnotation objectForKey:annotation] objectForKey:MGLAnnotationIDKey] integerValue] == newSelectedAnnotationID)
{
- [self selectAnnotation:annotation animated:YES];
- }
+ // only change selection status if not the currently selected annotation
+ if ( ! [annotation isEqual:self.selectedAnnotation])
+ {
+ [self selectAnnotation:annotation animated:YES];
+ }
- // either way, we should stop enumerating
- break;
+ // either way, we should stop enumerating
+ break;
+ }
}
}
+ else
+ {
+ // deselect any selected annotation
+ if (self.selectedAnnotation) [self deselectAnnotation:self.selectedAnnotation animated:YES];
+ }
}
- else
- {
- // deselect any selected annotation
- if (self.selectedAnnotation) [self deselectAnnotation:self.selectedAnnotation animated:YES];
- }
-
- NSLog(@"%i (%@)", newSelectedAnnotationID, self.selectedAnnotation.title);
}
- (void)handleDoubleTapGesture:(UITapGestureRecognizer *)doubleTap
{
- [self trackGestureEvent:@"DoubleTap" forRecognizer:doubleTap];
-
if ( ! self.isZoomEnabled) return;
mbglMap->cancelTransitions();
- if (doubleTap.state == UIGestureRecognizerStateEnded)
+ if (doubleTap.state == UIGestureRecognizerStateBegan)
+ {
+ [self trackGestureEvent:MGLEventGestureDoubleTap forRecognizer:doubleTap];
+ }
+ else if (doubleTap.state == UIGestureRecognizerStateEnded)
{
- mbglMap->scaleBy(2, [doubleTap locationInView:doubleTap.view].x, [doubleTap locationInView:doubleTap.view].y, secondsAsDuration(MGLAnimationDuration));
+ CGPoint doubleTapPoint = [doubleTap locationInView:doubleTap.view];
+
+ CGPoint zoomInPoint;
+
+ if (self.userTrackingMode != MGLUserTrackingModeNone)
+ {
+ CGPoint userPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self];
+ CGRect userLocationRect = CGRectMake(userPoint.x - 40, userPoint.y - 40, 80, 80);
+ if (CGRectContainsPoint(userLocationRect, doubleTapPoint))
+ {
+ zoomInPoint = userPoint;
+ }
+ }
+ else
+ {
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
+ zoomInPoint = doubleTapPoint;
+ }
+
+ mbglMap->scaleBy(2, zoomInPoint.x, zoomInPoint.y, secondsAsDuration(MGLAnimationDuration));
self.animatingGesture = YES;
@@ -907,17 +939,32 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)handleTwoFingerTapGesture:(UITapGestureRecognizer *)twoFingerTap
{
- [self trackGestureEvent:@"TwoFingerTap" forRecognizer:twoFingerTap];
-
if ( ! self.isZoomEnabled) return;
if (mbglMap->getZoom() == mbglMap->getMinZoom()) return;
mbglMap->cancelTransitions();
- if (twoFingerTap.state == UIGestureRecognizerStateEnded)
+ if (twoFingerTap.state == UIGestureRecognizerStateBegan)
+ {
+ [self trackGestureEvent:MGLEventGestureTwoFingerSingleTap forRecognizer:twoFingerTap];
+ }
+ else if (twoFingerTap.state == UIGestureRecognizerStateEnded)
{
- mbglMap->scaleBy(0.5, [twoFingerTap locationInView:twoFingerTap.view].x, [twoFingerTap locationInView:twoFingerTap.view].y, secondsAsDuration(MGLAnimationDuration));
+ CGPoint zoomOutPoint;
+
+ if (self.userTrackingMode != MGLUserTrackingModeNone)
+ {
+ zoomOutPoint = self.center;
+ }
+ else
+ {
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
+ zoomOutPoint = CGPointMake([twoFingerTap locationInView:twoFingerTap.view].x, [twoFingerTap locationInView:twoFingerTap.view].y);
+ }
+
+ mbglMap->scaleBy(0.5, zoomOutPoint.x, zoomOutPoint.y, secondsAsDuration(MGLAnimationDuration));
self.animatingGesture = YES;
@@ -936,17 +983,19 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)handleQuickZoomGesture:(UILongPressGestureRecognizer *)quickZoom
{
- [self trackGestureEvent:@"QuickZoom" forRecognizer:quickZoom];
-
if ( ! self.isZoomEnabled) return;
mbglMap->cancelTransitions();
if (quickZoom.state == UIGestureRecognizerStateBegan)
{
+ [self trackGestureEvent:MGLEventGestureQuickZoom forRecognizer:quickZoom];
+
self.scale = mbglMap->getScale();
self.quickZoomStart = [quickZoom locationInView:quickZoom.view].y;
+
+ self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (quickZoom.state == UIGestureRecognizerStateChanged)
{
@@ -962,7 +1011,16 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
{
[self unrotateIfNeededAnimated:YES];
- [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)];
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)];
+ }
+}
+
+- (void)handleCalloutAccessoryTapGesture:(UITapGestureRecognizer *)tap
+{
+ if ([self.delegate respondsToSelector:@selector(mapView:annotation:calloutAccessoryControlTapped:)])
+ {
+ [self.delegate mapView:self annotation:self.selectedAnnotation
+ calloutAccessoryControlTapped:(UIControl *)tap.view];
}
}
@@ -973,18 +1031,18 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
return ([validSimultaneousGestures containsObject:gestureRecognizer] && [validSimultaneousGestures containsObject:otherGestureRecognizer]);
}
-- (void) trackGestureEvent:(NSString *) gesture forRecognizer:(UIGestureRecognizer *) recognizer
+- (void)trackGestureEvent:(NSString *)gestureID forRecognizer:(UIGestureRecognizer *)recognizer
{
- // Send Map Zoom Event
- CGPoint ptInView = CGPointMake([recognizer locationInView:recognizer.view].x, [recognizer locationInView:recognizer.view].y);
- CLLocationCoordinate2D coord = [self convertPoint:ptInView toCoordinateFromView:recognizer.view];
- NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
- [dict setValue:[[NSNumber alloc] initWithDouble:coord.latitude] forKey:@"lat"];
- [dict setValue:[[NSNumber alloc] initWithDouble:coord.longitude] forKey:@"lng"];
- [dict setValue:[[NSNumber alloc] initWithDouble:[self zoomLevel]] forKey:@"zoom"];
- [dict setValue:gesture forKey:@"gesture"];
-
- [[MGLMapboxEvents sharedManager] pushEvent:@"map.click" withAttributes:dict];
+ CGPoint pointInView = CGPointMake([recognizer locationInView:recognizer.view].x, [recognizer locationInView:recognizer.view].y);
+ CLLocationCoordinate2D gestureCoordinate = [self convertPoint:pointInView toCoordinateFromView:recognizer.view];
+ double zoom = [self zoomLevel];
+
+ [MGLMapboxEvents pushEvent:MGLEventTypeMapTap withAttributes:@{
+ MGLEventKeyLatitude: @(gestureCoordinate.latitude),
+ MGLEventKeyLongitude: @(gestureCoordinate.longitude),
+ MGLEventKeyZoomLevel: @(zoom),
+ MGLEventKeyGestureID: gestureID
+ }];
}
#pragma mark - Properties -
@@ -1016,6 +1074,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)resetNorthAnimated:(BOOL)animated
{
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
CGFloat duration = (animated ? MGLAnimationDuration : 0);
mbglMap->setBearing(0, secondsAsDuration(duration));
@@ -1029,6 +1089,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
{
if (finished)
{
+ [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)];
+
[UIView animateWithDuration:MGLAnimationDuration
animations:^
{
@@ -1041,6 +1103,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)resetPosition
{
mbglMap->resetPosition();
+
+ [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)];
}
- (void)toggleDebug
@@ -1050,11 +1114,20 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
#pragma mark - Geography -
+- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated preservingTracking:(BOOL)tracking
+{
+ self.userTrackingMode = (tracking ? self.userTrackingMode : MGLUserTrackingModeNone);
+
+ [self setCenterCoordinate:coordinate animated:animated];
+}
+
- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated
{
CGFloat duration = (animated ? MGLAnimationDuration : 0);
mbglMap->setLatLng(coordinateToLatLng(coordinate), secondsAsDuration(duration));
+
+ [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)];
}
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
@@ -1069,11 +1142,15 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(double)zoomLevel animated:(BOOL)animated
{
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
CGFloat duration = (animated ? MGLAnimationDuration : 0);
mbglMap->setLatLngZoom(coordinateToLatLng(centerCoordinate), zoomLevel, secondsAsDuration(duration));
[self unrotateIfNeededAnimated:animated];
+
+ [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)];
}
- (double)zoomLevel
@@ -1083,11 +1160,15 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (void)setZoomLevel:(double)zoomLevel animated:(BOOL)animated
{
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
CGFloat duration = (animated ? MGLAnimationDuration : 0);
mbglMap->setZoom(zoomLevel, secondsAsDuration(duration));
[self unrotateIfNeededAnimated:animated];
+
+ [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)];
}
- (void)setZoomLevel:(double)zoomLevel
@@ -1095,6 +1176,22 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
[self setZoomLevel:zoomLevel animated:NO];
}
+- (void)zoomToSouthWestCoordinate:(CLLocationCoordinate2D)southWestCoordinate northEastCoordinate:(CLLocationCoordinate2D)northEastCoordinate animated:(BOOL)animated
+{
+ // NOTE: does not disrupt tracking mode
+
+ CLLocationCoordinate2D center = CLLocationCoordinate2DMake((northEastCoordinate.latitude + southWestCoordinate.latitude) / 2, (northEastCoordinate.longitude + southWestCoordinate.longitude) / 2);
+
+ CGFloat scale = mbglMap->getScale();
+ CGFloat scaleX = mbglMap->getState().getWidth() / (northEastCoordinate.longitude - southWestCoordinate.longitude);
+ CGFloat scaleY = mbglMap->getState().getHeight() / (northEastCoordinate.latitude - southWestCoordinate.latitude);
+ CGFloat minZoom = mbglMap->getMinZoom();
+ CGFloat maxZoom = mbglMap->getMaxZoom();
+ CGFloat zoomLevel = MAX(MIN(log(scale * MIN(scaleX, scaleY)) / log(2), maxZoom), minZoom);
+
+ [self setCenterCoordinate:center zoomLevel:zoomLevel animated:animated];
+}
+
- (CLLocationDirection)direction
{
double direction = mbglMap->getBearing() * -1;
@@ -1109,9 +1206,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
{
if ( ! animated && ! self.rotationAllowed) return;
+ self.userTrackingMode = MGLUserTrackingModeNone;
+
CGFloat duration = (animated ? MGLAnimationDuration : 0);
mbglMap->setBearing(direction * -1, secondsAsDuration(duration));
+
+ [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)];
}
- (void)setDirection:(CLLocationDirection)direction
@@ -1132,7 +1233,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr;
- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view
{
- mbgl::vec2<double> pixel = mbglMap->pixelForLatLng(mbgl::LatLng(coordinate.latitude, coordinate.longitude));
+ mbgl::vec2<double> pixel = mbglMap->pixelForLatLng(coordinateToLatLng(coordinate));
// flip y coordinate for iOS view origin in top left
//
@@ -1178,14 +1279,14 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
{
const std::string styleJSON = mbglMap->getStyleJSON();
- return [NSJSONSerialization JSONObjectWithData:[@(styleJSON.c_str()) dataUsingEncoding:[NSString defaultCStringEncoding]] options:0 error:nil];
+ return [NSJSONSerialization JSONObjectWithData:[@(styleJSON.c_str()) dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
}
- (void)setRawStyle:(NSDictionary *)style
{
NSData *data = [NSJSONSerialization dataWithJSONObject:style options:0 error:nil];
- [self setStyleJSON:[[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]]];
+ [self setStyleJSON:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}
- (NSArray *)bundledStyleNames
@@ -1219,53 +1320,12 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
if (isHybrid) {
styleName = [@"satellite-" stringByAppendingString:[styleName substringFromIndex:[hybridStylePrefix length]]];
}
- [self setStyleURL:[NSString stringWithFormat:@"styles/%@.json", styleName]];
+ [self setStyleURL:[NSURL URLWithString:[NSString stringWithFormat:@"styles/%@.json", styleName]]];
if (isHybrid) {
[self setStyleClasses:@[@"contours", @"labels"]];
}
}
-- (NSArray *)getStyleOrderedLayerNames
-{
- return [[self getRawStyle] valueForKeyPath:@"layers.id"];
-}
-
-- (void)setStyleOrderedLayerNames:(NSArray *)orderedLayerNames
-{
- NSMutableDictionary *style = [[self getRawStyle] deepMutableCopy];
- NSArray *oldLayers = style[@"layers"];
- NSMutableArray *newLayers = [NSMutableArray array];
-
- if ([orderedLayerNames count] != [[oldLayers valueForKeyPath:@"id"] count])
- {
- [NSException raise:@"invalid layer count"
- format:@"new layer count (%lu) should equal existing layer count (%lu)",
- (unsigned long)[orderedLayerNames count],
- (unsigned long)[[oldLayers valueForKeyPath:@"id"] count]];
- }
- else
- {
- for (NSString *newLayerName in orderedLayerNames)
- {
- if ( ! [[oldLayers valueForKeyPath:@"id"] containsObject:newLayerName])
- {
- [NSException raise:@"invalid layer name"
- format:@"layer name %@ unknown",
- newLayerName];
- }
- else
- {
- NSDictionary *newLayer = [oldLayers objectAtIndex:[[oldLayers valueForKeyPath:@"id"] indexOfObject:newLayerName]];
- [newLayers addObject:newLayer];
- }
- }
- }
-
- [style setValue:newLayers forKey:@"layers"];
-
- [self setRawStyle:style];
-}
-
- (NSArray *)getAppliedStyleClasses
{
NSMutableArray *returnArray = [NSMutableArray array];
@@ -1291,480 +1351,579 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
for (NSString *appliedClass in appliedClasses)
{
- newAppliedClasses.insert(newAppliedClasses.end(), [appliedClass cStringUsingEncoding:[NSString defaultCStringEncoding]]);
+ newAppliedClasses.insert(newAppliedClasses.end(), [appliedClass UTF8String]);
}
mbglMap->setDefaultTransitionDuration(secondsAsDuration(transitionDuration));
mbglMap->setClasses(newAppliedClasses);
}
-- (NSString *)getKeyTypeForLayer:(NSString *)layerName
+#pragma mark - Annotations -
+
+- (NSArray *)annotations
{
- NSDictionary *style = [self getRawStyle];
+ if ([_annotationIDsByAnnotation count])
+ {
+ NSMutableArray *result = [NSMutableArray array];
- NSString *bucketType;
+ NSEnumerator *keyEnumerator = [_annotationIDsByAnnotation keyEnumerator];
+ id <MGLAnnotation> annotation;
- if ([layerName isEqualToString:@"background"])
- {
- bucketType = @"background";
- }
- else
- {
- for (NSDictionary *layer in style[@"structure"])
+ while (annotation = [keyEnumerator nextObject])
{
- if ([layer[@"name"] isEqualToString:layerName])
- {
- bucketType = style[@"buckets"][layer[@"bucket"]][@"type"];
- break;
- }
+ [result addObject:annotation];
}
- }
- NSString *keyType;
-
- if ([bucketType isEqualToString:@"fill"])
- {
- keyType = MGLStyleKeyFill;
- }
- else if ([bucketType isEqualToString:@"line"])
- {
- keyType = MGLStyleKeyLine;
- }
- else if ([bucketType isEqualToString:@"point"])
- {
- keyType = MGLStyleKeyIcon;
- }
- else if ([bucketType isEqualToString:@"text"])
- {
- keyType = MGLStyleKeyText;
- }
- else if ([bucketType isEqualToString:@"raster"])
- {
- keyType = MGLStyleKeyRaster;
- }
- else if ([bucketType isEqualToString:@"composite"])
- {
- keyType = MGLStyleKeyComposite;
- }
- else if ([bucketType isEqualToString:@"background"])
- {
- keyType = MGLStyleKeyBackground;
- }
- else
- {
- [NSException raise:@"invalid bucket type"
- format:@"bucket type %@ unknown",
- bucketType];
+ return [NSArray arrayWithArray:result];
}
- return keyType;
+ return nil;
}
-- (NSDictionary *)getStyleDescriptionForLayer:(NSString *)layerName inClass:(NSString *)className
+- (void)addAnnotation:(id <MGLAnnotation>)annotation
{
- NSDictionary *style = [self getRawStyle];
+ if ( ! annotation) return;
- if ( ! [[style valueForKeyPath:@"classes.name"] containsObject:className])
- {
- [NSException raise:@"invalid class name"
- format:@"class name %@ unknown",
- className];
- }
+ // The core bulk add API is efficient with respect to indexing and
+ // screen refreshes, thus we should defer to it even for individual adds.
+ //
+ [self addAnnotations:@[ annotation ]];
+}
- NSUInteger classNumber = [[style valueForKeyPath:@"classes.name"] indexOfObject:className];
+- (void)addAnnotations:(NSArray *)annotations
+{
+ if ( ! annotations) return;
- if ( ! [[style[@"classes"][classNumber][@"layers"] allKeys] containsObject:layerName])
- {
- // layer specified in structure, but not styled
- //
- return nil;
- }
+ std::vector<mbgl::LatLng> latLngs;
+ latLngs.reserve(annotations.count);
- NSDictionary *layerStyle = style[@"classes"][classNumber][@"layers"][layerName];
+ std::vector<std::string> symbols;
+ symbols.reserve(annotations.count);
- NSMutableDictionary *styleDescription = [NSMutableDictionary dictionary];
+ BOOL delegateImplementsSymbolLookup = [self.delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)];
- for (NSString *keyName in [layerStyle allKeys])
+ for (id <MGLAnnotation> annotation in annotations)
{
- id value = layerStyle[keyName];
+ assert([annotation conformsToProtocol:@protocol(MGLAnnotation)]);
- while ([[style[@"constants"] allKeys] containsObject:value])
- {
- value = style[@"constants"][value];
- }
+ latLngs.push_back(coordinateToLatLng(annotation.coordinate));
- if ([[self.allowedStyleTypes[MGLStyleKeyGeneric] allKeys] containsObject:keyName])
+ NSString *symbolName = nil;
+
+ if (delegateImplementsSymbolLookup)
{
- [styleDescription setValue:[self typedPropertyForKeyName:keyName
- ofType:MGLStyleKeyGeneric
- withValue:value]
- forKey:keyName];
+ symbolName = [self.delegate mapView:self symbolNameForAnnotation:annotation];
}
- NSString *keyType = [self getKeyTypeForLayer:layerName];
+ symbols.push_back((symbolName ? [symbolName UTF8String] : ""));
+ }
+
+ std::vector<uint32_t> annotationIDs = mbglMap->addPointAnnotations(latLngs, symbols);
- if ([[self.allowedStyleTypes[keyType] allKeys] containsObject:keyName])
- {
- [styleDescription setValue:[self typedPropertyForKeyName:keyName
- ofType:keyType
- withValue:value]
- forKey:keyName];
- }
+ for (size_t i = 0; i < annotationIDs.size(); ++i)
+ {
+ [self.annotationIDsByAnnotation setObject:@{ MGLAnnotationIDKey : @(annotationIDs[i]) }
+ forKey:annotations[i]];
}
+}
+
+- (void)removeAnnotation:(id <MGLAnnotation>)annotation
+{
+ if ( ! annotation) return;
- return styleDescription;
+ // The core bulk deletion API is efficient with respect to indexing
+ // and screen refreshes, thus we should defer to it even for
+ // individual deletes.
+ //
+ [self removeAnnotations:@[ annotation ]];
}
-- (NSDictionary *)typedPropertyForKeyName:(NSString *)keyName ofType:(NSString *)keyType withValue:(id)value
+- (void)removeAnnotations:(NSArray *)annotations
{
- if ( ! [[self.allowedStyleTypes[keyType] allKeys] containsObject:keyName])
- {
- [NSException raise:@"invalid property name"
- format:@"property name %@ unknown",
- keyName];
- }
+ if ( ! annotations) return;
- NSArray *typeInfo = self.allowedStyleTypes[keyType][keyName];
+ std::vector<uint32_t> annotationIDsToRemove;
+ annotationIDsToRemove.reserve(annotations.count);
- if ([value isKindOfClass:[NSArray class]] && ! [typeInfo containsObject:MGLStyleValueTypeColor])
+ for (id <MGLAnnotation> annotation in annotations)
{
- if ([typeInfo containsObject:MGLStyleValueFunctionAllowed])
- {
- if ([[(NSArray *)value firstObject] isKindOfClass:[NSString class]])
- {
- NSString *functionType;
+ assert([annotation conformsToProtocol:@protocol(MGLAnnotation)]);
- if ([[(NSArray *)value firstObject] isEqualToString:@"linear"])
- {
- functionType = MGLStyleValueTypeFunctionLinear;
- }
- else if ([[(NSArray *)value firstObject] isEqualToString:@"stops"])
- {
- functionType = MGLStyleValueTypeFunctionStops;
- }
- else if ([[(NSArray *)value firstObject] isEqualToString:@"exponential"])
- {
- functionType = MGLStyleValueTypeFunctionExponential;
- }
- else if ([[(NSArray *)value firstObject] isEqualToString:@"min"])
- {
- functionType = MGLStyleValueTypeFunctionMinimumZoom;
- }
- else if ([[(NSArray *)value firstObject] isEqualToString:@"max"])
- {
- functionType = MGLStyleValueTypeFunctionMaximumZoom;
- }
+ annotationIDsToRemove.push_back([[[self.annotationIDsByAnnotation objectForKey:annotation]
+ objectForKey:MGLAnnotationIDKey] unsignedIntValue]);
+ [self.annotationIDsByAnnotation removeObjectForKey:annotation];
- if (functionType)
- {
- return @{ @"type" : functionType,
- @"value" : value };
- }
- }
- }
- else if ([typeInfo containsObject:MGLStyleValueTypeNumberPair])
+ if (annotation == self.selectedAnnotation)
{
- return @{ @"type" : MGLStyleValueTypeNumberPair,
- @"value" : value };
+ [self deselectAnnotation:annotation animated:NO];
}
}
- else if ([typeInfo containsObject:MGLStyleValueTypeNumber])
- {
- return @{ @"type" : MGLStyleValueTypeNumber,
- @"value" : value };
- }
- else if ([typeInfo containsObject:MGLStyleValueTypeBoolean])
- {
- return @{ @"type" : MGLStyleValueTypeBoolean,
- @"value" : @([(NSString *)value boolValue]) };
- }
- else if ([typeInfo containsObject:MGLStyleValueTypeString])
- {
- return @{ @"type" : MGLStyleValueTypeString,
- @"value" : value };
- }
- else if ([typeInfo containsObject:MGLStyleValueTypeColor])
- {
- UIColor *color;
- if ([(NSString *)value hasPrefix:@"#"])
- {
- color = [UIColor colorWithHexString:value];
- }
- else if ([(NSString *)value hasPrefix:@"rgb"])
- {
- color = [UIColor colorWithRGBAString:value];
- }
- else if ([(NSString *)value hasPrefix:@"hsl"])
- {
- [NSException raise:@"invalid color format"
- format:@"HSL color format not yet supported natively"];
- }
- else if ([value isKindOfClass:[NSArray class]] && [(NSArray *)value count] == 4)
- {
- color = [UIColor colorWithRed:[value[0] floatValue]
- green:[value[1] floatValue]
- blue:[value[2] floatValue]
- alpha:[value[3] floatValue]];
- }
- else if ([[UIColor class] respondsToSelector:NSSelectorFromString([NSString stringWithFormat:@"%@Color", [(NSString *)value lowercaseString]])])
- {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
+ mbglMap->removeAnnotations(annotationIDsToRemove);
+}
+
+- (NSArray *)selectedAnnotations
+{
+ return (self.selectedAnnotation ? @[ self.selectedAnnotation ] : @[]);
+}
- color = [[UIColor class] performSelector:NSSelectorFromString([NSString stringWithFormat:@"%@Color", [(NSString *)value lowercaseString]])];
+- (void)setSelectedAnnotations:(NSArray *)selectedAnnotations
+{
+ if ( ! selectedAnnotations.count) return;
-#pragma clang diagnostic pop
- }
+ id <MGLAnnotation> firstAnnotation = selectedAnnotations[0];
- return @{ @"type" : MGLStyleValueTypeColor,
- @"value" : color };
- }
+ assert([firstAnnotation conformsToProtocol:@protocol(MGLAnnotation)]);
- return nil;
+ if ( ! [self viewportBounds].contains(coordinateToLatLng(firstAnnotation.coordinate))) return;
+
+ [self selectAnnotation:firstAnnotation animated:NO];
}
-- (void)setStyleDescription:(NSDictionary *)styleDescription forLayer:(NSString *)layerName inClass:(NSString *)className
+- (void)selectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated
{
-#pragma unused(className)
+ if ( ! annotation) return;
+
+ if ( ! [self viewportBounds].contains(coordinateToLatLng(annotation.coordinate))) return;
+
+ if (annotation == self.selectedAnnotation) return;
+
+ self.userTrackingMode = MGLUserTrackingModeNone;
- NSMutableDictionary *convertedStyle = [NSMutableDictionary dictionary];
+ [self deselectAnnotation:self.selectedAnnotation animated:NO];
- for (NSString *key in [styleDescription allKeys])
+ self.selectedAnnotation = annotation;
+
+ if (annotation.title && [self.delegate respondsToSelector:@selector(mapView:annotationCanShowCallout:)] &&
+ [self.delegate mapView:self annotationCanShowCallout:annotation])
{
- NSArray *styleParameters = nil;
+ // build the callout
+ self.selectedAnnotationCalloutView = [self calloutViewForAnnotation:annotation];
+
+ CGRect calloutBounds;
- if ([[self.allowedStyleTypes[MGLStyleKeyGeneric] allKeys] containsObject:key])
+ if ([annotation isEqual:self.userLocation])
{
- styleParameters = self.allowedStyleTypes[MGLStyleKeyGeneric][key];
+ CGPoint calloutAnchorPoint = [self convertCoordinate:annotation.coordinate toPointToView:self];
+ calloutBounds = CGRectMake(calloutAnchorPoint.x - 1, calloutAnchorPoint.y - 13, 0, 0);
}
else
{
- NSString *keyType = [self getKeyTypeForLayer:layerName];
-
- if ([[self.allowedStyleTypes[keyType] allKeys] containsObject:key])
+ // determine symbol in use for point
+ NSString *symbol = MGLDefaultStyleMarkerSymbolName;
+ if ([self.delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)])
{
- styleParameters = self.allowedStyleTypes[keyType][key];
+ symbol = [self.delegate mapView:self symbolNameForAnnotation:annotation];
}
+ std::string symbolName([symbol UTF8String]);
+
+ // determine anchor point based on symbol
+ CGPoint calloutAnchorPoint = [self convertCoordinate:annotation.coordinate toPointToView:self];
+ double y = mbglMap->getTopOffsetPixelsForAnnotationSymbol(symbolName);
+ calloutBounds = CGRectMake(calloutAnchorPoint.x - 1, calloutAnchorPoint.y + y, 0, 0);
}
- if (styleParameters)
+ // consult delegate for left and/or right accessory views
+ if ([self.delegate respondsToSelector:@selector(mapView:leftCalloutAccessoryViewForAnnotation:)])
{
- if ([styleDescription[key][@"value"] isKindOfClass:[MGLStyleFunctionValue class]])
- {
- convertedStyle[key] = [(MGLStyleFunctionValue *)styleDescription[key][@"value"] rawStyle];
- }
- else if ([styleParameters containsObject:styleDescription[key][@"type"]])
+ self.selectedAnnotationCalloutView.leftAccessoryView =
+ [self.delegate mapView:self leftCalloutAccessoryViewForAnnotation:annotation];
+
+ if ([self.selectedAnnotationCalloutView.leftAccessoryView isKindOfClass:[UIControl class]])
{
- NSString *valueType = styleDescription[key][@"type"];
+ UITapGestureRecognizer *calloutAccessoryTap = [[UITapGestureRecognizer alloc] initWithTarget:self
+ action:@selector(handleCalloutAccessoryTapGesture:)];
- if ([valueType isEqualToString:MGLStyleValueTypeColor])
- {
- convertedStyle[key] = [@"#" stringByAppendingString:[(UIColor *)styleDescription[key][@"value"] hexStringFromColor]];
- }
- else
- {
- // the rest (bool/number/pair/string) are already JSON-convertible types
- //
- convertedStyle[key] = styleDescription[key][@"value"];
- }
+ [self.selectedAnnotationCalloutView.leftAccessoryView addGestureRecognizer:calloutAccessoryTap];
}
}
- else
+
+ if ([self.delegate respondsToSelector:@selector(mapView:rightCalloutAccessoryViewForAnnotation:)])
{
- [NSException raise:@"invalid style description format"
- format:@"unable to parse key '%@'",
- key];
+ self.selectedAnnotationCalloutView.rightAccessoryView =
+ [self.delegate mapView:self rightCalloutAccessoryViewForAnnotation:annotation];
+
+ if ([self.selectedAnnotationCalloutView.rightAccessoryView isKindOfClass:[UIControl class]])
+ {
+ UITapGestureRecognizer *calloutAccessoryTap = [[UITapGestureRecognizer alloc] initWithTarget:self
+ action:@selector(handleCalloutAccessoryTapGesture:)];
+
+ [self.selectedAnnotationCalloutView.rightAccessoryView addGestureRecognizer:calloutAccessoryTap];
+ }
}
+
+ // present popup
+ [self.selectedAnnotationCalloutView presentCalloutFromRect:calloutBounds
+ inView:self.glView
+ constrainedToView:self.glView
+ animated:animated];
}
-// NSMutableDictionary *style = [[self getRawStyle] deepMutableCopy];
-//
-// NSUInteger classIndex = [[[self getAllStyleClasses] valueForKey:@"name"] indexOfObject:className];
-//
-// style[@"classes"][classIndex][@"layers"][layerName] = convertedStyle;
-//
-// [self setRawStyle:style];
-}
-
-- (NSDictionary *)allowedStyleTypes
-{
- static NSDictionary *MGLStyleAllowedTypes = @{
- MGLStyleKeyGeneric : @{
- @"enabled" : @[ MGLStyleValueTypeBoolean, MGLStyleValueFunctionAllowed ],
- @"translate" : @[ MGLStyleValueTypeNumberPair, MGLStyleValueFunctionAllowed ],
- @"translate-anchor" : @[ MGLStyleValueTypeString, MGLStyleValueFunctionAllowed ],
- @"opacity" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"prerender" : @[ MGLStyleValueTypeBoolean ],
- @"prerender-buffer" : MGLStyleValueTypeNumber,
- @"prerender-size" : @[ MGLStyleValueTypeNumber ],
- @"prerender-blur" : @[ MGLStyleValueTypeNumber ] },
- MGLStyleKeyFill : @{
- @"color" : @[ MGLStyleValueTypeColor ],
- @"stroke" : @[ MGLStyleValueTypeColor ],
- @"antialias" : @[ MGLStyleValueTypeBoolean ],
- @"image" : @[ MGLStyleValueTypeString ] },
- MGLStyleKeyLine : @{
- @"color" : @[ MGLStyleValueTypeColor ],
- @"width" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"dasharray" : @[ MGLStyleValueTypeNumberPair, MGLStyleValueFunctionAllowed ] },
- MGLStyleKeyIcon : @{
- @"color" : @[ MGLStyleValueTypeColor ],
- @"image" : @[ MGLStyleValueTypeString ],
- @"size" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"radius" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed],
- @"blur" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ] },
- MGLStyleKeyText : @{
- @"color" : @[ MGLStyleValueTypeColor ],
- @"stroke" : @[ MGLStyleValueTypeColor ],
- @"strokeWidth" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"strokeBlur" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"size" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"rotate" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ],
- @"alwaysVisible" : @[ MGLStyleValueTypeBoolean ] },
- MGLStyleKeyRaster : @{},
- MGLStyleKeyComposite : @{},
- MGLStyleKeyBackground : @{
- @"color" : @[ MGLStyleValueTypeColor ] }
- };
-
- return MGLStyleAllowedTypes;
+ // notify delegate
+ if ([self.delegate respondsToSelector:@selector(mapView:didSelectAnnotation:)])
+ {
+ [self.delegate mapView:self didSelectAnnotation:annotation];
+ }
}
-#pragma mark - Annotations -
+- (SMCalloutView *)calloutViewForAnnotation:(id <MGLAnnotation>)annotation
+{
+ SMCalloutView *calloutView = [SMCalloutView platformCalloutView];
-- (NSArray *)annotations
+ if ([annotation respondsToSelector:@selector(title)]) calloutView.title = annotation.title;
+ if ([annotation respondsToSelector:@selector(subtitle)]) calloutView.subtitle = annotation.subtitle;
+
+ calloutView.tintColor = self.tintColor;
+
+ return calloutView;
+}
+
+- (void)deselectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated
{
- if ([_annotationsStore count])
+ if ( ! annotation) return;
+
+ if ([self.selectedAnnotation isEqual:annotation])
{
- NSMutableArray *result = [NSMutableArray array];
+ // dismiss popup
+ [self.selectedAnnotationCalloutView dismissCalloutAnimated:animated];
- NSEnumerator *keyEnumerator = [_annotationsStore keyEnumerator];
- id <MGLAnnotation> annotation;
+ // clean up
+ self.selectedAnnotationCalloutView = nil;
+ self.selectedAnnotation = nil;
+ }
- while (annotation = [keyEnumerator nextObject])
+ // notify delegate
+ if ([self.delegate respondsToSelector:@selector(mapView:didDeselectAnnotation:)])
+ {
+ [self.delegate mapView:self didDeselectAnnotation:annotation];
+ }
+}
+
+#pragma mark - User Location -
+
+- (void)setShowsUserLocation:(BOOL)showsUserLocation
+{
+ if (showsUserLocation == _showsUserLocation) return;
+
+ _showsUserLocation = showsUserLocation;
+
+ if (showsUserLocation)
+ {
+ if ([self.delegate respondsToSelector:@selector(mapViewWillStartLocatingUser:)])
{
- [result addObject:annotation];
+ [self.delegate mapViewWillStartLocatingUser:self];
+ }
+
+ self.userLocationAnnotationView = [[MGLUserLocationAnnotationView alloc] initInMapView:self];
+
+ self.locationManager = [CLLocationManager new];
+
+#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
+ // enable iOS 8+ location authorization API
+ //
+ if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)])
+ {
+ BOOL hasLocationDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] ||
+ [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"];
+ NSAssert(hasLocationDescription,
+ @"For iOS 8 and above, your app must have a value for NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in its Info.plist");
+ [self.locationManager requestWhenInUseAuthorization];
}
+#endif
+
+ self.locationManager.headingFilter = 5.0;
+ self.locationManager.delegate = self;
+ [self.locationManager startUpdatingLocation];
+ }
+ else
+ {
+ [self.locationManager stopUpdatingLocation];
+ [self.locationManager stopUpdatingHeading];
+ self.locationManager.delegate = nil;
+ self.locationManager = nil;
- return [NSArray arrayWithArray:result];
+ if ([self.delegate respondsToSelector:@selector(mapViewDidStopLocatingUser:)])
+ {
+ [self.delegate mapViewDidStopLocatingUser:self];
+ }
+
+ [self setUserTrackingMode:MGLUserTrackingModeNone animated:YES];
+
+ [self.userLocationAnnotationView removeFromSuperview];
+ self.userLocationAnnotationView = nil;
}
+}
- return nil;
+- (void)setUserLocationAnnotationView:(MGLUserLocationAnnotationView *)newAnnotationView
+{
+ if ( ! [newAnnotationView isEqual:_userLocationAnnotationView])
+ {
+ _userLocationAnnotationView = newAnnotationView;
+ }
}
-- (void)addAnnotation:(id <MGLAnnotation>)annotation
++ (NSSet *)keyPathsForValuesAffectingUserLocation
{
- if ( ! annotation) return;
+ return [NSSet setWithObject:@"userLocationAnnotationView"];
+}
- // The core bulk add API is efficient with respect to indexing and
- // screen refreshes, thus we should defer to it even for individual adds.
- //
- [self addAnnotations:@[ annotation ]];
+- (MGLUserLocation *)userLocation
+{
+ return self.userLocationAnnotationView.annotation;
}
-- (void)addAnnotations:(NSArray *)annotations
+- (BOOL)isUserLocationVisible
{
- if ( ! annotations) return;
+ if (self.userLocationAnnotationView)
+ {
+ CGPoint locationPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self];
- std::vector<mbgl::LatLng> latLngs;
- latLngs.reserve(annotations.count);
+ CGRect locationRect = CGRectMake(locationPoint.x - self.userLocation.location.horizontalAccuracy,
+ locationPoint.y - self.userLocation.location.horizontalAccuracy,
+ self.userLocation.location.horizontalAccuracy * 2,
+ self.userLocation.location.horizontalAccuracy * 2);
- std::vector<std::string> symbols;
- symbols.reserve(annotations.count);
+ return CGRectIntersectsRect([self bounds], locationRect);
+ }
- BOOL delegateImplementsSymbolLookup = [self.delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)];
+ return NO;
+}
- for (id <MGLAnnotation> annotation in annotations)
+- (void)setUserTrackingMode:(MGLUserTrackingMode)mode
+{
+ [self setUserTrackingMode:mode animated:YES];
+}
+
+- (void)setUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated
+{
+ if (mode == _userTrackingMode) return;
+
+ if (mode == MGLUserTrackingModeFollowWithHeading && ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate))
{
- assert([annotation conformsToProtocol:@protocol(MGLAnnotation)]);
+ mode = MGLUserTrackingModeNone;
+ }
- latLngs.push_back(coordinateToLatLng(annotation.coordinate));
+ _userTrackingMode = mode;
- NSString *symbolName = nil;
+ switch (_userTrackingMode)
+ {
+ case MGLUserTrackingModeNone:
+ default:
+ {
+ [self.locationManager stopUpdatingHeading];
- if (delegateImplementsSymbolLookup)
+ break;
+ }
+ case MGLUserTrackingModeFollow:
{
- symbolName = [self.delegate mapView:self symbolNameForAnnotation:annotation];
+ self.showsUserLocation = YES;
+
+ [self.locationManager stopUpdatingHeading];
+
+ if (self.userLocationAnnotationView)
+ {
+ #pragma clang diagnostic push
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ [self locationManager:self.locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location];
+ #pragma clang diagnostic pop
+ }
+
+ break;
}
+ case MGLUserTrackingModeFollowWithHeading:
+ {
+ self.showsUserLocation = YES;
- symbols.push_back((symbolName ? [symbolName cStringUsingEncoding:[NSString defaultCStringEncoding]] : ""));
- }
+ if (self.zoomLevel < 3) [self setZoomLevel:3 animated:YES];
- std::vector<uint32_t> annotationIDs = mbglMap->addPointAnnotations(latLngs, symbols);
+ if (self.userLocationAnnotationView)
+ {
+ #pragma clang diagnostic push
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ [self locationManager:self.locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location];
+ #pragma clang diagnostic pop
+ }
- for (size_t i = 0; i < annotationIDs.size(); ++i)
+ [self updateHeadingForDeviceOrientation];
+
+ [self.locationManager startUpdatingHeading];
+
+ break;
+ }
+ }
+
+ if ([self.delegate respondsToSelector:@selector(mapView:didChangeUserTrackingMode:animated:)])
{
- [self.annotationsStore setObject:@{ MGLAnnotationIDKey : @(annotationIDs[i]) }
- forKey:annotations[i]];
+ [self.delegate mapView:self didChangeUserTrackingMode:_userTrackingMode animated:animated];
}
}
-- (void)removeAnnotation:(id <MGLAnnotation>)annotation
+- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
- if ( ! annotation) return;
+ (void)manager;
- // The core bulk deletion API is efficient with respect to indexing
- // and screen refreshes, thus we should defer to it even for
- // individual deletes.
- //
- [self removeAnnotations:@[ annotation ]];
-}
+ if ( ! _showsUserLocation || ! newLocation || ! CLLocationCoordinate2DIsValid(newLocation.coordinate)) return;
-- (void)removeAnnotations:(NSArray *)annotations
-{
- if ( ! annotations) return;
+ if ([newLocation distanceFromLocation:oldLocation] || ! oldLocation)
+ {
+ self.userLocation.location = newLocation;
- std::vector<uint32_t> annotationIDsToRemove;
- annotationIDsToRemove.reserve(annotations.count);
+ // deselect user if applicable since we don't do callout tracking yet
+ if ([self.selectedAnnotation isEqual:self.userLocation]) [self deselectAnnotation:self.userLocation animated:NO];
- for (id <MGLAnnotation> annotation in annotations)
+ if ([self.delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)])
+ {
+ [self.delegate mapView:self didUpdateUserLocation:self.userLocation];
+ }
+ }
+
+ if (self.userTrackingMode != MGLUserTrackingModeNone)
{
- assert([annotation conformsToProtocol:@protocol(MGLAnnotation)]);
+ // center on user location unless we're already centered there (or very close)
+ //
+ CGPoint mapCenterPoint = [self convertPoint:self.center fromView:self.superview];
+ CGPoint userLocationPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self];
- annotationIDsToRemove.push_back([[[self.annotationsStore objectForKey:annotation] objectForKey:MGLAnnotationIDKey] unsignedIntValue]);
- [self.annotationsStore removeObjectForKey:annotation];
+ if (std::abs(userLocationPoint.x - mapCenterPoint.x) > 1.0 || std::abs(userLocationPoint.y - mapCenterPoint.y) > 1.0)
+ {
+ if (round(self.zoomLevel) >= 10)
+ {
+ // at sufficient detail, just re-center the map; don't zoom
+ //
+ [self setCenterCoordinate:self.userLocation.location.coordinate animated:YES preservingTracking:YES];
+ }
+ else
+ {
+ // otherwise re-center and zoom in to near accuracy confidence
+ //
+ float delta = (newLocation.horizontalAccuracy / 110000) * 1.2; // approx. meter per degree latitude, plus some margin
+
+ CLLocationCoordinate2D desiredSouthWest = CLLocationCoordinate2DMake(newLocation.coordinate.latitude - delta,
+ newLocation.coordinate.longitude - delta);
+
+ CLLocationCoordinate2D desiredNorthEast = CLLocationCoordinate2DMake(newLocation.coordinate.latitude + delta,
+ newLocation.coordinate.longitude + delta);
+
+ CGFloat pixelRadius = fminf(self.bounds.size.width, self.bounds.size.height) / 2;
+
+ CLLocationCoordinate2D actualSouthWest = [self convertPoint:CGPointMake(userLocationPoint.x - pixelRadius,
+ userLocationPoint.y - pixelRadius)
+ toCoordinateFromView:self];
+
+ CLLocationCoordinate2D actualNorthEast = [self convertPoint:CGPointMake(userLocationPoint.x + pixelRadius,
+ userLocationPoint.y + pixelRadius)
+ toCoordinateFromView:self];
+
+ if (desiredNorthEast.latitude != actualNorthEast.latitude ||
+ desiredNorthEast.longitude != actualNorthEast.longitude ||
+ desiredSouthWest.latitude != actualSouthWest.latitude ||
+ desiredSouthWest.longitude != actualSouthWest.longitude)
+ {
+ // assumes we won't disrupt tracking mode
+ [self zoomToSouthWestCoordinate:desiredSouthWest northEastCoordinate:desiredNorthEast animated:YES];
+ }
+ }
+ }
}
- mbglMap->removeAnnotations(annotationIDsToRemove);
+ self.userLocationAnnotationView.haloLayer.hidden = ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate) ||
+ newLocation.horizontalAccuracy > 10;
+
+ [self updateUserLocationAnnotationView];
}
-- (NSArray *)selectedAnnotations
+- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager
{
- return (self.selectedAnnotation ? @[ self.selectedAnnotation ] : @[]);
+ (void)manager;
+
+ if (self.displayHeadingCalibration) [self.locationManager performSelector:@selector(dismissHeadingCalibrationDisplay)
+ withObject:nil
+ afterDelay:10.0];
+
+ return self.displayHeadingCalibration;
}
-- (void)setSelectedAnnotations:(NSArray *)selectedAnnotations
+- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
- if ( ! selectedAnnotations.count) return;
+ (void)manager;
- id <MGLAnnotation> firstAnnotation = selectedAnnotations[0];
+ if ( ! _showsUserLocation || self.pan.state == UIGestureRecognizerStateBegan || newHeading.headingAccuracy < 0) return;
- assert([firstAnnotation conformsToProtocol:@protocol(MGLAnnotation)]);
+ self.userLocation.heading = newHeading;
- if ( ! [self viewportBounds].contains(coordinateToLatLng(firstAnnotation.coordinate))) return;
+ if ([self.delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)])
+ {
+ [self.delegate mapView:self didUpdateUserLocation:self.userLocation];
- self.selectedAnnotation = firstAnnotation;
-}
+ if ( ! _showsUserLocation) return;
+ }
-- (void)selectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated
-{
- (void)animated;
+ CLLocationDirection headingDirection = (newHeading.trueHeading > 0 ? newHeading.trueHeading : newHeading.magneticHeading);
- if ( ! annotation) return;
+ if (headingDirection > 0 && self.userTrackingMode == MGLUserTrackingModeFollowWithHeading)
+ {
+ mbglMap->setBearing(headingDirection, secondsAsDuration(MGLAnimationDuration));
+ }
+}
- if ( ! [self viewportBounds].contains(coordinateToLatLng(annotation.coordinate))) return;
+- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
+{
+ (void)manager;
- self.selectedAnnotation = annotation;
+ if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted)
+ {
+ self.userTrackingMode = MGLUserTrackingModeNone;
+ self.showsUserLocation = NO;
+ }
}
-- (void)deselectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated
+- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
- (void)animated;
+ (void)manager;
- if ( ! annotation) return;
+ if ([error code] == kCLErrorDenied)
+ {
+ self.userTrackingMode = MGLUserTrackingModeNone;
+ self.showsUserLocation = NO;
- if ([self.selectedAnnotation isEqual:annotation]) self.selectedAnnotation = nil;
+ if ([self.delegate respondsToSelector:@selector(mapView:didFailToLocateUserWithError:)])
+ {
+ [self.delegate mapView:self didFailToLocateUserWithError:error];
+ }
+ }
+}
+
+- (void)updateHeadingForDeviceOrientation
+{
+ if (self.locationManager)
+ {
+ // note that right/left device and interface orientations are opposites (see UIApplication.h)
+ //
+ switch ([[UIApplication sharedApplication] statusBarOrientation])
+ {
+ case (UIInterfaceOrientationLandscapeLeft):
+ {
+ self.locationManager.headingOrientation = CLDeviceOrientationLandscapeRight;
+ break;
+ }
+ case (UIInterfaceOrientationLandscapeRight):
+ {
+ self.locationManager.headingOrientation = CLDeviceOrientationLandscapeLeft;
+ break;
+ }
+ case (UIInterfaceOrientationPortraitUpsideDown):
+ {
+ self.locationManager.headingOrientation = CLDeviceOrientationPortraitUpsideDown;
+ break;
+ }
+ case (UIInterfaceOrientationPortrait):
+ default:
+ {
+ self.locationManager.headingOrientation = CLDeviceOrientationPortrait;
+ break;
+ }
+ }
+ }
}
#pragma mark - Utility -
@@ -1844,6 +2003,11 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
case mbgl::MapChangeRegionWillChange:
case mbgl::MapChangeRegionWillChangeAnimated:
{
+ [self updateUserLocationAnnotationView];
+ [self updateCompass];
+
+ [self deselectAnnotation:self.selectedAnnotation animated:NO];
+
BOOL animated = ([change unsignedIntegerValue] == mbgl::MapChangeRegionWillChangeAnimated);
@synchronized (self.regionChangeDelegateQueue)
@@ -1874,9 +2038,20 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
}
break;
}
+ case mbgl::MapChangeRegionIsChanging:
+ {
+ [self updateUserLocationAnnotationView];
+ [self updateCompass];
+
+ if ([self.delegate respondsToSelector:@selector(mapViewRegionIsChanging:)])
+ {
+ [self.delegate mapViewRegionIsChanging:self];
+ }
+ }
case mbgl::MapChangeRegionDidChange:
case mbgl::MapChangeRegionDidChangeAnimated:
{
+ [self updateUserLocationAnnotationView];
[self updateCompass];
if (self.pan.state == UIGestureRecognizerStateChanged ||
@@ -1942,6 +2117,32 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
}
}
+- (void)updateUserLocationAnnotationView
+{
+ if ( ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate)) {
+ self.userLocationAnnotationView.layer.hidden = YES;
+ return;
+ }
+
+ if ( ! self.userLocationAnnotationView.superview) [self.glView addSubview:self.userLocationAnnotationView];
+
+ CGPoint userPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self];
+
+ if (CGRectContainsPoint(CGRectInset(self.bounds, -MGLAnnotationUpdateViewportOutset.width,
+ -MGLAnnotationUpdateViewportOutset.height), userPoint))
+ {
+ self.userLocationAnnotationView.center = userPoint;
+
+ self.userLocationAnnotationView.layer.hidden = NO;
+
+ [self.userLocationAnnotationView setupLayers];
+ }
+ else
+ {
+ self.userLocationAnnotationView.layer.hidden = YES;
+ }
+}
+
- (void)updateCompass
{
double degrees = mbglMap->getBearing() * -1;
@@ -1993,8 +2194,11 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng)
- (void)invalidate
{
- // This is run in the main/UI thread.
+ assert([[NSThread currentThread] isMainThread]);
+
[self.glView setNeedsDisplay];
+
+ [self notifyMapChange:@(mbgl::MapChangeRegionIsChanging)];
}
class MBGLView : public mbgl::View
@@ -2022,12 +2226,9 @@ class MBGLView : public mbgl::View
}
else
{
- dispatch_async(dispatch_get_main_queue(), ^
- {
- [nativeView performSelector:@selector(notifyMapChange:)
- withObject:@(change)
- afterDelay:0];
- });
+ assert([[NSThread currentThread] isMainThread]);
+
+ [nativeView notifyMapChange:@(change)];
}
}
diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m
index a231b5115f..7b810d5cd5 100644
--- a/platform/ios/MGLMapboxEvents.m
+++ b/platform/ios/MGLMapboxEvents.m
@@ -1,42 +1,99 @@
-//
-// MapboxEvents.m
-// MapboxEvents
-//
-// Dynamic detection of ASIdentifierManager from Mixpanel
-// https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE
-//
-// Created by Brad Leege on 3/5/15.
-// Copyright (c) 2015 Mapbox. All rights reserved.
-//
-
#import "MGLMapboxEvents.h"
+
#import <UIKit/UIKit.h>
+#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
+
+#import "MGLMetricsLocationManager.h"
+
#include <sys/sysctl.h>
-#import <SystemConfiguration/CaptiveNetwork.h>
+
+static NSString *const MGLMapboxEventsUserAgent = @"MapboxEventsiOS/1.0";
+static NSString *const MGLMapboxEventsAPIBase = @"https://api.tiles.mapbox.com";
+
+NSString *const MGLEventTypeMapLoad = @"map.load";
+NSString *const MGLEventTypeMapTap = @"map.click";
+NSString *const MGLEventTypeMapDragEnd = @"map.dragend";
+NSString *const MGLEventTypeLocation = @"Location";
+
+NSString *const MGLEventKeyLatitude = @"lat";
+NSString *const MGLEventKeyLongitude = @"lng";
+NSString *const MGLEventKeyZoomLevel = @"zoom";
+NSString *const MGLEventKeyPushEnabled = @"enabled.push";
+NSString *const MGLEventKeyEmailEnabled = @"enabled.email";
+NSString *const MGLEventKeyGestureID = @"gesture";
+
+NSString *const MGLEventGestureSingleTap = @"SingleTap";
+NSString *const MGLEventGestureDoubleTap = @"DoubleTap";
+NSString *const MGLEventGestureTwoFingerSingleTap = @"TwoFingerTap";
+NSString *const MGLEventGestureQuickZoom = @"QuickZoom";
+NSString *const MGLEventGesturePanStart = @"Pan";
+NSString *const MGLEventGesturePinchStart = @"Pinch";
+NSString *const MGLEventGestureRotateStart = @"Rotation";
+
+//
+// Threadsafety conventions:
+//
+// All variables accessed from more than one thread are
+// designated `atomic` and accessed through dot syntax. The
+// main thread uses underscore syntax during the
+// initialization of the variable.
+//
+// All variables accessed outside of initialization and
+// from within a single thread use underscore syntax.
+//
+// All captures of `self` from within asynchronous
+// dispatches will use a `weakSelf` to avoid cyclical
+// strong references.
+//
@interface MGLMapboxEvents()
-@property (atomic) NSMutableArray *queue;
-@property (atomic) NSString *instance;
-@property (atomic) NSString *anonid;
-@property (atomic) NSTimer *timer;
+// All of the following properties are written to only from
+// the main thread, but can be read on any thread.
+//
+@property (atomic) NSString *token;
+@property (atomic) NSString *appName;
+@property (atomic) NSString *appVersion;
+@property (atomic) NSString *instanceID;
+@property (atomic) NSString *advertiserId;
+@property (atomic) NSString *vendorId;
+@property (atomic) NSString *appBundleId;
@property (atomic) NSString *userAgent;
+@property (atomic) NSString *model;
+@property (atomic) NSString *iOSVersion;
+@property (atomic) NSString *carrier;
+@property (atomic) NSUInteger flushAt;
+@property (atomic) NSDateFormatter *rfc3339DateFormatter;
+@property (atomic) CGFloat scale;
+
+// The timer is only ever accessed from the main thread.
+//
+@property (nonatomic) NSTimer *timer;
+
+// The flush expiration time is only ever accessed from the main thread.
+//
+@property (nonatomic) NSTimeInterval flushAfter;
+
+// This is an array of events to push. All access to it will be
+// from our own serial queue.
+//
+@property (nonatomic) NSMutableArray *eventQueue;
+
+// This is a custom serial queue for accessing the event queue.
+//
+@property (nonatomic) dispatch_queue_t serialQueue;
@end
@implementation MGLMapboxEvents
-static MGLMapboxEvents *sharedManager = nil;
-
-NSDateFormatter *rfc3339DateFormatter = nil;
-NSString *model;
-NSString *iOSVersion;
-NSString *carrier;
-NSNumber *scale;
+// Must be called from the main thread. Only called internally.
+//
+- (instancetype) init {
+ assert([[NSThread currentThread] isMainThread]);
-- (id) init {
self = [super init];
if (self) {
@@ -45,6 +102,8 @@ NSNumber *scale;
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
} else {
+ // Dynamic Settings.bundle loading based on:
+ // http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
@@ -57,14 +116,19 @@ NSNumber *scale;
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}
-
+ _appBundleId = [[NSBundle mainBundle] bundleIdentifier];
+ NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString];
+ _serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL);
+
// Configure Events Infrastructure
- _queue = [[NSMutableArray alloc] init];
+ _eventQueue = [[NSMutableArray alloc] init];
_flushAt = 20;
- _flushAfter = 10000;
- _api = @"https://api.tiles.mapbox.com";
+ _flushAfter = 60;
_token = nil;
- _instance = [[NSUUID UUID] UUIDString];
+ _instanceID = [[NSUUID UUID] UUIDString];
+ // Dynamic detection of ASIdentifierManager from Mixpanel
+ // https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE
+ _advertiserId = @"";
Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
if (ASIdentifierManagerClass) {
SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager");
@@ -75,232 +139,348 @@ NSNumber *scale;
if (trackingEnabled) {
SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier");
NSUUID *uuid = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector);
- _anonid = [uuid UUIDString];
- } else {
- _anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
+ _advertiserId = [uuid UUIDString];
}
- } else {
- _anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
+ _vendorId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
- model = [self getSysInfoByName:"hw.machine"];
- iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion];
+ _model = [self getSysInfoByName:"hw.machine"];
+ _iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion];
if ([UIScreen instancesRespondToSelector:@selector(nativeScale)]) {
- scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].nativeScale];
+ _scale = [UIScreen mainScreen].nativeScale;
} else {
- scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].scale];
+ _scale = [UIScreen mainScreen].scale;
}
CTCarrier *carrierVendor = [[[CTTelephonyNetworkInfo alloc] init] subscriberCellularProvider];
- carrier = [carrierVendor carrierName];
+ _carrier = [carrierVendor carrierName];
- _userAgent = @"MapboxEventsiOS/1.0";
+ _userAgent = MGLMapboxEventsUserAgent;
// Setup Date Format
- rfc3339DateFormatter = [[NSDateFormatter alloc] init];
+ _rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
- [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
- [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
- [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
+ [_rfc3339DateFormatter setLocale:enUSPOSIXLocale];
+ [_rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
+ [_rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return self;
}
-+ (id)sharedManager {
+// Can be called from any thread. Called implicitly from any
+// public class convenience methods.
+//
++ (instancetype)sharedManager {
static dispatch_once_t onceToken;
+ static MGLMapboxEvents *_sharedManager;
dispatch_once(&onceToken, ^{
- sharedManager = [[self alloc] init];
+ void (^setupBlock)() = ^{
+ _sharedManager = [[self alloc] init];
+ // setup dedicated location manager on first use
+ [MGLMetricsLocationManager sharedManager];
+ };
+ if ( ! [[NSThread currentThread] isMainThread]) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ setupBlock();
+ });
+ } else {
+ setupBlock();
+ }
});
- return sharedManager;
+ return _sharedManager;
}
+// Must be called from the main thread.
+//
++ (void) setToken:(NSString *)token {
+ assert([[NSThread currentThread] isMainThread]);
+ [MGLMapboxEvents sharedManager].token = token;
+}
+
+// Must be called from the main thread.
+//
++ (void) setAppName:(NSString *)appName {
+ assert([[NSThread currentThread] isMainThread]);
+ [MGLMapboxEvents sharedManager].appName = appName;
+}
+
+// Must be called from the main thread.
+//
++ (void) setAppVersion:(NSString *)appVersion {
+ assert([[NSThread currentThread] isMainThread]);
+ [MGLMapboxEvents sharedManager].appVersion = appVersion;
+}
+
+// Can be called from any thread. Can be called rapidly from
+// the UI thread, so performance is paramount.
+//
++ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
+ [[MGLMapboxEvents sharedManager] pushEvent:event withAttributes:attributeDictionary];
+ });
+}
+
+// Can be called from any thread. Called implicitly from public
+// use of +pushEvent:withAttributes:.
+//
- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
-
- // Opt Out Checking When Built
- if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) {
- NSLog(@"Mapbox Metrics are not enabled, so clear any currently stored events, and return without sending in data.");
- [_queue removeAllObjects];
- return;
- }
+ __weak MGLMapboxEvents *weakSelf = self;
- // Add Metrics Disabled App Wide Check
- if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) {
- NSLog(@"Mapbox Metrics have been disabled for this app.");
- [_queue removeAllObjects];
- return;
- }
-
- if (!event) {
- return;
- }
-
- NSMutableDictionary *evt = [[NSMutableDictionary alloc] init];
- // mapbox-events stock attributes
- [evt setObject:event forKey:@"event"];
- [evt setObject:[NSNumber numberWithInt:1] forKey:@"version"];
- [evt setObject:[self formatDate:[NSDate date]] forKey:@"created"];
- [evt setObject:self.instance forKey:@"instance"];
- [evt setObject:self.anonid forKey:@"anonid"];
-
- // mapbox-events-ios stock attributes
- [evt setValue:[rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"deviceTimestamp"];
- [evt setValue:model forKey:@"model"];
- [evt setValue:iOSVersion forKey:@"operatingSystem"];
- [evt setValue:[self getDeviceOrientation] forKey:@"orientation"];
- [evt setValue:[[NSNumber alloc] initWithFloat:(100 * [UIDevice currentDevice].batteryLevel)] forKey:@"batteryLevel"];
- [evt setValue:scale forKey:@"resolution"];
- [evt setValue:carrier forKey:@"carrier"];
- [evt setValue:[self getWifiNetworkName] forKey:@"wifi"];
- [evt setValue:[NSNumber numberWithInt:[self getContentSizeScale]] forKey:@"accessibilityFontScale"];
-
- for (NSString *key in [attributeDictionary allKeys]) {
- [evt setObject:[attributeDictionary valueForKey:key] forKey:key];
- }
-
- // Make Immutable Version
- NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt];
-
- // Put On The Queue
- [self.queue addObject:finalEvent];
-
- // Has Flush Limit Been Reached?
- if ((int)_queue.count >= (int)_flushAt) {
- [self flush];
- }
-
- // Reset Timer (Initial Starting of Timer after first event is pushed)
- [self startTimer];
+ dispatch_async(_serialQueue, ^{
+ // Opt Out Checking When Built
+ if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) {
+ [_eventQueue removeAllObjects];
+ return;
+ }
+
+ // Add Metrics Disabled App Wide Check
+ if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) {
+ [_eventQueue removeAllObjects];
+ return;
+ }
+
+ if (!event) return;
+
+ NSMutableDictionary *evt = [[NSMutableDictionary alloc] initWithDictionary:attributeDictionary];
+ // mapbox-events stock attributes
+ [evt setObject:event forKey:@"event"];
+ [evt setObject:@(1) forKey:@"version"];
+ [evt setObject:[weakSelf formatDate:[NSDate date]] forKey:@"created"];
+ [evt setObject:weakSelf.instanceID forKey:@"instance"];
+ [evt setObject:weakSelf.advertiserId forKey:@"advertiserId"];
+ [evt setObject:weakSelf.vendorId forKey:@"vendorId"];
+ [evt setObject:weakSelf.appBundleId forKeyedSubscript:@"appBundleId"];
+
+ // mapbox-events-ios stock attributes
+ [evt setValue:[weakSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"];
+ [evt setValue:weakSelf.model forKey:@"model"];
+ [evt setValue:weakSelf.iOSVersion forKey:@"operatingSystem"];
+ [evt setValue:[weakSelf getDeviceOrientation] forKey:@"orientation"];
+ [evt setValue:@(100 * [UIDevice currentDevice].batteryLevel) forKey:@"batteryLevel"];
+ [evt setValue:@(weakSelf.scale) forKey:@"resolution"];
+ [evt setValue:weakSelf.carrier forKey:@"carrier"];
+ [evt setValue:[weakSelf getCurrentCellularNetworkConnectionType] forKey:@"cellularNetworkType"];
+ [evt setValue:[weakSelf getWifiNetworkName] forKey:@"wifi"];
+ [evt setValue:@([weakSelf getContentSizeScale]) forKey:@"accessibilityFontScale"];
+
+ // Make Immutable Version
+ NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt];
+
+ // Put On The Queue
+ [_eventQueue addObject:finalEvent];
+
+ // Has Flush Limit Been Reached?
+ if (_eventQueue.count >= weakSelf.flushAt) {
+ [weakSelf flush];
+ }
+
+ // Reset Timer (Initial Starting of Timer after first event is pushed)
+ [weakSelf startTimer];
+ });
}
+// Can be called from any thread.
+//
++ (void) flush {
+ [[MGLMapboxEvents sharedManager] flush];
+}
+
+// Can be called from any thread.
+//
- (void) flush {
- if (_token == nil) {
- NSLog(@"token hasn't been set yet, so no events can be sent. return");
- return;
- }
-
- int upper = (int)_flushAt;
- if (_flushAt > [_queue count]) {
- if ([_queue count] == 0) {
- return;
+ if (self.token == nil) return;
+
+ __weak MGLMapboxEvents *weakSelf = self;
+
+ dispatch_async(_serialQueue, ^{
+ __block NSArray *events;
+
+ NSUInteger upper = weakSelf.flushAt;
+ if (weakSelf.flushAt > [_eventQueue count]) {
+ if ([_eventQueue count] == 0) {
+ return;
+ }
+ upper = [_eventQueue count];
}
- upper = (int)[_queue count];
- }
-
- // Create Array of Events to push to the Server
- NSRange theRange = NSMakeRange(0, upper);
- NSArray *events = [_queue subarrayWithRange:theRange];
- // Update Queue to remove events sent to server
- [_queue removeObjectsInRange:theRange];
-
- // Send Array of Events to Server
- [self postEvents:events];
+ // Create Array of Events to push to the Server
+ NSRange theRange = NSMakeRange(0, upper);
+ events = [_eventQueue subarrayWithRange:theRange];
+ // Update Queue to remove events sent to server
+ [_eventQueue removeObjectsInRange:theRange];
+
+ // Send Array of Events to Server
+ [weakSelf postEvents:events];
+ });
}
+// Can be called from any thread. Called implicitly from public
+// use of +flush. Posts an async network request to upload metrics.
+//
- (void) postEvents:(NSArray *)events {
- // Setup URL Request
- NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", _api, _token];
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
- [request setValue:[self getUserAgent] forHTTPHeaderField:@"User-Agent"];
- [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
- [request setHTTPMethod:@"POST"];
-
- // Convert Array of Dictionaries to JSON
- if ([NSJSONSerialization isValidJSONObject:events]) {
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil];
- [request setHTTPBody:jsonData];
+ __weak MGLMapboxEvents *weakSelf = self;
+
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
+ // Setup URL Request
+ NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, weakSelf.token];
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
+ [request setValue:[weakSelf getUserAgent] forHTTPHeaderField:@"User-Agent"];
+ [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
+ [request setHTTPMethod:@"POST"];
- // Send non blocking HTTP Request to server
- [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:nil];
- }
+ // Convert Array of Dictionaries to JSON
+ if ([NSJSONSerialization isValidJSONObject:events]) {
+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil];
+ [request setHTTPBody:jsonData];
+
+ // Send non blocking HTTP Request to server
+ [NSURLConnection sendAsynchronousRequest:request
+ queue:nil
+ completionHandler:nil];
+ }
+ });
}
+// Can be called from any thread.
+//
- (void) startTimer {
- // Stop Timer if it already exists
- if (_timer) {
- [_timer invalidate];
- _timer = nil;
+ void (^timerBlock)() = ^{
+ // Stop Timer if it already exists
+ if (_timer) {
+ [_timer invalidate];
+ _timer = nil;
+ }
+
+ // Start New Timer
+ _timer = [NSTimer scheduledTimerWithTimeInterval:_flushAfter
+ target:[self class]
+ selector:@selector(flush)
+ userInfo:nil
+ repeats:YES];
+ };
+
+ if ( ! [[NSThread currentThread] isMainThread]) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ timerBlock();
+ });
+ } else {
+ timerBlock();
}
-
- // Start New Timer
- NSTimeInterval interval = (double)((NSInteger)_flushAfter);
- _timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(flush) userInfo:nil repeats:YES];
}
+// Can be called from any thread.
+//
- (NSString *) getUserAgent {
-
- if (_appName != nil && _appVersion != nil && ([_userAgent rangeOfString:_appName].location == NSNotFound)) {
- _userAgent = [NSString stringWithFormat:@"%@/%@ %@", _appName, _appVersion, _userAgent];
+ if (self.appName != nil && self.appVersion != nil && ([self.userAgent rangeOfString:self.appName].location == NSNotFound)) {
+ self.userAgent = [NSString stringWithFormat:@"%@/%@ %@", self.appName, self.appVersion, self.userAgent];
}
- return _userAgent;
+ return self.userAgent;
}
+// Can be called from any thread.
+//
- (NSString *) formatDate:(NSDate *)date {
- return [rfc3339DateFormatter stringFromDate:date];
+ return [self.rfc3339DateFormatter stringFromDate:date];
}
+// Can be called from any thread.
+//
- (NSString *) getDeviceOrientation {
- switch ([UIDevice currentDevice].orientation) {
- case UIDeviceOrientationUnknown:
- return @"Unknown";
- break;
- case UIDeviceOrientationPortrait:
- return @"Portrait";
- break;
- case UIDeviceOrientationPortraitUpsideDown:
- return @"PortraitUpsideDown";
- break;
- case UIDeviceOrientationLandscapeLeft:
- return @"LandscapeLeft";
- break;
- case UIDeviceOrientationLandscapeRight:
- return @"LandscapeRight";
- break;
- case UIDeviceOrientationFaceUp:
- return @"FaceUp";
- break;
- case UIDeviceOrientationFaceDown:
- return @"FaceDown";
- break;
- default:
- return @"Default - Unknown";
- break;
+ __block NSString *result;
+
+ NSString *(^deviceOrientationBlock)(void) = ^{
+ switch ([UIDevice currentDevice].orientation) {
+ case UIDeviceOrientationUnknown:
+ result = @"Unknown";
+ break;
+ case UIDeviceOrientationPortrait:
+ result = @"Portrait";
+ break;
+ case UIDeviceOrientationPortraitUpsideDown:
+ result = @"PortraitUpsideDown";
+ break;
+ case UIDeviceOrientationLandscapeLeft:
+ result = @"LandscapeLeft";
+ break;
+ case UIDeviceOrientationLandscapeRight:
+ result = @"LandscapeRight";
+ break;
+ case UIDeviceOrientationFaceUp:
+ result = @"FaceUp";
+ break;
+ case UIDeviceOrientationFaceDown:
+ result = @"FaceDown";
+ break;
+ default:
+ result = @"Default - Unknown";
+ break;
+ }
+
+ return result;
+ };
+
+ if ( ! [[NSThread currentThread] isMainThread]) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ result = deviceOrientationBlock();
+ });
+ } else {
+ result = deviceOrientationBlock();
}
+
+ return result;
}
-- (int) getContentSizeScale {
- NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory;
-
- if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) {
- return -3;
- } else if ([sc isEqualToString:UIContentSizeCategorySmall]) {
- return -2;
- } else if ([sc isEqualToString:UIContentSizeCategoryMedium]) {
- return -1;
- } else if ([sc isEqualToString:UIContentSizeCategoryLarge]) {
- return 0;
- } else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) {
- return 1;
- } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
- return 2;
- } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
- return 3;
- } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
- return -11;
- } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
- return 10;
- } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
- return 11;
- } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
- return 12;
- } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
- return 13;
+// Can be called from any thread.
+//
+- (NSInteger) getContentSizeScale {
+ __block NSInteger result = -9999;
+
+ NSInteger (^contentSizeScaleBlock)(void) = ^{
+ NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory;
+
+ if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) {
+ result = -3;
+ } else if ([sc isEqualToString:UIContentSizeCategorySmall]) {
+ result = -2;
+ } else if ([sc isEqualToString:UIContentSizeCategoryMedium]) {
+ result = -1;
+ } else if ([sc isEqualToString:UIContentSizeCategoryLarge]) {
+ result = 0;
+ } else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) {
+ result = 1;
+ } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
+ result = 2;
+ } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
+ result = 3;
+ } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
+ result = -11;
+ } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
+ result = 10;
+ } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
+ result = 11;
+ } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
+ result = 12;
+ } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
+ result = 13;
+ }
+
+ return result;
+ };
+
+ if ( ! [[NSThread currentThread] isMainThread]) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ result = contentSizeScaleBlock();
+ });
+ } else {
+ result = contentSizeScaleBlock();
}
- return -9999;
-}
+ return result;
+}
+// Can be called from any thread.
+//
- (NSString *)getSysInfoByName:(char *)typeSpecifier
{
size_t size;
@@ -315,6 +495,8 @@ NSNumber *scale;
return results;
}
+// Can be called from any thread.
+//
- (NSString *) getWifiNetworkName {
NSString *ssid = @"";
@@ -324,14 +506,80 @@ NSNumber *scale;
if (info) {
ssid = info[@"SSID"];
} else {
- ssid = @"<<NONE>>";
+ ssid = @"NONE";
}
} else {
- ssid = @"<<NONE>>";
+ ssid = @"NONE";
}
return ssid;
}
+// Can be called from any thread.
+//
+- (NSString *) getCurrentCellularNetworkConnectionType {
+ CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
+ NSString *radioTech = telephonyInfo.currentRadioAccessTechnology;
+
+ if (radioTech == nil) {
+ return @"NONE";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyGPRS]) {
+ return @"GPRS";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyEdge]) {
+ return @"EDGE";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyWCDMA]) {
+ return @"WCDMA";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSDPA]) {
+ return @"HSDPA";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSUPA]) {
+ return @"HSUPA";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
+ return @"CDMA1x";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) {
+ return @"CDMAEVDORev0";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) {
+ return @"CDMAEVDORevA";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
+ return @"CDMAEVDORevB";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyeHRPD]) {
+ return @"HRPD";
+ } else if ([radioTech isEqualToString:CTRadioAccessTechnologyLTE]) {
+ return @"LTE";
+ } else {
+ return @"Unknown";
+ }
+}
+
+// Can be called from any thread.
+//
++ (BOOL) checkPushEnabled {
+ BOOL (^pushCheckBlock)(void) = ^{
+ BOOL blockResult;
+ if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) {
+ // iOS 8+
+ blockResult = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
+ } else {
+ // iOS 7
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
+ blockResult = (types == UIRemoteNotificationTypeNone) ? NO : YES;
+#pragma clang diagnostic pop
+ }
+ return blockResult;
+ };
+
+ __block BOOL result;
-@end \ No newline at end of file
+ if ( ! [[NSThread currentThread] isMainThread]) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ result = pushCheckBlock();
+ });
+ } else {
+ result = pushCheckBlock();
+ }
+
+ return result;
+}
+
+@end
diff --git a/platform/ios/MGLMetricsLocationManager.m b/platform/ios/MGLMetricsLocationManager.m
index 5eac0370dc..c0ff740b3a 100644
--- a/platform/ios/MGLMetricsLocationManager.m
+++ b/platform/ios/MGLMetricsLocationManager.m
@@ -1,48 +1,18 @@
-//
-// MBLocationManager.m
-// Hermes
-//
-// Dynamic Settings.bundle loading based on:
-// http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the
-//
-// Created by Brad Leege on 3/8/15.
-// Copyright (c) 2015 Mapbox. All rights reserved.
-//
-
-#import "MGLMetricsLocationManager.h"
-#import "CoreLocation/CoreLocation.h"
#import "MGLMapboxEvents.h"
+#import "MGLMetricsLocationManager.h"
-@interface MGLMetricsLocationManager()
+#import <CoreLocation/CoreLocation.h>
-@property (atomic) CLLocationManager *locationManager;
+@interface MGLMetricsLocationManager() <CLLocationManagerDelegate>
+
+@property (nonatomic) CLLocationManager *locationManager;
@end
@implementation MGLMetricsLocationManager
-static MGLMetricsLocationManager *sharedManager = nil;
-
-- (id) init {
+- (instancetype) init {
if (self = [super init]) {
-
- NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
- if(!settingsBundle) {
- NSLog(@"Could not find Settings.bundle");
- } else {
- NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
- NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
- NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
- for(NSDictionary *prefSpecification in preferences) {
- NSString *key = [prefSpecification objectForKey:@"Key"];
- if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) {
- [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
- }
- }
-
- [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
- }
-
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = 2;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
@@ -52,46 +22,31 @@ static MGLMetricsLocationManager *sharedManager = nil;
return self;
}
-+ (id)sharedManager {
++ (instancetype)sharedManager {
static dispatch_once_t onceToken;
+ static MGLMetricsLocationManager *sharedManager;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
-- (BOOL) isAuthorizedStatusDetermined {
- return ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined);
-}
-
-- (void) requestAlwaysAuthorization {
- if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
- [self.locationManager requestAlwaysAuthorization];
- } else {
- // This is iOS 7 or below so Starting Location Updates will trigger authorization request
- [self startUpdatingLocation];
- }
-}
-
-- (void) startUpdatingLocation {
- [self.locationManager startUpdatingLocation];
++ (void) startUpdatingLocation {
+ [[MGLMetricsLocationManager sharedManager].locationManager startUpdatingLocation];
}
-- (void) stopUpdatingLocation {
- [self.locationManager stopUpdatingLocation];
++ (void) stopUpdatingLocation {
+ [[MGLMetricsLocationManager sharedManager].locationManager stopUpdatingLocation];
}
#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
- CLLocation *loc = (CLLocation *)[locations objectAtIndex:0];
- NSLog(@"didUpdateLocations() called with %lu location in array. First Location = %f, %f", (unsigned long)locations.count, loc.coordinate.latitude, loc.coordinate.longitude);
-
// Iterate through locations to pass all data
for (CLLocation *loc in locations) {
- NSMutableDictionary *evt = [[NSMutableDictionary alloc] init];
- [evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.latitude] forKey:@"lat"];
- [evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.longitude] forKey:@"lng"];
- [[MGLMapboxEvents sharedManager] pushEvent:@"location" withAttributes:evt];
+ [MGLMapboxEvents pushEvent:MGLEventTypeLocation withAttributes:@{
+ MGLEventKeyLatitude: @(loc.coordinate.latitude),
+ MGLEventKeyLongitude: @(loc.coordinate.longitude)
+ }];
}
}
@@ -106,24 +61,23 @@ static MGLMetricsLocationManager *sharedManager = nil;
break;
case kCLAuthorizationStatusDenied:
newStatus = @"User Explcitly Denied";
- [[MGLMetricsLocationManager sharedManager] stopUpdatingLocation];
+ [MGLMetricsLocationManager stopUpdatingLocation];
break;
case kCLAuthorizationStatusAuthorized:
newStatus = @"User Has Authorized / Authorized Always";
- [[MGLMetricsLocationManager sharedManager] startUpdatingLocation];
+ [MGLMetricsLocationManager startUpdatingLocation];
break;
// case kCLAuthorizationStatusAuthorizedAlways:
// newStatus = @"Not Determined";
// break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
newStatus = @"User Has Authorized When In Use Only";
- [[MGLMetricsLocationManager sharedManager] startUpdatingLocation];
+ [MGLMetricsLocationManager startUpdatingLocation];
break;
default:
newStatus = @"Unknown";
break;
}
- NSLog(@"MGLMetricsLocationManager didChangeAuthorizationStatus() called. New Status = %@", newStatus);
}
@end
diff --git a/platform/ios/MGLStyleFunctionValue.m b/platform/ios/MGLStyleFunctionValue.m
deleted file mode 100644
index a319114eef..0000000000
--- a/platform/ios/MGLStyleFunctionValue.m
+++ /dev/null
@@ -1,190 +0,0 @@
-#import "MGLStyleFunctionValue.h"
-
-#import "MGLTypes.h"
-
-@interface MGLStyleFunctionValue ()
-
-@property (nonatomic) NSString *functionType;
-@property (nonatomic) NSDictionary *stops;
-@property (nonatomic) CGFloat zBase;
-@property (nonatomic) CGFloat val;
-@property (nonatomic) CGFloat slope;
-@property (nonatomic) CGFloat min;
-@property (nonatomic) CGFloat max;
-@property (nonatomic) CGFloat minimumZoom;
-@property (nonatomic) CGFloat maximumZoom;
-
-- (NSDictionary *)rawStyle;
-
-@end
-
-@implementation MGLStyleFunctionValue
-
-- (id)initWithFunctionType:(NSString *)functionType
- stops:(NSDictionary *)stops
- zBase:(CGFloat)zBase
- val:(CGFloat)val
- slope:(CGFloat)slope
- min:(CGFloat)min
- max:(CGFloat)max
- minimumZoom:(CGFloat)minimumZoom
- maximumZoom:(CGFloat)maximumZoom
-{
- self = [super init];
-
- if (self)
- {
- _functionType = functionType;
- _stops = stops;
- _zBase = zBase;
- _val = val;
- _slope = slope;
- _min = min;
- _max = max;
- _minimumZoom = minimumZoom;
- _maximumZoom = maximumZoom;
- }
-
- return self;
-}
-
-- (id)rawStyle
-{
- if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMinimumZoom])
- {
- return @[ @"min", @(self.minimumZoom) ];
- }
- else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMaximumZoom])
- {
- return @[ @"max", @(self.maximumZoom) ];
- }
- else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionLinear])
- {
- return @[ @"linear", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ];
- }
- else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionExponential])
- {
- return @[ @"exponential", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ];
- }
- else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionStops])
- {
- NSMutableArray *returnArray = [NSMutableArray array];
-
- for (NSNumber *z in [self.stops allKeys])
- {
- [returnArray addObject:@{ @"z" : z, @"val" : self.stops[z] }];
- }
-
- [returnArray insertObject:@"stops" atIndex:0];
-
- return returnArray;
- }
-
- return nil;
-}
-
-+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ...
-{
- NSMutableArray *numbersArray = [NSMutableArray array];
-
- va_list args;
- va_start(args, firstZoom);
-
- for (NSNumber *arg = firstZoom; arg != nil; arg = va_arg(args, NSNumber *))
- {
- [numbersArray addObject:arg];
- }
-
- va_end(args);
-
- NSAssert([numbersArray count] % 2 == 0, @"invalid number of arguments");
-
- NSMutableDictionary *stops = [NSMutableDictionary dictionary];
-
- for (NSUInteger i = 0; i < [numbersArray count]; i = i + 2)
- {
- stops[numbersArray[i]] = stops[numbersArray[i + 1]];
- }
-
- return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionStops
- stops:stops
- zBase:0
- val:0
- slope:0
- min:0
- max:0
- minimumZoom:0
- maximumZoom:0];
-}
-
-+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase
- initialValue:(CGFloat)val
- slope:(CGFloat)slope
- minimumValue:(CGFloat)min
- maximumValue:(CGFloat)max
-{
- NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level");
- NSAssert(min < max, @"minimum value must be less than maximum value");
-
- return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionLinear
- stops:nil
- zBase:zBase
- val:val
- slope:slope
- min:min
- max:max
- minimumZoom:0
- maximumZoom:0];
-}
-
-+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase
- initialValue:(CGFloat)val
- slope:(CGFloat)slope
- minimumValue:(CGFloat)min
- maximumValue:(CGFloat)max
-{
- NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level");
- NSAssert(min < max, @"minimum value must be less than maximum value");
-
- return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionExponential
- stops:nil
- zBase:zBase
- val:val
- slope:slope
- min:min
- max:max
- minimumZoom:0
- maximumZoom:0];
-}
-
-+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom
-{
- NSAssert(minimumZoom >= 0 && minimumZoom <= 18, @"invalid minimum zoom value");
-
- return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMinimumZoom
- stops:nil
- zBase:0
- val:0
- slope:0
- min:0
- max:0
- minimumZoom:minimumZoom
- maximumZoom:0];
-}
-
-+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom
-{
- NSAssert(maximumZoom >= 0 && maximumZoom <= 18, @"invalid maximum zoom value");
-
- return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMaximumZoom
- stops:nil
- zBase:0
- val:0
- slope:0
- min:0
- max:0
- minimumZoom:0
- maximumZoom:maximumZoom];
-}
-
-@end
diff --git a/platform/ios/MGLTypes.m b/platform/ios/MGLTypes.m
deleted file mode 100644
index 2928bc2f4c..0000000000
--- a/platform/ios/MGLTypes.m
+++ /dev/null
@@ -1,24 +0,0 @@
-#import "MGLTypes.h"
-
-NSString *const MGLStyleKeyGeneric = @"MGLStyleKeyGeneric";
-NSString *const MGLStyleKeyFill = @"MGLStyleKeyFill";
-NSString *const MGLStyleKeyLine = @"MGLStyleKeyLine";
-NSString *const MGLStyleKeyIcon = @"MGLStyleKeyIcon";
-NSString *const MGLStyleKeyText = @"MGLStyleKeyText";
-NSString *const MGLStyleKeyRaster = @"MGLStyleKeyRaster";
-NSString *const MGLStyleKeyComposite = @"MGLStyleKeyComposite";
-NSString *const MGLStyleKeyBackground = @"MGLStyleKeyBackground";
-
-NSString *const MGLStyleValueTypeBoolean = @"MGLStyleValueTypeBoolean";
-NSString *const MGLStyleValueTypeNumber = @"MGLStyleValueTypeNumber";
-NSString *const MGLStyleValueTypeNumberPair = @"MGLStyleValueTypeNumberPair";
-NSString *const MGLStyleValueTypeColor = @"MGLStyleValueTypeColor";
-NSString *const MGLStyleValueTypeString = @"MGLStyleValueTypeString";
-
-NSString *const MGLStyleValueFunctionAllowed = @"MGLStyleValueFunctionAllowed";
-
-NSString *const MGLStyleValueTypeFunctionMinimumZoom = @"MGLStyleValueTypeFunctionMinimumZoom";
-NSString *const MGLStyleValueTypeFunctionMaximumZoom = @"MGLStyleValueTypeFunctionMaximumZoom";
-NSString *const MGLStyleValueTypeFunctionLinear = @"MGLStyleValueTypeFunctionLinear";
-NSString *const MGLStyleValueTypeFunctionExponential = @"MGLStyleValueTypeFunctionExponential";
-NSString *const MGLStyleValueTypeFunctionStops = @"MGLStyleValueTypeFunctionStops";
diff --git a/platform/ios/MGLUserLocation.m b/platform/ios/MGLUserLocation.m
new file mode 100644
index 0000000000..054dfa686d
--- /dev/null
+++ b/platform/ios/MGLUserLocation.m
@@ -0,0 +1,57 @@
+#import "MGLUserLocation_Private.h"
+
+@implementation MGLUserLocation
+{
+ CLLocationCoordinate2D _coordinate;
+}
+
+@synthesize coordinate = _coordinate;
+
+- (instancetype)init
+{
+ if (self = [super init])
+ {
+ _coordinate = CLLocationCoordinate2DMake(MAXFLOAT, MAXFLOAT);
+ }
+
+ return self;
+}
+
++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
+{
+ return ! [key isEqualToString:@"location"] && ! [key isEqualToString:@"heading"];
+}
+
++ (NSSet *)keyPathsForValuesAffectingCoordinate
+{
+ return [NSSet setWithObject:@"location"];
+}
+
+- (void)setLocation:(CLLocation *)newLocation
+{
+ if ([newLocation distanceFromLocation:_location] && newLocation.coordinate.latitude != 0 &&
+ newLocation.coordinate.longitude != 0)
+ {
+ [self willChangeValueForKey:@"location"];
+ _location = newLocation;
+ _coordinate = _location.coordinate;
+ [self didChangeValueForKey:@"location"];
+ }
+}
+
+- (void)setHeading:(CLHeading *)newHeading
+{
+ if (newHeading.trueHeading != _heading.trueHeading)
+ {
+ [self willChangeValueForKey:@"heading"];
+ _heading = newHeading;
+ [self didChangeValueForKey:@"heading"];
+ }
+}
+
+- (NSString *)title
+{
+ if ( ! _title) return @"Current Location";
+}
+
+@end
diff --git a/platform/ios/MGLUserLocationAnnotationView.h b/platform/ios/MGLUserLocationAnnotationView.h
new file mode 100644
index 0000000000..c72d64ed8f
--- /dev/null
+++ b/platform/ios/MGLUserLocationAnnotationView.h
@@ -0,0 +1,18 @@
+#import <UIKit/UIKit.h>
+#import <CoreLocation/CoreLocation.h>
+
+#import "MGLUserLocation.h"
+
+@class MGLMapView;
+
+/** The MGLUserLocationAnnotationView class defines a specific type of annotation that identifies the user’s current location. You do not create instances of this class directly. Instead, you retrieve an existing MGLUserLocationAnnotationView object from the userLocation property of the map view displayed in your application. */
+@interface MGLUserLocationAnnotationView : UIView
+
+@property (nonatomic, weak) MGLMapView *mapView;
+@property (nonatomic) MGLUserLocation *annotation;
+@property (nonatomic, readonly) CALayer *haloLayer;
+
+- (instancetype)initInMapView:(MGLMapView *)mapView;
+- (void)setupLayers;
+
+@end
diff --git a/platform/ios/MGLUserLocationAnnotationView.m b/platform/ios/MGLUserLocationAnnotationView.m
new file mode 100644
index 0000000000..18c98bf1d0
--- /dev/null
+++ b/platform/ios/MGLUserLocationAnnotationView.m
@@ -0,0 +1,197 @@
+#import "MGLUserLocationAnnotationView.h"
+
+#import "MGLUserLocation_Private.h"
+#import "MGLAnnotation.h"
+#import "MGLMapView.h"
+
+const CGFloat MGLTrackingDotRingWidth = 24.0;
+
+@interface MGLUserLocationAnnotationView ()
+
+@property (nonatomic, readwrite) CALayer *haloLayer;
+
+@end
+
+#pragma mark -
+
+@implementation MGLUserLocationAnnotationView
+{
+ CALayer *_accuracyRingLayer;
+ CALayer *_dotBorderLayer;
+ CALayer *_dotLayer;
+}
+
+- (instancetype)initInMapView:(MGLMapView *)mapView
+{
+ if (self = [super init])
+ {
+ self.annotation = [[MGLUserLocation alloc] init];
+ _mapView = mapView;
+ [self setupLayers];
+ }
+ return self;
+}
+
+- (void)setTintColor:(UIColor *)tintColor
+{
+ UIImage *trackingDotHaloImage = [self trackingDotHaloImage];
+ _haloLayer.bounds = CGRectMake(0, 0, trackingDotHaloImage.size.width, trackingDotHaloImage.size.height);
+ _haloLayer.contents = (__bridge id)[trackingDotHaloImage CGImage];
+
+ UIImage *dotImage = [self dotImage];
+ _dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height);
+ _dotLayer.contents = (__bridge id)[dotImage CGImage];
+}
+
+- (void)setupLayers
+{
+ if (CLLocationCoordinate2DIsValid(self.annotation.coordinate))
+ {
+ if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy)
+ {
+ UIImage *accuracyRingImage = [self accuracyRingImage];
+ _accuracyRingLayer = [CALayer layer];
+ _haloLayer.bounds = CGRectMake(0, 0, accuracyRingImage.size.width, accuracyRingImage.size.height);
+ _haloLayer.contents = (__bridge id)[accuracyRingImage CGImage];
+ _haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
+
+ [self.layer addSublayer:_accuracyRingLayer];
+ }
+
+ if ( ! _haloLayer)
+ {
+ UIImage *haloImage = [self trackingDotHaloImage];
+ _haloLayer = [CALayer layer];
+ _haloLayer.bounds = CGRectMake(0, 0, haloImage.size.width, haloImage.size.height);
+ _haloLayer.contents = (__bridge id)[haloImage CGImage];
+ _haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
+
+ [CATransaction begin];
+
+ [CATransaction setAnimationDuration:3.5];
+ [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
+
+ // scale out radially
+ //
+ CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
+ boundsAnimation.repeatCount = MAXFLOAT;
+ boundsAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
+ boundsAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)];
+ boundsAnimation.removedOnCompletion = NO;
+
+ [_haloLayer addAnimation:boundsAnimation forKey:@"animateScale"];
+
+ // go transparent as scaled out
+ //
+ CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
+ opacityAnimation.repeatCount = MAXFLOAT;
+ opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
+ opacityAnimation.toValue = [NSNumber numberWithFloat:-1.0];
+ opacityAnimation.removedOnCompletion = NO;
+
+ [_haloLayer addAnimation:opacityAnimation forKey:@"animateOpacity"];
+
+ [CATransaction commit];
+
+ [self.layer addSublayer:_haloLayer];
+ }
+
+ // white dot background with shadow
+ //
+ if ( ! _dotBorderLayer)
+ {
+ CGRect rect = CGRectMake(0, 0, MGLTrackingDotRingWidth * 1.25, MGLTrackingDotRingWidth * 1.25);
+
+ UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
+ CGContextRef context = UIGraphicsGetCurrentContext();
+
+ CGContextSetShadow(context, CGSizeMake(0, 0), MGLTrackingDotRingWidth / 4.0);
+
+ CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
+ CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - MGLTrackingDotRingWidth) / 2.0, (rect.size.height - MGLTrackingDotRingWidth) / 2.0, MGLTrackingDotRingWidth, MGLTrackingDotRingWidth));
+
+ UIImage *whiteBackground = UIGraphicsGetImageFromCurrentImageContext();
+
+ UIGraphicsEndImageContext();
+
+ _dotBorderLayer = [CALayer layer];
+ _dotBorderLayer.bounds = CGRectMake(0, 0, whiteBackground.size.width, whiteBackground.size.height);
+ _dotBorderLayer.contents = (__bridge id)[whiteBackground CGImage];
+ _dotBorderLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
+ [self.layer addSublayer:_dotBorderLayer];
+ }
+
+ // pulsing, tinted dot sublayer
+ //
+ if ( ! _dotLayer)
+ {
+ UIImage *dotImage = [self dotImage];
+ _dotLayer = [CALayer layer];
+ _dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height);
+ _dotLayer.contents = (__bridge id)[dotImage CGImage];
+ _dotLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
+
+ CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
+ animation.repeatCount = MAXFLOAT;
+ animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)];
+ animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)];
+ animation.removedOnCompletion = NO;
+ animation.autoreverses = YES;
+ animation.duration = 1.5;
+ animation.beginTime = CACurrentMediaTime() + 1.0;
+ animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
+
+ [_dotLayer addAnimation:animation forKey:@"animateTransform"];
+
+ [self.layer addSublayer:_dotLayer];
+ }
+ }
+}
+
+- (UIImage *)accuracyRingImage
+{
+ CGFloat latRadians = self.annotation.coordinate.latitude * M_PI / 180.0f;
+ CGFloat pixelRadius = self.annotation.location.horizontalAccuracy / cos(latRadians) / [self.mapView metersPerPixelAtLatitude:self.annotation.coordinate.latitude];
+ UIGraphicsBeginImageContextWithOptions(CGSizeMake(pixelRadius * 2, pixelRadius * 2), NO, [[UIScreen mainScreen] scale]);
+
+ CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.7] CGColor]);
+ CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.15] CGColor]);
+ CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0);
+ CGContextStrokeEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, pixelRadius * 2, pixelRadius * 2));
+
+ UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
+ UIGraphicsEndImageContext();
+ return finalImage;
+}
+
+- (UIImage *)trackingDotHaloImage
+{
+ UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, [[UIScreen mainScreen] scale]);
+ CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[_mapView.tintColor colorWithAlphaComponent:0.75] CGColor]);
+ CGContextFillEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 100, 100));
+ UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
+ UIGraphicsEndImageContext();
+
+ return finalImage;
+}
+
+- (UIImage *)dotImage
+{
+ CGFloat tintedWidth = MGLTrackingDotRingWidth * 0.7;
+
+ CGRect rect = CGRectMake(0, 0, tintedWidth, tintedWidth);
+
+ UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
+ CGContextRef context = UIGraphicsGetCurrentContext();
+
+ CGContextSetFillColorWithColor(context, [_mapView.tintColor CGColor]);
+ CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - tintedWidth) / 2.0, (rect.size.height - tintedWidth) / 2.0, tintedWidth, tintedWidth));
+
+ UIImage *tintedForeground = UIGraphicsGetImageFromCurrentImageContext();
+
+ UIGraphicsEndImageContext();
+
+ return tintedForeground;
+}
+
+@end
diff --git a/platform/ios/MGLUserLocation_Private.h b/platform/ios/MGLUserLocation_Private.h
new file mode 100644
index 0000000000..d4f358bcbc
--- /dev/null
+++ b/platform/ios/MGLUserLocation_Private.h
@@ -0,0 +1,9 @@
+#import "MGLUserLocation.h"
+
+@interface MGLUserLocation (Private)
+
+@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
+@property (nonatomic, readwrite) CLLocation *location;
+@property (nonatomic, readwrite) CLHeading *heading;
+
+@end
diff --git a/platform/ios/NSArray+MGLAdditions.m b/platform/ios/NSArray+MGLAdditions.m
deleted file mode 100644
index 2bac42ce0b..0000000000
--- a/platform/ios/NSArray+MGLAdditions.m
+++ /dev/null
@@ -1,10 +0,0 @@
-#import "NSArray+MGLAdditions.h"
-
-@implementation NSArray (MGLAdditions)
-
-- (NSMutableArray *)deepMutableCopy
-{
- return (NSMutableArray *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)self, kCFPropertyListMutableContainersAndLeaves));
-}
-
-@end
diff --git a/platform/ios/NSDictionary+MGLAdditions.m b/platform/ios/NSDictionary+MGLAdditions.m
deleted file mode 100644
index 3228d56533..0000000000
--- a/platform/ios/NSDictionary+MGLAdditions.m
+++ /dev/null
@@ -1,10 +0,0 @@
-#import "NSDictionary+MGLAdditions.h"
-
-@implementation NSDictionary (MGLAdditions)
-
-- (NSMutableDictionary *)deepMutableCopy
-{
- return (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)self, kCFPropertyListMutableContainersAndLeaves));
-}
-
-@end
diff --git a/platform/ios/UIColor+MGLAdditions.m b/platform/ios/UIColor+MGLAdditions.m
deleted file mode 100644
index ae40735d15..0000000000
--- a/platform/ios/UIColor+MGLAdditions.m
+++ /dev/null
@@ -1,167 +0,0 @@
-#import "UIColor+MGLAdditions.h"
-
-/* Portions based on Erica Sadun's uicolor-utilities
- https://github.com/erica/uicolor-utilities */
-
-@interface UIColor (MGLAdditionsPrivate)
-
-+ (UIColor *)colorWithRGBHex:(UInt32)hex;
-- (CGColorSpaceModel)colorSpaceModel;
-- (BOOL)canProvideRGBComponents;
-- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha;
-- (UInt32)rgbHex;
-
-@end
-
-@implementation UIColor (MGLAdditions)
-
-+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString
-{
- UIColor *color;
-
- NSString *numberString = [rgbaString stringByReplacingOccurrencesOfString:@"rgba("
- withString:@""];
- numberString = [numberString stringByReplacingOccurrencesOfString:@"rgb("
- withString:@""];
- numberString = [numberString stringByReplacingOccurrencesOfString:@")"
- withString:@""];
-
- NSArray *numbers = [numberString componentsSeparatedByString:@","];
-
- if ([rgbaString hasPrefix:@"rgb("] && [numbers count] == 3)
- {
- color = [UIColor colorWithRed:[numbers[0] floatValue] / 255
- green:[numbers[1] floatValue] / 255
- blue:[numbers[2] floatValue] / 255
- alpha:1.0];
- }
- else if ([rgbaString hasPrefix:@"rgba("] && [numbers count] == 4)
- {
- color = [UIColor colorWithRed:[numbers[0] floatValue] / 255
- green:[numbers[1] floatValue] / 255
- blue:[numbers[2] floatValue] / 255
- alpha:[numbers[3] floatValue]];
- }
-
- return color;
-}
-
-- (NSString *)rgbaStringFromColor
-{
- CGFloat r,g,b,a;
-
- [self getRed:&r green:&g blue:&b alpha:&a];
-
- r *= 255;
- g *= 255;
- b *= 255;
- a *= 255;
-
- return [NSString stringWithFormat:@"rgba(%lu,%lu,%lu,%lu)", (unsigned long)r, (unsigned long)g, (unsigned long)b, (unsigned long)a];
-}
-
-+ (UIColor *)colorWithRGBHex:(UInt32)hex
-{
- int r = (hex >> 16) & 0xFF;
- int g = (hex >> 8) & 0xFF;
- int b = (hex) & 0xFF;
-
- return [UIColor colorWithRed:r / 255.0f
- green:g / 255.0f
- blue:b / 255.0f
- alpha:1.0f];
-}
-
-- (CGColorSpaceModel)colorSpaceModel
-{
- return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
-}
-
-- (BOOL)canProvideRGBComponents
-{
- switch (self.colorSpaceModel)
- {
- case kCGColorSpaceModelRGB:
- case kCGColorSpaceModelMonochrome:
- {
- return YES;
- }
- default:
- {
- return NO;
- }
- }
-}
-
-- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha
-{
- const CGFloat *components = CGColorGetComponents(self.CGColor);
-
- CGFloat r,g,b,a;
-
- switch (self.colorSpaceModel)
- {
- case kCGColorSpaceModelMonochrome:
- {
- r = g = b = components[0];
- a = components[1];
-
- break;
- }
- case kCGColorSpaceModelRGB:
- {
- r = components[0];
- g = components[1];
- b = components[2];
- a = components[3];
-
- break;
- }
- default:
- {
- return NO;
- }
- }
-
- if (red) *red = r;
- if (green) *green = g;
- if (blue) *blue = b;
- if (alpha) *alpha = a;
-
- return YES;
-}
-
-- (UInt32)rgbHex
-{
- NSAssert(self.canProvideRGBComponents, @"Must be a RGB color to use rgbHex");
-
- CGFloat r, g, b, a;
-
- if ( ! [self red:&r green:&g blue:&b alpha:&a])
- return 0;
-
- r = fminf(fmaxf(r, 0.0f), 1.0f);
- g = fminf(fmaxf(g, 0.0f), 1.0f);
- b = fminf(fmaxf(b, 0.0f), 1.0f);
-
- return (((int)roundf(r * 255)) << 16) | (((int)roundf(g * 255)) << 8) | (((int)roundf(b * 255)));
-}
-
-- (NSString *)hexStringFromColor
-{
- return [NSString stringWithFormat:@"%0.6X", (unsigned int)(self.rgbHex)];
-}
-
-+ (UIColor *)colorWithHexString:(NSString *)hexString
-{
- NSScanner *scanner = [NSScanner scannerWithString:[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]];
-
- unsigned hexNum;
-
- if ( ! [scanner scanHexInt:&hexNum])
- return nil;
-
- return [UIColor colorWithRGBHex:hexNum];
-}
-
-@end
diff --git a/platform/ios/resources/mapbox.png b/platform/ios/resources/mapbox.png
index 01b5596b67..5a9da3fe39 100644
--- a/platform/ios/resources/mapbox.png
+++ b/platform/ios/resources/mapbox.png
Binary files differ
diff --git a/platform/ios/resources/mapbox@2x.png b/platform/ios/resources/mapbox@2x.png
index ff4ef2558b..194aa64da2 100644
--- a/platform/ios/resources/mapbox@2x.png
+++ b/platform/ios/resources/mapbox@2x.png
Binary files differ
diff --git a/platform/ios/resources/mapbox@3x.png b/platform/ios/resources/mapbox@3x.png
index 5a2afcb17b..d1260a16f3 100644
--- a/platform/ios/resources/mapbox@3x.png
+++ b/platform/ios/resources/mapbox@3x.png
Binary files differ
diff --git a/platform/ios/vendor/SMCalloutView b/platform/ios/vendor/SMCalloutView
new file mode 160000
+Subproject 717078fb6b0d02b944a12f4d40fc15567489d23
diff --git a/src/mbgl/geometry/line_atlas.cpp b/src/mbgl/geometry/line_atlas.cpp
index 507cc7b087..f64989d661 100644
--- a/src/mbgl/geometry/line_atlas.cpp
+++ b/src/mbgl/geometry/line_atlas.cpp
@@ -4,6 +4,8 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
+#include <boost/functional/hash.hpp>
+
#include <sstream>
#include <cmath>
@@ -26,21 +28,22 @@ LineAtlas::~LineAtlas() {
}
LinePatternPos LineAtlas::getDashPosition(const std::vector<float> &dasharray, bool round) {
- std::lock_guard<std::recursive_mutex> lock(mtx);
-
- std::ostringstream sskey;
-
- for (const float &part : dasharray) {
- sskey << part << "-";
+ size_t key = round ? std::numeric_limits<size_t>::min() : std::numeric_limits<size_t>::max();
+ for (const float part : dasharray) {
+ boost::hash_combine<float>(key, part);
}
- sskey << round;
- std::string key = sskey.str();
- if (positions.find(key) == positions.end()) {
- positions[key] = addDash(dasharray, round);
- }
+ // Note: We're not handling hash collisions here.
- return positions[key];
+ std::lock_guard<std::recursive_mutex> lock(mtx);
+ const auto it = positions.find(key);
+ if (it == positions.end()) {
+ auto inserted = positions.emplace(key, addDash(dasharray, round));
+ assert(inserted.second);
+ return inserted.first->second;
+ } else {
+ return it->second;
+ }
}
LinePatternPos LineAtlas::addDash(const std::vector<float> &dasharray, bool round) {
@@ -55,7 +58,7 @@ LinePatternPos LineAtlas::addDash(const std::vector<float> &dasharray, bool roun
}
float length = 0;
- for (const float &part : dasharray) {
+ for (const float part : dasharray) {
length += part;
}
diff --git a/src/mbgl/geometry/line_atlas.hpp b/src/mbgl/geometry/line_atlas.hpp
index 191dc0c4d4..df60a2dec5 100644
--- a/src/mbgl/geometry/line_atlas.hpp
+++ b/src/mbgl/geometry/line_atlas.hpp
@@ -33,7 +33,7 @@ private:
std::atomic<bool> dirty;
uint32_t texture = 0;
int nextRow = 0;
- std::map<std::string, LinePatternPos> positions;
+ std::map<size_t, LinePatternPos> positions;
};
};
diff --git a/src/mbgl/geometry/sprite_atlas.cpp b/src/mbgl/geometry/sprite_atlas.cpp
index bf31c6e38e..c2686e2f34 100644
--- a/src/mbgl/geometry/sprite_atlas.cpp
+++ b/src/mbgl/geometry/sprite_atlas.cpp
@@ -73,7 +73,7 @@ Rect<SpriteAtlas::dimension> SpriteAtlas::allocateImage(const size_t pixel_width
// This is so we can scale down the texture coordinates and pack them
// into 2 bytes rather than 4 bytes.
const uint16_t pack_width = (pixel_width + 1) + (4 - (pixel_width + 1) % 4);
- const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_width + 1) % 4);
+ const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_height + 1) % 4);
// We have to allocate a new area in the bin, and store an empty image in it.
// Add a 1px border around every image.
@@ -165,37 +165,37 @@ void SpriteAtlas::copy(const Rect<dimension>& dst, const SpritePosition& src, co
static_cast<uint32_t>(dst.originalW * pixelRatio),
static_cast<uint32_t>(dst.originalH * pixelRatio) };
- util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos);
+ util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos, wrap);
// Add borders around the copied image if required.
if (wrap) {
// We're copying from the same image so we don't have to scale again.
const uint32_t border = 1;
+ const uint32_t borderX = dstPos.x != 0 ? border : 0;
+ const uint32_t borderY = dstPos.y != 0 ? border : 0;
+
// Left border
- if (dstPos.x >= border) {
- util::nearestNeighborScale(
- dstData, dstSize, { dstPos.x + dstPos.w - border - 1, dstPos.y, border, dstPos.h },
- dstData, dstSize, { dstPos.x - border, dstPos.y, border, dstPos.h });
- }
+ util::nearestNeighborScale(
+ dstData, dstSize, { dstPos.x + dstPos.w - borderX, dstPos.y, borderX, dstPos.h },
+ dstData, dstSize, { dstPos.x - borderX, dstPos.y, borderX, dstPos.h });
+
// Right border
util::nearestNeighborScale(dstData, dstSize, { dstPos.x, dstPos.y, border, dstPos.h },
dstData, dstSize,
{ dstPos.x + dstPos.w, dstPos.y, border, dstPos.h });
// Top border
- if (dstPos.y >= border) {
- util::nearestNeighborScale(
- dstData, dstSize, { dstPos.x - border, dstPos.y + dstPos.h - border - 1,
- dstPos.w + 2 * border, border },
- dstData, dstSize,
- { dstPos.x - border, dstPos.y - border, dstPos.w + 2 * border, border });
- }
+ util::nearestNeighborScale(
+ dstData, dstSize, { dstPos.x - borderX, dstPos.y + dstPos.h - borderY,
+ dstPos.w + border + borderX, borderY },
+ dstData, dstSize,
+ { dstPos.x - borderX, dstPos.y - borderY, dstPos.w + 2 * borderX, borderY });
// Bottom border
util::nearestNeighborScale(
- dstData, dstSize, { dstPos.x - border, dstPos.y, dstPos.w + 2 * border, border },
+ dstData, dstSize, { dstPos.x - borderX, dstPos.y, dstPos.w + 2 * borderX, border },
dstData, dstSize,
- { dstPos.x - border, dstPos.y + dstPos.h, dstPos.w + 2 * border, border });
+ { dstPos.x - borderX, dstPos.y + dstPos.h, dstPos.w + border + borderX, border });
}
dirty = true;
diff --git a/src/mbgl/geometry/static_vertex_buffer.cpp b/src/mbgl/geometry/static_vertex_buffer.cpp
index c86211c50f..c1e8caab9e 100644
--- a/src/mbgl/geometry/static_vertex_buffer.cpp
+++ b/src/mbgl/geometry/static_vertex_buffer.cpp
@@ -4,7 +4,7 @@
namespace mbgl {
StaticVertexBuffer::StaticVertexBuffer(std::initializer_list<std::pair<int16_t, int16_t>> init) {
- for (const std::pair<int16_t, int16_t> &vertex : init) {
+ for (const auto& vertex : init) {
vertex_type *vertices = static_cast<vertex_type *>(addElement());
vertices[0] = vertex.first;
vertices[1] = vertex.second;
diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp
index 24f72e8dca..c4ad6efc53 100644
--- a/src/mbgl/map/map.cpp
+++ b/src/mbgl/map/map.cpp
@@ -18,7 +18,6 @@
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/style/style_layer.hpp>
-#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
@@ -129,14 +128,22 @@ void Map::start(bool startPaused) {
// Remove all of these to make sure they are destructed in the correct thread.
style.reset();
+
+ // Since we don't have a stylesheet anymore, this will disable all Sources and cancel
+ // their associated requests.
+ updateSources();
+ assert(activeSources.empty());
+
+ // It's now safe to destroy/join the workers since there won't be any more callbacks that
+ // could dispatch to the worker pool.
workers.reset();
- activeSources.clear();
terminating = true;
// Closes all open handles on the loop. This means that the loop will automatically terminate.
asyncRender.reset();
asyncUpdate.reset();
+ asyncInvoke.reset();
asyncTerminate.reset();
});
@@ -144,6 +151,10 @@ void Map::start(bool startPaused) {
update();
});
+ asyncInvoke = util::make_unique<uv::async>(env->loop, [this] {
+ processTasks();
+ });
+
asyncRender = util::make_unique<uv::async>(env->loop, [this] {
// Must be called in Map thread.
assert(Environment::currentlyOn(ThreadType::Map));
@@ -315,6 +326,42 @@ void Map::triggerRender() {
asyncRender->send();
}
+// Runs the function in the map thread.
+void Map::invokeTask(std::function<void()>&& fn) {
+ {
+ std::lock_guard<std::mutex> lock(mutexTask);
+ tasks.emplace(::std::forward<std::function<void()>>(fn));
+ }
+
+ // TODO: Once we have aligned static and continuous rendering, this should always dispatch
+ // to the async queue.
+ if (asyncInvoke) {
+ asyncInvoke->send();
+ } else {
+ processTasks();
+ }
+}
+
+template <typename Fn> auto Map::invokeSyncTask(const Fn& fn) -> decltype(fn()) {
+ std::promise<decltype(fn())> promise;
+ invokeTask([&fn, &promise] { promise.set_value(fn()); });
+ return promise.get_future().get();
+}
+
+// Processes the functions that should be run in the map thread.
+void Map::processTasks() {
+ std::queue<std::function<void()>> queue;
+ {
+ std::lock_guard<std::mutex> lock(mutexTask);
+ queue.swap(tasks);
+ }
+
+ while (!queue.empty()) {
+ queue.front()();
+ queue.pop();
+ }
+}
+
void Map::checkForPause() {
std::unique_lock<std::mutex> lockRun (mutexRun);
while (pausing) {
@@ -352,13 +399,15 @@ void Map::setup() {
void Map::setStyleURL(const std::string &url) {
assert(Environment::currentlyOn(ThreadType::Main));
- const size_t pos = url.rfind('/');
+ const std::string styleURL = mbgl::util::mapbox::normalizeStyleURL(url, getAccessToken());
+
+ const size_t pos = styleURL.rfind('/');
std::string base = "";
if (pos != std::string::npos) {
- base = url.substr(0, pos + 1);
+ base = styleURL.substr(0, pos + 1);
}
- data->setStyleInfo({ url, base, "" });
+ data->setStyleInfo({ styleURL, base, "" });
triggerUpdate(Update::StyleInfo);
}
@@ -542,21 +591,31 @@ std::string Map::getAccessToken() const {
void Map::setDefaultPointAnnotationSymbol(const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Main));
- annotationManager->setDefaultPointAnnotationSymbol(symbol);
+ invokeTask([=] {
+ annotationManager->setDefaultPointAnnotationSymbol(symbol);
+ });
}
-uint32_t Map::addPointAnnotation(const LatLng& point, const std::string& symbol) {
+double Map::getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Main));
- std::vector<LatLng> points({ point });
- std::vector<std::string> symbols({ symbol });
- return addPointAnnotations(points, symbols)[0];
+ return invokeSyncTask([&] {
+ assert(sprite);
+ const SpritePosition pos = sprite->getSpritePosition(symbol);
+ return -pos.height / pos.pixelRatio / 2;
+ });
+}
+
+uint32_t Map::addPointAnnotation(const LatLng& point, const std::string& symbol) {
+ return addPointAnnotations({ point }, { symbol }).front();
}
std::vector<uint32_t> Map::addPointAnnotations(const std::vector<LatLng>& points, const std::vector<std::string>& symbols) {
assert(Environment::currentlyOn(ThreadType::Main));
- auto result = annotationManager->addPointAnnotations(points, symbols, *this);
- updateAnnotationTiles(result.first);
- return result.second;
+ return invokeSyncTask([&] {
+ auto result = annotationManager->addPointAnnotations(points, symbols, *this);
+ updateAnnotationTiles(result.first);
+ return result.second;
+ });
}
void Map::removeAnnotation(uint32_t annotation) {
@@ -566,22 +625,28 @@ void Map::removeAnnotation(uint32_t annotation) {
void Map::removeAnnotations(const std::vector<uint32_t>& annotations) {
assert(Environment::currentlyOn(ThreadType::Main));
- auto result = annotationManager->removeAnnotations(annotations, *this);
- updateAnnotationTiles(result);
+ invokeTask([=] {
+ auto result = annotationManager->removeAnnotations(annotations, *this);
+ updateAnnotationTiles(result);
+ });
}
-std::vector<uint32_t> Map::getAnnotationsInBounds(const LatLngBounds& bounds) const {
+std::vector<uint32_t> Map::getAnnotationsInBounds(const LatLngBounds& bounds) {
assert(Environment::currentlyOn(ThreadType::Main));
- return annotationManager->getAnnotationsInBounds(bounds, *this);
+ return invokeSyncTask([&] {
+ return annotationManager->getAnnotationsInBounds(bounds, *this);
+ });
}
-LatLngBounds Map::getBoundsForAnnotations(const std::vector<uint32_t>& annotations) const {
+LatLngBounds Map::getBoundsForAnnotations(const std::vector<uint32_t>& annotations) {
assert(Environment::currentlyOn(ThreadType::Main));
- return annotationManager->getBoundsForAnnotations(annotations);
+ return invokeSyncTask([&] {
+ return annotationManager->getBoundsForAnnotations(annotations);
+ });
}
void Map::updateAnnotationTiles(const std::vector<Tile::ID>& ids) {
- assert(Environment::currentlyOn(ThreadType::Main));
+ assert(Environment::currentlyOn(ThreadType::Map));
for (const auto &source : activeSources) {
if (source->info.type == SourceType::Annotations) {
source->source->invalidateTiles(*this, ids);
@@ -657,7 +722,11 @@ void Map::updateSources() {
// Then, reenable all of those that we actually use when drawing this layer.
if (style) {
- updateSources(style->layers);
+ for (const auto& layer : style->layers) {
+ if (layer->bucket && layer->bucket->style_source) {
+ (*activeSources.emplace(layer->bucket->style_source).first)->enabled = true;
+ }
+ }
}
// Then, construct or destroy the actual source object, depending on enabled state.
@@ -678,23 +747,9 @@ void Map::updateSources() {
});
}
-void Map::updateSources(const util::ptr<StyleLayerGroup> &group) {
- assert(Environment::currentlyOn(ThreadType::Map));
- if (!group) {
- return;
- }
- for (const util::ptr<StyleLayer> &layer : group->layers) {
- if (!layer) continue;
- if (layer->bucket && layer->bucket->style_source) {
- (*activeSources.emplace(layer->bucket->style_source).first)->enabled = true;
- }
-
- }
-}
-
void Map::updateTiles() {
assert(Environment::currentlyOn(ThreadType::Map));
- for (const auto &source : activeSources) {
+ for (const auto& source : activeSources) {
source->source->update(*this, getWorker(), style, *glyphAtlas, *glyphStore,
*spriteAtlas, getSprite(), *texturePool, [this]() {
assert(Environment::currentlyOn(ThreadType::Map));
@@ -741,7 +796,7 @@ void Map::loadStyleJSON(const std::string& json, const std::string& base) {
style = std::make_shared<Style>();
style->base = base;
style->loadJSON((const uint8_t *)json.c_str());
- style->cascadeClasses(data->getClasses());
+ style->cascade(data->getClasses());
style->setDefaultTransitionDuration(data->getDefaultTransitionDuration());
const std::string glyphURL = util::mapbox::normalizeGlyphsURL(style->glyph_url, getAccessToken());
@@ -754,7 +809,7 @@ void Map::prepare() {
assert(Environment::currentlyOn(ThreadType::Map));
const auto u = updated.exchange(static_cast<UpdateType>(Update::Nothing));
- if (u & static_cast<UpdateType>(Update::StyleInfo)) {
+ if ((u & static_cast<UpdateType>(Update::StyleInfo)) || !style) {
reloadStyle();
}
if (u & static_cast<UpdateType>(Update::Debug)) {
@@ -768,7 +823,7 @@ void Map::prepare() {
}
if (u & static_cast<UpdateType>(Update::Classes)) {
if (style) {
- style->cascadeClasses(data->getClasses());
+ style->cascade(data->getClasses());
}
}
@@ -784,7 +839,7 @@ void Map::prepare() {
if (style) {
updateSources();
- style->updateProperties(state.getNormalizedZoom(), animationTime);
+ style->recalculate(state.getNormalizedZoom(), animationTime);
// Allow the sprite atlas to potentially pull new sprite images if needed.
spriteAtlas->resize(state.getPixelRatio());
@@ -804,6 +859,7 @@ void Map::render() {
// Cleanup OpenGL objects that we abandoned since the last render call.
env->performCleanup();
+ assert(style);
assert(painter);
painter->render(*style, activeSources,
state, data->getAnimationTime());
diff --git a/src/mbgl/map/source.cpp b/src/mbgl/map/source.cpp
index 8189068886..0cf74147e4 100644
--- a/src/mbgl/map/source.cpp
+++ b/src/mbgl/map/source.cpp
@@ -78,7 +78,7 @@ void Source::updateClipIDs(const std::map<Tile::ID, ClipID> &mapping) {
}
void Source::updateMatrices(const mat4 &projMatrix, const TransformState &transform) {
- for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
+ for (const auto& pair : tiles) {
Tile &tile = *pair.second;
transform.matrixFor(tile.matrix, tile.id);
matrix::multiply(tile.matrix, projMatrix, tile.matrix);
@@ -90,7 +90,7 @@ size_t Source::getTileCount() const {
}
void Source::drawClippingMasks(Painter &painter) {
- for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
+ for (const auto& pair : tiles) {
Tile &tile = *pair.second;
gl::group group(std::string { "mask: " } + std::string(tile.id));
painter.drawClippingMask(tile.matrix, tile.clip);
@@ -99,7 +99,7 @@ void Source::drawClippingMasks(Painter &painter) {
void Source::render(Painter &painter, const StyleLayer &layer_desc) {
gl::group group(std::string { "layer: " } + layer_desc.id);
- for (const std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
+ for (const auto& pair : tiles) {
Tile &tile = *pair.second;
if (tile.data && tile.data->state == TileData::State::parsed) {
painter.renderTileLayer(tile, layer_desc, tile.matrix);
@@ -115,7 +115,7 @@ void Source::render(Painter &painter, const StyleLayer &layer_desc, const Tile::
}
void Source::finishRender(Painter &painter) {
- for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
+ for (const auto& pair : tiles) {
Tile &tile = *pair.second;
painter.renderTileDebug(tile);
}
@@ -252,7 +252,7 @@ bool Source::findLoadedChildren(const Tile::ID& id, int32_t maxCoveringZoom, std
bool complete = true;
int32_t z = id.z;
auto ids = id.children(z + 1);
- for (const Tile::ID& child_id : ids) {
+ for (const auto& child_id : ids) {
const TileData::State state = hasTile(child_id);
if (state == TileData::State::parsed) {
retain.emplace_front(child_id);
@@ -301,8 +301,6 @@ void Source::update(Map &map,
return;
}
- bool changed = false;
-
int32_t zoom = std::floor(getZoom(map.getState()));
std::forward_list<Tile::ID> required = coveringTiles(map.getState());
@@ -316,7 +314,7 @@ void Source::update(Map &map,
std::forward_list<Tile::ID> retain(required);
// Add existing child/parent tiles if the actual tile is not yet loaded
- for (const Tile::ID& id : required) {
+ for (const auto& id : required) {
const TileData::State state = addTile(map, worker, style, glyphAtlas, glyphStore,
spriteAtlas, sprite, texturePool, id, callback);
@@ -334,21 +332,15 @@ void Source::update(Map &map,
findLoadedParent(id, minCoveringZoom, retain);
}
}
-
- if (state == TileData::State::initial) {
- changed = true;
- }
}
// Remove tiles that we definitely don't need, i.e. tiles that are not on
// the required list.
std::set<Tile::ID> retain_data;
- util::erase_if(tiles, [&retain, &retain_data, &changed](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
+ util::erase_if(tiles, [&retain, &retain_data](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
Tile &tile = *pair.second;
bool obsolete = std::find(retain.begin(), retain.end(), tile.id) == retain.end();
- if (obsolete) {
- changed = true;
- } else {
+ if (!obsolete) {
retain_data.insert(tile.data->id);
}
return obsolete;
diff --git a/src/mbgl/map/tile_data.hpp b/src/mbgl/map/tile_data.hpp
index cce346d835..a5598fee3b 100644
--- a/src/mbgl/map/tile_data.hpp
+++ b/src/mbgl/map/tile_data.hpp
@@ -9,8 +9,6 @@
#include <mbgl/util/ptr.hpp>
#include <atomic>
-#include <exception>
-#include <iosfwd>
#include <string>
#include <functional>
@@ -22,7 +20,6 @@ typedef struct uv_loop_s uv_loop_t;
namespace mbgl {
-class Map;
class Environment;
class Painter;
class SourceInfo;
@@ -32,12 +29,6 @@ class Request;
class TileData : public std::enable_shared_from_this<TileData>,
private util::noncopyable {
public:
- struct exception : std::exception {};
- struct geometry_too_long_exception : exception {};
-
-public:
- typedef util::ptr<TileData> Ptr;
-
enum class State {
invalid,
initial,
@@ -47,7 +38,6 @@ public:
obsolete
};
-public:
TileData(Tile::ID const &id, const SourceInfo &);
~TileData();
@@ -65,16 +55,14 @@ public:
virtual void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) = 0;
virtual bool hasData(StyleLayer const &layer_desc) const = 0;
-public:
const Tile::ID id;
const std::string name;
std::atomic<State> state;
-public:
+protected:
const SourceInfo& source;
Environment& env;
-protected:
Request *req = nullptr;
std::string data;
diff --git a/src/mbgl/map/tile_parser.cpp b/src/mbgl/map/tile_parser.cpp
index fa7f4c093f..bc6de40565 100644
--- a/src/mbgl/map/tile_parser.cpp
+++ b/src/mbgl/map/tile_parser.cpp
@@ -3,8 +3,7 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
-#include <mbgl/style/style_layer_group.hpp>
-#include <mbgl/style/style_layout.hpp>
+#include <mbgl/style/style_source.hpp>
#include <mbgl/renderer/fill_bucket.hpp>
#include <mbgl/renderer/line_bucket.hpp>
#include <mbgl/renderer/symbol_bucket.hpp>
@@ -49,18 +48,10 @@ TileParser::TileParser(const GeometryTile& geometryTile_,
assert(collision);
}
-void TileParser::parse() {
- parseStyleLayers(style->layers);
-}
-
bool TileParser::obsolete() const { return tile.state == TileData::State::obsolete; }
-void TileParser::parseStyleLayers(util::ptr<const StyleLayerGroup> group) {
- if (!group) {
- return;
- }
-
- for (const util::ptr<const StyleLayer> &layer_desc : group->layers) {
+void TileParser::parse() {
+ for (const auto& layer_desc : style->layers) {
// Cancel early when parsing.
if (obsolete()) {
return;
@@ -122,65 +113,6 @@ void applyLayoutProperty(PropertyKey key, const ClassProperties &classProperties
}
}
-std::unique_ptr<StyleLayoutFill> parseStyleLayoutFill(const StyleBucket &/*bucket*/, const float /*z*/) {
- // no-op; Fill buckets don't currently have any applicable layout properties
- auto fillPtr = util::make_unique<StyleLayoutFill>();
- return fillPtr;
-}
-
-std::unique_ptr<StyleLayoutLine> parseStyleLayoutLine(const StyleBucket &bucket_desc, const float z) {
- auto linePtr = util::make_unique<StyleLayoutLine>();
- auto &line = *linePtr;
- applyLayoutProperty(PropertyKey::LineCap, bucket_desc.layout, line.cap, z);
- applyLayoutProperty(PropertyKey::LineJoin, bucket_desc.layout, line.join, z);
- applyLayoutProperty(PropertyKey::LineMiterLimit, bucket_desc.layout, line.miter_limit, z);
- applyLayoutProperty(PropertyKey::LineRoundLimit, bucket_desc.layout, line.round_limit, z);
- return linePtr;
-}
-
-std::unique_ptr<StyleLayoutSymbol> parseStyleLayoutSymbol(const StyleBucket &bucket_desc, const float z) {
- auto symbolPtr = util::make_unique<StyleLayoutSymbol>();
- auto &symbol = *symbolPtr;
- applyLayoutProperty(PropertyKey::SymbolPlacement, bucket_desc.layout, symbol.placement, z);
- if (symbol.placement == PlacementType::Line) {
- symbol.icon.rotation_alignment = RotationAlignmentType::Map;
- symbol.text.rotation_alignment = RotationAlignmentType::Map;
- };
- applyLayoutProperty(PropertyKey::SymbolMinDistance, bucket_desc.layout, symbol.min_distance, z);
- applyLayoutProperty(PropertyKey::SymbolAvoidEdges, bucket_desc.layout, symbol.avoid_edges, z);
-
- applyLayoutProperty(PropertyKey::IconAllowOverlap, bucket_desc.layout, symbol.icon.allow_overlap, z);
- applyLayoutProperty(PropertyKey::IconIgnorePlacement, bucket_desc.layout, symbol.icon.ignore_placement, z);
- applyLayoutProperty(PropertyKey::IconOptional, bucket_desc.layout, symbol.icon.optional, z);
- applyLayoutProperty(PropertyKey::IconRotationAlignment, bucket_desc.layout, symbol.icon.rotation_alignment, z);
- applyLayoutProperty(PropertyKey::IconMaxSize, bucket_desc.layout, symbol.icon.max_size, z);
- applyLayoutProperty(PropertyKey::IconImage, bucket_desc.layout, symbol.icon.image, z);
- applyLayoutProperty(PropertyKey::IconPadding, bucket_desc.layout, symbol.icon.padding, z);
- applyLayoutProperty(PropertyKey::IconRotate, bucket_desc.layout, symbol.icon.rotate, z);
- applyLayoutProperty(PropertyKey::IconKeepUpright, bucket_desc.layout, symbol.icon.keep_upright, z);
- applyLayoutProperty(PropertyKey::IconOffset, bucket_desc.layout, symbol.icon.offset, z);
-
- applyLayoutProperty(PropertyKey::TextRotationAlignment, bucket_desc.layout, symbol.text.rotation_alignment, z);
- applyLayoutProperty(PropertyKey::TextField, bucket_desc.layout, symbol.text.field, z);
- applyLayoutProperty(PropertyKey::TextFont, bucket_desc.layout, symbol.text.font, z);
- applyLayoutProperty(PropertyKey::TextMaxSize, bucket_desc.layout, symbol.text.max_size, z);
- applyLayoutProperty(PropertyKey::TextMaxWidth, bucket_desc.layout, symbol.text.max_width, z);
- applyLayoutProperty(PropertyKey::TextLineHeight, bucket_desc.layout, symbol.text.line_height, z);
- applyLayoutProperty(PropertyKey::TextLetterSpacing, bucket_desc.layout, symbol.text.letter_spacing, z);
- applyLayoutProperty(PropertyKey::TextMaxAngle, bucket_desc.layout, symbol.text.max_angle, z);
- applyLayoutProperty(PropertyKey::TextRotate, bucket_desc.layout, symbol.text.rotate, z);
- applyLayoutProperty(PropertyKey::TextPadding, bucket_desc.layout, symbol.text.padding, z);
- applyLayoutProperty(PropertyKey::TextIgnorePlacement, bucket_desc.layout, symbol.text.ignore_placement, z);
- applyLayoutProperty(PropertyKey::TextOptional, bucket_desc.layout, symbol.text.optional, z);
- applyLayoutProperty(PropertyKey::TextJustify, bucket_desc.layout, symbol.text.justify, z);
- applyLayoutProperty(PropertyKey::TextAnchor, bucket_desc.layout, symbol.text.anchor, z);
- applyLayoutProperty(PropertyKey::TextKeepUpright, bucket_desc.layout, symbol.text.keep_upright, z);
- applyLayoutProperty(PropertyKey::TextTransform, bucket_desc.layout, symbol.text.transform, z);
- applyLayoutProperty(PropertyKey::TextOffset, bucket_desc.layout, symbol.text.offset, z);
- applyLayoutProperty(PropertyKey::TextAllowOverlap, bucket_desc.layout, symbol.text.allow_overlap, z);
- return symbolPtr;
-}
-
std::unique_ptr<Bucket> TileParser::createBucket(const StyleBucket &bucketDesc) {
// Skip this bucket if we are to not render this
if (tile.id.z < std::floor(bucketDesc.min_zoom) && std::floor(bucketDesc.min_zoom) < tile.source.max_zoom) return nullptr;
@@ -230,32 +162,78 @@ void TileParser::addBucketGeometries(Bucket& bucket, const GeometryTileLayer& la
std::unique_ptr<Bucket> TileParser::createFillBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
- auto fill = parseStyleLayoutFill(bucket_desc, tile.id.z);
- auto bucket = util::make_unique<FillBucket>(std::move(fill),
- tile.fillVertexBuffer,
+ auto bucket = util::make_unique<FillBucket>(tile.fillVertexBuffer,
tile.triangleElementsBuffer,
tile.lineElementsBuffer);
addBucketGeometries(bucket, layer, bucket_desc.filter);
- return obsolete() ? nullptr : std::move(bucket);
+ return std::move(bucket);
}
std::unique_ptr<Bucket> TileParser::createLineBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
- auto line = parseStyleLayoutLine(bucket_desc, tile.id.z);
- auto bucket = util::make_unique<LineBucket>(std::move(line),
- tile.lineVertexBuffer,
+ auto bucket = util::make_unique<LineBucket>(tile.lineVertexBuffer,
tile.triangleElementsBuffer,
tile.pointElementsBuffer);
+
+ const float z = tile.id.z;
+ auto& layout = bucket->layout;
+
+ applyLayoutProperty(PropertyKey::LineCap, bucket_desc.layout, layout.cap, z);
+ applyLayoutProperty(PropertyKey::LineJoin, bucket_desc.layout, layout.join, z);
+ applyLayoutProperty(PropertyKey::LineMiterLimit, bucket_desc.layout, layout.miter_limit, z);
+ applyLayoutProperty(PropertyKey::LineRoundLimit, bucket_desc.layout, layout.round_limit, z);
+
addBucketGeometries(bucket, layer, bucket_desc.filter);
- return obsolete() ? nullptr : std::move(bucket);
+ return std::move(bucket);
}
std::unique_ptr<Bucket> TileParser::createSymbolBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
- auto symbol = parseStyleLayoutSymbol(bucket_desc, tile.id.z);
- auto bucket = util::make_unique<SymbolBucket>(std::move(symbol), *collision);
+ auto bucket = util::make_unique<SymbolBucket>(*collision);
+
+ const float z = tile.id.z;
+ auto& layout = bucket->layout;
+
+ applyLayoutProperty(PropertyKey::SymbolPlacement, bucket_desc.layout, layout.placement, z);
+ if (layout.placement == PlacementType::Line) {
+ layout.icon.rotation_alignment = RotationAlignmentType::Map;
+ layout.text.rotation_alignment = RotationAlignmentType::Map;
+ };
+ applyLayoutProperty(PropertyKey::SymbolMinDistance, bucket_desc.layout, layout.min_distance, z);
+ applyLayoutProperty(PropertyKey::SymbolAvoidEdges, bucket_desc.layout, layout.avoid_edges, z);
+
+ applyLayoutProperty(PropertyKey::IconAllowOverlap, bucket_desc.layout, layout.icon.allow_overlap, z);
+ applyLayoutProperty(PropertyKey::IconIgnorePlacement, bucket_desc.layout, layout.icon.ignore_placement, z);
+ applyLayoutProperty(PropertyKey::IconOptional, bucket_desc.layout, layout.icon.optional, z);
+ applyLayoutProperty(PropertyKey::IconRotationAlignment, bucket_desc.layout, layout.icon.rotation_alignment, z);
+ applyLayoutProperty(PropertyKey::IconMaxSize, bucket_desc.layout, layout.icon.max_size, z);
+ applyLayoutProperty(PropertyKey::IconImage, bucket_desc.layout, layout.icon.image, z);
+ applyLayoutProperty(PropertyKey::IconPadding, bucket_desc.layout, layout.icon.padding, z);
+ applyLayoutProperty(PropertyKey::IconRotate, bucket_desc.layout, layout.icon.rotate, z);
+ applyLayoutProperty(PropertyKey::IconKeepUpright, bucket_desc.layout, layout.icon.keep_upright, z);
+ applyLayoutProperty(PropertyKey::IconOffset, bucket_desc.layout, layout.icon.offset, z);
+
+ applyLayoutProperty(PropertyKey::TextRotationAlignment, bucket_desc.layout, layout.text.rotation_alignment, z);
+ applyLayoutProperty(PropertyKey::TextField, bucket_desc.layout, layout.text.field, z);
+ applyLayoutProperty(PropertyKey::TextFont, bucket_desc.layout, layout.text.font, z);
+ applyLayoutProperty(PropertyKey::TextMaxSize, bucket_desc.layout, layout.text.max_size, z);
+ applyLayoutProperty(PropertyKey::TextMaxWidth, bucket_desc.layout, layout.text.max_width, z);
+ applyLayoutProperty(PropertyKey::TextLineHeight, bucket_desc.layout, layout.text.line_height, z);
+ applyLayoutProperty(PropertyKey::TextLetterSpacing, bucket_desc.layout, layout.text.letter_spacing, z);
+ applyLayoutProperty(PropertyKey::TextMaxAngle, bucket_desc.layout, layout.text.max_angle, z);
+ applyLayoutProperty(PropertyKey::TextRotate, bucket_desc.layout, layout.text.rotate, z);
+ applyLayoutProperty(PropertyKey::TextPadding, bucket_desc.layout, layout.text.padding, z);
+ applyLayoutProperty(PropertyKey::TextIgnorePlacement, bucket_desc.layout, layout.text.ignore_placement, z);
+ applyLayoutProperty(PropertyKey::TextOptional, bucket_desc.layout, layout.text.optional, z);
+ applyLayoutProperty(PropertyKey::TextJustify, bucket_desc.layout, layout.text.justify, z);
+ applyLayoutProperty(PropertyKey::TextAnchor, bucket_desc.layout, layout.text.anchor, z);
+ applyLayoutProperty(PropertyKey::TextKeepUpright, bucket_desc.layout, layout.text.keep_upright, z);
+ applyLayoutProperty(PropertyKey::TextTransform, bucket_desc.layout, layout.text.transform, z);
+ applyLayoutProperty(PropertyKey::TextOffset, bucket_desc.layout, layout.text.offset, z);
+ applyLayoutProperty(PropertyKey::TextAllowOverlap, bucket_desc.layout, layout.text.allow_overlap, z);
+
bucket->addFeatures(
layer, bucket_desc.filter, reinterpret_cast<uintptr_t>(&tile), spriteAtlas, *sprite, glyphAtlas, glyphStore);
- return obsolete() ? nullptr : std::move(bucket);
+ return std::move(bucket);
}
}
diff --git a/src/mbgl/map/tile_parser.hpp b/src/mbgl/map/tile_parser.hpp
index 0ad42fdc91..2c16d2a2fd 100644
--- a/src/mbgl/map/tile_parser.hpp
+++ b/src/mbgl/map/tile_parser.hpp
@@ -28,7 +28,6 @@ class StyleLayoutFill;
class StyleLayoutRaster;
class StyleLayoutLine;
class StyleLayoutSymbol;
-class StyleLayerGroup;
class VectorTileData;
class Collision;
@@ -48,7 +47,6 @@ public:
private:
bool obsolete() const;
- void parseStyleLayers(util::ptr<const StyleLayerGroup> group);
std::unique_ptr<Bucket> createBucket(const StyleBucket&);
std::unique_ptr<Bucket> createFillBucket(const GeometryTileLayer&, const StyleBucket&);
@@ -58,7 +56,6 @@ private:
template <class Bucket>
void addBucketGeometries(Bucket&, const GeometryTileLayer&, const FilterExpression&);
-private:
const GeometryTile& geometryTile;
VectorTileData& tile;
diff --git a/src/mbgl/map/vector_tile.cpp b/src/mbgl/map/vector_tile.cpp
index dca2168a47..01d52a348a 100644
--- a/src/mbgl/map/vector_tile.cpp
+++ b/src/mbgl/map/vector_tile.cpp
@@ -35,26 +35,7 @@ VectorTileFeature::VectorTileFeature(pbf feature_pbf, const VectorTileLayer& lay
if (feature_pbf.tag == 1) { // id
id = feature_pbf.varint<uint64_t>();
} else if (feature_pbf.tag == 2) { // tags
- // tags are packed varints. They should have an even length.
- pbf tags = feature_pbf.message();
- while (tags) {
- uint32_t tag_key = tags.varint();
-
- if (layer.keys.size() <= tag_key) {
- throw std::runtime_error("feature referenced out of range key");
- }
-
- if (!tags) {
- throw std::runtime_error("uneven number of feature tag ids");
- }
-
- uint32_t tag_val = tags.varint();
- if (layer.values.size() <= tag_val) {
- throw std::runtime_error("feature referenced out of range value");
- }
-
- properties.emplace(tag_key, tag_val);
- }
+ tags_pbf = feature_pbf.message();
} else if (feature_pbf.tag == 3) { // type
type = (FeatureType)feature_pbf.varint();
} else if (feature_pbf.tag == 4) { // geometry
@@ -70,11 +51,30 @@ mapbox::util::optional<Value> VectorTileFeature::getValue(const std::string& key
if (keyIter == layer.keys.end()) {
return mapbox::util::optional<Value>();
}
- auto propIter = properties.find(keyIter->second);
- if (propIter == properties.end()) {
- return mapbox::util::optional<Value>();
+
+ pbf tags = tags_pbf;
+ while (tags) {
+ uint32_t tag_key = tags.varint();
+
+ if (layer.keys.size() <= tag_key) {
+ throw std::runtime_error("feature referenced out of range key");
+ }
+
+ if (!tags) {
+ throw std::runtime_error("uneven number of feature tag ids");
+ }
+
+ uint32_t tag_val = tags.varint();
+ if (layer.values.size() <= tag_val) {
+ throw std::runtime_error("feature referenced out of range value");
+ }
+
+ if (tag_key == keyIter->second) {
+ return layer.values[tag_val];
+ }
}
- return layer.values[propIter->second];
+
+ return mapbox::util::optional<Value>();
}
GeometryCollection VectorTileFeature::getGeometries() const {
diff --git a/src/mbgl/map/vector_tile.hpp b/src/mbgl/map/vector_tile.hpp
index 9a23c3b189..77a0b4ab16 100644
--- a/src/mbgl/map/vector_tile.hpp
+++ b/src/mbgl/map/vector_tile.hpp
@@ -22,7 +22,7 @@ private:
const VectorTileLayer& layer;
uint64_t id = 0;
FeatureType type = FeatureType::Unknown;
- std::unordered_map<uint32_t, uint32_t> properties;
+ pbf tags_pbf;
pbf geometry_pbf;
};
diff --git a/src/mbgl/renderer/debug_bucket.cpp b/src/mbgl/renderer/debug_bucket.cpp
index 3c56401e1e..6104e2456b 100644
--- a/src/mbgl/renderer/debug_bucket.cpp
+++ b/src/mbgl/renderer/debug_bucket.cpp
@@ -5,8 +5,6 @@
#include <cassert>
-struct geometry_too_long_exception : std::exception {};
-
using namespace mbgl;
DebugBucket::DebugBucket(DebugFontBuffer& fontBuffer_)
diff --git a/src/mbgl/renderer/fill_bucket.cpp b/src/mbgl/renderer/fill_bucket.cpp
index 26d0d1f4be..958ea3d998 100644
--- a/src/mbgl/renderer/fill_bucket.cpp
+++ b/src/mbgl/renderer/fill_bucket.cpp
@@ -28,12 +28,10 @@ void FillBucket::free(void *, void *ptr) {
::free(ptr);
}
-FillBucket::FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout_,
- FillVertexBuffer &vertexBuffer_,
+FillBucket::FillBucket(FillVertexBuffer &vertexBuffer_,
TriangleElementsBuffer &triangleElementsBuffer_,
LineElementsBuffer &lineElementsBuffer_)
- : styleLayout(std::move(styleLayout_)),
- allocator(new TESSalloc{
+ : allocator(new TESSalloc{
&alloc,
&realloc,
&free,
@@ -53,7 +51,6 @@ FillBucket::FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout_,
triangle_elements_start(triangleElementsBuffer_.index()),
line_elements_start(lineElementsBuffer.index()) {
assert(tesselator);
- assert(styleLayout);
}
FillBucket::~FillBucket() {
@@ -95,7 +92,7 @@ void FillBucket::tessellate() {
}
size_t total_vertex_count = 0;
- for (const std::vector<ClipperLib::IntPoint>& polygon : polygons) {
+ for (const auto& polygon : polygons) {
total_vertex_count += polygon.size();
}
@@ -112,12 +109,12 @@ void FillBucket::tessellate() {
line_group_type& lineGroup = *lineGroups.back();
uint32_t lineIndex = lineGroup.vertex_length;
- for (const std::vector<ClipperLib::IntPoint>& polygon : polygons) {
+ for (const auto& polygon : polygons) {
const size_t group_count = polygon.size();
assert(group_count >= 3);
std::vector<TESSreal> clipped_line;
- for (const ClipperLib::IntPoint& pt : polygon) {
+ for (const auto& pt : polygon) {
clipped_line.push_back(pt.X);
clipped_line.push_back(pt.Y);
vertexBuffer.add(pt.X, pt.Y);
diff --git a/src/mbgl/renderer/fill_bucket.hpp b/src/mbgl/renderer/fill_bucket.hpp
index 46b8f53857..937fd540ac 100644
--- a/src/mbgl/renderer/fill_bucket.hpp
+++ b/src/mbgl/renderer/fill_bucket.hpp
@@ -6,6 +6,7 @@
#include <mbgl/geometry/elements_buffer.hpp>
#include <mbgl/geometry/fill_buffer.hpp>
#include <mbgl/style/style_bucket.hpp>
+#include <mbgl/style/style_layout.hpp>
#include <clipper/clipper.hpp>
#include <libtess2/tesselator.h>
@@ -39,8 +40,7 @@ class FillBucket : public Bucket {
typedef ElementGroup<1> line_group_type;
public:
- FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout,
- FillVertexBuffer &vertexBuffer,
+ FillBucket(FillVertexBuffer &vertexBuffer,
TriangleElementsBuffer &triangleElementsBuffer,
LineElementsBuffer &lineElementsBuffer);
~FillBucket() override;
@@ -57,7 +57,7 @@ public:
void drawVertices(OutlineShader& shader);
public:
- const std::unique_ptr<const StyleLayoutFill> styleLayout;
+ StyleLayoutFill layout;
private:
TESSalloc *allocator;
diff --git a/src/mbgl/renderer/line_bucket.cpp b/src/mbgl/renderer/line_bucket.cpp
index 6eea0d8d0f..5404398ca0 100644
--- a/src/mbgl/renderer/line_bucket.cpp
+++ b/src/mbgl/renderer/line_bucket.cpp
@@ -12,22 +12,17 @@
#include <cassert>
-struct geometry_too_long_exception : std::exception {};
-
using namespace mbgl;
-LineBucket::LineBucket(std::unique_ptr<const StyleLayoutLine> styleLayout_,
- LineVertexBuffer &vertexBuffer_,
+LineBucket::LineBucket(LineVertexBuffer &vertexBuffer_,
TriangleElementsBuffer &triangleElementsBuffer_,
PointElementsBuffer &pointElementsBuffer_)
- : styleLayout(std::move(styleLayout_)),
- vertexBuffer(vertexBuffer_),
+ : vertexBuffer(vertexBuffer_),
triangleElementsBuffer(triangleElementsBuffer_),
pointElementsBuffer(pointElementsBuffer_),
vertex_start(vertexBuffer_.index()),
triangle_elements_start(triangleElementsBuffer_.index()),
point_elements_start(pointElementsBuffer_.index()) {
- assert(styleLayout);
}
LineBucket::~LineBucket() {
@@ -48,7 +43,6 @@ void LineBucket::addGeometry(const GeometryCollection& geometryCollection) {
}
void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
- auto &layout = *styleLayout;
// TODO: use roundLimit
// const float roundLimit = geometry.round_limit;
@@ -302,7 +296,7 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
assert(triangleGroups.back());
triangle_group_type& group = *triangleGroups.back();
- for (const TriangleElement& triangle : triangle_store) {
+ for (const auto& triangle : triangle_store) {
triangleElementsBuffer.add(
group.vertex_length + triangle.a,
group.vertex_length + triangle.b,
@@ -323,7 +317,7 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
assert(pointGroups.back());
point_group_type& group = *pointGroups.back();
- for (PointElement point : point_store) {
+ for (const auto point : point_store) {
pointElementsBuffer.add(group.vertex_length + point);
}
diff --git a/src/mbgl/renderer/line_bucket.hpp b/src/mbgl/renderer/line_bucket.hpp
index 25b2190176..e6e5f66d57 100644
--- a/src/mbgl/renderer/line_bucket.hpp
+++ b/src/mbgl/renderer/line_bucket.hpp
@@ -7,6 +7,7 @@
#include <mbgl/geometry/elements_buffer.hpp>
#include <mbgl/geometry/line_buffer.hpp>
#include <mbgl/style/style_bucket.hpp>
+#include <mbgl/style/style_layout.hpp>
#include <mbgl/util/vec.hpp>
#include <vector>
@@ -14,7 +15,6 @@
namespace mbgl {
class Style;
-class StyleLayoutLine;
class LineVertexBuffer;
class TriangleElementsBuffer;
class LineShader;
@@ -27,8 +27,7 @@ class LineBucket : public Bucket {
typedef ElementGroup<1> point_group_type;
public:
- LineBucket(std::unique_ptr<const StyleLayoutLine> styleLayout,
- LineVertexBuffer &vertexBuffer,
+ LineBucket(LineVertexBuffer &vertexBuffer,
TriangleElementsBuffer &triangleElementsBuffer,
PointElementsBuffer &pointElementsBuffer);
~LineBucket() override;
@@ -48,7 +47,7 @@ public:
void drawPoints(LinejoinShader& shader);
public:
- const std::unique_ptr<const StyleLayoutLine> styleLayout;
+ StyleLayoutLine layout;
private:
LineVertexBuffer& vertexBuffer;
diff --git a/src/mbgl/renderer/painter.cpp b/src/mbgl/renderer/painter.cpp
index dae9c766cc..0219ccec7f 100644
--- a/src/mbgl/renderer/painter.cpp
+++ b/src/mbgl/renderer/painter.cpp
@@ -2,7 +2,6 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
-#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/string.hpp>
@@ -226,7 +225,7 @@ void Painter::render(const Style& style, const std::set<util::ptr<StyleSource>>&
// Update all clipping IDs.
ClipIDGenerator generator;
- for (const util::ptr<StyleSource> &source : sources) {
+ for (const auto& source : sources) {
generator.update(source->source->getLoadedTiles());
source->source->updateMatrices(projMatrix, state);
}
@@ -237,23 +236,9 @@ void Painter::render(const Style& style, const std::set<util::ptr<StyleSource>>&
// Actually render the layers
if (debug::renderTree) { Log::Info(Event::Render, "{"); indent++; }
- if (style.layers) {
- renderLayers(*style.layers);
- }
- if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
-
- // Finalize the rendering, e.g. by calling debug render calls per tile.
- // This guarantees that we have at least one function per tile called.
- // When only rendering layers via the stylesheet, it's possible that we don't
- // ever visit a tile during rendering.
- for (const util::ptr<StyleSource> &source : sources) {
- source->source->finishRender(*this);
- }
-}
-void Painter::renderLayers(const StyleLayerGroup &group) {
// TODO: Correctly compute the number of layers recursively beforehand.
- float strata_thickness = 1.0f / (group.layers.size() + 1);
+ float strata_thickness = 1.0f / (style.layers.size() + 1);
// - FIRST PASS ------------------------------------------------------------
// Render everything top-to-bottom by using reverse iterators. Render opaque
@@ -263,7 +248,7 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "OPAQUE {");
}
int i = 0;
- for (auto it = group.layers.rbegin(), end = group.layers.rend(); it != end; ++it, ++i) {
+ for (auto it = style.layers.rbegin(), end = style.layers.rend(); it != end; ++it, ++i) {
setOpaque();
setStrata(i * strata_thickness);
renderLayer(**it);
@@ -279,7 +264,7 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "TRANSLUCENT {");
}
--i;
- for (auto it = group.layers.begin(), end = group.layers.end(); it != end; ++it, --i) {
+ for (auto it = style.layers.begin(), end = style.layers.end(); it != end; ++it, --i) {
setTranslucent();
setStrata(i * strata_thickness);
renderLayer(**it);
@@ -287,6 +272,16 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", --indent * 4, "", "}");
}
+
+ if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
+
+ // Finalize the rendering, e.g. by calling debug render calls per tile.
+ // This guarantees that we have at least one function per tile called.
+ // When only rendering layers via the stylesheet, it's possible that we don't
+ // ever visit a tile during rendering.
+ for (const auto& source : sources) {
+ source->source->finishRender(*this);
+ }
}
void Painter::renderLayer(const StyleLayer &layer_desc, const Tile::ID* id, const mat4* matrix) {
diff --git a/src/mbgl/renderer/painter.hpp b/src/mbgl/renderer/painter.hpp
index 9c9c6a4642..485098c116 100644
--- a/src/mbgl/renderer/painter.hpp
+++ b/src/mbgl/renderer/painter.hpp
@@ -43,7 +43,6 @@ class GlyphAtlas;
class LineAtlas;
class Source;
class StyleSource;
-class StyleLayerGroup;
class FillBucket;
class LineBucket;
@@ -81,7 +80,6 @@ public:
TransformState state,
std::chrono::steady_clock::time_point time);
- void renderLayers(const StyleLayerGroup &group);
void renderLayer(const StyleLayer &layer_desc, const Tile::ID* id = nullptr, const mat4* matrix = nullptr);
// Renders a particular layer from a tile.
diff --git a/src/mbgl/renderer/painter_clipping.cpp b/src/mbgl/renderer/painter_clipping.cpp
index 942be3e9bb..574cbe50af 100644
--- a/src/mbgl/renderer/painter_clipping.cpp
+++ b/src/mbgl/renderer/painter_clipping.cpp
@@ -17,7 +17,7 @@ void Painter::drawClippingMasks(const std::set<util::ptr<StyleSource>> &sources)
coveringPlainArray.bind(*plainShader, tileStencilBuffer, BUFFER_OFFSET(0));
- for (const util::ptr<StyleSource> &source : sources) {
+ for (const auto& source : sources) {
source->source->drawClippingMasks(*this);
}
diff --git a/src/mbgl/renderer/painter_debug.cpp b/src/mbgl/renderer/painter_debug.cpp
index 2c861aac00..7f9c990776 100644
--- a/src/mbgl/renderer/painter_debug.cpp
+++ b/src/mbgl/renderer/painter_debug.cpp
@@ -77,7 +77,7 @@ void Painter::renderDebugText(const std::vector<std::string> &strings) {
DebugFontBuffer debugFontBuffer;
int line = 25;
- for (const std::string &str : strings) {
+ for (const auto& str : strings) {
debugFontBuffer.addText(str.c_str(), 10, line, 0.75);
line += 20;
}
diff --git a/src/mbgl/renderer/painter_line.cpp b/src/mbgl/renderer/painter_line.cpp
index 679e4db7b0..a19d9873af 100644
--- a/src/mbgl/renderer/painter_line.cpp
+++ b/src/mbgl/renderer/painter_line.cpp
@@ -18,7 +18,7 @@ void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const
depthMask(false);
const auto &properties = layer_desc.getProperties<LineProperties>();
- const auto &layout = *bucket.styleLayout;
+ const auto &layout = bucket.layout;
// the distance over which the line edge fades out.
// Retina devices need a smaller distance to avoid aliasing.
diff --git a/src/mbgl/renderer/painter_raster.cpp b/src/mbgl/renderer/painter_raster.cpp
index 5e72676b92..72d15aabd0 100644
--- a/src/mbgl/renderer/painter_raster.cpp
+++ b/src/mbgl/renderer/painter_raster.cpp
@@ -2,7 +2,6 @@
#include <mbgl/platform/gl.hpp>
#include <mbgl/renderer/raster_bucket.hpp>
#include <mbgl/style/style_layer.hpp>
-#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/map/map.hpp>
diff --git a/src/mbgl/renderer/painter_symbol.cpp b/src/mbgl/renderer/painter_symbol.cpp
index 9476146e95..e1b4d88193 100644
--- a/src/mbgl/renderer/painter_symbol.cpp
+++ b/src/mbgl/renderer/painter_symbol.cpp
@@ -119,7 +119,7 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
}
const auto &properties = layer_desc.getProperties<SymbolProperties>();
- const auto &layout = *bucket.styleLayout;
+ const auto &layout = bucket.layout;
MBGL_CHECK_ERROR(glDisable(GL_STENCIL_TEST));
depthMask(false);
diff --git a/src/mbgl/renderer/symbol_bucket.cpp b/src/mbgl/renderer/symbol_bucket.cpp
index ad54581e10..d5940eccf1 100644
--- a/src/mbgl/renderer/symbol_bucket.cpp
+++ b/src/mbgl/renderer/symbol_bucket.cpp
@@ -22,9 +22,8 @@
namespace mbgl {
-SymbolBucket::SymbolBucket(std::unique_ptr<const StyleLayoutSymbol> styleLayout_, Collision &collision_)
- : styleLayout(std::move(styleLayout_)), collision(collision_) {
- assert(styleLayout);
+SymbolBucket::SymbolBucket(Collision &collision_)
+ : collision(collision_) {
}
SymbolBucket::~SymbolBucket() {
@@ -46,7 +45,6 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const GeometryTileLayer
const FilterExpression& filter,
GlyphStore &glyphStore,
const Sprite &sprite) {
- auto &layout = *styleLayout;
const bool has_text = layout.text.field.size();
const bool has_icon = layout.icon.image.size();
@@ -129,7 +127,6 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
Sprite& sprite,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore) {
- auto &layout = *styleLayout;
const std::vector<SymbolFeature> features = processFeatures(layer, filter, glyphStore, sprite);
float horizontalAlign = 0.5;
@@ -175,7 +172,7 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
const auto &fontStack = glyphStore.getFontStack(layout.text.font);
- for (const SymbolFeature &feature : features) {
+ for (const auto& feature : features) {
if (!feature.geometry.size()) continue;
Shaping shaping;
@@ -212,7 +209,7 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
// if either shaping or icon position is present, add the feature
if (shaping.size() || image) {
- for (const std::vector<Coordinate> &line : feature.geometry) {
+ for (const auto& line : feature.geometry) {
if (line.size()) {
addFeature(line, shaping, face, image);
}
@@ -228,7 +225,6 @@ const PlacementRange fullRange{{2 * M_PI, 0}};
void SymbolBucket::addFeature(const std::vector<Coordinate> &line, const Shaping &shaping,
const GlyphPositions &face, const Rect<uint16_t> &image) {
assert(line.size());
- auto &layout = *styleLayout;
const float minScale = 0.5f;
const float glyphSize = 24.0f;
@@ -276,7 +272,7 @@ void SymbolBucket::addFeature(const std::vector<Coordinate> &line, const Shaping
// TODO: figure out correct ascender height.
const vec2<float> origin = {0, -17};
- for (Anchor &anchor : anchors) {
+ for (auto& anchor : anchors) {
// Calculate the scales at which the text and icons can be first shown without overlap
Placement glyphPlacement;
@@ -363,7 +359,7 @@ void SymbolBucket::addSymbols(Buffer &buffer, const PlacedGlyphs &symbols, float
const float placementZoom = std::log(scale) / std::log(2) + zoom;
- for (const PlacedGlyph &symbol : symbols) {
+ for (const auto& symbol : symbols) {
const auto &tl = symbol.tl;
const auto &tr = symbol.tr;
const auto &bl = symbol.bl;
diff --git a/src/mbgl/renderer/symbol_bucket.hpp b/src/mbgl/renderer/symbol_bucket.hpp
index b7291c186c..4f425a49ec 100644
--- a/src/mbgl/renderer/symbol_bucket.hpp
+++ b/src/mbgl/renderer/symbol_bucket.hpp
@@ -10,7 +10,7 @@
#include <mbgl/text/types.hpp>
#include <mbgl/text/glyph.hpp>
#include <mbgl/style/style_bucket.hpp>
-#include <mbgl/util/ptr.hpp>
+#include <mbgl/style/style_layout.hpp>
#include <memory>
#include <map>
@@ -56,7 +56,7 @@ class SymbolBucket : public Bucket {
typedef ElementGroup<2> IconElementGroup;
public:
- SymbolBucket(std::unique_ptr<const StyleLayoutSymbol> styleLayout, Collision &collision);
+ SymbolBucket(Collision &collision);
~SymbolBucket() override;
void render(Painter &painter, const StyleLayer &layer_desc, const Tile::ID &id,
@@ -90,7 +90,7 @@ private:
void addSymbols(Buffer &buffer, const PlacedGlyphs &symbols, float scale, PlacementRange placementRange);
public:
- const std::unique_ptr<const StyleLayoutSymbol> styleLayout;
+ StyleLayoutSymbol layout;
bool sdfIcons = false;
private:
diff --git a/src/mbgl/style/style.cpp b/src/mbgl/style/style.cpp
index 45217950f6..d0adfe27c2 100644
--- a/src/mbgl/style/style.cpp
+++ b/src/mbgl/style/style.cpp
@@ -1,6 +1,6 @@
#include <mbgl/style/style.hpp>
#include <mbgl/map/sprite.hpp>
-#include <mbgl/style/style_layer_group.hpp>
+#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_parser.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/constants.hpp>
@@ -25,19 +25,21 @@ Style::Style()
// for deleting the std::unique_ptr<uv::rwlock>.
Style::~Style() {}
-void Style::updateProperties(float z, std::chrono::steady_clock::time_point now) {
+void Style::cascade(const std::vector<std::string>& classes) {
+ std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
+
+ for (const auto& layer : layers) {
+ layer->setClasses(classes, now, defaultTransition);
+ }
+}
+
+void Style::recalculate(float z, std::chrono::steady_clock::time_point now) {
uv::writelock lock(mtx);
zoomHistory.update(z, now);
- if (layers) {
- layers->updateProperties(z, now, zoomHistory);
- }
-
- // Apply transitions after the first time.
- if (!initial_render_complete) {
- initial_render_complete = true;
- return;
+ for (const auto& layer : layers) {
+ layer->updateProperties(z, now, zoomHistory);
}
}
@@ -49,22 +51,15 @@ void Style::setDefaultTransitionDuration(std::chrono::steady_clock::duration dur
defaultTransition.duration = duration;
}
-void Style::cascadeClasses(const std::vector<std::string>& classes) {
- if (layers) {
- layers->setClasses(classes, std::chrono::steady_clock::now(), defaultTransition);
- }
-}
-
bool Style::hasTransitions() const {
- if (layers) {
- if (layers->hasTransitions()) {
+ for (const auto& layer : layers) {
+ if (layer->hasTransitions()) {
return true;
}
}
return false;
}
-
void Style::loadJSON(const uint8_t *const data) {
uv::writelock lock(mtx);
diff --git a/src/mbgl/style/style.hpp b/src/mbgl/style/style.hpp
index 4de827a38c..453ebacff5 100644
--- a/src/mbgl/style/style.hpp
+++ b/src/mbgl/style/style.hpp
@@ -2,54 +2,43 @@
#define MBGL_STYLE_STYLE
#include <mbgl/style/property_transition.hpp>
-#include <mbgl/style/style_source.hpp>
#include <mbgl/style/zoom_history.hpp>
#include <mbgl/util/uv.hpp>
#include <mbgl/util/ptr.hpp>
+#include <mbgl/util/noncopyable.hpp>
#include <cstdint>
-#include <map>
#include <string>
-#include <unordered_map>
#include <vector>
-#include <set>
#include <chrono>
namespace mbgl {
-class Sprite;
class StyleLayer;
-class StyleLayerGroup;
class Style : public util::noncopyable {
public:
- struct exception : std::runtime_error { exception(const char *msg) : std::runtime_error(msg) {} };
-
Style();
~Style();
void loadJSON(const uint8_t *const data);
- size_t layerCount() const;
- void updateProperties(float z, std::chrono::steady_clock::time_point now);
-
- void setDefaultTransitionDuration(std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero());
- void cascadeClasses(const std::vector<std::string>&);
+ void cascade(const std::vector<std::string>&);
+ void recalculate(float z, std::chrono::steady_clock::time_point now);
+ void setDefaultTransitionDuration(std::chrono::steady_clock::duration);
bool hasTransitions() const;
const std::string &getSpriteURL() const;
- util::ptr<StyleLayerGroup> layers;
- std::vector<std::string> appliedClasses;
+ std::vector<util::ptr<StyleLayer>> layers;
std::string glyph_url;
std::string base;
private:
std::string sprite_url;
PropertyTransition defaultTransition;
- bool initial_render_complete = false;
std::unique_ptr<uv::rwlock> mtx;
ZoomHistory zoomHistory;
};
diff --git a/src/mbgl/style/style_layer.cpp b/src/mbgl/style/style_layer.cpp
index 1a4354be27..705d9800b1 100644
--- a/src/mbgl/style/style_layer.cpp
+++ b/src/mbgl/style/style_layer.cpp
@@ -1,6 +1,5 @@
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_bucket.hpp>
-#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/property_fallback.hpp>
#include <mbgl/util/interpolate.hpp>
@@ -32,7 +31,7 @@ void StyleLayer::setClasses(const std::vector<std::string> &class_names, const s
// Make sure that we also transition to the fallback value for keys that aren't changed by
// any applied classes.
- for (std::pair<const PropertyKey, AppliedClassProperties> &property_pair : appliedStyle) {
+ for (auto& property_pair : appliedStyle) {
const PropertyKey key = property_pair.first;
if (already_applied.find(key) != already_applied.end()) {
// This property has already been set by a previous class, so we don't need to
@@ -66,7 +65,7 @@ void StyleLayer::applyClassProperties(const ClassID class_id,
// Loop through all the properties in this style, and add transitions to them, if they're
// not already the most recent transition.
const ClassProperties &class_properties = style_it->second;
- for (const std::pair<PropertyKey, PropertyValue> &property_pair : class_properties) {
+ for (const auto& property_pair : class_properties) {
PropertyKey key = property_pair.first;
if (already_applied.find(key) != already_applied.end()) {
// This property has already been set by a previous class.
@@ -126,7 +125,7 @@ void StyleLayer::applyStyleProperty(PropertyKey key, T &target, const float z, c
AppliedClassProperties &applied = it->second;
// Iterate through all properties that we need to apply in order.
const PropertyEvaluator<T> evaluator(z, zoomHistory);
- for (AppliedClassProperty &property : applied.properties) {
+ for (auto& property : applied.properties) {
if (now >= property.begin) {
// We overwrite the current property with the new value.
target = mapbox::util::apply_visitor(evaluator, property.value);
@@ -144,7 +143,7 @@ void StyleLayer::applyTransitionedStyleProperty(PropertyKey key, T &target, cons
AppliedClassProperties &applied = it->second;
// Iterate through all properties that we need to apply in order.
const PropertyEvaluator<T> evaluator(z, zoomHistory);
- for (AppliedClassProperty &property : applied.properties) {
+ for (auto& property : applied.properties) {
if (now >= property.end) {
// We overwrite the current property with the new value.
target = mapbox::util::apply_visitor(evaluator, property.value);
@@ -250,7 +249,7 @@ void StyleLayer::updateProperties(float z, const std::chrono::steady_clock::time
}
bool StyleLayer::hasTransitions() const {
- for (const std::pair<PropertyKey, AppliedClassProperties> &pair : appliedStyle) {
+ for (const auto& pair : appliedStyle) {
if (pair.second.hasTransitions()) {
return true;
}
diff --git a/src/mbgl/style/style_layer.hpp b/src/mbgl/style/style_layer.hpp
index 6e1fc7912b..e33d510975 100644
--- a/src/mbgl/style/style_layer.hpp
+++ b/src/mbgl/style/style_layer.hpp
@@ -8,6 +8,7 @@
#include <mbgl/style/zoom_history.hpp>
#include <mbgl/util/ptr.hpp>
+#include <mbgl/util/noncopyable.hpp>
#include <vector>
#include <string>
@@ -18,9 +19,8 @@
namespace mbgl {
class StyleBucket;
-class StyleLayerGroup;
-class StyleLayer {
+class StyleLayer : public util::noncopyable {
public:
StyleLayer(const std::string &id, std::map<ClassID, ClassProperties> &&styles);
diff --git a/src/mbgl/style/style_layer_group.cpp b/src/mbgl/style/style_layer_group.cpp
deleted file mode 100644
index f57ec5cc7b..0000000000
--- a/src/mbgl/style/style_layer_group.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include <mbgl/style/style_layer_group.hpp>
-
-namespace mbgl {
-
-void StyleLayerGroup::setClasses(const std::vector<std::string> &class_names, std::chrono::steady_clock::time_point now,
- const PropertyTransition &defaultTransition) {
- for (const util::ptr<StyleLayer> &layer : layers) {
- if (layer) {
- layer->setClasses(class_names, now, defaultTransition);
- }
- }
-}
-
-void StyleLayerGroup::updateProperties(float z, std::chrono::steady_clock::time_point now, ZoomHistory &zoomHistory) {
- for (const util::ptr<StyleLayer> &layer: layers) {
- if (layer) {
- layer->updateProperties(z, now, zoomHistory);
- }
- }
-}
-
-bool StyleLayerGroup::hasTransitions() const {
- for (const util::ptr<const StyleLayer> &layer: layers) {
- if (layer) {
- if (layer->hasTransitions()) {
- return true;
- }
- }
- }
- return false;
-}
-
-
-}
diff --git a/src/mbgl/style/style_layer_group.hpp b/src/mbgl/style/style_layer_group.hpp
deleted file mode 100644
index 79b75a55e9..0000000000
--- a/src/mbgl/style/style_layer_group.hpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#ifndef MBGL_STYLE_STYLE_LAYER_GROUP
-#define MBGL_STYLE_STYLE_LAYER_GROUP
-
-#include <mbgl/style/style_layer.hpp>
-
-#include <vector>
-#include <chrono>
-
-namespace mbgl {
-
-class StyleLayerGroup {
-public:
- void setClasses(const std::vector<std::string> &class_names, std::chrono::steady_clock::time_point now,
- const PropertyTransition &defaultTransition);
- void updateProperties(float z, std::chrono::steady_clock::time_point now, ZoomHistory &zoomHistory);
-
- bool hasTransitions() const;
-public:
- std::vector<util::ptr<StyleLayer>> layers;
-};
-
-}
-
-#endif
diff --git a/src/mbgl/style/style_parser.cpp b/src/mbgl/style/style_parser.cpp
index 66938987fb..7024853704 100644
--- a/src/mbgl/style/style_parser.cpp
+++ b/src/mbgl/style/style_parser.cpp
@@ -1,6 +1,6 @@
#include <mbgl/style/style_source.hpp>
#include <mbgl/style/style_parser.hpp>
-#include <mbgl/style/style_layer_group.hpp>
+#include <mbgl/style/style_layer.hpp>
#include <mbgl/map/annotation.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/std.hpp>
@@ -9,6 +9,13 @@
#include <mbgl/platform/log.hpp>
#include <csscolorparser/csscolorparser.hpp>
+#pragma GCC diagnostic push
+#ifndef __clang__
+#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
+#endif
+#include <boost/algorithm/string.hpp>
+#pragma GCC diagnostic pop
+
#include <algorithm>
namespace mbgl {
@@ -28,8 +35,7 @@ void StyleParser::parse(JSVal document) {
}
if (document.HasMember("layers")) {
- root = createLayers(document["layers"]);
- parseLayers();
+ parseLayers(document["layers"]);
// create point annotations layer
//
@@ -38,8 +44,8 @@ void StyleParser::parse(JSVal document) {
std::map<ClassID, ClassProperties> paints;
util::ptr<StyleLayer> annotations = std::make_shared<StyleLayer>(id, std::move(paints));
annotations->type = StyleLayerType::Symbol;
- layers.emplace(id, std::pair<JSVal, util::ptr<StyleLayer>> { JSVal(id), annotations });
- root->layers.emplace_back(annotations);
+ layersMap.emplace(id, std::pair<JSVal, util::ptr<StyleLayer>> { JSVal(id), annotations });
+ layers.emplace_back(annotations);
util::ptr<StyleBucket> pointBucket = std::make_shared<StyleBucket>(annotations->type);
pointBucket->name = annotations->id;
@@ -447,6 +453,13 @@ bool StyleParser::parseOptionalProperty(const char *property_name, PropertyKey k
}
}
+std::string normalizeFontStack(const std::string &name) {
+ namespace algo = boost::algorithm;
+ std::vector<std::string> parts;
+ algo::split(parts, name, algo::is_any_of(","), algo::token_compress_on);
+ std::for_each(parts.begin(), parts.end(), [](std::string& str) { algo::trim(str); });
+ return algo::join(parts, ", ");
+}
template<> std::tuple<bool, std::string> StyleParser::parseProperty(JSVal value, const char *property_name) {
if (!value.IsString()) {
@@ -454,7 +467,13 @@ template<> std::tuple<bool, std::string> StyleParser::parseProperty(JSVal value,
return std::tuple<bool, std::string> { false, std::string() };
}
- return std::tuple<bool, std::string> { true, { value.GetString(), value.GetStringLength() } };
+ if (std::string { "text-font" } == property_name) {
+ return std::tuple<bool, std::string> {
+ true, normalizeFontStack({ value.GetString(), value.GetStringLength() })
+ };
+ } else {
+ return std::tuple<bool, std::string> { true, { value.GetString(), value.GetStringLength() } };
+ }
}
template<> std::tuple<bool, bool> StyleParser::parseProperty(JSVal value, const char *property_name) {
@@ -662,61 +681,48 @@ template<> std::tuple<bool, PiecewiseConstantFunction<Faded<std::string>>> Style
#pragma mark - Parse Layers
-std::unique_ptr<StyleLayerGroup> StyleParser::createLayers(JSVal value) {
- if (value.IsArray()) {
- std::unique_ptr<StyleLayerGroup> group = util::make_unique<StyleLayerGroup>();
- for (rapidjson::SizeType i = 0; i < value.Size(); ++i) {
- util::ptr<StyleLayer> layer = createLayer(value[i]);
- if (layer) {
- group->layers.emplace_back(layer);
- }
- }
- return group;
- } else {
+void StyleParser::parseLayers(JSVal value) {
+ if (!value.IsArray()) {
Log::Warning(Event::ParseStyle, "layers must be an array");
- return nullptr;
+ return;
}
-}
-util::ptr<StyleLayer> StyleParser::createLayer(JSVal value) {
- if (value.IsObject()) {
- if (!value.HasMember("id")) {
+ for (rapidjson::SizeType i = 0; i < value.Size(); ++i) {
+ JSVal layerValue = value[i];
+
+ if (!layerValue.IsObject()) {
+ Log::Warning(Event::ParseStyle, "layer must be an object");
+ continue;
+ }
+
+ if (!layerValue.HasMember("id")) {
Log::Warning(Event::ParseStyle, "layer must have an id");
- return nullptr;
+ continue;
}
- JSVal id = value["id"];
+ JSVal id = layerValue["id"];
if (!id.IsString()) {
Log::Warning(Event::ParseStyle, "layer id must be a string");
- return nullptr;
+ continue;
}
- const std::string layer_id = { id.GetString(), id.GetStringLength() };
-
- if (layers.find(layer_id) != layers.end()) {
- Log::Warning(Event::ParseStyle, "duplicate layer id %s", layer_id.c_str());
- return nullptr;
+ const std::string layerID = { id.GetString(), id.GetStringLength() };
+ if (layersMap.find(layerID) != layersMap.end()) {
+ Log::Warning(Event::ParseStyle, "duplicate layer id %s", layerID.c_str());
+ continue;
}
// Parse paints already, as they can't be inherited anyway.
std::map<ClassID, ClassProperties> paints;
- parsePaints(value, paints);
-
- util::ptr<StyleLayer> layer = std::make_shared<StyleLayer>(
- layer_id, std::move(paints));
+ parsePaints(layerValue, paints);
- // Store the layer ID so we can reference it later.
- layers.emplace(layer_id, std::pair<JSVal, util::ptr<StyleLayer>> { value, layer });
+ util::ptr<StyleLayer> layer = std::make_shared<StyleLayer>(layerID, std::move(paints));
- return layer;
- } else {
- Log::Warning(Event::ParseStyle, "layer must be an object");
- return nullptr;
+ layers.emplace_back(layer);
+ layersMap.emplace(layerID, std::pair<JSVal, util::ptr<StyleLayer>> { layerValue, layer });
}
-}
-void StyleParser::parseLayers() {
- for (std::pair<const std::string, std::pair<JSVal, util::ptr<StyleLayer>>> &pair : layers) {
+ for (auto& pair : layersMap) {
parseLayer(pair.second);
}
}
@@ -904,8 +910,8 @@ void StyleParser::parseReference(JSVal value, util::ptr<StyleLayer> &layer) {
return;
}
const std::string ref { value.GetString(), value.GetStringLength() };
- auto it = layers.find(ref);
- if (it == layers.end()) {
+ auto it = layersMap.find(ref);
+ if (it == layersMap.end()) {
Log::Warning(Event::ParseStyle, "layer '%s' references unknown layer %s", layer->id.c_str(), ref.c_str());
// We cannot parse this layer further.
return;
diff --git a/src/mbgl/style/style_parser.hpp b/src/mbgl/style/style_parser.hpp
index 736cb9e9fa..9ef74c8dc1 100644
--- a/src/mbgl/style/style_parser.hpp
+++ b/src/mbgl/style/style_parser.hpp
@@ -17,7 +17,6 @@ namespace mbgl {
enum class ClassID : uint32_t;
class StyleLayer;
-class StyleLayerGroup;
class StyleParser {
public:
@@ -27,8 +26,8 @@ public:
void parse(JSVal document);
- util::ptr<StyleLayerGroup> getLayers() {
- return root;
+ std::vector<util::ptr<StyleLayer>> getLayers() {
+ return layers;
}
std::string getSprite() const {
@@ -44,10 +43,7 @@ private:
JSVal replaceConstant(JSVal value);
void parseSources(JSVal value);
-
- std::unique_ptr<StyleLayerGroup> createLayers(JSVal value);
- util::ptr<StyleLayer> createLayer(JSVal value);
- void parseLayers();
+ void parseLayers(JSVal value);
void parseLayer(std::pair<JSVal, util::ptr<StyleLayer>> &pair);
void parsePaints(JSVal value, std::map<ClassID, ClassProperties> &paints);
void parsePaint(JSVal, ClassProperties &properties);
@@ -97,10 +93,10 @@ private:
std::unordered_map<std::string, const util::ptr<StyleSource>> sources;
// This stores the root layer.
- util::ptr<StyleLayerGroup> root;
+ std::vector<util::ptr<StyleLayer>> layers;
// This maps ids to Layer objects, with all items being at the root level.
- std::unordered_map<std::string, std::pair<JSVal, util::ptr<StyleLayer>>> layers;
+ std::unordered_map<std::string, std::pair<JSVal, util::ptr<StyleLayer>>> layersMap;
// Store a stack of layers we're parsing right now. This is to prevent reference cycles.
std::forward_list<StyleLayer *> stack;
diff --git a/src/mbgl/text/collision.cpp b/src/mbgl/text/collision.cpp
index 2e0ec6dce2..422cd0a60a 100644
--- a/src/mbgl/text/collision.cpp
+++ b/src/mbgl/text/collision.cpp
@@ -91,7 +91,7 @@ GlyphBox getMergedGlyphs(const GlyphBoxes &boxes, const CollisionAnchor &anchor)
mergedGlyphs.anchor = anchor;
CollisionRect &box = mergedGlyphs.box;
- for (const GlyphBox &glyph : boxes) {
+ for (const auto& glyph : boxes) {
const CollisionRect &gbox = glyph.box;
box.tl.x = util::min(box.tl.x, gbox.tl.x);
box.tl.y = util::min(box.tl.y, gbox.tl.y);
@@ -105,7 +105,7 @@ GlyphBox getMergedGlyphs(const GlyphBoxes &boxes, const CollisionAnchor &anchor)
float Collision::getPlacementScale(const GlyphBoxes &glyphs, float minPlacementScale, bool avoidEdges) {
- for (const GlyphBox &glyph : glyphs) {
+ for (const auto& glyph : glyphs) {
const CollisionRect &box = glyph.box;
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;
const CollisionAnchor &anchor = glyph.anchor;
@@ -141,7 +141,7 @@ float Collision::getPlacementScale(const GlyphBoxes &glyphs, float minPlacementS
const CollisionAnchor &na = anchor; // new anchor
const CollisionRect &nb = box; // new box
- for (const PlacementValue &value : blocking) {
+ for (const auto& value : blocking) {
const PlacementBox &placement = std::get<1>(value);
const CollisionAnchor &oa = placement.anchor; // old anchor
const CollisionRect &ob = placement.box; // old box
@@ -198,7 +198,7 @@ PlacementRange Collision::getPlacementRange(const GlyphBoxes &glyphs, float plac
bool horizontal) {
PlacementRange placementRange = {{2.0f * M_PI, 0}};
- for (const GlyphBox &glyph : glyphs) {
+ for (const auto& glyph : glyphs) {
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;
const CollisionAnchor &anchor = glyph.anchor;
@@ -216,7 +216,7 @@ PlacementRange Collision::getPlacementRange(const GlyphBoxes &glyphs, float plac
cTree.query(bgi::intersects(query_box), std::back_inserter(blocking));
}
- for (const PlacementValue &value : blocking) {
+ for (const auto& value : blocking) {
const Box &s = std::get<0>(value);
const PlacementBox &b = std::get<1>(value);
const CollisionRect &bbox2 = b.hBox ? b.hBox.get() : b.box;
@@ -265,7 +265,7 @@ void Collision::insert(const GlyphBoxes &glyphs, const CollisionAnchor &anchor,
std::vector<PlacementValue> allBounds;
allBounds.reserve(glyphs.size());
- for (const GlyphBox &glyph : glyphs) {
+ for (const auto& glyph : glyphs) {
const CollisionRect &box = glyph.box;
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;
diff --git a/src/mbgl/text/collision.hpp b/src/mbgl/text/collision.hpp
index b009982997..bba07b0fb1 100644
--- a/src/mbgl/text/collision.hpp
+++ b/src/mbgl/text/collision.hpp
@@ -4,6 +4,7 @@
#include <mbgl/text/types.hpp>
#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wshadow"
diff --git a/src/mbgl/text/glyph_store.cpp b/src/mbgl/text/glyph_store.cpp
index ab1776c04b..fd8f99ea5b 100644
--- a/src/mbgl/text/glyph_store.cpp
+++ b/src/mbgl/text/glyph_store.cpp
@@ -68,7 +68,7 @@ void align(Shaping &shaping, const float justify, const float horizontalAlign,
const float shiftX = (justify - horizontalAlign) * maxLineLength;
const float shiftY = (-verticalAlign * (line + 1) + 0.5) * lineHeight;
- for (PositionedGlyph &glyph : shaping) {
+ for (auto& glyph : shaping) {
glyph.x += shiftX;
glyph.y += shiftY;
}
@@ -251,7 +251,7 @@ void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set
// Attempt to load the glyph range. If the GlyphSet already exists, we are getting back
// the same shared_future.
- for (GlyphRange range : glyphRanges) {
+ for (const auto range : glyphRanges) {
futures.emplace_back(loadGlyphRange(fontStack, rangeSets, range));
}
}
@@ -259,7 +259,7 @@ void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set
// Now that we potentially created all GlyphSets, we are waiting for the results, one by one.
// When we get a result (or the GlyphSet is aready loaded), we are attempting to parse the
// GlyphSet.
- for (std::shared_future<GlyphPBF &> &future : futures) {
+ for (const auto& future : futures) {
future.get().parse(stack);
}
}
diff --git a/src/mbgl/text/placement.cpp b/src/mbgl/text/placement.cpp
index 9d9e82c75c..6a142cdf65 100644
--- a/src/mbgl/text/placement.cpp
+++ b/src/mbgl/text/placement.cpp
@@ -110,7 +110,7 @@ GlyphBox getMergedBoxes(const GlyphBoxes &glyphs, const Anchor &anchor) {
CollisionRect &box = mergedglyphs.box;
- for (const GlyphBox &glyph : glyphs) {
+ for (const auto& glyph : glyphs) {
const CollisionRect &gbox = glyph.box;
box.tl.x = util::min(box.tl.x, gbox.tl.x);
box.tl.y = util::min(box.tl.y, gbox.tl.y);
@@ -211,7 +211,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const uint32_t buffer = 3;
- for (const PositionedGlyph &shape : shaping) {
+ for (const auto& shape : shaping) {
auto face_it = face.find(shape.glyph);
if (face_it == face.end())
continue;
@@ -250,7 +250,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const CollisionRect obox{boxScale * x1, boxScale * y1, boxScale * x2, boxScale * y2};
- for (const GlyphInstance &instance : glyphInstances) {
+ for (const auto& instance : glyphInstances) {
vec2<float> tl = otl;
vec2<float> tr = otr;
vec2<float> bl = obl;
@@ -301,7 +301,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const float minPlacementScale = anchor.scale;
placement.minScale = std::numeric_limits<float>::infinity();
- for (const GlyphBox &box : placement.boxes) {
+ for (const auto& box : placement.boxes) {
placement.minScale = util::min(placement.minScale, box.minScale);
}
placement.minScale = util::max(minPlacementScale, Placement::globalMinScale);
diff --git a/src/mbgl/text/rotation_range.cpp b/src/mbgl/text/rotation_range.cpp
index 664ea9c709..efaa1c67ed 100644
--- a/src/mbgl/text/rotation_range.cpp
+++ b/src/mbgl/text/rotation_range.cpp
@@ -17,7 +17,7 @@ CollisionRange mergeCollisions(const CollisionList &collisions,
float min = 2.0f * M_PI;
float max = 0.0f;
- for (CollisionRange collision : collisions) {
+ for (const auto& collision : collisions) {
bool entryOutside =
ignoreRange[0] <= collision[0] && collision[0] <= ignoreRange[1];
bool exitOutside =
diff --git a/src/mbgl/util/clip_ids.cpp b/src/mbgl/util/clip_ids.cpp
index 8b1dcf8dd0..e7833b679f 100644
--- a/src/mbgl/util/clip_ids.cpp
+++ b/src/mbgl/util/clip_ids.cpp
@@ -18,7 +18,7 @@ ClipIDGenerator::Leaf::Leaf(Tile &tile_) : tile(tile_) {}
void ClipIDGenerator::Leaf::add(const Tile::ID &p) {
if (p.isChildOf(tile.id)) {
// Ensure that no already present child is a parent of the new p.
- for (const Tile::ID &child : children) {
+ for (const auto& child : children) {
if (p.isChildOf(child))
return;
}
@@ -31,7 +31,7 @@ bool ClipIDGenerator::Leaf::operator==(const Leaf &other) const {
}
bool ClipIDGenerator::reuseExisting(Leaf &leaf) {
- for (const std::vector<Leaf> &pool : pools) {
+ for (const auto& pool : pools) {
auto existing = std::find(pool.begin(), pool.end(), leaf);
if (existing != pool.end()) {
leaf.tile.clip = existing->tile.clip;
@@ -80,7 +80,7 @@ void ClipIDGenerator::update(std::forward_list<Tile *> tiles) {
// We are starting our count with 1 since we need at least 1 bit set to distinguish between
// areas without any tiles whatsoever and the current area.
uint8_t count = 1;
- for (Leaf &leaf : pool) {
+ for (auto& leaf : pool) {
leaf.tile.clip.mask = mask;
leaf.tile.clip.reference = count++ << bit_offset;
}
diff --git a/src/mbgl/util/mapbox.cpp b/src/mbgl/util/mapbox.cpp
index 5d9c630c11..a8da81d1fd 100644
--- a/src/mbgl/util/mapbox.cpp
+++ b/src/mbgl/util/mapbox.cpp
@@ -8,11 +8,12 @@ namespace mapbox {
const std::string mapbox = "mapbox://";
-std::string normalizeURL(const std::string& url, const std::string& accessToken) {
+std::string normalizeURL(const std::string& url, const std::string& pathPrefix, const std::string& accessToken) {
if (accessToken.empty())
throw std::runtime_error("You must provide a Mapbox API access token for Mapbox tile sources");
- return std::string("https://api.tiles.mapbox.com/v4/")
+ return std::string("https://api.tiles.mapbox.com")
+ + pathPrefix
+ url.substr(mapbox.length())
+ "?access_token="
+ accessToken;
@@ -22,7 +23,7 @@ std::string normalizeSourceURL(const std::string& url, const std::string& access
if (url.compare(0, mapbox.length(), mapbox) != 0)
return url;
- std::string result = normalizeURL(url + ".json", accessToken);
+ std::string result = normalizeURL(url + ".json", "/v4/", accessToken);
// TileJSON requests need a secure flag appended to their URLs so
// that the server knows to send SSL-ified resource references.
@@ -31,11 +32,20 @@ std::string normalizeSourceURL(const std::string& url, const std::string& access
return result;
}
+std::string normalizeStyleURL(const std::string& url, const std::string& accessToken) {
+ if (url.compare(0, mapbox.length(), mapbox) != 0)
+ return url;
+
+ const std::string user = url.substr(mapbox.length(), url.find('.') - mapbox.length());
+
+ return normalizeURL(url, "/styles/v1/" + user + "/", accessToken);
+}
+
std::string normalizeGlyphsURL(const std::string& url, const std::string& accessToken) {
if (url.compare(0, mapbox.length(), mapbox) != 0)
return url;
- return normalizeURL(url, accessToken);
+ return normalizeURL(url, "/v4/", accessToken);
}
std::string normalizeTileURL(const std::string& url, const std::string& sourceURL, SourceType sourceType) {
diff --git a/src/mbgl/util/mapbox.hpp b/src/mbgl/util/mapbox.hpp
index 8ad92c0b40..86ea349b8c 100644
--- a/src/mbgl/util/mapbox.hpp
+++ b/src/mbgl/util/mapbox.hpp
@@ -9,6 +9,7 @@ namespace util {
namespace mapbox {
std::string normalizeSourceURL(const std::string& url, const std::string& accessToken);
+std::string normalizeStyleURL(const std::string& url, const std::string& accessToken);
std::string normalizeGlyphsURL(const std::string& url, const std::string& accessToken);
std::string normalizeTileURL(const std::string& url, const std::string& sourceURL, SourceType sourceType);
diff --git a/src/mbgl/util/merge_lines.cpp b/src/mbgl/util/merge_lines.cpp
index 7eb8306707..4ff1caaf76 100644
--- a/src/mbgl/util/merge_lines.cpp
+++ b/src/mbgl/util/merge_lines.cpp
@@ -1,13 +1,16 @@
#include "merge_lines.hpp"
-#include <sstream>
+
+#include <boost/functional/hash.hpp>
namespace mbgl {
namespace util {
+using Index = std::map<size_t, unsigned int>;
+
unsigned int mergeFromRight(std::vector<SymbolFeature> &features,
- std::map<std::string, unsigned int> &rightIndex,
- std::map<std::string, unsigned int>::iterator left,
- std::string &rightKey,
+ Index &rightIndex,
+ Index::iterator left,
+ size_t rightKey,
std::vector<std::vector<Coordinate>> &geom) {
unsigned int index = left->second;
@@ -21,9 +24,9 @@ unsigned int mergeFromRight(std::vector<SymbolFeature> &features,
}
unsigned int mergeFromLeft(std::vector<SymbolFeature> &features,
- std::map<std::string, unsigned int> &leftIndex,
- std::string &leftKey,
- std::map<std::string, unsigned int>::iterator right,
+ Index &leftIndex,
+ size_t leftKey,
+ Index::iterator right,
std::vector<std::vector<Coordinate>> &geom) {
unsigned int index = right->second;
@@ -37,21 +40,20 @@ unsigned int mergeFromLeft(std::vector<SymbolFeature> &features,
return index;
}
-std::string
-getKey(const std::u32string &text, const std::vector<std::vector<Coordinate>> &geom, bool onRight) {
- const Coordinate &coord = onRight ? geom[0].back() : geom[0].front();
- std::ostringstream key;
- for (const char32_t &c : text) {
- key << (char)c;
- }
- key << ":" << coord.x << ":" << coord.y;
- return key.str();
+size_t
+getKey(const std::u32string& text, const std::vector<std::vector<Coordinate>>& geom, bool onRight) {
+ const Coordinate& coord = onRight ? geom[0].back() : geom[0].front();
+
+ auto hash = std::hash<std::u32string>()(text);
+ boost::hash_combine(hash, coord.x);
+ boost::hash_combine(hash, coord.y);
+ return hash;
}
void mergeLines(std::vector<SymbolFeature> &features) {
- std::map<std::string, unsigned int> leftIndex;
- std::map<std::string, unsigned int> rightIndex;
+ Index leftIndex;
+ Index rightIndex;
for (unsigned int k = 0; k < features.size(); k++) {
SymbolFeature &feature = features[k];
@@ -61,11 +63,11 @@ void mergeLines(std::vector<SymbolFeature> &features) {
continue;
}
- std::string leftKey = getKey(feature.label, geometry, false);
- std::string rightKey = getKey(feature.label, geometry, true);
+ const auto leftKey = getKey(feature.label, geometry, false);
+ const auto rightKey = getKey(feature.label, geometry, true);
- auto left = rightIndex.find(leftKey);
- auto right = leftIndex.find(rightKey);
+ const auto left = rightIndex.find(leftKey);
+ const auto right = leftIndex.find(rightKey);
if ((left != rightIndex.end()) && (right != leftIndex.end()) &&
(left->second != right->second)) {
diff --git a/src/mbgl/util/scaling.cpp b/src/mbgl/util/scaling.cpp
index a554b2e137..efc2709df3 100644
--- a/src/mbgl/util/scaling.cpp
+++ b/src/mbgl/util/scaling.cpp
@@ -49,38 +49,39 @@ namespace util {
void bilinearScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData, const vec2<uint32_t>& dstSize,
- const Rect<uint32_t>& dstPos) {
+ const Rect<uint32_t>& dstPos, bool wrap) {
const auto factor = getFactor(srcPos, dstPos);
const auto bounds = getBounds(srcSize, srcPos, dstSize, dstPos, factor);
- double fractSrcY = srcPos.y;
- double fractSrcX;
uint32_t x, y;
size_t i = dstSize.x * dstPos.y + dstPos.x;
for (y = 0; y < bounds.y; y++) {
- fractSrcX = srcPos.x;
- const uint32_t srcY0 = fractSrcY;
- const uint32_t srcY1 = std::min(srcY0 + 1, srcSize.y - 1);
+ const double fractY = y * factor.y;
+ const uint32_t Y0 = fractY;
+ const uint32_t Y1 = wrap ? (Y0 + 1) % srcPos.h : (Y0 + 1);
+ const uint32_t srcY0 = srcPos.y + Y0;
+ const uint32_t srcY1 = std::min(srcPos.y + Y1, srcSize.y - 1);
for (x = 0; x < bounds.x; x++) {
- const uint32_t srcX0 = fractSrcX;
- const uint32_t srcX1 = std::min(srcX0 + 1, srcSize.x - 1);
+ const double fractX = x * factor.x;
+ const uint32_t X0 = fractX;
+ const uint32_t X1 = wrap ? (X0 + 1) % srcPos.w : (X0 + 1);
+ const uint32_t srcX0 = srcPos.x + X0;
+ const uint32_t srcX1 = std::min(srcPos.x + X1, srcSize.x - 1);
const uint32_t tl = srcData[srcSize.x * srcY0 + srcX0];
const uint32_t tr = srcData[srcSize.x * srcY0 + srcX1];
const uint32_t bl = srcData[srcSize.x * srcY1 + srcX0];
const uint32_t br = srcData[srcSize.x * srcY1 + srcX1];
- const double dx = fractSrcX - srcX0;
- const double dy = fractSrcY - srcY0;
+ const double dx = fractX - X0;
+ const double dy = fractY - Y0;
uint32_t& dst = dstData[i + x];
b<0>(dst) = bilinearInterpolate(b<0>(tl), b<0>(tr), b<0>(bl), b<0>(br), dx, dy);
b<1>(dst) = bilinearInterpolate(b<1>(tl), b<1>(tr), b<1>(bl), b<1>(br), dx, dy);
b<2>(dst) = bilinearInterpolate(b<2>(tl), b<2>(tr), b<2>(bl), b<2>(br), dx, dy);
b<3>(dst) = bilinearInterpolate(b<3>(tl), b<3>(tr), b<3>(bl), b<3>(br), dx, dy);
- fractSrcX += factor.x;
}
i += dstSize.x;
- fractSrcY += factor.y;
}
}
@@ -108,4 +109,4 @@ void nearestNeighborScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize
}
}
-} \ No newline at end of file
+}
diff --git a/src/mbgl/util/scaling.hpp b/src/mbgl/util/scaling.hpp
index d2625e9219..74a43eb621 100644
--- a/src/mbgl/util/scaling.hpp
+++ b/src/mbgl/util/scaling.hpp
@@ -12,7 +12,7 @@ namespace util {
void bilinearScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData, const vec2<uint32_t>& dstSize,
- const Rect<uint32_t>& dstPos);
+ const Rect<uint32_t>& dstPos, bool wrap);
void nearestNeighborScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData,
diff --git a/test/fixtures/fixture_log_observer.cpp b/test/fixtures/fixture_log_observer.cpp
index 08a6415643..f66d185439 100644
--- a/test/fixtures/fixture_log_observer.cpp
+++ b/test/fixtures/fixture_log_observer.cpp
@@ -28,7 +28,7 @@ bool FixtureLogObserver::onRecord(EventSeverity severity, Event event, int64_t c
size_t FixtureLogObserver::count(const LogMessage &message) const {
size_t message_count = 0;
- for (const LogMessage &msg : messages) {
+ for (const auto& msg : messages) {
if (msg == message) {
message_count++;
msg.checked = true;
@@ -39,7 +39,7 @@ size_t FixtureLogObserver::count(const LogMessage &message) const {
std::vector<FixtureLogObserver::LogMessage> FixtureLogObserver::unchecked() const {
std::vector<LogMessage> unchecked_messages;
- for (const LogMessage &msg : messages) {
+ for (const auto& msg : messages) {
if (!msg.checked) {
unchecked_messages.push_back(msg);
msg.checked = true;
@@ -50,7 +50,7 @@ std::vector<FixtureLogObserver::LogMessage> FixtureLogObserver::unchecked() cons
::std::ostream &operator<<(::std::ostream &os,
const std::vector<FixtureLogObserver::LogMessage> &messages) {
- for (const FixtureLogObserver::LogMessage &message : messages) {
+ for (const auto& message : messages) {
os << "- " << message;
}
return os;
diff --git a/test/fixtures/sprites/atlas_reference.bin b/test/fixtures/sprites/atlas_reference.bin
index 57eb28bd93..d75d961b60 100644
--- a/test/fixtures/sprites/atlas_reference.bin
+++ b/test/fixtures/sprites/atlas_reference.bin
Binary files differ
diff --git a/test/fixtures/sprites/atlas_reference.png b/test/fixtures/sprites/atlas_reference.png
index 86fad30983..9107aefe09 100644
--- a/test/fixtures/sprites/atlas_reference.png
+++ b/test/fixtures/sprites/atlas_reference.png
Binary files differ
diff --git a/test/miscellaneous/bilinear.cpp b/test/miscellaneous/bilinear.cpp
index b7730303a0..9808e20fef 100644
--- a/test/miscellaneous/bilinear.cpp
+++ b/test/miscellaneous/bilinear.cpp
@@ -28,19 +28,19 @@ TEST(Bilinear, Scaling) {
uint32_t *dstData = dst.get();
std::fill(dstData, dstData + dstSize.x * dstSize.y, 0xFFFF00FF);
- util::bilinearScale(srcData, srcSize, { 0, 0, 24, 24 }, dstData, dstSize, { 8, 8, 24, 24 });
- util::bilinearScale(srcData, srcSize, { 26, 0, 24, 24 }, dstData, dstSize, { 0, 40, 48, 48 });
- util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 });
- util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 });
- util::bilinearScale(srcData, srcSize, { 104, 0, 24, 24 }, dstData, dstSize, { 96, 0, 48, 48 });
- util::bilinearScale(srcData, srcSize, { 52, 260, 24, 24 }, dstData, dstSize, { 108, 108, 38, 38 });
- util::bilinearScale(srcData, srcSize, { 380, 0, 24, 24 }, dstData, dstSize, { 36, 0, 24, 24 });
- util::bilinearScale(srcData, srcSize, { 396, 396, 24, 24 }, dstData, dstSize, { 0, 0, 50, 50 });
- util::bilinearScale(srcData, srcSize, { 380, 182, 12, 12 }, dstData, dstSize, { 52, 80, 24, 24 });
+ util::bilinearScale(srcData, srcSize, { 0, 0, 24, 24 }, dstData, dstSize, { 8, 8, 24, 24 }, false);
+ util::bilinearScale(srcData, srcSize, { 26, 0, 24, 24 }, dstData, dstSize, { 0, 40, 48, 48 }, false);
+ util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 }, false);
+ util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 }, false);
+ util::bilinearScale(srcData, srcSize, { 104, 0, 24, 24 }, dstData, dstSize, { 96, 0, 48, 48 }, false);
+ util::bilinearScale(srcData, srcSize, { 52, 260, 24, 24 }, dstData, dstSize, { 108, 108, 38, 38 }, false);
+ util::bilinearScale(srcData, srcSize, { 380, 0, 24, 24 }, dstData, dstSize, { 36, 0, 24, 24 }, false);
+ util::bilinearScale(srcData, srcSize, { 396, 396, 24, 24 }, dstData, dstSize, { 0, 0, 50, 50 }, false);
+ util::bilinearScale(srcData, srcSize, { 380, 182, 12, 12 }, dstData, dstSize, { 52, 80, 24, 24 }, false);
// From the bottom
- util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 0, 90, 12, 12 });
- util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 18, 90, 24, 24 });
+ util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 0, 90, 12, 12 }, false);
+ util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 18, 90, 24, 24 }, false);
const std::string data { reinterpret_cast<char *>(dstData), dstSize.x * dstSize.y * sizeof(uint32_t) };
util::write_file("test/fixtures/sprites/atlas_actual.png", util::compress_png(dstSize.x, dstSize.y, dstData));
diff --git a/test/miscellaneous/mapbox.cpp b/test/miscellaneous/mapbox.cpp
index 926c842e22..1aff2494a4 100644
--- a/test/miscellaneous/mapbox.cpp
+++ b/test/miscellaneous/mapbox.cpp
@@ -18,6 +18,11 @@ TEST(Mapbox, GlyphsURL) {
EXPECT_EQ(mbgl::util::mapbox::normalizeGlyphsURL("http://path", "key"), "http://path");
}
+TEST(Mapbox, StyleURL) {
+ EXPECT_EQ(mbgl::util::mapbox::normalizeStyleURL("mapbox://user.style", "key"), "https://api.tiles.mapbox.com/styles/v1/user/user.style?access_token=key");
+ EXPECT_EQ(mbgl::util::mapbox::normalizeStyleURL("http://path", "key"), "http://path");
+}
+
TEST(Mapbox, TileURL) {
try {
EXPECT_EQ(mbgl::util::mapbox::normalizeTileURL("http://path.png/tile.png", "mapbox://user.map", SourceType::Raster), "http://path.png/tile{ratio}.png");