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(
48 env, 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){};
operator ()OHOS::MiscServices::PanelManagerContext65 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(
142 napi_value callback, std::string type, 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
206
SendPrivateCommand(napi_env env,napi_callback_info info)207 napi_value JsKeyboardPanelManager::SendPrivateCommand(napi_env env, napi_callback_info info)
208 {
209 auto ctxt = std::make_shared<SendPrivateCommandContext>();
210 auto input = [ctxt](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
211 PARAM_CHECK_RETURN(env, argc > 0, "at least one parameter is required!", TYPE_NONE, napi_generic_failure);
212 CHECK_RETURN(JsUtils::GetValue(env, argv[0], ctxt->privateCommand) == napi_ok,
213 "commandData covert failed, type must be Record<string, CommandDataType>", napi_generic_failure);
214 if (!TextConfig::IsPrivateCommandValid(ctxt->privateCommand)) {
215 PARAM_CHECK_RETURN(
216 env, false, "commandData size limit 32KB, count limit 5.", TYPE_NONE, napi_generic_failure);
217 }
218 ctxt->info = { std::chrono::system_clock::now(), ctxt->privateCommand };
219 privateCommandQueue_.Push(ctxt->info);
220 return napi_ok;
221 };
222 auto output = [ctxt](napi_env env, napi_value *result) -> napi_status { return napi_ok; };
223 auto exec = [ctxt](AsyncCall::Context *ctx) {
224 privateCommandQueue_.Wait(ctxt->info);
225 int32_t code = ImeSystemCmdChannel::GetInstance()->SendPrivateCommand(ctxt->privateCommand);
226 privateCommandQueue_.Pop();
227 if (code == ErrorCode::NO_ERROR) {
228 ctxt->SetState(napi_ok);
229 } else {
230 ctxt->SetErrorCode(code);
231 }
232 };
233 ctxt->SetAction(std::move(input), std::move(output));
234 // 1 means JsAPI:SendPrivateCommand has 1 params at most.
235 AsyncCall asyncCall(env, info, ctxt, 1);
236 return asyncCall.Call(env, exec, "SendPrivateCommand");
237 }
238
GetDefaultInputMethod(napi_env env,napi_callback_info info)239 napi_value JsKeyboardPanelManager::GetDefaultInputMethod(napi_env env, napi_callback_info info)
240 {
241 std::shared_ptr<Property> property;
242 int32_t ret = ImeSystemCmdChannel::GetInstance()->GetDefaultImeCfg(property);
243 if (ret != ErrorCode::NO_ERROR || property == nullptr) {
244 IMSA_HILOGE("GetDefaultImeCfg failed or property is nullptr ret: %{public}d!", ret);
245 return nullptr;
246 }
247 return GetJsInputMethodProperty(env, *property);
248 }
249
GetJsInputMethodProperty(napi_env env,const Property & property)250 napi_value JsKeyboardPanelManager::GetJsInputMethodProperty(napi_env env, const Property &property)
251 {
252 napi_value obj = nullptr;
253 napi_create_object(env, &obj);
254
255 auto ret = JsUtil::Object::WriteProperty(env, obj, "packageName", property.name);
256 ret = ret && JsUtil::Object::WriteProperty(env, obj, "name", property.name);
257 ret = ret && JsUtil::Object::WriteProperty(env, obj, "methodId", property.id);
258 ret = ret && JsUtil::Object::WriteProperty(env, obj, "id", property.id);
259 ret = ret && JsUtil::Object::WriteProperty(env, obj, "icon", property.icon);
260 ret = ret && JsUtil::Object::WriteProperty(env, obj, "iconId", property.iconId);
261 ret = ret && JsUtil::Object::WriteProperty(env, obj, "label", property.label);
262 ret = ret && JsUtil::Object::WriteProperty(env, obj, "labelId", property.labelId);
263 if (!ret) {
264 IMSA_HILOGE("init module inputMethod.Panel.PanelType failed, ret: %{public}d", ret);
265 }
266 return obj;
267 }
268
ReceivePrivateCommand(const std::unordered_map<std::string,PrivateDataValue> & privateCommand)269 void JsKeyboardPanelManager::ReceivePrivateCommand(
270 const std::unordered_map<std::string, PrivateDataValue> &privateCommand)
271 {
272 IMSA_HILOGD("start.");
273 std::string type = "panelPrivateCommand";
274 auto entry = GetEntry(type, [&privateCommand](UvEntry &entry) { entry.privateCommand = privateCommand; });
275 if (entry == nullptr) {
276 return;
277 }
278 auto eventHandler = GetEventHandler();
279 if (eventHandler == nullptr) {
280 IMSA_HILOGE("eventHandler is nullptr!");
281 return;
282 }
283 auto task = [entry]() {
284 auto paramGetter = [entry](napi_env env, napi_value *args, uint8_t argc) -> bool {
285 if (argc < 1) {
286 return false;
287 }
288 napi_value jsObject = JsUtils::GetJsPrivateCommand(env, entry->privateCommand);
289 if (jsObject == nullptr) {
290 IMSA_HILOGE("jsObject is nullptr");
291 return false;
292 }
293 // 0 means the first param of callback.
294 args[0] = { jsObject };
295 return true;
296 };
297 // 1 means callback has 1 params.
298 JsCallbackHandler::Traverse(entry->vecCopy, { 1, paramGetter });
299 };
300 eventHandler->PostTask(task, type, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
301 }
302
NotifyPanelStatus(const SysPanelStatus & sysPanelStatus)303 void JsKeyboardPanelManager::NotifyPanelStatus(const SysPanelStatus &sysPanelStatus)
304 {
305 IMSA_HILOGD("start");
306 std::string type = "isPanelShow";
307 auto entry =
308 GetEntry(type, [sysPanelStatus](UvEntry &entry) { entry.sysPanelStatus = sysPanelStatus; });
309 if (entry == nullptr) {
310 return;
311 }
312 auto eventHandler = GetEventHandler();
313 if (eventHandler == nullptr) {
314 IMSA_HILOGE("eventHandler is nullptr!");
315 return;
316 }
317 auto task = [entry]() {
318 auto paramGetter = [entry](napi_env env, napi_value *args, uint8_t argc) -> bool {
319 if (argc < 1) {
320 return false;
321 }
322 napi_value jsObject = JsPanelStatus::Write(env, entry->sysPanelStatus);
323 if (jsObject == nullptr) {
324 IMSA_HILOGE("jsObject is nullptr!");
325 return false;
326 }
327 // 0 means the first param of callback.
328 args[0] = { jsObject };
329 return true;
330 };
331 // 1 means callback has 1 params.
332 JsCallbackHandler::Traverse(entry->vecCopy, { 1, paramGetter });
333 };
334 eventHandler->PostTask(task, type, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
335 }
336
GetEventHandler()337 std::shared_ptr<AppExecFwk::EventHandler> JsKeyboardPanelManager::GetEventHandler()
338 {
339 if (handler_ == nullptr) {
340 std::lock_guard<std::mutex> lock(eventHandlerMutex_);
341 if (handler_ == nullptr) {
342 handler_ = AppExecFwk::EventHandler::Current();
343 }
344 }
345 return handler_;
346 }
347
GetEntry(const std::string & type,EntrySetter entrySetter)348 std::shared_ptr<JsKeyboardPanelManager::UvEntry> JsKeyboardPanelManager::GetEntry(
349 const std::string &type, EntrySetter entrySetter)
350 {
351 IMSA_HILOGD("start, type: %{public}s", type.c_str());
352 std::shared_ptr<UvEntry> entry = nullptr;
353 {
354 std::lock_guard<std::recursive_mutex> lock(mutex_);
355 if (jsCbMap_[type].empty()) {
356 IMSA_HILOGD("%{public}s cb-vector is empty.", type.c_str());
357 return nullptr;
358 }
359 entry = std::make_shared<UvEntry>(jsCbMap_[type], type);
360 }
361 if (entrySetter != nullptr) {
362 entrySetter(*entry);
363 }
364 return entry;
365 }
366
Write(napi_env env,const SysPanelStatus & in)367 napi_value JsPanelStatus::Write(napi_env env, const SysPanelStatus &in)
368 {
369 napi_value jsObject = nullptr;
370 napi_create_object(env, &jsObject);
371 bool ret = JsUtil::Object::WriteProperty(env, jsObject, "isSecurity", in.isSecurity);
372 ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "flag", in.flag);
373 ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "width", in.width);
374 ret = ret && JsUtil::Object::WriteProperty(env, jsObject, "height", in.height);
375 return ret ? jsObject : JsUtil::Const::Null(env);
376 }
377 } // namespace MiscServices
378 } // namespace OHOS