summaryrefslogtreecommitdiff
path: root/platform/android/src/jni/generic_global_ref_deleter.hpp
blob: 7239e361a7834c46e7503ca739deb66b9155e9b4 (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
#pragma once

#include <jni/jni.hpp>

#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));
        }
    }
};


template < class TagType >
class GenericWeakObjectRefDeleter;

template < class TagType = jni::ObjectTag >
using GenericUniqueWeakObject = std::unique_ptr< const jni::Object<TagType>, GenericWeakObjectRefDeleter<TagType> >;

template < class TagType >
class GenericWeakObjectRefDeleter
{
public:
    using pointer = jni::PointerToValue< jni::Object<TagType> >;

    void operator()(pointer p) const
    {
        if (p)
        {
            auto env = AttachEnv();
            env->DeleteWeakGlobalRef(jni::Unwrap(p->Get()));
        }
    }
};

template < class TagType >
GenericUniqueWeakObject<TagType> SeizeGenericWeakRef(JNIEnv&, jni::Object<TagType>&& object)
{
    return GenericUniqueWeakObject<TagType>(jni::PointerToValue<jni::Object<TagType>>(std::move(object)), GenericWeakObjectRefDeleter<TagType>());
};

} // namespace android
} // namespace mbgl