• 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 "server_msg_handler.h"
17 
18 #include "anr_manager.h"
19 #include "app_mgr_client.h"
20 #include "authorization_dialog.h"
21 #include "authorize_helper.h"
22 #include "bytrace_adapter.h"
23 #include "cursor_drawing_component.h"
24 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
25 #include "dfx_hisysevent.h"
26 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
27 #include "display_event_monitor.h"
28 #include "event_log_helper.h"
29 #include "input_device_manager.h"
30 #include "input_event_handler.h"
31 #ifdef OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
32 #include "key_monitor_manager.h"
33 #endif // OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
34 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
35 #include "key_shortcut_manager.h"
36 #endif // SHORTCUT_KEY_MANAGER_ENABLED
37 #include "long_press_subscriber_handler.h"
38 #include "libinput_adapter.h"
39 #include "pointer_device_manager.h"
40 #include "time_cost_chk.h"
41 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
42 #include "touch_drawing_manager.h"
43 #endif // #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
44 #include "util.h"
45 
46 #undef MMI_LOG_DOMAIN
47 #define MMI_LOG_DOMAIN MMI_LOG_SERVER
48 #undef MMI_LOG_TAG
49 #define MMI_LOG_TAG "ServerMsgHandler"
50 
51 namespace OHOS {
52 namespace MMI {
53 namespace {
54 #ifdef OHOS_BUILD_ENABLE_SECURITY_COMPONENT
55 constexpr int32_t SECURITY_COMPONENT_SERVICE_ID = 3050;
56 #endif // OHOS_BUILD_ENABLE_SECURITY_COMPONENT
57 constexpr int32_t SEND_NOTICE_OVERTIME { 5 };
58 [[ maybe_unused ]] constexpr int32_t DEFAULT_POINTER_ID { 10000 };
59 [[ maybe_unused ]] constexpr int32_t CAST_POINTER_ID { 5000 };
60 const std::string PRODUCT_TYPE = system::GetParameter("const.product.devicetype", "unknown");
61 const std::string PRODUCT_TYPE_PC = "2in1";
62 [[ maybe_unused ]] constexpr int32_t WINDOW_ROTATE { 0 };
63 constexpr int32_t COMMON_PERMISSION_CHECK_ERROR { 201 };
64 constexpr int32_t CAST_INPUT_DEVICEID { 0xAAAAAAFF };
65 constexpr int32_t CAST_SCREEN_DEVICEID { 0xAAAAAAFE };
66 constexpr int32_t ANGLE_90 { 90 };
67 constexpr int32_t ANGLE_360 { 360 };
68 constexpr int32_t ERR_DEVICE_NOT_EXIST { 3900002 };
69 constexpr int32_t ERR_NON_INPUT_APPLICATION { 3900003 };
70 constexpr int32_t SIMULATE_EVENT_START_ID { 10000 };
71 constexpr float MM_TO_INCH { 25.4f };
72 constexpr int32_t SCREEN_DIAGONAL_0 { 0 };
73 constexpr int32_t SCREEN_DIAGONAL_8 { 8 };
74 constexpr int32_t SCREEN_DIAGONAL_18 { 18 };
75 constexpr int32_t SCREEN_DIAGONAL_27 { 27 };
76 constexpr int32_t SCREEN_DIAGONAL_55 { 55 };
77 constexpr float FACTOR_0 { 1.0f };
78 constexpr float FACTOR_8 { 0.7f };
79 constexpr float FACTOR_18 { 1.0f };
80 constexpr float FACTOR_27 { 1.2f };
81 constexpr float FACTOR_55 { 1.6f };
82 constexpr float FACTOR_MAX { 2.4f };
83 constexpr int64_t QUERY_AUTHORIZE_MAX_INTERVAL_TIME { 3000 };
84 constexpr uint32_t MAX_ENHANCE_CONFIG_SIZE { 1000 };
85 } // namespace
86 
Init(UDSServer & udsServer)87 void ServerMsgHandler::Init(UDSServer &udsServer)
88 {
89     udsServer_ = &udsServer;
90     MsgCallback funs[] = {
91         {MmiMessageId::DISPLAY_INFO, [this] (SessionPtr sess, NetPacket &pkt) {
92             return this->OnDisplayInfo(sess, pkt); }},
93         {MmiMessageId::WINDOW_INFO, [this] (SessionPtr sess, NetPacket &pkt) {
94             return this->OnWindowGroupInfo(sess, pkt); }},
95         {MmiMessageId::WINDOW_STATE_ERROR_CALLBACK, [this] (SessionPtr sess, NetPacket &pkt) {
96             return this->RegisterWindowStateErrorCallback(sess, pkt); }},
97 #ifdef OHOS_BUILD_ENABLE_SECURITY_COMPONENT
98         {MmiMessageId::SCINFO_CONFIG, [this] (SessionPtr sess, NetPacket &pkt) {
99             return this->OnEnhanceConfig(sess, pkt); }},
100 #endif // OHOS_BUILD_ENABLE_SECURITY_COMPONENT
101 
102     };
103     for (auto &it : funs) {
104         if (!RegistrationEvent(it)) {
105             MMI_HILOGW("Failed to register event errCode:%{public}d", EVENT_REG_FAIL);
106             continue;
107         }
108     }
109     AUTHORIZE_HELPER->Init(&clientDeathHandler_);
110 }
111 
OnMsgHandler(SessionPtr sess,NetPacket & pkt)112 void ServerMsgHandler::OnMsgHandler(SessionPtr sess, NetPacket& pkt)
113 {
114     CHKPV(sess);
115     auto id = pkt.GetMsgId();
116     TimeCostChk chk("ServerMsgHandler::OnMsgHandler", "overtime 300(us)", MAX_OVER_TIME, id);
117     BytraceAdapter::StartSocketHandle(static_cast<int32_t>(id));
118     auto callback = GetMsgCallback(id);
119     if (callback == nullptr) {
120         MMI_HILOGE("Unknown msg id:%{public}d,errCode:%{public}d", id, UNKNOWN_MSG_ID);
121         return;
122     }
123     auto ret = (*callback)(sess, pkt);
124     BytraceAdapter::StopSocketHandle();
125     if (ret < 0) {
126         MMI_HILOGE("Msg handling failed. id:%{public}d,errCode:%{public}d", id, ret);
127     }
128 }
129 
130 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
OnInjectKeyEvent(const std::shared_ptr<KeyEvent> keyEvent,int32_t pid,bool isNativeInject)131 int32_t ServerMsgHandler::OnInjectKeyEvent(const std::shared_ptr<KeyEvent> keyEvent, int32_t pid, bool isNativeInject)
132 {
133     CALL_DEBUG_ENTER;
134     CHKPR(keyEvent, ERROR_NULL_POINTER);
135     LogTracer lt(keyEvent->GetId(), keyEvent->GetEventType(), keyEvent->GetKeyAction());
136     if (isNativeInject) {
137         int32_t checkReturn = NativeInjectCheck(pid);
138         if (checkReturn != RET_OK) {
139             return checkReturn;
140         }
141     }
142     keyEvent->SetKeyIntention(KeyItemsTransKeyIntention(keyEvent->GetKeyItems()));
143     auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
144     CHKPR(inputEventNormalizeHandler, ERROR_NULL_POINTER);
145     inputEventNormalizeHandler->HandleKeyEvent(keyEvent);
146 #ifdef SHORTCUT_KEY_RULES_ENABLED
147     KEY_SHORTCUT_MGR->UpdateShortcutConsumed(keyEvent);
148 #endif // SHORTCUT_KEY_RULES_ENABLED
149     if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
150         MMI_HILOGD("Inject keyCode:%{private}d, action:%{public}d", keyEvent->GetKeyCode(), keyEvent->GetKeyAction());
151     } else {
152         MMI_HILOGD("Inject keyCode:%{private}d, action:%{public}d", keyEvent->GetKeyCode(), keyEvent->GetKeyAction());
153     }
154     return RET_OK;
155 }
156 
OnGetFunctionKeyState(int32_t funcKey,bool & state)157 int32_t ServerMsgHandler::OnGetFunctionKeyState(int32_t funcKey, bool &state)
158 {
159     CALL_INFO_TRACE;
160     bool hasVirtualKeyboard = false;
161 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
162     hasVirtualKeyboard = INPUT_DEV_MGR->HasVirtualKeyboardDevice();
163 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
164     std::vector<struct libinput_device*> input_device;
165     INPUT_DEV_MGR->GetMultiKeyboardDevice(input_device);
166     if (input_device.size() == 0 && !hasVirtualKeyboard) {
167         MMI_HILOGW("No keyboard device is currently available");
168         return ERR_DEVICE_NOT_EXIST;
169     }
170     const auto &keyEvent = KeyEventHdr->GetKeyEvent();
171     CHKPR(keyEvent, ERROR_NULL_POINTER);
172     state = keyEvent->GetFunctionKey(funcKey);
173     MMI_HILOGI("Get function key:%{public}d status as %{public}s", funcKey, state ? "open" : "close");
174     return RET_OK;
175 }
176 
OnSetFunctionKeyState(int32_t pid,int32_t funcKey,bool enable)177 int32_t ServerMsgHandler::OnSetFunctionKeyState(int32_t pid, int32_t funcKey, bool enable)
178 {
179     CALL_INFO_TRACE;
180     AppExecFwk::RunningProcessInfo processInfo;
181     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
182     CHKPR(appMgrClient, ERROR_NULL_POINTER);
183     auto begin = std::chrono::high_resolution_clock::now();
184     appMgrClient->GetRunningProcessInfoByPid(pid, processInfo);
185     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
186         std::chrono::high_resolution_clock::now() - begin).count();
187 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
188     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::GET_RUNNING_PROCESS_INFO_BY_PID, durationMS);
189 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
190     if (processInfo.extensionType_ != AppExecFwk::ExtensionAbilityType::INPUTMETHOD) {
191         MMI_HILOGW("It is prohibited for non-input applications");
192         return ERR_NON_INPUT_APPLICATION;
193     }
194     bool hasVirtualKeyboard = false;
195 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
196     hasVirtualKeyboard = INPUT_DEV_MGR->HasVirtualKeyboardDevice();
197 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
198     std::vector<struct libinput_device*> input_device;
199     int32_t DeviceId = -1;
200     INPUT_DEV_MGR->GetMultiKeyboardDevice(input_device);
201     if (input_device.size() == 0 && !hasVirtualKeyboard) {
202         MMI_HILOGW("No keyboard device is currently available");
203         return ERR_DEVICE_NOT_EXIST;
204     }
205     auto keyEvent = KeyEventHdr->GetKeyEvent();
206     CHKPR(keyEvent, ERROR_NULL_POINTER);
207     bool checkState = keyEvent->GetFunctionKey(funcKey);
208     MMI_HILOGI("checkState:%{public}d, enable:%{public}d", checkState, enable);
209     if (checkState == enable) {
210         return RET_OK;
211     }
212 #ifdef OHOS_BUILD_ENABLE_VKEYBOARD
213     if (funcKey == KeyEvent::CAPS_LOCK_FUNCTION_KEY) {
214         // set vkeyboard caps state with separate API.
215         MMI_HILOGI("Set vkb func state old:%{public}d, new:%{public}d", checkState, enable);
216         libinput_toggle_caps_key();
217     }
218 #endif // OHOS_BUILD_ENABLE_VKEYBOARD
219     for (auto it = input_device.begin(); it != input_device.end(); ++it) {
220         auto device = (*it);
221         DeviceId = INPUT_DEV_MGR->FindInputDeviceId(device);
222         if (LibinputAdapter::DeviceLedUpdate(device, funcKey, enable) != RET_OK) {
223             MMI_HILOGE("Failed to set the keyboard led, device id %{public}d", DeviceId);
224         }
225         int32_t state = libinput_get_funckey_state(device, funcKey);
226         if (state != enable) {
227             MMI_HILOGE("Failed to enable the function key, device id %{public}d", DeviceId);
228         }
229     }
230     int32_t ret = keyEvent->SetFunctionKey(funcKey, enable);
231     if (ret != funcKey) {
232         MMI_HILOGE("Failed to enable the function key");
233         return RET_ERR;
234     }
235     MMI_HILOGD("Update function key:%{public}d succeed", funcKey);
236     return RET_OK;
237 }
238 #endif // OHOS_BUILD_ENABLE_KEYBOARD
239 
240 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
OnInjectPointerEvent(const std::shared_ptr<PointerEvent> pointerEvent,int32_t pid,bool isNativeInject,bool isShell,int32_t useCoordinate)241 int32_t ServerMsgHandler::OnInjectPointerEvent(const std::shared_ptr<PointerEvent> pointerEvent, int32_t pid,
242     bool isNativeInject, bool isShell, int32_t useCoordinate)
243 {
244     CALL_DEBUG_ENTER;
245     CHKPR(pointerEvent, ERROR_NULL_POINTER);
246     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
247     if (isNativeInject) {
248         int32_t checkReturn = NativeInjectCheck(pid);
249         if (checkReturn != RET_OK) {
250             return checkReturn;
251         }
252     }
253     return OnInjectPointerEventExt(pointerEvent, isShell, useCoordinate);
254 }
255 
OnInjectTouchPadEvent(const std::shared_ptr<PointerEvent> pointerEvent,int32_t pid,const TouchpadCDG & touchpadCDG,bool isNativeInject,bool isShell)256 int32_t ServerMsgHandler::OnInjectTouchPadEvent(const std::shared_ptr<PointerEvent> pointerEvent, int32_t pid,
257     const TouchpadCDG &touchpadCDG, bool isNativeInject, bool isShell)
258 {
259     CALL_DEBUG_ENTER;
260     CHKPR(pointerEvent, ERROR_NULL_POINTER);
261     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
262     if (isNativeInject) {
263         int32_t checkReturn = NativeInjectCheck(pid);
264         if (checkReturn != RET_OK) {
265             return checkReturn;
266         }
267     }
268     return OnInjectTouchPadEventExt(pointerEvent, touchpadCDG, isShell);
269 }
270 
IsNavigationWindowInjectEvent(std::shared_ptr<PointerEvent> pointerEvent)271 bool ServerMsgHandler::IsNavigationWindowInjectEvent(std::shared_ptr<PointerEvent> pointerEvent)
272 {
273     return pointerEvent->GetZOrder() > 0;
274 }
275 
OnInjectTouchPadEventExt(const std::shared_ptr<PointerEvent> pointerEvent,const TouchpadCDG & touchpadCDG,bool isShell)276 int32_t ServerMsgHandler::OnInjectTouchPadEventExt(const std::shared_ptr<PointerEvent> pointerEvent,
277     const TouchpadCDG &touchpadCDG, bool isShell)
278 {
279     CALL_DEBUG_ENTER;
280     CHKPR(pointerEvent, ERROR_NULL_POINTER);
281     EndLogTraceId(pointerEvent->GetId());
282     pointerEvent->UpdateId();
283     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
284     auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
285     CHKPR(inputEventNormalizeHandler, ERROR_NULL_POINTER);
286     if (pointerEvent->GetSourceType() == PointerEvent::SOURCE_TYPE_MOUSE) {
287 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
288         int32_t ret = AccelerateMotionTouchpad(pointerEvent, touchpadCDG);
289         if (ret != RET_OK) {
290             MMI_HILOGE("Failed to accelerate motion, error:%{public}d", ret);
291             return ret;
292         }
293         UpdatePointerEvent(pointerEvent);
294         inputEventNormalizeHandler->HandlePointerEvent(pointerEvent);
295         CHKPR(pointerEvent, ERROR_NULL_POINTER);
296         pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY);
297         if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_HIDE_POINTER)) {
298             if (POINTER_DEV_MGR.isInit) {
299                 CursorDrawingComponent::GetInstance().SetMouseDisplayState(false);
300             }
301         } else if ((pointerEvent->GetPointerAction() < PointerEvent::POINTER_ACTION_PULL_DOWN) ||
302             (pointerEvent->GetPointerAction() > PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW)) {
303             if (POINTER_DEV_MGR.isInit && !CursorDrawingComponent::GetInstance().IsPointerVisible()) {
304                 CursorDrawingComponent::GetInstance().SetPointerVisible(getpid(), true, 0, false);
305             }
306         }
307 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
308     } else {
309             MMI_HILOGW("Source types are not Touchpad, source:%{public}d", pointerEvent->GetSourceType());
310     }
311     return SaveTargetWindowId(pointerEvent, isShell);
312 }
313 
DealGesturePointers(std::shared_ptr<PointerEvent> pointerEvent)314 void ServerMsgHandler::DealGesturePointers(std::shared_ptr<PointerEvent> pointerEvent)
315 {
316     if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY)) {
317         return;
318     }
319     MMI_HILOGI("Check : current PointerEvent's info :Id=>%{public}d, pointerId=>%{public}d",
320         pointerEvent->GetId(), pointerEvent->GetPointerId());
321     std::shared_ptr<PointerEvent> touchEvent = WIN_MGR->GetLastPointerEventForGesture();
322     if (touchEvent != nullptr) {
323         std::list<PointerEvent::PointerItem> listPtItems = touchEvent->GetAllPointerItems();
324         for (auto &item : listPtItems) {
325             MMI_HILOGI("Check : current Item : pointerId=>%{public}d, OriginPointerId=>%{public}d",
326                 item.GetPointerId(), item.GetOriginPointerId());
327             if ((item.GetPointerId() % SIMULATE_EVENT_START_ID) !=
328                 (pointerEvent->GetPointerId() % SIMULATE_EVENT_START_ID) && item.IsPressed()) {
329                 pointerEvent->AddPointerItem(item);
330                 MMI_HILOGI("Check : add Item : pointerId=>%{public}d, OriginPointerId=>%{public}d",
331                     item.GetPointerId(), item.GetOriginPointerId());
332             }
333         }
334     }
335 }
336 
OnInjectPointerEventExt(const std::shared_ptr<PointerEvent> pointerEvent,bool isShell,int32_t useCoordinate)337 int32_t ServerMsgHandler::OnInjectPointerEventExt(const std::shared_ptr<PointerEvent> pointerEvent, bool isShell,
338     int32_t useCoordinate)
339 {
340     CALL_DEBUG_ENTER;
341     CHKPR(pointerEvent, ERROR_NULL_POINTER);
342     EndLogTraceId(pointerEvent->GetId());
343     pointerEvent->UpdateId();
344     LogTracer lt(pointerEvent->GetId(), pointerEvent->GetEventType(), pointerEvent->GetPointerAction());
345     auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
346     CHKPR(inputEventNormalizeHandler, ERROR_NULL_POINTER);
347     switch (pointerEvent->GetSourceType()) {
348         case PointerEvent::SOURCE_TYPE_TOUCHSCREEN: {
349 #ifdef OHOS_BUILD_ENABLE_TOUCH
350             if (!FixTargetWindowId(pointerEvent, pointerEvent->GetPointerAction(), isShell)) {
351                 return RET_ERR;
352             }
353             DealGesturePointers(pointerEvent);
354             WIN_MGR->ProcessInjectEventGlobalXY(pointerEvent, useCoordinate);
355             inputEventNormalizeHandler->HandleTouchEvent(pointerEvent);
356             if (!pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY) &&
357                 !(IsCastInject(pointerEvent->GetDeviceId())) &&
358                 !IsNavigationWindowInjectEvent(pointerEvent)) {
359 #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
360                 TOUCH_DRAWING_MGR->TouchDrawHandler(pointerEvent);
361 #endif // #ifdef OHOS_BUILD_ENABLE_TOUCH_DRAWING
362             }
363 #endif // OHOS_BUILD_ENABLE_TOUCH
364             break;
365         }
366         case PointerEvent::SOURCE_TYPE_MOUSE:
367 #ifdef OHOS_BUILD_ENABLE_JOYSTICK
368         case PointerEvent::SOURCE_TYPE_JOYSTICK:
369 #endif // OHOS_BUILD_ENABLE_JOYSTICK
370         case PointerEvent::SOURCE_TYPE_TOUCHPAD: {
371 #ifdef OHOS_BUILD_ENABLE_POINTER
372             int32_t ret = AccelerateMotion(pointerEvent);
373             if (ret != RET_OK) {
374                 MMI_HILOGE("Failed to accelerate motion, error:%{public}d", ret);
375                 return ret;
376             }
377             UpdatePointerEvent(pointerEvent);
378             WIN_MGR->ProcessInjectEventGlobalXY(pointerEvent, useCoordinate);
379             inputEventNormalizeHandler->HandlePointerEvent(pointerEvent);
380             CHKPR(pointerEvent, ERROR_NULL_POINTER);
381             if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY)) {
382                 break;
383             } else if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_HIDE_POINTER)) {
384                 CursorDrawingComponent::GetInstance().SetMouseDisplayState(false);
385             } else if (((pointerEvent->GetPointerAction() < PointerEvent::POINTER_ACTION_PULL_DOWN) ||
386                 (pointerEvent->GetPointerAction() > PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW)) &&
387                 !CursorDrawingComponent::GetInstance().IsPointerVisible()) {
388                 CursorDrawingComponent::GetInstance().SetPointerVisible(getpid(), true, 0, false);
389             }
390 #endif // OHOS_BUILD_ENABLE_POINTER
391             break;
392         }
393         default: {
394             MMI_HILOGW("Source type is unknown, source:%{public}d", pointerEvent->GetSourceType());
395             break;
396         }
397     }
398     return SaveTargetWindowId(pointerEvent, isShell);
399 }
400 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
401 
402 #ifdef OHOS_BUILD_ENABLE_POINTER
ScreenFactor(const int32_t diagonalInch)403 float ServerMsgHandler::ScreenFactor(const int32_t diagonalInch)
404 {
405     if (diagonalInch <= SCREEN_DIAGONAL_0) {
406         return FACTOR_0;
407     } else if (diagonalInch < SCREEN_DIAGONAL_8) {
408         return FACTOR_8;
409     } else if (diagonalInch < SCREEN_DIAGONAL_18) {
410         return FACTOR_18;
411     } else if (diagonalInch < SCREEN_DIAGONAL_27) {
412         return FACTOR_27;
413     } else if (diagonalInch < SCREEN_DIAGONAL_55) {
414         return FACTOR_55;
415     } else {
416         return FACTOR_MAX;
417     }
418 }
419 
AccelerateMotion(std::shared_ptr<PointerEvent> pointerEvent)420 int32_t ServerMsgHandler::AccelerateMotion(std::shared_ptr<PointerEvent> pointerEvent)
421 {
422     if (!pointerEvent->HasFlag(InputEvent::EVENT_FLAG_RAW_POINTER_MOVEMENT) ||
423         (pointerEvent->GetSourceType() != PointerEvent::SOURCE_TYPE_MOUSE) ||
424         ((pointerEvent->GetPointerAction() != PointerEvent::POINTER_ACTION_MOVE) &&
425         (pointerEvent->GetPointerAction() != PointerEvent::POINTER_ACTION_PULL_MOVE) &&
426         (pointerEvent->GetPointerAction() != PointerEvent::POINTER_ACTION_BUTTON_DOWN))) {
427             return RET_OK;
428     }
429     PointerEvent::PointerItem pointerItem {};
430     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
431         MMI_HILOGE("Pointer event is corrupted");
432         return RET_ERR;
433     }
434     CursorPosition cursorPos = WIN_MGR->GetCursorPos();
435     if (cursorPos.displayId < 0) {
436         MMI_HILOGE("No display");
437         return RET_ERR;
438     }
439     Offset offset {
440         .dx = pointerItem.GetRawDx(),
441         .dy = pointerItem.GetRawDy(),
442     };
443     auto displayInfo = WIN_MGR->GetPhysicalDisplay(cursorPos.displayId);
444     CHKPR(displayInfo, ERROR_NULL_POINTER);
445 #ifndef OHOS_BUILD_EMULATOR
446     Direction displayDirection = WIN_MGR->GetDisplayDirection(displayInfo);
447     CalculateOffset(displayDirection, offset);
448 #endif // OHOS_BUILD_EMULATOR
449     int32_t ret = RET_OK;
450     if (pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
451         WIN_MGR->UpdateAndAdjustMouseLocation(cursorPos.displayId, cursorPos.cursorPos.x, cursorPos.cursorPos.y);
452         return RET_OK;
453     }
454     if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_TOUCHPAD_POINTER) &&
455         pointerEvent->HasFlag(InputEvent::EVENT_FLAG_VIRTUAL_TOUCHPAD_POINTER)) {
456         ret = HandleMotionAccelerateTouchpad(&offset, WIN_MGR->GetMouseIsCaptureMode(),
457             &cursorPos.cursorPos.x, &cursorPos.cursorPos.y,
458             MouseTransformProcessor::GetTouchpadSpeed(), static_cast<int32_t>(DeviceType::DEVICE_FOLD_PC_VIRT));
459     } else if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_TOUCHPAD_POINTER)) {
460         ret = HandleMotionAccelerateTouchpad(&offset, WIN_MGR->GetMouseIsCaptureMode(),
461             &cursorPos.cursorPos.x, &cursorPos.cursorPos.y,
462             MouseTransformProcessor::GetTouchpadSpeed(), static_cast<int32_t>(DeviceType::DEVICE_PC));
463     } else {
464         uint64_t deltaTime = 0;
465 #ifdef OHOS_BUILD_MOUSE_REPORTING_RATE
466         static uint64_t preTime = -1;
467         uint64_t currentTime = static_cast<uint64_t>(pointerEvent->GetActionTime());
468         preTime = fmin(preTime, currentTime);
469         deltaTime = (currentTime - preTime);
470         preTime = currentTime;
471 #endif // OHOS_BUILD_MOUSE_REPORTING_RATE
472         if (displayInfo->ppi != 0) {
473             int32_t diagonalMm = static_cast<int32_t>(sqrt((displayInfo->physicalWidth * displayInfo->physicalWidth) +
474             (displayInfo->physicalHeight * displayInfo->physicalHeight)));
475             int32_t diagonalInch = static_cast<int32_t>(diagonalMm / MM_TO_INCH);
476             float factor = ScreenFactor(diagonalInch);
477             ret = HandleMotionDynamicAccelerateMouse(&offset, WIN_MGR->GetMouseIsCaptureMode(),
478             &cursorPos.cursorPos.x, &cursorPos.cursorPos.y, MouseTransformProcessor::GetPointerSpeed(),
479             deltaTime, static_cast<double>(displayInfo->ppi), static_cast<double>(factor));
480         } else {
481             ret = HandleMotionAccelerateMouse(&offset, WIN_MGR->GetMouseIsCaptureMode(),
482             &cursorPos.cursorPos.x, &cursorPos.cursorPos.y,
483             MouseTransformProcessor::GetPointerSpeed(), static_cast<int32_t>(DeviceType::DEVICE_PC));
484         }
485     }
486     if (ret != RET_OK) {
487         MMI_HILOGE("Failed to accelerate pointer motion, error:%{public}d", ret);
488         return ret;
489     }
490     WIN_MGR->UpdateAndAdjustMouseLocation(cursorPos.displayId, cursorPos.cursorPos.x, cursorPos.cursorPos.y);
491     if (EventLogHelper::IsBetaVersion() && !pointerEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
492         MMI_HILOGD("Cursor move to (x:%.2f, y:%.2f, DisplayId:%d)",
493             cursorPos.cursorPos.x, cursorPos.cursorPos.y, cursorPos.displayId);
494     } else {
495         MMI_HILOGD("Cursor move to (x:%.2f, y:%.2f, DisplayId:%d)",
496             cursorPos.cursorPos.x, cursorPos.cursorPos.y, cursorPos.displayId);
497     }
498     return RET_OK;
499 }
500 
AccelerateMotionTouchpad(std::shared_ptr<PointerEvent> pointerEvent,const TouchpadCDG & touchpadCDG)501 int32_t ServerMsgHandler::AccelerateMotionTouchpad(std::shared_ptr<PointerEvent> pointerEvent,
502     const TouchpadCDG &touchpadCDG)
503 {
504     PointerEvent::PointerItem pointerItem {};
505     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
506         MMI_HILOGE("Pointer event is corrupted");
507         return RET_ERR;
508     }
509     CursorPosition cursorPos = WIN_MGR->GetCursorPos();
510     if (cursorPos.displayId < 0) {
511         MMI_HILOGE("No display");
512         return RET_ERR;
513     }
514     Offset offset {
515         .dx = pointerItem.GetRawDx(),
516         .dy = pointerItem.GetRawDy(),
517     };
518     auto displayInfo = WIN_MGR->GetPhysicalDisplay(cursorPos.displayId);
519     CHKPR(displayInfo, ERROR_NULL_POINTER);
520 #ifndef OHOS_BUILD_EMULATOR
521     Direction displayDirection = static_cast<Direction>((
522         ((displayInfo->direction - displayInfo->displayDirection) * ANGLE_90 + ANGLE_360) % ANGLE_360) / ANGLE_90);
523     CalculateOffset(displayDirection, offset);
524 #endif // OHOS_BUILD_EMULATOR
525     int32_t ret = RET_OK;
526 
527 #ifdef OHOS_BUILD_MOUSE_REPORTING_RATE
528     MMI_HILOGE("Hidumper before HandleMotionDynamicAccelerateTouchpad");
529     static uint64_t preTime = -1;
530     uint64_t currentTime = static_cast<uint64_t>(pointerEvent->GetActionTime());
531     preTime = fmin(preTime, currentTime);
532     uint64_t deltaTime = (currentTime - preTime);
533     MMI_HILOGE("DeltaTime before HandleMotionDynamicAccelerateTouchpad: %{public}PRId64 ms", deltaTime);
534 
535     double displaySize = sqrt(pow(displayInfo->width, 2) + pow(displayInfo->height, 2));
536     double touchpadSize = touchpadCDG.size;
537     double touchpadPPi = touchpadCDG.ppi;
538     int32_t touchpadSpeed = touchpadCDG.speed;
539     int32_t frequency = touchpadCDG.frequency;
540     if (touchpadSize <= 0 || touchpadPPi <= 0 || touchpadSpeed <= 0 || frequency <= 0) {
541         MMI_HILOGE("touchpadSize, touchpadPPi or touchpadSpeed are invalid,
542             touchpadSize:%{public}lf, touchpadPPi:%{public}lf, touchpadSpeed:%{public}d, frequency:%{public}d",
543             touchpadSize, touchpadPPi, touchpadSpeed, frequency);
544         return RET_ERR;
545     }
546     if (pointerEvent->GetPointerAction() == POINTER_ACTION_MOVE) {
547         ret = HandleMotionDynamicAccelerateTouchpad(&offset, WIN_MGR->GetMouseIsCaptureMode(), &cursorPos.cursorPos.x,
548             &cursorPos.cursorPos.y, touchpadSpeed, displaySize, touchpadSize, touchpadPPi, frequency);
549     }
550     MMI_HILOGE("DeltaTime after HandleMotionDynamicAccelerateTouchpad: %{public}PRId64 ms", deltaTime);
551     MMI_HILOGE("Hidumper after HandleMotionDynamicAccelerateTouchpad");
552     preTime = currentTime;
553 #else
554     ret = HandleMotionAccelerateTouchpad(&offset, WIN_MGR->GetMouseIsCaptureMode(),
555         &cursorPos.cursorPos.x, &cursorPos.cursorPos.y,
556         MouseTransformProcessor::GetTouchpadSpeed(), static_cast<int32_t>(DeviceType::DEVICE_PC));
557 #endif // OHOS_BUILD_MOUSE_REPORTING_RATE
558     if (ret != RET_OK) {
559         MMI_HILOGE("Failed to accelerate pointer motion, error:%{public}d", ret);
560         return ret;
561     }
562     WIN_MGR->UpdateAndAdjustMouseLocation(cursorPos.displayId, cursorPos.cursorPos.x, cursorPos.cursorPos.y);
563     if (EventLogHelper::IsBetaVersion() && !pointerEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
564         MMI_HILOGD("Cursor move to (x:%.2f, y:%.2f, DisplayId:%d)",
565             cursorPos.cursorPos.x, cursorPos.cursorPos.y, cursorPos.displayId);
566     } else {
567         MMI_HILOGD("Cursor move to (x:%.2f, y:%.2f, DisplayId:%d)",
568             cursorPos.cursorPos.x, cursorPos.cursorPos.y, cursorPos.displayId);
569     }
570     return RET_OK;
571 }
572 
CalculateOffset(Direction direction,Offset & offset)573 void ServerMsgHandler::CalculateOffset(Direction direction, Offset &offset)
574 {
575     std::negate<double> neg;
576     if (direction == DIRECTION90) {
577         double tmp = offset.dx;
578         offset.dx = offset.dy;
579         offset.dy = neg(tmp);
580     } else if (direction == DIRECTION180) {
581         offset.dx = neg(offset.dx);
582         offset.dy = neg(offset.dy);
583     } else if (direction == DIRECTION270) {
584         double tmp = offset.dx;
585         offset.dx = neg(offset.dy);
586         offset.dy = tmp;
587     }
588 }
589 #endif // OHOS_BUILD_ENABLE_POINTER
590 
591 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
UpdatePointerEvent(std::shared_ptr<PointerEvent> pointerEvent)592 void ServerMsgHandler::UpdatePointerEvent(std::shared_ptr<PointerEvent> pointerEvent)
593 {
594     if (!pointerEvent->HasFlag(InputEvent::EVENT_FLAG_RAW_POINTER_MOVEMENT) ||
595         (pointerEvent->GetSourceType() != PointerEvent::SOURCE_TYPE_MOUSE)) {
596         return;
597     }
598     PointerEvent::PointerItem pointerItem {};
599     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
600         MMI_HILOGE("Pointer event is corrupted");
601         return;
602     }
603     auto mouseInfo = WIN_MGR->GetMouseInfo();
604     pointerItem.SetDisplayX(mouseInfo.physicalX);
605     pointerItem.SetDisplayY(mouseInfo.physicalY);
606     pointerItem.SetDisplayXPos(mouseInfo.physicalX);
607     pointerItem.SetDisplayYPos(mouseInfo.physicalY);
608     pointerEvent->UpdatePointerItem(pointerEvent->GetPointerId(), pointerItem);
609     pointerEvent->SetTargetDisplayId(mouseInfo.displayId);
610 }
611 
SaveTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent,bool isShell)612 int32_t ServerMsgHandler::SaveTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent, bool isShell)
613 {
614     CHKPR(pointerEvent, ERROR_NULL_POINTER);
615     if ((pointerEvent->GetSourceType() == PointerEvent::SOURCE_TYPE_TOUCHSCREEN) &&
616         (pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_DOWN ||
617         pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_HOVER_ENTER)) {
618         int32_t pointerId = pointerEvent->GetPointerId();
619         PointerEvent::PointerItem pointerItem;
620         if (!pointerEvent->GetPointerItem(pointerId, pointerItem)) {
621             MMI_HILOGE("Can't find pointer item, pointer:%{public}d", pointerId);
622             return RET_ERR;
623         }
624         int32_t targetWindowId = pointerEvent->GetTargetWindowId();
625         if (isShell) {
626             shellTargetWindowIds_[pointerId] = targetWindowId;
627         } else if (IsCastInject(pointerEvent->GetDeviceId()) && (pointerEvent->GetZOrder() > 0)) {
628             castTargetWindowIds_[pointerId] = targetWindowId;
629         } else if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY)) {
630             accessTargetWindowIds_[pointerId] = targetWindowId;
631         } else {
632             nativeTargetWindowIds_[pointerId] = targetWindowId;
633         }
634     }
635     if ((pointerEvent->GetSourceType() == PointerEvent::SOURCE_TYPE_TOUCHSCREEN) &&
636         (pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_UP ||
637         pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_HOVER_EXIT)) {
638         int32_t pointerId = pointerEvent->GetPointerId();
639         if (isShell) {
640             shellTargetWindowIds_.erase(pointerId);
641         } else if (IsCastInject(pointerEvent->GetDeviceId()) && (pointerEvent->GetZOrder() > 0)) {
642             castTargetWindowIds_.erase(pointerId);
643         } else if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY)) {
644             accessTargetWindowIds_.erase(pointerId);
645         } else {
646             nativeTargetWindowIds_.erase(pointerId);
647         }
648     }
649     return RET_OK;
650 }
651 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
652 
653 #ifdef OHOS_BUILD_ENABLE_TOUCH
FixTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent,int32_t action,bool isShell)654 bool ServerMsgHandler::FixTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent,
655     int32_t action, bool isShell)
656 {
657     int32_t targetWindowId = -1;
658     if (isShell) {
659         targetWindowId = FixTargetWindowId(pointerEvent, shellTargetWindowIds_);
660     } else if ((IsCastInject(pointerEvent->GetDeviceId()))) {
661         targetWindowId = (pointerEvent->GetZOrder() > 0) ? // Gesture Window in Collaborative Scenarios
662         FixTargetWindowId(pointerEvent, castTargetWindowIds_, true, CAST_POINTER_ID) :
663         FixTargetWindowId(pointerEvent, nativeTargetWindowIds_, true, CAST_POINTER_ID);
664     } else if (pointerEvent->HasFlag(InputEvent::EVENT_FLAG_ACCESSIBILITY)) {
665         targetWindowId = FixTargetWindowId(pointerEvent, accessTargetWindowIds_);
666     } else {
667         targetWindowId = FixTargetWindowId(pointerEvent, nativeTargetWindowIds_, true, DEFAULT_POINTER_ID);
668     }
669     MMI_HILOGD("TargetWindowId:%{public}d %{public}d", pointerEvent->GetTargetWindowId(), targetWindowId);
670     return UpdateTouchEvent(pointerEvent, action, targetWindowId);
671 }
672 
FixTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent,const std::map<int32_t,int32_t> & targetWindowIdMap,bool bNeedResetPointerId,int32_t diffPointerId)673 int32_t ServerMsgHandler::FixTargetWindowId(std::shared_ptr<PointerEvent> pointerEvent,
674     const std::map<int32_t, int32_t>& targetWindowIdMap, bool bNeedResetPointerId, int32_t diffPointerId)
675 {
676     CHKPR(pointerEvent, RET_ERR);
677     int32_t pointerId = pointerEvent->GetPointerId();
678     PointerEvent::PointerItem pointerItem;
679     if (!pointerEvent->GetPointerItem(pointerId, pointerItem)) {
680         MMI_HILOGE("Can't find pointer item, pointer:%{public}d", pointerId);
681         return RET_ERR;
682     }
683     if (bNeedResetPointerId) {
684         if (diffPointerId <= 0) {
685             MMI_HILOGE("Parameter diffPointerId error, diffPointerId:%{public}d", pointerId);
686             return RET_ERR;
687         }
688         pointerEvent->RemovePointerItem(pointerId);
689         pointerId += diffPointerId;
690         pointerItem.SetPointerId(pointerId);
691         pointerEvent->UpdatePointerItem(pointerId, pointerItem);
692         pointerEvent->SetPointerId(pointerId);
693     }
694     auto iter = targetWindowIdMap.find(pointerEvent->GetPointerId());
695     if (iter != targetWindowIdMap.end()) {
696         return iter->second;
697     }
698     return RET_ERR;
699 }
700 
UpdateTouchEvent(std::shared_ptr<PointerEvent> pointerEvent,int32_t action,int32_t targetWindowId)701 bool ServerMsgHandler::UpdateTouchEvent(std::shared_ptr<PointerEvent> pointerEvent,
702     int32_t action, int32_t targetWindowId)
703 {
704     int32_t pointerId = pointerEvent->GetPointerId();
705     PointerEvent::PointerItem pointerItem;
706     if (!pointerEvent->GetPointerItem(pointerId, pointerItem)) {
707         MMI_HILOGE("Can't find pointer item, pointer:%{public}d", pointerId);
708         return false;
709     }
710     if (action == PointerEvent::POINTER_ACTION_HOVER_ENTER ||
711         action == PointerEvent::POINTER_ACTION_DOWN || targetWindowId < 0) {
712         MMI_HILOGD("Down event or targetWindowId less 0 is not need fix window id");
713         return true;
714     }
715     auto pointerIds = pointerEvent->GetPointerIds();
716     if (pointerIds.empty()) {
717         MMI_HILOGE("GetPointerIds is empty");
718         return false;
719     }
720 
721     pointerEvent->SetTargetWindowId(targetWindowId);
722     pointerItem.SetTargetWindowId(targetWindowId);
723     pointerEvent->UpdatePointerItem(pointerId, pointerItem);
724     return true;
725 }
726 #endif // OHOS_BUILD_ENABLE_TOUCH
727 
OnUiExtentionWindowInfo(NetPacket & pkt,WindowInfo & info)728 int32_t ServerMsgHandler::OnUiExtentionWindowInfo(NetPacket &pkt, WindowInfo& info)
729 {
730     uint32_t num = 0;
731     pkt >> num;
732     if (num > MAX_UI_EXTENSION_SIZE) {
733         MMI_HILOGE("Invalid num:%{public}u", num);
734         return RET_ERR;
735     }
736     if (pkt.ChkRWError()) {
737         MMI_HILOGE("Packet read display info failed");
738         return RET_ERR;
739     }
740     for (uint32_t i = 0; i < num; i++) {
741         WindowInfo extensionInfo;
742         pkt >> extensionInfo.id >> extensionInfo.pid >> extensionInfo.uid >> extensionInfo.area
743             >> extensionInfo.defaultHotAreas >> extensionInfo.pointerHotAreas >> extensionInfo.agentWindowId
744             >> extensionInfo.flags >> extensionInfo.action >> extensionInfo.displayId >> extensionInfo.groupId
745             >> extensionInfo.zOrder >> extensionInfo.pointerChangeAreas >> extensionInfo.transform
746             >> extensionInfo.windowInputType >> extensionInfo.privacyMode >> extensionInfo.windowType
747             >> extensionInfo.privacyUIFlag >> extensionInfo.rectChangeBySystem
748             >> extensionInfo.isSkipSelfWhenShowOnVirtualScreen >> extensionInfo.windowNameType;
749         info.uiExtentionWindowInfo.push_back(extensionInfo);
750         if (pkt.ChkRWError()) {
751             MMI_HILOGE("Packet read extention window info failed");
752             return RET_ERR;
753         }
754     }
755     return RET_OK;
756 }
757 
IsCastInject(int32_t deviceid)758 bool ServerMsgHandler::IsCastInject(int32_t deviceid)
759 {
760     return (deviceid == CAST_INPUT_DEVICEID || deviceid == CAST_SCREEN_DEVICEID);
761 }
762 
OnDisplayInfo(SessionPtr sess,NetPacket & pkt)763 int32_t ServerMsgHandler::OnDisplayInfo(SessionPtr sess, NetPacket &pkt)
764 {
765     CALL_DEBUG_ENTER;
766     CHKPR(sess, ERROR_NULL_POINTER);
767     int32_t tokenType = sess->GetTokenType();
768     if (tokenType != TokenType::TOKEN_NATIVE && tokenType != TokenType::TOKEN_SHELL &&
769         tokenType !=TokenType::TOKEN_SYSTEM_HAP) {
770         MMI_HILOGW("Not native or systemapp skip, pid:%{public}d tokenType:%{public}d", sess->GetPid(), tokenType);
771         return RET_ERR;
772     }
773     UserScreenInfo userScreenInfo;
774     oldDisplayGroupInfos_.clear();
775     pkt >> userScreenInfo.userId;
776     if (ReadScreensInfo(pkt, userScreenInfo) != RET_OK) {
777         return RET_ERR;
778     }
779     if (ReadDisplayGroupsInfo(pkt, userScreenInfo) != RET_OK) {
780         return RET_ERR;
781     }
782     if (!ChangeToOld(userScreenInfo)) {
783         return RET_ERR;
784     }
785     Printf(userScreenInfo);
786     for (auto &displayGroupInfo : oldDisplayGroupInfos_) {
787         WIN_MGR->UpdateDisplayInfoExtIfNeed(displayGroupInfo, true);
788     }
789     return RET_OK;
790 }
791 
ReadScreensInfo(NetPacket & pkt,UserScreenInfo & userScreenInfo)792 int32_t ServerMsgHandler::ReadScreensInfo(NetPacket &pkt, UserScreenInfo &userScreenInfo)
793 {
794     uint32_t num = 0;
795     pkt >> num;
796     if (num > MAX_SCREEN_SIZE) {
797         MMI_HILOGE("Too many screens, num:%{public}u", num);
798         return RET_ERR;
799     }
800     for (uint32_t i = 0; i < num; i++) {
801         ScreenInfo info;
802         pkt >> info.id >> info.uniqueId >> info.screenType >> info.width >> info.height >> info.physicalWidth
803             >> info.physicalHeight >> info.tpDirection >> info.dpi >> info.ppi >> info.rotation;
804         userScreenInfo.screens.push_back(info);
805     }
806     if (pkt.ChkRWError()) {
807         MMI_HILOGE("Read screens info error");
808         return RET_ERR;
809     }
810     return RET_OK;
811 }
812 
ReadDisplayGroupsInfo(NetPacket & pkt,UserScreenInfo & userScreenInfo)813 int32_t ServerMsgHandler::ReadDisplayGroupsInfo(NetPacket &pkt, UserScreenInfo &userScreenInfo)
814 {
815     uint32_t num = 0;
816     pkt >> num;
817     if (num > MAX_DISPLAY_GROUP_SIZE) {
818         MMI_HILOGE("Too many display groups, num:%{public}u", num);
819         return RET_ERR;
820     }
821     for (uint32_t i = 0; i < num; i++) {
822         DisplayGroupInfo info;
823         OLD::DisplayGroupInfo oldInfo;
824         pkt >> info.id >> info.name >> info.type >> info.mainDisplayId >> info.focusWindowId;
825         if (ReadDisplaysInfo(pkt, info) != RET_OK) {
826             return RET_ERR;
827         }
828         if (ReadWindowsInfo(pkt, info, oldInfo) != RET_OK) {
829             return RET_ERR;
830         }
831         userScreenInfo.displayGroups.push_back(info);
832         oldDisplayGroupInfos_.push_back(oldInfo);
833     }
834     return RET_OK;
835 }
836 
ReadDisplaysInfo(NetPacket & pkt,DisplayGroupInfo & displayGroupInfo)837 int32_t ServerMsgHandler::ReadDisplaysInfo(NetPacket &pkt, DisplayGroupInfo &displayGroupInfo)
838 {
839     uint32_t num = 0;
840     pkt >> num;
841     if (num > MAX_DISPLAY_SIZE) {
842         MMI_HILOGE("Too many displays, num:%{public}u", num);
843         return RET_ERR;
844     }
845     for (uint32_t i = 0; i < num; i++) {
846         DisplayInfo info;
847         pkt >> info.id >> info.x >> info.y >> info.width >> info.height >> info.dpi >> info.name
848             >> info.direction >> info.displayDirection >> info.displayMode >> info.transform
849             >> info.scalePercent >> info.expandHeight >> info.isCurrentOffScreenRendering
850             >> info.displaySourceMode >> info.oneHandX >> info.oneHandY >> info.screenArea >> info.rsId
851             >> info.offsetX >> info.offsetY >> info.pointerActiveWidth >> info.pointerActiveHeight;
852         displayGroupInfo.displaysInfo.push_back(info);
853         if (pkt.ChkRWError()) {
854             MMI_HILOGE("Packet read display info failed");
855             return RET_ERR;
856         }
857     }
858     return RET_OK;
859 }
860 
OnWindowGroupInfo(SessionPtr sess,NetPacket & pkt)861 int32_t ServerMsgHandler::OnWindowGroupInfo(SessionPtr sess, NetPacket &pkt)
862 {
863     CALL_DEBUG_ENTER;
864     CHKPR(sess, ERROR_NULL_POINTER);
865     int32_t tokenType = sess->GetTokenType();
866     if (tokenType != TokenType::TOKEN_NATIVE && tokenType != TokenType::TOKEN_SHELL &&
867         tokenType !=TokenType::TOKEN_SYSTEM_HAP) {
868         MMI_HILOGW("Not native or systemapp skip, pid:%{public}d tokenType:%{public}d", sess->GetPid(), tokenType);
869         return RET_ERR;
870     }
871     WindowGroupInfo windowGroupInfo;
872     pkt >> windowGroupInfo.focusWindowId >> windowGroupInfo.displayId;
873     uint32_t num = 0;
874     pkt >> num;
875     if (num > MAX_WINDOW_GROUP_INFO_SIZE) {
876         MMI_HILOGE("Invalid windowGroup info size:%{public}u", num);
877         return RET_ERR;
878     }
879     if (pkt.ChkRWError()) {
880         MMI_HILOGE("Packet read window group info failed");
881         return RET_ERR;
882     }
883     for (uint32_t i = 0; i < num; i++) {
884         WindowInfo info;
885         pkt >> info.id >> info.pid >> info.uid >> info.area >> info.defaultHotAreas
886             >> info.pointerHotAreas >> info.agentWindowId >> info.flags >> info.action
887             >> info.displayId >> info.groupId >> info.zOrder >> info.pointerChangeAreas >> info.transform
888             >> info.windowInputType >> info.privacyMode >> info.windowType >> info.isSkipSelfWhenShowOnVirtualScreen
889             >> info.windowNameType;
890         OnUiExtentionWindowInfo(pkt, info);
891         pkt >> info.rectChangeBySystem;
892         windowGroupInfo.windowsInfo.push_back(info);
893         if (pkt.ChkRWError()) {
894             MMI_HILOGE("Packet read display info failed");
895             return RET_ERR;
896         }
897     }
898     WIN_MGR->UpdateWindowInfo(windowGroupInfo);
899     return RET_OK;
900 }
901 
RegisterWindowStateErrorCallback(SessionPtr sess,NetPacket & pkt)902 int32_t ServerMsgHandler::RegisterWindowStateErrorCallback(SessionPtr sess, NetPacket &pkt)
903 {
904     CALL_DEBUG_ENTER;
905     CHKPR(sess, ERROR_NULL_POINTER);
906     int32_t tokenType = sess->GetTokenType();
907     if (tokenType != TokenType::TOKEN_NATIVE && tokenType != TokenType::TOKEN_SHELL &&
908         tokenType !=TokenType::TOKEN_SYSTEM_HAP) {
909         MMI_HILOGW("Not native or systemapp skip, pid:%{public}d tokenType:%{public}d", sess->GetPid(), tokenType);
910         return RET_ERR;
911     }
912     int32_t pid = sess->GetPid();
913     WIN_MGR->SetWindowStateNotifyPid(pid);
914     MMI_HILOGI("The pid:%{public}d", pid);
915     return RET_OK;
916 }
917 
918 #ifdef OHOS_BUILD_ENABLE_SECURITY_COMPONENT
OnEnhanceConfig(SessionPtr sess,NetPacket & pkt)919 int32_t ServerMsgHandler::OnEnhanceConfig(SessionPtr sess, NetPacket &pkt)
920 {
921     CHKPR(sess, ERROR_NULL_POINTER);
922     int32_t userId = sess->GetUid();
923     if (userId != SECURITY_COMPONENT_SERVICE_ID) {
924         MMI_HILOGE("Session is not security component service");
925         return RET_ERR;
926     }
927     uint32_t num = 0;
928     pkt >> num;
929     if (num > MAX_ENHANCE_CONFIG_SIZE) {
930         MMI_HILOGE("Invalid enhance data size:%{public}u", num);
931         return RET_ERR;
932     }
933     uint8_t cfg[num];
934     for (uint32_t i = 0; i < num; i++) {
935         pkt >> cfg[i];
936     }
937 
938     if (pkt.ChkRWError()) {
939         MMI_HILOGE("Packet read scinfo config failed");
940         return RET_ERR;
941     }
942     int32_t result = Security::SecurityComponent::SecCompEnhanceKit::SetEnhanceCfg(cfg, num);
943     if (result != 0) {
944         return RET_ERR;
945     }
946     return RET_OK;
947 }
948 #endif // OHOS_BUILD_ENABLE_SECURITY_COMPONENT
949 #if defined(OHOS_BUILD_ENABLE_INTERCEPTOR) || defined(OHOS_BUILD_ENABLE_MONITOR)
OnAddInputHandler(SessionPtr sess,InputHandlerType handlerType,HandleEventType eventType,int32_t priority,uint32_t deviceTags)950 int32_t ServerMsgHandler::OnAddInputHandler(SessionPtr sess, InputHandlerType handlerType,
951     HandleEventType eventType, int32_t priority, uint32_t deviceTags)
952 {
953     CHKPR(sess, ERROR_NULL_POINTER);
954     MMI_HILOGD("The handlerType:%{public}d", handlerType);
955 #ifdef OHOS_BUILD_ENABLE_INTERCEPTOR
956     if (handlerType == InputHandlerType::INTERCEPTOR) {
957         auto interceptorHandler = InputHandler->GetInterceptorHandler();
958         CHKPR(interceptorHandler, ERROR_NULL_POINTER);
959         return interceptorHandler->AddInputHandler(handlerType, eventType, priority, deviceTags, sess);
960     }
961 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR
962 #ifdef OHOS_BUILD_ENABLE_MONITOR
963     if (handlerType == InputHandlerType::MONITOR) {
964         auto monitorHandler = InputHandler->GetMonitorHandler();
965         CHKPR(monitorHandler, ERROR_NULL_POINTER);
966         return monitorHandler->AddInputHandler(handlerType, eventType, sess);
967     }
968 #endif // OHOS_BUILD_ENABLE_MONITOR
969     return RET_OK;
970 }
971 
OnRemoveInputHandler(SessionPtr sess,InputHandlerType handlerType,HandleEventType eventType,int32_t priority,uint32_t deviceTags)972 int32_t ServerMsgHandler::OnRemoveInputHandler(SessionPtr sess, InputHandlerType handlerType,
973     HandleEventType eventType, int32_t priority, uint32_t deviceTags)
974 {
975     CHKPR(sess, ERROR_NULL_POINTER);
976     MMI_HILOGD("OnRemoveInputHandler handlerType:%{public}d eventType:%{public}u", handlerType, eventType);
977 #ifdef OHOS_BUILD_ENABLE_INTERCEPTOR
978     if (handlerType == InputHandlerType::INTERCEPTOR) {
979         auto interceptorHandler = InputHandler->GetInterceptorHandler();
980         CHKPR(interceptorHandler, ERROR_NULL_POINTER);
981         interceptorHandler->RemoveInputHandler(handlerType, eventType, priority, deviceTags, sess);
982     }
983 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR
984 #ifdef OHOS_BUILD_ENABLE_MONITOR
985     if (handlerType == InputHandlerType::MONITOR) {
986         auto monitorHandler = InputHandler->GetMonitorHandler();
987         CHKPR(monitorHandler, ERROR_NULL_POINTER);
988         monitorHandler->RemoveInputHandler(handlerType, eventType, sess);
989         ANRMgr->RemoveTimersByType(sess, ANR_MONITOR);
990     }
991 #endif // OHOS_BUILD_ENABLE_MONITOR
992     return RET_OK;
993 }
994 
995 #endif // OHOS_BUILD_ENABLE_INTERCEPTOR || OHOS_BUILD_ENABLE_MONITOR
996 
OnAddGestureMonitor(SessionPtr sess,InputHandlerType handlerType,HandleEventType eventType,TouchGestureType gestureType,int32_t fingers)997 int32_t ServerMsgHandler::OnAddGestureMonitor(SessionPtr sess, InputHandlerType handlerType,
998     HandleEventType eventType, TouchGestureType gestureType, int32_t fingers)
999 {
1000 #ifdef OHOS_BUILD_ENABLE_MONITOR
1001     if (handlerType == InputHandlerType::MONITOR) {
1002         auto monitorHandler = InputHandler->GetMonitorHandler();
1003         CHKPR(monitorHandler, ERROR_NULL_POINTER);
1004         return monitorHandler->AddInputHandler(handlerType, eventType, sess, gestureType, fingers);
1005     }
1006 #endif // OHOS_BUILD_ENABLE_MONITOR
1007     return RET_OK;
1008 }
1009 
OnRemoveGestureMonitor(SessionPtr sess,InputHandlerType handlerType,HandleEventType eventType,TouchGestureType gestureType,int32_t fingers)1010 int32_t ServerMsgHandler::OnRemoveGestureMonitor(SessionPtr sess, InputHandlerType handlerType,
1011     HandleEventType eventType, TouchGestureType gestureType, int32_t fingers)
1012 {
1013 #ifdef OHOS_BUILD_ENABLE_MONITOR
1014     if (handlerType == InputHandlerType::MONITOR) {
1015         CHKPR(sess, ERROR_NULL_POINTER);
1016         auto monitorHandler = InputHandler->GetMonitorHandler();
1017         CHKPR(monitorHandler, ERROR_NULL_POINTER);
1018         monitorHandler->RemoveInputHandler(handlerType, eventType, sess, gestureType, fingers);
1019     }
1020 #endif // OHOS_BUILD_ENABLE_MONITOR
1021     return RET_OK;
1022 }
1023 
1024 #ifdef OHOS_BUILD_ENABLE_MONITOR
OnMarkConsumed(SessionPtr sess,int32_t eventId)1025 int32_t ServerMsgHandler::OnMarkConsumed(SessionPtr sess, int32_t eventId)
1026 {
1027     CHKPR(sess, ERROR_NULL_POINTER);
1028     auto monitorHandler = InputHandler->GetMonitorHandler();
1029     CHKPR(monitorHandler, ERROR_NULL_POINTER);
1030     monitorHandler->MarkConsumed(eventId, sess);
1031     return RET_OK;
1032 }
1033 #endif // OHOS_BUILD_ENABLE_MONITOR
1034 
ReadWindowsInfo(NetPacket & pkt,DisplayGroupInfo & displayGroupInfo,OLD::DisplayGroupInfo & oldDisplayGroupInfo)1035 int32_t ServerMsgHandler::ReadWindowsInfo(NetPacket &pkt, DisplayGroupInfo &displayGroupInfo,
1036     OLD::DisplayGroupInfo &oldDisplayGroupInfo)
1037 {
1038     uint32_t num = 0;
1039     pkt >> num;
1040     if (num > MAX_WINDOWS_SIZE) {
1041         MMI_HILOGE("Too many windows, num:%{public}u", num);
1042         return RET_ERR;
1043     }
1044     for (uint32_t i = 0; i < num; i++) {
1045             WindowInfo info;
1046             int32_t byteCount = 0;
1047             pkt >> info.id >> info.pid >> info.uid >> info.area >> info.defaultHotAreas
1048                 >> info.pointerHotAreas >> info.agentWindowId >> info.flags >> info.action
1049                 >> info.displayId >> info.groupId >> info.zOrder >> info.pointerChangeAreas >> info.transform
1050                 >> info.windowInputType >> info.privacyMode >> info.windowType
1051                 >> info.isSkipSelfWhenShowOnVirtualScreen >> info.windowNameType >> byteCount;
1052 
1053             OnUiExtentionWindowInfo(pkt, info);
1054             pkt >> info.rectChangeBySystem;
1055             displayGroupInfo.windowsInfo.push_back(info);
1056             oldDisplayGroupInfo.windowsInfo.push_back(info);
1057             if (pkt.ChkRWError()) {
1058                 MMI_HILOGE("read window info failed");
1059                 return RET_ERR;
1060             }
1061         }
1062     return RET_OK;
1063 }
1064 
ChangeToOld(const UserScreenInfo & userScreenInfo)1065 bool ServerMsgHandler::ChangeToOld(const UserScreenInfo& userScreenInfo)
1066 {
1067     if (userScreenInfo.displayGroups.size() != oldDisplayGroupInfos_.size()) {
1068         MMI_HILOGE("ChangeToOld size inconsistent, new size:%{public}zu, old size:%{public}zu",
1069             userScreenInfo.displayGroups.size(), oldDisplayGroupInfos_.size());
1070         return false;
1071     }
1072     size_t num = 0;
1073     for (auto &displayGroupInfo : userScreenInfo.displayGroups) {
1074         if (num >= oldDisplayGroupInfos_.size()) {
1075             MMI_HILOGE("num:%{public}zu", num);
1076             break;
1077         }
1078         oldDisplayGroupInfos_[num].groupId = displayGroupInfo.id;
1079         oldDisplayGroupInfos_[num].type = displayGroupInfo.type;
1080         oldDisplayGroupInfos_[num].mainDisplayId = displayGroupInfo.mainDisplayId;
1081         oldDisplayGroupInfos_[num].focusWindowId = displayGroupInfo.focusWindowId;
1082         oldDisplayGroupInfos_[num].currentUserId = userScreenInfo.userId;
1083         ChangeToOld(num, displayGroupInfo.displaysInfo, userScreenInfo.screens);
1084         num++;
1085     }
1086     return true;
1087 }
1088 
ChangeToOld(size_t num,const std::vector<DisplayInfo> & displaysInfo,const std::vector<ScreenInfo> & screens)1089 void ServerMsgHandler::ChangeToOld(size_t num, const std::vector<DisplayInfo>& displaysInfo,
1090     const std::vector<ScreenInfo>& screens)
1091 {
1092     for (auto &display : displaysInfo) {
1093         OLD::DisplayInfo oldDisplay;
1094         oldDisplay = {
1095             .id = display.id,
1096             .x = display.x,
1097             .y = display.y,
1098             .dpi = display.dpi,
1099             .name = display.name,
1100             .direction = display.direction,
1101             .displayDirection = display.displayDirection,
1102             .displayMode = display.displayMode,
1103             .transform = display.transform,
1104             .offsetX = display.offsetX,
1105             .offsetY = display.offsetY,
1106             .scalePercent = display.scalePercent,
1107             .expandHeight = display.expandHeight,
1108             .isCurrentOffScreenRendering = display.isCurrentOffScreenRendering,
1109             .displaySourceMode = display.displaySourceMode,
1110             .oneHandX = display.oneHandX,
1111             .oneHandY = display.oneHandY,
1112             .validWidth = display.width,
1113             .validHeight = display.height,
1114             .pointerActiveWidth = display.pointerActiveWidth,
1115             .pointerActiveHeight = display.pointerActiveHeight,
1116             .rsId = display.rsId,
1117         };
1118         for (auto &screen : screens) {
1119             if (screen.id == display.screenArea.id) {
1120                 oldDisplay.uniq = screen.uniqueId;
1121                 oldDisplay.ppi = screen.ppi;
1122                 oldDisplay.screenRealWidth = screen.width;
1123                 oldDisplay.screenRealHeight = screen.height;
1124                 oldDisplay.screenRealDPI = screen.dpi;
1125                 oldDisplay.fixedDirection = screen.tpDirection;
1126                 oldDisplay.physicalWidth = screen.physicalWidth;
1127                 oldDisplay.physicalHeight = screen.physicalHeight;
1128                 if (display.screenArea.area.width > 0 && display.screenArea.area.height > 0) {
1129                     if (oldDisplay.direction == Direction::DIRECTION0
1130                         || oldDisplay.direction == Direction::DIRECTION180) {
1131                         oldDisplay.width = static_cast<int32_t>(static_cast<double>(display.width) /
1132                             static_cast<double>(display.screenArea.area.width) * static_cast<double>(screen.width));
1133                         oldDisplay.height = static_cast<int32_t>(static_cast<double>(display.height) /
1134                             static_cast<double>(display.screenArea.area.height) * static_cast<double>(screen.height));
1135                     }
1136                     if (oldDisplay.direction == Direction::DIRECTION90
1137                         || oldDisplay.direction == Direction::DIRECTION270) {
1138                         oldDisplay.width = static_cast<int32_t>(static_cast<double>(display.width) /
1139                             static_cast<double>(display.screenArea.area.height) *static_cast<double>(screen.height));
1140                         oldDisplay.height = static_cast<int32_t>(static_cast<double>(display.height) /
1141                             static_cast<double>(display.screenArea.area.width) * static_cast<double>(screen.width));
1142                     }
1143                 }
1144                 break;
1145             }
1146         }
1147         if (num >= oldDisplayGroupInfos_.size()) {
1148             MMI_HILOGE("num:%{public}zu", num);
1149             break;
1150         }
1151         oldDisplayGroupInfos_[num].displaysInfo.emplace_back(oldDisplay);
1152     }
1153 }
1154 
Printf(const UserScreenInfo & userScreenInfo)1155 void ServerMsgHandler::Printf(const UserScreenInfo& userScreenInfo)
1156 {
1157     MMI_HILOGD("userScreenInfo-----------");
1158     size_t num = 0;
1159     for (const auto &item : userScreenInfo.screens) {
1160         MMI_HILOGD("screen%{public}zu, id:%{public}d, screenType:%{public}d, width:%{public}d, "
1161                    "height:%{public}d, physicalWidth:%{public}d, physicalHeight:%{public}d, tpDirection:%{public}d, "
1162                    "dpi%{public}d, ppi%{public}d, rotation%{public}d", num, item.id,
1163                    item.screenType, item.width, item.height, item.physicalWidth, item.physicalHeight, item.tpDirection,
1164                    item.dpi, item.ppi, item.rotation);
1165         num++;
1166     }
1167     num = 0;
1168     for (const auto &item : userScreenInfo.displayGroups) {
1169         MMI_HILOGD("displayGroups%{public}zu,id:%{public}d,type:%{public}d, mainDisplayId:%{public}d,"
1170             "focusWindowId:%{public}d",
1171             num, item.id, item.type, item.mainDisplayId, item.focusWindowId);
1172         size_t numDisplayInfo = 0;
1173         for (const auto &itemDisplay : item.displaysInfo) {
1174             MMI_HILOGD("displays%{public}zu,id:%{public}d,x:%{private}d,y:%{private}d,width:%{public}d,"
1175                 "height:%{public}d,dpi:%{public}d,direction:%{public}d,displayDirection:%{public}d,"
1176                 "displayMode:%{public}d,scalePercent:%{public}d, expandHeight:%{public}d,"
1177                 "isCurrentOffScreenRendering:%{public}d,displaySourceMode:%{public}d,oneHandX:%{private}d,"
1178                 "oneHandY:%{private}d, screenArea:{%{private}d:{%{private}d,%{public}d,%{public}d,%{public}d},"
1179                 "rsId:%{public}" PRIu64 "},offsetX:%{private}d,offsetY:%{private}d,pointerActiveWidth:%{public}d,"
1180                 "pointerActiveHeight:%{public}d,transform:",
1181                 numDisplayInfo, itemDisplay.id, itemDisplay.x, itemDisplay.y, itemDisplay.width, itemDisplay.height,
1182                 itemDisplay.dpi, itemDisplay.direction, itemDisplay.displayDirection,
1183                 itemDisplay.displayMode, itemDisplay.scalePercent, itemDisplay.expandHeight,
1184                 itemDisplay.isCurrentOffScreenRendering, itemDisplay.displaySourceMode, itemDisplay.oneHandX,
1185                 itemDisplay.oneHandY, itemDisplay.screenArea.id, itemDisplay.screenArea.area.x,
1186                 itemDisplay.screenArea.area.y, itemDisplay.screenArea.area.width, itemDisplay.screenArea.area.height,
1187                 itemDisplay.rsId, itemDisplay.offsetX, itemDisplay.offsetY,
1188                 itemDisplay.pointerActiveWidth, itemDisplay.pointerActiveHeight);
1189             for (auto& transform : itemDisplay.transform) {
1190                 MMI_HILOGD("%{public}f,", transform);
1191             }
1192             numDisplayInfo++;
1193         }
1194         num++;
1195     }
1196 }
1197 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
OnMoveMouse(int32_t offsetX,int32_t offsetY)1198 int32_t ServerMsgHandler::OnMoveMouse(int32_t offsetX, int32_t offsetY)
1199 {
1200     CALL_DEBUG_ENTER;
1201     if (MouseEventHdr->NormalizeMoveMouse(offsetX, offsetY)) {
1202         auto pointerEvent = MouseEventHdr->GetPointerEvent();
1203         CHKPR(pointerEvent, ERROR_NULL_POINTER);
1204         auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
1205         CHKPR(inputEventNormalizeHandler, ERROR_NULL_POINTER);
1206         inputEventNormalizeHandler->HandlePointerEvent(pointerEvent);
1207         MMI_HILOGD("Mouse movement message processed successfully");
1208     }
1209     return RET_OK;
1210 }
1211 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
1212 
1213 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
OnSubscribeKeyEvent(IUdsServer * server,int32_t pid,int32_t subscribeId,const std::shared_ptr<KeyOption> option)1214 int32_t ServerMsgHandler::OnSubscribeKeyEvent(IUdsServer *server, int32_t pid,
1215     int32_t subscribeId, const std::shared_ptr<KeyOption> option)
1216 {
1217     CALL_DEBUG_ENTER;
1218     CHKPR(server, ERROR_NULL_POINTER);
1219     auto sess = server->GetSessionByPid(pid);
1220     CHKPR(sess, ERROR_NULL_POINTER);
1221     auto subscriberHandler = InputHandler->GetSubscriberHandler();
1222     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1223     return subscriberHandler->SubscribeKeyEvent(sess, subscribeId, option);
1224 }
1225 
OnUnsubscribeKeyEvent(IUdsServer * server,int32_t pid,int32_t subscribeId)1226 int32_t ServerMsgHandler::OnUnsubscribeKeyEvent(IUdsServer *server, int32_t pid, int32_t subscribeId)
1227 {
1228     CALL_DEBUG_ENTER;
1229     CHKPR(server, ERROR_NULL_POINTER);
1230     auto sess = server->GetSessionByPid(pid);
1231     CHKPR(sess, ERROR_NULL_POINTER);
1232     auto subscriberHandler = InputHandler->GetSubscriberHandler();
1233     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1234     return subscriberHandler->UnsubscribeKeyEvent(sess, subscribeId);
1235 }
1236 
OnSubscribeHotkey(IUdsServer * server,int32_t pid,int32_t subscribeId,const std::shared_ptr<KeyOption> option)1237 int32_t ServerMsgHandler::OnSubscribeHotkey(IUdsServer *server, int32_t pid,
1238     int32_t subscribeId, const std::shared_ptr<KeyOption> option)
1239 {
1240 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
1241     CALL_DEBUG_ENTER;
1242     CHKPR(server, ERROR_NULL_POINTER);
1243     auto sess = server->GetSessionByPid(pid);
1244     CHKPR(sess, ERROR_NULL_POINTER);
1245     auto subscriberHandler = InputHandler->GetSubscriberHandler();
1246     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1247     return subscriberHandler->SubscribeHotkey(sess, subscribeId, option);
1248 #else
1249     MMI_HILOGI("OnSubscribeHotkey function does not support");
1250     return ERROR_UNSUPPORT;
1251 #endif // SHORTCUT_KEY_MANAGER_ENABLED
1252 }
1253 
OnUnsubscribeHotkey(IUdsServer * server,int32_t pid,int32_t subscribeId)1254 int32_t ServerMsgHandler::OnUnsubscribeHotkey(IUdsServer *server, int32_t pid, int32_t subscribeId)
1255 {
1256 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
1257     CALL_DEBUG_ENTER;
1258     CHKPR(server, ERROR_NULL_POINTER);
1259     auto sess = server->GetSessionByPid(pid);
1260     CHKPR(sess, ERROR_NULL_POINTER);
1261     auto subscriberHandler = InputHandler->GetSubscriberHandler();
1262     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1263     return subscriberHandler->UnsubscribeHotkey(sess, subscribeId);
1264 #else
1265     MMI_HILOGI("OnUnsubscribeHotkey function does not support");
1266     return ERROR_UNSUPPORT;
1267 #endif // SHORTCUT_KEY_MANAGER_ENABLED
1268 }
1269 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1270 
1271 #ifdef OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
SubscribeKeyMonitor(int32_t session,const KeyMonitorOption & keyOption)1272 int32_t ServerMsgHandler::SubscribeKeyMonitor(int32_t session, const KeyMonitorOption &keyOption)
1273 {
1274     if ((PRODUCT_TYPE != "phone") && (PRODUCT_TYPE != "tablet") && (PRODUCT_TYPE != "2in1")) {
1275         MMI_HILOGW("Does not support subscription of key monitor on %{public}s", PRODUCT_TYPE.c_str());
1276         return -CAPABILITY_NOT_SUPPORTED;
1277     }
1278     KeyMonitorManager::Monitor monitor {
1279         .session_ = session,
1280         .key_ = keyOption.GetKey(),
1281         .action_ = keyOption.GetAction(),
1282         .isRepeat_ = keyOption.IsRepeat(),
1283     };
1284     return KEY_MONITOR_MGR->AddMonitor(monitor);
1285 }
1286 
UnsubscribeKeyMonitor(int32_t session,const KeyMonitorOption & keyOption)1287 int32_t ServerMsgHandler::UnsubscribeKeyMonitor(int32_t session, const KeyMonitorOption &keyOption)
1288 {
1289     if ((PRODUCT_TYPE != "phone") && (PRODUCT_TYPE != "tablet") && (PRODUCT_TYPE != "2in1")) {
1290         MMI_HILOGW("Does not support subscription of key monitor on %{public}s", PRODUCT_TYPE.c_str());
1291         return -CAPABILITY_NOT_SUPPORTED;
1292     }
1293     KeyMonitorManager::Monitor monitor {
1294         .session_ = session,
1295         .key_ = keyOption.GetKey(),
1296         .action_ = keyOption.GetAction(),
1297         .isRepeat_ = keyOption.IsRepeat(),
1298     };
1299     KEY_MONITOR_MGR->RemoveMonitor(monitor);
1300     return RET_OK;
1301 }
1302 #endif // OHOS_BUILD_ENABLE_KEY_PRESSED_HANDLER
1303 
1304 #ifdef OHOS_BUILD_ENABLE_SWITCH
OnSubscribeSwitchEvent(IUdsServer * server,int32_t pid,int32_t subscribeId,int32_t switchType)1305 int32_t ServerMsgHandler::OnSubscribeSwitchEvent(
1306     IUdsServer *server, int32_t pid, int32_t subscribeId, int32_t switchType)
1307 {
1308     CALL_DEBUG_ENTER;
1309     CHKPR(server, ERROR_NULL_POINTER);
1310     auto sess = server->GetSessionByPid(pid);
1311     CHKPR(sess, ERROR_NULL_POINTER);
1312     auto subscriberHandler = InputHandler->GetSwitchSubscriberHandler();
1313     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1314     return subscriberHandler->SubscribeSwitchEvent(sess, subscribeId, switchType);
1315 }
1316 
OnUnsubscribeSwitchEvent(IUdsServer * server,int32_t pid,int32_t subscribeId)1317 int32_t ServerMsgHandler::OnUnsubscribeSwitchEvent(IUdsServer *server, int32_t pid, int32_t subscribeId)
1318 {
1319     CALL_DEBUG_ENTER;
1320     CHKPR(server, ERROR_NULL_POINTER);
1321     auto sess = server->GetSessionByPid(pid);
1322     CHKPR(sess, ERROR_NULL_POINTER);
1323     auto subscriberHandler = InputHandler->GetSwitchSubscriberHandler();
1324     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1325     return subscriberHandler->UnsubscribeSwitchEvent(sess, subscribeId);
1326 }
1327 
OnQuerySwitchStatus(int32_t switchType,int32_t & state)1328 int32_t ServerMsgHandler::OnQuerySwitchStatus(int32_t switchType, int32_t& state)
1329 {
1330     CALL_DEBUG_ENTER;
1331     auto subscriberHandler = InputHandler->GetSwitchSubscriberHandler();
1332     CHKPR(subscriberHandler, ERROR_NULL_POINTER);
1333     return subscriberHandler->QuerySwitchStatus(switchType, state);
1334 }
1335 #endif // OHOS_BUILD_ENABLE_SWITCH
1336 
OnSubscribeLongPressEvent(IUdsServer * server,int32_t pid,int32_t subscribeId,const LongPressRequest & longPressRequest)1337 int32_t ServerMsgHandler::OnSubscribeLongPressEvent(IUdsServer *server, int32_t pid, int32_t subscribeId,
1338     const LongPressRequest &longPressRequest)
1339 {
1340     CALL_DEBUG_ENTER;
1341     CHKPR(server, ERROR_NULL_POINTER);
1342     auto sess = server->GetSessionByPid(pid);
1343     CHKPR(sess, ERROR_NULL_POINTER);
1344     return LONG_PRESS_EVENT_HANDLER->SubscribeLongPressEvent(sess, subscribeId, longPressRequest);
1345 }
1346 
OnUnsubscribeLongPressEvent(IUdsServer * server,int32_t pid,int32_t subscribeId)1347 int32_t ServerMsgHandler::OnUnsubscribeLongPressEvent(IUdsServer *server, int32_t pid, int32_t subscribeId)
1348 {
1349     CALL_DEBUG_ENTER;
1350     CHKPR(server, ERROR_NULL_POINTER);
1351     auto sess = server->GetSessionByPid(pid);
1352     CHKPR(sess, ERROR_NULL_POINTER);
1353     return LONG_PRESS_EVENT_HANDLER->UnsubscribeLongPressEvent(sess, subscribeId);
1354 }
1355 
1356 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH) || defined(OHOS_BUILD_ENABLE_KEYBOARD)
AddInputEventFilter(sptr<IEventFilter> filter,int32_t filterId,int32_t priority,uint32_t deviceTags,int32_t clientPid)1357 int32_t ServerMsgHandler::AddInputEventFilter(sptr<IEventFilter> filter,
1358     int32_t filterId, int32_t priority, uint32_t deviceTags, int32_t clientPid)
1359 {
1360     auto filterHandler = InputHandler->GetFilterHandler();
1361     CHKPR(filterHandler, ERROR_NULL_POINTER);
1362     return filterHandler->AddInputEventFilter(filter, filterId, priority, deviceTags, clientPid);
1363 }
1364 
RemoveInputEventFilter(int32_t clientPid,int32_t filterId)1365 int32_t ServerMsgHandler::RemoveInputEventFilter(int32_t clientPid, int32_t filterId)
1366 {
1367     auto filterHandler = InputHandler->GetFilterHandler();
1368     CHKPR(filterHandler, ERROR_NULL_POINTER);
1369     return filterHandler->RemoveInputEventFilter(clientPid, filterId);
1370 }
1371 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH || OHOS_BUILD_ENABLE_KEYBOARD
1372 
1373 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
SetShieldStatus(int32_t shieldMode,bool isShield)1374 int32_t ServerMsgHandler::SetShieldStatus(int32_t shieldMode, bool isShield)
1375 {
1376     return KeyEventHdr->SetShieldStatus(shieldMode, isShield);
1377 }
1378 
GetShieldStatus(int32_t shieldMode,bool & isShield)1379 int32_t ServerMsgHandler::GetShieldStatus(int32_t shieldMode, bool &isShield)
1380 {
1381     return KeyEventHdr->GetShieldStatus(shieldMode, isShield);
1382 }
1383 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1384 
LaunchAbility()1385 void ServerMsgHandler::LaunchAbility()
1386 {
1387     CALL_DEBUG_ENTER;
1388 #ifndef OHOS_BUILD_ENABLE_WATCH
1389     AUTH_DIALOG.ConnectSystemUi();
1390 #endif // OHOS_BUILD_ENABLE_WATCH
1391 }
1392 
OnAuthorize(bool isAuthorize)1393 int32_t ServerMsgHandler::OnAuthorize(bool isAuthorize)
1394 {
1395     CALL_DEBUG_ENTER;
1396     if (isAuthorize) {
1397         auto state = AUTHORIZE_HELPER->GetAuthorizeState();
1398         int32_t authorPid = AUTHORIZE_HELPER->GetAuthorizePid();
1399         MMI_HILOGE("OnAuthorize not has authorizing s:%{public}d, authPid:%{public}d",
1400             state, authorPid);
1401         if (state == AuthorizeState::STATE_UNAUTHORIZE) {
1402             MMI_HILOGE("Current not has authorizing");
1403             return ERR_OK;
1404         }
1405         if (state == AuthorizeState::STATE_UNAUTHORIZE) {
1406             MMI_HILOGE("The injection permission has been granted. authPid:%{public}d ", authorPid);
1407             return ERR_OK;
1408         }
1409         InjectNoticeInfo noticeInfo;
1410         noticeInfo.pid = authorPid;
1411         AddInjectNotice(noticeInfo);
1412         auto result = AUTHORIZE_HELPER->AddAuthorizeProcess(authorPid, [&] (int32_t pid) {
1413                 CloseInjectNotice(pid);
1414         });
1415         if (result != RET_OK) {
1416             MMI_HILOGI("Authorize process failed, pid:%{public}d", authorPid);
1417         }
1418         MMI_HILOGD("Agree to apply injection,pid:%{public}d", authorPid);
1419         return ERR_OK;
1420     }
1421 
1422     auto state = AUTHORIZE_HELPER->GetAuthorizeState();
1423     int32_t curAuthPid = AUTHORIZE_HELPER->GetAuthorizePid();
1424     MMI_HILOGD("Reject application injection,s:%{public}d, authPid:%{public}d",
1425         state, curAuthPid);
1426     if (state != AuthorizeState::STATE_UNAUTHORIZE) {
1427         MMI_HILOGI("Cancel injection right,pid:%{public}d", curAuthPid);
1428         AUTHORIZE_HELPER->CancelAuthorize(curAuthPid);
1429         if (state == AuthorizeState::STATE_SELECTION_AUTHORIZE) {
1430             AUTH_DIALOG.CloseDialog();
1431         } else {
1432             CloseInjectNotice(AUTHORIZE_HELPER->GetAuthorizePid());
1433         }
1434     }
1435     return ERR_OK;
1436 }
1437 
OnCancelInjection(int32_t callPid)1438 int32_t ServerMsgHandler::OnCancelInjection(int32_t callPid)
1439 {
1440     CALL_DEBUG_ENTER;
1441     auto state = AUTHORIZE_HELPER->GetAuthorizeState();
1442     int32_t curAuthPid = AUTHORIZE_HELPER->GetAuthorizePid();
1443     MMI_HILOGD("Cancel application injection,s:%{public}d, authPid:%{public}d",
1444         state, curAuthPid);
1445     if (state != AuthorizeState::STATE_UNAUTHORIZE) {
1446         if (callPid != curAuthPid) {
1447             MMI_HILOGW("Authorized pid not callPid");
1448             return COMMON_PERMISSION_CHECK_ERROR;
1449         }
1450         AUTHORIZE_HELPER->CancelAuthorize(curAuthPid);
1451         if (state == AuthorizeState::STATE_SELECTION_AUTHORIZE) {
1452             AUTH_DIALOG.CloseDialog();
1453         } else {
1454             CloseInjectNotice(AUTHORIZE_HELPER->GetAuthorizePid());
1455         }
1456     }
1457     return ERR_OK;
1458 }
1459 
RequestInjection(const int32_t callingPid,int32_t & status,int32_t & reqId)1460 int32_t ServerMsgHandler::RequestInjection(const int32_t callingPid, int32_t &status, int32_t &reqId)
1461 {
1462     CALL_DEBUG_ENTER;
1463     if (!IsPC()) {
1464         return ERROR_DEVICE_NOT_SUPPORTED;
1465     }
1466     auto ret = QueryAuthorizedStatus(callingPid, status);
1467     MMI_HILOGD("QueryAuthorizedStatus,%{public}d,%{public}d,%{public}d",
1468         ret, callingPid, status);
1469     if (ret != ERR_OK) {
1470         MMI_HILOGE("QueryAuthorizedStatus,%{public}d,%{public}d", ret, callingPid);
1471         return ret;
1472     }
1473     if (static_cast<AUTHORIZE_QUERY_STATE>(status) != AUTHORIZE_QUERY_STATE::UNAUTHORIZED) {
1474         return ERR_OK;
1475     }
1476     if (CheckForRequestInjectionFrequentAccess(callingPid, QUERY_AUTHORIZE_MAX_INTERVAL_TIME)) {
1477         return ERROR_OPERATION_FREQUENT;
1478     }
1479     LaunchAbility();
1480     AuthorizeExitCallback fnCallback = [&] (int32_t pid) {
1481         MMI_HILOGI("User not authorized to inject %{public}d", pid);
1482         AUTH_DIALOG.CloseDialog();
1483     };
1484     reqId = GetRequestInjectionCallbackReqId();
1485     return AUTHORIZE_HELPER->AddAuthorizeProcess(callingPid, fnCallback, reqId);
1486 }
1487 
QueryAuthorizedStatus(const int32_t callingPid,int32_t & status)1488 int32_t ServerMsgHandler::QueryAuthorizedStatus(const int32_t callingPid, int32_t &status)
1489 {
1490     CALL_DEBUG_ENTER;
1491     auto state = AUTHORIZE_HELPER->GetAuthorizeState();
1492     if (state == AuthorizeState::STATE_UNAUTHORIZE) {
1493         status = static_cast<int32_t>(AUTHORIZE_QUERY_STATE::UNAUTHORIZED);
1494         return ERR_OK;
1495     }
1496     int32_t curAuthPid = AUTHORIZE_HELPER->GetAuthorizePid();
1497     if (curAuthPid == callingPid) {
1498         if (state == AuthorizeState::STATE_SELECTION_AUTHORIZE) {
1499             status = static_cast<int32_t>(AUTHORIZE_QUERY_STATE::CURRENT_PID_IN_AUTHORIZATION_SELECTION);
1500         } else {
1501             status = static_cast<int32_t>(AUTHORIZE_QUERY_STATE::CURRENT_PID_AUTHORIZED);
1502         }
1503         return ERR_OK;
1504     }
1505     if (state == AuthorizeState::STATE_SELECTION_AUTHORIZE) {
1506         status = static_cast<int32_t>(AUTHORIZE_QUERY_STATE::OTHER_PID_IN_AUTHORIZATION_SELECTION);
1507     } else {
1508         status = static_cast<int32_t>(AUTHORIZE_QUERY_STATE::OTHER_PID_AUTHORIZED);
1509     }
1510     return ERR_OK;
1511 }
1512 
IsPC() const1513 bool ServerMsgHandler::IsPC() const
1514 {
1515     return PRODUCT_TYPE == PRODUCT_TYPE_PC;
1516 }
1517 
GetRequestInjectionCallbackReqId()1518 int32_t ServerMsgHandler::GetRequestInjectionCallbackReqId()
1519 {
1520     static std::atomic<int32_t> reqId(1);
1521     if (reqId >= INT32_MAX - 1) {
1522         reqId = 1;
1523         return reqId;
1524     }
1525     return reqId.fetch_add(1);
1526 }
1527 
CheckForRequestInjectionFrequentAccess(int32_t callingPid,int64_t interval)1528 bool ServerMsgHandler::CheckForRequestInjectionFrequentAccess(int32_t callingPid, int64_t interval)
1529 {
1530     CALL_DEBUG_ENTER;
1531     int64_t curTimestamp = GetMillisTime();
1532     for (auto it = mapQueryAuthorizeLastTimestamp_.begin(); it != mapQueryAuthorizeLastTimestamp_.end();) {
1533         if (curTimestamp - it->second >= interval) {
1534             MMI_HILOGD("requestInjection %{public}" PRId64",%{public}" PRId64",%{public}" PRId64"",
1535             curTimestamp, it->second, curTimestamp - it->second);
1536             mapQueryAuthorizeLastTimestamp_.erase(it++);
1537         } else {
1538             it++;
1539         }
1540     }
1541     auto itFind = mapQueryAuthorizeLastTimestamp_.find(callingPid);
1542     if (itFind == mapQueryAuthorizeLastTimestamp_.end()) {
1543         MMI_HILOGD("requestInjection %{public}d", callingPid);
1544         mapQueryAuthorizeLastTimestamp_.insert(std::make_pair(callingPid, curTimestamp));
1545         return false;
1546     }
1547     return true;
1548 }
1549 
SetWindowInfo(int32_t infoId,WindowInfo & info)1550 void ServerMsgHandler::SetWindowInfo(int32_t infoId, WindowInfo &info)
1551 {
1552     CALL_DEBUG_ENTER;
1553     if (transparentWins_.find(infoId) == transparentWins_.end()) {
1554         MMI_HILOGE("The infoId is Invalid, infoId:%{public}d", infoId);
1555         return;
1556     }
1557     info.pixelMap = transparentWins_[infoId].get();
1558 }
1559 
SetPixelMapData(int32_t infoId,void * pixelMap)1560 int32_t ServerMsgHandler::SetPixelMapData(int32_t infoId, void *pixelMap) __attribute__((no_sanitize("cfi")))
1561 {
1562     CALL_DEBUG_ENTER;
1563     if (infoId < 0 || pixelMap == nullptr) {
1564         MMI_HILOGE("The infoId is invalid or pixelMap is nullptr");
1565         return ERR_INVALID_VALUE;
1566     }
1567 
1568     WIN_MGR->SetPixelMapData(infoId, pixelMap);
1569     return RET_OK;
1570 }
1571 
InitInjectNoticeSource()1572 bool ServerMsgHandler::InitInjectNoticeSource()
1573 {
1574     CALL_DEBUG_ENTER;
1575     MMI_HILOGD("Init InjectNoticeSource enter");
1576     if (injectNotice_ == nullptr) {
1577         injectNotice_ = std::make_shared<InjectNoticeManager>();
1578     }
1579     MMI_HILOGD("Injectnotice StartNoticeAbility end");
1580     if (!injectNotice_->IsAbilityStart()) {
1581         MMI_HILOGD("Injectnotice StartNoticeAbility begin");
1582         bool isStart = injectNotice_->StartNoticeAbility();
1583         if (!isStart) {
1584             MMI_HILOGE("Injectnotice StartNoticeAbility isStart:%{public}d", isStart);
1585             return false;
1586         }
1587         MMI_HILOGD("Injectnotice StartNoticeAbility end");
1588     }
1589     auto connection = injectNotice_->GetConnection();
1590     CHKPF(connection);
1591     if (!connection->IsConnected()) {
1592         MMI_HILOGD("Injectnotice ConnectNoticeSrv begin");
1593         bool isConnect = injectNotice_->ConnectNoticeSrv();
1594         if (!isConnect) {
1595             MMI_HILOGD("Injectnotice ConnectNoticeSrv isConnect:%{public}d", isConnect);
1596             return false;
1597         }
1598         MMI_HILOGD("Injectnotice ConnectNoticeSrv end");
1599     }
1600     MMI_HILOGD("Injectnotice InitInjectNoticeSource end");
1601     return true;
1602 }
1603 
AddInjectNotice(const InjectNoticeInfo & noticeInfo)1604 bool ServerMsgHandler::AddInjectNotice(const InjectNoticeInfo &noticeInfo)
1605 {
1606     CALL_DEBUG_ENTER;
1607     bool isInit = InitInjectNoticeSource();
1608     if (!isInit) {
1609         MMI_HILOGE("InitinjectNotice_ Source error");
1610         return false;
1611     }
1612     MMI_HILOGD("SendNotice submit begin");
1613     ffrt::submit([this, noticeInfo] {
1614         MMI_HILOGD("SendNotice submit enter");
1615         CHKPV(injectNotice_);
1616         auto pConnect = injectNotice_->GetConnection();
1617         CHKPV(pConnect);
1618         int32_t timeSecond = 0;
1619         while (timeSecond <= SEND_NOTICE_OVERTIME) {
1620             bool isConnect = pConnect->IsConnected();
1621             MMI_HILOGD("SendNotice %{public}d", isConnect);
1622             if (isConnect) {
1623                 MMI_HILOGD("SendNotice begin");
1624                 pConnect->SendNotice(noticeInfo);
1625                 break;
1626             }
1627             timeSecond += 1;
1628             sleep(1);
1629         }
1630         MMI_HILOGD("SendNotice submit leave");
1631     });
1632     return true;
1633 }
1634 
CloseInjectNotice(int32_t pid)1635 bool ServerMsgHandler::CloseInjectNotice(int32_t pid)
1636 {
1637     CALL_DEBUG_ENTER;
1638     bool isInit = InitInjectNoticeSource();
1639     if (!isInit) {
1640         MMI_HILOGE("InitinjectNotice_ Source error");
1641         return false;
1642     }
1643     MMI_HILOGD("CloseNotice submit begin");
1644     InjectNoticeInfo noticeInfo;
1645     noticeInfo.pid = pid;
1646     ffrt::submit([this, noticeInfo] {
1647         MMI_HILOGD("CloseNotice submit enter");
1648         CHKPV(injectNotice_);
1649         auto pConnect = injectNotice_->GetConnection();
1650         CHKPV(pConnect);
1651         int32_t timeSecond = 0;
1652         while (timeSecond <= SEND_NOTICE_OVERTIME) {
1653             bool isConnect = pConnect->IsConnected();
1654             MMI_HILOGD("CloseNotice %{public}d", isConnect);
1655             if (isConnect) {
1656                 MMI_HILOGD("CloseNotice begin");
1657                 pConnect->CancelNotice(noticeInfo);
1658                 break;
1659             }
1660             timeSecond += 1;
1661             sleep(1);
1662         }
1663         MMI_HILOGD("CloseNotice submit leave");
1664     });
1665     return true;
1666 }
1667 
OnTransferBinderClientSrv(const sptr<IRemoteObject> & binderClientObject,int32_t pid)1668 int32_t ServerMsgHandler::OnTransferBinderClientSrv(const sptr<IRemoteObject> &binderClientObject, int32_t pid)
1669 {
1670     CALL_DEBUG_ENTER;
1671     bool bRet = clientDeathHandler_.RegisterClientDeathRecipient(binderClientObject, pid);
1672     if (!bRet) {
1673         MMI_HILOGE("Failed to registerClientDeathRecipient");
1674         return RET_ERR;
1675     }
1676     return ERR_OK;
1677 }
1678 
NativeInjectCheck(int32_t pid)1679 int32_t ServerMsgHandler::NativeInjectCheck(int32_t pid)
1680 {
1681     CALL_DEBUG_ENTER;
1682     if (PRODUCT_TYPE != PRODUCT_TYPE_PC) {
1683         MMI_HILOGW("Current device has no permission");
1684         return COMMON_PERMISSION_CHECK_ERROR;
1685     }
1686     bool screenLocked = DISPLAY_MONITOR->GetScreenLocked();
1687     if (screenLocked) {
1688         MMI_HILOGW("Screen locked, no permission");
1689         return COMMON_PERMISSION_CHECK_ERROR;
1690     }
1691     if (pid <= 0) {
1692         MMI_HILOGW("Invalid process id pid:%{public}d", pid);
1693         return COMMON_PERMISSION_CHECK_ERROR;
1694     }
1695     auto state = AUTHORIZE_HELPER->GetAuthorizeState();
1696     MMI_HILOGI("The process is already being processed,s:%{public}d,pid:%{public}d,inputPid:%{public}d",
1697         state, AUTHORIZE_HELPER->GetAuthorizePid(), pid);
1698     if (state == AuthorizeState::STATE_UNAUTHORIZE) {
1699         LaunchAbility();
1700         AuthorizeExitCallback fnCallback = [&] (int32_t pid) {
1701             MMI_HILOGI("User not authorized to inject pid:%{public}d", pid);
1702             AUTH_DIALOG.CloseDialog();
1703         };
1704         AUTHORIZE_HELPER->AddAuthorizeProcess(pid, fnCallback);
1705         return COMMON_PERMISSION_CHECK_ERROR;
1706     }
1707 
1708     if (state == AuthorizeState::STATE_SELECTION_AUTHORIZE) {
1709         if (pid == AUTHORIZE_HELPER->GetAuthorizePid()) {
1710             MMI_HILOGI("The current PID is waiting for user authorization");
1711         } else {
1712             MMI_HILOGI("Another PID is waiting for user authorization");
1713         }
1714         return COMMON_PERMISSION_CHECK_ERROR;
1715     }
1716 
1717     // Currently, a process is authorized.state is AuthorizeState::STATE_AUTHORIZE
1718     if (pid != AUTHORIZE_HELPER->GetAuthorizePid()) {
1719         MMI_HILOGI("Other processes have been authorized");
1720         return COMMON_PERMISSION_CHECK_ERROR;
1721     }
1722     return RET_OK;
1723 }
1724 } // namespace MMI
1725 } // namespace OHOS
1726