1 /* 2 * Copyright (C) 2025 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 TRUE_ROOT_OBJECT_H 17 #define TRUE_ROOT_OBJECT_H 18 19 #ifdef __OHOS_PLATFORM__ 20 #include "napi/native_api.h" 21 #else 22 #include <node_api.h> 23 #endif 24 25 #include <meta/interface/intf_object.h> 26 27 namespace NapiApi { 28 class Object; 29 struct JsFuncArgs; 30 } // namespace NapiApi 31 32 // Which type of a pointer to use for storing a reference to a native object. 33 enum class PtrType { WEAK, STRONG }; 34 35 /** 36 * @brief Provide access to a native IObject that backs a JS object. Optionally make the IObject reference strong so 37 * that the lifetime is controlled by JS. For example, scene is kept strongly and objects owned by scene weakly. 38 */ 39 class TrueRootObject { 40 public: 41 TrueRootObject() = delete; 42 TrueRootObject(napi_env env, napi_callback_info info); 43 44 virtual void* GetInstanceImpl(uint32_t id) = 0; 45 virtual void DisposeNative(void*) = 0; 46 47 virtual bool IsStrong() const; 48 virtual META_NS::IObject::Ptr GetNativeObject() const; 49 template<typename Type> GetNativeObject()50 auto GetNativeObject() const 51 { 52 return interface_pointer_cast<Type>(GetNativeObject()); 53 } 54 virtual void SetNativeObject(META_NS::IObject::Ptr real, PtrType ptrType); 55 virtual void UnsetNativeObject(); 56 57 virtual void Finalize(napi_env env); 58 59 static void InjectNativeObject( 60 napi_env env, const META_NS::IObject::Ptr& obj, PtrType ptrType, NapiApi::JsFuncArgs& args); 61 62 protected: 63 virtual ~TrueRootObject() = default; 64 static void destroy(TrueRootObject* object); 65 66 private: 67 // Helper class to more safely pass the native object as a javascript constructor argument. 68 class InjectedNativeObject { 69 public: 70 InjectedNativeObject(const META_NS::IObject::Ptr& obj); 71 ~InjectedNativeObject() = default; 72 META_NS::IObject::Ptr Reset(); 73 74 private: 75 META_NS::IObject::Ptr object_; 76 }; 77 void ExtractNativeObject(NapiApi::Object& resourceParam); 78 META_NS::IObject::Ptr obj_; 79 META_NS::IObject::WeakPtr objW_; 80 }; 81 82 #endif 83