1 /* 2 * Copyright (c) 2021 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 OHOS_ABILITY_RUNTIME_JS_UTILS_H 17 #define OHOS_ABILITY_RUNTIME_JS_UTILS_H 18 19 #include "native_engine/native_engine.h" 20 21 #include "js_runtime.h" 22 23 namespace OHOS { 24 namespace AbilityRuntime { 25 class HandleScope final { 26 public: HandleScope(JsRuntime & jsRuntime)27 explicit HandleScope(JsRuntime& jsRuntime) 28 { 29 scopeManager_ = jsRuntime.GetNativeEngine().GetScopeManager(); 30 if (scopeManager_ != nullptr) { 31 nativeScope_ = scopeManager_->OpenEscape(); 32 } 33 } 34 ~HandleScope()35 ~HandleScope() 36 { 37 if (nativeScope_ != nullptr) { 38 scopeManager_->CloseEscape(nativeScope_); 39 nativeScope_ = nullptr; 40 } 41 scopeManager_ = nullptr; 42 } 43 Escape(NativeValue * value)44 HandleScope& Escape(NativeValue* value) 45 { 46 if (nativeScope_ != nullptr) { 47 scopeManager_->Escape(nativeScope_, value); 48 } 49 return *this; 50 } 51 52 HandleScope(const HandleScope&) = delete; 53 HandleScope(HandleScope&&) = delete; 54 HandleScope& operator=(const HandleScope&) = delete; 55 HandleScope& operator=(HandleScope&&) = delete; 56 57 private: 58 NativeScopeManager* scopeManager_ = nullptr; 59 NativeScope* nativeScope_ = nullptr; 60 }; 61 62 template<class T> ConvertNativeValueTo(NativeValue * value)63inline T* ConvertNativeValueTo(NativeValue* value) 64 { 65 return (value != nullptr) ? static_cast<T*>(value->GetInterface(T::INTERFACE_ID)) : nullptr; 66 } 67 } // namespace AbilityRuntime 68 } // namespace OHOS 69 70 #endif // OHOS_ABILITY_RUNTIME_JS_UTILS_H 71