1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef NAPI_REMOTE_OBJECT_HOLDER_H
17 #define NAPI_REMOTE_OBJECT_HOLDER_H
18 
19 #include <refbase.h>
20 #include <mutex>
21 
22 #include "napi_remote_object_internal.h"
23 
24 #include "napi/native_api.h"
25 
26 namespace OHOS {
27 class NAPIRemoteObjectHolder : public RefBase {
28 public:
29     explicit NAPIRemoteObjectHolder(napi_env env, const std::u16string &descriptor, napi_value thisVar);
30     ~NAPIRemoteObjectHolder();
31     sptr<IRemoteObject> Get();
32     void Set(sptr<IRemoteObject> object);
33     void attachLocalInterface(napi_value localInterface, std::string &descriptor);
34     napi_value queryLocalInterface(std::string &descriptor);
35     napi_ref GetJsObjectRef() const;
36     napi_env GetJsObjectEnv() const;
37     void CleanJsEnv();
Lock()38     void Lock()
39     {
40         mutex_.lock();
41     };
42 
Unlock()43     void Unlock()
44     {
45         mutex_.unlock();
46     };
47 
IncAttachCount()48     void IncAttachCount()
49     {
50         ++attachCount_;
51     };
52 
DecAttachCount()53     int32_t DecAttachCount()
54     {
55         if (attachCount_ > 0) {
56             --attachCount_;
57         }
58         return attachCount_;
59     };
60 
GetDescriptor()61     std::u16string GetDescriptor()
62     {
63         return descriptor_;
64     };
65 
66 private:
67     void DeleteJsObjectRefInUvWork();
68 
69     std::mutex mutex_;
70     napi_env env_ = nullptr;
71     std::thread::id jsThreadId_;
72     std::u16string descriptor_;
73     sptr<IRemoteObject> sptrCachedObject_;
74     wptr<IRemoteObject> wptrCachedObject_;
75     napi_ref localInterfaceRef_;
76     int32_t attachCount_;
77     napi_ref jsObjectRef_;
78 };
79 } // namespace OHOS
80 #endif // NAPI_REMOTE_OBJECT_HOLDER_H