• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_context_module.h"
16 
17 #include "base/log/log.h"
18 #include "frameworks/bridge/declarative_frontend/engine/bindings.h"
19 #include "frameworks/core/common/container.h"
20 
21 namespace OHOS::Ace::Framework {
22 
23 thread_local std::unordered_map<int32_t, std::shared_ptr<JsValue>> JsiContextModule::contexts_;
24 
GetInstance()25 JsiContextModule* JsiContextModule::GetInstance()
26 {
27     static JsiContextModule instance;
28     return &instance;
29 }
30 
GetContext(const std::shared_ptr<JsRuntime> & runtime,const std::shared_ptr<JsValue> & thisObj,const std::vector<std::shared_ptr<JsValue>> & argv,int32_t argc)31 std::shared_ptr<JsValue> JsiContextModule::GetContext(const std::shared_ptr<JsRuntime>& runtime,
32     const std::shared_ptr<JsValue>& thisObj, const std::vector<std::shared_ptr<JsValue>>& argv, int32_t argc)
33 {
34     int32_t currentInstance = Container::CurrentId();
35     LOGD("Current ID is %{public}d", currentInstance);
36     auto it = contexts_.find(currentInstance);
37     if (it == contexts_.end()) {
38         LOGW("Context with ID %{public}d not found!", currentInstance);
39         return runtime->NewUndefined();
40     }
41     return it->second;
42 }
43 
InitContextModule(const std::shared_ptr<JsRuntime> & runtime,std::shared_ptr<JsValue> moduleObj)44 void JsiContextModule::InitContextModule(const std::shared_ptr<JsRuntime>& runtime, std::shared_ptr<JsValue> moduleObj)
45 {
46     moduleObj->SetProperty(runtime, "getContext", runtime->NewFunction(JsiContextModule::GetContext));
47 }
48 
AddContext(int32_t key,const std::shared_ptr<JsValue> & value)49 void JsiContextModule::AddContext(int32_t key, const std::shared_ptr<JsValue>& value)
50 {
51     if (contexts_.find(key) != contexts_.end()) {
52         LOGW("Context exists for key %d", key);
53         return;
54     }
55     contexts_.emplace(key, value);
56 }
57 
RemoveContext(int32_t key)58 void JsiContextModule::RemoveContext(int32_t key)
59 {
60     auto it = contexts_.find(key);
61     if (it != contexts_.end()) {
62         contexts_.erase(it);
63     } else {
64         LOGW("Context with key %{public}d does not exist!", key);
65     }
66 }
67 
68 } // namespace OHOS::Ace::Framework