summaryrefslogtreecommitdiff
path: root/platform/android/src/style/sources/geojson_source.cpp
blob: 7fccc36a9fa3aedc43097a0b88820b1484ae9eda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#include "geojson_source.hpp"
#include "../../attach_env.hpp"

#include <mbgl/renderer/query.hpp>

// Java -> C++ conversion
#include "../android_conversion.hpp"
#include "../conversion/filter.hpp"
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/style/conversion/geojson_options.hpp>
#include <mbgl/style/conversion_impl.hpp>

// C++ -> Java conversion
#include "../../conversion/conversion.hpp"
#include "../../conversion/collection.hpp"
#include "../../geojson/feature.hpp"
#include "../conversion/url_or_tileset.hpp"

#include <string>
#include <mbgl/util/shared_thread_pool.hpp>

// GeoJSONSource uses a "coalescing" model for high frequency asynchronous data update calls,
// which in practice means, that any update that started processing is going to finish
// and the last scheduled update is going to finish as well. Any updates scheduled during processing can be canceled.
// Conversion from Java features to core ones is done on a worker thread and once finished,
// the ownership of the converted features is returned to the calling thread.
namespace mbgl {
namespace android {

    // This conversion is expected not to fail because it's used only in contexts where
    // the value was originally a GeoJsonOptions object on the Java side. If it fails
    // to convert, it's a bug in our serialization or Java-side static typing.
    static style::GeoJSONOptions convertGeoJSONOptions(jni::JNIEnv& env, const jni::Object<>& options) {
        using namespace mbgl::style::conversion;
        if (!options) {
            return style::GeoJSONOptions();
        }
        Error error;
        optional<style::GeoJSONOptions> result = convert<style::GeoJSONOptions>(
            mbgl::android::Value(env, options), error);
        if (!result) {
            throw std::logic_error(error.message);
        }
        return *result;
    }

    GeoJSONSource::GeoJSONSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& options)
        : Source(env, std::make_unique<mbgl::style::GeoJSONSource>(
                jni::Make<std::string>(env, sourceId),
                convertGeoJSONOptions(env, options)))
        , threadPool(sharedThreadPool())
        , converter(std::make_unique<Actor<FeatureConverter>>(*threadPool)) {
    }

    GeoJSONSource::GeoJSONSource(jni::JNIEnv& env,
                                 mbgl::style::Source& coreSource,
                                 AndroidRendererFrontend& frontend)
        : Source(env, coreSource, createJavaPeer(env), frontend)
        , threadPool(sharedThreadPool())
        , converter(std::make_unique<Actor<FeatureConverter>>(*threadPool)) {
    }

    GeoJSONSource::~GeoJSONSource() = default;

    void GeoJSONSource::setGeoJSONString(jni::JNIEnv& env, const jni::String& jString) {

        std::shared_ptr<std::string> json = std::make_shared<std::string>(jni::Make<std::string>(env, jString));

        Update::Converter converterFn = [this, json](ActorRef<Callback> _callback) {
            converter->self().invoke(&FeatureConverter::convertJson, json, _callback);
        };

        setAsync(converterFn);
    }

    void GeoJSONSource::setFeatureCollection(jni::JNIEnv& env, const jni::Object<geojson::FeatureCollection>& jFeatures) {
        setCollectionAsync(env, jFeatures);
    }

    void GeoJSONSource::setFeature(jni::JNIEnv& env, const jni::Object<geojson::Feature>& jFeature) {
        setCollectionAsync(env, jFeature);
    }

    void GeoJSONSource::setGeometry(jni::JNIEnv& env, const jni::Object<geojson::Geometry>& jGeometry) {
        setCollectionAsync(env, jGeometry);
    }

    void GeoJSONSource::setURL(jni::JNIEnv& env, const jni::String& url) {
        // Update the core source
        source.as<mbgl::style::GeoJSONSource>()->GeoJSONSource::setURL(jni::Make<std::string>(env, url));
    }

    jni::Local<jni::String> GeoJSONSource::getURL(jni::JNIEnv& env) {
        optional<std::string> url = source.as<mbgl::style::GeoJSONSource>()->GeoJSONSource::getURL();
        return url ? jni::Make<jni::String>(env, *url) : jni::Local<jni::String>();
    }

    jni::Local<jni::Array<jni::Object<geojson::Feature>>> GeoJSONSource::querySourceFeatures(jni::JNIEnv& env,
                                                                        const jni::Array<jni::Object<>>& jfilter) {
        using namespace mbgl::android::conversion;
        using namespace mbgl::android::geojson;

        std::vector<mbgl::Feature> features;
        if (rendererFrontend) {
            features = rendererFrontend->querySourceFeatures(source.getID(),
                { {}, toFilter(env, jfilter) });
        }
        return Feature::convert(env, features);
    }

    jni::Local<jni::Array<jni::Object<geojson::Feature>>> GeoJSONSource::getClusterChildren(jni::JNIEnv& env, const jni::Object<geojson::Feature>& feature) {
        using namespace mbgl::android::conversion;
        using namespace mbgl::android::geojson;

        if (rendererFrontend) {
            mbgl::Feature _feature = Feature::convert(env, feature);
            _feature.properties["cluster_id"] = static_cast<uint64_t>(_feature.properties["cluster_id"].get<double>());
            const auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "children", {});
            if (featureExtension.is<mbgl::FeatureCollection>()) {
                return Feature::convert(env, featureExtension.get<mbgl::FeatureCollection>());
            }
        }
        return jni::Array<jni::Object<Feature>>::New(env, 0);
    }

    jni::Local<jni::Array<jni::Object<geojson::Feature>>> GeoJSONSource::getClusterLeaves(jni::JNIEnv& env, const jni::Object<geojson::Feature>& feature, jni::jlong limit, jni::jlong offset) {
        using namespace mbgl::android::conversion;
        using namespace mbgl::android::geojson;

        if (rendererFrontend) {
            mbgl::Feature _feature = Feature::convert(env, feature);
            _feature.properties["cluster_id"] = static_cast<uint64_t>(_feature.properties["cluster_id"].get<double>());
            const std::map<std::string, mbgl::Value> options = { {"limit", static_cast<uint64_t>(limit)},
                                                                    {"offset", static_cast<uint64_t>(offset)} };
            auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "leaves", options);
            if (featureExtension.is<mbgl::FeatureCollection>()) {
                return Feature::convert(env, featureExtension.get<mbgl::FeatureCollection>());
            }
        }
        return jni::Array<jni::Object<Feature>>::New(env, 0);;
    }

    jint GeoJSONSource::getClusterExpansionZoom(jni::JNIEnv& env, const jni::Object<geojson::Feature>& feature) {
        using namespace mbgl::android::conversion;
        using namespace mbgl::android::geojson;

        if (rendererFrontend) {
            mbgl::Feature _feature = Feature::convert(env, feature);
            _feature.properties["cluster_id"] = static_cast<uint64_t>(_feature.properties["cluster_id"].get<double>());
            auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "expansion-zoom", {});
            if (featureExtension.is<mbgl::Value>()) {
                auto value = featureExtension.get<mbgl::Value>();
                if (value.is<uint64_t>()) {
                    return value.get<uint64_t>();
                }
            }
        }
        return 0;
    }

    jni::Local<jni::Object<Source>> GeoJSONSource::createJavaPeer(jni::JNIEnv& env) {
        static auto& javaClass = jni::Class<GeoJSONSource>::Singleton(env);
        static auto constructor = javaClass.GetConstructor<jni::jlong>(env);
        return javaClass.New(env, constructor, reinterpret_cast<jni::jlong>(this));
    }

    template <class JNIType>
    void GeoJSONSource::setCollectionAsync(jni::JNIEnv& env, const jni::Object<JNIType>& jObject) {
        auto global = jni::NewGlobal<jni::EnvAttachingDeleter>(env, jObject);
        auto object = std::make_shared<decltype(global)>(std::move(global));

        Update::Converter converterFn = [this, object](ActorRef<Callback> _callback) {
            converter->self().invoke(&FeatureConverter::convertObject<JNIType>, object, _callback);
        };

        setAsync(converterFn);
    }

    void GeoJSONSource::setAsync(Update::Converter converterFn) {
        awaitingUpdate = std::make_unique<Update>(
                std::move(converterFn),
                std::make_unique<Actor<Callback>>(
                        *Scheduler::GetCurrent(),
                        [this](GeoJSON /*geoJSON*/) {
                            // conversion from Java features to core ones finished
                            android::UniqueEnv _env = android::AttachEnv();

                            // Update the core source
//                            source.as<mbgl::style::GeoJSONSource>()->GeoJSONSource::setGeoJSON(geoJSON);

                            // if there is an awaiting update, execute it, otherwise, release resources
                            if (awaitingUpdate) {
                                update = std::move(awaitingUpdate);
                                update->converterFn(update->callback->self());
                            } else {
                                update.reset();
                            }
                        })
        );

        // If another update is running, wait
        if (update) {
            return;
        }

        // no updates are being processed, execute this one
        update = std::move(awaitingUpdate);
        update->converterFn(update->callback->self());
    }

    void GeoJSONSource::registerNative(jni::JNIEnv& env) {
        // Lookup the class
        static auto& javaClass = jni::Class<GeoJSONSource>::Singleton(env);

        #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod<decltype(MethodPtr), (MethodPtr)>(name)

        // Register the peer
        jni::RegisterNativePeer<GeoJSONSource>(
            env, javaClass, "nativePtr",
            jni::MakePeer<GeoJSONSource, const jni::String&, const jni::Object<>&>,
            "initialize",
            "finalize",
            METHOD(&GeoJSONSource::setGeoJSONString, "nativeSetGeoJsonString"),
            METHOD(&GeoJSONSource::setFeatureCollection, "nativeSetFeatureCollection"),
            METHOD(&GeoJSONSource::setFeature, "nativeSetFeature"),
            METHOD(&GeoJSONSource::setGeometry, "nativeSetGeometry"),
            METHOD(&GeoJSONSource::setURL, "nativeSetUrl"),
            METHOD(&GeoJSONSource::getURL, "nativeGetUrl"),
            METHOD(&GeoJSONSource::querySourceFeatures, "querySourceFeatures"),
            METHOD(&GeoJSONSource::getClusterChildren, "nativeGetClusterChildren"),
            METHOD(&GeoJSONSource::getClusterLeaves, "nativeGetClusterLeaves"),
            METHOD(&GeoJSONSource::getClusterExpansionZoom, "nativeGetClusterExpansionZoom")
        );
    }

    void FeatureConverter::convertJson(std::shared_ptr<std::string> json,
                                       ActorRef<Callback> callback) {
        using namespace mbgl::style::conversion;

        android::UniqueEnv _env = android::AttachEnv();

        // Convert the jni object
        Error error;
        optional<GeoJSON> converted = parseGeoJSON(*json, error);
        if(!converted) {
            mbgl::Log::Error(mbgl::Event::JNI, "Error setting geo json: " + error.message);
            return;
        }

        callback.invoke(&Callback::operator(), *converted);
    }

    template <class JNIType>
    void FeatureConverter::convertObject(std::shared_ptr<jni::Global<jni::Object<JNIType>, jni::EnvAttachingDeleter>> jObject, ActorRef<Callback> callback) {
        using namespace mbgl::android::geojson;

        android::UniqueEnv _env = android::AttachEnv();
        // Convert the jni object
        auto geometry = JNIType::convert(*_env, *jObject);
        callback.invoke(&Callback::operator(), GeoJSON(geometry));
    }

    Update::Update(Converter _converterFn, std::unique_ptr<Actor<Callback>> _callback)
            : converterFn(std::move(_converterFn))
            , callback(std::move(_callback)) {}

} // namespace android
} // namespace mbgl