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 "base/memory/referenced.h" 23 #include "base/utils/macros.h" 24 #include "base/utils/noncopyable.h" 25 #include "bridge/js_frontend/engine/common/js_engine.h" 26 #include "bridge/js_frontend/frontend_delegate.h" 27 28 namespace OHOS::Ace { 29 class ContainerScope; 30 31 class ACE_FORCE_EXPORT ScopedDelegate final { 32 public: 33 ScopedDelegate(const RefPtr<Framework::FrontendDelegate>& delegate, int32_t id); 34 ~ScopedDelegate(); 35 36 Framework::FrontendDelegate* operator->() const 37 { 38 return AceType::RawPtr(delegate_); 39 } 40 41 bool operator==(std::nullptr_t) const 42 { 43 return delegate_ == nullptr; 44 } 45 46 operator bool() const 47 { 48 return delegate_ != nullptr; 49 } 50 51 private: 52 RefPtr<Framework::FrontendDelegate> delegate_; 53 ContainerScope* scope_; 54 }; 55 56 class ACE_FORCE_EXPORT EngineHelper final { 57 public: 58 static void AddEngine(int32_t id, WeakPtr<Framework::JsEngine> engine); 59 60 static RefPtr<Framework::JsEngine> GetEngine(int32_t id); 61 62 static void RemoveEngine(int32_t id); 63 64 static RefPtr<Framework::JsEngine> GetCurrentEngine(); 65 66 static ScopedDelegate GetCurrentDelegate(); 67 68 static std::pair<int32_t, int32_t> GetPositionOnJsCode(); 69 70 private: 71 static std::pair<int32_t, int32_t> StringToPair(const std::string& match); 72 73 static std::unordered_map<int32_t, WeakPtr<Framework::JsEngine>> engineWeakMap_; 74 static std::shared_mutex mutex_; 75 76 ACE_DISALLOW_COPY_AND_MOVE(EngineHelper); 77 }; 78 } // namespace OHOS::Ace 79 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_ENGINE_HELPER_H 80