summaryrefslogtreecommitdiff
path: root/platform/android/src/snapshotter/map_snapshotter.cpp
blob: 5bccbd1ba8bf7adfd4ca8020709f5f528307f33e (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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#include "map_snapshotter.hpp"

#include <mbgl/actor/scheduler.hpp>
#include <mbgl/renderer/renderer.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/util/string.hpp>

#include "../attach_env.hpp"
#include "map_snapshot.hpp"

namespace mbgl {
namespace android {

MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env,
                               const jni::Object<MapSnapshotter>& _obj,
                               const jni::Object<FileSource>& _jFileSource,
                               jni::jfloat _pixelRatio,
                               jni::jint width,
                               jni::jint height,
                               const jni::String& styleURL,
                               const jni::String& styleJSON,
                               const jni::Object<LatLngBounds>& region,
                               const jni::Object<CameraPosition>& position,
                               jni::jboolean _showLogo,
                               const jni::String& _localIdeographFontFamily)
        : javaPeer(_env, _obj)
        , pixelRatio(_pixelRatio) {

    // Get a reference to the JavaVM for callbacks
    if (_env.GetJavaVM(&vm) < 0) {
        _env.ExceptionDescribe();
        return;
    }

    weakScheduler = mbgl::Scheduler::GetCurrent()->makeWeakPtr();

    jFileSource = FileSource::getNativePeer(_env, _jFileSource);
    auto size = mbgl::Size { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };

    showLogo = _showLogo;

    // Create the core snapshotter
    snapshotter = std::make_unique<mbgl::MapSnapshotter>(
        size,
        pixelRatio,
        mbgl::android::FileSource::getSharedResourceOptions(_env, _jFileSource),
        *this,
        _localIdeographFontFamily ? jni::Make<std::string>(_env, _localIdeographFontFamily) : optional<std::string>{});

    if (position) {
        snapshotter->setCameraOptions(CameraPosition::getCameraOptions(_env, position, pixelRatio));
    }

    if (region) {
        snapshotter->setRegion(LatLngBounds::getLatLngBounds(_env, region));
    }

    if (styleJSON) {
        snapshotter->setStyleJSON(jni::Make<std::string>(_env, styleJSON));
    } else {
        snapshotter->setStyleURL(jni::Make<std::string>(_env, styleURL));
    }
}

MapSnapshotter::~MapSnapshotter() {
    auto guard = weakScheduler.lock();
    if (weakScheduler && weakScheduler.get() != mbgl::Scheduler::GetCurrent()) {
        snapshotter->cancel();
        weakScheduler->schedule([ptr = snapshotter.release()]() mutable {
            if (ptr) {
                delete ptr;
            }
        });
    }
}

void MapSnapshotter::start(JNIEnv& env) {
    MBGL_VERIFY_THREAD(tid);
    activateFilesource(env);
    snapshotter->snapshot([this](std::exception_ptr err,
                                 PremultipliedImage image,
                                 std::vector<std::string> attributions,
                                 mbgl::MapSnapshotter::PointForFn pointForFn,
                                 mbgl::MapSnapshotter::LatLngForFn latLngForFn) {
        MBGL_VERIFY_THREAD(tid);
        android::UniqueEnv _env = android::AttachEnv();
        static auto& javaClass = jni::Class<MapSnapshotter>::Singleton(*_env);

        if (err) {
            // error handler callback
            static auto onSnapshotFailed = javaClass.GetMethod<void (jni::String)>(*_env, "onSnapshotFailed");
            auto weakReference = javaPeer.get(*_env);
            if (weakReference) {
                weakReference.Call(*_env, onSnapshotFailed, jni::Make<jni::String>(*_env, util::toString(err)));
            }
        } else {
            // Create the wrapper
            auto mapSnapshot = android::MapSnapshot::New(*_env, std::move(image), pixelRatio, attributions, showLogo, pointForFn, latLngForFn);

            // invoke callback
            static auto onSnapshotReady = javaClass.GetMethod<void (jni::Object<MapSnapshot>)>(*_env, "onSnapshotReady");
            auto weakReference = javaPeer.get(*_env);
            if (weakReference) {
                weakReference.Call(*_env, onSnapshotReady, mapSnapshot);
            }
        }

        deactivateFilesource(*_env);
    });
}

void MapSnapshotter::cancel(JNIEnv& env) {
    MBGL_VERIFY_THREAD(tid);
    snapshotter->cancel();
    deactivateFilesource(env);
}

void MapSnapshotter::setStyleUrl(JNIEnv& env, const jni::String& styleURL) {
    snapshotter->setStyleURL(jni::Make<std::string>(env, styleURL));
}

void MapSnapshotter::setStyleJson(JNIEnv& env, const jni::String& styleJSON) {
    snapshotter->setStyleJSON(jni::Make<std::string>(env, styleJSON));
}

void MapSnapshotter::setSize(JNIEnv&, jni::jint width, jni::jint height) {
    auto size = mbgl::Size { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };
    snapshotter->setSize(size);
}

void MapSnapshotter::setCameraPosition(JNIEnv& env, const jni::Object<CameraPosition>& position) {
    auto options = CameraPosition::getCameraOptions(env, position, pixelRatio);
    snapshotter->setCameraOptions(options);
}

void MapSnapshotter::setRegion(JNIEnv& env, const jni::Object<LatLngBounds>& region) {
    snapshotter->setRegion(LatLngBounds::getLatLngBounds(env, region));
}

// Private methods //

void MapSnapshotter::activateFilesource(JNIEnv& env) {
    if (!activatedFilesource) {
        activatedFilesource = true;
        jFileSource->resume(env);
    }
}

void MapSnapshotter::deactivateFilesource(JNIEnv& env) {
    if (activatedFilesource) {
        activatedFilesource = false;
        jFileSource->pause(env);
    }
}

void MapSnapshotter::onDidFailLoadingStyle(const std::string& error) {
    MBGL_VERIFY_THREAD(tid);
    android::UniqueEnv _env = android::AttachEnv();
    static auto& javaClass = jni::Class<MapSnapshotter>::Singleton(*_env);
    static auto onDidFailLoadingStyle = javaClass.GetMethod<void(jni::String)>(*_env, "onDidFailLoadingStyle");
    auto weakReference = javaPeer.get(*_env);
    if (weakReference) {
        weakReference.Call(*_env, onDidFailLoadingStyle, jni::Make<jni::String>(*_env, error));
    }
}

void MapSnapshotter::onDidFinishLoadingStyle() {
    MBGL_VERIFY_THREAD(tid);
    android::UniqueEnv _env = android::AttachEnv();

    static auto& javaClass = jni::Class<MapSnapshotter>::Singleton(*_env);
    static auto onDidFinishLoadingStyle = javaClass.GetMethod<void()>(*_env, "onDidFinishLoadingStyle");
    auto weakReference = javaPeer.get(*_env);
    if (weakReference) {
        weakReference.Call(*_env, onDidFinishLoadingStyle);
    }
}

void MapSnapshotter::onStyleImageMissing(const std::string& imageName) {
    MBGL_VERIFY_THREAD(tid);
    android::UniqueEnv _env = android::AttachEnv();
    static auto& javaClass = jni::Class<MapSnapshotter>::Singleton(*_env);
    static auto onStyleImageMissing = javaClass.GetMethod<void(jni::String)>(*_env, "onStyleImageMissing");
    auto weakReference = javaPeer.get(*_env);
    if (weakReference) {
        weakReference.Call(*_env, onStyleImageMissing, jni::Make<jni::String>(*_env, imageName));
    }
}

void MapSnapshotter::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint index) {
    assert(nativeLayerPtr != 0);
    const auto layers = snapshotter->getStyle().getLayers();
    auto* layer = reinterpret_cast<Layer*>(nativeLayerPtr);
    // Check index
    const int numLayers = layers.size() - 1;
    if (index > numLayers || index < 0) {
        Log::Error(Event::JNI, "Index out of range: %i", index);
        jni::ThrowNew(env,
                      jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"),
                      std::string("Invalid index").c_str());
    }
    // Insert it below the current at that index
    try {
        layer->addToStyle(snapshotter->getStyle(), layers.at(index)->getID());
    } catch (const std::runtime_error& error) {
        jni::ThrowNew(
            env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what());
    }
}

void MapSnapshotter::addLayerBelow(JNIEnv& env, jlong nativeLayerPtr, const jni::String& below) {
    assert(nativeLayerPtr != 0);

    auto* layer = reinterpret_cast<Layer*>(nativeLayerPtr);
    try {
        layer->addToStyle(
            snapshotter->getStyle(),
            below ? mbgl::optional<std::string>(jni::Make<std::string>(env, below)) : mbgl::optional<std::string>());
    } catch (const std::runtime_error& error) {
        jni::ThrowNew(
            env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what());
    }
}

void MapSnapshotter::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni::String& above) {
    assert(nativeLayerPtr != 0);
    auto* newLayer = reinterpret_cast<Layer*>(nativeLayerPtr);

    // Find the sibling
    const auto snapshotterLayers = snapshotter->getStyle().getLayers();
    auto siblingId = jni::Make<std::string>(env, above);

    size_t index = 0;
    for (auto* snapshotterLayer : snapshotterLayers) {
        ++index;
        if (snapshotterLayer->getID() == siblingId) {
            break;
        }
    }

    // Check if we found a sibling to place before
    mbgl::optional<std::string> before;
    if (index > snapshotterLayers.size()) {
        // Not found
        jni::ThrowNew(env,
                      jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"),
                      std::string("Could not find layer: ").append(siblingId).c_str());
    } else if (index < snapshotterLayers.size()) {
        // Place before the sibling
        before = {snapshotterLayers.at(index)->getID()};
    }

    // Add the layer
    try {
        newLayer->addToStyle(snapshotter->getStyle(), before);
    } catch (const std::runtime_error& error) {
        jni::ThrowNew(
            env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what());
    }
}

void MapSnapshotter::addSource(JNIEnv& env, const jni::Object<Source>& obj, jlong sourcePtr) {
    assert(sourcePtr != 0);

    auto* source = reinterpret_cast<Source*>(sourcePtr);
    try {
        source->addToStyle(env, obj, snapshotter->getStyle());
    } catch (const std::runtime_error& error) {
        jni::ThrowNew(
            env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what());
    }
}

void MapSnapshotter::addImages(JNIEnv& env, const jni::Array<jni::Object<mbgl::android::Image>>& jimages) {
    jni::NullCheck(env, &jimages);
    std::size_t len = jimages.Length(env);

    for (std::size_t i = 0; i < len; ++i) {
        auto image = mbgl::android::Image::getImage(env, jimages.Get(env, i));
        snapshotter->getStyle().addImage(std::make_unique<mbgl::style::Image>(image));
    }
}

// Static methods //

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

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

    // Register the peer
    jni::RegisterNativePeer<MapSnapshotter>(env,
                                            javaClass,
                                            "nativePtr",
                                            jni::MakePeer<MapSnapshotter,
                                                          const jni::Object<MapSnapshotter>&,
                                                          const jni::Object<FileSource>&,
                                                          jni::jfloat,
                                                          jni::jint,
                                                          jni::jint,
                                                          const jni::String&,
                                                          const jni::String&,
                                                          const jni::Object<LatLngBounds>&,
                                                          const jni::Object<CameraPosition>&,
                                                          jni::jboolean,
                                                          const jni::String&>,
                                            "nativeInitialize",
                                            "finalize",
                                            METHOD(&MapSnapshotter::setStyleUrl, "setStyleUrl"),
                                            METHOD(&MapSnapshotter::addLayerAt, "nativeAddLayerAt"),
                                            METHOD(&MapSnapshotter::addLayerBelow, "nativeAddLayerBelow"),
                                            METHOD(&MapSnapshotter::addLayerAbove, "nativeAddLayerAbove"),
                                            METHOD(&MapSnapshotter::addSource, "nativeAddSource"),
                                            METHOD(&MapSnapshotter::addImages, "nativeAddImages"),
                                            METHOD(&MapSnapshotter::setStyleJson, "setStyleJson"),
                                            METHOD(&MapSnapshotter::setSize, "setSize"),
                                            METHOD(&MapSnapshotter::setCameraPosition, "setCameraPosition"),
                                            METHOD(&MapSnapshotter::setRegion, "setRegion"),
                                            METHOD(&MapSnapshotter::start, "nativeStart"),
                                            METHOD(&MapSnapshotter::cancel, "nativeCancel"));
}

} // namespace android
} // namespace mbgl