1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/android/jni_weak_ref.h"
6 
7 #include <utility>
8 
9 #include "base/android/jni_android.h"
10 #include "base/logging.h"
11 
12 using base::android::AttachCurrentThread;
13 
JavaObjectWeakGlobalRef()14 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef() : obj_(nullptr) {}
15 
JavaObjectWeakGlobalRef(const JavaObjectWeakGlobalRef & orig)16 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
17     const JavaObjectWeakGlobalRef& orig)
18     : obj_(nullptr) {
19   Assign(orig);
20 }
21 
JavaObjectWeakGlobalRef(JavaObjectWeakGlobalRef && orig)22 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
23     JavaObjectWeakGlobalRef&& orig) noexcept
24     : obj_(orig.obj_) {
25   orig.obj_ = nullptr;
26 }
27 
JavaObjectWeakGlobalRef(JNIEnv * env,jobject obj)28 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj)
29     : obj_(env->NewWeakGlobalRef(obj)) {
30 }
31 
JavaObjectWeakGlobalRef(JNIEnv * env,const base::android::JavaRef<jobject> & obj)32 JavaObjectWeakGlobalRef::JavaObjectWeakGlobalRef(
33     JNIEnv* env,
34     const base::android::JavaRef<jobject>& obj)
35     : obj_(env->NewWeakGlobalRef(obj.obj())) {
36 }
37 
~JavaObjectWeakGlobalRef()38 JavaObjectWeakGlobalRef::~JavaObjectWeakGlobalRef() {
39   reset();
40 }
41 
operator =(const JavaObjectWeakGlobalRef & rhs)42 void JavaObjectWeakGlobalRef::operator=(const JavaObjectWeakGlobalRef& rhs) {
43   Assign(rhs);
44 }
45 
operator =(JavaObjectWeakGlobalRef && rhs)46 void JavaObjectWeakGlobalRef::operator=(JavaObjectWeakGlobalRef&& rhs) {
47   std::swap(obj_, rhs.obj_);
48 }
49 
reset()50 void JavaObjectWeakGlobalRef::reset() {
51   if (obj_) {
52     AttachCurrentThread()->DeleteWeakGlobalRef(obj_);
53     obj_ = nullptr;
54   }
55 }
56 
57 base::android::ScopedJavaLocalRef<jobject>
get(JNIEnv * env) const58     JavaObjectWeakGlobalRef::get(JNIEnv* env) const {
59   return GetRealObject(env, obj_);
60 }
61 
GetRealObject(JNIEnv * env,jweak obj)62 base::android::ScopedJavaLocalRef<jobject> GetRealObject(
63     JNIEnv* env, jweak obj) {
64   jobject real = nullptr;
65   if (obj)
66     real = env->NewLocalRef(obj);
67   return base::android::ScopedJavaLocalRef<jobject>(env, real);
68 }
69 
Assign(const JavaObjectWeakGlobalRef & other)70 void JavaObjectWeakGlobalRef::Assign(const JavaObjectWeakGlobalRef& other) {
71   if (&other == this)
72     return;
73 
74   JNIEnv* env = AttachCurrentThread();
75   if (obj_)
76     env->DeleteWeakGlobalRef(obj_);
77 
78   obj_ = other.obj_ ? env->NewWeakGlobalRef(other.obj_) : nullptr;
79 }
80