Merge master @ 353e5661de
2
.gitmodules
vendored
@@ -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
|
||||
|
||||
10
.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=
|
||||
|
||||
130
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 ####################################################
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<NativeMapView *>(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<JNINativeMethod, 63> methods = {{ // Can remove the extra brace in C++14
|
||||
const std::vector<JNINativeMethod> methods = {
|
||||
{"nativeCreate", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)J",
|
||||
reinterpret_cast<void *>(&nativeCreate)},
|
||||
{"nativeDestroy", "(J)V", reinterpret_cast<void *>(&nativeDestroy)},
|
||||
@@ -951,7 +942,6 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
{"nativeStop", "(J)V", reinterpret_cast<void *>(&nativeStop)},
|
||||
{"nativePause", "(J)V", reinterpret_cast<void *>(&nativePause)},
|
||||
{"nativeResume", "(J)V", reinterpret_cast<void *>(&nativeResume)},
|
||||
{"nativeRun", "(J)V", reinterpret_cast<void *>(&nativeRun)},
|
||||
{"nativeUpdate", "(J)V", reinterpret_cast<void *>(&nativeUpdate)},
|
||||
{"nativeTerminate", "(J)V", reinterpret_cast<void *>(&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<void *>(&nativeLatLngForProjectedMeters)},
|
||||
{"nativePixelForLatLng", "(JLcom/mapbox/mapboxgl/geometry/LatLng;)Landroid/graphics/PointF;", reinterpret_cast<void *>(&nativePixelForLatLng)},
|
||||
{"nativeLatLngForPixel", "(JLandroid/graphics/PointF;)Lcom/mapbox/mapboxgl/geometry/LatLng;", reinterpret_cast<void *>(&nativeLatLngForPixel)},
|
||||
}};
|
||||
};
|
||||
|
||||
if (env->RegisterNatives(nativeMapViewClass, methods.data(), methods.size()) < 0) {
|
||||
env->ExceptionDescribe();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/still_image.hpp>
|
||||
#include <mbgl/util/image.hpp>
|
||||
#include <mbgl/util/std.hpp>
|
||||
#include <mbgl/util/io.hpp>
|
||||
@@ -7,7 +8,7 @@
|
||||
#include <mbgl/platform/default/headless_display.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#ifndef __clang__
|
||||
@@ -19,12 +20,13 @@
|
||||
|
||||
namespace po = boost::program_options;
|
||||
|
||||
#include <uv.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
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<std::string> 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<const StillImage> image(reinterpret_cast<const StillImage *>(as->data));
|
||||
uv_close(reinterpret_cast<uv_handle_t *>(as), [](uv_handle_t *handle) {
|
||||
delete reinterpret_cast<uv_async_t *>(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<const StillImage> image) {
|
||||
async->data = const_cast<StillImage *>(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();
|
||||
}
|
||||
|
||||
@@ -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)',
|
||||
],
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
'include_dirs': [
|
||||
'../include',
|
||||
'../src',
|
||||
],
|
||||
|
||||
'variables': {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
'include_dirs': [
|
||||
'../include',
|
||||
'../src',
|
||||
],
|
||||
|
||||
'variables': {
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
],
|
||||
'GCC_WARN_PEDANTIC': 'YES',
|
||||
'GCC_WARN_UNINITIALIZED_AUTOS': 'YES_AGGRESSIVE',
|
||||
'MACOSX_DEPLOYMENT_TARGET': '10.9',
|
||||
},
|
||||
}, {
|
||||
'cflags_cc': [
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
'include_dirs': [
|
||||
'../include',
|
||||
'../src',
|
||||
],
|
||||
|
||||
'variables': {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
'include_dirs': [
|
||||
'../include',
|
||||
'../src',
|
||||
],
|
||||
|
||||
'variables': {
|
||||
|
||||
@@ -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',
|
||||
],
|
||||
},
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
'<@(uv_static_libs)',
|
||||
],
|
||||
'ldflags': [
|
||||
'-framework Foundation',
|
||||
'-framework ImageIO',
|
||||
'-framework CoreServices',
|
||||
'-framework OpenGL',
|
||||
|
||||
19
gyp/project.gyp
Normal file
@@ -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',
|
||||
]
|
||||
}],
|
||||
],
|
||||
}
|
||||
@@ -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' ],
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/view.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
33
include/mbgl/ios/MGLMapView+IBAdditions.h
Normal file
@@ -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
|
||||
@@ -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://<user.style>`).
|
||||
* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
|
||||
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL;
|
||||
|
||||
/** Initialize a map view with a given frame, the default style, and an access token.
|
||||
/** 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://<user.style>`).
|
||||
* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
|
||||
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL;
|
||||
|
||||
- (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<MGLMapViewDelegate> delegate;
|
||||
@property(nonatomic, weak) IBOutlet id<MGLMapViewDelegate> 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://<user.style>`).
|
||||
*
|
||||
* 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://<user.style>`). */
|
||||
- (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;
|
||||
|
||||
|
||||
@@ -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 <NSURLSessionDelegate>
|
||||
|
||||
// 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/projection.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/uv.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
#include <mbgl/util/vec.hpp>
|
||||
|
||||
@@ -22,6 +21,8 @@
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
|
||||
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(std::unique_ptr<const StillImage>)>;
|
||||
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<uint32_t> getAnnotationsInBounds(const LatLngBounds&);
|
||||
LatLngBounds getBoundsForAnnotations(const std::vector<uint32_t>&);
|
||||
|
||||
// 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<Sprite> 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<Tile::ID>&);
|
||||
void updateAnnotationTiles(const std::vector<TileID>&);
|
||||
|
||||
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<uv::worker> workers;
|
||||
std::unique_ptr<Worker> workers;
|
||||
std::thread thread;
|
||||
std::unique_ptr<uv::async> asyncTerminate;
|
||||
std::unique_ptr<uv::async> asyncUpdate;
|
||||
@@ -248,12 +261,11 @@ private:
|
||||
|
||||
const std::unique_ptr<MapData> data;
|
||||
|
||||
std::set<util::ptr<StyleSource>> activeSources;
|
||||
|
||||
std::atomic<UpdateType> updated;
|
||||
|
||||
std::mutex mutexTask;
|
||||
std::queue<std::function<void()>> tasks;
|
||||
StillImageCallback callback;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
21
include/mbgl/map/still_image.hpp
Normal file
@@ -0,0 +1,21 @@
|
||||
#ifndef MBGL_MAP_STILL_IMAGE
|
||||
#define MBGL_MAP_STILL_IMAGE
|
||||
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class StillImage : util::noncopyable {
|
||||
public:
|
||||
uint16_t width = 0;
|
||||
uint16_t height = 0;
|
||||
using Pixel = uint32_t;
|
||||
std::unique_ptr<Pixel[]> pixels;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,90 +0,0 @@
|
||||
#ifndef MBGL_MAP_TILE
|
||||
#define MBGL_MAP_TILE
|
||||
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <bitset>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <forward_list>
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
|
||||
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<uint64_t>()(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<ID> children(int32_t z) const;
|
||||
bool isChildOf(const Tile::ID &id) const;
|
||||
operator std::string() const;
|
||||
};
|
||||
|
||||
static std::forward_list<Tile::ID> cover(int8_t z, const box& bounds);
|
||||
|
||||
public:
|
||||
explicit Tile(const ID& id);
|
||||
|
||||
public:
|
||||
const Tile::ID id;
|
||||
ClipID clip;
|
||||
mat4 matrix;
|
||||
util::ptr<TileData> data;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,8 +1,6 @@
|
||||
#ifndef MBGL_MAP_TRANSFORM_STATE
|
||||
#define MBGL_MAP_TRANSFORM_STATE
|
||||
|
||||
#include <mbgl/map/tile.hpp>
|
||||
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/vec.hpp>
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef MBGL_MAP_UPDATE
|
||||
#define MBGL_MAP_UPDATE
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
|
||||
#include <mbgl/util/chrono.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
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<StillImage> 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.
|
||||
|
||||
@@ -24,32 +24,47 @@ class HeadlessDisplay;
|
||||
|
||||
class HeadlessView : public View {
|
||||
public:
|
||||
HeadlessView();
|
||||
HeadlessView(std::shared_ptr<HeadlessDisplay> display);
|
||||
HeadlessView(uint16_t width = 256, uint16_t height = 256, float pixelRatio = 1);
|
||||
HeadlessView(std::shared_ptr<HeadlessDisplay> 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<uint32_t[]> readPixels();
|
||||
|
||||
void activate() override;
|
||||
void deactivate() override;
|
||||
void notify() override;
|
||||
void invalidate() override;
|
||||
void discard() override;
|
||||
std::unique_ptr<StillImage> readStillImage() override;
|
||||
|
||||
private:
|
||||
void createContext();
|
||||
void loadExtensions();
|
||||
void clearBuffers();
|
||||
bool isActive();
|
||||
|
||||
private:
|
||||
std::shared_ptr<HeadlessDisplay> display_;
|
||||
uint16_t width_;
|
||||
uint16_t height_;
|
||||
float pixelRatio_;
|
||||
std::shared_ptr<HeadlessDisplay> 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;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <mbgl/platform/event.hpp>
|
||||
|
||||
#include <mbgl/util/std.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
@@ -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> Observer);
|
||||
static std::unique_ptr<Observer> removeObserver();
|
||||
|
||||
private:
|
||||
template <typename T, size_t N>
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
#ifndef MBGL_PLATFORM_PLATFORM
|
||||
#define MBGL_PLATFORM_PLATFORM
|
||||
|
||||
#include <mbgl/util/uv.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE
|
||||
#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE
|
||||
|
||||
#include <mbgl/storage/file_cache.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
typedef struct uv_loop_s uv_loop_t;
|
||||
|
||||
namespace mapbox { namespace util { template<typename... Types> class variant; } }
|
||||
namespace mapbox { namespace sqlite { class Database; class Statement; } }
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace util { template <typename T> class AsyncQueue; }
|
||||
|
||||
class SQLiteCache : public FileCache {
|
||||
struct GetAction;
|
||||
struct PutAction;
|
||||
struct RefreshAction;
|
||||
struct StopAction;
|
||||
using Action = mapbox::util::variant<GetAction, PutAction, RefreshAction, StopAction>;
|
||||
using Queue = util::AsyncQueue<Action>;
|
||||
|
||||
public:
|
||||
SQLiteCache(const std::string &path = ":memory:");
|
||||
~SQLiteCache();
|
||||
|
||||
void get(const Resource &resource, std::function<void(std::unique_ptr<Response>)> callback);
|
||||
void put(const Resource &resource, std::shared_ptr<const Response> 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
|
||||
@@ -4,24 +4,18 @@
|
||||
#include <mbgl/storage/file_source.hpp>
|
||||
#include <mbgl/storage/file_cache.hpp>
|
||||
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <thread>
|
||||
|
||||
namespace mapbox { namespace util { template<typename... Types> class variant; } }
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace util { template <typename T> class AsyncQueue; }
|
||||
|
||||
class SharedRequestBase;
|
||||
namespace util {
|
||||
template <typename T> 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<Request *> &observers,
|
||||
std::shared_ptr<const Response> 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<AddRequestAction, RemoveRequestAction, ResultAction,
|
||||
StopAction, AbortAction>;
|
||||
using Queue = util::AsyncQueue<Action>;
|
||||
|
||||
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<Resource, SharedRequestBase *, Resource::Hash> pending;
|
||||
|
||||
uv_loop_t *loop = nullptr;
|
||||
FileCache *cache = nullptr;
|
||||
Queue *queue = nullptr;
|
||||
std::thread thread;
|
||||
const std::unique_ptr<util::Thread<Impl>> thread;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ public:
|
||||
virtual ~FileCache() = default;
|
||||
|
||||
enum class Hint : uint8_t { Full, Refresh, No };
|
||||
using Callback = std::function<void(std::unique_ptr<Response>)>;
|
||||
|
||||
virtual void get(const Resource &resource,
|
||||
std::function<void(std::unique_ptr<Response>)> callback) = 0;
|
||||
virtual void get(const Resource &resource, Callback callback) = 0;
|
||||
virtual void put(const Resource &resource, std::shared_ptr<const Response> response, Hint hint) = 0;
|
||||
};
|
||||
|
||||
|
||||
30
include/mbgl/storage/sqlite_cache.hpp
Normal file
@@ -0,0 +1,30 @@
|
||||
#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE
|
||||
#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE
|
||||
|
||||
#include <mbgl/storage/file_cache.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace util {
|
||||
template <typename T> 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<const Response> response, Hint hint) override;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
const std::unique_ptr<util::Thread<Impl>> thread;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -74,6 +74,11 @@ inline vec2<T> normal(const S1& a, const S2& b) {
|
||||
return { dx / c, dy / c };
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T perp(const T& a) {
|
||||
return T(-a.y, a.x);
|
||||
}
|
||||
|
||||
template <typename T, typename S1, typename S2>
|
||||
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 <typename S>
|
||||
inline S unit(const S& a) {
|
||||
return a * (1 / mag(a));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T clamp(T value, T min, T max) {
|
||||
return value < min ? min : (value > max ? max : value);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
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 <typename T>
|
||||
T smoothstep(T edge0, T edge1, T x) {
|
||||
T t = clamp((x - edge0) / (edge1 - edge0), T(0), T(1));
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
#ifndef MBGL_UTIL_UV_MESSENGER
|
||||
#define MBGL_UTIL_UV_MESSENGER
|
||||
|
||||
#include <uv.h>
|
||||
|
||||
#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
|
||||
@@ -17,7 +17,6 @@ std::string cwd();
|
||||
class rwlock;
|
||||
class loop;
|
||||
class async;
|
||||
class worker;
|
||||
class mutex;
|
||||
class cond;
|
||||
|
||||
|
||||
@@ -61,7 +61,13 @@ struct vec2 {
|
||||
template <typename O>
|
||||
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
|
||||
operator-(const O &o) const {
|
||||
return {x - o.x, y - o.y};
|
||||
return vec2<T>(x - o.x, y - o.y);
|
||||
}
|
||||
|
||||
template <typename O>
|
||||
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
|
||||
operator+(const O &o) const {
|
||||
return vec2<T>(x + o.x, y + o.y);
|
||||
}
|
||||
|
||||
template <typename M>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#import "MBXAppDelegate.h"
|
||||
#import "MBXViewController.h"
|
||||
#import <mbgl/ios/MGLMapboxEvents.h>
|
||||
|
||||
@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
|
||||
|
||||
@@ -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 () <UIActionSheetDelegate, MGLMapViewDelegate>
|
||||
|
||||
@@ -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
|
||||
|
||||
BIN
ios/app/img/TrackingHeadingMask.png
Normal file
|
After Width: | Height: | Size: 250 B |
BIN
ios/app/img/TrackingHeadingMask@2x.png
Normal file
|
After Width: | Height: | Size: 467 B |
BIN
ios/app/img/TrackingHeadingMask@3x.png
Normal file
|
After Width: | Height: | Size: 672 B |
BIN
ios/app/img/TrackingLocationMask.png
Normal file
|
After Width: | Height: | Size: 407 B |
BIN
ios/app/img/TrackingLocationMask@2x.png
Normal file
|
After Width: | Height: | Size: 680 B |
BIN
ios/app/img/TrackingLocationMask@3x.png
Normal file
|
After Width: | Height: | Size: 903 B |
BIN
ios/app/img/TrackingLocationOffMask.png
Normal file
|
After Width: | Height: | Size: 493 B |
BIN
ios/app/img/TrackingLocationOffMask@2x.png
Normal file
|
After Width: | Height: | Size: 973 B |
BIN
ios/app/img/TrackingLocationOffMask@3x.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 521 B |
@@ -6,7 +6,7 @@
|
||||
#include <mbgl/platform/default/settings_json.hpp>
|
||||
#include <mbgl/platform/default/glfw_view.hpp>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
|
||||
#include <signal.h>
|
||||
#include <getopt.h>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <mbgl/platform/darwin/Reachability.h>
|
||||
#include <mbgl/platform/default/glfw_view.hpp>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/network_status.hpp>
|
||||
|
||||
#include <mbgl/util/geo.hpp>
|
||||
|
||||
@@ -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'
|
||||
},
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#include <mbgl/storage/default/http_request.hpp>
|
||||
#include <mbgl/storage/default/http_context.hpp>
|
||||
#include <mbgl/storage/http_request.hpp>
|
||||
#include <mbgl/storage/http_context.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
#include <mbgl/util/uv.hpp>
|
||||
|
||||
@@ -47,7 +47,7 @@ class HTTPNSURLContext;
|
||||
|
||||
class HTTPRequestImpl {
|
||||
public:
|
||||
HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr<Response> response);
|
||||
HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::shared_ptr<const Response> response);
|
||||
~HTTPRequestImpl();
|
||||
|
||||
void cancel();
|
||||
@@ -66,7 +66,7 @@ private:
|
||||
HTTPRequest *request = nullptr;
|
||||
NSURLSessionDataTask *task = nullptr;
|
||||
std::unique_ptr<Response> response;
|
||||
std::unique_ptr<Response> existingResponse;
|
||||
const std::shared_ptr<const Response> 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<Response> existingResponse_)
|
||||
std::shared_ptr<const Response> 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> response) {
|
||||
void HTTPRequest::start(uv_loop_t *loop, std::shared_ptr<const Response> response) {
|
||||
MBGL_VERIFY_THREAD(tid);
|
||||
|
||||
assert(!ptr);
|
||||
ptr = new HTTPRequestImpl(this, loop, std::move(response));
|
||||
ptr = new HTTPRequestImpl(this, loop, response);
|
||||
}
|
||||
|
||||
void HTTPRequest::retryImmediately() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#include <mbgl/storage/default/asset_request.hpp>
|
||||
#include <mbgl/storage/asset_request.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
#include <mbgl/util/std.hpp>
|
||||
#include <mbgl/util/util.hpp>
|
||||
@@ -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> response) {
|
||||
void AssetRequest::start(uv_loop_t *loop, std::shared_ptr<const Response> response) {
|
||||
MBGL_VERIFY_THREAD(tid);
|
||||
|
||||
// We're ignoring the existing response if any.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include <mbgl/storage/default/asset_request.hpp>
|
||||
#include <mbgl/storage/default/thread_context.hpp>
|
||||
#include <mbgl/storage/asset_request.hpp>
|
||||
#include <mbgl/storage/thread_context.hpp>
|
||||
#include <mbgl/android/jni.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
@@ -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> response) {
|
||||
void AssetRequest::start(uv_loop_t *loop, std::shared_ptr<const Response> response) {
|
||||
MBGL_VERIFY_THREAD(tid);
|
||||
|
||||
// We're ignoring the existing response if any.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
|
||||
#include <mbgl/platform/default/headless_view.hpp>
|
||||
#include <mbgl/platform/default/headless_display.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
|
||||
#include <mbgl/map/still_image.hpp>
|
||||
|
||||
#include <mbgl/util/std.hpp>
|
||||
|
||||
#include <stdexcept>
|
||||
@@ -36,17 +39,17 @@ CGLProc CGLGetProcAddress(const char *proc) {
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
|
||||
HeadlessView::HeadlessView()
|
||||
: display_(std::make_shared<HeadlessDisplay>()) {
|
||||
createContext();
|
||||
loadExtensions();
|
||||
HeadlessView::HeadlessView(uint16_t width, uint16_t height, float pixelRatio)
|
||||
: display(std::make_shared<HeadlessDisplay>()) {
|
||||
resize(width, height, pixelRatio);
|
||||
}
|
||||
|
||||
HeadlessView::HeadlessView(std::shared_ptr<HeadlessDisplay> display)
|
||||
: display_(display) {
|
||||
createContext();
|
||||
loadExtensions();
|
||||
HeadlessView::HeadlessView(std::shared_ptr<HeadlessDisplay> 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<const char *>(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<std::mutex> 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<std::mutex> 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<uint32_t[]> HeadlessView::readPixels() {
|
||||
const unsigned int w = width_ * pixelRatio_;
|
||||
const unsigned int h = height_ * pixelRatio_;
|
||||
std::unique_ptr<StillImage> HeadlessView::readStillImage() {
|
||||
assert(isActive());
|
||||
|
||||
auto pixels = util::make_unique<uint32_t[]>(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<StillImage>();
|
||||
image->width = w;
|
||||
image->height = h;
|
||||
image->pixels = util::make_unique<uint32_t[]>(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<char[]>(stride);
|
||||
char *rgba = reinterpret_cast<char *>(pixels.get());
|
||||
for (int i = 0, j = height_ - 1; i < j; i++, j--) {
|
||||
char *rgba = reinterpret_cast<char *>(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) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include <mbgl/storage/default/http_request.hpp>
|
||||
#include <mbgl/storage/default/http_context.hpp>
|
||||
#include <mbgl/storage/http_request.hpp>
|
||||
#include <mbgl/storage/http_context.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
#include <mbgl/util/chrono.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
@@ -95,7 +95,7 @@ class HTTPRequestImpl {
|
||||
MBGL_STORE_THREAD(tid)
|
||||
|
||||
public:
|
||||
HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr<Response> response);
|
||||
HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::shared_ptr<const Response> response);
|
||||
~HTTPRequestImpl();
|
||||
|
||||
void handleResult(CURLcode code);
|
||||
@@ -123,7 +123,7 @@ private:
|
||||
std::unique_ptr<Response> response;
|
||||
|
||||
// In case of revalidation requests, this will store the old response.
|
||||
std::unique_ptr<Response> existingResponse;
|
||||
const std::shared_ptr<const Response> 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> response_)
|
||||
HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, std::shared_ptr<const Response> 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> response) {
|
||||
void HTTPRequest::start(uv_loop_t *loop, std::shared_ptr<const Response> response) {
|
||||
MBGL_VERIFY_THREAD(tid);
|
||||
|
||||
assert(!ptr);
|
||||
ptr = new HTTPRequestImpl(this, loop, std::move(response));
|
||||
ptr = new HTTPRequestImpl(this, loop, response);
|
||||
}
|
||||
|
||||
void HTTPRequest::retryImmediately() {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/default/request.hpp>
|
||||
#include "sqlite_cache_impl.hpp"
|
||||
#include <mbgl/storage/request.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
|
||||
#include <mbgl/util/util.hpp>
|
||||
#include <mbgl/util/async_queue.hpp>
|
||||
#include <mbgl/util/variant.hpp>
|
||||
#include <mbgl/util/compression.hpp>
|
||||
#include <mbgl/util/io.hpp>
|
||||
#include <mbgl/util/thread.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
|
||||
#include "sqlite3.hpp"
|
||||
|
||||
#include <uv.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <sqlite3.h>
|
||||
|
||||
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<void(std::unique_ptr<Response>)> callback;
|
||||
};
|
||||
|
||||
struct SQLiteCache::PutAction {
|
||||
const Resource resource;
|
||||
const std::shared_ptr<const Response> response;
|
||||
};
|
||||
|
||||
struct SQLiteCache::RefreshAction {
|
||||
const Resource resource;
|
||||
const int64_t expires;
|
||||
};
|
||||
|
||||
struct SQLiteCache::StopAction {
|
||||
};
|
||||
|
||||
struct SQLiteCache::ActionDispatcher {
|
||||
SQLiteCache &cache;
|
||||
template <typename T> 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<util::Thread<Impl>>("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<void(std::unique_ptr<Response>)> 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<const Response> 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<Database>(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<Database>(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<Response> 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<Statement>(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>();
|
||||
response->status = Response::Status(getStmt->get<int>(0));
|
||||
response->modified = getStmt->get<int64_t>(1);
|
||||
response->etag = getStmt->get<std::string>(2);
|
||||
response->expires = getStmt->get<int64_t>(3);
|
||||
response->data = getStmt->get<std::string>(4);
|
||||
if (getStmt->get<int>(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<Statement>(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>();
|
||||
response->status = Response::Status(getStmt->get<int>(0));
|
||||
response->modified = getStmt->get<int64_t>(1);
|
||||
response->etag = getStmt->get<std::string>(2);
|
||||
response->expires = getStmt->get<int64_t>(3);
|
||||
response->data = getStmt->get<std::string>(4);
|
||||
if (getStmt->get<int>(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<const Response> 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<Statement>(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<const Response> response) {
|
||||
try {
|
||||
if (!db) {
|
||||
createDatabase();
|
||||
}
|
||||
|
||||
if (!refreshStmt) {
|
||||
refreshStmt = util::make_unique<Statement>( // 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<Statement>(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<Statement>( // 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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
39
platform/default/sqlite_cache_impl.hpp
Normal file
@@ -0,0 +1,39 @@
|
||||
#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE_IMPL
|
||||
#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE_IMPL
|
||||
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
|
||||
namespace mapbox {
|
||||
namespace sqlite {
|
||||
class Database;
|
||||
class Statement;
|
||||
}
|
||||
}
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class SQLiteCache::Impl {
|
||||
public:
|
||||
Impl(const std::string &path = ":memory:");
|
||||
~Impl();
|
||||
|
||||
std::unique_ptr<Response> get(const Resource&);
|
||||
void put(const Resource& resource, std::shared_ptr<const Response> 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
|
||||
@@ -1,4 +1,5 @@
|
||||
#import "MGLMapView.h"
|
||||
#import "MGLMapView+IBAdditions.h"
|
||||
|
||||
#import <mbgl/platform/log.hpp>
|
||||
#import <mbgl/platform/gl.hpp>
|
||||
@@ -10,11 +11,13 @@
|
||||
#include <mbgl/platform/platform.hpp>
|
||||
#include <mbgl/platform/darwin/reachability.h>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/default/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/network_status.hpp>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
|
||||
#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 () <UIGestureRecognizerDelegate, GLKViewDelegate, CLLocationManagerDelegate>
|
||||
|
||||
@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<uint32_t> annotationsNearbyLastTap;
|
||||
@property (nonatomic, weak) id <MGLAnnotation> 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
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#import <CoreTelephony/CTCarrier.h>
|
||||
|
||||
#import "MGLMetricsLocationManager.h"
|
||||
#import "NSProcessInfo+MGLAdditions.h"
|
||||
|
||||
#include <sys/sysctl.h>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
7
platform/ios/NSProcessInfo+MGLAdditions.h
Normal file
@@ -0,0 +1,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface NSProcessInfo (MGLAdditions)
|
||||
|
||||
- (BOOL)mgl_isInterfaceBuilderDesignablesAgent;
|
||||
|
||||
@end
|
||||
10
platform/ios/NSProcessInfo+MGLAdditions.m
Normal file
@@ -0,0 +1,10 @@
|
||||
#import "NSProcessInfo+MGLAdditions.h"
|
||||
|
||||
@implementation NSProcessInfo (MGLAdditions)
|
||||
|
||||
- (BOOL)mgl_isInterfaceBuilderDesignablesAgent
|
||||
{
|
||||
return [self.processName isEqualToString:@"IBDesignablesAgentCocoaTouch"];
|
||||
}
|
||||
|
||||
@end
|
||||
8
platform/ios/NSString+MGLAdditions.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface NSString (MGLAdditions)
|
||||
|
||||
/** Returns the receiver if non-empty or nil if empty. */
|
||||
- (NSString *)mgl_stringOrNilIfEmpty;
|
||||
|
||||
@end
|
||||
10
platform/ios/NSString+MGLAdditions.m
Normal file
@@ -0,0 +1,10 @@
|
||||
#import "NSString+MGLAdditions.h"
|
||||
|
||||
@implementation NSString (MGLAdditions)
|
||||
|
||||
- (NSString *)mgl_stringOrNilIfEmpty
|
||||
{
|
||||
return self.length ? self : nil;
|
||||
}
|
||||
|
||||
@end
|
||||
BIN
platform/ios/resources/api_mapbox_com-geotrust.der
Normal file
@@ -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):
|
||||
|
||||
13
scripts/ios_travis/upload_screenshots.sh
Executable file
@@ -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
|
||||
@@ -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 \
|
||||
|
||||
24
scripts/publish_ios.sh
Executable file
@@ -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}
|
||||
16
scripts/test_ios.sh
Executable file
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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<element_type *>(addElement());
|
||||
data[0] = a;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <mbgl/map/annotation.hpp>
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/tile_id.hpp>
|
||||
#include <mbgl/map/live_tile.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
#include <mbgl/util/std.hpp>
|
||||
@@ -29,7 +30,7 @@ private:
|
||||
private:
|
||||
const AnnotationType type = AnnotationType::Point;
|
||||
const AnnotationSegments geometry;
|
||||
std::unordered_map<Tile::ID, std::weak_ptr<const LiveTileFeature>, Tile::ID::Hash> tileFeatures;
|
||||
std::unordered_map<TileID, std::weak_ptr<const LiveTileFeature>, TileID::Hash> tileFeatures;
|
||||
const LatLngBounds bounds;
|
||||
};
|
||||
|
||||
@@ -82,7 +83,7 @@ vec2<double> AnnotationManager::projectPoint(const LatLng& point) {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
std::pair<std::vector<Tile::ID>, AnnotationIDs> AnnotationManager::addPointAnnotations(
|
||||
std::pair<std::vector<TileID>, AnnotationIDs> AnnotationManager::addPointAnnotations(
|
||||
const std::vector<LatLng>& points, const std::vector<std::string>& symbols, const Map& map) {
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
|
||||
@@ -97,7 +98,7 @@ std::pair<std::vector<Tile::ID>, AnnotationIDs> AnnotationManager::addPointAnnot
|
||||
std::vector<uint32_t> annotationIDs;
|
||||
annotationIDs.reserve(points.size());
|
||||
|
||||
std::vector<Tile::ID> affectedTiles;
|
||||
std::vector<TileID> affectedTiles;
|
||||
|
||||
for (size_t i = 0; i < points.size(); ++i) {
|
||||
const uint32_t annotationID = nextID();
|
||||
@@ -121,7 +122,7 @@ std::pair<std::vector<Tile::ID>, 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<std::vector<Tile::ID>, AnnotationIDs> AnnotationManager::addPointAnnot
|
||||
return std::make_pair(affectedTiles, annotationIDs);
|
||||
}
|
||||
|
||||
std::vector<Tile::ID> AnnotationManager::removeAnnotations(const AnnotationIDs& ids, const Map& map) {
|
||||
std::vector<TileID> AnnotationManager::removeAnnotations(const AnnotationIDs& ids, const Map& map) {
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
|
||||
std::vector<Tile::ID> affectedTiles;
|
||||
std::vector<TileID> affectedTiles;
|
||||
|
||||
std::vector<uint32_t> z2s;
|
||||
uint8_t zoomCount = map.getMaxZoom() + 1;
|
||||
@@ -208,7 +209,7 @@ std::vector<Tile::ID> 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<Tile::ID> 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<uint32_t> AnnotationManager::getAnnotationsInBounds(const LatLngBoun
|
||||
const vec2<double> 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<uint32_t> 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<std::mutex> lock(mtx);
|
||||
|
||||
const auto tile_it = tiles.find(id);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#ifndef MBGL_MAP_ANNOTATIONS
|
||||
#define MBGL_MAP_ANNOTATIONS
|
||||
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/map/tile_id.hpp>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/std.hpp>
|
||||
@@ -28,13 +28,13 @@ public:
|
||||
~AnnotationManager();
|
||||
|
||||
void setDefaultPointAnnotationSymbol(const std::string& symbol);
|
||||
std::pair<std::vector<Tile::ID>, AnnotationIDs> addPointAnnotations(
|
||||
std::pair<std::vector<TileID>, AnnotationIDs> addPointAnnotations(
|
||||
const std::vector<LatLng>&, const std::vector<std::string>& symbols, const Map&);
|
||||
std::vector<Tile::ID> removeAnnotations(const AnnotationIDs&, const Map&);
|
||||
std::vector<TileID> 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<uint32_t, std::unique_ptr<Annotation>> annotations;
|
||||
std::unordered_map<Tile::ID, std::pair<std::unordered_set<uint32_t>, std::unique_ptr<LiveTile>>, Tile::ID::Hash> tiles;
|
||||
std::unordered_map<TileID, std::pair<std::unordered_set<uint32_t>, std::unique_ptr<LiveTile>>, TileID::Hash> tiles;
|
||||
uint32_t nextID_ = 0;
|
||||
};
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
#include <mbgl/map/live_tile_data.hpp>
|
||||
#include <mbgl/map/live_tile.hpp>
|
||||
#include <mbgl/map/tile_parser.hpp>
|
||||
#include <mbgl/style/style_source.hpp>
|
||||
#include <mbgl/map/source.hpp>
|
||||
#include <mbgl/map/vector_tile.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
LiveTileData::LiveTileData(Tile::ID const& id_,
|
||||
LiveTileData::LiveTileData(const TileID& id_,
|
||||
AnnotationManager& annotationManager_,
|
||||
float mapMaxZoom,
|
||||
util::ptr<Style> style_,
|
||||
@@ -31,34 +31,33 @@ void LiveTileData::parse() {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!style) {
|
||||
throw std::runtime_error("style isn't present in LiveTileData object anymore");
|
||||
}
|
||||
const LiveTile* tile = annotationManager.getTile(id);
|
||||
|
||||
if (source.type == SourceType::Annotations) {
|
||||
const LiveTile* tile = annotationManager.getTile(id);
|
||||
|
||||
if (tile) {
|
||||
// Parsing creates state that is encapsulated in TileParser. While parsing,
|
||||
// the TileParser object writes results into this objects. All other state
|
||||
// is going to be discarded afterwards.
|
||||
TileParser parser(*tile, *this, style, glyphAtlas, glyphStore, spriteAtlas, sprite);
|
||||
|
||||
// Clear the style so that we don't have a cycle in the shared_ptr references.
|
||||
style.reset();
|
||||
|
||||
parser.parse();
|
||||
} else {
|
||||
state = State::obsolete;
|
||||
if (tile) {
|
||||
try {
|
||||
if (!style) {
|
||||
throw std::runtime_error("style isn't present in LiveTileData object anymore");
|
||||
}
|
||||
} else {
|
||||
throw std::runtime_error("unknown live tile source type");
|
||||
|
||||
// Parsing creates state that is encapsulated in TileParser. While parsing,
|
||||
// the TileParser object writes results into this objects. All other state
|
||||
// is going to be discarded afterwards.
|
||||
TileParser parser(*tile, *this, style, glyphAtlas, glyphStore, spriteAtlas, sprite);
|
||||
|
||||
// Clear the style so that we don't have a cycle in the shared_ptr references.
|
||||
style.reset();
|
||||
|
||||
parser.parse();
|
||||
} catch (const std::exception& ex) {
|
||||
Log::Error(Event::ParseTile, "Live-parsing [%d/%d/%d] failed: %s", id.z, id.x, id.y, ex.what());
|
||||
state = State::obsolete;
|
||||
return;
|
||||
}
|
||||
} catch (const std::exception& ex) {
|
||||
Log::Error(Event::ParseTile, "Live-parsing [%d/%d/%d] failed: %s", id.z, id.x, id.y, ex.what());
|
||||
} else {
|
||||
// Clear the style so that we don't have a cycle in the shared_ptr references.
|
||||
style.reset();
|
||||
|
||||
state = State::obsolete;
|
||||
return;
|
||||
}
|
||||
|
||||
if (state != State::obsolete) {
|
||||
|
||||
@@ -9,7 +9,7 @@ class AnnotationManager;
|
||||
|
||||
class LiveTileData : public VectorTileData {
|
||||
public:
|
||||
LiveTileData(Tile::ID const&,
|
||||
LiveTileData(const TileID&,
|
||||
AnnotationManager&,
|
||||
float mapMaxZoom,
|
||||
util::ptr<Style>,
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
#include <mbgl/map/environment.hpp>
|
||||
#include <mbgl/map/view.hpp>
|
||||
#include <mbgl/map/map_data.hpp>
|
||||
#include <mbgl/map/still_image.hpp>
|
||||
#include <mbgl/platform/platform.hpp>
|
||||
#include <mbgl/map/source.hpp>
|
||||
#include <mbgl/renderer/painter.hpp>
|
||||
#include <mbgl/map/annotation.hpp>
|
||||
#include <mbgl/map/sprite.hpp>
|
||||
#include <mbgl/util/math.hpp>
|
||||
#include <mbgl/util/clip_ids.hpp>
|
||||
#include <mbgl/util/clip_id.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
#include <mbgl/util/constants.hpp>
|
||||
#include <mbgl/util/uv_detail.hpp>
|
||||
@@ -27,6 +28,7 @@
|
||||
#include <mbgl/util/uv.hpp>
|
||||
#include <mbgl/util/mapbox.hpp>
|
||||
#include <mbgl/util/exception.hpp>
|
||||
#include <mbgl/util/worker.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
@@ -78,7 +80,7 @@ Map::Map(View& view_, FileSource& fileSource_)
|
||||
}
|
||||
|
||||
Map::~Map() {
|
||||
if (mode == Mode::Continuous) {
|
||||
if (mode != Mode::None) {
|
||||
stop();
|
||||
}
|
||||
|
||||
@@ -90,7 +92,6 @@ Map::~Map() {
|
||||
"MapandMain");
|
||||
|
||||
// Explicitly reset all pointers.
|
||||
activeSources.clear();
|
||||
sprite.reset();
|
||||
glyphStore.reset();
|
||||
style.reset();
|
||||
@@ -106,18 +107,18 @@ Map::~Map() {
|
||||
env->performCleanup();
|
||||
}
|
||||
|
||||
uv::worker &Map::getWorker() {
|
||||
Worker& Map::getWorker() {
|
||||
assert(workers);
|
||||
return *workers;
|
||||
}
|
||||
|
||||
void Map::start(bool startPaused) {
|
||||
void Map::start(bool startPaused, Mode renderMode) {
|
||||
assert(Environment::currentlyOn(ThreadType::Main));
|
||||
assert(mode == Mode::None);
|
||||
|
||||
// When starting map rendering in another thread, we perform async/continuously
|
||||
// updated rendering. Only in these cases, we attach the async handlers.
|
||||
mode = Mode::Continuous;
|
||||
mode = renderMode;
|
||||
|
||||
// Reset the flag.
|
||||
isStopped = false;
|
||||
@@ -129,11 +130,6 @@ void Map::start(bool startPaused) {
|
||||
// Remove all of these to make sure they are destructed in the correct thread.
|
||||
style.reset();
|
||||
|
||||
// Since we don't have a stylesheet anymore, this will disable all Sources and cancel
|
||||
// their associated requests.
|
||||
updateSources();
|
||||
assert(activeSources.empty());
|
||||
|
||||
// It's now safe to destroy/join the workers since there won't be any more callbacks that
|
||||
// could dispatch to the worker pool.
|
||||
workers.reset();
|
||||
@@ -148,6 +144,10 @@ void Map::start(bool startPaused) {
|
||||
});
|
||||
|
||||
asyncUpdate = util::make_unique<uv::async>(env->loop, [this] {
|
||||
// Whenever we call triggerUpdate(), we ref() the asyncUpdate handle to make sure that all
|
||||
// of the calls actually get triggered.
|
||||
asyncUpdate->unref();
|
||||
|
||||
update();
|
||||
});
|
||||
|
||||
@@ -189,15 +189,15 @@ void Map::start(bool startPaused) {
|
||||
triggerUpdate();
|
||||
}
|
||||
|
||||
void Map::stop(std::function<void ()> callback) {
|
||||
void Map::stop(std::function<void ()> cb) {
|
||||
assert(Environment::currentlyOn(ThreadType::Main));
|
||||
assert(mode == Mode::Continuous);
|
||||
assert(mode != Mode::None);
|
||||
|
||||
asyncTerminate->send();
|
||||
|
||||
resume();
|
||||
|
||||
if (callback) {
|
||||
if (cb) {
|
||||
// Wait until the render thread stopped. We are using this construct instead of plainly
|
||||
// relying on the thread_join because the system might need to run things in the current
|
||||
// thread that is required for the render thread to terminate correctly. This is for example
|
||||
@@ -205,7 +205,7 @@ void Map::stop(std::function<void ()> callback) {
|
||||
// thread (== main thread) is blocked. The callback function should use an efficient waiting
|
||||
// function to avoid a busy waiting loop.
|
||||
while (!isStopped) {
|
||||
callback();
|
||||
cb();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,7 +236,7 @@ void Map::pause(bool waitForPause) {
|
||||
|
||||
void Map::resume() {
|
||||
assert(Environment::currentlyOn(ThreadType::Main));
|
||||
assert(mode == Mode::Continuous);
|
||||
assert(mode != Mode::None);
|
||||
|
||||
mutexRun.lock();
|
||||
pausing = false;
|
||||
@@ -244,21 +244,28 @@ void Map::resume() {
|
||||
mutexRun.unlock();
|
||||
}
|
||||
|
||||
void Map::run() {
|
||||
ThreadType threadType = ThreadType::Map;
|
||||
std::string threadName("Map");
|
||||
void Map::renderStill(StillImageCallback fn) {
|
||||
assert(Environment::currentlyOn(ThreadType::Main));
|
||||
|
||||
if (mode == Mode::None) {
|
||||
mode = Mode::Static;
|
||||
|
||||
// FIXME: Threads should have only one purpose. When running on Static mode,
|
||||
// we are currently not spawning a Map thread and running the code on the
|
||||
// Main thread, thus, the Main thread in this case is both Main and Map thread.
|
||||
threadType = static_cast<ThreadType>(static_cast<uint8_t>(threadType) | static_cast<uint8_t>(ThreadType::Main));
|
||||
threadName += "andMain";
|
||||
if (mode != Mode::Still) {
|
||||
throw util::Exception("Map is not in still image render mode");
|
||||
}
|
||||
|
||||
EnvironmentScope mapScope(*env, threadType, threadName);
|
||||
if (callback) {
|
||||
throw util::Exception("Map is currently rendering an image");
|
||||
}
|
||||
|
||||
assert(mode == Mode::Still);
|
||||
|
||||
callback = std::move(fn);
|
||||
|
||||
triggerUpdate(Update::RenderStill);
|
||||
}
|
||||
|
||||
void Map::run() {
|
||||
EnvironmentScope mapScope(*env, ThreadType::Map, "Map");
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
assert(mode != Mode::None);
|
||||
|
||||
if (mode == Mode::Continuous) {
|
||||
checkForPause();
|
||||
@@ -266,37 +273,57 @@ void Map::run() {
|
||||
|
||||
auto styleInfo = data->getStyleInfo();
|
||||
|
||||
if (mode == Mode::Static && !style && (styleInfo.url.empty() && styleInfo.json.empty())) {
|
||||
throw util::Exception("Style is not set");
|
||||
}
|
||||
|
||||
view.activate();
|
||||
view.discard();
|
||||
|
||||
workers = util::make_unique<uv::worker>(env->loop, 4, "Tile Worker");
|
||||
workers = util::make_unique<Worker>(env->loop, 4);
|
||||
|
||||
setup();
|
||||
prepare();
|
||||
|
||||
if (mode == Mode::Continuous) {
|
||||
terminating = false;
|
||||
while(!terminating) {
|
||||
while (!terminating) {
|
||||
uv_run(env->loop, UV_RUN_DEFAULT);
|
||||
checkForPause();
|
||||
}
|
||||
} else if (mode == Mode::Still) {
|
||||
terminating = false;
|
||||
while (!terminating) {
|
||||
uv_run(env->loop, UV_RUN_DEFAULT);
|
||||
|
||||
// After the loop terminated, these async handles may have been deleted if the terminate()
|
||||
// callback was fired. In this case, we are exiting the loop.
|
||||
if (asyncTerminate && asyncUpdate) {
|
||||
// Otherwise, loop termination means that we have acquired and parsed all resources
|
||||
// required for this map image and we can now proceed to rendering.
|
||||
render();
|
||||
auto image = view.readStillImage();
|
||||
|
||||
// We are moving the callback out of the way and empty it in case the callback function
|
||||
// starts the next map image render.
|
||||
assert(callback);
|
||||
StillImageCallback cb;
|
||||
std::swap(cb, callback);
|
||||
|
||||
// Now we can finally invoke the callback function with the map image we rendered.
|
||||
cb(std::move(image));
|
||||
|
||||
// To prepare for the next event loop run, we have to make sure the async handles keep
|
||||
// the loop alive.
|
||||
asyncTerminate->ref();
|
||||
asyncUpdate->ref();
|
||||
asyncInvoke->ref();
|
||||
asyncRender->ref();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
uv_run(env->loop, UV_RUN_DEFAULT);
|
||||
abort();
|
||||
}
|
||||
|
||||
// Run the event loop once more to make sure our async delete handlers are called.
|
||||
uv_run(env->loop, UV_RUN_ONCE);
|
||||
|
||||
// If the map rendering wasn't started asynchronously, we perform one render
|
||||
// *after* all events have been processed.
|
||||
if (mode == Mode::Static) {
|
||||
render();
|
||||
mode = Mode::None;
|
||||
}
|
||||
|
||||
view.deactivate();
|
||||
}
|
||||
|
||||
@@ -314,14 +341,14 @@ void Map::renderSync() {
|
||||
void Map::triggerUpdate(const Update u) {
|
||||
updated |= static_cast<UpdateType>(u);
|
||||
|
||||
if (mode == Mode::Static) {
|
||||
prepare();
|
||||
} else if (asyncUpdate) {
|
||||
if (asyncUpdate) {
|
||||
asyncUpdate->ref();
|
||||
asyncUpdate->send();
|
||||
}
|
||||
}
|
||||
|
||||
void Map::triggerRender() {
|
||||
assert(mode == Mode::Continuous);
|
||||
assert(asyncRender);
|
||||
asyncRender->send();
|
||||
}
|
||||
@@ -333,12 +360,8 @@ void Map::invokeTask(std::function<void()>&& fn) {
|
||||
tasks.emplace(::std::forward<std::function<void()>>(fn));
|
||||
}
|
||||
|
||||
// TODO: Once we have aligned static and continuous rendering, this should always dispatch
|
||||
// to the async queue.
|
||||
if (asyncInvoke) {
|
||||
asyncInvoke->send();
|
||||
} else {
|
||||
processTasks();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,6 +419,10 @@ void Map::setup() {
|
||||
painter->setup();
|
||||
}
|
||||
|
||||
std::string Map::getStyleURL() const {
|
||||
return data->getStyleInfo().url;
|
||||
}
|
||||
|
||||
void Map::setStyleURL(const std::string &url) {
|
||||
assert(Environment::currentlyOn(ThreadType::Main));
|
||||
|
||||
@@ -618,14 +645,15 @@ LatLngBounds Map::getBoundsForAnnotations(const std::vector<uint32_t>& annotatio
|
||||
});
|
||||
}
|
||||
|
||||
void Map::updateAnnotationTiles(const std::vector<Tile::ID>& ids) {
|
||||
void Map::updateAnnotationTiles(const std::vector<TileID>& ids) {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
for (const auto &source : activeSources) {
|
||||
if (!style) return;
|
||||
for (const auto &source : style->sources) {
|
||||
if (source->info.type == SourceType::Annotations) {
|
||||
source->source->invalidateTiles(*this, ids);
|
||||
return;
|
||||
source->invalidateTiles(ids);
|
||||
}
|
||||
}
|
||||
triggerUpdate();
|
||||
}
|
||||
|
||||
#pragma mark - Toggles
|
||||
@@ -685,45 +713,11 @@ Duration Map::getDefaultTransitionDuration() {
|
||||
return data->getDefaultTransitionDuration();
|
||||
}
|
||||
|
||||
void Map::updateSources() {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
|
||||
// First, disable all existing sources.
|
||||
for (const auto& source : activeSources) {
|
||||
source->enabled = false;
|
||||
}
|
||||
|
||||
// Then, reenable all of those that we actually use when drawing this layer.
|
||||
if (style) {
|
||||
for (const auto& layer : style->layers) {
|
||||
if (layer->bucket && layer->bucket->style_source) {
|
||||
(*activeSources.emplace(layer->bucket->style_source).first)->enabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Then, construct or destroy the actual source object, depending on enabled state.
|
||||
for (const auto& source : activeSources) {
|
||||
if (source->enabled) {
|
||||
if (!source->source) {
|
||||
source->source = std::make_shared<Source>(source->info);
|
||||
source->source->load(*this, *env);
|
||||
}
|
||||
} else {
|
||||
source->source.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, remove all sources that are disabled.
|
||||
util::erase_if(activeSources, [](util::ptr<StyleSource> source){
|
||||
return !source->enabled;
|
||||
});
|
||||
}
|
||||
|
||||
void Map::updateTiles() {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
for (const auto& source : activeSources) {
|
||||
source->source->update(*this, getWorker(), style, *glyphAtlas, *glyphStore,
|
||||
if (!style) return;
|
||||
for (const auto& source : style->sources) {
|
||||
source->update(*this, getWorker(), style, *glyphAtlas, *glyphStore,
|
||||
*spriteAtlas, getSprite(), *texturePool, [this]() {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
triggerUpdate();
|
||||
@@ -756,7 +750,7 @@ void Map::reloadStyle() {
|
||||
Log::Error(Event::Setup, "loading style failed: %s", res.message.c_str());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
} else if (!styleInfo.json.empty()) {
|
||||
// We got JSON data directly.
|
||||
loadStyleJSON(styleInfo.json, styleInfo.base);
|
||||
}
|
||||
@@ -775,6 +769,13 @@ void Map::loadStyleJSON(const std::string& json, const std::string& base) {
|
||||
const std::string glyphURL = util::mapbox::normalizeGlyphsURL(style->glyph_url, getAccessToken());
|
||||
glyphStore->setURL(glyphURL);
|
||||
|
||||
for (const auto& source : style->sources) {
|
||||
source->load(getAccessToken(), *env, [this]() {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
triggerUpdate();
|
||||
});
|
||||
}
|
||||
|
||||
triggerUpdate(Update::Zoom);
|
||||
}
|
||||
|
||||
@@ -802,6 +803,19 @@ void Map::prepare() {
|
||||
painter->setDebug(data->getDebug());
|
||||
}
|
||||
|
||||
if (u & static_cast<UpdateType>(Update::RenderStill)) {
|
||||
// Triggers a view resize.
|
||||
view.discard();
|
||||
|
||||
// Whenever we trigger an image render, we are unrefing all async handles so the loop will
|
||||
// eventually terminate. However, it'll stay alive as long as there are pending requests
|
||||
// (like work requests or HTTP requests).
|
||||
asyncTerminate->unref();
|
||||
asyncUpdate->unref();
|
||||
asyncInvoke->unref();
|
||||
asyncRender->unref();
|
||||
}
|
||||
|
||||
if (style) {
|
||||
if (u & static_cast<UpdateType>(Update::DefaultTransitionDuration)) {
|
||||
style->setDefaultTransitionDuration(data->getDefaultTransitionDuration());
|
||||
@@ -817,8 +831,6 @@ void Map::prepare() {
|
||||
style->recalculate(state.getNormalizedZoom(), now);
|
||||
}
|
||||
|
||||
updateSources();
|
||||
|
||||
// Allow the sprite atlas to potentially pull new sprite images if needed.
|
||||
spriteAtlas->resize(state.getPixelRatio());
|
||||
spriteAtlas->setSprite(getSprite());
|
||||
@@ -834,16 +846,41 @@ void Map::prepare() {
|
||||
void Map::render() {
|
||||
assert(Environment::currentlyOn(ThreadType::Map));
|
||||
|
||||
view.discard();
|
||||
|
||||
// Cleanup OpenGL objects that we abandoned since the last render call.
|
||||
env->performCleanup();
|
||||
|
||||
assert(style);
|
||||
assert(painter);
|
||||
painter->render(*style, activeSources,
|
||||
state, data->getAnimationTime());
|
||||
|
||||
painter->render(*style, state, data->getAnimationTime());
|
||||
|
||||
// Schedule another rerender when we definitely need a next frame.
|
||||
if (transform.needsTransition() || style->hasTransitions()) {
|
||||
triggerUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
void Map::setSourceTileCacheSize(size_t size) {
|
||||
if (size != getSourceTileCacheSize()) {
|
||||
invokeTask([=] {
|
||||
sourceCacheSize = size;
|
||||
if (!style) return;
|
||||
for (const auto &source : style->sources) {
|
||||
source->setCacheSize(sourceCacheSize);
|
||||
}
|
||||
env->performCleanup();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void Map::onLowMemory() {
|
||||
invokeTask([=] {
|
||||
if (!style) return;
|
||||
for (const auto &source : style->sources) {
|
||||
source->onLowMemory();
|
||||
}
|
||||
env->performCleanup();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
RasterTileData::RasterTileData(Tile::ID const &id_, TexturePool &texturePool,
|
||||
RasterTileData::RasterTileData(const TileID& id_, TexturePool &texturePool,
|
||||
const SourceInfo &source_)
|
||||
: TileData(id_, source_), bucket(texturePool, layout) {
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#ifndef MBGL_MAP_RASTER_TILE_DATA
|
||||
#define MBGL_MAP_RASTER_TILE_DATA
|
||||
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/map/tile_data.hpp>
|
||||
#include <mbgl/style/style_layout.hpp>
|
||||
#include <mbgl/renderer/raster_bucket.hpp>
|
||||
@@ -17,7 +16,7 @@ class RasterTileData : public TileData {
|
||||
friend class TileParser;
|
||||
|
||||
public:
|
||||
RasterTileData(Tile::ID const &id, TexturePool &, const SourceInfo &);
|
||||
RasterTileData(const TileID&, TexturePool&, const SourceInfo&);
|
||||
~RasterTileData();
|
||||
|
||||
void parse() override;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/environment.hpp>
|
||||
#include <mbgl/map/transform.hpp>
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/renderer/painter.hpp>
|
||||
#include <mbgl/util/constants.hpp>
|
||||
#include <mbgl/util/raster.hpp>
|
||||
@@ -18,6 +19,8 @@
|
||||
#include <mbgl/style/style_layer.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
#include <mbgl/util/uv_detail.hpp>
|
||||
#include <mbgl/util/token.hpp>
|
||||
#include <mbgl/util/tile_cover.hpp>
|
||||
|
||||
#include <mbgl/map/vector_tile_data.hpp>
|
||||
#include <mbgl/map/raster_tile_data.hpp>
|
||||
@@ -27,15 +30,105 @@
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
Source::Source(SourceInfo& info_)
|
||||
: info(info_)
|
||||
void parse(const rapidjson::Value& value, std::vector<std::string>& target, const char *name) {
|
||||
if (!value.HasMember(name))
|
||||
return;
|
||||
|
||||
const rapidjson::Value& property = value[name];
|
||||
if (!property.IsArray())
|
||||
return;
|
||||
|
||||
for (rapidjson::SizeType i = 0; i < property.Size(); i++)
|
||||
if (!property[i].IsString())
|
||||
return;
|
||||
|
||||
for (rapidjson::SizeType i = 0; i < property.Size(); i++)
|
||||
target.emplace_back(std::string(property[i].GetString(), property[i].GetStringLength()));
|
||||
}
|
||||
|
||||
void parse(const rapidjson::Value& value, std::string& target, const char* name) {
|
||||
if (!value.HasMember(name))
|
||||
return;
|
||||
|
||||
const rapidjson::Value& property = value[name];
|
||||
if (!property.IsString())
|
||||
return;
|
||||
|
||||
target = { property.GetString(), property.GetStringLength() };
|
||||
}
|
||||
|
||||
void parse(const rapidjson::Value& value, uint16_t& target, const char* name) {
|
||||
if (!value.HasMember(name))
|
||||
return;
|
||||
|
||||
const rapidjson::Value& property = value[name];
|
||||
if (!property.IsUint())
|
||||
return;
|
||||
|
||||
unsigned int uint = property.GetUint();
|
||||
if (uint > std::numeric_limits<uint16_t>::max())
|
||||
return;
|
||||
|
||||
target = uint;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
void parse(const rapidjson::Value& value, std::array<float, N>& target, const char* name) {
|
||||
if (!value.HasMember(name))
|
||||
return;
|
||||
|
||||
const rapidjson::Value& property = value[name];
|
||||
if (!property.IsArray() || property.Size() != N)
|
||||
return;
|
||||
|
||||
for (rapidjson::SizeType i = 0; i < property.Size(); i++)
|
||||
if (!property[i].IsNumber())
|
||||
return;
|
||||
|
||||
for (rapidjson::SizeType i = 0; i < property.Size(); i++)
|
||||
target[i] = property[i].GetDouble();
|
||||
}
|
||||
|
||||
void SourceInfo::parseTileJSONProperties(const rapidjson::Value& value) {
|
||||
parse(value, tiles, "tiles");
|
||||
parse(value, min_zoom, "minzoom");
|
||||
parse(value, max_zoom, "maxzoom");
|
||||
parse(value, attribution, "attribution");
|
||||
parse(value, center, "center");
|
||||
parse(value, bounds, "bounds");
|
||||
}
|
||||
|
||||
std::string SourceInfo::tileURL(const TileID& id, float pixelRatio) const {
|
||||
std::string result = tiles.at((id.x + id.y) % tiles.size());
|
||||
result = util::mapbox::normalizeTileURL(result, url, type);
|
||||
result = util::replaceTokens(result, [&](const std::string &token) -> std::string {
|
||||
if (token == "z") return util::toString(id.z);
|
||||
if (token == "x") return util::toString(id.x);
|
||||
if (token == "y") return util::toString(id.y);
|
||||
if (token == "prefix") {
|
||||
std::string prefix { 2 };
|
||||
prefix[0] = "0123456789abcdef"[id.x % 16];
|
||||
prefix[1] = "0123456789abcdef"[id.y % 16];
|
||||
return prefix;
|
||||
}
|
||||
if (token == "ratio") return pixelRatio > 1.0 ? "@2x" : "";
|
||||
return "";
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
Source::Source()
|
||||
{
|
||||
}
|
||||
|
||||
Source::~Source() {}
|
||||
|
||||
// Note: This is a separate function that must be called exactly once after creation
|
||||
// The reason this isn't part of the constructor is that calling shared_from_this() in
|
||||
// the constructor fails.
|
||||
void Source::load(Map &map, Environment &env) {
|
||||
void Source::load(const std::string& accessToken,
|
||||
Environment& env,
|
||||
std::function<void()> callback) {
|
||||
if (info.url.empty()) {
|
||||
loaded = true;
|
||||
return;
|
||||
@@ -43,8 +136,8 @@ void Source::load(Map &map, Environment &env) {
|
||||
|
||||
util::ptr<Source> source = shared_from_this();
|
||||
|
||||
const std::string url = util::mapbox::normalizeSourceURL(info.url, map.getAccessToken());
|
||||
env.request({ Resource::Kind::JSON, url }, [source, &map](const Response &res) {
|
||||
const std::string url = util::mapbox::normalizeSourceURL(info.url, accessToken);
|
||||
env.request({ Resource::Kind::JSON, url }, [source, callback](const Response &res) {
|
||||
if (res.status != Response::Successful) {
|
||||
Log::Warning(Event::General, "Failed to load source TileJSON: %s", res.message.c_str());
|
||||
return;
|
||||
@@ -61,19 +154,7 @@ void Source::load(Map &map, Environment &env) {
|
||||
source->info.parseTileJSONProperties(d);
|
||||
source->loaded = true;
|
||||
|
||||
map.triggerUpdate();
|
||||
});
|
||||
}
|
||||
|
||||
void Source::updateClipIDs(const std::map<Tile::ID, ClipID> &mapping) {
|
||||
std::for_each(tiles.begin(), tiles.end(), [&mapping](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
|
||||
Tile &tile = *pair.second;
|
||||
auto it = mapping.find(tile.id);
|
||||
if (it != mapping.end()) {
|
||||
tile.clip = it->second;
|
||||
} else {
|
||||
tile.clip = ClipID {};
|
||||
}
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,10 +166,6 @@ void Source::updateMatrices(const mat4 &projMatrix, const TransformState &transf
|
||||
}
|
||||
}
|
||||
|
||||
size_t Source::getTileCount() const {
|
||||
return tiles.size();
|
||||
}
|
||||
|
||||
void Source::drawClippingMasks(Painter &painter) {
|
||||
for (const auto& pair : tiles) {
|
||||
Tile &tile = *pair.second;
|
||||
@@ -107,13 +184,6 @@ void Source::render(Painter &painter, const StyleLayer &layer_desc) {
|
||||
}
|
||||
}
|
||||
|
||||
void Source::render(Painter &painter, const StyleLayer &layer_desc, const Tile::ID &id, const mat4 &matrix) {
|
||||
auto it = tiles.find(id);
|
||||
if (it != tiles.end() && it->second->data && it->second->data->state == TileData::State::parsed) {
|
||||
painter.renderTileLayer(*it->second, layer_desc, matrix);
|
||||
}
|
||||
}
|
||||
|
||||
void Source::finishRender(Painter &painter) {
|
||||
for (const auto& pair : tiles) {
|
||||
Tile &tile = *pair.second;
|
||||
@@ -121,16 +191,6 @@ void Source::finishRender(Painter &painter) {
|
||||
}
|
||||
}
|
||||
|
||||
std::forward_list<Tile::ID> Source::getIDs() const {
|
||||
std::forward_list<Tile::ID> ptrs;
|
||||
|
||||
std::transform(tiles.begin(), tiles.end(), std::front_inserter(ptrs), [](const std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
|
||||
Tile &tile = *pair.second;
|
||||
return tile.id;
|
||||
});
|
||||
return ptrs;
|
||||
}
|
||||
|
||||
std::forward_list<Tile *> Source::getLoadedTiles() const {
|
||||
std::forward_list<Tile *> ptrs;
|
||||
auto it = ptrs.before_begin();
|
||||
@@ -143,7 +203,7 @@ std::forward_list<Tile *> Source::getLoadedTiles() const {
|
||||
}
|
||||
|
||||
|
||||
TileData::State Source::hasTile(const Tile::ID& id) {
|
||||
TileData::State Source::hasTile(const TileID& id) {
|
||||
auto it = tiles.find(id);
|
||||
if (it != tiles.end()) {
|
||||
Tile &tile = *it->second;
|
||||
@@ -155,11 +215,11 @@ TileData::State Source::hasTile(const Tile::ID& id) {
|
||||
return TileData::State::invalid;
|
||||
}
|
||||
|
||||
TileData::State Source::addTile(Map &map, uv::worker &worker,
|
||||
TileData::State Source::addTile(Map &map, Worker &worker,
|
||||
util::ptr<Style> style, GlyphAtlas &glyphAtlas,
|
||||
GlyphStore &glyphStore, SpriteAtlas &spriteAtlas,
|
||||
util::ptr<Sprite> sprite, TexturePool &texturePool,
|
||||
const Tile::ID &id, std::function<void()> callback) {
|
||||
const TileID &id, std::function<void()> callback) {
|
||||
const TileData::State state = hasTile(id);
|
||||
|
||||
if (state != TileData::State::invalid) {
|
||||
@@ -171,7 +231,7 @@ TileData::State Source::addTile(Map &map, uv::worker &worker,
|
||||
|
||||
// We couldn't find the tile in the list. Create a new one.
|
||||
// Try to find the associated TileData object.
|
||||
const Tile::ID normalized_id = id.normalized();
|
||||
const TileID normalized_id = id.normalized();
|
||||
|
||||
auto it = tile_data.find(normalized_id);
|
||||
if (it != tile_data.end()) {
|
||||
@@ -184,6 +244,10 @@ TileData::State Source::addTile(Map &map, uv::worker &worker,
|
||||
new_tile.data.reset();
|
||||
}
|
||||
|
||||
if (!new_tile.data) {
|
||||
new_tile.data = cache.get(normalized_id.to_uint64());
|
||||
}
|
||||
|
||||
if (!new_tile.data) {
|
||||
// If we don't find working tile data, we're just going to load it.
|
||||
if (info.type == SourceType::Vector) {
|
||||
@@ -218,7 +282,7 @@ int32_t Source::coveringZoomLevel(const TransformState& state) const {
|
||||
return std::floor(getZoom(state));
|
||||
}
|
||||
|
||||
std::forward_list<Tile::ID> Source::coveringTiles(const TransformState& state) const {
|
||||
std::forward_list<TileID> Source::coveringTiles(const TransformState& state) const {
|
||||
int32_t z = coveringZoomLevel(state);
|
||||
|
||||
if (z < info.min_zoom) return {{}};
|
||||
@@ -228,9 +292,9 @@ std::forward_list<Tile::ID> Source::coveringTiles(const TransformState& state) c
|
||||
box points = state.cornersToBox(z);
|
||||
const vec2<double>& center = points.center;
|
||||
|
||||
std::forward_list<Tile::ID> covering_tiles = Tile::cover(z, points);
|
||||
std::forward_list<TileID> covering_tiles = tileCover(z, points);
|
||||
|
||||
covering_tiles.sort([¢er](const Tile::ID& a, const Tile::ID& b) {
|
||||
covering_tiles.sort([¢er](const TileID& a, const TileID& b) {
|
||||
// Sorts by distance from the box center
|
||||
return std::fabs(a.x - center.x) + std::fabs(a.y - center.y) <
|
||||
std::fabs(b.x - center.x) + std::fabs(b.y - center.y);
|
||||
@@ -248,7 +312,7 @@ std::forward_list<Tile::ID> Source::coveringTiles(const TransformState& state) c
|
||||
*
|
||||
* @return boolean Whether the children found completely cover the tile.
|
||||
*/
|
||||
bool Source::findLoadedChildren(const Tile::ID& id, int32_t maxCoveringZoom, std::forward_list<Tile::ID>& retain) {
|
||||
bool Source::findLoadedChildren(const TileID& id, int32_t maxCoveringZoom, std::forward_list<TileID>& retain) {
|
||||
bool complete = true;
|
||||
int32_t z = id.z;
|
||||
auto ids = id.children(z + 1);
|
||||
@@ -276,9 +340,9 @@ bool Source::findLoadedChildren(const Tile::ID& id, int32_t maxCoveringZoom, std
|
||||
*
|
||||
* @return boolean Whether a parent was found.
|
||||
*/
|
||||
bool Source::findLoadedParent(const Tile::ID& id, int32_t minCoveringZoom, std::forward_list<Tile::ID>& retain) {
|
||||
bool Source::findLoadedParent(const TileID& id, int32_t minCoveringZoom, std::forward_list<TileID>& retain) {
|
||||
for (int32_t z = id.z - 1; z >= minCoveringZoom; --z) {
|
||||
const Tile::ID parent_id = id.parent(z);
|
||||
const TileID parent_id = id.parent(z);
|
||||
const TileData::State state = hasTile(parent_id);
|
||||
if (state == TileData::State::parsed) {
|
||||
retain.emplace_front(parent_id);
|
||||
@@ -289,7 +353,7 @@ bool Source::findLoadedParent(const Tile::ID& id, int32_t minCoveringZoom, std::
|
||||
}
|
||||
|
||||
void Source::update(Map &map,
|
||||
uv::worker &worker,
|
||||
Worker &worker,
|
||||
util::ptr<Style> style,
|
||||
GlyphAtlas &glyphAtlas,
|
||||
GlyphStore &glyphStore,
|
||||
@@ -302,7 +366,7 @@ void Source::update(Map &map,
|
||||
}
|
||||
|
||||
int32_t zoom = std::floor(getZoom(map.getState()));
|
||||
std::forward_list<Tile::ID> required = coveringTiles(map.getState());
|
||||
std::forward_list<TileID> required = coveringTiles(map.getState());
|
||||
|
||||
// Determine the overzooming/underzooming amounts.
|
||||
int32_t minCoveringZoom = util::clamp<int32_t>(zoom - 10, info.min_zoom, info.max_zoom);
|
||||
@@ -311,7 +375,7 @@ void Source::update(Map &map,
|
||||
// Retain is a list of tiles that we shouldn't delete, even if they are not
|
||||
// the most ideal tile for the current viewport. This may include tiles like
|
||||
// parent or child tiles that are *already* loaded.
|
||||
std::forward_list<Tile::ID> retain(required);
|
||||
std::forward_list<TileID> retain(required);
|
||||
|
||||
// Add existing child/parent tiles if the actual tile is not yet loaded
|
||||
for (const auto& id : required) {
|
||||
@@ -334,20 +398,33 @@ void Source::update(Map &map,
|
||||
}
|
||||
}
|
||||
|
||||
if (info.type != SourceType::Raster && cache.getSize() == 0) {
|
||||
size_t conservativeCacheSize = ((float)map.getState().getWidth() / util::tileSize) *
|
||||
((float)map.getState().getHeight() / util::tileSize) *
|
||||
(map.getMaxZoom() - map.getMinZoom() + 1) *
|
||||
0.5;
|
||||
cache.setSize(conservativeCacheSize);
|
||||
}
|
||||
|
||||
auto& tileCache = cache;
|
||||
auto& type = info.type;
|
||||
|
||||
// Remove tiles that we definitely don't need, i.e. tiles that are not on
|
||||
// the required list.
|
||||
std::set<Tile::ID> retain_data;
|
||||
util::erase_if(tiles, [&retain, &retain_data](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
|
||||
std::set<TileID> retain_data;
|
||||
util::erase_if(tiles, [&retain, &retain_data, &tileCache, &type](std::pair<const TileID, std::unique_ptr<Tile>> &pair) {
|
||||
Tile &tile = *pair.second;
|
||||
bool obsolete = std::find(retain.begin(), retain.end(), tile.id) == retain.end();
|
||||
if (!obsolete) {
|
||||
retain_data.insert(tile.data->id);
|
||||
} else if (type != SourceType::Raster && tile.data->ready()) {
|
||||
tileCache.add(tile.id.normalized().to_uint64(), tile.data);
|
||||
}
|
||||
return obsolete;
|
||||
});
|
||||
|
||||
// Remove all the expired pointers from the set.
|
||||
util::erase_if(tile_data, [&retain_data](std::pair<const Tile::ID, std::weak_ptr<TileData>> &pair) {
|
||||
util::erase_if(tile_data, [&retain_data, &tileCache](std::pair<const TileID, std::weak_ptr<TileData>> &pair) {
|
||||
const util::ptr<TileData> tile = pair.second.lock();
|
||||
if (!tile) {
|
||||
return true;
|
||||
@@ -355,7 +432,9 @@ void Source::update(Map &map,
|
||||
|
||||
bool obsolete = retain_data.find(tile->id) == retain_data.end();
|
||||
if (obsolete) {
|
||||
tile->cancel();
|
||||
if (!tileCache.has(tile->id.normalized().to_uint64())) {
|
||||
tile->cancel();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
@@ -365,12 +444,20 @@ void Source::update(Map &map,
|
||||
updated = map.getTime();
|
||||
}
|
||||
|
||||
void Source::invalidateTiles(Map& map, const std::vector<Tile::ID>& ids) {
|
||||
void Source::invalidateTiles(const std::vector<TileID>& ids) {
|
||||
cache.clear();
|
||||
for (auto& id : ids) {
|
||||
tiles.erase(id);
|
||||
tile_data.erase(id);
|
||||
}
|
||||
map.triggerUpdate();
|
||||
}
|
||||
|
||||
void Source::setCacheSize(size_t size) {
|
||||
cache.setSize(size);
|
||||
}
|
||||
|
||||
void Source::onLowMemory() {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
#ifndef MBGL_MAP_SOURCE
|
||||
#define MBGL_MAP_SOURCE
|
||||
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/map/tile_id.hpp>
|
||||
#include <mbgl/map/tile_data.hpp>
|
||||
#include <mbgl/style/style_source.hpp>
|
||||
#include <mbgl/map/tile_cache.hpp>
|
||||
#include <mbgl/style/types.hpp>
|
||||
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
#include <mbgl/util/chrono.hpp>
|
||||
|
||||
#include <rapidjson/document.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <forward_list>
|
||||
#include <iosfwd>
|
||||
@@ -19,6 +22,7 @@ namespace mbgl {
|
||||
|
||||
class Map;
|
||||
class Environment;
|
||||
class Worker;
|
||||
class GlyphAtlas;
|
||||
class GlyphStore;
|
||||
class SpriteAtlas;
|
||||
@@ -28,50 +32,75 @@ class Style;
|
||||
class Painter;
|
||||
class StyleLayer;
|
||||
class TransformState;
|
||||
class Tile;
|
||||
struct ClipID;
|
||||
struct box;
|
||||
|
||||
class SourceInfo : private util::noncopyable {
|
||||
public:
|
||||
SourceType type = SourceType::Vector;
|
||||
std::string url;
|
||||
std::vector<std::string> tiles;
|
||||
uint16_t tile_size = 512;
|
||||
uint16_t min_zoom = 0;
|
||||
uint16_t max_zoom = 22;
|
||||
std::string attribution;
|
||||
std::array<float, 3> center = {{0, 0, 0}};
|
||||
std::array<float, 4> bounds = {{-180, -90, 180, 90}};
|
||||
|
||||
void parseTileJSONProperties(const rapidjson::Value&);
|
||||
std::string tileURL(const TileID& id, float pixelRatio) const;
|
||||
};
|
||||
|
||||
class Source : public std::enable_shared_from_this<Source>, private util::noncopyable {
|
||||
public:
|
||||
Source(SourceInfo&);
|
||||
Source();
|
||||
~Source();
|
||||
|
||||
void load(Map &, Environment &);
|
||||
void update(Map &, uv::worker &, util::ptr<Style>, GlyphAtlas &, GlyphStore &,
|
||||
void load(const std::string& accessToken,
|
||||
Environment&,
|
||||
std::function<void()> callback);
|
||||
|
||||
void update(Map &, Worker &, util::ptr<Style>, GlyphAtlas &, GlyphStore &,
|
||||
SpriteAtlas &, util::ptr<Sprite>, TexturePool &, std::function<void()> callback);
|
||||
void invalidateTiles(Map&, const std::vector<Tile::ID>&);
|
||||
|
||||
void invalidateTiles(const std::vector<TileID>&);
|
||||
|
||||
void updateMatrices(const mat4 &projMatrix, const TransformState &transform);
|
||||
void drawClippingMasks(Painter &painter);
|
||||
size_t getTileCount() const;
|
||||
void render(Painter &painter, const StyleLayer &layer_desc);
|
||||
void render(Painter &painter, const StyleLayer &layer_desc, const Tile::ID &id, const mat4 &matrix);
|
||||
void finishRender(Painter &painter);
|
||||
|
||||
std::forward_list<Tile::ID> getIDs() const;
|
||||
std::forward_list<Tile *> getLoadedTiles() const;
|
||||
void updateClipIDs(const std::map<Tile::ID, ClipID> &mapping);
|
||||
|
||||
void setCacheSize(size_t);
|
||||
void onLowMemory();
|
||||
|
||||
SourceInfo info;
|
||||
bool enabled;
|
||||
|
||||
private:
|
||||
bool findLoadedChildren(const Tile::ID& id, int32_t maxCoveringZoom, std::forward_list<Tile::ID>& retain);
|
||||
bool findLoadedParent(const Tile::ID& id, int32_t minCoveringZoom, std::forward_list<Tile::ID>& retain);
|
||||
bool findLoadedChildren(const TileID& id, int32_t maxCoveringZoom, std::forward_list<TileID>& retain);
|
||||
bool findLoadedParent(const TileID& id, int32_t minCoveringZoom, std::forward_list<TileID>& retain);
|
||||
int32_t coveringZoomLevel(const TransformState&) const;
|
||||
std::forward_list<Tile::ID> coveringTiles(const TransformState&) const;
|
||||
std::forward_list<TileID> coveringTiles(const TransformState&) const;
|
||||
|
||||
TileData::State addTile(Map &, uv::worker &, util::ptr<Style>, GlyphAtlas &,
|
||||
TileData::State addTile(Map &, Worker &, util::ptr<Style>, GlyphAtlas &,
|
||||
GlyphStore &, SpriteAtlas &, util::ptr<Sprite>, TexturePool &,
|
||||
const Tile::ID &, std::function<void()> callback);
|
||||
const TileID &, std::function<void()> callback);
|
||||
|
||||
TileData::State hasTile(const Tile::ID& id);
|
||||
TileData::State hasTile(const TileID& id);
|
||||
|
||||
double getZoom(const TransformState &state) const;
|
||||
|
||||
SourceInfo& info;
|
||||
bool loaded = false;
|
||||
|
||||
// Stores the time when this source was most recently updated.
|
||||
TimePoint updated = TimePoint::min();
|
||||
|
||||
std::map<Tile::ID, std::unique_ptr<Tile>> tiles;
|
||||
std::map<Tile::ID, std::weak_ptr<TileData>> tile_data;
|
||||
std::map<TileID, std::unique_ptr<Tile>> tiles;
|
||||
std::map<TileID, std::weak_ptr<TileData>> tile_data;
|
||||
TileCache cache;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,147 +1,3 @@
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/util/vec.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
#include <mbgl/util/box.hpp>
|
||||
|
||||
|
||||
#include <cassert>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
#include <iostream>
|
||||
|
||||
Tile::Tile(const ID& id_)
|
||||
: id(id_) {
|
||||
}
|
||||
|
||||
Tile::ID Tile::ID::parent(int8_t parent_z) const {
|
||||
assert(parent_z < z);
|
||||
int32_t dim = std::pow(2, z - parent_z);
|
||||
return Tile::ID{
|
||||
parent_z,
|
||||
(x >= 0 ? x : x - dim + 1) / dim,
|
||||
y / dim
|
||||
};
|
||||
}
|
||||
|
||||
std::forward_list<Tile::ID> Tile::ID::children(int32_t child_z) const {
|
||||
assert(child_z > z);
|
||||
int32_t factor = std::pow(2, child_z - z);
|
||||
|
||||
std::forward_list<ID> child_ids;
|
||||
for (int32_t ty = y * factor, y_max = (y + 1) * factor; ty < y_max; ++ty) {
|
||||
for (int32_t tx = x * factor, x_max = (x + 1) * factor; tx < x_max; ++tx) {
|
||||
child_ids.emplace_front(child_z, tx, ty);
|
||||
}
|
||||
}
|
||||
return child_ids;
|
||||
}
|
||||
|
||||
Tile::ID Tile::ID::normalized() const {
|
||||
int32_t dim = std::pow(2, z);
|
||||
int32_t nx = x, ny = y;
|
||||
while (nx < 0) nx += dim;
|
||||
while (nx >= dim) nx -= dim;
|
||||
return ID { z, nx, ny };
|
||||
}
|
||||
|
||||
bool Tile::ID::isChildOf(const Tile::ID &parent_id) const {
|
||||
if (parent_id.z >= z || parent_id.w != w) {
|
||||
return false;
|
||||
}
|
||||
int32_t scale = std::pow(2, z - parent_id.z);
|
||||
return parent_id.x == ((x < 0 ? x - scale + 1 : x) / scale) &&
|
||||
parent_id.y == y / scale;
|
||||
}
|
||||
|
||||
|
||||
Tile::ID::operator std::string() const {
|
||||
return util::toString(z) + "/" + util::toString(x) + "/" + util::toString(y);
|
||||
}
|
||||
|
||||
|
||||
// Taken from polymaps src/Layer.js
|
||||
// https://github.com/simplegeo/polymaps/blob/master/src/Layer.js#L333-L383
|
||||
|
||||
struct edge {
|
||||
double x0 = 0, y0 = 0;
|
||||
double x1 = 0, y1 = 0;
|
||||
double dx = 0, dy = 0;
|
||||
|
||||
edge(vec2<double> a, vec2<double> b) {
|
||||
if (a.y > b.y) { std::swap(a, b); }
|
||||
x0 = a.x;
|
||||
y0 = a.y;
|
||||
x1 = b.x;
|
||||
y1 = b.y;
|
||||
dx = b.x - a.x;
|
||||
dy = b.y - a.y;
|
||||
}
|
||||
};
|
||||
|
||||
typedef const std::function<void(int32_t x0, int32_t x1, int32_t y)> ScanLine;
|
||||
|
||||
// scan-line conversion
|
||||
static void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine scanLine) {
|
||||
double y0 = std::fmax(ymin, std::floor(e1.y0));
|
||||
double y1 = std::fmin(ymax, std::ceil(e1.y1));
|
||||
|
||||
// sort edges by x-coordinate
|
||||
if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ?
|
||||
(e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) :
|
||||
(e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) {
|
||||
std::swap(e0, e1);
|
||||
}
|
||||
|
||||
// scan lines!
|
||||
double m0 = e0.dx / e0.dy;
|
||||
double m1 = e1.dx / e1.dy;
|
||||
double d0 = e0.dx > 0; // use y + 1 to compute x0
|
||||
double d1 = e1.dx < 0; // use y + 1 to compute x1
|
||||
for (int32_t y = y0; y < y1; y++) {
|
||||
double x0 = m0 * std::fmax(0, std::fmin(e0.dy, y + d0 - e0.y0)) + e0.x0;
|
||||
double x1 = m1 * std::fmax(0, std::fmin(e1.dy, y + d1 - e1.y0)) + e1.x0;
|
||||
scanLine(std::floor(x1), std::ceil(x0), y);
|
||||
}
|
||||
}
|
||||
|
||||
// scan-line conversion
|
||||
static void scanTriangle(const mbgl::vec2<double> a, const mbgl::vec2<double> b, const mbgl::vec2<double> c, int32_t ymin, int32_t ymax, ScanLine& scanLine) {
|
||||
edge ab = edge(a, b);
|
||||
edge bc = edge(b, c);
|
||||
edge ca = edge(c, a);
|
||||
|
||||
// sort edges by y-length
|
||||
if (ab.dy > bc.dy) { std::swap(ab, bc); }
|
||||
if (ab.dy > ca.dy) { std::swap(ab, ca); }
|
||||
if (bc.dy > ca.dy) { std::swap(bc, ca); }
|
||||
|
||||
// scan span! scan span!
|
||||
if (ab.dy) scanSpans(ca, ab, ymin, ymax, scanLine);
|
||||
if (bc.dy) scanSpans(ca, bc, ymin, ymax, scanLine);
|
||||
}
|
||||
|
||||
std::forward_list<Tile::ID> Tile::cover(int8_t z, const mbgl::box &bounds) {
|
||||
int32_t tiles = 1 << z;
|
||||
std::forward_list<mbgl::Tile::ID> t;
|
||||
|
||||
auto scanLine = [&](int32_t x0, int32_t x1, int32_t y) {
|
||||
int32_t x;
|
||||
if (y >= 0 && y <= tiles) {
|
||||
for (x = x0; x < x1; x++) {
|
||||
t.emplace_front(z, x, y);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Divide the screen up in two triangles and scan each of them:
|
||||
// \---+
|
||||
// | \ |
|
||||
// +---\.
|
||||
scanTriangle(bounds.tl, bounds.tr, bounds.br, 0, tiles, scanLine);
|
||||
scanTriangle(bounds.br, bounds.bl, bounds.tl, 0, tiles, scanLine);
|
||||
|
||||
t.unique();
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
28
src/mbgl/map/tile.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#ifndef MBGL_MAP_TILE
|
||||
#define MBGL_MAP_TILE
|
||||
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
#include <mbgl/util/clip_id.hpp>
|
||||
#include <mbgl/map/tile_id.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class TileData;
|
||||
struct box;
|
||||
|
||||
class Tile : private util::noncopyable {
|
||||
public:
|
||||
explicit Tile(const TileID& id_)
|
||||
: id(id_) {}
|
||||
|
||||
const TileID id;
|
||||
ClipID clip;
|
||||
mat4 matrix;
|
||||
util::ptr<TileData> data;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
64
src/mbgl/map/tile_cache.cpp
Normal file
@@ -0,0 +1,64 @@
|
||||
#include <mbgl/map/tile_cache.hpp>
|
||||
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
void TileCache::setSize(size_t size_) {
|
||||
size = size_;
|
||||
|
||||
while (orderedKeys.size() > size) {
|
||||
auto key = orderedKeys.front();
|
||||
orderedKeys.pop_front();
|
||||
tiles.erase(key);
|
||||
}
|
||||
|
||||
assert(orderedKeys.size() <= size);
|
||||
|
||||
tiles.reserve(size);
|
||||
}
|
||||
|
||||
void TileCache::add(uint64_t key, std::shared_ptr<TileData> data) {
|
||||
|
||||
// insert new or query existing data
|
||||
if (tiles.emplace(key, data).second) {
|
||||
// remove existing data key
|
||||
orderedKeys.remove(key);
|
||||
}
|
||||
|
||||
// (re-)insert data key as newest
|
||||
orderedKeys.push_back(key);
|
||||
|
||||
// purge oldest key/data if necessary
|
||||
if (orderedKeys.size() > size) {
|
||||
get(orderedKeys.front());
|
||||
}
|
||||
|
||||
assert(orderedKeys.size() <= size);
|
||||
};
|
||||
|
||||
std::shared_ptr<TileData> TileCache::get(uint64_t key) {
|
||||
|
||||
std::shared_ptr<TileData> data;
|
||||
|
||||
auto it = tiles.find(key);
|
||||
if (it != tiles.end()) {
|
||||
data = it->second;
|
||||
tiles.erase(it);
|
||||
orderedKeys.remove(key);
|
||||
assert(data->ready());
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
bool TileCache::has(uint64_t key) {
|
||||
return tiles.find(key) != tiles.end();
|
||||
}
|
||||
|
||||
void TileCache::clear() {
|
||||
orderedKeys.clear();
|
||||
tiles.clear();
|
||||
}
|
||||
|
||||
};
|
||||
30
src/mbgl/map/tile_cache.hpp
Normal file
@@ -0,0 +1,30 @@
|
||||
#ifndef MBGL_MAP_TILE_CACHE
|
||||
#define MBGL_MAP_TILE_CACHE
|
||||
|
||||
#include <mbgl/map/tile_data.hpp>
|
||||
|
||||
#include <list>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class TileCache {
|
||||
public:
|
||||
TileCache(size_t size_ = 0) : size(size_) {}
|
||||
|
||||
void setSize(size_t);
|
||||
size_t getSize() const { return size; };
|
||||
void add(uint64_t key, std::shared_ptr<TileData> data);
|
||||
std::shared_ptr<TileData> get(uint64_t key);
|
||||
bool has(uint64_t key);
|
||||
void clear();
|
||||
private:
|
||||
std::unordered_map<uint64_t, std::shared_ptr<TileData>> tiles;
|
||||
std::list<uint64_t> orderedKeys;
|
||||
|
||||
size_t size;
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,18 +1,14 @@
|
||||
#include <mbgl/map/tile_data.hpp>
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/environment.hpp>
|
||||
#include <mbgl/style/style_source.hpp>
|
||||
#include <mbgl/map/source.hpp>
|
||||
|
||||
#include <mbgl/util/token.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
#include <mbgl/util/mapbox.hpp>
|
||||
#include <mbgl/storage/file_source.hpp>
|
||||
#include <mbgl/util/uv_detail.hpp>
|
||||
#include <mbgl/util/worker.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
TileData::TileData(Tile::ID const& id_, const SourceInfo& source_)
|
||||
TileData::TileData(const TileID& id_, const SourceInfo& source_)
|
||||
: id(id_),
|
||||
name(id),
|
||||
state(State::initial),
|
||||
@@ -24,59 +20,30 @@ TileData::TileData(Tile::ID const& id_, const SourceInfo& source_)
|
||||
}
|
||||
|
||||
TileData::~TileData() {
|
||||
if (req) {
|
||||
env.cancelRequest(req);
|
||||
}
|
||||
cancel();
|
||||
}
|
||||
|
||||
const std::string TileData::toString() const {
|
||||
return std::string { "[tile " } + name + "]";
|
||||
}
|
||||
|
||||
void TileData::request(uv::worker &worker, float pixelRatio, std::function<void()> callback) {
|
||||
if (source.tiles.empty())
|
||||
return;
|
||||
|
||||
std::string url = source.tiles[(id.x + id.y) % source.tiles.size()];
|
||||
url = util::mapbox::normalizeTileURL(url, source.url, source.type);
|
||||
url = util::replaceTokens(url, [&](const std::string &token) -> std::string {
|
||||
if (token == "z") return util::toString(id.z);
|
||||
if (token == "x") return util::toString(id.x);
|
||||
if (token == "y") return util::toString(id.y);
|
||||
if (token == "prefix") {
|
||||
std::string prefix { 2 };
|
||||
prefix[0] = "0123456789abcdef"[id.x % 16];
|
||||
prefix[1] = "0123456789abcdef"[id.y % 16];
|
||||
return prefix;
|
||||
}
|
||||
if (token == "ratio") return pixelRatio > 1.0 ? "@2x" : "";
|
||||
return "";
|
||||
});
|
||||
|
||||
void TileData::request(Worker& worker, float pixelRatio, std::function<void()> callback) {
|
||||
std::string url = source.tileURL(id, pixelRatio);
|
||||
state = State::loading;
|
||||
|
||||
std::weak_ptr<TileData> weak_tile = shared_from_this();
|
||||
req = env.request({ Resource::Kind::Tile, url }, [weak_tile, url, callback, &worker](const Response &res) {
|
||||
util::ptr<TileData> tile = weak_tile.lock();
|
||||
if (!tile || tile->state == State::obsolete) {
|
||||
// noop. Tile is obsolete and we're now just waiting for the refcount
|
||||
// to drop to zero for destruction.
|
||||
req = env.request({ Resource::Kind::Tile, url }, [url, callback, &worker, this](const Response &res) {
|
||||
req = nullptr;
|
||||
|
||||
if (res.status != Response::Successful) {
|
||||
Log::Error(Event::HttpRequest, "[%s] tile loading failed: %s", url.c_str(), res.message.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear the request object.
|
||||
tile->req = nullptr;
|
||||
state = State::loaded;
|
||||
data = res.data;
|
||||
|
||||
if (res.status == Response::Successful) {
|
||||
tile->state = State::loaded;
|
||||
|
||||
tile->data = res.data;
|
||||
|
||||
// Schedule tile parsing in another thread
|
||||
tile->reparse(worker, callback);
|
||||
} else {
|
||||
Log::Error(Event::HttpRequest, "[%s] tile loading failed: %s", url.c_str(), res.message.c_str());
|
||||
}
|
||||
// Schedule tile parsing in another thread
|
||||
reparse(worker, callback);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -90,18 +57,16 @@ void TileData::cancel() {
|
||||
}
|
||||
}
|
||||
|
||||
void TileData::reparse(uv::worker& worker, std::function<void()> callback)
|
||||
{
|
||||
// We're creating a new work request. The work request deletes itself after it executed
|
||||
// the after work handler
|
||||
new uv::work<util::ptr<TileData>>(
|
||||
worker,
|
||||
[this](util::ptr<TileData>& tile) {
|
||||
EnvironmentScope scope(env, ThreadType::TileWorker, "TileWorker_" + tile->name);
|
||||
void TileData::reparse(Worker& worker, std::function<void()> callback) {
|
||||
util::ptr<TileData> tile = shared_from_this();
|
||||
worker.send(
|
||||
[tile]() {
|
||||
EnvironmentScope scope(tile->env, ThreadType::TileWorker, "TileWorker_" + tile->name);
|
||||
tile->parse();
|
||||
},
|
||||
[callback](util::ptr<TileData>&) {
|
||||
[tile, callback]() {
|
||||
// `tile` is bound in this lambda to ensure that if it's the last owning pointer,
|
||||
// destruction happens on the map thread, not the worker thread.
|
||||
callback();
|
||||
},
|
||||
shared_from_this());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#ifndef MBGL_MAP_TILE_DATA
|
||||
#define MBGL_MAP_TILE_DATA
|
||||
|
||||
#include <mbgl/map/tile.hpp>
|
||||
#include <mbgl/map/tile_id.hpp>
|
||||
#include <mbgl/renderer/debug_bucket.hpp>
|
||||
#include <mbgl/geometry/debug_font_buffer.hpp>
|
||||
|
||||
@@ -12,12 +12,6 @@
|
||||
#include <string>
|
||||
#include <functional>
|
||||
|
||||
namespace uv {
|
||||
class worker;
|
||||
}
|
||||
|
||||
typedef struct uv_loop_s uv_loop_t;
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class Environment;
|
||||
@@ -25,6 +19,7 @@ class Painter;
|
||||
class SourceInfo;
|
||||
class StyleLayer;
|
||||
class Request;
|
||||
class Worker;
|
||||
|
||||
class TileData : public std::enable_shared_from_this<TileData>,
|
||||
private util::noncopyable {
|
||||
@@ -38,11 +33,11 @@ public:
|
||||
obsolete
|
||||
};
|
||||
|
||||
TileData(Tile::ID const &id, const SourceInfo &);
|
||||
TileData(const TileID&, const SourceInfo&);
|
||||
~TileData();
|
||||
|
||||
void request(uv::worker&, float pixelRatio, std::function<void ()> callback);
|
||||
void reparse(uv::worker&, std::function<void ()> callback);
|
||||
void request(Worker&, float pixelRatio, std::function<void ()> callback);
|
||||
void reparse(Worker&, std::function<void ()> callback);
|
||||
void cancel();
|
||||
const std::string toString() const;
|
||||
|
||||
@@ -55,7 +50,7 @@ public:
|
||||
virtual void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) = 0;
|
||||
virtual bool hasData(StyleLayer const &layer_desc) const = 0;
|
||||
|
||||
const Tile::ID id;
|
||||
const TileID id;
|
||||
const std::string name;
|
||||
std::atomic<State> state;
|
||||
|
||||
|
||||