1 /*
2  * Copyright (c) 2024 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 "js_keyboard_panel_manager.h"
17 
18 #include "event_checker.h"
19 #include "input_method_utils.h"
20 #include "js_callback_handler.h"
21 #include "js_util.h"
22 #include "js_utils.h"
23 
24 namespace OHOS {
25 namespace MiscServices {
26 constexpr int32_t MAX_WAIT_TIME_PRIVATE_COMMAND = 2000;
27 BlockQueue<PrivateCommandInfo> JsKeyboardPanelManager::privateCommandQueue_{ MAX_WAIT_TIME_PRIVATE_COMMAND };
28 std::mutex JsKeyboardPanelManager::managerMutex_;
29 sptr<JsKeyboardPanelManager> JsKeyboardPanelManager::keyboardPanelManager_{ nullptr };
30 
JsKeyboardPanelManager()31 JsKeyboardPanelManager::JsKeyboardPanelManager()
32 {
33     std::lock_guard<std::mutex> lock(eventHandlerMutex_);
34     handler_ = AppExecFwk::EventHandler::Current();
35 }
36 
Init(napi_env env, napi_value info)37 napi_value JsKeyboardPanelManager::Init(napi_env env, napi_value info)
38 {
39     napi_property_descriptor descriptor[] = {
40         DECLARE_NAPI_FUNCTION("sendPrivateCommand", SendPrivateCommand),
41         DECLARE_NAPI_FUNCTION("getSmartMenuCfg", GetSmartMenuCfg),
42         DECLARE_NAPI_FUNCTION("on", Subscribe),
43         DECLARE_NAPI_FUNCTION("off", UnSubscribe),
44         DECLARE_NAPI_FUNCTION("getDefaultInputMethod", GetDefaultInputMethod),
45         DECLARE_NAPI_FUNCTION("connectSystemCmd", ConnectSystemCmd),
46     };
47     NAPI_CALL(env,
48         napi_define_properties(env, info, sizeof(descriptor) / sizeof(napi_property_descriptor), descriptor));
49     return info;
50 }
51 
GetInstance()52 sptr<JsKeyboardPanelManager> JsKeyboardPanelManager::GetInstance()
53 {
54     if (keyboardPanelManager_ == nullptr) {
55         std::lock_guard<std::mutex> lock(managerMutex_);
56         if (keyboardPanelManager_ == nullptr) {
57             keyboardPanelManager_ = new (std::nothrow) JsKeyboardPanelManager();
58         }
59     }
60     return keyboardPanelManager_;
61 }
62 
63 struct PanelManagerContext : public AsyncCall::Context {
PanelManagerContextOHOS::MiscServices::PanelManagerContext64     PanelManagerContext() : Context(nullptr, nullptr){};
65     napi_status operator()(napi_env env, napi_value *result) override
66     {
67         if (status_ != napi_ok) {
68             output_ = nullptr;
69             return status_;
70         }
71         return Context::operator()(env, result);
72     }
73 };
74 
ConnectSystemCmd(napi_env env, napi_callback_info info)75 napi_value JsKeyboardPanelManager::ConnectSystemCmd(napi_env env, napi_callback_info info)
76 {
77     auto ctxt = std::make_shared<PanelManagerContext>();
78     auto manager = JsKeyboardPanelManager::GetInstance();
79     auto exec = [ctxt, env, manager](AsyncCall::Context *ctx) {
80         auto ret = ImeSystemCmdChannel::GetInstance()->ConnectSystemCmd(manager);
81         ctxt->SetErrorCode(ret);
82         CHECK_RETURN_VOID(ret == ErrorCode::NO_ERROR, "ConnectSystemCmd return error!");
83         ctxt->SetState(napi_ok);
84     };
85     // 0 means JsAPI:ConnectSystemCmd has 0 params at most.
86     AsyncCall asyncCall(env, info, ctxt, 0);
87     return asyncCall.Call(env, exec, "ConnectSystemCmd");
88 }
89 
Subscribe(napi_env env, napi_callback_info info)90 napi_value JsKeyboardPanelManager::Subscribe(napi_env env, napi_callback_info info)
91 {
92     size_t argc = 2; // has 2 param
93     napi_value argv[2] = { nullptr };
94     napi_value thisVar = nullptr;
95     void *data = nullptr;
96     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data));
97     std::string type;
98     // 2 means least param num.
99     if (argc < 2 || !JsUtil::GetValue(env, argv[0], type) ||
100         !EventChecker::IsValidEventType(EventSubscribeModule::KEYBOARD_PANEL_MANAGER, type) ||
101         JsUtil::GetType(env, argv[1]) != napi_function) {
102         IMSA_HILOGE("subscribe failed, type: %{public}s!", type.c_str());
103         return nullptr;
104     }
105     auto manager = JsKeyboardPanelManager::GetInstance();
106     IMSA_HILOGD("subscribe type: %{public}s.", type.c_str());
107     std::shared_ptr<JSCallbackObject> callback =
108         std::make_shared<JSCallbackObject>(env, argv[1], std::this_thread::get_id());
109     manager->RegisterListener(argv[1], type, callback);
110     return JsUtil::Const::Null(env);
111 }
112 
UnSubscribe(napi_env env, napi_callback_info info)113 napi_value JsKeyboardPanelManager::UnSubscribe(napi_env env, napi_callback_info info)
114 {
115     size_t argc = 2; // has 2 param
116     napi_value argv[2] = { nullptr };
117     napi_value thisVar = nullptr;
118     void *data = nullptr;
119     NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data));
120     std::string type;
121     // 1 means least param num.
122     if (argc < 1 || !JsUtil::GetValue(env, argv[0], type) ||
123         !EventChecker::IsValidEventType(EventSubscribeModule::KEYBOARD_PANEL_MANAGER, type)) {
124         IMSA_HILOGE("unsubscribe failed, type: %{public}s!", type.c_str());
125         return nullptr;
126     }
127     auto manager = JsKeyboardPanelManager::GetInstance();
128     // if the second param is not napi_function/napi_null/napi_undefined, return
129     auto paramType = JsUtil::GetType(env, argv[1]);
130     if (paramType != napi_function && paramType != napi_null && paramType != napi_undefined) {
131         return nullptr;
132     }
133     // if the second param is napi_function, delete it, else delete all
134     argv[1] = paramType == napi_function ? argv[1] : nullptr;
135 
136     IMSA_HILOGD("unsubscribe type: %{public}s.", type.c_str());
137     manager->UnRegisterListener(argv[1], type);
138     return JsUtil::Const::Null(env);
139 }
140 
RegisterListener(napi_value callback, std::string type, std::shared_ptr<JSCallbackObject> callbackObj)141 void JsKeyboardPanelManager::RegisterListener(napi_value callback, std::string type,
142     std::shared_ptr<JSCallbackObject> callbackObj)
143 {
144     IMSA_HILOGD("register listener: %{public}s.", type.c_str());
145     std::lock_guard<std::recursive_mutex> lock(mutex_);
146     if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) {
147         IMSA_HILOGD("methodName: %{public}s is not registered!", type.c_str());
148     }
149     auto callbacks = jsCbMap_[type];
150     bool ret = std::any_of(callbacks.begin(), callbacks.end(), [&callback](std::shared_ptr<JSCallbackObject> cb) {
151         return JsUtils::Equals(cb->env_, callback, cb->callback_, cb->threadId_);
152     });
153     if (ret) {
154         IMSA_HILOGD("callback already registered!");
155         return;
156     }
157 
158     IMSA_HILOGI("add %{public}s callbackObj into jsCbMap_.", type.c_str());
159     jsCbMap_[type].push_back(std::move(callbackObj));
160 }
161 
UnRegisterListener(napi_value callback, std::string type)162 void JsKeyboardPanelManager::UnRegisterListener(napi_value callback, std::string type)
163 {
164     IMSA_HILOGI("event: %{public}s.", type.c_str());
165     std::lock_guard<std::recursive_mutex> lock(mutex_);
166     if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) {
167         IMSA_HILOGE("methodName: %{public}s already unRegistered!", type.c_str());
168         return;
169     }
170 
171     if (callback == nullptr) {
172         jsCbMap_.erase(type);
173         IMSA_HILOGI("callback is nullptr.");
174         return;
175     }
176 
177     for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end(); item++) {
178         if (JsUtils::Equals((*item)->env_, callback, (*item)->callback_, (*item)->threadId_)) {
179             jsCbMap_[type].erase(item);
180             break;
181         }
182     }
183 
184     if (jsCbMap_[type].empty()) {
185         jsCbMap_.erase(type);
186     }
187 }
188 
GetSmartMenuCfg(napi_env env, napi_callback_info info)189 napi_value JsKeyboardPanelManager::GetSmartMenuCfg(napi_env env, napi_callback_info info)
190 {
191     auto ctxt = std::make_shared<SmartMenuContext>();
192     auto output = [ctxt](napi_env env, napi_value *result) -> napi_status {
193         *result = JsUtil::GetValue(env, ctxt->smartMenu);
194         return napi_ok;
195     };
196     auto exec = [ctxt](AsyncCall::Context *ctx) {
197         ctxt->smartMenu = ImeSystemCmdChannel::GetInstance()->GetSmartMenuCfg();
198         ctxt->SetState(napi_ok);
199     };
200     ctxt->SetAction(nullptr, std::move(output));
201     // 1 means JsAPI:displayOptionalInputMethod has 1 params at most.
202     AsyncCall asyncCall(env, info, ctxt, 1);
203     return asyncCall.Call(env, exec, "GetSmartMenuCfg");
204 }
205 
SendPrivateCommand(napi_env env, napi_callback_info info)206 napi_value JsKeyboardPanelManager::SendPrivateCommand(napi_env env, napi_callback_info info)
207 {
208     auto ctxt = std::make_shared<SendPrivateCommandContext>();
209     auto input = [ctxt](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
210         PARAM_CHECK_RETURN(env, argc > 0, "at least one parameter is required!", TYPE_NONE, napi_generic_failure);
211         CHECK_RETURN(JsUtils::GetValue(env, argv[0], ctxt->privateCommand) == napi_ok,
212             "commandData covert failed, type must be Record<string, CommandDataType>", napi_generic_failure);
213         if (!TextConfig::IsPrivateCommandValid(ctxt->privateCommand)) {
214             PARAM_CHECK_RETURN(env, false, "commandData size limit 32KB, count limit 5.", TYPE_NONE,
215                 napi_generic_failure);
216         }
217         ctxt->info = { std::chrono::system_clock::now(), ctxt->privateCommand };
218         privateCommandQueue_.Push(ctxt->info);
219         return napi_ok;
220     };
221     auto output = [ctxt](napi_env env, napi_value *result) -> napi_status { return napi_ok; };
222     auto exec = [ctxt](AsyncCall::Context *ctx) {
223         privateCommandQueue_.Wait(ctxt->info);
224         int32_t code = ImeSystemCmdChannel::GetInstance()->SendPrivateCommand(ctxt->privateCommand);
225         privateCommandQueue_.Pop();
226         if (code == ErrorCode::NO_ERROR) {
227             ctxt->SetState(napi_ok);
228         } else {
229             ctxt->SetErrorCode(code);
230         }
231     };
232     ctxt->SetAction(std::move(input), std::move(output));
233     // 1 means JsAPI:SendPrivateCommand has 1 params at most.
234     AsyncCall asyncCall(env, info, ctxt, 1);
235     return asyncCall.Call(env, exec, "SendPrivateCommand");
236 }
237 
GetDefaultInputMethod(napi_env env, napi_callback_info info)238 napi_value JsKeyboardPanelManager::GetDefaultInputMethod(napi_env env, napi_callback_info info)
239 {
240     std::shared_ptr<Property> property;
241     int32_t ret = ImeSystemCmdChannel::GetInstance()->GetDefaultImeCfg(property);
242     if (ret != ErrorCode::NO_ERROR || property == nullptr) {
243         IMSA_HILOGE("GetDefaultImeCfg failed or property is nullptr ret: %{public}d!", ret);
244         return nullptr;
245     }
246     return GetJsInputMethodProperty(env, *property);
247 }
248 
GetJsInputMethodProperty(napi_env env, const Property &property)249 napi_value JsKeyboardPanelManager::GetJsInputMethodProperty(napi_env env, const Property &property)
250 {
251     napi_value obj = nullptr;
252     napi_create_object(env, &obj);
253 
254     auto ret = JsUtil::Object::WriteProperty(env, obj, "packageName", property.name);
255     ret = ret && JsUtil::Object::WriteProperty(env, obj, "name", property.name);
256     ret = ret && JsUtil::Object::WriteProperty(env, obj, "methodId", property.id);
257     ret = ret && JsUtil::Object::WriteProperty(env, obj, "id", property.id);
258     ret = ret && JsUtil::Object::WriteProperty(env, obj, "icon", property.icon);
259     ret = ret && JsUtil::Object::WriteProperty(env, obj, "iconId", property.iconId);
260     ret = ret && JsUtil::Object::WriteProperty(env, obj, "label", property.label);
261     ret = ret && JsUtil::Object::WriteProperty(env, obj, "labelId", property.labelId);
262     if (!ret) {
263         IMSA_HILOGE("init module inputMethod.Panel.PanelType failed, ret: %{public}d", ret);
264     }
265     return obj;
266 }
267 
ReceivePrivateCommand( const std::unordered_map<std::string, PrivateDataValue> &privateCommand)268 void JsKeyboardPanelManager::ReceivePrivateCommand(
269     const std::unordered_map<std::string, PrivateDataValue> &privateCommand)
270 {
271     IMSA_HILOGD("start.");
272     std::string type = "panelPrivateCommand";
273     auto entry = GetEntry(type, [&privateCommand](UvEntry &entry) { entry.privateCommand = privateCommand; });
274     if (entry == nullptr) {
275         return;
276     }
277     auto eventHandler = GetEventHandler();
278     if (eventHandler == nullptr) {
279         IMSA_HILOGE("eventHandler is nullptr!");
280         return;
281     }
282     auto task = [entry]() {
283         auto paramGetter = [entry](napi_env env, napi_value *args, uint8_t argc) -> bool {
284             if (argc < 1) {
285                 return false;
286             }
287             napi_value jsObject = JsUtils::GetJsPrivateCommand(env, entry->privateCommand);
288             if (jsObject == nullptr) {
289                 IMSA_HILOGE("jsObject is nullptr");
290                 return false;
291             }
292             // 0 means the first param of callback.
293             args[0] = { jsObject };
294             return true;
295         };
296         // 1 means callback has 1 params.
297         JsCallbackHandler::Traverse(entry->vecCopy, { 1, paramGetter });
298     };
299     eventHandler->PostTask(task, type, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
300 }
301 
NotifyPanelStatus(const SysPanelStatus &sysPanelStatus)302 void JsKeyboardPanelManager::NotifyPanelStatus(const SysPanelStatus &sysPanelStatus)
303 {
304     IMSA_HILOGD("start");
305     std::string type = "isPanelShow";
306     auto entry =
307         GetEntry(type, [sysPanelStatus](UvEntry &entry) { entry.sysPanelStatus = sysPanelStatus; });
308     if (entry == nullptr) {
309         return;
310     }
311     auto eventHandler = GetEventHandler();
312     if (eventHandler == nullptr) {
313         IMSA_HILOGE("eventHandler is nullptr!");
314         return;
315     }
316     auto task = [entry]() {
317         auto paramGetter = [entry](napi_env env, napi_value *args, uint8_t argc) -> bool {
318             if (argc < 1) {
319                 return false;
320             }
321             napi_value jsObject = JsPanelStatus::Write(env, entry->sysPanelStatus);
322             if (jsObject == nullptr) {
323                 IMSA_HILOGE("jsObject is nullptr!");
324                 return false;
325             }
326             // 0 means the first param of callback.
327             args[0] = { jsObject };
328             return true;
329         };
330         // 1 means callback has 1 params.
331         JsCallbackHandler::Traverse(entry->vecCopy, { 1, paramGetter });
332     };
333     eventHandler->PostTask(task, type, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
334 }
335 
GetEventHandler()336 std::shared_ptr<AppExecFwk::EventHandler> JsKeyboardPanelManager::GetEventHandler()
337 {
338     if (handler_ == nullptr) {
339         std::lock_guard<std::mutex> lock(eventHandlerMutex_);
340         if (handler_ == nullptr) {
341             handler_ = AppExecFwk::EventHandler::Current();
342         }
343     }
344     return handler_;
345 }
346 
GetEntry(const std::string &type, EntrySetter entrySetter)347 std::shared_ptr<JsKeyboardPanelManager::UvEntry> JsKeyboardPanelManager::GetEntry(const std::string &type,
348     EntrySetter entrySetter)
349 {
350     IMSA_HILOGD("start, type: %{public}s", type.c_str());
351     std::shared_ptr<UvEntry> entry = nullptr;
352     {
353         std::lock_guard<std::recursive_mutex> lock(mutex_);
354         if (jsCbMap_[type].empty()) {
355             IMSA_HILOGD("%{public}s cb-vector is empty.", type.c_str());
356             return nullptr;
357         }
358         entry = std::make_shared<UvEntry>(jsCbMap_[type], type);
359     }
360     if (entrySetter != nullptr) {
361         entrySetter(*entry);
362     }
363     return entry;
364 }
365 
Write(napi_env env, const SysPanelStatus &in)366 napi_value JsPanelStatus::Write(napi_env env, const SysPanelStatus &in)
367 {
368     napi_value jsObject = nullptr;
369     napi_create_object(env, &jsObject);
370     bool ret = JsUtil::Object::WriteProperty(env, jsObject, "inputType", static_cast<int32_t>(in.inputType));
371     ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "flag", in.flag);
372     ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "width", in.width);
373     ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "height", in.height);
374     return ret ? jsObject : JsUtil::Const::Null(env);
375 }
376 } // namespace MiscServices
377 } // namespace OHOS