• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 "mmi_service.h"
17 
18 #ifdef OHOS_BUILD_PC_PRIORITY
19 #include <sched.h>
20 #endif // OHOS_BUILD_PC_PRIORITY
21 #include <sys/signalfd.h>
22 #include <csignal>
23 #ifdef OHOS_RSS_CLIENT
24 #include <unordered_map>
25 #endif // OHOS_RSS_CLIENT
26 
27 #include "bundle_name_parser.h"
28 #include "misc_product_type_parser.h"
29 #include "product_type_parser.h"
30 #include "special_input_device_parser.h"
31 #include "product_name_definition_parser.h"
32 #include "json_parser.h"
33 
34 #include "ability_manager_client.h"
35 #include "account_manager.h"
36 #include "anr_manager.h"
37 #include "app_state_observer.h"
38 #include "device_event_monitor.h"
39 #include "dfx_dump_catcher.h"
40 #include "dfx_hisysevent.h"
41 
42 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
43 #include "display_event_monitor.h"
44 #endif // OHOS_BUILD_ENABLE_KEYBOARD
45 #include "event_dump.h"
46 #include "event_statistic.h"
47 #include "event_log_helper.h"
48 #include "ffrt.h"
49 #ifdef OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
50 #include "fingersense_wrapper.h"
51 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
52 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
53 #include "gesturesense_wrapper.h"
54 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
55 #ifndef OHOS_BUILD_ENABLE_WATCH
56 #include "infrared_emitter_controller.h"
57 #endif // OHOS_BUILD_ENABLE_WATCH
58 #include "ipc_skeleton.h"
59 #include "i_preference_manager.h"
60 #include "key_auto_repeat.h"
61 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
62 #include "key_shortcut_manager.h"
63 #endif // SHORTCUT_KEY_MANAGER_ENABLED
64 #include "permission_helper.h"
65 #include "pointer_device_manager.h"
66 #include "cursor_drawing_component.h"
67 #include "touch_event_normalize.h"
68 #if defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
69 #include "touch_gesture_manager.h"
70 #endif // defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
71 #include "util_ex.h"
72 #include "xcollie/xcollie.h"
73 #ifdef OHOS_BUILD_ENABLE_POINTER
74 #include "touchpad_settings_handler.h"
75 #include "account_manager.h"
76 #endif // OHOS_BUILD_ENABLE_POINTER
77 #include "multimodal_input_plugin_manager.h"
78 
79 #ifdef OHOS_RSS_CLIENT
80 #include "res_sched_client.h"
81 #include "res_type.h"
82 #include "system_ability_definition.h"
83 #endif // OHOS_RSS_CLIENT
84 #include "setting_datashare.h"
85 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
86 #include "touch_drawing_manager.h"
87 #endif // #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
88 #ifdef OHOS_BUILD_ENABLE_ANCO
89 #include "app_mgr_client.h"
90 #include "running_process_info.h"
91 #endif // OHOS_BUILD_ENABLE_ANCO
92 
93 #ifdef PLAYER_FRAMEWORK_EXISTS
94 #include "input_screen_capture_agent.h"
95 #endif // PLAYER_FRAMEWORK_EXISTS
96 #include "tablet_subscriber_handler.h"
97 #include "config_policy_utils.h"
98 #undef MMI_LOG_TAG
99 #define MMI_LOG_TAG "MMIService"
100 #undef MMI_LOG_DOMAIN
101 #define MMI_LOG_DOMAIN MMI_LOG_SERVER
102 
103 namespace OHOS {
104 namespace MMI {
105 namespace {
106 std::mutex g_instanceMutex;
107 MMIService* g_MMIService;
108 const std::string DEF_INPUT_SEAT { "seat0" };
109 const char* THREAD_NAME { "mmi_service" };
110 constexpr int32_t WATCHDOG_INTERVAL_TIME { 30000 };
111 [[ maybe_unused ]] constexpr int32_t WATCHDOG_DELAY_TIME { 40000 };
112 constexpr int32_t RELOAD_DEVICE_TIME { 2000 };
113 [[ maybe_unused ]] constexpr int32_t WATCHDOG_WARNTIME { 6000 };
114 [[ maybe_unused ]] constexpr int32_t WATCHDOG_BLOCKTIME { 3000 };
115 constexpr int32_t REMOVE_OBSERVER { -2 };
116 constexpr int32_t REPEAT_COUNT { 2 };
117 constexpr int32_t UNSUBSCRIBED { -1 };
118 constexpr int32_t UNOBSERVED { -1 };
119 constexpr int32_t SUBSCRIBED { 1 };
120 [[ maybe_unused ]] constexpr int32_t DISTRIBUTE_TIME { 1000 }; // 1000ms
121 constexpr int32_t COMMON_PARAMETER_ERROR { 401 };
122 constexpr size_t MAX_FRAME_NUMS { 100 };
123 constexpr int32_t THREAD_BLOCK_TIMER_SPAN_S { 3 };
124 constexpr int32_t PRINT_INTERVAL_TIME { 30000 };
125 constexpr int32_t RETRY_CHECK_TIMES { 5 };
126 constexpr int32_t CHECK_EEVENT_INTERVAL_TIME { 4000 };
127 constexpr int32_t MAX_MULTI_TOUCH_POINT_NUM { 10 };
128 const int32_t DEFAULT_POINTER_COLOR { 0x000000 };
129 constexpr int32_t MAX_SPEED { 20 };
130 constexpr int32_t MIN_SPEED { 1 };
131 constexpr int32_t MIN_ROWS { 1 };
132 constexpr int32_t MAX_ROWS { 100 };
133 constexpr int32_t TOUCHPAD_SCROLL_ROWS { 3 };
134 constexpr int32_t UID_TRANSFORM_DIVISOR { 200000 };
135 const std::string PRODUCT_DEVICE_TYPE = system::GetParameter("const.product.devicetype", "unknown");
136 const std::string PRODUCT_TYPE_PC = "2in1";
137 const int32_t ERROR_WINDOW_ID_PERMISSION_DENIED = 26500001;
138 constexpr int32_t MAX_DEVICE_NUM { 10 };
139 constexpr int32_t GAME_UID { 7011 };
140 constexpr int32_t PENGLAI_UID { 7655 };
141 constexpr int32_t SYNERGY_UID { 5521 };
142 
143 const size_t QUOTES_BEGIN = 1;
144 const size_t QUOTES_END = 2;
145 const std::set<int32_t> g_keyCodeValueSet = {
146 #ifndef OHOS_BUILD_ENABLE_WATCH
147     KeyEvent::KEYCODE_FN, KeyEvent::KEYCODE_DPAD_UP, KeyEvent::KEYCODE_DPAD_DOWN, KeyEvent::KEYCODE_DPAD_LEFT,
148     KeyEvent::KEYCODE_DPAD_RIGHT, KeyEvent::KEYCODE_ALT_LEFT, KeyEvent::KEYCODE_ALT_RIGHT,
149     KeyEvent::KEYCODE_SHIFT_LEFT, KeyEvent::KEYCODE_SHIFT_RIGHT, KeyEvent::KEYCODE_TAB, KeyEvent::KEYCODE_ENTER,
150     KeyEvent::KEYCODE_DEL, KeyEvent::KEYCODE_MENU, KeyEvent::KEYCODE_PAGE_UP, KeyEvent::KEYCODE_PAGE_DOWN,
151     KeyEvent::KEYCODE_ESCAPE, KeyEvent::KEYCODE_FORWARD_DEL, KeyEvent::KEYCODE_CTRL_LEFT, KeyEvent::KEYCODE_CTRL_RIGHT,
152     KeyEvent::KEYCODE_CAPS_LOCK, KeyEvent::KEYCODE_SCROLL_LOCK, KeyEvent::KEYCODE_META_LEFT,
153     KeyEvent::KEYCODE_META_RIGHT, KeyEvent::KEYCODE_SYSRQ, KeyEvent::KEYCODE_BREAK, KeyEvent::KEYCODE_MOVE_HOME,
154     KeyEvent::KEYCODE_MOVE_END, KeyEvent::KEYCODE_INSERT, KeyEvent::KEYCODE_F1, KeyEvent::KEYCODE_F2,
155     KeyEvent::KEYCODE_F3, KeyEvent::KEYCODE_F4, KeyEvent::KEYCODE_F5, KeyEvent::KEYCODE_F6, KeyEvent::KEYCODE_F7,
156     KeyEvent::KEYCODE_F8, KeyEvent::KEYCODE_F9, KeyEvent::KEYCODE_F10, KeyEvent::KEYCODE_F11, KeyEvent::KEYCODE_F12,
157     KeyEvent::KEYCODE_NUM_LOCK
158 #endif // OHOS_BUILD_ENABLE_WATCH
159 };
160 #ifdef OHOS_BUILD_ENABLE_ANCO
161 constexpr int32_t DEFAULT_USER_ID { 100 };
162 #endif // OHOS_BUILD_ENABLE_ANCO
163 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
164 const std::string PRODUCT_TYPE = OHOS::system::GetParameter("const.build.product", "HYM");
165 // Define vkeyboard functions from vendor
166 const std::string VKEYBOARD_PATH { "libvkeyboard_device.z.so" };
167 void* g_VKeyboardHandle = nullptr;
168 typedef int32_t (*HANDLE_TOUCHPOINT_TYPE)(
169     double screenX, double screenY, int touchId, int32_t eventType, double touchPressure,
170     int32_t longAxis, int32_t shortAxis);
171 HANDLE_TOUCHPOINT_TYPE handleTouchPoint_ = nullptr;
172 typedef int32_t (*STATEMACINEMESSAGQUEUE_GETLIBINPUTMESSAGE_TYPE)(
173     int& delayMs, int& toggleCodeSecond, int& keyCode);
174 STATEMACINEMESSAGQUEUE_GETLIBINPUTMESSAGE_TYPE statemachineMessageQueue_getLibinputMessage_ = nullptr;
175 typedef void (*TRACKPADENGINE_GETALLTOUCHMESSAGE_TYPE)(
176     std::vector<std::vector<int32_t>>& retMsgList);
177 TRACKPADENGINE_GETALLTOUCHMESSAGE_TYPE trackPadEngine_getAllTouchMessage_ = nullptr;
178 typedef void (*TRACKPADENGINE_CLEARTOUCHMESSAGE_TYPE)();
179 TRACKPADENGINE_CLEARTOUCHMESSAGE_TYPE trackPadEngine_clearTouchMessage_ = nullptr;
180 typedef void (*TRACKPADENGINE_GETALLKEYMESSAGE_TYPE)(
181     std::vector<std::vector<int32_t>>& retMsgList);
182 TRACKPADENGINE_GETALLKEYMESSAGE_TYPE trackPadEngine_getAllKeyMessage_ = nullptr;
183 typedef void (*TRACKPADENGINE_CLEARKEYMESSAGE_TYPE)();
184 TRACKPADENGINE_CLEARKEYMESSAGE_TYPE trackPadEngine_clearKeyMessage_ = nullptr;
185 typedef int32_t (*VKEYBOARD_CREATEVKEYBOARDDEVICE_TYPE)(IRemoteObject* &vkeyboardDevice);
186 VKEYBOARD_CREATEVKEYBOARDDEVICE_TYPE vkeyboard_createVKeyboardDevice_ = nullptr;
187 typedef int32_t (*VKEYBOARD_ONFUNCKEYEVENT_TYPE)(std::shared_ptr<KeyEvent> funcKeyEvent);
188 VKEYBOARD_ONFUNCKEYEVENT_TYPE vkeyboard_onFuncKeyEvent_ = nullptr;
189 typedef void (*VKEYBOARD_HARDWAREKEYEVENTDETECTED_TYPE)(const std::string &keyName);
190 VKEYBOARD_HARDWAREKEYEVENTDETECTED_TYPE vkeyboard_hardwareKeyEventDetected_ = nullptr;
191 typedef int32_t (*VKEYBOARD_GETKEYBOARDACTIVATIONSTATE_TYPE)();
192 VKEYBOARD_GETKEYBOARDACTIVATIONSTATE_TYPE vkeyboard_getKeyboardActivationState_ = nullptr;
193 typedef bool (*GAUSSIANKEYBOARD_ISFLOATINGKEYBOARD_TYPE)();
194 GAUSSIANKEYBOARD_ISFLOATINGKEYBOARD_TYPE gaussiankeyboard_isFloatingKeyboard_ = nullptr;
195 typedef bool (*VKEYBOARD_ISSHOWN)();
196 VKEYBOARD_ISSHOWN vkeyboard_isShown_ = nullptr;
197 typedef int32_t (*GET_LIBINPUT_EVENT_FOR_VKEYBOARD_TYPE)(
198     libinput_event_touch *touch, int32_t& delayMs, std::vector<libinput_event*>& events);
199 GET_LIBINPUT_EVENT_FOR_VKEYBOARD_TYPE getLibinputEventForVKeyboard_ = nullptr;
200 typedef int32_t (*GET_LIBINPUT_EVENT_FOR_VTRACKPAD_TYPE)(
201     libinput_event_touch *touch, std::vector<libinput_event*>& events);
202 GET_LIBINPUT_EVENT_FOR_VTRACKPAD_TYPE getLibinputEventForVTrackpad_ = nullptr;
203 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
204 #ifdef OHOS_BUILD_PC_PRIORITY
205 constexpr int32_t PC_PRIORITY { 2 };
206 #endif // OHOS_BUILD_PC_PRIORITY
207 } // namespace
208 
209 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(MMIService::GetInstance());
210 
CheckDefineOutput(const char * fmt,Ts...args)211 template <class... Ts> void CheckDefineOutput(const char *fmt, Ts... args)
212 {
213     CHKPV(fmt);
214     char buf[MAX_PACKET_BUF_SIZE] = {};
215     int32_t ret = snprintf_s(buf, MAX_PACKET_BUF_SIZE, MAX_PACKET_BUF_SIZE - 1, fmt, args...);
216     if (ret == -1) {
217         KMSG_LOGE("Call snprintf_s failed.ret = %d", ret);
218         return;
219     }
220     KMSG_LOGI("%s", buf);
221     MMI_HILOGI("%{public}s", buf);
222 }
223 
CheckDefine()224 static void CheckDefine()
225 {
226     CheckDefineOutput("ChkDefs:");
227 #ifdef OHOS_BUILD_ENABLE_POINTER_DRAWING
228     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_POINTER_DRAWING");
229 #endif // OHOS_BUILD_ENABLE_POINTER_DRAWING
230 #ifdef OHOS_BUILD_ENABLE_INTERCEPTOR
231     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_INTERCEPTOR");
232 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR
233 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
234     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_KEYBOARD");
235 #endif // OHOS_BUILD_ENABLE_KEYBOARD
236 #ifdef OHOS_BUILD_ENABLE_POINTER
237     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_POINTER");
238 #endif // OHOS_BUILD_ENABLE_POINTER
239 #ifdef OHOS_BUILD_ENABLE_TOUCH
240     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_TOUCH");
241 #endif // OHOS_BUILD_ENABLE_TOUCH
242 #ifdef OHOS_BUILD_ENABLE_MONITOR
243     CheckDefineOutput("%-40s", "OHOS_BUILD_ENABLE_MONITOR");
244 #endif // OHOS_BUILD_ENABLE_MONITOR
245 }
246 
MMIService()247 MMIService::MMIService() : SystemAbility(MMIService::MULTIMODAL_INPUT_CONNECT_SERVICE_ID, true) {}
248 
~MMIService()249 MMIService::~MMIService()
250 {
251     if (g_MMIService != nullptr) {
252         g_MMIService = nullptr;
253     }
254     MMI_HILOGI("~MMIService");
255 }
256 
GetInstance()257 MMIService* MMIService::GetInstance()
258 {
259     if (g_MMIService == nullptr) {
260         std::lock_guard<std::mutex> lock(g_instanceMutex);
261         if (g_MMIService == nullptr) {
262             MMI_HILOGI("New MMIService");
263             g_MMIService = new MMIService();
264         }
265     }
266     return g_MMIService;
267 }
268 
AddEpoll(EpollEventType type,int32_t fd,bool readOnly)269 int32_t MMIService::AddEpoll(EpollEventType type, int32_t fd, bool readOnly)
270 {
271     if (type < EPOLL_EVENT_BEGIN || type >= EPOLL_EVENT_END) {
272         MMI_HILOGE("Invalid param type");
273         return RET_ERR;
274     }
275     if (fd < 0) {
276         MMI_HILOGE("Invalid param fd_");
277         return RET_ERR;
278     }
279     if (mmiFd_ < 0) {
280         MMI_HILOGE("Invalid param mmiFd_");
281         return RET_ERR;
282     }
283     auto eventData = std::make_shared<mmi_epoll_event>();
284     eventData->fd = fd;
285     eventData->event_type = type;
286     MMI_HILOGI("The userdata:[fd:%{public}d, type:%{public}d]", eventData->fd, eventData->event_type);
287 
288     struct epoll_event ev = {};
289     if (readOnly) {
290         ev.events = 0;
291     } else {
292         ev.events = EPOLLIN;
293     }
294     ev.data.fd = fd;
295     auto ret = EpollCtl(fd, EPOLL_CTL_ADD, ev, mmiFd_);
296     if (ret < 0) {
297         eventData = nullptr;
298         ev.data.ptr = nullptr;
299         return ret;
300     }
301     AddEpollEvent(fd, eventData);
302     return RET_OK;
303 }
304 
DelEpoll(EpollEventType type,int32_t fd)305 int32_t MMIService::DelEpoll(EpollEventType type, int32_t fd)
306 {
307     if (type < EPOLL_EVENT_BEGIN || type >= EPOLL_EVENT_END) {
308         MMI_HILOGE("Invalid param type");
309         return RET_ERR;
310     }
311     if (fd < 0) {
312         MMI_HILOGE("Invalid param fd_");
313         return RET_ERR;
314     }
315     if (mmiFd_ < 0) {
316         MMI_HILOGE("Invalid param mmiFd_");
317         return RET_ERR;
318     }
319     struct epoll_event ev = {};
320     auto ret = EpollCtl(fd, EPOLL_CTL_DEL, ev, mmiFd_);
321     if (ret < 0) {
322         MMI_HILOGE("DelEpoll failed");
323         return ret;
324     }
325     return RET_OK;
326 }
327 
IsRunning() const328 bool MMIService::IsRunning() const
329 {
330     return (state_ == ServiceRunningState::STATE_RUNNING);
331 }
332 
InitLibinputService()333 bool MMIService::InitLibinputService()
334 {
335     if (!(libinputAdapter_.Init([](void *event, int64_t frameTime) { InputHandler->OnEvent(event, frameTime); }))) {
336         MMI_HILOGE("Libinput init, bind failed");
337         return false;
338     }
339     auto inputFds = libinputAdapter_.GetInputFds();
340     for (auto fd : inputFds) {
341         auto ret = AddEpoll(EPOLL_EVENT_INPUT, fd);
342         if (ret < 0) {
343             MMI_HILOGE("AddEpoll error ret:%{public}d", ret);
344             EpollClose();
345             return false;
346         }
347         MMI_HILOGD("AddEpoll, epollfd:%{public}d, fd:%{public}d", mmiFd_, fd);
348     }
349     return true;
350 }
351 
InitService()352 bool MMIService::InitService()
353 {
354     MMI_HILOGD("Server msg handler Init");
355     sMsgHandler_.Init(*this);
356     if (state_ != ServiceRunningState::STATE_NOT_START) {
357         MMI_HILOGE("Service running status is not enabled");
358         return false;
359     }
360     if (EpollCreate(MAX_EVENT_SIZE) < 0) {
361         MMI_HILOGE("Create epoll failed");
362         return false;
363     }
364     auto ret = AddEpoll(EPOLL_EVENT_SOCKET, epollFd_);
365     if (ret < 0) {
366         MMI_HILOGE("AddEpoll error ret:%{public}d", ret);
367         EpollClose();
368         return false;
369     }
370     state_ = ServiceRunningState::STATE_RUNNING;
371     if (!(Publish(this))) {
372         state_ = ServiceRunningState::STATE_NOT_START;
373         MMI_HILOGE("Service initialization failed");
374         EpollClose();
375         return false;
376     }
377     MMI_HILOGI("AddEpoll, epollfd:%{public}d, fd:%{public}d", mmiFd_, epollFd_);
378     return true;
379 }
380 
InitDelegateTasks()381 bool MMIService::InitDelegateTasks()
382 {
383     CALL_DEBUG_ENTER;
384     if (!delegateTasks_.Init()) {
385         MMI_HILOGE("The delegate task init failed");
386         return false;
387     }
388     auto ret = AddEpoll(EPOLL_EVENT_ETASK, delegateTasks_.GetReadFd());
389     if (ret < 0) {
390         MMI_HILOGE("AddEpoll error ret:%{public}d", ret);
391         EpollClose();
392         return false;
393     }
394     std::function<int32_t(DTaskCallback)> fun = [this](DTaskCallback cb) -> int32_t {
395         return delegateTasks_.PostSyncTask(cb);
396     };
397     std::function<int32_t(DTaskCallback)> asyncFun = [this](DTaskCallback cb) -> int32_t {
398         return delegateTasks_.PostAsyncTask(cb);
399     };
400     delegateInterface_ = std::make_shared<DelegateInterface>(fun, asyncFun);
401     delegateInterface_->Init();
402     MMI_HILOGI("AddEpoll, epollfd:%{public}d, fd:%{public}d", mmiFd_, delegateTasks_.GetReadFd());
403     return true;
404 }
405 __attribute__((no_sanitize("cfi")))
Init()406 int32_t MMIService::Init()
407 {
408     CheckDefine();
409     MMI_HILOGD("WindowsManager Init");
410     WIN_MGR->Init(*this);
411     MMI_HILOGD("NapProcess Init");
412     NapProcess::GetInstance()->Init(*this);
413     MMI_HILOGD("ANRManager Init");
414     ANRMgr->Init(*this);
415     InputPluginManager::GetInstance()->Init();
416     MMI_HILOGI("PointerDrawingManager Init");
417     mmiFd_ = EpollCreate(MAX_EVENT_SIZE);
418     if (mmiFd_ < 0) {
419         MMI_HILOGE("Create epoll failed");
420         return EPOLL_CREATE_FAIL;
421     }
422     MMI_HILOGD("Input msg handler init");
423     InputHandler->Init(*this);
424     MMI_HILOGD("Init DelegateTasks init");
425     if (!InitDelegateTasks()) {
426         MMI_HILOGE("Delegate tasks init failed");
427         return ETASKS_INIT_FAIL;
428     }
429     MMI_HILOGD("Libinput service init");
430     if (!InitLibinputService()) {
431         MMI_HILOGE("Libinput init failed");
432         return LIBINPUT_INIT_FAIL;
433     }
434     SetRecvFun([this] (SessionPtr sess, NetPacket& pkt) {sMsgHandler_.OnMsgHandler(sess, pkt);});
435     KeyMapMgr->GetConfigKeyValue("default_keymap", KeyMapMgr->GetDefaultKeyId());
436     OHOS::system::SetParameter(INPUT_POINTER_DEVICES, "false");
437     if (!InitService()) {
438         MMI_HILOGE("Saservice init failed");
439         return SASERVICE_INIT_FAIL;
440     }
441     MMI_HILOGI("Set para input.pointer.device false");
442     return RET_OK;
443 }
444 
OnStart()445 void MMIService::OnStart()
446 {
447     CHK_PID_AND_TID();
448     int32_t ret = Init();
449     CHKNOKRV(ret, "Init mmi_service failed");
450     MMI_HILOGD("Started successfully");
451     AddReloadDeviceTimer();
452     auto keyHandler = InputHandler->GetKeyCommandHandler();
453     if (keyHandler != nullptr) {
454         keyHandler->PreHandleEvent();
455     }
456     t_ = std::thread([this] {this->OnThread();});
457     pthread_setname_np(t_.native_handle(), THREAD_NAME);
458     eventMonitorThread_ = std::thread(&EventStatistic::WriteEventFile);
459     pthread_setname_np(eventMonitorThread_.native_handle(), "event-monitor");
460     InitCustomConfig();
461 #ifdef OHOS_RSS_CLIENT
462     MMI_HILOGI("Add system ability listener start");
463     AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
464     MMI_HILOGI("Add system ability listener success");
465 #endif // OHOS_RSS_CLIENT
466 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
467     MMI_HILOGI("Add SA listener COMMON_EVENT_SERVICE_ID start");
468     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
469     MMI_HILOGI("Add SA listener COMMON_EVENT_SERVICE_ID success");
470 #endif // OHOS_BUILD_ENABLE_KEYBOARD
471 #if defined(OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER) && defined(OHOS_BUILD_ENABLE_KEYBOARD)
472     FINGERSENSE_WRAPPER->InitFingerSenseWrapper();
473     if (FINGERSENSE_WRAPPER->enableFingersense_ != nullptr) {
474         MMI_HILOGI("Start enable fingersense");
475         FINGERSENSE_WRAPPER->enableFingersense_();
476     }
477 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER && OHOS_BUILD_ENABLE_KEYBOARD
478 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
479     GESTURESENSE_WRAPPER->InitGestureSenseWrapper();
480 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
481     MMI_HILOGI("Add app manager service listener start");
482     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
483     APP_OBSERVER_MGR->InitAppStateObserver();
484     MMI_HILOGI("Add app manager service listener end");
485     AddSystemAbilityListener(RENDER_SERVICE);
486     AddAppDebugListener();
487     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
488 #ifdef OHOS_BUILD_ENABLE_COMBINATION_KEY
489     AddSystemAbilityListener(SENSOR_SERVICE_ABILITY_ID);
490 #endif // OHOS_BUILD_ENABLE_COMBINATION_KEY
491 #ifdef OHOS_BUILD_ENABLE_ANCO
492     InitAncoUds();
493 #endif // OHOS_BUILD_ENABLE_ANCO
494     InitPreferences();
495 #if OHOS_BUILD_ENABLE_POINTER
496     bool switchFlag = false;
497     TOUCH_EVENT_HDR->GetTouchpadDoubleTapAndDragState(switchFlag);
498     TOUCH_EVENT_HDR->SetTouchpadDoubleTapAndDragState(switchFlag);
499 #endif
500     TimerMgr->AddTimer(WATCHDOG_INTERVAL_TIME, -1, [this]() {
501         MMI_HILOGI("Set thread status flag to true");
502         threadStatusFlag_ = true;
503     }, "MMIService-OnStart");
504     [[ maybe_unused ]] auto taskFunc = [this]() {
505         if (threadStatusFlag_) {
506             MMI_HILOGI("Set thread status flag to false");
507             threadStatusFlag_ = false;
508         } else {
509             MMI_HILOGI("Mmi-server Timeout");
510         }
511     };
512     MMI_HILOGI("Run periodical task success");
513     InitPrintClientInfo();
514 }
515 
OnStop()516 void MMIService::OnStop()
517 {
518     CHK_PID_AND_TID();
519     UdsStop();
520     libinputAdapter_.Stop();
521     state_ = ServiceRunningState::STATE_NOT_START;
522 #ifdef OHOS_RSS_CLIENT
523     MMI_HILOGI("Remove system ability listener start");
524     RemoveSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
525     MMI_HILOGI("Remove system ability listener success");
526 #endif // OHOS_RSS_CLIENT
527 #ifdef OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
528     RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
529 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
530     RemoveSystemAbilityListener(APP_MGR_SERVICE_ID);
531     RemoveSystemAbilityListener(RENDER_SERVICE);
532     RemoveAppDebugListener();
533     RemoveSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
534 #ifdef OHOS_BUILD_ENABLE_ANCO
535     StopAncoUds();
536 #endif // OHOS_BUILD_ENABLE_ANCO
537 }
538 
AddAppDebugListener()539 void MMIService::AddAppDebugListener()
540 {
541     CALL_DEBUG_ENTER;
542     appDebugListener_ = AppDebugListener::GetInstance();
543     auto begin = std::chrono::high_resolution_clock::now();
544     auto errCode =
545         AAFwk::AbilityManagerClient::GetInstance()->RegisterAppDebugListener(appDebugListener_);
546     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
547         std::chrono::high_resolution_clock::now() - begin).count();
548 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
549     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::REGISTER_APP_DEBUG_LISTENER, durationMS);
550 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
551     if (errCode != RET_OK) {
552         MMI_HILOGE("Call RegisterAppDebugListener failed, errCode:%{public}d", errCode);
553     }
554 }
555 
RemoveAppDebugListener()556 void MMIService::RemoveAppDebugListener()
557 {
558     CALL_DEBUG_ENTER;
559     CHKPV(appDebugListener_);
560     auto begin = std::chrono::high_resolution_clock::now();
561     auto errCode = AAFwk::AbilityManagerClient::GetInstance()->UnregisterAppDebugListener(appDebugListener_);
562     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
563         std::chrono::high_resolution_clock::now() - begin).count();
564 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
565     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::REGISTER_APP_DEBUG_LISTENER, durationMS);
566 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
567     if (errCode != RET_OK) {
568         MMI_HILOGE("Call UnregisterAppDebugListener failed, errCode:%{public}d", errCode);
569     }
570 }
571 
AllocSocketFd(const std::string & programName,const int32_t moduleType,int32_t & toReturnClientFd,int32_t & tokenType)572 ErrCode MMIService::AllocSocketFd(const std::string &programName, const int32_t moduleType, int32_t &toReturnClientFd,
573     int32_t &tokenType)
574 {
575     int32_t pid = GetCallingPid();
576     if (!IsRunning()) {
577         MMI_HILOGE("Service is not running. pid:%{public}d, go switch default", pid);
578         return MMISERVICE_NOT_RUNNING;
579     }
580     if (programName.empty()) {
581         MMI_HILOGE("Invalid programName");
582         return RET_ERR;
583     }
584     tokenType = PER_HELPER->GetTokenType();
585     toReturnClientFd = MMIService::INVALID_SOCKET_FD;
586     int32_t serverFd = MMIService::INVALID_SOCKET_FD;
587     int32_t uid = GetCallingUid();
588     MMI_HILOGI("Enter, programName:%{public}s, moduleType:%{public}d, pid:%{public}d",
589         programName.c_str(), moduleType, pid);
590     int32_t ret = delegateTasks_.PostSyncTask(
591         [this, programName, moduleType, uid, pid, &serverFd, &toReturnClientFd, &tokenType] {
592             return this->AddSocketPairInfo(programName, moduleType, uid, pid, serverFd, toReturnClientFd, tokenType);
593         }
594         );
595     DfxHisysevent::ClientConnectData data = {
596         .pid = pid,
597         .uid = uid,
598         .moduleType = moduleType,
599         .programName = programName,
600         .serverFd = serverFd
601     };
602     if (ret != RET_OK) {
603         MMI_HILOGE("Call AddSocketPairInfo failed, return:%{public}d", ret);
604         DfxHisysevent::OnClientConnect(data, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT);
605         if (toReturnClientFd >= 0) {
606             fdsan_close_with_tag(toReturnClientFd, TAG);
607         }
608         return ret;
609     }
610     MMI_HILOGIK("Leave, programName:%{public}s, moduleType:%{public}d, alloc success", programName.c_str(),
611                 moduleType);
612     DfxHisysevent::OnClientConnect(data, OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR);
613     return RET_OK;
614 }
615 
AddInputEventFilter(const sptr<IEventFilter> & filter,int32_t filterId,int32_t priority,uint32_t deviceTags)616 ErrCode MMIService::AddInputEventFilter(const sptr<IEventFilter>& filter, int32_t filterId, int32_t priority,
617     uint32_t deviceTags)
618 {
619     CALL_INFO_TRACE;
620     if (!PER_HELPER->VerifySystemApp()) {
621         MMI_HILOGE("Verify system APP failed");
622         return ERROR_NOT_SYSAPI;
623     }
624     if (!PER_HELPER->CheckInputEventFilter()) {
625         MMI_HILOGE("Filter permission check failed");
626         return ERROR_NO_PERMISSION;
627     }
628 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH) || defined(OHOS_BUILD_ENABLE_KEYBOARD)
629     sptr<IEventFilter> filterPtr = filter;
630     CHKPR(filterPtr, ERROR_NULL_POINTER);
631     int32_t clientPid = GetCallingPid();
632     int32_t ret = delegateTasks_.PostSyncTask(
633         [this, filterPtr, filterId, priority, deviceTags, clientPid] {
634             return sMsgHandler_.AddInputEventFilter(filterPtr, filterId, priority, deviceTags, clientPid);
635         }
636         );
637     if (ret != RET_OK) {
638         MMI_HILOGE("Add event filter failed, return:%{public}d", ret);
639         return ret;
640     }
641 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH || OHOS_BUILD_ENABLE_KEYBOARD
642     return RET_OK;
643 }
644 
RemoveInputEventFilter(int32_t filterId)645 ErrCode MMIService::RemoveInputEventFilter(int32_t filterId)
646 {
647     CALL_INFO_TRACE;
648     if (!PER_HELPER->VerifySystemApp()) {
649         MMI_HILOGE("Verify system APP failed");
650         return ERROR_NOT_SYSAPI;
651     }
652     if (!PER_HELPER->CheckInputEventFilter()) {
653         MMI_HILOGE("Filter permission check failed");
654         return ERROR_NO_PERMISSION;
655     }
656 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH) || defined(OHOS_BUILD_ENABLE_KEYBOARD)
657     int32_t clientPid = GetCallingPid();
658     int32_t ret = delegateTasks_.PostSyncTask(
659         [this, filterId, clientPid] {
660             return sMsgHandler_.RemoveInputEventFilter(filterId, clientPid);
661         }
662         );
663     if (ret != RET_OK) {
664         MMI_HILOGE("Remove event filter failed, return:%{public}d", ret);
665         return ret;
666     }
667 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH || OHOS_BUILD_ENABLE_KEYBOARD
668     return RET_OK;
669 }
670 
OnConnected(SessionPtr s)671 void MMIService::OnConnected(SessionPtr s)
672 {
673     CHKPV(s);
674     MMI_HILOGI("Get fd:%{public}d", s->GetFd());
675 #ifdef OHOS_BUILD_ENABLE_ANCO
676     if (s->GetProgramName() != BUNDLE_NAME_PARSER.GetBundleName("SHELL_ASSISTANT")) {
677         return;
678     }
679     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
680     if (appMgrClient == nullptr) {
681         return;
682     }
683     int32_t userid = WIN_MGR->GetCurrentUserId();
684     if (userid < 0) {
685         userid = DEFAULT_USER_ID;
686     }
687     std::vector<AppExecFwk::RunningProcessInfo> info;
688     auto begin = std::chrono::high_resolution_clock::now();
689     appMgrClient->GetProcessRunningInfosByUserId(info, userid);
690     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
691         std::chrono::high_resolution_clock::now() - begin).count();
692 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
693     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::GET_PROC_RUNNING_INFOS_BY_UID, durationMS);
694 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
695     for (auto &item : info) {
696         if (item.bundleNames.empty()) {
697             continue;
698         }
699         if (BUNDLE_NAME_PARSER.GetBundleName("SHELL_ASSISTANT") == item.bundleNames[0].c_str()) {
700             MMI_HILOGW("Record client processes pid %{public}d", item.pid_);
701             shellAssitentPid_ = item.pid_;
702         }
703     }
704 #endif // OHOS_BUILD_ENABLE_ANCO
705 }
706 
OnDisconnected(SessionPtr s)707 void MMIService::OnDisconnected(SessionPtr s)
708 {
709     CHKPV(s);
710     MMI_HILOGW("Enter, session desc:%{public}s, fd:%{public}d", s->GetDescript().c_str(), s->GetFd());
711     auto ret = RemoveInputEventFilter(-1);
712     if (ret != RET_OK) {
713         MMI_HILOGF("Remove all filter failed, ret:%{public}d", ret);
714     }
715 #ifdef OHOS_BUILD_ENABLE_ANCO
716     if (s->GetProgramName() == BUNDLE_NAME_PARSER.GetBundleName("SHELL_ASSISTANT") &&
717         shellAssitentPid_ == s->GetPid()) {
718         MMI_HILOGW("Clean all shell windows pid:%{public}d", s->GetPid());
719         shellAssitentPid_ = -1;
720         IInputWindowsManager::GetInstance()->CleanShellWindowIds();
721     }
722 #endif // OHOS_BUILD_ENABLE_ANCO
723 #ifdef OHOS_BUILD_ENABLE_POINTER
724     if (POINTER_DEV_MGR.isInit) {
725         CursorDrawingComponent::GetInstance().DeletePointerVisible(s->GetPid());
726     }
727 #endif // OHOS_BUILD_ENABLE_POINTER
728 }
729 
SetMouseScrollRows(int32_t rows)730 ErrCode MMIService::SetMouseScrollRows(int32_t rows)
731 {
732     CALL_INFO_TRACE;
733     if (!IsRunning()) {
734         MMI_HILOGE("Service is not running");
735         return MMISERVICE_NOT_RUNNING;
736     }
737     if (!PER_HELPER->VerifySystemApp()) {
738         MMI_HILOGE("Verify system APP failed");
739         return ERROR_NOT_SYSAPI;
740     }
741 #if defined OHOS_BUILD_ENABLE_POINTER
742     int32_t ret = delegateTasks_.PostSyncTask(
743         [rows] {
744             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetMouseScrollRows(rows);
745         }
746         );
747     if (ret != RET_OK) {
748         MMI_HILOGE("Set the number of mouse scrolling rows failed, return:%{public}d", ret);
749         return ret;
750     }
751 #endif // OHOS_BUILD_ENABLE_POINTER
752     return RET_OK;
753 }
754 
SetCustomCursorPixelMap(int32_t windowId,int32_t focusX,int32_t focusY,const CursorPixelMap & curPixelMap)755 ErrCode MMIService::SetCustomCursorPixelMap(int32_t windowId, int32_t focusX, int32_t focusY,
756     const CursorPixelMap& curPixelMap)
757 {
758     CALL_INFO_TRACE;
759     if (!IsRunning()) {
760         MMI_HILOGE("Service is not running");
761         return MMISERVICE_NOT_RUNNING;
762     }
763     if (windowId <= 0) {
764         MMI_HILOGE("Invalid windowId:%{public}d", windowId);
765         return RET_ERR;
766     }
767     CHKPR(curPixelMap.pixelMap, ERROR_NULL_POINTER);
768     int32_t pid = GetCallingPid();
769     int32_t ret = delegateTasks_.PostSyncTask(std::bind(
770         [pid, windowId] {
771             return WIN_MGR->CheckWindowIdPermissionByPid(windowId, pid);
772         })
773         );
774     if (windowId > 0 && ret != RET_OK) {
775         MMI_HILOGE("Set the custom cursor failed, ret:%{public}d", ret);
776         return ERROR_WINDOW_ID_PERMISSION_DENIED;
777     }
778 #if defined OHOS_BUILD_ENABLE_POINTER
779     auto type = PER_HELPER->GetTokenType();
780     if (windowId < 0 && (type == OHOS::Security::AccessToken::TOKEN_HAP ||
781         type == OHOS::Security::AccessToken::TOKEN_NATIVE)) {
782         // The windowID of the application must be greater than 0
783         MMI_HILOGE("Set the custom cursor failed, ret:%{public}d", RET_ERR);
784         return RET_ERR;
785     }
786     if (windowId >= 0) {
787         int32_t res = CheckPidPermission(pid);
788         if (res != RET_OK) {
789             MMI_HILOGE("Check pid permission failed");
790             return res;
791         }
792     }
793     ret = delegateTasks_.PostSyncTask(std::bind(
794         [curPixelMap, pid, windowId, focusX, focusY] {
795             return CursorDrawingComponent::GetInstance().SetCustomCursor(curPixelMap,
796                 pid, windowId, focusX, focusY);
797         }
798         ));
799     if (ret != RET_OK) {
800         MMI_HILOGE("Set the custom cursor failed, ret:%{public}d", ret);
801         return ret;
802     }
803 #endif // OHOS_BUILD_ENABLE_POINTER
804     return RET_OK;
805 }
806 
SetMouseIcon(int32_t windowId,const CursorPixelMap & curPixelMap)807 ErrCode MMIService::SetMouseIcon(int32_t windowId, const CursorPixelMap& curPixelMap)
808 {
809     CALL_INFO_TRACE;
810     if (!PER_HELPER->VerifySystemApp()) {
811         MMI_HILOGE("Verify system APP failed");
812         return ERROR_NOT_SYSAPI;
813     }
814     if (!IsRunning()) {
815         MMI_HILOGE("Service is not running");
816         return MMISERVICE_NOT_RUNNING;
817     }
818     CHKPR(curPixelMap.pixelMap, ERROR_NULL_POINTER);
819 #if defined OHOS_BUILD_ENABLE_POINTER
820     int32_t pid = GetCallingPid();
821     int32_t ret = CheckPidPermission(pid);
822     if (ret != RET_OK) {
823         MMI_HILOGE("Check pid permission failed");
824         return ret;
825     }
826     ret = delegateTasks_.PostSyncTask(std::bind(
827         [pid, windowId, curPixelMap] {
828             return CursorDrawingComponent::GetInstance().SetMouseIcon(pid, windowId, curPixelMap);
829         }
830         ));
831     if (ret != RET_OK) {
832         MMI_HILOGE("Set the mouse icon failed, return:%{public}d", ret);
833         return ret;
834     }
835 #endif // OHOS_BUILD_ENABLE_POINTER
836     return RET_OK;
837 }
838 
SetMouseHotSpot(int32_t pid,int32_t windowId,int32_t hotSpotX,int32_t hotSpotY)839 ErrCode MMIService::SetMouseHotSpot(int32_t pid, int32_t windowId, int32_t hotSpotX, int32_t hotSpotY)
840 {
841     CALL_INFO_TRACE;
842     if (!PER_HELPER->VerifySystemApp()) {
843         MMI_HILOGE("Verify system APP failed");
844         return ERROR_NOT_SYSAPI;
845     }
846     if (!IsRunning()) {
847         MMI_HILOGE("Service is not running");
848         return MMISERVICE_NOT_RUNNING;
849     }
850     if (windowId <= 0) {
851         MMI_HILOGE("Invalid windowId:%{public}d", windowId);
852         return RET_ERR;
853     }
854 #if defined OHOS_BUILD_ENABLE_POINTER
855     int32_t ret = CheckPidPermission(pid);
856     if (ret != RET_OK) {
857         MMI_HILOGE("Check pid permission failed");
858         return ret;
859     }
860     ret = delegateTasks_.PostSyncTask(
861         [pid, windowId, hotSpotX, hotSpotY] {
862             if (!POINTER_DEV_MGR.isInit) {
863                 return RET_ERR;
864             }
865             return CursorDrawingComponent::GetInstance().SetMouseHotSpot(pid, windowId, hotSpotX, hotSpotY);
866         }
867         );
868     if (ret != RET_OK) {
869         MMI_HILOGE("Set the mouse hot spot failed, return:%{public}d", ret);
870         return ret;
871     }
872 #endif // OHOS_BUILD_ENABLE_POINTER
873     return RET_OK;
874 }
875 
SetNapStatus(int32_t pid,int32_t uid,const std::string & bundleName,int32_t napStatus)876 ErrCode MMIService::SetNapStatus(int32_t pid, int32_t uid, const std::string& bundleName, int32_t napStatus)
877 {
878     CALL_INFO_TRACE;
879     if (!PER_HELPER->VerifySystemApp()) {
880         MMI_HILOGE("Verify system APP failed");
881         return ERROR_NOT_SYSAPI;
882     }
883     if (!IsRunning()) {
884         MMI_HILOGE("Service is not running");
885         return MMISERVICE_NOT_RUNNING;
886     }
887     int32_t ret = CheckPidPermission(pid);
888     if (ret != RET_OK) {
889         MMI_HILOGD("Check pid permission failed");
890         return ret;
891     }
892     NapProcess::GetInstance()->SetNapStatus(pid, uid, bundleName, napStatus);
893     return RET_OK;
894 }
895 
896 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadMouseScrollRows(int32_t & rows)897 int32_t MMIService::ReadMouseScrollRows(int32_t &rows)
898 {
899     rows = MouseEventHdr->GetMouseScrollRows();
900     return RET_OK;
901 }
902 #endif // OHOS_BUILD_ENABLE_POINTER
903 
GetMouseScrollRows(int32_t & rows)904 ErrCode MMIService::GetMouseScrollRows(int32_t &rows)
905 {
906     CALL_INFO_TRACE;
907     if (!IsRunning()) {
908         MMI_HILOGE("Service is not running");
909         return MMISERVICE_NOT_RUNNING;
910     }
911     if (!PER_HELPER->VerifySystemApp()) {
912         MMI_HILOGE("Verify system APP failed");
913         return ERROR_NOT_SYSAPI;
914     }
915     rows = TOUCHPAD_SCROLL_ROWS;
916 #ifdef OHOS_BUILD_ENABLE_POINTER
917     int32_t ret = delegateTasks_.PostSyncTask(
918         [this, &rows] {
919             return this->ReadMouseScrollRows(rows);
920         }
921         );
922     if (ret != RET_OK) {
923         MMI_HILOGE("Get the number of mouse scrolling rows failed, ret:%{public}d", ret);
924         return ret;
925     }
926 #endif // OHOS_BUILD_ENABLE_POINTER
927     return RET_OK;
928 }
929 
SetPointerSize(int32_t size)930 ErrCode MMIService::SetPointerSize(int32_t size)
931 {
932     CALL_INFO_TRACE;
933     if (!IsRunning()) {
934         MMI_HILOGE("Service is not running");
935         return MMISERVICE_NOT_RUNNING;
936     }
937     if (!PER_HELPER->VerifySystemApp()) {
938         MMI_HILOGE("Verify system APP failed");
939         return ERROR_NOT_SYSAPI;
940     }
941 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
942     int32_t ret = delegateTasks_.PostSyncTask(
943         [size] {
944             return CursorDrawingComponent::GetInstance().SetPointerSize(size);
945         }
946         );
947     if (ret != RET_OK) {
948         MMI_HILOGE("Set pointer size failed, return:%{public}d", ret);
949         return ret;
950     }
951 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
952     return RET_OK;
953 }
954 
955 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
ReadPointerSize(int32_t & size)956 int32_t MMIService::ReadPointerSize(int32_t &size)
957 {
958     size = CursorDrawingComponent::GetInstance().GetPointerSize();
959     return RET_OK;
960 }
961 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
962 
GetPointerSize(int32_t & size)963 ErrCode MMIService::GetPointerSize(int32_t &size)
964 {
965     CALL_INFO_TRACE;
966     if (!IsRunning()) {
967         MMI_HILOGE("Service is not running");
968         return MMISERVICE_NOT_RUNNING;
969     }
970     if (!PER_HELPER->VerifySystemApp()) {
971         MMI_HILOGE("Verify system APP failed");
972         return ERROR_NOT_SYSAPI;
973     }
974     size = 1;
975 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
976     int32_t ret = delegateTasks_.PostSyncTask(
977         [this, &size] {
978             return this->ReadPointerSize(size);
979         }
980         );
981     if (ret != RET_OK) {
982         MMI_HILOGE("Get pointer size failed, return:%{public}d", ret);
983         return ret;
984     }
985 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
986     return RET_OK;
987 }
988 
GetCursorSurfaceId(uint64_t & surfaceId)989 ErrCode MMIService::GetCursorSurfaceId(uint64_t &surfaceId)
990 {
991     CALL_INFO_TRACE;
992     if (!IsRunning()) {
993         MMI_HILOGE("Service is not running");
994         return MMISERVICE_NOT_RUNNING;
995     }
996     if (!PER_HELPER->VerifySystemApp()) {
997         MMI_HILOGE("Verify system APP failed");
998         return ERROR_NOT_SYSAPI;
999     }
1000     surfaceId = 0;
1001 #ifdef OHOS_BUILD_ENABLE_POINTER
1002     auto ret = delegateTasks_.PostSyncTask(
1003         [&surfaceId] {
1004             return CursorDrawingComponent::GetInstance().GetCursorSurfaceId(surfaceId);
1005         });
1006     if (ret != RET_OK) {
1007         MMI_HILOGE("GetCursorSurfaceId fail, error:%{public}d", ret);
1008         return ret;
1009     }
1010 #endif // OHOS_BUILD_ENABLE_POINTER
1011     return RET_OK;
1012 }
1013 
SetMousePrimaryButton(int32_t primaryButton)1014 ErrCode MMIService::SetMousePrimaryButton(int32_t primaryButton)
1015 {
1016     CALL_INFO_TRACE;
1017     if (!PER_HELPER->VerifySystemApp()) {
1018         MMI_HILOGE("Verify system APP failed");
1019         return ERROR_NOT_SYSAPI;
1020     }
1021 #if defined OHOS_BUILD_ENABLE_POINTER
1022     int32_t ret = delegateTasks_.PostSyncTask(
1023         [primaryButton] {
1024             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetMousePrimaryButton(primaryButton);
1025         }
1026         );
1027     if (ret != RET_OK) {
1028         MMI_HILOGE("Set mouse primary button failed, return:%{public}d", ret);
1029         return ret;
1030     }
1031 #endif // OHOS_BUILD_ENABLE_POINTER
1032     return RET_OK;
1033 }
1034 
1035 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadMousePrimaryButton(int32_t & primaryButton)1036 int32_t MMIService::ReadMousePrimaryButton(int32_t &primaryButton)
1037 {
1038     primaryButton = MouseEventHdr->GetMousePrimaryButton();
1039     return RET_OK;
1040 }
1041 #endif // OHOS_BUILD_ENABLE_POINTER
1042 
GetMousePrimaryButton(int32_t & primaryButton)1043 ErrCode MMIService::GetMousePrimaryButton(int32_t &primaryButton)
1044 {
1045     CALL_INFO_TRACE;
1046     if (!PER_HELPER->VerifySystemApp()) {
1047         MMI_HILOGE("Verify system APP failed");
1048         return ERROR_NOT_SYSAPI;
1049     }
1050     primaryButton = -1;
1051 #ifdef OHOS_BUILD_ENABLE_POINTER
1052     int32_t ret = delegateTasks_.PostSyncTask(
1053         [this, &primaryButton] {
1054             return this->ReadMousePrimaryButton(primaryButton);
1055         }
1056         );
1057     if (ret != RET_OK) {
1058         MMI_HILOGE("Get mouse primary button failed, return:%{public}d", ret);
1059         return ret;
1060     }
1061 #endif // OHOS_BUILD_ENABLE_POINTER
1062     return RET_OK;
1063 }
1064 
SetPointerVisible(bool visible,int32_t priority)1065 ErrCode MMIService::SetPointerVisible(bool visible, int32_t priority)
1066 {
1067     CALL_INFO_TRACE;
1068     if (priority < 0) {
1069         MMI_HILOGE("Invalid priority:%{public}d", priority);
1070         return RET_ERR;
1071     }
1072 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
1073     auto tokenId = IPCSkeleton::GetCallingTokenID();
1074     auto tokenType = OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
1075     bool isHap = false;
1076     if (tokenType == OHOS::Security::AccessToken::TOKEN_HAP) {
1077         isHap = true;
1078     }
1079     int32_t clientPid = GetCallingPid();
1080     int32_t ret = delegateTasks_.PostSyncTask(
1081         [clientPid, visible, priority, isHap] {
1082             if (!POINTER_DEV_MGR.isInit) {
1083                 return RET_ERR;
1084             }
1085             return CursorDrawingComponent::GetInstance().SetPointerVisible(clientPid, visible, priority, isHap);
1086         }
1087         );
1088     if (ret != RET_OK) {
1089         MMI_HILOGE("Set pointer visible failed, return:%{public}d", ret);
1090         return ret;
1091     }
1092 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1093     return RET_OK;
1094 }
1095 
1096 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
CheckPointerVisible(bool & visible)1097 int32_t MMIService::CheckPointerVisible(bool &visible)
1098 {
1099     WIN_MGR->UpdatePointerDrawingManagerWindowInfo();
1100     if (POINTER_DEV_MGR.isInit) {
1101         visible = CursorDrawingComponent::GetInstance().IsPointerVisible();
1102     }
1103     return RET_OK;
1104 }
1105 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1106 
IsPointerVisible(bool & visible)1107 ErrCode MMIService::IsPointerVisible(bool &visible)
1108 {
1109     CALL_DEBUG_ENTER;
1110     visible = false;
1111 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
1112     int32_t ret = delegateTasks_.PostSyncTask(
1113         [this, &visible] {
1114             return this->CheckPointerVisible(visible);
1115         }
1116         );
1117     if (ret != RET_OK) {
1118         MMI_HILOGE("Is pointer visible failed, return:%{public}d", ret);
1119         return ret;
1120     }
1121 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1122     return RET_OK;
1123 }
1124 
MarkProcessed(int32_t eventType,int32_t eventId)1125 ErrCode MMIService::MarkProcessed(int32_t eventType, int32_t eventId)
1126 {
1127     CALL_DEBUG_ENTER;
1128     if (!IsRunning()) {
1129         MMI_HILOGE("Service is not running");
1130         return MMISERVICE_NOT_RUNNING;
1131     }
1132     CHKPR(ANRMgr, RET_ERR);
1133     int32_t clientPid = GetCallingPid();
1134     int32_t ret = delegateTasks_.PostSyncTask(
1135         [clientPid, eventType, eventId] {
1136             return ::OHOS::DelayedSingleton<ANRManager>::GetInstance()->MarkProcessed(clientPid, eventType, eventId);
1137         }
1138         );
1139     if (ret != RET_OK) {
1140         MMI_HILOGD("Mark event processed failed, ret:%{public}d", ret);
1141         return ret;
1142     }
1143     return RET_OK;
1144 }
1145 
SetPointerColor(int32_t color)1146 ErrCode MMIService::SetPointerColor(int32_t color)
1147 {
1148     CALL_INFO_TRACE;
1149     if (!IsRunning()) {
1150         MMI_HILOGE("Service is not running");
1151         return MMISERVICE_NOT_RUNNING;
1152     }
1153     if (!PER_HELPER->VerifySystemApp()) {
1154         MMI_HILOGE("Verify system APP failed");
1155         return ERROR_NOT_SYSAPI;
1156     }
1157 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
1158     int32_t ret = delegateTasks_.PostSyncTask(
1159         [color] {
1160             if (!POINTER_DEV_MGR.isInit) {
1161                 return RET_ERR;
1162             }
1163             return CursorDrawingComponent::GetInstance().SetPointerColor(color);
1164         }
1165         );
1166     if (ret != RET_OK) {
1167         MMI_HILOGE("Set pointer color failed, return:%{public}d", ret);
1168         return ret;
1169     }
1170 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1171     return RET_OK;
1172 }
1173 
1174 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
ReadPointerColor(int32_t & color)1175 int32_t MMIService::ReadPointerColor(int32_t &color)
1176 {
1177     if (POINTER_DEV_MGR.isInit) {
1178         color = CursorDrawingComponent::GetInstance().GetPointerColor();
1179     }
1180     return RET_OK;
1181 }
1182 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1183 
GetPointerColor(int32_t & color)1184 ErrCode MMIService::GetPointerColor(int32_t &color)
1185 {
1186     CALL_INFO_TRACE;
1187     if (!IsRunning()) {
1188         MMI_HILOGE("Service is not running");
1189         return MMISERVICE_NOT_RUNNING;
1190     }
1191     if (!PER_HELPER->VerifySystemApp()) {
1192         MMI_HILOGE("Verify system APP failed");
1193         return ERROR_NOT_SYSAPI;
1194     }
1195     color = DEFAULT_POINTER_COLOR;
1196 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
1197     int32_t ret = delegateTasks_.PostSyncTask(
1198         [this, &color] {
1199             return this->ReadPointerColor(color);
1200         }
1201         );
1202     if (ret != RET_OK) {
1203         MMI_HILOGE("Get pointer color failed, return:%{public}d", ret);
1204         return ret;
1205     }
1206 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1207     return RET_OK;
1208 }
1209 
SetPointerSpeed(int32_t speed)1210 ErrCode MMIService::SetPointerSpeed(int32_t speed)
1211 {
1212     CALL_INFO_TRACE;
1213     if (!PER_HELPER->VerifySystemApp()) {
1214         MMI_HILOGE("Verify system APP failed");
1215         return ERROR_NOT_SYSAPI;
1216     }
1217 #ifdef OHOS_BUILD_ENABLE_POINTER
1218     int32_t ret = delegateTasks_.PostSyncTask(
1219         [speed] {
1220             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetPointerSpeed(speed);
1221         }
1222         );
1223     if (ret != RET_OK) {
1224         MMI_HILOGE("Set pointer speed failed, return:%{public}d", ret);
1225         return ret;
1226     }
1227 #endif // OHOS_BUILD_ENABLE_POINTER
1228     return RET_OK;
1229 }
1230 
1231 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadPointerSpeed(int32_t & speed)1232 int32_t MMIService::ReadPointerSpeed(int32_t &speed)
1233 {
1234     speed = MouseEventHdr->GetPointerSpeed();
1235     return RET_OK;
1236 }
1237 #endif // OHOS_BUILD_ENABLE_POINTER
1238 
GetPointerSpeed(int32_t & speed)1239 ErrCode MMIService::GetPointerSpeed(int32_t &speed)
1240 {
1241     CALL_INFO_TRACE;
1242     if (!PER_HELPER->VerifySystemApp()) {
1243         MMI_HILOGE("Verify system APP failed");
1244         return ERROR_NOT_SYSAPI;
1245     }
1246     speed = 0;
1247 #ifdef OHOS_BUILD_ENABLE_POINTER
1248     int32_t ret = delegateTasks_.PostSyncTask(
1249         [this, &speed] {
1250             return this->ReadPointerSpeed(speed);
1251         }
1252         );
1253     if (ret != RET_OK) {
1254         MMI_HILOGE("Get pointer speed failed, return:%{public}d", ret);
1255         return ret;
1256     }
1257 #endif // OHOS_BUILD_ENABLE_POINTER
1258     return RET_OK;
1259 }
1260 
NotifyNapOnline()1261 ErrCode MMIService::NotifyNapOnline()
1262 {
1263     CALL_DEBUG_ENTER;
1264     NapProcess::GetInstance()->NotifyNapOnline();
1265     return RET_OK;
1266 }
1267 
RemoveInputEventObserver()1268 ErrCode MMIService::RemoveInputEventObserver()
1269 {
1270     CALL_DEBUG_ENTER;
1271     if (!PER_HELPER->VerifySystemApp()) {
1272         MMI_HILOGE("Verify system APP failed");
1273         return ERROR_NOT_SYSAPI;
1274     }
1275     NapProcess::GetInstance()->RemoveInputEventObserver();
1276     return RET_OK;
1277 }
1278 
SetPointerStyle(int32_t windowId,const PointerStyle & pointerStyle,bool isUiExtension)1279 ErrCode MMIService::SetPointerStyle(int32_t windowId, const PointerStyle& pointerStyle, bool isUiExtension)
1280 {
1281     CALL_INFO_TRACE;
1282     if (!PER_HELPER->VerifySystemApp()) {
1283         if (windowId < 0) {
1284             MMI_HILOGE("windowId is negative number and not system hap, set pointerStyle failed");
1285             return ERROR_NOT_SYSAPI;
1286         }
1287     }
1288     if (windowId == -1 && !PER_HELPER->VerifySystemApp()) {
1289         MMI_HILOGE("Can not set global winid, because this is not sys app");
1290         return ERROR_NOT_SYSAPI;
1291     }
1292 #ifdef OHOS_BUILD_ENABLE_POINTER
1293     int32_t clientPid = GetCallingPid();
1294     int32_t ret = delegateTasks_.PostSyncTask(
1295         [clientPid, windowId, pointerStyle, isUiExtension] {
1296             if (!POINTER_DEV_MGR.isInit) {
1297                 return RET_ERR;
1298             }
1299             return CursorDrawingComponent::GetInstance().SetPointerStyle(
1300                 clientPid, windowId, pointerStyle, isUiExtension);
1301         }
1302         );
1303     if (ret != RET_OK) {
1304         MMI_HILOGE("Set pointer style failed, return:%{public}d", ret);
1305         return ret;
1306     }
1307 #endif // OHOS_BUILD_ENABLE_POINTER
1308     return RET_OK;
1309 }
1310 
ClearWindowPointerStyle(int32_t pid,int32_t windowId)1311 ErrCode MMIService::ClearWindowPointerStyle(int32_t pid, int32_t windowId)
1312 {
1313     CALL_DEBUG_ENTER;
1314     if (windowId <= 0) {
1315         MMI_HILOGE("Invalid windowId:%{public}d", windowId);
1316         return RET_ERR;
1317     }
1318 #ifdef OHOS_BUILD_ENABLE_POINTER
1319     int32_t ret = CheckPidPermission(pid);
1320     if (ret != RET_OK) {
1321         MMI_HILOGE("Check pid permission failed");
1322         return ret;
1323     }
1324     ret = delegateTasks_.PostSyncTask(
1325         [pid, windowId] {
1326             if (!POINTER_DEV_MGR.isInit) {
1327                 return RET_ERR;
1328             }
1329             return CursorDrawingComponent::GetInstance().ClearWindowPointerStyle(pid, windowId);
1330         }
1331         );
1332     if (ret != RET_OK) {
1333         MMI_HILOGE("Set pointer style failed, return:%{public}d", ret);
1334         return ret;
1335     }
1336 #endif // OHOS_BUILD_ENABLE_POINTER
1337     return RET_OK;
1338 }
1339 
GetPointerStyle(int32_t windowId,PointerStyle & pointerStyle,bool isUiExtension)1340 ErrCode MMIService::GetPointerStyle(int32_t windowId, PointerStyle& pointerStyle, bool isUiExtension)
1341 {
1342     CALL_DEBUG_ENTER;
1343 #ifdef OHOS_BUILD_ENABLE_POINTER
1344     int32_t clientPid = GetCallingPid();
1345     int32_t ret = delegateTasks_.PostSyncTask(
1346         [clientPid, windowId, &pointerStyle, isUiExtension] {
1347             if (!POINTER_DEV_MGR.isInit) {
1348                 return RET_ERR;
1349             }
1350             return CursorDrawingComponent::GetInstance().GetPointerStyle(
1351                 clientPid, windowId, pointerStyle, isUiExtension);
1352         }
1353         );
1354     if (ret != RET_OK) {
1355         MMI_HILOGE("Get pointer style failed, return:%{public}d", ret);
1356         return ret;
1357     }
1358 #endif // OHOS_BUILD_ENABLE_POINTER
1359     return RET_OK;
1360 }
1361 
SetHoverScrollState(bool state)1362 ErrCode MMIService::SetHoverScrollState(bool state)
1363 {
1364     CALL_INFO_TRACE;
1365     if (!PER_HELPER->VerifySystemApp()) {
1366         MMI_HILOGE("Verify system APP failed");
1367         return ERROR_NOT_SYSAPI;
1368     }
1369 #if defined OHOS_BUILD_ENABLE_POINTER
1370     int32_t ret = delegateTasks_.PostSyncTask(
1371         [state] {
1372             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->SetHoverScrollState(state);
1373         }
1374         );
1375     if (ret != RET_OK) {
1376         MMI_HILOGE("Set mouse hover scroll state failed, return:%{public}d", ret);
1377         return ret;
1378     }
1379 #endif // OHOS_BUILD_ENABLE_POINTER
1380     return RET_OK;
1381 }
1382 
1383 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadHoverScrollState(bool & state)1384 int32_t MMIService::ReadHoverScrollState(bool &state)
1385 {
1386     state = WIN_MGR->GetHoverScrollState();
1387     return RET_OK;
1388 }
1389 #endif // OHOS_BUILD_ENABLE_POINTER
1390 
GetHoverScrollState(bool & state)1391 ErrCode MMIService::GetHoverScrollState(bool &state)
1392 {
1393     CALL_INFO_TRACE;
1394     if (!PER_HELPER->VerifySystemApp()) {
1395         MMI_HILOGE("Verify system APP failed");
1396         return ERROR_NOT_SYSAPI;
1397     }
1398     state = true;
1399 #ifdef OHOS_BUILD_ENABLE_POINTER
1400     int32_t ret = delegateTasks_.PostSyncTask(
1401         [this, &state] {
1402             return this->ReadHoverScrollState(state);
1403         }
1404         );
1405     if (ret != RET_OK) {
1406         MMI_HILOGE("Get mouse hover scroll state, return:%{public}d", ret);
1407         return ret;
1408     }
1409 #endif // OHOS_BUILD_ENABLE_POINTER
1410     return RET_OK;
1411 }
1412 
OnSupportKeys(int32_t deviceId,std::vector<int32_t> & keys,std::vector<bool> & keystroke)1413 int32_t MMIService::OnSupportKeys(int32_t deviceId, std::vector<int32_t> &keys, std::vector<bool> &keystroke)
1414 {
1415     CALL_DEBUG_ENTER;
1416     int32_t ret = INPUT_DEV_MGR->SupportKeys(deviceId, keys, keystroke);
1417     if (ret != RET_OK) {
1418         MMI_HILOGE("Device id not support");
1419         return ret;
1420     }
1421     if (keystroke.size() > MAX_SUPPORT_KEY) {
1422         MMI_HILOGE("Device exceeds the max range");
1423         return RET_ERR;
1424     }
1425     return RET_OK;
1426 }
1427 
SupportKeys(int32_t deviceId,const std::vector<int32_t> & keys,std::vector<bool> & keystroke)1428 ErrCode MMIService::SupportKeys(int32_t deviceId, const std::vector<int32_t>& keys, std::vector<bool>& keystroke)
1429 {
1430     CALL_DEBUG_ENTER;
1431     if (deviceId < 0) {
1432         MMI_HILOGE("invalid deviceId :%{public}d", deviceId);
1433         return RET_ERR;
1434     }
1435     if (keys.size() < 0 || keys.size() > ExtraData::MAX_BUFFER_SIZE) {
1436         MMI_HILOGE("Invalid size:%{public}zu", keys.size());
1437         return RET_ERR;
1438     }
1439     std::vector<int32_t> keyCode {};
1440     for (auto &item : keys) {
1441         keyCode.push_back(item);
1442     }
1443     int32_t ret = delegateTasks_.PostSyncTask(
1444         [this, deviceId, &keyCode, &keystroke] {
1445             return this->OnSupportKeys(deviceId, keyCode, keystroke);
1446         }
1447         );
1448     if (ret != RET_OK) {
1449         MMI_HILOGE("Support keys info process failed, ret:%{public}d", ret);
1450         return ret;
1451     }
1452     return RET_OK;
1453 }
1454 
OnGetDeviceIds(std::vector<int32_t> & ids)1455 int32_t MMIService::OnGetDeviceIds(std::vector<int32_t> &ids)
1456 {
1457     CALL_DEBUG_ENTER;
1458     ids = INPUT_DEV_MGR->GetInputDeviceIds();
1459     return RET_OK;
1460 }
1461 
GetDeviceIds(std::vector<int32_t> & ids)1462 ErrCode MMIService::GetDeviceIds(std::vector<int32_t> &ids)
1463 {
1464     CALL_DEBUG_ENTER;
1465     int32_t ret = delegateTasks_.PostSyncTask(
1466         [this, &ids] {
1467             return this->OnGetDeviceIds(ids);
1468         }
1469         );
1470     if (ret != RET_OK) {
1471         MMI_HILOGE("Get deviceids failed, ret:%{public}d", ret);
1472         return ret;
1473     }
1474     return RET_OK;
1475 }
1476 
OnGetDevice(int32_t deviceId,std::shared_ptr<InputDevice> inputDevice)1477 int32_t MMIService::OnGetDevice(int32_t deviceId, std::shared_ptr<InputDevice> inputDevice)
1478 {
1479     CALL_DEBUG_ENTER;
1480     if (INPUT_DEV_MGR->GetInputDevice(deviceId) == nullptr) {
1481         MMI_HILOGE("Input device not found");
1482         return COMMON_PARAMETER_ERROR;
1483     }
1484     auto tmpDevice = INPUT_DEV_MGR->GetInputDevice(deviceId);
1485     CHKPR(tmpDevice, COMMON_PARAMETER_ERROR);
1486     inputDevice->SetId(tmpDevice->GetId());
1487     inputDevice->SetType(tmpDevice->GetType());
1488     inputDevice->SetName(tmpDevice->GetName());
1489     inputDevice->SetBus(tmpDevice->GetBus());
1490     inputDevice->SetVersion(tmpDevice->GetVersion());
1491     inputDevice->SetProduct(tmpDevice->GetProduct());
1492     inputDevice->SetVendor(tmpDevice->GetVendor());
1493     inputDevice->SetPhys(tmpDevice->GetPhys());
1494     inputDevice->SetUniq(tmpDevice->GetUniq());
1495     inputDevice->SetCapabilities(tmpDevice->GetCapabilities());
1496     inputDevice->SetAxisInfo(tmpDevice->GetAxisInfo());
1497 
1498     return RET_OK;
1499 }
1500 
GetDevice(int32_t deviceId,InputDevice & inputDevice)1501 ErrCode MMIService::GetDevice(int32_t deviceId, InputDevice& inputDevice)
1502 {
1503     CALL_DEBUG_ENTER;
1504     auto inputDeviceInfo = std::make_shared<InputDevice>(inputDevice);
1505     CHKPR(inputDeviceInfo, ERROR_NULL_POINTER);
1506     int32_t ret = delegateTasks_.PostSyncTask(
1507         [this, deviceId, inputDeviceInfo] {
1508             return this->OnGetDevice(deviceId, inputDeviceInfo);
1509         }
1510         );
1511     if (ret != RET_OK) {
1512         MMI_HILOGE("Get input device info failed, ret:%{public}d", ret);
1513         return ret;
1514     }
1515     inputDevice = *inputDeviceInfo;
1516     return RET_OK;
1517 }
1518 
OnRegisterDevListener(int32_t pid)1519 int32_t MMIService::OnRegisterDevListener(int32_t pid)
1520 {
1521     auto sess = GetSession(GetClientFd(pid));
1522     CHKPR(sess, RET_ERR);
1523     INPUT_DEV_MGR->AddDevListener(sess);
1524     return RET_OK;
1525 }
1526 
RegisterDevListener()1527 ErrCode MMIService::RegisterDevListener()
1528 {
1529     CALL_DEBUG_ENTER;
1530     int32_t pid = GetCallingPid();
1531     int32_t ret = delegateTasks_.PostSyncTask(
1532         [this, pid] {
1533             return this->OnRegisterDevListener(pid);
1534         }
1535         );
1536     if (ret != RET_OK) {
1537         MMI_HILOGE("Register device listener failed, ret:%{public}d", ret);
1538         return ret;
1539     }
1540     return RET_OK;
1541 }
1542 
OnUnregisterDevListener(int32_t pid)1543 int32_t MMIService::OnUnregisterDevListener(int32_t pid)
1544 {
1545     auto sess = GetSession(GetClientFd(pid));
1546     INPUT_DEV_MGR->RemoveDevListener(sess);
1547     return RET_OK;
1548 }
1549 
UnregisterDevListener()1550 ErrCode MMIService::UnregisterDevListener()
1551 {
1552     CALL_DEBUG_ENTER;
1553     int32_t pid = GetCallingPid();
1554     int32_t ret = delegateTasks_.PostSyncTask(
1555         [this, pid] {
1556             return this->OnUnregisterDevListener(pid);
1557         }
1558         );
1559     if (ret != RET_OK) {
1560         MMI_HILOGE("Unregister device listener failed failed, ret:%{public}d", ret);
1561         return ret;
1562     }
1563     return RET_OK;
1564 }
1565 
OnGetKeyboardType(int32_t deviceId,int32_t & keyboardType)1566 int32_t MMIService::OnGetKeyboardType(int32_t deviceId, int32_t &keyboardType)
1567 {
1568     CALL_DEBUG_ENTER;
1569     int32_t ret = INPUT_DEV_MGR->GetKeyboardType(deviceId, keyboardType);
1570     if (ret != RET_OK) {
1571         MMI_HILOGD("GetKeyboardType call failed");
1572         return ret;
1573     }
1574     return RET_OK;
1575 }
1576 
GetKeyboardType(int32_t deviceId,int32_t & keyboardType)1577 ErrCode MMIService::GetKeyboardType(int32_t deviceId, int32_t &keyboardType)
1578 {
1579     CALL_DEBUG_ENTER;
1580     if (deviceId < 0) {
1581         MMI_HILOGE("invalid deviceId :%{public}d", deviceId);
1582         return RET_ERR;
1583     }
1584     keyboardType = 0;
1585     int32_t ret = delegateTasks_.PostSyncTask(
1586         [this, deviceId, &keyboardType] {
1587             return this->OnGetKeyboardType(deviceId, keyboardType);
1588         }
1589         );
1590     if (ret != RET_OK) {
1591         MMI_HILOGD("Get keyboard type failed, ret:%{public}d", ret);
1592         return ret;
1593     }
1594     return ret;
1595 }
1596 
SetKeyboardRepeatDelay(int32_t delay)1597 ErrCode MMIService::SetKeyboardRepeatDelay(int32_t delay)
1598 {
1599     CALL_INFO_TRACE;
1600     if (!IsRunning()) {
1601         MMI_HILOGE("Service is not running");
1602         return MMISERVICE_NOT_RUNNING;
1603     }
1604     if (!PER_HELPER->VerifySystemApp()) {
1605         MMI_HILOGE("Verify system APP failed");
1606         return ERROR_NOT_SYSAPI;
1607     }
1608 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
1609     int32_t ret = delegateTasks_.PostSyncTask(
1610         [delay] {
1611             return ::OHOS::DelayedSingleton<KeyAutoRepeat>::GetInstance()->SetKeyboardRepeatDelay(delay);
1612         }
1613         );
1614     if (ret != RET_OK) {
1615         MMI_HILOGE("Set keyboard repeat delay failed, ret:%{public}d", ret);
1616         return ret;
1617     }
1618 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1619     return RET_OK;
1620 }
1621 
SetKeyboardRepeatRate(int32_t rate)1622 ErrCode MMIService::SetKeyboardRepeatRate(int32_t rate)
1623 {
1624     CALL_INFO_TRACE;
1625     if (!IsRunning()) {
1626         MMI_HILOGE("Service is not running");
1627         return MMISERVICE_NOT_RUNNING;
1628     }
1629     if (!PER_HELPER->VerifySystemApp()) {
1630         MMI_HILOGE("Verify system APP failed");
1631         return ERROR_NOT_SYSAPI;
1632     }
1633 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
1634     int32_t ret = delegateTasks_.PostSyncTask(
1635         [rate] {
1636             return ::OHOS::DelayedSingleton<KeyAutoRepeat>::GetInstance()->SetKeyboardRepeatRate(rate);
1637         }
1638         );
1639     if (ret != RET_OK) {
1640         MMI_HILOGE("Set keyboard repeat rate failed, ret:%{public}d", ret);
1641         return ret;
1642     }
1643 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1644     return RET_OK;
1645 }
1646 
GetKeyboardRepeatDelay(int32_t & delay)1647 ErrCode MMIService::GetKeyboardRepeatDelay(int32_t &delay)
1648 {
1649     CALL_INFO_TRACE;
1650     if (!IsRunning()) {
1651         MMI_HILOGE("Service is not running");
1652         return MMISERVICE_NOT_RUNNING;
1653     }
1654     if (!PER_HELPER->VerifySystemApp()) {
1655         MMI_HILOGE("Verify system APP failed");
1656         return ERROR_NOT_SYSAPI;
1657     }
1658     delay = 0;
1659 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
1660     int32_t ret = delegateTasks_.PostSyncTask(
1661         [&delay] {
1662             return ::OHOS::DelayedSingleton<KeyAutoRepeat>::GetInstance()->GetKeyboardRepeatDelay(delay);
1663         }
1664         );
1665     if (ret != RET_OK) {
1666         MMI_HILOGE("Get keyboard repeat delay failed, ret:%{public}d", ret);
1667         return ret;
1668     }
1669 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1670     return RET_OK;
1671 }
1672 
GetKeyboardRepeatRate(int32_t & rate)1673 ErrCode MMIService::GetKeyboardRepeatRate(int32_t &rate)
1674 {
1675     CALL_INFO_TRACE;
1676     if (!IsRunning()) {
1677         MMI_HILOGE("Service is not running");
1678         return MMISERVICE_NOT_RUNNING;
1679     }
1680     if (!PER_HELPER->VerifySystemApp()) {
1681         MMI_HILOGE("Verify system APP failed");
1682         return ERROR_NOT_SYSAPI;
1683     }
1684     rate = 0;
1685 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
1686     int32_t ret = delegateTasks_.PostSyncTask(
1687         [&rate] {
1688             return ::OHOS::DelayedSingleton<KeyAutoRepeat>::GetInstance()->GetKeyboardRepeatRate(rate);
1689         }
1690         );
1691     if (ret != RET_OK) {
1692         MMI_HILOGE("Get keyboard repeat rate failed, ret:%{public}d", ret);
1693         return ret;
1694     }
1695 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1696     return RET_OK;
1697 }
1698 
1699 #if defined(OHOS_BUILD_ENABLE_INTERCEPTOR) || defined(OHOS_BUILD_ENABLE_MONITOR)
CheckAddInput(int32_t pid,InputHandlerType handlerType,HandleEventType eventType,int32_t priority,uint32_t deviceTags)1700 int32_t MMIService::CheckAddInput(int32_t pid, InputHandlerType handlerType, HandleEventType eventType,
1701     int32_t priority, uint32_t deviceTags)
1702 {
1703     auto sess = GetSessionByPid(pid);
1704     CHKPR(sess, ERROR_NULL_POINTER);
1705     return sMsgHandler_.OnAddInputHandler(sess, handlerType, eventType, priority, deviceTags);
1706 }
1707 
1708 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR || OHOS_BUILD_ENABLE_MONITOR
1709 
CheckInputHandlerVaild(InputHandlerType handlerType)1710 int32_t MMIService::CheckInputHandlerVaild(InputHandlerType handlerType)
1711 {
1712     if (!PER_HELPER->VerifySystemApp()) {
1713         if (handlerType == InputHandlerType::MONITOR) {
1714 #ifdef PLAYER_FRAMEWORK_EXISTS
1715             int32_t pid = GetCallingPid();
1716             bool ret = InputScreenCaptureAgent::GetInstance().IsScreenCaptureWorking(pid);
1717             if (!ret) {
1718                 MMI_HILOGE("Calling pid is:%{public}d", pid);
1719                 return ERROR_NO_PERMISSION;
1720             }
1721 #else
1722             return ERROR_NOT_SYSAPI;
1723 #endif
1724         } else if (handlerType != InputHandlerType::INTERCEPTOR) {
1725             MMI_HILOGE("Verify system APP failed");
1726             return ERROR_NOT_SYSAPI;
1727         }
1728     }
1729 
1730     if (!IsRunning()) {
1731         MMI_HILOGE("Service is not running");
1732         return MMISERVICE_NOT_RUNNING;
1733     }
1734     if ((handlerType == InputHandlerType::INTERCEPTOR) && (!PER_HELPER->CheckInterceptor())) {
1735         MMI_HILOGE("Interceptor permission check failed");
1736         return ERROR_NO_PERMISSION;
1737     }
1738     if ((handlerType == InputHandlerType::MONITOR) && (!PER_HELPER->CheckMonitor())) {
1739         MMI_HILOGE("Monitor permission check failed");
1740         return ERROR_NO_PERMISSION;
1741     }
1742     return RET_OK;
1743 }
1744 
AddInputHandler(int32_t handlerType,uint32_t eventType,int32_t priority,uint32_t deviceTags,const std::vector<int32_t> & actionsType)1745 ErrCode MMIService::AddInputHandler(int32_t handlerType, uint32_t eventType, int32_t priority,
1746     uint32_t deviceTags, const std::vector<int32_t>& actionsType)
1747 {
1748     CALL_INFO_TRACE;
1749     bool isRegisterCaptureCb = false;
1750     InputHandlerType hType = static_cast<InputHandlerType>(handlerType);
1751     HandleEventType eType = static_cast<HandleEventType>(eventType);
1752     int32_t res = CheckInputHandlerVaild(hType);
1753     if (res != RET_OK) {
1754         MMI_HILOGE("CheckInputHandlerVaild failed, ret:%{public}d", res);
1755         return res;
1756     }
1757 #if defined(OHOS_BUILD_ENABLE_MONITOR) && defined(PLAYER_FRAMEWORK_EXISTS)
1758     if (!PER_HELPER->VerifySystemApp() && hType == InputHandlerType::MONITOR) {
1759         isRegisterCaptureCb = true;
1760     }
1761 #endif // OHOS_BUILD_ENABLE_MONITOR && PLAYER_FRAMEWORK_EXISTS
1762 #if defined(OHOS_BUILD_ENABLE_INTERCEPTOR) || defined(OHOS_BUILD_ENABLE_MONITOR)
1763     int32_t pid = GetCallingPid();
1764     int32_t ret = delegateTasks_.PostSyncTask(
1765         [this, pid, hType, eType, priority, deviceTags, isRegisterCaptureCb] {
1766             if (isRegisterCaptureCb) {
1767 #if defined(OHOS_BUILD_ENABLE_MONITOR) && defined(PLAYER_FRAMEWORK_EXISTS)
1768                 RegisterScreenCaptureCallback();
1769 #endif // OHOS_BUILD_ENABLE_MONITOR && PLAYER_FRAMEWORK_EXISTS
1770             }
1771             return this->CheckAddInput(pid, hType, eType, priority, deviceTags);
1772         });
1773     if (ret != RET_OK) {
1774         MMI_HILOGE("Add input handler failed, ret:%{public}d", ret);
1775         return ret;
1776     }
1777     ret = ObserverAddInputHandler(pid);
1778     if (ret != RET_OK) {
1779         MMI_HILOGE("AddInputHandler info to observer failed, ret:%{public}d", ret);
1780         return ret;
1781     }
1782 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR || OHOS_BUILD_ENABLE_MONITOR
1783     return RET_OK;
1784 }
1785 
AddPreInputHandler(int32_t handlerId,uint32_t eventType,const std::vector<int32_t> & keys)1786 ErrCode MMIService::AddPreInputHandler(int32_t handlerId, uint32_t eventType, const std::vector<int32_t>& keys)
1787 {
1788     CALL_DEBUG_ENTER;
1789     if (!PER_HELPER->VerifySystemApp()) {
1790         return ERROR_NOT_SYSAPI;
1791     }
1792     if (!IsRunning()) {
1793         MMI_HILOGE("Service is not running");
1794         return MMISERVICE_NOT_RUNNING;
1795     }
1796     if (!PER_HELPER->CheckMonitor()) {
1797         MMI_HILOGE("Monitor permission check failed");
1798         return ERROR_NO_PERMISSION;
1799     }
1800     HandleEventType eType = static_cast<HandleEventType>(eventType);
1801 #ifdef OHOS_BUILD_ENABLE_MONITOR
1802     int32_t pid = GetCallingPid();
1803     int32_t ret = delegateTasks_.PostSyncTask([this, pid, handlerId, eType, keys] () -> int32_t {
1804         auto sess = GetSessionByPid(pid);
1805         CHKPR(sess, ERROR_NULL_POINTER);
1806         auto preMonitorHandler = InputHandler->GetEventPreMonitorHandler();
1807         CHKPR(preMonitorHandler, RET_ERR);
1808         return preMonitorHandler->AddInputHandler(sess, handlerId, eType, keys);
1809     });
1810     if (ret != RET_OK) {
1811         MMI_HILOGE("The AddPreInputHandler key event processed failed, ret:%{public}d", ret);
1812         return ret;
1813     }
1814 #endif // OHOS_BUILD_ENABLE_MONITOR
1815     return RET_OK;
1816 }
1817 
RemovePreInputHandler(int32_t handlerId)1818 ErrCode MMIService::RemovePreInputHandler(int32_t handlerId)
1819 {
1820     CALL_DEBUG_ENTER;
1821     if (!PER_HELPER->VerifySystemApp()) {
1822         return ERROR_NOT_SYSAPI;
1823     }
1824     if (!IsRunning()) {
1825         MMI_HILOGE("Service is not running");
1826         return MMISERVICE_NOT_RUNNING;
1827     }
1828     if (!PER_HELPER->CheckMonitor()) {
1829         MMI_HILOGE("Monitor permission check failed");
1830         return ERROR_NO_PERMISSION;
1831     }
1832 #ifdef OHOS_BUILD_ENABLE_MONITOR
1833     int32_t pid = GetCallingPid();
1834     int32_t ret = delegateTasks_.PostSyncTask([this, pid, handlerId] () -> int32_t {
1835         auto sess = GetSessionByPid(pid);
1836         CHKPR(sess, ERROR_NULL_POINTER);
1837         auto preMonitorHandler = InputHandler->GetEventPreMonitorHandler();
1838         CHKPR(preMonitorHandler, RET_ERR);
1839         preMonitorHandler->RemoveInputHandler(sess, handlerId);
1840         return RET_OK;
1841     });
1842     if (ret != RET_OK) {
1843         MMI_HILOGE("Remove pre input handler failed, ret:%{public}d", ret);
1844         return ret;
1845     }
1846 #endif // OHOS_BUILD_ENABLE_MONITOR
1847     return RET_OK;
1848 }
1849 
1850 #if defined(OHOS_BUILD_ENABLE_INTERCEPTOR) || defined(OHOS_BUILD_ENABLE_MONITOR)
CheckRemoveInput(int32_t pid,InputHandlerType handlerType,HandleEventType eventType,int32_t priority,uint32_t deviceTags)1851 int32_t MMIService::CheckRemoveInput(int32_t pid, InputHandlerType handlerType, HandleEventType eventType,
1852     int32_t priority, uint32_t deviceTags)
1853 {
1854     auto sess = GetSessionByPid(pid);
1855     CHKPR(sess, ERROR_NULL_POINTER);
1856     return sMsgHandler_.OnRemoveInputHandler(sess, handlerType, eventType, priority, deviceTags);
1857 }
1858 
ObserverAddInputHandler(int32_t pid)1859 int32_t MMIService::ObserverAddInputHandler(int32_t pid)
1860 {
1861     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
1862         OHOS::MMI::NapProcess::NapStatusData napData;
1863         napData.pid = GetCallingPid();
1864         napData.uid = GetCallingUid();
1865         auto sess = GetSessionByPid(pid);
1866         CHKPR(sess, ERROR_NULL_POINTER);
1867         napData.bundleName = sess->GetProgramName();
1868         int32_t syncState = SUBSCRIBED;
1869         MMI_HILOGD("AddInputHandler info to observer : pid:%{public}d, uid:%d, bundleName:%{public}s",
1870             napData.pid, napData.uid, napData.bundleName.c_str());
1871         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
1872         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
1873             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
1874         }
1875     }
1876     return RET_OK;
1877 }
1878 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR || OHOS_BUILD_ENABLE_MONITOR
1879 
CheckRemoveInputHandlerVaild(InputHandlerType handlerType)1880 int32_t MMIService::CheckRemoveInputHandlerVaild(InputHandlerType handlerType)
1881 {
1882     if (!PER_HELPER->VerifySystemApp()) {
1883         if (handlerType != InputHandlerType::MONITOR && handlerType != InputHandlerType::INTERCEPTOR) {
1884             MMI_HILOGE("Verify system APP failed");
1885             return ERROR_NOT_SYSAPI;
1886         }
1887     }
1888     if (!IsRunning()) {
1889         MMI_HILOGE("Service is not running");
1890         return MMISERVICE_NOT_RUNNING;
1891     }
1892     if ((handlerType == InputHandlerType::INTERCEPTOR) && (!PER_HELPER->CheckInterceptor())) {
1893         MMI_HILOGE("Interceptor permission check failed");
1894         return ERROR_NO_PERMISSION;
1895     }
1896     if ((handlerType == InputHandlerType::MONITOR) && (!PER_HELPER->CheckMonitor())) {
1897         MMI_HILOGE("Monitor permission check failed");
1898         return ERROR_NO_PERMISSION;
1899     }
1900     return RET_OK;
1901 }
1902 
RemoveInputHandler(int32_t handlerType,uint32_t eventType,int32_t priority,uint32_t deviceTags,const std::vector<int32_t> & actionsType)1903 ErrCode MMIService::RemoveInputHandler(int32_t handlerType, uint32_t eventType, int32_t priority,
1904     uint32_t deviceTags, const std::vector<int32_t>& actionsType)
1905 {
1906     CALL_INFO_TRACE;
1907     InputHandlerType hType = static_cast<InputHandlerType>(handlerType);
1908     HandleEventType eType = static_cast<HandleEventType>(eventType);
1909     int32_t res = CheckRemoveInputHandlerVaild(hType);
1910     if (res != RET_OK) {
1911         MMI_HILOGE("CheckRemoveInputHandlerVaild failed, ret:%{public}d", res);
1912         return res;
1913     }
1914 #if defined(OHOS_BUILD_ENABLE_INTERCEPTOR) || defined(OHOS_BUILD_ENABLE_MONITOR)
1915     int32_t pid = GetCallingPid();
1916     int32_t ret = delegateTasks_.PostSyncTask(
1917         [this, pid, hType, eType, priority, deviceTags] {
1918             return this->CheckRemoveInput(pid, hType, eType, priority, deviceTags);
1919         }
1920         );
1921     if (ret != RET_OK) {
1922         MMI_HILOGE("Remove input handler failed, ret:%{public}d", ret);
1923         return ret;
1924     }
1925     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
1926         OHOS::MMI::NapProcess::NapStatusData napData;
1927         napData.pid = GetCallingPid();
1928         napData.uid = GetCallingUid();
1929         auto sess = GetSessionByPid(pid);
1930         CHKPR(sess, ERROR_NULL_POINTER);
1931         napData.bundleName = sess->GetProgramName();
1932         int32_t syncState = UNSUBSCRIBED;
1933         MMI_HILOGD("RemoveInputHandler info to observer : pid:%{public}d, uid:%{public}d, bundleName:%{public}s",
1934             napData.pid, napData.uid, napData.bundleName.c_str());
1935         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
1936         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
1937             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
1938         }
1939     }
1940 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR || OHOS_BUILD_ENABLE_MONITOR
1941     return RET_OK;
1942 }
1943 
AddGestureMonitor(int32_t handlerType,uint32_t eventType,uint32_t gestureType,int32_t fingers)1944 ErrCode MMIService::AddGestureMonitor(int32_t handlerType, uint32_t eventType, uint32_t gestureType, int32_t fingers)
1945 {
1946     CALL_INFO_TRACE;
1947     if (!PER_HELPER->VerifySystemApp()) {
1948         MMI_HILOGE("Verify system APP failed");
1949         return ERROR_NOT_SYSAPI;
1950     }
1951     if (!IsRunning()) {
1952         MMI_HILOGE("Service is not running");
1953         return MMISERVICE_NOT_RUNNING;
1954     }
1955     if (!PER_HELPER->CheckMonitor()) {
1956         MMI_HILOGE("Monitor permission check failed");
1957         return ERROR_NO_PERMISSION;
1958     }
1959     InputHandlerType hType = static_cast<InputHandlerType>(handlerType);
1960     HandleEventType eType = static_cast<HandleEventType>(eventType);
1961     TouchGestureType gType = static_cast<TouchGestureType>(gestureType);
1962     if (hType != InputHandlerType::MONITOR) {
1963         MMI_HILOGE("Illegal type:%{public}d", hType);
1964         return RET_ERR;
1965     }
1966 #if defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
1967     int32_t pid = GetCallingPid();
1968     int32_t ret = delegateTasks_.PostSyncTask(
1969         [this, pid, hType, eType, gType, fingers]() -> int32_t {
1970             if (((eType & HANDLE_EVENT_TYPE_TOUCH_GESTURE) != HANDLE_EVENT_TYPE_TOUCH_GESTURE)) {
1971                 MMI_HILOGE("Illegal type:%{public}d", eType);
1972                 return RET_ERR;
1973             }
1974             if (!GestureMonitorHandler::CheckMonitorValid(gType, fingers)) {
1975                 MMI_HILOGE("Wrong number of fingers:%{public}d", fingers);
1976                 return RET_ERR;
1977             }
1978             if (touchGestureMgr_ == nullptr) {
1979                 touchGestureMgr_ = std::make_shared<TouchGestureManager>(delegateInterface_);
1980             }
1981             touchGestureMgr_->AddHandler(pid, gType, fingers);
1982 
1983             auto sess = GetSessionByPid(pid);
1984             CHKPR(sess, ERROR_NULL_POINTER);
1985             return sMsgHandler_.OnAddGestureMonitor(sess, hType, eType, gType, fingers);
1986         });
1987     if (ret != RET_OK) {
1988         MMI_HILOGE("Add gesture handler failed, ret:%{public}d", ret);
1989         return ret;
1990     }
1991 #endif // OHOS_BUILD_ENABLE_TOUCH && OHOS_BUILD_ENABLE_MONITOR
1992     return RET_OK;
1993 }
1994 
RemoveGestureMonitor(int32_t handlerType,uint32_t eventType,uint32_t gestureType,int32_t fingers)1995 ErrCode MMIService::RemoveGestureMonitor(int32_t handlerType, uint32_t eventType, uint32_t gestureType, int32_t fingers)
1996 {
1997     CALL_INFO_TRACE;
1998     if (!PER_HELPER->VerifySystemApp()) {
1999         MMI_HILOGE("Verify system APP failed");
2000         return ERROR_NOT_SYSAPI;
2001     }
2002     if (!IsRunning()) {
2003         MMI_HILOGE("Service is not running");
2004         return MMISERVICE_NOT_RUNNING;
2005     }
2006     if (!PER_HELPER->CheckMonitor()) {
2007         MMI_HILOGE("Monitor permission check failed");
2008         return ERROR_NO_PERMISSION;
2009     }
2010     InputHandlerType hType = static_cast<InputHandlerType>(handlerType);
2011     HandleEventType eType = static_cast<HandleEventType>(eventType);
2012     TouchGestureType gType = static_cast<TouchGestureType>(gestureType);
2013     if (hType != InputHandlerType::MONITOR) {
2014         MMI_HILOGE("Illegal type:%{public}d", hType);
2015         return RET_ERR;
2016     }
2017 #if defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
2018     int32_t pid = GetCallingPid();
2019     int32_t ret = delegateTasks_.PostSyncTask(
2020         [this, pid, hType, eType, gType, fingers]() -> int32_t {
2021             auto sess = GetSessionByPid(pid);
2022             CHKPR(sess, ERROR_NULL_POINTER);
2023             int32_t ret = sMsgHandler_.OnRemoveGestureMonitor(sess, hType, eType, gType, fingers);
2024             if (ret != RET_OK) {
2025                 MMI_HILOGE("Failed to remove gesture recognizer, ret:%{public}d", ret);
2026                 return ret;
2027             }
2028             if (touchGestureMgr_ != nullptr) {
2029                 touchGestureMgr_->RemoveHandler(pid, gType, fingers);
2030             }
2031             return RET_OK;
2032         });
2033     if (ret != RET_OK) {
2034         MMI_HILOGE("Remove gesture handler failed, ret:%{public}d", ret);
2035         return ret;
2036     }
2037 #endif // OHOS_BUILD_ENABLE_TOUCH && OHOS_BUILD_ENABLE_MONITOR
2038     return RET_OK;
2039 }
2040 
2041 #ifdef OHOS_BUILD_ENABLE_MONITOR
CheckMarkConsumed(int32_t pid,int32_t eventId)2042 int32_t MMIService::CheckMarkConsumed(int32_t pid, int32_t eventId)
2043 {
2044     auto sess = GetSessionByPid(pid);
2045     CHKPR(sess, ERROR_NULL_POINTER);
2046     return sMsgHandler_.OnMarkConsumed(sess, eventId);
2047 }
2048 #endif // OHOS_BUILD_ENABLE_MONITOR
2049 
MarkEventConsumed(int32_t eventId)2050 ErrCode MMIService::MarkEventConsumed(int32_t eventId)
2051 {
2052     CALL_DEBUG_ENTER;
2053     if (!PER_HELPER->CheckMonitor()) {
2054         MMI_HILOGE("Permission check failed");
2055         return ERROR_NO_PERMISSION;
2056     }
2057     if (!IsRunning()) {
2058         MMI_HILOGE("Service is not running");
2059         return MMISERVICE_NOT_RUNNING;
2060     }
2061 #ifdef OHOS_BUILD_ENABLE_MONITOR
2062     int32_t pid = GetCallingPid();
2063     int32_t ret = delegateTasks_.PostSyncTask(
2064         [this, pid, eventId] {
2065             return this->CheckMarkConsumed(pid, eventId);
2066         }
2067         );
2068     if (ret != RET_OK) {
2069         MMI_HILOGE("Mark event consumed failed, ret:%{public}d", ret);
2070         return ret;
2071     }
2072 #endif // OHOS_BUILD_ENABLE_MONITOR
2073     return RET_OK;
2074 }
2075 
MoveMouseEvent(int32_t offsetX,int32_t offsetY)2076 ErrCode MMIService::MoveMouseEvent(int32_t offsetX, int32_t offsetY)
2077 {
2078     CALL_DEBUG_ENTER;
2079     if (!PER_HELPER->VerifySystemApp()) {
2080         MMI_HILOGE("Verify system APP failed");
2081         return ERROR_NOT_SYSAPI;
2082     }
2083     if (!PER_HELPER->CheckMouseCursor()) {
2084         MMI_HILOGE("Mouse cursor permission check failed");
2085         return ERROR_NO_PERMISSION;
2086     }
2087     if (!IsRunning()) {
2088         MMI_HILOGE("Service is not running");
2089         return MMISERVICE_NOT_RUNNING;
2090     }
2091 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2092     int32_t ret =
2093         delegateTasks_.PostSyncTask(
2094             [this, offsetX, offsetY] {
2095                 return sMsgHandler_.OnMoveMouse(offsetX, offsetY);
2096             }
2097             );
2098     if (ret != RET_OK) {
2099         MMI_HILOGE("The movemouse event processed failed, ret:%{public}d", ret);
2100         return ret;
2101     }
2102 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2103     return RET_OK;
2104 }
2105 
InjectKeyEvent(const KeyEvent & keyEvent,bool isNativeInject)2106 ErrCode MMIService::InjectKeyEvent(const KeyEvent& keyEvent, bool isNativeInject)
2107 {
2108     CALL_DEBUG_ENTER;
2109     if (!IsRunning()) {
2110         MMI_HILOGE("Service is not running");
2111         return MMISERVICE_NOT_RUNNING;
2112     }
2113     if (!isNativeInject && !PER_HELPER->VerifySystemApp()) {
2114         MMI_HILOGE("Verify system APP failed");
2115         return ERROR_NOT_SYSAPI;
2116     }
2117     auto keyEventPtr = std::make_shared<KeyEvent>(keyEvent);
2118     CHKPR(keyEventPtr, ERROR_NULL_POINTER);
2119 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2120     int32_t ret;
2121     int32_t pid = GetCallingPid();
2122 #ifdef OHOS_BUILD_ENABLE_ANCO
2123     ret = InjectKeyEventExt(keyEventPtr, pid, isNativeInject);
2124 #else
2125     ret = delegateTasks_.PostSyncTask(
2126         [this, keyEventPtr, pid, isNativeInject] {
2127             return this->CheckInjectKeyEvent(keyEventPtr, pid, isNativeInject);
2128         }
2129         );
2130 #endif // OHOS_BUILD_ENABLE_ANCO
2131     if (ret != RET_OK) {
2132         MMI_HILOGE("Inject key event failed, ret:%{public}d", ret);
2133         return ret;
2134     }
2135 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2136     return RET_OK;
2137 }
2138 
CheckInjectKeyEvent(const std::shared_ptr<KeyEvent> keyEvent,int32_t pid,bool isNativeInject)2139 int32_t MMIService::CheckInjectKeyEvent(const std::shared_ptr<KeyEvent> keyEvent, int32_t pid, bool isNativeInject)
2140 {
2141 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2142     CHKPR(keyEvent, ERROR_NULL_POINTER);
2143     LogTracer lt(keyEvent->GetId(), keyEvent->GetEventType(), keyEvent->GetKeyAction());
2144     return sMsgHandler_.OnInjectKeyEvent(keyEvent, pid, isNativeInject);
2145 #else
2146     return RET_OK;
2147 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2148 }
2149 
2150 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
OnGetKeyState(std::vector<int32_t> & pressedKeys,std::unordered_map<int32_t,int32_t> & specialKeysState)2151 int32_t MMIService::OnGetKeyState(std::vector<int32_t> &pressedKeys,
2152     std::unordered_map<int32_t, int32_t> &specialKeysState)
2153 {
2154     auto keyEvent = KeyEventHdr->GetKeyEvent();
2155     CHKPR(keyEvent, ERROR_NULL_POINTER);
2156     pressedKeys = keyEvent->GetPressedKeys();
2157     for (auto iter = pressedKeys.begin(); iter != pressedKeys.end();) {
2158         if (g_keyCodeValueSet.find(*iter) == g_keyCodeValueSet.end()) {
2159             iter = pressedKeys.erase(iter);
2160             continue;
2161         }
2162         ++iter;
2163     }
2164     specialKeysState[KeyEvent::KEYCODE_CAPS_LOCK] =
2165         static_cast<int32_t>(keyEvent->GetFunctionKey(KeyEvent::CAPS_LOCK_FUNCTION_KEY));
2166     specialKeysState[KeyEvent::KEYCODE_SCROLL_LOCK] =
2167         static_cast<int32_t>(keyEvent->GetFunctionKey(KeyEvent::SCROLL_LOCK_FUNCTION_KEY));
2168     specialKeysState[KeyEvent::KEYCODE_NUM_LOCK] =
2169         static_cast<int32_t>(keyEvent->GetFunctionKey(KeyEvent::NUM_LOCK_FUNCTION_KEY));
2170     return RET_OK;
2171 }
2172 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2173 
CheckInjectPointerEvent(const std::shared_ptr<PointerEvent> pointerEvent,int32_t pid,bool isNativeInject,bool isShell,int32_t useCoordinate)2174 int32_t MMIService::CheckInjectPointerEvent(const std::shared_ptr<PointerEvent> pointerEvent,
2175     int32_t pid, bool isNativeInject, bool isShell, int32_t useCoordinate)
2176 {
2177 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
2178     CHKPR(pointerEvent, ERROR_NULL_POINTER);
2179     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
2180     return sMsgHandler_.OnInjectPointerEvent(pointerEvent, pid, isNativeInject, isShell, useCoordinate);
2181 #else
2182     return RET_OK;
2183 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
2184 }
2185 
CheckTouchPadEvent(const std::shared_ptr<PointerEvent> pointerEvent,int32_t pid,const TouchpadCDG & touchpadCDG,bool isNativeInject,bool isShell)2186 int32_t MMIService::CheckTouchPadEvent(const std::shared_ptr<PointerEvent> pointerEvent,
2187     int32_t pid, const TouchpadCDG &touchpadCDG, bool isNativeInject, bool isShell)
2188 {
2189 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
2190     CHKPR(pointerEvent, ERROR_NULL_POINTER);
2191     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
2192     return sMsgHandler_.OnInjectTouchPadEvent(pointerEvent, pid, touchpadCDG, isNativeInject, isShell);
2193 #else
2194     return RET_OK;
2195 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
2196 }
2197 
InjectPointerEvent(const PointerEvent & pointerEvent,bool isNativeInject,int32_t useCoordinate)2198 ErrCode MMIService::InjectPointerEvent(const PointerEvent& pointerEvent, bool isNativeInject, int32_t useCoordinate)
2199 {
2200     CALL_DEBUG_ENTER;
2201     if (!IsRunning()) {
2202         MMI_HILOGE("Service is not running");
2203         return MMISERVICE_NOT_RUNNING;
2204     }
2205     if (!isNativeInject && !PER_HELPER->VerifySystemApp()) {
2206         MMI_HILOGE("Verify system APP failed");
2207         return ERROR_NOT_SYSAPI;
2208     }
2209     auto pointerEventPtr = std::make_shared<PointerEvent>(pointerEvent);
2210     CHKPR(pointerEventPtr, ERROR_NULL_POINTER);
2211 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
2212     int32_t ret;
2213     int32_t pid = GetCallingPid();
2214     bool isShell = PER_HELPER->RequestFromShell();
2215 #ifdef OHOS_BUILD_ENABLE_ANCO
2216     ret = InjectPointerEventExt(pointerEventPtr, pid, isNativeInject, isShell);
2217 #else
2218     ret = delegateTasks_.PostSyncTask(
2219         [this, pointerEventPtr, pid, isNativeInject, isShell, useCoordinate] {
2220             return this->CheckInjectPointerEvent(pointerEventPtr, pid, isNativeInject, isShell, useCoordinate);
2221         }
2222         );
2223 #endif // OHOS_BUILD_ENABLE_ANCO
2224     if (ret != RET_OK) {
2225         MMI_HILOGE("Inject pointer event failed, ret:%{public}d", ret);
2226         return ret;
2227     }
2228 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
2229     return RET_OK;
2230 }
2231 
InjectTouchPadEvent(const PointerEvent & pointerEvent,const TouchpadCDG & touchpadCDG,bool isNativeInject)2232 ErrCode MMIService::InjectTouchPadEvent(const PointerEvent& pointerEvent,
2233     const TouchpadCDG& touchpadCDG, bool isNativeInject)
2234 {
2235     CALL_DEBUG_ENTER;
2236     if (!IsRunning()) {
2237         MMI_HILOGE("Service is not running");
2238         return MMISERVICE_NOT_RUNNING;
2239     }
2240     if (!PER_HELPER->VerifySystemApp()) {
2241         MMI_HILOGE("Verify system APP failed");
2242         return ERROR_NOT_SYSAPI;
2243     }
2244     auto pointerEventPtr = std::make_shared<PointerEvent>(pointerEvent);
2245     CHKPR(pointerEventPtr, ERROR_NULL_POINTER);
2246 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
2247     int32_t ret;
2248     int32_t pid = GetCallingPid();
2249     bool isShell = PER_HELPER->RequestFromShell();
2250     ret = delegateTasks_.PostSyncTask(
2251         [this, pointerEventPtr, pid, touchpadCDG, isNativeInject, isShell] {
2252             return sMsgHandler_.OnInjectTouchPadEvent(pointerEventPtr, pid, touchpadCDG, isNativeInject, isShell);
2253         }
2254         );
2255     if (ret != RET_OK) {
2256         MMI_HILOGE("Inject touchpad event failed, ret:%{public}d", ret);
2257         return ret;
2258     }
2259 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
2260     return RET_OK;
2261 }
2262 
2263 #ifdef OHOS_RSS_CLIENT
OnAddResSchedSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2264 void MMIService::OnAddResSchedSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
2265 {
2266     int sleepSeconds = 1;
2267     sleep(sleepSeconds);
2268     uint64_t tid = tid_.load();
2269     int32_t userInteraction = 2;
2270     std::unordered_map<std::string, std::string> payload;
2271     payload["uid"] = std::to_string(getuid());
2272     payload["pid"] = std::to_string(getpid());
2273     payload["extType"] = "10002";
2274     payload["tid"] = std::to_string(tid);
2275     payload["isSa"] = "1";
2276     payload["cgroupPrio"] = "1";
2277     payload["threadName"] = "mmi_service";
2278     auto begin = std::chrono::high_resolution_clock::now();
2279     ResourceSchedule::ResSchedClient::GetInstance().ReportData(
2280         ResourceSchedule::ResType::RES_TYPE_KEY_PERF_SCENE, userInteraction, payload);
2281     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
2282             std::chrono::high_resolution_clock::now() - begin).count();
2283 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
2284     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::RESOURCE_SCHEDULE_REPORT_DATA, durationMS);
2285 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
2286     sleep(sleepSeconds);
2287 #ifdef OHOS_BUILD_PC_PRIORITY
2288     SetMmiServicePriority(tid);
2289 #endif // OHOS_BUILD_PC_PRIORITY
2290 }
2291 #endif // OHOS_RSS_CLIENT
2292 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2293 void MMIService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
2294 {
2295     CALL_INFO_TRACE;
2296     MMI_HILOGI("The systemAbilityId is %{public}d", systemAbilityId);
2297 #ifdef OHOS_RSS_CLIENT
2298     if (systemAbilityId == RES_SCHED_SYS_ABILITY_ID) {
2299         OnAddResSchedSystemAbility(systemAbilityId, deviceId);
2300 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
2301         TOUCH_DRAWING_MGR->ResetTouchWindow();
2302 #endif // OHOS_BUILD_ENABLE_TOUCH_DRAWING
2303     }
2304 #endif // OHOS_RSS_CLIENT
2305 #ifdef OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
2306     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
2307         isCesStart_ = true;
2308     }
2309 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
2310     if (systemAbilityId == APP_MGR_SERVICE_ID) {
2311         APP_OBSERVER_MGR->InitAppStateObserver();
2312     }
2313     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
2314         DEVICE_MONITOR->InitCommonEventSubscriber();
2315         ACCOUNT_MGR->GetCurrentAccountSetting();
2316 #if defined(OHOS_BUILD_ENABLE_KEYBOARD) && defined(OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER)
2317         DISPLAY_MONITOR->InitCommonEventSubscriber();
2318 #endif // OHOS_BUILD_ENABLE_KEYBOARD && OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
2319 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
2320         libinputAdapter_.RegisterBootStatusReceiver();
2321 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
2322 #ifdef OHOS_BUILD_ENABLE_ANCO
2323         WIN_MGR->InitializeAnco();
2324 #endif // OHOS_BUILD_ENABLE_ANCO
2325 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2326     if (!POINTER_DEV_MGR.isFirstAddCommonEventService) {
2327         CursorDrawingComponent::GetInstance().RegisterDisplayStatusReceiver();
2328     }
2329 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2330     }
2331 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2332     if (systemAbilityId == RENDER_SERVICE && !POINTER_DEV_MGR.isFirstAddRenderService) {
2333         CursorDrawingComponent::GetInstance().InitPointerCallback();
2334     }
2335     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID && !POINTER_DEV_MGR.isFirstAddDisplayManagerService) {
2336         CursorDrawingComponent::GetInstance().InitScreenInfo();
2337         CursorDrawingComponent::GetInstance().SubscribeScreenModeChange();
2338     }
2339 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2340     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_SA_ID) {
2341         WIN_MGR->SetFoldState();
2342 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2343         KeyEventHdr->Init();
2344 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2345     }
2346 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2347     if ((systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) &&
2348         !POINTER_DEV_MGR.isFirstAdddistributedKVDataService) {
2349         if (SettingDataShare::GetInstance(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID).CheckIfSettingsDataReady()) {
2350             CursorDrawingComponent::GetInstance().InitPointerObserver();
2351         }
2352     }
2353 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2354 #ifdef OHOS_BUILD_ENABLE_COMBINATION_KEY
2355     if (systemAbilityId == SENSOR_SERVICE_ABILITY_ID) {
2356         MMI_HILOGI("The systemAbilityId is %{public}d", systemAbilityId);
2357     }
2358 #endif // OHOS_BUILD_ENABLE_COMBINATION_KEY
2359 #ifdef OHOS_BUILD_ENABLE_POINTER
2360     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
2361         TOUCHPAD_MGR->SetCommonEventReady();
2362         TOUCHPAD_MGR->RegisterTpObserver(ACCOUNT_MGR->GetCurrentAccountSetting().GetAccountId());
2363     }
2364 #endif
2365 }
2366 
2367 #if defined(OHOS_BUILD_ENABLE_MONITOR) && defined(PLAYER_FRAMEWORK_EXISTS)
ScreenCaptureCallback(int32_t pid,bool isStart)2368 void MMIService::ScreenCaptureCallback(int32_t pid, bool isStart)
2369 {
2370     auto service = MMIService::GetInstance();
2371     CHKPV(service);
2372     int32_t ret = service->delegateTasks_.PostSyncTask(
2373         [pid, isStart] {
2374             auto monitorHandler = InputHandler->GetMonitorHandler();
2375             CHKPR(monitorHandler, RET_ERR);
2376             monitorHandler->ProcessScreenCapture(pid, isStart);
2377             return RET_OK;
2378         });
2379 }
2380 
RegisterScreenCaptureCallback()2381 void MMIService::RegisterScreenCaptureCallback()
2382 {
2383     if (hasRegisterListener_) {
2384         return;
2385     }
2386     InputScreenCaptureAgent::GetInstance().RegisterListener(ScreenCaptureCallback);
2387     hasRegisterListener_ = true;
2388 }
2389 #endif // OHOS_BUILD_ENABLE_MONITOR && PLAYER_FRAMEWORK_EXISTS
2390 
SubscribeKeyEvent(int32_t subscribeId,const KeyOption & keyOption)2391 ErrCode MMIService::SubscribeKeyEvent(int32_t subscribeId, const KeyOption& keyOption)
2392 {
2393     if (!IsRunning()) {
2394         MMI_HILOGE("Service is not running");
2395         return MMISERVICE_NOT_RUNNING;
2396     }
2397     if (!PER_HELPER->VerifySystemApp()) {
2398         MMI_HILOGE("Verify system APP failed");
2399         return ERROR_NOT_SYSAPI;
2400     }
2401     CALL_DEBUG_ENTER;
2402     auto keyOptionPtr = std::make_shared<KeyOption>(keyOption);
2403     CHKPR(keyOptionPtr, ERROR_NULL_POINTER);
2404 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2405     int32_t pid = GetCallingPid();
2406     int32_t ret = delegateTasks_.PostSyncTask(
2407         [this, pid, subscribeId, keyOptionPtr] {
2408             return sMsgHandler_.OnSubscribeKeyEvent(this, pid, subscribeId, keyOptionPtr);
2409         });
2410     if (ret != RET_OK) {
2411         MMI_HILOGE("The subscribe key event processed failed, ret:%{public}d", ret);
2412         return ret;
2413     }
2414     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
2415         OHOS::MMI::NapProcess::NapStatusData napData;
2416         napData.pid = GetCallingPid();
2417         napData.uid = GetCallingUid();
2418         auto sess = GetSessionByPid(pid);
2419         CHKPR(sess, ERROR_NULL_POINTER);
2420         napData.bundleName = sess->GetProgramName();
2421         int32_t syncState = SUBSCRIBED;
2422         MMI_HILOGD("SubscribeKeyEvent info to observer : pid:%{public}d, uid:%{public}d, bundleName:%{public}s",
2423             napData.pid, napData.uid, napData.bundleName.c_str());
2424         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
2425         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
2426             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
2427         }
2428     }
2429 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2430     return RET_OK;
2431 }
2432 
UnsubscribeKeyEvent(int32_t subscribeId)2433 ErrCode MMIService::UnsubscribeKeyEvent(int32_t subscribeId)
2434 {
2435     CALL_INFO_TRACE;
2436     if (!IsRunning()) {
2437         MMI_HILOGE("Service is not running");
2438         return MMISERVICE_NOT_RUNNING;
2439     }
2440     if (!PER_HELPER->VerifySystemApp()) {
2441         MMI_HILOGE("Verify system APP failed");
2442         return ERROR_NOT_SYSAPI;
2443     }
2444     if (subscribeId < 0) {
2445         MMI_HILOGE("Invalid subscribe");
2446         return RET_ERR;
2447     }
2448 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2449     int32_t pid = GetCallingPid();
2450     int32_t ret = delegateTasks_.PostSyncTask(
2451         [this, pid, subscribeId] {
2452             return sMsgHandler_.OnUnsubscribeKeyEvent(this, pid, subscribeId);
2453         });
2454     if (ret != RET_OK) {
2455         MMI_HILOGE("The unsubscribe key event processed failed, ret:%{public}d", ret);
2456         return ret;
2457     }
2458     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
2459         OHOS::MMI::NapProcess::NapStatusData napData;
2460         napData.pid = GetCallingPid();
2461         napData.uid = GetCallingUid();
2462         auto sess = GetSessionByPid(pid);
2463         CHKPR(sess, ERROR_NULL_POINTER);
2464         napData.bundleName = sess->GetProgramName();
2465         int32_t syncState = UNSUBSCRIBED;
2466         MMI_HILOGD("UnsubscribeKeyEvent info to observer : pid:%{public}d, uid:%{public}d, bundleName:%{public}s",
2467             napData.pid, napData.uid, napData.bundleName.c_str());
2468         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
2469         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
2470             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
2471         }
2472     }
2473 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2474     return RET_OK;
2475 }
2476 
SubscribeHotkey(int32_t subscribeId,const KeyOption & keyOption)2477 ErrCode MMIService::SubscribeHotkey(int32_t subscribeId, const KeyOption& keyOption)
2478 {
2479     CALL_DEBUG_ENTER;
2480     if (!IsRunning()) {
2481         MMI_HILOGE("Service is not running");
2482         return MMISERVICE_NOT_RUNNING;
2483     }
2484     if (subscribeId < 0) {
2485         MMI_HILOGE("Invalid subscribe");
2486         return RET_ERR;
2487     }
2488     auto keyOptionPtr = std::make_shared<KeyOption>(keyOption);
2489     CHKPR(keyOptionPtr, ERROR_NULL_POINTER);
2490 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2491     int32_t pid = GetCallingPid();
2492     int32_t ret = delegateTasks_.PostSyncTask(
2493         [this, pid, subscribeId, keyOptionPtr] {
2494             return sMsgHandler_.OnSubscribeHotkey(this, pid, subscribeId, keyOptionPtr);
2495         });
2496     if (ret != RET_OK) {
2497         MMI_HILOGE("ServerMsgHandler::OnSubscribeHotkey fail, error:%{public}d", ret);
2498         return ret;
2499     }
2500     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
2501         OHOS::MMI::NapProcess::NapStatusData napData;
2502         napData.pid = GetCallingPid();
2503         napData.uid = GetCallingUid();
2504         auto sess = GetSessionByPid(pid);
2505         CHKPR(sess, ERROR_NULL_POINTER);
2506         napData.bundleName = sess->GetProgramName();
2507         int32_t syncState = SUBSCRIBED;
2508         MMI_HILOGD("SubscribeHotkey info to observer : pid:%{public}d, bundleName:%{public}s",
2509             napData.pid, napData.bundleName.c_str());
2510         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
2511         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
2512             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
2513         }
2514     }
2515 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2516     return RET_OK;
2517 }
2518 
UnsubscribeHotkey(int32_t subscribeId)2519 ErrCode MMIService::UnsubscribeHotkey(int32_t subscribeId)
2520 {
2521     CALL_INFO_TRACE;
2522     if (!IsRunning()) {
2523         MMI_HILOGE("Service is not running");
2524         return MMISERVICE_NOT_RUNNING;
2525     }
2526     if (subscribeId < 0) {
2527         MMI_HILOGE("Invalid subscribe");
2528         return RET_ERR;
2529     }
2530 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2531     int32_t pid = GetCallingPid();
2532     int32_t ret = delegateTasks_.PostSyncTask(
2533         [this, pid, subscribeId] {
2534             return sMsgHandler_.OnUnsubscribeHotkey(this, pid, subscribeId);
2535         });
2536     if (ret != RET_OK) {
2537         MMI_HILOGE("ServerMsgHandler::OnUnsubscribeHotkey fail, error:%{public}d", ret);
2538         return ret;
2539     }
2540     if (NapProcess::GetInstance()->GetNapClientPid() != REMOVE_OBSERVER) {
2541         OHOS::MMI::NapProcess::NapStatusData napData;
2542         napData.pid = GetCallingPid();
2543         napData.uid = GetCallingUid();
2544         auto sess = GetSessionByPid(pid);
2545         CHKPR(sess, ERROR_NULL_POINTER);
2546         napData.bundleName = sess->GetProgramName();
2547         int32_t syncState = UNSUBSCRIBED;
2548         MMI_HILOGD("UnsubscribeHotkey info to observer : pid:%{public}d, bundleName:%{public}s",
2549             napData.pid, napData.bundleName.c_str());
2550         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
2551         if (NapProcess::GetInstance()->GetNapClientPid() != UNOBSERVED) {
2552             NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
2553         }
2554     }
2555 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2556     return RET_OK;
2557 }
2558 
2559 #ifdef OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
SubscribeKeyMonitor(const KeyMonitorOption & keyOption)2560 ErrCode MMIService::SubscribeKeyMonitor(const KeyMonitorOption &keyOption)
2561 {
2562     CALL_INFO_TRACE;
2563     if (!IsRunning()) {
2564         MMI_HILOGE("Service is not running");
2565         return MMISERVICE_NOT_RUNNING;
2566     }
2567     int32_t pid = GetCallingPid();
2568     int32_t ret = delegateTasks_.PostSyncTask(
2569         [this, pid, keyOption] {
2570             return sMsgHandler_.SubscribeKeyMonitor(pid, keyOption);
2571         });
2572     if (ret != RET_OK) {
2573         MMI_HILOGE("ServerMsgHandler::SubscribeKeyMonitor fail, error:%{public}d", ret);
2574     }
2575     return ret;
2576 }
2577 
UnsubscribeKeyMonitor(const KeyMonitorOption & keyOption)2578 ErrCode MMIService::UnsubscribeKeyMonitor(const KeyMonitorOption &keyOption)
2579 {
2580     if (!IsRunning()) {
2581         MMI_HILOGE("Service is not running");
2582         return MMISERVICE_NOT_RUNNING;
2583     }
2584     int32_t pid = GetCallingPid();
2585     int32_t ret = delegateTasks_.PostSyncTask(
2586         [this, pid, keyOption] {
2587             return sMsgHandler_.UnsubscribeKeyMonitor(pid, keyOption);
2588         });
2589     if (ret != RET_OK) {
2590         MMI_HILOGE("ServerMsgHandler::UnsubscribeKeyMonitor fail, error:%{public}d", ret);
2591     }
2592     return ret;
2593 }
2594 #endif // OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
2595 
SubscribeSwitchEvent(int32_t subscribeId,int32_t switchType)2596 ErrCode MMIService::SubscribeSwitchEvent(int32_t subscribeId, int32_t switchType)
2597 {
2598     CALL_INFO_TRACE;
2599     if (!PER_HELPER->VerifySystemApp()) {
2600         MMI_HILOGE("Verify system APP failed");
2601         return ERROR_NOT_SYSAPI;
2602     }
2603     if (!IsRunning()) {
2604         MMI_HILOGE("Service is not running");
2605         return MMISERVICE_NOT_RUNNING;
2606     }
2607 #ifdef OHOS_BUILD_ENABLE_SWITCH
2608     int32_t pid = GetCallingPid();
2609     int32_t ret = delegateTasks_.PostSyncTask(
2610         [this, pid, subscribeId, switchType] {
2611             return sMsgHandler_.OnSubscribeSwitchEvent(this, pid, subscribeId, switchType);
2612         }
2613         );
2614     if (ret != RET_OK) {
2615         MMI_HILOGE("The subscribe switch event processed failed, ret:%{public}d", ret);
2616         return ret;
2617     }
2618 #endif // OHOS_BUILD_ENABLE_SWITCH
2619     return RET_OK;
2620 }
2621 
UnsubscribeSwitchEvent(int32_t subscribeId)2622 ErrCode MMIService::UnsubscribeSwitchEvent(int32_t subscribeId)
2623 {
2624     CALL_INFO_TRACE;
2625     if (!PER_HELPER->VerifySystemApp()) {
2626         MMI_HILOGE("Verify system APP failed");
2627         return ERROR_NOT_SYSAPI;
2628     }
2629     if (!IsRunning()) {
2630         MMI_HILOGE("Service is not running");
2631         return MMISERVICE_NOT_RUNNING;
2632     }
2633     if (subscribeId < 0) {
2634         MMI_HILOGE("Invalid subscribeId");
2635         return RET_ERR;
2636     }
2637 #ifdef OHOS_BUILD_ENABLE_SWITCH
2638     int32_t pid = GetCallingPid();
2639     int32_t ret = delegateTasks_.PostSyncTask(
2640         [this, pid, subscribeId] {
2641             return sMsgHandler_.OnUnsubscribeSwitchEvent(this, pid, subscribeId);
2642         }
2643         );
2644     if (ret != RET_OK) {
2645         MMI_HILOGE("The unsubscribe switch event processed failed, ret:%{public}d", ret);
2646         return ret;
2647     }
2648 #endif // OHOS_BUILD_ENABLE_SWITCH
2649     return RET_OK;
2650 }
2651 
QuerySwitchStatus(int32_t switchType,int32_t & state)2652 ErrCode MMIService::QuerySwitchStatus(int32_t switchType, int32_t& state)
2653 {
2654     CALL_INFO_TRACE;
2655     if (!PER_HELPER->VerifySystemApp()) {
2656         MMI_HILOGE("Verify system APP failed");
2657         return ERROR_NOT_SYSAPI;
2658     }
2659 
2660     if (!IsRunning()) {
2661         MMI_HILOGE("Service is not running");
2662         return MMISERVICE_NOT_RUNNING;
2663     }
2664     state = 0;
2665 #ifdef OHOS_BUILD_ENABLE_SWITCH
2666     int32_t ret = delegateTasks_.PostSyncTask(
2667         [this, switchType, &state] {
2668             return sMsgHandler_.OnQuerySwitchStatus(switchType, state);
2669         }
2670         );
2671     if (ret != RET_OK) {
2672         MMI_HILOGE("The query switch state processed failed, ret:%{public}d", ret);
2673         return ret;
2674     }
2675 #endif // OHOS_BUILD_ENABLE_SWITCH
2676     return RET_OK;
2677 }
2678 
SubscribeTabletProximity(int32_t subscribeId)2679 ErrCode MMIService::SubscribeTabletProximity(int32_t subscribeId)
2680 {
2681     CALL_INFO_TRACE;
2682     if (!PER_HELPER->VerifySystemApp()) {
2683         MMI_HILOGE("Verify system APP failed");
2684         return ERROR_NOT_SYSAPI;
2685     }
2686     if (!IsRunning()) {
2687         MMI_HILOGE("Service is not running");
2688         return MMISERVICE_NOT_RUNNING;
2689     }
2690     int32_t pid = GetCallingPid();
2691     int32_t ret = delegateTasks_.PostSyncTask(
2692         [this, pid, subscribeId] {
2693             auto sess = this->GetSessionByPid(pid);
2694             CHKPR(sess, RET_ERR);
2695             return TABLET_SCRIBER_HANDLER->SubscribeTabletProximity(sess, subscribeId);
2696         }
2697         );
2698     if (ret != RET_OK) {
2699         MMI_HILOGE("The subscribe tablet event processed failed, ret:%{public}d", ret);
2700         return ret;
2701     }
2702     return RET_OK;
2703 }
2704 
UnsubscribetabletProximity(int32_t subscribeId)2705 ErrCode MMIService::UnsubscribetabletProximity(int32_t subscribeId)
2706 {
2707     CALL_INFO_TRACE;
2708     if (!PER_HELPER->VerifySystemApp()) {
2709         MMI_HILOGE("Verify system APP failed");
2710         return ERROR_NOT_SYSAPI;
2711     }
2712     if (!IsRunning()) {
2713         MMI_HILOGE("Service is not running");
2714         return MMISERVICE_NOT_RUNNING;
2715     }
2716     if (subscribeId < 0) {
2717         MMI_HILOGE("Invalid subscribeId");
2718         return RET_ERR;
2719     }
2720     int32_t pid = GetCallingPid();
2721     int32_t ret = delegateTasks_.PostSyncTask(
2722         [this, pid, subscribeId] {
2723             auto sess = this->GetSessionByPid(pid);
2724             CHKPR(sess, RET_ERR);
2725             return TABLET_SCRIBER_HANDLER->UnsubscribetabletProximity(sess, subscribeId);
2726         }
2727         );
2728     if (ret != RET_OK) {
2729         MMI_HILOGE("The unsubscribe tablet event processed failed, ret:%{public}d", ret);
2730         return ret;
2731     }
2732     return RET_OK;
2733 }
2734 
SubscribeLongPressEvent(int32_t subscribeId,const LongPressRequest & longPressRequest)2735 ErrCode MMIService::SubscribeLongPressEvent(int32_t subscribeId, const LongPressRequest &longPressRequest)
2736 {
2737     CALL_INFO_TRACE;
2738     if (!PER_HELPER->VerifySystemApp()) {
2739         MMI_HILOGE("Verify system APP failed");
2740         return ERROR_NOT_SYSAPI;
2741     }
2742     if (!IsRunning()) {
2743         MMI_HILOGE("Service is not running");
2744         return MMISERVICE_NOT_RUNNING;
2745     }
2746     int32_t pid = GetCallingPid();
2747     int32_t ret = delegateTasks_.PostSyncTask(
2748         [this, pid, subscribeId, longPressRequest] {
2749             return sMsgHandler_.OnSubscribeLongPressEvent(this, pid, subscribeId, longPressRequest);
2750         }
2751         );
2752     if (ret != RET_OK) {
2753         MMI_HILOGE("The subscribe long press event processed failed, ret:%{public}d", ret);
2754         return ret;
2755     }
2756     return RET_OK;
2757 }
2758 
UnsubscribeLongPressEvent(int32_t subscribeId)2759 ErrCode MMIService::UnsubscribeLongPressEvent(int32_t subscribeId)
2760 {
2761     CALL_INFO_TRACE;
2762     if (!PER_HELPER->VerifySystemApp()) {
2763         MMI_HILOGE("Verify system APP failed");
2764         return ERROR_NOT_SYSAPI;
2765     }
2766     if (!IsRunning()) {
2767         MMI_HILOGE("Service is not running");
2768         return MMISERVICE_NOT_RUNNING;
2769     }
2770     int32_t pid = GetCallingPid();
2771     int32_t ret = delegateTasks_.PostSyncTask(
2772         [this, pid, subscribeId] {
2773             return sMsgHandler_.OnUnsubscribeLongPressEvent(this, pid, subscribeId);
2774         }
2775         );
2776     if (ret != RET_OK) {
2777         MMI_HILOGE("The unsubscribe long press event processed failed, ret:%{public}d", ret);
2778         return ret;
2779     }
2780     return RET_OK;
2781 }
2782 
SetAnrObserver()2783 ErrCode MMIService::SetAnrObserver()
2784 {
2785     CALL_INFO_TRACE;
2786     if (!PER_HELPER->VerifySystemApp()) {
2787         MMI_HILOGE("Verify system APP failed");
2788         return ERROR_NOT_SYSAPI;
2789     }
2790     if (!IsRunning()) {
2791         MMI_HILOGE("Service is not running");
2792         return MMISERVICE_NOT_RUNNING;
2793     }
2794     int32_t pid = GetCallingPid();
2795     int32_t ret = delegateTasks_.PostSyncTask(
2796         [pid] {
2797             return ::OHOS::DelayedSingleton<ANRManager>::GetInstance()->SetANRNoticedPid(pid);
2798         }
2799         );
2800     if (ret != RET_OK) {
2801         MMI_HILOGE("Set ANRNoticed pid failed, ret:%{public}d", ret);
2802         return ret;
2803     }
2804     return RET_OK;
2805 }
2806 
GetDisplayBindInfo(std::vector<DisplayBindInfo> & infos)2807 ErrCode MMIService::GetDisplayBindInfo(std::vector<DisplayBindInfo>& infos)
2808 {
2809     CALL_INFO_TRACE;
2810     if (!PER_HELPER->VerifySystemApp()) {
2811         MMI_HILOGE("Verify system APP failed");
2812         return ERROR_NOT_SYSAPI;
2813     }
2814     if (!IsRunning()) {
2815         MMI_HILOGE("Service is not running");
2816         return MMISERVICE_NOT_RUNNING;
2817     }
2818     infos.clear();
2819     int32_t ret = delegateTasks_.PostSyncTask(
2820         [&infos] {
2821             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->GetDisplayBindInfo(infos);
2822         }
2823         );
2824     if (ret != RET_OK) {
2825         MMI_HILOGE("GetDisplayBindInfo pid failed, ret:%{public}d", ret);
2826         return ret;
2827     }
2828     return RET_OK;
2829 }
2830 
GetAllMmiSubscribedEvents(MmiEventMap & mmiEventMap)2831 ErrCode MMIService::GetAllMmiSubscribedEvents(MmiEventMap& mmiEventMap)
2832 {
2833     CALL_INFO_TRACE;
2834     if (!PER_HELPER->VerifySystemApp()) {
2835         MMI_HILOGE("Verify system APP failed");
2836         return ERROR_NOT_SYSAPI;
2837     }
2838     if (!IsRunning()) {
2839         MMI_HILOGE("Service is not running");
2840         return MMISERVICE_NOT_RUNNING;
2841     }
2842     mmiEventMap.datas.clear();
2843     NapProcess::GetInstance()->GetAllMmiSubscribedEvents(mmiEventMap.datas);
2844     return RET_OK;
2845 }
2846 
SetDisplayBind(int32_t deviceId,int32_t displayId,std::string & msg)2847 ErrCode MMIService::SetDisplayBind(int32_t deviceId, int32_t displayId, std::string &msg)
2848 {
2849     CALL_INFO_TRACE;
2850     if (!PER_HELPER->VerifySystemApp()) {
2851         MMI_HILOGE("Verify system APP failed");
2852         return ERROR_NOT_SYSAPI;
2853     }
2854     if (!IsRunning()) {
2855         MMI_HILOGE("Service is not running");
2856         return MMISERVICE_NOT_RUNNING;
2857     }
2858     int32_t ret = delegateTasks_.PostSyncTask(
2859         [deviceId, displayId, &msg] {
2860             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->SetDisplayBind(deviceId, displayId, msg);
2861         }
2862         );
2863     if (ret != RET_OK) {
2864         MMI_HILOGE("SetDisplayBind pid failed, ret:%{public}d", ret);
2865         return ret;
2866     }
2867     return RET_OK;
2868 }
2869 
GetFunctionKeyState(int32_t funcKey,bool & state)2870 ErrCode MMIService::GetFunctionKeyState(int32_t funcKey, bool &state)
2871 {
2872     CALL_INFO_TRACE;
2873     if (!IsRunning()) {
2874         MMI_HILOGE("Service is not running");
2875         return MMISERVICE_NOT_RUNNING;
2876     }
2877     state = false;
2878 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2879     int32_t ret = delegateTasks_.PostSyncTask(
2880         [this, funcKey, &state] {
2881             return sMsgHandler_.OnGetFunctionKeyState(funcKey, state);
2882         }
2883         );
2884     if (ret != RET_OK) {
2885         MMI_HILOGE("Failed to get the keyboard status, ret:%{public}d", ret);
2886         return ret;
2887     }
2888 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2889     return RET_OK;
2890 }
2891 
SetFunctionKeyState(int32_t funcKey,bool enable)2892 ErrCode MMIService::SetFunctionKeyState(int32_t funcKey, bool enable)
2893 {
2894     CALL_INFO_TRACE;
2895     if (!PER_HELPER->CheckFunctionKeyEnabled()) {
2896         MMI_HILOGE("Set function key state permission check failed");
2897         return ERROR_KEYBOARD_NO_PERMISSION;
2898     }
2899     if (!IsRunning()) {
2900         MMI_HILOGE("Service is not running");
2901         return MMISERVICE_NOT_RUNNING;
2902     }
2903     if (funcKey != KeyEvent::NUM_LOCK_FUNCTION_KEY && funcKey != KeyEvent::CAPS_LOCK_FUNCTION_KEY &&
2904         funcKey != KeyEvent::SCROLL_LOCK_FUNCTION_KEY) {
2905         MMI_HILOGE("Invalid funcKey:%{public}d", funcKey);
2906         return RET_ERR;
2907     }
2908 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
2909     int32_t clientPid = GetCallingPid();
2910     int32_t ret = delegateTasks_.PostSyncTask(
2911         [this, clientPid, funcKey, enable] {
2912             return sMsgHandler_.OnSetFunctionKeyState(clientPid, funcKey, enable);
2913         }
2914         );
2915     if (ret != RET_OK) {
2916         MMI_HILOGE("Failed to update the keyboard status, ret:%{public}d", ret);
2917         return ret;
2918     }
2919 #endif // OHOS_BUILD_ENABLE_KEYBOARD
2920     return RET_OK;
2921 }
2922 
SetPointerLocation(int32_t x,int32_t y,int32_t displayId)2923 ErrCode MMIService::SetPointerLocation(int32_t x, int32_t y, int32_t displayId)
2924 {
2925     CALL_INFO_TRACE;
2926     if (!PER_HELPER->VerifySystemApp()) {
2927         MMI_HILOGE("StubSetPointerLocation Verify system APP failed");
2928         return ERROR_NOT_SYSAPI;
2929     }
2930     if (!PER_HELPER->CheckMouseCursor()) {
2931         MMI_HILOGE("Mouse cursor permission check failed");
2932         return ERROR_NO_PERMISSION;
2933     }
2934     if (!IsRunning()) {
2935         MMI_HILOGE("Service is not running");
2936         return MMISERVICE_NOT_RUNNING;
2937     }
2938 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2939     int32_t ret = delegateTasks_.PostSyncTask(
2940         [x, y, displayId] {
2941             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetPointerLocation(x, y, displayId);
2942         }
2943         );
2944     if (ret != RET_OK) {
2945         MMI_HILOGE("Set pointer location failed, ret:%{public}d", ret);
2946         return ret;
2947     }
2948 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2949     return RET_OK;
2950 }
2951 
GetPointerLocation(int32_t & displayId,double & displayX,double & displayY)2952 ErrCode MMIService::GetPointerLocation(int32_t &displayId, double &displayX, double &displayY)
2953 {
2954     CALL_INFO_TRACE;
2955 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2956     auto tokenId = IPCSkeleton::GetCallingTokenID();
2957     auto tokenType = OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
2958     if (tokenType != OHOS::Security::AccessToken::TOKEN_HAP) {
2959         return ERROR_APP_NOT_FOCUSED;
2960     }
2961     int32_t clientPid = GetCallingPid();
2962     int32_t ret = delegateTasks_.PostSyncTask(
2963         [this, &displayId, &displayX, &displayY, clientPid] {
2964             if (!INPUT_DEV_MGR->HasPointerDevice() && !INPUT_DEV_MGR->HasVirtualPointerDevice()) {
2965                 MMI_HILOGE("There hasn't any pointer device");
2966                 return ERROR_DEVICE_NO_POINTER;
2967             }
2968             if (!WIN_MGR->CheckAppFocused(clientPid)) {
2969                 return ERROR_APP_NOT_FOCUSED;
2970             }
2971             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->GetPointerLocation(displayId,
2972                 displayX, displayY);
2973         });
2974     if (ret != RET_OK) {
2975         MMI_HILOGE("Get pointer location failed, ret:%{public}d", ret);
2976         return ret;
2977     }
2978 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2979     return RET_OK;
2980 }
2981 
OnDelegateTask(epoll_event & ev)2982 void MMIService::OnDelegateTask(epoll_event &ev)
2983 {
2984     if ((ev.events & EPOLLIN) == 0) {
2985         MMI_HILOGW("Not epollin");
2986         return;
2987     }
2988     delegateTasks_.ProcessTasks();
2989 }
2990 
OnThread()2991 void MMIService::OnThread()
2992 {
2993     SetThreadName(std::string("mmi_service"));
2994     uint64_t tid = GetThisThreadId();
2995     delegateTasks_.SetWorkerThreadId(tid);
2996     MMI_HILOGI("Main worker thread start. tid:%{public}" PRId64 "", tid);
2997 #ifdef OHOS_BUILD_PC_PRIORITY
2998     SetMmiServicePriority(0);
2999 #endif // OHOS_BUILD_PC_PRIORITY
3000 #ifdef OHOS_RSS_CLIENT
3001     tid_.store(tid);
3002 #endif // OHOS_RSS_CLIENT
3003     PreEventLoop();
3004 
3005     while (state_ == ServiceRunningState::STATE_RUNNING) {
3006 #if defined(OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER) && defined(OHOS_BUILD_ENABLE_KEYBOARD)
3007         if (isCesStart_ && !DISPLAY_MONITOR->IsCommonEventSubscriberInit()) {
3008             DISPLAY_MONITOR->InitCommonEventSubscriber();
3009         }
3010 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER && OHOS_BUILD_ENABLE_KEYBOARD
3011         epoll_event ev[MAX_EVENT_SIZE] = {};
3012         int32_t timeout = TimerMgr->CalcNextDelay();
3013         MMI_HILOGD("timeout:%{public}d", timeout);
3014         int32_t count = EpollWait(ev[0], MAX_EVENT_SIZE, timeout, mmiFd_);
3015         for (int32_t i = 0; i < count && state_ == ServiceRunningState::STATE_RUNNING; i++) {
3016             auto mmiEdIter = epollEventMap_.find(ev[i].data.fd);
3017             if (mmiEdIter == epollEventMap_.end()) {
3018                 MMI_HILOGD("Invalid event %{public}d %{public}d", ev[i].data.fd, count);
3019                 continue;
3020             }
3021             std::shared_ptr<mmi_epoll_event> mmiEd = mmiEdIter->second;
3022             CHKPC(mmiEd);
3023             epoll_event event = ev[i];
3024             if (mmiEd->event_type == EPOLL_EVENT_INPUT) {
3025                 CalculateFuntionRunningTime([this, &mmiEd] () { libinputAdapter_.EventDispatch(mmiEd->fd); },
3026                     "EPOLL_EVENT_INPUT");
3027             } else if (mmiEd->event_type == EPOLL_EVENT_SOCKET) {
3028                 CalculateFuntionRunningTime([this, &event]() { this->OnEpollEvent(event); }, "MMI:EPOLL_EVENT_SOCKET");
3029             } else if (mmiEd->event_type == EPOLL_EVENT_SIGNAL) {
3030                 OnSignalEvent(mmiEd->fd);
3031             } else if (mmiEd->event_type == EPOLL_EVENT_ETASK) {
3032                 CalculateFuntionRunningTime([this, &event]() { this->OnDelegateTask(event); }, "MMI:EPOLL_EVENT_ETASK");
3033             } else {
3034                 MMI_HILOGW("Unknown epoll event type:%{public}d", mmiEd->event_type);
3035             }
3036         }
3037         TimerMgr->ProcessTimers();
3038         if (state_ != ServiceRunningState::STATE_RUNNING) {
3039             break;
3040         }
3041     }
3042     MMI_HILOGI("Main worker thread stop. tid:%{public}" PRId64 "", tid);
3043 }
3044 
3045 #ifdef OHOS_BUILD_PC_PRIORITY
SetMmiServicePriority(int32_t tid)3046 void MMIService::SetMmiServicePriority(int32_t tid)
3047 {
3048     struct sched_param param = {0};
3049     param.sched_priority = PC_PRIORITY;
3050     int32_t schRet = sched_setscheduler(tid, SCHED_FIFO, &param);
3051     if (schRet != 0) {
3052         MMI_HILOGE("mmi_service Couldn't set SCHED_FIFO, schRet:%{public}d", schRet);
3053     } else {
3054         MMI_HILOGI("The mmi_service set SCHED_FIFO succeed, schRet:%{public}d", schRet);
3055     }
3056 }
3057 #endif // OHOS_BUILD_PC_PRIORITY
3058 
PreEventLoop()3059 void MMIService::PreEventLoop()
3060 {
3061 #if defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
3062     SetupTouchGestureHandler();
3063 #endif // defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
3064     libinputAdapter_.ProcessPendingEvents();
3065 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
3066     TOUCH_DRAWING_MGR->Initialize();
3067 #endif // OHOS_BUILD_ENABLE_TOUCH_DRAWING
3068 }
3069 
InitSignalHandler()3070 bool MMIService::InitSignalHandler()
3071 {
3072     CALL_DEBUG_ENTER;
3073     sigset_t mask = { 0 };
3074     int32_t retCode = sigfillset(&mask);
3075     if (retCode < 0) {
3076         MMI_HILOGE("Fill signal set failed:%{public}d", errno);
3077         return false;
3078     }
3079 
3080     retCode = sigprocmask(SIG_SETMASK, &mask, nullptr);
3081     if (retCode < 0) {
3082         MMI_HILOGE("Sigprocmask failed:%{public}d", errno);
3083         return false;
3084     }
3085 
3086     int32_t fdSignal = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);
3087     if (fdSignal < 0) {
3088         MMI_HILOGE("Signal fd failed:%{public}d", errno);
3089         return false;
3090     }
3091 
3092     retCode = AddEpoll(EPOLL_EVENT_SIGNAL, fdSignal);
3093     if (retCode < 0) {
3094         MMI_HILOGE("AddEpoll signalFd failed:%{public}d", retCode);
3095         close(fdSignal);
3096         return false;
3097     }
3098     return true;
3099 }
3100 
OnSignalEvent(int32_t signalFd)3101 void MMIService::OnSignalEvent(int32_t signalFd)
3102 {
3103     CALL_DEBUG_ENTER;
3104     signalfd_siginfo sigInfo;
3105     int32_t size = ::read(signalFd, &sigInfo, sizeof(signalfd_siginfo));
3106     if (size != static_cast<int32_t>(sizeof(signalfd_siginfo))) {
3107         MMI_HILOGE("Read signal info failed, invalid size:%{public}d, errno:%{public}d", size, errno);
3108         return;
3109     }
3110     int32_t signo = static_cast<int32_t>(sigInfo.ssi_signo);
3111     MMI_HILOGD("Receive signal:%{public}d", signo);
3112     switch (signo) {
3113         case SIGINT:
3114         case SIGQUIT:
3115         case SIGILL:
3116         case SIGABRT:
3117         case SIGBUS:
3118         case SIGFPE:
3119         case SIGKILL:
3120         case SIGSEGV:
3121         case SIGTERM: {
3122             state_ = ServiceRunningState::STATE_EXIT;
3123             break;
3124         }
3125         default: {
3126             break;
3127         }
3128     }
3129 }
3130 
AddReloadDeviceTimer()3131 void MMIService::AddReloadDeviceTimer()
3132 {
3133     CALL_DEBUG_ENTER;
3134     TimerMgr->AddTimer(RELOAD_DEVICE_TIME, REPEAT_COUNT, [this]() {
3135         auto deviceIds = INPUT_DEV_MGR->GetInputDeviceIds();
3136         if (deviceIds.empty()) {
3137             libinputAdapter_.ReloadDevice();
3138         }
3139     }, "MMIService-AddReloadDeviceTimer");
3140 }
3141 
Dump(int32_t fd,const std::vector<std::u16string> & args)3142 int32_t MMIService::Dump(int32_t fd, const std::vector<std::u16string> &args)
3143 {
3144     CALL_DEBUG_ENTER;
3145     if (fd < 0) {
3146         MMI_HILOGE("The fd is invalid");
3147         return DUMP_PARAM_ERR;
3148     }
3149     if (args.empty()) {
3150         MMI_HILOGE("The args cannot be empty");
3151         mprintf(fd, "args cannot be empty\n");
3152         MMIEventDump->DumpHelp(fd);
3153         return DUMP_PARAM_ERR;
3154     }
3155     std::vector<std::string> argList = { "" };
3156     std::transform(args.begin(), args.end(), std::back_inserter(argList),
3157         [](const std::u16string &arg) { return Str16ToStr8(arg); });
3158     MMIEventDump->ParseCommand(fd, argList);
3159     return RET_OK;
3160 }
3161 
SetMouseCaptureMode(int32_t windowId,bool isCaptureMode)3162 ErrCode MMIService::SetMouseCaptureMode(int32_t windowId, bool isCaptureMode)
3163 {
3164     CALL_INFO_TRACE;
3165     if (!PER_HELPER->VerifySystemApp()) {
3166         MMI_HILOGE("Verify system APP failed");
3167         return ERROR_NOT_SYSAPI;
3168     }
3169     if (windowId <= 0) {
3170         MMI_HILOGE("Invalid windowId:%{public}d", windowId);
3171         return RET_ERR;
3172     }
3173     int32_t ret = delegateTasks_.PostSyncTask(
3174         [windowId, isCaptureMode] {
3175             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->SetMouseCaptureMode(windowId, isCaptureMode);
3176         }
3177         );
3178     if (ret != RET_OK) {
3179         MMI_HILOGE("Set capture failed, return:%{public}d", ret);
3180         return ret;
3181     }
3182     return RET_OK;
3183 }
3184 
OnGetWindowPid(int32_t windowId,int32_t & windowPid)3185 int32_t MMIService::OnGetWindowPid(int32_t windowId, int32_t &windowPid)
3186 {
3187     CALL_DEBUG_ENTER;
3188     windowPid = WIN_MGR->GetWindowPid(windowId);
3189     if (windowPid == RET_ERR) {
3190         MMI_HILOGE("Get window pid failed");
3191         return RET_ERR;
3192     }
3193     MMI_HILOGD("The windowpid is:%{public}d", windowPid);
3194     return RET_OK;
3195 }
3196 
GetWindowPid(int32_t windowId,int32_t & windowPid)3197 ErrCode MMIService::GetWindowPid(int32_t windowId, int32_t &windowPid)
3198 {
3199     CALL_INFO_TRACE;
3200     if (!IsRunning()) {
3201         MMI_HILOGE("Service is not running");
3202         return MMISERVICE_NOT_RUNNING;
3203     }
3204     windowPid = INVALID_PID;
3205     int32_t ret = delegateTasks_.PostSyncTask(
3206         [this, windowId, &windowPid] {
3207             return this->OnGetWindowPid(windowId, windowPid);
3208         }
3209         );
3210     if (ret != RET_OK) {
3211         MMI_HILOGE("OnGetWindowPid failed, ret:%{public}d", ret);
3212         return ret;
3213     }
3214     MMI_HILOGD("The windowpid is:%{public}d", windowPid);
3215     return RET_OK;
3216 }
3217 
AppendExtraData(const ExtraData & extraData)3218 ErrCode MMIService::AppendExtraData(const ExtraData &extraData)
3219 {
3220     CALL_DEBUG_ENTER;
3221     if (!PER_HELPER->VerifySystemApp()) {
3222         MMI_HILOGE("Verify system APP failed");
3223         return ERROR_NOT_SYSAPI;
3224     }
3225     if (!IsRunning()) {
3226         MMI_HILOGE("Service is not running");
3227         return MMISERVICE_NOT_RUNNING;
3228     }
3229     if (extraData.buffer.size() > ExtraData::MAX_BUFFER_SIZE) {
3230         MMI_HILOGE("Append extra data failed, buffer is oversize:%{public}zu", extraData.buffer.size());
3231         return ERROR_OVER_SIZE_BUFFER;
3232     }
3233     if (extraData.sourceType != InputEvent::SOURCE_TYPE_TOUCHSCREEN &&
3234         extraData.sourceType != InputEvent::SOURCE_TYPE_MOUSE) {
3235         MMI_HILOGE("Invalid extraData.sourceType:%{public}d", extraData.sourceType);
3236         return RET_ERR;
3237     }
3238     if (extraData.pointerId < 0 || extraData.pullId < 0) {
3239         MMI_HILOGE("Invalid extraData.pointerId or extraData.pullId or extraData.eventId, pointerId:%{public}d,"
3240             "pullId:%{public}d, eventId:%{public}d", extraData.pointerId, extraData.pullId, extraData.eventId);
3241         return RET_ERR;
3242     }
3243     int32_t ret = delegateTasks_.PostSyncTask(
3244         [extraData] {
3245             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->AppendExtraData(extraData);
3246         }
3247         );
3248     if (ret != RET_OK) {
3249         MMI_HILOGE("Append extra data failed:%{public}d", ret);
3250     }
3251     return ret;
3252 }
3253 
EnableInputDevice(bool enable)3254 ErrCode MMIService::EnableInputDevice(bool enable)
3255 {
3256     CALL_DEBUG_ENTER;
3257     int32_t ret = delegateTasks_.PostSyncTask(
3258         [enable] {
3259             return ::OHOS::MMI::InputDeviceManager::GetInstance()->OnEnableInputDevice(enable);
3260         }
3261         );
3262     if (ret != RET_OK) {
3263         MMI_HILOGE("OnEnableInputDevice failed:%{public}d", ret);
3264     }
3265     return ret;
3266 }
3267 
3268 #if defined(OHOS_BUILD_ENABLE_KEYBOARD) && defined(OHOS_BUILD_ENABLE_COMBINATION_KEY)
UpdateCombineKeyState(bool enable)3269 int32_t MMIService::UpdateCombineKeyState(bool enable)
3270 {
3271     auto eventSubscriberHandler = InputHandler->GetSubscriberHandler();
3272     CHKPR(eventSubscriberHandler, RET_ERR);
3273     int32_t ret = eventSubscriberHandler->EnableCombineKey(enable);
3274     if (ret != RET_OK) {
3275         MMI_HILOGE("EnableCombineKey is failed in key command:%{public}d", ret);
3276     }
3277 
3278     auto eventKeyCommandHandler = InputHandler->GetKeyCommandHandler();
3279     CHKPR(eventKeyCommandHandler, RET_ERR);
3280     ret = eventKeyCommandHandler->EnableCombineKey(enable);
3281     if (ret != RET_OK) {
3282         MMI_HILOGE("EnableCombineKey is failed in key command:%{public}d", ret);
3283     }
3284     return ret;
3285 }
3286 #endif // OHOS_BUILD_ENABLE_KEYBOARD && OHOS_BUILD_ENABLE_COMBINATION_KEY
3287 
CheckPidPermission(int32_t pid)3288 int32_t MMIService::CheckPidPermission(int32_t pid)
3289 {
3290     CALL_DEBUG_ENTER;
3291     int32_t checkingPid = GetCallingPid();
3292     if (checkingPid != pid) {
3293         MMI_HILOGD("Check pid failed, input pid:%{public}d, but checking pid:%{public}d", pid, checkingPid);
3294         return RET_ERR;
3295     }
3296     return RET_OK;
3297 }
3298 
EnableCombineKey(bool enable)3299 ErrCode MMIService::EnableCombineKey(bool enable)
3300 {
3301     CALL_DEBUG_ENTER;
3302     if (!PER_HELPER->VerifySystemApp()) {
3303         MMI_HILOGE("Verify system APP failed");
3304         return ERROR_NOT_SYSAPI;
3305     }
3306     if (!IsRunning()) {
3307         MMI_HILOGE("Service is not running");
3308         return MMISERVICE_NOT_RUNNING;
3309     }
3310 #if defined(OHOS_BUILD_ENABLE_KEYBOARD) && defined(OHOS_BUILD_ENABLE_COMBINATION_KEY)
3311     int32_t ret = delegateTasks_.PostSyncTask(
3312         [this, enable] {
3313             return this->UpdateCombineKeyState(enable);
3314         }
3315         );
3316     if (ret != RET_OK) {
3317         MMI_HILOGE("Set key down duration failed:%{public}d", ret);
3318         return ret;
3319     }
3320 #endif // OHOS_BUILD_ENABLE_KEYBOARD && OHOS_BUILD_ENABLE_COMBINATION_KEY
3321     return RET_OK;
3322 }
3323 
3324 #if defined(OHOS_BUILD_ENABLE_KEYBOARD) && defined(OHOS_BUILD_ENABLE_COMBINATION_KEY)
UpdateSettingsXml(const std::string & businessId,int32_t delay)3325 int32_t MMIService::UpdateSettingsXml(const std::string &businessId, int32_t delay)
3326 {
3327     std::shared_ptr<KeyCommandHandler> eventKeyCommandHandler = InputHandler->GetKeyCommandHandler();
3328     CHKPR(eventKeyCommandHandler, RET_ERR);
3329     return eventKeyCommandHandler->UpdateSettingsXml(businessId, delay);
3330 }
3331 #endif // OHOS_BUILD_ENABLE_KEYBOARD && OHOS_BUILD_ENABLE_COMBINATION_KEY
3332 
SetKeyDownDuration(const std::string & businessId,int32_t delay)3333 ErrCode MMIService::SetKeyDownDuration(const std::string &businessId, int32_t delay)
3334 {
3335     CALL_INFO_TRACE;
3336     if (!PER_HELPER->VerifySystemApp()) {
3337         MMI_HILOGE("Verify system APP failed");
3338         return ERROR_NOT_SYSAPI;
3339     }
3340     if (!IsRunning()) {
3341         MMI_HILOGE("Service is not running");
3342         return MMISERVICE_NOT_RUNNING;
3343     }
3344 #if defined(OHOS_BUILD_ENABLE_KEYBOARD) && defined(OHOS_BUILD_ENABLE_COMBINATION_KEY)
3345     int32_t ret = delegateTasks_.PostSyncTask(
3346         [this, businessId, delay] {
3347             return this->UpdateSettingsXml(businessId, delay);
3348         }
3349         );
3350     if (ret != RET_OK) {
3351         MMI_HILOGE("Set key down duration failed:%{public}d", ret);
3352         return ret;
3353     }
3354 #endif // OHOS_BUILD_ENABLE_KEYBOARD && OHOS_BUILD_ENABLE_COMBINATION_KEY
3355     return RET_OK;
3356 }
3357 
3358 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadTouchpadScrollSwich(bool & switchFlag)3359 int32_t MMIService::ReadTouchpadScrollSwich(bool &switchFlag)
3360 {
3361     MouseEventHdr->GetTouchpadScrollSwitch(switchFlag);
3362     return RET_OK;
3363 }
3364 
ReadTouchpadScrollDirection(bool & switchFlag)3365 int32_t MMIService::ReadTouchpadScrollDirection(bool &switchFlag)
3366 {
3367     MouseEventHdr->GetTouchpadScrollDirection(switchFlag);
3368     return RET_OK;
3369 }
3370 
ReadTouchpadTapSwitch(bool & switchFlag)3371 int32_t MMIService::ReadTouchpadTapSwitch(bool &switchFlag)
3372 {
3373     MouseEventHdr->GetTouchpadTapSwitch(switchFlag);
3374     return RET_OK;
3375 }
3376 
ReadTouchpadPointerSpeed(int32_t & speed)3377 int32_t MMIService::ReadTouchpadPointerSpeed(int32_t &speed)
3378 {
3379     MouseEventHdr->GetTouchpadPointerSpeed(speed);
3380     return RET_OK;
3381 }
3382 
ReadTouchpadCDG(TouchpadCDG & touchpadCDG)3383 int32_t MMIService::ReadTouchpadCDG(TouchpadCDG &touchpadCDG)
3384 {
3385     MouseEventHdr->GetTouchpadCDG(touchpadCDG);
3386     return RET_OK;
3387 }
3388 
ReadTouchpadPinchSwitch(bool & switchFlag)3389 int32_t MMIService::ReadTouchpadPinchSwitch(bool &switchFlag)
3390 {
3391     TOUCH_EVENT_HDR->GetTouchpadPinchSwitch(switchFlag);
3392     return RET_OK;
3393 }
3394 
ReadTouchpadSwipeSwitch(bool & switchFlag)3395 int32_t MMIService::ReadTouchpadSwipeSwitch(bool &switchFlag)
3396 {
3397     TOUCH_EVENT_HDR->GetTouchpadSwipeSwitch(switchFlag);
3398     return RET_OK;
3399 }
3400 
ReadTouchpadRightMenuType(int32_t & type)3401 int32_t MMIService::ReadTouchpadRightMenuType(int32_t &type)
3402 {
3403     MouseEventHdr->GetTouchpadRightClickType(type);
3404     return RET_OK;
3405 }
3406 
ReadTouchpadRotateSwitch(bool & rotateSwitch)3407 int32_t MMIService::ReadTouchpadRotateSwitch(bool &rotateSwitch)
3408 {
3409     TOUCH_EVENT_HDR->GetTouchpadRotateSwitch(rotateSwitch);
3410     return RET_OK;
3411 }
3412 
ReadTouchpadDoubleTapAndDragState(bool & switchFlag)3413 int32_t MMIService::ReadTouchpadDoubleTapAndDragState(bool &switchFlag)
3414 {
3415     TOUCH_EVENT_HDR->GetTouchpadDoubleTapAndDragState(switchFlag);
3416     return RET_OK;
3417 }
3418 
3419 #endif // OHOS_BUILD_ENABLE_POINTER
3420 
SetTouchpadScrollSwitch(bool switchFlag)3421 ErrCode MMIService::SetTouchpadScrollSwitch(bool switchFlag)
3422 {
3423     CALL_INFO_TRACE;
3424     if (!IsRunning()) {
3425         MMI_HILOGE("Service is not running");
3426         return MMISERVICE_NOT_RUNNING;
3427     }
3428     if (!PER_HELPER->VerifySystemApp()) {
3429         MMI_HILOGE("Verify system APP failed");
3430         return ERROR_NOT_SYSAPI;
3431     }
3432 #if defined OHOS_BUILD_ENABLE_POINTER
3433     int32_t clientPid = GetCallingPid();
3434     int32_t ret = delegateTasks_.PostSyncTask(
3435         [clientPid, switchFlag] {
3436             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetTouchpadScrollSwitch(clientPid,
3437                 switchFlag);
3438         }
3439         );
3440     if (ret != RET_OK) {
3441         MMI_HILOGE("Set touchpad scroll switch failed, return:%{public}d", ret);
3442         return ret;
3443     }
3444 #endif // OHOS_BUILD_ENABLE_POINTER
3445     return RET_OK;
3446 }
3447 
GetTouchpadScrollSwitch(bool & switchFlag)3448 ErrCode MMIService::GetTouchpadScrollSwitch(bool &switchFlag)
3449 {
3450     CALL_INFO_TRACE;
3451     if (!IsRunning()) {
3452         MMI_HILOGE("Service is not running");
3453         return MMISERVICE_NOT_RUNNING;
3454     }
3455     if (!PER_HELPER->VerifySystemApp()) {
3456         MMI_HILOGE("Verify system APP failed");
3457         return ERROR_NOT_SYSAPI;
3458     }
3459     switchFlag = true;
3460 #ifdef OHOS_BUILD_ENABLE_POINTER
3461     int32_t ret = delegateTasks_.PostSyncTask(
3462         [this, &switchFlag] {
3463             return this->ReadTouchpadScrollSwich(switchFlag);
3464         }
3465         );
3466     if (ret != RET_OK) {
3467         MMI_HILOGE("Get touchpad scroll switch failed, return:%{public}d", ret);
3468         return ret;
3469     }
3470 #endif // OHOS_BUILD_ENABLE_POINTER
3471     return RET_OK;
3472 }
3473 
SetTouchpadScrollDirection(bool state)3474 ErrCode MMIService::SetTouchpadScrollDirection(bool state)
3475 {
3476     CALL_INFO_TRACE;
3477     if (!IsRunning()) {
3478         MMI_HILOGE("Service is not running");
3479         return MMISERVICE_NOT_RUNNING;
3480     }
3481     if (!PER_HELPER->VerifySystemApp()) {
3482         MMI_HILOGE("Verify system APP failed");
3483         return ERROR_NOT_SYSAPI;
3484     }
3485 #if defined OHOS_BUILD_ENABLE_POINTER
3486     int32_t ret = delegateTasks_.PostSyncTask(
3487         [state] {
3488             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetTouchpadScrollDirection(state);
3489         }
3490         );
3491     if (ret != RET_OK) {
3492         MMI_HILOGE("Set touchpad scroll direction switch failed, return:%{public}d", ret);
3493         return ret;
3494     }
3495 #endif // OHOS_BUILD_ENABLE_POINTER
3496     return RET_OK;
3497 }
3498 
GetTouchpadScrollDirection(bool & state)3499 ErrCode MMIService::GetTouchpadScrollDirection(bool &state)
3500 {
3501     CALL_INFO_TRACE;
3502     if (!IsRunning()) {
3503         MMI_HILOGE("Service is not running");
3504         return MMISERVICE_NOT_RUNNING;
3505     }
3506     if (!PER_HELPER->VerifySystemApp()) {
3507         MMI_HILOGE("Verify system APP failed");
3508         return ERROR_NOT_SYSAPI;
3509     }
3510     state = true;
3511 #ifdef OHOS_BUILD_ENABLE_POINTER
3512     int32_t ret = delegateTasks_.PostSyncTask(
3513         [this, &state] {
3514             return this->ReadTouchpadScrollDirection(state);
3515         }
3516         );
3517     if (ret != RET_OK) {
3518         MMI_HILOGE("Get touchpad scroll direction switch failed, return:%{public}d", ret);
3519         return ret;
3520     }
3521 #endif // OHOS_BUILD_ENABLE_POINTER
3522     return RET_OK;
3523 }
3524 
SetTouchpadTapSwitch(bool switchFlag)3525 ErrCode MMIService::SetTouchpadTapSwitch(bool switchFlag)
3526 {
3527     CALL_INFO_TRACE;
3528     if (!IsRunning()) {
3529         MMI_HILOGE("Service is not running");
3530         return MMISERVICE_NOT_RUNNING;
3531     }
3532     if (!PER_HELPER->VerifySystemApp()) {
3533         MMI_HILOGE("Verify system APP failed");
3534         return ERROR_NOT_SYSAPI;
3535     }
3536 #if defined OHOS_BUILD_ENABLE_POINTER
3537     int32_t ret = delegateTasks_.PostSyncTask(
3538         [switchFlag] {
3539             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetTouchpadTapSwitch(switchFlag);
3540         }
3541         );
3542     if (ret != RET_OK) {
3543         MMI_HILOGE("Set touchpad tap switch failed, return:%{public}d", ret);
3544         return ret;
3545     }
3546 #endif // OHOS_BUILD_ENABLE_POINTER
3547     return RET_OK;
3548 }
3549 
GetTouchpadTapSwitch(bool & switchFlag)3550 ErrCode MMIService::GetTouchpadTapSwitch(bool &switchFlag)
3551 {
3552     CALL_INFO_TRACE;
3553     if (!IsRunning()) {
3554         MMI_HILOGE("Service is not running");
3555         return MMISERVICE_NOT_RUNNING;
3556     }
3557     if (!PER_HELPER->VerifySystemApp()) {
3558         MMI_HILOGE("Verify system APP failed");
3559         return ERROR_NOT_SYSAPI;
3560     }
3561     switchFlag = true;
3562 #ifdef OHOS_BUILD_ENABLE_POINTER
3563     int32_t ret = delegateTasks_.PostSyncTask(
3564         [this, &switchFlag] {
3565             return this->ReadTouchpadTapSwitch(switchFlag);
3566         }
3567         );
3568     if (ret != RET_OK) {
3569         MMI_HILOGE("Get touchpad tap switch failed, return:%{public}d", ret);
3570         return ret;
3571     }
3572 #endif // OHOS_BUILD_ENABLE_POINTER
3573     return RET_OK;
3574 }
3575 
SetTouchpadPointerSpeed(int32_t speed)3576 ErrCode MMIService::SetTouchpadPointerSpeed(int32_t speed)
3577 {
3578     CALL_INFO_TRACE;
3579     if (!IsRunning()) {
3580         MMI_HILOGE("Service is not running");
3581         return MMISERVICE_NOT_RUNNING;
3582     }
3583     if (!PER_HELPER->VerifySystemApp()) {
3584         MMI_HILOGE("Verify system APP failed");
3585         return ERROR_NOT_SYSAPI;
3586     }
3587     if (speed < MIN_SPEED) {
3588         speed = MIN_SPEED;
3589     } else if (speed > MAX_SPEED) {
3590         speed = MAX_SPEED;
3591     }
3592 #if defined OHOS_BUILD_ENABLE_POINTER
3593     int32_t ret = delegateTasks_.PostSyncTask(
3594         [speed] {
3595             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetTouchpadPointerSpeed(speed);
3596         }
3597         );
3598     if (ret != RET_OK) {
3599         MMI_HILOGE("Set touchpad speed failed, return:%{public}d", ret);
3600         return ret;
3601     }
3602 #endif // OHOS_BUILD_ENABLE_POINTER
3603     return RET_OK;
3604 }
3605 
GetTouchpadPointerSpeed(int32_t & speed)3606 ErrCode MMIService::GetTouchpadPointerSpeed(int32_t &speed)
3607 {
3608     CALL_INFO_TRACE;
3609     if (!IsRunning()) {
3610         MMI_HILOGE("Service is not running");
3611         return MMISERVICE_NOT_RUNNING;
3612     }
3613     if (!PER_HELPER->VerifySystemApp()) {
3614         MMI_HILOGE("Verify system APP failed");
3615         return ERROR_NOT_SYSAPI;
3616     }
3617     speed = 1;
3618 #ifdef OHOS_BUILD_ENABLE_POINTER
3619     int32_t ret = delegateTasks_.PostSyncTask(
3620         [this, &speed] {
3621             return this->ReadTouchpadPointerSpeed(speed);
3622         }
3623         );
3624     if (ret != RET_OK) {
3625         MMI_HILOGE("Get touchpad speed failed, return:%{public}d", ret);
3626         return ret;
3627     }
3628 #endif // OHOS_BUILD_ENABLE_POINTER
3629     return RET_OK;
3630 }
3631 
GetTouchpadCDG(TouchpadCDG & touchpadCDG)3632 ErrCode MMIService::GetTouchpadCDG(TouchpadCDG &touchpadCDG)
3633 {
3634     CALL_INFO_TRACE;
3635     if (!IsRunning()) {
3636         MMI_HILOGE("Service is not running");
3637         return MMISERVICE_NOT_RUNNING;
3638     }
3639     if (!PER_HELPER->VerifySystemApp()) {
3640         MMI_HILOGE("Verify system APP failed");
3641         return ERROR_NOT_SYSAPI;
3642     }
3643     touchpadCDG.ppi = 0.0;
3644     touchpadCDG.size = 0.0;
3645     touchpadCDG.speed = 0;
3646     touchpadCDG.frequency = 0;
3647 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
3648     int32_t ret = delegateTasks_.PostSyncTask(
3649         [this, &touchpadCDG] {
3650             return this->ReadTouchpadCDG(touchpadCDG);
3651         }
3652         );
3653     if (ret != RET_OK) {
3654         MMI_HILOGE("Get touchpad option failed, return:%{public}d", ret);
3655         return ret;
3656     }
3657 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
3658     return RET_OK;
3659 }
3660 
SetTouchpadPinchSwitch(bool switchFlag)3661 ErrCode MMIService::SetTouchpadPinchSwitch(bool switchFlag)
3662 {
3663     CALL_INFO_TRACE;
3664     if (!IsRunning()) {
3665         MMI_HILOGE("Service is not running");
3666         return MMISERVICE_NOT_RUNNING;
3667     }
3668     if (!PER_HELPER->VerifySystemApp()) {
3669         MMI_HILOGE("Verify system APP failed");
3670         return ERROR_NOT_SYSAPI;
3671     }
3672 #if defined OHOS_BUILD_ENABLE_POINTER
3673     int32_t ret = delegateTasks_.PostSyncTask(
3674         [switchFlag] {
3675             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadPinchSwitch(switchFlag);
3676         }
3677         );
3678     if (ret != RET_OK) {
3679         MMI_HILOGE("Set touch pad pinch switch failed, return:%{public}d", ret);
3680         return ret;
3681     }
3682 #endif // OHOS_BUILD_ENABLE_POINTER
3683     return RET_OK;
3684 }
3685 
GetTouchpadPinchSwitch(bool & switchFlag)3686 ErrCode MMIService::GetTouchpadPinchSwitch(bool &switchFlag)
3687 {
3688     CALL_INFO_TRACE;
3689     if (!IsRunning()) {
3690         MMI_HILOGE("Service is not running");
3691         return MMISERVICE_NOT_RUNNING;
3692     }
3693     if (!PER_HELPER->VerifySystemApp()) {
3694         MMI_HILOGE("Verify system APP failed");
3695         return ERROR_NOT_SYSAPI;
3696     }
3697     switchFlag = true;
3698 #ifdef OHOS_BUILD_ENABLE_POINTER
3699     int32_t ret = delegateTasks_.PostSyncTask(
3700         [this, &switchFlag] {
3701             return this->ReadTouchpadPinchSwitch(switchFlag);
3702         }
3703         );
3704     if (ret != RET_OK) {
3705         MMI_HILOGE("Get touch pad pinch switch failed, return:%{public}d", ret);
3706         return ret;
3707     }
3708 #endif // OHOS_BUILD_ENABLE_POINTER
3709     return RET_OK;
3710 }
3711 
SetTouchpadSwipeSwitch(bool switchFlag)3712 ErrCode MMIService::SetTouchpadSwipeSwitch(bool switchFlag)
3713 {
3714     CALL_INFO_TRACE;
3715     if (!IsRunning()) {
3716         MMI_HILOGE("Service is not running");
3717         return MMISERVICE_NOT_RUNNING;
3718     }
3719     if (!PER_HELPER->VerifySystemApp()) {
3720         MMI_HILOGE("Verify system APP failed");
3721         return ERROR_NOT_SYSAPI;
3722     }
3723 #if defined OHOS_BUILD_ENABLE_POINTER
3724     int32_t ret = delegateTasks_.PostSyncTask(
3725         [switchFlag] {
3726             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadSwipeSwitch(switchFlag);
3727         }
3728         );
3729     if (ret != RET_OK) {
3730         MMI_HILOGE("Set touchpad swipe switch failed, return:%{public}d", ret);
3731         return ret;
3732     }
3733 #endif // OHOS_BUILD_ENABLE_POINTER
3734     return RET_OK;
3735 }
3736 
GetTouchpadSwipeSwitch(bool & switchFlag)3737 ErrCode MMIService::GetTouchpadSwipeSwitch(bool &switchFlag)
3738 {
3739     CALL_INFO_TRACE;
3740     if (!IsRunning()) {
3741         MMI_HILOGE("Service is not running");
3742         return MMISERVICE_NOT_RUNNING;
3743     }
3744     if (!PER_HELPER->VerifySystemApp()) {
3745         MMI_HILOGE("Verify system APP failed");
3746         return ERROR_NOT_SYSAPI;
3747     }
3748     switchFlag = true;
3749 #ifdef OHOS_BUILD_ENABLE_POINTER
3750     int32_t ret = delegateTasks_.PostSyncTask(
3751         [this, &switchFlag] {
3752             return this->ReadTouchpadSwipeSwitch(switchFlag);
3753         }
3754         );
3755     if (ret != RET_OK) {
3756         MMI_HILOGE("Get touchpad swipe switch failed, return:%{public}d", ret);
3757         return ret;
3758     }
3759 #endif // OHOS_BUILD_ENABLE_POINTER
3760     return RET_OK;
3761 }
3762 
IsValidType(int32_t type)3763 bool MMIService::IsValidType(int32_t type)
3764 {
3765     if (type != RightClickType::TOUCHPAD_RIGHT_BUTTON &&
3766         type != RightClickType::TOUCHPAD_LEFT_BUTTON &&
3767         type != RightClickType::TOUCHPAD_TWO_FINGER_TAP &&
3768         type != RightClickType::TOUCHPAD_TWO_FINGER_TAP_OR_RIGHT_BUTTON &&
3769         type != RightClickType::TOUCHPAD_TWO_FINGER_TAP_OR_LEFT_BUTTON) {
3770         return false;
3771     }
3772     return true;
3773 }
3774 
SetTouchpadRightClickType(int32_t type)3775 ErrCode MMIService::SetTouchpadRightClickType(int32_t type)
3776 {
3777     CALL_INFO_TRACE;
3778     if (!IsRunning()) {
3779         MMI_HILOGE("Service is not running");
3780         return MMISERVICE_NOT_RUNNING;
3781     }
3782     if (!PER_HELPER->VerifySystemApp()) {
3783         MMI_HILOGE("Verify system APP failed");
3784         return ERROR_NOT_SYSAPI;
3785     }
3786     if (!IsValidType(type)) {
3787         MMI_HILOGE("Invalid type:%{public}d", type);
3788         return RET_ERR;
3789     }
3790 #if defined OHOS_BUILD_ENABLE_POINTER
3791     int32_t ret = delegateTasks_.PostSyncTask(
3792         [type] {
3793             return ::OHOS::DelayedSingleton<MouseEventNormalize>::GetInstance()->SetTouchpadRightClickType(type);
3794         }
3795         );
3796     if (ret != RET_OK) {
3797         MMI_HILOGE("Set touchpad right button menu type failed, return:%{public}d", ret);
3798         return ret;
3799     }
3800 #endif // OHOS_BUILD_ENABLE_POINTER
3801     return RET_OK;
3802 }
3803 
GetTouchpadRightClickType(int32_t & type)3804 ErrCode MMIService::GetTouchpadRightClickType(int32_t &type)
3805 {
3806     CALL_INFO_TRACE;
3807     if (!IsRunning()) {
3808         MMI_HILOGE("Service is not running");
3809         return MMISERVICE_NOT_RUNNING;
3810     }
3811     if (!PER_HELPER->VerifySystemApp()) {
3812         MMI_HILOGE("Verify system APP failed");
3813         return ERROR_NOT_SYSAPI;
3814     }
3815     type = 1;
3816 #ifdef OHOS_BUILD_ENABLE_POINTER
3817     int32_t ret = delegateTasks_.PostSyncTask(
3818         [this, &type] {
3819             return this->ReadTouchpadRightMenuType(type);
3820         }
3821         );
3822     if (ret != RET_OK) {
3823         MMI_HILOGE("Get touchpad right button menu type failed, return:%{public}d", ret);
3824         return ret;
3825     }
3826 #endif // OHOS_BUILD_ENABLE_POINTER
3827     return RET_OK;
3828 }
3829 
SetTouchpadRotateSwitch(bool rotateSwitch)3830 ErrCode MMIService::SetTouchpadRotateSwitch(bool rotateSwitch)
3831 {
3832     CALL_INFO_TRACE;
3833     if (!IsRunning()) {
3834         MMI_HILOGE("Service is not running");
3835         return MMISERVICE_NOT_RUNNING;
3836     }
3837     if (!PER_HELPER->VerifySystemApp()) {
3838         MMI_HILOGE("Verify system APP failed");
3839         return ERROR_NOT_SYSAPI;
3840     }
3841 #if defined OHOS_BUILD_ENABLE_POINTER
3842     int32_t ret = delegateTasks_.PostSyncTask(
3843         [rotateSwitch] {
3844             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadRotateSwitch(rotateSwitch);
3845         }
3846         );
3847     if (ret != RET_OK) {
3848         MMI_HILOGE("Set touchpad rotate switch failed, ret:%{public}d", ret);
3849         return ret;
3850     }
3851 #endif // OHOS_BUILD_ENABLE_POINTER
3852     return RET_OK;
3853 }
3854 
GetTouchpadRotateSwitch(bool & rotateSwitch)3855 ErrCode MMIService::GetTouchpadRotateSwitch(bool &rotateSwitch)
3856 {
3857     CALL_INFO_TRACE;
3858     if (!IsRunning()) {
3859         MMI_HILOGE("Service is not running");
3860         return MMISERVICE_NOT_RUNNING;
3861     }
3862     if (!PER_HELPER->VerifySystemApp()) {
3863         MMI_HILOGE("Verify system APP failed");
3864         return ERROR_NOT_SYSAPI;
3865     }
3866     rotateSwitch = true;
3867 #ifdef OHOS_BUILD_ENABLE_POINTER
3868     int32_t ret = delegateTasks_.PostSyncTask(
3869         [this, &rotateSwitch] {
3870             return this->ReadTouchpadRotateSwitch(rotateSwitch);
3871         }
3872         );
3873     if (ret != RET_OK) {
3874         MMI_HILOGE("Get touchpad rotate switch failed, ret:%{public}d", ret);
3875         return ret;
3876     }
3877 #endif // OHOS_BUILD_ENABLE_POINTER
3878     return RET_OK;
3879 }
3880 
SetTouchpadDoubleTapAndDragState(bool switchFlag)3881 ErrCode MMIService::SetTouchpadDoubleTapAndDragState(bool switchFlag)
3882 {
3883     CALL_INFO_TRACE;
3884     if (!IsRunning()) {
3885         MMI_HILOGE("Service is not running");
3886         return MMISERVICE_NOT_RUNNING;
3887     }
3888     if (!PER_HELPER->VerifySystemApp()) {
3889         MMI_HILOGE("Verify system APP failed");
3890         return ERROR_NOT_SYSAPI;
3891     }
3892 #ifdef OHOS_BUILD_ENABLE_POINTER
3893     int32_t ret = delegateTasks_.PostSyncTask(
3894         [switchFlag] {
3895             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadDoubleTapAndDragState(
3896                 switchFlag);
3897         }
3898         );
3899     if (ret != RET_OK) {
3900         MMI_HILOGE("Failed to SetTouchpadDoubleTapAndDragState status, ret:%{public}d", ret);
3901         return ret;
3902     }
3903 #endif // OHOS_BUILD_ENABLE_POINTER
3904     return RET_OK;
3905 }
3906 
GetTouchpadDoubleTapAndDragState(bool & switchFlag)3907 ErrCode MMIService::GetTouchpadDoubleTapAndDragState(bool &switchFlag)
3908 {
3909     CALL_INFO_TRACE;
3910     if (!IsRunning()) {
3911         MMI_HILOGE("Service is not running");
3912         return MMISERVICE_NOT_RUNNING;
3913     }
3914     if (!PER_HELPER->VerifySystemApp()) {
3915         MMI_HILOGE("Verify system APP failed");
3916         return ERROR_NOT_SYSAPI;
3917     }
3918     switchFlag = true;
3919 #ifdef OHOS_BUILD_ENABLE_POINTER
3920     int32_t ret = delegateTasks_.PostSyncTask(
3921         [this, &switchFlag] {
3922             return this->ReadTouchpadDoubleTapAndDragState(switchFlag);
3923         }
3924         );
3925     if (ret != RET_OK) {
3926         MMI_HILOGE("Failed to GetTouchpadDoubleTapAndDragState status, ret:%{public}d", ret);
3927         return ret;
3928     }
3929 #endif // OHOS_BUILD_ENABLE_POINTER
3930     return RET_OK;
3931 }
3932 
SetShieldStatus(int32_t shieldMode,bool isShield)3933 ErrCode MMIService::SetShieldStatus(int32_t shieldMode, bool isShield)
3934 {
3935     CALL_INFO_TRACE;
3936     if (!PER_HELPER->VerifySystemApp()) {
3937         MMI_HILOGE("Verify system APP failed");
3938         return ERROR_NOT_SYSAPI;
3939     }
3940     if (!PER_HELPER->CheckDispatchControl()) {
3941         MMI_HILOGE("Input dispatch control permission check failed");
3942         return ERROR_NO_PERMISSION;
3943     }
3944     if (!IsRunning()) {
3945         MMI_HILOGE("Service is not running");
3946         return MMISERVICE_NOT_RUNNING;
3947     }
3948 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
3949     int32_t ret = delegateTasks_.PostSyncTask(
3950         [this, shieldMode, isShield] {
3951             return sMsgHandler_.SetShieldStatus(shieldMode, isShield);
3952         }
3953         );
3954     if (ret != RET_OK) {
3955         MMI_HILOGE("Set shield event interception state failed, return:%{public}d", ret);
3956         return ret;
3957     }
3958 #endif // OHOS_BUILD_ENABLE_KEYBOARD
3959     return RET_OK;
3960 }
3961 
GetShieldStatus(int32_t shieldMode,bool & isShield)3962 ErrCode MMIService::GetShieldStatus(int32_t shieldMode, bool &isShield)
3963 {
3964     CALL_INFO_TRACE;
3965     if (!PER_HELPER->VerifySystemApp()) {
3966         MMI_HILOGE("Verify system APP failed");
3967         return ERROR_NOT_SYSAPI;
3968     }
3969     if (!PER_HELPER->CheckDispatchControl()) {
3970         MMI_HILOGE("Input dispatch control permission check failed");
3971         return ERROR_NO_PERMISSION;
3972     }
3973     if (!IsRunning()) {
3974         MMI_HILOGE("Service is not running");
3975         return MMISERVICE_NOT_RUNNING;
3976     }
3977     isShield = false;
3978 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
3979     int32_t ret = delegateTasks_.PostSyncTask(
3980         [this, shieldMode, &isShield] {
3981             return sMsgHandler_.GetShieldStatus(shieldMode, isShield);
3982         }
3983         );
3984     if (ret != RET_OK) {
3985         MMI_HILOGE("Failed to set shield event interception status, ret:%{public}d", ret);
3986         return ret;
3987     }
3988 #endif // OHOS_BUILD_ENABLE_KEYBOARD
3989     return RET_OK;
3990 }
3991 
GetKeyState(std::vector<int32_t> & pressedKeys,std::unordered_map<int32_t,int32_t> & specialKeysState)3992 ErrCode MMIService::GetKeyState(std::vector<int32_t>& pressedKeys,
3993     std::unordered_map<int32_t, int32_t>& specialKeysState)
3994 {
3995     CALL_INFO_TRACE;
3996 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
3997     int32_t ret = delegateTasks_.PostSyncTask(
3998         [this, &pressedKeys, &specialKeysState] {
3999             return this->OnGetKeyState(pressedKeys, specialKeysState);
4000         }
4001         );
4002     if (ret != RET_OK) {
4003         MMI_HILOGE("Get pressed keys failed, return:%{public}d", ret);
4004         return ret;
4005     }
4006 #endif // OHOS_BUILD_ENABLE_KEYBOARD
4007     return RET_OK;
4008 }
4009 
Authorize(bool isAuthorize)4010 ErrCode MMIService::Authorize(bool isAuthorize)
4011 {
4012     CALL_DEBUG_ENTER;
4013     if (!PER_HELPER->VerifySystemApp()) {
4014         MMI_HILOGE("Verify system APP failed");
4015         return ERROR_NOT_SYSAPI;
4016     }
4017     if (!PER_HELPER->CheckAuthorize()) {
4018         MMI_HILOGE("Input authorize permission check failed");
4019         return ERROR_NO_PERMISSION;
4020     }
4021     int32_t ret = delegateTasks_.PostSyncTask(
4022         [this, isAuthorize] {
4023             return this->OnAuthorize(isAuthorize);
4024         }
4025         );
4026     if (ret != RET_OK) {
4027         MMI_HILOGE("OnAuthorize failed, ret:%{public}d", ret);
4028         return ret;
4029     }
4030     return RET_OK;
4031 }
4032 
OnAuthorize(bool isAuthorize)4033 int32_t MMIService::OnAuthorize(bool isAuthorize)
4034 {
4035     return sMsgHandler_.OnAuthorize(isAuthorize);
4036 }
4037 
CancelInjection()4038 ErrCode MMIService::CancelInjection()
4039 {
4040     CALL_DEBUG_ENTER;
4041     int32_t callPid = GetCallingPid();
4042     int32_t ret = delegateTasks_.PostSyncTask(
4043         [this, callPid] {
4044             return this->OnCancelInjection(callPid);
4045         }
4046         );
4047     if (ret != RET_OK) {
4048         MMI_HILOGE("OnCancelInjection failed, ret:%{public}d", ret);
4049         return ret;
4050     }
4051     return RET_OK;
4052 }
4053 
OnCancelInjection(int32_t callPid)4054 int32_t MMIService::OnCancelInjection(int32_t callPid)
4055 {
4056     return sMsgHandler_.OnCancelInjection(callPid);
4057 }
4058 
HasIrEmitter(bool & hasIrEmitter)4059 ErrCode MMIService::HasIrEmitter(bool &hasIrEmitter)
4060 {
4061     CALL_DEBUG_ENTER;
4062     if (!PER_HELPER->VerifySystemApp()) {
4063         MMI_HILOGE("Verify system APP failed");
4064         return ERROR_NOT_SYSAPI;
4065     }
4066     hasIrEmitter = false;
4067     int32_t ret = delegateTasks_.PostSyncTask(
4068         [this, &hasIrEmitter] {
4069             return this->OnHasIrEmitter(hasIrEmitter);
4070         }
4071         );
4072     if (ret != RET_OK) {
4073         MMI_HILOGE("OnHasIrEmitter failed, ret:%{public}d", ret);
4074         return ret;
4075     }
4076     return RET_OK;
4077 }
4078 
RequestInjection(int32_t & status,int32_t & reqId)4079 ErrCode MMIService::RequestInjection(int32_t &status, int32_t &reqId)
4080 {
4081     int32_t pid = GetCallingPid();
4082     int32_t ret = delegateTasks_.PostSyncTask(
4083         [this, pid, &status, &reqId] {
4084             return sMsgHandler_.RequestInjection(pid, status, reqId);
4085         }
4086         );
4087     if (ret != RET_OK) {
4088         MMI_HILOGE("RequestInjection failed, ret:%{public}d", ret);
4089         return ret;
4090     }
4091     return RET_OK;
4092 }
4093 
QueryAuthorizedStatus(int32_t & status)4094 ErrCode MMIService::QueryAuthorizedStatus(int32_t &status)
4095 {
4096     int32_t pid = GetCallingPid();
4097     int32_t ret = delegateTasks_.PostSyncTask(
4098         [this, pid, &status] {
4099             return sMsgHandler_.QueryAuthorizedStatus(pid, status);
4100         }
4101         );
4102     if (ret != RET_OK) {
4103         MMI_HILOGE("QueryAuthorizedStatus failed, ret:%{public}d", ret);
4104         return ret;
4105     }
4106     return RET_OK;
4107 }
4108 
GetInfraredFrequencies(std::vector<InfraredFrequency> & frequencies)4109 ErrCode MMIService::GetInfraredFrequencies(std::vector<InfraredFrequency>& frequencies)
4110 {
4111     CALL_DEBUG_ENTER;
4112     if (!PER_HELPER->CheckInfraredEmmit()) {
4113         MMI_HILOGE("Infrared permission check failed");
4114         return ERROR_NO_PERMISSION;
4115     }
4116 #ifndef OHOS_BUILD_ENABLE_WATCH
4117     MMI_HILOGI("Start get infrared frequency");
4118     std::vector<InfraredFrequencyInfo> infos;
4119     if (!InfraredEmitterController::GetInstance()->GetFrequencies(infos)) {
4120         MMI_HILOGE("Failed to get frequencies");
4121         return RET_ERR;
4122     }
4123     for (auto &item : infos) {
4124         InfraredFrequency info;
4125         info.min_ = item.min_;
4126         info.max_ = item.max_;
4127         frequencies.push_back(info);
4128     }
4129     std::string context = "";
4130     int32_t size = static_cast<int32_t>(frequencies.size());
4131     for (int32_t i = 0; i < size; i++) {
4132         context = context + "frequencies[" + std::to_string(i) + "]. max=" + std::to_string(frequencies[i].max_) +
4133         ",min=" + std::to_string(frequencies[i].min_) + ";";
4134     }
4135     MMI_HILOGD("Data from hdf context:%{public}s", context.c_str());
4136 #endif // OHOS_BUILD_ENABLE_WATCH
4137     return RET_OK;
4138 }
4139 
TransmitInfrared(int64_t number,const std::vector<int64_t> & pattern)4140 ErrCode MMIService::TransmitInfrared(int64_t number, const std::vector<int64_t>& pattern)
4141 {
4142     CALL_DEBUG_ENTER;
4143     if (!PER_HELPER->CheckInfraredEmmit()) {
4144         MMI_HILOGE("StubTransmitInfrared permission check failed. returnCode:%{public}d", ERROR_NO_PERMISSION);
4145         return ERROR_NO_PERMISSION;
4146     }
4147 #ifndef OHOS_BUILD_ENABLE_WATCH
4148     std::string context = "infraredFrequency:" + std::to_string(number) + ";";
4149     int32_t size = static_cast<int32_t>(pattern.size());
4150     for (int32_t i = 0; i < size; i++) {
4151         context = context + "index:" + std::to_string(i) + ": pattern:" + std::to_string(pattern[i]) + ";";
4152     }
4153     MMI_HILOGI("TransmitInfrared para context:%{public}s", context.c_str());
4154     if (!InfraredEmitterController::GetInstance()->Transmit(number, pattern)) {
4155         MMI_HILOGE("Failed to transmit");
4156         return RET_ERR;
4157     }
4158 #endif // OHOS_BUILD_ENABLE_WATCH
4159     return RET_OK;
4160 }
4161 
4162 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
CreateVKeyboardDevice(sptr<IRemoteObject> & vkeyboardDevice)4163 ErrCode MMIService::CreateVKeyboardDevice(sptr<IRemoteObject> &vkeyboardDevice)
4164 {
4165     CALL_INFO_TRACE;
4166     if (!PER_HELPER->VerifySystemApp()) {
4167         MMI_HILOGE("StubCreateVKeyboardDevice Verify system APP failed");
4168         return ERROR_NOT_SYSAPI;
4169     }
4170     vkeyboardDevice = nullptr;
4171     isFoldPC_ = PRODUCT_TYPE == DEVICE_TYPE_FOLD_PC;
4172     if (!isFoldPC_) {
4173         MMI_HILOGE("Failed to create vkeyboard device, feature not support");
4174         return RET_ERR;
4175     }
4176     int32_t ret = RET_OK;
4177     // init keyboard handler
4178     if (g_VKeyboardHandle == nullptr) {
4179         InitVKeyboardFuncHandler();
4180     }
4181     if (g_VKeyboardHandle == nullptr) {
4182         MMI_HILOGE("VKeyboard handler is nullptr");
4183         return RET_ERR;
4184     } else {
4185         ret = delegateTasks_.PostSyncTask(
4186             [this, &vkeyboardDevice] {
4187                 return this->OnCreateVKeyboardDevice(vkeyboardDevice);
4188             }
4189             );
4190         if (ret != RET_OK) {
4191             MMI_HILOGE("Failed to create vkeyboard device, ret:%{public}d", ret);
4192         }
4193     }
4194     return ret;
4195 }
4196 
OnCreateVKeyboardDevice(sptr<IRemoteObject> & vkeyboardDevice)4197 int32_t MMIService::OnCreateVKeyboardDevice(sptr<IRemoteObject> &vkeyboardDevice)
4198 {
4199     if (g_VKeyboardHandle == nullptr) {
4200         MMI_HILOGE("VKeyboard handler is nullptr");
4201         return RET_ERR;
4202     }
4203     vkeyboard_createVKeyboardDevice_ = (VKEYBOARD_CREATEVKEYBOARDDEVICE_TYPE)dlsym(
4204         g_VKeyboardHandle, "CreateVKeyboardDevice");
4205     IRemoteObject* vkbDevice = nullptr;
4206     int32_t ret = vkeyboard_createVKeyboardDevice_(vkbDevice);
4207     if (ret != RET_OK) {
4208         MMI_HILOGE("Create vkeyboard device failed");
4209         return ret;
4210     }
4211     if (vkbDevice == nullptr) {
4212         MMI_HILOGE("VKeyboard device pointer is nullptr");
4213         return RET_ERR;
4214     }
4215     vkeyboardDevice = sptr(vkbDevice);
4216 
4217     vkeyboard_onFuncKeyEvent_ = (VKEYBOARD_ONFUNCKEYEVENT_TYPE)dlsym(
4218         g_VKeyboardHandle, "OnFuncKeyEvent");
4219 
4220     auto keyEvent = KeyEventHdr->GetKeyEvent();
4221     CHKPR(keyEvent, ERROR_NULL_POINTER);
4222     if (vkeyboard_onFuncKeyEvent_ != nullptr) {
4223         vkeyboard_onFuncKeyEvent_(keyEvent);
4224     }
4225     return RET_OK;
4226 }
4227 
InitVKeyboardFuncHandler()4228 void MMIService::InitVKeyboardFuncHandler()
4229 {
4230     if (isFoldPC_) {
4231         // Initialize vkeyboard handler
4232         g_VKeyboardHandle = dlopen(VKEYBOARD_PATH.c_str(), RTLD_NOW);
4233         if (g_VKeyboardHandle != nullptr) {
4234             handleTouchPoint_ = (HANDLE_TOUCHPOINT_TYPE)dlsym(g_VKeyboardHandle, "HandleTouchPoint");
4235             vkeyboard_hardwareKeyEventDetected_ = (VKEYBOARD_HARDWAREKEYEVENTDETECTED_TYPE)dlsym(
4236                 g_VKeyboardHandle, "HardwareKeyEventDetected");
4237             vkeyboard_getKeyboardActivationState_ = (VKEYBOARD_GETKEYBOARDACTIVATIONSTATE_TYPE)dlsym(
4238                 g_VKeyboardHandle, "GetKeyboardActivationState");
4239             gaussiankeyboard_isFloatingKeyboard_ = (GAUSSIANKEYBOARD_ISFLOATINGKEYBOARD_TYPE)dlsym(
4240                 g_VKeyboardHandle, "IsFloatingKeyboard");
4241             vkeyboard_isShown_ = (VKEYBOARD_ISSHOWN)dlsym(g_VKeyboardHandle, "IsVKeyboardShown");
4242             getLibinputEventForVKeyboard_ = (GET_LIBINPUT_EVENT_FOR_VKEYBOARD_TYPE)dlsym(
4243                 g_VKeyboardHandle, "GetLibinputEventForVKeyboard");
4244             getLibinputEventForVTrackpad_ = (GET_LIBINPUT_EVENT_FOR_VTRACKPAD_TYPE)dlsym(
4245                 g_VKeyboardHandle, "GetLibinputEventForVTrackpad");
4246             libinputAdapter_.InitVKeyboard(handleTouchPoint_,
4247                 vkeyboard_hardwareKeyEventDetected_,
4248                 vkeyboard_getKeyboardActivationState_,
4249                 gaussiankeyboard_isFloatingKeyboard_,
4250                 vkeyboard_isShown_,
4251                 getLibinputEventForVKeyboard_,
4252                 getLibinputEventForVTrackpad_);
4253         }
4254     }
4255 }
4256 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
4257 
OnHasIrEmitter(bool & hasIrEmitter)4258 int32_t MMIService::OnHasIrEmitter(bool &hasIrEmitter)
4259 {
4260     hasIrEmitter = false;
4261     return RET_OK;
4262 }
4263 
SetPixelMapData(int32_t infoId,const CursorPixelMap & curPixelMap)4264 ErrCode MMIService::SetPixelMapData(int32_t infoId, const CursorPixelMap& curPixelMap)
4265 {
4266     CALL_DEBUG_ENTER;
4267     if (!PER_HELPER->VerifySystemApp()) {
4268         MMI_HILOGE("Verify system APP failed");
4269         return ERROR_NOT_SYSAPI;
4270     }
4271     if (!IsRunning()) {
4272         MMI_HILOGE("Service is not running");
4273         return MMISERVICE_NOT_RUNNING;
4274     }
4275     if (infoId <= 0) {
4276         MMI_HILOGE("Invalid infoId:%{public}d", infoId);
4277         return RET_ERR;
4278     }
4279     CHKPR(curPixelMap.pixelMap, ERROR_NULL_POINTER);
4280     void* pixelMap = curPixelMap.pixelMap;
4281     int32_t ret = delegateTasks_.PostSyncTask(
4282         [this, infoId, pixelMap] {
4283             return sMsgHandler_.SetPixelMapData(infoId, pixelMap);
4284         }
4285         );
4286     if (ret != RET_OK) {
4287         MMI_HILOGE("Failed to set pixelmap, ret:%{public}d", ret);
4288         return ret;
4289     }
4290     return RET_OK;
4291 }
4292 
InitPreferences()4293 void MMIService::InitPreferences()
4294 {
4295     PREFERENCES_MGR->InitPreferences();
4296 #ifdef OHOS_BUILD_ENABLE_MOVE_EVENT_FILTERS
4297     int32_t ret = SetMoveEventFilters(PREFERENCES_MGR->GetBoolValue("moveEventFilterFlag", false));
4298     if (ret != RET_OK) {
4299         MMI_HILOGE("Failed to read moveEventFilterFlag, ret:%{public}d", ret);
4300     }
4301 #endif // OHOS_BUILD_ENABLE_MOVE_EVENT_FILTERS
4302 }
4303 
SetMoveEventFilters(bool flag)4304 ErrCode MMIService::SetMoveEventFilters(bool flag)
4305 {
4306     CALL_DEBUG_ENTER;
4307     if (!PER_HELPER->VerifySystemApp()) {
4308         MMI_HILOGE("StubSetMoveEventFilters Verify system APP failed");
4309         return ERROR_NOT_SYSAPI;
4310     }
4311     if (!IsRunning()) {
4312         MMI_HILOGE("Service is not running");
4313         return MMISERVICE_NOT_RUNNING;
4314     }
4315 #ifdef OHOS_BUILD_ENABLE_MOVE_EVENT_FILTERS
4316     int32_t ret = delegateTasks_.PostSyncTask(
4317         std::bind(&InputEventHandler::SetMoveEventFilters, InputHandler, flag));
4318     if (ret != RET_OK) {
4319         MMI_HILOGE("Failed to set move event filter flag, ret:%{public}d", ret);
4320         return ret;
4321     }
4322 #endif // OHOS_BUILD_ENABLE_MOVE_EVENT_FILTERS
4323     return RET_OK;
4324 }
4325 
SetCurrentUser(int32_t userId)4326 ErrCode MMIService::SetCurrentUser(int32_t userId)
4327 {
4328     CALL_INFO_TRACE;
4329     if (!PER_HELPER->VerifySystemApp()) {
4330         MMI_HILOGE("StubSetCurrentUser Verify system APP failed");
4331         return ERROR_NOT_SYSAPI;
4332     }
4333     int32_t callingUid = GetCallingUid();
4334     if (callingUid < UID_TRANSFORM_DIVISOR) {
4335         MMI_HILOGE("CallingUid is not within the range:%{public}d", callingUid);
4336         return RET_ERR;
4337     }
4338     if (callingUid / UID_TRANSFORM_DIVISOR != userId) {
4339         MMI_HILOGE("Invalid CallingUid:%{public}d", callingUid);
4340         return RET_ERR;
4341     }
4342     int32_t ret = delegateTasks_.PostSyncTask(
4343         [userId] {
4344             return ::OHOS::MMI::IInputWindowsManager::GetInstance()->SetCurrentUser(userId);
4345         }
4346         );
4347     if (ret != RET_OK) {
4348         MMI_HILOGE("Failed to set current user, ret:%{public}d", ret);
4349         return ret;
4350     }
4351     auto eventKeyCommandHandler = InputHandler->GetKeyCommandHandler();
4352     CHKPR(eventKeyCommandHandler, RET_ERR);
4353     ret = delegateTasks_.PostSyncTask(
4354         [userId, eventKeyCommandHandler] {
4355             return eventKeyCommandHandler->RegisterKnuckleSwitchByUserId(userId);
4356         }
4357         );
4358     if (ret != RET_OK) {
4359         MMI_HILOGE("Failed to set current user, ret:%{public}d", ret);
4360         return ret;
4361     }
4362     return RET_OK;
4363 }
4364 
SetTouchpadThreeFingersTapSwitch(bool switchFlag)4365 ErrCode MMIService::SetTouchpadThreeFingersTapSwitch(bool switchFlag)
4366 {
4367     CALL_INFO_TRACE;
4368     if (!PER_HELPER->VerifySystemApp()) {
4369         MMI_HILOGE("StubSetTouchpadThreeFingersTapSwitch Verify system APP failed");
4370         return ERROR_NOT_SYSAPI;
4371     }
4372 #ifdef OHOS_BUILD_ENABLE_POINTER
4373     int32_t ret = delegateTasks_.PostSyncTask(
4374         [switchFlag] {
4375             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadThreeFingersTapSwitch(
4376                 switchFlag);
4377         }
4378         );
4379     if (ret != RET_OK) {
4380         MMI_HILOGE("Failed to SetTouchpadThreeFingersTapSwitch status, ret:%{public}d", ret);
4381         return ret;
4382     }
4383 #endif // OHOS_BUILD_ENABLE_POINTER
4384     return RET_OK;
4385 }
4386 
GetTouchpadThreeFingersTapSwitch(bool & switchFlag)4387 ErrCode MMIService::GetTouchpadThreeFingersTapSwitch(bool &switchFlag)
4388 {
4389     CALL_INFO_TRACE;
4390     if (!PER_HELPER->VerifySystemApp()) {
4391         MMI_HILOGE("StubGetTouchpadThreeFingersTapSwitch Verify system APP failed");
4392         return ERROR_NOT_SYSAPI;
4393     }
4394     switchFlag = true;
4395 #ifdef OHOS_BUILD_ENABLE_POINTER
4396     int32_t ret = delegateTasks_.PostSyncTask(
4397         [&switchFlag] {
4398             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->GetTouchpadThreeFingersTapSwitch(
4399                 switchFlag);
4400         }
4401         );
4402     if (ret != RET_OK) {
4403         MMI_HILOGE("Failed to GetTouchpadThreeFingersTapSwitch status, ret:%{public}d", ret);
4404         return ret;
4405     }
4406 #endif // OHOS_BUILD_ENABLE_POINTER
4407     return RET_OK;
4408 }
4409 
AddVirtualInputDevice(const InputDevice & device,int32_t & deviceId)4410 ErrCode MMIService::AddVirtualInputDevice(const InputDevice& device, int32_t& deviceId)
4411 {
4412     CALL_DEBUG_ENTER;
4413     if (!PER_HELPER->VerifySystemApp()) {
4414         MMI_HILOGE("Verify system APP failed");
4415         return ERROR_NOT_SYSAPI;
4416     }
4417     deviceId = -1;
4418     auto devicePtr = std::make_shared<InputDevice>(device);
4419     CHKPR(devicePtr, ERROR_NULL_POINTER);
4420     int32_t ret = delegateTasks_.PostSyncTask(
4421         [devicePtr, &deviceId] {
4422             return ::OHOS::MMI::InputDeviceManager::GetInstance()->AddVirtualInputDevice(devicePtr, deviceId);
4423         }
4424         );
4425     if (ret != RET_OK) {
4426         MMI_HILOGE("AddVirtualInputDevice failed:%{public}d", ret);
4427     }
4428     return ret;
4429 }
4430 
RemoveVirtualInputDevice(int32_t deviceId)4431 ErrCode MMIService::RemoveVirtualInputDevice(int32_t deviceId)
4432 {
4433     CALL_DEBUG_ENTER;
4434     if (!PER_HELPER->VerifySystemApp()) {
4435         MMI_HILOGE("Verify system APP failed");
4436         return ERROR_NOT_SYSAPI;
4437     }
4438     if (deviceId < 0) {
4439         MMI_HILOGE("invalid deviceId :%{public}d", deviceId);
4440         return RET_ERR;
4441     }
4442     int32_t ret = delegateTasks_.PostSyncTask(
4443         [deviceId] {
4444             return ::OHOS::MMI::InputDeviceManager::GetInstance()->RemoveVirtualInputDevice(deviceId);
4445         }
4446         );
4447     if (ret != RET_OK) {
4448         MMI_HILOGE("RemoveVirtualInputDevice failed:%{public}d", ret);
4449     }
4450     return ret;
4451 }
4452 
EnableHardwareCursorStats(bool enable)4453 ErrCode MMIService::EnableHardwareCursorStats(bool enable)
4454 {
4455     CALL_DEBUG_ENTER;
4456     if (!PER_HELPER->VerifySystemApp()) {
4457         MMI_HILOGE("Verify system APP failed");
4458         return ERROR_NOT_SYSAPI;
4459     }
4460 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
4461     int32_t pid = GetCallingPid();
4462     int32_t ret = delegateTasks_.PostSyncTask(
4463         [pid, enable] {
4464             return CursorDrawingComponent::GetInstance().EnableHardwareCursorStats(pid, enable);
4465         }
4466         );
4467     if (ret != RET_OK) {
4468         MMI_HILOGE("Enable hardware cursor stats failed, ret:%{public}d", ret);
4469         return ret;
4470     }
4471 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
4472     return RET_OK;
4473 }
4474 
GetHardwareCursorStats(uint32_t & frameCount,uint32_t & vsyncCount)4475 ErrCode MMIService::GetHardwareCursorStats(uint32_t &frameCount, uint32_t &vsyncCount)
4476 {
4477     CALL_DEBUG_ENTER;
4478     if (!PER_HELPER->VerifySystemApp()) {
4479         MMI_HILOGE("Verify system APP failed");
4480         return ERROR_NOT_SYSAPI;
4481     }
4482     frameCount = 0;
4483     vsyncCount = 0;
4484 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
4485     int32_t pid = GetCallingPid();
4486     int32_t ret = delegateTasks_.PostSyncTask(
4487         [pid, &frameCount, &vsyncCount] {
4488             return CursorDrawingComponent::GetInstance().GetHardwareCursorStats(pid, frameCount, vsyncCount);
4489         }
4490         );
4491     if (ret != RET_OK) {
4492         MMI_HILOGE("Get hardware cursor stats failed, ret:%{public}d", ret);
4493         return ret;
4494     }
4495 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
4496     return RET_OK;
4497 }
4498 
4499 #ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
GetPointerSnapshot(CursorPixelMap & pixelMapPtr)4500 ErrCode MMIService::GetPointerSnapshot(CursorPixelMap& pixelMapPtr)
4501 {
4502     CALL_INFO_TRACE;
4503     if (!IsRunning()) {
4504         MMI_HILOGE("Service is not running");
4505         return MMISERVICE_NOT_RUNNING;
4506     }
4507     if (!PER_HELPER->VerifySystemApp()) {
4508         MMI_HILOGE("Verify system APP failed");
4509         return ERROR_NOT_SYSAPI;
4510     }
4511     std::shared_ptr<Media::PixelMap> pixelMap;
4512 #if defined OHOS_BUILD_ENABLE_POINTER
4513     MMI_HILOGI("Get pointer snapshot from process(%{public}d)", GetCallingPid());
4514     int32_t ret = delegateTasks_.PostSyncTask(std::bind(
4515         std::bind(&IPointerDrawingManager::GetPointerSnapshot,
4516             IPointerDrawingManager::GetInstance(), &pixelMap)));
4517     if (ret != RET_OK) {
4518         MMI_HILOGE("Get the pointer snapshot failed, ret:%{public}d", ret);
4519         return ret;
4520     }
4521 #endif // OHOS_BUILD_ENABLE_POINTER
4522     CHKPR(pixelMap, ERR_INVALID_VALUE);
4523     pixelMapPtr.pixelMap = static_cast<void*>(&pixelMap);
4524     return RET_OK;
4525 }
4526 #endif // OHOS_BUILD_ENABLE_MAGICCURSOR
4527 
SetTouchpadScrollRows(int32_t rows)4528 ErrCode MMIService::SetTouchpadScrollRows(int32_t rows)
4529 {
4530     CALL_INFO_TRACE;
4531     if (!IsRunning()) {
4532         MMI_HILOGE("Service is not running");
4533         return MMISERVICE_NOT_RUNNING;
4534     }
4535     if (!PER_HELPER->VerifySystemApp()) {
4536         MMI_HILOGE("Verify system APP failed");
4537         return ERROR_NOT_SYSAPI;
4538     }
4539     int32_t newRows = std::clamp(rows, MIN_ROWS, MAX_ROWS);
4540 #ifdef OHOS_BUILD_ENABLE_POINTER
4541     int32_t ret = delegateTasks_.PostSyncTask(
4542         [newRows] {
4543             return ::OHOS::DelayedSingleton<TouchEventNormalize>::GetInstance()->SetTouchpadScrollRows(newRows);
4544         }
4545         );
4546     if (ret != RET_OK) {
4547         MMI_HILOGE("Set the number of touchpad scrolling rows failed, return %{public}d", ret);
4548         return ret;
4549     }
4550 #endif // OHOS_BUILD_ENABLE_POINTER
4551     return RET_OK;
4552 }
4553 
4554 #ifdef OHOS_BUILD_ENABLE_POINTER
ReadTouchpadScrollRows(int32_t & rows)4555 int32_t MMIService::ReadTouchpadScrollRows(int32_t &rows)
4556 {
4557     rows = TOUCH_EVENT_HDR->GetTouchpadScrollRows();
4558     return RET_OK;
4559 }
4560 #endif // OHOS_BUILD_ENABLE_POINTER
4561 
GetTouchpadScrollRows(int32_t & rows)4562 ErrCode MMIService::GetTouchpadScrollRows(int32_t &rows)
4563 {
4564     CALL_INFO_TRACE;
4565     if (!IsRunning()) {
4566         MMI_HILOGE("Service is not running");
4567         return MMISERVICE_NOT_RUNNING;
4568     }
4569     if (!PER_HELPER->VerifySystemApp()) {
4570         MMI_HILOGE("Verify system APP failed");
4571         return ERROR_NOT_SYSAPI;
4572     }
4573     rows = TOUCHPAD_SCROLL_ROWS;
4574 #ifdef OHOS_BUILD_ENABLE_POINTER
4575     int32_t ret = delegateTasks_.PostSyncTask(
4576         [this, &rows] {
4577             return this->ReadTouchpadScrollRows(rows);
4578         }
4579         );
4580     if (ret != RET_OK) {
4581         MMI_HILOGE("Get the number of touchpad scrolling rows failed, return %{public}d, pid:%{public}d", ret,
4582             GetCallingPid());
4583         return ret;
4584     }
4585 #endif // OHOS_BUILD_ENABLE_POINTER
4586     if (rows < MIN_ROWS || rows > MAX_ROWS) {
4587         MMI_HILOGD("Invalid touchpad scroll rows:%{public}d", rows);
4588     }
4589     return RET_OK;
4590 }
4591 
4592 #ifdef OHOS_BUILD_ENABLE_ANCO
AncoAddChannel(const sptr<IAncoChannel> & channel)4593 ErrCode MMIService::AncoAddChannel(const sptr<IAncoChannel>& channel)
4594 {
4595     if (!PER_HELPER->VerifySystemApp()) {
4596         MMI_HILOGE("Verify system APP failed");
4597         return ERROR_NOT_SYSAPI;
4598     }
4599     sptr<IAncoChannel> ancoChannel = channel;
4600     int32_t ret = delegateTasks_.PostSyncTask([ancoChannel]() {
4601         return WIN_MGR->AncoAddChannel(ancoChannel);
4602     });
4603     if (ret != RET_OK) {
4604         MMI_HILOGE("AncoAddChannel fail, error:%{public}d", ret);
4605     }
4606     SyncKnuckleStatus();
4607     return ret;
4608 }
4609 
AncoRemoveChannel(const sptr<IAncoChannel> & channel)4610 ErrCode MMIService::AncoRemoveChannel(const sptr<IAncoChannel>& channel)
4611 {
4612     if (!PER_HELPER->VerifySystemApp()) {
4613         MMI_HILOGE("Verify system APP failed");
4614         return ERROR_NOT_SYSAPI;
4615     }
4616     sptr<IAncoChannel> ancoChannel = channel;
4617     int32_t ret = delegateTasks_.PostSyncTask([ancoChannel]() {
4618         return WIN_MGR->AncoRemoveChannel(ancoChannel);
4619     });
4620     if (ret != RET_OK) {
4621         MMI_HILOGE("AncoRemoveChannel fail, error:%{public}d", ret);
4622     }
4623     return ret;
4624 }
4625 #endif // OHOS_BUILD_ENABLE_ANCO
4626 
TransferBinderClientSrv(const sptr<IRemoteObject> & binderClientObject)4627 ErrCode MMIService::TransferBinderClientSrv(const sptr<IRemoteObject> &binderClientObject)
4628 {
4629     CALL_DEBUG_ENTER;
4630     int32_t pid = GetCallingPid();
4631     int32_t ret =
4632         delegateTasks_.PostSyncTask(
4633             [this, pid, binderClientObject] {
4634                 return sMsgHandler_.OnTransferBinderClientSrv(binderClientObject, pid);
4635             }
4636         );
4637     MMI_HILOGI("TransferBinderClientSrv result:%{public}d", ret);
4638     return ret;
4639 }
4640 
CalculateFuntionRunningTime(std::function<void ()> func,const std::string & flag)4641 void MMIService::CalculateFuntionRunningTime(std::function<void()> func, const std::string &flag)
4642 {
4643     std::function<void (void *)> printLog = std::bind(&MMIService::PrintLog, this, flag, THREAD_BLOCK_TIMER_SPAN_S,
4644         getpid(), gettid());
4645     int32_t id = HiviewDFX::XCollie::GetInstance().SetTimer(flag, THREAD_BLOCK_TIMER_SPAN_S, printLog, nullptr,
4646         HiviewDFX::XCOLLIE_FLAG_NOOP);
4647     func();
4648     HiviewDFX::XCollie::GetInstance().CancelTimer(id);
4649 }
4650 
PrintLog(const std::string & flag,int32_t duration,int32_t pid,int32_t tid)4651 void MMIService::PrintLog(const std::string &flag, int32_t duration, int32_t pid, int32_t tid)
4652 {
4653     std::string dfxThreadBlockMsg { "MMIBlockTask name:" };
4654     dfxThreadBlockMsg += flag;
4655     dfxThreadBlockMsg += ", duration time:";
4656     dfxThreadBlockMsg += std::to_string(duration);
4657     dfxThreadBlockMsg += ", pid:";
4658     dfxThreadBlockMsg += std::to_string(pid);
4659     dfxThreadBlockMsg += ", tid:";
4660     dfxThreadBlockMsg += std::to_string(tid);
4661     MMI_HILOGW("DfxThreadBlockMsg:%{public}s", dfxThreadBlockMsg.c_str());
4662     OHOS::HiviewDFX::DfxDumpCatcher dumpCatcher;
4663     dumpCatcher.DumpCatch(pid, tid, dfxThreadBlockMsg, MAX_FRAME_NUMS, false);
4664     MMI_HILOGW("BlockMsg:%{public}s", dfxThreadBlockMsg.c_str());
4665 }
4666 
SkipPointerLayer(bool isSkip)4667 ErrCode MMIService::SkipPointerLayer(bool isSkip)
4668 {
4669     CALL_INFO_TRACE;
4670     if (!PER_HELPER->VerifySystemApp()) {
4671         MMI_HILOGE("Verify system APP failed");
4672         return ERROR_NOT_SYSAPI;
4673     }
4674 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
4675     int32_t ret = delegateTasks_.PostSyncTask(
4676         [isSkip] {
4677             return CursorDrawingComponent::GetInstance().SkipPointerLayer(isSkip);
4678         }
4679         );
4680     if (ret != RET_OK) {
4681         MMI_HILOGE("Skip pointer layerfailed, return:%{public}d", ret);
4682         return ret;
4683     }
4684 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
4685     return RET_OK;
4686 }
4687 
OnSessionDelete(SessionPtr session)4688 void MMIService::OnSessionDelete(SessionPtr session)
4689 {
4690     CALL_DEBUG_ENTER;
4691     CHKPV(session);
4692     std::string programName = session->GetProgramName();
4693     std::lock_guard<std::mutex> guard(mutex_);
4694     auto it = clientInfos_.find(programName);
4695     if (it != clientInfos_.end()) {
4696         clientInfos_.erase(it);
4697         MMI_HILOGD("Clear the client info, programName:%{public}s", programName.c_str());
4698     }
4699 }
4700 
SetClientInfo(int32_t pid,uint64_t readThreadId)4701 ErrCode MMIService::SetClientInfo(int32_t pid, uint64_t readThreadId)
4702 {
4703     CALL_DEBUG_ENTER;
4704     if (!IsRunning()) {
4705         MMI_HILOGE("Service is not running");
4706         return MMISERVICE_NOT_RUNNING;
4707     }
4708     if (readThreadId < 0) {
4709         MMI_HILOGE("invalid readThreadId:%{public}" PRIu64, readThreadId);
4710         return RET_ERR;
4711     }
4712     auto sess = GetSessionByPid(pid);
4713     CHKPR(sess, ERROR_NULL_POINTER);
4714     std::string programName = sess->GetProgramName();
4715     std::lock_guard<std::mutex> guard(mutex_);
4716     if (clientInfos_.find(programName) != clientInfos_.end()) {
4717         clientInfos_[programName].pid = pid;
4718         clientInfos_[programName].readThreadId = readThreadId;
4719         return RET_OK;
4720     }
4721     ClientInfo clientInfo {
4722         .pid = pid,
4723         .readThreadId = readThreadId
4724     };
4725     clientInfos_[programName] = clientInfo;
4726     return RET_OK;
4727 }
4728 
InitPrintClientInfo()4729 void MMIService::InitPrintClientInfo()
4730 {
4731     CALL_DEBUG_ENTER;
4732     TimerMgr->AddLongTimer(PRINT_INTERVAL_TIME, -1, [this]() {
4733         ffrt::submit([this] {
4734             std::lock_guard<std::mutex> guard(mutex_);
4735             for (const auto &info : clientInfos_) {
4736                 if (static_cast<uint64_t>(info.second.pid) == info.second.readThreadId) {
4737                     MMI_HILOGD("The application main thread and event reading thread are combined, such as:"
4738                     "programName:%{public}s, pid:%{public}d, mainThreadId:%{public}d, readThreadId:%{public}" PRIu64,
4739                     info.first.c_str(), info.second.pid, info.second.pid, info.second.readThreadId);
4740                     return;
4741                 }
4742             }
4743             if (!clientInfos_.empty()) {
4744                 auto it = clientInfos_.begin();
4745                 MMI_HILOGI("The application main thread and event reading thread are separated, such as:"
4746                 "programName:%{public}s, pid:%{public}d, mainThreadId:%{public}d, readThreadId:%{public}" PRIu64,
4747                 it->first.c_str(), it->second.pid, it->second.pid, it->second.readThreadId);
4748             }
4749         });
4750     }, "MMIService-InitPrintClientInfo");
4751     std::function<void(SessionPtr)> callback = [this](SessionPtr sess) {
4752         return this->OnSessionDelete(sess);
4753     };
4754     AddSessionDeletedCallback(callback);
4755 }
4756 
GetIntervalSinceLastInput(int64_t & timeInterval)4757 ErrCode MMIService::GetIntervalSinceLastInput(int64_t &timeInterval)
4758 {
4759     CALL_INFO_TRACE;
4760     timeInterval = 0;
4761     int32_t ret = delegateTasks_.PostSyncTask(std::bind(&InputEventHandler::GetIntervalSinceLastInput,
4762         InputHandler, std::ref(timeInterval)));
4763     MMI_HILOGD("timeInterval:%{public}" PRId64, timeInterval);
4764     if (ret != RET_OK) {
4765         MMI_HILOGE("Failed to GetIntervalSinceLastInput, ret:%{public}d", ret);
4766     }
4767     return ret;
4768 }
4769 
GetAllSystemHotkeys(std::vector<KeyOption> & keyOptions)4770 ErrCode MMIService::GetAllSystemHotkeys(std::vector<KeyOption>& keyOptions)
4771 {
4772     CALL_DEBUG_ENTER;
4773     std::vector<std::unique_ptr<KeyOption>> options {};
4774     int32_t ret = delegateTasks_.PostSyncTask(
4775         [this, &options] {
4776             return this->OnGetAllSystemHotkey(options);
4777         }
4778         );
4779     if (ret != RET_OK) {
4780         MMI_HILOGD("Get all system hot key, ret:%{public}d", ret);
4781         return ret;
4782     }
4783     keyOptions.clear();
4784     for (const auto &item : options) {
4785         keyOptions.push_back(std::move(*item));
4786     }
4787     return RET_OK;
4788 }
4789 
OnGetAllSystemHotkey(std::vector<std::unique_ptr<KeyOption>> & keyOptions)4790 int32_t MMIService::OnGetAllSystemHotkey(std::vector<std::unique_ptr<KeyOption>> &keyOptions)
4791 {
4792     CALL_DEBUG_ENTER;
4793     #ifdef SHORTCUT_KEY_MANAGER_ENABLED
4794     return KEY_SHORTCUT_MGR->GetAllSystemHotkeys(keyOptions);
4795     #endif // SHORTCUT_KEY_MANAGER_ENABLED
4796     MMI_HILOGI("OnGetAllSystemHotkey function does not support");
4797     return ERROR_UNSUPPORT;
4798 }
4799 
4800 #if defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
SetupTouchGestureHandler()4801 void MMIService::SetupTouchGestureHandler()
4802 {
4803     touchGestureMgr_ = std::make_shared<TouchGestureManager>(delegateInterface_);
4804     WIN_MGR->AttachTouchGestureMgr(touchGestureMgr_);
4805 }
4806 #endif // defined(OHOS_BUILD_ENABLE_TOUCH) && defined(OHOS_BUILD_ENABLE_MONITOR)
4807 
SetInputDeviceEnable(int32_t deviceId,bool enable,int32_t index,int32_t pid,SessionPtr sess)4808 int32_t MMIService::SetInputDeviceEnable(int32_t deviceId, bool enable, int32_t index, int32_t pid, SessionPtr sess)
4809 {
4810     CALL_INFO_TRACE;
4811     CHKPR(sess, RET_ERR);
4812     int32_t ret = INPUT_DEV_MGR->SetInputDeviceEnabled(deviceId, enable, index, pid, sess);
4813     if (RET_OK != ret) {
4814         MMI_HILOGE("Set inputdevice enabled failed, return:%{public}d", ret);
4815         return ret;
4816     }
4817     return RET_OK;
4818 }
4819 
SetInputDeviceEnabled(int32_t deviceId,bool enable,int32_t index)4820 ErrCode MMIService::SetInputDeviceEnabled(int32_t deviceId, bool enable, int32_t index)
4821 {
4822     if (!IsRunning()) {
4823         MMI_HILOGE("Service is not running");
4824         return MMISERVICE_NOT_RUNNING;
4825     }
4826     if (!PER_HELPER->VerifySystemApp()) {
4827         MMI_HILOGE("Verify system APP failed");
4828         return ERROR_NOT_SYSAPI;
4829     }
4830     if (!PER_HELPER->CheckInputDeviceController()) {
4831         MMI_HILOGE("Controller permission check failed");
4832         return ERROR_NO_PERMISSION;
4833     }
4834     if (deviceId < 0) {
4835         MMI_HILOGE("invalid deviceId :%{public}d", deviceId);
4836         return RET_ERR;
4837     }
4838     CALL_INFO_TRACE;
4839     int32_t pid = GetCallingPid();
4840     auto sess = GetSessionByPid(pid);
4841     int32_t ret = delegateTasks_.PostAsyncTask(
4842         [this, deviceId, enable, index, pid, sess] {
4843             return this->SetInputDeviceEnable(deviceId, enable, index, pid, sess);
4844         }
4845         );
4846     if (ret != RET_OK) {
4847         MMI_HILOGE("Set inputdevice enable failed, return:%{public}d", ret);
4848         return ret;
4849     }
4850     return RET_OK;
4851 }
4852 
ShiftAppPointerEvent(const ShiftWindowParam & param,bool autoGenDown)4853 ErrCode MMIService::ShiftAppPointerEvent(const ShiftWindowParam &param, bool autoGenDown)
4854 {
4855     CALL_DEBUG_ENTER;
4856     if (!PER_HELPER->VerifySystemApp()) {
4857         MMI_HILOGE("Verify system APP failed");
4858         return ERROR_NOT_SYSAPI;
4859     }
4860     if (!IsRunning()) {
4861         MMI_HILOGE("Service is not running");
4862         return MMISERVICE_NOT_RUNNING;
4863     }
4864 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
4865     int32_t ret = delegateTasks_.PostSyncTask(
4866         [param, autoGenDown]() {
4867             return WIN_MGR->ShiftAppPointerEvent(param, autoGenDown);
4868         }
4869         );
4870     if (ret != RET_OK) {
4871         MMI_HILOGE("Shift AppPointerEvent failed, return:%{public}d", ret);
4872         return ret;
4873     }
4874 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
4875     return RET_OK;
4876 }
4877 
SetCustomCursor(int32_t windowId,const CustomCursorParcel & curParcel,const CursorOptionsParcel & cOptionParcel)4878 ErrCode MMIService::SetCustomCursor(int32_t windowId,
4879     const CustomCursorParcel& curParcel, const CursorOptionsParcel& cOptionParcel)
4880 {
4881     CALL_INFO_TRACE;
4882     if (!IsRunning()) {
4883         MMI_HILOGE("Service is not running");
4884         return MMISERVICE_NOT_RUNNING;
4885     }
4886     int32_t pid = GetCallingPid();
4887     int32_t ret = delegateTasks_.PostSyncTask(std::bind(
4888         [pid, windowId] {
4889             return WIN_MGR->CheckWindowIdPermissionByPid(windowId, pid);
4890         })
4891         );
4892     if (windowId > 0 && ret != RET_OK) {
4893         MMI_HILOGE("Set the custom cursor failed, ret:%{public}d", ret);
4894         return ERROR_WINDOW_ID_PERMISSION_DENIED;
4895     }
4896     CustomCursor cursor;
4897     cursor.pixelMap = curParcel.pixelMap;
4898     cursor.focusX = curParcel.focusX;
4899     cursor.focusY = curParcel.focusY;
4900     CursorOptions options;
4901     options.followSystem = cOptionParcel.followSystem;
4902 #if defined OHOS_BUILD_ENABLE_POINTER
4903     ret = delegateTasks_.PostSyncTask(std::bind(
4904         [pid, windowId, cursor, options] {
4905             if (!POINTER_DEV_MGR.isInit) {
4906                 return RET_ERR;
4907             }
4908             return CursorDrawingComponent::GetInstance().SetCustomCursor(pid, windowId, cursor, options);
4909         }
4910         ));
4911     if (ret != RET_OK) {
4912         MMI_HILOGE("Set the custom cursor failed, ret:%{public}d", ret);
4913         return ret;
4914     }
4915 #endif // OHOS_BUILD_ENABLE_POINTER
4916     return RET_OK;
4917 }
4918 
4919 #ifdef OHOS_BUILD_ENABLE_ANCO
CheckKnuckleEvent(float pointX,float pointY,bool & isKnuckleType)4920 ErrCode MMIService::CheckKnuckleEvent(float pointX, float pointY, bool &isKnuckleType)
4921 {
4922     CALL_INFO_TRACE;
4923     if (!PER_HELPER->VerifySystemApp()) {
4924         MMI_HILOGE("Verify system APP failed");
4925         return ERROR_NOT_SYSAPI;
4926     }
4927     isKnuckleType = false;
4928 #if defined(OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER)
4929     int tryTimes = RETRY_CHECK_TIMES;
4930     int32_t ret = RET_ERR;
4931     for (int count = 0; count < tryTimes; ++count) {
4932         ret = FINGERSENSE_WRAPPER->CheckKnuckleEvent(pointX, pointY, isKnuckleType);
4933         if (ret == RET_OK) {
4934             break;
4935         }
4936         std::this_thread::sleep_for(std::chrono::microseconds(CHECK_EEVENT_INTERVAL_TIME));
4937     }
4938     return ret;
4939 #endif // OHOS_BUILD_ENABLE_FINGERSENSE_WRAPPER
4940     return RET_OK;
4941 }
4942 
SyncKnuckleStatus()4943 int32_t MMIService::SyncKnuckleStatus()
4944 {
4945     CALL_DEBUG_ENTER;
4946     int ret = delegateTasks_.PostSyncTask([] {
4947         auto keyHandler = InputHandler->GetKeyCommandHandler();
4948         if (keyHandler == nullptr) {
4949             return RET_ERR;
4950         }
4951         bool isKnuckleEnable = !keyHandler->SkipKnuckleDetect();
4952         return WIN_MGR->SyncKnuckleStatus(isKnuckleEnable);
4953     });
4954     if (ret != RET_OK) {
4955         MMI_HILOGE("post sync knuckle status fail, ret:%{public}d", ret);
4956     }
4957     return ret;
4958 }
4959 #endif
4960 
SetMultiWindowScreenIdInner(uint64_t screenId,uint64_t displayNodeScreenId)4961 int32_t MMIService::SetMultiWindowScreenIdInner(uint64_t screenId, uint64_t displayNodeScreenId)
4962 {
4963 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
4964     TOUCH_DRAWING_MGR->SetMultiWindowScreenId(screenId, displayNodeScreenId);
4965 #endif // OHOS_BUILD_ENABLE_TOUCH_DRAWING
4966 #ifndef OHOS_BUILD_ENABLE_WATCH
4967     KnuckleDrawingComponent::GetInstance().SetMultiWindowScreenId(screenId, displayNodeScreenId);
4968 #endif // OHOS_BUILD_ENABLE_WATCH
4969     return RET_OK;
4970 }
4971 
SetMultiWindowScreenId(uint64_t screenId,uint64_t displayNodeScreenId)4972 ErrCode MMIService::SetMultiWindowScreenId(uint64_t screenId, uint64_t displayNodeScreenId)
4973 {
4974     if (!PER_HELPER->VerifySystemApp()) {
4975         MMI_HILOGE("Verify system APP failed");
4976         return ERROR_NOT_SYSAPI;
4977     }
4978     int32_t ret = delegateTasks_.PostSyncTask(
4979         [this, &screenId, &displayNodeScreenId] {
4980             return this->SetMultiWindowScreenIdInner(screenId, displayNodeScreenId);
4981         }
4982     );
4983     if (ret != RET_OK) {
4984         MMI_HILOGE("SetMultiWindowScreenId failed, return:%{public}d", ret);
4985         return ret;
4986     }
4987     return RET_OK;
4988 }
4989 
SetKnuckleSwitch(bool knuckleSwitch)4990 ErrCode MMIService::SetKnuckleSwitch(bool knuckleSwitch)
4991 {
4992     CALL_INFO_TRACE;
4993     int32_t callingUid = GetCallingUid();
4994     int32_t gameUid = 7011;
4995     if (callingUid != gameUid || !PER_HELPER->VerifySystemApp()) {
4996         MMI_HILOGE("Verify system APP failed");
4997         return ERROR_NOT_SYSAPI;
4998     }
4999     int32_t pid = GetCallingPid();
5000     auto sess = GetSessionByPid(pid);
5001     auto eventKeyCommandHandler = InputHandler->GetKeyCommandHandler();
5002     CHKPR(eventKeyCommandHandler, RET_ERR);
5003     int32_t ret = delegateTasks_.PostAsyncTask(
5004         [knuckleSwitch, eventKeyCommandHandler] {
5005             return eventKeyCommandHandler->SetKnuckleSwitch(knuckleSwitch);
5006         }
5007         );
5008     if (ret != RET_OK) {
5009         MMI_HILOGE("SetKnuckleSwitch failed, return:%{public}d", ret);
5010         return ret;
5011     }
5012     return RET_OK;
5013 }
5014 
LaunchAiScreenAbility()5015 ErrCode MMIService::LaunchAiScreenAbility()
5016 {
5017     int32_t pid = GetCallingPid();
5018     int ret = delegateTasks_.PostSyncTask(
5019         [pid] {
5020         auto keyHandler = InputHandler->GetKeyCommandHandler();
5021         if (keyHandler == nullptr) {
5022             return RET_ERR;
5023         }
5024         return keyHandler->LaunchAiScreenAbility(pid);
5025     });
5026     if (ret != RET_OK) {
5027         MMI_HILOGE("LaunchAiScreenAbility failed, return:%{public}d", ret);
5028     }
5029     return ret;
5030 }
5031 
GetMaxMultiTouchPointNum(int32_t & pointNum)5032 ErrCode MMIService::GetMaxMultiTouchPointNum(int32_t &pointNum)
5033 {
5034     pointNum = -1;
5035     int ret = delegateTasks_.PostSyncTask(
5036         [&pointNum] () {
5037             auto productDeviceType = PRODUCT_DEVICE_TYPE;
5038             MMI_HILOGI("ProductDeviceType:%{public}s", productDeviceType.c_str());
5039             pointNum = MAX_MULTI_TOUCH_POINT_NUM;
5040             return RET_OK;
5041         }
5042     );
5043     if (ret != RET_OK) {
5044         MMI_HILOGE("GetMaxMultiTouchPointNum failed, return:%{public}d", ret);
5045     }
5046     return ret;
5047 }
5048 
DealConsumers(std::vector<std::string> & filterNames,const DeviceConsumer & consumer)5049 void MMIService::DealConsumers(std::vector<std::string>& filterNames, const DeviceConsumer &consumer)
5050 {
5051     int32_t callingUid = GetCallingUid();
5052     for (const auto& uid : consumer.uids) {
5053         if (uid == callingUid) {
5054             filterNames.push_back(consumer.name);
5055         }
5056     }
5057 }
5058 
FilterConsumers(const std::vector<std::string> & deviceNames)5059 std::vector<std::string> MMIService::FilterConsumers(const std::vector<std::string> &deviceNames)
5060 {
5061     std::vector<std::string> filterNames;
5062     for (const auto& consumer : consumersData_.consumers) {
5063         if (std::find(deviceNames.begin(), deviceNames.end(), consumer.name) != deviceNames.end()) {
5064             DealConsumers(filterNames, consumer);
5065         }
5066     }
5067     return filterNames;
5068 }
5069 
UpdateConsumers(const cJSON * consumer)5070 void MMIService::UpdateConsumers(const cJSON* consumer)
5071 {
5072     DeviceConsumer deviceConsumer;
5073     cJSON* name = cJSON_GetObjectItemCaseSensitive(consumer, "name");
5074     if (name != nullptr && cJSON_IsString(name)) {
5075         char *nameString = cJSON_Print(name);
5076         std::string nameStr(nameString);
5077         if (!nameStr.empty() && nameStr.front() == '"' && nameStr.back() == '"') {
5078             nameStr = nameStr.substr(QUOTES_BEGIN, nameStr.size() - QUOTES_END);
5079         }
5080         deviceConsumer.name = nameStr;
5081         cJSON_free(nameString);
5082     }
5083     cJSON* uid_array = cJSON_GetObjectItemCaseSensitive(consumer, "uids");
5084     if (uid_array != nullptr && cJSON_IsArray(uid_array)) {
5085         cJSON* uid;
5086         cJSON_ArrayForEach(uid, uid_array) {
5087             if (cJSON_IsNumber(uid)) {
5088                 deviceConsumer.uids.push_back(cJSON_GetNumberValue(uid));
5089             }
5090         }
5091     }
5092     consumersData_.consumers.push_back(deviceConsumer);
5093 }
5094 
ParseDeviceConsumerConfig()5095 bool MMIService::ParseDeviceConsumerConfig()
5096 {
5097     CALL_DEBUG_ENTER;
5098     consumersData_.consumers.clear();
5099     const char configName[] { "/etc/multimodalinput/input_device_consumers.json" };
5100     char buf[MAX_PATH_LEN] {};
5101 
5102     char *filePath = GetOneCfgFile(configName, buf, sizeof(buf));
5103     if (filePath == nullptr || filePath[0] == '\0' || strlen(filePath) > MAX_PATH_LEN) {
5104         MMI_HILOGE("Can not get customization config file");
5105         return false;
5106     }
5107     std::string defaultConfig = filePath;
5108     std::string jsonStr = ReadJsonFile(defaultConfig);
5109     if (jsonStr.empty()) {
5110         MMI_HILOGE("Read configFile failed");
5111         return false;
5112     }
5113     JsonParser jsonData(jsonStr.c_str());
5114     if (!cJSON_IsObject(jsonData.Get())) {
5115         MMI_HILOGE("The json data is not object");
5116         return false;
5117     }
5118     cJSON* consumers = cJSON_GetObjectItemCaseSensitive(jsonData.Get(), "consumers");
5119     if (!cJSON_IsArray(consumers)) {
5120         MMI_HILOGE("consumers number must be array");
5121         return false;
5122     }
5123     cJSON* consumer;
5124     cJSON_ArrayForEach(consumer, consumers) {
5125         if (cJSON_IsObject(consumer)) {
5126             UpdateConsumers(consumer);
5127         }
5128     }
5129     return true;
5130 }
5131 
SetInputDeviceConsumer(const std::vector<std::string> & deviceNames)5132 ErrCode MMIService::SetInputDeviceConsumer(const std::vector<std::string>& deviceNames)
5133 {
5134     CALL_INFO_TRACE;
5135     if (deviceNames.size() < 0 || deviceNames.size() > MAX_DEVICE_NUM) {
5136         MMI_HILOGE("Invalid size:%{public}d", static_cast<int32_t>(deviceNames.size()));
5137         return RET_ERR;
5138     }
5139     bool flag = ParseDeviceConsumerConfig();
5140     if (!flag) {
5141         return ERROR_NO_PERMISSION;
5142     }
5143     auto nameVec = FilterConsumers(deviceNames);
5144     if (nameVec.empty()) {
5145         return ERROR_NO_PERMISSION;
5146     }
5147     int32_t pid = GetCallingPid();
5148     auto sess = GetSessionByPid(pid);
5149     CHKPR(sess, ERROR_NULL_POINTER);
5150     int32_t ret = delegateTasks_.PostSyncTask(
5151         [this, &nameVec, &sess] {
5152             return DEVICEHANDLER->SetDeviceConsumerHandler(nameVec, sess);
5153         }
5154     );
5155     if (ret != RET_OK) {
5156         MMI_HILOGE("SetDeviceConsumerHandler failed, return:%{public}d", ret);
5157         return ret;
5158     }
5159     return RET_OK;
5160 }
5161 
ClearInputDeviceConsumer(const std::vector<std::string> & deviceNames)5162 ErrCode MMIService::ClearInputDeviceConsumer(const std::vector<std::string>& deviceNames)
5163 {
5164     CALL_INFO_TRACE;
5165     if (deviceNames.size() < 0 || deviceNames.size() > MAX_DEVICE_NUM) {
5166         MMI_HILOGE("Invalid size:%{public}d", static_cast<int32_t>(deviceNames.size()));
5167         return RET_ERR;
5168     }
5169     bool flag = ParseDeviceConsumerConfig();
5170     if (!flag) {
5171         return ERROR_NO_PERMISSION;
5172     }
5173     auto nameVec = FilterConsumers(deviceNames);
5174     if (nameVec.empty()) {
5175         return ERROR_NO_PERMISSION;
5176     }
5177     int32_t pid = GetCallingPid();
5178     auto sess = GetSessionByPid(pid);
5179     int32_t ret = delegateTasks_.PostSyncTask(
5180         [this, &nameVec, &sess] {
5181             return DEVICEHANDLER->ClearDeviceConsumerHandler(nameVec, sess);
5182         }
5183     );
5184     if (ret != RET_OK) {
5185         MMI_HILOGE("ClearInputDeviceConsumer failed, return:%{public}d", ret);
5186         return ret;
5187     }
5188     return RET_OK;
5189 }
5190 
InitCustomConfig()5191 ErrCode MMIService::InitCustomConfig()
5192 {
5193     CALL_INFO_TRACE;
5194     ErrCode errCode { RET_OK };
5195     if (BUNDLE_NAME_PARSER.Init() != RET_OK) {
5196         MMI_HILOGE("BUNDLE_NAME_PARSER.Init failed");
5197         errCode = RET_ERR;
5198     }
5199     if (MISC_PRODUCT_TYPE_PARSER.Init() != RET_OK) {
5200         MMI_HILOGE("MISC_PRODUCT_TYPE_PARSER.Init failed");
5201         errCode = RET_ERR;
5202     }
5203     if (PRODUCT_TYPE_PARSER.Init() != RET_OK) {
5204         MMI_HILOGE("PRODUCT_TYPE_PARSER.Init failed");
5205         errCode = RET_ERR;
5206     }
5207     if (PRODUCT_NAME_DEFINITION_PARSER.Init() != RET_OK) {
5208         MMI_HILOGE("PRODUCT_NAME_DEFINITION_PARSER.Init failed");
5209         errCode = RET_ERR;
5210     }
5211     if (SPECIAL_INPUT_DEVICE_PARSER.Init() != RET_OK) {
5212         MMI_HILOGE("SPECIAL_INPUT_DEVICE_PARSER.Init failed");
5213         errCode = RET_ERR;
5214     }
5215     return errCode;
5216 }
5217 
SubscribeInputActive(int32_t subscribeId,int64_t interval)5218 ErrCode MMIService::SubscribeInputActive(int32_t subscribeId, int64_t interval)
5219 {
5220     CALL_INFO_TRACE;
5221     if (!PER_HELPER->VerifySystemApp()) {
5222         MMI_HILOGE("Verify system APP failed");
5223         return ERROR_NOT_SYSAPI;
5224     }
5225 
5226     if (!IsRunning()) {
5227         MMI_HILOGE("Service is not running");
5228         return MMISERVICE_NOT_RUNNING;
5229     }
5230     int32_t pid = GetCallingPid();
5231     int32_t ret = delegateTasks_.PostSyncTask(
5232         [this, pid, subscribeId, interval] {
5233             auto sess = this->GetSessionByPid(pid);
5234             CHKPR(sess, RET_ERR);
5235             auto subscriberHandler = InputHandler->GetInputActiveSubscriberHandler();
5236             CHKPR(subscriberHandler, RET_ERR);
5237             return subscriberHandler->SubscribeInputActive(sess, subscribeId, interval);
5238         }
5239         );
5240     if (ret != RET_OK) {
5241         MMI_HILOGE("The subscribe input active processed failed, ret:%{public}d", ret);
5242         return ret;
5243     }
5244     return RET_OK;
5245 }
5246 
UnsubscribeInputActive(int32_t subscribeId)5247 ErrCode MMIService::UnsubscribeInputActive(int32_t subscribeId)
5248 {
5249     CALL_INFO_TRACE;
5250     if (!PER_HELPER->VerifySystemApp()) {
5251         MMI_HILOGE("Verify system APP failed");
5252         return ERROR_NOT_SYSAPI;
5253     }
5254     if (!IsRunning()) {
5255         MMI_HILOGE("Service is not running");
5256         return MMISERVICE_NOT_RUNNING;
5257     }
5258     if (subscribeId < 0) {
5259         MMI_HILOGE("Invalid subscribeId");
5260         return RET_ERR;
5261     }
5262     int32_t pid = GetCallingPid();
5263     int32_t ret = delegateTasks_.PostSyncTask(
5264         [this, pid, subscribeId] {
5265             auto sess = this->GetSessionByPid(pid);
5266             CHKPR(sess, RET_ERR);
5267             auto subscriberHandler = InputHandler->GetInputActiveSubscriberHandler();
5268             CHKPR(subscriberHandler, RET_ERR);
5269             return subscriberHandler->UnsubscribeInputActive(sess, subscribeId);
5270         }
5271         );
5272     if (ret != RET_OK) {
5273         MMI_HILOGE("The unsubscribe input active processed failed, ret:%{public}d", ret);
5274         return ret;
5275     }
5276     return RET_OK;
5277 }
5278 
SetMouseAccelerateMotionSwitch(int32_t deviceId,bool enable)5279 ErrCode MMIService::SetMouseAccelerateMotionSwitch(int32_t deviceId, bool enable)
5280 {
5281     CALL_INFO_TRACE;
5282     if (!PER_HELPER->RequestFromShell()) {
5283         MMI_HILOGE("Verify Request From Shell failed");
5284         return ERROR_NO_PERMISSION;
5285     }
5286     int32_t ret = delegateTasks_.PostSyncTask(
5287         [deviceId, enable] {
5288             return MouseEventHdr->SetMouseAccelerateMotionSwitch(deviceId, enable);
5289         }
5290     );
5291     if (ret != RET_OK) {
5292         MMI_HILOGE("Set accelerate motion switch failed, return:%{public}d", ret);
5293         return ret;
5294     }
5295     return RET_OK;
5296 }
5297 
SwitchScreenCapturePermission(uint32_t permissionType,bool enable)5298 ErrCode MMIService::SwitchScreenCapturePermission(uint32_t permissionType, bool enable)
5299 {
5300     CALL_INFO_TRACE;
5301     int32_t callingUid = GetCallingUid();
5302     if (!PER_HELPER->VerifySystemApp()) {
5303         MMI_HILOGE("Verify system APP failed");
5304         return ERROR_NOT_SYSAPI;
5305     }
5306     if (callingUid != PENGLAI_UID && callingUid != GAME_UID) {
5307         MMI_HILOGE("Verify specified system APP failed");
5308         return ERROR_NO_PERMISSION;
5309     }
5310     int32_t pid = GetCallingPid();
5311     auto sess = GetSessionByPid(pid);
5312     auto eventKeyCommandHandler = InputHandler->GetKeyCommandHandler();
5313     CHKPR(eventKeyCommandHandler, RET_ERR);
5314     int32_t ret = delegateTasks_.PostSyncTask(
5315         [permissionType, enable, eventKeyCommandHandler] {
5316             return eventKeyCommandHandler->SwitchScreenCapturePermission(permissionType, enable);
5317         }
5318         );
5319     if (ret != RET_OK) {
5320         MMI_HILOGE("SwitchScreenCapturePermission failed, return:%{public}d", ret);
5321         return ret;
5322     }
5323     return RET_OK;
5324 }
5325 
ClearMouseHideFlag(int32_t eventId)5326 ErrCode MMIService::ClearMouseHideFlag(int32_t eventId)
5327 {
5328     CALL_INFO_TRACE;
5329     int32_t callingUid = GetCallingUid();
5330     if (!PER_HELPER->VerifySystemApp()) {
5331         MMI_HILOGE("Verify system APP failed");
5332         return ERROR_NOT_SYSAPI;
5333     }
5334     if (callingUid != SYNERGY_UID) {
5335         MMI_HILOGE("Verify specified synergy application failed");
5336         return ERROR_NO_PERMISSION;
5337     }
5338     int32_t ret = delegateTasks_.PostSyncTask([eventId] () {
5339         return WIN_MGR->ClearMouseHideFlag(eventId);
5340     });
5341     if (ret != RET_OK) {
5342         MMI_HILOGE("ClearMouseHideFlag failed, return:%{public}d", ret);
5343         return ret;
5344     }
5345     return RET_OK;
5346 }
5347 
QueryPointerRecord(int32_t count,std::vector<std::shared_ptr<PointerEvent>> & pointerList)5348 ErrCode MMIService::QueryPointerRecord(int32_t count, std::vector<std::shared_ptr<PointerEvent>> &pointerList)
5349 {
5350     CALL_INFO_TRACE;
5351     if (!PER_HELPER->VerifySystemApp()) {
5352         MMI_HILOGE("Verify system APP failed");
5353         return ERROR_NOT_SYSAPI;
5354     }
5355     if (!PER_HELPER->CheckMonitor()) {
5356         MMI_HILOGE("Verify Request From Monitor failed");
5357         return ERROR_NO_PERMISSION;
5358     }
5359     int32_t ret = delegateTasks_.PostSyncTask(
5360         [count, &pointerList] {
5361             return EventStatistic::QueryPointerRecord(count, pointerList);
5362         }
5363     );
5364     if (ret != RET_OK) {
5365         MMI_HILOGE("query pointerRecord failed, return:%{public}d", ret);
5366         return ret;
5367     }
5368     return RET_OK;
5369 }
5370 } // namespace MMI
5371 } // namespace OHOS
5372