diff --git a/.clang-format b/.clang-format index 0565d7379..86d562e74 100644 --- a/.clang-format +++ b/.clang-format @@ -2,9 +2,11 @@ Standard: Cpp11 IndentWidth: 4 AccessModifierOffset: -4 UseTab: Never -BinPackParameters: true +BinPackParameters: false AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false +AllowShortBlocksOnASingleLine: false +AllowShortFunctionsOnASingleLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: true AlwaysBreakTemplateDeclarations: true NamespaceIndentation: None @@ -12,5 +14,5 @@ PointerBindsToType: false SpacesInParentheses: false BreakBeforeBraces: Attach ColumnLimit: 100 -Cpp11BracedListStyle: true +Cpp11BracedListStyle: false SpacesBeforeTrailingComments: 1 diff --git a/.gitignore b/.gitignore index 98d9e2828..4a61e999e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,11 +3,14 @@ *.o *.actual.png *.diff.png +*.pyc /mason_packages -/config.gypi -/config-ios.gypi -/config-android.gypi +/config/*.gypi /build +/macosx/build +/linux/build +/test/build +/test/node_modules /include/mbgl/shader/shaders.hpp /src/shader/shaders_gl.cpp /src/shader/shaders_gles2.cpp diff --git a/.gitmodules b/.gitmodules index 588802377..8242fab9b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,3 +13,7 @@ [submodule "styles"] path = styles url = https://github.com/mapbox/mapbox-gl-styles.git + +[submodule "app/ios"] + path = app/ios + url = https://github.com/mapbox/mapbox-gl-cocoa.git \ No newline at end of file diff --git a/.mason b/.mason index 3833ddbd7..03869fd11 160000 --- a/.mason +++ b/.mason @@ -1 +1 @@ -Subproject commit 3833ddbd71dfed6d6325429518bb22bbf94b7a97 +Subproject commit 03869fd11e4bc619d3ba7e4f8a1f00d4612c90ea diff --git a/.travis.yml b/.travis.yml index 9dccffe9e..e42f9fde7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -53,13 +53,13 @@ before_install: - if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then sudo service postgresql stop; fi - source ./scripts/local_mason.sh - source ./scripts/travis_helper.sh +- source ./scripts/install_node.sh - source ./scripts/flags.sh - ./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 install: -- if [[ ${MASON_PLATFORM} != "android" ]]; then make config.gypi; fi - ulimit -c before_script: diff --git a/Makefile b/Makefile index 7d2fd5e6f..d26aa2fbb 100644 --- a/Makefile +++ b/Makefile @@ -1,143 +1,174 @@ BUILDTYPE ?= Release PYTHON ?= python -V ?= 1 PREFIX ?= /usr/local +ANDROID_ABI ?= arm-v7 JOBS ?= 1 ifeq ($(shell uname -s), Darwin) -PLATFORM ?= osx +HOST ?= osx endif -PLATFORM ?= linux +HOST ?= linux -.PHONY: all -all: mbgl-core mbgl-platform mbgl-headless +all: mbgl -config.gypi: configure - ./configure +include config/defaults.mk -config-ios.gypi: configure - MASON_PLATFORM=ios ./configure config-ios.gypi +#### Dependencies ############################################################## + +# Wildcard targets get removed after build by default, but we want to preserve the config. +.PRECIOUS: config/%.gypi +config/%.gypi: CMD = ./configure config/$*.gypi +config/%.gypi: configure + @$(ENV_$*) ./scripts/flock.py build/Configure.lock ./configure config/$*.gypi #### Library builds ############################################################ -.PHONY: mbgl-core -mbgl-core: build/mbgl/Makefile - $(MAKE) -C build/mbgl BUILDTYPE=$(BUILDTYPE) V=$(V) mbgl-core +.PRECOIUS: Makefile/mbgl +Makefile/mbgl: config/$(HOST).gypi + deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make -.PHONY: mbgl-platform -mbgl-platform: build/mbgl/Makefile - $(MAKE) -C build/mbgl BUILDTYPE=$(BUILDTYPE) V=$(V) mbgl-$(PLATFORM) +mbgl: Makefile/mbgl + $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) everything -.PHONY: mbgl-headless -mbgl-headless: build/mbgl/Makefile - $(MAKE) -C build/mbgl BUILDTYPE=$(BUILDTYPE) V=$(V) mbgl-headless +standalone: Makefile/mbgl + LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) standalone -.PHONY: install -install: build/mbgl/Makefile - $(MAKE) -C build/mbgl BUILDTYPE=$(BUILDTYPE) V=$(V) install - -#### Build scripts ############################################################# - -.PHONY: build/mbgl/Makefile -build/mbgl/Makefile: mapboxgl.gyp config.gypi - deps/run_gyp mapboxgl.gyp -Iconfig.gypi -Dplatform=$(PLATFORM) -Dinstall_prefix=$(PREFIX) --depth=. -Goutput_dir=.. --generator-output=./build/mbgl -f make - -.PHONY: build/test/Makefile -build/test/Makefile: test/test.gyp config.gypi - deps/run_gyp test/test.gyp -Iconfig.gypi -Dplatform=$(PLATFORM) --depth=. -Goutput_dir=.. --generator-output=./build/test -f make - -.PHONY: build/linux/Makefile -build/linux/Makefile: linux/mapboxgl-app.gyp config.gypi - deps/run_gyp linux/mapboxgl-app.gyp -Iconfig.gypi -Dplatform=linux --depth=. -Goutput_dir=.. --generator-output=./build/linux -f make - -.PHONY: build/macosx/Makefile -build/macosx/Makefile: macosx/mapboxgl-app.gyp config.gypi - deps/run_gyp macosx/mapboxgl-app.gyp -Iconfig.gypi -Dplatform=osx --depth=. -Goutput_dir=.. --generator-output=./build/macosx -f make - -.PHONY: build/render/Makefile -build/render/Makefile: bin/render.gyp config.gypi - deps/run_gyp bin/render.gyp -Iconfig.gypi -Dplatform=$(PLATFORM) --depth=. -Goutput_dir=.. --generator-output=./build/render -f make - -.PHONY: build/test/test.xcodeproj -build/test/test.xcodeproj: test/test.gyp config.gypi - deps/run_gyp test/test.gyp -Iconfig.gypi -Dplatform=$(PLATFORM) --depth=. -Goutput_dir=.. --generator-output=./build -f xcode - -.PHONY: build/macosx/mapboxgl-app.xcodeproj -build/macosx/mapboxgl-app.xcodeproj: macosx/mapboxgl-app.gyp config.gypi - deps/run_gyp macosx/mapboxgl-app.gyp -Iconfig.gypi -Dplatform=osx --depth=. --generator-output=./build -f xcode - -.PHONY: build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj -build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj: ios/mapbox-gl-cocoa/app/mapboxgl-app.gyp config-ios.gypi - deps/run_gyp ios/mapbox-gl-cocoa/app/mapboxgl-app.gyp -Iconfig-ios.gypi -Dplatform=ios --depth=. --generator-output=./build -f xcode - -.PHONY: build/linux/mapboxgl-app.xcodeproj -build/linux/mapboxgl-app.xcodeproj: linux/mapboxgl-app.gyp config.gypi - deps/run_gyp linux/mapboxgl-app.gyp -Iconfig.gypi -Dplatform=linux --depth=. --generator-output=./build -f xcode - -.PHONY: build/bin/render.xcodeproj - build/bin/render.xcodeproj: bin/render.gyp config.gypi - deps/run_gyp bin/render.gyp -Iconfig.gypi -Dplatform=$(PLATFORM) --depth=. --generator-output=./build -f xcode - -.PHONY: android -android: - ./scripts/local_mason.sh && \ - MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=$(MASON_ANDROID_ABI) ./.mason/mason env PATH && \ - export CXX="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env CXX`" && \ - export CC="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env CC`" && \ - export LD="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env LD`" && \ - export LINK="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env CXX`" && \ - export AR="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env AR`" && \ - export RANLIB="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env RANLIB`" && \ - export STRIP="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env STRIP`" && \ - export LDFLAGS="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env LDFLAGS` ${LDFLAGS}" && \ - export CFLAGS="`MASON_DIR=./.mason MASON_PLATFORM= MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env CFLAGS` ${CFLAGS}" && \ - export CPPFLAGS="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env CPPFLAGS` ${CPPFLAGS}" && \ - export PATH="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env PATH`:${PATH}" && \ - export JNIDIR="`MASON_DIR=./.mason MASON_PLATFORM=android MASON_ANDROID_ABI=${MASON_ANDROID_ABI} ./.mason/mason env JNIDIR`" && \ - MASON_PLATFORM=android MASON_ANDROID_ABI=$(MASON_ANDROID_ABI) ./configure config-android.gypi && \ - deps/run_gyp android/mapboxgl-app.gyp -Iconfig-android.gypi -Dplatform=android --depth=. --generator-output=./build/android/$(MASON_ANDROID_ABI) -f make-android && \ - $(MAKE) -C build/android/$(MASON_ANDROID_ABI) -j$(JOBS) BUILDTYPE=$(BUILDTYPE) V=$(V) androidapp && \ - BUILDTYPE=$(BUILDTYPE) MASON_ANDROID_ABI=$(MASON_ANDROID_ABI) ./android/scripts/copy-files.sh && \ - cd android/java && \ - ./gradlew --parallel-threads=$(JOBS) build - -##### Test cases ############################################################### - -test: build/test/Makefile - $(MAKE) -C build/test BUILDTYPE=$(BUILDTYPE) V=$(V) test - -test_%: build/test/Makefile - $(MAKE) -C build/test BUILDTYPE=$(BUILDTYPE) V=$(V) $* - (cd build/$(BUILDTYPE) && exec ./test_$*) - -# build Mac OS X project for Xcode -xtest: build/test/test.xcodeproj - open ./build/test/test.xcodeproj - -##### Makefile builds ########################################################## +install: Makefile/mbgl + LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) install -# Builds the linux app with make. -linux: build/linux/Makefile - $(MAKE) -C build/linux BUILDTYPE=$(BUILDTYPE) V=$(V) linuxapp +##### Test builds ############################################################## -# Executes the Linux binary -run-linux: linux - (cd build/$(BUILDTYPE) && ./mapbox-gl) +.PRECIOUS: Makefile/test +Makefile/test: test/test.gyp config/$(HOST).gypi + deps/run_gyp test/test.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make -# Builds the OS X app with make. -osx: build/macosx/Makefile - $(MAKE) -C build/macosx BUILDTYPE=$(BUILDTYPE) V=$(V) osxapp +test: Makefile/test + $(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 + 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 `sysctl -n hw.ncpu` + +xtest-%: xtest + ./scripts/run_tests.sh "build/osx/Build/Products/$(BUILDTYPE)/test" --gtest_filter=$* + + +#### Mac OS X application builds ############################################### + +.PRECIOUS: Makefile/osx +Makefile/osx: macosx/mapboxgl-app.gyp config/osx.gypi + deps/run_gyp macosx/mapboxgl-app.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f make + +.PHONY: osx run-osx +osx: Makefile/osx + $(MAKE) -C build/osx BUILDTYPE=$(BUILDTYPE) osxapp -# Executes the OS X binary run-osx: osx - build/$(BUILDTYPE)/Mapbox\ GL.app/Contents/MacOS/MAPBOX\ GL + "build/osx/$(BUILDTYPE)/Mapbox GL.app/Contents/MacOS/Mapbox GL" -# Builds the CLI render app -render: build/render/Makefile - $(MAKE) -C build/render BUILDTYPE=$(BUILDTYPE) V=$(V) mbgl-render -##### Xcode projects ########################################################### +.PRECIOUS: Xcode/osx +Xcode/osx: macosx/mapboxgl-app.gyp config/osx.gypi + 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: Xcode/osx + xcodebuild -project ./build/osx/macosx/mapboxgl-app.xcodeproj -configuration $(BUILDTYPE) -target osxapp -jobs `sysctl -n hw.ncpu` + +run-xosx: xosx + "build/osx/Build/Products/$(BUILDTYPE)/Mapbox GL.app/Contents/MacOS/Mapbox GL" + +# Legacy name +xproj: xosx-proj + + + +#### iOS application builds #################################################### + +.PRECIOUS: Xcode/ios +Xcode/ios: ios/mapbox-gl-cocoa/app/mapboxgl-app.gyp config/ios.gypi + deps/run_gyp ios/mapbox-gl-cocoa/app/mapboxgl-app.gyp $(CONFIG_ios) $(LIBS_ios) --generator-output=./build/ios -f xcode + +.PHONY: ios-proj ios run-ios +ios-proj: Xcode/ios + open ./build/ios/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj + +ios: Xcode/ios + xcodebuild -sdk iphonesimulator ARCHS=x86_64 -project ./build/ios/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj -configuration $(BUILDTYPE) -target iosapp -jobs `sysctl -n hw.ncpu` + +# Legacy name +iproj: ios-proj + + +#### Linux application builds ################################################## + +.PRECIOUS: Makefile/linux +Makefile/linux: linux/mapboxgl-app.gyp config/$(HOST).gypi + deps/run_gyp linux/mapboxgl-app.gyp $(CONFIG_$(HOST)) $(LIBS_linux) --generator-output=./build/$(HOST) -f make + +.PHONY: linux run-linux +linux: Makefile/linux + $(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 + 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 + +run-xlinux: xlinux + "build/osx/Build/Products/$(BUILDTYPE)/mapbox-gl" + +# Legacy name +lproj: xlinux-proj + + +#### Android libaries ######################################################### + +.PRECIOUS: Makefile/android-% +Makefile/android-%: CMD = deps/run_gyp android/mapboxgl-app.gyp $(CONFIG_android-$*) $(LIBS_android) --generator-output=./build/android-$* -f make-android +Makefile/android-%: config/android-%.gypi + @echo $(CMD) + @$(ENV_android-$*) $(CMD) + +# Builds a particular android architecture. +android-lib-%: Makefile/android-% + @$(ENV_android-$*) ./scripts/flock.py -v build/Android.lock $(MAKE) -C build/android-$* BUILDTYPE=$(BUILDTYPE) androidapp + +# Builds the selected/default Android library +android: android-lib-$(ANDROID_ABI) + cd android/java && ./gradlew --parallel-threads=$(JOBS) build + +# Builds all android architectures. +android-all: $(ANDROID_ABIS) + cd android/java && ./gradlew --parallel-threads=$(JOBS) build + + +##### Maintenace operations #################################################### .PHONY: clear_xcode_cache clear_xcode_cache: @@ -153,22 +184,6 @@ ifeq ($(PLATFORM), osx) fi endif -xproj: build/macosx/mapboxgl-app.xcodeproj - open ./build/macosx/mapboxgl-app.xcodeproj - -iproj: build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj - open ./build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj - -rproj: build/bin/render.xcodeproj - open ./build/bin/render.xcodeproj - -# build Linux project for Xcode (Runs on Mac OS X too, but without platform-specific code) -lproj: build/linux/mapboxgl-app.xcodeproj - open ./build/linux/mapboxgl-app.xcodeproj - - -##### Maintenace operations #################################################### - .PHONY: clear_sqlite_cache clear_sqlite_cache: ifeq ($(PLATFORM), osx) @@ -180,8 +195,12 @@ endif clean: clear_sqlite_cache clear_xcode_cache -find ./deps/gyp -name "*.pyc" -exec rm {} \; -rm -rf ./build/ - -rm -rf ./macosx/build/ - -rm -rf ./config.gypi ./config-ios.gypi ./config-android.gypi + -rm -rf ./macosx/build + -rm -rf ./linux/build + -rm -rf ./ios/mapbox-gl-cocoa/build + -rm -rf ./ios/mapbox-gl-cocoa/app/build + -rm -rf ./test/build + -rm -rf ./config/*.gypi -rm -rf ./android/java/build ./android/java/app/build ./android/java/lib/build -rm -rf ./android/java/lib/src/main/jniLibs ./android/java/lib/src/main/assets -rm -f ./android/test/features.zip diff --git a/README.md b/README.md index e88538aaa..ab24baff3 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ To create projects, you can run: - `make lproj`: Creates an Xcode project with platform-independent handlers for downloads and settings storage. This is what is also being built on Linux. - `make osx run-osx`: Builds and runs the OS X application on the command line with `xcodebuild`. - `make linux run-linux`: Builds and runs the Linux application with `make`. +- `make test-*` Builds and runs all tests. You can specify individual tests by replacing * with their name. Note that you can't have more than one project in Xcode open at a time since they the static library project is shared across the OS X, Linux and iOS project. diff --git a/android/cpp/jni.cpp b/android/cpp/jni.cpp index 9123d9aba..122ec794d 100644 --- a/android/cpp/jni.cpp +++ b/android/cpp/jni.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #pragma clang diagnostic ignored "-Wunused-parameter" @@ -380,19 +381,19 @@ jobject JNICALL nativeGetClasses(JNIEnv *env, jobject obj, jlong nativeMapViewPt } void JNICALL nativeSetDefaultTransitionDuration(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, - jlong milliseconds) { + jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetDefaultTransitionDuration"); assert(nativeMapViewPtr != 0); - assert(milliseconds >= 0); + assert(duration >= 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setDefaultTransitionDuration(milliseconds); + nativeMapView->getMap().setDefaultTransitionDuration(std::chrono::milliseconds(duration)); } jlong JNICALL nativeGetDefaultTransitionDuration(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeGetDefaultTransitionDuration"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getDefaultTransitionDuration(); + return std::chrono::duration_cast(nativeMapView->getMap().getDefaultTransitionDuration()).count(); } void JNICALL nativeSetStyleURL(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jstring url) { @@ -423,14 +424,14 @@ nativeSetAccessToken(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jstring a mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetAccessToken"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getFileSource().setAccessToken(std_string_from_jstring(env, accessToken)); + nativeMapView->getMap().setAccessToken(std_string_from_jstring(env, accessToken)); } jstring JNICALL nativeGetAccessToken(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeGetAccessToken"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return std_string_to_jstring(env, nativeMapView->getFileSource().getAccessToken()); + return std_string_to_jstring(env, nativeMapView->getMap().getAccessToken()); } void JNICALL nativeCancelTransitions(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { @@ -441,15 +442,15 @@ void JNICALL nativeCancelTransitions(JNIEnv *env, jobject obj, jlong nativeMapVi } void JNICALL nativeMoveBy(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble dx, jdouble dy, - jdouble duration) { + jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeMoveBy"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().moveBy(dx, dy, duration); + nativeMapView->getMap().moveBy(dx, dy, std::chrono::milliseconds(duration)); } void JNICALL nativeSetLonLat(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jobject lonLat, - jdouble duration) { + jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetLonLat"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); @@ -466,7 +467,7 @@ void JNICALL nativeSetLonLat(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, j return; } - nativeMapView->getMap().setLonLat(lon, lat, duration); + nativeMapView->getMap().setLonLat(lon, lat, std::chrono::milliseconds(duration)); } jobject JNICALL nativeGetLonLat(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { @@ -507,19 +508,19 @@ void JNICALL nativeResetPosition(JNIEnv *env, jobject obj, jlong nativeMapViewPt } void JNICALL nativeScaleBy(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble ds, jdouble cx, - jdouble cy, jdouble duration) { + jdouble cy, jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeScaleBy"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().scaleBy(ds, cx, cy, duration); + nativeMapView->getMap().scaleBy(ds, cx, cy, std::chrono::milliseconds(duration)); } void JNICALL nativeSetScale(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble scale, - jdouble cx, jdouble cy, jdouble duration) { + jdouble cx, jdouble cy, jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetScale"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setScale(scale, cx, cy, duration); + nativeMapView->getMap().setScale(scale, cx, cy, std::chrono::milliseconds(duration)); } jdouble JNICALL nativeGetScale(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { @@ -530,11 +531,11 @@ jdouble JNICALL nativeGetScale(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) } void JNICALL -nativeSetZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble zoom, jdouble duration) { +nativeSetZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble zoom, jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetZoom"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setZoom(zoom, duration); + nativeMapView->getMap().setZoom(zoom, std::chrono::milliseconds(duration)); } jdouble JNICALL nativeGetZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { @@ -545,7 +546,7 @@ jdouble JNICALL nativeGetZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) } void JNICALL nativeSetLonLatZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, - jobject lonLatZoom, jdouble duration) { + jobject lonLatZoom, jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetLonLatZoom"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); @@ -568,7 +569,7 @@ void JNICALL nativeSetLonLatZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPt return; } - nativeMapView->getMap().setLonLatZoom(lon, lat, zoom, duration); + nativeMapView->getMap().setLonLatZoom(lon, lat, zoom, std::chrono::milliseconds(duration)); } jobject JNICALL nativeGetLonLatZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) { @@ -623,19 +624,19 @@ jdouble JNICALL nativeGetMaxZoom(JNIEnv *env, jobject obj, jlong nativeMapViewPt } void JNICALL nativeRotateBy(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble sx, - jdouble sy, jdouble ex, jdouble ey, jdouble duration) { + jdouble sy, jdouble ex, jdouble ey, jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeRotateBy"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().rotateBy(sx, sy, ex, ey, duration); + nativeMapView->getMap().rotateBy(sx, sy, ex, ey, std::chrono::milliseconds(duration)); } void JNICALL nativeSetBearing(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble degrees, - jdouble duration) { + jlong duration) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetBearing"); assert(nativeMapViewPtr != 0); NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setBearing(degrees, duration); + nativeMapView->getMap().setBearing(degrees, std::chrono::milliseconds(duration)); } void JNICALL nativeSetBearing(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jdouble degrees, @@ -701,8 +702,9 @@ void JNICALL nativeSetReachability(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jboolean status) { mbgl::Log::Debug(mbgl::Event::JNI, "nativeSetReachability"); assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getFileSource().setReachability(status); + if (status) { + mbgl::NetworkStatus::Reachable(); + } } } @@ -889,20 +891,20 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"nativeGetAccessToken", "(J)Ljava/lang/String;", reinterpret_cast(&nativeGetAccessToken)}, {"nativeCancelTransitions", "(J)V", reinterpret_cast(&nativeCancelTransitions)}, - {"nativeMoveBy", "(JDDD)V", reinterpret_cast(&nativeMoveBy)}, - {"nativeSetLonLat", "(JLcom/mapbox/mapboxgl/lib/LonLat;D)V", + {"nativeMoveBy", "(JDDJ)V", reinterpret_cast(&nativeMoveBy)}, + {"nativeSetLonLat", "(JLcom/mapbox/mapboxgl/lib/LonLat;J)V", reinterpret_cast(&nativeSetLonLat)}, {"nativeGetLonLat", "(J)Lcom/mapbox/mapboxgl/lib/LonLat;", reinterpret_cast(&nativeGetLonLat)}, {"nativeStartPanning", "(J)V", reinterpret_cast(&nativeStartPanning)}, {"nativeStopPanning", "(J)V", reinterpret_cast(&nativeStopPanning)}, {"nativeResetPosition", "(J)V", reinterpret_cast(&nativeResetPosition)}, - {"nativeScaleBy", "(JDDDD)V", reinterpret_cast(&nativeScaleBy)}, - {"nativeSetScale", "(JDDDD)V", reinterpret_cast(&nativeSetScale)}, + {"nativeScaleBy", "(JDDDJ)V", reinterpret_cast(&nativeScaleBy)}, + {"nativeSetScale", "(JDDDJ)V", reinterpret_cast(&nativeSetScale)}, {"nativeGetScale", "(J)D", reinterpret_cast(&nativeGetScale)}, - {"nativeSetZoom", "(JDD)V", reinterpret_cast(&nativeSetZoom)}, + {"nativeSetZoom", "(JDJ)V", reinterpret_cast(&nativeSetZoom)}, {"nativeGetZoom", "(J)D", reinterpret_cast(&nativeGetZoom)}, - {"nativeSetLonLatZoom", "(JLcom/mapbox/mapboxgl/lib/LonLatZoom;D)V", + {"nativeSetLonLatZoom", "(JLcom/mapbox/mapboxgl/lib/LonLatZoom;J)V", reinterpret_cast(&nativeSetLonLatZoom)}, {"nativeGetLonLatZoom", "(J)Lcom/mapbox/mapboxgl/lib/LonLatZoom;", reinterpret_cast(&nativeGetLonLatZoom)}, @@ -911,10 +913,10 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"nativeStopPanning", "(J)V", reinterpret_cast(&nativeStopScaling)}, {"nativeGetMinZoom", "(J)D", reinterpret_cast(&nativeGetMinZoom)}, {"nativeGetMaxZoom", "(J)D", reinterpret_cast(&nativeGetMaxZoom)}, - {"nativeRotateBy", "(JDDDDD)V", reinterpret_cast(&nativeRotateBy)}, - {"nativeSetBearing", "(JDD)V", + {"nativeRotateBy", "(JDDDDJ)V", reinterpret_cast(&nativeRotateBy)}, + {"nativeSetBearing", "(JDJ)V", reinterpret_cast( - static_cast( + static_cast( &nativeSetBearing))}, {"nativeSetBearing", "(JDDD)V", reinterpret_cast( diff --git a/android/cpp/native_map_view.cpp b/android/cpp/native_map_view.cpp index e177fd497..cd3445e24 100644 --- a/android/cpp/native_map_view.cpp +++ b/android/cpp/native_map_view.cpp @@ -54,7 +54,8 @@ void log_gl_string(GLenum name, const char *label) { NativeMapView::NativeMapView(JNIEnv *env, jobject obj_) : mbgl::View(*this), - fileSource(mbgl::platform::defaultCacheDatabase()), + fileCache(mbgl::android::cachePath + "/mbgl-cache.db"), + fileSource(&fileCache), map(*this, fileSource) { mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::NativeMapView"); @@ -140,7 +141,7 @@ void NativeMapView::notify() { mbgl::Map &NativeMapView::getMap() { return map; } -mbgl::CachingHTTPFileSource &NativeMapView::getFileSource() { return fileSource; } +mbgl::DefaultFileSource &NativeMapView::getFileSource() { return fileSource; } bool NativeMapView::inEmulator() { // Detect if we are in emulator @@ -718,7 +719,7 @@ void NativeMapView::resume() { } } -void NativeMapView::notifyMapChange(mbgl::MapChange, mbgl::timestamp) { +void NativeMapView::notifyMapChange(mbgl::MapChange, std::chrono::steady_clock::duration) { mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::notifyMapChange()"); assert(vm != nullptr); diff --git a/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/MapView.java b/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/MapView.java index 36e530a17..4c51df654 100644 --- a/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/MapView.java +++ b/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/MapView.java @@ -46,6 +46,9 @@ public class MapView extends SurfaceView { // Tag used for logging private static final String TAG = "MapView"; + // Used for animation + private static final long ANIMATION_DURATION = 300; + // Used for saving instance state private static final String STATE_CENTER_COORDINATE = "centerCoordinate"; private static final String STATE_CENTER_DIRECTION = "centerDirection"; @@ -188,7 +191,7 @@ public class MapView extends SurfaceView { if (!isInEditMode()) { if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) { mZoomButtonsController = new ZoomButtonsController(this); - mZoomButtonsController.setZoomSpeed(300); + mZoomButtonsController.setZoomSpeed(ANIMATION_DURATION); mZoomButtonsController.setOnZoomListener(new OnZoomListener()); } @@ -213,7 +216,7 @@ public class MapView extends SurfaceView { } public void setCenterCoordinate(LonLat centerCoordinate, boolean animated) { - double duration = animated ? 0.3 : 0.0; + long duration = animated ? ANIMATION_DURATION : 0; mNativeMapView.setLonLat(centerCoordinate, duration); } @@ -223,7 +226,7 @@ public class MapView extends SurfaceView { public void setCenterCoordinate(LonLatZoom centerCoordinate, boolean animated) { - double duration = animated ? 0.3 : 0.0; + long duration = animated ? ANIMATION_DURATION : 0; mNativeMapView.setLonLatZoom(centerCoordinate, duration); } @@ -243,8 +246,7 @@ public class MapView extends SurfaceView { } public void setDirection(double direction, boolean animated) { - double duration = animated ? 0.3 : 0.0; - + long duration = animated ? ANIMATION_DURATION : 0; mNativeMapView.setBearing(-direction, duration); } @@ -265,7 +267,7 @@ public class MapView extends SurfaceView { } public void setZoomLevel(double zoomLevel, boolean animated) { - double duration = animated ? 0.3 : 0.0; + long duration = animated ? ANIMATION_DURATION : 0; mNativeMapView.setZoom(zoomLevel, duration); } @@ -565,10 +567,10 @@ public class MapView extends SurfaceView { mNativeMapView.cancelTransitions(); if (zoomIn) { - mNativeMapView.scaleBy(2.0, x / mScreenDensity, y / mScreenDensity, 0.3); + mNativeMapView.scaleBy(2.0, x / mScreenDensity, y / mScreenDensity, ANIMATION_DURATION); } else { // TODO two finger tap zoom out - mNativeMapView.scaleBy(0.5, x / mScreenDensity, y / mScreenDensity, 0.3); + mNativeMapView.scaleBy(0.5, x / mScreenDensity, y / mScreenDensity, ANIMATION_DURATION); } } @@ -695,7 +697,7 @@ public class MapView extends SurfaceView { // Cancel any animation mNativeMapView.cancelTransitions(); - mNativeMapView.moveBy(velocityX * duration / 2.0 / mScreenDensity, velocityY * duration / 2.0 / mScreenDensity, duration); + mNativeMapView.moveBy(velocityX * duration / 2.0 / mScreenDensity, velocityY * duration / 2.0 / mScreenDensity, (long)(duration * 1000.0f)); return true; } diff --git a/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/NativeMapView.java b/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/NativeMapView.java index 845decbe8..de8e8df75 100644 --- a/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/NativeMapView.java +++ b/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/NativeMapView.java @@ -234,18 +234,18 @@ class NativeMapView { } public void moveBy(double dx, double dy) { - moveBy(dx, dy, 0.0); + moveBy(dx, dy, 0); } - public void moveBy(double dx, double dy, double duration) { + public void moveBy(double dx, double dy, long duration) { nativeMoveBy(mNativeMapViewPtr, dx, dy, duration); } public void setLonLat(LonLat lonLat) { - setLonLat(lonLat, 0.0); + setLonLat(lonLat, 0); } - public void setLonLat(LonLat lonLat, double duration) { + public void setLonLat(LonLat lonLat, long duration) { nativeSetLonLat(mNativeMapViewPtr, lonLat, duration); } @@ -270,10 +270,10 @@ class NativeMapView { } public void scaleBy(double ds, double cx, double cy) { - scaleBy(ds, cx, cy, 0.0); + scaleBy(ds, cx, cy, 0); } - public void scaleBy(double ds, double cx, double cy, double duration) { + public void scaleBy(double ds, double cx, double cy, long duration) { nativeScaleBy(mNativeMapViewPtr, ds, cx, cy, duration); } @@ -282,10 +282,10 @@ class NativeMapView { } public void setScale(double scale, double cx, double cy) { - setScale(scale, cx, cy, 0.0); + setScale(scale, cx, cy, 0); } - public void setScale(double scale, double cx, double cy, double duration) { + public void setScale(double scale, double cx, double cy, long duration) { nativeSetScale(mNativeMapViewPtr, scale, cx, cy, duration); } @@ -294,10 +294,10 @@ class NativeMapView { } public void setZoom(double zoom) { - setZoom(zoom, 0.0); + setZoom(zoom, 0); } - public void setZoom(double zoom, double duration) { + public void setZoom(double zoom, long duration) { nativeSetZoom(mNativeMapViewPtr, zoom, duration); } @@ -306,10 +306,10 @@ class NativeMapView { } public void setLonLatZoom(LonLatZoom lonLatZoom) { - setLonLatZoom(lonLatZoom, 0.0); + setLonLatZoom(lonLatZoom, 0); } - public void setLonLatZoom(LonLatZoom lonLatZoom, double duration) { + public void setLonLatZoom(LonLatZoom lonLatZoom, long duration) { nativeSetLonLatZoom(mNativeMapViewPtr, lonLatZoom, duration); } @@ -338,19 +338,19 @@ class NativeMapView { } public void rotateBy(double sx, double sy, double ex, double ey) { - rotateBy(sx, sy, ex, ey, 0.0); + rotateBy(sx, sy, ex, ey, 0); } public void rotateBy(double sx, double sy, double ex, double ey, - double duration) { + long duration) { nativeRotateBy(mNativeMapViewPtr, sx, sy, ex, ey, duration); } public void setBearing(double degrees) { - setBearing(degrees, 0.0); + setBearing(degrees, 0); } - public void setBearing(double degrees, double duration) { + public void setBearing(double degrees, long duration) { nativeSetBearing(mNativeMapViewPtr, degrees, duration); } @@ -468,7 +468,7 @@ class NativeMapView { private native List nativeGetClasses(long nativeMapViewPtr); private native void nativeSetDefaultTransitionDuration( - long nativeMapViewPtr, long milliseconds); + long nativeMapViewPtr, long duration); private native long nativeGetDefaultTransitionDuration(long nativeMapViewPtr); @@ -486,10 +486,10 @@ class NativeMapView { private native void nativeCancelTransitions(long nativeMapViewPtr); private native void nativeMoveBy(long nativeMapViewPtr, double dx, - double dy, double duration); + double dy, long duration); private native void nativeSetLonLat(long nativeMapViewPtr, LonLat lonLat, - double duration); + long duration); private native LonLat nativeGetLonLat(long nativeMapViewPtr); @@ -500,20 +500,20 @@ class NativeMapView { private native void nativeResetPosition(long nativeMapViewPtr); private native void nativeScaleBy(long nativeMapViewPtr, double ds, - double cx, double cy, double duration); + double cx, double cy, long duration); private native void nativeSetScale(long nativeMapViewPtr, double scale, - double cx, double cy, double duration); + double cx, double cy, long duration); private native double nativeGetScale(long nativeMapViewPtr); private native void nativeSetZoom(long nativeMapViewPtr, double zoom, - double duration); + long duration); private native double nativeGetZoom(long nativeMapViewPtr); private native void nativeSetLonLatZoom(long nativeMapViewPtr, - LonLatZoom lonLatZoom, double duration); + LonLatZoom lonLatZoom, long duration); private native LonLatZoom nativeGetLonLatZoom(long nativeMapViewPtr); @@ -528,10 +528,10 @@ class NativeMapView { private native double nativeGetMaxZoom(long nativeMapViewPtr); private native void nativeRotateBy(long nativeMapViewPtr, double sx, - double sy, double ex, double ey, double duration); + double sy, double ex, double ey, long duration); private native void nativeSetBearing(long nativeMapViewPtr, double degrees, - double duration); + long duration); private native void nativeSetBearing(long nativeMapViewPtr, double degrees, double cx, double cy); diff --git a/android/mapboxgl-app.gyp b/android/mapboxgl-app.gyp index 60ec22164..5933db4c1 100644 --- a/android/mapboxgl-app.gyp +++ b/android/mapboxgl-app.gyp @@ -3,16 +3,26 @@ '../gyp/common.gypi', ], 'targets': [ - { - 'target_name': 'androidapp', + { 'target_name': 'android-lib', 'product_name': 'mapbox-gl', 'type': 'shared_library', + 'hard_dependency': 1, + + 'dependencies': [ + '../mbgl.gyp:core', + '../mbgl.gyp:platform-<(platform_lib)', + '../mbgl.gyp:http-<(http_lib)', + '../mbgl.gyp:asset-<(asset_lib)', + '../mbgl.gyp:cache-<(cache_lib)', + ], + 'sources': [ './cpp/native_map_view.cpp', './cpp/jni.cpp', ], + 'cflags_cc': [ - '-I<(boost_root)/include', + '<@(boost_cflags)', ], 'libraries': [ '<@(openssl_static_libs)', @@ -50,15 +60,35 @@ 'libraries': [ '<@(ldflags)' ], }] ], - 'dependencies': [ - '../mapboxgl.gyp:mbgl-standalone', - '../mapboxgl.gyp:mbgl-android', - '../mapboxgl.gyp:copy_certificate_bundle', + }, + + + { 'target_name': 'androidapp', + 'type': 'none', + 'hard_dependency': 1, + + 'variables': { + 'pwd': '../build.log; then echo 'ANDROID BUILD PASSED' diff --git a/bin/render.cpp b/bin/render.cpp index ba17498c8..827f247d6 100644 --- a/bin/render.cpp +++ b/bin/render.cpp @@ -9,7 +9,8 @@ #include #include -#include +#include +#include #if __APPLE__ #include @@ -35,7 +36,7 @@ int main(int argc, char *argv[]) { int height = 256; double pixelRatio = 1.0; std::string output = "out.png"; - std::string cache = "cache.sqlite"; + std::string cache_file = "cache.sqlite"; std::vector classes; std::string token; @@ -51,7 +52,7 @@ int main(int argc, char *argv[]) { ("class,c", po::value(&classes)->value_name("name"), "Class name") ("token,t", po::value(&token)->value_name("key")->default_value(token), "Mapbox access token") ("output,o", po::value(&output)->value_name("file")->default_value(output), "Output file name") - ("cache,d", po::value(&cache)->value_name("file")->default_value(cache), "Cache database file name") + ("cache,d", po::value(&cache_file)->value_name("file")->default_value(cache_file), "Cache database file name") ; try { @@ -74,7 +75,8 @@ int main(int argc, char *argv[]) { Log::Set(); #endif - CachingHTTPFileSource fileSource(cache); + mbgl::SQLiteCache cache(cache_file); + mbgl::DefaultFileSource fileSource(&cache); // Try to load the token from the environment. if (!token.size()) { @@ -84,14 +86,15 @@ int main(int argc, char *argv[]) { } } - // Set access token if present - if (token.size()) { - fileSource.setAccessToken(std::string(token)); - } HeadlessView view; Map map(view, fileSource); + // Set access token if present + if (token.size()) { + map.setAccessToken(std::string(token)); + } + map.setStyleJSON(style, "."); map.setClasses(classes); diff --git a/bin/render.gyp b/bin/render.gyp index 0a41b02a8..316a7f3ed 100644 --- a/bin/render.gyp +++ b/bin/render.gyp @@ -3,51 +3,54 @@ '../gyp/common.gypi', ], 'targets': [ - { - 'target_name': 'mbgl-render', + { 'target_name': 'mbgl-render', 'product_name': 'mbgl-render', 'type': 'executable', + + 'dependencies': [ + '../mbgl.gyp:core', + '../mbgl.gyp:platform-<(platform_lib)', + '../mbgl.gyp:headless-<(headless_lib)', + '../mbgl.gyp:http-<(http_lib)', + '../mbgl.gyp:asset-<(asset_lib)', + '../mbgl.gyp:cache-<(cache_lib)', + '../mbgl.gyp:copy_certificate_bundle', + ], + + 'include_dirs': [ + '../src', + ], + 'sources': [ './render.cpp', ], + 'variables' : { - 'cflags': [ - '<@(uv_cflags)', - '<@(png_cflags)', - '-I<(boost_root)/include', + 'cflags_cc': [ + '<@(glfw3_cflags)', + '<@(boost_cflags)', ], 'ldflags': [ '<@(glfw3_ldflags)', - '<@(uv_ldflags)', - '<@(sqlite3_static_libs)', - '<@(sqlite3_ldflags)', - '<@(curl_ldflags)', - '<@(png_ldflags)', - '<@(uv_static_libs)', - '-L<(boost_root)/lib', + '<@(boost_ldflags)', '-lboost_program_options' ], + 'libraries': [ + '<@(glfw3_static_libs)', + ], }, + 'conditions': [ - # add libuv include path and OpenGL libs - ['OS == "mac"', - { - 'xcode_settings': { - 'OTHER_CPLUSPLUSFLAGS': ['<@(cflags)'], - 'OTHER_LDFLAGS': ['<@(ldflags)'], - }, - }, - { - 'cflags': ['<@(cflags)'], - 'libraries': ['<@(ldflags)'], - }], - ], - 'include_dirs': [ '../src' ], - 'dependencies': [ - '../mapboxgl.gyp:mbgl-standalone', - '../mapboxgl.gyp:mbgl-headless', - '../mapboxgl.gyp:mbgl-<(platform)', - '../mapboxgl.gyp:copy_certificate_bundle', + ['OS == "mac"', { + 'libraries': [ '<@(libraries)' ], + 'xcode_settings': { + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], + 'OTHER_LDFLAGS': [ '<@(ldflags)' ], + } + }, { + 'cflags_cc': [ '<@(cflags_cc)' ], + 'libraries': [ '<@(libraries)', '<@(ldflags)' ], + }] ], }, ], diff --git a/config/defaults.mk b/config/defaults.mk new file mode 100644 index 000000000..2aa11ccbe --- /dev/null +++ b/config/defaults.mk @@ -0,0 +1,67 @@ + +#### Configuration defaults #################################################### + +ENV_osx = MASON_PLATFORM=osx +CONFIG_osx = -Dhost=osx -Iconfig/osx.gypi -Dinstall_prefix=$(PREFIX) +LIBS_osx = -Dheadless_lib=$(word 1,$(HEADLESS) cgl) +LIBS_osx += -Dplatform_lib=$(word 1,$(PLATFORM) osx) +LIBS_osx += -Dasset_lib=$(word 1,$(ASSET) fs) +LIBS_osx += -Dhttp_lib=$(word 1,$(HTTP) nsurl) +LIBS_osx += -Dcache_lib=$(word 1,$(CACHE) sqlite) +LIBS_osx += --depth=. -Goutput_dir=. + + +ENV_ios = MASON_PLATFORM=ios +CONFIG_ios = -Dhost=ios -Iconfig/ios.gypi -Dinstall_prefix=$(PREFIX) +LIBS_ios = -Dheadless_lib=none +LIBS_ios += -Dplatform_lib=$(word 1,$(PLATFORM) ios) +LIBS_ios += -Dasset_lib=$(word 1,$(ASSET) fs) +LIBS_ios += -Dhttp_lib=$(word 1,$(HTTP) nsurl) +LIBS_ios += -Dcache_lib=$(word 1,$(CACHE) sqlite) +LIBS_ios += --depth=. -Goutput_dir=. + + +ENV_linux = MASON_PLATFORM=linux +CONFIG_linux = -Dhost=linux -Iconfig/linux.gypi -Dinstall_prefix=$(PREFIX) +LIBS_linux = -Dheadless_lib=$(word 1,$(HEADLESS) glx) +LIBS_linux += -Dplatform_lib=$(word 1,$(PLATFORM) linux) +LIBS_linux += -Dasset_lib=$(word 1,$(ASSET) fs) +LIBS_linux += -Dhttp_lib=$(word 1,$(HTTP) curl) +LIBS_linux += -Dcache_lib=$(word 1,$(CACHE) sqlite) +LIBS_linux += --depth=. -Goutput_dir=. + +ANDROID_ABIS += android-lib-arm-v8 +ENV_android-arm-v8 = $(shell MASON_ANDROID_ABI=arm-v8 ./scripts/android_env.sh) +CONFIG_android-arm-v8 = -Dhost=android -Iconfig/android-arm-v8.gypi + +ANDROID_ABIS += android-lib-arm-v7 +ENV_android-arm-v7 = $(shell MASON_ANDROID_ABI=arm-v7 ./scripts/android_env.sh) +CONFIG_android-arm-v7 = -Dhost=android -Iconfig/android-arm-v7.gypi + +ANDROID_ABIS += android-lib-arm-v5 +ENV_android-arm-v5 = $(shell MASON_ANDROID_ABI=arm-v5 ./scripts/android_env.sh) +CONFIG_android-arm-v5 = -Dhost=android -Iconfig/android-arm-v5.gypi + +ANDROID_ABIS += android-lib-x86 +ENV_android-x86 = $(shell MASON_ANDROID_ABI=x86 ./scripts/android_env.sh) +CONFIG_android-x86 = -Dhost=android -Iconfig/android-x86.gypi + +# OpenSSL build is incomplete. +# ANDROID_ABIS += android-lib-x86-64 +# ENV_android-x86-64 = $(shell MASON_ANDROID_ABI=x86-64 ./scripts/android_env.sh) +# CONFIG_android-x86-64 = -Dhost=android -Iconfig/android-x86-64.gypi + +ANDROID_ABIS += android-lib-mips +ENV_android-mips = $(shell MASON_ANDROID_ABI=mips ./scripts/android_env.sh) +CONFIG_android-mips = -Dhost=android -Iconfig/android-mips.gypi + +ANDROID_ABIS += android-lib-mips-64 +ENV_android-mips-64 = $(shell MASON_ANDROID_ABI=mips-64 ./scripts/android_env.sh) +CONFIG_android-mips-64 = -Dhost=android -Iconfig/android-mips-64.gypi + +LIBS_android = -Dheadless_lib=none +LIBS_android += -Dplatform_lib=$(word 1,$(PLATFORM) android) +LIBS_android += -Dasset_lib=$(word 1,$(ASSET) zip) +LIBS_android += -Dhttp_lib=$(word 1,$(HTTP) curl) +LIBS_android += -Dcache_lib=$(word 1,$(CACHE) sqlite) +LIBS_android += --depth=. -Goutput_dir=. diff --git a/configure b/configure index 14982c211..fec0bfd31 100755 --- a/configure +++ b/configure @@ -3,7 +3,7 @@ set -e set -o pipefail -CONFIG_FILE=${1:-config.gypi} +CONFIG_FILE=$1 if [ `uname -s` = 'Darwin' ]; then MASON_PLATFORM=${MASON_PLATFORM:-osx} @@ -46,11 +46,24 @@ case ${MASON_PLATFORM} in ZLIB_VERSION=system BOOST_VERSION=system NUNICODE_VERSION=1.5.1 + LIBZIP_VERSION=0.11.2 ;; esac function abort { >&2 echo -e "\033[1m\033[31m$1\033[0m"; exit 1; } +if [ -z ${CONFIG_FILE} ]; then + abort 'You need to specify an output path for the configuration file' +fi + +if [[ ${MASON_PLATFORM} = 'android' && -z ${MASON_ANDROID_ABI} ]]; then + abort 'You need to specify an ABI for android platforms' +fi + +echo -n "MASON_PLATFORM=${MASON_PLATFORM} " +if [ ${MASON_PLATFORM} = 'android' ]; then echo -n "MASON_ANDROID_ABI=${MASON_ANDROID_ABI} " ; fi +echo $0 $@ + PYTHON=`which python || abort 'Cannot find python'` >&2 echo -en "\033[1m\033[32m* Using " @@ -72,7 +85,7 @@ LN=$'\n' CONFIG="# Do not edit. Generated by the configure script. { 'target_defaults': { - 'cflags': [], + 'cflags%': [], 'default_configuration': 'Release', 'defines': [], 'include_dirs': [], @@ -84,79 +97,78 @@ CONFIG="# Do not edit. Generated by the configure script. if [ ! -z ${BOOST_VERSION} ]; then mason install boost ${BOOST_VERSION} - CONFIG+=" 'boost_root': '$(mason prefix boost ${BOOST_VERSION})',"$LN + CONFIG+=" 'boost_cflags%': $(quote_flags $(mason cflags boost ${BOOST_VERSION})),"$LN + CONFIG+=" 'boost_ldflags%': $(quote_flags $(mason ldflags boost ${BOOST_VERSION})),"$LN fi if [ ! -z ${OPENSSL_VERSION} ]; then mason install openssl ${OPENSSL_VERSION} - CONFIG+=" 'openssl_static_libs': $(quote_flags $(mason static_libs openssl ${OPENSSL_VERSION})),"$LN - CONFIG+=" 'openssl_cflags': $(quote_flags $(mason cflags openssl ${OPENSSL_VERSION})),"$LN - CONFIG+=" 'openssl_ldflags': $(quote_flags $(mason ldflags openssl ${OPENSSL_VERSION})),"$LN + CONFIG+=" 'openssl_static_libs%': $(quote_flags $(mason static_libs openssl ${OPENSSL_VERSION})),"$LN + CONFIG+=" 'openssl_cflags%': $(quote_flags $(mason cflags openssl ${OPENSSL_VERSION})),"$LN + CONFIG+=" 'openssl_ldflags%': $(quote_flags $(mason ldflags openssl ${OPENSSL_VERSION})),"$LN fi if [ ! -z ${LIBCURL_VERSION} ]; then mason install libcurl ${LIBCURL_VERSION} - CONFIG+=" 'curl_static_libs': $(quote_flags $(mason static_libs libcurl ${LIBCURL_VERSION})),"$LN - CONFIG+=" 'curl_cflags': $(quote_flags $(mason cflags libcurl ${LIBCURL_VERSION})),"$LN - CONFIG+=" 'curl_ldflags': $(quote_flags $(mason ldflags libcurl ${LIBCURL_VERSION})),"$LN -else - CONFIG+=" 'curl_static_libs': [],"$LN + CONFIG+=" 'curl_static_libs%': $(quote_flags $(mason static_libs libcurl ${LIBCURL_VERSION})),"$LN + CONFIG+=" 'curl_cflags%': $(quote_flags $(mason cflags libcurl ${LIBCURL_VERSION})),"$LN + CONFIG+=" 'curl_ldflags%': $(quote_flags $(mason ldflags libcurl ${LIBCURL_VERSION})),"$LN fi if [ ! -z ${GLFW_VERSION} ]; then mason install glfw ${GLFW_VERSION} - CONFIG+=" 'glfw3_static_libs': $(quote_flags $(mason static_libs glfw ${GLFW_VERSION})),"$LN - CONFIG+=" 'glfw3_cflags': $(quote_flags $(mason cflags glfw ${GLFW_VERSION})),"$LN - CONFIG+=" 'glfw3_ldflags': $(quote_flags $(mason ldflags glfw ${GLFW_VERSION})),"$LN + CONFIG+=" 'glfw3_static_libs%': $(quote_flags $(mason static_libs glfw ${GLFW_VERSION})),"$LN + CONFIG+=" 'glfw3_cflags%': $(quote_flags $(mason cflags glfw ${GLFW_VERSION})),"$LN + CONFIG+=" 'glfw3_ldflags%': $(quote_flags $(mason ldflags glfw ${GLFW_VERSION})),"$LN fi if [ ! -z ${LIBPNG_VERSION} ]; then mason install libpng ${LIBPNG_VERSION} - CONFIG+=" 'png_static_libs': $(quote_flags $(mason static_libs libpng ${LIBPNG_VERSION})),"$LN - CONFIG+=" 'png_cflags': $(quote_flags $(mason cflags libpng ${LIBPNG_VERSION})),"$LN - CONFIG+=" 'png_ldflags': $(quote_flags $(mason ldflags libpng ${LIBPNG_VERSION})),"$LN + CONFIG+=" 'png_static_libs%': $(quote_flags $(mason static_libs libpng ${LIBPNG_VERSION})),"$LN + CONFIG+=" 'png_cflags%': $(quote_flags $(mason cflags libpng ${LIBPNG_VERSION})),"$LN + CONFIG+=" 'png_ldflags%': $(quote_flags $(mason ldflags libpng ${LIBPNG_VERSION})),"$LN fi if [ ! -z ${LIBJPEG_VERSION} ]; then mason install jpeg ${LIBJPEG_VERSION} - CONFIG+=" 'jpeg_static_libs': $(quote_flags $(mason static_libs jpeg ${LIBJPEG_VERSION})),"$LN - CONFIG+=" 'jpeg_cflags': $(quote_flags $(mason cflags jpeg ${LIBJPEG_VERSION})),"$LN - CONFIG+=" 'jpeg_ldflags': $(quote_flags $(mason ldflags jpeg ${LIBJPEG_VERSION})),"$LN + CONFIG+=" 'jpeg_static_libs%': $(quote_flags $(mason static_libs jpeg ${LIBJPEG_VERSION})),"$LN + CONFIG+=" 'jpeg_cflags%': $(quote_flags $(mason cflags jpeg ${LIBJPEG_VERSION})),"$LN + CONFIG+=" 'jpeg_ldflags%': $(quote_flags $(mason ldflags jpeg ${LIBJPEG_VERSION})),"$LN fi if [ ! -z ${SQLITE_VERSION} ]; then mason install sqlite ${SQLITE_VERSION} - CONFIG+=" 'sqlite3_static_libs': $(quote_flags $(mason static_libs sqlite ${SQLITE_VERSION})),"$LN - CONFIG+=" 'sqlite3_cflags': $(quote_flags $(mason cflags sqlite ${SQLITE_VERSION})),"$LN - CONFIG+=" 'sqlite3_ldflags': $(quote_flags $(mason ldflags sqlite ${SQLITE_VERSION})),"$LN + CONFIG+=" 'sqlite3_static_libs%': $(quote_flags $(mason static_libs sqlite ${SQLITE_VERSION})),"$LN + CONFIG+=" 'sqlite3_cflags%': $(quote_flags $(mason cflags sqlite ${SQLITE_VERSION})),"$LN + CONFIG+=" 'sqlite3_ldflags%': $(quote_flags $(mason ldflags sqlite ${SQLITE_VERSION})),"$LN fi if [ ! -z ${LIBUV_VERSION} ]; then mason install libuv ${LIBUV_VERSION} - CONFIG+=" 'uv_static_libs': $(quote_flags $(mason static_libs libuv ${LIBUV_VERSION})),"$LN - CONFIG+=" 'uv_cflags': $(quote_flags $(mason cflags libuv ${LIBUV_VERSION})),"$LN - CONFIG+=" 'uv_ldflags': $(quote_flags $(mason ldflags libuv ${LIBUV_VERSION})),"$LN + CONFIG+=" 'uv_static_libs%': $(quote_flags $(mason static_libs libuv ${LIBUV_VERSION})),"$LN + CONFIG+=" 'uv_cflags%': $(quote_flags $(mason cflags libuv ${LIBUV_VERSION})),"$LN + CONFIG+=" 'uv_ldflags%': $(quote_flags $(mason ldflags libuv ${LIBUV_VERSION})),"$LN fi if [ ! -z ${ZLIB_VERSION} ]; then mason install zlib ${ZLIB_VERSION} - CONFIG+=" 'zlib_static_libs': $(quote_flags $(mason static_libs zlib ${ZLIB_VERSION})),"$LN - CONFIG+=" 'zlib_cflags': $(quote_flags $(mason cflags zlib ${ZLIB_VERSION})),"$LN - CONFIG+=" 'zlib_ldflags': $(quote_flags $(mason ldflags zlib ${ZLIB_VERSION})),"$LN + CONFIG+=" 'zlib_static_libs%': $(quote_flags $(mason static_libs zlib ${ZLIB_VERSION})),"$LN + CONFIG+=" 'zlib_cflags%': $(quote_flags $(mason cflags zlib ${ZLIB_VERSION})),"$LN + CONFIG+=" 'zlib_ldflags%': $(quote_flags $(mason ldflags zlib ${ZLIB_VERSION})),"$LN fi if [ ! -z ${NUNICODE_VERSION} ]; then mason install nunicode ${NUNICODE_VERSION} - CONFIG+=" 'nu_static_libs': $(quote_flags $(mason static_libs nunicode ${NUNICODE_VERSION})),"$LN - CONFIG+=" 'nu_cflags': $(quote_flags $(mason cflags nunicode ${NUNICODE_VERSION})),"$LN - CONFIG+=" 'nu_ldflags': $(quote_flags $(mason ldflags nunicode ${NUNICODE_VERSION})),"$LN + CONFIG+=" 'nu_static_libs%': $(quote_flags $(mason static_libs nunicode ${NUNICODE_VERSION})),"$LN + CONFIG+=" 'nu_cflags%': $(quote_flags $(mason cflags nunicode ${NUNICODE_VERSION})),"$LN + CONFIG+=" 'nu_ldflags%': $(quote_flags $(mason ldflags nunicode ${NUNICODE_VERSION})),"$LN fi if [ ! -z ${LIBZIP_VERSION} ]; then mason install libzip ${LIBZIP_VERSION} - CONFIG+=" 'zip_static_libs': $(quote_flags $(mason static_libs libzip ${LIBZIP_VERSION})),"$LN - CONFIG+=" 'zip_cflags': $(quote_flags $(mason cflags libzip ${LIBZIP_VERSION})),"$LN - CONFIG+=" 'zip_ldflags': $(quote_flags $(mason ldflags libzip ${LIBZIP_VERSION})),"$LN + CONFIG+=" 'zip_static_libs%': $(quote_flags $(mason static_libs libzip ${LIBZIP_VERSION})),"$LN + CONFIG+=" 'zip_cflags%': $(quote_flags $(mason cflags libzip ${LIBZIP_VERSION})),"$LN + CONFIG+=" 'zip_ldflags%': $(quote_flags $(mason ldflags libzip ${LIBZIP_VERSION})),"$LN fi CONFIG+=" } @@ -164,5 +176,4 @@ CONFIG+=" } " echo "${CONFIG}" > ${CONFIG_FILE} - cat ${CONFIG_FILE} diff --git a/gyp/asset-fs.gypi b/gyp/asset-fs.gypi new file mode 100644 index 000000000..0606eaf7f --- /dev/null +++ b/gyp/asset-fs.gypi @@ -0,0 +1,52 @@ +{ + 'targets': [ + { 'target_name': 'asset-fs', + 'product_name': 'mbgl-asset-fs', + 'type': 'static_library', + 'standalone_static_library': 1, + 'hard_dependency': 1, + + 'sources': [ + '../platform/default/asset_request_fs.cpp', + ], + + 'include_dirs': [ + '../include', + ], + + 'variables': { + 'cflags_cc': [ + '<@(uv_cflags)', + '<@(boost_cflags)', + ], + 'ldflags': [ + '<@(uv_ldflags)', + ], + 'libraries': [ + '<@(uv_static_libs)', + ], + }, + + 'conditions': [ + ['OS == "mac"', { + 'xcode_settings': { + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], + }, + }, { + 'cflags_cc': [ '<@(cflags_cc)' ], + }], + ], + + 'link_settings': { + 'conditions': [ + ['OS == "mac"', { + 'libraries': [ '<@(libraries)' ], + 'xcode_settings': { 'OTHER_LDFLAGS': [ '<@(ldflags)' ] } + }, { + 'libraries': [ '<@(libraries)', '<@(ldflags)' ], + }] + ], + }, + }, + ], +} diff --git a/gyp/asset-zip.gypi b/gyp/asset-zip.gypi new file mode 100644 index 000000000..25df2a3d8 --- /dev/null +++ b/gyp/asset-zip.gypi @@ -0,0 +1,62 @@ +{ + 'targets': [ + { 'target_name': 'asset-zip', + 'product_name': 'mbgl-asset-zip', + 'type': 'static_library', + 'standalone_static_library': 1, + 'hard_dependency': 1, + + 'sources': [ + '../platform/default/asset_request_zip.cpp', + '../platform/default/uv_zip.c', + ], + + 'include_dirs': [ + '../include', + ], + + 'variables': { + 'cflags': [ + '<@(uv_cflags)', + '<@(zip_cflags)', + ], + 'cflags_cc': [ + '<@(uv_cflags)', + '<@(zip_cflags)', + '<@(boost_cflags)', + ], + 'ldflags': [ + '<@(uv_ldflags)', + '<@(zip_ldflags)', + ], + 'libraries': [ + '<@(uv_static_libs)', + '<@(zip_static_libs)', + ], + }, + + 'conditions': [ + ['OS == "mac"', { + 'xcode_settings': { + 'OTHER_CFLAGS': [ '<@(cflags)' ], + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], + }, + }, { + 'cflags': [ '<@(cflags)' ], + 'cflags_cc': [ '<@(cflags_cc)' ], + }], + ], + + 'link_settings': { + 'conditions': [ + ['OS == "mac"', { + 'libraries': [ '<@(libraries)' ], + 'xcode_settings': { 'OTHER_LDFLAGS': [ '<@(ldflags)' ] } + }, { + 'libraries': [ '<@(libraries)', '<@(ldflags)' ], + }] + ], + }, + }, + ], +} diff --git a/gyp/cache-sqlite.gypi b/gyp/cache-sqlite.gypi new file mode 100644 index 000000000..53af8dab5 --- /dev/null +++ b/gyp/cache-sqlite.gypi @@ -0,0 +1,64 @@ +{ + 'targets': [ + { 'target_name': 'cache-sqlite', + 'product_name': 'mbgl-cache-sqlite', + 'type': 'static_library', + 'standalone_static_library': 1, + 'hard_dependency': 1, + + 'sources': [ + '../platform/default/sqlite_cache.cpp', + '../platform/default/sqlite3.hpp', + '../platform/default/sqlite3.cpp', + '../platform/default/compression.hpp', + '../platform/default/compression.cpp', + ], + + 'include_dirs': [ + '../include', + ], + + 'variables': { + 'cflags_cc': [ + '<@(uv_cflags)', + '<@(sqlite3_cflags)', + ], + 'ldflags': [ + '<@(uv_ldflags)', + '<@(sqlite3_ldflags)', + '<@(zlib_ldflags)', + ], + 'libraries': [ + '<@(uv_static_libs)', + '<@(sqlite3_static_libs)', + '<@(zlib_static_libs)', + ], + }, + + 'conditions': [ + ['OS == "mac"', { + 'xcode_settings': { + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], + }, + }, { + 'cflags_cc': [ '<@(cflags_cc)' ], + }], + ], + + 'link_settings': { + 'conditions': [ + ['OS == "mac"', { + 'libraries': [ '<@(libraries)' ], + 'xcode_settings': { 'OTHER_LDFLAGS': [ '<@(ldflags)' ] } + }, { + 'libraries': [ '<@(libraries)', '<@(ldflags)' ], + }] + ], + }, + + 'direct_dependent_settings': { + 'include_dirs': [ '../include' ], + }, + }, + ], +} diff --git a/gyp/common.gypi b/gyp/common.gypi index d219ba2f9..7cf13fff6 100644 --- a/gyp/common.gypi +++ b/gyp/common.gypi @@ -1,19 +1,18 @@ { 'variables': { 'install_prefix%': '', - 'standalone_product_dir':' -#include + +// Forward definition of JNI types +typedef class _jclass* jclass; +typedef struct _jmethodID* jmethodID; +typedef struct _jfieldID* jfieldID; namespace mbgl { namespace android { diff --git a/include/mbgl/android/native_map_view.hpp b/include/mbgl/android/native_map_view.hpp index 8641d277b..bfe544c2b 100644 --- a/include/mbgl/android/native_map_view.hpp +++ b/include/mbgl/android/native_map_view.hpp @@ -4,7 +4,8 @@ #include #include #include -#include +#include +#include #include #include @@ -25,10 +26,10 @@ public: void swap() override; void notify() override; - void notifyMapChange(mbgl::MapChange change, mbgl::timestamp delay) override; + void notifyMapChange(mbgl::MapChange change, std::chrono::steady_clock::duration delay = std::chrono::steady_clock::duration::zero()) override; mbgl::Map &getMap(); - mbgl::CachingHTTPFileSource &getFileSource(); + mbgl::DefaultFileSource &getFileSource(); void initializeDisplay(); void terminateDisplay(); @@ -61,7 +62,8 @@ private: ANativeWindow *window = nullptr; - mbgl::CachingHTTPFileSource fileSource; + mbgl::SQLiteCache fileCache; + mbgl::DefaultFileSource fileSource; mbgl::Map map; EGLDisplay display = EGL_NO_DISPLAY; diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index 21fc8f301..ae0228544 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -3,7 +3,6 @@ #include #include -#include #include #include @@ -16,6 +15,7 @@ #include #include #include +#include namespace mbgl { @@ -83,8 +83,8 @@ public: void setClasses(const std::vector&); std::vector getClasses() const; - void setDefaultTransitionDuration(uint64_t milliseconds = 0); - uint64_t getDefaultTransitionDuration(); + void setDefaultTransitionDuration(std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + std::chrono::steady_clock::duration getDefaultTransitionDuration(); void setStyleURL(const std::string &url); void setStyleJSON(std::string newStyleJSON, const std::string &base = ""); std::string getStyleJSON() const; @@ -93,20 +93,20 @@ public: void cancelTransitions(); // Position - void moveBy(double dx, double dy, double duration = 0); - void setLonLat(double lon, double lat, double duration = 0); + void moveBy(double dx, double dy, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setLonLat(double lon, double lat, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void getLonLat(double &lon, double &lat) const; void startPanning(); void stopPanning(); void resetPosition(); // Scale - void scaleBy(double ds, double cx = -1, double cy = -1, double duration = 0); - void setScale(double scale, double cx = -1, double cy = -1, double duration = 0); + void scaleBy(double ds, double cx = -1, double cy = -1, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setScale(double scale, double cx = -1, double cy = -1, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); double getScale() const; - void setZoom(double zoom, double duration = 0); + void setZoom(double zoom, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); double getZoom() const; - void setLonLatZoom(double lon, double lat, double zoom, double duration = 0); + void setLonLatZoom(double lon, double lat, double zoom, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void getLonLatZoom(double &lon, double &lat, double &zoom) const; void resetZoom(); void startScaling(); @@ -115,21 +115,25 @@ public: double getMaxZoom() const; // Rotation - void rotateBy(double sx, double sy, double ex, double ey, double duration = 0); - void setBearing(double degrees, double duration = 0); + void rotateBy(double sx, double sy, double ex, double ey, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setBearing(double degrees, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void setBearing(double degrees, double cx, double cy); double getBearing() const; void resetNorth(); void startRotating(); void stopRotating(); + // API + void setAccessToken(const std::string &token); + const std::string &getAccessToken() const; + // Debug void setDebug(bool value); void toggleDebug(); bool getDebug() const; inline const TransformState &getState() const { return state; } - inline timestamp getTime() const { return animationTime; } + inline std::chrono::steady_clock::time_point getTime() const { return animationTime; } private: util::ptr getSprite(); @@ -160,7 +164,10 @@ private: Mode mode = Mode::None; +public: // TODO: make private again std::unique_ptr loop; + +private: std::unique_ptr workers; std::thread thread; std::unique_ptr asyncTerminate; @@ -191,7 +198,7 @@ private: View &view; -#ifndef NDEBUG +#ifdef DEBUG const std::thread::id mainThread; std::thread::id mapThread; #endif @@ -214,11 +221,12 @@ private: std::string styleURL; std::string styleJSON = ""; std::vector classes; + std::string accessToken; - std::atomic_uint_fast64_t defaultTransitionDuration; + std::chrono::steady_clock::duration defaultTransitionDuration; bool debug = false; - timestamp animationTime = 0; + std::chrono::steady_clock::time_point animationTime = std::chrono::steady_clock::time_point::min(); std::set> activeSources; }; diff --git a/include/mbgl/map/transform.hpp b/include/mbgl/map/transform.hpp index a42b7aa10..246270da1 100644 --- a/include/mbgl/map/transform.hpp +++ b/include/mbgl/map/transform.hpp @@ -1,7 +1,6 @@ #ifndef MBGL_MAP_TRANSFORM #define MBGL_MAP_TRANSFORM -#include #include #include @@ -9,6 +8,7 @@ #include #include #include +#include namespace mbgl { @@ -25,18 +25,18 @@ public: uint16_t fb_width, uint16_t fb_height); // Position - void moveBy(double dx, double dy, timestamp duration = 0); - void setLonLat(double lon, double lat, timestamp duration = 0); - void setLonLatZoom(double lon, double lat, double zoom, timestamp duration = 0); + void moveBy(double dx, double dy, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setLonLat(double lon, double lat, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setLonLatZoom(double lon, double lat, double zoom, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void getLonLat(double& lon, double& lat) const; void getLonLatZoom(double& lon, double& lat, double& zoom) const; void startPanning(); void stopPanning(); // Zoom - void scaleBy(double ds, double cx = -1, double cy = -1, timestamp duration = 0); - void setScale(double scale, double cx = -1, double cy = -1, timestamp duration = 0); - void setZoom(double zoom, timestamp duration = 0); + void scaleBy(double ds, double cx = -1, double cy = -1, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setScale(double scale, double cx = -1, double cy = -1, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setZoom(double zoom, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); double getZoom() const; double getScale() const; void startScaling(); @@ -45,8 +45,8 @@ public: double getMaxZoom() const; // Angle - void rotateBy(double sx, double sy, double ex, double ey, timestamp duration = 0); - void setAngle(double angle, timestamp duration = 0); + void rotateBy(double sx, double sy, double ex, double ey, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void setAngle(double angle, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void setAngle(double angle, double cx, double cy); double getAngle() const; void startRotating(); @@ -54,7 +54,7 @@ public: // Transitions bool needsTransition() const; - void updateTransitions(timestamp now); + void updateTransitions(std::chrono::steady_clock::time_point now); void cancelTransitions(); // Transform state @@ -64,10 +64,10 @@ public: private: // Functions prefixed with underscores will *not* perform any locks. It is the caller's // responsibility to lock this object. - void _moveBy(double dx, double dy, timestamp duration = 0); - void _setScale(double scale, double cx, double cy, timestamp duration = 0); - void _setScaleXY(double new_scale, double xn, double yn, timestamp duration = 0); - void _setAngle(double angle, timestamp duration = 0); + void _moveBy(double dx, double dy, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void _setScale(double scale, double cx, double cy, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void _setScaleXY(double new_scale, double xn, double yn, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); + void _setAngle(double angle, std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero()); void _clearPanning(); void _clearRotating(); void _clearScaling(); diff --git a/include/mbgl/map/view.hpp b/include/mbgl/map/view.hpp index 75fcb4e64..b94b8c0b9 100644 --- a/include/mbgl/map/view.hpp +++ b/include/mbgl/map/view.hpp @@ -1,7 +1,7 @@ #ifndef MBGL_MAP_VIEW #define MBGL_MAP_VIEW -#include +#include namespace mbgl { @@ -44,7 +44,7 @@ public: // 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. - virtual void notifyMapChange(MapChange change, timestamp delay = 0) = 0; + virtual void notifyMapChange(MapChange change, std::chrono::steady_clock::duration delay = std::chrono::steady_clock::duration::zero()) = 0; protected: mbgl::Map *map = nullptr; diff --git a/include/mbgl/platform/default/glfw_view.hpp b/include/mbgl/platform/default/glfw_view.hpp index 8ec282891..7156d4ff1 100644 --- a/include/mbgl/platform/default/glfw_view.hpp +++ b/include/mbgl/platform/default/glfw_view.hpp @@ -2,7 +2,6 @@ #define MBGL_COMMON_GLFW_VIEW #include -#include #ifdef NVIDIA #define GLFW_INCLUDE_ES2 @@ -19,7 +18,7 @@ public: void activate(); void deactivate(); void notify(); - void notifyMapChange(mbgl::MapChange change, mbgl::timestamp delay = 0); + void notifyMapChange(mbgl::MapChange change, std::chrono::steady_clock::duration delay = std::chrono::steady_clock::duration::zero()); static void key(GLFWwindow *window, int key, int scancode, int action, int mods); static void scroll(GLFWwindow *window, double xoffset, double yoffset); diff --git a/include/mbgl/platform/default/headless_view.hpp b/include/mbgl/platform/default/headless_view.hpp index 387011aa0..2fad430e6 100644 --- a/include/mbgl/platform/default/headless_view.hpp +++ b/include/mbgl/platform/default/headless_view.hpp @@ -7,6 +7,7 @@ #define GL_GLEXT_PROTOTYPES #include #define MBGL_USE_GLX 1 +#undef Status #endif #include @@ -31,7 +32,7 @@ public: std::unique_ptr readPixels(); void notify(); - void notifyMapChange(MapChange change, timestamp delay = 0); + void notifyMapChange(MapChange change, std::chrono::steady_clock::duration delay = std::chrono::steady_clock::duration::zero()); void activate(); void deactivate(); void swap(); diff --git a/include/mbgl/platform/default/jpeg_reader.hpp b/include/mbgl/platform/default/jpeg_reader.hpp index 7122f24cd..e041c0a5d 100644 --- a/include/mbgl/platform/default/jpeg_reader.hpp +++ b/include/mbgl/platform/default/jpeg_reader.hpp @@ -9,7 +9,13 @@ extern "C" #include } +#pragma GCC diagnostic push +#ifndef __clang__ +#pragma GCC diagnostic ignored "-Wunused-local-typedefs" +#pragma GCC diagnostic ignored "-Wshadow" +#endif #include +#pragma GCC diagnostic pop namespace mbgl { namespace util { diff --git a/include/mbgl/platform/default/png_reader.hpp b/include/mbgl/platform/default/png_reader.hpp index 66debd4fb..649e7a75c 100644 --- a/include/mbgl/platform/default/png_reader.hpp +++ b/include/mbgl/platform/default/png_reader.hpp @@ -11,7 +11,13 @@ extern "C" #include #include +#pragma GCC diagnostic push +#ifndef __clang__ +#pragma GCC diagnostic ignored "-Wunused-local-typedefs" +#pragma GCC diagnostic ignored "-Wshadow" +#endif #include +#pragma GCC diagnostic pop namespace mbgl { namespace util { diff --git a/include/mbgl/platform/platform.hpp b/include/mbgl/platform/platform.hpp index b4aaccb8b..ea630c095 100644 --- a/include/mbgl/platform/platform.hpp +++ b/include/mbgl/platform/platform.hpp @@ -17,10 +17,11 @@ std::string uppercase(const std::string &string); // Lowercase a string, potentially using platform-specific routines. std::string lowercase(const std::string &string); -// Returns the path to the default cache database on this system. -std::string defaultCacheDatabase(); +// Returns the path to the root folder of the application. +const std::string &applicationRoot(); -std::string applicationRoot(); +// Returns the path to the asset location. +const std::string &assetRoot(); // Shows an alpha image with the specified dimensions in a named window. void show_debug_image(std::string name, const char *data, size_t width, size_t height); diff --git a/include/mbgl/storage/asset_request.hpp b/include/mbgl/storage/asset_request.hpp deleted file mode 100644 index 3114d41ad..000000000 --- a/include/mbgl/storage/asset_request.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef MBGL_STORAGE_ASSET_REQUEST -#define MBGL_STORAGE_ASSET_REQUEST - -#include - -namespace mbgl { - -typedef struct uv_loop_s uv_loop_t; - -struct AssetRequestBaton; - -class AssetRequest : public BaseRequest { -public: - AssetRequest(const std::string &path, uv_loop_t *loop); - ~AssetRequest(); - - void cancel(); - -private: - AssetRequestBaton *ptr = nullptr; - - friend struct AssetRequestBaton; -}; - -} - -#endif diff --git a/include/mbgl/storage/asset_request_baton.hpp b/include/mbgl/storage/asset_request_baton.hpp deleted file mode 100644 index 2cbb6c51c..000000000 --- a/include/mbgl/storage/asset_request_baton.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef MBGL_STORAGE_ASSET_REQUEST_BATON -#define MBGL_STORAGE_ASSET_REQUEST_BATON - -#include -#include - -#include - -namespace mbgl { - -class AssetRequest; - -struct AssetRequestBaton { - AssetRequestBaton(AssetRequest *request_, const std::string &path, uv_loop_t *loop); - - const std::thread::id threadId; - AssetRequest *request = nullptr; - std::unique_ptr asyncRun; - std::string path; - bool canceled = false; - - void cancel(); - static void notifyError(AssetRequestBaton *ptr, const int code, const char *message); - static void notifySuccess(AssetRequestBaton *ptr, const std::string body); - static void cleanup(AssetRequestBaton *ptr); - - // IMPLEMENT THIS PLATFORM SPECIFIC FUNCTION: - - // Called to load the asset. Platform-specific implementation. - static void run(AssetRequestBaton *ptr); - -}; - - -} - - -#endif diff --git a/include/mbgl/storage/caching_http_file_source.hpp b/include/mbgl/storage/caching_http_file_source.hpp deleted file mode 100644 index 655afa639..000000000 --- a/include/mbgl/storage/caching_http_file_source.hpp +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef MBGL_STORAGE_CACHING_HTTP_FILE_SOURCE -#define MBGL_STORAGE_CACHING_HTTP_FILE_SOURCE - -#include - -#include -#include - -typedef struct uv_messenger_s uv_messenger_t; - -namespace mbgl { - -class BaseRequest; -class SQLiteStore; - -class CachingHTTPFileSource : public FileSource { -public: - CachingHTTPFileSource(const std::string &path_); - virtual ~CachingHTTPFileSource(); - - // Stores and checks the libuv loop for requests - void setLoop(uv_loop_t*); - bool hasLoop(); - void clearLoop(); - - // Set the base path/URL for relative requests - void setBase(std::string); - - // Set the Mapbox API access token - void setAccessToken(std::string); - - // Get the Mapbox API access token - std::string getAccessToken() const; - - std::unique_ptr request(ResourceType type, const std::string &url); - - void prepare(std::function fn); - - // Call this when the network status reachability changed. - void setReachability(bool reachable); - -private: - std::thread::id threadId; - - // Mapbox API access token. - std::string accessToken; - - // Path to the cache database. - std::string path; - - // Stores a URL that is used as a base for loading resources with relative path. - std::string base; - - std::unordered_map> pending; - util::ptr store; - uv_loop_t *loop = nullptr; - uv_messenger_t *queue = nullptr; -}; - -} - -#endif diff --git a/include/mbgl/storage/default/asset_request.hpp b/include/mbgl/storage/default/asset_request.hpp new file mode 100644 index 000000000..c582c025f --- /dev/null +++ b/include/mbgl/storage/default/asset_request.hpp @@ -0,0 +1,24 @@ +#ifndef MBGL_STORAGE_DEFAULT_ASSET_REQUEST +#define MBGL_STORAGE_DEFAULT_ASSET_REQUEST + +#include "shared_request_base.hpp" + +namespace mbgl { + +class AssetRequest : public SharedRequestBase { +public: + AssetRequest(DefaultFileSource *source, const Resource &resource); + + void start(uv_loop_t *loop, std::unique_ptr response = nullptr); + void cancel(); + +private: + ~AssetRequest(); + void *ptr = nullptr; + + friend class AssetRequestImpl; +}; + +} + +#endif diff --git a/include/mbgl/storage/default/http_context.hpp b/include/mbgl/storage/default/http_context.hpp new file mode 100644 index 000000000..6b9518dab --- /dev/null +++ b/include/mbgl/storage/default/http_context.hpp @@ -0,0 +1,76 @@ +#ifndef MBGL_STORAGE_DEFAULT_HTTP_CONTEXT +#define MBGL_STORAGE_DEFAULT_HTTP_CONTEXT + +#include "thread_context.hpp" +#include + +#include + +namespace mbgl { + +class HTTPRequest; + +// This is a template class that provides a per-thread Context object. It can be used by HTTP +// implementations to store global state. It also implements the NetworkStatus mechanism and +// triggers immediate retries on all requests waiting for network status changes. + +template +class HTTPContext : public ThreadContext { +public: + HTTPContext(uv_loop_t *loop); + ~HTTPContext(); + + void addRequest(HTTPRequest *request); + void removeRequest(HTTPRequest *baton); + +public: + // Will be fired when the network status becomes reachable. + uv_async_t *reachability = nullptr; + + // A list of all pending HTTPRequestImpls that we need to notify when the network status + // changes. + std::set requests; +}; + +template +HTTPContext::HTTPContext(uv_loop_t *loop_) + : ThreadContext(loop_) { + reachability = new uv_async_t; + reachability->data = this; +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + uv_async_init(loop_, reachability, [](uv_async_t *async, int) { +#else + uv_async_init(loop_, reachability, [](uv_async_t *async) { +#endif + for (auto request : reinterpret_cast(async->data)->requests) { + request->retryImmediately(); + } + }); + // Allow the loop to quit even though this handle is still active. + uv_unref(reinterpret_cast(reachability)); + NetworkStatus::Subscribe(reachability); +} + +template +HTTPContext::~HTTPContext() { + MBGL_VERIFY_THREAD(HTTPContext::tid); + + assert(requests.empty()); + + NetworkStatus::Unsubscribe(reachability); + uv::close(reachability); +} + +template +void HTTPContext::addRequest(HTTPRequest *request) { + requests.insert(request); +} + +template +void HTTPContext::removeRequest(HTTPRequest *request) { + requests.erase(request); +} + +} + +#endif diff --git a/include/mbgl/storage/default/http_request.hpp b/include/mbgl/storage/default/http_request.hpp new file mode 100644 index 000000000..914e622f1 --- /dev/null +++ b/include/mbgl/storage/default/http_request.hpp @@ -0,0 +1,26 @@ +#ifndef MBGL_STORAGE_DEFAULT_HTTP_REQUEST +#define MBGL_STORAGE_DEFAULT_HTTP_REQUEST + +#include "shared_request_base.hpp" + +namespace mbgl { + +class HTTPRequest : public SharedRequestBase { +public: + HTTPRequest(DefaultFileSource *source, const Resource &resource); + + void start(uv_loop_t *loop, std::unique_ptr response = nullptr); + void cancel(); + + void retryImmediately(); + +private: + ~HTTPRequest(); + void *ptr = nullptr; + + friend class HTTPRequestImpl; +}; + +} + +#endif diff --git a/include/mbgl/storage/default/request.hpp b/include/mbgl/storage/default/request.hpp new file mode 100644 index 000000000..81ed14a56 --- /dev/null +++ b/include/mbgl/storage/default/request.hpp @@ -0,0 +1,51 @@ +#ifndef MBGL_STORAGE_DEFAULT_REQUEST +#define MBGL_STORAGE_DEFAULT_REQUEST + +#include + +#include +#include + +#include +#include + +typedef struct uv_async_s uv_async_t; +typedef struct uv_loop_s uv_loop_t; + +namespace mbgl { + +class Response; + +class Request : private util::noncopyable { + MBGL_STORE_THREAD(tid) + +public: + using Callback = std::function; + Request(const Resource &resource, uv_loop_t *loop, Callback callback); + ~Request(); + +public: + // May be called from any thread. + void notify(const std::shared_ptr &response); + void destruct(); + + // May be called only from the thread the Request was created in. + void cancel(); + +private: + static void notifyCallback(uv_async_t *async); + static void cancelCallback(uv_async_t *async); + +private: + uv_async_t *notify_async = nullptr; + uv_async_t *destruct_async = nullptr; + Callback callback; + std::shared_ptr response; + +public: + const Resource resource; +}; + +} + +#endif diff --git a/include/mbgl/storage/default/shared_request_base.hpp b/include/mbgl/storage/default/shared_request_base.hpp new file mode 100644 index 000000000..a0f3e8d4e --- /dev/null +++ b/include/mbgl/storage/default/shared_request_base.hpp @@ -0,0 +1,88 @@ +#ifndef MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE +#define MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE + +#include +#include +#include +#include +#include + +#include +#include +#include + +typedef struct uv_loop_s uv_loop_t; + +namespace mbgl { + +class Request; +class Response; +class DefaultFileSource; + +class SharedRequestBase : private util::noncopyable { +protected: + MBGL_STORE_THREAD(tid) + +public: + SharedRequestBase(DefaultFileSource *source_, const Resource &resource_) + : resource(resource_), source(source_) {} + + virtual void start(uv_loop_t *loop, std::unique_ptr response = nullptr) = 0; + virtual void cancel() = 0; + + void notify(std::unique_ptr response, FileCache::Hint hint) { + MBGL_VERIFY_THREAD(tid); + + if (source) { + source->notify(this, observers, std::shared_ptr(response.release()), + hint); + } + } + + void subscribe(Request *request) { + MBGL_VERIFY_THREAD(tid); + + observers.insert(request); + } + + void unsubscribeAll() { + MBGL_VERIFY_THREAD(tid); + + source = nullptr; + observers.clear(); + cancel(); + } + + void unsubscribe(Request *request) { + MBGL_VERIFY_THREAD(tid); + + observers.erase(request); + + if (observers.empty()) { + // There are no observers anymore. We are initiating cancelation. + if (source) { + // First, remove this SharedRequestBase from the source. + source->notify(this, observers, nullptr, FileCache::Hint::No); + } + + // Then, initiate cancelation of this request + cancel(); + } + } + +protected: + virtual ~SharedRequestBase() { + MBGL_VERIFY_THREAD(tid); + } + +public: + const Resource resource; + +private: + DefaultFileSource *source = nullptr; + std::set observers; +}; + +} + +#endif diff --git a/include/mbgl/storage/default/sqlite_cache.hpp b/include/mbgl/storage/default/sqlite_cache.hpp new file mode 100644 index 000000000..8f2746561 --- /dev/null +++ b/include/mbgl/storage/default/sqlite_cache.hpp @@ -0,0 +1,52 @@ +#ifndef MBGL_STORAGE_DEFAULT_SQLITE_CACHE +#define MBGL_STORAGE_DEFAULT_SQLITE_CACHE + +#include + +#include +#include + +typedef struct uv_loop_s uv_loop_t; + +namespace mapbox { namespace util { template class variant; } } +namespace mapbox { namespace sqlite { class Database; class Statement; } } + +namespace mbgl { + +namespace util { template class AsyncQueue; } + +class SQLiteCache : public FileCache { + struct GetAction; + struct PutAction; + struct RefreshAction; + struct StopAction; + using Action = mapbox::util::variant; + using Queue = util::AsyncQueue; + +public: + SQLiteCache(const std::string &path = ":memory:"); + ~SQLiteCache(); + + void get(const Resource &resource, std::function)> callback); + void put(const Resource &resource, std::shared_ptr response, Hint hint); + +private: + struct ActionDispatcher; + void process(GetAction &action); + void process(PutAction &action); + void process(RefreshAction &action); + void process(StopAction &action); + + void createDatabase(); + + const std::string path; + uv_loop_t *loop = nullptr; + Queue *queue = nullptr; + std::thread thread; + std::unique_ptr<::mapbox::sqlite::Database> db; + std::unique_ptr<::mapbox::sqlite::Statement> getStmt, putStmt, refreshStmt; +}; + +} + +#endif diff --git a/include/mbgl/storage/default/thread_context.hpp b/include/mbgl/storage/default/thread_context.hpp new file mode 100644 index 000000000..763c83a25 --- /dev/null +++ b/include/mbgl/storage/default/thread_context.hpp @@ -0,0 +1,78 @@ +#ifndef MBGL_STORAGE_DEFAULT_THREAD_CONTEXT +#define MBGL_STORAGE_DEFAULT_THREAD_CONTEXT + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace mbgl { + +// This is a template class that provides a per-thread and per-loop Context object. It can be used +// by implementations to store global state. + +template +class ThreadContext : private util::noncopyable { +protected: + MBGL_STORE_THREAD(tid) + using Map = std::map>; + +public: + static Context *Get(uv_loop_t *loop); + +private: + static pthread_key_t key; + static pthread_once_t once; + +public: + ThreadContext(uv_loop_t *loop); + ~ThreadContext(); + +public: + uv_loop_t *loop; +}; + +template +Context *ThreadContext::Get(uv_loop_t *loop) { + pthread_once(&once, []() { + pthread_key_create(&key, [](void *ptr) { + assert(ptr); + delete reinterpret_cast(ptr); + }); + }); + auto contexts = reinterpret_cast(pthread_getspecific(key)); + if (!contexts) { + contexts = new Map(); + pthread_setspecific(key, contexts); + } + + // Now find a ThreadContext that matches the requested loop. + auto it = contexts->find(loop); + if (it == contexts->end()) { + auto result = contexts->emplace(loop, util::make_unique(loop)); + assert(result.second); // Make sure it was actually inserted. + return result.first->second.get(); + } else { + return it->second.get(); + } +} + +template +ThreadContext::ThreadContext(uv_loop_t *loop_) : loop(loop_) { +} + +template +ThreadContext::~ThreadContext() { + MBGL_VERIFY_THREAD(tid); +} + + +} + +#endif diff --git a/include/mbgl/storage/default_file_source.hpp b/include/mbgl/storage/default_file_source.hpp new file mode 100644 index 000000000..21048e99e --- /dev/null +++ b/include/mbgl/storage/default_file_source.hpp @@ -0,0 +1,60 @@ +#ifndef MBGL_STORAGE_DEFAULT_DEFAULT_FILE_SOURCE +#define MBGL_STORAGE_DEFAULT_DEFAULT_FILE_SOURCE + +#include +#include + +#include +#include +#include + +namespace mapbox { namespace util { template class variant; } } + +namespace mbgl { + +namespace util { template class AsyncQueue; } + +class SharedRequestBase; + +class DefaultFileSource : public FileSource { +public: + DefaultFileSource(FileCache *cache); + DefaultFileSource(FileCache *cache, uv_loop_t *loop); + ~DefaultFileSource(); + + Request *request(const Resource &resource, uv_loop_t *loop, Callback callback); + void cancel(Request *request); + void request(const Resource &resource, Callback callback); + + enum class CacheHint : uint8_t { Full, Refresh, No }; + void notify(SharedRequestBase *sharedRequest, const std::set &observers, + std::shared_ptr response, FileCache::Hint hint); + +private: + struct ActionDispatcher; + struct AddRequestAction; + struct RemoveRequestAction; + struct ResultAction; + struct StopAction; + using Action = + mapbox::util::variant; + using Queue = util::AsyncQueue; + + void process(AddRequestAction &action); + void process(RemoveRequestAction &action); + void process(ResultAction &action); + void process(StopAction &action); + + SharedRequestBase *find(const Resource &resource); + + std::unordered_map pending; + + uv_loop_t *loop = nullptr; + FileCache *cache = nullptr; + Queue *queue = nullptr; + std::thread thread; +}; + +} + +#endif diff --git a/include/mbgl/storage/file_cache.hpp b/include/mbgl/storage/file_cache.hpp new file mode 100644 index 000000000..97e75a5d8 --- /dev/null +++ b/include/mbgl/storage/file_cache.hpp @@ -0,0 +1,27 @@ +#ifndef MBGL_STORAGE_FILE_CACHE +#define MBGL_STORAGE_FILE_CACHE + +#include + +#include +#include + +namespace mbgl { + +struct Resource; +class Response; + +class FileCache : private util::noncopyable { +public: + virtual ~FileCache() = default; + + enum class Hint : uint8_t { Full, Refresh, No }; + + virtual void get(const Resource &resource, + std::function)> callback) = 0; + virtual void put(const Resource &resource, std::shared_ptr response, Hint hint) = 0; +}; + +} + +#endif diff --git a/include/mbgl/storage/file_source.hpp b/include/mbgl/storage/file_source.hpp index 23a1462ae..8517d6e4a 100644 --- a/include/mbgl/storage/file_source.hpp +++ b/include/mbgl/storage/file_source.hpp @@ -1,29 +1,38 @@ #ifndef MBGL_STORAGE_FILE_SOURCE #define MBGL_STORAGE_FILE_SOURCE -#include -#include -#include +#include "response.hpp" +#include "resource.hpp" + +#include +#include +#include -#include #include typedef struct uv_loop_s uv_loop_t; - namespace mbgl { -class FileSource : public util::noncopyable { +class Request; + +class FileSource : private util::noncopyable { +protected: + MBGL_STORE_THREAD(tid) + public: virtual ~FileSource() = default; - virtual void setLoop(uv_loop_t*) = 0; - virtual bool hasLoop() = 0; - virtual void clearLoop() = 0; + using Callback = std::function; - virtual void setBase(std::string) = 0; - virtual std::unique_ptr request(ResourceType type, const std::string &url) = 0; - virtual void prepare(std::function fn) = 0; + // These can be called from any thread. The callback will be invoked in the loop. + // You can only cancel a request from the same thread it was created in. + virtual Request *request(const Resource &resource, uv_loop_t *loop, Callback callback) = 0; + virtual void cancel(Request *request) = 0; + + // These can be called from any thread. The callback will be invoked in an arbitrary other thread. + // You cannot cancel these requests. + virtual void request(const Resource &resource, Callback callback) = 0; }; } diff --git a/include/mbgl/storage/http_request_baton.hpp b/include/mbgl/storage/http_request_baton.hpp deleted file mode 100644 index 11abfb71d..000000000 --- a/include/mbgl/storage/http_request_baton.hpp +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef MBGL_STORAGE_HTTP_REQUEST_BATON -#define MBGL_STORAGE_HTTP_REQUEST_BATON - -#include -#include - -#include -#include - -typedef struct uv_async_s uv_async_t; - -namespace mbgl { - -class HTTPRequest; - -enum class HTTPResponseType : int8_t { - // This error probably won't be resolved by retrying anytime soon. We are giving up. - PermanentError = -5, - - // This error might be resolved by waiting some time (e.g. server issues). - // We are going to do an exponential back-off and will try again in a few seconds. - TemporaryError = -4, - - // This error was caused by a temporary error and it is likely that it will be resolved - // immediately. We are going to try again right away. This is like the TemporaryError, except - // that we will not perform exponential back-off. - SingularError = -3, - - // This error might be resolved once the network reachability status changes. - // We are going to watch the network status for changes and will retry as soon as the operating - // system notifies us of a network status change. - ConnectionError = -2, - - // The request was canceled programatically. - Canceled = -1, - - // The request is still in progress. - Unknown = 0, - - // The request returned data successfully. We retrieved and decoded the data successfully. - Successful = 1, - - // The request confirmed that the data wasn't changed. We already have the data. - NotModified = 2, -}; - -struct HTTPRequestBaton { - HTTPRequestBaton(const std::string &path); - ~HTTPRequestBaton(); - - const std::thread::id threadId; - const std::string path; - - HTTPRequest *request = nullptr; - uv_async_t *async = nullptr; - - HTTPResponseType type = HTTPResponseType::Unknown; - std::unique_ptr response; - - // Implementation specific use. - void *ptr = nullptr; - - // IMPLEMENT THESE 3 PLATFORM SPECIFIC FUNCTIONS: - - // Begin the HTTP request. Platform-specific implementation. - static void start(const util::ptr &ptr); - - // This will be called to stop/cancel the HTTP request (if possible). Platform-specific implementation. - static void stop(const util::ptr &ptr); -}; - -} - -#endif diff --git a/include/mbgl/storage/network_status.hpp b/include/mbgl/storage/network_status.hpp new file mode 100644 index 000000000..cac2ae193 --- /dev/null +++ b/include/mbgl/storage/network_status.hpp @@ -0,0 +1,25 @@ +#ifndef MBGL_STORAGE_NETWORK_STATUS +#define MBGL_STORAGE_NETWORK_STATUS + +#include +#include + +typedef struct uv_async_s uv_async_t; + +namespace mbgl { + +class NetworkStatus { +public: + static void Reachable(); + + static void Subscribe(uv_async_t *async); + static void Unsubscribe(uv_async_t *async); + +private: + static std::mutex mtx; + static std::set observers; +}; + +} + +#endif \ No newline at end of file diff --git a/include/mbgl/storage/request.hpp b/include/mbgl/storage/request.hpp deleted file mode 100644 index 845c9a6da..000000000 --- a/include/mbgl/storage/request.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef MBGL_STORAGE_REQUEST -#define MBGL_STORAGE_REQUEST - -#include -#include - -#include - -#include -#include - -typedef struct uv_loop_s uv_loop_t; - -namespace mbgl { - -class BaseRequest; - -class Request { -private: - Request(const Request &) = delete; - Request(Request &&) = delete; - Request& operator=(const Request &) = delete; - Request& operator=(Request &&) = delete; - -public: - Request(const util::ptr &base); - ~Request(); - - void onload(CompletedCallback cb); - void oncancel(AbortedCallback cb); - void cancel(); - -private: - const std::thread::id thread_id; - util::ptr base; - std::forward_list callbacks; -}; - -} - -#endif \ No newline at end of file diff --git a/include/mbgl/storage/request_callback.hpp b/include/mbgl/storage/request_callback.hpp deleted file mode 100644 index 01427bd96..000000000 --- a/include/mbgl/storage/request_callback.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef MBGL_STORAGE_REQUEST_CALLBACK -#define MBGL_STORAGE_REQUEST_CALLBACK - -#include - -#include - -namespace mbgl { - -class Response; - -using CompletedCallback = std::function; -using AbortedCallback = std::function; - -using Callback = mapbox::util::variant< - CompletedCallback, - AbortedCallback ->; - -} - -#endif diff --git a/include/mbgl/storage/resource.hpp b/include/mbgl/storage/resource.hpp new file mode 100644 index 000000000..cfd52caa7 --- /dev/null +++ b/include/mbgl/storage/resource.hpp @@ -0,0 +1,35 @@ +#ifndef MBGL_STORAGE_RESOURCE +#define MBGL_STORAGE_RESOURCE + +#include +#include + +namespace mbgl { + +struct Resource { + enum Kind : uint8_t { + Unknown = 0, + Tile = 1, + Glyphs = 2, + Image = 3, + JSON = 4, + }; + + const Kind kind; + const std::string url; + + inline bool operator==(const Resource &res) const { + return kind == res.kind && url == res.url; + } + + struct Hash { + std::size_t operator()(Resource const& r) const { + return std::hash()(r.url) ^ (std::hash()(r.kind) << 1); + } + }; + +}; + +} + +#endif diff --git a/include/mbgl/storage/resource_type.hpp b/include/mbgl/storage/resource_type.hpp deleted file mode 100644 index b7204a9fa..000000000 --- a/include/mbgl/storage/resource_type.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef MBGL_STORAGE_RESOURCE_TYPE -#define MBGL_STORAGE_RESOURCE_TYPE - -#include - -namespace mbgl { - -enum class ResourceType : uint8_t { - Unknown = 0, - Tile = 1, - Glyphs = 2, - Image = 3, - JSON = 4 -}; - -} - -#endif diff --git a/include/mbgl/storage/response.hpp b/include/mbgl/storage/response.hpp index 9357ad3c6..cf22d9002 100644 --- a/include/mbgl/storage/response.hpp +++ b/include/mbgl/storage/response.hpp @@ -2,25 +2,21 @@ #define MBGL_STORAGE_RESPONSE #include -#include namespace mbgl { - - class Response { public: - long code = 0; + enum Status : bool { Error, Successful }; + + Status status = Error; + std::string message; int64_t modified = 0; int64_t expires = 0; std::string etag; std::string data; - - std::string message; - - static int64_t parseCacheControl(const char *value); }; } -#endif \ No newline at end of file +#endif diff --git a/include/mbgl/util/async_queue.hpp b/include/mbgl/util/async_queue.hpp new file mode 100644 index 000000000..b3eaabc31 --- /dev/null +++ b/include/mbgl/util/async_queue.hpp @@ -0,0 +1,95 @@ +#ifndef MBGL_UTIL_ASYNC_QUEUE +#define MBGL_UTIL_ASYNC_QUEUE + +#include "std.hpp" + +#include + +#include +#include +#include +#include +#include + + +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 +#define UV_ASYNC_PARAMS(handle) uv_async_t *handle, int +#else +#define UV_ASYNC_PARAMS(handle) uv_async_t *handle +#endif + +namespace mbgl { +namespace util { + +template +class AsyncQueue { +public: + AsyncQueue(uv_loop_t *loop, std::function fn) : + callback(fn) { + async.data = this; + uv_async_init(loop, &async, [](UV_ASYNC_PARAMS(handle)) { + auto q = reinterpret_cast(handle->data); + q->process(); + }); + } + + void send(T &&data) { + { + std::lock_guard lock(mutex); + queue.push(util::make_unique(std::move(data))); + } + uv_async_send(&async); + } + + void send(std::unique_ptr data) { + { + std::lock_guard lock(mutex); + queue.push(std::move(data)); + } + uv_async_send(&async); + } + + void stop() { + uv_close((uv_handle_t *)&async, [](uv_handle_t *handle) { + delete reinterpret_cast(handle->data); + }); + } + + void ref() { + uv_ref((uv_handle_t *)&async); + } + + void unref() { + uv_unref((uv_handle_t *)&async); + } + +private: + ~AsyncQueue() { + } + + void process() { + std::unique_ptr item; + while (true) { + mutex.lock(); + if (queue.empty()) { + mutex.unlock(); + break; + } + item = std::move(queue.front()); + queue.pop(); + mutex.unlock(); + callback(*item); + } + } + +private: + std::mutex mutex; + uv_async_t async; + std::queue> queue; + std::function callback; +}; + +} +} + +#endif diff --git a/include/mbgl/util/time.hpp b/include/mbgl/util/time.hpp index e8afbeff6..c2e931b10 100644 --- a/include/mbgl/util/time.hpp +++ b/include/mbgl/util/time.hpp @@ -7,41 +7,13 @@ namespace mbgl { -typedef uint64_t timestamp; - namespace util { - -// Returns time in nanoseconds since an arbitrary point in the past. This has -// no relation to the current time, but is continuously increasing, so -// comparisons between different timestamps produce meaningful values. -timestamp now(); - - // Returns the RFC1123 formatted date. E.g. "Tue, 04 Nov 2014 02:13:24 GMT" std::string rfc1123(std::time_t time); } -// used for time conversions -constexpr timestamp operator"" _nanoseconds (long double ns) { return ns; } -constexpr timestamp operator"" _nanosecond (long double ns) { return ns; } -constexpr timestamp operator"" _microseconds (long double us) { return us * 1e3; } -constexpr timestamp operator"" _microsecond (long double us) { return us * 1e3; } -constexpr timestamp operator"" _milliseconds (long double ms) { return ms * 1e6; } -constexpr timestamp operator"" _millisecond (long double ms) { return ms * 1e6; } -constexpr timestamp operator"" _seconds (long double s) { return s * 1e9; } -constexpr timestamp operator"" _second (long double s) { return s * 1e9; } - -constexpr timestamp operator"" _nanoseconds (unsigned long long ns) { return ns; } -constexpr timestamp operator"" _nanosecond (unsigned long long ns) { return ns; } -constexpr timestamp operator"" _microseconds (unsigned long long us) { return us * 1e3; } -constexpr timestamp operator"" _microsecond (unsigned long long us) { return us * 1e3; } -constexpr timestamp operator"" _milliseconds (unsigned long long ms) { return ms * 1e6; } -constexpr timestamp operator"" _millisecond (unsigned long long ms) { return ms * 1e6; } -constexpr timestamp operator"" _seconds (unsigned long long s) { return s * 1e9; } -constexpr timestamp operator"" _second (unsigned long long s) { return s * 1e9; } - } #endif diff --git a/include/mbgl/util/util.hpp b/include/mbgl/util/util.hpp new file mode 100644 index 000000000..2b0fd9cdd --- /dev/null +++ b/include/mbgl/util/util.hpp @@ -0,0 +1,17 @@ +#ifndef MBGL_UTIL_UTIL +#define MBGL_UTIL_UTIL + +#ifdef DEBUG + +#include +#define MBGL_STORE_THREAD(tid) const std::thread::id tid = std::this_thread::get_id(); +#define MBGL_VERIFY_THREAD(tid) assert(tid == std::this_thread::get_id()); + +#else + +#define MBGL_STORE_THREAD(tid) +#define MBGL_VERIFY_THREAD(tid) + +#endif + +#endif diff --git a/include/mbgl/util/uv.hpp b/include/mbgl/util/uv.hpp index f59037c1d..85f93e78b 100644 --- a/include/mbgl/util/uv.hpp +++ b/include/mbgl/util/uv.hpp @@ -3,10 +3,11 @@ #include +typedef struct uv_handle_s uv_handle_t; typedef struct uv_async_s uv_async_t; typedef struct uv_timer_s uv_timer_t; -typedef struct uv_handle_s uv_handle_t; typedef struct uv_loop_s uv_loop_t; +typedef struct uv_fs_s uv_fs_t; namespace uv { @@ -19,6 +20,15 @@ class worker; class mutex; class cond; +const char *getFileRequestError(uv_fs_t *req); + +template +void close(T *specific) { + uv_close(reinterpret_cast(specific), [](uv_handle_t *generic) { + delete reinterpret_cast(generic); + }); +} + } #endif diff --git a/include/mbgl/util/variant.hpp b/include/mbgl/util/variant.hpp index 2de195cd6..411f1918d 100644 --- a/include/mbgl/util/variant.hpp +++ b/include/mbgl/util/variant.hpp @@ -10,7 +10,7 @@ #include #include -#include +#include "recursive_wrapper.hpp" #ifdef _MSC_VER // http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx @@ -34,7 +34,19 @@ // translates to 100 #define VARIANT_VERSION (VARIANT_MAJOR_VERSION*100000) + (VARIANT_MINOR_VERSION*100) + (VARIANT_PATCH_VERSION) -namespace mapbox { namespace util { namespace detail { +namespace mapbox { namespace util { + +// static visitor +template +struct static_visitor +{ + using result_type = R; +protected: + static_visitor() {} + ~static_visitor() {} +}; + +namespace detail { static constexpr std::size_t invalid_value = std::size_t(-1); @@ -109,18 +121,38 @@ struct select_type<0, T, Types...> using type = T; }; -} // namespace detail -// static visitor -template -struct static_visitor +template +struct enable_if_type { using type = R; }; + +template +struct result_of_unary_visit { - using result_type = R; -protected: - static_visitor() {} - ~static_visitor() {} + using type = typename std::result_of::type; }; +template +struct result_of_unary_visit::type > +{ + using type = typename F::result_type; +}; + +template +struct result_of_binary_visit +{ + using type = typename std::result_of::type; +}; + + +template +struct result_of_binary_visit::type > +{ + using type = typename F::result_type; +}; + + +} // namespace detail + template struct static_max; @@ -225,7 +257,7 @@ struct dispatcher; template struct dispatcher { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_unary_visit::type; VARIANT_INLINE static result_type apply_const(V const& v, F f) { if (v.get_type_index() == sizeof...(Types)) @@ -254,7 +286,7 @@ struct dispatcher template struct dispatcher { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_unary_visit::type; VARIANT_INLINE static result_type apply_const(V const&, F) { throw std::runtime_error(std::string("unary dispatch: FAIL ") + typeid(V).name()); @@ -273,7 +305,7 @@ struct binary_dispatcher_rhs; template struct binary_dispatcher_rhs { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f) { if (rhs.get_type_index() == sizeof...(Types)) // call binary functor @@ -305,7 +337,7 @@ struct binary_dispatcher_rhs template struct binary_dispatcher_rhs { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const&, V const&, F) { throw std::runtime_error("binary dispatch: FAIL"); @@ -323,7 +355,7 @@ struct binary_dispatcher_lhs; template struct binary_dispatcher_lhs { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f) { if (lhs.get_type_index() == sizeof...(Types)) // call binary functor @@ -353,7 +385,7 @@ struct binary_dispatcher_lhs template struct binary_dispatcher_lhs { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const&, V const&, F) { throw std::runtime_error("binary dispatch: FAIL"); @@ -371,7 +403,7 @@ struct binary_dispatcher; template struct binary_dispatcher { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const& v0, V const& v1, F f) { if (v0.get_type_index() == sizeof...(Types)) @@ -416,7 +448,7 @@ struct binary_dispatcher template struct binary_dispatcher { - using result_type = typename F::result_type; + using result_type = typename detail::result_of_binary_visit::type; VARIANT_INLINE static result_type apply_const(V const&, V const&, F) { throw std::runtime_error("binary dispatch: FAIL"); @@ -448,7 +480,7 @@ struct less_comp }; template -class comparer : public static_visitor +class comparer { public: explicit comparer(Variant const& lhs) noexcept @@ -467,7 +499,7 @@ private: // operator<< helper template -class printer : public static_visitor<> +class printer { public: explicit printer(Out & out) diff --git a/ios/mapbox-gl-cocoa b/ios/mapbox-gl-cocoa index 2e5bfbdcd..37c9f7267 160000 --- a/ios/mapbox-gl-cocoa +++ b/ios/mapbox-gl-cocoa @@ -1 +1 @@ -Subproject commit 2e5bfbdcd54c893864c263b41a27846627e10f0c +Subproject commit 37c9f726752674f87758cd351316413f978f1606 diff --git a/linux/main.cpp b/linux/main.cpp index 245cb527f..12f77ffe5 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -4,7 +4,8 @@ #include #include #include -#include +#include +#include #include #include @@ -64,7 +65,9 @@ int main(int argc, char *argv[]) { sigaction(SIGINT, &sigIntHandler, NULL); view = new GLFWView(); - mbgl::CachingHTTPFileSource fileSource(mbgl::platform::defaultCacheDatabase()); + + mbgl::SQLiteCache cache("/tmp/mbgl-cache.db"); + mbgl::DefaultFileSource fileSource(&cache); mbgl::Map map(*view, fileSource); // Load settings @@ -78,12 +81,13 @@ int main(int argc, char *argv[]) { if (token == nullptr) { mbgl::Log::Warning(mbgl::Event::Setup, "no access token set. mapbox.com tiles won't work."); } else { - fileSource.setAccessToken(std::string(token)); + map.setAccessToken(std::string(token)); } // Load style - if (style.empty()) + if (style.empty()) { style = std::string("asset://") + std::string("styles/bright-v7.json"); + } map.setStyleURL(style); diff --git a/linux/mapboxgl-app.gyp b/linux/mapboxgl-app.gyp index 60eb16de3..afcc3a83a 100644 --- a/linux/mapboxgl-app.gyp +++ b/linux/mapboxgl-app.gyp @@ -3,55 +3,52 @@ '../gyp/common.gypi', ], 'targets': [ - { - 'target_name': 'linuxapp', + { 'target_name': 'linuxapp', 'product_name': 'mapbox-gl', 'type': 'executable', + + 'dependencies': [ + '../mbgl.gyp:core', + '../mbgl.gyp:platform-<(platform_lib)', + '../mbgl.gyp:http-<(http_lib)', + '../mbgl.gyp:asset-<(asset_lib)', + '../mbgl.gyp:cache-<(cache_lib)', + '../mbgl.gyp:bundle_styles', + '../mbgl.gyp:copy_certificate_bundle', + ], + 'sources': [ - './main.cpp', + 'main.cpp', '../platform/default/settings_json.cpp', '../platform/default/glfw_view.cpp', '../platform/default/log_stderr.cpp', ], - 'xcode_settings': { - 'OTHER_CPLUSPLUSFLAGS':[ + + 'variables' : { + 'cflags_cc': [ '<@(glfw3_cflags)', - '<@(png_cflags)', - '<@(jpeg_cflags)', ], - }, - 'cflags_cc': [ - '<@(glfw3_cflags)', - '<@(png_cflags)', - '<@(jpeg_cflags)', - '-I<(boost_root)/include', - ], - 'variables': { 'ldflags': [ - '<@(png_ldflags)', - '<@(sqlite3_static_libs)', - '<@(sqlite3_ldflags)', - '<@(glfw3_static_libs)', '<@(glfw3_ldflags)', - '<@(curl_ldflags)', - '<@(zlib_ldflags)', + ], + 'libraries': [ + '<@(glfw3_static_libs)', ], }, + 'conditions': [ ['OS == "mac"', { + 'libraries': [ '<@(libraries)' ], 'xcode_settings': { + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], 'OTHER_LDFLAGS': [ '<@(ldflags)' ], } }, { - 'libraries': [ '<@(ldflags)' ], + 'cflags_cc': [ '<@(cflags_cc)' ], + 'libraries': [ '<@(libraries)', '<@(ldflags)' ], }] ], - 'dependencies': [ - '../mapboxgl.gyp:mbgl-standalone', - '../mapboxgl.gyp:mbgl-linux', - '../mapboxgl.gyp:bundle_styles', - '../mapboxgl.gyp:copy_certificate_bundle', - ], + 'copies': [{ 'files': [ '../styles/styles' ], 'destination': '<(PRODUCT_DIR)' diff --git a/macosx/main.mm b/macosx/main.mm index 277f8c44d..d61d7d16b 100644 --- a/macosx/main.mm +++ b/macosx/main.mm @@ -3,7 +3,9 @@ #include #include #include -#include +#include +#include +#include #import @@ -70,13 +72,39 @@ } @end +// Returns the path to the default cache database on this system. +const std::string &defaultCacheDatabase() { + static const std::string path = []() -> std::string { + NSArray *paths = NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, YES); + if ([paths count] == 0) { + // Disable the cache if we don't have a location to write. + return ""; + } + + NSString *p = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Mapbox GL"]; + + if (![[NSFileManager defaultManager] createDirectoryAtPath:p + withIntermediateDirectories:YES + attributes:nil + error:nil]) { + // Disable the cache if we couldn't create the directory. + return ""; + } + + return [[p stringByAppendingPathComponent:@"cache.db"] UTF8String]; + }(); + return path; +} + int main() { mbgl::Log::Set(); GLFWView view; - mbgl::CachingHTTPFileSource fileSource(mbgl::platform::defaultCacheDatabase()); + + mbgl::SQLiteCache cache(defaultCacheDatabase()); + mbgl::DefaultFileSource fileSource(&cache); mbgl::Map map(view, fileSource); - mbgl::CachingHTTPFileSource *fileSourcePtr = &fileSource; URLHandler *handler = [[URLHandler alloc] init]; [handler setMap:&map]; @@ -86,7 +114,7 @@ int main() { // Notify map object when network reachability status changes. Reachability* reachability = [Reachability reachabilityForInternetConnection]; reachability.reachableBlock = ^(Reachability *) { - fileSourcePtr->setReachability(true); + mbgl::NetworkStatus::Reachable(); }; [reachability startNotifier]; @@ -99,7 +127,7 @@ int main() { // Set access token if present NSString *accessToken = [[NSProcessInfo processInfo] environment][@"MAPBOX_ACCESS_TOKEN"]; if (!accessToken) mbgl::Log::Warning(mbgl::Event::Setup, "No access token set. Mapbox vector tiles won't work."); - if (accessToken) fileSource.setAccessToken([accessToken cStringUsingEncoding:[NSString defaultCStringEncoding]]); + if (accessToken) map.setAccessToken([accessToken cStringUsingEncoding:[NSString defaultCStringEncoding]]); // Load style map.setStyleURL("asset://styles/bright-v7.json"); diff --git a/macosx/mapboxgl-app.gyp b/macosx/mapboxgl-app.gyp index 192604d3c..37280286e 100644 --- a/macosx/mapboxgl-app.gyp +++ b/macosx/mapboxgl-app.gyp @@ -3,10 +3,24 @@ '../gyp/common.gypi', ], 'targets': [ - { - 'target_name': 'osxapp', + { 'target_name': 'osxapp', 'product_name': 'Mapbox GL', 'type': 'executable', + 'product_extension': 'app', + 'mac_bundle': 1, + 'mac_bundle_resources': [ + 'Icon.icns', + ], + + 'dependencies': [ + '../mbgl.gyp:bundle_styles', + '../mbgl.gyp:core', + '../mbgl.gyp:platform-<(platform_lib)', + '../mbgl.gyp:http-<(http_lib)', + '../mbgl.gyp:asset-<(asset_lib)', + '../mbgl.gyp:cache-<(cache_lib)', + ], + 'sources': [ './main.mm', '../platform/darwin/settings_nsuserdefaults.hpp', @@ -15,51 +29,34 @@ '../platform/default/glfw_view.hpp', '../platform/default/glfw_view.cpp', ], - 'product_extension': 'app', - 'mac_bundle': 1, - 'mac_bundle_resources': [ - 'Icon.icns', + + 'variables' : { + 'cflags_cc': [ + '<@(glfw3_cflags)', + ], + 'ldflags': [ + '-framework SystemConfiguration', # For NSUserDefaults and Reachability + '<@(glfw3_ldflags)', + ], + 'libraries': [ + '<@(glfw3_static_libs)', + ], + }, + + 'libraries': [ + '<@(libraries)', ], + 'xcode_settings': { 'SDKROOT': 'macosx', 'SUPPORTED_PLATFORMS':'macosx', - 'OTHER_CPLUSPLUSFLAGS': [ - '<@(glfw3_cflags)' - ], - 'OTHER_LDFLAGS': [ - '<@(glfw3_ldflags)', - '-framework SystemConfiguration', - ], + 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], + 'OTHER_LDFLAGS': [ '<@(ldflags)' ], 'SDKROOT': 'macosx', 'INFOPLIST_FILE': 'Info.plist', - 'MACOSX_DEPLOYMENT_TARGET':'10.9', + 'MACOSX_DEPLOYMENT_TARGET': '10.9', 'CLANG_ENABLE_OBJC_ARC': 'YES' }, - 'variables' : { - 'ldflags': [ - '<@(uv_ldflags)', - '<@(uv_static_libs)', - '<@(sqlite3_static_libs)', - '<@(sqlite3_ldflags)', - '<@(glfw3_static_libs)', - '<@(glfw3_ldflags)', - '<@(zlib_ldflags)', - ] - }, - 'conditions': [ - ['OS == "mac"', { - 'xcode_settings': { - 'OTHER_LDFLAGS': [ '<@(ldflags)' ], - } - }, { - 'ldflags': [ '<@(ldflags)' ], - }] - ], - 'dependencies': [ - '../mapboxgl.gyp:bundle_styles', - '../mapboxgl.gyp:mbgl-core', - '../mapboxgl.gyp:mbgl-osx', - ] } ] } diff --git a/mapboxgl.gyp b/mapboxgl.gyp deleted file mode 100644 index 7ce215dc6..000000000 --- a/mapboxgl.gyp +++ /dev/null @@ -1,13 +0,0 @@ -{ - 'includes': [ - './gyp/common.gypi', - './gyp/shaders.gypi', - './gyp/version.gypi', - './gyp/styles.gypi', - './gyp/certificates.gypi', - './gyp/mbgl-core.gypi', - './gyp/mbgl-platform.gypi', - './gyp/mbgl-headless.gypi', - './gyp/install.gypi', - ], -} diff --git a/mbgl.gyp b/mbgl.gyp new file mode 100644 index 000000000..b6b00455e --- /dev/null +++ b/mbgl.gyp @@ -0,0 +1,26 @@ +{ + 'includes': [ + './gyp/common.gypi', + './gyp/shaders.gypi', + './gyp/version.gypi', + './gyp/styles.gypi', + './gyp/certificates.gypi', + './gyp/standalone.gypi', + './gyp/core.gypi', + './gyp/none.gypi', + './gyp/install.gypi', + ], + 'conditions': [ + ['headless_lib == "cgl"', { 'includes': [ './gyp/headless-cgl.gypi' ] } ], + ['headless_lib == "glx"', { 'includes': [ './gyp/headless-glx.gypi' ] } ], + ['platform_lib == "osx"', { 'includes': [ './gyp/platform-osx.gypi' ] } ], + ['platform_lib == "ios"', { 'includes': [ './gyp/platform-ios.gypi' ] } ], + ['platform_lib == "linux"', { 'includes': [ './gyp/platform-linux.gypi' ] } ], + ['platform_lib == "android"', { 'includes': [ './gyp/platform-android.gypi' ] } ], + ['http_lib == "curl"', { 'includes': [ './gyp/http-curl.gypi' ] } ], + ['http_lib == "nsurl"', { 'includes': [ './gyp/http-nsurl.gypi' ] } ], + ['asset_lib == "fs"', { 'includes': [ './gyp/asset-fs.gypi' ] } ], + ['asset_lib == "zip"', { 'includes': [ './gyp/asset-zip.gypi' ] } ], + ['cache_lib == "sqlite"', { 'includes': [ './gyp/cache-sqlite.gypi' ] } ], + ], +} diff --git a/platform/android/asset_request_libzip.cpp b/platform/android/asset_request_libzip.cpp deleted file mode 100644 index 77f9ae7da..000000000 --- a/platform/android/asset_request_libzip.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include -#include -#include -#include -#include - -#include -// NOTE a bug in the Android NDK breaks std::errno -// See https://code.google.com/p/android/issues/detail?id=72349 -// After this is fixed change usage errno to std::errno -#include - -namespace mbgl { - -struct AssetRequestBaton { - AssetRequestBaton(AssetRequest *request_, const std::string &path, uv_loop_t *loop); - ~AssetRequestBaton(); - - const std::thread::id threadId; - AssetRequest *request = nullptr; - std::unique_ptr asyncRun; - std::string path; - bool canceled = false; - - void cancel(); - static void notifyError(AssetRequestBaton *ptr, const int code, const char *message); - static void notifySuccess(AssetRequestBaton *ptr, const std::string body); - static void cleanup(AssetRequestBaton *ptr); - static void run(AssetRequestBaton *ptr); -}; - -AssetRequestBaton::AssetRequestBaton(AssetRequest *request_, const std::string &path_, uv_loop_t *loop) -: threadId(std::this_thread::get_id()), -request(request_), -path(path_) { - - asyncRun = mbgl::util::make_unique(loop, [this]() { - run(this); - }); - - asyncRun->send(); -} - -AssetRequestBaton::~AssetRequestBaton() { -} - -void AssetRequestBaton::cancel() { - canceled = true; -} - -void AssetRequestBaton::notifyError(AssetRequestBaton *ptr, const int code, const char *message) { - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->request && !ptr->canceled) { - ptr->request->response = std::unique_ptr(new Response); - ptr->request->response->code = code; - ptr->request->response->message = message; - ptr->request->notify(); - } -} - -void AssetRequestBaton::notifySuccess(AssetRequestBaton *ptr, const std::string body) { - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->request && !ptr->canceled) { - ptr->request->response = std::unique_ptr(new Response); - ptr->request->response->code = 200; - ptr->request->response->data = body; - ptr->request->notify(); - } -} - -void AssetRequestBaton::cleanup(AssetRequestBaton *ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->request) { - ptr->request->ptr = nullptr; - } - - ptr->asyncRun.reset(); - - delete ptr; - ptr = nullptr; -} - -void AssetRequestBaton::run(AssetRequestBaton *ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->canceled || !ptr->request) { - // Either the AssetRequest object has been destructed, or the - // request was canceled. - cleanup(ptr); - return; - } - - int error = 0; - struct zip *apk = zip_open(mbgl::android::apkPath.c_str(), 0, &error); - if ((apk == nullptr) || ptr->canceled || !ptr->request) { - // Opening the APK failed or was canceled. There isn't much left we can do. - const int messageSize = zip_error_to_str(nullptr, 0, error, errno); - const std::unique_ptr message = mbgl::util::make_unique(messageSize); - zip_error_to_str(message.get(), 0, error, errno); - notifyError(ptr, 500, message.get()); - cleanup(ptr); - return; - } - - std::string apkFilePath = "assets/" + ptr->path; - struct zip_file *apkFile = zip_fopen(apk, apkFilePath.c_str(), ZIP_FL_NOCASE); - if ((apkFile == nullptr) || ptr->canceled || !ptr->request) { - // Opening the asset failed or was canceled. We already have an open file handle - // though, which we'll have to close. - zip_error_get(apk, &error, nullptr); - notifyError(ptr, error == ZIP_ER_NOENT ? 404 : 500, zip_strerror(apk)); - zip_close(apk); - apk = nullptr; - cleanup(ptr); - return; - } - - struct zip_stat stat; - if ((zip_stat(apk, apkFilePath.c_str(), ZIP_FL_NOCASE, &stat) != 0) || ptr->canceled || !ptr->request) { - // Stating failed or was canceled. We already have an open file handle - // though, which we'll have to close. - notifyError(ptr, 500, zip_strerror(apk)); - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - cleanup(ptr); - return; - } - - const std::unique_ptr data = mbgl::util::make_unique(stat.size); - - if (static_cast(zip_fread(apkFile, reinterpret_cast(data.get()), stat.size)) != stat.size || ptr->canceled || !ptr->request) { - // Reading failed or was canceled. We already have an open file handle - // though, which we'll have to close. - notifyError(ptr, 500, zip_file_strerror(apkFile)); - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - cleanup(ptr); - return; - } - - std::string body(data.get(), stat.size); - notifySuccess(ptr, body); - - if (zip_fclose(apkFile) != 0) { - // Closing the asset failed. But there isn't anything we can do. - } - apkFile = nullptr; - - if (zip_close(apk) != 0) { - // Closing the APK failed. But there isn't anything we can do. - } - apk = nullptr; - - cleanup(ptr); -} - -AssetRequest::AssetRequest(const std::string &path_, uv_loop_t *loop) -: BaseRequest(path_) { - if (!path.empty() && path[0] == '/') { - // This is an absolute path. We don't allow this. Note that this is not a way to absolutely - // prevent access to resources outside the application bundle; e.g. there could be symlinks - // in the application bundle that link to outside. We don't care about these. - response = util::make_unique(); - response->code = 403; - response->message = "Path is outside the application bundle"; - notify(); - } else { - // Note: The AssetRequestBaton object is deleted in AssetRequestBaton::cleanup(). - ptr = new AssetRequestBaton(this, path, loop); - } -} - -void AssetRequest::cancel() { - assert(std::this_thread::get_id() == threadId); - - if (ptr) { - ptr->cancel(); - - // When deleting a AssetRequest object with a uv_fs_* call is in progress, we are making sure - // that the callback doesn't accidentally reference this object again. - ptr->request = nullptr; - ptr = nullptr; - } - - notify(); -} - -AssetRequest::~AssetRequest() { - assert(std::this_thread::get_id() == threadId); - cancel(); - - // Note: The AssetRequestBaton object is deleted in AssetRequestBaton::cleanup(). -} - -} diff --git a/platform/android/cache_database_data.cpp b/platform/android/cache_database_data.cpp deleted file mode 100644 index 2fefcdc4a..000000000 --- a/platform/android/cache_database_data.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include -#include - -namespace mbgl { -namespace platform { - -// Returns the path to the default cache database on this system. -std::string defaultCacheDatabase() { - return mbgl::android::cachePath + "/mbgl-cache.db"; -} - -} -} diff --git a/platform/darwin/application_root.mm b/platform/darwin/application_root.mm index 19b872c54..d4702c7ec 100644 --- a/platform/darwin/application_root.mm +++ b/platform/darwin/application_root.mm @@ -5,8 +5,8 @@ namespace mbgl { namespace platform { -// Returns the path to the default shader cache on this system. -std::string applicationRoot() { +// Returns the path to the root folder of the application. +const std::string &applicationRoot() { static const std::string root = []() -> std::string { NSString *path = [[[NSBundle mainBundle] resourceURL] path]; return {[path cStringUsingEncoding : NSUTF8StringEncoding], diff --git a/platform/darwin/asset_root.mm b/platform/darwin/asset_root.mm new file mode 100644 index 000000000..375975a84 --- /dev/null +++ b/platform/darwin/asset_root.mm @@ -0,0 +1,18 @@ +#import + +#include + +namespace mbgl { +namespace platform { + +// Returns the path to the root folder of the application. +const std::string &assetRoot() { + static const std::string root = []() -> std::string { + NSString *path = [[[NSBundle mainBundle] resourceURL] path]; + return {[path cStringUsingEncoding : NSUTF8StringEncoding], + [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding]}; + }(); + return root; +} +} +} diff --git a/platform/darwin/http_request_baton_cocoa.mm b/platform/darwin/http_request_baton_cocoa.mm deleted file mode 100644 index 4a59837e3..000000000 --- a/platform/darwin/http_request_baton_cocoa.mm +++ /dev/null @@ -1,155 +0,0 @@ -#include -#include -#include -#include -#include - -#include - -#include - -#import - -namespace mbgl { - -dispatch_once_t request_initialize = 0; -NSURLSession *session = nullptr; - -NSString *userAgent = nil; - -void HTTPRequestBaton::start(const util::ptr &ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - - // Starts the request. - util::ptr baton = ptr; - - dispatch_once(&request_initialize, ^{ - NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; - sessionConfig.timeoutIntervalForResource = 30; - sessionConfig.HTTPMaximumConnectionsPerHost = 8; - sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; - sessionConfig.URLCache = nil; - - session = [NSURLSession sessionWithConfiguration:sessionConfig]; - - // Write user agent string - NSDictionary *systemVersion = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]; - userAgent = [NSString stringWithFormat:@"MapboxGL/%d.%d.%d (+https://mapbox.com/mapbox-gl/; %s; %@ %@)", - version::major, version::minor, version::patch, version::revision, - [systemVersion objectForKey:@"ProductName"], - [systemVersion objectForKey:@"ProductVersion"] - ]; - }); - - NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@(baton->path.c_str())]]; - if (baton->response) { - if (!baton->response->etag.empty()) { - [request addValue:@(baton->response->etag.c_str()) forHTTPHeaderField:@"If-None-Match"]; - } else if (baton->response->modified) { - const std::string time = util::rfc1123(baton->response->modified); - [request addValue:@(time.c_str()) forHTTPHeaderField:@"If-Modified-Since"]; - } - } - - [request addValue:userAgent forHTTPHeaderField:@"User-Agent"]; - - NSURLSessionDataTask *task = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *res, NSError *error) { - if (error) { - if ([error code] == NSURLErrorCancelled) { - // The response code remains at 0 to indicate cancelation. - // In addition, we don't need any response object. - baton->response.reset(); - baton->type = HTTPResponseType::Canceled; - } else { - // TODO: Use different codes for host not found, timeout, invalid URL etc. - // These can be categorized in temporary and permanent errors. - baton->response = util::make_unique(); - baton->response->code = [(NSHTTPURLResponse *)res statusCode]; - baton->response->message = [[error localizedDescription] UTF8String]; - - switch ([error code]) { - case NSURLErrorBadServerResponse: // 5xx errors - baton->type = HTTPResponseType::TemporaryError; - break; - - case NSURLErrorTimedOut: - case NSURLErrorUserCancelledAuthentication: - baton->type = HTTPResponseType::SingularError; // retry immediately - break; - - case NSURLErrorNetworkConnectionLost: - case NSURLErrorCannotFindHost: - case NSURLErrorCannotConnectToHost: - case NSURLErrorDNSLookupFailed: - case NSURLErrorNotConnectedToInternet: - case NSURLErrorInternationalRoamingOff: - case NSURLErrorCallIsActive: - case NSURLErrorDataNotAllowed: - baton->type = HTTPResponseType::ConnectionError; - break; - - default: - baton->type = HTTPResponseType::PermanentError; - } - } - } else if ([res isKindOfClass:[NSHTTPURLResponse class]]) { - const long code = [(NSHTTPURLResponse *)res statusCode]; - if (code == 304) { - // Assume a Response object already exists. - assert(baton->response); - } else { - baton->response = util::make_unique(); - baton->response->code = code; - baton->response->data = {(const char *)[data bytes], [data length]}; - } - - if (code == 304) { - baton->type = HTTPResponseType::NotModified; - } else if (code == 200) { - baton->type = HTTPResponseType::Successful; - } else { - baton->type = HTTPResponseType::PermanentError; - } - - NSDictionary *headers = [(NSHTTPURLResponse *)res allHeaderFields]; - NSString *cache_control = [headers objectForKey:@"Cache-Control"]; - if (cache_control) { - baton->response->expires = Response::parseCacheControl([cache_control UTF8String]); - } - - NSString *last_modified = [headers objectForKey:@"Last-Modified"]; - if (last_modified) { - baton->response->modified = parse_date([last_modified UTF8String]); - } - - NSString *etag = [headers objectForKey:@"ETag"]; - if (etag) { - baton->response->etag = [etag UTF8String]; - } - } else { - // This should never happen. - baton->type = HTTPResponseType::PermanentError; - baton->response = util::make_unique(); - baton->response->code = -1; - baton->response->message = "response class is not NSHTTPURLResponse"; - } - - uv_async_send(baton->async); - }]; - - [task resume]; - - baton->ptr = const_cast(CFBridgingRetain(task)); -} - -void HTTPRequestBaton::stop(const util::ptr &ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - assert(ptr->ptr); - - NSURLSessionDataTask *task = CFBridgingRelease(ptr->ptr); - ptr->ptr = nullptr; - [task cancel]; -} - -} diff --git a/platform/darwin/http_request_nsurl.mm b/platform/darwin/http_request_nsurl.mm new file mode 100644 index 000000000..83c010f8b --- /dev/null +++ b/platform/darwin/http_request_nsurl.mm @@ -0,0 +1,419 @@ +#include +#include +#include +#include + +#include +#include + +#import + +#include +#include + +namespace mbgl { + +enum class ResponseStatus : uint8_t { + // This error probably won't be resolved by retrying anytime soon. We are giving up. + PermanentError, + + // This error might be resolved by waiting some time (e.g. server issues). + // We are going to do an exponential back-off and will try again in a few seconds. + TemporaryError, + + // This error was caused by a temporary error and it is likely that it will be resolved + // immediately. We are going to try again right away. This is like the TemporaryError, except + // that we will not perform exponential back-off. + SingularError, + + // This error might be resolved once the network reachability status changes. + // We are going to watch the network status for changes and will retry as soon as the + // operating system notifies us of a network status change. + ConnectionError, + + // The request was canceled mid-way. + Canceled, + + // The request returned data successfully. We retrieved and decoded the data successfully. + Successful, + + // The request confirmed that the data wasn't changed. We already have the data. + NotModified, +}; + +// ------------------------------------------------------------------------------------------------- + +class HTTPNSURLContext; + +class HTTPRequestImpl { +public: + HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr response); + ~HTTPRequestImpl(); + + void cancel(); + void cancelTimer(); + + void start(); + void handleResult(NSData *data, NSURLResponse *res, NSError *error); + void handleResponse(); + + void retry(uint64_t timeout); + void retryImmediately(); + static void restart(uv_timer_t *timer, int); + +private: + HTTPNSURLContext *context = nullptr; + HTTPRequest *request = nullptr; + NSURLSessionDataTask *task = nullptr; + std::unique_ptr response; + std::unique_ptr existingResponse; + ResponseStatus status = ResponseStatus::PermanentError; + uv_async_t *async = nullptr; + int attempts = 0; + uv_timer_t *timer = nullptr; + enum : bool { PreemptImmediately, ExponentialBackoff } strategy = PreemptImmediately; + + static const int maxAttempts = 4; +}; + +// ------------------------------------------------------------------------------------------------- + +class HTTPNSURLContext : public HTTPContext { +public: + HTTPNSURLContext(uv_loop_t *loop); + ~HTTPNSURLContext(); + + NSURLSession *session = nil; + NSString *userAgent = nil; +}; + +template<> pthread_key_t ThreadContext::key{}; +template<> pthread_once_t ThreadContext::once = PTHREAD_ONCE_INIT; + +HTTPNSURLContext::HTTPNSURLContext(uv_loop_t *loop_) : HTTPContext(loop_) { + @autoreleasepool { + NSURLSessionConfiguration *sessionConfig = + [NSURLSessionConfiguration defaultSessionConfiguration]; + sessionConfig.timeoutIntervalForResource = 30; + sessionConfig.HTTPMaximumConnectionsPerHost = 8; + sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + sessionConfig.URLCache = nil; + + session = [NSURLSession sessionWithConfiguration:sessionConfig]; + [session retain]; + + // Write user agent string + userAgent = @"MapboxGL"; + } +} + +HTTPNSURLContext::~HTTPNSURLContext() { + [session release]; + session = nullptr; + + [userAgent release]; + userAgent = nullptr; +} + +// ------------------------------------------------------------------------------------------------- + +HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, + std::unique_ptr existingResponse_) + : context(HTTPNSURLContext::Get(loop)), + request(request_), + existingResponse(std::move(existingResponse_)), + async(new uv_async_t) { + assert(request); + context->addRequest(request); + + async->data = this; + uv_async_init(loop, async, [](uv_async_t *as, int) { + auto impl = reinterpret_cast(as->data); + impl->handleResponse(); + }); + + start(); +} + +void HTTPRequestImpl::start() { + assert(!task); + + attempts++; + + @autoreleasepool { + NSMutableURLRequest *req = [[NSMutableURLRequest alloc] + initWithURL:[NSURL URLWithString:@(request->resource.url.c_str())]]; + if (existingResponse) { + if (!existingResponse->etag.empty()) { + [req addValue:@(existingResponse->etag.c_str()) forHTTPHeaderField:@"If-None-Match"]; + } else if (existingResponse->modified) { + const std::string time = util::rfc1123(existingResponse->modified); + [req addValue:@(time.c_str()) forHTTPHeaderField:@"If-Modified-Since"]; + } + } + + [req addValue:context->userAgent forHTTPHeaderField:@"User-Agent"]; + + task = [context->session dataTaskWithRequest:req + completionHandler:^(NSData *data, NSURLResponse *res, + NSError *error) { handleResult(data, res, error); }]; + [req release]; + [task retain]; + [task resume]; + } +} + +void HTTPRequestImpl::handleResponse() { + if (task) { + [task release]; + task = nullptr; + } + + if (request) { + if (status == ResponseStatus::TemporaryError && attempts < maxAttempts) { + strategy = ExponentialBackoff; + return retry((1 << (attempts - 1)) * 1000); + } else if (status == ResponseStatus::ConnectionError && attempts < maxAttempts) { + // By default, we will retry every 30 seconds (network change notification will + // preempt the timeout). + strategy = PreemptImmediately; + return retry(30000); + } + + // Actually return the response. + if (status == ResponseStatus::NotModified) { + request->notify(std::move(response), FileCache::Hint::Refresh); + } else { + request->notify(std::move(response), FileCache::Hint::Full); + } + + context->removeRequest(request); + delete request; + request = nullptr; + } + + delete this; +} + +void HTTPRequestImpl::cancel() { + context->removeRequest(request); + request = nullptr; + + // Stop the backoff timer to avoid re-triggering this request. + cancelTimer(); + + if (task) { + [task cancel]; + [task release]; + task = nullptr; + } +} + +void HTTPRequestImpl::cancelTimer() { + if (timer) { + uv_timer_stop(timer); + uv::close(timer); + timer = nullptr; + } +} + +HTTPRequestImpl::~HTTPRequestImpl() { + assert(!task); + assert(async); + + // Stop the backoff timer to avoid re-triggering this request. + cancelTimer(); + + uv::close(async); + + if (request) { + context->removeRequest(request); + request->ptr = nullptr; + } +} + +int64_t parseCacheControl(const char *value) { + if (value) { + unsigned long long seconds = 0; + // TODO: cache-control may contain other information as well: + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + if (std::sscanf(value, "max-age=%llu", &seconds) == 1) { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count() + + seconds; + } + } + + return 0; +} + +void HTTPRequestImpl::handleResult(NSData *data, NSURLResponse *res, NSError *error) { + if (error) { + if ([error code] == NSURLErrorCancelled) { + status = ResponseStatus::Canceled; + } else { + // TODO: Use different codes for host not found, timeout, invalid URL etc. + // These can be categorized in temporary and permanent errors. + response = util::make_unique(); + response->status = Response::Error; + response->message = [[error localizedDescription] UTF8String]; + + switch ([error code]) { + case NSURLErrorBadServerResponse: // 5xx errors + status = ResponseStatus::TemporaryError; + break; + + case NSURLErrorTimedOut: + case NSURLErrorUserCancelledAuthentication: + status = ResponseStatus::SingularError; // retry immediately + break; + + case NSURLErrorNetworkConnectionLost: + case NSURLErrorCannotFindHost: + case NSURLErrorCannotConnectToHost: + case NSURLErrorDNSLookupFailed: + case NSURLErrorNotConnectedToInternet: + case NSURLErrorInternationalRoamingOff: + case NSURLErrorCallIsActive: + case NSURLErrorDataNotAllowed: + status = ResponseStatus::ConnectionError; + break; + + default: + status = ResponseStatus::PermanentError; + } + } + } else if ([res isKindOfClass:[NSHTTPURLResponse class]]) { + const long responseCode = [(NSHTTPURLResponse *)res statusCode]; + + response = util::make_unique(); + response->data = {(const char *)[data bytes], [data length]}; + + NSDictionary *headers = [(NSHTTPURLResponse *)res allHeaderFields]; + NSString *cache_control = [headers objectForKey:@"Cache-Control"]; + if (cache_control) { + response->expires = parseCacheControl([cache_control UTF8String]); + } + + NSString *expires = [headers objectForKey:@"Expires"]; + if (expires) { + response->expires = parse_date([expires UTF8String]); + } + + NSString *last_modified = [headers objectForKey:@"Last-Modified"]; + if (last_modified) { + response->modified = parse_date([last_modified UTF8String]); + } + + NSString *etag = [headers objectForKey:@"ETag"]; + if (etag) { + response->etag = [etag UTF8String]; + } + + 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; + } + status = ResponseStatus::NotModified; + } else { + // This is an unsolicited 304 response and should only happen on malfunctioning + // HTTP servers. It likely doesn't include any data, but we don't have much options. + response->status = Response::Successful; + status = ResponseStatus::Successful; + } + } else if (responseCode == 200) { + response->status = Response::Successful; + status = ResponseStatus::Successful; + } else if (responseCode >= 500 && responseCode < 600) { + // Server errors may be temporary, so back off exponentially. + response->status = Response::Error; + response->message = "HTTP status code " + std::to_string(responseCode); + status = ResponseStatus::TemporaryError; + } else { + // We don't know how to handle any other errors, so declare them as permanently failing. + response->status = Response::Error; + response->message = "HTTP status code " + std::to_string(responseCode); + status = ResponseStatus::PermanentError; + } + } else { + // This should never happen. + status = ResponseStatus::PermanentError; + response = util::make_unique(); + response->status = Response::Error; + response->message = "response class is not NSHTTPURLResponse"; + } + + uv_async_send(async); +} + +void HTTPRequestImpl::retry(uint64_t timeout) { + response.reset(); + + assert(!timer); + timer = new uv_timer_t; + timer->data = this; + uv_timer_init(async->loop, timer); + uv_timer_start(timer, restart, timeout, 0); +} + +void HTTPRequestImpl::retryImmediately() { + // All batons get notified when the network status changed, but some of them + // might not actually wait for the network to become available again. + if (timer && strategy == PreemptImmediately) { + // Triggers the timer upon the next event loop iteration. + uv_timer_stop(timer); + uv_timer_start(timer, restart, 0, 0); + } +} + +void HTTPRequestImpl::restart(uv_timer_t *timer, int) { + // Restart the request. + auto impl = reinterpret_cast(timer->data); + + // Get rid of the timer. + impl->timer = nullptr; + uv::close(timer); + + impl->start(); +} + +// ------------------------------------------------------------------------------------------------- + +HTTPRequest::HTTPRequest(DefaultFileSource *source, const Resource &resource) + : SharedRequestBase(source, resource) { +} + +HTTPRequest::~HTTPRequest() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->cancel(); + } +} + +void HTTPRequest::start(uv_loop_t *loop, std::unique_ptr response) { + MBGL_VERIFY_THREAD(tid); + + assert(!ptr); + ptr = new HTTPRequestImpl(this, loop, std::move(response)); +} + +void HTTPRequest::retryImmediately() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->retryImmediately(); + } +} + +void HTTPRequest::cancel() { + MBGL_VERIFY_THREAD(tid); + + delete this; +} + +} diff --git a/platform/darwin/log_nslog.mm b/platform/darwin/log_nslog.mm index b196930b2..ea5fddf0b 100644 --- a/platform/darwin/log_nslog.mm +++ b/platform/darwin/log_nslog.mm @@ -7,14 +7,13 @@ namespace mbgl { void NSLogBackend::record(EventSeverity severity, Event event, const std::string &msg) { - NSLog(@"[%s] %s: %@", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), - [[NSString alloc] initWithBytes:msg.data() - length:msg.size() - encoding:NSUTF8StringEncoding]); + NSString *message = + [[NSString alloc] initWithBytes:msg.data() length:msg.size() encoding:NSUTF8StringEncoding]; + NSLog(@"[%s] %s: %@", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), message); + [message release]; } - -void NSLogBackend::record(EventSeverity severity, Event event, const char* format, ...) { +void NSLogBackend::record(EventSeverity severity, Event event, const char *format, ...) { va_list args; va_start(args, format); const size_t len = vsnprintf(NULL, 0, format, args); @@ -23,17 +22,22 @@ void NSLogBackend::record(EventSeverity severity, Event event, const char* forma va_start(args, format); vsnprintf(buffer.get(), len + 1, format, args); va_end(args); - NSLog(@"[%s] %s: %s", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), buffer.get()); + NSLog(@"[%s] %s: %s", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), + buffer.get()); } void NSLogBackend::record(EventSeverity severity, Event event, int64_t code) { - NSLog(@"[%s] %s: (%lld)", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), code); + NSLog(@"[%s] %s: (%lld)", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), + code); } -void NSLogBackend::record(EventSeverity severity, Event event, int64_t code, const std::string &msg) { - NSLog(@"[%s] %s: (%lld) %@", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), code, - [[NSString alloc] initWithBytes:msg.data() - length:msg.size() - encoding:NSUTF8StringEncoding]); +void NSLogBackend::record(EventSeverity severity, Event event, int64_t code, + const std::string &msg) { + NSString *message = + [[NSString alloc] initWithBytes:msg.data() length:msg.size() encoding:NSUTF8StringEncoding]; + NSLog(@"[%s] %s: (%lld) %@", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), + code, message); + [message release]; } + } diff --git a/platform/darwin/string_nsstring.mm b/platform/darwin/string_nsstring.mm index 9b1dc745c..86c2c07ed 100644 --- a/platform/darwin/string_nsstring.mm +++ b/platform/darwin/string_nsstring.mm @@ -6,15 +6,27 @@ namespace mbgl { namespace platform { std::string uppercase(const std::string &string) { - NSString *nsstring = [[NSString alloc] initWithBytesNoCopy:const_cast(string.data()) length:string.size() encoding:NSUTF8StringEncoding freeWhenDone:NO]; - nsstring = [nsstring uppercaseString]; - return { [nsstring cStringUsingEncoding:NSUTF8StringEncoding], [nsstring lengthOfBytesUsingEncoding:NSUTF8StringEncoding] }; + NSString *original = [[NSString alloc] initWithBytesNoCopy:const_cast(string.data()) + length:string.size() + encoding:NSUTF8StringEncoding + freeWhenDone:NO]; + NSString *uppercase = [original uppercaseString]; + const std::string result{[uppercase cStringUsingEncoding : NSUTF8StringEncoding], + [uppercase lengthOfBytesUsingEncoding:NSUTF8StringEncoding]}; + [original release]; + return result; } std::string lowercase(const std::string &string) { - NSString *nsstring = [[NSString alloc] initWithBytesNoCopy:const_cast(string.data()) length:string.size() encoding:NSUTF8StringEncoding freeWhenDone:NO]; - nsstring = [nsstring lowercaseString]; - return { [nsstring cStringUsingEncoding:NSUTF8StringEncoding], [nsstring lengthOfBytesUsingEncoding:NSUTF8StringEncoding] }; + NSString *original = [[NSString alloc] initWithBytesNoCopy:const_cast(string.data()) + length:string.size() + encoding:NSUTF8StringEncoding + freeWhenDone:NO]; + NSString *lowercase = [original lowercaseString]; + const std::string result{[lowercase cStringUsingEncoding : NSUTF8StringEncoding], + [lowercase lengthOfBytesUsingEncoding:NSUTF8StringEncoding]}; + [original release]; + return result; } } diff --git a/platform/default/application_root.cpp b/platform/default/application_root.cpp index f25a44d46..6669a049a 100644 --- a/platform/default/application_root.cpp +++ b/platform/default/application_root.cpp @@ -1,13 +1,26 @@ #include -#include +#include +#include namespace mbgl { namespace platform { -// Returns the path the application root. -std::string applicationRoot() { - static const std::string root = uv::cwd(); +// Returns the path to the root folder of the application. +const std::string &applicationRoot() { + static const std::string root = []() -> std::string { + size_t max = 0; + std::string dir; + do { + // Gradually increase the length of the string in case the path was truncated. + max += 256; + dir.resize(max); + uv_exepath(const_cast(dir.data()), &max); + } while (max == dir.size()); + dir.resize(max - 1); + dir = dirname(const_cast(dir.c_str())); + return dir; + }(); return root; } diff --git a/platform/default/asset_request_fs.cpp b/platform/default/asset_request_fs.cpp new file mode 100644 index 000000000..24856e520 --- /dev/null +++ b/platform/default/asset_request_fs.cpp @@ -0,0 +1,252 @@ +#include +#include +#include +#include +#include +#include + +#include + +#pragma GCC diagnostic push +#ifndef __clang__ +#pragma GCC diagnostic ignored "-Wunused-local-typedefs" +#pragma GCC diagnostic ignored "-Wshadow" +#endif +#include +#pragma GCC diagnostic pop + +#include + + +namespace algo = boost::algorithm; + +namespace mbgl { + +class AssetRequestImpl { + MBGL_STORE_THREAD(tid) + +public: + AssetRequestImpl(AssetRequest *request, uv_loop_t *loop); + ~AssetRequestImpl(); + + static void fileOpened(uv_fs_t *req); + static void fileStated(uv_fs_t *req); + static void fileRead(uv_fs_t *req); + static void fileClosed(uv_fs_t *req); + static void notifyError(uv_fs_t *req); + static void cleanup(uv_fs_t *req); + + + AssetRequest *request = nullptr; + bool canceled = false; + uv_fs_t req; + uv_file fd = -1; + uv_buf_t buffer; + std::unique_ptr response; +}; + +AssetRequestImpl::~AssetRequestImpl() { + MBGL_VERIFY_THREAD(tid); + + if (request) { + request->ptr = nullptr; + } +} + +AssetRequestImpl::AssetRequestImpl(AssetRequest *request_, uv_loop_t *loop) : request(request_) { + req.data = this; + + const auto &url = request->resource.url; + std::string path; + if (url.size() <= 8 || url[8] == '/') { + // This is an empty or absolute path. + path = url.substr(8); + } else { + // This is a relative path. Prefix with the application root. + path = platform::assetRoot() + "/" + url.substr(8); + } + + uv_fs_open(loop, &req, path.c_str(), O_RDONLY, S_IRUSR, fileOpened); +} + +void AssetRequestImpl::fileOpened(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + + if (req->result < 0) { + // Opening failed or was canceled. There isn't much left we can do. + notifyError(req); + cleanup(req); + } else { + const uv_file fd = uv_file(req->result); + + // We're going to reuse this handle, so we need to cleanup first. + uv_fs_req_cleanup(req); + + if (self->canceled) { + // The request was canceled. + uv_fs_close(req->loop, req, fd, fileClosed); + } else { + self->fd = fd; + uv_fs_fstat(req->loop, req, fd, fileStated); + } + } +} + +void AssetRequestImpl::fileStated(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + + if (req->result != 0 || self->canceled) { + // Stating failed or was canceled. We already have an open file handle + // though, which we'll have to close. + notifyError(req); + + uv_fs_req_cleanup(req); + uv_fs_close(req->loop, req, self->fd, fileClosed); + } else { +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + auto stat = static_cast(req->ptr); +#else + auto stat = static_cast(req->ptr); +#endif + if (stat->st_size > std::numeric_limits::max()) { + // File is too large for us to open this way because uv_buf's only support unsigned + // ints as maximum size. + auto response = util::make_unique(); + response->status = Response::Error; +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + response->message = uv_strerror(uv_err_t {UV_EFBIG, 0}); +#else + response->message = uv_strerror(UV_EFBIG); +#endif + assert(self->request); + self->request->notify(std::move(response), FileCache::Hint::No); + delete self->request; + + uv_fs_req_cleanup(req); + uv_fs_close(req->loop, req, self->fd, fileClosed); + } else { + self->response = util::make_unique(); +#ifdef __APPLE__ + self->response->modified = stat->st_mtimespec.tv_sec; +#else + self->response->modified = stat->st_mtime; +#endif + self->response->etag = std::to_string(stat->st_ino); + const auto size = (unsigned int)(stat->st_size); + self->response->data.resize(size); + self->buffer = uv_buf_init(const_cast(self->response->data.data()), size); + uv_fs_req_cleanup(req); +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + uv_fs_read(req->loop, req, self->fd, self->buffer.base, self->buffer.len, -1, fileRead); +#else + uv_fs_read(req->loop, req, self->fd, &self->buffer, 1, 0, fileRead); +#endif + } + } +} + +void AssetRequestImpl::fileRead(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + + if (req->result < 0 || self->canceled) { + // Stating failed or was canceled. We already have an open file handle + // though, which we'll have to close. + notifyError(req); + } else { + // File was successfully read. + self->response->status = Response::Successful; + assert(self->request); + self->request->notify(std::move(self->response), FileCache::Hint::No); + delete self->request; + } + + uv_fs_req_cleanup(req); + uv_fs_close(req->loop, req, self->fd, fileClosed); +} + +void AssetRequestImpl::fileClosed(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + (void(self)); // Silence unused variable error in Release mode + + if (req->result < 0) { + // Closing the file failed. But there isn't anything we can do. + } + + cleanup(req); +} + +void AssetRequestImpl::notifyError(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + + if (req->result < 0 && !self->canceled && req->result != UV_ECANCELED) { + auto response = util::make_unique(); + response->status = Response::Error; + response->message = uv::getFileRequestError(req); + assert(self->request); + self->request->notify(std::move(response), FileCache::Hint::No); + delete self->request; + } +} + +void AssetRequestImpl::cleanup(uv_fs_t *req) { + assert(req->data); + auto self = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(self->tid); + uv_fs_req_cleanup(req); + delete self; +} + +// ------------------------------------------------------------------------------------------------- + +AssetRequest::AssetRequest(DefaultFileSource *source_, const Resource &resource_) + : SharedRequestBase(source_, resource_) { + assert(algo::starts_with(resource.url, "asset://")); +} + +AssetRequest::~AssetRequest() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->request = nullptr; + } +} + +void AssetRequest::start(uv_loop_t *loop, std::unique_ptr response) { + MBGL_VERIFY_THREAD(tid); + + // We're ignoring the existing response if any. + (void(response)); + + assert(!ptr); + ptr = new AssetRequestImpl(this, loop); + // Note: the AssetRequestImpl deletes itself. +} + +void AssetRequest::cancel() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->canceled = true; + + // uv_cancel fails frequently when the request has already been started. + // In that case, we have to let it complete and check the canceled bool + // instead. The cancelation callback will delete the AssetRequest object. + uv_cancel((uv_req_t *)&reinterpret_cast(ptr)->req); + } else { + // This request is canceled before we called start. We're safe to delete + // ourselves now. + delete this; + } +} + +} diff --git a/platform/default/asset_request_libuv.cpp b/platform/default/asset_request_libuv.cpp deleted file mode 100644 index 0e0b7280a..000000000 --- a/platform/default/asset_request_libuv.cpp +++ /dev/null @@ -1,223 +0,0 @@ -#include -#include -#include -#include - -#include - -#include - -namespace mbgl { - -struct AssetRequestBaton { - AssetRequestBaton(AssetRequest *request_, const std::string &path, uv_loop_t *loop); - ~AssetRequestBaton(); - - void cancel(); - static void fileOpened(uv_fs_t *req); - static void fileStated(uv_fs_t *req); - static void fileRead(uv_fs_t *req); - static void fileClosed(uv_fs_t *req); - static void notifyError(uv_fs_t *req); - static void cleanup(uv_fs_t *req); - - const std::thread::id threadId; - AssetRequest *request = nullptr; - uv_fs_t req; - uv_file fd = -1; - bool canceled = false; - std::string body; - uv_buf_t buffer; -}; - -AssetRequestBaton::AssetRequestBaton(AssetRequest *request_, const std::string &path, uv_loop_t *loop) - : threadId(std::this_thread::get_id()), request(request_) { - req.data = this; - uv_fs_open(loop, &req, path.c_str(), O_RDONLY, S_IRUSR, fileOpened); -} - -AssetRequestBaton::~AssetRequestBaton() { -} - -void AssetRequestBaton::cancel() { - canceled = true; - - // uv_cancel fails frequently when the request has already been started. - // In that case, we have to let it complete and check the canceled bool - // instead. - uv_cancel((uv_req_t *)&req); -} - -void AssetRequestBaton::notifyError(uv_fs_t *req) { - AssetRequestBaton *ptr = reinterpret_cast(req->data); - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->request && req->result < 0 && !ptr->canceled && req->result != UV_ECANCELED) { - ptr->request->response = util::make_unique(); - ptr->request->response->code = req->result == UV_ENOENT ? 404 : 500; -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 - ptr->request->response->message = uv_strerror(uv_last_error(req->loop)); -#else - ptr->request->response->message = uv_strerror(int(req->result)); -#endif - ptr->request->notify(); - } -} - -void AssetRequestBaton::fileOpened(uv_fs_t *req) { - AssetRequestBaton *ptr = reinterpret_cast(req->data); - assert(std::this_thread::get_id() == ptr->threadId); - - if (req->result < 0) { - // Opening failed or was canceled. There isn't much left we can do. - notifyError(req); - cleanup(req); - } else { - const uv_file fd = uv_file(req->result); - - // We're going to reuse this handle, so we need to cleanup first. - uv_fs_req_cleanup(req); - - if (ptr->canceled || !ptr->request) { - // Either the AssetRequest object has been destructed, or the - // request was canceled. - uv_fs_close(req->loop, req, fd, fileClosed); - } else { - ptr->fd = fd; - uv_fs_fstat(req->loop, req, fd, fileStated); - } - } -} - -void AssetRequestBaton::fileStated(uv_fs_t *req) { - AssetRequestBaton *ptr = reinterpret_cast(req->data); - assert(std::this_thread::get_id() == ptr->threadId); - - if (req->result != 0 || ptr->canceled || !ptr->request) { - // Stating failed or was canceled. We already have an open file handle - // though, which we'll have to close. - notifyError(req); - - uv_fs_req_cleanup(req); - uv_fs_close(req->loop, req, ptr->fd, fileClosed); - } else { -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 - const uv_statbuf_t *stat = static_cast(req->ptr); -#else - const uv_stat_t *stat = static_cast(req->ptr); -#endif - if (stat->st_size > std::numeric_limits::max()) { - // File is too large for us to open this way because uv_buf's only support unsigned - // ints as maximum size. - if (ptr->request) { - ptr->request->response = util::make_unique(); - ptr->request->response->code = UV_EFBIG; -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 - ptr->request->response->message = uv_strerror(uv_err_t {UV_EFBIG, 0}); -#else - ptr->request->response->message = uv_strerror(UV_EFBIG); -#endif - ptr->request->notify(); - } - - uv_fs_req_cleanup(req); - uv_fs_close(req->loop, req, ptr->fd, fileClosed); - } else { - const unsigned int size = (unsigned int)(stat->st_size); - ptr->body.resize(size); - ptr->buffer = uv_buf_init(const_cast(ptr->body.data()), size); - uv_fs_req_cleanup(req); -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 - uv_fs_read(req->loop, req, ptr->fd, ptr->buffer.base, ptr->buffer.len, -1, fileRead); -#else - uv_fs_read(req->loop, req, ptr->fd, &ptr->buffer, 1, 0, fileRead); -#endif - } - } -} - -void AssetRequestBaton::fileRead(uv_fs_t *req) { - AssetRequestBaton *ptr = reinterpret_cast(req->data); - assert(std::this_thread::get_id() == ptr->threadId); - - if (req->result < 0 || ptr->canceled || !ptr->request) { - // Reading failed or was canceled. We already have an open file handle - // though, which we'll have to close. - notifyError(req); - } else { - // File was successfully read. - if (ptr->request) { - ptr->request->response = util::make_unique(); - ptr->request->response->code = 200; - ptr->request->response->data = std::move(ptr->body); - ptr->request->notify(); - } - } - - uv_fs_req_cleanup(req); - uv_fs_close(req->loop, req, ptr->fd, fileClosed); -} - -void AssetRequestBaton::fileClosed(uv_fs_t *req) { - assert(std::this_thread::get_id() == (reinterpret_cast(req->data))->threadId); - - if (req->result < 0) { - // Closing the file failed. But there isn't anything we can do. - } - - cleanup(req); -} - -void AssetRequestBaton::cleanup(uv_fs_t *req) { - AssetRequestBaton *ptr = reinterpret_cast(req->data); - assert(std::this_thread::get_id() == ptr->threadId); - - if (ptr->request) { - ptr->request->ptr = nullptr; - } - - uv_fs_req_cleanup(req); - delete ptr; - ptr = nullptr; -} - - -AssetRequest::AssetRequest(const std::string &path_, uv_loop_t *loop) - : BaseRequest(path_) { - if (!path.empty() && path[0] == '/') { - // This is an absolute path. We don't allow this. Note that this is not a way to absolutely - // prevent access to resources outside the application bundle; e.g. there could be symlinks - // in the application bundle that link to outside. We don't care about these. - response = util::make_unique(); - response->code = 403; - response->message = "Path is outside the application bundle"; - notify(); - } else { - // Note: The AssetRequestBaton object is deleted in AssetRequestBaton::cleanup(). - ptr = new AssetRequestBaton(this, platform::applicationRoot() + "/" + path, loop); - } -} - -void AssetRequest::cancel() { - assert(std::this_thread::get_id() == threadId); - - if (ptr) { - ptr->cancel(); - - // When deleting a AssetRequest object with a uv_fs_* call is in progress, we are making sure - // that the callback doesn't accidentally reference this object again. - ptr->request = nullptr; - ptr = nullptr; - } - - notify(); -} - -AssetRequest::~AssetRequest() { - assert(std::this_thread::get_id() == threadId); - cancel(); - - // Note: The AssetRequestBaton object is deleted in AssetRequestBaton::cleanup(). -} - -} diff --git a/platform/default/asset_request_zip.cpp b/platform/default/asset_request_zip.cpp new file mode 100644 index 000000000..9a5f598bb --- /dev/null +++ b/platform/default/asset_request_zip.cpp @@ -0,0 +1,301 @@ +#include +#include +#include +#include +#include +#include + +#include "uv_zip.h" + +#pragma GCC diagnostic push +#ifndef __clang__ +#pragma GCC diagnostic ignored "-Wunused-local-typedefs" +#pragma GCC diagnostic ignored "-Wshadow" +#endif +#include +#pragma GCC diagnostic pop + +#include + +namespace algo = boost::algorithm; + +namespace mbgl { + +class AssetZipContext : public ThreadContext { +public: + AssetZipContext(uv_loop_t *loop); + ~AssetZipContext(); + + uv_zip_t *getHandle(); + void returnHandle(uv_zip_t *zip); + +private: + // A list of resuable uv_zip handles to avoid creating and destroying them all the time. + std::forward_list handles; +}; + +// ------------------------------------------------------------------------------------------------- + +template<> pthread_key_t ThreadContext::key{}; +template<> pthread_once_t ThreadContext::once = PTHREAD_ONCE_INIT; + +AssetZipContext::AssetZipContext(uv_loop_t *loop_) : ThreadContext(loop_) { +} + +uv_zip_t *AssetZipContext::getHandle() { + if (!handles.empty()) { + auto zip = handles.front(); + handles.pop_front(); + return zip; + } else { + return nullptr; + } +} + +void AssetZipContext::returnHandle(uv_zip_t *zip) { + uv_zip_cleanup(zip); + handles.push_front(zip); +} + +AssetZipContext::~AssetZipContext() { + // Close all zip handles + for (auto zip : handles) { + uv_zip_discard(loop, zip, [](uv_zip_t *zip_) { + uv_zip_cleanup(zip_); + delete zip_; + }); + } + handles.clear(); +} + +// ------------------------------------------------------------------------------------------------- + +class AssetRequestImpl { + MBGL_STORE_THREAD(tid) + +public: + AssetRequestImpl(AssetRequest *request, uv_loop_t *loop); + ~AssetRequestImpl(); + + void cancel(); + +private: + AssetZipContext &context; + AssetRequest *request = nullptr; + const std::string path; + std::unique_ptr response; + uv_buf_t buffer; + +private: + void openZipArchive(); + void archiveOpened(uv_zip_t *zip); + void fileStated(uv_zip_t *zip); + void fileOpened(uv_zip_t *zip); + void fileRead(uv_zip_t *zip); + void fileClosed(uv_zip_t *zip); + void cleanup(uv_zip_t *zip); + + void notifyError(const char *message); +}; + +// ------------------------------------------------------------------------------------------------- + +AssetRequestImpl::~AssetRequestImpl() { + MBGL_VERIFY_THREAD(tid); + + if (request) { + request->ptr = nullptr; + } +} + +AssetRequestImpl::AssetRequestImpl(AssetRequest *request_, uv_loop_t *loop) + : context(*AssetZipContext::Get(loop)), + request(request_), + path(request->resource.url.substr(8)) { + auto zip = context.getHandle(); + if (zip) { + archiveOpened(zip); + } else { + openZipArchive(); + } +} + +void AssetRequestImpl::openZipArchive() { + uv_fs_t *req = new uv_fs_t(); + req->data = this; + + // We're using uv_fs_open first to obtain a file descriptor. Then, uv_zip_fdopen will operate + // on a read-only file. + uv_fs_open(context.loop, req, platform::assetRoot().c_str(), O_RDONLY, S_IRUSR, [](uv_fs_t *fsReq) { + if (fsReq->result < 0) { + auto impl = reinterpret_cast(fsReq->data); + impl->notifyError(uv::getFileRequestError(fsReq)); + delete impl; + } else { + uv_zip_t *zip = new uv_zip_t(); + uv_zip_init(zip); + zip->data = fsReq->data; + uv_zip_fdopen(fsReq->loop, zip, uv_file(fsReq->result), 0, [](uv_zip_t *openZip) { + auto impl = reinterpret_cast(openZip->data); + if (openZip->result < 0) { + impl->notifyError(openZip->message); + delete openZip; + delete impl; + } else { + impl->archiveOpened(openZip); + } + }); + } + + uv_fs_req_cleanup(fsReq); + delete fsReq; + fsReq = nullptr; + }); +} + +#define INVOKE_MEMBER(name) \ + [](uv_zip_t *zip_) { \ + assert(zip_->data); \ + reinterpret_cast(zip_->data)->name(zip_); \ + } + +void AssetRequestImpl::archiveOpened(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + zip->data = this; + uv_zip_stat(context.loop, zip, path.c_str(), 0, INVOKE_MEMBER(fileStated)); +} + +void AssetRequestImpl::fileStated(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + if (!request || zip->result < 0) { + // Stat failed, probably because the file doesn't exist. + if (zip->result < 0) { + notifyError(zip->message); + } + cleanup(zip); + } else if (!(zip->stat->valid & ZIP_STAT_SIZE)) { + // We couldn't obtain the size of the file. + notifyError("Could not determine file size in zip file"); + cleanup(zip); + } else { + response = util::make_unique(); + + // Allocate the space for reading the data. + response->data.resize(zip->stat->size); + buffer = uv_buf_init(const_cast(response->data.data()), zip->stat->size); + + // Get the modification time in case we have one. + if (zip->stat->valid & ZIP_STAT_MTIME) { + response->modified = zip->stat->mtime; + } + + uv_zip_fopen(context.loop, zip, path.c_str(), 0, INVOKE_MEMBER(fileOpened)); + } +} + +void AssetRequestImpl::fileOpened(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + if (zip->result < 0) { + // Opening failed. + notifyError(zip->message); + cleanup(zip); + } else if (!request) { + // The request was canceled. Close the file again. + uv_zip_fclose(context.loop, zip, zip->file, INVOKE_MEMBER(fileClosed)); + } else { + uv_zip_fread(context.loop, zip, zip->file, &buffer, INVOKE_MEMBER(fileRead)); + } +} + +void AssetRequestImpl::fileRead(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + if (zip->result < 0) { + // Reading failed. We still have an open file handle though. + notifyError(zip->message); + } else if (request) { + response->status = Response::Successful; + request->notify(std::move(response), FileCache::Hint::No); + delete request; + assert(request == nullptr); + } + + uv_zip_fclose(context.loop, zip, zip->file, INVOKE_MEMBER(fileClosed)); +} + +void AssetRequestImpl::fileClosed(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + if (zip->result < 0) { + // Closing the file failed. But there isn't anything we can do. + } + + cleanup(zip); +} + +void AssetRequestImpl::cleanup(uv_zip_t *zip) { + MBGL_VERIFY_THREAD(tid); + + context.returnHandle(zip); + delete this; +} + +void AssetRequestImpl::notifyError(const char *message) { + MBGL_VERIFY_THREAD(tid); + + if (request) { + response = util::make_unique(); + response->status = Response::Error; + response->message = message; + request->notify(std::move(response), FileCache::Hint::No); + delete request; + assert(request == nullptr); + } else { + // The request was already canceled and deleted. + } +} + +void AssetRequestImpl::cancel() { + request = nullptr; +} + +// ------------------------------------------------------------------------------------------------- + +AssetRequest::AssetRequest(DefaultFileSource *source_, const Resource &resource_) + : SharedRequestBase(source_, resource_) { + assert(algo::starts_with(resource.url, "asset://")); +} + +AssetRequest::~AssetRequest() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->cancel(); + } +} + +void AssetRequest::start(uv_loop_t *loop, std::unique_ptr response) { + MBGL_VERIFY_THREAD(tid); + + // We're ignoring the existing response if any. + (void(response)); + + assert(!ptr); + ptr = new AssetRequestImpl(this, loop); + // Note: the AssetRequestImpl deletes itself. +} + +void AssetRequest::cancel() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->cancel(); + } + + delete this; +} + +} diff --git a/platform/default/asset_root.cpp b/platform/default/asset_root.cpp new file mode 100644 index 000000000..2b20018c4 --- /dev/null +++ b/platform/default/asset_root.cpp @@ -0,0 +1,28 @@ +#include + +#include +#include + +namespace mbgl { +namespace platform { + +// Returns the path to the root folder of the application. +const std::string &assetRoot() { + static const std::string root = []() -> std::string { + size_t max = 0; + std::string dir; + do { + // Gradually increase the length of the string in case the path was truncated. + max += 256; + dir.resize(max); + uv_exepath(const_cast(dir.data()), &max); + } while (max == dir.size()); + dir.resize(max - 1); + dir = dirname(const_cast(dir.c_str())); + return dir; + }(); + return root; +} + +} +} diff --git a/platform/default/cache_database_tmp.cpp b/platform/default/cache_database_tmp.cpp deleted file mode 100644 index 6132ace69..000000000 --- a/platform/default/cache_database_tmp.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include - -namespace mbgl { -namespace platform { - -// Returns the path to the default cache database on this system. -std::string defaultCacheDatabase() { - return "/tmp/mbgl-cache.db"; -} - -} -} diff --git a/src/mbgl/util/compression.cpp b/platform/default/compression.cpp similarity index 83% rename from src/mbgl/util/compression.cpp rename to platform/default/compression.cpp index d6d637054..c8b38e742 100644 --- a/src/mbgl/util/compression.cpp +++ b/platform/default/compression.cpp @@ -1,10 +1,25 @@ -#include +#include "compression.hpp" #include #include #include + +// Check zlib library version. +const static bool zlibVersionCheck = []() { + const char *const version = zlibVersion(); + if (version[0] != ZLIB_VERSION[0]) { + char message[96]; + snprintf(message, 96, "zlib version mismatch: headers report %s, but library reports %s", + ZLIB_VERSION, version); + throw std::runtime_error(message); + } + + return true; +}(); + + namespace mbgl { namespace util { diff --git a/src/mbgl/util/compression.hpp b/platform/default/compression.hpp similarity index 100% rename from src/mbgl/util/compression.hpp rename to platform/default/compression.hpp diff --git a/platform/default/glfw_view.cpp b/platform/default/glfw_view.cpp index 748f27ed2..8306229d4 100644 --- a/platform/default/glfw_view.cpp +++ b/platform/default/glfw_view.cpp @@ -174,7 +174,7 @@ void GLFWView::key(GLFWwindow *window, int key, int /*scancode*/, int action, in break; case GLFW_KEY_R: if (!mods) { - view->map->setDefaultTransitionDuration(300); + view->map->setDefaultTransitionDuration(std::chrono::milliseconds(300)); if (view->map->hasClass("night")) { view->map->removeClass("night"); } else { @@ -239,9 +239,9 @@ void GLFWView::mouseClick(GLFWwindow *window, int button, int action, int modifi double now = glfwGetTime(); if (now - view->lastClick < 0.4 /* ms */) { if (modifiers & GLFW_MOD_SHIFT) { - view->map->scaleBy(0.5, view->lastX, view->lastY, 0.5); + view->map->scaleBy(0.5, view->lastX, view->lastY, std::chrono::milliseconds(500)); } else { - view->map->scaleBy(2.0, view->lastX, view->lastY, 0.5); + view->map->scaleBy(2.0, view->lastX, view->lastY, std::chrono::milliseconds(500)); } } view->lastClick = now; @@ -301,7 +301,7 @@ void GLFWView::swap() { fps(); } -void GLFWView::notifyMapChange(mbgl::MapChange /*change*/, mbgl::timestamp /*delay*/) { +void GLFWView::notifyMapChange(mbgl::MapChange /*change*/, std::chrono::steady_clock::duration /*delay*/) { // no-op } diff --git a/platform/default/headless_view.cpp b/platform/default/headless_view.cpp index 148ff12a0..9df58f802 100644 --- a/platform/default/headless_view.cpp +++ b/platform/default/headless_view.cpp @@ -244,7 +244,7 @@ void HeadlessView::notify() { // no-op } -void HeadlessView::notifyMapChange(mbgl::MapChange /*change*/, mbgl::timestamp /*delay*/) { +void HeadlessView::notifyMapChange(mbgl::MapChange /*change*/, std::chrono::steady_clock::duration /*delay*/) { // no-op } diff --git a/platform/default/http_request_baton_curl.cpp b/platform/default/http_request_baton_curl.cpp deleted file mode 100644 index 9e8cf6471..000000000 --- a/platform/default/http_request_baton_curl.cpp +++ /dev/null @@ -1,629 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#ifdef __ANDROID__ - #include - #include - #include -#endif - -#include -#include - -#include - -#include -#include -#include -#include - - -// Check curl library version. -const static bool curl_version_check = []() { - const auto version = curl_version_info(CURLVERSION_NOW); - if (version->version_num != LIBCURL_VERSION_NUM) { - throw std::runtime_error(mbgl::util::sprintf<96>( - "libcurl version mismatch: headers report %d.%d.%d, but library reports %d.%d.%d", - (LIBCURL_VERSION_NUM >> 16) & 0xFF, (LIBCURL_VERSION_NUM >> 8) & 0xFF, LIBCURL_VERSION_NUM & 0xFF, - (version->version_num >> 16) & 0xFF, (version->version_num >> 8) & 0xFF, version->version_num & 0xFF)); - } - return true; -}(); - - -// This file contains code from http://curl.haxx.se/libcurl/c/multi-uv.html: - -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* Example application code using the multi socket interface to download - multiple files at once, but instead of using curl_multi_perform and - curl_multi_wait, which uses select(), we use libuv. - It supports epoll, kqueue, etc. on unixes and fast IO completion ports on - Windows, which means, it should be very fast on all platforms.. - - Written by Clemens Gruber, based on an outdated example from uvbook and - some tests from libuv. - - Requires libuv and (of course) libcurl. - - See http://nikhilm.github.com/uvbook/ for more information on libuv. -*/ - -// Handles the request thread + messaging to the thread. -static uv_once_t once; -static uv_loop_t *loop = nullptr; -static uv_messenger_t start_messenger; -static uv_messenger_t stop_messenger; -static uv_thread_t thread; -static std::thread::id thread_id; - -// Used as the CURL timer function to periodically check for socket updates. -static uv_timer_t timeout; - -// CURL multi handle that we use to request multiple URLs at the same time, without having to block -// and spawn threads. -static CURLM *multi = nullptr; - -// CURL share handles are used for sharing session state (e.g.) -static uv_mutex_t share_mutex; -static CURLSH *share = nullptr; - -// A queue that we use for storing resuable CURL easy handles to avoid creating and destroying them -// all the time. -static std::queue handles; - -namespace mbgl { - -struct Context { - const util::ptr baton; - CURL *handle = nullptr; - curl_slist *headers = nullptr; - - Context(const util::ptr &baton_) : baton(baton_) { - assert(baton); - baton->ptr = this; - - if (!handles.empty()) { - handle = handles.front(); - handles.pop(); - } else { - handle = curl_easy_init(); - } - } - - ~Context() { - baton->ptr = nullptr; - - if (headers) { - curl_slist_free_all(headers); - headers = nullptr; - } - - CURLMcode error = curl_multi_remove_handle(multi, handle); - if (error != CURLM_OK) { - baton->response = util::make_unique(); - baton->response->code = -1; - baton->response->message = curl_multi_strerror(error); - } - - curl_easy_setopt(handle, CURLOPT_PRIVATE, nullptr); - curl_easy_reset(handle); - handles.push(handle); - handle = nullptr; - - if (baton->async) { - uv_async_send(baton->async); - baton->async = nullptr; - } - } -}; - -struct Socket { -private: - uv_poll_t poll_handle; - -public: - const curl_socket_t sockfd = 0; - -public: - Socket(curl_socket_t sockfd_) : sockfd(sockfd_) { - uv_poll_init_socket(loop, &poll_handle, sockfd); - poll_handle.data = this; - } - - void start(int events, uv_poll_cb cb) { - uv_poll_start(&poll_handle, events, cb); - } - - void stop() { - assert(poll_handle.data); - poll_handle.data = nullptr; - uv_poll_stop(&poll_handle); - uv_close((uv_handle_t *)&poll_handle, [](uv_handle_t *handle) { - delete (Socket *)handle->data; - }); - } - -private: - // Make the destructor private to ensure that we can only close the Socket - // with stop(), and disallow manual deletion. - ~Socket() { - assert(!poll_handle.data); - } -}; - -// Locks the CURL share handle -void curl_share_lock(CURL *, curl_lock_data, curl_lock_access, void *) { - uv_mutex_lock(&share_mutex); -} - -// Unlocks the CURL share handle -void curl_share_unlock(CURL *, curl_lock_data, void *) { - uv_mutex_unlock(&share_mutex); -} - -void check_multi_info() { - CURLMsg *message = nullptr; - int pending = 0; - - while ((message = curl_multi_info_read(multi, &pending))) { - switch (message->msg) { - case CURLMSG_DONE: { - Context *context = nullptr; - curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&context); - assert(context); - - auto baton = context->baton; - - // This request is complete. We are removing the pointer to the CURL easy handle again - // to prevent this request from getting canceled. - context->baton->ptr = nullptr; - - // Add human-readable error code - if (message->data.result != CURLE_OK) { - baton->response->message = curl_easy_strerror(message->data.result); - baton->response->code = -1; - - switch (message->data.result) { - case CURLE_COULDNT_RESOLVE_PROXY: - case CURLE_COULDNT_RESOLVE_HOST: - case CURLE_COULDNT_CONNECT: - baton->type = HTTPResponseType::ConnectionError; - break; - - case CURLE_OPERATION_TIMEDOUT: - baton->type = HTTPResponseType::TemporaryError; - break; - - default: - baton->type = HTTPResponseType::PermanentError; - } - } else { - long code = 0; - curl_easy_getinfo(message->easy_handle, CURLINFO_RESPONSE_CODE, &code); - - if (code != 304) { - baton->response->code = code; - } - - if (code == 304) { - baton->type = HTTPResponseType::NotModified; - } else if (code == 200) { - baton->type = HTTPResponseType::Successful; - } else if (code >= 500 && code < 600) { - baton->type = HTTPResponseType::TemporaryError; - } else if (code >= 400 && code < 500) { - baton->type = HTTPResponseType::PermanentError; - } else { - assert(!"code must be either 200 or 304"); - } - } - - delete context; - } break; - - default: - // This should never happen, because there are no other message types. - throw std::runtime_error("CURLMSG returned unknown message type"); - } - } -} - -void curl_perform(uv_poll_t *req, int /* status */, int events) { - int flags = 0; - - uv_timer_stop(&timeout); - - if (events & UV_READABLE) { - flags |= CURL_CSELECT_IN; - } - if (events & UV_WRITABLE) { - flags |= CURL_CSELECT_OUT; - } - - Socket *context = (Socket *)req->data; - int running_handles = 0; - curl_multi_socket_action(multi, context->sockfd, flags, &running_handles); - - check_multi_info(); -} - -int handle_socket(CURL * /* handle */, curl_socket_t s, int action, void * /* userp */, void *socketp) { - Socket *socket = (Socket *)socketp; - if (!socket && action != CURL_POLL_REMOVE) { - socket = new Socket(s); - curl_multi_assign(multi, s, (void *)socket); - } - - switch (action) { - case CURL_POLL_IN: - socket->start(UV_READABLE, curl_perform); - break; - case CURL_POLL_OUT: - socket->start(UV_WRITABLE, curl_perform); - break; - case CURL_POLL_REMOVE: - if (socket) { - socket->stop(); - curl_multi_assign(multi, s, NULL); - } - break; - default: - abort(); - } - - return 0; -} - -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 -void on_timeout(uv_timer_t * /* req */, int /* status */) { -#else -void on_timeout(uv_timer_t * /* req */) { -#endif - int running_handles; - CURLMcode error = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, &running_handles); - if (error != CURLM_OK) { - throw std::runtime_error(std::string("CURL multi error: ") + curl_multi_strerror(error)); - } - - check_multi_info(); -} - -void start_timeout(CURLM * /* multi */, long timeout_ms, void * /* userp */) { - if (timeout_ms <= 0) { - timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in a bit */ - } - uv_timer_start(&timeout, on_timeout, timeout_ms, 0); -} - -void thread_init(void *) { -#ifdef __APPLE__ - pthread_setname_np("CURL"); -#endif - thread_id = std::this_thread::get_id(); - - if (curl_global_init(CURL_GLOBAL_ALL)) { - throw std::runtime_error("Could not init cURL"); - } - - uv_timer_init(loop, &timeout); - - CURLSHcode share_error; - share = curl_share_init(); - - share_error = curl_share_setopt(share, CURLSHOPT_LOCKFUNC, curl_share_lock); - if (share_error != CURLSHE_OK) { - throw std::runtime_error(std::string("CURL share error: ") + curl_share_strerror(share_error)); - } - - share_error = curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, curl_share_unlock); - if (share_error != CURLSHE_OK) { - throw std::runtime_error(std::string("CURL share error: ") + curl_share_strerror(share_error)); - } - - CURLMcode multi_error; - multi = curl_multi_init(); - - multi_error = curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, handle_socket); - if (multi_error != CURLM_OK) { - throw std::runtime_error(std::string("CURL multi error: ") + curl_multi_strerror(multi_error)); - } - multi_error = curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, start_timeout); - if (multi_error != CURLM_OK) { - throw std::runtime_error(std::string("CURL multi error: ") + curl_multi_strerror(multi_error)); - } - - // Main event loop. This will not return until the request loop is terminated. - uv_run(loop, UV_RUN_DEFAULT); - - curl_multi_cleanup(multi); - multi = nullptr; - - curl_share_cleanup(share); - share = nullptr; - - thread_id = std::thread::id(); -} - -// This function is called when we have new data for a request. We just append it to the string -// containing the previous data. -size_t curl_write_cb(void *const contents, const size_t size, const size_t nmemb, void *const userp) { - auto &response = *(std::unique_ptr *)userp; - assert(response); - response->data.append((char *)contents, size * nmemb); - return size * nmemb; -} - -// Compares the beginning of the (non-zero-terminated!) data buffer with the (zero-terminated!) -// header string. If the data buffer contains the header string at the beginning, it returns -// the length of the header string == begin of the value, otherwise it returns npos. -// The comparison of the header is ASCII-case-insensitive. -size_t header_matches(const char *const header, const char *const buffer, const size_t length) { - const size_t header_length = strlen(header); - if (length < header_length) return std::string::npos; - size_t i = 0; - while (i < length && i < header_length && std::tolower(buffer[i]) == header[i]) { - i++; - } - return i == header_length ? i : std::string::npos; -} - -size_t curl_header_cb(char * const buffer, const size_t size, const size_t nmemb, void *const userp) { - const size_t length = size * nmemb; - - auto &response = *(std::unique_ptr *)userp; - assert(response); - - size_t begin = std::string::npos; - if ((begin = header_matches("last-modified: ", buffer, length)) != std::string::npos) { - // Always overwrite the modification date; We might already have a value here from the - // Date header, but this one is more accurate. - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n - response->modified = curl_getdate(value.c_str(), nullptr); - } else if ((begin = header_matches("etag: ", buffer, length)) != std::string::npos) { - response->etag = { buffer + begin, length - begin - 2 }; // remove \r\n - } else if ((begin = header_matches("cache-control: ", buffer, length)) != std::string::npos) { - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n - response->expires = Response::parseCacheControl(value.c_str()); - } - - return length; -} - -// This function is called to load the CA bundle -// from http://curl.haxx.se/libcurl/c/cacertinmem.html -#ifdef __ANDROID__ -static CURLcode sslctx_function(CURL */*curl*/, void *sslctx, void */*parm*/) { - - int error = 0; - struct zip *apk = zip_open(mbgl::android::apkPath.c_str(), 0, &error); - if (apk == nullptr) { - return CURLE_SSL_CACERT_BADFILE; - } - - struct zip_file *apkFile = zip_fopen(apk, "assets/ca-bundle.crt", ZIP_FL_NOCASE); - if (apkFile == nullptr) { - zip_close(apk); - apk = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - struct zip_stat stat; - if (zip_stat(apk, "assets/ca-bundle.crt", ZIP_FL_NOCASE, &stat) != 0) { - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - if (stat.size > std::numeric_limits::max()) { - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - const std::unique_ptr pem = util::make_unique(stat.size); - - if (static_cast(zip_fread(apkFile, reinterpret_cast(pem.get()), stat.size)) != stat.size) { - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - // get a pointer to the X509 certificate store (which may be empty!) - X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX *)sslctx); - if (store == nullptr) { - return CURLE_SSL_CACERT_BADFILE; - } - - // get a BIO - BIO *bio = BIO_new_mem_buf(pem.get(), static_cast(stat.size)); - if (bio == nullptr) { - store = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - // use it to read the PEM formatted certificate from memory into an X509 - // structure that SSL can use - X509 *cert = nullptr; - while (PEM_read_bio_X509(bio, &cert, 0, nullptr) != nullptr) { - if (cert == nullptr) { - BIO_free(bio); - bio = nullptr; - store = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - // add our certificate to this store - if (X509_STORE_add_cert(store, cert) == 0) { - X509_free(cert); - cert = nullptr; - BIO_free(bio); - bio = nullptr; - store = nullptr; - return CURLE_SSL_CACERT_BADFILE; - } - - X509_free(cert); - cert = nullptr; - } - - // decrease reference counts - BIO_free(bio); - bio = nullptr; - - zip_fclose(apkFile); - apkFile = nullptr; - zip_close(apk); - apk = nullptr; - - // all set to go - return CURLE_OK; -} -#endif - -std::string buildUserAgentString() { -#ifdef __ANDROID__ - return util::sprintf<128>("MapboxGL/%d.%d.%d (+https://mapbox.com/mapbox-gl/; %s; %s %s)", - version::major, version::minor, version::patch, version::revision, "Android", mbgl::android::androidRelease.c_str()); -#else - utsname name; - uname(&name); - return util::sprintf<128>("MapboxGL/%d.%d.%d (+https://mapbox.com/mapbox-gl/; %s; %s %s)", - version::major, version::minor, version::patch, version::revision, name.sysname, name.release); -#endif -} - -// This function must run in the CURL thread. -void start_request(void *const ptr) { - assert(std::this_thread::get_id() == thread_id); - static const std::string userAgent = buildUserAgentString(); - - // The Context object stores information that we need to retain throughout the request, such - // as the actual CURL easy handle, the baton, and the list of headers. The Context itself is - // stored in both the CURL easy handle's PRIVATE field, and the baton's `ptr` field. - auto context = new Context(*(util::ptr *)ptr); - delete (util::ptr *)ptr; - - if (context->baton->response) { - if (!context->baton->response->etag.empty()) { - const std::string header = std::string("If-None-Match: ") + context->baton->response->etag; - context->headers = curl_slist_append(context->headers, header.c_str()); - } else if (context->baton->response->modified) { - const std::string time = - std::string("If-Modified-Since: ") + util::rfc1123(context->baton->response->modified); - context->headers = curl_slist_append(context->headers, time.c_str()); - } - } - - if (context->headers) { - curl_easy_setopt(context->handle, CURLOPT_HTTPHEADER, context->headers); - } - - if (!context->baton->response) { - context->baton->response = util::make_unique(); - } - - // Carry on the shared pointer in the private information of the CURL handle. - curl_easy_setopt(context->handle, CURLOPT_PRIVATE, context); -#ifndef __ANDROID__ - curl_easy_setopt(context->handle, CURLOPT_CAINFO, "ca-bundle.crt"); -#else - curl_easy_setopt(context->handle, CURLOPT_SSLCERTTYPE, "PEM"); - curl_easy_setopt(context->handle, CURLOPT_SSL_CTX_FUNCTION, sslctx_function); -#endif - curl_easy_setopt(context->handle, CURLOPT_FOLLOWLOCATION, 1); - curl_easy_setopt(context->handle, CURLOPT_URL, context->baton->path.c_str()); - curl_easy_setopt(context->handle, CURLOPT_WRITEFUNCTION, curl_write_cb); - curl_easy_setopt(context->handle, CURLOPT_WRITEDATA, &context->baton->response); - curl_easy_setopt(context->handle, CURLOPT_HEADERFUNCTION, curl_header_cb); - curl_easy_setopt(context->handle, CURLOPT_HEADERDATA, &context->baton->response); - curl_easy_setopt(context->handle, CURLOPT_ACCEPT_ENCODING, "gzip, deflate"); - curl_easy_setopt(context->handle, CURLOPT_USERAGENT, userAgent.c_str()); - curl_easy_setopt(context->handle, CURLOPT_SHARE, share); - - // Start requesting the information. - curl_multi_add_handle(multi, context->handle); -} - -// This function must run in the CURL thread. -void stop_request(void *const ptr) { - assert(std::this_thread::get_id() == thread_id); - auto baton = *(util::ptr *)ptr; - delete (util::ptr *)ptr; - assert(baton); - - if (baton->async) { - baton->type = HTTPResponseType::Canceled; - - assert(baton->ptr); - - // We can still stop the request because it is still in progress. - delete (Context *)baton->ptr; - assert(!baton->ptr); - } else { - // If the async handle is gone, it means that the actual request has been completed before - // we got a chance to cancel it. In this case, this is a no-op. It is likely that - // the pointer below is the last lifeline of the HTTPRequestBaton. This means we're going - // to delete the HTTPRequestBaton in the current (CURL) thread. - } -} - -void create_thread() { - uv_mutex_init(&share_mutex); -#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 - loop = uv_loop_new(); -#else - loop = new uv_loop_t; - uv_loop_init(loop); -#endif - uv_messenger_init(loop, &start_messenger, start_request); - uv_messenger_init(loop, &stop_messenger, stop_request); - uv_thread_create(&thread, thread_init, nullptr); -} - -// This function must be run from the main thread (== where the HTTPRequestBaton was created) -void HTTPRequestBaton::start(const util::ptr &ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - uv_once(&once, create_thread); - uv_messenger_send(&start_messenger, new util::ptr(ptr)); -} - -// This function must be run from the main thread (== where the HTTPRequestBaton was created) -void HTTPRequestBaton::stop(const util::ptr &ptr) { - assert(std::this_thread::get_id() == ptr->threadId); - uv_once(&once, create_thread); - uv_messenger_send(&stop_messenger, new util::ptr(ptr)); -} - -} diff --git a/platform/default/http_request_curl.cpp b/platform/default/http_request_curl.cpp new file mode 100644 index 000000000..411c5ee47 --- /dev/null +++ b/platform/default/http_request_curl.cpp @@ -0,0 +1,648 @@ +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +void handleError(CURLMcode code) { + if (code != CURLM_OK) { + throw std::runtime_error(std::string("CURL multi error: ") + curl_multi_strerror(code)); + } +} + +void handleError(CURLcode code) { + if (code != CURLE_OK) { + throw std::runtime_error(std::string("CURL easy error: ") + curl_easy_strerror(code)); + } +} + +namespace mbgl { + +enum class ResponseStatus : int8_t { + // This error probably won't be resolved by retrying anytime soon. We are giving up. + PermanentError, + + // This error might be resolved by waiting some time (e.g. server issues). + // We are going to do an exponential back-off and will try again in a few seconds. + TemporaryError, + + // This error might be resolved once the network reachability status changes. + // We are going to watch the network status for changes and will retry as soon as the + // operating system notifies us of a network status change. + ConnectionError, + + // The request returned data successfully. We retrieved and decoded the data successfully. + Successful, + + // The request confirmed that the data wasn't changed. We already have the data. + NotModified, +}; + +class HTTPRequestImpl; + +class HTTPCURLContext : public HTTPContext { + +public: + HTTPCURLContext(uv_loop_t *loop); + ~HTTPCURLContext(); + + static int handleSocket(CURL *handle, curl_socket_t s, int action, void *userp, void *socketp); + static void perform(uv_poll_t *req, int status, int events); + static int startTimeout(CURLM *multi, long timeout_ms, void *userp); +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + static void onTimeout(uv_timer_t *req, int status); +#else + static void onTimeout(uv_timer_t *req); +#endif + + CURL *getHandle(); + void returnHandle(CURL *handle); + void checkMultiInfo(); + +public: + // Used as the CURL timer function to periodically check for socket updates. + uv_timer_t *timeout = nullptr; + + // CURL multi handle that we use to request multiple URLs at the same time, without having to + // block and spawn threads. + CURLM *multi = nullptr; + + // CURL share handles are used for sharing session state (e.g.) + CURLSH *share = nullptr; + + // A queue that we use for storing resuable CURL easy handles to avoid creating and destroying + // them all the time. + std::queue handles; +}; + + +class HTTPRequestImpl { + MBGL_STORE_THREAD(tid) + +public: + HTTPRequestImpl(HTTPRequest *request, uv_loop_t *loop, std::unique_ptr response); + ~HTTPRequestImpl(); + + void handleResult(CURLcode code); + void abandon(); + void retryImmediately(); + +private: + static size_t headerCallback(char *const buffer, const size_t size, const size_t nmemb, void *userp); + static size_t writeCallback(void *const contents, const size_t size, const size_t nmemb, void *userp); + + void retry(uint64_t timeout); +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 + static void restart(uv_timer_t *timer, int); +#else + static void restart(uv_timer_t *timer); +#endif + void finish(ResponseStatus status); + void start(); + +private: + HTTPCURLContext *context = nullptr; + HTTPRequest *request = nullptr; + + // Will store the current response. + std::unique_ptr response; + + // In case of revalidation requests, this will store the old response. + std::unique_ptr existingResponse; + + CURL *handle = nullptr; + curl_slist *headers = nullptr; + + uv_timer_t *timer = nullptr; + enum : bool { PreemptImmediately, ExponentialBackoff } strategy = PreemptImmediately; + int attempts = 0; + + static const int maxAttempts = 4; +}; + + + +struct Socket { +private: + uv_poll_t poll; + +public: + HTTPCURLContext *context = nullptr; + const curl_socket_t sockfd = 0; + +public: + Socket(HTTPCURLContext *context_, curl_socket_t sockfd_) : context(context_), sockfd(sockfd_) { + assert(context); + uv_poll_init_socket(context->loop, &poll, sockfd); + poll.data = this; + } + + void start(int events, uv_poll_cb cb) { + uv_poll_start(&poll, events, cb); + } + + void stop() { + assert(poll.data); + uv_poll_stop(&poll); + uv_close((uv_handle_t *)&poll, [](uv_handle_t *handle) { + assert(handle->data); + delete reinterpret_cast(handle->data); + }); + } + +private: + // Make the destructor private to ensure that we can only close the Socket + // with stop(), and disallow manual deletion. + ~Socket() = default; +}; + +// ------------------------------------------------------------------------------------------------- + +template<> pthread_key_t ThreadContext::key{}; +template<> pthread_once_t ThreadContext::once = PTHREAD_ONCE_INIT; + +HTTPCURLContext::HTTPCURLContext(uv_loop_t *loop_) : HTTPContext(loop_) { + if (curl_global_init(CURL_GLOBAL_ALL)) { + throw std::runtime_error("Could not init cURL"); + } + + timeout = new uv_timer_t; + timeout->data = this; + uv_timer_init(loop, timeout); + + share = curl_share_init(); + + multi = curl_multi_init(); + handleError(curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, handleSocket)); + handleError(curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, this)); + handleError(curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, startTimeout)); + handleError(curl_multi_setopt(multi, CURLMOPT_TIMERDATA, this)); +} + +HTTPCURLContext::~HTTPCURLContext() { + curl_multi_cleanup(multi); + multi = nullptr; + + curl_share_cleanup(share); + share = nullptr; + + uv_timer_stop(timeout); + uv::close(timeout); +} + +CURL *HTTPCURLContext::getHandle() { + if (!handles.empty()) { + auto handle = handles.front(); + handles.pop(); + return handle; + } else { + return curl_easy_init(); + } +} + +void HTTPCURLContext::returnHandle(CURL *handle) { + curl_easy_reset(handle); + handles.push(handle); +} + +void HTTPCURLContext::checkMultiInfo() { + MBGL_VERIFY_THREAD(tid); + CURLMsg *message = nullptr; + int pending = 0; + + while ((message = curl_multi_info_read(multi, &pending))) { + switch (message->msg) { + case CURLMSG_DONE: { + HTTPRequestImpl *baton = nullptr; + curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&baton); + assert(baton); + baton->handleResult(message->data.result); + } break; + + default: + // This should never happen, because there are no other message types. + throw std::runtime_error("CURLMsg returned unknown message type"); + } + } +} + +void HTTPCURLContext::perform(uv_poll_t *req, int /* status */, int events) { + assert(req->data); + auto socket = reinterpret_cast(req->data); + auto context = socket->context; + MBGL_VERIFY_THREAD(context->tid); + + int flags = 0; + + if (events & UV_READABLE) { + flags |= CURL_CSELECT_IN; + } + if (events & UV_WRITABLE) { + flags |= CURL_CSELECT_OUT; + } + + + int running_handles = 0; + curl_multi_socket_action(context->multi, socket->sockfd, flags, &running_handles); + context->checkMultiInfo(); +} + +int HTTPCURLContext::handleSocket(CURL * /* handle */, curl_socket_t s, int action, void *userp, + void *socketp) { + auto socket = reinterpret_cast(socketp); + assert(userp); + auto context = reinterpret_cast(userp); + MBGL_VERIFY_THREAD(context->tid); + + if (!socket && action != CURL_POLL_REMOVE) { + socket = new Socket(context, s); + curl_multi_assign(context->multi, s, (void *)socket); + } + + switch (action) { + case CURL_POLL_IN: + socket->start(UV_READABLE, perform); + break; + case CURL_POLL_OUT: + socket->start(UV_WRITABLE, perform); + break; + case CURL_POLL_REMOVE: + if (socket) { + socket->stop(); + curl_multi_assign(context->multi, s, nullptr); + } + break; + default: + throw std::runtime_error("Unhandled CURL socket action"); + } + + return 0; +} + +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 +void HTTPCURLContext::onTimeout(uv_timer_t *req, int /* status */) { +#else +void HTTPCURLContext::onTimeout(uv_timer_t *req) { +#endif + assert(req->data); + auto context = reinterpret_cast(req->data); + MBGL_VERIFY_THREAD(context->tid); + int running_handles; + CURLMcode error = curl_multi_socket_action(context->multi, CURL_SOCKET_TIMEOUT, 0, &running_handles); + if (error != CURLM_OK) { + throw std::runtime_error(std::string("CURL multi error: ") + curl_multi_strerror(error)); + } + context->checkMultiInfo(); +} + +int HTTPCURLContext::startTimeout(CURLM * /* multi */, long timeout_ms, void *userp) { + assert(userp); + auto context = reinterpret_cast(userp); + MBGL_VERIFY_THREAD(context->tid); + if (timeout_ms < 0) { + // A timeout of 0 ms means that the timer will invoked in the next loop iteration. + timeout_ms = 0; + } + uv_timer_stop(context->timeout); + uv_timer_start(context->timeout, onTimeout, timeout_ms, 0); + return 0; +} + +// ------------------------------------------------------------------------------------------------- + +HTTPRequestImpl::HTTPRequestImpl(HTTPRequest *request_, uv_loop_t *loop, std::unique_ptr response_) + : context(HTTPCURLContext::Get(loop)), + request(request_), + existingResponse(std::move(response_)), + handle(context->getHandle()) { + assert(request); + context->addRequest(request); + + // If there's already a response, set the correct etags/modified headers to make sure we are + // getting a 304 response if possible. This avoids redownloading unchanged data. + if (existingResponse) { + if (!existingResponse->etag.empty()) { + const std::string header = std::string("If-None-Match: ") + existingResponse->etag; + headers = curl_slist_append(headers, header.c_str()); + } else if (existingResponse->modified) { + const std::string time = + std::string("If-Modified-Since: ") + util::rfc1123(existingResponse->modified); + headers = curl_slist_append(headers, time.c_str()); + } + } + + if (headers) { + curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); + } + + handleError(curl_easy_setopt(handle, CURLOPT_PRIVATE, this)); + handleError(curl_easy_setopt(handle, CURLOPT_CAINFO, "ca-bundle.crt")); + handleError(curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1)); + handleError(curl_easy_setopt(handle, CURLOPT_URL, request->resource.url.c_str())); + handleError(curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writeCallback)); + handleError(curl_easy_setopt(handle, CURLOPT_WRITEDATA, this)); + handleError(curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, headerCallback)); + handleError(curl_easy_setopt(handle, CURLOPT_HEADERDATA, this)); + handleError(curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, "gzip, deflate")); + handleError(curl_easy_setopt(handle, CURLOPT_USERAGENT, "MapboxGL/1.0")); + handleError(curl_easy_setopt(handle, CURLOPT_SHARE, context->share)); + + start(); +} + +void HTTPRequestImpl::abandon() { + if (request) { + context->removeRequest(request); + request = nullptr; + } +} + +void HTTPRequestImpl::start() { + // Count up the attempts. + attempts++; + + // Start requesting the information. + handleError(curl_multi_add_handle(context->multi, handle)); +} + +HTTPRequestImpl::~HTTPRequestImpl() { + MBGL_VERIFY_THREAD(tid); + + if (request) { + context->removeRequest(request); + request->ptr = nullptr; + } + + handleError(curl_multi_remove_handle(context->multi, handle)); + context->returnHandle(handle); + handle = nullptr; + + if (timer) { + // Stop the backoff timer to avoid re-triggering this request. + uv_timer_stop(timer); + uv::close(timer); + timer = nullptr; + } + + if (headers) { + curl_slist_free_all(headers); + headers = nullptr; + } +} + +// This function is called when we have new data for a request. We just append it to the string +// containing the previous data. +size_t HTTPRequestImpl::writeCallback(void *const contents, const size_t size, const size_t nmemb, void *userp) { + assert(userp); + auto impl = reinterpret_cast(userp); + MBGL_VERIFY_THREAD(impl->tid); + + if (!impl->response) { + impl->response = util::make_unique(); + } + + impl->response->data.append((char *)contents, size * nmemb); + return size * nmemb; +} + +// Compares the beginning of the (non-zero-terminated!) data buffer with the (zero-terminated!) +// header string. If the data buffer contains the header string at the beginning, it returns +// the length of the header string == begin of the value, otherwise it returns npos. +// The comparison of the header is ASCII-case-insensitive. +size_t headerMatches(const char *const header, const char *const buffer, const size_t length) { + const size_t headerLength = strlen(header); + if (length < headerLength) { + return std::string::npos; + } + size_t i = 0; + while (i < length && i < headerLength && std::tolower(buffer[i]) == std::tolower(header[i])) { + i++; + } + return i == headerLength ? i : std::string::npos; +} + +int64_t parseCacheControl(const char *value) { + if (value) { + unsigned long long seconds = 0; + // TODO: cache-control may contain other information as well: + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + if (std::sscanf(value, "max-age=%llu", &seconds) == 1) { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count() + + seconds; + } + } + + return 0; +} + +size_t HTTPRequestImpl::headerCallback(char *const buffer, const size_t size, const size_t nmemb, void *userp) { + assert(userp); + auto baton = reinterpret_cast(userp); + MBGL_VERIFY_THREAD(baton->tid); + + if (!baton->response) { + baton->response = util::make_unique(); + } + + const size_t length = size * nmemb; + size_t begin = std::string::npos; + if ((begin = headerMatches("last-modified: ", buffer, length)) != std::string::npos) { + // Always overwrite the modification date; We might already have a value here from the + // Date header, but this one is more accurate. + const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + baton->response->modified = curl_getdate(value.c_str(), nullptr); + } else if ((begin = headerMatches("etag: ", buffer, length)) != std::string::npos) { + baton->response->etag = { buffer + begin, length - begin - 2 }; // remove \r\n + } else if ((begin = headerMatches("cache-control: ", buffer, length)) != std::string::npos) { + const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + baton->response->expires = parseCacheControl(value.c_str()); + } else if ((begin = headerMatches("expires: ", buffer, length)) != std::string::npos) { + const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + baton->response->expires = curl_getdate(value.c_str(), nullptr); + } + + return length; +} + + +void HTTPRequestImpl::retry(uint64_t timeout) { + handleError(curl_multi_remove_handle(context->multi, handle)); + + response.reset(); + + assert(!timer); + timer = new uv_timer_t; + timer->data = this; + uv_timer_init(context->loop, timer); + uv_timer_start(timer, restart, timeout, 0); +} + +void HTTPRequestImpl::retryImmediately() { + // All batons get notified when the network status changed, but some of them + // might not actually wait for the network to become available again. + if (timer && strategy == PreemptImmediately) { + // Triggers the timer upon the next event loop iteration. + uv_timer_stop(timer); + uv_timer_start(timer, restart, 0, 0); + } +} + +#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 +void HTTPRequestImpl::restart(uv_timer_t *timer, int) { +#else +void HTTPRequestImpl::restart(uv_timer_t *timer) { +#endif + // Restart the request. + auto baton = reinterpret_cast(timer->data); + + // Get rid of the timer. + baton->timer = nullptr; + uv::close(timer); + + baton->start(); +} + +void HTTPRequestImpl::finish(ResponseStatus status) { + if (status == ResponseStatus::TemporaryError && attempts < maxAttempts) { + strategy = ExponentialBackoff; + return retry((1 << (attempts - 1)) * 1000); + } else if (status == ResponseStatus::ConnectionError && attempts < maxAttempts) { + // By default, we will retry every 30 seconds (network change notification will + // preempt the timeout). + strategy = PreemptImmediately; + return retry(30000); + } + + // Actually return the response. + if (status == ResponseStatus::NotModified) { + request->notify(std::move(response), FileCache::Hint::Refresh); + } else { + request->notify(std::move(response), FileCache::Hint::Full); + } + + delete request; + delete this; +} + +void HTTPRequestImpl::handleResult(CURLcode code) { + MBGL_VERIFY_THREAD(tid); + + if (!request) { + // In this case, it doesn't make sense to even process the response even further since + // the request was canceled anyway. + delete this; + return; + } + + // Make sure a response object exists in case we haven't got any headers + // or content. + if (!response) { + response = util::make_unique(); + } + + // Add human-readable error code + if (code != CURLE_OK) { + response->message = curl_easy_strerror(code); + + switch (code) { + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_COULDNT_CONNECT: + response->status = Response::Error; + return finish(ResponseStatus::ConnectionError); + + case CURLE_OPERATION_TIMEDOUT: + response->status = Response::Error; + return finish(ResponseStatus::TemporaryError); + + default: + response->status = Response::Error; + return finish(ResponseStatus::PermanentError); + } + } else { + long responseCode = 0; + curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &responseCode); + + 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; + } + return finish(ResponseStatus::NotModified); + } else { + // This is an unsolicited 304 response and should only happen on malfunctioning + // HTTP servers. It likely doesn't include any data, but we don't have much options. + response->status = Response::Successful; + return finish(ResponseStatus::Successful); + } + } else if (responseCode == 200) { + response->status = Response::Successful; + return finish(ResponseStatus::Successful); + } else if (responseCode >= 500 && responseCode < 600) { + // Server errors may be temporary, so back off exponentially. + response->status = Response::Error; + response->message = "HTTP status code " + std::to_string(responseCode); + return finish(ResponseStatus::TemporaryError); + } else { + // We don't know how to handle any other errors, so declare them as permanently failing. + response->status = Response::Error; + response->message = "HTTP status code " + std::to_string(responseCode); + return finish(ResponseStatus::PermanentError); + } + } + + throw std::runtime_error("Response hasn't been handled"); +} + +// ------------------------------------------------------------------------------------------------- + +HTTPRequest::HTTPRequest(DefaultFileSource *source_, const Resource &resource_) + : SharedRequestBase(source_, resource_) { +} + +HTTPRequest::~HTTPRequest() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->abandon(); + } +} + +void HTTPRequest::start(uv_loop_t *loop, std::unique_ptr response) { + MBGL_VERIFY_THREAD(tid); + + assert(!ptr); + ptr = new HTTPRequestImpl(this, loop, std::move(response)); +} + +void HTTPRequest::retryImmediately() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + reinterpret_cast(ptr)->retryImmediately(); + } +} + +void HTTPRequest::cancel() { + MBGL_VERIFY_THREAD(tid); + + if (ptr) { + delete reinterpret_cast(ptr); + ptr = nullptr; + } + + delete this; +} + +} diff --git a/src/mbgl/util/sqlite3.cpp b/platform/default/sqlite3.cpp similarity index 82% rename from src/mbgl/util/sqlite3.cpp rename to platform/default/sqlite3.cpp index 787db8399..6a27314c5 100644 --- a/src/mbgl/util/sqlite3.cpp +++ b/platform/default/sqlite3.cpp @@ -1,7 +1,28 @@ -#include +#include "sqlite3.hpp" #include #include +#include + +// Check sqlite3 library version. +const static bool sqliteVersionCheck = []() { + if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER) { + char message[96]; + snprintf(message, 96, + "sqlite3 libversion mismatch: headers report %d, but library reports %d", + SQLITE_VERSION_NUMBER, sqlite3_libversion_number()); + throw std::runtime_error(message); + } + if (strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID) != 0) { + char message[256]; + snprintf(message, 256, + "sqlite3 sourceid mismatch: headers report \"%s\", but library reports \"%s\"", + SQLITE_SOURCE_ID, sqlite3_sourceid()); + throw std::runtime_error(message); + } + + return true; +}(); namespace mapbox { namespace sqlite { diff --git a/src/mbgl/util/sqlite3.hpp b/platform/default/sqlite3.hpp similarity index 100% rename from src/mbgl/util/sqlite3.hpp rename to platform/default/sqlite3.hpp diff --git a/platform/default/sqlite_cache.cpp b/platform/default/sqlite_cache.cpp new file mode 100644 index 000000000..ab1ee040f --- /dev/null +++ b/platform/default/sqlite_cache.cpp @@ -0,0 +1,271 @@ +#include +#include +#include + +#include +#include +#include +#include + +#include "sqlite3.hpp" +#include "compression.hpp" + +#include + +#include + +namespace mbgl { + +std::string removeAccessTokenFromURL(const std::string &url) { + const size_t token_start = url.find("access_token="); + // Ensure that token exists, isn't at the front and is preceded by either & or ?. + if (token_start == std::string::npos || token_start == 0 || !(url[token_start - 1] == '&' || url[token_start - 1] == '?')) { + return url; + } + + const size_t token_end = url.find_first_of('&', token_start); + if (token_end == std::string::npos) { + // The token is the last query argument. We slice away the "&access_token=..." part + return url.substr(0, token_start - 1); + } else { + // We slice away the "access_token=...&" part. + return url.substr(0, token_start) + url.substr(token_end + 1); + } +} + +std::string convertMapboxDomainsToProtocol(const std::string &url) { + const size_t protocol_separator = url.find("://"); + if (protocol_separator == std::string::npos) { + return url; + } + + const std::string protocol = url.substr(0, protocol_separator); + if (!(protocol == "http" || protocol == "https")) { + return url; + } + + const size_t domain_begin = protocol_separator + 3; + const size_t path_separator = url.find("/", domain_begin); + if (path_separator == std::string::npos) { + return url; + } + + const std::string domain = url.substr(domain_begin, path_separator - domain_begin); + if (domain.find(".tiles.mapbox.com") != std::string::npos) { + return "mapbox://" + url.substr(path_separator + 1); + } else { + return url; + } +} + +std::string unifyMapboxURLs(const std::string &url) { + return removeAccessTokenFromURL(convertMapboxDomainsToProtocol(url)); +} + + +using namespace mapbox::sqlite; + +struct SQLiteCache::GetAction { + const Resource resource; + const std::function)> callback; +}; + +struct SQLiteCache::PutAction { + const Resource resource; + const std::shared_ptr response; +}; + +struct SQLiteCache::RefreshAction { + const Resource resource; + const int64_t expires; +}; + +struct SQLiteCache::StopAction { +}; + +struct SQLiteCache::ActionDispatcher { + SQLiteCache &cache; + template void operator()(T &t) { cache.process(t); } +}; + +SQLiteCache::SQLiteCache(const std::string &path_) + : path(path_), + loop(uv_loop_new()), + queue(new Queue(loop, [this](Action &action) { + mapbox::util::apply_visitor(ActionDispatcher{ *this }, action); + })), + thread([this]() { +#ifdef __APPLE__ + pthread_setname_np("SQLite Cache"); +#endif + uv_run(loop, UV_RUN_DEFAULT); + }) +{ +} + +SQLiteCache::~SQLiteCache() { + if (thread.joinable()) { + if (queue) { + queue->send(StopAction{ }); + } + thread.join(); + uv_loop_delete(loop); + } +} + + +void SQLiteCache::get(const Resource &resource, std::function)> callback) { + // Can be called from any thread, but most likely from the file source thread. + // Will try to load the URL from the SQLite database and call the callback when done. + // Note that the callback is probably going to invoked from another thread, so the caller + // must make sure that it can run in that thread. + assert(queue); + queue->send(GetAction{ resource, callback }); +} + +void SQLiteCache::put(const Resource &resource, std::shared_ptr response, Hint hint) { + // Can be called from any thread, but most likely from the file source thread. We are either + // storing a new response or updating the currently stored response, potentially setting a new + // expiry date. + assert(queue); + assert(response); + + if (hint == Hint::Full) { + queue->send(PutAction{ resource, response }); + } else if (hint == Hint::Refresh) { + queue->send(RefreshAction{ resource, response->expires }); + } +} + +void SQLiteCache::createDatabase() { + db = util::make_unique(path.c_str(), ReadWrite | Create); + + constexpr const char *const sql = "" + "CREATE TABLE IF NOT EXISTS `http_cache` (" + " `url` TEXT PRIMARY KEY NOT NULL," + " `status` INTEGER NOT NULL," // The response status (Successful or Error). + " `kind` INTEGER NOT NULL," // The kind of file. + " `modified` INTEGER," // Timestamp when the file was last modified. + " `etag` TEXT," + " `expires` INTEGER," // Timestamp when the server says the file expires. + " `data` BLOB," + " `compressed` INTEGER NOT NULL DEFAULT 0" // Whether the data is compressed. + ");" + "CREATE INDEX IF NOT EXISTS `http_cache_kind_idx` ON `http_cache` (`kind`);"; + + try { + db->exec(sql); + } catch(mapbox::sqlite::Exception &) { + // 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.release(); + } + } +} + +void SQLiteCache::process(GetAction &action) { + // This is called in the SQLite event loop. + if (!db) { + createDatabase(); + } + + if (!getStmt) { + // Initialize the statement 0 1 + getStmt = util::make_unique(db->prepare("SELECT `status`, `modified`, " + // 2 3 4 5 1 + "`etag`, `expires`, `data`, `compressed` FROM `http_cache` WHERE `url` = ?")); + } else { + getStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(action.resource.url); + getStmt->bind(1, unifiedURL.c_str()); + if (getStmt->run()) { + // There is data. + auto response = util::make_unique(); + response->status = Response::Status(getStmt->get(0)); + response->modified = getStmt->get(1); + response->etag = getStmt->get(2); + response->expires = getStmt->get(3); + response->data = getStmt->get(4); + if (getStmt->get(5)) { // == compressed + response->data = util::decompress(response->data); + } + action.callback(std::move(response)); + } else { + // There is no data. + action.callback(nullptr); + } +} + +void SQLiteCache::process(PutAction &action) { + if (!db) { + createDatabase(); + } + + if (!putStmt) { + putStmt = util::make_unique(db->prepare("REPLACE INTO `http_cache` (" + // 1 2 3 4 5 6 7 8 + "`url`, `status`, `kind`, `modified`, `etag`, `expires`, `data`, `compressed`" + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?)")); + } else { + putStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(action.resource.url); + putStmt->bind(1 /* url */, unifiedURL.c_str()); + putStmt->bind(2 /* status */, int(action.response->status)); + putStmt->bind(3 /* kind */, int(action.resource.kind)); + putStmt->bind(4 /* modified */, action.response->modified); + putStmt->bind(5 /* etag */, action.response->etag.c_str()); + putStmt->bind(6 /* expires */, action.response->expires); + + std::string data; + if (action.resource.kind != Resource::Image) { + // Do not compress images, since they are typically compressed already. + data = util::compress(action.response->data); + } + + if (!data.empty() && data.size() < action.response->data.size()) { + // Store the compressed data when it is smaller than the original + // uncompressed data. + putStmt->bind(7 /* data */, data, false); // do not retain the string internally. + putStmt->bind(8 /* compressed */, true); + } else { + putStmt->bind(7 /* data */, action.response->data, false); // do not retain the string internally. + putStmt->bind(8 /* compressed */, false); + } + + putStmt->run(); +} + +void SQLiteCache::process(RefreshAction &action) { + if (!db) { + createDatabase(); + } + + if (!refreshStmt) { + refreshStmt = util::make_unique( // 1 2 + db->prepare("UPDATE `http_cache` SET `expires` = ? WHERE `url` = ?")); + } else { + refreshStmt->reset(); + } + + const std::string unifiedURL = unifyMapboxURLs(action.resource.url); + refreshStmt->bind(1, int64_t(action.expires)); + refreshStmt->bind(2, unifiedURL.c_str()); + refreshStmt->run(); +} + +void SQLiteCache::process(StopAction &) { + assert(queue); + queue->stop(); + queue = nullptr; +} + +} diff --git a/platform/default/uv_zip.c b/platform/default/uv_zip.c new file mode 100644 index 000000000..b6d2c2ebe --- /dev/null +++ b/platform/default/uv_zip.c @@ -0,0 +1,202 @@ +#include "uv_zip.h" + +#include +#include +#include + + +void uv__zip_open_error(uv_zip_t *zip, int error) { + zip->result = -error; + if (zip->message) { + free((char *)zip->message); + zip->message = NULL; + } + const zip_uint64_t size = zip_error_to_str(NULL, 0, error, errno) + 1; + zip->message = malloc(size); + zip_error_to_str((char *)zip->message, size, error, errno); +} + +void uv__zip_store_error(uv_zip_t *zip, const char *message) { + if (zip->message) { + free((char *)zip->message); + zip->message = NULL; + } + const unsigned long length = strlen(message); + zip->message = malloc(length); + strncpy((char *)zip->message, message, length); +} + +void uv__zip_error(uv_zip_t *zip) { + int error; + zip_error_get(zip->archive, &error, NULL); + zip->result = -error; + uv__zip_store_error(zip, zip_strerror(zip->archive)); +} + +void uv__zip_file_error(uv_zip_t *zip) { + int error; + zip_file_error_get(zip->file, &error, NULL); + zip->result = -error; + uv__zip_store_error(zip, zip_file_strerror(zip->file)); +} + +void uv__zip_work_open(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(!zip->archive); + + int error; + zip->archive = zip_open(zip->path, zip->flags, &error); + if (!zip->archive) { + uv__zip_open_error(zip, error); + } else { + zip->result = 0; + } +} + +void uv__zip_work_fdopen(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(!zip->archive); + + // extract the fd + uv_file fd = *(uv_file *)zip->path; + free((uv_file *)zip->path); + zip->path = NULL; + + int error; + zip->archive = zip_fdopen(fd, zip->flags, &error); + if (!zip->archive) { + uv__zip_open_error(zip, error); + } else { + zip->result = 0; + } +} + +void uv__zip_work_stat(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(zip->archive); + if (!zip->stat) { + zip->stat = malloc(sizeof(struct zip_stat)); + zip_stat_init(zip->stat); + } + if (0 != zip_stat(zip->archive, zip->path, zip->flags, zip->stat)) { + uv__zip_error(zip); + } +} + +void uv__zip_work_fopen(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(zip->archive); + zip->file = zip_fopen(zip->archive, zip->path, zip->flags); + if (!zip->file) { + uv__zip_error(zip); + } +} + +void uv__zip_work_fread(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(zip->file); + assert(zip->buf); + zip->result = zip_fread(zip->file, zip->buf->base, zip->buf->len); + if (zip->result < 0) { + uv__zip_file_error(zip); + } +} + +void uv__zip_work_fclose(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(zip->file); + zip->result = zip_fclose(zip->file); + if (zip->result != 0) { + uv__zip_file_error(zip); + } +} + +void uv__zip_work_discard(uv_work_t *req) { + uv_zip_t *zip = (uv_zip_t *)req->data; + assert(zip->archive); + zip_discard(zip->archive); + zip->archive = NULL; + zip->result = 0; +} + +void uv__zip_after_work(uv_work_t *req, int status) { + uv_zip_t *zip = (uv_zip_t *)req->data; + if (zip->cb) { + zip->cb(zip); + } +} + +void uv_zip_init(uv_zip_t *zip) { + zip->work.data = zip; + zip->message = NULL; + zip->stat = NULL; + uv_zip_cleanup(zip); +} + +void uv_zip_cleanup(uv_zip_t *zip) { + zip->data = NULL; + zip->flags = 0; + zip->result = 0; + zip->path = NULL; + zip->cb = NULL; + zip->archive = NULL; + zip->file = NULL; + zip->buf = NULL; + + if (zip->message) { + free((char *)zip->message); + zip->message = NULL; + } + + if (zip->stat) { + free(zip->stat); + zip->stat = NULL; + } +} + +int uv_zip_open(uv_loop_t* loop, uv_zip_t *zip, const char *path, zip_flags_t flags, uv_zip_cb cb) { + zip->path = path; + zip->flags = flags; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_open, uv__zip_after_work); +} + +int uv_zip_fdopen(uv_loop_t* loop, uv_zip_t *zip, uv_file fd, int flags, uv_zip_cb cb) { + zip->path = malloc(sizeof(uv_file)); + *(uv_file *)zip->path = fd; + zip->flags = flags; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_fdopen, uv__zip_after_work); +} + +int uv_zip_stat(uv_loop_t* loop, uv_zip_t *zip, const char *fname, zip_flags_t flags, uv_zip_cb cb) { + zip->path = fname; + zip->flags = flags; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_stat, uv__zip_after_work); +} + +int uv_zip_fopen(uv_loop_t* loop, uv_zip_t *zip, const char *fname, zip_flags_t flags, uv_zip_cb cb) { + zip->path = fname; + zip->flags = flags; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_fopen, uv__zip_after_work); +} + +int uv_zip_fclose(uv_loop_t* loop, uv_zip_t *zip, struct zip_file *file, uv_zip_cb cb) { + zip->file = file; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_fclose, uv__zip_after_work); +} + +int uv_zip_fread(uv_loop_t* loop, uv_zip_t *zip, struct zip_file *file, uv_buf_t *buf, uv_zip_cb cb) { + zip->file = file; + zip->buf = buf; + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_fread, uv__zip_after_work); +} + +int uv_zip_discard(uv_loop_t* loop, uv_zip_t *zip, uv_zip_cb cb) { + zip->cb = cb; + return uv_queue_work(loop, &zip->work, uv__zip_work_discard, uv__zip_after_work); +} diff --git a/platform/default/uv_zip.h b/platform/default/uv_zip.h new file mode 100644 index 000000000..5908763f0 --- /dev/null +++ b/platform/default/uv_zip.h @@ -0,0 +1,45 @@ +#ifndef UV_ZIP +#define UV_ZIP + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef struct uv_zip_s uv_zip_t; + +typedef void (*uv_zip_cb)(uv_zip_t* req); + +struct uv_zip_s { + uv_work_t work; + ssize_t result; + const char *message; + struct zip *archive; + struct zip_file *file; + struct zip_stat *stat; + void *data; + zip_flags_t flags; + const char *path; + uv_zip_cb cb; + uv_buf_t *buf; +}; + +void uv_zip_init(uv_zip_t *zip); +void uv_zip_cleanup(uv_zip_t *zip); + +int uv_zip_open(uv_loop_t* loop, uv_zip_t *zip, const char *path, zip_flags_t flags, uv_zip_cb cb); +int uv_zip_fdopen(uv_loop_t* loop, uv_zip_t *zip, uv_file fd, int flags, uv_zip_cb cb); +int uv_zip_stat(uv_loop_t* loop, uv_zip_t *zip, const char *fname, zip_flags_t flags, uv_zip_cb cb); +int uv_zip_fopen(uv_loop_t* loop, uv_zip_t *zip, const char *fname, zip_flags_t flags, uv_zip_cb cb); +int uv_zip_fread(uv_loop_t* loop, uv_zip_t *zip, struct zip_file *file, uv_buf_t *buf, uv_zip_cb cb); +int uv_zip_fclose(uv_loop_t* loop, uv_zip_t *zip, struct zip_file *file, uv_zip_cb cb); +int uv_zip_discard(uv_loop_t* loop, uv_zip_t *zip, uv_zip_cb cb); + +#ifdef __cplusplus +} +#endif + +#endif // UV_ZIP diff --git a/platform/ios/cache_database_library.mm b/platform/ios/cache_database_library.mm deleted file mode 100644 index 7989e73a4..000000000 --- a/platform/ios/cache_database_library.mm +++ /dev/null @@ -1,21 +0,0 @@ -#import - -#include - -namespace mbgl { -namespace platform { - -// Returns the path to the default cache database on this system. -std::string defaultCacheDatabase() { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); - if ([paths count] == 0) { - // Disable the cache if we don't have a location to write. - return ""; - } - - NSString *libraryDirectory = [paths objectAtIndex:0]; - return [[libraryDirectory stringByAppendingPathComponent:@"cache.db"] UTF8String]; -} - -} -} diff --git a/platform/osx/cache_database_application_support.mm b/platform/osx/cache_database_application_support.mm deleted file mode 100644 index 974ea537c..000000000 --- a/platform/osx/cache_database_application_support.mm +++ /dev/null @@ -1,31 +0,0 @@ -#import - -#include - -namespace mbgl { -namespace platform { - -// Returns the path to the default cache database on this system. -std::string defaultCacheDatabase() { - NSArray *paths = - NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - if ([paths count] == 0) { - // Disable the cache if we don't have a location to write. - return ""; - } - - NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Mapbox GL"]; - - if (![[NSFileManager defaultManager] createDirectoryAtPath:path - withIntermediateDirectories:YES - attributes:nil - error:nil]) { - // Disable the cache if we couldn't create the directory. - return ""; - } - - return [[path stringByAppendingPathComponent:@"cache.db"] UTF8String]; -} - -} -} diff --git a/scripts/android_env.sh b/scripts/android_env.sh new file mode 100755 index 000000000..93b1452a5 --- /dev/null +++ b/scripts/android_env.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +set -e +set -o pipefail + +./scripts/local_mason.sh + +export MASON_PLATFORM=android + +export PATH=`.mason/mason env PATH` + +echo MASON_PLATFORM=\"android\" +echo MASON_ANDROID_ABI=\"${MASON_ANDROID_ABI}\" + +echo CXX=\"`which $(.mason/mason env CXX)`\" +echo CC=\"`which $(.mason/mason env CC)`\" +echo LD=\"`which $(.mason/mason env LD)`\" +echo LINK=\"`which $(.mason/mason env CXX)`\" +echo AR=\"`which $(.mason/mason env AR)`\" +echo RANLIB=\"`which $(.mason/mason env RANLIB)`\" +echo STRIP=\"`which $(.mason/mason env STRIP)`\" +echo LDFLAGS=\"`.mason/mason env LDFLAGS` ${LDFLAGS}\" +echo CFLAGS=\"`.mason/mason env CFLAGS` ${CFLAGS}\" +echo CPPFLAGS=\"`.mason/mason env CPPFLAGS` ${CPPFLAGS}\" +echo JNIDIR=\"`.mason/mason env JNIDIR`\" diff --git a/scripts/flags.sh b/scripts/flags.sh index 8703677d0..10cc88e5c 100755 --- a/scripts/flags.sh +++ b/scripts/flags.sh @@ -30,6 +30,3 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then # fi # fi fi - -# turn off a few warnings -export CXXFLAGS="-Wno-unknown-warning-option -Wno-unused-local-typedefs -Wno-unknown-pragmas ${CXXFLAGS}"; diff --git a/scripts/flock.py b/scripts/flock.py new file mode 100755 index 000000000..6ceb585cd --- /dev/null +++ b/scripts/flock.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +import fcntl, os, subprocess, sys, errno + +# from http://stackoverflow.com/a/600612 +def mkdir_p(path): + try: + os.makedirs(path) + except OSError as exc: # Python >2.5 + if exc.errno == errno.EEXIST and os.path.isdir(path): + pass + else: raise + +def flock(lockfile, cmd_list, verbose = False): + mkdir_p(os.path.dirname(lockfile)) + fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + if verbose: + print(' '.join(cmd_list)) + return subprocess.call(cmd_list) + +if '__main__' == __name__: + try: + if sys.argv[1] == '-v': + sys.exit(flock(sys.argv[2], sys.argv[3:], True)) + else: + sys.exit(flock(sys.argv[1], sys.argv[2:])) + except KeyboardInterrupt: + sys.exit(1) diff --git a/scripts/install_node.sh b/scripts/install_node.sh new file mode 100755 index 000000000..ecb5b8835 --- /dev/null +++ b/scripts/install_node.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +mason install node 0.10.35 +export PATH="`mason prefix node 0.10.35`/bin":"$PATH" diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index e10700076..e4c9e77ea 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -3,34 +3,42 @@ set -e set -o pipefail -cd build/${BUILDTYPE:-Release} +if [ `uname -s` = 'Darwin' ]; then HOST=${HOST:-osx} ; else HOST=${HOST:-linux} ; fi -for TEST in ./test_* ; do - # allow writing core files - ulimit -c unlimited -S - echo 'ulimit -c: '`ulimit -c` +CMD=$1 +shift + +# allow writing core files +ulimit -c unlimited -S +echo 'ulimit -c: '`ulimit -c` +if [ -f /proc/sys/kernel/core_pattern ]; then echo '/proc/sys/kernel/core_pattern: '`cat /proc/sys/kernel/core_pattern` +fi - if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then - sysctl kernel.core_pattern - fi +if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then + sysctl kernel.core_pattern +fi - RESULT=0 - ${TEST} || RESULT=$? +# install test server dependencies +if [ ! -d "test/node_modules/express" ]; then + (cd test; npm install express@4.11.1) +fi - if [[ ${RESULT} != 0 ]]; then - echo "The program crashed with exit code ${RESULT}. We're now trying to output the core dump." - fi +RESULT=0 +${CMD} "$@" || RESULT=$? - # output core dump if we got one - for DUMP in $(find ./ -maxdepth 1 -name 'core*' -print); do - gdb ${TEST} ${DUMP} -ex "thread apply all bt" -ex "set pagination 0" -batch - rm -rf ${DUMP} - done +if [[ ${RESULT} != 0 ]]; then + echo "The program crashed with exit code ${RESULT}. We're now trying to output the core dump." +fi - # now we should present travis with the original - # error code so the run cleanly stops - if [[ ${RESULT} != 0 ]]; then - exit $RESULT - fi +# output core dump if we got one +for DUMP in $(find ./ -maxdepth 1 -name 'core*' -print); do + gdb ${CMD} ${DUMP} -ex "thread apply all bt" -ex "set pagination 0" -batch + rm -rf ${DUMP} done + +# now we should present travis with the original +# error code so the run cleanly stops +if [[ ${RESULT} != 0 ]]; then + exit $RESULT +fi diff --git a/scripts/travis_script.sh b/scripts/travis_script.sh index 308dfb8f1..71635b5c7 100755 --- a/scripts/travis_script.sh +++ b/scripts/travis_script.sh @@ -23,7 +23,7 @@ elif [[ ${TRAVIS_OS_NAME} == "linux" ]]; then git submodule update --init test/suite mapbox_time "run_tests" \ - ./scripts/run_tests.sh + make test-* BUILDTYPE=${BUILDTYPE} mapbox_time "compare_results" \ ./scripts/compare_images.sh @@ -38,11 +38,8 @@ elif [[ ${TRAVIS_OS_NAME} == "osx" ]]; then # # build OS X # - mapbox_time "create_osx_project" \ - make build/macosx/mapboxgl-app.xcodeproj - - mapbox_time "build_osx" \ - xcodebuild -project ./build/macosx/mapboxgl-app.xcodeproj -jobs $JOBS + mapbox_time "build_osx_project" \ + make xosx -j$JOBS # # build iOS @@ -50,9 +47,6 @@ elif [[ ${TRAVIS_OS_NAME} == "osx" ]]; then mapbox_time "checkout_cocoa_bindings" \ git submodule update --init ios/mapbox-gl-cocoa - mapbox_time "create_ios_project" \ - make build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj - - mapbox_time "build_ios" \ - xcodebuild -project ./build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj -sdk iphonesimulator ONLY_ACTIVE_ARCH=NO -jobs $JOBS + mapbox_time "build_ios_project" \ + make ios -j$JOBS fi diff --git a/src/mbgl/geometry/buffer.hpp b/src/mbgl/geometry/buffer.hpp index 0b28f77d0..3649574bb 100644 --- a/src/mbgl/geometry/buffer.hpp +++ b/src/mbgl/geometry/buffer.hpp @@ -80,7 +80,7 @@ protected: } } pos += itemSize; - return static_cast(array) + (pos - itemSize); + return reinterpret_cast(array) + (pos - itemSize); } // Get a pointer to the item at a given index. @@ -92,7 +92,7 @@ protected: if (i * itemSize >= pos) { throw new std::runtime_error("Can't get element after array bounds"); } else { - return static_cast(array) + (i * itemSize); + return reinterpret_cast(array) + (i * itemSize); } } diff --git a/src/mbgl/geometry/elements_buffer.hpp b/src/mbgl/geometry/elements_buffer.hpp index 9255337cb..5c1b421d3 100644 --- a/src/mbgl/geometry/elements_buffer.hpp +++ b/src/mbgl/geometry/elements_buffer.hpp @@ -21,11 +21,6 @@ struct ElementGroup : public util::noncopyable { : vertex_length(vertex_length_), elements_length(elements_length_) { } - - ElementGroup(ElementGroup &&rhs) noexcept - : array(std::move(rhs.array)), - vertex_length(rhs.vertex_length), - elements_length(rhs.elements_length) {}; }; class TriangleElementsBuffer : public Buffer< diff --git a/src/mbgl/geometry/sprite_atlas.cpp b/src/mbgl/geometry/sprite_atlas.cpp index 35365c7e4..93440b0e6 100644 --- a/src/mbgl/geometry/sprite_atlas.cpp +++ b/src/mbgl/geometry/sprite_atlas.cpp @@ -66,13 +66,29 @@ bool SpriteAtlas::resize(const float newRatio) { } void copy_bitmap(const uint32_t *src, const int src_stride, const int src_x, const int src_y, - uint32_t *dst, const int dst_stride, const int dst_x, const int dst_y, - const int width, const int height) { - src += src_y * src_stride + src_x; - dst += dst_y * dst_stride + dst_x; - for (int y = 0; y < height; y++, src += src_stride, dst += dst_stride) { - for (int x = 0; x < width; x++) { - dst[x] = src[x]; + uint32_t *dst, const int dst_stride, const int dst_height, const int dst_x, const int dst_y, + const int width, const int height, const bool wrap) { + if (wrap) { + + for (int y = -1; y <= height; y++) { + int dst_y_wrapped = (y + dst_y + dst_height) % dst_height; + int src_y_wrapped = ((y + height) % height) + src_y; + int srcI = src_y_wrapped * src_stride + src_x; + int dstI = dst_y_wrapped * dst_stride; + for (int x = -1; x <= width; x++) { + int dst_x_wrapped = (x + dst_x + dst_stride) % dst_stride; + int src_x_wrapped = (x + width) % width; + dst[dstI + dst_x_wrapped] = src[srcI + src_x_wrapped]; + } + } + + } else { + dst += dst_y * dst_stride + dst_x; + src += src_y * src_stride + src_x; + for (int y = 0; y < height; y++, src += src_stride, dst += dst_stride) { + for (int x = 0; x < width; x++) { + dst[x] = src[x]; + } } } } @@ -97,7 +113,7 @@ Rect SpriteAtlas::allocateImage(const size_t pixel_width return rect; } -Rect SpriteAtlas::getImage(const std::string& name) { +Rect SpriteAtlas::getImage(const std::string& name, const bool wrap) { std::lock_guard lock(mtx); auto rect_it = images.find(name); @@ -120,7 +136,7 @@ Rect SpriteAtlas::getImage(const std::string& name) { images.emplace(name, rect); - copy(rect, pos); + copy(rect, pos, wrap); return rect; } @@ -128,7 +144,7 @@ Rect SpriteAtlas::getImage(const std::string& name) { SpriteAtlasPosition SpriteAtlas::getPosition(const std::string& name, bool repeating) { std::lock_guard lock(mtx); - Rect rect = getImage(name); + Rect rect = getImage(name, repeating); if (repeating) { // When the image is repeating, get the correct position of the image, rather than the // one rounded up to 4 pixels. @@ -157,7 +173,7 @@ void SpriteAtlas::allocate() { } } -void SpriteAtlas::copy(const Rect& dst, const SpritePosition& src) { +void SpriteAtlas::copy(const Rect& dst, const SpritePosition& src, const bool wrap) { if (!sprite->raster) return; const uint32_t *src_img = reinterpret_cast(sprite->raster->getData()); if (!src_img) return; @@ -171,10 +187,12 @@ void SpriteAtlas::copy(const Rect& dst, const SpritePosition& src) { /* source y */ src.y, /* dest buffer */ dst_img, /* dest stride */ width * pixelRatio, + /* dest height */ height * pixelRatio, /* dest x */ dst.x * pixelRatio, /* dest y */ dst.y * pixelRatio, /* icon dimension */ src.width, - /* icon dimension */ src.height + /* icon dimension */ src.height, + /* wrap padding */ wrap ); dirty = true; @@ -188,7 +206,7 @@ void SpriteAtlas::setSprite(util::ptr sprite_) { if (!sprite->isLoaded()) return; util::erase_if(uninitialized, [this](const std::string &name) { - Rect dst = getImage(name); + Rect dst = getImage(name, false); const SpritePosition& src = sprite->getSpritePosition(name); if (!src) { if (debug::spriteWarnings) { @@ -198,7 +216,7 @@ void SpriteAtlas::setSprite(util::ptr sprite_) { } if (src.width == dst.w * pixelRatio && src.height == dst.h * pixelRatio && src.pixelRatio == pixelRatio) { - copy(dst, src); + copy(dst, src, false); return true; } else { if (debug::spriteWarnings) { @@ -217,8 +235,8 @@ void SpriteAtlas::bind(bool linear) { #ifndef GL_ES_VERSION_2_0 MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); #endif - MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); - MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); + MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)); + MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)); first = true; } else { MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture)); diff --git a/src/mbgl/geometry/sprite_atlas.hpp b/src/mbgl/geometry/sprite_atlas.hpp index ebfd69edf..079c15cef 100644 --- a/src/mbgl/geometry/sprite_atlas.hpp +++ b/src/mbgl/geometry/sprite_atlas.hpp @@ -46,7 +46,7 @@ public: // This getter attempts to read the image from the sprite if it is already loaded. // In that case, it copies it into the sprite atlas and returns the dimensions. // Otherwise, it returns a 0/0/0/0 rect. - Rect getImage(const std::string& name); + Rect getImage(const std::string& name, const bool wrap); SpriteAtlasPosition getPosition(const std::string& name, bool repeating = false); @@ -66,7 +66,7 @@ public: private: void allocate(); Rect allocateImage(size_t width, size_t height); - void copy(const Rect& dst, const SpritePosition& src); + void copy(const Rect& dst, const SpritePosition& src, const bool wrap); std::recursive_mutex mtx; float pixelRatio = 1.0f; diff --git a/src/mbgl/geometry/vao.cpp b/src/mbgl/geometry/vao.cpp index 0868d9251..00976b4d5 100644 --- a/src/mbgl/geometry/vao.cpp +++ b/src/mbgl/geometry/vao.cpp @@ -4,6 +4,9 @@ namespace mbgl { +VertexArrayObject::VertexArrayObject() { +} + VertexArrayObject::~VertexArrayObject() { if (!gl::DeleteVertexArrays) return; diff --git a/src/mbgl/geometry/vao.hpp b/src/mbgl/geometry/vao.hpp index 2ecba731f..72bacfd79 100644 --- a/src/mbgl/geometry/vao.hpp +++ b/src/mbgl/geometry/vao.hpp @@ -11,15 +11,8 @@ namespace mbgl { class VertexArrayObject : public util::noncopyable { public: - inline VertexArrayObject() {}; - - inline VertexArrayObject(VertexArrayObject &&rhs) noexcept - : vao(rhs.vao), - bound_shader(rhs.bound_shader), - bound_shader_name(rhs.bound_shader_name), - bound_vertex_buffer(rhs.bound_vertex_buffer), - bound_elements_buffer(rhs.bound_elements_buffer), - bound_offset(rhs.bound_offset) {}; + VertexArrayObject(); + ~VertexArrayObject(); template inline void bind(Shader& shader, VertexBuffer &vertexBuffer, char *offset) { @@ -50,7 +43,9 @@ public: } } - ~VertexArrayObject(); + inline GLuint getID() const { + return vao; + } private: void bindVertexArrayObject(); diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index ff584c54b..5aff7a2b7 100644 --- a/src/mbgl/map/map.cpp +++ b/src/mbgl/map/map.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -25,6 +24,7 @@ #include #include #include +#include #include #include @@ -54,44 +54,12 @@ const static bool uvVersionCheck = []() { return true; }(); - -#include -// Check zlib library version. -const static bool zlibVersionCheck = []() { - const char *const version = zlibVersion(); - if (version[0] != ZLIB_VERSION[0]) { - throw std::runtime_error(mbgl::util::sprintf<96>( - "zlib version mismatch: headers report %s, but library reports %s", ZLIB_VERSION, version)); - } - - return true; -}(); - - -#include -// Check sqlite3 library version. -const static bool sqliteVersionCheck = []() { - if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER) { - throw std::runtime_error(mbgl::util::sprintf<96>( - "sqlite3 libversion mismatch: headers report %d, but library reports %d", - SQLITE_VERSION_NUMBER, sqlite3_libversion_number())); - } - if (strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID) != 0) { - throw std::runtime_error(mbgl::util::sprintf<256>( - "sqlite3 sourceid mismatch: headers report \"%s\", but library reports \"%s\"", - SQLITE_SOURCE_ID, sqlite3_sourceid())); - } - - return true; -}(); - - using namespace mbgl; Map::Map(View& view_, FileSource& fileSource_) : loop(util::make_unique()), view(view_), -#ifndef NDEBUG +#ifdef DEBUG mainThread(std::this_thread::get_id()), mapThread(mainThread), #endif @@ -128,9 +96,7 @@ Map::~Map() { } uv::worker &Map::getWorker() { - if (!workers) { - workers = util::make_unique(**loop, 4, "Tile Worker"); - } + assert(workers); return *workers; } @@ -154,8 +120,6 @@ void Map::start(bool startPaused) { workers.reset(); activeSources.clear(); - fileSource.clearLoop(); - terminating = true; // Closes all open handles on the loop. This means that the loop will automatically terminate. @@ -188,7 +152,7 @@ void Map::start(bool startPaused) { } thread = std::thread([this]() { -#ifndef NDEBUG +#ifdef DEBUG mapThread = std::this_thread::get_id(); #endif @@ -198,7 +162,7 @@ void Map::start(bool startPaused) { run(); -#ifndef NDEBUG +#ifdef DEBUG mapThread = std::thread::id(); #endif @@ -266,7 +230,7 @@ void Map::resume() { void Map::run() { if (mode == Mode::None) { -#ifndef NDEBUG +#ifdef DEBUG mapThread = mainThread; #endif mode = Mode::Static; @@ -278,6 +242,9 @@ void Map::run() { } view.activate(); + + workers = util::make_unique(**loop, 4, "Tile Worker"); + setup(); prepare(); @@ -298,11 +265,10 @@ void Map::run() { // *after* all events have been processed. if (mode == Mode::Static) { render(); -#ifndef NDEBUG +#ifdef DEBUG mapThread = std::thread::id(); #endif mode = Mode::None; - fileSource.clearLoop(); } view.deactivate(); @@ -387,13 +353,14 @@ void Map::setStyleJSON(std::string newStyleJSON, const std::string &base) { style = std::make_shared