1 /* 2 * Copyright (c) 2022 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 FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_ENGINE_HELPER_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_ENGINE_HELPER_H 18 19 #include <mutex> 20 #include <shared_mutex> 21 22 #include "core/common/container.h" 23 #include "base/memory/referenced.h" 24 #include "base/utils/macros.h" 25 #include "base/utils/noncopyable.h" 26 #include "bridge/js_frontend/engine/common/js_engine.h" 27 #include "bridge/js_frontend/frontend_delegate.h" 28 29 namespace OHOS::Ace { 30 class ContainerScope; 31 32 class ACE_FORCE_EXPORT ScopedDelegate final { 33 public: 34 ScopedDelegate(const RefPtr<Framework::FrontendDelegate>& delegate, int32_t id); 35 ~ScopedDelegate(); 36 37 Framework::FrontendDelegate* operator->() const 38 { 39 return AceType::RawPtr(delegate_); 40 } 41 42 bool operator==(std::nullptr_t) const 43 { 44 return delegate_ == nullptr; 45 } 46 47 operator bool() const 48 { 49 return delegate_ != nullptr; 50 } 51 52 private: 53 RefPtr<Framework::FrontendDelegate> delegate_; 54 ContainerScope* scope_; 55 }; 56 57 class ACE_FORCE_EXPORT EngineHelper final { 58 public: 59 static void AddEngine(int32_t id, WeakPtr<Framework::JsEngine> engine); 60 61 static RefPtr<Framework::JsEngine> GetEngine(int32_t id); 62 63 static void RemoveEngine(int32_t id); 64 65 static RefPtr<Framework::JsEngine> GetCurrentEngine(); 66 67 static RefPtr<Framework::JsEngine> GetCurrentEngineSafely(); 68 69 static ScopedDelegate GetCurrentDelegate(); 70 71 static ScopedDelegate GetCurrentDelegateSafely(); 72 73 static ScopedDelegate GetDefaultDelegate(); 74 75 static std::pair<int32_t, int32_t> GetPositionOnJsCode(); 76 77 static ScopedDelegate GetDelegateByContainer(RefPtr<Container> container); 78 79 static void RegisterRemoveUIContextFunc(const std::function<void(int32_t)>& removeUIContextFunc); 80 81 private: 82 static std::pair<int32_t, int32_t> StringToPair(const std::string& match); 83 84 static std::unordered_map<int32_t, WeakPtr<Framework::JsEngine>> engineWeakMap_; 85 static std::shared_mutex mutex_; 86 87 static std::function<void(int32_t)> removeUIContextFunc_; 88 89 ACE_DISALLOW_COPY_AND_MOVE(EngineHelper); 90 }; 91 } // namespace OHOS::Ace 92 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_ENGINE_HELPER_H 93