diff --git a/.gitmodules b/.gitmodules index 9e5265a6a..6a4b1d516 100644 --- a/.gitmodules +++ b/.gitmodules @@ -12,7 +12,7 @@ [submodule "test/ios/KIF"] path = test/ios/KIF - url = https://github.com/mapbox/KIF.git + url = https://github.com/kif-framework/KIF.git [submodule "platform/ios/vendor/SMCalloutView"] path = platform/ios/vendor/SMCalloutView diff --git a/.travis.yml b/.travis.yml index e3c541c86..71936b872 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,7 +35,10 @@ matrix: env: BUILDTYPE=Release JOBS=8 compiler: gcc - os: osx - env: BUILDTYPE=Debug JOBS=8 + env: BUILDTYPE=Debug JOBS=8 MASON_PLATFORM=osx + compiler: clang + - os: osx + env: BUILDTYPE=Release JOBS=8 MASON_PLATFORM=ios compiler: clang env: @@ -54,6 +57,7 @@ env: - IOS_PROFILE_NAME="ios-in-house" - secure: "nQqSM8rd7OHtV4MqmNqVnkrVHqxKqQsaWRYk4/nPdhbeVWtTtkk0df711LrF1TUtbEPEewHxYUvTZ/UXmwJNeoKdzTHavI8hnatRkgjyxGERPn1il1Otelht9I+LQQHf+plrpRjVWBrNIW0Zox1B3cqn6d3NglpbXrEQ2EjYGNA=" # end iOS code signing + - KIF_SCREENSHOTS="${TRAVIS_BUILD_DIR}/screenshots" before_install: - if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then sudo service mysql stop; fi @@ -65,6 +69,7 @@ before_install: - ./scripts/travis_before_install.sh - if [[ ${TRAVIS_OS_NAME} == "linux" && ${MASON_PLATFORM} != "android" ]]; then export LD_LIBRARY_PATH=`mason prefix mesa 10.4.3`/lib; fi - if [[ ${TRAVIS_OS_NAME} == "linux" && ${MASON_PLATFORM} != "android" ]]; then glxinfo; fi +- if [[ ${TRAVIS_OS_NAME} == "osx" && ${TEST_OS} == "ios" ]]; then mkdir -p ${KIF_SCREENSHOTS}; fi install: - ulimit -c @@ -85,6 +90,9 @@ script: after_script: - ./scripts/ios_travis/remove-key.sh +after_failure: +- if [[ ${TRAVIS_OS_NAME} == "osx" && ${TEST_OS} == "ios" ]]; then ./scripts/ios_travis/upload_screenshots.sh; fi + notifications: slack: secure: HHQYr7sF8M1SzoWSqgKVYtwAgGdLLCyTMsQjFhEEQNYO92ZwURE5s03qWTGH5k8+4Yqn26yrXt3NztLC4JIOpcGervN2mSZyq4dZgFTcWEd61igw0qwSenlwvFfbE1ASK/KYCzfyn9MIfHN+ovwLoRxXZkPwinKDvl3DXjBaFNg= diff --git a/Makefile b/Makefile index 4c830fd83..11eb5e530 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,16 @@ PREFIX ?= /usr/local ANDROID_ABI ?= arm-v7 ifeq ($(shell uname -s), Darwin) -HOST ?= osx +HOST = osx +HEADLESS = cgl JOBS ?= $(shell sysctl -n hw.ncpu) endif -HOST ?= linux + +ifeq ($(shell uname -s), Linux) +HOST = linux +JOBS ?= $(shell sysctl -n hw.ncpu) +endif + JOBS ?= 1 all: mbgl @@ -28,48 +34,45 @@ styles/styles: SMCalloutView: git submodule update --init platform/ios/vendor/SMCalloutView +KIF: + git submodule update --init test/ios/KIF + + +#### Build files ############################################################### + +.PRECIOUS: Makefile/project +Makefile/project: config/$(HOST).gypi styles/styles SMCalloutView + deps/run_gyp gyp/project.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make + +.PRECIOUS: Xcode/project +Xcode/project: config/$(HOST).gypi styles/styles SMCalloutView + deps/run_gyp gyp/project.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f xcode + + #### Library builds ############################################################ -.PRECIOUS: Makefile/mbgl -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 +mbgl: Makefile/project $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) everything -standalone: Makefile/mbgl +standalone: Makefile/project LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) standalone -install: Makefile/mbgl +install: Makefile/project LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) install -.PRECIOUS: Xcode/mbgl -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 SMCalloutView - deps/run_gyp test/test.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make - -test: Makefile/test +.PHONY: test +test: Makefile/project $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) test test-%: test ./scripts/run_tests.sh "build/$(HOST)/$(BUILDTYPE)/test" --gtest_filter=$* - -.PRECIOUS: Xcode/test -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 -xtest-proj: Xcode/test - open ./build/osx/test/test.xcodeproj - -xtest: Xcode/test - xcodebuild -project ./build/osx/test/test.xcodeproj -configuration $(BUILDTYPE) -target test -jobs $(JOBS) +.PHONY: xtest +xtest: Xcode/project + xcodebuild -project ./build/osx/gyp/project.xcodeproj -configuration $(BUILDTYPE) -target test -jobs $(JOBS) xtest-%: xtest ./scripts/run_tests.sh "build/osx/Build/Products/$(BUILDTYPE)/test" --gtest_filter=$* @@ -77,31 +80,22 @@ xtest-%: xtest #### Mac OS X application builds ############################################### -.PRECIOUS: Makefile/osx -Makefile/osx: macosx/mapboxgl-app.gyp config/osx.gypi styles/styles - deps/run_gyp macosx/mapboxgl-app.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f make - .PHONY: osx run-osx -osx: Makefile/osx +osx: Makefile/project $(MAKE) -C build/osx BUILDTYPE=$(BUILDTYPE) osxapp run-osx: osx "build/osx/$(BUILDTYPE)/Mapbox GL.app/Contents/MacOS/Mapbox GL" - -.PRECIOUS: Xcode/osx -Xcode/osx: macosx/mapboxgl-app.gyp config/osx.gypi styles/styles - deps/run_gyp macosx/mapboxgl-app.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f xcode - .PHONY: xosx-proj xosx run-xosx -xosx-proj: Xcode/osx - open ./build/osx/macosx/mapboxgl-app.xcodeproj +xosx-proj: Xcode/project + open ./build/osx/gyp/project.xcodeproj -xosx: Xcode/osx - xcodebuild -project ./build/osx/macosx/mapboxgl-app.xcodeproj -configuration $(BUILDTYPE) -target osxapp -jobs $(JOBS) +xosx: Xcode/project + xcodebuild -project ./build/osx/gyp/project.xcodeproj -configuration $(BUILDTYPE) -target osxapp -jobs $(JOBS) run-xosx: xosx - "build/osx/Build/Products/$(BUILDTYPE)/Mapbox GL.app/Contents/MacOS/Mapbox GL" + "gyp/build/$(BUILDTYPE)/Mapbox GL.app/Contents/MacOS/Mapbox GL" # Legacy name xproj: xosx-proj @@ -114,7 +108,7 @@ xproj: xosx-proj 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 +.PHONY: ios-proj ios isim ipackage ios-proj: Xcode/ios open ./build/ios/ios/app/mapboxgl-app.xcodeproj @@ -124,40 +118,31 @@ ios: Xcode/ios isim: Xcode/ios xcodebuild -sdk iphonesimulator ARCHS="x86_64 i386" -project ./build/ios/ios/app/mapboxgl-app.xcodeproj -configuration Debug -target iosapp -jobs $(JOBS) +ipackage: clean Xcode/ios + ./scripts/package_ios.sh + +itest: ipackage KIF + ./scripts/test_ios.sh + # Legacy name iproj: ios-proj #### Linux application builds ################################################## -.PRECIOUS: Makefile/linux -Makefile/linux: linux/mapboxgl-app.gyp config/$(HOST).gypi styles/styles - deps/run_gyp linux/mapboxgl-app.gyp $(CONFIG_$(HOST)) $(LIBS_linux) --generator-output=./build/$(HOST) -f make - .PHONY: linux run-linux -linux: Makefile/linux +linux: Makefile/project $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) linuxapp run-linux: linux (cd build/$(HOST)/$(BUILDTYPE) && ./mapbox-gl) - -.PRECIOUS: Xcode/linux -Xcode/linux: linux/mapboxgl-app.gyp config/osx.gypi styles/styles - deps/run_gyp linux/mapboxgl-app.gyp $(CONFIG_osx) $(LIBS_linux) --generator-output=./build/osx -f xcode - -.PHONY: lproj lbuild run-xlinux -xlinux-proj: Xcode/linux - open ./build/osx/linux/mapboxgl-app.xcodeproj - -xlinux: Xcode/linux - xcodebuild -project ./build/osx/linux/mapboxgl-app.xcodeproj -configuration $(BUILDTYPE) -target linuxapp +.PHONY: xlinux run-xlinux +xlinux: Xcode/project + xcodebuild -project ./build/osx/gyp/project.xcodeproj -configuration $(BUILDTYPE) -target linuxapp -jobs $(JOBS) run-xlinux: xlinux - "build/osx/Build/Products/$(BUILDTYPE)/mapbox-gl" - -# Legacy name -lproj: xlinux-proj + "gyp/build/$(BUILDTYPE)/mapbox-gl" #### Android libaries ######################################################### @@ -189,22 +174,15 @@ android-deploy: $(ANDROID_ABIS) android-project: android-lib + ##### Render builds ############################################################ -.PRECIOUS: Makefile/render -Makefile/render: bin/render.gyp config/$(HOST).gypi - deps/run_gyp bin/render.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make - -render: Makefile/render +render: Makefile/project $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) mbgl-render -.PRECIOUS: Xcode/render -Xcode/render: bin/render.gyp config/osx.gypi styles/styles - deps/run_gyp bin/render.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f xcode - -.PHONY: xrender-proj -xrender-proj: Xcode/render - open ./build/osx/bin/render.xcodeproj +.PHONY: xrender run-xrender +xrender: Xcode/project + xcodebuild -project ./build/osx/gyp/project.xcodeproj -configuration $(BUILDTYPE) -target mbgl-render -jobs $(JOBS) ##### Maintenace operations #################################################### diff --git a/README.md b/README.md index f48a72b99..a44b13861 100644 --- a/README.md +++ b/README.md @@ -64,11 +64,14 @@ If you merely want to install the library for iOS and try it out as an Objective - `libc++.dylib` - `libsqlite3.dylib` - `libz.dylib` -4. [Set the Mapbox API access token](#mapbox-api-access-tokens). -5. `#import "MGLMapView.h"` +4. Add `-ObjC` to your target's "Other Linker Flags" build setting (`OTHER_LDFLAGS`). +5. [Set the Mapbox API access token](#mapbox-api-access-tokens). +6. `#import "MapboxGL.h"` If you want to build from source and/or contribute to development of the project, run `make iproj`, which will create and open an Xcode project which can build the entire library from source as well as an Objective-C test app. +You can also run `make itest` to run the included tests. Requires `brew install xcpretty`. + Target devices: iPhone 4S and above (5, 5c, 5s, 6, 6 Plus) and iPad 2 and above (3, 4, Mini, Air, Mini 2, Air 2). Target iOS: 7.0 through 8.1 diff --git a/android/cpp/jni.cpp b/android/cpp/jni.cpp index b6e46ed5a..ac5188484 100644 --- a/android/cpp/jni.cpp +++ b/android/cpp/jni.cpp @@ -283,13 +283,6 @@ void JNICALL nativeResume(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { nativeMapView->resume(); } -void JNICALL nativeRun(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeRun"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().run(); -} - void JNICALL nativeUpdate(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeUpdate"); assert(nativeMapViewPtr != 0); @@ -934,9 +927,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { return JNI_ERR; } - // NOTE: if you get java.lang.UnsatisfiedLinkError you likely forgot to set the size of the - // array correctly (too large) - std::array methods = {{ // Can remove the extra brace in C++14 + const std::vector methods = { {"nativeCreate", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)J", reinterpret_cast(&nativeCreate)}, {"nativeDestroy", "(J)V", reinterpret_cast(&nativeDestroy)}, @@ -951,7 +942,6 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"nativeStop", "(J)V", reinterpret_cast(&nativeStop)}, {"nativePause", "(J)V", reinterpret_cast(&nativePause)}, {"nativeResume", "(J)V", reinterpret_cast(&nativeResume)}, - {"nativeRun", "(J)V", reinterpret_cast(&nativeRun)}, {"nativeUpdate", "(J)V", reinterpret_cast(&nativeUpdate)}, {"nativeTerminate", "(J)V", reinterpret_cast(&nativeTerminate)}, {"nativeResize", "(JIIFII)V", @@ -1022,7 +1012,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"nativeLatLngForProjectedMeters", "(JLcom/mapbox/mapboxgl/geometry/ProjectedMeters;)Lcom/mapbox/mapboxgl/geometry/LatLng;", reinterpret_cast(&nativeLatLngForProjectedMeters)}, {"nativePixelForLatLng", "(JLcom/mapbox/mapboxgl/geometry/LatLng;)Landroid/graphics/PointF;", reinterpret_cast(&nativePixelForLatLng)}, {"nativeLatLngForPixel", "(JLandroid/graphics/PointF;)Lcom/mapbox/mapboxgl/geometry/LatLng;", reinterpret_cast(&nativeLatLngForPixel)}, - }}; + }; if (env->RegisterNatives(nativeMapViewClass, methods.data(), methods.size()) < 0) { env->ExceptionDescribe(); diff --git a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java index d7ca950fb..4dcd5ef8e 100644 --- a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java +++ b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java @@ -89,10 +89,6 @@ class NativeMapView { nativeResume(mNativeMapViewPtr); } - public void run() { - nativeRun(mNativeMapViewPtr); - } - public void update() { nativeUpdate(mNativeMapViewPtr); } @@ -398,8 +394,6 @@ class NativeMapView { private native void nativeResume(long nativeMapViewPtr); - private native void nativeRun(long nativeMapViewPtr); - private native void nativeUpdate(long nativeMapViewPtr); private native void nativeTerminate(long nativeMapViewPtr); diff --git a/bin/render.cpp b/bin/render.cpp index 01f692909..cd7a54f48 100644 --- a/bin/render.cpp +++ b/bin/render.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -7,7 +8,7 @@ #include #include #include -#include +#include #pragma GCC diagnostic push #ifndef __clang__ @@ -19,12 +20,13 @@ namespace po = boost::program_options; +#include + #include #include #include int main(int argc, char *argv[]) { - std::string style_path; double lat = 0, lon = 0; double zoom = 0; @@ -33,7 +35,7 @@ int main(int argc, char *argv[]) { int width = 512; int height = 512; double pixelRatio = 1.0; - std::string output = "out.png"; + static std::string output = "out.png"; std::string cache_file = "cache.sqlite"; std::vector classes; std::string token; @@ -81,6 +83,8 @@ int main(int argc, char *argv[]) { HeadlessView view; Map map(view, fileSource); + map.start(Map::Mode::Still); + // Set access token if present if (token.size()) { map.setAccessToken(std::string(token)); @@ -93,14 +97,24 @@ int main(int argc, char *argv[]) { map.setLatLngZoom({ lat, lon }, zoom); map.setBearing(bearing); - // Run the loop. It will terminate when we don't have any further listeners. - map.run(); + uv_async_t *async = new uv_async_t; + uv_async_init(uv_default_loop(), async, [](uv_async_t *as, int) { + std::unique_ptr image(reinterpret_cast(as->data)); + uv_close(reinterpret_cast(as), [](uv_handle_t *handle) { + delete reinterpret_cast(handle); + }); - // Get the data from the GPU. - auto pixels = view.readPixels(); + const std::string png = util::compress_png(image->width, image->height, image->pixels.get()); + util::write_file(output, png); + }); - const unsigned int w = width * pixelRatio; - const unsigned int h = height * pixelRatio; - const std::string image = util::compress_png(w, h, pixels.get()); - util::write_file(output, image); + map.renderStill([async](std::unique_ptr image) { + async->data = const_cast(image.release()); + uv_async_send(async); + }); + + // This loop will terminate once the async was fired. + uv_run(uv_default_loop(), UV_RUN_DEFAULT); + + map.stop(); } diff --git a/bin/render.gyp b/bin/render.gypi similarity index 93% rename from bin/render.gyp rename to bin/render.gypi index 316a7f3ed..b205e7a95 100644 --- a/bin/render.gyp +++ b/bin/render.gypi @@ -28,15 +28,18 @@ 'variables' : { 'cflags_cc': [ '<@(glfw3_cflags)', + '<@(uv_cflags)', '<@(boost_cflags)', ], 'ldflags': [ '<@(glfw3_ldflags)', + '<@(uv_ldflags)', '<@(boost_ldflags)', '-lboost_program_options' ], 'libraries': [ '<@(glfw3_static_libs)', + '<@(uv_static_libs)', ], }, diff --git a/gyp/asset-fs.gypi b/gyp/asset-fs.gypi index f8ec0e355..f7fbea1c7 100644 --- a/gyp/asset-fs.gypi +++ b/gyp/asset-fs.gypi @@ -12,6 +12,7 @@ 'include_dirs': [ '../include', + '../src', ], 'variables': { diff --git a/gyp/asset-zip.gypi b/gyp/asset-zip.gypi index 5c57aa18b..8a195649f 100644 --- a/gyp/asset-zip.gypi +++ b/gyp/asset-zip.gypi @@ -13,6 +13,7 @@ 'include_dirs': [ '../include', + '../src', ], 'variables': { diff --git a/gyp/common.gypi b/gyp/common.gypi index 01f1451dd..fbfa68711 100644 --- a/gyp/common.gypi +++ b/gyp/common.gypi @@ -23,6 +23,7 @@ ], 'GCC_WARN_PEDANTIC': 'YES', 'GCC_WARN_UNINITIALIZED_AUTOS': 'YES_AGGRESSIVE', + 'MACOSX_DEPLOYMENT_TARGET': '10.9', }, }, { 'cflags_cc': [ diff --git a/gyp/http-curl.gypi b/gyp/http-curl.gypi index c97ad370b..b7c583235 100644 --- a/gyp/http-curl.gypi +++ b/gyp/http-curl.gypi @@ -12,6 +12,7 @@ 'include_dirs': [ '../include', + '../src', ], 'variables': { diff --git a/gyp/http-nsurl.gypi b/gyp/http-nsurl.gypi index 5a079fdee..a64c8508e 100644 --- a/gyp/http-nsurl.gypi +++ b/gyp/http-nsurl.gypi @@ -12,6 +12,7 @@ 'include_dirs': [ '../include', + '../src', ], 'variables': { diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index 9965db57a..f70743118 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -20,6 +20,7 @@ '../include/mbgl/ios/MGLMapboxEvents.h', '../platform/ios/MGLMapboxEvents.m', '../include/mbgl/ios/MGLMapView.h', + '../include/mbgl/ios/MGLMapView+IBAdditions.h', '../platform/ios/MGLMapView.mm', '../include/mbgl/ios/MGLAnnotation.h', '../include/mbgl/ios/MGLUserLocation.h', @@ -30,6 +31,10 @@ '../include/mbgl/ios/MGLMetricsLocationManager.h', '../platform/ios/MGLMetricsLocationManager.m', '../include/mbgl/ios/MGLTypes.h', + '../platform/ios/NSProcessInfo+MGLAdditions.h', + '../platform/ios/NSProcessInfo+MGLAdditions.m', + '../platform/ios/NSString+MGLAdditions.h', + '../platform/ios/NSString+MGLAdditions.m', '../platform/ios/vendor/SMCalloutView/SMCalloutView.h', '../platform/ios/vendor/SMCalloutView/SMCalloutView.m', ], @@ -50,6 +55,7 @@ '-framework MobileCoreServices', '-framework QuartzCore', '-framework SystemConfiguration', + '-ObjC', ], }, diff --git a/gyp/platform-osx.gypi b/gyp/platform-osx.gypi index aecb05859..6d6c35b29 100644 --- a/gyp/platform-osx.gypi +++ b/gyp/platform-osx.gypi @@ -26,6 +26,7 @@ '<@(uv_static_libs)', ], 'ldflags': [ + '-framework Foundation', '-framework ImageIO', '-framework CoreServices', '-framework OpenGL', diff --git a/gyp/project.gyp b/gyp/project.gyp new file mode 100644 index 000000000..9f53eef51 --- /dev/null +++ b/gyp/project.gyp @@ -0,0 +1,19 @@ +{ + 'conditions': [ + ['host == "osx"', { + 'includes': [ + '../macosx/mapboxgl-app.gypi', + '../linux/mapboxgl-app.gypi', + '../test/test.gypi', + '../bin/render.gypi', + ] + }], + ['host == "linux"', { + 'includes': [ + '../linux/mapboxgl-app.gypi', + '../test/test.gypi', + '../bin/render.gypi', + ] + }], + ], +} diff --git a/gyp/styles.gypi b/gyp/styles.gypi index e1cd344fe..8b3032b58 100644 --- a/gyp/styles.gypi +++ b/gyp/styles.gypi @@ -19,7 +19,7 @@ 'hard_dependency': 1, 'dependencies': [ 'touch_styles' ], # required for xcode http://openradar.appspot.com/7232149 'conditions': [ - ['OS == "mac"', { + ['platform_lib == "osx" or platform_lib == "ios"', { 'direct_dependent_settings': { 'mac_bundle_resources': [ '../styles/styles' ], } diff --git a/include/mbgl/android/native_map_view.hpp b/include/mbgl/android/native_map_view.hpp index 21784f531..14ccaba3f 100644 --- a/include/mbgl/android/native_map_view.hpp +++ b/include/mbgl/android/native_map_view.hpp @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/mbgl/ios/MGLMapView+IBAdditions.h b/include/mbgl/ios/MGLMapView+IBAdditions.h new file mode 100644 index 000000000..df9a19a6b --- /dev/null +++ b/include/mbgl/ios/MGLMapView+IBAdditions.h @@ -0,0 +1,33 @@ +#import "MGLMapView.h" + +@interface MGLMapView (IBAdditions) + +// Core properties that can be manipulated in the Attributes inspector in +// Interface Builder. These redeclarations merely add the IBInspectable keyword. +// They appear here to ensure that they appear above the convenience properties; +// inspectables declared in MGLMapView.h are always sorted before those in +// MGLMapView+IBAdditions.h, due to ASCII sort order. + +@property (nonatomic) IBInspectable NSString *accessToken; +@property (nonatomic) IBInspectable NSString *mapID; + +// Convenience properties related to the initial viewport. These properties +// are not meant to be used outside of Interface Builder. latitude and longitude +// are backed by properties of type CLLocationDegrees, but these declarations +// must use the type double because Interface Builder is unaware that +// CLLocationDegrees is a typedef for double. + +@property (nonatomic) IBInspectable double latitude; +@property (nonatomic) IBInspectable double longitude; +@property (nonatomic) IBInspectable double zoomLevel; + +// Renamed properties. Interface Builder derives the display name of each +// inspectable from the runtime name, but runtime names don’t always make sense +// in UI. + +@property (nonatomic) IBInspectable BOOL allowsZooming; +@property (nonatomic) IBInspectable BOOL allowsScrolling; +@property (nonatomic) IBInspectable BOOL allowsRotating; +@property (nonatomic) IBInspectable BOOL showsUserLocation; + +@end diff --git a/include/mbgl/ios/MGLMapView.h b/include/mbgl/ios/MGLMapView.h index 17741b171..8717b5e8a 100644 --- a/include/mbgl/ios/MGLMapView.h +++ b/include/mbgl/ios/MGLMapView.h @@ -13,48 +13,34 @@ * Use of MGLMapView requires a Mapbox API access token. Obtain an access token on the [Mapbox account page](https://www.mapbox.com/account/apps/). If you instantiate an MGLMapView from Interface Builder, rendering of the map won't begin until the accessToken property has been set. * * @warning Please note that you are responsible for getting permission to use the map data, and for ensuring your use adheres to the relevant terms of use. */ +IB_DESIGNABLE @interface MGLMapView : UIView #pragma mark - Initializing a Map View /** @name Initializing a Map View */ -/** Initialize a map view with a given frame, style, and access token. -* @param frame The frame with which to initialize the map view. -* @param accessToken A Mapbox API access token. -* @param styleJSON The map stylesheet as JSON text. -* @return An initialized map view, or `nil` if the map view was unable to be initialized. */ -- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleJSON:(NSString *)styleJSON; - -/** Initialize a map view with a given frame, bundled style name, and access token. -* @param frame The frame with which to initialize the map view. -* @param accessToken A Mapbox API access token. -* @param styleName The map style name to use. -* @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://`). -* @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. +/** Initialize a map view with the default style and a given frame and access token. * @param frame The frame with which to initialize the map view. * @param accessToken A Mapbox API access token. * @return An initialized map view, or `nil` if the map view was unable to be initialized. */ - (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken; +/** Initialize a map view with a given frame, access token, and style URL. + * @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://`). + * @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; + - (instancetype)initWithFrame:(CGRect)frame __attribute__((unavailable("Instantiating an MGLMapView requires setting a style and/or an access token."))); #pragma mark - Authorizing Access /** @name Authorizing Access */ -/** Sets a Mapbox API access token for the map view. -* @param accessToken A Mapbox API token. */ -- (void)setAccessToken:(NSString *)accessToken; +/** Mapbox API access token for the map view. */ +@property (nonatomic) NSString *accessToken; #pragma mark - Managing Constraints @@ -63,7 +49,7 @@ /** A view controller whose top and bottom layout guides to use for proper setup of constraints in the map view internals. * * Certain components of the map view, such as the heading compass and the data attribution button, need to be aware of the view controller layout in order to avoid positioning content under a top navigation bar or a bottom toolbar. */ -@property (nonatomic, weak) UIViewController *viewControllerForLayoutGuides; +@property (nonatomic, weak) IBOutlet UIViewController *viewControllerForLayoutGuides; #pragma mark - Accessing Map Properties @@ -95,7 +81,7 @@ /** @name Accessing the Delegate */ // TODO -@property(nonatomic, weak) id delegate; +@property(nonatomic, weak) IBOutlet id delegate; #pragma mark - Manipulating the Visible Portion of the Map @@ -148,7 +134,7 @@ - (void)setDirection:(CLLocationDirection)direction animated:(BOOL)animated; /** Resets the map rotation to a northern heading. */ -- (void)resetNorth; +- (IBAction)resetNorth; #pragma mark - Converting Map Coordinates @@ -178,27 +164,34 @@ /** @name Styling the Map */ -/** Sets the map style. -* @param styleJSON The map stylesheet as JSON text. */ -- (void)setStyleJSON:(NSString *)styleJSON; +/** Mapbox map ID of the style currently displayed in the receiver, or `nil` if the style does not have a map ID. +* +* The style may lack a map ID if it is located at an HTTP, HTTPS, or local file URL. Use `styleURL` to get the URL in these cases. +* +* To display the default style, set this property to `nil`. */ +@property (nonatomic) NSString *mapID; -/** Returns the raw JSON style as a native dictionary object. */ -- (NSDictionary *)getRawStyle; +/** Returns the URLs to the styles bundled with the library. */ +- (NSArray *)bundledStyleURLs; -/** Sets the raw JSON style as a native dictionary object with a transition animation. -* @param style The style JSON as a dictionary object. */ -- (void)setRawStyle:(NSDictionary *)style; +/** URL of the style currently displayed in the receiver. +* +* The URL may be a full HTTP or HTTPS URL or a Mapbox URL indicating the style’s map ID (`mapbox://`). +* +* To display the default style, set this property to `nil`. */ +@property (nonatomic) NSURL *styleURL; -/** Returns the names of the styles bundled with the library. */ -- (NSArray *)bundledStyleNames; +/** Currently active style classes, represented as an array of string identifiers. */ +@property (nonatomic) NSArray *styleClasses; -/** Sets the map style to a named, bundled style. -* @param styleName The map style name to use. */ -- (void)useBundledStyleNamed:(NSString *)styleName; +/** Returns a Boolean value indicating whether the style class with the given identifier is currently active. */ +- (BOOL)hasStyleClass:(NSString *)styleClass; -/** 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://`). */ -- (void)setStyleURL:(NSURL *)styleURL; +/** Activates the style class with the given identifier. */ +- (void)addStyleClass:(NSString *)styleClass; + +/** Deactivates the style class with the given identifier. */ +- (void)removeStyleClass:(NSString *)styleClass; #pragma mark - Annotating the Map @@ -286,6 +279,9 @@ /** Toggle the current value of debugActive. */ - (void)toggleDebug; +/** Empties the in-memory tile cache. */ +- (void)emptyMemoryCache; + /** Resets the map to the minimum zoom level, a center coordinate of (0, 0), and a northern heading. */ - (void)resetPosition; diff --git a/include/mbgl/ios/MGLMapboxEvents.h b/include/mbgl/ios/MGLMapboxEvents.h index e51371368..7a4c45fe1 100644 --- a/include/mbgl/ios/MGLMapboxEvents.h +++ b/include/mbgl/ios/MGLMapboxEvents.h @@ -10,6 +10,9 @@ extern NSString *const MGLEventKeyLongitude; extern NSString *const MGLEventKeyZoomLevel; extern NSString *const MGLEventKeySpeed; extern NSString *const MGLEventKeyCourse; +extern NSString *const MGLEventKeyAltitude; +extern NSString *const MGLEventKeyHorizontalAccuracy; +extern NSString *const MGLEventKeyVerticalAccuracy; extern NSString *const MGLEventKeyPushEnabled; extern NSString *const MGLEventKeyEmailEnabled; extern NSString *const MGLEventKeyGestureID; @@ -22,13 +25,15 @@ extern NSString *const MGLEventGesturePanStart; extern NSString *const MGLEventGesturePinchStart; extern NSString *const MGLEventGestureRotateStart; -@interface MGLMapboxEvents : NSObject +@interface MGLMapboxEvents : NSObject // You must call these methods from the main thread. // + (void) setToken:(NSString *)token; + (void) setAppName:(NSString *)appName; + (void) setAppVersion:(NSString *)appVersion; ++ (void) pauseMetricsCollection; ++ (void) resumeMetricsCollection; // You can call this method from any thread. Significant work will // be dispatched to a low-priority background queue and all diff --git a/include/mbgl/ios/MGLMetricsLocationManager.h b/include/mbgl/ios/MGLMetricsLocationManager.h index 7281d0501..5f3b56818 100644 --- a/include/mbgl/ios/MGLMetricsLocationManager.h +++ b/include/mbgl/ios/MGLMetricsLocationManager.h @@ -2,8 +2,10 @@ @interface MGLMetricsLocationManager : NSObject -// This method can be called from any thread. +// These methods can be called from any thread. // + (instancetype)sharedManager; ++ (void) startUpdatingLocation; ++ (void) stopUpdatingLocation; @end diff --git a/src/mbgl/map/environment.hpp b/include/mbgl/map/environment.hpp similarity index 100% rename from src/mbgl/map/environment.hpp rename to include/mbgl/map/environment.hpp diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index cdcfa27e4..f9738debe 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -22,6 +21,8 @@ #include #include +namespace uv { class async; } + namespace mbgl { class Painter; @@ -30,7 +31,6 @@ class LayerDescription; class Sprite; class Style; class StyleLayer; -class StyleSource; class TexturePool; class FileSource; class View; @@ -41,16 +41,25 @@ class Environment; class EnvironmentScope; class AnnotationManager; class MapData; +class Worker; +class StillImage; class Map : private util::noncopyable { friend class View; public: + enum class Mode : uint8_t { + None, // we're not doing any processing + Continuous, // continually updating map + Still, // a once-off still image. + }; + explicit Map(View&, FileSource&); ~Map(); // Start the map render thread. It is asynchronous. - void start(bool startPaused = false); + void start(bool startPaused = false, Mode mode = Mode::Continuous); + inline void start(Mode renderMode) { start(false, renderMode); } // Stop the map render thread. This call will block until the map rendering thread stopped. // The optional callback function will be invoked repeatedly until the map thread is stopped. @@ -64,10 +73,8 @@ public: // Resumes a paused render thread void resume(); - // Runs the map event loop. ONLY run this function when you want to get render a single frame - // with this map object. It will *not* spawn a separate thread and instead block until the - // frame is completely rendered. - void run(); + using StillImageCallback = std::function)>; + void renderStill(StillImageCallback callback); // Triggers a synchronous or asynchronous render. void renderSync(); @@ -96,6 +103,7 @@ public: Duration getDefaultTransitionDuration(); void setStyleURL(const std::string& url); void setStyleJSON(const std::string& json, const std::string& base = ""); + std::string getStyleURL() const; std::string getStyleJSON() const; // Transition @@ -150,6 +158,11 @@ public: std::vector getAnnotationsInBounds(const LatLngBounds&); LatLngBounds getBoundsForAnnotations(const std::vector&); + // Memory + void setSourceTileCacheSize(size_t); + size_t getSourceTileCacheSize() const { return sourceCacheSize; } + void onLowMemory(); + // Debug void setDebug(bool value); void toggleDebug(); @@ -160,12 +173,17 @@ public: inline AnnotationManager& getAnnotationManager() const { return *annotationManager; } private: + // Runs the map event loop. ONLY run this function when you want to get render a single frame + // with this map object. It will *not* spawn a separate thread and instead block until the + // frame is completely rendered. + void run(); + // This may only be called by the View object. void resize(uint16_t width, uint16_t height, float ratio = 1); void resize(uint16_t width, uint16_t height, float ratio, uint16_t fbWidth, uint16_t fbHeight); util::ptr getSprite(); - uv::worker& getWorker(); + Worker& getWorker(); // Checks if render thread needs to pause void checkForPause(); @@ -174,7 +192,6 @@ private: void setup(); void updateTiles(); - void updateSources(); // Triggered by triggerUpdate(); void update(); @@ -193,13 +210,9 @@ private: void processTasks(); - void updateAnnotationTiles(const std::vector&); + void updateAnnotationTiles(const std::vector&); - enum class Mode : uint8_t { - None, // we're not doing any processing - Continuous, // continually updating map - Static, // a once-off static image. - }; + size_t sourceCacheSize; Mode mode = Mode::None; @@ -208,7 +221,7 @@ private: View &view; private: - std::unique_ptr workers; + std::unique_ptr workers; std::thread thread; std::unique_ptr asyncTerminate; std::unique_ptr asyncUpdate; @@ -248,12 +261,11 @@ private: const std::unique_ptr data; - std::set> activeSources; - std::atomic updated; std::mutex mutexTask; std::queue> tasks; + StillImageCallback callback; }; } diff --git a/include/mbgl/map/still_image.hpp b/include/mbgl/map/still_image.hpp new file mode 100644 index 000000000..b9ce0620f --- /dev/null +++ b/include/mbgl/map/still_image.hpp @@ -0,0 +1,21 @@ +#ifndef MBGL_MAP_STILL_IMAGE +#define MBGL_MAP_STILL_IMAGE + +#include + +#include +#include + +namespace mbgl { + +class StillImage : util::noncopyable { +public: + uint16_t width = 0; + uint16_t height = 0; + using Pixel = uint32_t; + std::unique_ptr pixels; +}; + +} + +#endif diff --git a/include/mbgl/map/tile.hpp b/include/mbgl/map/tile.hpp deleted file mode 100644 index 146ebe6ad..000000000 --- a/include/mbgl/map/tile.hpp +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef MBGL_MAP_TILE -#define MBGL_MAP_TILE - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace mbgl { - -class TileData; -struct box; - -struct ClipID { - inline ClipID() {} - inline ClipID(const std::string &mask_, const std::string &reference_) : mask(mask_), reference(reference_) {} - - std::bitset<8> mask; - std::bitset<8> reference; - - inline bool operator==(const ClipID &other) const { - return mask == other.mask && reference == other.reference; - } -}; - -class Tile : private util::noncopyable { -public: - struct ID { - const int16_t w = 0; - const int8_t z = 0; - const int32_t x = 0, y = 0; - - inline explicit ID(int8_t z_, int32_t x_, int32_t y_) - : w((x_ < 0 ? x_ - (1 << z_) + 1 : x_) / (1 << z_)), z(z_), x(x_), y(y_) {} - - inline uint64_t to_uint64() const { - return ((std::pow(2, z) * y + x) * 32) + z; - } - - struct Hash { - std::size_t operator()(ID const& i) const { - return std::hash()(i.to_uint64()); - } - }; - - inline bool operator==(const ID& rhs) const { - return w == rhs.w && z == rhs.z && x == rhs.x && y == rhs.y; - } - - inline bool operator!=(const ID& rhs) const { - return !operator==(rhs); - } - - inline bool operator<(const ID &rhs) const { - if (w != rhs.w) return w < rhs.w; - if (z != rhs.z) return z < rhs.z; - if (x != rhs.x) return x < rhs.x; - return y < rhs.y; - } - - ID parent(int8_t z) const; - ID normalized() const; - std::forward_list children(int32_t z) const; - bool isChildOf(const Tile::ID &id) const; - operator std::string() const; - }; - - static std::forward_list cover(int8_t z, const box& bounds); - -public: - explicit Tile(const ID& id); - -public: - const Tile::ID id; - ClipID clip; - mat4 matrix; - util::ptr data; -}; - -} - -#endif diff --git a/include/mbgl/map/transform_state.hpp b/include/mbgl/map/transform_state.hpp index c1a324a89..f6a00a4a3 100644 --- a/include/mbgl/map/transform_state.hpp +++ b/include/mbgl/map/transform_state.hpp @@ -1,8 +1,6 @@ #ifndef MBGL_MAP_TRANSFORM_STATE #define MBGL_MAP_TRANSFORM_STATE -#include - #include #include #include @@ -13,12 +11,15 @@ namespace mbgl { +class TileID; +struct box; + class TransformState { friend class Transform; public: // Matrix - void matrixFor(mat4& matrix, const Tile::ID& id) const; + void matrixFor(mat4& matrix, const TileID& id) const; box cornersToBox(uint32_t z) const; // Dimensions diff --git a/include/mbgl/map/update.hpp b/include/mbgl/map/update.hpp index 3aa871bf0..727122af6 100644 --- a/include/mbgl/map/update.hpp +++ b/include/mbgl/map/update.hpp @@ -1,6 +1,8 @@ #ifndef MBGL_MAP_UPDATE #define MBGL_MAP_UPDATE +#include + namespace mbgl { using UpdateType = uint32_t; @@ -12,6 +14,7 @@ enum class Update : UpdateType { DefaultTransitionDuration = 1 << 2, Classes = 1 << 3, Zoom = 1 << 4, + RenderStill = 1 << 5, }; } diff --git a/include/mbgl/map/view.hpp b/include/mbgl/map/view.hpp index 9b29227d8..8e21233b7 100644 --- a/include/mbgl/map/view.hpp +++ b/include/mbgl/map/view.hpp @@ -3,9 +3,12 @@ #include +#include + namespace mbgl { class Map; +class StillImage; enum MapChange : uint8_t { MapChangeRegionWillChange = 0, @@ -40,6 +43,14 @@ public: // (i.e. map->renderSync() or map->renderAsync() must be called as a result of this) virtual void invalidate() = 0; + // Called from the render (=GL) thread. Signals that the contents of the contents + // may be discarded. The default is a no-op. + virtual void discard(); + + // Reads the pixel data from the current framebuffer. If your View implementation + // doesn't support reading from the framebuffer, return a null pointer. + virtual std::unique_ptr readStillImage(); + // Notifies a watcher of map x/y/scale/rotation changes. // Must only be called from the same thread that caused the change. // Must not be called from the render thread. diff --git a/include/mbgl/platform/default/headless_view.hpp b/include/mbgl/platform/default/headless_view.hpp index 5ba6709a4..3262afc46 100644 --- a/include/mbgl/platform/default/headless_view.hpp +++ b/include/mbgl/platform/default/headless_view.hpp @@ -24,32 +24,47 @@ class HeadlessDisplay; class HeadlessView : public View { public: - HeadlessView(); - HeadlessView(std::shared_ptr display); + HeadlessView(uint16_t width = 256, uint16_t height = 256, float pixelRatio = 1); + HeadlessView(std::shared_ptr display, uint16_t width = 256, uint16_t height = 256, float pixelRatio = 1); ~HeadlessView(); - void createContext(); - void loadExtensions(); - void resize(uint16_t width, uint16_t height, float pixelRatio); - std::unique_ptr readPixels(); void activate() override; void deactivate() override; void notify() override; void invalidate() override; + void discard() override; + std::unique_ptr readStillImage() override; private: + void createContext(); + void loadExtensions(); void clearBuffers(); + bool isActive(); private: - std::shared_ptr display_; - uint16_t width_; - uint16_t height_; - float pixelRatio_; + std::shared_ptr display; + + struct Dimensions { + inline Dimensions(uint16_t width = 0, uint16_t height = 0, float pixelRatio = 0); + inline uint16_t pixelWidth() const { return width * pixelRatio; } + inline uint16_t pixelHeight() const { return height * pixelRatio; } + + uint16_t width = 0; + uint16_t height = 0; + float pixelRatio = 0; + }; + + // These are the values that represent the state of the current framebuffer. + Dimensions current; + + // These are the values that will be used after the next discard() event. + std::mutex prospectiveMutex; + Dimensions prospective; #if MBGL_USE_CGL - CGLContextObj glContext; + CGLContextObj glContext = nullptr; #endif #if MBGL_USE_GLX @@ -64,6 +79,8 @@ private: GLuint fbo = 0; GLuint fboDepthStencil = 0; GLuint fboColor = 0; + + std::thread::id thread; }; } diff --git a/include/mbgl/platform/log.hpp b/include/mbgl/platform/log.hpp index 5d287eb57..d6f3cd1ab 100644 --- a/include/mbgl/platform/log.hpp +++ b/include/mbgl/platform/log.hpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -12,7 +13,7 @@ namespace mbgl { class Log { public: - class Observer { + class Observer : private util::noncopyable { public: virtual ~Observer() = default; @@ -22,6 +23,7 @@ public: }; static void setObserver(std::unique_ptr Observer); + static std::unique_ptr removeObserver(); private: template diff --git a/include/mbgl/platform/platform.hpp b/include/mbgl/platform/platform.hpp index ac90d0d3d..cd87e2256 100644 --- a/include/mbgl/platform/platform.hpp +++ b/include/mbgl/platform/platform.hpp @@ -1,8 +1,6 @@ #ifndef MBGL_PLATFORM_PLATFORM #define MBGL_PLATFORM_PLATFORM -#include - #include #include diff --git a/include/mbgl/storage/default/sqlite_cache.hpp b/include/mbgl/storage/default/sqlite_cache.hpp deleted file mode 100644 index 8f2746561..000000000 --- a/include/mbgl/storage/default/sqlite_cache.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE -#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE - -#include - -#include -#include - -typedef struct uv_loop_s uv_loop_t; - -namespace mapbox { namespace util { template class variant; } } -namespace mapbox { namespace sqlite { class Database; class Statement; } } - -namespace mbgl { - -namespace util { template class AsyncQueue; } - -class SQLiteCache : public FileCache { - struct GetAction; - struct PutAction; - struct RefreshAction; - struct StopAction; - using Action = mapbox::util::variant; - using Queue = util::AsyncQueue; - -public: - SQLiteCache(const std::string &path = ":memory:"); - ~SQLiteCache(); - - void get(const Resource &resource, std::function)> callback); - void put(const Resource &resource, std::shared_ptr response, Hint hint); - -private: - struct ActionDispatcher; - void process(GetAction &action); - void process(PutAction &action); - void process(RefreshAction &action); - void process(StopAction &action); - - void createDatabase(); - - const std::string path; - uv_loop_t *loop = nullptr; - Queue *queue = nullptr; - std::thread thread; - std::unique_ptr<::mapbox::sqlite::Database> db; - std::unique_ptr<::mapbox::sqlite::Statement> getStmt, putStmt, refreshStmt; -}; - -} - -#endif diff --git a/include/mbgl/storage/default_file_source.hpp b/include/mbgl/storage/default_file_source.hpp index 7aab54f73..f39374716 100644 --- a/include/mbgl/storage/default_file_source.hpp +++ b/include/mbgl/storage/default_file_source.hpp @@ -4,24 +4,18 @@ #include #include -#include -#include -#include - -namespace mapbox { namespace util { template class variant; } } - namespace mbgl { -namespace util { template class AsyncQueue; } - -class SharedRequestBase; +namespace util { +template class Thread; +} class DefaultFileSource : public FileSource { public: DefaultFileSource(FileCache *cache, const std::string &root = ""); - DefaultFileSource(FileCache *cache, uv_loop_t *loop, const std::string &root = ""); ~DefaultFileSource() override; + // FileSource API Request *request(const Resource &resource, uv_loop_t *loop, const Environment &env, Callback callback) override; void cancel(Request *request) override; @@ -29,37 +23,10 @@ public: void abort(const Environment &env) override; - void notify(SharedRequestBase *sharedRequest, const std::set &observers, - std::shared_ptr response, FileCache::Hint hint); - public: - const std::string assetRoot; - + class Impl; private: - struct ActionDispatcher; - struct AddRequestAction; - struct RemoveRequestAction; - struct ResultAction; - struct StopAction; - struct AbortAction; - using Action = mapbox::util::variant; - using Queue = util::AsyncQueue; - - void process(AddRequestAction &action); - void process(RemoveRequestAction &action); - void process(ResultAction &action); - void process(StopAction &action); - void process(AbortAction &action); - - SharedRequestBase *find(const Resource &resource); - - std::unordered_map pending; - - uv_loop_t *loop = nullptr; - FileCache *cache = nullptr; - Queue *queue = nullptr; - std::thread thread; + const std::unique_ptr> thread; }; } diff --git a/include/mbgl/storage/file_cache.hpp b/include/mbgl/storage/file_cache.hpp index 97e75a5d8..f815d5b8c 100644 --- a/include/mbgl/storage/file_cache.hpp +++ b/include/mbgl/storage/file_cache.hpp @@ -16,9 +16,9 @@ public: virtual ~FileCache() = default; enum class Hint : uint8_t { Full, Refresh, No }; + using Callback = std::function)>; - virtual void get(const Resource &resource, - std::function)> callback) = 0; + virtual void get(const Resource &resource, Callback callback) = 0; virtual void put(const Resource &resource, std::shared_ptr response, Hint hint) = 0; }; diff --git a/include/mbgl/storage/default/request.hpp b/include/mbgl/storage/request.hpp similarity index 100% rename from include/mbgl/storage/default/request.hpp rename to include/mbgl/storage/request.hpp diff --git a/include/mbgl/storage/sqlite_cache.hpp b/include/mbgl/storage/sqlite_cache.hpp new file mode 100644 index 000000000..b216f74d7 --- /dev/null +++ b/include/mbgl/storage/sqlite_cache.hpp @@ -0,0 +1,30 @@ +#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE +#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE + +#include + +#include + +namespace mbgl { + +namespace util { +template class Thread; +} + +class SQLiteCache : public FileCache { +public: + SQLiteCache(const std::string &path = ":memory:"); + ~SQLiteCache() override; + + // FileCache API + void get(const Resource &resource, Callback callback) override; + void put(const Resource &resource, std::shared_ptr response, Hint hint) override; + +private: + class Impl; + const std::unique_ptr> thread; +}; + +} + +#endif diff --git a/include/mbgl/util/math.hpp b/include/mbgl/util/math.hpp index e800fc784..6dea628e9 100644 --- a/include/mbgl/util/math.hpp +++ b/include/mbgl/util/math.hpp @@ -74,6 +74,11 @@ inline vec2 normal(const S1& a, const S2& b) { return { dx / c, dy / c }; } +template +inline T perp(const T& a) { + return T(-a.y, a.x); +} + template inline T dist(const S1& a, const S2& b) { T dx = b.x - a.x; @@ -93,11 +98,22 @@ inline T mag(const S& a) { return std::sqrt(a.x * a.x + a.y * a.y); } +template +inline S unit(const S& a) { + return a * (1 / mag(a)); +} + template T clamp(T value, T min, T max) { return value < min ? min : (value > max ? max : value); } +template +T wrap(T value, T min, T max) { + T d = max - min; + return value == max ? value : std::fmod((std::fmod((value - min), d) + d), d) + min; +} + template T smoothstep(T edge0, T edge1, T x) { T t = clamp((x - edge0) / (edge1 - edge0), T(0), T(1)); diff --git a/include/mbgl/util/uv-messenger.h b/include/mbgl/util/uv-messenger.h deleted file mode 100644 index 35c5ce218..000000000 --- a/include/mbgl/util/uv-messenger.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef MBGL_UTIL_UV_MESSENGER -#define MBGL_UTIL_UV_MESSENGER - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct uv_messenger_s uv_messenger_t; -typedef void (*uv_messenger_cb)(void *arg); -typedef void (*uv_messenger_stop_cb)(uv_messenger_t *msgr); - -struct uv_messenger_s { - uv_mutex_t mutex; - uv_async_t async; - uv_messenger_cb callback; - uv_messenger_stop_cb stop_callback; - void *data; - void *queue[2]; -}; - -int uv_messenger_init(uv_loop_t *loop, uv_messenger_t *msgr, uv_messenger_cb callback); -void uv_messenger_send(uv_messenger_t *msgr, void *arg); -void uv_messenger_stop(uv_messenger_t *msgr, uv_messenger_stop_cb stop_callback); -void uv_messenger_ref(uv_messenger_t *msgr); -void uv_messenger_unref(uv_messenger_t *msgr); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/include/mbgl/util/uv.hpp b/include/mbgl/util/uv.hpp index 6f0a91604..19c6c5b4d 100644 --- a/include/mbgl/util/uv.hpp +++ b/include/mbgl/util/uv.hpp @@ -17,7 +17,6 @@ std::string cwd(); class rwlock; class loop; class async; -class worker; class mutex; class cond; diff --git a/include/mbgl/util/vec.hpp b/include/mbgl/util/vec.hpp index 32de85275..052dffcfa 100644 --- a/include/mbgl/util/vec.hpp +++ b/include/mbgl/util/vec.hpp @@ -61,7 +61,13 @@ struct vec2 { template inline typename std::enable_if::value, vec2>::type operator-(const O &o) const { - return {x - o.x, y - o.y}; + return vec2(x - o.x, y - o.y); + } + + template + inline typename std::enable_if::value, vec2>::type + operator+(const O &o) const { + return vec2(x + o.x, y + o.y); } template diff --git a/ios/MapboxGL.podspec b/ios/MapboxGL.podspec index b474f7c9e..57de3f6f3 100644 --- a/ios/MapboxGL.podspec +++ b/ios/MapboxGL.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |m| m.name = 'MapboxGL' - m.version = '0.1.0' + m.version = '0.2.15' m.summary = 'Open source vector map solution for iOS with full styling capabilities.' m.description = 'Open source OpenGL-based vector map solution for iOS with full styling capabilities and Cocoa bindings.' @@ -11,23 +11,24 @@ Pod::Spec.new do |m| m.screenshot = 'https://raw.githubusercontent.com/mapbox/mapbox-gl-native/master/ios/screenshot.png' m.social_media_url = 'https://twitter.com/mapbox' - m.source = { :http => "http://mapbox.s3.amazonaws.com/mapbox-gl-native/ios/mapbox-gl-ios-#{m.version.to_s}.zip" } + m.source = { + :http => "http://mapbox.s3.amazonaws.com/mapbox-gl-native/ios/builds/mapbox-gl-ios-#{m.version.to_s}.zip", + :flatten => true + } m.platform = :ios m.ios.deployment_target = '7.0' - m.source_files = 'Headers/*.h' - m.requires_arc = true + m.preserve_paths = '**' + m.source_files = 'Headers/*.h' m.resource_bundle = { 'MapboxGL' => 'MapboxGL.bundle/*' } - - m.frameworks = 'CoreLocation', 'CoreTelephony', 'GLKit', 'ImageIO', 'MobileCoreServices', 'QuartzCore', 'SystemConfiguration' - - m.libraries = 'c++', 'sqlite3', 'z' - m.vendored_library = 'libMapboxGL.a' + + m.frameworks = 'CoreLocation', 'CoreTelephony', 'GLKit', 'ImageIO', 'MobileCoreServices', 'QuartzCore', 'SystemConfiguration' + m.libraries = 'c++', 'sqlite3', 'z' m.xcconfig = { 'OTHER_CPLUSPLUSFLAGS' => '-std=gnu++11 -stdlib=libc++' } end diff --git a/ios/app/MBXAppDelegate.m b/ios/app/MBXAppDelegate.m index f0541b997..f2ef69ec6 100644 --- a/ios/app/MBXAppDelegate.m +++ b/ios/app/MBXAppDelegate.m @@ -1,5 +1,6 @@ #import "MBXAppDelegate.h" #import "MBXViewController.h" +#import @implementation MBXAppDelegate @@ -12,4 +13,26 @@ return YES; } +/** +- (void)applicationWillEnterForeground:(UIApplication *)application +{ + // Example of how to resume Metrics Collection + + // Reasons for needing to resume: + // 1. In UIBackground and app starts listening for Location Updates where it previously had not been listening. + // 2. App is entering foreground where it had called pauseMetricsCollection. + [MGLMapboxEvents resumeMetricsCollection]; +} + +- (void)applicationDidEnterBackground:(UIApplication *)application +{ + // Example of how to pause Metrics Collection + + // Reason for needing to pause: + // 1. Either entering or already in UIBackground and app stops listening for Location Updates + // via any CLLocationManager instance it may have. + [MGLMapboxEvents pauseMetricsCollection]; +} +*/ + @end diff --git a/ios/app/MBXViewController.mm b/ios/app/MBXViewController.mm index c9973bcb7..13235beb0 100644 --- a/ios/app/MBXViewController.mm +++ b/ios/app/MBXViewController.mm @@ -11,15 +11,17 @@ static UIColor *const kTintColor = [UIColor colorWithRed:0.120 green:0.550 blue:0.670 alpha:1.000]; static NSArray *const kStyleNames = @[ + @"Mapbox Streets", @"Emerald", + @"Light", + @"Dark", @"Bright", @"Basic", @"Outdoors", @"Satellite", - @"Hybrid", ]; -static NSString *const kStyleVersion = @"v7"; +static NSString *const kStyleVersion = @"7"; @interface MBXViewController () @@ -80,13 +82,13 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; action:@selector(showSettings)]; UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom]; - [titleButton setFrame:CGRectMake(0, 0, 120, 40)]; + [titleButton setFrame:CGRectMake(0, 0, 150, 40)]; [titleButton setTitle:[kStyleNames firstObject] forState:UIControlStateNormal]; [titleButton setTitleColor:kTintColor forState:UIControlStateNormal]; [titleButton addTarget:self action:@selector(cycleStyles) forControlEvents:UIControlEventTouchUpInside]; self.navigationItem.titleView = titleButton; - self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"locateUser.png"] + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"TrackingLocationOffMask.png"] style:UIBarButtonItemStylePlain target:self action:@selector(locateUser)]; @@ -143,6 +145,7 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; otherButtonTitles:@"Reset North", @"Reset Position", @"Toggle Debug", + @"Empty Memory", @"Add 100 Points", @"Add 1,000 Points", @"Add 10,000 Points", @@ -168,17 +171,21 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 3) { - [self parseFeaturesAddingCount:100]; + [self.mapView emptyMemoryCache]; } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 4) { - [self parseFeaturesAddingCount:1000]; + [self parseFeaturesAddingCount:100]; } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 5) { - [self parseFeaturesAddingCount:10000]; + [self parseFeaturesAddingCount:1000]; } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 6) + { + [self parseFeaturesAddingCount:10000]; + } + else if (buttonIndex == actionSheet.firstOtherButtonIndex + 7) { [self.mapView removeAnnotations:self.mapView.annotations]; } @@ -246,10 +253,10 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; styleName = [kStyleNames objectAtIndex:index]; } - [self.mapView useBundledStyleNamed: - [[[styleName lowercaseString] - stringByAppendingString:@"-"] - stringByAppendingString:kStyleVersion]]; + self.mapView.styleURL = [NSURL URLWithString: + [NSString stringWithFormat:@"asset://styles/%@-v%@.json", + [[styleName lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@"-"], + kStyleVersion]]; [titleButton setTitle:styleName forState:UIControlStateNormal]; } @@ -294,6 +301,29 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; return YES; } +- (void)mapView:(MGLMapView *)mapView didChangeUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated +{ + UIImage *newButtonImage; + + switch (mode) { + case MGLUserTrackingModeNone: + newButtonImage = [UIImage imageNamed:@"TrackingLocationOffMask.png"]; + break; + + case MGLUserTrackingModeFollow: + newButtonImage = [UIImage imageNamed:@"TrackingLocationMask.png"]; + break; + + case MGLUserTrackingModeFollowWithHeading: + newButtonImage = [UIImage imageNamed:@"TrackingHeadingMask.png"]; + break; + } + + [UIView animateWithDuration:0.25 animations:^{ + self.navigationItem.rightBarButtonItem.image = newButtonImage; + }]; +} + #pragma clang diagnostic pop @end diff --git a/ios/app/img/TrackingHeadingMask.png b/ios/app/img/TrackingHeadingMask.png new file mode 100644 index 000000000..9ec0567a3 Binary files /dev/null and b/ios/app/img/TrackingHeadingMask.png differ diff --git a/ios/app/img/TrackingHeadingMask@2x.png b/ios/app/img/TrackingHeadingMask@2x.png new file mode 100644 index 000000000..0df8ccc22 Binary files /dev/null and b/ios/app/img/TrackingHeadingMask@2x.png differ diff --git a/ios/app/img/TrackingHeadingMask@3x.png b/ios/app/img/TrackingHeadingMask@3x.png new file mode 100644 index 000000000..e4b93e42e Binary files /dev/null and b/ios/app/img/TrackingHeadingMask@3x.png differ diff --git a/ios/app/img/TrackingLocationMask.png b/ios/app/img/TrackingLocationMask.png new file mode 100644 index 000000000..bb7348c48 Binary files /dev/null and b/ios/app/img/TrackingLocationMask.png differ diff --git a/ios/app/img/TrackingLocationMask@2x.png b/ios/app/img/TrackingLocationMask@2x.png new file mode 100644 index 000000000..35c5a293e Binary files /dev/null and b/ios/app/img/TrackingLocationMask@2x.png differ diff --git a/ios/app/img/TrackingLocationMask@3x.png b/ios/app/img/TrackingLocationMask@3x.png new file mode 100644 index 000000000..af523975a Binary files /dev/null and b/ios/app/img/TrackingLocationMask@3x.png differ diff --git a/ios/app/img/TrackingLocationOffMask.png b/ios/app/img/TrackingLocationOffMask.png new file mode 100644 index 000000000..87b26c571 Binary files /dev/null and b/ios/app/img/TrackingLocationOffMask.png differ diff --git a/ios/app/img/TrackingLocationOffMask@2x.png b/ios/app/img/TrackingLocationOffMask@2x.png new file mode 100644 index 000000000..232d534b4 Binary files /dev/null and b/ios/app/img/TrackingLocationOffMask@2x.png differ diff --git a/ios/app/img/TrackingLocationOffMask@3x.png b/ios/app/img/TrackingLocationOffMask@3x.png new file mode 100644 index 000000000..b609fbe84 Binary files /dev/null and b/ios/app/img/TrackingLocationOffMask@3x.png differ diff --git a/ios/app/img/locateUser.png b/ios/app/img/locateUser.png deleted file mode 100644 index aa8d1cf52..000000000 Binary files a/ios/app/img/locateUser.png and /dev/null differ diff --git a/ios/app/img/locateUser@2x.png b/ios/app/img/locateUser@2x.png deleted file mode 100644 index 29c490593..000000000 Binary files a/ios/app/img/locateUser@2x.png and /dev/null differ diff --git a/ios/app/img/locateUser@3x.png b/ios/app/img/locateUser@3x.png deleted file mode 100644 index 206a5ae80..000000000 Binary files a/ios/app/img/locateUser@3x.png and /dev/null differ diff --git a/linux/main.cpp b/linux/main.cpp index 4d5474c02..6afa3f7f6 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include diff --git a/linux/mapboxgl-app.gyp b/linux/mapboxgl-app.gypi similarity index 100% rename from linux/mapboxgl-app.gyp rename to linux/mapboxgl-app.gypi diff --git a/macosx/main.mm b/macosx/main.mm index 087544f7c..add763189 100644 --- a/macosx/main.mm +++ b/macosx/main.mm @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include diff --git a/macosx/mapboxgl-app.gyp b/macosx/mapboxgl-app.gypi similarity index 94% rename from macosx/mapboxgl-app.gyp rename to macosx/mapboxgl-app.gypi index 39aef6435..381795404 100644 --- a/macosx/mapboxgl-app.gyp +++ b/macosx/mapboxgl-app.gypi @@ -53,8 +53,7 @@ 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], 'OTHER_LDFLAGS': [ '<@(ldflags)' ], 'SDKROOT': 'macosx', - 'INFOPLIST_FILE': 'Info.plist', - 'MACOSX_DEPLOYMENT_TARGET': '10.9', + 'INFOPLIST_FILE': '../macosx/Info.plist', 'CLANG_ENABLE_OBJC_ARC': 'YES' }, } diff --git a/platform/darwin/http_request_nsurl.mm b/platform/darwin/http_request_nsurl.mm index 7be5f226f..0fd4a4e8f 100644 --- a/platform/darwin/http_request_nsurl.mm +++ b/platform/darwin/http_request_nsurl.mm @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include @@ -47,7 +47,7 @@ class HTTPNSURLContext; class HTTPRequestImpl { public: - HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr response); + HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::shared_ptr response); ~HTTPRequestImpl(); void cancel(); @@ -66,7 +66,7 @@ private: HTTPRequest *request = nullptr; NSURLSessionDataTask *task = nullptr; std::unique_ptr response; - std::unique_ptr existingResponse; + const std::shared_ptr existingResponse; ResponseStatus status = ResponseStatus::PermanentError; uv_async_t *async = nullptr; int attempts = 0; @@ -118,10 +118,10 @@ HTTPNSURLContext::~HTTPNSURLContext() { // ------------------------------------------------------------------------------------------------- HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, - std::unique_ptr existingResponse_) + std::shared_ptr existingResponse_) : context(HTTPNSURLContext::Get(loop)), request(request_), - existingResponse(std::move(existingResponse_)), + existingResponse(existingResponse_), async(new uv_async_t) { assert(request); context->addRequest(request); @@ -326,12 +326,12 @@ void HTTPRequestImpl::handleResult(NSData *data, NSURLResponse *res, NSError *er if (responseCode == 304) { if (existingResponse) { - // We're going to reuse the old response object, but need to copy over the new - // expires value (if possible). - std::swap(response, existingResponse); - if (existingResponse->expires) { - response->expires = existingResponse->expires; - } + // We're going to copy over the existing response's data. + response->status = existingResponse->status; + response->message = existingResponse->message; + response->modified = existingResponse->modified; + response->etag = existingResponse->etag; + response->data = existingResponse->data; status = ResponseStatus::NotModified; } else { // This is an unsolicited 304 response and should only happen on malfunctioning @@ -397,7 +397,7 @@ void HTTPRequestImpl::restart(uv_timer_t *timer, int) { // ------------------------------------------------------------------------------------------------- -HTTPRequest::HTTPRequest(DefaultFileSource *source, const Resource &resource) +HTTPRequest::HTTPRequest(DefaultFileSource::Impl *source, const Resource &resource) : SharedRequestBase(source, resource) { } @@ -409,11 +409,11 @@ HTTPRequest::~HTTPRequest() { } } -void HTTPRequest::start(uv_loop_t *loop, std::unique_ptr response) { +void HTTPRequest::start(uv_loop_t *loop, std::shared_ptr response) { MBGL_VERIFY_THREAD(tid); assert(!ptr); - ptr = new HTTPRequestImpl(this, loop, std::move(response)); + ptr = new HTTPRequestImpl(this, loop, response); } void HTTPRequest::retryImmediately() { diff --git a/platform/default/asset_request_fs.cpp b/platform/default/asset_request_fs.cpp index 5ebde2d88..a7d813b72 100644 --- a/platform/default/asset_request_fs.cpp +++ b/platform/default/asset_request_fs.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -207,7 +207,7 @@ void AssetRequestImpl::cleanup(uv_fs_t *req) { // ------------------------------------------------------------------------------------------------- -AssetRequest::AssetRequest(DefaultFileSource *source_, const Resource &resource_) +AssetRequest::AssetRequest(DefaultFileSource::Impl *source_, const Resource &resource_) : SharedRequestBase(source_, resource_) { assert(algo::starts_with(resource.url, "asset://")); } @@ -220,7 +220,7 @@ AssetRequest::~AssetRequest() { } } -void AssetRequest::start(uv_loop_t *loop, std::unique_ptr response) { +void AssetRequest::start(uv_loop_t *loop, std::shared_ptr response) { MBGL_VERIFY_THREAD(tid); // We're ignoring the existing response if any. diff --git a/platform/default/asset_request_zip.cpp b/platform/default/asset_request_zip.cpp index fd27c4b95..22d426c76 100644 --- a/platform/default/asset_request_zip.cpp +++ b/platform/default/asset_request_zip.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include #include @@ -275,7 +275,7 @@ void AssetRequestImpl::cancel() { // ------------------------------------------------------------------------------------------------- -AssetRequest::AssetRequest(DefaultFileSource *source_, const Resource &resource_) +AssetRequest::AssetRequest(DefaultFileSource::Impl *source_, const Resource &resource_) : SharedRequestBase(source_, resource_) { assert(algo::starts_with(resource.url, "asset://")); } @@ -288,7 +288,7 @@ AssetRequest::~AssetRequest() { } } -void AssetRequest::start(uv_loop_t *loop, std::unique_ptr response) { +void AssetRequest::start(uv_loop_t *loop, std::shared_ptr response) { MBGL_VERIFY_THREAD(tid); // We're ignoring the existing response if any. diff --git a/platform/default/headless_view.cpp b/platform/default/headless_view.cpp index df85ee714..f8622604e 100644 --- a/platform/default/headless_view.cpp +++ b/platform/default/headless_view.cpp @@ -1,7 +1,10 @@ + #include #include #include +#include + #include #include @@ -36,17 +39,17 @@ CGLProc CGLGetProcAddress(const char *proc) { namespace mbgl { - -HeadlessView::HeadlessView() - : display_(std::make_shared()) { - createContext(); - loadExtensions(); +HeadlessView::HeadlessView(uint16_t width, uint16_t height, float pixelRatio) + : display(std::make_shared()) { + resize(width, height, pixelRatio); } -HeadlessView::HeadlessView(std::shared_ptr display) - : display_(display) { - createContext(); - loadExtensions(); +HeadlessView::HeadlessView(std::shared_ptr display_, + uint16_t width, + uint16_t height, + float pixelRatio) + : display(display_) { + resize(width, height, pixelRatio); } void HeadlessView::loadExtensions() { @@ -54,8 +57,6 @@ void HeadlessView::loadExtensions() { return; } - activate(); - pthread_once(&loadGLExtensions, [] { const char *extensionPtr = reinterpret_cast(MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS))); @@ -95,17 +96,15 @@ void HeadlessView::loadExtensions() { gl::isDepth24Supported = true; extensionsLoaded = true; - - deactivate(); } void HeadlessView::createContext() { - if (!display_) { + if (!display) { throw std::runtime_error("Display is not set"); } #if MBGL_USE_CGL - CGLError error = CGLCreateContext(display_->pixelFormat, NULL, &glContext); + CGLError error = CGLCreateContext(display->pixelFormat, NULL, &glContext); if (error != kCGLNoError) { throw std::runtime_error(std::string("Error creating GL context object:") + CGLErrorString(error) + "\n"); } @@ -117,8 +116,8 @@ void HeadlessView::createContext() { #endif #if MBGL_USE_GLX - xDisplay = display_->xDisplay; - fbConfigs = display_->fbConfigs; + xDisplay = display->xDisplay; + fbConfigs = display->fbConfigs; if (!glContext) { // Try to create a legacy context @@ -147,17 +146,34 @@ void HeadlessView::createContext() { #endif } +bool HeadlessView::isActive() { + return std::this_thread::get_id() == thread; +} + void HeadlessView::resize(const uint16_t width, const uint16_t height, const float pixelRatio) { + std::lock_guard lock(prospectiveMutex); + prospective = { width, height, pixelRatio }; +} + +HeadlessView::Dimensions::Dimensions(uint16_t width_, uint16_t height_, float pixelRatio_) + : width(width_), height(height_), pixelRatio(pixelRatio_) { +} + +void HeadlessView::discard() { + assert(isActive()); + + { // Obtain the new values. + std::lock_guard lock(prospectiveMutex); + if (current.pixelWidth() == prospective.pixelWidth() && current.pixelHeight() == prospective.pixelHeight()) { + return; + } + current = prospective; + } + clearBuffers(); - width_ = width; - height_ = height; - pixelRatio_ = pixelRatio; - - const unsigned int w = width_ * pixelRatio_; - const unsigned int h = height_ * pixelRatio_; - - activate(); + const unsigned int w = current.width * current.pixelRatio; + const unsigned int h = current.height * current.pixelRatio; // Create depth/stencil buffer MBGL_CHECK_ERROR(glGenRenderbuffersEXT(1, &fboDepthStencil)); @@ -193,35 +209,36 @@ void HeadlessView::resize(const uint16_t width, const uint16_t height, const flo throw std::runtime_error(error.str()); } - View::resize(width, height, pixelRatio, w, h); - - deactivate(); + View::resize(current.width, current.height, current.pixelRatio, w, h); } -std::unique_ptr HeadlessView::readPixels() { - const unsigned int w = width_ * pixelRatio_; - const unsigned int h = height_ * pixelRatio_; +std::unique_ptr HeadlessView::readStillImage() { + assert(isActive()); - auto pixels = util::make_unique(w * h); + const unsigned int w = current.pixelWidth(); + const unsigned int h = current.pixelHeight(); - activate(); - MBGL_CHECK_ERROR(glReadPixels(0, 0, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, pixels.get())); - deactivate(); + auto image = util::make_unique(); + image->width = w; + image->height = h; + image->pixels = util::make_unique(w * h); + + MBGL_CHECK_ERROR(glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels.get())); const int stride = w * 4; auto tmp = util::make_unique(stride); - char *rgba = reinterpret_cast(pixels.get()); - for (int i = 0, j = height_ - 1; i < j; i++, j--) { + char *rgba = reinterpret_cast(image->pixels.get()); + for (int i = 0, j = h - 1; i < j; i++, j--) { std::memcpy(tmp.get(), rgba + i * stride, stride); std::memcpy(rgba + i * stride, rgba + j * stride, stride); std::memcpy(rgba + j * stride, tmp.get(), stride); } - return pixels; + return image; } void HeadlessView::clearBuffers() { - activate(); + assert(isActive()); MBGL_CHECK_ERROR(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)); @@ -239,12 +256,12 @@ void HeadlessView::clearBuffers() { MBGL_CHECK_ERROR(glDeleteRenderbuffersEXT(1, &fboDepthStencil)); fboDepthStencil = 0; } - - deactivate(); } HeadlessView::~HeadlessView() { + activate(); clearBuffers(); + deactivate(); #if MBGL_USE_CGL CGLDestroyContext(glContext); @@ -265,6 +282,15 @@ void HeadlessView::notify() { } void HeadlessView::activate() { + if (thread != std::thread::id()) { + throw std::runtime_error("OpenGL context was already current"); + } + thread = std::this_thread::get_id(); + + if (!glContext) { + createContext(); + } + #if MBGL_USE_CGL CGLError error = CGLSetCurrentContext(glContext); if (error != kCGLNoError) { @@ -277,9 +303,17 @@ void HeadlessView::activate() { throw std::runtime_error("Switching OpenGL context failed.\n"); } #endif + + loadExtensions(); + discard(); } void HeadlessView::deactivate() { + if (thread == std::thread::id()) { + throw std::runtime_error("OpenGL context was not current"); + } + thread = std::thread::id(); + #if MBGL_USE_CGL CGLError error = CGLSetCurrentContext(nullptr); if (error != kCGLNoError) { diff --git a/platform/default/http_request_curl.cpp b/platform/default/http_request_curl.cpp index a7ec162aa..1672c9cdb 100644 --- a/platform/default/http_request_curl.cpp +++ b/platform/default/http_request_curl.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include #include @@ -95,7 +95,7 @@ class HTTPRequestImpl { MBGL_STORE_THREAD(tid) public: - HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr response); + HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::shared_ptr response); ~HTTPRequestImpl(); void handleResult(CURLcode code); @@ -123,7 +123,7 @@ private: std::unique_ptr response; // In case of revalidation requests, this will store the old response. - std::unique_ptr existingResponse; + const std::shared_ptr existingResponse; CURL *handle = nullptr; curl_slist *headers = nullptr; @@ -425,10 +425,10 @@ static CURLcode sslctx_function(CURL * /* curl */, void *sslctx, void * /* parm } #endif -HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, std::unique_ptr response_) +HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, std::shared_ptr response_) : context(HTTPCURLContext::Get(loop)), request(request_), - existingResponse(std::move(response_)), + existingResponse(response_), handle(context->getHandle()) { assert(request); context->addRequest(request); @@ -688,12 +688,12 @@ void HTTPRequestImpl::handleResult(CURLcode code) { if (responseCode == 304) { if (existingResponse) { - // We're going to reuse the old response object, but need to copy over the new - // expires value (if possible). - std::swap(response, existingResponse); - if (existingResponse->expires) { - response->expires = existingResponse->expires; - } + // We're going to copy over the existing response's data. + response->status = existingResponse->status; + response->message = existingResponse->message; + response->modified = existingResponse->modified; + response->etag = existingResponse->etag; + response->data = existingResponse->data; return finish(ResponseStatus::NotModified); } else { // This is an unsolicited 304 response and should only happen on malfunctioning @@ -722,7 +722,7 @@ void HTTPRequestImpl::handleResult(CURLcode code) { // ------------------------------------------------------------------------------------------------- -HTTPRequest::HTTPRequest(DefaultFileSource *source_, const Resource &resource_) +HTTPRequest::HTTPRequest(DefaultFileSource::Impl *source_, const Resource &resource_) : SharedRequestBase(source_, resource_) { } @@ -734,11 +734,11 @@ HTTPRequest::~HTTPRequest() { } } -void HTTPRequest::start(uv_loop_t *loop, std::unique_ptr response) { +void HTTPRequest::start(uv_loop_t *loop, std::shared_ptr response) { MBGL_VERIFY_THREAD(tid); assert(!ptr); - ptr = new HTTPRequestImpl(this, loop, std::move(response)); + ptr = new HTTPRequestImpl(this, loop, response); } void HTTPRequest::retryImmediately() { diff --git a/platform/default/sqlite3.cpp b/platform/default/sqlite3.cpp index 19ecaba0b..b2ae4e65b 100644 --- a/platform/default/sqlite3.cpp +++ b/platform/default/sqlite3.cpp @@ -76,11 +76,16 @@ Statement::Statement(sqlite3 *db, const char *sql) { } } -#define CHECK_SQLITE_OK(err) \ +#define CHECK_SQLITE_OK_STMT(err, stmt) \ if (err != SQLITE_OK) { \ throw Exception { err, sqlite3_errmsg(sqlite3_db_handle(stmt)) }; \ } +#define CHECK_SQLITE_OK(err) \ + if (err != SQLITE_OK) { \ + throw Exception { err, sqlite3_errstr(err) }; \ + } + Statement::Statement(Statement &&other) { *this = std::move(other); } @@ -92,8 +97,7 @@ Statement &Statement::operator=(Statement &&other) { Statement::~Statement() { if (stmt) { - const int err = sqlite3_finalize(stmt); - CHECK_SQLITE_OK(err) + sqlite3_finalize(stmt); } } @@ -101,38 +105,38 @@ Statement::operator bool() const { return stmt != nullptr; } -#define BIND_3(type, value) \ +#define BIND_3(type, value, stmt) \ assert(stmt); \ const int err = sqlite3_bind_##type(stmt, offset, value); \ - CHECK_SQLITE_OK(err) + CHECK_SQLITE_OK_STMT(err, stmt) -#define BIND_5(type, value, length, param) \ +#define BIND_5(type, value, length, param, stmt) \ assert(stmt); \ const int err = sqlite3_bind_##type(stmt, offset, value, length, param); \ - CHECK_SQLITE_OK(err) + CHECK_SQLITE_OK_STMT(err, stmt) template <> void Statement::bind(int offset, int value) { - BIND_3(int, value) + BIND_3(int, value, stmt) } template <> void Statement::bind(int offset, int64_t value) { - BIND_3(int64, value) + BIND_3(int64, value, stmt) } template <> void Statement::bind(int offset, double value) { - BIND_3(double, value) + BIND_3(double, value, stmt) } template <> void Statement::bind(int offset, bool value) { - BIND_3(int, value) + BIND_3(int, value, stmt) } template <> void Statement::bind(int offset, const char *value) { - BIND_5(text, value, -1, nullptr) + BIND_5(text, value, -1, nullptr, stmt) } void Statement::bind(int offset, const std::string &value, bool retain) { - BIND_5(blob, value.data(), int(value.size()), retain ? SQLITE_TRANSIENT : SQLITE_STATIC) + BIND_5(blob, value.data(), int(value.size()), retain ? SQLITE_TRANSIENT : SQLITE_STATIC, stmt) } bool Statement::run() { @@ -143,7 +147,8 @@ bool Statement::run() { } else if (err == SQLITE_ROW) { return true; } else { - throw std::runtime_error("failed to run statement"); + CHECK_SQLITE_OK_STMT(err, stmt) + return false; } } diff --git a/platform/default/sqlite_cache.cpp b/platform/default/sqlite_cache.cpp index b8d47159c..a57e666e9 100644 --- a/platform/default/sqlite_cache.cpp +++ b/platform/default/sqlite_cache.cpp @@ -1,18 +1,14 @@ -#include -#include +#include "sqlite_cache_impl.hpp" +#include #include -#include -#include -#include #include +#include +#include #include #include "sqlite3.hpp" - -#include - -#include +#include namespace mbgl { @@ -65,81 +61,34 @@ std::string unifyMapboxURLs(const std::string &url) { using namespace mapbox::sqlite; -struct SQLiteCache::GetAction { - const Resource resource; - const std::function)> callback; -}; - -struct SQLiteCache::PutAction { - const Resource resource; - const std::shared_ptr response; -}; - -struct SQLiteCache::RefreshAction { - const Resource resource; - const int64_t expires; -}; - -struct SQLiteCache::StopAction { -}; - -struct SQLiteCache::ActionDispatcher { - SQLiteCache &cache; - template void operator()(T &t) { cache.process(t); } -}; - -SQLiteCache::SQLiteCache(const std::string &path_) - : path(path_), - loop(uv_loop_new()), - queue(new Queue(loop, [this](Action &action) { - mapbox::util::apply_visitor(ActionDispatcher{ *this }, action); - })), - thread([this]() { -#ifdef __APPLE__ - pthread_setname_np("SQLite Cache"); -#endif - uv_run(loop, UV_RUN_DEFAULT); - }) -{ +SQLiteCache::SQLiteCache(const std::string& path_) + : thread(util::make_unique>("SQLite Cache", path_)) { } -SQLiteCache::~SQLiteCache() { - if (thread.joinable()) { - if (queue) { - queue->send(StopAction{ }); - } - thread.join(); - uv_loop_delete(loop); +SQLiteCache::~SQLiteCache() = default; + +SQLiteCache::Impl::Impl(const std::string& path_) + : path(path_) { +} + +SQLiteCache::Impl::~Impl() { + // Deleting these SQLite objects may result in exceptions, but we're in a destructor, so we + // can't throw anything. + try { + getStmt.reset(); + putStmt.reset(); + refreshStmt.reset(); + db.reset(); + } catch (mapbox::sqlite::Exception& ex) { + Log::Error(Event::Database, ex.code, ex.what()); } } - -void SQLiteCache::get(const Resource &resource, std::function)> callback) { - // Can be called from any thread, but most likely from the file source thread. - // Will try to load the URL from the SQLite database and call the callback when done. - // Note that the callback is probably going to invoked from another thread, so the caller - // must make sure that it can run in that thread. - assert(queue); - queue->send(GetAction{ resource, callback }); -} - -void SQLiteCache::put(const Resource &resource, std::shared_ptr response, Hint hint) { - // Can be called from any thread, but most likely from the file source thread. We are either - // storing a new response or updating the currently stored response, potentially setting a new - // expiry date. - assert(queue); - assert(response); - - if (hint == Hint::Full) { - queue->send(PutAction{ resource, response }); - } else if (hint == Hint::Refresh) { - queue->send(RefreshAction{ resource, response->expires }); - } -} - -void SQLiteCache::createDatabase() { +void SQLiteCache::Impl::createDatabase() { db = util::make_unique(path.c_str(), ReadWrite | Create); +} +void SQLiteCache::Impl::createSchema() { constexpr const char *const sql = "" "CREATE TABLE IF NOT EXISTS `http_cache` (" " `url` TEXT PRIMARY KEY NOT NULL," @@ -155,117 +104,164 @@ void SQLiteCache::createDatabase() { try { db->exec(sql); - } catch(mapbox::sqlite::Exception &) { + schema = true; + } catch (mapbox::sqlite::Exception &ex) { + if (ex.code == SQLITE_NOTADB) { + Log::Warning(Event::Database, "Trashing invalid database"); + db.reset(); + try { + util::deleteFile(path); + } catch (util::IOException& ioEx) { + Log::Error(Event::Database, ex.code, ex.what()); + } + db = util::make_unique(path.c_str(), ReadWrite | Create); + } else { + Log::Error(Event::Database, ex.code, ex.what()); + } + // Creating the database table + index failed. That means there may already be one, likely // with different columsn. Drop it and try to create a new one. - try { - db->exec("DROP TABLE IF EXISTS `http_cache`"); - db->exec(sql); - } catch (mapbox::sqlite::Exception &ex) { - Log::Error(Event::Database, "Failed to create database: %s", ex.what()); - db.reset(); + db->exec("DROP TABLE IF EXISTS `http_cache`"); + db->exec(sql); + } +} + +void SQLiteCache::get(const Resource &resource, Callback callback) { + // Can be called from any thread, but most likely from the file source thread. + // Will try to load the URL from the SQLite database and call the callback when done. + // Note that the callback is probably going to invoked from another thread, so the caller + // must make sure that it can run in that thread. + thread->invokeWithResult(&Impl::get, callback, resource); +} + +std::unique_ptr SQLiteCache::Impl::get(const Resource &resource) { + try { + // This is called in the SQLite event loop. + if (!db) { + createDatabase(); } - } -} -void SQLiteCache::process(GetAction &action) { - // This is called in the SQLite event loop. - if (!db) { - createDatabase(); - } - - if (!getStmt) { - // Initialize the statement 0 1 - getStmt = util::make_unique(db->prepare("SELECT `status`, `modified`, " - // 2 3 4 5 1 - "`etag`, `expires`, `data`, `compressed` FROM `http_cache` WHERE `url` = ?")); - } else { - getStmt->reset(); - } - - const std::string unifiedURL = unifyMapboxURLs(action.resource.url); - getStmt->bind(1, unifiedURL.c_str()); - if (getStmt->run()) { - // There is data. - auto response = util::make_unique(); - response->status = Response::Status(getStmt->get(0)); - response->modified = getStmt->get(1); - response->etag = getStmt->get(2); - response->expires = getStmt->get(3); - response->data = getStmt->get(4); - if (getStmt->get(5)) { // == compressed - response->data = util::decompress(response->data); + if (!schema) { + createSchema(); } - action.callback(std::move(response)); - } else { - // There is no data. - action.callback(nullptr); + + if (!getStmt) { + // Initialize the statement 0 1 + getStmt = util::make_unique(db->prepare("SELECT `status`, `modified`, " + // 2 3 4 5 1 + "`etag`, `expires`, `data`, `compressed` FROM `http_cache` WHERE `url` = ?")); + } else { + getStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(resource.url); + getStmt->bind(1, unifiedURL.c_str()); + if (getStmt->run()) { + // There is data. + auto response = util::make_unique(); + response->status = Response::Status(getStmt->get(0)); + response->modified = getStmt->get(1); + response->etag = getStmt->get(2); + response->expires = getStmt->get(3); + response->data = getStmt->get(4); + if (getStmt->get(5)) { // == compressed + response->data = util::decompress(response->data); + } + return std::move(response); + } else { + // There is no data. + return nullptr; + } + } catch (mapbox::sqlite::Exception& ex) { + Log::Error(Event::Database, ex.code, ex.what()); + return nullptr; } } -void SQLiteCache::process(PutAction &action) { - if (!db) { - createDatabase(); +void SQLiteCache::put(const Resource &resource, std::shared_ptr response, Hint hint) { + // Can be called from any thread, but most likely from the file source thread. We are either + // storing a new response or updating the currently stored response, potentially setting a new + // expiry date. + if (hint == Hint::Full) { + thread->invoke(&Impl::put, resource, std::move(response)); + } else if (hint == Hint::Refresh) { + thread->invoke(&Impl::refresh, resource, int64_t(response->expires)); } - - if (!putStmt) { - putStmt = util::make_unique(db->prepare("REPLACE INTO `http_cache` (" - // 1 2 3 4 5 6 7 8 - "`url`, `status`, `kind`, `modified`, `etag`, `expires`, `data`, `compressed`" - ") VALUES(?, ?, ?, ?, ?, ?, ?, ?)")); - } else { - putStmt->reset(); - } - - const std::string unifiedURL = unifyMapboxURLs(action.resource.url); - putStmt->bind(1 /* url */, unifiedURL.c_str()); - putStmt->bind(2 /* status */, int(action.response->status)); - putStmt->bind(3 /* kind */, int(action.resource.kind)); - putStmt->bind(4 /* modified */, action.response->modified); - putStmt->bind(5 /* etag */, action.response->etag.c_str()); - putStmt->bind(6 /* expires */, action.response->expires); - - std::string data; - if (action.resource.kind != Resource::Image) { - // Do not compress images, since they are typically compressed already. - data = util::compress(action.response->data); - } - - if (!data.empty() && data.size() < action.response->data.size()) { - // Store the compressed data when it is smaller than the original - // uncompressed data. - putStmt->bind(7 /* data */, data, false); // do not retain the string internally. - putStmt->bind(8 /* compressed */, true); - } else { - putStmt->bind(7 /* data */, action.response->data, false); // do not retain the string internally. - putStmt->bind(8 /* compressed */, false); - } - - putStmt->run(); } -void SQLiteCache::process(RefreshAction &action) { - if (!db) { - createDatabase(); - } +void SQLiteCache::Impl::put(const Resource& resource, std::shared_ptr response) { + try { + if (!db) { + createDatabase(); + } - if (!refreshStmt) { - refreshStmt = util::make_unique( // 1 2 - db->prepare("UPDATE `http_cache` SET `expires` = ? WHERE `url` = ?")); - } else { - refreshStmt->reset(); - } + if (!schema) { + createSchema(); + } - const std::string unifiedURL = unifyMapboxURLs(action.resource.url); - refreshStmt->bind(1, int64_t(action.expires)); - refreshStmt->bind(2, unifiedURL.c_str()); - refreshStmt->run(); + if (!putStmt) { + putStmt = util::make_unique(db->prepare("REPLACE INTO `http_cache` (" + // 1 2 3 4 5 6 7 8 + "`url`, `status`, `kind`, `modified`, `etag`, `expires`, `data`, `compressed`" + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?)")); + } else { + putStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(resource.url); + putStmt->bind(1 /* url */, unifiedURL.c_str()); + putStmt->bind(2 /* status */, int(response->status)); + putStmt->bind(3 /* kind */, int(resource.kind)); + putStmt->bind(4 /* modified */, response->modified); + putStmt->bind(5 /* etag */, response->etag.c_str()); + putStmt->bind(6 /* expires */, response->expires); + + std::string data; + if (resource.kind != Resource::Image) { + // Do not compress images, since they are typically compressed already. + data = util::compress(response->data); + } + + if (!data.empty() && data.size() < response->data.size()) { + // Store the compressed data when it is smaller than the original + // uncompressed data. + putStmt->bind(7 /* data */, data, false); // do not retain the string internally. + putStmt->bind(8 /* compressed */, true); + } else { + putStmt->bind(7 /* data */, response->data, false); // do not retain the string internally. + putStmt->bind(8 /* compressed */, false); + } + + putStmt->run(); + } catch (mapbox::sqlite::Exception& ex) { + Log::Error(Event::Database, ex.code, ex.what()); + } } -void SQLiteCache::process(StopAction &) { - assert(queue); - queue->stop(); - queue = nullptr; +void SQLiteCache::Impl::refresh(const Resource& resource, int64_t expires) { + try { + if (!db) { + createDatabase(); + } + + if (!schema) { + createSchema(); + } + + if (!refreshStmt) { + refreshStmt = util::make_unique( // 1 2 + db->prepare("UPDATE `http_cache` SET `expires` = ? WHERE `url` = ?")); + } else { + refreshStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(resource.url); + refreshStmt->bind(1, int64_t(expires)); + refreshStmt->bind(2, unifiedURL.c_str()); + refreshStmt->run(); + } catch (mapbox::sqlite::Exception& ex) { + Log::Error(Event::Database, ex.code, ex.what()); + } } } diff --git a/platform/default/sqlite_cache_impl.hpp b/platform/default/sqlite_cache_impl.hpp new file mode 100644 index 000000000..2ebaa284a --- /dev/null +++ b/platform/default/sqlite_cache_impl.hpp @@ -0,0 +1,39 @@ +#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE_IMPL +#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE_IMPL + +#include + +namespace mapbox { +namespace sqlite { +class Database; +class Statement; +} +} + +namespace mbgl { + +class SQLiteCache::Impl { +public: + Impl(const std::string &path = ":memory:"); + ~Impl(); + + std::unique_ptr get(const Resource&); + void put(const Resource& resource, std::shared_ptr response); + void refresh(const Resource& resource, int64_t expires); + +private: + void createDatabase(); + void createSchema(); + + const std::string path; + std::unique_ptr<::mapbox::sqlite::Database> db; + std::unique_ptr<::mapbox::sqlite::Statement> getStmt; + std::unique_ptr<::mapbox::sqlite::Statement> putStmt; + std::unique_ptr<::mapbox::sqlite::Statement> refreshStmt; + bool schema = false; +}; + + +} + +#endif diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index d48694917..f9ed77041 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -1,4 +1,5 @@ #import "MGLMapView.h" +#import "MGLMapView+IBAdditions.h" #import #import @@ -10,11 +11,13 @@ #include #include #include -#include +#include #include #include #import "MGLTypes.h" +#import "NSString+MGLAdditions.h" +#import "NSProcessInfo+MGLAdditions.h" #import "MGLAnnotation.h" #import "MGLUserLocationAnnotationView.h" #import "MGLUserLocation_Private.h" @@ -42,9 +45,10 @@ const std::string &defaultCacheDatabase() { static dispatch_once_t loadGLExtensions; -NSString *const MGLDefaultStyleName = @"Emerald"; -NSString *const MGLStyleVersion = @"v7"; +NSString *const MGLDefaultStyleName = @"mapbox-streets"; +NSString *const MGLStyleVersion = @"7"; NSString *const MGLDefaultStyleMarkerSymbolName = @"default_marker"; +NSString *const MGLMapboxAccessTokenManagerURLDisplayString = @"mapbox.com/account/apps"; const NSTimeInterval MGLAnimationDuration = 0.3; const CGSize MGLAnnotationUpdateViewportOutset = {150, 150}; @@ -52,12 +56,18 @@ const CGFloat MGLMinimumZoom = 3; NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; +static NSURL *MGLURLForBundledStyleNamed(NSString *styleName) +{ + return [NSURL URLWithString:[NSString stringWithFormat:@"asset://styles/%@.json", styleName]]; +} + #pragma mark - Private - @interface MGLMapView () @property (nonatomic) EAGLContext *context; @property (nonatomic) GLKView *glView; +@property (nonatomic) UIImageView *glSnapshotView; @property (nonatomic) NSOperationQueue *regionChangeDelegateQueue; @property (nonatomic) UIImageView *compass; @property (nonatomic) UIImageView *logoBug; @@ -66,7 +76,7 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; @property (nonatomic) UIPinchGestureRecognizer *pinch; @property (nonatomic) UIRotationGestureRecognizer *rotate; @property (nonatomic) UILongPressGestureRecognizer *quickZoom; -@property (nonatomic) NSMutableArray *bundledStyleNames; +@property (nonatomic) NSMutableArray *bundledStyleURLs; @property (nonatomic) NSMapTable *annotationIDsByAnnotation; @property (nonatomic) std::vector annotationsNearbyLastTap; @property (nonatomic, weak) id selectedAnnotation; @@ -83,6 +93,11 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; @end @implementation MGLMapView +{ + BOOL _isTargetingInterfaceBuilder; + CLLocationDegrees _pendingLatitude; + CLLocationDegrees _pendingLongitude; +} #pragma mark - Setup & Teardown - @@ -100,37 +115,22 @@ MBGLView *mbglView = nullptr; mbgl::SQLiteCache *mbglFileCache = nullptr; mbgl::DefaultFileSource *mbglFileSource = nullptr; -- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleJSON:(NSString *)styleJSON +- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self && [self commonInit]) { - if (accessToken) [self setAccessToken:accessToken]; - - if (styleJSON || accessToken) - { - // If style is set directly, pass it on. If not, if we have an access - // token, we can pass nil and use the default style. - // - [self setStyleJSON:styleJSON]; - } + self.styleURL = nil; + return self; } - return self; + return nil; } -- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken bundledStyleNamed:(NSString *)styleName +- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken { - self = [super initWithFrame:frame]; - - if (self && [self commonInit]) - { - if (accessToken) [self setAccessToken:accessToken]; - if (styleName) [self useBundledStyleNamed:styleName]; - } - - return self; + return [self initWithFrame:frame accessToken:accessToken styleURL:nil]; } - (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL @@ -139,69 +139,72 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; if (self && [self commonInit]) { - if (accessToken) [self setAccessToken:accessToken]; - if (styleURL) [self setStyleURL:styleURL]; + self.accessToken = accessToken; + self.styleURL = styleURL; } return self; } -- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken -{ - return [self initWithFrame:frame accessToken:accessToken styleJSON:nil]; -} - - (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (self && [self commonInit]) { + self.styleURL = nil; return self; } return nil; } -- (void)setAccessToken:(NSString *)accessToken +- (NSString *)accessToken { - if (accessToken) - { - mbglMap->setAccessToken((std::string)[accessToken UTF8String]); - [MGLMapboxEvents setToken:accessToken]; - } + return @(mbglMap->getAccessToken().c_str()).mgl_stringOrNilIfEmpty; } -- (void)setStyleJSON:(NSString *)styleJSON +- (void)setAccessToken:(NSString *)accessToken { - if ( ! styleJSON) - { - [self useBundledStyleNamed:[[[MGLDefaultStyleName lowercaseString] - stringByAppendingString:@"-"] - stringByAppendingString:MGLStyleVersion]]; - } - else - { - mbglMap->setStyleJSON((std::string)[styleJSON UTF8String]); - } + mbglMap->setAccessToken(accessToken ? (std::string)[accessToken UTF8String] : ""); + [MGLMapboxEvents setToken:accessToken.mgl_stringOrNilIfEmpty]; +} + ++ (NSSet *)keyPathsForValuesAffectingStyleURL +{ + return [NSSet setWithObjects:@"mapID", @"accessToken", nil]; +} + +- (NSURL *)styleURL +{ + NSString *styleURLString = @(mbglMap->getStyleURL().c_str()).mgl_stringOrNilIfEmpty; + return styleURLString ? [NSURL URLWithString:styleURLString] : nil; } - (void)setStyleURL:(NSURL *)styleURL { - std::string styleURLString([[styleURL absoluteString] UTF8String]); - + if (_isTargetingInterfaceBuilder) return; + + if ( ! styleURL) + { + styleURL = MGLURLForBundledStyleNamed([NSString stringWithFormat:@"%@-v%@", + MGLDefaultStyleName.lowercaseString, + MGLStyleVersion]); + } + if ( ! [styleURL scheme]) { - mbglMap->setStyleURL(std::string("asset://") + styleURLString); - } - else - { - mbglMap->setStyleURL(styleURLString); + // Assume a relative path into the developer’s bundle. + styleURL = [[NSBundle mainBundle] URLForResource:styleURL.path withExtension:nil]; } + + mbglMap->setStyleURL([[styleURL absoluteString] UTF8String]); } - (BOOL)commonInit { + _isTargetingInterfaceBuilder = NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent; + // create context // _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; @@ -238,11 +241,14 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [self insertSubview:_glView atIndex:0]; _glView.contentMode = UIViewContentModeCenter; - [self setBackgroundColor:[UIColor clearColor]]; + + self.backgroundColor = [UIColor clearColor]; + self.clipsToBounds = YES; // load extensions // - dispatch_once(&loadGLExtensions, ^{ + dispatch_once(&loadGLExtensions, ^ + { const std::string extensions = (char *)glGetString(GL_EXTENSIONS); using namespace mbgl; @@ -288,9 +294,9 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // setup logo bug // - _logoBug = [[UIImageView alloc] initWithImage:[MGLMapView resourceImageNamed:@"mapbox.png"]]; + UIImage *logo = [[MGLMapView resourceImageNamed:@"mapbox.png"] imageWithAlignmentRectInsets:UIEdgeInsetsMake(1.5, 4, 3.5, 2)]; + _logoBug = [[UIImageView alloc] initWithImage:logo]; _logoBug.accessibilityLabel = @"Mapbox logo"; - _logoBug.frame = CGRectMake(8, self.bounds.size.height - _logoBug.bounds.size.height - 4, _logoBug.bounds.size.width, _logoBug.bounds.size.height); _logoBug.translatesAutoresizingMaskIntoConstraints = NO; [self addSubview:_logoBug]; @@ -299,7 +305,6 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; _attributionButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; _attributionButton.accessibilityLabel = @"Attribution info"; [_attributionButton addTarget:self action:@selector(showAttribution:) forControlEvents:UIControlEventTouchUpInside]; - _attributionButton.frame = CGRectMake(self.bounds.size.width - _attributionButton.bounds.size.width - 8, self.bounds.size.height - _attributionButton.bounds.size.height - 8, _attributionButton.bounds.size.width, _attributionButton.bounds.size.height); _attributionButton.translatesAutoresizingMaskIntoConstraints = NO; [self addSubview:_attributionButton]; @@ -310,7 +315,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; UIImage *compassImage = [MGLMapView resourceImageNamed:@"Compass.png"]; _compass.frame = CGRectMake(0, 0, compassImage.size.width, compassImage.size.height); _compass.alpha = 0; - UIView *container = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.size.width - compassImage.size.width - 5, 5, compassImage.size.width, compassImage.size.height)]; + UIView *container = [[UIView alloc] initWithFrame:CGRectZero]; [container addSubview:_compass]; container.translatesAutoresizingMaskIntoConstraints = NO; [container addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCompassTapGesture:)]]; @@ -361,18 +366,24 @@ 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]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; // set initial position // mbglMap->setLatLngZoom(mbgl::LatLng(0, 0), mbglMap->getMinZoom()); + _pendingLatitude = NAN; + _pendingLongitude = NAN; // setup change delegate queue // _regionChangeDelegateQueue = [NSOperationQueue new]; _regionChangeDelegateQueue.maxConcurrentOperationCount = 1; - // start the main loop - mbglMap->start(); + // start the main loop, but not on the IB canvas + if ( ! _isTargetingInterfaceBuilder) + { + mbglMap->start(); + } // metrics: map load event const mbgl::LatLng latLng = mbglMap->getLatLng(); @@ -480,70 +491,122 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // views so they don't underlap navigation or tool bars. If we don't have a reference, apply // constraints against ourself to maintain (albeit less ideal) placement of the subviews. // - NSString *topGuideFormatString = (self.viewControllerForLayoutGuides ? @"[topLayoutGuide]" : @"|"); - NSString *bottomGuideFormatString = (self.viewControllerForLayoutGuides ? @"[bottomLayoutGuide]" : @"|"); - - id topGuideViewsObject = (self.viewControllerForLayoutGuides ? (id)self.viewControllerForLayoutGuides.topLayoutGuide : (id)@""); - id bottomGuideViewsObject = (self.viewControllerForLayoutGuides ? (id)self.viewControllerForLayoutGuides.bottomLayoutGuide : (id)@""); - - UIView *constraintParentView = (self.viewControllerForLayoutGuides.view ? self.viewControllerForLayoutGuides.view : self); + UIView *constraintParentView = (self.viewControllerForLayoutGuides.view ? + self.viewControllerForLayoutGuides.view : + self); // compass // UIView *compassContainer = self.compass.superview; - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:%@-topSpacing-[container]", topGuideFormatString] - options:0 - metrics:@{ @"topSpacing" : @(5) } - views:@{ @"topLayoutGuide" : topGuideViewsObject, - @"container" : compassContainer }]]; + if (self.viewControllerForLayoutGuides) + { + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:compassContainer + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self.viewControllerForLayoutGuides.topLayoutGuide + attribute:NSLayoutAttributeBottom + multiplier:1 + constant:5]]; + } + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:compassContainer + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self + attribute:NSLayoutAttributeTop + multiplier:1 + constant:5]]; - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[container]-rightSpacing-|" - options:0 - metrics:@{ @"rightSpacing" : @(5) } - views:@{ @"container" : compassContainer }]]; + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self + attribute:NSLayoutAttributeTrailing + relatedBy:NSLayoutRelationEqual + toItem:compassContainer + attribute:NSLayoutAttributeTrailing + multiplier:1 + constant:5]]; - [compassContainer addConstraint:[NSLayoutConstraint constraintWithItem:compassContainer - attribute:NSLayoutAttributeWidth - relatedBy:NSLayoutRelationEqual - toItem:nil - attribute:NSLayoutAttributeNotAnAttribute - multiplier:1 - constant:self.compass.image.size.width]]; + [compassContainer addConstraint: + [NSLayoutConstraint constraintWithItem:compassContainer + attribute:NSLayoutAttributeWidth + relatedBy:NSLayoutRelationEqual + toItem:nil + attribute:NSLayoutAttributeNotAnAttribute + multiplier:1 + constant:self.compass.image.size.width]]; - [compassContainer addConstraint:[NSLayoutConstraint constraintWithItem:compassContainer - attribute:NSLayoutAttributeHeight - relatedBy:NSLayoutRelationEqual - toItem:nil - attribute:NSLayoutAttributeNotAnAttribute - multiplier:1 - constant:self.compass.image.size.height]]; + [compassContainer addConstraint: + [NSLayoutConstraint constraintWithItem:compassContainer + attribute:NSLayoutAttributeHeight + relatedBy:NSLayoutRelationEqual + toItem:nil + attribute:NSLayoutAttributeNotAnAttribute + multiplier:1 + constant:self.compass.image.size.height]]; // logo bug // - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[logoBug]-bottomSpacing-%@", bottomGuideFormatString] - options:0 - metrics:@{ @"bottomSpacing" : @(4) } - views:@{ @"logoBug" : self.logoBug, - @"bottomLayoutGuide" : bottomGuideViewsObject }]]; + if (self.viewControllerForLayoutGuides) + { + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self.viewControllerForLayoutGuides.bottomLayoutGuide + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self.logoBug + attribute:NSLayoutAttributeBaseline + multiplier:1 + constant:8]]; + } + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self + attribute:NSLayoutAttributeBottom + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self.logoBug + attribute:NSLayoutAttributeBaseline + multiplier:1 + constant:8]]; - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-leftSpacing-[logoBug]" - options:0 - metrics:@{ @"leftSpacing" : @(8) } - views:@{ @"logoBug" : self.logoBug }]]; + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self.logoBug + attribute:NSLayoutAttributeLeading + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeLeading + multiplier:1 + constant:8]]; // attribution button // - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[attributionButton]-bottomSpacing-%@", bottomGuideFormatString] - options:0 - metrics:@{ @"bottomSpacing" : @(8) } - views:@{ @"attributionButton" : self.attributionButton, - @"bottomLayoutGuide" : bottomGuideViewsObject }]]; + if (self.viewControllerForLayoutGuides) + { + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self.viewControllerForLayoutGuides.bottomLayoutGuide + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self.attributionButton + attribute:NSLayoutAttributeBaseline + multiplier:1 + constant:8]]; + } + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self + attribute:NSLayoutAttributeBottom + relatedBy:NSLayoutRelationGreaterThanOrEqual + toItem:self.attributionButton + attribute:NSLayoutAttributeBaseline + multiplier:1 + constant:8]]; - [constraintParentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[attributionButton]-rightSpacing-|" - options:0 - metrics:@{ @"rightSpacing" : @(8) } - views:@{ @"attributionButton" : self.attributionButton }]]; + [constraintParentView addConstraint: + [NSLayoutConstraint constraintWithItem:self + attribute:NSLayoutAttributeTrailing + relatedBy:NSLayoutRelationEqual + toItem:self.attributionButton + attribute:NSLayoutAttributeTrailing + multiplier:1 + constant:8]]; [super updateConstraints]; } @@ -551,15 +614,33 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // This is the delegate of the GLKView object's display call. - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { - mbglView->resize(rect.size.width, rect.size.height, view.contentScaleFactor, view.drawableWidth, view.drawableHeight); - mbglMap->renderSync(); + if ( ! self.glSnapshotView || self.glSnapshotView.hidden) + { + mbglView->resize(rect.size.width, rect.size.height, view.contentScaleFactor, view.drawableWidth, view.drawableHeight); + + CGFloat zoomFactor = mbglMap->getMaxZoom() - mbglMap->getMinZoom() + 1; + CGFloat cpuFactor = (CGFloat)[[NSProcessInfo processInfo] processorCount]; + CGFloat memoryFactor = (CGFloat)[[NSProcessInfo processInfo] physicalMemory] / 1000 / 1000 / 1000; + CGFloat sizeFactor = ((CGFloat)mbglMap->getState().getWidth() / mbgl::util::tileSize) * + ((CGFloat)mbglMap->getState().getHeight() / mbgl::util::tileSize); + + NSUInteger cacheSize = zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5; + + mbglMap->setSourceTileCacheSize(cacheSize); + + mbglMap->renderSync(); + } } // This gets called when the view dimension changes, e.g. because the device is being rotated. - (void)layoutSubviews { [super layoutSubviews]; - mbglMap->triggerUpdate(); + + if ( ! _isTargetingInterfaceBuilder) + { + mbglMap->triggerUpdate(); + } } #pragma mark - Life Cycle - @@ -570,7 +651,17 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)appDidBackground:(NSNotification *)notification { [MGLMapboxEvents flush]; - + + if ( ! self.glSnapshotView) + { + self.glSnapshotView = [[UIImageView alloc] initWithFrame:self.glView.frame]; + self.glSnapshotView.autoresizingMask = self.glView.autoresizingMask; + [self insertSubview:self.glSnapshotView aboveSubview:self.glView]; + } + + self.glSnapshotView.image = self.glView.snapshot; + self.glSnapshotView.hidden = NO; + mbglMap->stop(); [self.glView deleteDrawable]; @@ -578,6 +669,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)appWillForeground:(NSNotification *)notification { + self.glSnapshotView.hidden = YES; + [self.glView bindDrawable]; mbglMap->start(); @@ -1052,6 +1145,21 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; #pragma mark - Properties - ++ (NSSet *)keyPathsForValuesAffectingZoomEnabled +{ + return [NSSet setWithObject:@"allowsZooming"]; +} + ++ (NSSet *)keyPathsForValuesAffectingScrollEnabled +{ + return [NSSet setWithObject:@"allowsScrolling"]; +} + ++ (NSSet *)keyPathsForValuesAffectingRotateEnabled +{ + return [NSSet setWithObject:@"allowsRotating"]; +} + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" @@ -1095,12 +1203,6 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; if (finished) { [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; - - [UIView animateWithDuration:MGLAnimationDuration - animations:^ - { - self.compass.alpha = 0; - }]; } }]; } @@ -1117,8 +1219,18 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; mbglMap->toggleDebug(); } +- (void)emptyMemoryCache +{ + mbglMap->onLowMemory(); +} + #pragma mark - Geography - ++ (NSSet *)keyPathsForValuesAffectingCenterCoordinate +{ + return [NSSet setWithObjects:@"latitude", @"longitude", nil]; +} + - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated preservingTracking:(BOOL)tracking { self.userTrackingMode = (tracking ? self.userTrackingMode : MGLUserTrackingModeNone); @@ -1284,58 +1396,48 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) #pragma mark - Styling - -- (NSDictionary *)getRawStyle +- (NSArray *)bundledStyleURLs { - const std::string styleJSON = mbglMap->getStyleJSON(); + if ( ! _bundledStyleURLs) + { + NSString *stylesPath = [[MGLMapView resourceBundlePath] stringByAppendingPathComponent:@"styles"]; - 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:NSUTF8StringEncoding]]; -} - -- (NSArray *)bundledStyleNames -{ - if (!_bundledStyleNames) { - NSString *stylesPath = [[MGLMapView resourceBundlePath] stringByAppendingString:@"/styles"]; - - _bundledStyleNames = [NSMutableArray array]; + _bundledStyleURLs = [NSMutableArray array]; NSArray *bundledStyleNamesWithExtensions = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:stylesPath error:nil]; - NSString *hybridStylePrefix = @"hybrid-"; - NSString *satelliteStylePrefix = @"satellite-"; - for (NSString *fileName in bundledStyleNamesWithExtensions) { - NSString *styleName = [fileName stringByDeletingPathExtension]; - [_bundledStyleNames addObject:styleName]; - - // Add satellite raster & "hybrid" (satellite raster + vector contours & labels) - if ([styleName hasPrefix:satelliteStylePrefix]) { - [_bundledStyleNames addObject:[hybridStylePrefix stringByAppendingString:[styleName substringFromIndex:[satelliteStylePrefix length]]]]; - } + for (NSString *fileName in bundledStyleNamesWithExtensions) + { + [_bundledStyleURLs addObject:MGLURLForBundledStyleNamed([fileName stringByDeletingPathExtension])]; } } - return [NSArray arrayWithArray:_bundledStyleNames]; + return [NSArray arrayWithArray:_bundledStyleURLs]; } -- (void)useBundledStyleNamed:(NSString *)styleName ++ (NSSet *)keyPathsForValuesAffectingMapID { - NSString *hybridStylePrefix = @"hybrid-"; - BOOL isHybrid = [styleName hasPrefix:hybridStylePrefix]; - if (isHybrid) { - styleName = [@"satellite-" stringByAppendingString:[styleName substringFromIndex:[hybridStylePrefix length]]]; + return [NSSet setWithObjects:@"styleURL", @"accessToken", nil]; +} + +- (NSString *)mapID +{ + NSURL *styleURL = self.styleURL; + return [styleURL.scheme isEqualToString:@"mapbox"] ? styleURL.host.mgl_stringOrNilIfEmpty : nil; +} + +- (void)setMapID:(NSString *)mapID +{ + if (mapID) + { + self.styleURL = [NSURL URLWithString:[NSString stringWithFormat:@"mapbox://%@", mapID]]; } - [self setStyleURL:[NSURL URLWithString:[NSString stringWithFormat:@"styles/%@.json", styleName]]]; - if (isHybrid) { - [self setStyleClasses:@[@"contours", @"labels"]]; + else + { + self.styleURL = nil; } } -- (NSArray *)getAppliedStyleClasses +- (NSArray *)styleClasses { NSMutableArray *returnArray = [NSMutableArray array]; @@ -1367,6 +1469,27 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) mbglMap->setClasses(newAppliedClasses); } +- (BOOL)hasStyleClass:(NSString *)styleClass +{ + return styleClass && mbglMap->hasClass([styleClass UTF8String]); +} + +- (void)addStyleClass:(NSString *)styleClass +{ + if (styleClass) + { + mbglMap->addClass([styleClass UTF8String]); + } +} + +- (void)removeStyleClass:(NSString *)styleClass +{ + if (styleClass) + { + mbglMap->removeClass([styleClass UTF8String]); + } +} + #pragma mark - Annotations - - (NSArray *)annotations @@ -1624,6 +1747,8 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) } self.userLocationAnnotationView = [[MGLUserLocationAnnotationView alloc] initInMapView:self]; + self.userLocationAnnotationView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | + UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin); self.locationManager = [CLLocationManager new]; @@ -2176,6 +2301,17 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) } completion:nil]; } + else if (mbglMap->getBearing() == 0 && self.compass.alpha > 0) + { + [UIView animateWithDuration:MGLAnimationDuration + delay:0 + options:UIViewAnimationOptionBeginFromCurrentState + animations:^ + { + self.compass.alpha = 0; + } + completion:nil]; + } } + (UIImage *)resourceImageNamed:(NSString *)imageName @@ -2215,6 +2351,135 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) [self notifyMapChange:@(mbgl::MapChangeRegionIsChanging)]; } +- (void)prepareForInterfaceBuilder +{ + [super prepareForInterfaceBuilder]; + + self.layer.borderColor = [UIColor colorWithWhite:184/255. alpha:1].CGColor; + self.layer.borderWidth = 1; + + if (self.accessToken) + { + self.layer.backgroundColor = [UIColor colorWithRed:59/255. + green:178/255. + blue:208/255. + alpha:0.8].CGColor; + + UIImage *image = [[self class] resourceImageNamed:@"mapbox.png"]; + UIImageView *previewView = [[UIImageView alloc] initWithImage:image]; + previewView.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:previewView]; + [self addConstraint: + [NSLayoutConstraint constraintWithItem:previewView + attribute:NSLayoutAttributeCenterXWithinMargins + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterXWithinMargins + multiplier:1 + constant:0]]; + [self addConstraint: + [NSLayoutConstraint constraintWithItem:previewView + attribute:NSLayoutAttributeCenterYWithinMargins + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterYWithinMargins + multiplier:1 + constant:0]]; + } + else + { + UIView *diagnosticView = [[UIView alloc] init]; + diagnosticView.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:diagnosticView]; + + // Headline + UILabel *headlineLabel = [[UILabel alloc] init]; + headlineLabel.text = @"No Access Token"; + headlineLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]; + headlineLabel.textAlignment = NSTextAlignmentCenter; + headlineLabel.numberOfLines = 1; + headlineLabel.translatesAutoresizingMaskIntoConstraints = NO; + [headlineLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + [diagnosticView addSubview:headlineLabel]; + + // Explanation + UILabel *explanationLabel = [[UILabel alloc] init]; + explanationLabel.text = @"To display a map here, you must provide a Mapbox access token. Get an access token from:"; + explanationLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; + explanationLabel.numberOfLines = 0; + explanationLabel.translatesAutoresizingMaskIntoConstraints = NO; + [explanationLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + [diagnosticView addSubview:explanationLabel]; + + // Link + UIButton *linkButton = [UIButton buttonWithType:UIButtonTypeSystem]; + [linkButton setTitle:MGLMapboxAccessTokenManagerURLDisplayString forState:UIControlStateNormal]; + linkButton.translatesAutoresizingMaskIntoConstraints = NO; + [linkButton setContentCompressionResistancePriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + [diagnosticView addSubview:linkButton]; + + // More explanation + UILabel *explanationLabel2 = [[UILabel alloc] init]; + explanationLabel2.text = @"and enter it into the Access Token field in the Attributes inspector."; + explanationLabel2.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; + explanationLabel2.numberOfLines = 0; + explanationLabel2.translatesAutoresizingMaskIntoConstraints = NO; + [explanationLabel2 setContentCompressionResistancePriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + [diagnosticView addSubview:explanationLabel2]; + + // Constraints + NSDictionary *views = @{ + @"container": diagnosticView, + @"headline": headlineLabel, + @"explanation": explanationLabel, + @"link": linkButton, + @"explanation2": explanationLabel2, + }; + [self addConstraint: + [NSLayoutConstraint constraintWithItem:diagnosticView + attribute:NSLayoutAttributeCenterYWithinMargins + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterYWithinMargins + multiplier:1 + constant:0]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[container(20@20)]-|" + options:NSLayoutFormatAlignAllCenterY + metrics:nil + views:views]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headline]-[explanation]-[link]-[explanation2]|" + options:0 + metrics:nil + views:views]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[headline]|" + options:0 + metrics:nil + views:views]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[explanation]|" + options:0 + metrics:nil + views:views]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[link]|" + options:0 + metrics:nil + views:views]]; + [self addConstraints: + [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[explanation2]|" + options:0 + metrics:nil + views:views]]; + } +} + class MBGLView : public mbgl::View { public: @@ -2256,7 +2521,8 @@ class MBGLView : public mbgl::View [EAGLContext setCurrentContext:nil]; } - void resize(uint16_t width, uint16_t height, float ratio, uint16_t fbWidth, uint16_t fbHeight) { + void resize(uint16_t width, uint16_t height, float ratio, uint16_t fbWidth, uint16_t fbHeight) + { View::resize(width, height, ratio, fbWidth, fbHeight); } @@ -2272,3 +2538,109 @@ class MBGLView : public mbgl::View }; @end + +@implementation MGLMapView (IBAdditions) + ++ (NSSet *)keyPathsForValuesAffectingLatitude +{ + return [NSSet setWithObject:@"centerCoordinate"]; +} + +- (double)latitude +{ + return self.centerCoordinate.latitude; +} + +- (void)setLatitude:(double)latitude +{ + if ( ! isnan(_pendingLongitude)) + { + self.centerCoordinate = CLLocationCoordinate2DMake(latitude, _pendingLongitude); + _pendingLatitude = NAN; + _pendingLongitude = NAN; + } + else + { + // Not enough info to make a valid center coordinate yet. Stash this + // latitude away until the longitude is set too. + _pendingLatitude = latitude; + } +} + ++ (NSSet *)keyPathsForValuesAffectingLongitude +{ + return [NSSet setWithObject:@"centerCoordinate"]; +} + +- (double)longitude +{ + return self.centerCoordinate.longitude; +} + +- (void)setLongitude:(double)longitude +{ + if ( ! isnan(_pendingLatitude)) + { + self.centerCoordinate = CLLocationCoordinate2DMake(_pendingLatitude, longitude); + _pendingLatitude = NAN; + _pendingLongitude = NAN; + } + else + { + // Not enough info to make a valid center coordinate yet. Stash this + // longitude away until the latitude is set too. + _pendingLongitude = longitude; + } +} + ++ (NSSet *)keyPathsForValuesAffectingAllowsZooming +{ + return [NSSet setWithObject:@"zoomEnabled"]; +} + +- (BOOL)allowsZooming +{ + return self.zoomEnabled; +} + +- (void)setAllowsZooming:(BOOL)allowsZooming +{ + self.zoomEnabled = allowsZooming; +} + ++ (NSSet *)keyPathsForValuesAffectingAllowsScrolling +{ + return [NSSet setWithObject:@"scrollEnabled"]; +} + +- (BOOL)allowsScrolling +{ + return self.scrollEnabled; +} + +- (void)setAllowsScrolling:(BOOL)allowsScrolling +{ + self.scrollEnabled = allowsScrolling; +} + ++ (NSSet *)keyPathsForValuesAffectingAllowsRotating +{ + return [NSSet setWithObject:@"rotateEnabled"]; +} + +- (BOOL)allowsRotating +{ + return self.rotateEnabled; +} + +- (void)setAllowsRotating:(BOOL)allowsRotating +{ + self.rotateEnabled = allowsRotating; +} + +- (void)didReceiveMemoryWarning +{ + mbglMap->onLowMemory(); +} + +@end diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 1db0f9e9f..ee1ae82e7 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -6,6 +6,7 @@ #import #import "MGLMetricsLocationManager.h" +#import "NSProcessInfo+MGLAdditions.h" #include @@ -22,6 +23,9 @@ NSString *const MGLEventKeyLongitude = @"lng"; NSString *const MGLEventKeyZoomLevel = @"zoom"; NSString *const MGLEventKeySpeed = @"speed"; NSString *const MGLEventKeyCourse = @"course"; +NSString *const MGLEventKeyAltitude = @"altitude"; +NSString *const MGLEventKeyHorizontalAccuracy = @"horizontalAccuracy"; +NSString *const MGLEventKeyVerticalAccuracy = @"verticalAccuracy"; NSString *const MGLEventKeyPushEnabled = @"enabled.push"; NSString *const MGLEventKeyEmailEnabled = @"enabled.email"; NSString *const MGLEventKeyGestureID = @"gesture"; @@ -46,7 +50,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // from within a single thread use underscore syntax. // // All captures of `self` from within asynchronous -// dispatches will use a `weakSelf` to avoid cyclical +// dispatches will use a `strongSelf` to avoid cyclical // strong references. // @@ -69,6 +73,13 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; @property (atomic) NSUInteger flushAt; @property (atomic) NSDateFormatter *rfc3339DateFormatter; @property (atomic) CGFloat scale; +@property (atomic) NSURLSession *session; +@property (atomic) NSData *geoTrustCert; + + +// The isPaused state tracker is only ever accessed from the main thread. +// +@property (nonatomic) BOOL isPaused; // The timer is only ever accessed from the main thread. // @@ -123,11 +134,31 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; _serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL); // Configure Events Infrastructure + // =============================== + + _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; + + // Load Local Copy of Server's Public Key + NSString *cerPath = nil; + NSArray *bundles = [NSBundle allFrameworks]; + for (int lc = 0; lc < bundles.count; lc++) { + NSBundle *b = [bundles objectAtIndex:lc]; + cerPath = [[NSBundle mainBundle] pathForResource:@"api_mapbox_com-geotrust" ofType:@"der"]; + if (cerPath != nil) { + break; + } + } + if (cerPath != nil) { + _geoTrustCert = [NSData dataWithContentsOfFile:cerPath]; + } + + // Events Control _eventQueue = [[NSMutableArray alloc] init]; _flushAt = 20; _flushAfter = 60; _token = nil; _instanceID = [[NSUUID UUID] UUIDString]; + // Dynamic detection of ASIdentifierManager from Mixpanel // https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE _advertiserId = @""; @@ -163,8 +194,15 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; 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 setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"]; + // Clear Any System TimeZone Cache + [NSTimeZone resetSystemTimeZone]; + [_rfc3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; + + // Enable Battery Monitoring + [UIDevice currentDevice].batteryMonitoringEnabled = YES; + + _isPaused = NO; } return self; } @@ -176,17 +214,20 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; static dispatch_once_t onceToken; static MGLMapboxEvents *_sharedManager; dispatch_once(&onceToken, ^{ - 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(), ^{ + if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { + 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(); - }); - } else { - setupBlock(); + } } }); return _sharedManager; @@ -213,6 +254,28 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [MGLMapboxEvents sharedManager].appVersion = appVersion; } +// Must be called from the main thread. +// ++ (void) pauseMetricsCollection { + assert([[NSThread currentThread] isMainThread]); + if ([MGLMapboxEvents sharedManager].isPaused) { + return; + } + [MGLMapboxEvents sharedManager].isPaused = YES; + [MGLMetricsLocationManager stopUpdatingLocation]; +} + +// Must be called from the main thread. +// ++ (void) resumeMetricsCollection { + assert([[NSThread currentThread] isMainThread]); + if (![MGLMapboxEvents sharedManager].isPaused) { + return; + } + [MGLMapboxEvents sharedManager].isPaused = NO; + [MGLMetricsLocationManager startUpdatingLocation]; +} + // Can be called from any thread. Can be called rapidly from // the UI thread, so performance is paramount. // @@ -229,6 +292,9 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; __weak MGLMapboxEvents *weakSelf = self; dispatch_async(_serialQueue, ^{ + MGLMapboxEvents *strongSelf = weakSelf; + if ( ! strongSelf) return; + // Opt Out Checking When Built if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) { [_eventQueue removeAllObjects]; @@ -241,29 +307,46 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return; } + // Metrics Collection Has Been Paused + if (_isPaused) { + 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"]; + [evt setObject:[strongSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"]; + [evt setObject:strongSelf.instanceID forKey:@"instance"]; + [evt setObject:strongSelf.advertiserId forKey:@"advertiserId"]; + [evt setObject:strongSelf.vendorId forKey:@"vendorId"]; + [evt setObject:strongSelf.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"]; + [evt setValue:strongSelf.model forKey:@"model"]; + [evt setValue:strongSelf.iOSVersion forKey:@"operatingSystem"]; + [evt setValue:[strongSelf getDeviceOrientation] forKey:@"orientation"]; + [evt setValue:@((int)(100 * [UIDevice currentDevice].batteryLevel)) forKey:@"batteryLevel"]; + [evt setValue:@(strongSelf.scale) forKey:@"resolution"]; + [evt setValue:strongSelf.carrier forKey:@"carrier"]; + + NSString *cell = [strongSelf getCurrentCellularNetworkConnectionType]; + if (cell) { + [evt setValue:cell forKey:@"cellularNetworkType"]; + } else { + [evt setObject:[NSNull null] forKey:@"cellularNetworkType"]; + } + + NSString *wifi = [strongSelf getWifiNetworkName]; + if (wifi) { + [evt setValue:wifi forKey:@"wifi"]; + } else { + [evt setObject:[NSNull null] forKey:@"wifi"]; + } + + [evt setValue:@([strongSelf getContentSizeScale]) forKey:@"accessibilityFontScale"]; // Make Immutable Version NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt]; @@ -272,12 +355,12 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [_eventQueue addObject:finalEvent]; // Has Flush Limit Been Reached? - if (_eventQueue.count >= weakSelf.flushAt) { - [weakSelf flush]; + if (_eventQueue.count >= strongSelf.flushAt) { + [strongSelf flush]; } // Reset Timer (Initial Starting of Timer after first event is pushed) - [weakSelf startTimer]; + [strongSelf startTimer]; }); } @@ -295,10 +378,13 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; __weak MGLMapboxEvents *weakSelf = self; dispatch_async(_serialQueue, ^{ + MGLMapboxEvents *strongSelf = weakSelf; + if ( ! strongSelf) return; + __block NSArray *events; - NSUInteger upper = weakSelf.flushAt; - if (weakSelf.flushAt > [_eventQueue count]) { + NSUInteger upper = strongSelf.flushAt; + if (strongSelf.flushAt > [_eventQueue count]) { if ([_eventQueue count] == 0) { return; } @@ -313,7 +399,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [_eventQueue removeObjectsInRange:theRange]; // Send Array of Events to Server - [weakSelf postEvents:events]; + [strongSelf postEvents:events]; }); } @@ -324,10 +410,13 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; __weak MGLMapboxEvents *weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ + MGLMapboxEvents *strongSelf = weakSelf; + if (!strongSelf) return; + // Setup URL Request - NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, weakSelf.token]; + NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, strongSelf.token]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; - [request setValue:[weakSelf getUserAgent] forHTTPHeaderField:@"User-Agent"]; + [request setValue:[strongSelf getUserAgent] forHTTPHeaderField:@"User-Agent"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPMethod:@"POST"]; @@ -337,9 +426,8 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [request setHTTPBody:jsonData]; // Send non blocking HTTP Request to server - [NSURLConnection sendAsynchronousRequest:request - queue:nil - completionHandler:nil]; + NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler: nil]; + [task resume]; } }); } @@ -501,17 +589,13 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // - (NSString *) getWifiNetworkName { - NSString *ssid = @""; + NSString *ssid = nil; CFArrayRef interfaces = CNCopySupportedInterfaces(); if (interfaces) { NSDictionary *info = (__bridge NSDictionary *)CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(interfaces, 0)); if (info) { ssid = info[@"SSID"]; - } else { - ssid = @"NONE"; } - } else { - ssid = @"NONE"; } return ssid; @@ -520,11 +604,11 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // - (NSString *) getCurrentCellularNetworkConnectionType { - CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new]; + CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init]; NSString *radioTech = telephonyInfo.currentRadioAccessTechnology; if (radioTech == nil) { - return @"NONE"; + return nil; } else if ([radioTech isEqualToString:CTRadioAccessTechnologyGPRS]) { return @"GPRS"; } else if ([radioTech isEqualToString:CTRadioAccessTechnologyEdge]) { @@ -584,4 +668,49 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return result; } +#pragma mark NSURLSessionDelegate +- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^) (NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { + + if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + + SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust]; + NSString *domain = [[challenge protectionSpace] host]; + SecTrustResultType trustResult; + + // Validate the certificate chain with the device's trust store anyway + // This *might* give use revocation checking + SecTrustEvaluate(serverTrust, &trustResult); + if (trustResult == kSecTrustResultUnspecified) + { + // Look for a pinned certificate in the server's certificate chain + long numKeys = SecTrustGetCertificateCount(serverTrust); + + BOOL found = false; + for (int lc = 0; lc < numKeys; lc++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, lc); + NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate)); + + // Compare Remote Key With Local Version + if ([remoteCertificateData isEqualToData:_geoTrustCert]) { + // Found the certificate; continue connecting + completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); + found = true; + break; + } + } + + if (!found) { + // The certificate wasn't found in the certificate chain; cancel the connection + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); + } + } + else + { + // Certificate chain validation failed; cancel the connection + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); + } + } + +} + @end diff --git a/platform/ios/MGLMetricsLocationManager.m b/platform/ios/MGLMetricsLocationManager.m index 7a6d12ec1..af9b0a71b 100644 --- a/platform/ios/MGLMetricsLocationManager.m +++ b/platform/ios/MGLMetricsLocationManager.m @@ -14,9 +14,7 @@ - (instancetype) init { if (self = [super init]) { _locationManager = [[CLLocationManager alloc] init]; - _locationManager.distanceFilter = 2; - _locationManager.desiredAccuracy = kCLLocationAccuracyBest; - _locationManager.pausesLocationUpdatesAutomatically = YES; + _locationManager.distanceFilter = 10; [_locationManager setDelegate:self]; } return self; @@ -47,7 +45,10 @@ MGLEventKeyLatitude: @(loc.coordinate.latitude), MGLEventKeyLongitude: @(loc.coordinate.longitude), MGLEventKeySpeed: @(loc.speed), - MGLEventKeyCourse: @(loc.course) + MGLEventKeyCourse: @(loc.course), + MGLEventKeyAltitude: @(loc.altitude), + MGLEventKeyHorizontalAccuracy: @(loc.horizontalAccuracy), + MGLEventKeyVerticalAccuracy: @(loc.verticalAccuracy) }]; } } diff --git a/platform/ios/MGLUserLocationAnnotationView.m b/platform/ios/MGLUserLocationAnnotationView.m index 7a68d711f..c130582d6 100644 --- a/platform/ios/MGLUserLocationAnnotationView.m +++ b/platform/ios/MGLUserLocationAnnotationView.m @@ -30,6 +30,7 @@ const CGFloat MGLTrackingDotRingWidth = 24.0; self.annotation.mapView = mapView; _mapView = mapView; [self setupLayers]; + self.accessibilityLabel = @"User location"; } return self; } @@ -102,7 +103,7 @@ const CGFloat MGLTrackingDotRingWidth = 24.0; // if ( ! _dotBorderLayer) { - CGRect rect = CGRectMake(0, 0, MGLTrackingDotRingWidth * 1.25, MGLTrackingDotRingWidth * 1.25); + CGRect rect = CGRectMake(0, 0, MGLTrackingDotRingWidth * 1.5, MGLTrackingDotRingWidth * 1.5); UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]); CGContextRef context = UIGraphicsGetCurrentContext(); diff --git a/platform/ios/NSProcessInfo+MGLAdditions.h b/platform/ios/NSProcessInfo+MGLAdditions.h new file mode 100644 index 000000000..a117f3b76 --- /dev/null +++ b/platform/ios/NSProcessInfo+MGLAdditions.h @@ -0,0 +1,7 @@ +#import + +@interface NSProcessInfo (MGLAdditions) + +- (BOOL)mgl_isInterfaceBuilderDesignablesAgent; + +@end diff --git a/platform/ios/NSProcessInfo+MGLAdditions.m b/platform/ios/NSProcessInfo+MGLAdditions.m new file mode 100644 index 000000000..fca183c1f --- /dev/null +++ b/platform/ios/NSProcessInfo+MGLAdditions.m @@ -0,0 +1,10 @@ +#import "NSProcessInfo+MGLAdditions.h" + +@implementation NSProcessInfo (MGLAdditions) + +- (BOOL)mgl_isInterfaceBuilderDesignablesAgent +{ + return [self.processName isEqualToString:@"IBDesignablesAgentCocoaTouch"]; +} + +@end diff --git a/platform/ios/NSString+MGLAdditions.h b/platform/ios/NSString+MGLAdditions.h new file mode 100644 index 000000000..913f1cacd --- /dev/null +++ b/platform/ios/NSString+MGLAdditions.h @@ -0,0 +1,8 @@ +#import + +@interface NSString (MGLAdditions) + +/** Returns the receiver if non-empty or nil if empty. */ +- (NSString *)mgl_stringOrNilIfEmpty; + +@end diff --git a/platform/ios/NSString+MGLAdditions.m b/platform/ios/NSString+MGLAdditions.m new file mode 100644 index 000000000..d80c34cef --- /dev/null +++ b/platform/ios/NSString+MGLAdditions.m @@ -0,0 +1,10 @@ +#import "NSString+MGLAdditions.h" + +@implementation NSString (MGLAdditions) + +- (NSString *)mgl_stringOrNilIfEmpty +{ + return self.length ? self : nil; +} + +@end diff --git a/platform/ios/resources/api_mapbox_com-geotrust.der b/platform/ios/resources/api_mapbox_com-geotrust.der new file mode 100644 index 000000000..116144bc0 Binary files /dev/null and b/platform/ios/resources/api_mapbox_com-geotrust.der differ diff --git a/scripts/build-version.py b/scripts/build-version.py index 3fe789185..0110e6a2e 100755 --- a/scripts/build-version.py +++ b/scripts/build-version.py @@ -13,9 +13,9 @@ else: if sys.argv[2] == sys.argv[3]: tag = [0, 0, 0] else: - ver = re.sub("[^0-9.]", "", sys.argv[2]) + ver = re.sub("[^0-9.]", "", sys.argv[2]) tag = map(int, ver.split('.')) - rev = sys.argv[3][0:8] + rev = sys.argv[3][0:8] def mkdir_p(path): diff --git a/scripts/ios_travis/upload_screenshots.sh b/scripts/ios_travis/upload_screenshots.sh new file mode 100755 index 000000000..88a6427f7 --- /dev/null +++ b/scripts/ios_travis/upload_screenshots.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +set -e +set -o pipefail +set -u + +ls $KIF_SCREENSHOTS/ + +REPO_NAME=$(basename $TRAVIS_REPO_SLUG) + +aws s3 cp $KIF_SCREENSHOTS/ s3://mapbox/$REPO_NAME/ios/tests/$TRAVIS_JOB_NUMBER/ --acl public-read --recursive > /dev/null + +echo http://mapbox.s3.amazonaws.com/$REPO_NAME/ios/tests/$TRAVIS_JOB_NUMBER/index.html diff --git a/scripts/package_ios.sh b/scripts/package_ios.sh index 588ff6d94..07e568faa 100755 --- a/scripts/package_ios.sh +++ b/scripts/package_ios.sh @@ -6,7 +6,7 @@ set -u NAME=MapboxGL OUTPUT=build/ios/pkg -IOS_SDK_VERSION=8.1 +IOS_SDK_VERSION=`xcrun --sdk iphoneos --show-sdk-version` LIBUV_VERSION=0.10.28 function step { >&2 echo -e "\033[1m\033[36m* $@\033[0m"; } @@ -31,11 +31,12 @@ step "Creating build files..." export MASON_PLATFORM=ios export BUILDTYPE=${BUILDTYPE:-Release} export HOST=ios -make Xcode/mbgl +make Xcode/ios -step "Building iOS targets..." +step "Building iOS device targets..." xcodebuild -sdk iphoneos${IOS_SDK_VERSION} \ ARCHS="arm64 armv7 armv7s" \ + ONLY_ACTIVE_ARCH=NO \ -project ./build/ios/mbgl.xcodeproj \ -configuration ${BUILDTYPE} \ -target everything \ @@ -45,6 +46,7 @@ xcodebuild -sdk iphoneos${IOS_SDK_VERSION} \ step "Building iOS Simulator targets..." xcodebuild -sdk iphonesimulator${IOS_SDK_VERSION} \ ARCHS="x86_64 i386" \ + ONLY_ACTIVE_ARCH=NO \ -project ./build/ios/mbgl.xcodeproj \ -configuration ${BUILDTYPE} \ -target everything \ diff --git a/scripts/publish_ios.sh b/scripts/publish_ios.sh new file mode 100755 index 000000000..f65f3e560 --- /dev/null +++ b/scripts/publish_ios.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -e +set -o pipefail +set -u + +# +# iOS release tag format is `ios-vX.Y.Z`; `X.Y.Z` gets passed in +# +PUBLISH_VERSION="$1" + +# +# zip +# +cd build/ios/pkg/static +ZIP=mapbox-gl-ios-${PUBLISH_VERSION}.zip +rm -f ../${ZIP} +zip -r ../${ZIP} * +# +# upload +# +REPO_NAME=$(basename $TRAVIS_REPO_SLUG) +aws s3 cp ../${ZIP} s3://mapbox/$REPO_NAME/ios/builds/ --acl public-read > /dev/null +echo http://mapbox.s3.amazonaws.com/$REPO_NAME/ios/builds/${ZIP} diff --git a/scripts/test_ios.sh b/scripts/test_ios.sh new file mode 100755 index 000000000..77d4d90ad --- /dev/null +++ b/scripts/test_ios.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +set -e +set -o pipefail +set -u + +xcodebuild \ + -project ./test/ios/ios-tests.xcodeproj \ + -scheme 'Mapbox GL Tests' \ + -sdk iphonesimulator \ + -destination 'platform=iOS Simulator,name=iPhone 5s,OS=7.1' \ + -destination 'platform=iOS Simulator,name=iPhone 5s,OS=latest' \ + -destination 'platform=iOS Simulator,name=iPad 2,OS=7.1' \ + -destination 'platform=iOS Simulator,name=iPad 2,OS=latest' \ + test \ + | xcpretty diff --git a/scripts/travis_script.sh b/scripts/travis_script.sh index 45bda62c3..093b31273 100755 --- a/scripts/travis_script.sh +++ b/scripts/travis_script.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash +COMMIT_MESSAGE=$(git show -s --format=%B $1 | tr -d '\n') +PUBLISH_TAG=$(echo "$COMMIT_MESSAGE" | grep -oE '\[publish [a-z0-9\.\-]+\]' | grep -oE '[a-z0-9\.\-]+' | tail -n1) +PUBLISH_PLATFORM=$(echo "$PUBLISH_TAG" | awk -F '-v' '{ print $1 }') +PUBLISH_VERSION=$(echo "$PUBLISH_TAG" | awk -F '-v' '{ print $2 }') + set -e set -o pipefail @@ -34,18 +39,33 @@ elif [[ ${TRAVIS_OS_NAME} == "linux" ]]; then mapbox_time_finish fi -elif [[ ${TRAVIS_OS_NAME} == "osx" ]]; then +elif [[ ${TRAVIS_OS_NAME} == "osx" && ${MASON_PLATFORM} == "osx" ]]; then # # build OS X # - mapbox_time "build_osx_project" \ + mapbox_time "build_osx" \ make xosx -j$JOBS +elif [[ ${TRAVIS_OS_NAME} == "osx" && ${MASON_PLATFORM} == "ios" ]]; then # - # build iOS + # conditionally publish or test # - mapbox_time "build_ios_project_device_release" \ - make ios -j$JOBS - mapbox_time "build_ios_project_simulator_debug" \ - make isim -j$JOBS + if [[ -n "$PUBLISH_TAG" ]]; then + # + # build & package iOS + # + mapbox_time "package_ios" + make ipackage + # + # publish iOS build + # + mapbox_time "deploy_ios" + ./scripts/publish_ios.sh "$PUBLISH_VERSION" + else + # + # build & test iOS + # + mapbox_time "run_ios_tests" + make itest + fi fi diff --git a/src/mbgl/geometry/elements_buffer.cpp b/src/mbgl/geometry/elements_buffer.cpp index 79af1b7e3..3e2e2794d 100644 --- a/src/mbgl/geometry/elements_buffer.cpp +++ b/src/mbgl/geometry/elements_buffer.cpp @@ -14,8 +14,3 @@ void LineElementsBuffer::add(element_type a, element_type b) { elements[0] = a; elements[1] = b; } - -void PointElementsBuffer::add(element_type a) { - uint16_t *data = static_cast(addElement()); - data[0] = a; -} diff --git a/src/mbgl/geometry/elements_buffer.hpp b/src/mbgl/geometry/elements_buffer.hpp index 5c1b421d3..24753ebaf 100644 --- a/src/mbgl/geometry/elements_buffer.hpp +++ b/src/mbgl/geometry/elements_buffer.hpp @@ -44,16 +44,6 @@ public: void add(element_type a, element_type b); }; -class PointElementsBuffer : public Buffer< - 2, // bytes per point (1 unsigned short) - GL_ELEMENT_ARRAY_BUFFER -> { -public: - typedef uint16_t element_type; - - void add(element_type a); -}; - } #endif diff --git a/src/mbgl/map/annotation.cpp b/src/mbgl/map/annotation.cpp index fa26af785..b921c08f7 100644 --- a/src/mbgl/map/annotation.cpp +++ b/src/mbgl/map/annotation.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -29,7 +30,7 @@ private: private: const AnnotationType type = AnnotationType::Point; const AnnotationSegments geometry; - std::unordered_map, Tile::ID::Hash> tileFeatures; + std::unordered_map, TileID::Hash> tileFeatures; const LatLngBounds bounds; }; @@ -82,7 +83,7 @@ vec2 AnnotationManager::projectPoint(const LatLng& point) { return { x, y }; } -std::pair, AnnotationIDs> AnnotationManager::addPointAnnotations( +std::pair, AnnotationIDs> AnnotationManager::addPointAnnotations( const std::vector& points, const std::vector& symbols, const Map& map) { std::lock_guard lock(mtx); @@ -97,7 +98,7 @@ std::pair, AnnotationIDs> AnnotationManager::addPointAnnot std::vector annotationIDs; annotationIDs.reserve(points.size()); - std::vector affectedTiles; + std::vector affectedTiles; for (size_t i = 0; i < points.size(); ++i) { const uint32_t annotationID = nextID(); @@ -121,7 +122,7 @@ std::pair, AnnotationIDs> AnnotationManager::addPointAnnot for (int8_t z = maxZoom; z >= 0; z--) { affectedTiles.emplace_back(z, x, y); - Tile::ID tileID = affectedTiles.back(); + TileID tileID = affectedTiles.back(); // calculate tile coordinate const Coordinate coordinate(extent * (p.x * z2 - x), extent * (p.y * z2 - y)); @@ -180,10 +181,10 @@ std::pair, AnnotationIDs> AnnotationManager::addPointAnnot return std::make_pair(affectedTiles, annotationIDs); } -std::vector AnnotationManager::removeAnnotations(const AnnotationIDs& ids, const Map& map) { +std::vector AnnotationManager::removeAnnotations(const AnnotationIDs& ids, const Map& map) { std::lock_guard lock(mtx); - std::vector affectedTiles; + std::vector affectedTiles; std::vector z2s; uint8_t zoomCount = map.getMaxZoom() + 1; @@ -208,7 +209,7 @@ std::vector AnnotationManager::removeAnnotations(const AnnotationIDs& p = projectPoint(latLng); x = z2s[z] * p.x; y = z2s[z] * p.y; - Tile::ID tid(z, x, y); + TileID tid(z, x, y); // erase annotation from tile's list auto& tileAnnotations = tiles[tid].first; tileAnnotations.erase(annotationID); @@ -225,7 +226,7 @@ std::vector AnnotationManager::removeAnnotations(const AnnotationIDs& } } - // Tile::IDs for tiles that need refreshed. + // TileIDs for tiles that need refreshed. return affectedTiles; } @@ -239,13 +240,13 @@ std::vector AnnotationManager::getAnnotationsInBounds(const LatLngBoun const vec2 nePoint = projectPoint(queryBounds.ne); // tiles number y from top down - const Tile::ID nwTile(z, swPoint.x * z2, nePoint.y * z2); - const Tile::ID seTile(z, nePoint.x * z2, swPoint.y * z2); + const TileID nwTile(z, swPoint.x * z2, nePoint.y * z2); + const TileID seTile(z, nePoint.x * z2, swPoint.y * z2); std::vector matchingAnnotations; for (auto& tile : tiles) { - Tile::ID id = tile.first; + TileID id = tile.first; if (id.z == z) { if (id.x >= nwTile.x && id.x <= seTile.x && id.y >= nwTile.y && id.y <= seTile.y) { if (id.x > nwTile.x && id.x < seTile.x && id.y > nwTile.y && id.y < seTile.y) { @@ -292,7 +293,7 @@ LatLngBounds AnnotationManager::getBoundsForAnnotations(const AnnotationIDs& ids return bounds; } -const LiveTile* AnnotationManager::getTile(Tile::ID const& id) { +const LiveTile* AnnotationManager::getTile(const TileID& id) { std::lock_guard lock(mtx); const auto tile_it = tiles.find(id); diff --git a/include/mbgl/map/annotation.hpp b/src/mbgl/map/annotation.hpp similarity index 76% rename from include/mbgl/map/annotation.hpp rename to src/mbgl/map/annotation.hpp index efd91d908..f1596dbdf 100644 --- a/include/mbgl/map/annotation.hpp +++ b/src/mbgl/map/annotation.hpp @@ -1,7 +1,7 @@ #ifndef MBGL_MAP_ANNOTATIONS #define MBGL_MAP_ANNOTATIONS -#include +#include #include #include #include @@ -28,13 +28,13 @@ public: ~AnnotationManager(); void setDefaultPointAnnotationSymbol(const std::string& symbol); - std::pair, AnnotationIDs> addPointAnnotations( + std::pair, AnnotationIDs> addPointAnnotations( const std::vector&, const std::vector& symbols, const Map&); - std::vector removeAnnotations(const AnnotationIDs&, const Map&); + std::vector removeAnnotations(const AnnotationIDs&, const Map&); AnnotationIDs getAnnotationsInBounds(const LatLngBounds&, const Map&) const; LatLngBounds getBoundsForAnnotations(const AnnotationIDs&) const; - const LiveTile* getTile(Tile::ID const& id); + const LiveTile* getTile(const TileID& id); static const std::string layerID; @@ -46,7 +46,7 @@ private: mutable std::mutex mtx; std::string defaultPointAnnotationSymbol; std::unordered_map> annotations; - std::unordered_map, std::unique_ptr>, Tile::ID::Hash> tiles; + std::unordered_map, std::unique_ptr>, TileID::Hash> tiles; uint32_t nextID_ = 0; }; diff --git a/src/mbgl/map/live_tile_data.cpp b/src/mbgl/map/live_tile_data.cpp index dd83ed422..8b4f46deb 100644 --- a/src/mbgl/map/live_tile_data.cpp +++ b/src/mbgl/map/live_tile_data.cpp @@ -2,13 +2,13 @@ #include #include #include -#include +#include #include #include using namespace mbgl; -LiveTileData::LiveTileData(Tile::ID const& id_, +LiveTileData::LiveTileData(const TileID& id_, AnnotationManager& annotationManager_, float mapMaxZoom, util::ptr