1 /*
2  * Copyright (c) 2023 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 #ifndef ANR_HANDLER_H
17 #define ANR_HANDLER_H
18 
19 #include <memory>
20 #include <mutex>
21 #include <list>
22 #include <unordered_map>
23 
24 #include "event_handler.h"
25 #include "nocopyable.h"
26 #include "singleton.h"
27 #include "session_stage_interface.h"
28 namespace OHOS {
29 namespace Rosen {
30 class ANRHandler {
31     DECLARE_DELAYED_SINGLETON(ANRHandler);
32 
33 public:
34     DISALLOW_COPY_AND_MOVE(ANRHandler);
35 
36     void SetSessionStage(int32_t eventId, const wptr<ISessionStage> &sessionStage);
37     void HandleEventConsumed(int32_t eventId, int64_t actionTime);
38     void OnWindowDestroyed(int32_t persistentId);
39 private:
40     using Task = std::function<void()>;
41     bool PostTask(Task &&task, const std::string& name = "ANRHandlerTask", int64_t delayTime = 0);
42     void MarkProcessed();
43     void SendEvent(int32_t eventId, int64_t delayTime);
44     void SetAnrHandleState(int32_t eventId, bool status);
45     void ClearExpiredEvents(int32_t eventId);
46     int32_t GetPersistentIdOfEvent(int32_t eventId);
47     bool IsOnEventHandler(int32_t persistentId);
48     void UpdateLatestEventId(int32_t eventId);
49 private:
50     std::shared_ptr<AppExecFwk::EventHandler> eventHandler_ { nullptr };
51     struct ANRHandlerState {
52         std::unordered_map<int32_t, bool> sendStatus;
53         int32_t currentEventIdToReceipt { -1 };
54         std::list<int32_t> eventsToReceipt;
55     };
56     ANRHandlerState anrHandlerState_;
57     struct SessionInfo {
58         int32_t persistentId;
59         wptr<ISessionStage> sessionStage;
60     };
61     std::unordered_map<int32_t, SessionInfo> sessionStageMap_;
62 };
63 } // namespace Rosen
64 } // namespace OHOS
65 #endif // ANR_HANDLER_H