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 #include "frameworks/bridge/common/utils/engine_helper.h"
17
18 #include "base/subwindow/subwindow_manager.h"
19 #include "core/common/container.h"
20 #include "core/common/container_scope.h"
21
22 namespace OHOS::Ace {
23 std::shared_mutex EngineHelper::mutex_;
24 std::unordered_map<int32_t, WeakPtr<Framework::JsEngine>> EngineHelper::engineWeakMap_;
25
ScopedDelegate(Framework::FrontendDelegate * delegate,int32_t id)26 ScopedDelegate::ScopedDelegate(Framework::FrontendDelegate* delegate, int32_t id)
27 : delegate_(delegate), scope_(new ContainerScope(id))
28 {}
29
~ScopedDelegate()30 ScopedDelegate::~ScopedDelegate()
31 {
32 delete scope_;
33 scope_ = nullptr;
34 }
35
AddEngine(int32_t id,WeakPtr<Framework::JsEngine> engine)36 void EngineHelper::AddEngine(int32_t id, WeakPtr<Framework::JsEngine> engine)
37 {
38 std::unique_lock<std::shared_mutex> lock(mutex_);
39 engineWeakMap_.emplace(id, engine);
40 }
41
GetEngine(int32_t id)42 RefPtr<Framework::JsEngine> EngineHelper::GetEngine(int32_t id)
43 {
44 std::shared_lock<std::shared_mutex> lock(mutex_);
45 if (id >= MIN_SUBCONTAINER_ID && id < MIN_PLUGIN_SUBCONTAINER_ID) {
46 id = SubwindowManager::GetInstance()->GetParentContainerId(id);
47 }
48 auto iter = engineWeakMap_.find(id);
49 if (iter != engineWeakMap_.end()) {
50 return iter->second.Upgrade();
51 }
52 return nullptr;
53 }
54
RemoveEngine(int32_t id)55 void EngineHelper::RemoveEngine(int32_t id)
56 {
57 std::unique_lock<std::shared_mutex> lock(mutex_);
58 engineWeakMap_.erase(id);
59 }
60
GetCurrentEngine()61 RefPtr<Framework::JsEngine> EngineHelper::GetCurrentEngine()
62 {
63 return GetEngine(Container::CurrentId());
64 }
65
GetCurrentDelegate()66 ScopedDelegate EngineHelper::GetCurrentDelegate()
67 {
68 auto engine = GetCurrentEngine();
69 if (engine) {
70 return { engine->GetFrontend(), Container::CurrentId() };
71 }
72 LOGW("Can't find current engine, using active one");
73 auto container = Container::GetActive();
74 if (!container) {
75 return { nullptr, -1 };
76 }
77 engine = GetEngine(container->GetInstanceId());
78 return { engine ? engine->GetFrontend() : nullptr, container->GetInstanceId() };
79 }
80
81 } // namespace OHOS::Ace