• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "accessible_ability_manager_service.h"
17 
18 #include <cinttypes>
19 #include <new>
20 #include <string>
21 #include <unistd.h>
22 #include <functional>
23 #include <hitrace_meter.h>
24 
25 #include "ability_info.h"
26 #include "accessibility_event_info.h"
27 #ifdef OHOS_BUILD_ENABLE_POWER_MANAGER
28 #include "accessibility_power_manager.h"
29 #endif
30 #include "accessibility_window_manager.h"
31 #include "hilog_wrapper.h"
32 #include "input_manager.h"
33 #include "iservice_registry.h"
34 #include "os_account_manager.h"
35 #include "parameter.h"
36 #include "system_ability_definition.h"
37 #include "utils.h"
38 #include "accessibility_short_key_dialog.h"
39 #include <ipc_skeleton.h>
40 
41 
42 using namespace std;
43 
44 namespace OHOS {
45 namespace Accessibility {
46 namespace {
47     const std::string AAMS_SERVICE_NAME = "AccessibleAbilityManagerService";
48     const std::string AAMS_ACTION_RUNNER_NAME = "AamsActionRunner";
49     const std::string UI_TEST_BUNDLE_NAME = "ohos.uitest";
50     const std::string UI_TEST_ABILITY_NAME = "uitestability";
51     const std::string SYSTEM_PARAMETER_AAMS_NAME = "accessibility.config.ready";
52     const std::string GRAPHIC_ANIMATION_SCALE_NAME = "persist.sys.graphic.animationscale";
53     const std::string ARKUI_ANIMATION_SCALE_NAME = "persist.sys.arkui.animationscale";
54     const std::string SCREEN_READER_BUNDLE_ABILITY_NAME = "com.huawei.hmos.screenreader/AccessibilityExtAbility";
55     const std::string DEVICE_PROVISIONED = "device_provisioned";
56     const std::string SCREEN_MAGNIFICATION_KEY = "accessibility_display_magnification_enabled";
57     const std::string SCREEN_MAGNIFICATION_TYPE = "accessibility_magnification_capability";
58     const std::string USER_SETUP_COMPLETED = "user_setup_complete";
59     const std::string DELAY_UNLOAD_TASK = "TASK_UNLOAD_ACCESSIBILITY_SA";
60     const std::string ACCESSIBILITY_CLONE_FLAG = "accessibility_config_clone";
61     const std::string SHORTCUT_ENABLED = "accessibility_shortcut_enabled";
62     constexpr int32_t INVALID_SHORTCUT_STATE = 2;
63     constexpr int32_t QUERY_USER_ID_RETRY_COUNT = 600;
64     constexpr int32_t QUERY_USER_ID_SLEEP_TIME = 50;
65     constexpr uint32_t TIME_OUT_OPERATOR = 5000;
66     constexpr int32_t REQUEST_ID_MAX = 0xFFFFFFFF;
67     constexpr int32_t REQUEST_ID_MIN = 0x0000FFFF;
68     constexpr int32_t DEFAULT_ACCOUNT_ID = 100;
69     constexpr int32_t ROOT_UID = 0;
70     constexpr int32_t UNLOAD_TASK_INTERNAL = 3 * 60 * 1000; // ms
71     constexpr int32_t TREE_ID_INVALID = 0;
72     constexpr uint32_t ELEMENT_MOVE_BIT = 40;
73     constexpr int32_t SINGLE_TREE_ID = 0;
74     constexpr int32_t TREE_ID_MAX = 0x00001FFF;
75     constexpr int32_t WINDOW_ID_INVALID = -1;
76     constexpr int64_t ELEMENT_ID_INVALID = -1;
77     enum SCREENREADER_STATE : int32_t {
78         UNINIT = -1,
79         OFF = 0,
80         ON = 1,
81     };
82 } // namespace
83 
84 const bool REGISTER_RESULT =
85     SystemAbility::MakeAndRegisterAbility(&Singleton<AccessibleAbilityManagerService>::GetInstance());
86 
AccessibleAbilityManagerService()87 AccessibleAbilityManagerService::AccessibleAbilityManagerService()
88     : SystemAbility(ACCESSIBILITY_MANAGER_SERVICE_ID, true)
89 {
90     HILOG_INFO("AccessibleAbilityManagerService is constructed");
91     dependentServicesStatus_[ABILITY_MGR_SERVICE_ID] = false;
92     dependentServicesStatus_[BUNDLE_MGR_SERVICE_SYS_ABILITY_ID] = false;
93     dependentServicesStatus_[COMMON_EVENT_SERVICE_ID] = false;
94     dependentServicesStatus_[DISPLAY_MANAGER_SERVICE_SA_ID] = false;
95     dependentServicesStatus_[SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN] = false;
96     dependentServicesStatus_[WINDOW_MANAGER_SERVICE_ID] = false;
97     dependentServicesStatus_[DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID] = false;
98 
99     accessibilitySettings_ = std::make_shared<AccessibilitySettings>();
100 }
101 
~AccessibleAbilityManagerService()102 AccessibleAbilityManagerService::~AccessibleAbilityManagerService()
103 {
104     HILOG_INFO("AccessibleAbilityManagerService::~AccessibleAbilityManagerService");
105 
106     inputInterceptor_ = nullptr;
107     touchEventInjector_ = nullptr;
108     keyEventFilter_ = nullptr;
109     accessibilityShortKey_ = nullptr;
110     a11yAccountsData_.Clear(); // clear account data
111 }
112 
OnStart()113 void AccessibleAbilityManagerService::OnStart()
114 {
115     HILOG_INFO("AccessibleAbilityManagerService::OnStart start");
116     if (!runner_) {
117         runner_ = AppExecFwk::EventRunner::Create(AAMS_SERVICE_NAME);
118         if (!runner_) {
119             HILOG_ERROR("AccessibleAbilityManagerService::OnStart failed:create AAMS runner failed");
120             return;
121         }
122     }
123 
124     if (!handler_) {
125         handler_ = std::make_shared<AAMSEventHandler>(runner_);
126         if (!handler_) {
127             HILOG_ERROR("AccessibleAbilityManagerService::OnStart failed:create AAMS event handler failed");
128             return;
129         }
130     }
131 
132     if (!actionRunner_) {
133         actionRunner_ = AppExecFwk::EventRunner::Create(AAMS_ACTION_RUNNER_NAME);
134         if (!actionRunner_) {
135             HILOG_ERROR("AccessibleAbilityManagerService::OnStart failed:create AAMS action runner failed");
136             return;
137         }
138     }
139 
140     if (!actionHandler_) {
141         actionHandler_ = std::make_shared<AAMSEventHandler>(actionRunner_);
142         if (!actionHandler_) {
143             HILOG_ERROR("AccessibleAbilityManagerService::OnStart failed:create AAMS action handler failed");
144             return;
145         }
146     }
147 
148     SetParameter(SYSTEM_PARAMETER_AAMS_NAME.c_str(), "false");
149 
150     HILOG_DEBUG("AddAbilityListener!");
151     AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
152     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
153     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
154     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
155     AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
156     AddSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID);
157     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
158 
159     accessibilitySettings_->RegisterSettingsHandler(handler_);
160 }
161 
OnStop()162 void AccessibleAbilityManagerService::OnStop()
163 {
164     HILOG_INFO("stop AccessibleAbilityManagerService");
165     if (!handler_) {
166         HILOG_ERROR("AccessibleAbilityManagerService::OnStop failed!");
167         return;
168     }
169 
170     std::promise<void> syncPromise;
171     std::future syncFuture = syncPromise.get_future();
172     handler_->PostTask([this, &syncPromise]() {
173         HILOG_DEBUG();
174 
175         Singleton<AccessibilityCommonEvent>::GetInstance().UnSubscriberEvent();
176 #ifdef OHOS_BUILD_ENABLE_DISPLAY_MANAGER
177         Singleton<AccessibilityDisplayManager>::GetInstance().UnregisterDisplayListener();
178 #endif
179         Singleton<AccessibilityWindowManager>::GetInstance().DeregisterWindowListener();
180 
181         currentAccountId_ = -1;
182         a11yAccountsData_.Clear();
183         stateObservers_.Clear();
184         bundleManager_ = nullptr;
185         inputInterceptor_ = nullptr;
186         touchEventInjector_ = nullptr;
187         keyEventFilter_ = nullptr;
188         accessibilityShortKey_ = nullptr;
189         stateObserversDeathRecipient_ = nullptr;
190         bundleManagerDeathRecipient_ = nullptr;
191 
192         syncPromise.set_value();
193         }, "TASK_ONSTOP");
194     syncFuture.wait();
195 
196     for (auto &iter : dependentServicesStatus_) {
197         iter.second = false;
198     }
199 
200     isReady_ = false;
201     isPublished_ = false;
202     SetParameter(SYSTEM_PARAMETER_AAMS_NAME.c_str(), "false");
203     HILOG_INFO("AccessibleAbilityManagerService::OnStop OK.");
204 }
205 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)206 void AccessibleAbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
207 {
208     HILOG_DEBUG("systemAbilityId:%{public}d added!", systemAbilityId);
209     if (!handler_) {
210         HILOG_DEBUG("Event handler is nullptr.");
211         return;
212     }
213 
214     handler_->PostTask([=]() {
215         auto iter = dependentServicesStatus_.find(systemAbilityId);
216         if (iter == dependentServicesStatus_.end()) {
217             HILOG_ERROR("SystemAbilityId is not found!");
218             return;
219         }
220 
221         dependentServicesStatus_[systemAbilityId] = true;
222         if (std::any_of(dependentServicesStatus_.begin(), dependentServicesStatus_.end(),
223             [](const std::map<int32_t, bool>::value_type &status) { return !status.second; })) {
224             HILOG_DEBUG("Not all the dependence is ready!");
225             return;
226         }
227 
228         if (Init() == false) {
229             HILOG_ERROR("AccessibleAbilityManagerService::Init failed!");
230             return;
231         }
232 
233         if (!isPublished_) {
234             if (Publish(this) == false) {
235                 HILOG_ERROR("AccessibleAbilityManagerService::Publish failed!");
236                 return;
237             }
238             isPublished_ = true;
239         }
240 
241         InitInnerResource();
242 
243         isReady_ = true;
244         SetParameter(SYSTEM_PARAMETER_AAMS_NAME.c_str(), "true");
245         HILOG_DEBUG("AAMS is ready!");
246         RegisterShortKeyEvent();
247         PostDelayUnloadTask();
248         RegisterScreenMagnificationState();
249         RegisterScreenMagnificationType();
250         }, "OnAddSystemAbility");
251 }
252 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)253 void AccessibleAbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
254 {
255     HILOG_INFO("systemAbilityId:%{public}d removed!", systemAbilityId);
256     if (!handler_) {
257         HILOG_DEBUG("Event handler is nullptr.");
258         return;
259     }
260 
261     handler_->PostTask([=]() {
262         HILOG_INFO("Remove system ability start");
263         auto iter = dependentServicesStatus_.find(systemAbilityId);
264         if (iter == dependentServicesStatus_.end()) {
265             HILOG_ERROR("SystemAbilityId is not found!");
266             return;
267         }
268 
269         dependentServicesStatus_[systemAbilityId] = false;
270         if (isReady_) {
271             SwitchedUser(-1);
272             Singleton<AccessibilityCommonEvent>::GetInstance().UnSubscriberEvent();
273 #ifdef OHOS_BUILD_ENABLE_DISPLAY_MANAGER
274             Singleton<AccessibilityDisplayManager>::GetInstance().UnregisterDisplayListener();
275 #endif
276             Singleton<AccessibilityWindowManager>::GetInstance().DeregisterWindowListener();
277             Singleton<AccessibilityWindowManager>::GetInstance().DeInit();
278 
279             isReady_ = false;
280             SetParameter(SYSTEM_PARAMETER_AAMS_NAME.c_str(), "false");
281         }
282         }, "OnRemoveSystemAbility");
283 }
284 
Dump(int fd,const std::vector<std::u16string> & args)285 int AccessibleAbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
286 {
287     HILOG_DEBUG("dump AccessibilityManagerServiceInfo");
288     if (!handler_) {
289         HILOG_ERROR("Parameters check failed!");
290         return RET_ERR_NULLPTR;
291     }
292     std::promise<int> syncPromise;
293     std::future syncFuture = syncPromise.get_future();
294     handler_->PostTask([this, &syncPromise, fd, args]() {
295         if (!accessibilityDumper_) {
296             accessibilityDumper_ = new(std::nothrow) AccessibilityDumper();
297             if (!accessibilityDumper_) {
298                 HILOG_ERROR("accessibilityDumper_ is nullptr");
299                 syncPromise.set_value(-1);
300                 return;
301             }
302         }
303         syncPromise.set_value(accessibilityDumper_->Dump(fd, args));
304         }, "TASK_DUMP_INFO");
305     return syncFuture.get();
306 }
307 
VerifyingToKenId(const int32_t windowId,const int64_t elementId)308 RetError AccessibleAbilityManagerService::VerifyingToKenId(const int32_t windowId, const int64_t elementId)
309 {
310     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
311     int32_t treeId = (static_cast<uint64_t>(elementId) >> ELEMENT_MOVE_BIT);
312     HILOG_DEBUG("VerifyingToKenId: treeId[%{public}d], windowId[%{public}d], elementId[%{public}" PRId64 "]",
313         treeId, windowId, elementId);
314     if (elementId == ELEMENT_ID_INVALID || windowId == WINDOW_ID_INVALID) {
315         HILOG_DEBUG("windowId[%{public}d], elementId[%{public}" PRId64 "]", windowId, elementId);
316         return RET_OK;
317     }
318     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
319     if (accountData == nullptr) {
320         Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
321             A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
322             HILOG_ERROR("Get current account data failed!!");
323             return RET_ERR_CONNECTION_EXIST;
324     }
325     HILOG_DEBUG("treeId %{public}d, windowId %{public}d", treeId, windowId);
326     int32_t realId =
327         Singleton<AccessibilityWindowManager>::GetInstance().ConvertToRealWindowId(windowId, FOCUS_TYPE_INVALID);
328     sptr<AccessibilityWindowConnection> connection = accountData->GetAccessibilityWindowConnection(realId);
329     if (connection == nullptr) {
330         HILOG_ERROR("connection is empty.");
331         return RET_ERR_REGISTER_EXIST;
332     }
333     uint32_t expectTokenId = connection->GetTokenIdMap(treeId);
334     if (tokenId != expectTokenId) {
335         HILOG_DEBUG("tokenId error!");
336         return RET_ERR_TOKEN_ID;
337     }
338 
339     return RET_OK;
340 }
341 
SendEvent(const AccessibilityEventInfo & uiEvent,const int32_t flag)342 RetError AccessibleAbilityManagerService::SendEvent(const AccessibilityEventInfo &uiEvent, const int32_t flag)
343 {
344     HILOG_DEBUG("eventType[%{public}d] gestureId[%{public}d] windowId[%{public}d]"
345         "elementId: %{public}" PRId64 " winId: %{public}d treeId: %{public}d",
346         uiEvent.GetEventType(), uiEvent.GetGestureType(), uiEvent.GetWindowId(),
347         uiEvent.GetElementInfo().GetAccessibilityId(),
348         uiEvent.GetElementInfo().GetWindowId(), uiEvent.GetElementInfo().GetBelongTreeId());
349     if (!handler_) {
350         HILOG_ERROR("Parameters check failed!");
351         return RET_ERR_NULLPTR;
352     }
353     if (flag) {
354         if (VerifyingToKenId(uiEvent.GetElementInfo().GetWindowId(),
355             uiEvent.GetElementInfo().GetAccessibilityId()) == RET_OK) {
356             HILOG_DEBUG("VerifyingToKenId ok");
357         } else {
358             HILOG_DEBUG("VerifyingToKenId failed");
359             return RET_ERR_CONNECTION_EXIST;
360         }
361     }
362 
363     UpdateAccessibilityWindowStateByEvent(uiEvent);
364     handler_->PostTask([this, uiEvent]() {
365         HILOG_DEBUG();
366         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
367         if (!accountData) {
368             HILOG_ERROR("accountData is nullptr.");
369             return;
370         }
371 
372         const_cast<AccessibilityEventInfo&>(uiEvent).SetTimeStamp(Utils::GetSystemTime());
373         map<string, sptr<AccessibleAbilityConnection>> abilities = accountData->GetConnectedA11yAbilities();
374         for (auto &ability : abilities) {
375             if (ability.second) {
376                 ability.second->OnAccessibilityEvent(const_cast<AccessibilityEventInfo&>(uiEvent));
377             }
378         }
379         }, "TASK_SEND_EVENT");
380     return RET_OK;
381 }
382 
RegisterStateObserver(const sptr<IAccessibleAbilityManagerStateObserver> & stateObserver)383 uint32_t AccessibleAbilityManagerService::RegisterStateObserver(
384     const sptr<IAccessibleAbilityManagerStateObserver>& stateObserver)
385 {
386     HILOG_DEBUG();
387     if (!stateObserver || !handler_) {
388         HILOG_ERROR("parameters check failed!");
389         return 0;
390     }
391 
392     std::lock_guard<std::mutex> lock(mutex_);
393     if (!stateObserversDeathRecipient_) {
394         stateObserversDeathRecipient_ = new(std::nothrow) StateCallbackDeathRecipient();
395         if (!stateObserversDeathRecipient_) {
396             HILOG_ERROR("stateObserversDeathRecipient_ is null");
397             return 0;
398         }
399     }
400 
401     if (!stateObserver->AsObject()) {
402         HILOG_ERROR("object is null");
403         return 0;
404     }
405 
406     stateObserver->AsObject()->AddDeathRecipient(stateObserversDeathRecipient_);
407     stateObservers_.AddStateObserver(stateObserver);
408     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
409     if (accountData == nullptr) {
410         return 0;
411     }
412 
413     return accountData->GetAccessibilityState();
414 }
415 
GetRealWindowAndElementId(int32_t & windowId,int64_t & elementId)416 void AccessibleAbilityManagerService::GetRealWindowAndElementId(int32_t& windowId, int64_t& elementId)
417 {
418     HILOG_DEBUG("real windowId %{public}d", windowId);
419     if (!handler_) {
420         return;
421     }
422 
423     std::promise<void> syncPromise;
424     std::future syncFuture = syncPromise.get_future();
425     handler_->PostTask([&, this]() {
426         Singleton<AccessibilityWindowManager>::GetInstance().GetRealWindowAndElementId(windowId, elementId);
427         syncPromise.set_value();
428         }, "GET_REAL_WINDOW_AND_ELEMENT_ID");
429     return syncFuture.get();
430 }
431 
GetSceneBoardInnerWinId(int32_t windowId,int64_t elementId,int32_t & innerWid)432 void AccessibleAbilityManagerService::GetSceneBoardInnerWinId(int32_t windowId, int64_t elementId,
433     int32_t& innerWid)
434 {
435     HILOG_DEBUG("real windowId %{public}d", windowId);
436     if (!handler_) {
437         return;
438     }
439 
440     std::promise<void> syncPromise;
441     std::future syncFuture = syncPromise.get_future();
442     handler_->PostTask([&, this]() {
443         Singleton<AccessibilityWindowManager>::GetInstance().GetSceneBoardInnerWinId(windowId, elementId, innerWid);
444         syncPromise.set_value();
445         }, "GET_SCENE_BOARD_INNER_WINDOW_ID");
446     return syncFuture.get();
447 }
448 
GetRealIdConnection()449 sptr<AccessibilityWindowConnection> AccessibleAbilityManagerService::GetRealIdConnection()
450 {
451     HILOG_DEBUG();
452     int32_t windowId = ANY_WINDOW_ID;
453     int32_t focusType = FOCUS_TYPE_ACCESSIBILITY;
454     int32_t realId = Singleton<AccessibilityWindowManager>::GetInstance().ConvertToRealWindowId(windowId, focusType);
455 
456     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
457     if (!accountData) {
458         HILOG_ERROR("GetCurrentAccountData failed");
459         return sptr<AccessibilityWindowConnection>();
460     }
461     return accountData->GetAccessibilityWindowConnection(realId);
462 }
463 
FindFocusedElementByConnection(sptr<AccessibilityWindowConnection> connection,AccessibilityElementInfo & elementInfo)464 bool AccessibleAbilityManagerService::FindFocusedElementByConnection(sptr<AccessibilityWindowConnection> connection,
465     AccessibilityElementInfo &elementInfo)
466 {
467     HILOG_DEBUG();
468     int64_t elementId = -1;
469     int32_t focusType = FOCUS_TYPE_ACCESSIBILITY;
470     if (!connection || !connection->GetProxy()) {
471         HILOG_ERROR("GetAccessibilityWindowConnection failed");
472         return false;
473     }
474 
475     uint32_t timeOut = 5000;
476     sptr<ElementOperatorCallbackImpl> focusCallback = new(std::nothrow) ElementOperatorCallbackImpl();
477     if (!focusCallback) {
478         HILOG_ERROR("Failed to create focusCallback.");
479         return false;
480     }
481     std::future<void> focusFuture = focusCallback->promise_.get_future();
482     connection->GetProxy()->FindFocusedElementInfo(elementId, focusType, GenerateRequestId(), focusCallback);
483     std::future_status waitFocus = focusFuture.wait_for(std::chrono::milliseconds(timeOut));
484     if (waitFocus != std::future_status::ready) {
485         HILOG_ERROR("FindFocusedElementInfo Failed to wait result");
486         return false;
487     }
488     elementInfo = focusCallback->accessibilityInfoResult_;
489     return true;
490 }
491 
FindFocusedElement(AccessibilityElementInfo & elementInfo)492 bool AccessibleAbilityManagerService::FindFocusedElement(AccessibilityElementInfo &elementInfo)
493 {
494     HILOG_DEBUG();
495     sptr<AccessibilityWindowConnection> connection = GetRealIdConnection();
496     FindFocusedElementByConnection(connection, elementInfo);
497     if (elementInfo.GetAccessibilityId() >= 0) {
498         HILOG_DEBUG("find focused element success.");
499         return true;
500     }
501     int32_t windowId = GetFocusWindowId();
502     int64_t elementId = GetFocusElementId();
503     sptr<IAccessibilityElementOperator> elementOperator = nullptr;
504     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
505     if (accountData == nullptr) {
506         HILOG_ERROR("GetCurrentAccountData failed");
507         return false;
508     }
509     connection = accountData->GetAccessibilityWindowConnection(windowId);
510     HILOG_DEBUG("windowId[%{public}d], elementId[%{public}" PRId64 "]", windowId, elementId);
511     if (connection == nullptr) {
512         HILOG_ERROR("connection is nullptr");
513         return false;
514     }
515     sptr<ElementOperatorCallbackImpl> callBack = new(std::nothrow) ElementOperatorCallbackImpl();
516     if (callBack == nullptr) {
517         HILOG_ERROR("Failed to create callBack.");
518         return false;
519     }
520     std::future<void> promiseFuture = callBack->promise_.get_future();
521     GetElementOperatorConnection(connection, elementId, elementOperator);
522     if (elementOperator == nullptr) {
523         HILOG_ERROR("elementOperator is nullptr");
524         return false;
525     }
526     elementOperator->SearchElementInfoByAccessibilityId(elementId, GenerateRequestId(), callBack, 0);
527     std::future_status waitFocus = promiseFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
528     if (waitFocus != std::future_status::ready) {
529         ipcTimeoutNum_++;
530         HILOG_ERROR("Failed to wait result, number %{public}" PRId64 "", ipcTimeoutNum_);
531         return false;
532     }
533 
534     if (callBack->elementInfosResult_.size() <= 0) {
535         HILOG_ERROR("SearchElementInfoByAccessibilityId return null");
536         return false;
537     }
538     elementInfo = callBack->elementInfosResult_[0];
539     return true;
540 }
541 
GetElementOperatorConnection(sptr<AccessibilityWindowConnection> & connection,const int64_t elementId,sptr<IAccessibilityElementOperator> & elementOperator)542 void AccessibleAbilityManagerService::GetElementOperatorConnection(sptr<AccessibilityWindowConnection> &connection,
543     const int64_t elementId, sptr<IAccessibilityElementOperator> &elementOperator)
544 {
545     int32_t treeId = 0;
546     if (elementId > 0) {
547         treeId = GetTreeIdBySplitElementId(elementId);
548         elementOperator = connection->GetCardProxy(treeId);
549     } else {
550         elementOperator = connection->GetProxy();
551     }
552     HILOG_DEBUG("elementId:%{public}" PRId64 " treeId:%{public}d", elementId, treeId);
553 }
554 
ExecuteActionOnAccessibilityFocused(const ActionType & action)555 bool AccessibleAbilityManagerService::ExecuteActionOnAccessibilityFocused(const ActionType &action)
556 {
557     HILOG_DEBUG();
558     int32_t windowId = GetFocusWindowId();
559     int64_t elementId = GetFocusElementId();
560     uint32_t timeOut = 5000;
561     int32_t treeId = GetTreeIdBySplitElementId(elementId);
562     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
563     if (accountData == nullptr) {
564         HILOG_ERROR("GetCurrentAccountData failed");
565         return false;
566     }
567     sptr<AccessibilityWindowConnection> connection = accountData->GetAccessibilityWindowConnection(windowId);
568     HILOG_DEBUG("windowId[%{public}d], elementId[%{public}" PRId64 "], action[%{public}d", windowId, elementId,
569         action);
570     if (connection == nullptr) {
571         HILOG_ERROR("connection is nullptr");
572         return false;
573     }
574     std::map<std::string, std::string> actionArguments {};
575     sptr<ElementOperatorCallbackImpl> actionCallback = new(std::nothrow) ElementOperatorCallbackImpl();
576     if (actionCallback == nullptr) {
577         HILOG_ERROR("Failed to create actionCallback.");
578         return false;
579     }
580     std::future<void> actionFuture = actionCallback->promise_.get_future();
581     if (treeId > TREE_ID_INVALID) {
582         if (connection->GetCardProxy(treeId) != nullptr) {
583             connection->GetCardProxy(treeId)->ExecuteAction(elementId, action,
584                 actionArguments, GenerateRequestId(), actionCallback);
585         } else {
586             HILOG_ERROR("get operation is nullptr");
587             return false;
588         }
589     } else {
590         connection->GetProxy()->ExecuteAction(elementId, action, actionArguments, GenerateRequestId(), actionCallback);
591     }
592     std::future_status waitAction = actionFuture.wait_for(std::chrono::milliseconds(timeOut));
593     if (waitAction != std::future_status::ready) {
594         HILOG_ERROR("ExecuteAction Failed to wait result");
595         return false;
596     }
597 
598     return actionCallback->executeActionResult_;
599 }
600 
SetFocusWindowId(const int32_t focusWindowId)601 void AccessibleAbilityManagerService::SetFocusWindowId(const int32_t focusWindowId)
602 {
603     focusWindowId_ = focusWindowId;
604 }
605 
GetFocusWindowId()606 int32_t AccessibleAbilityManagerService::GetFocusWindowId()
607 {
608     return focusWindowId_;
609 }
610 
SetFocusElementId(const int64_t focusElementId)611 void AccessibleAbilityManagerService::SetFocusElementId(const int64_t focusElementId)
612 {
613     focusElementId_ = focusElementId;
614 }
615 
GetFocusElementId()616 int64_t AccessibleAbilityManagerService::GetFocusElementId()
617 {
618     return focusElementId_;
619 }
620 
RegisterCaptionObserver(const sptr<IAccessibleAbilityManagerCaptionObserver> & callback)621 uint32_t AccessibleAbilityManagerService::RegisterCaptionObserver(
622     const sptr<IAccessibleAbilityManagerCaptionObserver> &callback)
623 {
624     HILOG_DEBUG();
625     if (!callback || !actionHandler_) {
626         HILOG_ERROR("Parameters check failed!");
627         return ERR_INVALID_VALUE;
628     }
629 
630     std::shared_ptr<std::promise<uint32_t>> syncPromise = std::make_shared<std::promise<uint32_t>>();
631     std::future syncFuture = syncPromise->get_future();
632     actionHandler_->PostTask([this, syncPromise, callback]() {
633         HILOG_DEBUG();
634         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
635         if (!accountData) {
636             HILOG_ERROR("Account data is null");
637             syncPromise->set_value(ERR_INVALID_VALUE);
638             return;
639         }
640         if (!captionPropertyCallbackDeathRecipient_) {
641             captionPropertyCallbackDeathRecipient_ = new(std::nothrow) CaptionPropertyCallbackDeathRecipient();
642             if (!captionPropertyCallbackDeathRecipient_) {
643                 HILOG_ERROR("captionPropertyCallbackDeathRecipient_ is null");
644                 syncPromise->set_value(ERR_INVALID_VALUE);
645                 return;
646             }
647         }
648         if (!callback->AsObject()) {
649             HILOG_ERROR("object is null");
650             syncPromise->set_value(0);
651             return;
652         }
653         callback->AsObject()->AddDeathRecipient(captionPropertyCallbackDeathRecipient_);
654         accountData->AddCaptionPropertyCallback(callback);
655         HILOG_DEBUG("the size of caption property callbacks is %{public}zu",
656             accountData->GetCaptionPropertyCallbacks().size());
657         syncPromise->set_value(NO_ERROR);
658         }, "TASK_REGISTER_CAPTION_OBSERVER");
659 
660     std::future_status wait = syncFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
661     if (wait != std::future_status::ready) {
662         HILOG_ERROR("Failed to wait RegisterCaptionObserver result");
663         return RET_ERR_TIME_OUT;
664     }
665     return syncFuture.get();
666 }
667 
RegisterEnableAbilityListsObserver(const sptr<IAccessibilityEnableAbilityListsObserver> & observer)668 void AccessibleAbilityManagerService::RegisterEnableAbilityListsObserver(
669     const sptr<IAccessibilityEnableAbilityListsObserver> &observer)
670 {
671     HILOG_DEBUG();
672     if (!observer || !actionHandler_) {
673         HILOG_ERROR("Parameters check failed!");
674         return;
675     }
676 
677     std::shared_ptr<std::promise<void>> syncPromisePtr = std::make_shared<std::promise<void>>();
678     std::future syncFuture = syncPromisePtr->get_future();
679     actionHandler_->PostTask([this, syncPromisePtr, observer]() {
680         HILOG_DEBUG();
681         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
682         if (!accountData) {
683             HILOG_ERROR("Account data is null");
684             syncPromisePtr->set_value();
685             return;
686         }
687         if (!enableAbilityListsObserverDeathRecipient_) {
688             enableAbilityListsObserverDeathRecipient_ = new(std::nothrow) EnableAbilityListsObserverDeathRecipient();
689             if (!enableAbilityListsObserverDeathRecipient_) {
690                 HILOG_ERROR("enableAbilityListsObserverDeathRecipient_ is null");
691                 syncPromisePtr->set_value();
692                 return;
693             }
694         }
695         if (!observer->AsObject()) {
696             HILOG_ERROR("object is null");
697             syncPromisePtr->set_value();
698             return;
699         }
700         observer->AsObject()->AddDeathRecipient(enableAbilityListsObserverDeathRecipient_);
701         accountData->AddEnableAbilityListsObserver(observer);
702         syncPromisePtr->set_value();
703         }, "TASK_REGISTER_ENABLE_ABILITY_LISTS_OBSERVER");
704 
705     std::future_status wait = syncFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
706     if (wait != std::future_status::ready) {
707         HILOG_ERROR("Failed to wait RegisterEnableAbilityListsObserver result");
708         return;
709     }
710     return syncFuture.get();
711 }
712 
GetAbilityList(const uint32_t abilityTypes,const int32_t stateType,std::vector<AccessibilityAbilityInfo> & infos)713 RetError AccessibleAbilityManagerService::GetAbilityList(const uint32_t abilityTypes, const int32_t stateType,
714     std::vector<AccessibilityAbilityInfo> &infos)
715 {
716     HILOG_DEBUG("abilityTypes(%{public}d) stateType(%{public}d)", abilityTypes, stateType);
717     if (!handler_ || (stateType > ABILITY_STATE_INSTALLED) || (stateType < ABILITY_STATE_ENABLE)) {
718         HILOG_ERROR("Parameters check failed! stateType:%{public}d", stateType);
719         return RET_ERR_INVALID_PARAM;
720     }
721 
722     std::promise<RetError> syncPromise;
723     std::future syncFuture = syncPromise.get_future();
724     handler_->PostTask([this, &syncPromise, &infos, abilityTypes, stateType]() {
725         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
726         if (!accountData) {
727             HILOG_ERROR("Get current account data failed!!");
728             syncPromise.set_value(RET_ERR_FAILED);
729             return;
730         }
731 
732         vector<AccessibilityAbilityInfo> abilities;
733         accountData->GetAbilitiesByState(static_cast<AbilityStateType>(stateType), abilities);
734         HILOG_DEBUG("abilityes count is %{public}zu", abilities.size());
735         for (auto &ability : abilities) {
736             if (abilityTypes == AccessibilityAbilityTypes::ACCESSIBILITY_ABILITY_TYPE_ALL ||
737                 (ability.GetAccessibilityAbilityType() & abilityTypes)) {
738                 infos.push_back(ability);
739             }
740         }
741         HILOG_DEBUG("infos count is %{public}zu", infos.size());
742         syncPromise.set_value(RET_OK);
743         }, "TASK_GET_ABILITY_LIST");
744     return syncFuture.get();
745 }
746 
RegisterElementOperator(const int32_t windowId,const sptr<IAccessibilityElementOperator> & operation,bool isApp)747 RetError AccessibleAbilityManagerService::RegisterElementOperator(
748     const int32_t windowId, const sptr<IAccessibilityElementOperator> &operation, bool isApp)
749 {
750     if (!handler_) {
751         Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
752             A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
753         HILOG_ERROR("handler_ is nullptr.");
754         return RET_ERR_NULLPTR;
755     }
756     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
757     if (CheckCallingUid() != RET_OK) {
758         return RET_ERR_SAMGR;
759     }
760     handler_->PostTask([=]() {
761         HILOG_INFO("Register windowId[%{public}d]", windowId);
762         HITRACE_METER_NAME(HITRACE_TAG_ACCESSIBILITY_MANAGER, "RegisterElementOperator");
763         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
764         if (!accountData) {
765             Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
766                 A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
767             HILOG_ERROR("Get current account data failed!!");
768             return;
769         }
770         sptr<AccessibilityWindowConnection> oldConnection = accountData->GetAccessibilityWindowConnection(windowId);
771         if (isApp && oldConnection) {
772             HILOG_WARN("no need to register again.");
773             return;
774         }
775         DeleteConnectionAndDeathRecipient(windowId, oldConnection);
776         sptr<AccessibilityWindowConnection> connection =
777             new(std::nothrow) AccessibilityWindowConnection(windowId, operation, currentAccountId_);
778         if (!connection) {
779             Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
780                 A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
781             HILOG_ERROR("New  AccessibilityWindowConnection failed!!");
782             return;
783         }
784         connection->SetTokenIdMap(SINGLE_TREE_ID, tokenId);
785         accountData->AddAccessibilityWindowConnection(windowId, connection);
786 
787         IsCheckWindowIdEventExist(windowId);
788         if (operation && operation->AsObject()) {
789             sptr<IRemoteObject::DeathRecipient> deathRecipient =
790                 new(std::nothrow) InteractionOperationDeathRecipient(windowId);
791             if (!deathRecipient) {
792                 Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
793                     A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
794                 HILOG_ERROR("Create interactionOperationDeathRecipient failed");
795                 return;
796             }
797 
798             bool result = operation->AsObject()->AddDeathRecipient(deathRecipient);
799             interactionOperationDeathRecipients_[windowId] = deathRecipient;
800             HILOG_DEBUG("The result of adding operation's death recipient is %{public}d", result);
801         }
802         }, "TASK_REGISTER_ELEMENT_OPERATOR");
803     return RET_OK;
804 }
805 
IsCheckWindowIdEventExist(const int32_t windowId)806 void AccessibleAbilityManagerService::IsCheckWindowIdEventExist(const int32_t windowId)
807 {
808     if (CheckWindowIdEventExist(windowId)) {
809         SendEvent(windowFocusEventMap_[windowId]);
810         windowFocusEventMap_.erase(windowId);
811     }
812 }
813 
RegisterElementOperatorChildWork(const Registration & parameter,const int32_t treeId,const int64_t nodeId,const sptr<IAccessibilityElementOperator> & operation,const uint32_t tokenId,bool isApp)814 RetError AccessibleAbilityManagerService::RegisterElementOperatorChildWork(const Registration &parameter,
815     const int32_t treeId, const int64_t nodeId, const sptr<IAccessibilityElementOperator> &operation,
816     const uint32_t tokenId, bool isApp)
817 {
818     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
819     if (accountData == nullptr) {
820         Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
821             A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
822         HILOG_ERROR("Get current account data failed!!");
823         return RET_ERR_REGISTER_EXIST;
824     }
825 
826     sptr<AccessibilityWindowConnection> parentConnection =
827         accountData->GetAccessibilityWindowConnection(parameter.parentWindowId);
828     if (isApp && parentConnection) {
829         sptr<IAccessibilityElementOperator> parentAamsOper =
830             parentConnection->GetCardProxy(parameter.parentTreeId);
831         if (parentAamsOper != nullptr) {
832             parentAamsOper->SetChildTreeIdAndWinId(nodeId, treeId, parameter.windowId);
833         } else {
834             HILOG_DEBUG("parentAamsOper is nullptr");
835         }
836     }
837 
838     operation->SetBelongTreeId(treeId);
839     operation->SetParentWindowId(parameter.parentWindowId);
840     sptr<AccessibilityWindowConnection> oldConnection =
841         accountData->GetAccessibilityWindowConnection(parameter.windowId);
842     if (isApp && oldConnection) {
843         if (oldConnection->GetCardProxy(treeId) != nullptr) {
844             HILOG_WARN("no need to register again.");
845             return RET_ERR_REGISTER_EXIST;
846         } else {
847             oldConnection->SetCardProxy(treeId, operation);
848             SetTokenIdMapAndRootParentId(oldConnection, treeId, nodeId, tokenId);
849         }
850     }
851     return RET_OK;
852 }
853 
SetTokenIdMapAndRootParentId(const sptr<AccessibilityWindowConnection> connection,const int32_t treeId,const int64_t nodeId,const uint32_t tokenId)854 void AccessibleAbilityManagerService::SetTokenIdMapAndRootParentId(
855     const sptr<AccessibilityWindowConnection> connection,
856     const int32_t treeId, const int64_t nodeId, const uint32_t tokenId)
857 {
858     connection->SetTokenIdMap(treeId, tokenId);
859     connection->SetRootParentId(treeId, nodeId);
860 }
861 
RegisterElementOperator(Registration parameter,const sptr<IAccessibilityElementOperator> & operation,bool isApp)862 RetError AccessibleAbilityManagerService::RegisterElementOperator(Registration parameter,
863     const sptr<IAccessibilityElementOperator> &operation, bool isApp)
864 {
865     if (CheckCallingUid() != RET_OK) {
866         return RET_ERR_SAMGR;
867     }
868     static std::atomic<int32_t> treeId(1);
869     int32_t treeIdSingle = treeId.fetch_add(1, std::memory_order_relaxed);
870     if (treeIdSingle > TREE_ID_MAX) {
871         HILOG_ERROR("TreeId more than 13.");
872         return RET_ERR_TREE_TOO_BIG;
873     }
874     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
875     int64_t nodeId = parameter.elementId;
876     HILOG_INFO("get treeId element and treeid - treeId: %{public}d parameter.elementId[%{public}" PRId64 "]"
877         "element[%{public}" PRId64 "]",
878         treeIdSingle, parameter.elementId, nodeId);
879 
880     if (!handler_) {
881         Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
882             A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
883         HILOG_ERROR("handler_ is nullptr.");
884         return RET_ERR_NULLPTR;
885     }
886     handler_->PostTask([=]() {
887         HILOG_INFO("Register windowId[%{public}d]", parameter.windowId);
888         HITRACE_METER_NAME(HITRACE_TAG_ACCESSIBILITY_MANAGER, "RegisterElementOperator");
889         if (RET_OK != RegisterElementOperatorChildWork(parameter, treeIdSingle, nodeId, operation, tokenId, isApp)) {
890             return;
891         }
892         if (CheckWindowIdEventExist(parameter.windowId)) {
893             SendEvent(windowFocusEventMap_[parameter.windowId]);
894             windowFocusEventMap_.erase(parameter.windowId);
895         }
896         if (operation && operation->AsObject()) {
897             sptr<IRemoteObject::DeathRecipient> deathRecipient =
898                 new(std::nothrow) InteractionOperationDeathRecipient(parameter.windowId, treeIdSingle);
899             if (deathRecipient == nullptr) {
900                 Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
901                     A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
902                 HILOG_ERROR("Create interactionOperationDeathRecipient failed");
903                 return;
904             }
905             bool result = operation->AsObject()->AddDeathRecipient(deathRecipient);
906             interactionOperationDeathMap_[parameter.windowId][treeIdSingle] = deathRecipient;
907             HILOG_DEBUG("The result of adding operation's death recipient is %{public}d", result);
908         }
909         }, "TASK_REGISTER_ELEMENT_OPERATOR");
910     return RET_OK;
911 }
912 
DeleteConnectionAndDeathRecipient(const int32_t windowId,const sptr<AccessibilityWindowConnection> & connection)913 void AccessibleAbilityManagerService::DeleteConnectionAndDeathRecipient(
914     const int32_t windowId, const sptr<AccessibilityWindowConnection> &connection)
915 {
916     HILOG_DEBUG();
917     if (!connection) {
918         HILOG_ERROR("connection is nullptr");
919         return;
920     }
921 
922     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
923     if (!accountData) {
924         Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
925             A11yError::ERROR_CONNECT_TARGET_APPLICATION_FAILED);
926         HILOG_ERROR("Get current account data failed!!");
927         return;
928     }
929 
930     accountData->RemoveAccessibilityWindowConnection(windowId);
931     if (!connection->GetProxy()) {
932         HILOG_WARN("proxy is null");
933         return;
934     }
935     auto object = connection->GetProxy()->AsObject();
936     if (object) {
937         auto iter = interactionOperationDeathRecipients_.find(windowId);
938         if (iter != interactionOperationDeathRecipients_.end()) {
939             sptr<IRemoteObject::DeathRecipient> deathRecipient = iter->second;
940             bool result = object->RemoveDeathRecipient(deathRecipient);
941             HILOG_DEBUG("The result of deleting connection's death recipient is %{public}d", result);
942             interactionOperationDeathRecipients_.erase(iter);
943         }
944     }
945 }
946 
DeregisterElementOperator(int32_t windowId)947 RetError AccessibleAbilityManagerService::DeregisterElementOperator(int32_t windowId)
948 {
949     if (!handler_) {
950         HILOG_ERROR("handler_ is nullptr.");
951         return RET_ERR_NULLPTR;
952     }
953 
954     handler_->PostTask([=]() {
955         HILOG_INFO("Deregister windowId[%{public}d]", windowId);
956         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
957         if (!accountData) {
958             HILOG_ERROR("accountData is nullptr.");
959             return;
960         }
961         sptr<AccessibilityWindowConnection> connection = accountData->GetAccessibilityWindowConnection(windowId);
962         if (!connection) {
963             HILOG_WARN("The operation of windowId[%{public}d] has not been registered.", windowId);
964             return;
965         }
966         accountData->RemoveAccessibilityWindowConnection(windowId);
967         StopCallbackWait(windowId);
968 
969         if (!connection->GetProxy()) {
970             HILOG_ERROR("proxy is null");
971             return;
972         }
973 
974         auto object = connection->GetProxy()->AsObject();
975         if (object) {
976             auto iter = interactionOperationDeathRecipients_.find(windowId);
977             if (iter != interactionOperationDeathRecipients_.end()) {
978                 sptr<IRemoteObject::DeathRecipient> deathRecipient = iter->second;
979                 bool result = object->RemoveDeathRecipient(deathRecipient);
980                 HILOG_DEBUG("The result of deleting operation's death recipient is %{public}d", result);
981                 interactionOperationDeathRecipients_.erase(iter);
982             } else {
983                 HILOG_INFO("cannot find remote object. windowId[%{public}d]", windowId);
984             }
985         }
986         }, "TASK_DEREGISTER_ELEMENT_OPERATOR");
987     return RET_OK;
988 }
989 
DeregisterElementOperator(int32_t windowId,const int32_t treeId)990 RetError AccessibleAbilityManagerService::DeregisterElementOperator(int32_t windowId, const int32_t treeId)
991 {
992     if (!handler_) {
993         HILOG_ERROR("handler_ is nullptr.");
994         return RET_ERR_NULLPTR;
995     }
996 
997     handler_->PostTask([=]() {
998         HILOG_INFO("Deregister windowId[%{public}d], treeId[%{public}d] start", windowId, treeId);
999         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1000         if (!accountData) {
1001             HILOG_ERROR("accountData is nullptr.");
1002             return;
1003         }
1004         sptr<AccessibilityWindowConnection> connection = accountData->GetAccessibilityWindowConnection(windowId);
1005         if (connection == nullptr) {
1006             HILOG_WARN("The operation of windowId[%{public}d] has not been registered.", windowId);
1007             return;
1008         }
1009         StopCallbackWait(windowId, treeId);
1010 
1011         if (!connection->GetCardProxy(treeId)) {
1012             HILOG_ERROR("proxy is null");
1013             return;
1014         }
1015 
1016         auto object = connection->GetCardProxy(treeId)->AsObject();
1017         if (object) {
1018             RemoveTreeDeathRecipient(windowId, treeId, connection);
1019         }
1020         }, "TASK_DEREGISTER_ELEMENT_OPERATOR");
1021     return RET_OK;
1022 }
1023 
RemoveTreeDeathRecipient(const int32_t windowId,const int32_t treeId,const sptr<AccessibilityWindowConnection> connection)1024 void AccessibleAbilityManagerService::RemoveTreeDeathRecipient(const int32_t windowId, const int32_t treeId,
1025     const sptr<AccessibilityWindowConnection> connection)
1026 {
1027     auto object = connection->GetCardProxy(treeId)->AsObject();
1028     connection->EraseProxy(treeId);
1029     auto iter = interactionOperationDeathMap_.find(windowId);
1030     if (iter != interactionOperationDeathMap_.end()) {
1031         auto iterTree = iter->second.find(treeId);
1032         if (iterTree != iter->second.end()) {
1033             sptr<IRemoteObject::DeathRecipient> deathRecipient = iterTree->second;
1034             bool result = object->RemoveDeathRecipient(deathRecipient);
1035             HILOG_DEBUG("The result of deleting operation's death recipient is %{public}d", result);
1036             iter->second.erase(iterTree);
1037         } else {
1038             HILOG_ERROR("cannot find remote object. treeId[%{public}d]", treeId);
1039         }
1040     } else {
1041         HILOG_ERROR("cannot find remote object. windowId[%{public}d]", windowId);
1042     }
1043 }
1044 
GetCaptionProperty(AccessibilityConfig::CaptionProperty & caption)1045 RetError AccessibleAbilityManagerService::GetCaptionProperty(AccessibilityConfig::CaptionProperty &caption)
1046 {
1047     return accessibilitySettings_->GetCaptionProperty(caption);
1048 }
1049 
SetCaptionProperty(const AccessibilityConfig::CaptionProperty & caption)1050 RetError AccessibleAbilityManagerService::SetCaptionProperty(const AccessibilityConfig::CaptionProperty &caption)
1051 {
1052     return accessibilitySettings_->SetCaptionProperty(caption);
1053 }
1054 
SetCaptionState(const bool state)1055 RetError AccessibleAbilityManagerService::SetCaptionState(const bool state)
1056 {
1057     return accessibilitySettings_->SetCaptionState(state);
1058 }
1059 
GetEnabledState()1060 bool AccessibleAbilityManagerService::GetEnabledState()
1061 {
1062     HILOG_DEBUG();
1063     if (!handler_) {
1064         HILOG_ERROR("handler_ is nullptr.");
1065         return false;
1066     }
1067 
1068     std::promise<bool> syncPromise;
1069     std::future syncFuture = syncPromise.get_future();
1070     handler_->PostTask([this, &syncPromise]() {
1071         HILOG_DEBUG();
1072         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1073         if (!accountData) {
1074             HILOG_ERROR("accountData is nullptr");
1075             syncPromise.set_value(false);
1076             return;
1077         }
1078         bool result = accountData->GetConfig()->GetEnabledState();
1079         syncPromise.set_value(result);
1080         }, "TASK_GET_ENABLE_STATE");
1081     return syncFuture.get();
1082 }
1083 
GetCaptionState(bool & state)1084 RetError AccessibleAbilityManagerService::GetCaptionState(bool &state)
1085 {
1086     return accessibilitySettings_->GetCaptionState(state);
1087 }
1088 
GetTouchGuideState()1089 bool AccessibleAbilityManagerService::GetTouchGuideState()
1090 {
1091     HILOG_DEBUG();
1092     if (!handler_) {
1093         HILOG_ERROR("handler_ is nullptr.");
1094         return false;
1095     }
1096 
1097     std::promise<bool> syncPromise;
1098     std::future syncFuture = syncPromise.get_future();
1099     handler_->PostTask([this, &syncPromise]() {
1100         HILOG_DEBUG();
1101         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1102         if (!accountData) {
1103             HILOG_ERROR("accountData is nullptr");
1104             syncPromise.set_value(false);
1105             return;
1106         }
1107         bool result = accountData->GetConfig()->GetTouchGuideState();
1108         syncPromise.set_value(result);
1109         }, "TASK_GET_TOUCH_GUIDE_STATE");
1110     return syncFuture.get();
1111 }
1112 
GetGestureState()1113 bool AccessibleAbilityManagerService::GetGestureState()
1114 {
1115     HILOG_DEBUG();
1116     if (!handler_) {
1117         HILOG_ERROR("handler_ is nullptr.");
1118         return false;
1119     }
1120 
1121     std::promise<bool> syncPromise;
1122     std::future syncFuture = syncPromise.get_future();
1123     handler_->PostTask([this, &syncPromise]() {
1124         HILOG_DEBUG();
1125         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1126         if (!accountData) {
1127             HILOG_ERROR("accountData is nullptr");
1128             syncPromise.set_value(false);
1129             return;
1130         }
1131         bool result = accountData->GetConfig()->GetGestureState();
1132         syncPromise.set_value(result);
1133         }, "TASK_GET_GESTURE_STATE");
1134     return syncFuture.get();
1135 }
1136 
GetKeyEventObserverState()1137 bool AccessibleAbilityManagerService::GetKeyEventObserverState()
1138 {
1139     HILOG_DEBUG();
1140     if (!handler_) {
1141         HILOG_ERROR("handler_ is nullptr.");
1142         return false;
1143     }
1144 
1145     std::promise<bool> syncPromise;
1146     std::future syncFuture = syncPromise.get_future();
1147     handler_->PostTask([this, &syncPromise]() {
1148         HILOG_DEBUG();
1149         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1150         if (!accountData) {
1151             HILOG_ERROR("accountData is nullptr");
1152             syncPromise.set_value(false);
1153             return;
1154         }
1155         bool result = accountData->GetConfig()->GetKeyEventObserverState();
1156         syncPromise.set_value(result);
1157         }, "TASK_GET_KEY_EVENT_OBSERVER_STATE");
1158     return syncFuture.get();
1159 }
1160 
EnableAbility(const std::string & name,const uint32_t capabilities)1161 RetError AccessibleAbilityManagerService::EnableAbility(const std::string &name, const uint32_t capabilities)
1162 {
1163     HILOG_DEBUG();
1164     if (!handler_) {
1165         HILOG_ERROR("handler_ is nullptr.");
1166         return RET_ERR_NULLPTR;
1167     }
1168 
1169     std::promise<RetError> syncPromise;
1170     std::future syncFuture = syncPromise.get_future();
1171     handler_->PostTask([this, &syncPromise, &name, &capabilities]() {
1172         HILOG_DEBUG();
1173         RetError result = InnerEnableAbility(name, capabilities);
1174         syncPromise.set_value(result);
1175         }, "TASK_ENABLE_ABILITIES");
1176     return syncFuture.get();
1177 }
1178 
SetTargetAbility(const int32_t targetAbilityValue)1179 bool AccessibleAbilityManagerService::SetTargetAbility(const int32_t targetAbilityValue)
1180 {
1181     HILOG_DEBUG();
1182 
1183     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1184     if (!accountData) {
1185         HILOG_ERROR("accountData is nullptr");
1186         return false;
1187     }
1188 
1189     bool state;
1190     switch (targetAbilityValue) {
1191         case HIGH_CONTRAST_TEXT:
1192             state = accountData->GetConfig()->GetHighContrastTextState();
1193             return SetHighContrastTextState(!state) == RET_OK;
1194         case INVERT_COLOR:
1195             state = accountData->GetConfig()->GetInvertColorState();
1196             return SetInvertColorState(!state) == RET_OK;
1197         case ANIMATION_OFF:
1198             state = accountData->GetConfig()->GetAnimationOffState();
1199             return SetAnimationOffState(!state) == RET_OK;
1200         case SCREEN_MAGNIFICATION:
1201             state = accountData->GetConfig()->GetScreenMagnificationState();
1202             return SetScreenMagnificationState(!state) == RET_OK;
1203         case AUDIO_MONO:
1204             state = accountData->GetConfig()->GetAudioMonoState();
1205             return SetAudioMonoState(!state) == RET_OK;
1206         case MOUSE_KEY:
1207             state = accountData->GetConfig()->GetMouseKeyState();
1208             return SetMouseKeyState(!state) == RET_OK;
1209         case CAPTION_STATE:
1210             state = accountData->GetConfig()->GetCaptionState();
1211             return SetCaptionState(!state) == RET_OK;
1212         default:
1213             return false;
1214     }
1215 }
1216 
InnerEnableAbility(const std::string & name,const uint32_t capabilities)1217 RetError AccessibleAbilityManagerService::InnerEnableAbility(const std::string &name, const uint32_t capabilities)
1218 {
1219     HILOG_DEBUG();
1220     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1221     if (!accountData) {
1222         HILOG_ERROR("accountData is nullptr");
1223         return RET_ERR_NULLPTR;
1224     }
1225     auto iter = removedAutoStartAbilities_.begin();
1226     for (; iter != removedAutoStartAbilities_.end(); ++iter) {
1227         if (*iter == name) {
1228             removedAutoStartAbilities_.erase(iter);
1229             break;
1230         }
1231     }
1232     return accountData->EnableAbility(name, capabilities);
1233 }
1234 
GetEnabledAbilities(std::vector<std::string> & enabledAbilities)1235 RetError AccessibleAbilityManagerService::GetEnabledAbilities(std::vector<std::string> &enabledAbilities)
1236 {
1237     HILOG_DEBUG();
1238     if (!handler_) {
1239         HILOG_ERROR("handler_ is nullptr.");
1240         return RET_ERR_NULLPTR;
1241     }
1242 
1243     std::promise<RetError> syncPromise;
1244     std::future syncFuture = syncPromise.get_future();
1245     handler_->PostTask([this, &syncPromise, &enabledAbilities]() {
1246         HILOG_DEBUG();
1247         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1248         if (!accountData) {
1249             HILOG_ERROR("accountData is nullptr");
1250             syncPromise.set_value(RET_ERR_NULLPTR);
1251             return;
1252         }
1253         enabledAbilities = accountData->GetEnabledAbilities();
1254         syncPromise.set_value(RET_OK);
1255         }, "TASK_GET_ENABLE_ABILITIES");
1256     return syncFuture.get();
1257 }
1258 
DisableAbility(const std::string & name)1259 RetError AccessibleAbilityManagerService::DisableAbility(const std::string &name)
1260 {
1261     HILOG_INFO();
1262     if (!actionHandler_) {
1263         HILOG_ERROR("actionHandler_ is nullptr.");
1264         return RET_ERR_NULLPTR;
1265     }
1266 
1267     std::promise<RetError> syncPromise;
1268     std::future syncFuture = syncPromise.get_future();
1269     actionHandler_->PostTask([this, &syncPromise, &name]() {
1270         HILOG_DEBUG();
1271         RetError result = InnerDisableAbility(name);
1272         syncPromise.set_value(result);
1273         }, "TASK_DISABLE_ABILITIES");
1274     return syncFuture.get();
1275 }
1276 
InnerDisableAbility(const std::string & name)1277 RetError AccessibleAbilityManagerService::InnerDisableAbility(const std::string &name)
1278 {
1279     HILOG_INFO();
1280     HITRACE_METER_NAME(HITRACE_TAG_ACCESSIBILITY_MANAGER, "InnerDisableAbility:" + name);
1281 
1282     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1283     if (!accountData) {
1284         HILOG_ERROR("accountData is nullptr");
1285         return RET_ERR_NULLPTR;
1286     }
1287     if (accountData->GetConnectingA11yAbility(name) != nullptr) {
1288         HILOG_WARN("refuse to disconnect ability %{public}s when connecting", name.c_str());
1289         return RET_OK;
1290     }
1291     if (name == SCREEN_READER_BUNDLE_ABILITY_NAME) {
1292         ExecuteActionOnAccessibilityFocused(ACCESSIBILITY_ACTION_CLEAR_ACCESSIBILITY_FOCUS);
1293     }
1294     RetError ret = accountData->RemoveEnabledAbility(name);
1295     if (ret != RET_OK) {
1296         HILOG_ERROR("RemoveEnabledAbility failed");
1297         return ret;
1298     }
1299     accountData->SetAbilityAutoStartState(name, false);
1300     accountData->RemoveConnectingA11yAbility(name);
1301     accountData->UpdateAbilities();
1302     return RET_OK;
1303 }
1304 
EnableUITestAbility(const sptr<IRemoteObject> & obj)1305 RetError AccessibleAbilityManagerService::EnableUITestAbility(const sptr<IRemoteObject> &obj)
1306 {
1307     HILOG_DEBUG();
1308     if (!handler_) {
1309         HILOG_ERROR("handler_ is nullptr.");
1310         return RET_ERR_NULLPTR;
1311     }
1312 
1313     if (!obj) {
1314         HILOG_ERROR("obj is nullptr.");
1315         return RET_ERR_NULLPTR;
1316     }
1317 
1318     std::promise<RetError> syncPromise;
1319     std::future syncFuture = syncPromise.get_future();
1320     handler_->PostTask([this, &syncPromise, obj]() {
1321         HILOG_DEBUG();
1322         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1323         if (!accountData) {
1324             HILOG_ERROR("accountData is nullptr");
1325             syncPromise.set_value(RET_ERR_NULLPTR);
1326             return;
1327         }
1328         std::string uiTestUri = Utils::GetUri(UI_TEST_BUNDLE_NAME, UI_TEST_ABILITY_NAME);
1329         sptr<AccessibleAbilityConnection> connection = accountData->GetAccessibleAbilityConnection(uiTestUri);
1330         if (connection) {
1331             HILOG_ERROR("connection is existed!!");
1332             syncPromise.set_value(RET_ERR_CONNECTION_EXIST);
1333             return;
1334         }
1335 
1336         std::function<void()> addUITestClientFunc = std::bind(&AccessibilityAccountData::AddUITestClient, accountData,
1337             obj, UI_TEST_BUNDLE_NAME, UI_TEST_ABILITY_NAME);
1338         handler_->PostTask(addUITestClientFunc, "AddUITestClient");
1339         syncPromise.set_value(RET_OK);
1340         }, "TASK_ENABLE_UI_TEST_ABILITIES");
1341     return syncFuture.get();
1342 }
1343 
DisableUITestAbility()1344 RetError AccessibleAbilityManagerService::DisableUITestAbility()
1345 {
1346     HILOG_DEBUG();
1347     if (!handler_) {
1348         HILOG_ERROR("handler_ is nullptr.");
1349         return RET_ERR_NULLPTR;
1350     }
1351 
1352     std::shared_ptr<std::promise<RetError>> syncPromise = std::make_shared<std::promise<RetError>>();
1353     std::future syncFuture = syncPromise->get_future();
1354     handler_->PostTask([this, syncPromise]() {
1355         HILOG_DEBUG();
1356         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1357         if (!accountData) {
1358             HILOG_ERROR("accountData is nullptr");
1359             syncPromise->set_value(RET_ERR_NULLPTR);
1360             return;
1361         }
1362         std::string uiTestUri = Utils::GetUri(UI_TEST_BUNDLE_NAME, UI_TEST_ABILITY_NAME);
1363         sptr<AccessibleAbilityConnection> connection = accountData->GetAccessibleAbilityConnection(uiTestUri);
1364         if (!connection) {
1365             HILOG_ERROR("connection is not existed!!");
1366             syncPromise->set_value(RET_ERR_NO_CONNECTION);
1367             return;
1368         }
1369         std::function<void()> removeUITestClientFunc =
1370             std::bind(&AccessibilityAccountData::RemoveUITestClient, accountData, connection, UI_TEST_BUNDLE_NAME);
1371         handler_->PostTask(removeUITestClientFunc, "RemoveUITestClient");
1372         syncPromise->set_value(RET_OK);
1373         }, "TASK_DISABLE_UI_TEST_ABILITIES");
1374 
1375     std::future_status wait = syncFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
1376     if (wait != std::future_status::ready) {
1377         HILOG_ERROR("Failed to wait DisableUITestAbility result");
1378         return RET_ERR_TIME_OUT;
1379     }
1380     return syncFuture.get();
1381 }
1382 
GetActiveWindow()1383 int32_t AccessibleAbilityManagerService::GetActiveWindow()
1384 {
1385     HILOG_DEBUG();
1386     return Singleton<AccessibilityWindowManager>::GetInstance().activeWindowId_;
1387 }
1388 
Init()1389 bool AccessibleAbilityManagerService::Init()
1390 {
1391     HILOG_DEBUG();
1392     Singleton<AccessibilityCommonEvent>::GetInstance().SubscriberEvent(handler_);
1393 #ifdef OHOS_BUILD_ENABLE_DISPLAY_MANAGER
1394     Singleton<AccessibilityDisplayManager>::GetInstance().RegisterDisplayListener(handler_);
1395 #endif
1396     Singleton<AccessibilityWindowManager>::GetInstance().RegisterWindowListener(handler_);
1397     bool result = Singleton<AccessibilityWindowManager>::GetInstance().Init();
1398     HILOG_DEBUG("wms init result is %{public}d", result);
1399 
1400     int32_t retry = QUERY_USER_ID_RETRY_COUNT;
1401     int32_t sleepTime = QUERY_USER_ID_SLEEP_TIME;
1402     std::vector<int32_t> accountIds;
1403     ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds);
1404     while (ret != ERR_OK || accountIds.size() == 0) {
1405         HILOG_DEBUG("Query account information failed, left retry count:%{public}d", retry);
1406         if (retry == 0) {
1407             HILOG_ERROR("Query account information failed!!!");
1408             break;
1409         }
1410         std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
1411         ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds);
1412         retry--;
1413     }
1414 
1415     if (accountIds.size() > 0) {
1416         HILOG_DEBUG("Query account information success, account id:%{public}d", accountIds[0]);
1417         SwitchedUser(accountIds[0]);
1418     }
1419 
1420     return true;
1421 }
1422 
InitInnerResource()1423 void AccessibleAbilityManagerService::InitInnerResource()
1424 {
1425     UpdateSettingsInAtoHosTask();
1426 }
1427 
OnRemoteDied(const wptr<IRemoteObject> & remote)1428 void AccessibleAbilityManagerService::InteractionOperationDeathRecipient::OnRemoteDied(
1429     const wptr<IRemoteObject> &remote)
1430 {
1431     Utils::RecordUnavailableEvent(A11yUnavailableEvent::CONNECT_EVENT,
1432         A11yError::ERROR_TARGET_APPLICATION_DISCONNECT_ABNORMALLY);
1433     HILOG_INFO();
1434     if (treeId_ > 0) {
1435         Singleton<AccessibleAbilityManagerService>::GetInstance().DeregisterElementOperator(windowId_, treeId_);
1436     } else {
1437         Singleton<AccessibleAbilityManagerService>::GetInstance().DeregisterElementOperator(windowId_);
1438     }
1439 }
1440 
GetCurrentAccountData()1441 sptr<AccessibilityAccountData> AccessibleAbilityManagerService::GetCurrentAccountData()
1442 {
1443     HILOG_DEBUG();
1444     if (currentAccountId_ == -1) {
1445         HILOG_ERROR("current account id is wrong");
1446         return nullptr;
1447     }
1448 
1449     return a11yAccountsData_.GetCurrentAccountData(currentAccountId_);
1450 }
1451 
GetAccountData(int32_t accountId)1452 sptr<AccessibilityAccountData> AccessibleAbilityManagerService::GetAccountData(int32_t accountId)
1453 {
1454     HILOG_DEBUG();
1455     return a11yAccountsData_.GetAccountData(accountId);
1456 }
1457 
GetBundleMgrProxy()1458 sptr<AppExecFwk::IBundleMgr> AccessibleAbilityManagerService::GetBundleMgrProxy()
1459 {
1460     HILOG_DEBUG();
1461     if (bundleManager_) {
1462         return bundleManager_;
1463     }
1464 
1465     sptr<ISystemAbilityManager> systemAbilityManager =
1466         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1467     if (!systemAbilityManager) {
1468         HILOG_ERROR("failed:fail to get system ability mgr.");
1469         return nullptr;
1470     }
1471 
1472     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1473     if (!remoteObject) {
1474         HILOG_ERROR("failed:fail to get bundle manager proxy.");
1475         return nullptr;
1476     }
1477 
1478     bundleManager_ = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1479     if (!bundleManager_) {
1480         HILOG_ERROR("fail to new bundle manager.");
1481         return nullptr;
1482     }
1483 
1484     if (!bundleManagerDeathRecipient_) {
1485         bundleManagerDeathRecipient_ = new(std::nothrow) BundleManagerDeathRecipient();
1486         if (!bundleManagerDeathRecipient_) {
1487             HILOG_ERROR("bundleManagerDeathRecipient_ is null");
1488             return nullptr;
1489         }
1490     }
1491 
1492     bundleManager_->AsObject()->AddDeathRecipient(bundleManagerDeathRecipient_);
1493     return bundleManager_;
1494 }
1495 
GetAccessibilityWindowConnection(int32_t windowId)1496 sptr<AccessibilityWindowConnection> AccessibleAbilityManagerService::GetAccessibilityWindowConnection(
1497     int32_t windowId)
1498 {
1499     HILOG_DEBUG("windowId(%{public}d)", windowId);
1500     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1501     if (!accountData) {
1502         HILOG_ERROR("Get account data failed");
1503         return nullptr;
1504     }
1505     return accountData->GetAccessibilityWindowConnection(windowId);
1506 }
1507 
ClearFocus(int32_t windowId)1508 void AccessibleAbilityManagerService::ClearFocus(int32_t windowId)
1509 {
1510     HILOG_DEBUG();
1511     sptr<AccessibilityWindowConnection> connection = GetAccessibilityWindowConnection(windowId);
1512     if (connection && connection->GetProxy()) {
1513         connection->GetProxy()->ClearFocus();
1514     }
1515 }
1516 
OutsideTouch(int32_t windowId)1517 void AccessibleAbilityManagerService::OutsideTouch(int32_t windowId)
1518 {
1519     HILOG_DEBUG();
1520     sptr<AccessibilityWindowConnection> connection = GetAccessibilityWindowConnection(windowId);
1521     if (connection && connection->GetProxy()) {
1522         connection->GetProxy()->OutsideTouch();
1523     }
1524 }
1525 
SetTouchEventInjector(const sptr<TouchEventInjector> & touchEventInjector)1526 void AccessibleAbilityManagerService::SetTouchEventInjector(const sptr<TouchEventInjector> &touchEventInjector)
1527 {
1528     HILOG_DEBUG();
1529     touchEventInjector_ = touchEventInjector;
1530 }
1531 
SetKeyEventFilter(const sptr<KeyEventFilter> & keyEventFilter)1532 void AccessibleAbilityManagerService::SetKeyEventFilter(const sptr<KeyEventFilter> &keyEventFilter)
1533 {
1534     HILOG_DEBUG();
1535     keyEventFilter_ = keyEventFilter;
1536 }
1537 
OnRemoteDied(const wptr<IRemoteObject> & remote)1538 void AccessibleAbilityManagerService::StateCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
1539 {
1540     Singleton<AccessibleAbilityManagerService>::GetInstance().RemoveCallback(STATE_CALLBACK, this, remote);
1541 }
1542 
OnRemoteDied(const wptr<IRemoteObject> & remote)1543 void AccessibleAbilityManagerService::CaptionPropertyCallbackDeathRecipient::OnRemoteDied(
1544     const wptr<IRemoteObject> &remote)
1545 {
1546     Singleton<AccessibleAbilityManagerService>::GetInstance().RemoveCallback(CAPTION_PROPERTY_CALLBACK, this, remote);
1547 }
1548 
OnRemoteDied(const wptr<IRemoteObject> & remote)1549 void AccessibleAbilityManagerService::EnableAbilityListsObserverDeathRecipient::OnRemoteDied(
1550     const wptr<IRemoteObject> &remote)
1551 {
1552     Singleton<AccessibleAbilityManagerService>::GetInstance().RemoveCallback(
1553         ENABLE_ABILITY_LISTS_CALLBACK, this, remote);
1554 }
1555 
AddedUser(int32_t accountId)1556 void AccessibleAbilityManagerService::AddedUser(int32_t accountId)
1557 {
1558     HILOG_DEBUG();
1559     a11yAccountsData_.AddAccountData(accountId);
1560 }
1561 
RemovedUser(int32_t accountId)1562 void AccessibleAbilityManagerService::RemovedUser(int32_t accountId)
1563 {
1564     HILOG_DEBUG();
1565     if (accountId == currentAccountId_) {
1566         HILOG_ERROR("Remove user failed, this account is current account.");
1567         return;
1568     }
1569 
1570     auto accountData = a11yAccountsData_.RemoveAccountData(accountId);
1571     if (accountData) {
1572         accountData->GetConfig()->ClearData();
1573         return;
1574     }
1575 
1576     HILOG_ERROR("accountId is not exist");
1577 }
1578 
SwitchedUser(int32_t accountId)1579 void AccessibleAbilityManagerService::SwitchedUser(int32_t accountId)
1580 {
1581     HILOG_DEBUG();
1582 
1583     if (accountId == currentAccountId_) {
1584         HILOG_WARN("The account is current account id.");
1585         return;
1586     }
1587     OffZoomGesture();
1588 
1589     std::map<std::string, uint32_t> importantEnabledAbilities;
1590     SCREENREADER_STATE screenReaderState = SCREENREADER_STATE::UNINIT;
1591     // Clear last account's data
1592     if (currentAccountId_ != -1) {
1593         HILOG_DEBUG();
1594         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1595         if (!accountData) {
1596             HILOG_ERROR("Current account data is null");
1597             return;
1598         }
1599         defaultConfigCallbacks_ = accountData->GetConfigCallbacks();
1600         screenReaderState = accountData->GetDefaultUserScreenReaderState() ?
1601             SCREENREADER_STATE::ON : SCREENREADER_STATE::OFF;
1602         accountData->GetImportantEnabledAbilities(importantEnabledAbilities);
1603         accountData->OnAccountSwitched();
1604         UpdateAccessibilityManagerService();
1605     }
1606 
1607     // Switch account id
1608     currentAccountId_ = accountId;
1609 
1610     // Initialize data for current account
1611     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1612     if (!accountData) {
1613         HILOG_ERROR("accountData is nullptr.");
1614         return;
1615     }
1616     accountData->Init();
1617     accountData->SetConfigCallbacks(defaultConfigCallbacks_);
1618 #ifdef OHOS_BUILD_ENABLE_POWER_MANAGER
1619     float discount = accountData->GetConfig()->GetBrightnessDiscount();
1620     if (!Singleton<AccessibilityPowerManager>::GetInstance().DiscountBrightness(discount)) {
1621         HILOG_ERROR("Failed to set brightness discount");
1622     }
1623 #endif
1624     AccountSA::OsAccountType accountType = accountData->GetAccountType();
1625     if (screenReaderState != SCREENREADER_STATE::UNINIT &&
1626         (accountType == AccountSA::OsAccountType::PRIVATE || accountType == AccountSA::OsAccountType::ADMIN)) {
1627         bool state = (screenReaderState == SCREENREADER_STATE::ON) ? true : false;
1628         accountData->SetAbilityAutoStartState(SCREEN_READER_BUNDLE_ABILITY_NAME, state);
1629         HILOG_INFO("set screenreader auto-start state = %{public}d", true);
1630     }
1631 
1632     if (accountData->GetInstalledAbilitiesFromBMS()) {
1633         accountData->UpdateImportantEnabledAbilities(importantEnabledAbilities);
1634         accountData->UpdateAbilities();
1635         UpdateAccessibilityManagerService();
1636     }
1637     UpdateAllSetting();
1638     UpdateAutoStartAbilities();
1639     RegisterShortKeyEvent();
1640     RegisterScreenMagnificationState();
1641     RegisterScreenMagnificationType();
1642 }
1643 
PackageRemoved(const std::string & bundleName)1644 void AccessibleAbilityManagerService::PackageRemoved(const std::string &bundleName)
1645 {
1646     sptr<AccessibilityAccountData> packageAccount = GetCurrentAccountData();
1647     if (!packageAccount) {
1648         HILOG_ERROR("packageAccount is nullptr.");
1649         return;
1650     }
1651 
1652     packageAccount->DelAutoStartPrefKeyInRemovePkg(bundleName);
1653     std::vector<std::string> multiTarget = packageAccount->GetConfig()->GetShortkeyMultiTarget();
1654     std::string name = packageAccount->GetConfig()->GetShortkeyTarget();
1655     auto installedAbilities_ = packageAccount->GetInstalledAbilities();
1656     for (auto &installAbility : installedAbilities_) {
1657         std::string abilityId = installAbility.GetId();
1658         HILOG_DEBUG("abilityId%{public}s", abilityId.c_str());
1659         if (bundleName != installAbility.GetPackageName()) {
1660             continue;
1661         }
1662         if (std::find(removedAutoStartAbilities_.begin(), removedAutoStartAbilities_.end(), abilityId)
1663             == removedAutoStartAbilities_.end()) {
1664             removedAutoStartAbilities_.push_back(abilityId);
1665         }
1666         // no use later version
1667         if (abilityId == name) {
1668             std::string targetName = "";
1669             packageAccount->GetConfig()->SetShortkeyTarget(targetName);
1670             UpdateShortkeyTarget();
1671         }
1672         // multi
1673         for (const auto &target : multiTarget) {
1674             if (target == abilityId) {
1675                 packageAccount->GetConfig()->SetShortkeyMultiTargetInPkgRemove(abilityId);
1676                 UpdateShortkeyMultiTarget();
1677             }
1678         }
1679     }
1680 
1681     if (packageAccount->RemoveAbility(bundleName)) {
1682         HILOG_DEBUG("ability%{public}s removed!", bundleName.c_str());
1683         UpdateAccessibilityManagerService();
1684     }
1685 }
1686 
PackageAdd(const std::string & bundleName)1687 void AccessibleAbilityManagerService::PackageAdd(const std::string &bundleName)
1688 {
1689     sptr<AccessibilityAccountData> packageAccount = GetCurrentAccountData();
1690     if (!packageAccount) {
1691         HILOG_ERROR("packageAccount is nullptr");
1692         return;
1693     }
1694     for (auto &abilityId : removedAutoStartAbilities_) {
1695         if (packageAccount->GetAbilityAutoStartState(abilityId)) {
1696             packageAccount->SetAbilityAutoStartState(abilityId, false);
1697         }
1698     }
1699     packageAccount->AddAbility(bundleName);
1700 }
1701 
PackageChanged(const std::string & bundleName)1702 void AccessibleAbilityManagerService::PackageChanged(const std::string &bundleName)
1703 {
1704     sptr<AccessibilityAccountData> packageAccount = GetCurrentAccountData();
1705     if (!packageAccount) {
1706         HILOG_ERROR("packageAccount is nullptr");
1707         return;
1708     }
1709 
1710     bool isNeedUpdateShortKeyTarget = false;
1711     std::string target = packageAccount->GetConfig()->GetShortkeyTarget();
1712     if (target.substr(0, target.find("/")) == bundleName) {
1713         isNeedUpdateShortKeyTarget = true;
1714     }
1715     std::vector<std::string> multiTarget = packageAccount->GetConfig()->GetShortkeyMultiTarget();
1716 
1717     packageAccount->ChangeAbility(bundleName);
1718     UpdateAccessibilityManagerService();
1719 
1720     std::vector<std::string> sameBundleTarget;
1721     auto installedAbilities_ = packageAccount->GetInstalledAbilities();
1722     for (auto &installAbility : installedAbilities_) {
1723         std::string abilityId = installAbility.GetId();
1724         if (bundleName != installAbility.GetPackageName()) {
1725             continue;
1726         }
1727         if (abilityId == target) {
1728             isNeedUpdateShortKeyTarget = false;
1729         }
1730         sameBundleTarget.push_back(abilityId);
1731     }
1732 
1733     if (isNeedUpdateShortKeyTarget) {
1734         packageAccount->GetConfig()->SetShortkeyTarget("");
1735         UpdateShortkeyTarget();
1736     }
1737     std::vector<std::string> tmpAbilities = multiTarget;
1738     bool isNeedUpdateShortKeyMultiTarget = false;
1739     Utils::SelectUsefulFromVecWithSameBundle(tmpAbilities, sameBundleTarget,
1740         isNeedUpdateShortKeyMultiTarget, bundleName);
1741     if (isNeedUpdateShortKeyMultiTarget) {
1742         packageAccount->GetConfig()->SetShortkeyMultiTarget(tmpAbilities);
1743         UpdateShortkeyMultiTarget();
1744     }
1745 }
1746 
SetFindFocusedElementInfoResult(const AccessibilityElementInfo & info,const int32_t requestId)1747 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetFindFocusedElementInfoResult(
1748     const AccessibilityElementInfo &info, const int32_t requestId)
1749 {
1750     HILOG_DEBUG("Response [requestId:%{public}d]", requestId);
1751     if (Singleton<AccessibleAbilityManagerService>::GetInstance().VerifyingToKenId(info.GetWindowId(),
1752         info.GetAccessibilityId()) == RET_OK) {
1753         HILOG_DEBUG("VerifyingToKenId ok");
1754         accessibilityInfoResult_ = info;
1755         promise_.set_value();
1756     } else {
1757         HILOG_DEBUG("VerifyingToKenId failed");
1758         promise_.set_value();
1759     }
1760 }
1761 
SetSearchElementInfoByTextResult(const std::vector<AccessibilityElementInfo> & infos,const int32_t requestId)1762 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetSearchElementInfoByTextResult(
1763     const std::vector<AccessibilityElementInfo> &infos, const int32_t requestId)
1764 {
1765     HILOG_DEBUG("Response [requestId:%{public}d]", requestId);
1766     for (auto info : infos) {
1767         if (Singleton<AccessibleAbilityManagerService>::GetInstance().VerifyingToKenId(info.GetWindowId(),
1768             info.GetAccessibilityId()) == RET_OK) {
1769             HILOG_DEBUG("VerifyingToKenId ok");
1770         } else {
1771             HILOG_DEBUG("VerifyingToKenId failed");
1772             elementInfosResult_.clear();
1773             promise_.set_value();
1774             return;
1775         }
1776         elementInfosResult_ = infos;
1777     }
1778     promise_.set_value();
1779 }
1780 
SetSearchElementInfoByAccessibilityIdResult(const std::vector<AccessibilityElementInfo> & infos,const int32_t requestId)1781 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetSearchElementInfoByAccessibilityIdResult(
1782     const std::vector<AccessibilityElementInfo> &infos, const int32_t requestId)
1783 {
1784     HILOG_DEBUG("Response [requestId:%{public}d]", requestId);
1785     for (auto info : infos) {
1786         if (Singleton<AccessibleAbilityManagerService>::GetInstance().VerifyingToKenId(info.GetWindowId(),
1787             info.GetAccessibilityId()) == RET_OK) {
1788             HILOG_DEBUG("VerifyingToKenId ok");
1789         } else {
1790             HILOG_DEBUG("VerifyingToKenId failed");
1791             elementInfosResult_.clear();
1792             promise_.set_value();
1793             return;
1794         }
1795         elementInfosResult_ = infos;
1796     }
1797     promise_.set_value();
1798 }
1799 
SetFocusMoveSearchResult(const AccessibilityElementInfo & info,const int32_t requestId)1800 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetFocusMoveSearchResult(
1801     const AccessibilityElementInfo &info, const int32_t requestId)
1802 {
1803     HILOG_DEBUG("Response [requestId:%{public}d]", requestId);
1804     if (Singleton<AccessibleAbilityManagerService>::GetInstance().VerifyingToKenId(info.GetWindowId(),
1805         info.GetAccessibilityId()) == RET_OK) {
1806         HILOG_DEBUG("VerifyingToKenId ok");
1807         accessibilityInfoResult_ = info;
1808         promise_.set_value();
1809     } else {
1810         HILOG_DEBUG("VerifyingToKenId failed");
1811         promise_.set_value();
1812     }
1813 }
1814 
SetExecuteActionResult(const bool succeeded,const int32_t requestId)1815 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetExecuteActionResult(const bool succeeded,
1816     const int32_t requestId)
1817 {
1818     HILOG_DEBUG("Response [result:%{public}d, requestId:%{public}d]", succeeded, requestId);
1819     executeActionResult_ = succeeded;
1820     promise_.set_value();
1821 }
1822 
SetCursorPositionResult(const int32_t cursorPosition,const int32_t requestId)1823 void AccessibleAbilityManagerService::ElementOperatorCallbackImpl::SetCursorPositionResult(const int32_t cursorPosition,
1824     const int32_t requestId)
1825 {
1826     HILOG_INFO("ElementOperatorCallbackImpl::SetCursorPositionResult [result:%{public}d]",
1827         cursorPosition);
1828     HILOG_DEBUG("cursorPosition [result:%{public}d, requestId:%{public}d]", cursorPosition, requestId);
1829     callCursorPosition_ = cursorPosition;
1830     promise_.set_value();
1831 }
1832 
GetParentElementRecursively(int32_t windowId,int64_t elementId,std::vector<AccessibilityElementInfo> & infos)1833 bool AccessibleAbilityManagerService::GetParentElementRecursively(int32_t windowId, int64_t elementId,
1834     std::vector<AccessibilityElementInfo>& infos)
1835 {
1836     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1837     if (!accountData) {
1838         HILOG_ERROR("GetCurrentAccountData failed");
1839         return false;
1840     }
1841 
1842     int32_t treeId = 0;
1843     sptr<IAccessibilityElementOperator> elementOperator = nullptr;
1844     sptr<AccessibilityWindowConnection> connection = accountData->GetAccessibilityWindowConnection(windowId);
1845     if (!connection) {
1846         HILOG_ERROR("GetAccessibilityWindowConnection failed");
1847         return false;
1848     }
1849 
1850     if (elementId > 0) {
1851         treeId = GetTreeIdBySplitElementId(elementId);
1852         elementOperator = connection->GetCardProxy(treeId);
1853     } else {
1854         elementOperator = connection->GetProxy();
1855     }
1856     if (elementOperator == nullptr) {
1857         HILOG_DEBUG("elementOperator failed elementId: %{public}" PRId64 " winId: %{public}d treeId: %{public}d",
1858             elementId, windowId, treeId);
1859         return false;
1860     }
1861     sptr<ElementOperatorCallbackImpl> callBack = new(std::nothrow) ElementOperatorCallbackImpl();
1862     if (callBack == nullptr) {
1863         HILOG_ERROR("Failed to create callBack.");
1864         return false;
1865     }
1866 
1867     std::future<void> promiseFuture = callBack->promise_.get_future();
1868     elementOperator->SearchElementInfoByAccessibilityId(elementId, GenerateRequestId(), callBack, 0);
1869     std::future_status waitFocus = promiseFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
1870     if (waitFocus != std::future_status::ready) {
1871         ipcTimeoutNum_++;
1872         HILOG_ERROR("Failed to wait result, number %{public}" PRId64 "", ipcTimeoutNum_);
1873         return false;
1874     }
1875 
1876     for (auto& info : callBack->elementInfosResult_) {
1877         if (info.GetAccessibilityId() == AccessibilityElementInfo::UNDEFINED_ACCESSIBILITY_ID) {
1878             HILOG_ERROR("SearchElementInfoByAccessibilityId elementInfo from ace is wrong");
1879             return false;
1880         }
1881     }
1882 
1883     infos = callBack->elementInfosResult_;
1884     HILOG_DEBUG("Get parent element success, size %{public}zu", infos.size());
1885     return true;
1886 }
1887 
FindInnerWindowId(const AccessibilityEventInfo & event,int32_t & windowId)1888 void AccessibleAbilityManagerService::FindInnerWindowId(const AccessibilityEventInfo &event, int32_t& windowId)
1889 {
1890     HILOG_DEBUG();
1891     auto mapTable = Singleton<AccessibilityWindowManager>::GetInstance().sceneBoardElementIdMap_.GetAllPairs();
1892     int64_t elementId = event.GetAccessibilityId();
1893     while (1) {
1894         for (auto iter = mapTable.begin(); iter != mapTable.end(); iter++) {
1895             if (elementId == iter->second) {
1896                 windowId = iter->first;
1897                 HILOG_DEBUG("inner windowId %{public}d", windowId);
1898                 return;
1899             }
1900         }
1901 
1902         std::vector<AccessibilityElementInfo> infos = {};
1903         if (GetParentElementRecursively(event.GetWindowId(), elementId, infos) == false || infos.size() == 0) {
1904             HILOG_ERROR("find parent element failed");
1905             return;
1906         }
1907 
1908         if (infos[0].GetComponentType() == "root") {
1909             HILOG_ERROR("can not find parent element, has reach root node");
1910             return;
1911         }
1912 
1913         elementId = infos[0].GetParentNodeId();
1914     }
1915 }
1916 
UpdateAccessibilityWindowStateByEvent(const AccessibilityEventInfo & event)1917 void AccessibleAbilityManagerService::UpdateAccessibilityWindowStateByEvent(const AccessibilityEventInfo &event)
1918 {
1919     EventType evtType = event.GetEventType();
1920     HILOG_DEBUG("windowId is %{public}d", event.GetWindowId());
1921     int32_t windowId = event.GetWindowId();
1922     if (windowId == 1 && (evtType == TYPE_VIEW_HOVER_ENTER_EVENT || evtType == TYPE_VIEW_ACCESSIBILITY_FOCUSED_EVENT)) {
1923         FindInnerWindowId(event, windowId);
1924     }
1925 
1926     switch (evtType) {
1927         case TYPE_VIEW_HOVER_ENTER_EVENT:
1928         case TYPE_VIEW_ACCESSIBILITY_FOCUSED_EVENT:
1929             Singleton<AccessibilityWindowManager>::GetInstance().SetActiveWindow(windowId, false);
1930             Singleton<AccessibilityWindowManager>::GetInstance().SetAccessibilityFocusedWindow(windowId);
1931             break;
1932         default:
1933             break;
1934     }
1935 }
1936 
UpdateAccessibilityManagerService()1937 void AccessibleAbilityManagerService::UpdateAccessibilityManagerService()
1938 {
1939     HILOG_DEBUG("start.");
1940 
1941     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1942     if (!accountData) {
1943         HILOG_ERROR("Account data is null");
1944         return;
1945     }
1946 
1947     accountData->UpdateAccountCapabilities();
1948     UpdateInputFilter();
1949     UpdateAccessibilityState();
1950     UpdateShortKeyRegister();
1951 }
1952 
UpdateAccessibilityState()1953 void AccessibleAbilityManagerService::UpdateAccessibilityState()
1954 {
1955     HILOG_DEBUG("start.");
1956     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1957     if (!accountData) {
1958         HILOG_ERROR("Account data is null");
1959         return;
1960     }
1961     uint32_t state = accountData->GetAccessibilityState();
1962     if (!(state & STATE_ACCESSIBILITY_ENABLED)) {
1963         Singleton<AccessibilityWindowManager>::GetInstance().ClearAccessibilityFocused();
1964     }
1965 
1966     stateObservers_.OnStateObservers(state);
1967 }
1968 
UpdateCaptionProperty()1969 void AccessibleAbilityManagerService::UpdateCaptionProperty()
1970 {
1971     return accessibilitySettings_->UpdateCaptionProperty();
1972 }
1973 
UpdateSettingsInAtoHosTask()1974 void AccessibleAbilityManagerService::UpdateSettingsInAtoHosTask()
1975 {
1976     HILOG_DEBUG();
1977     if (!handler_) {
1978         HILOG_ERROR("UpdateSettingsInAtoHosTask: handler is nullptr!");
1979         return;
1980     }
1981     handler_->PostTask([=]() {
1982         UpdateSettingsInAtoHos();
1983         }, "UPDATE_SETTINGS_IN_ATOHOS_TASK");
1984 }
1985 
UpdateAutoStartAbilities()1986 void AccessibleAbilityManagerService::UpdateAutoStartAbilities()
1987 {
1988     HILOG_DEBUG();
1989     if (!handler_) {
1990         HILOG_ERROR("UpdateAutoStartAbilities: handler is nullptr.");
1991         return;
1992     }
1993 
1994     handler_->PostTask([=]() {
1995         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
1996         if (!accountData) {
1997             HILOG_ERROR("Account data is null");
1998             return;
1999         }
2000         for (auto &abilityId : removedAutoStartAbilities_) {
2001             if (accountData->GetAbilityAutoStartState(abilityId)) {
2002                 accountData->SetAbilityAutoStartState(abilityId, false);
2003             }
2004         }
2005         accountData->UpdateAutoStartEnabledAbilities();
2006         accountData->UpdateAbilities();
2007         }, "UPDATE_AUTO_START_ABILITIES");
2008 }
2009 
UpdateSettingsInAtoHos()2010 void AccessibleAbilityManagerService::UpdateSettingsInAtoHos()
2011 {
2012     HILOG_DEBUG();
2013     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2014     if (!accountData) {
2015         HILOG_ERROR("accountData is nullptr.");
2016         return;
2017     }
2018 
2019     if (!accountData->GetConfig()->GetStartFromAtoHosState() || currentAccountId_ != DEFAULT_ACCOUNT_ID) {
2020         HILOG_INFO("Not first start from a to hos.");
2021         return;
2022     }
2023     accessibilitySettings_->UpdateSettingsInAtoHos();
2024 }
2025 
UpdateInputFilter()2026 void AccessibleAbilityManagerService::UpdateInputFilter()
2027 {
2028     HILOG_DEBUG("start.");
2029 
2030     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2031     if (!accountData) {
2032         HILOG_ERROR("Account data is null");
2033         return;
2034     }
2035 
2036     uint32_t flag = accountData->GetInputFilterFlag();
2037     HILOG_DEBUG("InputInterceptor flag is %{public}d", flag);
2038 
2039     inputInterceptor_ = AccessibilityInputInterceptor::GetInstance();
2040     if (!inputInterceptor_) {
2041         HILOG_ERROR("inputInterceptor_ is null.");
2042         return;
2043     }
2044     inputInterceptor_->SetAvailableFunctions(flag);
2045     Utils::RecordStartingA11yEvent(flag);
2046 }
2047 
UpdateAllSetting()2048 void AccessibleAbilityManagerService::UpdateAllSetting()
2049 {
2050     accessibilitySettings_->UpdateAllSetting();
2051 }
2052 
UpdateShortKeyRegister()2053 void AccessibleAbilityManagerService::UpdateShortKeyRegister()
2054 {
2055     HILOG_DEBUG();
2056 
2057     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2058     if (accountData == nullptr) {
2059         HILOG_ERROR("Account data is null!");
2060         return;
2061     }
2062 
2063     bool shortKeyState = accountData->GetConfig()->GetShortKeyState();
2064     if (shortKeyState) {
2065         accessibilityShortKey_ = nullptr;
2066         accessibilityShortKey_ = new (std::nothrow) AccessibilityShortKey();
2067         if (accessibilityShortKey_ == nullptr) {
2068             HILOG_ERROR("Create AccessibilityShortKey failed");
2069             return;
2070         }
2071         accessibilityShortKey_->Register();
2072     } else {
2073         accessibilityShortKey_ = nullptr;
2074     }
2075 }
2076 
SetScreenMagnificationState(const bool state)2077 RetError AccessibleAbilityManagerService::SetScreenMagnificationState(const bool state)
2078 {
2079     return accessibilitySettings_->SetScreenMagnificationState(state);
2080 }
2081 
SetShortKeyState(const bool state)2082 RetError AccessibleAbilityManagerService::SetShortKeyState(const bool state)
2083 {
2084     return accessibilitySettings_->SetShortKeyState(state);
2085 }
2086 
SetMouseKeyState(const bool state)2087 RetError AccessibleAbilityManagerService::SetMouseKeyState(const bool state)
2088 {
2089     return accessibilitySettings_->SetMouseKeyState(state);
2090 }
2091 
SetMouseAutoClick(const int32_t time)2092 RetError AccessibleAbilityManagerService::SetMouseAutoClick(const int32_t time)
2093 {
2094     return accessibilitySettings_->SetMouseAutoClick(time);
2095 }
2096 
SetShortkeyTarget(const std::string & name)2097 RetError AccessibleAbilityManagerService::SetShortkeyTarget(const std::string &name)
2098 {
2099     return accessibilitySettings_->SetShortkeyTarget(name);
2100 }
2101 
SetShortkeyMultiTarget(const std::vector<std::string> & name)2102 RetError AccessibleAbilityManagerService::SetShortkeyMultiTarget(const std::vector<std::string> &name)
2103 {
2104     return accessibilitySettings_->SetShortkeyMultiTarget(name);
2105 }
2106 
SetHighContrastTextState(const bool state)2107 RetError AccessibleAbilityManagerService::SetHighContrastTextState(const bool state)
2108 {
2109     return accessibilitySettings_->SetHighContrastTextState(state);
2110 }
2111 
SetDaltonizationState(const bool state)2112 RetError AccessibleAbilityManagerService::SetDaltonizationState(const bool state)
2113 {
2114     return accessibilitySettings_->SetDaltonizationState(state);
2115 }
2116 
SetInvertColorState(const bool state)2117 RetError AccessibleAbilityManagerService::SetInvertColorState(const bool state)
2118 {
2119     return accessibilitySettings_->SetInvertColorState(state);
2120 }
2121 
SetAnimationOffState(const bool state)2122 RetError AccessibleAbilityManagerService::SetAnimationOffState(const bool state)
2123 {
2124     return accessibilitySettings_->SetAnimationOffState(state);
2125 }
2126 
SetAudioMonoState(const bool state)2127 RetError AccessibleAbilityManagerService::SetAudioMonoState(const bool state)
2128 {
2129     return accessibilitySettings_->SetAudioMonoState(state);
2130 }
2131 
SetDaltonizationColorFilter(const uint32_t filter)2132 RetError AccessibleAbilityManagerService::SetDaltonizationColorFilter(const uint32_t filter)
2133 {
2134     return accessibilitySettings_->SetDaltonizationColorFilter(filter);
2135 }
2136 
SetContentTimeout(const uint32_t time)2137 RetError AccessibleAbilityManagerService::SetContentTimeout(const uint32_t time)
2138 {
2139     return accessibilitySettings_->SetContentTimeout(time);
2140 }
2141 
SetBrightnessDiscount(const float discount)2142 RetError AccessibleAbilityManagerService::SetBrightnessDiscount(const float discount)
2143 {
2144     return accessibilitySettings_->SetBrightnessDiscount(discount);
2145 }
2146 
SetAudioBalance(const float balance)2147 RetError AccessibleAbilityManagerService::SetAudioBalance(const float balance)
2148 {
2149     return accessibilitySettings_->SetAudioBalance(balance);
2150 }
2151 
SetClickResponseTime(const uint32_t time)2152 RetError AccessibleAbilityManagerService::SetClickResponseTime(const uint32_t time)
2153 {
2154     return accessibilitySettings_->SetClickResponseTime(time);
2155 }
2156 
SetIgnoreRepeatClickState(const bool state)2157 RetError AccessibleAbilityManagerService::SetIgnoreRepeatClickState(const bool state)
2158 {
2159     return accessibilitySettings_->SetIgnoreRepeatClickState(state);
2160 }
2161 
SetIgnoreRepeatClickTime(const uint32_t time)2162 RetError AccessibleAbilityManagerService::SetIgnoreRepeatClickTime(const uint32_t time)
2163 {
2164     return accessibilitySettings_->SetIgnoreRepeatClickTime(time);
2165 }
2166 
GetScreenMagnificationState(bool & state)2167 RetError AccessibleAbilityManagerService::GetScreenMagnificationState(bool &state)
2168 {
2169     return accessibilitySettings_->GetScreenMagnificationState(state);
2170 }
2171 
GetShortKeyState(bool & state)2172 RetError AccessibleAbilityManagerService::GetShortKeyState(bool &state)
2173 {
2174     return accessibilitySettings_->GetShortKeyState(state);
2175 }
2176 
GetMouseKeyState(bool & state)2177 RetError AccessibleAbilityManagerService::GetMouseKeyState(bool &state)
2178 {
2179     return accessibilitySettings_->GetMouseKeyState(state);
2180 }
2181 
GetMouseAutoClick(int32_t & time)2182 RetError AccessibleAbilityManagerService::GetMouseAutoClick(int32_t &time)
2183 {
2184     return accessibilitySettings_->GetMouseAutoClick(time);
2185 }
2186 
GetShortkeyTarget(std::string & name)2187 RetError AccessibleAbilityManagerService::GetShortkeyTarget(std::string &name)
2188 {
2189     return accessibilitySettings_->GetShortkeyTarget(name);
2190 }
2191 
GetShortkeyMultiTarget(std::vector<std::string> & name)2192 RetError AccessibleAbilityManagerService::GetShortkeyMultiTarget(std::vector<std::string> &name)
2193 {
2194     return accessibilitySettings_->GetShortkeyMultiTarget(name);
2195 }
2196 
GetHighContrastTextState(bool & state)2197 RetError AccessibleAbilityManagerService::GetHighContrastTextState(bool &state)
2198 {
2199     return accessibilitySettings_->GetHighContrastTextState(state);
2200 }
2201 
GetDaltonizationState(bool & state)2202 RetError AccessibleAbilityManagerService::GetDaltonizationState(bool &state)
2203 {
2204     return accessibilitySettings_->GetDaltonizationState(state);
2205 }
2206 
GetInvertColorState(bool & state)2207 RetError AccessibleAbilityManagerService::GetInvertColorState(bool &state)
2208 {
2209     return accessibilitySettings_->GetInvertColorState(state);
2210 }
2211 
GetAnimationOffState(bool & state)2212 RetError AccessibleAbilityManagerService::GetAnimationOffState(bool &state)
2213 {
2214     return accessibilitySettings_->GetAnimationOffState(state);
2215 }
2216 
GetAudioMonoState(bool & state)2217 RetError AccessibleAbilityManagerService::GetAudioMonoState(bool &state)
2218 {
2219     return accessibilitySettings_->GetAudioMonoState(state);
2220 }
2221 
GetDaltonizationColorFilter(uint32_t & type)2222 RetError AccessibleAbilityManagerService::GetDaltonizationColorFilter(uint32_t &type)
2223 {
2224     return accessibilitySettings_->GetDaltonizationColorFilter(type);
2225 }
2226 
GetContentTimeout(uint32_t & timer)2227 RetError AccessibleAbilityManagerService::GetContentTimeout(uint32_t &timer)
2228 {
2229     return accessibilitySettings_->GetContentTimeout(timer);
2230 }
2231 
GetBrightnessDiscount(float & brightness)2232 RetError AccessibleAbilityManagerService::GetBrightnessDiscount(float &brightness)
2233 {
2234     return accessibilitySettings_->GetBrightnessDiscount(brightness);
2235 }
2236 
GetAudioBalance(float & balance)2237 RetError AccessibleAbilityManagerService::GetAudioBalance(float &balance)
2238 {
2239     return accessibilitySettings_->GetAudioBalance(balance);
2240 }
2241 
GetClickResponseTime(uint32_t & time)2242 RetError AccessibleAbilityManagerService::GetClickResponseTime(uint32_t &time)
2243 {
2244     return accessibilitySettings_->GetClickResponseTime(time);
2245 }
2246 
GetIgnoreRepeatClickState(bool & state)2247 RetError AccessibleAbilityManagerService::GetIgnoreRepeatClickState(bool &state)
2248 {
2249     return accessibilitySettings_->GetIgnoreRepeatClickState(state);
2250 }
2251 
GetIgnoreRepeatClickTime(uint32_t & time)2252 RetError AccessibleAbilityManagerService::GetIgnoreRepeatClickTime(uint32_t &time)
2253 {
2254     return accessibilitySettings_->GetIgnoreRepeatClickTime(time);
2255 }
2256 
GetAllConfigs(AccessibilityConfigData & configData)2257 void AccessibleAbilityManagerService::GetAllConfigs(AccessibilityConfigData &configData)
2258 {
2259     HILOG_DEBUG();
2260     std::shared_ptr<std::promise<void>> syncPromise = std::make_shared<std::promise<void>>();
2261     std::shared_ptr<AccessibilityConfigData> config = std::make_shared<AccessibilityConfigData>();
2262     if (syncPromise == nullptr || config == nullptr) {
2263         HILOG_WARN("create syncPromise or config failed");
2264         return;
2265     }
2266     std::future syncFuture = syncPromise->get_future();
2267     actionHandler_->PostTask([this, syncPromise, config]() {
2268         HILOG_DEBUG();
2269         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2270         if (!accountData) {
2271             HILOG_ERROR("accountData is nullptr");
2272             syncPromise->set_value();
2273             return;
2274         }
2275 
2276         config->highContrastText_ = accountData->GetConfig()->GetHighContrastTextState();
2277         config->daltonizationState_ = accountData->GetConfig()->GetDaltonizationState();
2278         config->invertColor_ = accountData->GetConfig()->GetInvertColorState();
2279         config->animationOff_ = accountData->GetConfig()->GetAnimationOffState();
2280         config->audioMono_ = accountData->GetConfig()->GetAudioMonoState();
2281         config->mouseKey_ = accountData->GetConfig()->GetMouseKeyState();
2282         config->captionState_ = accountData->GetConfig()->GetCaptionState();
2283         config->screenMagnifier_ = accountData->GetConfig()->GetScreenMagnificationState();
2284         config->shortkey_ = accountData->GetConfig()->GetShortKeyState();
2285         config->mouseAutoClick_ = accountData->GetConfig()->GetMouseAutoClick();
2286         config->daltonizationColorFilter_ = accountData->GetConfig()->GetDaltonizationColorFilter();
2287         config->contentTimeout_ = accountData->GetConfig()->GetContentTimeout();
2288         config->brightnessDiscount_ = accountData->GetConfig()->GetBrightnessDiscount();
2289         config->audioBalance_ = accountData->GetConfig()->GetAudioBalance();
2290         config->shortkeyTarget_ = accountData->GetConfig()->GetShortkeyTarget();
2291         config->shortkeyMultiTarget_ = accountData->GetConfig()->GetShortkeyMultiTarget();
2292         config->captionProperty_ = accountData->GetConfig()->GetCaptionProperty();
2293         syncPromise->set_value();
2294         }, "TASK_GET_ALL_CONFIGS");
2295 
2296     std::future_status wait = syncFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
2297     if (wait != std::future_status::ready) {
2298         HILOG_ERROR("Failed to wait GetAllConfigs result");
2299         return;
2300     }
2301     configData = *config;
2302     return syncFuture.get();
2303 }
2304 
EnableShortKeyTargetAbility(const std::string & name)2305 bool AccessibleAbilityManagerService::EnableShortKeyTargetAbility(const std::string &name)
2306 {
2307     HILOG_DEBUG();
2308     HILOG_INFO("EnableShortKeyTargetAbility name = %{public}s", name.c_str());
2309     HITRACE_METER_NAME(HITRACE_TAG_ACCESSIBILITY_MANAGER, "EnableShortKeyTargetAbility");
2310 
2311     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2312     if (!accountData) {
2313         HILOG_ERROR("accountData is nullptr");
2314         return false;
2315     }
2316 
2317     std::string targetAbility;
2318     if (name != "") {
2319         targetAbility = name;
2320     } else {
2321         targetAbility = accountData->GetConfig()->GetShortkeyTarget();
2322         HILOG_DEBUG("target ability is [%{public}s]", targetAbility.c_str());
2323         if (targetAbility == "") {
2324             HILOG_ERROR("target ability is null");
2325             return false;
2326         }
2327     }
2328 
2329     auto it = AccessibilityConfigTable.find(targetAbility);
2330     if (it != AccessibilityConfigTable.end()) {
2331         return SetTargetAbility(it->second);
2332     }
2333 
2334     uint32_t capabilities = CAPABILITY_GESTURE | CAPABILITY_KEY_EVENT_OBSERVER | CAPABILITY_RETRIEVE |
2335         CAPABILITY_TOUCH_GUIDE | CAPABILITY_ZOOM;
2336     RetError enableState = accountData->EnableAbility(targetAbility, capabilities);
2337     if (enableState == RET_ERR_CONNECTION_EXIST) {
2338         HILOG_DEBUG();
2339         return InnerDisableAbility(targetAbility) == RET_OK;
2340     }
2341     return enableState == RET_OK;
2342 }
2343 
OnShortKeyProcess()2344 void AccessibleAbilityManagerService::OnShortKeyProcess()
2345 {
2346     HILOG_DEBUG();
2347 
2348     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2349     if (accountData == nullptr) {
2350         HILOG_ERROR("accountData is nullptr");
2351         return;
2352     }
2353 
2354     AccessibilityShortkeyDialog shortkeyDialog;
2355 
2356     std::vector<std::string> shortkeyMultiTarget = accountData->GetConfig()->GetShortkeyMultiTarget();
2357     if (shortkeyMultiTarget.size() == 0) {
2358         EnableShortKeyTargetAbility();
2359     } else if (shortkeyMultiTarget.size() == 1) {
2360         EnableShortKeyTargetAbility(shortkeyMultiTarget[0]);
2361     } else {
2362         // dialog
2363         if (shortkeyDialog.ConnectDialog(ShortKeyDialogType::FUNCTION_SELECT)) {
2364             HILOG_DEBUG("ready to build dialog");
2365         }
2366     }
2367 }
2368 
DisableShortKeyTargetAbility()2369 bool AccessibleAbilityManagerService::DisableShortKeyTargetAbility()
2370 {
2371     HILOG_DEBUG();
2372     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2373     if (!accountData) {
2374         HILOG_ERROR("accountData is nullptr");
2375         return false;
2376     }
2377 
2378     std::string targetAbility = accountData->GetConfig()->GetShortkeyTarget();
2379     HILOG_DEBUG("target ability is [%{public}s]", targetAbility.c_str());
2380     if (targetAbility == "") {
2381         HILOG_ERROR("target ability is null");
2382         return false;
2383     }
2384     return InnerDisableAbility(targetAbility) == RET_OK;
2385 }
2386 
RegisterConfigObserver(const sptr<IAccessibleAbilityManagerConfigObserver> & callback)2387 uint32_t AccessibleAbilityManagerService::RegisterConfigObserver(
2388     const sptr<IAccessibleAbilityManagerConfigObserver> &callback)
2389 {
2390     HILOG_DEBUG();
2391     if (!callback || !actionHandler_) {
2392         HILOG_ERROR("Parameters check failed!");
2393         return ERR_INVALID_VALUE;
2394     }
2395 
2396     std::shared_ptr<std::promise<uint32_t>> syncPromisePtr = std::make_shared<std::promise<uint32_t>>();
2397     std::future syncFuture = syncPromisePtr->get_future();
2398     actionHandler_->PostTask([this, syncPromisePtr, callback]() {
2399         HILOG_DEBUG();
2400         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2401         if (!accountData) {
2402             HILOG_ERROR("Account data is null");
2403             syncPromisePtr->set_value(ERR_INVALID_VALUE);
2404             return;
2405         }
2406         if (!configCallbackDeathRecipient_) {
2407             configCallbackDeathRecipient_ = new(std::nothrow) ConfigCallbackDeathRecipient();
2408             if (!configCallbackDeathRecipient_) {
2409                 HILOG_ERROR("configCallbackDeathRecipient_ is null");
2410                 syncPromisePtr->set_value(ERR_INVALID_VALUE);
2411                 return;
2412             }
2413         }
2414         if (!callback->AsObject()) {
2415             HILOG_ERROR("object is null");
2416             syncPromisePtr->set_value(0);
2417             return;
2418         }
2419         callback->AsObject()->AddDeathRecipient(configCallbackDeathRecipient_);
2420         accountData->AddConfigCallback(callback);
2421         HILOG_DEBUG("the size of caption property callbacks is %{public}zu",
2422             accountData->GetConfigCallbacks().size());
2423         syncPromisePtr->set_value(NO_ERROR);
2424         }, "TASK_REGISTER_CONFIG_OBSERVER");
2425 
2426     std::future_status wait = syncFuture.wait_for(std::chrono::milliseconds(TIME_OUT_OPERATOR));
2427     if (wait != std::future_status::ready) {
2428         HILOG_ERROR("Failed to wait RegisterConfigObserver result");
2429         return RET_ERR_TIME_OUT;
2430     }
2431     return syncFuture.get();
2432 }
2433 
OnRemoteDied(const wptr<IRemoteObject> & remote)2434 void AccessibleAbilityManagerService::ConfigCallbackDeathRecipient::OnRemoteDied(
2435     const wptr<IRemoteObject> &remote)
2436 {
2437     Singleton<AccessibleAbilityManagerService>::GetInstance().RemoveCallback(CONFIG_CALLBACK, this, remote);
2438 }
2439 
OnRemoteDied(const wptr<IRemoteObject> & remote)2440 void AccessibleAbilityManagerService::BundleManagerDeathRecipient::OnRemoteDied(
2441     const wptr<IRemoteObject> &remote)
2442 {
2443     Singleton<AccessibleAbilityManagerService>::GetInstance().OnBundleManagerDied(remote);
2444 }
2445 
UpdateConfigState()2446 void AccessibleAbilityManagerService::UpdateConfigState()
2447 {
2448     return accessibilitySettings_->UpdateConfigState();
2449 }
2450 
UpdateAudioBalance()2451 void AccessibleAbilityManagerService::UpdateAudioBalance()
2452 {
2453     return accessibilitySettings_->UpdateAudioBalance();
2454 }
2455 
UpdateBrightnessDiscount()2456 void AccessibleAbilityManagerService::UpdateBrightnessDiscount()
2457 {
2458     return accessibilitySettings_->UpdateBrightnessDiscount();
2459 }
2460 
UpdateContentTimeout()2461 void AccessibleAbilityManagerService::UpdateContentTimeout()
2462 {
2463     return accessibilitySettings_->UpdateContentTimeout();
2464 }
2465 
UpdateDaltonizationColorFilter()2466 void AccessibleAbilityManagerService::UpdateDaltonizationColorFilter()
2467 {
2468     return accessibilitySettings_->UpdateDaltonizationColorFilter();
2469 }
2470 
UpdateMouseAutoClick()2471 void AccessibleAbilityManagerService::UpdateMouseAutoClick()
2472 {
2473     return accessibilitySettings_->UpdateMouseAutoClick();
2474 }
2475 
UpdateShortkeyTarget()2476 void AccessibleAbilityManagerService::UpdateShortkeyTarget()
2477 {
2478     return accessibilitySettings_->UpdateShortkeyTarget();
2479 }
2480 
UpdateShortkeyMultiTarget()2481 void AccessibleAbilityManagerService::UpdateShortkeyMultiTarget()
2482 {
2483     return accessibilitySettings_->UpdateShortkeyMultiTarget();
2484 }
2485 
UpdateClickResponseTime()2486 void AccessibleAbilityManagerService::UpdateClickResponseTime()
2487 {
2488     return accessibilitySettings_->UpdateClickResponseTime();
2489 }
2490 
UpdateIgnoreRepeatClickTime()2491 void AccessibleAbilityManagerService::UpdateIgnoreRepeatClickTime()
2492 {
2493     return accessibilitySettings_->UpdateIgnoreRepeatClickTime();
2494 }
2495 
RemoveCallback(CallBackID callback,const sptr<DeathRecipient> & recipient,const wptr<IRemoteObject> & remote)2496 void AccessibleAbilityManagerService::RemoveCallback(CallBackID callback,
2497     const sptr<DeathRecipient> &recipient, const wptr<IRemoteObject> &remote)
2498 {
2499     HILOG_INFO("remove callback[%{public}d]", callback);
2500     if (!handler_) {
2501         HILOG_ERROR("handler is nullptr");
2502         return;
2503     }
2504     handler_->PostTask([=]() {
2505         if (!remote.GetRefPtr()) {
2506             HILOG_ERROR("remote is null");
2507             return;
2508         }
2509         remote->RemoveDeathRecipient(recipient);
2510 
2511         if (callback == CONFIG_CALLBACK) {
2512             RemoveSavedConfigCallback(remote);
2513         }
2514         auto accountData = GetCurrentAccountData();
2515         if (!accountData) {
2516             HILOG_ERROR("Current account data is null");
2517             return;
2518         }
2519         switch (callback) {
2520             case STATE_CALLBACK:
2521                 stateObservers_.RemoveStateObserver(remote);
2522                 break;
2523             case CAPTION_PROPERTY_CALLBACK:
2524                 accountData->RemoveCaptionPropertyCallback(remote);
2525                 break;
2526             case ENABLE_ABILITY_LISTS_CALLBACK:
2527                 accountData->RemoveEnableAbilityListsObserver(remote);
2528                 break;
2529             case CONFIG_CALLBACK:
2530                 accountData->RemoveConfigCallback(remote);
2531                 break;
2532             default:
2533                 break;
2534         }
2535         }, "RemoveCallback");
2536 }
2537 
RemoveSavedConfigCallback(const wptr<IRemoteObject> & callback)2538 void AccessibleAbilityManagerService::RemoveSavedConfigCallback(const wptr<IRemoteObject>& callback)
2539 {
2540     HILOG_DEBUG("start.");
2541     for (auto itr = defaultConfigCallbacks_.begin(); itr != defaultConfigCallbacks_.end(); itr++) {
2542         if ((*itr)->AsObject() == callback) {
2543             defaultConfigCallbacks_.erase(itr);
2544             break;
2545         }
2546     }
2547 }
2548 
OnBundleManagerDied(const wptr<IRemoteObject> & remote)2549 void AccessibleAbilityManagerService::OnBundleManagerDied(const wptr<IRemoteObject> &remote)
2550 {
2551     HILOG_INFO("OnBundleManagerDied ");
2552     if (!handler_) {
2553         HILOG_ERROR("handler is nullptr");
2554         return;
2555     }
2556 
2557     handler_->PostTask([=]() {
2558         if (!remote.GetRefPtr() || !bundleManager_) {
2559             HILOG_ERROR("remote is null");
2560             return;
2561         }
2562 
2563         bundleManager_->AsObject()->RemoveDeathRecipient(bundleManagerDeathRecipient_);
2564         bundleManager_ = nullptr;
2565         }, "OnBundleManagerDied");
2566 }
2567 
AddStateObserver(const sptr<IAccessibleAbilityManagerStateObserver> & stateObserver)2568 void AccessibleAbilityManagerService::StateObservers::AddStateObserver(
2569     const sptr<IAccessibleAbilityManagerStateObserver>& stateObserver)
2570 {
2571     std::lock_guard<std::mutex> lock(stateObserversMutex_);
2572     auto iter = std::find(observersList_.begin(), observersList_.end(), stateObserver);
2573     if (iter == observersList_.end()) {
2574         observersList_.push_back(stateObserver);
2575         HILOG_DEBUG("register state observer successfully");
2576         return;
2577     }
2578 
2579     HILOG_INFO("state observer is existed");
2580 }
2581 
OnStateObservers(uint32_t state)2582 void AccessibleAbilityManagerService::StateObservers::OnStateObservers(uint32_t state)
2583 {
2584     std::lock_guard<std::mutex> lock(stateObserversMutex_);
2585     for (auto& stateObserver : observersList_) {
2586         if (stateObserver) {
2587             stateObserver->OnStateChanged(state);
2588         }
2589     }
2590 }
2591 
RemoveStateObserver(const wptr<IRemoteObject> & remote)2592 void AccessibleAbilityManagerService::StateObservers::RemoveStateObserver(const wptr<IRemoteObject> &remote)
2593 {
2594     std::lock_guard<std::mutex> lock(stateObserversMutex_);
2595     auto iter = std::find_if(observersList_.begin(), observersList_.end(),
2596         [remote](const sptr<IAccessibleAbilityManagerStateObserver>& stateObserver) {
2597             return stateObserver->AsObject() == remote;
2598         });
2599     if (iter != observersList_.end()) {
2600         observersList_.erase(iter);
2601     }
2602 }
2603 
Clear()2604 void AccessibleAbilityManagerService::StateObservers::Clear()
2605 {
2606     std::lock_guard<std::mutex> lock(stateObserversMutex_);
2607     observersList_.clear();
2608 }
2609 
GetFocusedWindowId(int32_t & focusedWindowId)2610 RetError AccessibleAbilityManagerService::GetFocusedWindowId(int32_t &focusedWindowId)
2611 {
2612     HILOG_DEBUG();
2613     return Singleton<AccessibilityWindowManager>::GetInstance().GetFocusedWindowId(focusedWindowId);
2614 }
2615 
OnDeviceProvisioned()2616 void AccessibleAbilityManagerService::OnDeviceProvisioned()
2617 {
2618     HILOG_DEBUG();
2619     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2620     if (!accountData) {
2621         HILOG_ERROR("accountData is nullptr");
2622         return;
2623     }
2624     AccessibilitySettingProvider& provider = AccessibilitySettingProvider::GetInstance(POWER_MANAGER_SERVICE_ID);
2625     provider.UnregisterObserver(DEVICE_PROVISIONED);
2626     if (accountData->GetConfig()->GetDbHandle()) {
2627         accountData->GetConfig()->GetDbHandle()->UnregisterObserver(USER_SETUP_COMPLETED);
2628     }
2629     if (accountData->GetDefaultUserScreenReaderState()) {
2630         HILOG_INFO("Modify shortKeyTimeout and shortKeyOnLockScreenState");
2631         accountData->GetConfig()->SetShortKeyOnLockScreenState(true);
2632         UpdateConfigState();
2633     }
2634 }
2635 
InitializeShortKeyState()2636 void AccessibleAbilityManagerService::InitializeShortKeyState()
2637 {
2638     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2639     if (!accountData) {
2640         HILOG_ERROR("accountData is nullptr");
2641         return;
2642     }
2643 
2644     bool shortKeyFlag = false;
2645     if (accountData->GetAccountId() != DEFAULT_ACCOUNT_ID && accountData->GetConfig()->GetDbHandle() != nullptr) {
2646         if (accountData->GetConfig()->GetDbHandle()->GetIntValue(SHORTCUT_ENABLED, INVALID_SHORTCUT_STATE) ==
2647             INVALID_SHORTCUT_STATE) {
2648             HILOG_INFO("Initialize the shortcut key state of PrivateSpace");
2649             shortKeyFlag = true;
2650         }
2651     } else if (accountData->GetAccountId() == DEFAULT_ACCOUNT_ID) {
2652         HILOG_INFO("Initialize the shortcut key state of MainSpace");
2653         shortKeyFlag = true;
2654     }
2655 
2656     if (shortKeyFlag) {
2657         accountData->GetConfig()->SetShortKeyState(true);
2658         std::vector<std::string> tmpVec { SCREEN_READER_BUNDLE_ABILITY_NAME };
2659         accountData->GetConfig()->SetShortkeyMultiTarget(tmpVec);
2660         UpdateConfigState();
2661         Singleton<AccessibleAbilityManagerService>::GetInstance().UpdateShortKeyRegister();
2662     }
2663 }
2664 
RegisterProvisionCallback()2665 void AccessibleAbilityManagerService::RegisterProvisionCallback()
2666 {
2667     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2668     if (!accountData) {
2669         HILOG_ERROR("accountData is nullptr");
2670         return;
2671     }
2672 
2673     AccessibilitySettingProvider& service = AccessibilitySettingProvider::GetInstance(POWER_MANAGER_SERVICE_ID);
2674     AccessibilitySettingObserver::UpdateFunc func = [ = ](const std::string &state) {
2675         Singleton<AccessibleAbilityManagerService>::GetInstance().OnDeviceProvisioned();
2676     };
2677     service.RegisterObserver(DEVICE_PROVISIONED, func);
2678     if (accountData->GetConfig()->GetDbHandle() != nullptr) {
2679         accountData->GetConfig()->GetDbHandle()->RegisterObserver(USER_SETUP_COMPLETED, func);
2680     }
2681 }
2682 
RegisterShortKeyEvent()2683 void AccessibleAbilityManagerService::RegisterShortKeyEvent()
2684 {
2685     HILOG_DEBUG();
2686     if (!handler_) {
2687         HILOG_ERROR("handler_ is nullptr");
2688         return;
2689     }
2690     handler_->PostTask([=]() {
2691         HILOG_DEBUG();
2692         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2693         if (!accountData) {
2694             HILOG_ERROR("accountData is nullptr");
2695             return;
2696         }
2697         AccessibilitySettingProvider& provider = AccessibilitySettingProvider::GetInstance(POWER_MANAGER_SERVICE_ID);
2698         bool oobeState = false;
2699         bool userSetupState = false;
2700         provider.GetBoolValue(DEVICE_PROVISIONED, oobeState);
2701         if (accountData->GetConfig()->GetDbHandle() != nullptr) {
2702             userSetupState = accountData->GetConfig()->GetDbHandle()->GetBoolValue(USER_SETUP_COMPLETED, false);
2703         }
2704         if (accountData->GetAccountId() == DEFAULT_ACCOUNT_ID && (oobeState == false || userSetupState == false)) {
2705             InitializeShortKeyState();
2706             RegisterProvisionCallback();
2707         } else if (accountData->GetAccountId() != DEFAULT_ACCOUNT_ID) {
2708             InitializeShortKeyState();
2709         }
2710         }, "REGISTER_SHORTKEY_OBSERVER");
2711 }
2712 
OffZoomGesture()2713 void AccessibleAbilityManagerService::OffZoomGesture()
2714 {
2715     HILOG_INFO();
2716 #ifdef OHOS_BUILD_ENABLE_DISPLAY_MANAGER
2717     AccessibilityDisplayManager &displayMgr = Singleton<AccessibilityDisplayManager>::GetInstance();
2718     uint64_t currentScreen = displayMgr.GetDefaultDisplayId();
2719     float normalScale = 1.0f;
2720     float defaultAnchor = 0.5f;
2721     displayMgr.SetDisplayScale(currentScreen, normalScale, normalScale, defaultAnchor, defaultAnchor);
2722     return;
2723 #else
2724     HILOG_INFO("not support zoom");
2725     return;
2726 #endif
2727 }
2728 
OnScreenMagnificationStateChanged()2729 void AccessibleAbilityManagerService::OnScreenMagnificationStateChanged()
2730 {
2731     HILOG_DEBUG();
2732     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2733     if (accountData == nullptr) {
2734         HILOG_ERROR("accountData is nullptr");
2735         return;
2736     }
2737 
2738     std::shared_ptr<AccessibilitySettingsConfig> config = accountData->GetConfig();
2739     if (config == nullptr) {
2740         HILOG_ERROR("config is nullptr");
2741         return;
2742     }
2743 
2744     if (config->GetDbHandle() == nullptr) {
2745         HILOG_ERROR("datashareHelper is nullptr");
2746         return;
2747     }
2748 
2749     bool screenMagnificationEnabled = false;
2750     screenMagnificationEnabled = config->GetDbHandle()->GetBoolValue(SCREEN_MAGNIFICATION_KEY, false);
2751     config->SetScreenMagnificationState(screenMagnificationEnabled);
2752     Singleton<AccessibleAbilityManagerService>::GetInstance().UpdateInputFilter();
2753     if (!screenMagnificationEnabled) {
2754         OffZoomGesture();
2755     }
2756 }
2757 
RegisterScreenMagnificationState()2758 void AccessibleAbilityManagerService::RegisterScreenMagnificationState()
2759 {
2760     HILOG_DEBUG();
2761     if (handler_ == nullptr) {
2762         HILOG_ERROR("handler_ is nullptr");
2763         return;
2764     }
2765     handler_->PostTask([=]() {
2766         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2767         if (accountData == nullptr) {
2768             HILOG_ERROR("accountData is nullptr");
2769             return;
2770         }
2771 
2772         AccessibilitySettingObserver::UpdateFunc func = [ = ](const std::string &state) {
2773             Singleton<AccessibleAbilityManagerService>::GetInstance().OnScreenMagnificationStateChanged();
2774         };
2775         if (accountData->GetConfig()->GetDbHandle()) {
2776             accountData->GetConfig()->GetDbHandle()->RegisterObserver(SCREEN_MAGNIFICATION_KEY, func);
2777         }
2778         }, "REGISTER_SCREEN_ZOOM_OBSERVER");
2779 }
2780 
OnScreenMagnificationTypeChanged()2781 void AccessibleAbilityManagerService::OnScreenMagnificationTypeChanged()
2782 {
2783     HILOG_DEBUG();
2784     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2785     if (accountData == nullptr) {
2786         HILOG_ERROR("accountData is nullptr");
2787         return;
2788     }
2789 
2790     std::shared_ptr<AccessibilitySettingsConfig> config = accountData->GetConfig();
2791     if (config == nullptr) {
2792         HILOG_ERROR("config is nullptr");
2793         return;
2794     }
2795 
2796     if (config->GetDbHandle() == nullptr) {
2797         HILOG_ERROR("datashareHelper is nullptr");
2798         return;
2799     }
2800 
2801     uint32_t screenMagnificationType = 0;
2802     screenMagnificationType =
2803         static_cast<uint32_t>(config->GetDbHandle()->GetIntValue(SCREEN_MAGNIFICATION_TYPE, 0));
2804     config->SetScreenMagnificationType(screenMagnificationType);
2805     Singleton<AccessibleAbilityManagerService>::GetInstance().UpdateInputFilter();
2806 }
2807 
RegisterScreenMagnificationType()2808 void AccessibleAbilityManagerService::RegisterScreenMagnificationType()
2809 {
2810     HILOG_DEBUG();
2811     if (handler_ == nullptr) {
2812         HILOG_ERROR("handler_ is nullptr");
2813         return;
2814     }
2815     handler_->PostTask([=]() {
2816         sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2817         if (accountData == nullptr) {
2818             HILOG_ERROR("accountData is nullptr");
2819             return;
2820         }
2821 
2822         AccessibilitySettingObserver::UpdateFunc func = [ = ](const std::string &state) {
2823             Singleton<AccessibleAbilityManagerService>::GetInstance().OnScreenMagnificationTypeChanged();
2824         };
2825         if (accountData->GetConfig()->GetDbHandle()) {
2826             accountData->GetConfig()->GetDbHandle()->RegisterObserver(SCREEN_MAGNIFICATION_TYPE, func);
2827         }
2828         }, "REGISTER_SCREEN_ZOOM_TYPE_OBSERVER");
2829 }
2830 
InsertWindowIdEventPair(int32_t windowId,const AccessibilityEventInfo & event)2831 void AccessibleAbilityManagerService::InsertWindowIdEventPair(int32_t windowId, const AccessibilityEventInfo &event)
2832 {
2833     HILOG_DEBUG("insert event, windowId: %{public}d", windowId);
2834     windowFocusEventMap_[windowId] = event;
2835 }
2836 
CheckWindowIdEventExist(int32_t windowId)2837 bool AccessibleAbilityManagerService::CheckWindowIdEventExist(int32_t windowId)
2838 {
2839     return windowFocusEventMap_.count(windowId);
2840 }
2841 
CheckWindowRegister(int32_t windowId)2842 bool AccessibleAbilityManagerService::CheckWindowRegister(int32_t windowId)
2843 {
2844     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2845     if (!accountData) {
2846         HILOG_ERROR("accountData is nullptr.");
2847         return false;
2848     }
2849     return accountData->GetAccessibilityWindowConnection(windowId) != nullptr;
2850 }
2851 
PostDelayUnloadTask()2852 void AccessibleAbilityManagerService::PostDelayUnloadTask()
2853 {
2854     auto task = [=]() {
2855         sptr<ISystemAbilityManager> systemAbilityManager =
2856             SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2857         if (systemAbilityManager == nullptr) {
2858             HILOG_ERROR("failed to get system ability mgr");
2859             return;
2860         }
2861         if (!IsNeedUnload()) {
2862             return;
2863         }
2864         int32_t ret = systemAbilityManager->UnloadSystemAbility(ACCESSIBILITY_MANAGER_SERVICE_ID);
2865         if (ret != ERR_OK) {
2866             HILOG_ERROR("unload system ability failed");
2867             return;
2868         }
2869     };
2870     handler_->RemoveTask(DELAY_UNLOAD_TASK);
2871     handler_->PostTask(task, DELAY_UNLOAD_TASK, UNLOAD_TASK_INTERNAL);
2872 }
2873 
IsNeedUnload()2874 bool AccessibleAbilityManagerService::IsNeedUnload()
2875 {
2876     HILOG_DEBUG();
2877     // always return true to avoid stability problem
2878     return false;
2879     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
2880     if (!accountData) {
2881         HILOG_ERROR("accountData is nullptr");
2882         return true;
2883     }
2884 
2885     // do not unload when any extension is enabled
2886     std::vector<std::string> enableAbilityList = accountData->GetEnabledAbilities();
2887     if (enableAbilityList.size() != 0) {
2888         return false;
2889     }
2890     if (!accountData->GetConfig()) {
2891         return true;
2892     }
2893     if (accountData->GetConfig()->GetHighContrastTextState() != false ||
2894         accountData->GetConfig()->GetDaltonizationState() != false ||
2895         accountData->GetConfig()->GetInvertColorState() != false ||
2896         accountData->GetConfig()->GetAnimationOffState() != false ||
2897         accountData->GetConfig()->GetMouseKeyState() != false ||
2898         accountData->GetConfig()->GetCaptionState() != false ||
2899         accountData->GetConfig()->GetScreenMagnificationState() != false ||
2900         accountData->GetConfig()->GetShortKeyState() != false ||
2901         accountData->GetConfig()->GetShortKeyOnLockScreenState() != false ||
2902         accountData->GetConfig()->GetBrightnessDiscount() != 1) {
2903         return false;
2904     }
2905     return true;
2906 }
2907 
GetTreeIdBySplitElementId(const int64_t elementId)2908 int32_t AccessibleAbilityManagerService::GetTreeIdBySplitElementId(const int64_t elementId)
2909 {
2910     if (elementId < 0) {
2911         HILOG_DEBUG("The elementId is -1");
2912         return elementId;
2913     }
2914     int32_t treeId = (static_cast<uint64_t>(elementId) >> ELEMENT_MOVE_BIT);
2915     return treeId;
2916 }
2917 
AddRequestId(int32_t windowId,int32_t treeId,int32_t requestId,sptr<IAccessibilityElementOperatorCallback> callback)2918 void AccessibleAbilityManagerService::AddRequestId(int32_t windowId, int32_t treeId, int32_t requestId,
2919     sptr<IAccessibilityElementOperatorCallback> callback)
2920 {
2921     std::lock_guard<std::mutex> lock(mutex_);
2922     HILOG_DEBUG("Add windowId: %{public}d treeId: %{public}d requestId: %{public}d", windowId, treeId, requestId);
2923     if (!windowRequestIdMap_.count(windowId)) {
2924         windowRequestIdMap_[windowId] = {};
2925     }
2926     if (!windowRequestIdMap_[windowId].count(treeId)) {
2927         windowRequestIdMap_[windowId][treeId] = {};
2928     }
2929     if (!windowRequestIdMap_[windowId][treeId].count(requestId)) {
2930         windowRequestIdMap_[windowId][treeId].insert(requestId);
2931         requestIdMap_[requestId] = callback;
2932     }
2933 }
2934 
RemoveRequestId(int32_t requestId)2935 void AccessibleAbilityManagerService::RemoveRequestId(int32_t requestId)
2936 {
2937     std::lock_guard<std::mutex> lock(mutex_);
2938     HILOG_DEBUG("RemoveRequestId requestId: %{public}d", requestId);
2939     for (auto &window : windowRequestIdMap_) {
2940         for (auto &tree : window.second) {
2941             auto it = tree.second.find(requestId);
2942             if (it != tree.second.end()) {
2943                 HILOG_DEBUG("tree.second.erase requestId:%{public}d", requestId);
2944                 tree.second.erase(it);
2945             }
2946             auto ite = requestIdMap_.find(requestId);
2947             if (ite != requestIdMap_.end()) {
2948                 HILOG_DEBUG("requestIdMap_.erase requestId:%{public}d", requestId);
2949                 requestIdMap_.erase(ite);
2950             }
2951         }
2952     }
2953 }
2954 
StopCallbackWait(int32_t windowId)2955 void AccessibleAbilityManagerService::StopCallbackWait(int32_t windowId)
2956 {
2957     HILOG_INFO("StopCallbackWait start windowId: %{public}d", windowId);
2958     if (!windowRequestIdMap_.count(windowId)) {
2959         HILOG_DEBUG("windowId not exists");
2960         return;
2961     }
2962     for (auto iter = windowRequestIdMap_[windowId].begin(); iter != windowRequestIdMap_[windowId].end(); ++iter) {
2963         HILOG_DEBUG("stop callback wait windowId: %{public}d, treeId: %{public}d", windowId, iter->first);
2964         StopCallbackWait(windowId, iter->first);
2965     }
2966 }
2967 
StopCallbackWait(int32_t windowId,int32_t treeId)2968 void AccessibleAbilityManagerService::StopCallbackWait(int32_t windowId, int32_t treeId)
2969 {
2970     std::lock_guard<std::mutex> lock(mutex_);
2971     HILOG_INFO("StopCallbackWait start windowId: %{public}d treeId: %{public}d", windowId, treeId);
2972     if (!windowRequestIdMap_.count(windowId)) {
2973         return;
2974     }
2975     if (!windowRequestIdMap_[windowId].count(treeId)) {
2976         return;
2977     }
2978     auto requestIds = windowRequestIdMap_[windowId][treeId];
2979     for (auto requestId = requestIds.begin(); requestId != requestIds.end();) {
2980         HILOG_DEBUG("stop callback wait windowId: %{public}d, requestId: %{public}d", windowId, *requestId);
2981         auto iter = requestIdMap_.find(*requestId);
2982         if (iter != requestIdMap_.end()) {
2983             HILOG_DEBUG("requestIdMap_ set callback and erase requestId:%{public}d", *requestId);
2984             sptr<IAccessibilityElementOperatorCallback> callback = requestIdMap_[*requestId];
2985             if (callback != nullptr) {
2986                 callback->SetExecuteActionResult(false, *requestId);
2987             }
2988             requestIdMap_.erase(iter);
2989         }
2990         requestId = requestIds.erase(requestId);
2991     }
2992 }
2993 
GetRootParentId(int32_t windowId,int32_t treeId)2994 int64_t AccessibleAbilityManagerService::GetRootParentId(int32_t windowId, int32_t treeId)
2995 {
2996     int64_t elementId = 0;
2997     HILOG_DEBUG();
2998     sptr<AccessibilityWindowConnection> connection = GetAccessibilityWindowConnection(windowId);
2999     if (!connection) {
3000         HILOG_WARN("The operator of windowId[%{public}d] has not been registered.", windowId);
3001         return RET_ERR_NO_CONNECTION;
3002     }
3003     connection->GetRootParentId(treeId, elementId);
3004     return elementId;
3005 }
3006 
GetAllTreeId(int32_t windowId,std::vector<int32_t> & treeIds)3007 RetError AccessibleAbilityManagerService::GetAllTreeId(int32_t windowId, std::vector<int32_t> &treeIds)
3008 {
3009     HILOG_DEBUG();
3010     sptr<AccessibilityWindowConnection> connection = GetAccessibilityWindowConnection(windowId);
3011     if (!connection) {
3012         HILOG_WARN("The operator of windowId[%{public}d] has not been registered.", windowId);
3013         return RET_ERR_NO_CONNECTION;
3014     }
3015     connection->GetAllTreeId(treeIds);
3016     return RET_OK;
3017 }
3018 
GenerateRequestId()3019 int32_t AccessibleAbilityManagerService::GenerateRequestId()
3020 {
3021     int32_t requestId = requestId_.fetch_add(1, std::memory_order_relaxed);
3022     if (requestId == REQUEST_ID_MAX) {
3023         requestId_ = REQUEST_ID_MIN;
3024         requestId = requestId_.fetch_add(1, std::memory_order_relaxed);
3025     }
3026     return requestId;
3027 }
3028 
CheckCallingUid()3029 RetError AccessibleAbilityManagerService::CheckCallingUid()
3030 {
3031     int32_t accountId = Utils::GetUserIdByCallingUid();
3032     if (accountId != currentAccountId_ && accountId != ROOT_UID) {
3033         HILOG_WARN("accountId is diff from currentAccountId_.");
3034         return RET_ERR_SAMGR;
3035     }
3036     return RET_OK;
3037 }
3038 
OnDataClone()3039 void AccessibleAbilityManagerService::OnDataClone()
3040 {
3041     AccessibilitySettingProvider& provider = AccessibilitySettingProvider::GetInstance(POWER_MANAGER_SERVICE_ID);
3042     bool cloneState = false;
3043     provider.GetBoolValue(ACCESSIBILITY_CLONE_FLAG, cloneState);
3044     if (cloneState == false) {
3045         return;
3046     }
3047     sptr<AccessibilityAccountData> accountData = GetCurrentAccountData();
3048     if (accountData == nullptr) {
3049         HILOG_WARN("accountData is nullptr.");
3050         return;
3051     }
3052     if (accountData->GetConfig() != nullptr) {
3053         accountData->GetConfig()->OnDataClone();
3054         UpdateAllSetting();
3055         UpdateAutoStartAbilities();
3056         UpdateInputFilter();
3057         HILOG_INFO("accessibility reload config.");
3058     } else {
3059         HILOG_WARN("config_ is nullptr");
3060     }
3061 }
3062 } // namespace Accessibility
3063 } // namespace OHOS
3064