From 465c949153a838bb3159204ab268eb551fbd2e6c Mon Sep 17 00:00:00 2001 From: Ivo van Dongen Date: Thu, 16 Feb 2017 16:16:47 +0200 Subject: [android] jni high level binding refactor --- platform/android/src/annotation/marker.cpp | 31 + platform/android/src/annotation/marker.hpp | 30 + platform/android/src/annotation/multi_point.hpp | 42 + platform/android/src/annotation/polygon.cpp | 49 + platform/android/src/annotation/polygon.hpp | 40 + platform/android/src/annotation/polyline.cpp | 49 + platform/android/src/annotation/polyline.hpp | 40 + platform/android/src/conversion/collection.hpp | 13 + platform/android/src/conversion/color.hpp | 24 + platform/android/src/default_file_source.cpp | 20 - platform/android/src/default_file_source.hpp | 12 - platform/android/src/file_source.cpp | 106 + platform/android/src/file_source.hpp | 53 + .../android/src/geometry/conversion/feature.hpp | 38 +- platform/android/src/geometry/feature.cpp | 20 + platform/android/src/geometry/feature.hpp | 29 + platform/android/src/geometry/geometry.hpp | 16 + platform/android/src/geometry/lat_lng.cpp | 31 + platform/android/src/geometry/lat_lng.hpp | 31 + platform/android/src/geometry/lat_lng_bounds.cpp | 31 + platform/android/src/geometry/lat_lng_bounds.hpp | 29 + platform/android/src/geometry/projected_meters.cpp | 20 + platform/android/src/geometry/projected_meters.hpp | 26 + platform/android/src/graphics/pointf.cpp | 20 + platform/android/src/graphics/pointf.hpp | 25 + platform/android/src/graphics/rectf.cpp | 35 + platform/android/src/graphics/rectf.hpp | 31 + platform/android/src/gson/json_object.hpp | 16 + platform/android/src/java/util.cpp | 18 + platform/android/src/java/util.hpp | 33 + platform/android/src/jni.cpp | 2108 +------------------- platform/android/src/jni.hpp | 10 +- .../android/src/jni/generic_global_ref_deleter.hpp | 22 + platform/android/src/native_map_view.cpp | 1163 ++++++++--- platform/android/src/native_map_view.hpp | 256 ++- platform/android/src/offline/offline_manager.cpp | 164 ++ platform/android/src/offline/offline_manager.hpp | 75 + platform/android/src/offline/offline_region.cpp | 308 +++ platform/android/src/offline/offline_region.hpp | 99 + .../src/offline/offline_region_definition.cpp | 69 + .../src/offline/offline_region_definition.hpp | 34 + .../android/src/offline/offline_region_error.cpp | 53 + .../android/src/offline/offline_region_error.hpp | 21 + .../android/src/offline/offline_region_status.cpp | 39 + .../android/src/offline/offline_region_status.hpp | 21 + platform/android/src/style/android_conversion.hpp | 1 - 46 files changed, 3037 insertions(+), 2364 deletions(-) create mode 100644 platform/android/src/annotation/marker.cpp create mode 100644 platform/android/src/annotation/marker.hpp create mode 100644 platform/android/src/annotation/multi_point.hpp create mode 100644 platform/android/src/annotation/polygon.cpp create mode 100644 platform/android/src/annotation/polygon.hpp create mode 100644 platform/android/src/annotation/polyline.cpp create mode 100644 platform/android/src/annotation/polyline.hpp create mode 100644 platform/android/src/conversion/color.hpp delete mode 100644 platform/android/src/default_file_source.cpp delete mode 100644 platform/android/src/default_file_source.hpp create mode 100644 platform/android/src/file_source.cpp create mode 100644 platform/android/src/file_source.hpp create mode 100644 platform/android/src/geometry/feature.cpp create mode 100644 platform/android/src/geometry/feature.hpp create mode 100644 platform/android/src/geometry/geometry.hpp create mode 100644 platform/android/src/geometry/lat_lng.cpp create mode 100644 platform/android/src/geometry/lat_lng.hpp create mode 100644 platform/android/src/geometry/lat_lng_bounds.cpp create mode 100644 platform/android/src/geometry/lat_lng_bounds.hpp create mode 100644 platform/android/src/geometry/projected_meters.cpp create mode 100644 platform/android/src/geometry/projected_meters.hpp create mode 100644 platform/android/src/graphics/pointf.cpp create mode 100644 platform/android/src/graphics/pointf.hpp create mode 100644 platform/android/src/graphics/rectf.cpp create mode 100644 platform/android/src/graphics/rectf.hpp create mode 100644 platform/android/src/gson/json_object.hpp create mode 100644 platform/android/src/java/util.cpp create mode 100644 platform/android/src/java/util.hpp create mode 100644 platform/android/src/jni/generic_global_ref_deleter.hpp create mode 100644 platform/android/src/offline/offline_manager.cpp create mode 100644 platform/android/src/offline/offline_manager.hpp create mode 100644 platform/android/src/offline/offline_region.cpp create mode 100644 platform/android/src/offline/offline_region.hpp create mode 100644 platform/android/src/offline/offline_region_definition.cpp create mode 100644 platform/android/src/offline/offline_region_definition.hpp create mode 100644 platform/android/src/offline/offline_region_error.cpp create mode 100644 platform/android/src/offline/offline_region_error.hpp create mode 100644 platform/android/src/offline/offline_region_status.cpp create mode 100644 platform/android/src/offline/offline_region_status.hpp (limited to 'platform/android/src') diff --git a/platform/android/src/annotation/marker.cpp b/platform/android/src/annotation/marker.cpp new file mode 100644 index 0000000000..a1fe436dbd --- /dev/null +++ b/platform/android/src/annotation/marker.cpp @@ -0,0 +1,31 @@ +#include "marker.hpp" + +namespace mbgl { +namespace android { + +jni::Class Marker::javaClass; + +mbgl::Point Marker::getPosition(jni::JNIEnv& env, jni::Object marker) { + static auto positionField = Marker::javaClass.GetField>(env, "position"); + auto jPosition = marker.Get(env, positionField); + auto position = LatLng::getGeometry(env, jPosition); + jni::DeleteLocalRef(env, jPosition); + return position; +} + +std::string Marker::getIconId(jni::JNIEnv& env, jni::Object marker) { + static auto iconIdField = Marker::javaClass.GetField(env, "iconId"); + auto jIconId = marker.Get(env, iconIdField); + auto iconId = jni::Make(env, jIconId); + jni::DeleteLocalRef(env, jIconId); + return iconId; +} + +void Marker::registerNative(jni::JNIEnv& env) { + // Lookup the class + Marker::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/marker.hpp b/platform/android/src/annotation/marker.hpp new file mode 100644 index 0000000000..b11a225245 --- /dev/null +++ b/platform/android/src/annotation/marker.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +#include + +#include "../geometry/lat_lng.hpp" + +namespace mbgl { +namespace android { + +class Marker : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/annotations/Marker"; }; + + static jni::Class javaClass; + + static mbgl::Point getPosition(jni::JNIEnv&, jni::Object); + + static std::string getIconId(jni::JNIEnv&, jni::Object); + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/multi_point.hpp b/platform/android/src/annotation/multi_point.hpp new file mode 100644 index 0000000000..e1152dfd60 --- /dev/null +++ b/platform/android/src/annotation/multi_point.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include "../geometry/lat_lng.hpp" +#include "../java/util.hpp" + +namespace mbgl { +namespace android { + +class MultiPoint : protected mbgl::util::noncopyable { + +protected: + + template + static Geometry toGeometry(JNIEnv& env, jni::Object pointsList) { + NullCheck(env, &pointsList); + auto jarray = java::util::List::toArray(env, pointsList); + NullCheck(env, &jarray); + + std::size_t size = jarray.Length(env); + + Geometry geometry; + geometry.reserve(size); + + for (std::size_t i = 0; i < size; i++) { + auto latLng = jarray.Get(env, i); + NullCheck(env, &latLng); + + geometry.push_back(LatLng::getGeometry(env, latLng)); + + jni::DeleteLocalRef(env, latLng); + } + + jni::DeleteLocalRef(env, jarray); + return geometry; + } +}; + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/polygon.cpp b/platform/android/src/annotation/polygon.cpp new file mode 100644 index 0000000000..ba82fc34dc --- /dev/null +++ b/platform/android/src/annotation/polygon.cpp @@ -0,0 +1,49 @@ +#include "polygon.hpp" + +#include "../conversion/color.hpp" + +namespace mbgl { +namespace android { + +jni::Class Polygon::javaClass; + +mbgl::FillAnnotation Polygon::toAnnotation(jni::JNIEnv& env, jni::Object polygon) { + auto points = Polygon::getPoints(env, polygon); + + mbgl::FillAnnotation annotation { mbgl::Polygon { MultiPoint::toGeometry>(env, points) } }; + annotation.opacity = { Polygon::getOpacity(env, polygon) }; + annotation.color = { Polygon::getFillColor(env, polygon) }; + annotation.outlineColor = { Polygon::getOutlineColor(env, polygon) }; + + jni::DeleteLocalRef(env, points); + + return annotation; +} + +jni::Object Polygon::getPoints(jni::JNIEnv& env, jni::Object polygon) { + static auto field = Polygon::javaClass.GetField>(env, "points"); + return polygon.Get(env, field); +} + +float Polygon::getOpacity(jni::JNIEnv& env, jni::Object polygon) { + static auto field = Polygon::javaClass.GetField(env, "alpha"); + return polygon.Get(env, field); +} + +mbgl::Color Polygon::getFillColor(jni::JNIEnv& env, jni::Object polygon) { + static auto field = Polygon::javaClass.GetField(env, "fillColor"); + return *conversion::convert(env, polygon.Get(env, field)); +} + +mbgl::Color Polygon::getOutlineColor(jni::JNIEnv& env, jni::Object polygon) { + static auto field = Polygon::javaClass.GetField(env, "strokeColor"); + return *conversion::convert(env, polygon.Get(env, field)); +} + +void Polygon::registerNative(jni::JNIEnv& env) { + Polygon::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/polygon.hpp b/platform/android/src/annotation/polygon.hpp new file mode 100644 index 0000000000..658aa5344b --- /dev/null +++ b/platform/android/src/annotation/polygon.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#include + +#include "multi_point.hpp" + +#include "../geometry/lat_lng.hpp" +#include "../java/util.hpp" + +namespace mbgl { +namespace android { + +class Polygon : private MultiPoint { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/annotations/Polygon"; }; + + static jni::Class javaClass; + + static mbgl::FillAnnotation toAnnotation(jni::JNIEnv&, jni::Object); + + static void registerNative(jni::JNIEnv&); + +private: + + static jni::Object getPoints(jni::JNIEnv&, jni::Object); + + static float getOpacity(jni::JNIEnv&, jni::Object); + + static mbgl::Color getFillColor(jni::JNIEnv&, jni::Object); + + static mbgl::Color getOutlineColor(jni::JNIEnv&, jni::Object); +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/polyline.cpp b/platform/android/src/annotation/polyline.cpp new file mode 100644 index 0000000000..3723dc1871 --- /dev/null +++ b/platform/android/src/annotation/polyline.cpp @@ -0,0 +1,49 @@ +#include "polyline.hpp" + +#include "../conversion/color.hpp" + +namespace mbgl { +namespace android { + +jni::Class Polyline::javaClass; + +mbgl::LineAnnotation Polyline::toAnnotation(jni::JNIEnv& env, jni::Object polyline) { + auto points = Polyline::getPoints(env, polyline); + + mbgl::LineAnnotation annotation { MultiPoint::toGeometry>(env, points) }; + annotation.opacity = { Polyline::getOpacity(env, polyline) }; + annotation.color = { Polyline::getColor(env, polyline) }; + annotation.width = { Polyline::getWidth(env, polyline) }; + + jni::DeleteLocalRef(env, points); + + return annotation; +} + +jni::Object Polyline::getPoints(jni::JNIEnv& env, jni::Object polyline) { + static auto field = Polyline::javaClass.GetField>(env, "points"); + return polyline.Get(env, field); +} + +float Polyline::getOpacity(jni::JNIEnv& env, jni::Object polyline) { + static auto field = Polyline::javaClass.GetField(env, "alpha"); + return polyline.Get(env, field); +} + +mbgl::Color Polyline::getColor(jni::JNIEnv& env, jni::Object polyline) { + static auto field = Polyline::javaClass.GetField(env, "color"); + return *conversion::convert(env, polyline.Get(env, field)); +} + +float Polyline::getWidth(jni::JNIEnv& env, jni::Object polyline) { + static auto field = Polyline::javaClass.GetField(env, "width"); + return polyline.Get(env, field); +} + +void Polyline::registerNative(jni::JNIEnv& env) { + Polyline::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/annotation/polyline.hpp b/platform/android/src/annotation/polyline.hpp new file mode 100644 index 0000000000..bcc616a5f7 --- /dev/null +++ b/platform/android/src/annotation/polyline.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#include + +#include "multi_point.hpp" + +#include "../geometry/lat_lng.hpp" +#include "../java/util.hpp" + +namespace mbgl { +namespace android { + +class Polyline : private MultiPoint { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/annotations/Polyline"; }; + + static jni::Class javaClass; + + static mbgl::LineAnnotation toAnnotation(jni::JNIEnv&, jni::Object); + + static void registerNative(jni::JNIEnv&); + +private: + + static jni::Object getPoints(jni::JNIEnv&, jni::Object); + + static float getOpacity(jni::JNIEnv&, jni::Object); + + static mbgl::Color getColor(jni::JNIEnv&, jni::Object); + + static float getWidth(jni::JNIEnv&, jni::Object); +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/conversion/collection.hpp b/platform/android/src/conversion/collection.hpp index 0f67c685f4..da5eed64d2 100644 --- a/platform/android/src/conversion/collection.hpp +++ b/platform/android/src/conversion/collection.hpp @@ -38,6 +38,19 @@ inline std::vector toVector(JNIEnv& env, jni::jarray& return vector; } +inline std::vector toVector(JNIEnv& env, jni::Array array) { + std::vector vector; + std::size_t len = array.Length(env); + + for (std::size_t i = 0; i < len; i++) { + jni::String jstr = array.Get(env, i); + vector.push_back(*convert(env, jstr)); + jni::DeleteLocalRef(env, jstr); + } + + return vector; +} + } } } diff --git a/platform/android/src/conversion/color.hpp b/platform/android/src/conversion/color.hpp new file mode 100644 index 0000000000..40aa68d4a9 --- /dev/null +++ b/platform/android/src/conversion/color.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "conversion.hpp" + +#include + +namespace mbgl { +namespace android { +namespace conversion { + +template <> +struct Converter { + Result operator()(jni::JNIEnv&, const int& color) const { + float r = (color >> 16) & 0xFF; + float g = (color >> 8) & 0xFF; + float b = (color) & 0xFF; + float a = (color >> 24) & 0xFF; + return { mbgl::Color( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f ) }; + } +}; + +} // namespace conversion +} // namespace style +} // namespace mbgl diff --git a/platform/android/src/default_file_source.cpp b/platform/android/src/default_file_source.cpp deleted file mode 100644 index 4d6924b496..0000000000 --- a/platform/android/src/default_file_source.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "default_file_source.hpp" -#include - -#include - -namespace mbgl { -namespace android { - -DefaultFileSource& defaultFileSource(const std::string& cachePath_, const std::string& assetRoot_) { - static auto cachePath = cachePath_; - assert(cachePath == cachePath_); - static auto assetRoot = assetRoot_; - assert(assetRoot == assetRoot_); - - static DefaultFileSource defaultFileSource{ cachePath, assetRoot }; - return defaultFileSource; -} - -} // namespace android -} // namespace mbgl diff --git a/platform/android/src/default_file_source.hpp b/platform/android/src/default_file_source.hpp deleted file mode 100644 index e0cc28583c..0000000000 --- a/platform/android/src/default_file_source.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -namespace mbgl { -namespace android { - -DefaultFileSource& defaultFileSource(const std::string& cachePath = ":memory:", - const std::string& assetRoot = "."); - -} // namespace android -} // namespace mbgl diff --git a/platform/android/src/file_source.cpp b/platform/android/src/file_source.cpp new file mode 100644 index 0000000000..30e1ff50fe --- /dev/null +++ b/platform/android/src/file_source.cpp @@ -0,0 +1,106 @@ +#include "file_source.hpp" + +#include + +#include + +#include "jni/generic_global_ref_deleter.hpp" + + +namespace mbgl { +namespace android { + +// FileSource // + +FileSource::FileSource(jni::JNIEnv& _env, jni::String accessToken, jni::String _cachePath, jni::String _apkPath) { + // Create a core default file source + fileSource = std::make_unique( + jni::Make(_env, _cachePath) + "/mbgl-offline.db", + jni::Make(_env, _apkPath)); + + // Set access token + fileSource->setAccessToken(jni::Make(_env, accessToken)); +} + +FileSource::~FileSource() { +} + +jni::String FileSource::getAccessToken(jni::JNIEnv& env) { + return jni::Make(env, fileSource->getAccessToken()); +} + +void FileSource::setAccessToken(jni::JNIEnv& env, jni::String token) { + fileSource->setAccessToken(jni::Make(env, token)); +} + +void FileSource::setAPIBaseUrl(jni::JNIEnv& env, jni::String url) { + fileSource->setAPIBaseURL(jni::Make(env, url)); +} + +void FileSource::setResourceTransform(jni::JNIEnv& env, jni::Object transformCallback) { + if (transformCallback) { + // Launch transformCallback + fileSource->setResourceTransform([ + // Capture the ResourceTransformCallback object as a managed global into + // the lambda. It is released automatically when we're setting a new ResourceTransform in + // a subsequent call. + // Note: we're converting it to shared_ptr because this lambda is converted to a std::function, + // which requires copyability of its captured variables. + callback = std::shared_ptr(transformCallback.NewGlobalRef(env).release()->Get(), GenericGlobalRefDeleter()), + env + ](mbgl::Resource::Kind kind, std::string&& url_) { + return FileSource::ResourceTransformCallback::onURL(const_cast(env), jni::Object(*callback), int(kind), url_); + }); + } else { + // Reset the callback + fileSource->setResourceTransform(nullptr); + } +} + +jni::Class FileSource::javaClass; + +FileSource* FileSource::getNativePeer(jni::JNIEnv& env, jni::Object jFileSource) { + static auto field = FileSource::javaClass.GetField(env, "nativePtr"); + return reinterpret_cast(jFileSource.Get(env, field)); +} + +mbgl::DefaultFileSource& FileSource::getDefaultFileSource(jni::JNIEnv& env, jni::Object jFileSource) { + FileSource* fileSource = FileSource::getNativePeer(env, jFileSource); + assert(fileSource != nullptr); + return *fileSource->fileSource; +} + +void FileSource::registerNative(jni::JNIEnv& env) { + //Register classes + FileSource::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); + FileSource::ResourceTransformCallback::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); + + #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, FileSource::javaClass, "nativePtr", + std::make_unique, + "initialize", + "finalize", + METHOD(&FileSource::getAccessToken, "getAccessToken"), + METHOD(&FileSource::setAccessToken, "setAccessToken"), + METHOD(&FileSource::setAPIBaseUrl, "setApiBaseUrl"), + METHOD(&FileSource::setResourceTransform, "setResourceTransform") + ); +} + + +// FileSource::ResourceTransformCallback // + +jni::Class FileSource::ResourceTransformCallback::javaClass; + +std::string FileSource::ResourceTransformCallback::onURL(jni::JNIEnv& env, jni::Object callback, int kind, std::string url_) { + static auto method = FileSource::ResourceTransformCallback::javaClass.GetMethod(env, "onURL"); + auto url = jni::Make(env, url_); + url = callback.Call(env, method, kind, url); + return jni::Make(env, url); +} + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/file_source.hpp b/platform/android/src/file_source.hpp new file mode 100644 index 0000000000..073e393e05 --- /dev/null +++ b/platform/android/src/file_source.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include + +#include + +namespace mbgl { +namespace android { + +/** + * Peer class for the Android FileSource holder. Ensures that a single DefaultFileSource is used + */ +class FileSource { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource"; }; + + struct ResourceTransformCallback { + static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource$ResourceTransformCallback"; } + + static std::string onURL(jni::JNIEnv&, jni::Object, int, std::string); + + static jni::Class javaClass; + }; + + FileSource(jni::JNIEnv&, jni::String, jni::String, jni::String); + + ~FileSource(); + + jni::String getAccessToken(jni::JNIEnv&); + + void setAccessToken(jni::JNIEnv&, jni::String); + + void setAPIBaseUrl(jni::JNIEnv&, jni::String); + + void setResourceTransform(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static FileSource* getNativePeer(jni::JNIEnv&, jni::Object); + + static mbgl::DefaultFileSource& getDefaultFileSource(jni::JNIEnv&, jni::Object); + + static void registerNative(jni::JNIEnv&); + +private: + + std::unique_ptr fileSource; +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/conversion/feature.hpp b/platform/android/src/geometry/conversion/feature.hpp index 18f2741d66..921138e859 100644 --- a/platform/android/src/geometry/conversion/feature.hpp +++ b/platform/android/src/geometry/conversion/feature.hpp @@ -3,6 +3,7 @@ #include "../../conversion/constant.hpp" #include "../../conversion/conversion.hpp" #include "geometry.hpp" +#include "../../gson/json_object.hpp" #include #include @@ -10,6 +11,7 @@ #include #include "../../jni/local_object.hpp" +#include "../feature.hpp" #include #include @@ -168,39 +170,45 @@ struct Converter> { template <> -struct Converter { - Result operator()(jni::JNIEnv& env, const mbgl::Feature& value) const { - static jni::jclass* javaClass = jni::NewGlobalRef(env, &jni::FindClass(env, "com/mapbox/services/commons/geojson/Feature")).release(); - static jni::jmethodID* fromGeometry = &jni::GetStaticMethodID(env, *javaClass, "fromGeometry", "(Lcom/mapbox/services/commons/geojson/Geometry;Lcom/google/gson/JsonObject;Ljava/lang/String;)Lcom/mapbox/services/commons/geojson/Feature;"); +struct Converter, mbgl::Feature> { + Result> operator()(jni::JNIEnv& env, const mbgl::Feature& value) const { // Convert Id FeatureIdVisitor idEvaluator; std::string id = (value.id) ? mapbox::geometry::identifier::visit(value.id.value(), idEvaluator) : ""; - jni::LocalObject jid = jni::NewLocalObject(env, *convert(env, id)); + auto jid = jni::Make(env, id); // Convert properties - jni::LocalObject properties = jni::NewLocalObject(env, *convert(env, value.properties)); + auto properties = jni::Object(*convert(env, value.properties)); // Convert geometry - jni::LocalObject geometry = jni::NewLocalObject(env, *convert(env, value.geometry)); + auto geometry = jni::Object(*convert(env, value.geometry)); // Create feature - return {reinterpret_cast(jni::CallStaticMethod(env, *javaClass, *fromGeometry, geometry.get(), properties.get(), jid.get()))}; + auto feature = Feature::fromGeometry(env, geometry, properties, jid); + + //Cleanup + jni::DeleteLocalRef(env, jid); + jni::DeleteLocalRef(env, geometry); + jni::DeleteLocalRef(env, properties); + + return feature; } }; template <> -struct Converter*, std::vector> { - Result*> operator()(jni::JNIEnv& env, const std::vector& value) const { - static jni::jclass* featureClass = jni::NewGlobalRef(env, &jni::FindClass(env, "com/mapbox/services/commons/geojson/Feature")).release(); - jni::jarray& jarray = jni::NewObjectArray(env, value.size(), *featureClass); +struct Converter>, std::vector> { + Result>> operator()(jni::JNIEnv& env, const std::vector& value) const { + + auto features = jni::Array>::New(env, value.size(), Feature::javaClass); for(size_t i = 0; i < value.size(); i = i + 1) { - jni::LocalObject converted = jni::NewLocalObject(env, *convert(env, value.at(i))); - jni::SetObjectArrayElement(env, jarray, i, converted.get()); + auto converted = *convert, mbgl::Feature>(env, value.at(i)); + features.Set(env, i, converted); + jni::DeleteLocalRef(env, converted); } - return {&jarray}; + return {features}; } }; diff --git a/platform/android/src/geometry/feature.cpp b/platform/android/src/geometry/feature.cpp new file mode 100644 index 0000000000..5355d50ab7 --- /dev/null +++ b/platform/android/src/geometry/feature.cpp @@ -0,0 +1,20 @@ +#include "feature.hpp" + +namespace mbgl { +namespace android { + +jni::Object Feature::fromGeometry(jni::JNIEnv& env, jni::Object geometry, jni::Object properties, jni::String id) { + static auto method = Feature::javaClass.GetStaticMethod (jni::Object, jni::Object, jni::String)>(env, "fromGeometry"); + return Feature::javaClass.Call(env, method, geometry, properties, id); +} + +void Feature::registerNative(jni::JNIEnv& env) { + // Lookup the class + Feature::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class Feature::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/feature.hpp b/platform/android/src/geometry/feature.hpp new file mode 100644 index 0000000000..7f2733430c --- /dev/null +++ b/platform/android/src/geometry/feature.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +#include + +#include "geometry.hpp" +#include "../gson/json_object.hpp" + +namespace mbgl { +namespace android { + +class Feature : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "com/mapbox/services/commons/geojson/Feature"; }; + + static jni::Object fromGeometry(jni::JNIEnv&, jni::Object, jni::Object, jni::String); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/geometry.hpp b/platform/android/src/geometry/geometry.hpp new file mode 100644 index 0000000000..5c8ae39181 --- /dev/null +++ b/platform/android/src/geometry/geometry.hpp @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace mbgl { +namespace android { + +class Geometry : private mbgl::util::noncopyable { +public: + static constexpr auto Name() { return "com/mapbox/services/commons/geojson/Geometry"; }; + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/lat_lng.cpp b/platform/android/src/geometry/lat_lng.cpp new file mode 100644 index 0000000000..9cf3630107 --- /dev/null +++ b/platform/android/src/geometry/lat_lng.cpp @@ -0,0 +1,31 @@ +#include "lat_lng.hpp" + +namespace mbgl { +namespace android { + +jni::Object LatLng::New(jni::JNIEnv& env, double latitude, double longitude) { + static auto constructor = LatLng::javaClass.GetConstructor(env); + return LatLng::javaClass.New(env, constructor, latitude, longitude); +} + +mbgl::Point LatLng::getGeometry(jni::JNIEnv& env, jni::Object latLng) { + static auto latitudeField = LatLng::javaClass.GetField(env, "latitude"); + static auto longitudeField = LatLng::javaClass.GetField(env, "longitude"); + return mbgl::Point(latLng.Get(env, longitudeField), latLng.Get(env, latitudeField)); +} + +mbgl::LatLng LatLng::getLatLng(jni::JNIEnv& env, jni::Object latLng) { + auto point = LatLng::getGeometry(env, latLng); + return mbgl::LatLng(point.y, point.x); +} + +void LatLng::registerNative(jni::JNIEnv& env) { + // Lookup the class + LatLng::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class LatLng::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/lat_lng.hpp b/platform/android/src/geometry/lat_lng.hpp new file mode 100644 index 0000000000..1ac32ae32e --- /dev/null +++ b/platform/android/src/geometry/lat_lng.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include + +#include + +namespace mbgl { +namespace android { + +class LatLng : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLng"; }; + + static jni::Object New(jni::JNIEnv&, double, double); + + static mbgl::Point getGeometry(jni::JNIEnv&, jni::Object); + + static mbgl::LatLng getLatLng(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/lat_lng_bounds.cpp b/platform/android/src/geometry/lat_lng_bounds.cpp new file mode 100644 index 0000000000..9efacde120 --- /dev/null +++ b/platform/android/src/geometry/lat_lng_bounds.cpp @@ -0,0 +1,31 @@ +#include "lat_lng_bounds.hpp" + +namespace mbgl { +namespace android { + +jni::Object LatLngBounds::New(jni::JNIEnv& env, mbgl::LatLngBounds bounds) { + static auto constructor = LatLngBounds::javaClass.GetConstructor(env); + return LatLngBounds::javaClass.New(env, constructor, bounds.north(), bounds.east(), bounds.south(), bounds.west()); +} + +mbgl::LatLngBounds LatLngBounds::getLatLngBounds(jni::JNIEnv& env, jni::Object bounds) { + static auto swLat = LatLngBounds::javaClass.GetField(env, "mLatSouth"); + static auto swLon = LatLngBounds::javaClass.GetField(env, "mLonWest"); + static auto neLat = LatLngBounds::javaClass.GetField(env, "mLatNorth"); + static auto neLon = LatLngBounds::javaClass.GetField(env, "mLonEast"); + return mbgl::LatLngBounds::hull( + { bounds.Get(env, swLat), bounds.Get(env, swLon) }, + { bounds.Get(env, neLat), bounds.Get(env, neLon) } + ); +} + +void LatLngBounds::registerNative(jni::JNIEnv& env) { + // Lookup the class + LatLngBounds::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class LatLngBounds::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/lat_lng_bounds.hpp b/platform/android/src/geometry/lat_lng_bounds.hpp new file mode 100644 index 0000000000..1c853e4b67 --- /dev/null +++ b/platform/android/src/geometry/lat_lng_bounds.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include + +#include + +namespace mbgl { +namespace android { + +class LatLngBounds : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLngBounds"; }; + + static jni::Object New(jni::JNIEnv&, mbgl::LatLngBounds); + + static mbgl::LatLngBounds getLatLngBounds(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/projected_meters.cpp b/platform/android/src/geometry/projected_meters.cpp new file mode 100644 index 0000000000..f3d9d1b0ef --- /dev/null +++ b/platform/android/src/geometry/projected_meters.cpp @@ -0,0 +1,20 @@ +#include "projected_meters.hpp" + +namespace mbgl { +namespace android { + +jni::Object ProjectedMeters::New(jni::JNIEnv& env, double northing, double easting) { + static auto constructor = ProjectedMeters::javaClass.GetConstructor(env); + return ProjectedMeters::javaClass.New(env, constructor, northing, easting); +} + +void ProjectedMeters::registerNative(jni::JNIEnv& env) { + // Lookup the class + ProjectedMeters::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class ProjectedMeters::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/geometry/projected_meters.hpp b/platform/android/src/geometry/projected_meters.hpp new file mode 100644 index 0000000000..9b70967b5d --- /dev/null +++ b/platform/android/src/geometry/projected_meters.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +#include + +namespace mbgl { +namespace android { + +class ProjectedMeters : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/ProjectedMeters"; }; + + static jni::Object New(jni::JNIEnv&, double, double); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/graphics/pointf.cpp b/platform/android/src/graphics/pointf.cpp new file mode 100644 index 0000000000..6e91b81416 --- /dev/null +++ b/platform/android/src/graphics/pointf.cpp @@ -0,0 +1,20 @@ +#include "pointf.hpp" + +namespace mbgl { +namespace android { + +jni::Object PointF::New(jni::JNIEnv& env, float x, float y) { + static auto constructor = PointF::javaClass.GetConstructor(env); + return PointF::javaClass.New(env, constructor, x, y); +} + +void PointF::registerNative(jni::JNIEnv& env) { + // Lookup the class + PointF::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class PointF::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/graphics/pointf.hpp b/platform/android/src/graphics/pointf.hpp new file mode 100644 index 0000000000..ea25ad2b40 --- /dev/null +++ b/platform/android/src/graphics/pointf.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +namespace mbgl { +namespace android { + +class PointF : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "android/graphics/PointF"; }; + + static jni::Object New(jni::JNIEnv&, float, float); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/graphics/rectf.cpp b/platform/android/src/graphics/rectf.cpp new file mode 100644 index 0000000000..1b375dad18 --- /dev/null +++ b/platform/android/src/graphics/rectf.cpp @@ -0,0 +1,35 @@ +#include "rectf.hpp" + +namespace mbgl { +namespace android { + +float RectF::getLeft(jni::JNIEnv& env, jni::Object rectf) { + static auto field = RectF::javaClass.GetField(env, "left"); + return rectf.Get(env, field); +} + +float RectF::getTop(jni::JNIEnv& env, jni::Object rectf) { + static auto field = RectF::javaClass.GetField(env, "top"); + return rectf.Get(env, field); +} + +float RectF::getRight(jni::JNIEnv& env, jni::Object rectf) { + static auto field = RectF::javaClass.GetField(env, "right"); + return rectf.Get(env, field); +} + +float RectF::getBottom(jni::JNIEnv& env, jni::Object rectf) { + static auto field = RectF::javaClass.GetField(env, "bottom"); + return rectf.Get(env, field); +} + +void RectF::registerNative(jni::JNIEnv& env) { + // Lookup the class + RectF::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +jni::Class RectF::javaClass; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/graphics/rectf.hpp b/platform/android/src/graphics/rectf.hpp new file mode 100644 index 0000000000..0f3a7756d5 --- /dev/null +++ b/platform/android/src/graphics/rectf.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include + +#include + +namespace mbgl { +namespace android { + +class RectF : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "android/graphics/RectF"; }; + + static float getLeft(jni::JNIEnv&, jni::Object); + + static float getTop(jni::JNIEnv&, jni::Object); + + static float getRight(jni::JNIEnv&, jni::Object); + + static float getBottom(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/gson/json_object.hpp b/platform/android/src/gson/json_object.hpp new file mode 100644 index 0000000000..a7de0b1978 --- /dev/null +++ b/platform/android/src/gson/json_object.hpp @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace mbgl { +namespace android { + +class JsonObject : private mbgl::util::noncopyable { +public: + static constexpr auto Name() { return "com/google/gson/JsonObject"; }; + +}; + + +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/java/util.cpp b/platform/android/src/java/util.cpp new file mode 100644 index 0000000000..c630e403d9 --- /dev/null +++ b/platform/android/src/java/util.cpp @@ -0,0 +1,18 @@ +#include "util.hpp" + +namespace mbgl { +namespace android { +namespace java { +namespace util { + +jni::Class List::javaClass; + +void registerNative(jni::JNIEnv& env) { + List::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + + +} // namespace util +} // namespace java +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/java/util.hpp b/platform/android/src/java/util.hpp new file mode 100644 index 0000000000..1a552c7124 --- /dev/null +++ b/platform/android/src/java/util.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include + +#include + +namespace mbgl { +namespace android { +namespace java { +namespace util { + +class List : private mbgl::util::noncopyable { +public: + + static constexpr auto Name() { return "java/util/List"; }; + + template + static jni::Array> toArray(jni::JNIEnv& env, jni::Object list) { + static auto toArray = List::javaClass.GetMethod> ()>(env, "toArray"); + return (jni::Array>) list.Call(env, toArray); + }; + + static jni::Class javaClass; + +}; + +void registerNative(jni::JNIEnv&); + + +} // namespace util +} // namespace java +} // namespace android +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/jni.cpp b/platform/android/src/jni.cpp index 59602c3299..bd12cff3fa 100755 --- a/platform/android/src/jni.cpp +++ b/platform/android/src/jni.cpp @@ -1,21 +1,29 @@ -#include -#include -#include -#include -#include -#include +#include "jni.hpp" -#include -#include +#include -#include "jni.hpp" -#include "java_types.hpp" -#include "native_map_view.hpp" +#include "annotation/marker.hpp" +#include "annotation/polygon.hpp" +#include "annotation/polyline.hpp" #include "bitmap.hpp" #include "bitmap_factory.hpp" #include "connectivity_listener.hpp" -#include "default_file_source.hpp" -#include "attach_env.hpp" +#include "conversion/conversion.hpp" +#include "conversion/collection.hpp" +#include "file_source.hpp" +#include "geometry/feature.hpp" +#include "geometry/lat_lng.hpp" +#include "geometry/lat_lng_bounds.hpp" +#include "geometry/projected_meters.hpp" +#include "graphics/pointf.hpp" +#include "graphics/rectf.hpp" +#include "java_types.hpp" +#include "native_map_view.hpp" +#include "offline/offline_manager.hpp" +#include "offline/offline_region.hpp" +#include "offline/offline_region_definition.hpp" +#include "offline/offline_region_error.hpp" +#include "offline/offline_region_status.hpp" #include "style/functions/categorical_stops.hpp" #include "style/functions/exponential_stops.hpp" #include "style/functions/identity_stops.hpp" @@ -24,30 +32,6 @@ #include "style/layers/layers.hpp" #include "style/sources/sources.hpp" -#include "conversion/conversion.hpp" -#include "conversion/collection.hpp" -#include "geometry/conversion/feature.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#pragma clang diagnostic ignored "-Wunused-parameter" - namespace mbgl { namespace android { @@ -55,129 +39,7 @@ void RegisterNativeHTTPRequest(JNIEnv&); JavaVM* theJVM; -std::string cachePath; -std::string dataPath; -std::string apkPath; -std::string androidRelease; - -jni::jmethodID* onInvalidateId = nullptr; -jni::jmethodID* onMapChangedId = nullptr; -jni::jmethodID* onFpsChangedId = nullptr; -jni::jmethodID* onSnapshotReadyId = nullptr; - -jni::jclass* latLngClass = nullptr; -jni::jmethodID* latLngConstructorId = nullptr; -jni::jfieldID* latLngLatitudeId = nullptr; -jni::jfieldID* latLngLongitudeId = nullptr; - -jni::jclass* latLngBoundsClass = nullptr; -jni::jmethodID* latLngBoundsConstructorId = nullptr; -jni::jfieldID* latLngBoundsLatNorthId = nullptr; -jni::jfieldID* latLngBoundsLatSouthId = nullptr; -jni::jfieldID* latLngBoundsLonEastId = nullptr; -jni::jfieldID* latLngBoundsLonWestId = nullptr; - -jni::jclass* iconClass = nullptr; -jni::jfieldID* iconIdId = nullptr; - -jni::jclass* markerClass = nullptr; -jni::jfieldID* markerPositionId = nullptr; -jni::jfieldID* markerIconId = nullptr; -jni::jfieldID* markerIdId = nullptr; - -jni::jclass* polylineClass = nullptr; -jni::jfieldID* polylineAlphaId = nullptr; -jni::jfieldID* polylineColorId = nullptr; -jni::jfieldID* polylineWidthId = nullptr; -jni::jfieldID* polylinePointsId = nullptr; - -jni::jclass* polygonClass = nullptr; -jni::jfieldID* polygonAlphaId = nullptr; -jni::jfieldID* polygonFillColorId = nullptr; -jni::jfieldID* polygonStrokeColorId = nullptr; -jni::jfieldID* polygonPointsId = nullptr; - -jni::jmethodID* listToArrayId = nullptr; - -jni::jclass* arrayListClass = nullptr; -jni::jmethodID* arrayListConstructorId = nullptr; -jni::jmethodID* arrayListAddId = nullptr; - -jni::jclass* projectedMetersClass = nullptr; -jni::jmethodID* projectedMetersConstructorId = nullptr; -jni::jfieldID* projectedMetersNorthingId = nullptr; -jni::jfieldID* projectedMetersEastingId = nullptr; - -jni::jclass* pointFClass = nullptr; -jni::jmethodID* pointFConstructorId = nullptr; -jni::jfieldID* pointFXId = nullptr; -jni::jfieldID* pointFYId = nullptr; - -jni::jclass* rectFClass = nullptr; -jni::jmethodID* rectFConstructorId = nullptr; -jni::jfieldID* rectFLeftId = nullptr; -jni::jfieldID* rectFTopId = nullptr; -jni::jfieldID* rectFRightId = nullptr; -jni::jfieldID* rectFBottomId = nullptr; - -// Offline declarations start - -jni::jfieldID* offlineManagerClassPtrId = nullptr; - -jni::jmethodID* listOnListMethodId = nullptr; -jni::jmethodID* listOnErrorMethodId = nullptr; - -jni::jclass* offlineRegionClass = nullptr; -jni::jmethodID* offlineRegionConstructorId = nullptr; -jni::jfieldID* offlineRegionOfflineManagerId = nullptr; -jni::jfieldID* offlineRegionIdId = nullptr; -jni::jfieldID* offlineRegionDefinitionId = nullptr; -jni::jfieldID* offlineRegionMetadataId = nullptr; -jni::jfieldID* offlineRegionPtrId = nullptr; - -jni::jclass* offlineRegionDefinitionClass = nullptr; -jni::jmethodID* offlineRegionDefinitionConstructorId = nullptr; -jni::jfieldID* offlineRegionDefinitionStyleURLId = nullptr; -jni::jfieldID* offlineRegionDefinitionBoundsId = nullptr; -jni::jfieldID* offlineRegionDefinitionMinZoomId = nullptr; -jni::jfieldID* offlineRegionDefinitionMaxZoomId = nullptr; -jni::jfieldID* offlineRegionDefinitionPixelRatioId = nullptr; - -jni::jmethodID* createOnCreateMethodId = nullptr; -jni::jmethodID* createOnErrorMethodId = nullptr; - -jni::jmethodID* transformOnURLMethodId = nullptr; - -jni::jmethodID* updateMetadataOnUpdateMethodId = nullptr; -jni::jmethodID* updateMetadataOnErrorMethodId = nullptr; - -jni::jmethodID* offlineRegionObserveronStatusChangedId = nullptr; -jni::jmethodID* offlineRegionObserveronErrorId = nullptr; -jni::jmethodID* offlineRegionObserveronLimitId = nullptr; - -jni::jclass* offlineRegionStatusClass = nullptr; -jni::jmethodID* offlineRegionStatusConstructorId = nullptr; -jni::jfieldID* offlineRegionStatusDownloadStateId = nullptr; -jni::jfieldID* offlineRegionStatusCompletedResourceCountId = nullptr; -jni::jfieldID* offlineRegionStatusCompletedResourceSizeId = nullptr; -jni::jfieldID* offlineRegionStatusCompletedTileCountId = nullptr; -jni::jfieldID* offlineRegionStatusCompletedTileSizeId = nullptr; -jni::jfieldID* offlineRegionStatusRequiredResourceCountId = nullptr; -jni::jfieldID* offlineRegionStatusRequiredResourceCountIsPreciseId = nullptr; - -jni::jclass* offlineRegionErrorClass = nullptr; -jni::jmethodID* offlineRegionErrorConstructorId = nullptr; -jni::jfieldID* offlineRegionErrorReasonId = nullptr; -jni::jfieldID* offlineRegionErrorMessageId = nullptr; - -jni::jmethodID* offlineRegionStatusOnStatusId = nullptr; -jni::jmethodID* offlineRegionStatusOnErrorId = nullptr; - -jni::jmethodID* offlineRegionDeleteOnDeleteId = nullptr; -jni::jmethodID* offlineRegionDeleteOnErrorId = nullptr; - -// Offline declarations end - +//TODO: remove bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { assert(vm != nullptr); assert(env != nullptr); @@ -205,6 +67,7 @@ bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { return detach; } +//TODO: remove void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach) { if (detach) { assert(vm != nullptr); @@ -219,1900 +82,61 @@ void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach) { *env = nullptr; } -std::string std_string_from_jstring(JNIEnv *env, jni::jstring* jstr) { - return jni::Make(*env, jni::String(jstr)); -} - -jni::jstring* std_string_to_jstring(JNIEnv *env, std::string str) { - return jni::Make(*env, str).Get(); -} - -std::vector std_vector_string_from_jobject(JNIEnv *env, jni::jobject* jlist) { - std::vector vector; - - jni::NullCheck(*env, jlist); - jni::jarray* jarray = - reinterpret_cast*>(jni::CallMethod(*env, jlist, *listToArrayId)); - - jni::NullCheck(*env, jarray); - std::size_t len = jni::GetArrayLength(*env, *jarray); - - for (std::size_t i = 0; i < len; i++) { - jni::jstring* jstr = reinterpret_cast(jni::GetObjectArrayElement(*env, *jarray, i)); - vector.push_back(std_string_from_jstring(env, jstr)); - } - - return vector; -} - -jni::jobject* std_vector_string_to_jobject(JNIEnv *env, std::vector vector) { - jni::jobject* jlist = &jni::NewObject(*env, *arrayListClass, *arrayListConstructorId); - - for (const auto& str : vector) { - jni::CallMethod(*env, jlist, *arrayListAddId, std_string_to_jstring(env, str)); - } - - return jlist; -} - -jni::jarray* std_vector_uint_to_jobject(JNIEnv *env, const std::vector& vector) { - jni::jarray& jarray = jni::NewArray(*env, vector.size()); - - std::vector v; - v.reserve(vector.size()); - std::move(vector.begin(), vector.end(), std::back_inserter(v)); - - jni::SetArrayRegion(*env, jarray, 0, v); - - return &jarray; -} - -static std::vector metadata_from_java(JNIEnv* env, jni::jarray& j) { - std::size_t length = jni::GetArrayLength(*env, j); - std::vector c; - c.resize(length); - jni::GetArrayRegion(*env, j, 0, length, reinterpret_cast(c.data())); - return c; -} - -static jni::jarray* metadata_from_native(JNIEnv* env, const std::vector& c) { - std::size_t length = static_cast(c.size()); - jni::jarray& j = jni::NewArray(*env, length); - jni::SetArrayRegion(*env, j, 0, c.size(), reinterpret_cast(c.data())); - return &j; -} - -static mbgl::LatLngBounds latlngbounds_from_java(JNIEnv *env, jni::jobject* latLngBounds) { - jdouble swLat = jni::GetField(*env, latLngBounds, *latLngBoundsLatSouthId); - jdouble swLon = jni::GetField(*env, latLngBounds, *latLngBoundsLonWestId); - jdouble neLat = jni::GetField(*env, latLngBounds, *latLngBoundsLatNorthId); - jdouble neLon = jni::GetField(*env, latLngBounds, *latLngBoundsLonEastId); - return mbgl::LatLngBounds::hull({ swLat, swLon }, { neLat, neLon }); -} - -static jni::jobject* latlngbounds_from_native(JNIEnv *env, mbgl::LatLngBounds bounds) { - double northLatitude = bounds.north(); - double eastLongitude = bounds.east(); - double southLatitude = bounds.south(); - double westLongitude = bounds.west(); - - jni::jobject* jbounds = &jni::NewObject(*env, *latLngBoundsClass, *latLngBoundsConstructorId, - northLatitude, eastLongitude, southLatitude, westLongitude); - - return jbounds; -} - -} -} - -namespace { - -using namespace mbgl::android; -using DebugOptions = mbgl::MapDebugOptions; - -jlong nativeCreate(JNIEnv *env, jni::jobject* obj, jni::jstring* cachePath_, jni::jstring* dataPath_, jni::jstring* apkPath_, jfloat pixelRatio, jint availableProcessors, jlong totalMemory) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeCreate"); - cachePath = std_string_from_jstring(env, cachePath_); - dataPath = std_string_from_jstring(env, dataPath_); - apkPath = std_string_from_jstring(env, apkPath_); - return reinterpret_cast(new NativeMapView(env, jni::Unwrap(obj), pixelRatio, availableProcessors, totalMemory)); -} - -void nativeDestroy(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeDestroy"); - assert(nativeMapViewPtr != 0); - delete reinterpret_cast(nativeMapViewPtr); -} - -void nativeInitializeDisplay(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeInitializeDisplay"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->initializeDisplay(); -} - -void nativeTerminateDisplay(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeTerminateDisplay"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->terminateDisplay(); -} - -void nativeInitializeContext(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeInitializeContext"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->initializeContext(); -} - -void nativeTerminateContext(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeTerminateContext"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->terminateContext(); -} - -void nativeCreateSurface(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jobject* surface) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeCreateSurface"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->createSurface(ANativeWindow_fromSurface(env, jni::Unwrap(surface))); -} - -void nativeDestroySurface(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeDestroySurface"); - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->destroySurface(); -} - -void nativeUpdate(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->invalidate(); -} - -void nativeRender(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->render(); -} - -void nativeViewResize(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jint width, jint height) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeViewResize"); - assert(nativeMapViewPtr != 0); - assert(width >= 0); - assert(height >= 0); - assert(width <= UINT16_MAX); - assert(height <= UINT16_MAX); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->resizeView(width, height); -} - -void nativeFramebufferResize(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jint fbWidth, jint fbHeight) { - mbgl::Log::Debug(mbgl::Event::JNI, "nativeFramebufferResize"); - assert(nativeMapViewPtr != 0); - assert(fbWidth >= 0); - assert(fbHeight >= 0); - assert(fbWidth <= UINT16_MAX); - assert(fbHeight <= UINT16_MAX); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->resizeFramebuffer(fbWidth, fbHeight); -} - -void nativeRemoveClass(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* clazz) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().removeClass(std_string_from_jstring(env, clazz)); -} - -jboolean nativeHasClass(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* clazz) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().hasClass(std_string_from_jstring(env, clazz)); -} - -void nativeAddClass(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* clazz) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().addClass(std_string_from_jstring(env, clazz)); -} - -void nativeSetClasses(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jobject* classes) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setClasses(std_vector_string_from_jobject(env, classes)); -} - -jni::jobject* nativeGetClasses(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return std_vector_string_to_jobject(env, nativeMapView->getMap().getClasses()); -} - -void nativeSetAPIBaseURL(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* url) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getFileSource().setAPIBaseURL(std_string_from_jstring(env, url)); -} - -void nativeSetStyleUrl(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* url) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setStyleURL(std_string_from_jstring(env, url)); -} - -jni::jstring* nativeGetStyleUrl(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr){ - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return std_string_to_jstring(env, nativeMapView->getMap().getStyleURL()); -} - -void nativeSetStyleJson(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* newStyleJson) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setStyleJSON(std_string_from_jstring(env, newStyleJson)); -} - -jni::jstring* nativeGetStyleJson(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return std_string_to_jstring(env, nativeMapView->getMap().getStyleJSON()); -} - -void nativeSetAccessToken(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* accessToken) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getFileSource().setAccessToken(std_string_from_jstring(env, accessToken)); -} - -jni::jstring* nativeGetAccessToken(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return std_string_to_jstring(env, nativeMapView->getFileSource().getAccessToken()); -} - -void nativeCancelTransitions(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().cancelTransitions(); -} - -void nativeSetGestureInProgress(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jboolean inProgress) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setGestureInProgress(inProgress); -} - -void nativeMoveBy(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble dx, jdouble dy, - jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::AnimationOptions animationOptions; - if (duration > 0) { - animationOptions.duration.emplace(mbgl::Milliseconds(duration)); - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0.3, 0.6, 1.0 }); - } - - nativeMapView->getMap().moveBy({dx, dy}, animationOptions); -} - -void nativeSetLatLng(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble latitude, jdouble longitude, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setLatLng(mbgl::LatLng(latitude, longitude), nativeMapView->getInsets(), mbgl::Duration(duration)); -} - -jni::jobject* nativeGetLatLng(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::LatLng latLng = nativeMapView->getMap().getLatLng(nativeMapView->getInsets()); - return &jni::NewObject(*env, *latLngClass, *latLngConstructorId, latLng.latitude, latLng.longitude); -} - -jdoubleArray nativeGetCameraValues(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::LatLng latLng = nativeMapView->getMap().getLatLng(nativeMapView->getInsets()); - jdoubleArray output = env->NewDoubleArray(5); - jsize start = 0; - jsize leng = 5; - jdouble buf[5]; - buf[0] = latLng.latitude; - buf[1] = latLng.longitude; - buf[2] = -nativeMapView->getMap().getBearing(); - buf[3] = nativeMapView->getMap().getPitch(); - buf[4] = nativeMapView->getMap().getZoom(); - env->SetDoubleArrayRegion(output, start, leng, buf); - - if (output == nullptr) { - env->ExceptionDescribe(); - return nullptr; - } - - return output; -} - -void nativeResetPosition(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().resetPosition(); -} - -jdouble nativeGetPitch(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getPitch(); -} - -void nativeSetPitch(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble pitch, jlong milliseconds) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::Duration duration((mbgl::Milliseconds(milliseconds))); - nativeMapView->getMap().setPitch(pitch, duration); -} - -void nativeScaleBy(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble ds, jdouble cx, - jdouble cy, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate center(cx, cy); - nativeMapView->getMap().scaleBy(ds, center, mbgl::Milliseconds(duration)); -} - -void nativeSetScale(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble scale, - jdouble cx, jdouble cy, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate center(cx, cy); - nativeMapView->getMap().setScale(scale, center, mbgl::Milliseconds(duration)); -} - -jdouble nativeGetScale(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getScale(); -} - -void nativeSetZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble zoom, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setZoom(zoom, mbgl::Milliseconds(duration)); -} - -jdouble nativeGetZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getZoom(); -} - -void nativeResetZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().resetZoom(); -} - -void nativeSetMinZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble zoom) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setMinZoom(zoom); -} - -jdouble nativeGetMinZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getMinZoom(); -} - -void nativeSetMaxZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble zoom) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().setMaxZoom(zoom); -} - -jdouble nativeGetMaxZoom(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getMaxZoom(); -} - -void nativeRotateBy(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble sx, - jdouble sy, jdouble ex, jdouble ey, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate first(sx, sy); - mbgl::ScreenCoordinate second(ex, ey); - nativeMapView->getMap().rotateBy(first, second, mbgl::Milliseconds(duration)); -} - -void nativeSetBearing(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble degrees, - jlong milliseconds) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::Duration duration((mbgl::Milliseconds(milliseconds))); - nativeMapView->getMap().setBearing(degrees, duration); -} - -void nativeSetFocalBearing(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble degrees, jdouble fx, - jdouble fy, jlong milliseconds) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate center(fx, fy); - nativeMapView->getMap().setBearing(degrees, center, mbgl::Milliseconds(milliseconds)); -} - -void nativeSetBearingXY(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble degrees, - jdouble cx, jdouble cy) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate center(cx, cy); - nativeMapView->getMap().setBearing(degrees, center); -} - -jdouble nativeGetBearing(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getBearing(); -} - -void nativeResetNorth(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().resetNorth(); -} - -void nativeUpdateMarker(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong markerId, jdouble lat, jdouble lon, jni::jstring* jid) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - if (markerId == -1) { - return; - } - std::string iconId = std_string_from_jstring(env, jid); - // Because Java only has int, not unsigned int, we need to bump the annotation id up to a long. - nativeMapView->getMap().updateAnnotation(markerId, mbgl::SymbolAnnotation { mbgl::Point(lon, lat), iconId }); -} - -jni::jarray* nativeAddMarkers(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jarray* jarray) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - NullCheck(*env, jarray); - std::size_t len = jni::GetArrayLength(*env, *jarray); - - mbgl::AnnotationIDs ids; - ids.reserve(len); - - for (std::size_t i = 0; i < len; i++) { - jni::jobject* marker = jni::GetObjectArrayElement(*env, *jarray, i); - jni::jobject* position = jni::GetField(*env, marker, *markerPositionId); - jni::jobject* icon = jni::GetField(*env, marker, *markerIconId); - jni::jstring* jid = reinterpret_cast(jni::GetField(*env, icon, *iconIdId)); - - jdouble latitude = jni::GetField(*env, position, *latLngLatitudeId); - jdouble longitude = jni::GetField(*env, position, *latLngLongitudeId); - - ids.push_back(nativeMapView->getMap().addAnnotation(mbgl::SymbolAnnotation { - mbgl::Point(longitude, latitude), - std_string_from_jstring(env, jid) - })); - - jni::DeleteLocalRef(*env, position); - jni::DeleteLocalRef(*env, jid); - jni::DeleteLocalRef(*env, icon); - jni::DeleteLocalRef(*env, marker); - } - - return std_vector_uint_to_jobject(env, ids); -} - -static mbgl::Color toColor(jint color) { - float r = (color >> 16) & 0xFF; - float g = (color >> 8) & 0xFF; - float b = (color) & 0xFF; - float a = (color >> 24) & 0xFF; - return { r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }; -} - -template -Geometry toGeometry(JNIEnv *env, jni::jobject* jlist) { - NullCheck(*env, jlist); - jni::jarray* jarray = - reinterpret_cast*>(jni::CallMethod(*env, jlist, *listToArrayId)); - NullCheck(*env, jarray); - - std::size_t size = jni::GetArrayLength(*env, *jarray); - - Geometry geometry; - geometry.reserve(size); - - for (std::size_t i = 0; i < size; i++) { - jni::jobject* latLng = reinterpret_cast(jni::GetObjectArrayElement(*env, *jarray, i)); - NullCheck(*env, latLng); - - geometry.push_back(mbgl::Point( - jni::GetField(*env, latLng, *latLngLongitudeId), - jni::GetField(*env, latLng, *latLngLatitudeId))); - - jni::DeleteLocalRef(*env, latLng); - } - - jni::DeleteLocalRef(*env, jarray); - jni::DeleteLocalRef(*env, jlist); - - return geometry; -} - -jni::jarray* nativeAddPolylines(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jarray* jarray) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - NullCheck(*env, jarray); - std::size_t len = jni::GetArrayLength(*env, *jarray); - - mbgl::AnnotationIDs ids; - ids.reserve(len); - - for (std::size_t i = 0; i < len; i++) { - jni::jobject* polyline = jni::GetObjectArrayElement(*env, *jarray, i); - jni::jobject* points = jni::GetField(*env, polyline, *polylinePointsId); - - mbgl::LineAnnotation annotation { toGeometry>(env, points) }; - annotation.opacity = { jni::GetField(*env, polyline, *polylineAlphaId) }; - annotation.color = { toColor(jni::GetField(*env, polyline, *polylineColorId)) }; - annotation.width = { jni::GetField(*env, polyline, *polylineWidthId) }; - ids.push_back(nativeMapView->getMap().addAnnotation(annotation)); - - jni::DeleteLocalRef(*env, polyline); - } - - return std_vector_uint_to_jobject(env, ids); -} - -jni::jarray* nativeAddPolygons(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jarray* jarray) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - NullCheck(*env, jarray); - std::size_t len = jni::GetArrayLength(*env, *jarray); - - mbgl::AnnotationIDs ids; - ids.reserve(len); - - for (std::size_t i = 0; i < len; i++) { - jni::jobject* polygon = jni::GetObjectArrayElement(*env, *jarray, i); - jni::jobject* points = jni::GetField(*env, polygon, *polygonPointsId); - - mbgl::FillAnnotation annotation { mbgl::Polygon { toGeometry>(env, points) } }; - annotation.opacity = { jni::GetField(*env, polygon, *polygonAlphaId) }; - annotation.outlineColor = { toColor(jni::GetField(*env, polygon, *polygonStrokeColorId)) }; - annotation.color = { toColor(jni::GetField(*env, polygon, *polygonFillColorId)) }; - ids.push_back(nativeMapView->getMap().addAnnotation(annotation)); - - jni::DeleteLocalRef(*env, polygon); - } - - return std_vector_uint_to_jobject(env, ids); -} - -void nativeUpdatePolygon(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong polygonId, jni::jobject* polygon) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - jni::jobject* points = jni::GetField(*env, polygon, *polygonPointsId); - - mbgl::FillAnnotation annotation { mbgl::Polygon { toGeometry>(env, points) } }; - annotation.opacity = { jni::GetField(*env, polygon, *polygonAlphaId) }; - annotation.outlineColor = { toColor(jni::GetField(*env, polygon, *polygonStrokeColorId)) }; - annotation.color = { toColor(jni::GetField(*env, polygon, *polygonFillColorId)) }; - nativeMapView->getMap().updateAnnotation(polygonId, annotation); -} - -void nativeUpdatePolyline(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong polylineId, jni::jobject* polyline) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - jni::jobject* points = jni::GetField(*env, polyline, *polylinePointsId); - - mbgl::LineAnnotation annotation { toGeometry>(env, points) }; - annotation.opacity = { jni::GetField(*env, polyline, *polylineAlphaId) }; - annotation.color = { toColor(jni::GetField(*env, polyline, *polylineColorId)) }; - annotation.width = { jni::GetField(*env, polyline, *polylineWidthId) }; - nativeMapView->getMap().updateAnnotation(polylineId, annotation); -} - -void nativeRemoveAnnotations(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jarray* jarray) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - NullCheck(*env, jarray); - std::size_t len = jni::GetArrayLength(*env, *jarray); - auto elements = jni::GetArrayElements(*env, *jarray); - jlong* jids = std::get<0>(elements).get(); - - for (std::size_t i = 0; i < len; i++) { - if(jids[i] == -1L) - continue; - nativeMapView->getMap().removeAnnotation(jids[i]); - } -} - -jni::jarray* nativeQueryPointAnnotations(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jobject* rect) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - // Conversion - jfloat left = jni::GetField(*env, rect, *rectFLeftId); - jfloat right = jni::GetField(*env, rect, *rectFRightId); - jfloat top = jni::GetField(*env, rect, *rectFTopId); - jfloat bottom = jni::GetField(*env, rect, *rectFBottomId); - mbgl::ScreenBox box = { - { left, top }, - { right, bottom }, - }; +void registerNatives(JavaVM *vm) { + theJVM = vm; - // Assume only points for now - mbgl::AnnotationIDs ids = nativeMapView->getMap().queryPointAnnotations(box); + jni::JNIEnv& env = jni::GetEnv(*vm, jni::jni_version_1_6); - return std_vector_uint_to_jobject(env, ids); -} + // For the DefaultFileSource + static mbgl::util::RunLoop mainRunLoop; + FileSource::registerNative(env); -void nativeAddAnnotationIcon(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, - jni::jstring* symbol, jint width, jint height, jfloat scale, jni::jarray* jpixels) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); + // Basic types + java::registerNatives(env); + java::util::registerNative(env); + PointF::registerNative(env); + RectF::registerNative(env); - const std::string symbolName = std_string_from_jstring(env, symbol); + // Geometry + Feature::registerNative(env); + LatLng::registerNative(env); + LatLngBounds::registerNative(env); + ProjectedMeters::registerNative(env); - NullCheck(*env, jpixels); - std::size_t size = jni::GetArrayLength(*env, *jpixels); - mbgl::PremultipliedImage premultipliedImage( - { static_cast(width), static_cast(height) }); + //Annotation + Marker::registerNative(env); + Polygon::registerNative(env); + Polyline::registerNative(env); - if (premultipliedImage.bytes() != uint32_t(size)) { - throw mbgl::util::SpriteImageException("Sprite image pixel count mismatch"); - } + // Map + NativeMapView::registerNative(env); - jni::GetArrayRegion(*env, *jpixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); + // Http + RegisterNativeHTTPRequest(env); - auto iconImage = std::make_shared( - std::move(premultipliedImage), - float(scale)); + // Bitmap + Bitmap::registerNative(env); + BitmapFactory::registerNative(env); - nativeMapView->getMap().addAnnotationIcon(symbolName, iconImage); -} + // Style + registerNativeLayers(env); + registerNativeSources(env); + Stop::registerNative(env); + CategoricalStops::registerNative(env); + ExponentialStops::registerNative(env); + IdentityStops::registerNative(env); + IntervalStops::registerNative(env); -void nativeSetVisibleCoordinateBounds(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, - jni::jarray* coordinates, jni::jobject* padding, jdouble direction, jlong duration) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - jfloat left = jni::GetField(*env, padding, *rectFLeftId); - jfloat right = jni::GetField(*env, padding, *rectFRightId); - jfloat top = jni::GetField(*env, padding, *rectFTopId); - jfloat bottom = jni::GetField(*env, padding, *rectFBottomId); - - NullCheck(*env, coordinates); - std::size_t count = jni::GetArrayLength(*env, *coordinates); - - mbgl::EdgeInsets mbglInsets = {top, left, bottom, right}; - std::vector latLngs; - latLngs.reserve(count); - - for (std::size_t i = 0; i < count; i++) { - jni::jobject* latLng = jni::GetObjectArrayElement(*env, *coordinates, i); - jdouble latitude = jni::GetField(*env, latLng, *latLngLatitudeId); - jdouble longitude = jni::GetField(*env, latLng, *latLngLongitudeId); - latLngs.push_back(mbgl::LatLng(latitude, longitude)); - } - - mbgl::CameraOptions cameraOptions = nativeMapView->getMap().cameraForLatLngs(latLngs, mbglInsets); - if (direction >= 0) { - // convert from degrees to radians - cameraOptions.angle = (-direction * M_PI) / 180; - } - mbgl::AnimationOptions animationOptions; - if (duration > 0) { - animationOptions.duration.emplace(mbgl::Milliseconds(duration)); - // equivalent to kCAMediaTimingFunctionDefault in iOS - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0.25, 0.1, 0.25, 0.1 }); - } - - nativeMapView->getMap().easeTo(cameraOptions, animationOptions); -} - -jni::jarray* nativeQueryRenderedFeaturesForPoint(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jfloat x, jni::jfloat y, jni::jarray* layerIds) { - using namespace mbgl::android::conversion; - using namespace mapbox::geometry; - - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::optional> layers; - if (layerIds != nullptr && jni::GetArrayLength(*env, *layerIds) > 0) { - layers = toVector(*env, *layerIds); - } - point point = {x, y}; - - return *convert*, std::vector>(*env, nativeMapView->getMap().queryRenderedFeatures(point, layers)); -} - -jni::jarray* nativeQueryRenderedFeaturesForBox(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jfloat left, jni::jfloat top, jni::jfloat right, jni::jfloat bottom, jni::jarray* layerIds) { - using namespace mbgl::android::conversion; - using namespace mapbox::geometry; - - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::optional> layers; - if (layerIds != nullptr && jni::GetArrayLength(*env, *layerIds) > 0) { - layers = toVector(*env, *layerIds); - } - box box = { point{ left, top}, point{ right, bottom } }; - - return *convert*, std::vector>(*env, nativeMapView->getMap().queryRenderedFeatures(box, layers)); -} - -void nativeOnLowMemory(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().onLowMemory(); -} - -void nativeSetDebug(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jboolean debug) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - DebugOptions debugOptions = debug ? DebugOptions::TileBorders | DebugOptions::ParseStatus | DebugOptions::Collision - : DebugOptions::NoDebug; - nativeMapView->getMap().setDebug(debugOptions); - nativeMapView->enableFps(debug); -} - -void nativeToggleDebug(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().cycleDebugOptions(); - nativeMapView->enableFps(nativeMapView->getMap().getDebug() != DebugOptions::NoDebug); -} - -jboolean nativeGetDebug(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getDebug() != DebugOptions::NoDebug; -} - -jboolean nativeIsFullyLoaded(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().isFullyLoaded(); -} - -void nativeSetReachability(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jboolean status) { - assert(nativeMapViewPtr != 0); - if (status) { - mbgl::NetworkStatus::Reachable(); - } -} - -jdouble nativeGetMetersPerPixelAtLatitude(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble lat, jdouble zoom) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getMetersPerPixelAtLatitude(lat, zoom); -} - -jni::jobject* nativeProjectedMetersForLatLng(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble latitude, jdouble longitude) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ProjectedMeters projectedMeters = nativeMapView->getMap().projectedMetersForLatLng(mbgl::LatLng(latitude, longitude)); - return &jni::NewObject(*env, *projectedMetersClass, *projectedMetersConstructorId, projectedMeters.northing, projectedMeters.easting); -} - -jni::jobject* nativeLatLngForProjectedMeters(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble northing, jdouble easting) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::LatLng latLng = nativeMapView->getMap().latLngForProjectedMeters(mbgl::ProjectedMeters(northing, easting)); - return &jni::NewObject(*env, *latLngClass, *latLngConstructorId, latLng.latitude, latLng.longitude); -} - -jni::jobject* nativePixelForLatLng(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble latitude, jdouble longitude) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::ScreenCoordinate pixel = nativeMapView->getMap().pixelForLatLng(mbgl::LatLng(latitude, longitude)); - return &jni::NewObject(*env, *pointFClass, *pointFConstructorId, static_cast(pixel.x), static_cast(pixel.y)); -} - -jni::jobject* nativeLatLngForPixel(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jfloat x, jfloat y) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::LatLng latLng = nativeMapView->getMap().latLngForPixel(mbgl::ScreenCoordinate(x, y)); - return &jni::NewObject(*env, *latLngClass, *latLngConstructorId, latLng.latitude, latLng.longitude); -} - -jdouble nativeGetTopOffsetPixelsForAnnotationSymbol(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* symbolName) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - return nativeMapView->getMap().getTopOffsetPixelsForAnnotationIcon(std_string_from_jstring(env, symbolName)); -} - -void nativeJumpTo(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble angle, jdouble latitude, jdouble longitude, jdouble pitch, jdouble zoom) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::CameraOptions options; - if (angle != -1) { - options.angle = (-angle * M_PI) / 180; - } - options.center = mbgl::LatLng(latitude, longitude); - options.padding = nativeMapView->getInsets(); - if (pitch != -1) { - options.pitch = pitch * M_PI / 180; - } - if (zoom != -1) { - options.zoom = zoom; - } - - nativeMapView->getMap().jumpTo(options); -} - -void nativeEaseTo(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble angle, jdouble latitude, jdouble longitude, jlong duration, jdouble pitch, jdouble zoom, jboolean easing) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::CameraOptions cameraOptions; - if (angle != -1) { - cameraOptions.angle = (-angle * M_PI) / 180; - } - cameraOptions.center = mbgl::LatLng(latitude, longitude); - cameraOptions.padding = nativeMapView->getInsets(); - if (pitch != -1) { - cameraOptions.pitch = pitch * M_PI / 180; - } - if (zoom != -1) { - cameraOptions.zoom = zoom; - } - mbgl::AnimationOptions animationOptions; - animationOptions.duration.emplace(mbgl::Duration(duration)); - - if (!easing) { - // add a linear interpolator instead of easing - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0, 1, 1 }); - } - - nativeMapView->getMap().easeTo(cameraOptions, animationOptions); -} - -void nativeSetContentPadding(JNIEnv *env, jni::jobject* obj,long nativeMapViewPtr, double top, double left, double bottom, double right) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->setInsets({top, left, bottom, right}); -} - -void nativeFlyTo(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jdouble angle, jdouble latitude, jdouble longitude, jlong duration, jdouble pitch, jdouble zoom) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - mbgl::CameraOptions cameraOptions; - if (angle != -1) { - cameraOptions.angle = (-angle * M_PI) / 180 ; - } - cameraOptions.center = mbgl::LatLng(latitude, longitude); - cameraOptions.padding = nativeMapView->getInsets(); - if (pitch != -1) { - cameraOptions.pitch = pitch * M_PI / 180; - } - if (zoom != -1) { - cameraOptions.zoom = zoom; - } - mbgl::AnimationOptions animationOptions; - animationOptions.duration.emplace(mbgl::Duration(duration)); - - nativeMapView->getMap().flyTo(cameraOptions, animationOptions); -} - -jlong nativeGetTransitionDuration(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(env); - assert(nativeMapViewPtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - const auto transitionOptions = nativeMapView->getMap().getTransitionOptions(); - return transitionOptions.duration.value_or(mbgl::Duration::zero()).count(); -} - -void nativeSetTransitionDuration(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong duration) { - assert(env); - assert(nativeMapViewPtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - auto transitionOptions = nativeMapView->getMap().getTransitionOptions(); - transitionOptions.duration = std::chrono::duration_cast(std::chrono::duration(duration)); - nativeMapView->getMap().setTransitionOptions(transitionOptions); -} - -jlong nativeGetTransitionDelay(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(env); - assert(nativeMapViewPtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - const auto transitionOptions = nativeMapView->getMap().getTransitionOptions(); - return transitionOptions.delay.value_or(mbgl::Duration::zero()).count(); -} - -void nativeSetTransitionDelay(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong delay) { - assert(env); - assert(nativeMapViewPtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - auto transitionOptions = nativeMapView->getMap().getTransitionOptions(); - transitionOptions.delay = std::chrono::duration_cast(std::chrono::duration(delay)); - nativeMapView->getMap().setTransitionOptions(transitionOptions); -} - -jni::jobject* nativeGetLayer(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* layerId) { - assert(env); - assert(nativeMapViewPtr != 0); - - // Get the native map peer - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - // Find the layer - mbgl::style::Layer* coreLayer = nativeMapView->getMap().getLayer(std_string_from_jstring(env, layerId)); - if (!coreLayer) { - mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); - return jni::Object(); - } - - // Create and return the layer's native peer - return createJavaLayerPeer(*env, nativeMapView->getMap(), *coreLayer); -} - -void nativeAddLayer(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong nativeLayerPtr, jni::jstring* before) { - assert(nativeMapViewPtr != 0); - assert(nativeLayerPtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - Layer *layer = reinterpret_cast(nativeLayerPtr); - try { - layer->addToMap(nativeMapView->getMap(), before ? mbgl::optional(std_string_from_jstring(env, before)) : mbgl::optional()); - } catch (const std::runtime_error& error) { - jni::ThrowNew(*env, jni::FindClass(*env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); - } -} - -/** - * Remove by layer id. Ownership is not transferred back - */ -void nativeRemoveLayerById(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* id) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - nativeMapView->getMap().removeLayer(std_string_from_jstring(env, id)); -} - -/** - * Remove with wrapper object id. Ownership is transferred back to the wrapper - */ -void nativeRemoveLayer(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong layerPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::android::Layer *layer = reinterpret_cast(layerPtr); - - std::unique_ptr coreLayer = nativeMapView->getMap().removeLayer(layer->get().getID()); - if (coreLayer) { - layer->setLayer(std::move(coreLayer)); - } -} - - -jni::jobject* nativeGetSource(JNIEnv *env, jni::jobject* obj, jni::jlong nativeMapViewPtr, jni::jstring* sourceId) { - assert(env); - assert(nativeMapViewPtr != 0); - - // Get the native map peer - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - // Find the source - mbgl::style::Source* coreSource = nativeMapView->getMap().getSource(std_string_from_jstring(env, sourceId)); - if (!coreSource) { - mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); - return jni::Object(); - } - - // Create and return the source's native peer - return createJavaSourcePeer(*env, nativeMapView->getMap(), *coreSource); -} - -void nativeAddSource(JNIEnv *env, jni::jobject* obj, jni::jlong nativeMapViewPtr, jni::jlong nativeSourcePtr) { - assert(nativeMapViewPtr != 0); - assert(nativeSourcePtr != 0); - - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - Source *source = reinterpret_cast(nativeSourcePtr); - try { - source->addToMap(nativeMapView->getMap()); - } catch (const std::runtime_error& error) { - jni::ThrowNew(*env, jni::FindClass(*env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); - } -} - -void nativeRemoveSourceById(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* id) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().removeSource(std_string_from_jstring(env, id)); -} - -void nativeRemoveSource(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jlong sourcePtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - mbgl::android::Source *source = reinterpret_cast(sourcePtr); - - std::unique_ptr coreSource = nativeMapView->getMap().removeSource(source->get().getID()); - if (coreSource) { - source->setSource(std::move(coreSource)); - } -} - -void nativeAddImage(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* name, jni::jint width, jni::jint height, jni::jfloat pixelRatio, jni::jarray* data) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - - // Create Pre-multiplied image from byte[] - NullCheck(*env, data); - std::size_t size = jni::GetArrayLength(*env, *data); - mbgl::PremultipliedImage premultipliedImage( - { static_cast(width), static_cast(height) }); - - if (premultipliedImage.bytes() != uint32_t(size)) { - throw mbgl::util::SpriteImageException("Sprite image pixel count mismatch"); - } - - jni::GetArrayRegion(*env, *data, 0, size, reinterpret_cast(premultipliedImage.data.get())); - - // Wrap in a SpriteImage with the correct pixel ratio - auto spriteImage = std::make_unique(std::move(premultipliedImage), float(pixelRatio)); - - nativeMapView->getMap().addImage(std_string_from_jstring(env, name), std::move(spriteImage)); -} - -void nativeRemoveImage(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr, jni::jstring* name) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->getMap().removeImage(std_string_from_jstring(env, name)); -} - -void nativeScheduleTakeSnapshot(JNIEnv *env, jni::jobject* obj, jlong nativeMapViewPtr) { - assert(nativeMapViewPtr != 0); - NativeMapView *nativeMapView = reinterpret_cast(nativeMapViewPtr); - nativeMapView->scheduleTakeSnapshot(); -} - -// Offline calls begin - -jlong sharedDefaultFileSource(JNIEnv *env, jni::jobject* obj, jni::jstring* cachePath_, jni::jstring* assetRoot_) { - return reinterpret_cast(&defaultFileSource(std_string_from_jstring(env, cachePath_), - std_string_from_jstring(env, assetRoot_))); -} - -void setAccessToken(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr, jni::jstring* accessToken_) { - assert(defaultFileSourcePtr != 0); - std::string accessToken = std_string_from_jstring(env, accessToken_); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - defaultFileSource->setAccessToken(accessToken); -} - -jni::jstring* getAccessToken(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr) { - assert(defaultFileSourcePtr != 0); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - std::string accessToken = defaultFileSource->getAccessToken(); - return std_string_to_jstring(env, accessToken); -} - -void listOfflineRegions(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr, jni::jobject* listCallback) { - // Checks - assert(defaultFileSourcePtr != 0); - NullCheck(*env, listCallback); - - // Makes sure the objects don't get GC'ed - obj = jni::NewGlobalRef(*env, obj).release(); - listCallback = jni::NewGlobalRef(*env, listCallback).release(); - - // Launch listCallback - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - defaultFileSource->listOfflineRegions([obj, defaultFileSourcePtr, listCallback](std::exception_ptr error, mbgl::optional> regions) mutable { - - // Reattach, the callback comes from a different thread - JNIEnv *env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - if (renderDetach) { - mbgl::Log::Debug(mbgl::Event::JNI, "Attached."); - } - - if (error) { - std::string message = mbgl::util::toString(error); - jni::CallMethod(*env2, listCallback, *listOnErrorMethodId, std_string_to_jstring(env2, message)); - } else if (regions) { - // Build jni::jarray* - std::size_t index = 0; - jni::jarray* jregions = &jni::NewObjectArray(*env2, regions->size(), *offlineRegionClass, NULL); - for (auto& region : *regions) { - // Create a new local reference frame (capacity 2 for the NewObject allocations below) - // to avoid a local reference table overflow (#5629) - jni::UniqueLocalFrame frame = jni::PushLocalFrame(*env2, 2); - - // Build the Region object - jni::jobject* jregion = &jni::NewObject(*env2, *offlineRegionClass, *offlineRegionConstructorId); - jni::SetField(*env2, jregion, *offlineRegionOfflineManagerId, obj); - jni::SetField(*env2, jregion, *offlineRegionIdId, region.getID()); - - // Definition object - mbgl::OfflineTilePyramidRegionDefinition definition = region.getDefinition(); - jni::jobject* jdefinition = &jni::NewObject(*env2, *offlineRegionDefinitionClass, *offlineRegionDefinitionConstructorId); - jni::SetField(*env2, jdefinition, *offlineRegionDefinitionStyleURLId, std_string_to_jstring(env2, definition.styleURL)); - jni::SetField(*env2, jdefinition, *offlineRegionDefinitionBoundsId, latlngbounds_from_native(env2, definition.bounds)); - jni::SetField(*env2, jdefinition, *offlineRegionDefinitionMinZoomId, definition.minZoom); - jni::SetField(*env2, jdefinition, *offlineRegionDefinitionMaxZoomId, definition.maxZoom); - jni::SetField(*env2, jdefinition, *offlineRegionDefinitionPixelRatioId, definition.pixelRatio); - jni::SetField(*env2, jregion, *offlineRegionDefinitionId, jdefinition); - - // Metadata object - jni::jarray* metadata = metadata_from_native(env2, region.getMetadata()); - jni::SetField(*env2, jregion, *offlineRegionMetadataId, metadata); - - // Moves the region on the stack into a heap-allocated one - jni::SetField(*env2, jregion, *offlineRegionPtrId, - reinterpret_cast(new mbgl::OfflineRegion(std::move(region)))); - - jni::SetObjectArrayElement(*env2, *jregions, index, jregion); - index++; - } - - // Trigger callback - jni::CallMethod(*env2, listCallback, *listOnListMethodId, jregions); - } - - // Delete global refs and detach when we're done - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(obj)); - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(listCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - }); -} - -void createOfflineRegion(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr, jni::jobject* definition_, jni::jarray* metadata_, jni::jobject* createCallback) { - // Checks - assert(defaultFileSourcePtr != 0); - NullCheck(*env, createCallback); - - // Definition fields - jni::jstring* jStyleURL = reinterpret_cast(jni::GetField(*env, definition_, *offlineRegionDefinitionStyleURLId)); - std::string styleURL = std_string_from_jstring(env, jStyleURL); - jni::jobject* jBounds = jni::GetField(*env, definition_, *offlineRegionDefinitionBoundsId); - jdouble jMinZoom = jni::GetField(*env, definition_, *offlineRegionDefinitionMinZoomId); - jdouble jMaxZoom = jni::GetField(*env, definition_, *offlineRegionDefinitionMaxZoomId); - jfloat jPixelRatio = jni::GetField(*env, definition_, *offlineRegionDefinitionPixelRatioId); - - // Convert bounds fields to native - mbgl::LatLngBounds bounds = latlngbounds_from_java(env, jBounds); - - // Definition - mbgl::OfflineTilePyramidRegionDefinition definition(styleURL, bounds, jMinZoom, jMaxZoom, jPixelRatio); - - // Metadata - mbgl::OfflineRegionMetadata metadata; - if (metadata_ != nullptr) { - metadata = metadata_from_java(env, *metadata_); - } - - // Makes sure the objects don't get GC'ed - obj = jni::NewGlobalRef(*env, obj).release(); - createCallback = jni::NewGlobalRef(*env, createCallback).release(); - - // Launch createCallback - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - defaultFileSource->createOfflineRegion(definition, metadata, [obj, defaultFileSourcePtr, createCallback] (std::exception_ptr error, mbgl::optional region) mutable { - - // Reattach, the callback comes from a different thread - JNIEnv *env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - if (renderDetach) { - mbgl::Log::Debug(mbgl::Event::JNI, "Attached."); - } - - if (error) { - std::string message = mbgl::util::toString(error); - jni::CallMethod(*env2, createCallback, *createOnErrorMethodId, std_string_to_jstring(env2, message)); - } else if (region) { - // Build the Region object - jni::jobject* jregion = &jni::NewObject(*env2, *offlineRegionClass, *offlineRegionConstructorId); - jni::SetField(*env2, jregion, *offlineRegionOfflineManagerId, obj); - jni::SetField(*env2, jregion, *offlineRegionIdId, region->getID()); - - // Metadata object - jni::jarray* jmetadata = metadata_from_native(env2, region->getMetadata()); - jni::SetField(*env2, jregion, *offlineRegionMetadataId, jmetadata); - - // Moves the region on the stack into a heap-allocated one - jni::SetField(*env2, jregion, *offlineRegionPtrId, - reinterpret_cast(new mbgl::OfflineRegion(std::move(*region)))); - - // Invoke Java callback - jni::CallMethod(*env2, createCallback, *createOnCreateMethodId, jregion); - } - - // Delete global refs and detach when we're done - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(obj)); - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(createCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - }); -} - -// A deleter that doesn't retain an JNIEnv handle but instead tries to attach the JVM. This means -// it can be used on any thread to delete a global ref. -struct GenericGlobalRefDeleter { - void operator()(jni::jobject* p) const { - if (p) { - auto env = AttachEnv(); - env->DeleteGlobalRef(jni::Unwrap(p)); - } - } -}; - -void setResourceTransform(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr, jni::jobject* transformCallback) { - // Checks - assert(defaultFileSourcePtr != 0); - - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - if (transformCallback) { - // Launch transformCallback - defaultFileSource->setResourceTransform([ - // Capture the OfflineManager and ResourceTransformCallback objects as a managed global into - // the lambda. They are released automatically when we're setting a new ResourceTransform in - // a subsequent call. - // Note: we're converting them to shared_ptrs because this lambda is converted to a std::function, - // which requires copyability of its captured variables. - offlineManager = std::shared_ptr(jni::NewGlobalRef(*env, obj).release(), GenericGlobalRefDeleter()), - callback = std::shared_ptr(jni::NewGlobalRef(*env, transformCallback).release(), GenericGlobalRefDeleter()), - env - ](mbgl::Resource::Kind kind, std::string&& url_) { - auto url = std_string_to_jstring(env, url_); - url = reinterpret_cast(jni::CallMethod( - *env, callback.get(), *transformOnURLMethodId, int(kind), url)); - return std_string_from_jstring(env, url); - }); - } else { - // Reset the callback - defaultFileSource->setResourceTransform(nullptr); - } -} - -void setOfflineMapboxTileCountLimit(JNIEnv *env, jni::jobject* obj, jlong defaultFileSourcePtr, jlong limit) { - // Checks - assert(defaultFileSourcePtr != 0); - assert(limit > 0); - - // Set limit - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - defaultFileSource->setOfflineMapboxTileCountLimit(limit); -} - -mbgl::OfflineRegion* getOfflineRegionPeer(JNIEnv *env, jni::jobject* offlineRegion_) { - jlong offlineRegionPtr = jni::GetField(*env, offlineRegion_, *offlineRegionPtrId); - if (!offlineRegionPtr) { - jni::ThrowNew(*env, jni::FindClass(*env, "java/lang/IllegalStateException"), - "Use of OfflineRegion after OfflineRegion.delete"); - } - return reinterpret_cast(offlineRegionPtr); -} - -void destroyOfflineRegion(JNIEnv *env, jni::jobject* offlineRegion_) { - // Offline region - jlong offlineRegionPtr = jni::GetField(*env, offlineRegion_, *offlineRegionPtrId); - if (!offlineRegionPtr) { - return; // Already deleted - } - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Release the observer and delete the region - mbgl::OfflineRegion *offlineRegion = reinterpret_cast(offlineRegionPtr); - defaultFileSource->setOfflineRegionObserver(*offlineRegion, nullptr); - jni::SetField(*env, offlineRegion_, *offlineRegionPtrId, 0); - delete offlineRegion; -} - -void setOfflineRegionObserver(JNIEnv *env, jni::jobject* offlineRegion_, jni::jobject* observerCallback) { - // Offline region - mbgl::OfflineRegion* offlineRegion = getOfflineRegionPeer(env, offlineRegion_); - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Define the observer - class Observer : public mbgl::OfflineRegionObserver { - public: - Observer(jni::UniqueGlobalRef&& observerCallback_) - : observerCallback(std::move(observerCallback_)) { - } - - ~Observer() override { - mbgl::Log::Debug(mbgl::Event::JNI, "~Observer()"); - // Env - JNIEnv* env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - jni::DeleteGlobalRef(*env2, std::move(observerCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - } - - void statusChanged(mbgl::OfflineRegionStatus status) override { - // Env - JNIEnv* env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - - // Conver to jint - jint downloadState; - switch(status.downloadState) { - case mbgl::OfflineRegionDownloadState::Inactive: - downloadState = 0; - break; - case mbgl::OfflineRegionDownloadState::Active: - downloadState = 1; - break; - } - - // Create a new local reference frame (capacity 1 for the NewObject allocation below) - // to avoid a local reference table overflow (#4706) - jni::UniqueLocalFrame frame = jni::PushLocalFrame(*env2, 1); - - // Stats object - jni::jobject* jstatus = &jni::NewObject(*env2, *offlineRegionStatusClass, *offlineRegionStatusConstructorId); - jni::SetField(*env2, jstatus, *offlineRegionStatusDownloadStateId, downloadState); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedResourceCountId, status.completedResourceCount); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedResourceSizeId, status.completedResourceSize); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedTileCountId, status.completedTileCount); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedTileSizeId, status.completedTileSize); - jni::SetField(*env2, jstatus, *offlineRegionStatusRequiredResourceCountId, status.requiredResourceCount); - jni::SetField(*env2, jstatus, *offlineRegionStatusRequiredResourceCountIsPreciseId, status.requiredResourceCountIsPrecise); - jni::CallMethod(*env2, observerCallback.get(), *offlineRegionObserveronStatusChangedId, jstatus); - - // Detach when we're done - detach_jni_thread(theJVM, &env2, renderDetach); - } - - void responseError(mbgl::Response::Error error) override { - // Env - JNIEnv* env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - - // Handle the value of reason independently of the underlying int value - std::string errorReason; - switch(error.reason) { - case mbgl::Response::Error::Reason::Success: - errorReason = "REASON_SUCCESS"; - break; - case mbgl::Response::Error::Reason::NotFound: - errorReason = "REASON_NOT_FOUND"; - break; - case mbgl::Response::Error::Reason::Server: - errorReason = "REASON_SERVER"; - break; - case mbgl::Response::Error::Reason::Connection: - errorReason = "REASON_CONNECTION"; - break; - case mbgl::Response::Error::Reason::RateLimit: - errorReason = "REASON_RATE_LIMIT"; - break; - case mbgl::Response::Error::Reason::Other: - errorReason = "REASON_OTHER"; - break; - } - - // Error object - jni::UniqueLocalFrame frame = jni::PushLocalFrame(*env2, 3); - jni::jobject* jerror = &jni::NewObject(*env2, *offlineRegionErrorClass, *offlineRegionErrorConstructorId); - jni::SetField(*env2, jerror, *offlineRegionErrorReasonId, std_string_to_jstring(env2, errorReason)); - jni::SetField(*env2, jerror, *offlineRegionErrorMessageId, std_string_to_jstring(env2, error.message)); - jni::CallMethod(*env2, observerCallback.get(), *offlineRegionObserveronErrorId, jerror); - - // Detach when we're done - detach_jni_thread(theJVM, &env2, renderDetach); - } - - void mapboxTileCountLimitExceeded(uint64_t limit) override { - // Env - JNIEnv* env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - - // Send limit - jni::CallMethod(*env2, observerCallback.get(), *offlineRegionObserveronLimitId, jlong(limit)); - - // Detach when we're done - detach_jni_thread(theJVM, &env2, renderDetach); - } - - jni::UniqueGlobalRef observerCallback; - }; - - // Set the observer - defaultFileSource->setOfflineRegionObserver(*offlineRegion, - std::make_unique(jni::NewGlobalRef(*env, observerCallback))); -} - -void setOfflineRegionDownloadState(JNIEnv *env, jni::jobject* offlineRegion_, jint offlineRegionDownloadState) { - // State - mbgl::OfflineRegionDownloadState state; - if (offlineRegionDownloadState == 0) { - state = mbgl::OfflineRegionDownloadState::Inactive; - } else if (offlineRegionDownloadState == 1) { - state = mbgl::OfflineRegionDownloadState::Active; - } else { - mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); - return; - } - - // Offline region - mbgl::OfflineRegion* offlineRegion = getOfflineRegionPeer(env, offlineRegion_); - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Set new state - defaultFileSource->setOfflineRegionDownloadState(*offlineRegion, state); -} - -void getOfflineRegionStatus(JNIEnv *env, jni::jobject* offlineRegion_, jni::jobject* statusCallback) { - // Offline region - mbgl::OfflineRegion* offlineRegion = getOfflineRegionPeer(env, offlineRegion_); - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Makes sure the callback doesn't get GC'ed - statusCallback = jni::NewGlobalRef(*env, statusCallback).release(); - - // Set new state - defaultFileSource->getOfflineRegionStatus(*offlineRegion, [statusCallback](std::exception_ptr error, mbgl::optional status) mutable { - - // Reattach, the callback comes from a different thread - JNIEnv *env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - if (renderDetach) { - mbgl::Log::Debug(mbgl::Event::JNI, "Attached."); - } - - if (error) { - std::string message = mbgl::util::toString(error); - jni::CallMethod(*env2, statusCallback, *offlineRegionStatusOnErrorId, std_string_to_jstring(env2, message)); - } else if (status) { - // Conver to jint - jint downloadState = -1; - if (status->downloadState == mbgl::OfflineRegionDownloadState::Inactive) { - downloadState = 0; - } else if (status->downloadState == mbgl::OfflineRegionDownloadState::Active) { - downloadState = 1; - } else { - mbgl::Log::Error(mbgl::Event::JNI, "Unsupported OfflineRegionDownloadState value."); - return; - } - - // Stats object - jni::jobject* jstatus = &jni::NewObject(*env2, *offlineRegionStatusClass, *offlineRegionStatusConstructorId); - jni::SetField(*env2, jstatus, *offlineRegionStatusDownloadStateId, downloadState); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedResourceCountId, status->completedResourceCount); - jni::SetField(*env2, jstatus, *offlineRegionStatusCompletedResourceSizeId, status->completedResourceSize); - jni::SetField(*env2, jstatus, *offlineRegionStatusRequiredResourceCountId, status->requiredResourceCount); - jni::SetField(*env2, jstatus, *offlineRegionStatusRequiredResourceCountIsPreciseId, status->requiredResourceCountIsPrecise); - jni::CallMethod(*env2, statusCallback, *offlineRegionStatusOnStatusId, jstatus); - } - - // Delete global refs and detach when we're done - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(statusCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - }); -} - -void deleteOfflineRegion(JNIEnv *env, jni::jobject* offlineRegion_, jni::jobject* deleteCallback) { - // Offline region - mbgl::OfflineRegion* offlineRegion = getOfflineRegionPeer(env, offlineRegion_); - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Makes sure the callback doesn't get GC'ed - deleteCallback = jni::NewGlobalRef(*env, deleteCallback).release(); - - // Set new state - jni::SetField(*env, offlineRegion_, *offlineRegionPtrId, 0); - defaultFileSource->deleteOfflineRegion(std::move(*offlineRegion), [deleteCallback](std::exception_ptr error) mutable { - - // Reattach, the callback comes from a different thread - JNIEnv *env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - if (renderDetach) { - mbgl::Log::Debug(mbgl::Event::JNI, "Attached."); - } - - if (error) { - std::string message = mbgl::util::toString(error); - jni::CallMethod(*env2, deleteCallback, *offlineRegionDeleteOnErrorId, std_string_to_jstring(env2, message)); - } else { - jni::CallMethod(*env2, deleteCallback, *offlineRegionDeleteOnDeleteId); - } - - // Delete global refs and detach when we're done - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(deleteCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - }); -} - -void updateOfflineRegionMetadata(JNIEnv *env, jni::jobject* offlineRegion_, jni::jarray* metadata_, jni::jobject* updateCallback) { - // Offline region - mbgl::OfflineRegion* offlineRegion = getOfflineRegionPeer(env, offlineRegion_); - - // File source - jni::jobject* jmanager = jni::GetField(*env, offlineRegion_, *offlineRegionOfflineManagerId); - jlong defaultFileSourcePtr = jni::GetField(*env, jmanager, *offlineManagerClassPtrId); - mbgl::DefaultFileSource *defaultFileSource = reinterpret_cast(defaultFileSourcePtr); - - // Id conversion - int64_t id = offlineRegion->getID(); - - // Metadata - mbgl::OfflineRegionMetadata metadata; - if (metadata_ != nullptr) { - metadata = metadata_from_java(env, *metadata_); - } - - // Makes sure the objects don't get GC'ed - updateCallback = jni::NewGlobalRef(*env, updateCallback).release(); - - // Launch updateCallback - defaultFileSource->updateOfflineMetadata(id, metadata, [updateCallback] (std::exception_ptr error, mbgl::optional data) mutable { - // Reattach, the callback comes from a different thread - JNIEnv *env2; - jboolean renderDetach = attach_jni_thread(theJVM, &env2, "Offline Thread"); - if (renderDetach) { - mbgl::Log::Debug(mbgl::Event::JNI, "Attached."); - } - - if (error) { - std::string message = mbgl::util::toString(error); - jni::CallMethod(*env2, updateCallback, *updateMetadataOnErrorMethodId, std_string_to_jstring(env2, message)); - } else if (data) { - jni::jarray* jmetadata = metadata_from_native(env2, *data); - jni::CallMethod(*env2, updateCallback, *updateMetadataOnUpdateMethodId, jmetadata); - } - - // Delete global refs and detach when we're done - jni::DeleteGlobalRef(*env2, jni::UniqueGlobalRef(updateCallback)); - detach_jni_thread(theJVM, &env2, renderDetach); - }); -} - -// Offline calls end - -} // anonymous - -namespace mbgl { -namespace android { - -void registerNatives(JavaVM *vm) { - theJVM = vm; - - jni::JNIEnv& env = jni::GetEnv(*vm, jni::jni_version_1_6); - - static mbgl::util::RunLoop mainRunLoop; - - mbgl::android::RegisterNativeHTTPRequest(env); - - java::registerNatives(env); - Bitmap::registerNative(env); - BitmapFactory::registerNative(env); - registerNativeLayers(env); - registerNativeSources(env); - Stop::registerNative(env); - CategoricalStops::registerNative(env); - ExponentialStops::registerNative(env); - IdentityStops::registerNative(env); - IntervalStops::registerNative(env); + // Connectivity ConnectivityListener::registerNative(env); - latLngClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/geometry/LatLng"); - latLngClass = jni::NewGlobalRef(env, latLngClass).release(); - latLngConstructorId = &jni::GetMethodID(env, *latLngClass, "", "(DD)V"); - latLngLatitudeId = &jni::GetFieldID(env, *latLngClass, "latitude", "D"); - latLngLongitudeId = &jni::GetFieldID(env, *latLngClass, "longitude", "D"); - - latLngBoundsClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/geometry/LatLngBounds"); - latLngBoundsClass = jni::NewGlobalRef(env, latLngBoundsClass).release(); - latLngBoundsConstructorId = &jni::GetMethodID(env, *latLngBoundsClass, "", "(DDDD)V"); - latLngBoundsLatNorthId = &jni::GetFieldID(env, *latLngBoundsClass, "mLatNorth", "D"); - latLngBoundsLatSouthId = &jni::GetFieldID(env, *latLngBoundsClass, "mLatSouth", "D"); - latLngBoundsLonEastId = &jni::GetFieldID(env, *latLngBoundsClass, "mLonEast", "D"); - latLngBoundsLonWestId = &jni::GetFieldID(env, *latLngBoundsClass, "mLonWest", "D"); - - iconClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/annotations/Icon"); - iconClass = jni::NewGlobalRef(env, iconClass).release(); - iconIdId = &jni::GetFieldID(env, *iconClass, "mId", "Ljava/lang/String;"); - - markerClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/annotations/Marker"); - markerClass = jni::NewGlobalRef(env, markerClass).release(); - markerPositionId = &jni::GetFieldID(env, *markerClass, "position", "Lcom/mapbox/mapboxsdk/geometry/LatLng;"); - markerIconId = &jni::GetFieldID(env, *markerClass, "icon", "Lcom/mapbox/mapboxsdk/annotations/Icon;"); - markerIdId = &jni::GetFieldID(env, *markerClass, "id", "J"); - - polylineClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/annotations/Polyline"); - polylineClass = jni::NewGlobalRef(env, polylineClass).release(); - polylineAlphaId = &jni::GetFieldID(env, *polylineClass, "alpha", "F"); - polylineColorId = &jni::GetFieldID(env, *polylineClass, "color", "I"); - polylineWidthId = &jni::GetFieldID(env, *polylineClass, "width", "F"); - polylinePointsId = &jni::GetFieldID(env, *polylineClass, "points", "Ljava/util/List;"); - - polygonClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/annotations/Polygon"); - polygonClass = jni::NewGlobalRef(env, polygonClass).release(); - polygonAlphaId = &jni::GetFieldID(env, *polygonClass, "alpha", "F"); - polygonFillColorId = &jni::GetFieldID(env, *polygonClass, "fillColor", "I"); - polygonStrokeColorId = &jni::GetFieldID(env, *polygonClass, "strokeColor", "I"); - polygonPointsId = &jni::GetFieldID(env, *polygonClass, "points", "Ljava/util/List;"); - - jni::jclass* listClass = &jni::FindClass(env, "java/util/List"); - listToArrayId = &jni::GetMethodID(env, *listClass, "toArray", "()[Ljava/lang/Object;"); - - arrayListClass = &jni::FindClass(env, "java/util/ArrayList"); - arrayListClass = jni::NewGlobalRef(env, arrayListClass).release(); - arrayListConstructorId = &jni::GetMethodID(env, *arrayListClass, "", "()V"); - arrayListAddId = &jni::GetMethodID(env, *arrayListClass, "add", "(Ljava/lang/Object;)Z"); - - projectedMetersClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/geometry/ProjectedMeters"); - projectedMetersClass = jni::NewGlobalRef(env, projectedMetersClass).release(); - projectedMetersConstructorId = &jni::GetMethodID(env, *projectedMetersClass, "", "(DD)V"); - projectedMetersNorthingId = &jni::GetFieldID(env, *projectedMetersClass, "northing", "D"); - projectedMetersEastingId = &jni::GetFieldID(env, *projectedMetersClass, "easting", "D"); - - pointFClass = &jni::FindClass(env, "android/graphics/PointF"); - pointFClass = jni::NewGlobalRef(env, pointFClass).release(); - pointFConstructorId = &jni::GetMethodID(env, *pointFClass, "", "(FF)V"); - pointFXId = &jni::GetFieldID(env, *pointFClass, "x", "F"); - pointFYId = &jni::GetFieldID(env, *pointFClass, "y", "F"); - - rectFClass = &jni::FindClass(env, "android/graphics/RectF"); - rectFClass = jni::NewGlobalRef(env, rectFClass).release(); - rectFConstructorId = &jni::GetMethodID(env, *rectFClass, "", "()V"); - rectFLeftId = &jni::GetFieldID(env, *rectFClass, "left", "F"); - rectFRightId = &jni::GetFieldID(env, *rectFClass, "right", "F"); - rectFTopId = &jni::GetFieldID(env, *rectFClass, "top", "F"); - rectFBottomId = &jni::GetFieldID(env, *rectFClass, "bottom", "F"); - - jni::jclass& nativeMapViewClass = jni::FindClass(env, "com/mapbox/mapboxsdk/maps/NativeMapView"); - - onInvalidateId = &jni::GetMethodID(env, nativeMapViewClass, "onInvalidate", "()V"); - onMapChangedId = &jni::GetMethodID(env, nativeMapViewClass, "onMapChanged", "(I)V"); - onFpsChangedId = &jni::GetMethodID(env, nativeMapViewClass, "onFpsChanged", "(D)V"); - onSnapshotReadyId = &jni::GetMethodID(env, nativeMapViewClass, "onSnapshotReady","(Landroid/graphics/Bitmap;)V"); - - #define MAKE_NATIVE_METHOD(name, sig) jni::MakeNativeMethod( #name, sig ) - - jni::RegisterNatives(env, nativeMapViewClass, - MAKE_NATIVE_METHOD(nativeCreate, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;FIJ)J"), - MAKE_NATIVE_METHOD(nativeDestroy, "(J)V"), - MAKE_NATIVE_METHOD(nativeInitializeDisplay, "(J)V"), - MAKE_NATIVE_METHOD(nativeTerminateDisplay, "(J)V"), - MAKE_NATIVE_METHOD(nativeInitializeContext, "(J)V"), - MAKE_NATIVE_METHOD(nativeTerminateContext, "(J)V"), - MAKE_NATIVE_METHOD(nativeCreateSurface, "(JLandroid/view/Surface;)V"), - MAKE_NATIVE_METHOD(nativeDestroySurface, "(J)V"), - MAKE_NATIVE_METHOD(nativeUpdate, "(J)V"), - MAKE_NATIVE_METHOD(nativeRender, "(J)V"), - MAKE_NATIVE_METHOD(nativeViewResize, "(JII)V"), - MAKE_NATIVE_METHOD(nativeFramebufferResize, "(JII)V"), - MAKE_NATIVE_METHOD(nativeAddClass, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeRemoveClass, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeHasClass, "(JLjava/lang/String;)Z"), - MAKE_NATIVE_METHOD(nativeSetClasses, "(JLjava/util/List;)V"), - MAKE_NATIVE_METHOD(nativeGetClasses, "(J)Ljava/util/List;"), - MAKE_NATIVE_METHOD(nativeSetStyleUrl, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeGetStyleUrl, "(J)Ljava/lang/String;"), - MAKE_NATIVE_METHOD(nativeSetStyleJson, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeGetStyleJson, "(J)Ljava/lang/String;"), - MAKE_NATIVE_METHOD(nativeSetAccessToken, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeGetAccessToken, "(J)Ljava/lang/String;"), - MAKE_NATIVE_METHOD(nativeCancelTransitions, "(J)V"), - MAKE_NATIVE_METHOD(nativeSetGestureInProgress, "(JZ)V"), - MAKE_NATIVE_METHOD(nativeMoveBy, "(JDDJ)V"), - MAKE_NATIVE_METHOD(nativeSetLatLng, "(JDDJ)V"), - MAKE_NATIVE_METHOD(nativeGetLatLng, "(J)Lcom/mapbox/mapboxsdk/geometry/LatLng;"), - MAKE_NATIVE_METHOD(nativeResetPosition, "(J)V"), - MAKE_NATIVE_METHOD(nativeGetCameraValues, "(J)[D"), - MAKE_NATIVE_METHOD(nativeGetPitch, "(J)D"), - MAKE_NATIVE_METHOD(nativeSetPitch, "(JDJ)V"), - MAKE_NATIVE_METHOD(nativeScaleBy, "(JDDDJ)V"), - MAKE_NATIVE_METHOD(nativeSetScale, "(JDDDJ)V"), - MAKE_NATIVE_METHOD(nativeGetScale, "(J)D"), - MAKE_NATIVE_METHOD(nativeSetZoom, "(JDJ)V"), - MAKE_NATIVE_METHOD(nativeGetZoom, "(J)D"), - MAKE_NATIVE_METHOD(nativeResetZoom, "(J)V"), - MAKE_NATIVE_METHOD(nativeGetMinZoom, "(J)D"), - MAKE_NATIVE_METHOD(nativeSetMinZoom, "(JD)V"), - MAKE_NATIVE_METHOD(nativeGetMaxZoom, "(J)D"), - MAKE_NATIVE_METHOD(nativeSetMaxZoom, "(JD)V"), - MAKE_NATIVE_METHOD(nativeRotateBy, "(JDDDDJ)V"), - MAKE_NATIVE_METHOD(nativeSetBearing, "(JDJ)V"), - MAKE_NATIVE_METHOD(nativeSetFocalBearing, "(JDDDJ)V"), - MAKE_NATIVE_METHOD(nativeSetBearingXY, "(JDDD)V"), - MAKE_NATIVE_METHOD(nativeGetBearing, "(J)D"), - MAKE_NATIVE_METHOD(nativeResetNorth, "(J)V"), - MAKE_NATIVE_METHOD(nativeAddMarkers, "(J[Lcom/mapbox/mapboxsdk/annotations/Marker;)[J"), - MAKE_NATIVE_METHOD(nativeAddPolylines, "(J[Lcom/mapbox/mapboxsdk/annotations/Polyline;)[J"), - MAKE_NATIVE_METHOD(nativeAddPolygons, "(J[Lcom/mapbox/mapboxsdk/annotations/Polygon;)[J"), - MAKE_NATIVE_METHOD(nativeUpdateMarker, "(JJDDLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeUpdatePolygon, "(JJLcom/mapbox/mapboxsdk/annotations/Polygon;)V"), - MAKE_NATIVE_METHOD(nativeUpdatePolyline, "(JJLcom/mapbox/mapboxsdk/annotations/Polyline;)V"), - MAKE_NATIVE_METHOD(nativeRemoveAnnotations, "(J[J)V"), - MAKE_NATIVE_METHOD(nativeQueryPointAnnotations, "(JLandroid/graphics/RectF;)[J"), - MAKE_NATIVE_METHOD(nativeAddAnnotationIcon, "(JLjava/lang/String;IIF[B)V"), - MAKE_NATIVE_METHOD(nativeSetVisibleCoordinateBounds, "(J[Lcom/mapbox/mapboxsdk/geometry/LatLng;Landroid/graphics/RectF;DJ)V"), - MAKE_NATIVE_METHOD(nativeOnLowMemory, "(J)V"), - MAKE_NATIVE_METHOD(nativeSetDebug, "(JZ)V"), - MAKE_NATIVE_METHOD(nativeToggleDebug, "(J)V"), - MAKE_NATIVE_METHOD(nativeGetDebug, "(J)Z"), - MAKE_NATIVE_METHOD(nativeIsFullyLoaded, "(J)Z"), - MAKE_NATIVE_METHOD(nativeSetReachability, "(JZ)V"), - MAKE_NATIVE_METHOD(nativeGetMetersPerPixelAtLatitude, "(JDD)D"), - MAKE_NATIVE_METHOD(nativeProjectedMetersForLatLng, "(JDD)Lcom/mapbox/mapboxsdk/geometry/ProjectedMeters;"), - MAKE_NATIVE_METHOD(nativeLatLngForProjectedMeters, "(JDD)Lcom/mapbox/mapboxsdk/geometry/LatLng;"), - MAKE_NATIVE_METHOD(nativePixelForLatLng, "(JDD)Landroid/graphics/PointF;"), - MAKE_NATIVE_METHOD(nativeLatLngForPixel, "(JFF)Lcom/mapbox/mapboxsdk/geometry/LatLng;"), - MAKE_NATIVE_METHOD(nativeGetTopOffsetPixelsForAnnotationSymbol, "(JLjava/lang/String;)D"), - MAKE_NATIVE_METHOD(nativeJumpTo, "(JDDDDD)V"), - MAKE_NATIVE_METHOD(nativeEaseTo, "(JDDDJDDZ)V"), - MAKE_NATIVE_METHOD(nativeFlyTo, "(JDDDJDD)V"), - MAKE_NATIVE_METHOD(nativeGetTransitionDuration, "(J)J"), - MAKE_NATIVE_METHOD(nativeSetTransitionDuration, "(JJ)V"), - MAKE_NATIVE_METHOD(nativeGetTransitionDelay, "(J)J"), - MAKE_NATIVE_METHOD(nativeSetTransitionDelay, "(JJ)V"), - MAKE_NATIVE_METHOD(nativeGetLayer, "(JLjava/lang/String;)Lcom/mapbox/mapboxsdk/style/layers/Layer;"), - MAKE_NATIVE_METHOD(nativeAddLayer, "(JJLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeRemoveLayerById, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeRemoveLayer, "(JJ)V"), - MAKE_NATIVE_METHOD(nativeGetSource, "(JLjava/lang/String;)Lcom/mapbox/mapboxsdk/style/sources/Source;"), - MAKE_NATIVE_METHOD(nativeAddSource, "(JJ)V"), - MAKE_NATIVE_METHOD(nativeRemoveSourceById, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeRemoveSource, "(JJ)V"), - MAKE_NATIVE_METHOD(nativeAddImage, "(JLjava/lang/String;IIF[B)V"), - MAKE_NATIVE_METHOD(nativeRemoveImage, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(nativeSetContentPadding, "(JDDDD)V"), - MAKE_NATIVE_METHOD(nativeScheduleTakeSnapshot, "(J)V"), - MAKE_NATIVE_METHOD(nativeQueryRenderedFeaturesForPoint, "(JFF[Ljava/lang/String;)[Lcom/mapbox/services/commons/geojson/Feature;"), - MAKE_NATIVE_METHOD(nativeQueryRenderedFeaturesForBox, "(JFFFF[Ljava/lang/String;)[Lcom/mapbox/services/commons/geojson/Feature;"), - MAKE_NATIVE_METHOD(nativeSetAPIBaseURL, "(JLjava/lang/String;)V") - ); - - // Offline begin - - struct OfflineManager { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager"; } - - struct ListOfflineRegionsCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback"; } - }; - - struct CreateOfflineRegionsCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback"; } - }; - - struct ResourceTransformCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$ResourceTransformCallback"; } - }; - }; - - struct OfflineRegion { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion"; } - }; - - jni::Class offlineManagerClass = jni::Class::Find(env); - offlineManagerClassPtrId = &jni::GetFieldID(env, offlineManagerClass, "mDefaultFileSourcePtr", "J"); - - jni::RegisterNatives(env, offlineManagerClass, - MAKE_NATIVE_METHOD(sharedDefaultFileSource, "(Ljava/lang/String;Ljava/lang/String;)J"), - MAKE_NATIVE_METHOD(setAccessToken, "(JLjava/lang/String;)V"), - MAKE_NATIVE_METHOD(getAccessToken, "(J)Ljava/lang/String;"), - MAKE_NATIVE_METHOD(listOfflineRegions, "(JLcom/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback;)V"), - MAKE_NATIVE_METHOD(createOfflineRegion, "(JLcom/mapbox/mapboxsdk/offline/OfflineRegionDefinition;[BLcom/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback;)V"), - MAKE_NATIVE_METHOD(setResourceTransform, "(JLcom/mapbox/mapboxsdk/offline/OfflineManager$ResourceTransformCallback;)V"), - MAKE_NATIVE_METHOD(setOfflineMapboxTileCountLimit, "(JJ)V") - ); - - jni::Class listOfflineRegionsCallbackClass = jni::Class::Find(env); - listOnListMethodId = &jni::GetMethodID(env, listOfflineRegionsCallbackClass, "onList", "([Lcom/mapbox/mapboxsdk/offline/OfflineRegion;)V"); - listOnErrorMethodId = &jni::GetMethodID(env, listOfflineRegionsCallbackClass, "onError", "(Ljava/lang/String;)V"); - - jni::Class createOfflineRegionCallbackClass = jni::Class::Find(env); - createOnCreateMethodId = &jni::GetMethodID(env, createOfflineRegionCallbackClass, "onCreate", "(Lcom/mapbox/mapboxsdk/offline/OfflineRegion;)V"); - createOnErrorMethodId = &jni::GetMethodID(env, createOfflineRegionCallbackClass, "onError", "(Ljava/lang/String;)V"); - - jni::Class resourceTransformCallbackClass = jni::Class::Find(env); - transformOnURLMethodId = &jni::GetMethodID(env, resourceTransformCallbackClass, "onURL", "(ILjava/lang/String;)Ljava/lang/String;"); - - offlineRegionClass = &jni::FindClass(env, OfflineRegion::Name()); - offlineRegionClass = jni::NewGlobalRef(env, offlineRegionClass).release(); - offlineRegionConstructorId = &jni::GetMethodID(env, *offlineRegionClass, "", "()V"); - offlineRegionOfflineManagerId = &jni::GetFieldID(env, *offlineRegionClass, "offlineManager", "Lcom/mapbox/mapboxsdk/offline/OfflineManager;"); - offlineRegionIdId = &jni::GetFieldID(env, *offlineRegionClass, "mId", "J"); - offlineRegionDefinitionId = &jni::GetFieldID(env, *offlineRegionClass, "mDefinition", "Lcom/mapbox/mapboxsdk/offline/OfflineRegionDefinition;"); - offlineRegionMetadataId = &jni::GetFieldID(env, *offlineRegionClass, "mMetadata", "[B"); - offlineRegionPtrId = &jni::GetFieldID(env, *offlineRegionClass, "mOfflineRegionPtr", "J"); - - jni::RegisterNatives(env, *offlineRegionClass, - MAKE_NATIVE_METHOD(destroyOfflineRegion, "()V"), - MAKE_NATIVE_METHOD(setOfflineRegionObserver, "(Lcom/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionObserver;)V"), - MAKE_NATIVE_METHOD(setOfflineRegionDownloadState, "(I)V"), - MAKE_NATIVE_METHOD(getOfflineRegionStatus, "(Lcom/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback;)V"), - MAKE_NATIVE_METHOD(deleteOfflineRegion, "(Lcom/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback;)V"), - MAKE_NATIVE_METHOD(updateOfflineRegionMetadata, "([BLcom/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback;)V") - ); - - // This needs to be updated once we support more than one type of region definition - offlineRegionDefinitionClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition"); - offlineRegionDefinitionClass = jni::NewGlobalRef(env, offlineRegionDefinitionClass).release(); - offlineRegionDefinitionConstructorId = &jni::GetMethodID(env, *offlineRegionDefinitionClass, "", "()V"); - offlineRegionDefinitionStyleURLId = &jni::GetFieldID(env, *offlineRegionDefinitionClass, "styleURL", "Ljava/lang/String;"); - offlineRegionDefinitionBoundsId = &jni::GetFieldID(env, *offlineRegionDefinitionClass, "bounds", "Lcom/mapbox/mapboxsdk/geometry/LatLngBounds;"); - offlineRegionDefinitionMinZoomId = &jni::GetFieldID(env, *offlineRegionDefinitionClass, "minZoom", "D"); - offlineRegionDefinitionMaxZoomId = &jni::GetFieldID(env, *offlineRegionDefinitionClass, "maxZoom", "D"); - offlineRegionDefinitionPixelRatioId = &jni::GetFieldID(env, *offlineRegionDefinitionClass, "pixelRatio", "F"); - - jni::jclass* offlineRegionObserverClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionObserver"); - offlineRegionObserveronStatusChangedId = &jni::GetMethodID(env, *offlineRegionObserverClass, "onStatusChanged", "(Lcom/mapbox/mapboxsdk/offline/OfflineRegionStatus;)V"); - offlineRegionObserveronErrorId = &jni::GetMethodID(env, *offlineRegionObserverClass, "onError", "(Lcom/mapbox/mapboxsdk/offline/OfflineRegionError;)V"); - offlineRegionObserveronLimitId = &jni::GetMethodID(env, *offlineRegionObserverClass, "mapboxTileCountLimitExceeded", "(J)V"); - - offlineRegionStatusClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegionStatus"); - offlineRegionStatusClass = jni::NewGlobalRef(env, offlineRegionStatusClass).release(); - offlineRegionStatusConstructorId = &jni::GetMethodID(env, *offlineRegionStatusClass, "", "()V"); - offlineRegionStatusDownloadStateId = &jni::GetFieldID(env, *offlineRegionStatusClass, "downloadState", "I"); - offlineRegionStatusCompletedResourceCountId = &jni::GetFieldID(env, *offlineRegionStatusClass, "completedResourceCount", "J"); - offlineRegionStatusCompletedResourceSizeId = &jni::GetFieldID(env, *offlineRegionStatusClass, "completedResourceSize", "J"); - offlineRegionStatusCompletedTileCountId = &jni::GetFieldID(env, *offlineRegionStatusClass, "completedTileCount", "J"); - offlineRegionStatusCompletedTileSizeId = &jni::GetFieldID(env, *offlineRegionStatusClass, "completedTileSize", "J"); - offlineRegionStatusRequiredResourceCountId = &jni::GetFieldID(env, *offlineRegionStatusClass, "requiredResourceCount", "J"); - offlineRegionStatusRequiredResourceCountIsPreciseId = &jni::GetFieldID(env, *offlineRegionStatusClass, "requiredResourceCountIsPrecise", "Z"); - - offlineRegionErrorClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegionError"); - offlineRegionErrorClass = jni::NewGlobalRef(env, offlineRegionErrorClass).release(); - offlineRegionErrorConstructorId = &jni::GetMethodID(env, *offlineRegionErrorClass, "", "()V"); - offlineRegionErrorReasonId = &jni::GetFieldID(env, *offlineRegionErrorClass, "reason", "Ljava/lang/String;"); - offlineRegionErrorMessageId = &jni::GetFieldID(env, *offlineRegionErrorClass, "message", "Ljava/lang/String;"); - - jni::jclass* offlineRegionStatusCallbackClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback"); - offlineRegionStatusOnStatusId = &jni::GetMethodID(env, *offlineRegionStatusCallbackClass, "onStatus", "(Lcom/mapbox/mapboxsdk/offline/OfflineRegionStatus;)V"); - offlineRegionStatusOnErrorId = &jni::GetMethodID(env, *offlineRegionStatusCallbackClass, "onError", "(Ljava/lang/String;)V"); - - jni::jclass* offlineRegionDeleteCallbackClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback"); - offlineRegionDeleteOnDeleteId = &jni::GetMethodID(env, *offlineRegionDeleteCallbackClass, "onDelete", "()V"); - offlineRegionDeleteOnErrorId = &jni::GetMethodID(env, *offlineRegionDeleteCallbackClass, "onError", "(Ljava/lang/String;)V"); - - jni::jclass* offlineRegionUpdateMetadataCallbackClass = &jni::FindClass(env, "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback"); - updateMetadataOnUpdateMethodId = &jni::GetMethodID(env, *offlineRegionUpdateMetadataCallbackClass, "onUpdate", "([B)V"); - updateMetadataOnErrorMethodId = &jni::GetMethodID(env, *offlineRegionUpdateMetadataCallbackClass, "onError", "(Ljava/lang/String;)V"); - - // Offline end - - char release[PROP_VALUE_MAX] = ""; - __system_property_get("ro.build.version.release", release); - androidRelease = std::string(release); + // Offline + OfflineManager::registerNative(env); + OfflineRegion::registerNative(env); + OfflineRegionDefinition::registerNative(env); + OfflineTilePyramidRegionDefinition::registerNative(env); + OfflineRegionError::registerNative(env); + OfflineRegionStatus::registerNative(env); } } // namespace android diff --git a/platform/android/src/jni.hpp b/platform/android/src/jni.hpp index d12030f3c1..f0c113f754 100644 --- a/platform/android/src/jni.hpp +++ b/platform/android/src/jni.hpp @@ -14,15 +14,9 @@ extern JavaVM* theJVM; extern std::string cachePath; extern std::string dataPath; extern std::string apkPath; -extern std::string androidRelease; -extern jmethodID onInvalidateId; -extern jmethodID onMapChangedId; -extern jmethodID onFpsChangedId; -extern jmethodID onSnapshotReadyId; - -extern bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName); -extern void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach); +bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName); +void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach); extern void registerNatives(JavaVM* vm); diff --git a/platform/android/src/jni/generic_global_ref_deleter.hpp b/platform/android/src/jni/generic_global_ref_deleter.hpp new file mode 100644 index 0000000000..4e53e0a0ce --- /dev/null +++ b/platform/android/src/jni/generic_global_ref_deleter.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include + +#include "../attach_env.hpp" + +namespace mbgl { +namespace android { + +// A deleter that doesn't retain an JNIEnv handle but instead tries to attach the JVM. This means +// it can be used on any thread to delete a global ref. +struct GenericGlobalRefDeleter { + void operator()(jni::jobject* p) const { + if (p) { + auto env = AttachEnv(); + env->DeleteGlobalRef(jni::Unwrap(p)); + } + } +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/native_map_view.cpp b/platform/android/src/native_map_view.cpp index b36b477f2f..a0bd06345f 100755 --- a/platform/android/src/native_map_view.cpp +++ b/platform/android/src/native_map_view.cpp @@ -1,6 +1,4 @@ #include "native_map_view.hpp" -#include "jni.hpp" -#include "default_file_source.hpp" #include #include @@ -11,90 +9,91 @@ #include -#include -#include -#include -#include +#include +#include + +#include + #include +#include #include #include +#include +#include +#include #include #include +#include +#include +#include + +#include "conversion/conversion.hpp" +#include "conversion/collection.hpp" +#include "geometry/conversion/feature.hpp" +#include "jni.hpp" +#include "attach_env.hpp" #include "bitmap.hpp" +#include "run_loop_impl.hpp" +#include "java/util.hpp" namespace mbgl { namespace android { -NativeMapView::NativeMapView(JNIEnv *env_, jobject obj_, float pixelRatio, int availableProcessors_, size_t totalMemory_) - : env(env_), - availableProcessors(availableProcessors_), - totalMemory(totalMemory_), - fileSource(defaultFileSource(mbgl::android::cachePath + "/mbgl-offline.db", mbgl::android::apkPath)), - threadPool(sharedThreadPool()) { - - assert(env_ != nullptr); - assert(obj_ != nullptr); - - if (env->GetJavaVM(&vm) < 0) { - env->ExceptionDescribe(); - return; - } - - obj = env->NewWeakGlobalRef(obj_); - if (obj == nullptr) { - env->ExceptionDescribe(); +NativeMapView::NativeMapView(jni::JNIEnv& _env, jni::Object _obj, jni::Object jFileSource, + jni::jfloat _pixelRatio, jni::jint _availableProcessors, jni::jlong _totalMemory) : + javaPeer(_obj.NewWeakGlobalRef(_env)), + pixelRatio(_pixelRatio), + availableProcessors(_availableProcessors), + totalMemory(_totalMemory), + threadPool(sharedThreadPool()) { + + // Get a reference to the JavaVM for callbacks + if (_env.GetJavaVM(&vm) < 0) { + _env.ExceptionDescribe(); return; } + // Create the core map map = std::make_unique( *this, mbgl::Size{ static_cast(width), static_cast(height) }, - pixelRatio, fileSource, *threadPool, MapMode::Continuous); + pixelRatio, mbgl::android::FileSource::getDefaultFileSource(_env, jFileSource) + , *threadPool, MapMode::Continuous); + //Calculate a fitting cache size based on device parameters float zoomFactor = map->getMaxZoom() - map->getMinZoom() + 1; float cpuFactor = availableProcessors; float memoryFactor = static_cast(totalMemory) / 1000.0f / 1000.0f / 1000.0f; float sizeFactor = (static_cast(map->getSize().width) / mbgl::util::tileSize) * - (static_cast(map->getSize().height) / mbgl::util::tileSize); - - size_t cacheSize = zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5f; + (static_cast(map->getSize().height) / mbgl::util::tileSize); - map->setSourceTileCacheSize(cacheSize); + map->setSourceTileCacheSize(zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5f); } +/** + * Called through NativeMapView#destroy() + */ NativeMapView::~NativeMapView() { - terminateContext(); - destroySurface(); - terminateDisplay(); - - assert(vm != nullptr); - assert(obj != nullptr); + _terminateContext(); + _destroySurface(); + _terminateDisplay(); map.reset(); - env->DeleteWeakGlobalRef(obj); - - obj = nullptr; - env = nullptr; vm = nullptr; } -mbgl::Size NativeMapView::getFramebufferSize() const { - return { static_cast(fbWidth), static_cast(fbHeight) }; -} - -void NativeMapView::updateViewBinding() { - getContext().bindFramebuffer.setCurrentValue(0); - assert(mbgl::gl::value::BindFramebuffer::Get() == getContext().bindFramebuffer.getCurrentValue()); - getContext().viewport.setCurrentValue({ 0, 0, getFramebufferSize() }); - assert(mbgl::gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); -} - +/** + * From mbgl::View + */ void NativeMapView::bind() { getContext().bindFramebuffer = 0; getContext().viewport = { 0, 0, getFramebufferSize() }; } +/** + * From mbgl::Backend. + */ void NativeMapView::activate() { if (active++) { return; @@ -123,6 +122,9 @@ void NativeMapView::activate() { } } +/** + * From mbgl::Backend. + */ void NativeMapView::deactivate() { if (--active) { return; @@ -147,17 +149,57 @@ void NativeMapView::deactivate() { } } +/** + * From mbgl::Backend. Callback to java NativeMapView#onInvalidate(). + * + * May be called from any thread + */ void NativeMapView::invalidate() { + android::UniqueEnv _env = android::AttachEnv(); + static auto onInvalidate = javaClass.GetMethod(*_env, "onInvalidate"); + javaPeer->Call(*_env, onInvalidate); +} + +/** + * From mbgl::Backend. Callback to java NativeMapView#onMapChanged(int). + * + * May be called from any thread + */ +void NativeMapView::notifyMapChange(mbgl::MapChange change) { assert(vm != nullptr); - assert(obj != nullptr); - env->CallVoidMethod(obj, onInvalidateId); - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); - } + android::UniqueEnv _env = android::AttachEnv(); + static auto onMapChanged = javaClass.GetMethod(*_env, "onMapChanged"); + javaPeer->Call(*_env, onMapChanged, (int) change); } -void NativeMapView::render() { +// JNI Methods // + +void NativeMapView::initializeDisplay(jni::JNIEnv&) { + _initializeDisplay(); +} + +void NativeMapView::terminateDisplay(jni::JNIEnv&) { + _terminateDisplay(); +} + +void NativeMapView::initializeContext(jni::JNIEnv&) { + _initializeContext(); +} + +void NativeMapView::terminateContext(jni::JNIEnv&) { + _terminateContext(); +} + +void NativeMapView::createSurface(jni::JNIEnv& env, jni::Object<> _surface) { + _createSurface(ANativeWindow_fromSurface(&env, jni::Unwrap(*_surface))); +} + +void NativeMapView::destroySurface(jni::JNIEnv&) { + _destroySurface(); +} + +void NativeMapView::render(jni::JNIEnv& env) { BackendScope guard(*this); if (framebufferSizeChanged) { @@ -173,13 +215,12 @@ void NativeMapView::render() { // take snapshot auto image = getContext().readFramebuffer(getFramebufferSize()); - auto bitmap = Bitmap::CreateBitmap(*env, std::move(image)); + auto bitmap = Bitmap::CreateBitmap(env, std::move(image)); // invoke Mapview#OnSnapshotReady - env->CallVoidMethod(obj, onSnapshotReadyId, jni::Unwrap(*bitmap)); - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); - } + android::UniqueEnv _env = android::AttachEnv(); + static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); + javaPeer->Call(*_env, onSnapshotReady, bitmap); } if ((display != EGL_NO_DISPLAY) && (surface != EGL_NO_SURFACE)) { @@ -195,13 +236,611 @@ void NativeMapView::render() { } } -mbgl::Map &NativeMapView::getMap() { return *map; } +void NativeMapView::update(jni::JNIEnv&) { + invalidate(); +} + +void NativeMapView::resizeView(jni::JNIEnv&, int w, int h) { + width = w; + height = h; + map->setSize({ static_cast(width), static_cast(height) }); +} + +void NativeMapView::resizeFramebuffer(jni::JNIEnv&, int w, int h) { + fbWidth = w; + fbHeight = h; + framebufferSizeChanged = true; + invalidate(); +} + +jni::String NativeMapView::getStyleUrl(jni::JNIEnv& env) { + return jni::Make(env, map->getStyleURL()); +} + +void NativeMapView::setStyleUrl(jni::JNIEnv& env, jni::String url) { + map->setStyleURL(jni::Make(env, url)); +} + +jni::String NativeMapView::getStyleJson(jni::JNIEnv& env) { + return jni::Make(env, map->getStyleJSON()); +} + +void NativeMapView::setStyleJson(jni::JNIEnv& env, jni::String json) { + map->setStyleJSON(jni::Make(env, json)); +} + +void NativeMapView::cancelTransitions(jni::JNIEnv&) { + map->cancelTransitions(); +} + +void NativeMapView::setGestureInProgress(jni::JNIEnv&, jni::jboolean inProgress) { + map->setGestureInProgress(inProgress); +} + +void NativeMapView::moveBy(jni::JNIEnv&, jni::jdouble dx, jni::jdouble dy, jni::jlong duration) { + mbgl::AnimationOptions animationOptions; + if (duration > 0) { + animationOptions.duration.emplace(mbgl::Milliseconds(duration)); + animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0.3, 0.6, 1.0 }); + } + map->moveBy({dx, dy}, animationOptions); +} + +void NativeMapView::jumpTo(jni::JNIEnv&, jni::jdouble angle, jni::jdouble latitude, jni::jdouble longitude, jni::jdouble pitch, jni::jdouble zoom) { + mbgl::CameraOptions options; + if (angle != -1) { + options.angle = (-angle * M_PI) / 180; + } + options.center = mbgl::LatLng(latitude, longitude); + options.padding = insets; + if (pitch != -1) { + options.pitch = pitch * M_PI / 180; + } + if (zoom != -1) { + options.zoom = zoom; + } + + map->jumpTo(options); +} + +void NativeMapView::easeTo(jni::JNIEnv&, jni::jdouble angle, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom, jni::jboolean easing) { + mbgl::CameraOptions cameraOptions; + if (angle != -1) { + cameraOptions.angle = (-angle * M_PI) / 180; + } + cameraOptions.center = mbgl::LatLng(latitude, longitude); + cameraOptions.padding = insets; + if (pitch != -1) { + cameraOptions.pitch = pitch * M_PI / 180; + } + if (zoom != -1) { + cameraOptions.zoom = zoom; + } + + mbgl::AnimationOptions animationOptions; + animationOptions.duration.emplace(mbgl::Duration(duration)); + if (!easing) { + // add a linear interpolator instead of easing + animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0, 1, 1 }); + } + + map->easeTo(cameraOptions, animationOptions); +} + +void NativeMapView::flyTo(jni::JNIEnv&, jni::jdouble angle, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom) { + mbgl::CameraOptions cameraOptions; + if (angle != -1) { + cameraOptions.angle = (-angle * M_PI) / 180 ; + } + cameraOptions.center = mbgl::LatLng(latitude, longitude); + cameraOptions.padding = insets; + if (pitch != -1) { + cameraOptions.pitch = pitch * M_PI / 180; + } + if (zoom != -1) { + cameraOptions.zoom = zoom; + } + + mbgl::AnimationOptions animationOptions; + animationOptions.duration.emplace(mbgl::Duration(duration)); + map->flyTo(cameraOptions, animationOptions); +} + +jni::Object NativeMapView::getLatLng(JNIEnv& env) { + mbgl::LatLng latLng = map->getLatLng(insets); + return LatLng::New(env, latLng.latitude, latLng.longitude); +} + +void NativeMapView::setLatLng(jni::JNIEnv&, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration) { + map->setLatLng(mbgl::LatLng(latitude, longitude), insets, mbgl::Milliseconds(duration)); +} + +void NativeMapView::setReachability(jni::JNIEnv&, jni::jboolean reachable) { + if (reachable) { + mbgl::NetworkStatus::Reachable(); + } +} + +void NativeMapView::resetPosition(jni::JNIEnv&) { + map->resetPosition(); +} + +jni::jdouble NativeMapView::getPitch(jni::JNIEnv&) { + return map->getPitch(); +} + +void NativeMapView::setPitch(jni::JNIEnv&, jni::jdouble pitch, jni::jlong duration) { + map->setPitch(pitch, mbgl::Milliseconds(duration)); +} + +void NativeMapView::scaleBy(jni::JNIEnv&, jni::jdouble ds, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { + mbgl::ScreenCoordinate center(cx, cy); + map->scaleBy(ds, center, mbgl::Milliseconds(duration)); +} + +void NativeMapView::setScale(jni::JNIEnv&, jni::jdouble scale, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { + mbgl::ScreenCoordinate center(cx, cy); + map->setScale(scale, center, mbgl::Milliseconds(duration)); +} + +jni::jdouble NativeMapView::getScale(jni::JNIEnv&) { + return map->getScale(); +} + +void NativeMapView::setZoom(jni::JNIEnv&, jni::jdouble zoom, jni::jlong duration) { + map->setZoom(zoom, mbgl::Milliseconds(duration)); +} + +jni::jdouble NativeMapView::getZoom(jni::JNIEnv&) { + return map->getZoom(); +} + +void NativeMapView::resetZoom(jni::JNIEnv&) { + map->resetZoom(); +} + +void NativeMapView::setMinZoom(jni::JNIEnv&, jni::jdouble zoom) { + map->setMinZoom(zoom); +} + +jni::jdouble NativeMapView::getMinZoom(jni::JNIEnv&) { + return map->getMinZoom(); +} + +void NativeMapView::setMaxZoom(jni::JNIEnv&, jni::jdouble zoom) { + map->setMaxZoom(zoom); +} + +jni::jdouble NativeMapView::getMaxZoom(jni::JNIEnv&) { + return map->getMaxZoom(); +} + +void NativeMapView::rotateBy(jni::JNIEnv&, jni::jdouble sx, jni::jdouble sy, jni::jdouble ex, jni::jdouble ey, jni::jlong duration) { + mbgl::ScreenCoordinate first(sx, sy); + mbgl::ScreenCoordinate second(ex, ey); + map->rotateBy(first, second, mbgl::Milliseconds(duration)); +} + +void NativeMapView::setBearing(jni::JNIEnv&, jni::jdouble degrees, jni::jlong duration) { + map->setBearing(degrees, mbgl::Milliseconds(duration)); +} + +void NativeMapView::setBearingXY(jni::JNIEnv&, jni::jdouble degrees, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { + mbgl::ScreenCoordinate center(cx, cy); + map->setBearing(degrees, center, mbgl::Milliseconds(duration)); +} + +jni::jdouble NativeMapView::getBearing(jni::JNIEnv&) { + return map->getBearing(); +} + +void NativeMapView::resetNorth(jni::JNIEnv&) { + map->resetNorth(); +} + +void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, jni::Array> coordinates, jni::Object padding, jdouble direction, jni::jlong duration) { + NullCheck(env, &coordinates); + std::size_t count = coordinates.Length(env); + + std::vector latLngs; + latLngs.reserve(count); + + for (std::size_t i = 0; i < count; i++) { + auto latLng = coordinates.Get(env, i); + latLngs.push_back(LatLng::getLatLng(env, latLng)); + jni::DeleteLocalRef(env, latLng); + } + + mbgl::EdgeInsets mbglInsets = { RectF::getTop(env, padding), RectF::getLeft(env, padding), RectF::getBottom(env, padding), RectF::getRight(env, padding) }; + mbgl::CameraOptions cameraOptions = map->cameraForLatLngs(latLngs, mbglInsets); + if (direction >= 0) { + // convert from degrees to radians + cameraOptions.angle = (-direction * M_PI) / 180; + } + + mbgl::AnimationOptions animationOptions; + if (duration > 0) { + animationOptions.duration.emplace(mbgl::Milliseconds(duration)); + // equivalent to kCAMediaTimingFunctionDefault in iOS + animationOptions.easing.emplace(mbgl::util::UnitBezier { 0.25, 0.1, 0.25, 0.1 }); + } + + map->easeTo(cameraOptions, animationOptions); +} + +void NativeMapView::setContentPadding(JNIEnv&, double top, double left, double bottom, double right) { + insets = {top, left, bottom, right}; +} + +void NativeMapView::scheduleSnapshot(jni::JNIEnv&) { + snapshot = true; +} + +void NativeMapView::enableFps(jni::JNIEnv&, jni::jboolean enable) { + fpsEnabled = enable; +} + +jni::Array NativeMapView::getCameraValues(jni::JNIEnv& env) { + //Create buffer with values + jdouble buf[5]; + mbgl::LatLng latLng = map->getLatLng(insets); + buf[0] = latLng.latitude; + buf[1] = latLng.longitude; + buf[2] = -map->getBearing(); + buf[3] = map->getPitch(); + buf[4] = map->getZoom(); + + //Convert to Java array + auto output = jni::Array::New(env, 5); + jni::SetArrayRegion(env, *output, 0, 5, buf); + + return output; +} + +void NativeMapView::updateMarker(jni::JNIEnv& env, jni::jlong markerId, jni::jdouble lat, jni::jdouble lon, jni::String jid) { + if (markerId == -1) { + return; + } + + std::string iconId = jni::Make(env, jid); + // Because Java only has int, not unsigned int, we need to bump the annotation id up to a long. + map->updateAnnotation(markerId, mbgl::SymbolAnnotation { mbgl::Point(lon, lat), iconId }); +} + +jni::Array NativeMapView::addMarkers(jni::JNIEnv& env, jni::Array> jmarkers) { + jni::NullCheck(env, &jmarkers); + std::size_t len = jmarkers.Length(env); + + std::vector ids; + ids.reserve(len); + + for (std::size_t i = 0; i < len; i++) { + jni::Object marker = jmarkers.Get(env, i); + ids.push_back(map->addAnnotation(mbgl::SymbolAnnotation { + Marker::getPosition(env, marker), + Marker::getIconId(env, marker) + })); + + jni::DeleteLocalRef(env, marker); + } + + auto result = jni::Array::New(env, len); + result.SetRegion>(env, 0, ids); + + return result; +} + +void NativeMapView::onLowMemory(JNIEnv&) { + map->onLowMemory(); +} + +using DebugOptions = mbgl::MapDebugOptions; + +void NativeMapView::setDebug(JNIEnv&, jni::jboolean debug) { + DebugOptions debugOptions = debug ? DebugOptions::TileBorders | DebugOptions::ParseStatus | DebugOptions::Collision + : DebugOptions::NoDebug; + map->setDebug(debugOptions); + fpsEnabled = debug; +} + +void NativeMapView::cycleDebugOptions(JNIEnv&) { + map->cycleDebugOptions(); + fpsEnabled = map->getDebug() != DebugOptions::NoDebug; +} + +jni::jboolean NativeMapView::getDebug(JNIEnv&) { + return map->getDebug() != DebugOptions::NoDebug; +} + +jni::jboolean NativeMapView::isFullyLoaded(JNIEnv&) { + return map->isFullyLoaded(); +} + +jni::jdouble NativeMapView::getMetersPerPixelAtLatitude(JNIEnv&, jni::jdouble lat, jni::jdouble zoom) { + return map->getMetersPerPixelAtLatitude(lat, zoom); +} + +jni::Object NativeMapView::projectedMetersForLatLng(JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude) { + mbgl::ProjectedMeters projectedMeters = map->projectedMetersForLatLng(mbgl::LatLng(latitude, longitude)); + return ProjectedMeters::New(env, projectedMeters.northing, projectedMeters.easting); +} + +jni::Object NativeMapView::pixelForLatLng(JNIEnv& env, jdouble latitude, jdouble longitude) { + mbgl::ScreenCoordinate pixel = map->pixelForLatLng(mbgl::LatLng(latitude, longitude)); + return PointF::New(env, static_cast(pixel.x), static_cast(pixel.y)); +} + +jni::Object NativeMapView::latLngForProjectedMeters(JNIEnv& env, jdouble northing, jdouble easting) { + mbgl::LatLng latLng = map->latLngForProjectedMeters(mbgl::ProjectedMeters(northing, easting)); + return LatLng::New(env, latLng.latitude, latLng.longitude); +} + +jni::Object NativeMapView::latLngForPixel(JNIEnv& env, jfloat x, jfloat y) { + mbgl::LatLng latLng = map->latLngForPixel(mbgl::ScreenCoordinate(x, y)); + return LatLng::New(env, latLng.latitude, latLng.longitude); +} + +jni::Array NativeMapView::addPolylines(JNIEnv& env, jni::Array> polylines) { + NullCheck(env, &polylines); + std::size_t len = polylines.Length(env); + + std::vector ids; + ids.reserve(len); + + for (std::size_t i = 0; i < len; i++) { + auto polyline = polylines.Get(env, i); + + mbgl::LineAnnotation annotation = Polyline::toAnnotation(env, polyline); + ids.push_back(map->addAnnotation(annotation)); + + jni::DeleteLocalRef(env, polyline); + } + + auto result = jni::Array::New(env, len); + result.SetRegion>(env, 0, ids); + + return result; +} + + +jni::Array NativeMapView::addPolygons(JNIEnv& env, jni::Array> polygons) { + NullCheck(env, &polygons); + std::size_t len = polygons.Length(env); + + std::vector ids; + ids.reserve(len); + + for (std::size_t i = 0; i < len; i++) { + auto polygon = polygons.Get(env, i); + + mbgl::FillAnnotation annotation = Polygon::toAnnotation(env, polygon); + ids.push_back(map->addAnnotation(annotation)); + + jni::DeleteLocalRef(env, polygon); + } + + auto result = jni::Array::New(env, len); + result.SetRegion>(env, 0, ids); + + return result; +} + +//TODO: Move to Polyline class and make native peer +void NativeMapView::updatePolyline(JNIEnv& env, jlong polylineId, jni::Object polyline) { + mbgl::LineAnnotation annotation = Polyline::toAnnotation(env, polyline); + map->updateAnnotation(polylineId, annotation); +} + +//TODO: Move to Polygon class and make native peer +void NativeMapView::updatePolygon(JNIEnv& env, jlong polygonId, jni::Object polygon) { + mbgl::FillAnnotation annotation = Polygon::toAnnotation(env, polygon); + map->updateAnnotation(polygonId, annotation); +} + +void NativeMapView::removeAnnotations(JNIEnv& env, jni::Array ids) { + NullCheck(env, &ids); + std::size_t len = ids.Length(env); + auto elements = jni::GetArrayElements(env, *ids); + jlong* jids = std::get<0>(elements).get(); + + for (std::size_t i = 0; i < len; i++) { + if(jids[i] == -1L) { + continue; + } + map->removeAnnotation(jids[i]); + } +} + +void NativeMapView::addAnnotationIcon(JNIEnv& env, jni::String symbol, jint w, jint h, jfloat scale, jni::Array jpixels) { + const std::string symbolName = jni::Make(env, symbol); + + NullCheck(env, &jpixels); + std::size_t size = jpixels.Length(env); + + mbgl::PremultipliedImage premultipliedImage({ static_cast(w), static_cast(h) }); + if (premultipliedImage.bytes() != uint32_t(size)) { + throw mbgl::util::SpriteImageException("Sprite image pixel count mismatch"); + } + + jni::GetArrayRegion(env, *jpixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); + auto iconImage = std::make_shared(std::move(premultipliedImage), float(scale)); + map->addAnnotationIcon(symbolName, iconImage); +} -mbgl::DefaultFileSource& NativeMapView::getFileSource() { - return fileSource; +jdouble NativeMapView::getTopOffsetPixelsForAnnotationSymbol(JNIEnv& env, jni::String symbolName) { + return map->getTopOffsetPixelsForAnnotationIcon(jni::Make(env, symbolName)); } -void NativeMapView::initializeDisplay() { +jlong NativeMapView::getTransitionDuration(JNIEnv&) { + const auto transitionOptions = map->getTransitionOptions(); + return transitionOptions.duration.value_or(mbgl::Duration::zero()).count(); +} + +void NativeMapView::setTransitionDuration(JNIEnv&, jlong duration) { + auto transitionOptions = map->getTransitionOptions(); + transitionOptions.duration = std::chrono::duration_cast(std::chrono::duration(duration)); + map->setTransitionOptions(transitionOptions); +} + +jlong NativeMapView::getTransitionDelay(JNIEnv&) { + const auto transitionOptions = map->getTransitionOptions(); + return transitionOptions.delay.value_or(mbgl::Duration::zero()).count(); +} + +void NativeMapView::setTransitionDelay(JNIEnv&, jlong delay) { + auto transitionOptions = map->getTransitionOptions(); + transitionOptions.delay = std::chrono::duration_cast(std::chrono::duration(delay)); + map->setTransitionOptions(transitionOptions); +} + +jni::Array NativeMapView::queryPointAnnotations(JNIEnv& env, jni::Object rect) { + // Convert input + mbgl::ScreenBox box = { + { RectF::getLeft(env, rect), RectF::getTop(env, rect) }, + { RectF::getRight(env, rect), RectF::getBottom(env, rect) }, + }; + + // Assume only points for now + mbgl::AnnotationIDs ids = map->queryPointAnnotations(box); + + // Convert result + std::vector longIds(ids.begin(), ids.end()); + auto result = jni::Array::New(env, ids.size()); + result.SetRegion>(env, 0, longIds); + + return result; +} + +jni::Array> NativeMapView::queryRenderedFeaturesForPoint(JNIEnv& env, jni::jfloat x, jni::jfloat y, jni::Array layerIds) { + using namespace mbgl::android::conversion; + using namespace mapbox::geometry; + + mbgl::optional> layers; + if (layerIds != nullptr && layerIds.Length(env) > 0) { + layers = toVector(env, layerIds); + } + point point = {x, y}; + + return *convert>, std::vector>(env, map->queryRenderedFeatures(point, layers)); +} + +jni::Array> NativeMapView::queryRenderedFeaturesForBox(JNIEnv& env, jni::jfloat left, jni::jfloat top, jni::jfloat right, jni::jfloat bottom, jni::Array layerIds) { + using namespace mbgl::android::conversion; + using namespace mapbox::geometry; + + mbgl::optional> layers; + if (layerIds != nullptr && layerIds.Length(env) > 0) { + layers = toVector(env, layerIds); + } + box box = { point{ left, top}, point{ right, bottom } }; + + return *convert>, std::vector>(env, map->queryRenderedFeatures(box, layers)); +} + +jni::Object NativeMapView::getLayer(JNIEnv& env, jni::String layerId) { + + // Find the layer + mbgl::style::Layer* coreLayer = map->getLayer(jni::Make(env, layerId)); + if (!coreLayer) { + mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); + return jni::Object(); + } + + // Create and return the layer's native peer + return jni::Object(createJavaLayerPeer(env, *map, *coreLayer)); +} + +void NativeMapView::addLayer(JNIEnv& env, jlong nativeLayerPtr, jni::String before) { + assert(nativeLayerPtr != 0); + + Layer *layer = reinterpret_cast(nativeLayerPtr); + try { + layer->addToMap(*map, before ? mbgl::optional(jni::Make(env, before)) : mbgl::optional()); + } catch (const std::runtime_error& error) { + jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + } +} + +/** + * Remove by layer id. Ownership is not transferred back + */ +void NativeMapView::removeLayerById(JNIEnv& env, jni::String id) { + map->removeLayer(jni::Make(env, id)); +} + +/** + * Remove with wrapper object id. Ownership is transferred back to the wrapper + */ +void NativeMapView::removeLayer(JNIEnv&, jlong layerPtr) { + assert(layerPtr != 0); + + mbgl::android::Layer *layer = reinterpret_cast(layerPtr); + std::unique_ptr coreLayer = map->removeLayer(layer->get().getID()); + if (coreLayer) { + layer->setLayer(std::move(coreLayer)); + } +} + + +jni::Object NativeMapView::getSource(JNIEnv& env, jni::String sourceId) { + // Find the source + mbgl::style::Source* coreSource = map->getSource(jni::Make(env, sourceId)); + if (!coreSource) { + mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); + return jni::Object(); + } + + // Create and return the source's native peer + return jni::Object(createJavaSourcePeer(env, *map, *coreSource)); +} + +void NativeMapView::addSource(JNIEnv& env, jni::jlong sourcePtr) { + assert(sourcePtr != 0); + + Source *source = reinterpret_cast(sourcePtr); + try { + source->addToMap(*map); + } catch (const std::runtime_error& error) { + jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); + } +} + +void NativeMapView::removeSourceById(JNIEnv& env, jni::String id) { + map->removeSource(jni::Make(env, id)); +} + +void NativeMapView::removeSource(JNIEnv&, jlong sourcePtr) { + assert(sourcePtr != 0); + + mbgl::android::Source *source = reinterpret_cast(sourcePtr); + std::unique_ptr coreSource = map->removeSource(source->get().getID()); + if (coreSource) { + source->setSource(std::move(coreSource)); + } +} + +void NativeMapView::addImage(JNIEnv& env, jni::String name, jni::jint w, jni::jint h, jni::jfloat scale, jni::Array pixels) { + jni::NullCheck(env, &pixels); + std::size_t size = pixels.Length(env); + + mbgl::PremultipliedImage premultipliedImage({ static_cast(w), static_cast(h) }); + if (premultipliedImage.bytes() != uint32_t(size)) { + throw mbgl::util::SpriteImageException("Sprite image pixel count mismatch"); + } + + jni::GetArrayRegion(env, *pixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); + auto spriteImage = std::make_unique(std::move(premultipliedImage), float(scale)); + + map->addImage(jni::Make(env, name), std::move(spriteImage)); +} + +void NativeMapView::removeImage(JNIEnv& env, jni::String name) { + map->removeImage(jni::Make(env, name)); +} + +// Private methods // + +void NativeMapView::_initializeDisplay() { assert(display == EGL_NO_DISPLAY); assert(config == nullptr); assert(format < 0); @@ -286,145 +925,6 @@ void NativeMapView::initializeDisplay() { } } -void NativeMapView::terminateDisplay() { - if (display != EGL_NO_DISPLAY) { - // Destroy the surface first, if it still exists. This call needs a valid surface. - if (surface != EGL_NO_SURFACE) { - if (!eglDestroySurface(display, surface)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroySurface() returned error %d", - eglGetError()); - throw std::runtime_error("eglDestroySurface() failed"); - } - surface = EGL_NO_SURFACE; - } - - if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { - mbgl::Log::Error(mbgl::Event::OpenGL, - "eglMakeCurrent(EGL_NO_CONTEXT) returned error %d", eglGetError()); - throw std::runtime_error("eglMakeCurrent() failed"); - } - - if (!eglTerminate(display)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglTerminate() returned error %d", - eglGetError()); - throw std::runtime_error("eglTerminate() failed"); - } - } - - display = EGL_NO_DISPLAY; - config = nullptr; - format = -1; -} - -void NativeMapView::initializeContext() { - assert(display != EGL_NO_DISPLAY); - assert(context == EGL_NO_CONTEXT); - assert(config != nullptr); - - const EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; - context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs); - if (context == EGL_NO_CONTEXT) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglCreateContext() returned error %d", - eglGetError()); - throw std::runtime_error("eglCreateContext() failed"); - } -} - -void NativeMapView::terminateContext() { - if (display != EGL_NO_DISPLAY) { - - if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { - mbgl::Log::Error(mbgl::Event::OpenGL, - "eglMakeCurrent(EGL_NO_CONTEXT) returned error %d", eglGetError()); - throw std::runtime_error("eglMakeCurrent() failed"); - } - - if (context != EGL_NO_CONTEXT) { - if (!eglDestroyContext(display, context)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroyContext() returned error %d", - eglGetError()); - throw std::runtime_error("eglDestroyContext() failed"); - } - } - } - - context = EGL_NO_CONTEXT; -} - -void NativeMapView::createSurface(ANativeWindow *window_) { - assert(window == nullptr); - assert(window_ != nullptr); - window = window_; - - assert(display != EGL_NO_DISPLAY); - assert(surface == EGL_NO_SURFACE); - assert(config != nullptr); - assert(format >= 0); - - ANativeWindow_setBuffersGeometry(window, 0, 0, format); - - const EGLint surfaceAttribs[] = {EGL_NONE}; - surface = eglCreateWindowSurface(display, config, window, surfaceAttribs); - if (surface == EGL_NO_SURFACE) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglCreateWindowSurface() returned error %d", - eglGetError()); - throw std::runtime_error("eglCreateWindowSurface() failed"); - } - - if (!firstTime) { - firstTime = true; - - BackendScope guard(*this); - - if (!eglMakeCurrent(display, surface, surface, context)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglMakeCurrent() returned error %d", - eglGetError()); - throw std::runtime_error("eglMakeCurrent() failed"); - } - - mbgl::gl::InitializeExtensions([] (const char * name) { - return reinterpret_cast(eglGetProcAddress(name)); - }); - } -} - -void NativeMapView::destroySurface() { - if (surface != EGL_NO_SURFACE) { - if (!eglDestroySurface(display, surface)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroySurface() returned error %d", - eglGetError()); - throw std::runtime_error("eglDestroySurface() failed"); - } - } - - surface = EGL_NO_SURFACE; - - if (window != nullptr) { - ANativeWindow_release(window); - window = nullptr; - } -} - -void NativeMapView::scheduleTakeSnapshot() { - snapshot = true; -} - -// Speed -/* -typedef enum { - Format16Bit = 0, - Format32BitNoAlpha = 1, - Format32BitAlpha = 2, - Format24Bit = 3, - Unknown = 4 -} BufferFormat; - -typedef enum { - Format16Depth8Stencil = 0, - Format24Depth8Stencil = 1, -} DepthStencilFormat; -*/ - // Quality typedef enum { Format16Bit = 3, @@ -589,18 +1089,134 @@ EGLConfig NativeMapView::chooseConfig(const EGLConfig configs[], EGLint numConfi return configId; } -void NativeMapView::notifyMapChange(mbgl::MapChange change) { - assert(vm != nullptr); - assert(obj != nullptr); +void NativeMapView::_terminateDisplay() { + if (display != EGL_NO_DISPLAY) { + // Destroy the surface first, if it still exists. This call needs a valid surface. + if (surface != EGL_NO_SURFACE) { + if (!eglDestroySurface(display, surface)) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroySurface() returned error %d", + eglGetError()); + throw std::runtime_error("eglDestroySurface() failed"); + } + surface = EGL_NO_SURFACE; + } - env->CallVoidMethod(obj, onMapChangedId, change); - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); + if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { + mbgl::Log::Error(mbgl::Event::OpenGL, + "eglMakeCurrent(EGL_NO_CONTEXT) returned error %d", eglGetError()); + throw std::runtime_error("eglMakeCurrent() failed"); + } + + if (!eglTerminate(display)) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglTerminate() returned error %d", + eglGetError()); + throw std::runtime_error("eglTerminate() failed"); + } } + + display = EGL_NO_DISPLAY; + config = nullptr; + format = -1; } -void NativeMapView::enableFps(bool enable) { - fpsEnabled = enable; +void NativeMapView::_initializeContext() { + assert(display != EGL_NO_DISPLAY); + assert(context == EGL_NO_CONTEXT); + assert(config != nullptr); + + const EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; + context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs); + if (context == EGL_NO_CONTEXT) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglCreateContext() returned error %d", + eglGetError()); + throw std::runtime_error("eglCreateContext() failed"); + } +} + +void NativeMapView::_terminateContext() { + if (display != EGL_NO_DISPLAY) { + + if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { + mbgl::Log::Error(mbgl::Event::OpenGL, + "eglMakeCurrent(EGL_NO_CONTEXT) returned error %d", eglGetError()); + throw std::runtime_error("eglMakeCurrent() failed"); + } + + if (context != EGL_NO_CONTEXT) { + if (!eglDestroyContext(display, context)) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroyContext() returned error %d", + eglGetError()); + throw std::runtime_error("eglDestroyContext() failed"); + } + } + } + + context = EGL_NO_CONTEXT; +} + +void NativeMapView::_createSurface(ANativeWindow *window_) { + assert(window == nullptr); + assert(window_ != nullptr); + window = window_; + + assert(display != EGL_NO_DISPLAY); + assert(surface == EGL_NO_SURFACE); + assert(config != nullptr); + assert(format >= 0); + + ANativeWindow_setBuffersGeometry(window, 0, 0, format); + + const EGLint surfaceAttribs[] = {EGL_NONE}; + surface = eglCreateWindowSurface(display, config, window, surfaceAttribs); + if (surface == EGL_NO_SURFACE) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglCreateWindowSurface() returned error %d", + eglGetError()); + throw std::runtime_error("eglCreateWindowSurface() failed"); + } + + if (firstRender) { + firstRender = false; + + BackendScope guard(*this); + + if (!eglMakeCurrent(display, surface, surface, context)) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglMakeCurrent() returned error %d", + eglGetError()); + throw std::runtime_error("eglMakeCurrent() failed"); + } + + mbgl::gl::InitializeExtensions([] (const char * name) { + return reinterpret_cast(eglGetProcAddress(name)); + }); + } +} + +void NativeMapView::_destroySurface() { + if (surface != EGL_NO_SURFACE) { + if (!eglDestroySurface(display, surface)) { + mbgl::Log::Error(mbgl::Event::OpenGL, "eglDestroySurface() returned error %d", + eglGetError()); + throw std::runtime_error("eglDestroySurface() failed"); + } + } + + surface = EGL_NO_SURFACE; + + if (window != nullptr) { + ANativeWindow_release(window); + window = nullptr; + } +} + +mbgl::Size NativeMapView::getFramebufferSize() const { + return { static_cast(fbWidth), static_cast(fbHeight) }; +} + +void NativeMapView::updateViewBinding() { + getContext().bindFramebuffer.setCurrentValue(0); + assert(mbgl::gl::value::BindFramebuffer::Get() == getContext().bindFramebuffer.getCurrentValue()); + getContext().viewport.setCurrentValue({ 0, 0, getFramebufferSize() }); + assert(mbgl::gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); } void NativeMapView::updateFps() { @@ -618,35 +1234,116 @@ void NativeMapView::updateFps() { if (currentTime - timeElapsed >= 1) { fps = frames / ((currentTime - timeElapsed) / 1E9); - mbgl::Log::Debug(mbgl::Event::Render, "FPS: %4.2f", fps); + mbgl::Log::Info(mbgl::Event::Render, "FPS: %4.2f", fps); timeElapsed = currentTime; frames = 0; } assert(vm != nullptr); - assert(obj != nullptr); - - env->CallVoidMethod(obj, onFpsChangedId, fps); - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); - } -} - -void NativeMapView::resizeView(int w, int h) { - width = w; - height = h; - map->setSize({ static_cast(width), static_cast(height) }); -} -void NativeMapView::resizeFramebuffer(int w, int h) { - fbWidth = w; - fbHeight = h; - framebufferSizeChanged = true; - invalidate(); + android::UniqueEnv _env = android::AttachEnv(); + static auto onFpsChanged = javaClass.GetMethod(*_env, "onFpsChanged"); + javaPeer->Call(*_env, onFpsChanged, fps); } -void NativeMapView::setInsets(mbgl::EdgeInsets insets_) { - insets = insets_; +// Static methods // + +jni::Class NativeMapView::javaClass; + +void NativeMapView::registerNative(jni::JNIEnv& env) { + // Lookup the class + NativeMapView::javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); + + #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer(env, NativeMapView::javaClass, "nativePtr", + std::make_unique, jni::Object, jni::jfloat, jni::jint, jni::jlong>, + "nativeInitialize", + "nativeDestroy", + METHOD(&NativeMapView::render, "nativeRender"), + METHOD(&NativeMapView::update, "nativeUpdate"), + METHOD(&NativeMapView::resizeView, "nativeResizeView"), + METHOD(&NativeMapView::resizeFramebuffer, "nativeResizeFramebuffer"), + METHOD(&NativeMapView::initializeDisplay, "nativeInitializeDisplay"), + METHOD(&NativeMapView::terminateDisplay, "nativeTerminateDisplay"), + METHOD(&NativeMapView::initializeContext, "nativeInitializeContext"), + METHOD(&NativeMapView::terminateContext, "nativeTerminateContext"), + METHOD(&NativeMapView::createSurface, "nativeCreateSurface"), + METHOD(&NativeMapView::destroySurface, "nativeDestroySurface"), + METHOD(&NativeMapView::getStyleUrl, "nativeGetStyleUrl"), + METHOD(&NativeMapView::setStyleUrl, "nativeSetStyleUrl"), + METHOD(&NativeMapView::getStyleJson, "nativeGetStyleJson"), + METHOD(&NativeMapView::setStyleJson, "nativeSetStyleJson"), + METHOD(&NativeMapView::cancelTransitions, "nativeCancelTransitions"), + METHOD(&NativeMapView::setGestureInProgress, "nativeSetGestureInProgress"), + METHOD(&NativeMapView::moveBy, "nativeMoveBy"), + METHOD(&NativeMapView::jumpTo, "nativeJumpTo"), + METHOD(&NativeMapView::easeTo, "nativeEaseTo"), + METHOD(&NativeMapView::flyTo, "nativeFlyTo"), + METHOD(&NativeMapView::getLatLng, "nativeGetLatLng"), + METHOD(&NativeMapView::setLatLng, "nativeSetLatLng"), + METHOD(&NativeMapView::setReachability, "nativeSetReachability"), + METHOD(&NativeMapView::resetPosition, "nativeResetPosition"), + METHOD(&NativeMapView::getPitch, "nativeGetPitch"), + METHOD(&NativeMapView::setPitch, "nativeSetPitch"), + METHOD(&NativeMapView::scaleBy, "nativeScaleBy"), + METHOD(&NativeMapView::getScale, "nativeGetScale"), + METHOD(&NativeMapView::setScale, "nativeSetScale"), + METHOD(&NativeMapView::getZoom, "nativeGetZoom"), + METHOD(&NativeMapView::setZoom, "nativeSetZoom"), + METHOD(&NativeMapView::resetZoom, "nativeResetZoom"), + METHOD(&NativeMapView::setMinZoom, "nativeSetMinZoom"), + METHOD(&NativeMapView::getMinZoom, "nativeGetMinZoom"), + METHOD(&NativeMapView::setMaxZoom, "nativeSetMaxZoom"), + METHOD(&NativeMapView::getMaxZoom, "nativeGetMaxZoom"), + METHOD(&NativeMapView::rotateBy, "nativeRotateBy"), + METHOD(&NativeMapView::setBearing, "nativeSetBearing"), + METHOD(&NativeMapView::setBearingXY, "nativeSetBearingXY"), + METHOD(&NativeMapView::getBearing, "nativeGetBearing"), + METHOD(&NativeMapView::resetNorth, "nativeResetNorth"), + METHOD(&NativeMapView::setVisibleCoordinateBounds, "nativeSetVisibleCoordinateBounds"), + METHOD(&NativeMapView::setContentPadding, "nativeSetContentPadding"), + METHOD(&NativeMapView::scheduleSnapshot, "nativeTakeSnapshot"), + METHOD(&NativeMapView::enableFps, "nativeSetEnableFps"), + METHOD(&NativeMapView::getCameraValues, "nativeGetCameraValues"), + METHOD(&NativeMapView::updateMarker, "nativeUpdateMarker"), + METHOD(&NativeMapView::addMarkers, "nativeAddMarkers"), + METHOD(&NativeMapView::setDebug, "nativeSetDebug"), + METHOD(&NativeMapView::cycleDebugOptions, "nativeCycleDebugOptions"), + METHOD(&NativeMapView::getDebug, "nativeGetDebug"), + METHOD(&NativeMapView::isFullyLoaded, "nativeIsFullyLoaded"), + METHOD(&NativeMapView::onLowMemory, "nativeOnLowMemory"), + METHOD(&NativeMapView::getMetersPerPixelAtLatitude, "nativeGetMetersPerPixelAtLatitude"), + METHOD(&NativeMapView::projectedMetersForLatLng, "nativeProjectedMetersForLatLng"), + METHOD(&NativeMapView::pixelForLatLng, "nativePixelForLatLng"), + METHOD(&NativeMapView::latLngForProjectedMeters, "nativeLatLngForProjectedMeters"), + METHOD(&NativeMapView::latLngForPixel, "nativeLatLngForPixel"), + METHOD(&NativeMapView::addPolylines, "nativeAddPolylines"), + METHOD(&NativeMapView::addPolygons, "nativeAddPolygons"), + METHOD(&NativeMapView::updatePolyline, "nativeUpdatePolyline"), + METHOD(&NativeMapView::updatePolygon, "nativeUpdatePolygon"), + METHOD(&NativeMapView::removeAnnotations, "nativeRemoveAnnotations"), + METHOD(&NativeMapView::addAnnotationIcon, "nativeAddAnnotationIcon"), + METHOD(&NativeMapView::getTopOffsetPixelsForAnnotationSymbol, "nativeGetTopOffsetPixelsForAnnotationSymbol"), + METHOD(&NativeMapView::getTransitionDuration, "nativeGetTransitionDuration"), + METHOD(&NativeMapView::setTransitionDuration, "nativeSetTransitionDuration"), + METHOD(&NativeMapView::getTransitionDelay, "nativeGetTransitionDelay"), + METHOD(&NativeMapView::setTransitionDelay, "nativeSetTransitionDelay"), + METHOD(&NativeMapView::queryPointAnnotations, "nativeQueryPointAnnotations"), + METHOD(&NativeMapView::queryRenderedFeaturesForPoint, "nativeQueryRenderedFeaturesForPoint"), + METHOD(&NativeMapView::queryRenderedFeaturesForBox, "nativeQueryRenderedFeaturesForBox"), + METHOD(&NativeMapView::getLayer, "nativeGetLayer"), + METHOD(&NativeMapView::addLayer, "nativeAddLayer"), + METHOD(&NativeMapView::removeLayerById, "nativeRemoveLayerById"), + METHOD(&NativeMapView::removeLayer, "nativeRemoveLayer"), + METHOD(&NativeMapView::getSource, "nativeGetSource"), + METHOD(&NativeMapView::addSource, "nativeAddSource"), + METHOD(&NativeMapView::removeSourceById, "nativeRemoveSourceById"), + METHOD(&NativeMapView::removeSource, "nativeRemoveSource"), + METHOD(&NativeMapView::addImage, "nativeAddImage"), + METHOD(&NativeMapView::removeImage, "nativeRemoveImage") + ); } } diff --git a/platform/android/src/native_map_view.hpp b/platform/android/src/native_map_view.hpp index e776b839fc..b8a7a3914c 100755 --- a/platform/android/src/native_map_view.hpp +++ b/platform/android/src/native_map_view.hpp @@ -1,71 +1,265 @@ #pragma once +#include +#include #include #include -#include #include #include +#include #include +#include + +#include "file_source.hpp" +#include "annotation/marker.hpp" +#include "annotation/polygon.hpp" +#include "annotation/polyline.hpp" +#include "graphics/pointf.hpp" +#include "graphics/rectf.hpp" +#include "geometry/feature.hpp" +#include "geometry/lat_lng.hpp" +#include "geometry/projected_meters.hpp" +#include "style/layers/layers.hpp" +#include "style/sources/sources.hpp" #include #include #include #include +#include namespace mbgl { namespace android { -class NativeMapView : public mbgl::View, public mbgl::Backend { +class NativeMapView : public View, public Backend { public: - NativeMapView(JNIEnv *env, jobject obj, float pixelRatio, int availableProcessors, size_t totalMemory); + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/NativeMapView"; }; + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + + NativeMapView(jni::JNIEnv&, jni::Object, jni::Object, jni::jfloat, jni::jint, jni::jlong); + virtual ~NativeMapView(); - mbgl::Size getFramebufferSize() const; - void updateViewBinding(); + // mbgl::View // + void bind() override; - void invalidate() override; + // mbgl::Backend // + void invalidate() override; void notifyMapChange(mbgl::MapChange) override; - mbgl::Map &getMap(); - mbgl::DefaultFileSource &getFileSource(); + // JNI // - void initializeDisplay(); - void terminateDisplay(); + void destroy(jni::JNIEnv&); - void initializeContext(); - void terminateContext(); + void render(jni::JNIEnv&); - void createSurface(ANativeWindow *window); - void destroySurface(); + void update(jni::JNIEnv&); - void render(); + void resizeView(jni::JNIEnv&, int, int); - void enableFps(bool enable); - void updateFps(); + void resizeFramebuffer(jni::JNIEnv&, int, int); + + void initializeDisplay(jni::JNIEnv&); + + void terminateDisplay(jni::JNIEnv&); + + void initializeContext(jni::JNIEnv&); + + void terminateContext(jni::JNIEnv&); + + void createSurface(jni::JNIEnv&, jni::Object<>); + + void destroySurface(jni::JNIEnv&); + + jni::String getStyleUrl(jni::JNIEnv&); + + void setStyleUrl(jni::JNIEnv&, jni::String); + + jni::String getStyleJson(jni::JNIEnv&); + + void setStyleJson(jni::JNIEnv&, jni::String); + + void cancelTransitions(jni::JNIEnv&); + + void setGestureInProgress(jni::JNIEnv&, jni::jboolean); + + void moveBy(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jlong); + + void jumpTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble); + + void easeTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, jni::jboolean); + + void flyTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble); + + jni::Object getLatLng(JNIEnv&); + + void setLatLng(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jlong); + + void setReachability(jni::JNIEnv&, jni::jboolean); + + void resetPosition(jni::JNIEnv&); + + jni::jdouble getPitch(jni::JNIEnv&); + + void setPitch(jni::JNIEnv&, jni::jdouble, jni::jlong); + + void scaleBy(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong); + + void setScale(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong); + + jni::jdouble getScale(jni::JNIEnv&); + + void setZoom(jni::JNIEnv&, jni::jdouble, jni::jlong); + + jni::jdouble getZoom(jni::JNIEnv&); + + void resetZoom(jni::JNIEnv&); + + void setMinZoom(jni::JNIEnv&, jni::jdouble); + + jni::jdouble getMinZoom(jni::JNIEnv&); + + void setMaxZoom(jni::JNIEnv&, jni::jdouble); + + jni::jdouble getMaxZoom(jni::JNIEnv&); + + void rotateBy(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong); + + void setBearing(jni::JNIEnv&, jni::jdouble, jni::jlong); + + void setBearingXY(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong); + + jni::jdouble getBearing(jni::JNIEnv&); + + void resetNorth(jni::JNIEnv&); + + void setVisibleCoordinateBounds(JNIEnv&, jni::Array>, jni::Object, jni::jdouble, jni::jlong); + + void setContentPadding(JNIEnv&, double, double, double, double); + + void scheduleSnapshot(jni::JNIEnv&); + + void enableFps(jni::JNIEnv&, jni::jboolean enable); + + jni::Array getCameraValues(jni::JNIEnv&); + + void updateMarker(jni::JNIEnv&, jni::jlong, jni::jdouble, jni::jdouble, jni::String); + + jni::Array addMarkers(jni::JNIEnv&, jni::Array>); - void resizeView(int width, int height); - void resizeFramebuffer(int width, int height); - mbgl::EdgeInsets getInsets() { return insets;} - void setInsets(mbgl::EdgeInsets insets_); + void onLowMemory(JNIEnv& env); - void scheduleTakeSnapshot(); + void setDebug(JNIEnv&, jni::jboolean); + + void cycleDebugOptions(JNIEnv&); + + jni::jboolean getDebug(JNIEnv&); + + jni::jboolean isFullyLoaded(JNIEnv&); + + jni::jdouble getMetersPerPixelAtLatitude(JNIEnv&, jni::jdouble, jni::jdouble); + + jni::Object projectedMetersForLatLng(JNIEnv&, jni::jdouble, jni::jdouble); + + jni::Object pixelForLatLng(JNIEnv&, jdouble, jdouble); + + jni::Object latLngForProjectedMeters(JNIEnv&, jdouble, jdouble); + + jni::Object latLngForPixel(JNIEnv&, jfloat, jfloat); + + jni::Array addPolylines(JNIEnv&, jni::Array>); + + jni::Array addPolygons(JNIEnv&, jni::Array>); + + void updatePolyline(JNIEnv&, jlong, jni::Object); + + void updatePolygon(JNIEnv&, jlong, jni::Object); + + void removeAnnotations(JNIEnv&, jni::Array); + + void addAnnotationIcon(JNIEnv&, jni::String, jint, jint, jfloat, jni::Array); + + jni::jdouble getTopOffsetPixelsForAnnotationSymbol(JNIEnv&, jni::String); + + jni::jlong getTransitionDuration(JNIEnv&); + + void setTransitionDuration(JNIEnv&, jni::jlong); + + jni::jlong getTransitionDelay(JNIEnv&); + + void setTransitionDelay(JNIEnv&, jni::jlong); + + jni::Array queryPointAnnotations(JNIEnv&, jni::Object); + + jni::Array> queryRenderedFeaturesForPoint(JNIEnv&, jni::jfloat, jni::jfloat, jni::Array); + + jni::Array> queryRenderedFeaturesForBox(JNIEnv&, jni::jfloat, jni::jfloat, jni::jfloat, jni::jfloat, jni::Array); + + jni::Object getLayer(JNIEnv&, jni::String); + + void addLayer(JNIEnv&, jlong, jni::String); + + void removeLayerById(JNIEnv&, jni::String); + + void removeLayer(JNIEnv&, jlong); + + jni::Object getSource(JNIEnv&, jni::String); + + void addSource(JNIEnv&, jni::jlong); + + void removeSourceById(JNIEnv&, jni::String); + + void removeSource(JNIEnv&, jlong); + + void addImage(JNIEnv&, jni::String, jni::jint, jni::jint, jni::jfloat, jni::Array); + + void removeImage(JNIEnv&, jni::String); protected: + // mbgl::Backend // + void activate() override; void deactivate() override; private: + void _initializeDisplay(); + + void _terminateDisplay(); + + void _initializeContext(); + + void _terminateContext(); + + void _createSurface(ANativeWindow*); + + void _destroySurface(); + EGLConfig chooseConfig(const EGLConfig configs[], EGLint numConfigs); + void updateViewBinding(); + mbgl::Size getFramebufferSize() const; + + void updateFps(); + private: + JavaVM *vm = nullptr; - JNIEnv *env = nullptr; - jweak obj = nullptr; + jni::UniqueWeakObject javaPeer; + + std::string styleUrl; + std::string apiKey; ANativeWindow *window = nullptr; + EGLConfig config = nullptr; + EGLint format = -1; + EGLDisplay oldDisplay = EGL_NO_DISPLAY; EGLSurface oldReadSurface = EGL_NO_SURFACE; EGLSurface oldDrawSurface = EGL_NO_SURFACE; @@ -75,15 +269,11 @@ private: EGLSurface surface = EGL_NO_SURFACE; EGLContext context = EGL_NO_CONTEXT; - EGLConfig config = nullptr; - EGLint format = -1; - std::string styleUrl; - std::string apiKey; - - bool firstTime = false; + float pixelRatio; bool fpsEnabled = false; bool snapshot = false; + bool firstRender = true; double fps = 0.0; int width = 0; @@ -96,12 +286,12 @@ private: size_t totalMemory = 0; // Ensure these are initialised last - mbgl::DefaultFileSource& fileSource; std::shared_ptr threadPool; std::unique_ptr map; mbgl::EdgeInsets insets; unsigned active = 0; }; -} -} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_manager.cpp b/platform/android/src/offline/offline_manager.cpp new file mode 100644 index 0000000000..02871e7fdf --- /dev/null +++ b/platform/android/src/offline/offline_manager.cpp @@ -0,0 +1,164 @@ +#include "offline_manager.hpp" + +#include + +#include "../attach_env.hpp" +#include "../jni/generic_global_ref_deleter.hpp" + +namespace mbgl { +namespace android { + +// OfflineManager // + +OfflineManager::OfflineManager(jni::JNIEnv& env, jni::Object jFileSource) + : fileSource(mbgl::android::FileSource::getDefaultFileSource(env, jFileSource)) { +} + +OfflineManager::~OfflineManager() {} + +void OfflineManager::setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong limit) { + fileSource.setOfflineMapboxTileCountLimit(limit); +} + +void OfflineManager::listOfflineRegions(jni::JNIEnv& env_, jni::Object jFileSource_, jni::Object callback_) { + // list regions + fileSource.listOfflineRegions([ + //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile + callback = std::shared_ptr(callback_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()), + jFileSource = std::shared_ptr(jFileSource_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()) + ](std::exception_ptr error, mbgl::optional> regions) mutable { + + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineManager::ListOfflineRegionsCallback::onError(*env, jni::Object(*callback), error); + } else if (regions) { + OfflineManager::ListOfflineRegionsCallback::onList(*env, jni::Object(*jFileSource), jni::Object(*callback), std::move(regions)); + } + }); +} + +void OfflineManager::createOfflineRegion(jni::JNIEnv& env_, + jni::Object jFileSource_, + jni::Object definition_, + jni::Array metadata_, + jni::Object callback_) { + // Convert + + // XXX hardcoded cast for now as we only support OfflineTilePyramidRegionDefinition + auto definition = OfflineTilePyramidRegionDefinition::getDefinition(env_, jni::Object(*definition_)); + + mbgl::OfflineRegionMetadata metadata; + if (metadata_) { + metadata = OfflineRegion::metadata(env_, metadata_); + } + + // Create region + fileSource.createOfflineRegion(definition, metadata, [ + //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile + callback = std::shared_ptr(callback_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()), + jFileSource = std::shared_ptr(jFileSource_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()) + ](std::exception_ptr error, mbgl::optional region) mutable { + + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineManager::CreateOfflineRegionCallback::onError(*env, jni::Object(*callback), error); + } else if (region) { + OfflineManager::CreateOfflineRegionCallback::onCreate( + *env, + jni::Object(*jFileSource), + jni::Object(*callback), std::move(region) + ); + } + }); +} + +jni::Class OfflineManager::javaClass; + +void OfflineManager::registerNative(jni::JNIEnv& env) { + OfflineManager::ListOfflineRegionsCallback::registerNative(env); + OfflineManager::CreateOfflineRegionCallback::registerNative(env); + + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); + + #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + jni::RegisterNativePeer( env, javaClass, "nativePtr", + std::make_unique>, + "initialize", + "finalize", + METHOD(&OfflineManager::setOfflineMapboxTileCountLimit, "setOfflineMapboxTileCountLimit"), + METHOD(&OfflineManager::listOfflineRegions, "listOfflineRegions"), + METHOD(&OfflineManager::createOfflineRegion, "createOfflineRegion")); +} + +// OfflineManager::ListOfflineRegionsCallback // + +void OfflineManager::ListOfflineRegionsCallback::onError(jni::JNIEnv& env, + jni::Object callback, + std::exception_ptr error) { + static auto method = javaClass.GetMethod(env, "onError"); + std::string message = mbgl::util::toString(error); + callback.Call(env, method, jni::Make(env, message)); +} + +void OfflineManager::ListOfflineRegionsCallback::onList(jni::JNIEnv& env, + jni::Object jFileSource, + jni::Object callback, + mbgl::optional> regions) { + //Convert the regions to java peer objects + std::size_t index = 0; + auto jregions = jni::Array>::New(env, regions->size(), OfflineRegion::javaClass); + for (auto& region : *regions) { + auto jregion = OfflineRegion::New(env, jFileSource, std::move(region)); + jregions.Set(env, index, jregion); + jni::DeleteLocalRef(env, jregion); + index++; + } + + // Trigger callback + static auto method = javaClass.GetMethod>)>(env, "onList"); + callback.Call(env, method, jregions); + jni::DeleteLocalRef(env, jregions); +} + +jni::Class OfflineManager::ListOfflineRegionsCallback::javaClass; + +void OfflineManager::ListOfflineRegionsCallback::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +// OfflineManager::CreateOfflineRegionCallback // + +void OfflineManager::CreateOfflineRegionCallback::onError(jni::JNIEnv& env, + jni::Object callback, + std::exception_ptr error) { + static auto method = javaClass.GetMethod(env, "onError"); + std::string message = mbgl::util::toString(error); + callback.Call(env, method, jni::Make(env, message)); +} + +void OfflineManager::CreateOfflineRegionCallback::onCreate(jni::JNIEnv& env, + jni::Object jFileSource, + jni::Object callback, + mbgl::optional region) { + //Convert the region to java peer object + auto jregion = OfflineRegion::New(env, jFileSource, std::move(*region)); + + // Trigger callback + static auto method = javaClass.GetMethod)>(env, "onCreate"); + callback.Call(env, method, jregion); + jni::DeleteLocalRef(env, jregion); +} + +jni::Class OfflineManager::CreateOfflineRegionCallback::javaClass; + +void OfflineManager::CreateOfflineRegionCallback::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_manager.hpp b/platform/android/src/offline/offline_manager.hpp new file mode 100644 index 0000000000..9ae2714ca2 --- /dev/null +++ b/platform/android/src/offline/offline_manager.hpp @@ -0,0 +1,75 @@ +#pragma once + + +#include +#include +#include + +#include "../file_source.hpp" +#include "offline_region.hpp" +#include "offline_region_definition.hpp" + + +namespace mbgl { +namespace android { + +class OfflineManager { +public: + + class ListOfflineRegionsCallback { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback";} + + static void onError(jni::JNIEnv&, jni::Object, std::exception_ptr); + + static void onList(jni::JNIEnv&, + jni::Object, + jni::Object, + mbgl::optional>); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + class CreateOfflineRegionCallback { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback"; } + + static void onError(jni::JNIEnv&, jni::Object, std::exception_ptr); + + static void onCreate(jni::JNIEnv&, + jni::Object, + jni::Object, + mbgl::optional); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager"; }; + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + + OfflineManager(jni::JNIEnv&, jni::Object); + ~OfflineManager(); + + void setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong limit); + + void listOfflineRegions(jni::JNIEnv&, jni::Object, jni::Object callback); + + void createOfflineRegion(jni::JNIEnv&, + jni::Object jFileSource_, + jni::Object definition, + jni::Array metadata, + jni::Object callback); + +private: + mbgl::DefaultFileSource& fileSource; +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region.cpp b/platform/android/src/offline/offline_region.cpp new file mode 100644 index 0000000000..856434d266 --- /dev/null +++ b/platform/android/src/offline/offline_region.cpp @@ -0,0 +1,308 @@ +#include "offline_region.hpp" + +#include +#include + +#include "offline_region_definition.hpp" +#include "offline_region_error.hpp" +#include "offline_region_status.hpp" +#include "../attach_env.hpp" +#include "../jni/generic_global_ref_deleter.hpp" + +namespace mbgl { +namespace android { + +// OfflineRegion // + +OfflineRegion::OfflineRegion(jni::JNIEnv& env, jni::jlong offlineRegionPtr, jni::Object jFileSource) + : region(reinterpret_cast(offlineRegionPtr)), + fileSource(mbgl::android::FileSource::getDefaultFileSource(env, jFileSource)) {} + +OfflineRegion::~OfflineRegion() {} + +void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, jni::Object callback) { + + // Define the observer + class Observer : public mbgl::OfflineRegionObserver { + public: + Observer(jni::UniqueObject&& callback_) + //TODO add a generic deleter for jni::Object + : callback(callback_.release()->Get()) { + } + + ~Observer() override { + android::UniqueEnv env = android::AttachEnv(); + env->DeleteGlobalRef(Unwrap(*callback)); + } + + void statusChanged(mbgl::OfflineRegionStatus status) override { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + // Status object + auto jStatus = OfflineRegionStatus::New(*env, status); + + // Call + static auto method = OfflineRegion::OfflineRegionObserver::javaClass + .GetMethod)>(*env, "onStatusChanged"); + callback.Call(*env, method, jStatus); + + // Delete references + jni::DeleteLocalRef(*env, jStatus); + } + + void responseError(mbgl::Response::Error error) override { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + // Error object + auto jError = OfflineRegionError::New(*env, error); + + // Call + static auto method = OfflineRegion::OfflineRegionObserver::javaClass + .GetMethod)>(*env, "onError"); + callback.Call(*env, method, jError); + + // Delete references + jni::DeleteLocalRef(*env, jError); + } + + void mapboxTileCountLimitExceeded(uint64_t limit) override { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + // Send limit + static auto method = OfflineRegion::OfflineRegionObserver::javaClass + .GetMethod(*env, "mapboxTileCountLimitExceeded"); + callback.Call(*env, method, jlong(limit)); + } + + jni::Object callback; + }; + + // Set the observer + fileSource.setOfflineRegionObserver(*region, std::make_unique(callback.NewGlobalRef(env_))); +} + +void OfflineRegion::setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint jState) { + // State + mbgl::OfflineRegionDownloadState state; + switch (jState) { + case 0: + state = mbgl::OfflineRegionDownloadState::Inactive; + break; + case 1: + state = mbgl::OfflineRegionDownloadState::Active; + break; + default: + mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); + return; + } + + fileSource.setOfflineRegionDownloadState(*region, state); +} + +void OfflineRegion::getOfflineRegionStatus(jni::JNIEnv& env_, jni::Object callback_) { + + fileSource.getOfflineRegionStatus(*region, [ + //Ensure the object is not gc'd in the meanwhile + callback = std::shared_ptr(callback_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()) + ](std::exception_ptr error, mbgl::optional status) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineRegionStatusCallback::onError(*env, jni::Object(*callback), error); + } else if (status) { + OfflineRegionStatusCallback::onStatus(*env, jni::Object(*callback), std::move(status)); + } + }); +} + +void OfflineRegion::deleteOfflineRegion(jni::JNIEnv& env_, jni::Object callback_) { + // Delete + fileSource.deleteOfflineRegion(std::move(*region), [ + //Ensure the object is not gc'd in the meanwhile + callback = std::shared_ptr(callback_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()) + ](std::exception_ptr error) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineRegionDeleteCallback::onError(*env, jni::Object(*callback), error); + } else { + OfflineRegionDeleteCallback::onDelete(*env, jni::Object(*callback)); + } + }); +} + +void OfflineRegion::updateOfflineRegionMetadata(jni::JNIEnv& env_, jni::Array jMetadata, jni::Object callback_) { + + // Convert + auto metadata = OfflineRegion::metadata(env_, jMetadata); + + fileSource.updateOfflineMetadata(region->getID(), metadata, [ + //Ensure the object is not gc'd in the meanwhile + callback = std::shared_ptr(callback_.NewGlobalRef(env_).release()->Get(), GenericGlobalRefDeleter()) + ](std::exception_ptr error, mbgl::optional data) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineRegionUpdateMetadataCallback::onError(*env, jni::Object(*callback), error); + } else if (data) { + OfflineRegionUpdateMetadataCallback::onUpdate(*env, jni::Object(*callback), std::move(data)); + } + }); +} + +jni::Object OfflineRegion::New(jni::JNIEnv& env, jni::Object jFileSource, mbgl::OfflineRegion region) { + + // Definition + auto definition = jni::Object(*OfflineTilePyramidRegionDefinition::New(env, region.getDefinition())); + + // Metadata + auto metadata = OfflineRegion::metadata(env, region.getMetadata()); + + // Create region java object + static auto constructor = OfflineRegion::javaClass.GetConstructor, jni::jlong, jni::Object, jni::Array>(env); + auto jregion = OfflineRegion::javaClass.New(env, constructor, + reinterpret_cast(new mbgl::OfflineRegion(std::move(region))), //Copy a region to the heap + jFileSource, jni::jlong(region.getID()), definition, metadata); + + //Delete references + jni::DeleteLocalRef(env, definition); + jni::DeleteLocalRef(env, metadata); + + return jregion; +} + +jni::Array OfflineRegion::metadata(jni::JNIEnv& env, mbgl::OfflineRegionMetadata metadata_) { + std::vector convertedMetadata(metadata_.begin(), metadata_.end()); + std::size_t length = static_cast(convertedMetadata.size()); + auto metadata = jni::Array::New(env, length); + metadata.SetRegion>(env, 0, convertedMetadata); + return metadata; +} + +mbgl::OfflineRegionMetadata OfflineRegion::metadata(jni::JNIEnv& env, jni::Array metadata_) { + std::size_t length = metadata_.Length(env); + auto metadata_tmp = std::vector(); + metadata_tmp.resize(length); + metadata_.GetRegion>(env, 0, metadata_tmp); + auto metadata = std::vector(metadata_tmp.begin(), metadata_tmp.end()); + return metadata; +} + +jni::Class OfflineRegion::javaClass; + +void OfflineRegion::registerNative(jni::JNIEnv& env) { + OfflineRegion::OfflineRegionObserver::registerNative(env); + OfflineRegion::OfflineRegionStatusCallback::registerNative(env); + OfflineRegion::OfflineRegionDeleteCallback::registerNative(env); + OfflineRegion::OfflineRegionUpdateMetadataCallback::registerNative(env); + + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); + + #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + jni::RegisterNativePeer( env, javaClass, "nativePtr", + std::make_unique>, + "initialize", + "finalize", + METHOD(&OfflineRegion::setOfflineRegionObserver, "setOfflineRegionObserver"), + METHOD(&OfflineRegion::setOfflineRegionDownloadState, "setOfflineRegionDownloadState"), + METHOD(&OfflineRegion::getOfflineRegionStatus, "getOfflineRegionStatus"), + METHOD(&OfflineRegion::deleteOfflineRegion, "deleteOfflineRegion"), + METHOD(&OfflineRegion::updateOfflineRegionMetadata, "updateOfflineRegionMetadata") + ); +} + +// OfflineRegionObserver // + +jni::Class OfflineRegion::OfflineRegionObserver::javaClass; + +void OfflineRegion::OfflineRegionObserver::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +// OfflineRegionStatusCallback // + +jni::Class OfflineRegion::OfflineRegionStatusCallback::javaClass; + +void OfflineRegion::OfflineRegionStatusCallback::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +void OfflineRegion::OfflineRegionStatusCallback::onError(jni::JNIEnv& env, + jni::Object callback, + std::exception_ptr error) { + static auto method = javaClass.GetMethod(env, "onError"); + std::string message = mbgl::util::toString(error); + callback.Call(env, method, jni::Make(env, message)); +} + +void OfflineRegion::OfflineRegionStatusCallback::onStatus(jni::JNIEnv& env, + jni::Object callback, + mbgl::optional status) { + //Convert to java peer object + auto jStatus = OfflineRegionStatus::New(env, std::move(*status)); + + // Trigger callback + static auto method = javaClass.GetMethod)>(env, "onStatus"); + callback.Call(env, method, jStatus); + jni::DeleteLocalRef(env, jStatus); +} + +// OfflineRegionDeleteCallback // + +jni::Class OfflineRegion::OfflineRegionDeleteCallback::javaClass; + +void OfflineRegion::OfflineRegionDeleteCallback::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +void OfflineRegion::OfflineRegionDeleteCallback::onError(jni::JNIEnv& env, + jni::Object callback, + std::exception_ptr error) { + static auto method = javaClass.GetMethod(env, "onError"); + std::string message = mbgl::util::toString(error); + callback.Call(env, method, jni::Make(env, message)); +} + +void OfflineRegion::OfflineRegionDeleteCallback::onDelete(jni::JNIEnv& env, jni::Object callback) { + // Trigger callback + static auto method = javaClass.GetMethod(env, "onDelete"); + callback.Call(env, method); +} + +// OfflineRegionUpdateMetadataCallback // + +jni::Class OfflineRegion::OfflineRegionUpdateMetadataCallback::javaClass; + +void OfflineRegion::OfflineRegionUpdateMetadataCallback::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onError(jni::JNIEnv& env, + jni::Object callback, + std::exception_ptr error) { + static auto method = javaClass.GetMethod(env, "onError"); + std::string message = mbgl::util::toString(error); + callback.Call(env, method, jni::Make(env, message)); +} + +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onUpdate(jni::JNIEnv& env, + jni::Object callback, + mbgl::optional metadata) { + //Convert to java peer object + auto jMetadata = OfflineRegion::metadata(env, std::move(*metadata)); + + // Trigger callback + static auto method = javaClass.GetMethod)>(env, "onUpdate"); + callback.Call(env, method, jMetadata); + jni::DeleteLocalRef(env, jMetadata); +} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region.hpp b/platform/android/src/offline/offline_region.hpp new file mode 100644 index 0000000000..c05383a91a --- /dev/null +++ b/platform/android/src/offline/offline_region.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include +#include + +#include "../file_source.hpp" + +#include + +namespace mbgl { +namespace android { + +class OfflineRegion { +public: + class OfflineRegionObserver { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionObserver"; }; + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + class OfflineRegionStatusCallback { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback"; }; + + static void onError(jni::JNIEnv&, jni::Object, std::exception_ptr); + + static void onStatus(jni::JNIEnv&, + jni::Object, + mbgl::optional); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + class OfflineRegionDeleteCallback { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback"; }; + + static void onError(jni::JNIEnv&, jni::Object, std::exception_ptr); + + static void onDelete(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + class OfflineRegionUpdateMetadataCallback { + public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback"; }; + + static void onError(jni::JNIEnv&, jni::Object, std::exception_ptr); + + static void onUpdate(jni::JNIEnv&, + jni::Object, + mbgl::optional); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + }; + + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion"; }; + + OfflineRegion(jni::JNIEnv&, jni::jlong, jni::Object); + + ~OfflineRegion(); + + void setOfflineRegionObserver(jni::JNIEnv&, jni::Object); + + void setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint); + + void getOfflineRegionStatus(jni::JNIEnv&, jni::Object); + + void deleteOfflineRegion(jni::JNIEnv&, jni::Object); + + void updateOfflineRegionMetadata(jni::JNIEnv&, jni::Array, jni::Object); + + static jni::Object New(jni::JNIEnv&, jni::Object, mbgl::OfflineRegion); + + static jni::Array metadata(jni::JNIEnv&, mbgl::OfflineRegionMetadata); + + static mbgl::OfflineRegionMetadata metadata(jni::JNIEnv&, jni::Array); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +private: + std::unique_ptr region; + mbgl::DefaultFileSource& fileSource; +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_definition.cpp b/platform/android/src/offline/offline_region_definition.cpp new file mode 100644 index 0000000000..66a9bdf99d --- /dev/null +++ b/platform/android/src/offline/offline_region_definition.cpp @@ -0,0 +1,69 @@ +#include "offline_region_definition.hpp" + +#include "../geometry/lat_lng_bounds.hpp" + +namespace mbgl { +namespace android { + +// OfflineRegionDefinition // + +jni::Class OfflineRegionDefinition::javaClass; + +void OfflineRegionDefinition::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +// OfflineTilePyramidRegionDefinition // + +jni::Object OfflineTilePyramidRegionDefinition::New(jni::JNIEnv& env, mbgl::OfflineTilePyramidRegionDefinition definition) { + + //Convert objects + auto styleURL = jni::Make(env, definition.styleURL); + auto bounds = LatLngBounds::New(env, definition.bounds); + + static auto constructor = javaClass.GetConstructor, jni::jdouble, jni::jdouble, jni::jfloat>(env); + auto jdefinition = javaClass.New(env, constructor, styleURL, bounds, definition.minZoom, definition.maxZoom, definition.pixelRatio); + + //Delete References + jni::DeleteLocalRef(env, styleURL); + jni::DeleteLocalRef(env, bounds); + + return jdefinition; +} + +mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::getDefinition(jni::JNIEnv& env, jni::Object jDefinition) { + // Field references + static auto styleURLF = javaClass.GetField(env, "styleURL"); + static auto boundsF = javaClass.GetField>(env, "bounds"); + static auto minZoomF = javaClass.GetField(env, "minZoom"); + static auto maxZoomF = javaClass.GetField(env, "maxZoom"); + static auto pixelRatioF = javaClass.GetField(env, "pixelRatio"); + + // Get objects + auto jStyleURL = jDefinition.Get(env, styleURLF); + auto jBounds = jDefinition.Get(env, boundsF); + + // Create definition + mbgl::OfflineTilePyramidRegionDefinition definition( + jni::Make(env, jStyleURL), + LatLngBounds::getLatLngBounds(env, jBounds), + jDefinition.Get(env, minZoomF), + jDefinition.Get(env, maxZoomF), + jDefinition.Get(env, pixelRatioF) + ); + + // Delete references + jni::DeleteLocalRef(env, jStyleURL); + jni::DeleteLocalRef(env, jBounds); + + return definition; +} + +jni::Class OfflineTilePyramidRegionDefinition::javaClass; + +void OfflineTilePyramidRegionDefinition::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_definition.hpp b/platform/android/src/offline/offline_region_definition.hpp new file mode 100644 index 0000000000..2ca82a4d96 --- /dev/null +++ b/platform/android/src/offline/offline_region_definition.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +namespace mbgl { +namespace android { + +class OfflineRegionDefinition { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegionDefinition"; }; + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + +class OfflineTilePyramidRegionDefinition: public OfflineRegionDefinition { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition"; }; + + static jni::Object New(jni::JNIEnv&, mbgl::OfflineTilePyramidRegionDefinition); + + static mbgl::OfflineTilePyramidRegionDefinition getDefinition(jni::JNIEnv&, jni::Object); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); + +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_error.cpp b/platform/android/src/offline/offline_region_error.cpp new file mode 100644 index 0000000000..b0a19f934f --- /dev/null +++ b/platform/android/src/offline/offline_region_error.cpp @@ -0,0 +1,53 @@ +#include "offline_region_error.hpp" + +namespace mbgl { +namespace android { + +jni::Object OfflineRegionError::New(jni::JNIEnv& env, mbgl::Response::Error error) { + + // Handle the value of reason independently of the underlying int value + std::string reason; + switch(error.reason) { + case mbgl::Response::Error::Reason::Success: + reason = "REASON_SUCCESS"; + break; + case mbgl::Response::Error::Reason::NotFound: + reason = "REASON_NOT_FOUND"; + break; + case mbgl::Response::Error::Reason::Server: + reason = "REASON_SERVER"; + break; + case mbgl::Response::Error::Reason::Connection: + reason = "REASON_CONNECTION"; + break; + case mbgl::Response::Error::Reason::RateLimit: + reason = "REASON_RATE_LIMIT"; + break; + case mbgl::Response::Error::Reason::Other: + reason = "REASON_OTHER"; + break; + } + + // Convert + auto jReason = jni::Make(env, reason); + auto jMessage = jni::Make(env, error.message); + + // Create java object + static auto constructor = javaClass.GetConstructor(env); + auto jError = javaClass.New(env, constructor, jReason, jMessage); + + // Delete references + jni::DeleteLocalRef(env, jReason); + jni::DeleteLocalRef(env, jMessage); + + return jError; +} + +jni::Class OfflineRegionError::javaClass; + +void OfflineRegionError::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_error.hpp b/platform/android/src/offline/offline_region_error.hpp new file mode 100644 index 0000000000..61efaca67e --- /dev/null +++ b/platform/android/src/offline/offline_region_error.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace mbgl { +namespace android { + +class OfflineRegionError { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegionError"; }; + + static jni::Object New(jni::JNIEnv&, mbgl::Response::Error); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_status.cpp b/platform/android/src/offline/offline_region_status.cpp new file mode 100644 index 0000000000..d0bbae124f --- /dev/null +++ b/platform/android/src/offline/offline_region_status.cpp @@ -0,0 +1,39 @@ +#include "offline_region_status.hpp" + +namespace mbgl { +namespace android { + +jni::Object OfflineRegionStatus::New(jni::JNIEnv& env, mbgl::OfflineRegionStatus status) { + + // Convert to jint + jint downloadState; + switch(status.downloadState) { + case mbgl::OfflineRegionDownloadState::Inactive: + downloadState = 0; + break; + case mbgl::OfflineRegionDownloadState::Active: + downloadState = 1; + break; + } + + // Create java object + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, + downloadState, + jlong(status.completedResourceCount), + jlong(status.completedResourceSize), + jlong(status.completedTileCount), + jlong(status.completedTileSize), + jlong(status.requiredResourceCount), + jboolean(status.requiredResourceCountIsPrecise) + ); +} + +jni::Class OfflineRegionStatus::javaClass; + +void OfflineRegionStatus::registerNative(jni::JNIEnv& env) { + javaClass = *jni::Class::Find(env).NewGlobalRef(env).release(); +} + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/offline/offline_region_status.hpp b/platform/android/src/offline/offline_region_status.hpp new file mode 100644 index 0000000000..b29a653655 --- /dev/null +++ b/platform/android/src/offline/offline_region_status.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace mbgl { +namespace android { + +class OfflineRegionStatus { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegionStatus"; }; + + static jni::Object New(jni::JNIEnv&, mbgl::OfflineRegionStatus status); + + static jni::Class javaClass; + + static void registerNative(jni::JNIEnv&); +}; + +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/style/android_conversion.hpp b/platform/android/src/style/android_conversion.hpp index 8ae694d115..d9b88ab52b 100644 --- a/platform/android/src/style/android_conversion.hpp +++ b/platform/android/src/style/android_conversion.hpp @@ -4,7 +4,6 @@ #include #include -#include #include #include -- cgit v1.2.1