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 #include "active_key_event.h"
17
18 #include <vector>
19
20 #include "event_log_task.h"
21 #include "file_util.h"
22 #include "hiview_logger.h"
23 #include "sys_event.h"
24 #include "time_util.h"
25 #include "trace_collector.h"
26 namespace OHOS {
27 namespace HiviewDFX {
28 DEFINE_LOG_LABEL(0xD002D01, "EventLogger-ActiveKeyEvent");
ActiveKeyEvent()29 ActiveKeyEvent::ActiveKeyEvent()
30 {
31 triggeringTime_ = 0;
32 logStore_ = nullptr;
33 }
34
~ActiveKeyEvent()35 ActiveKeyEvent::~ActiveKeyEvent()
36 {
37 std::unique_lock<ffrt::mutex> uniqueLock(mutex_);
38 for (auto it = subscribeIds_.begin(); it != subscribeIds_.end(); it = subscribeIds_.erase(it)) {
39 if (*it >= 0) {
40 MMI::InputManager::GetInstance()->UnsubscribeKeyEvent(*it);
41 HIVIEW_LOGI("~ActiveKeyEvent subscribeId_: %{public}d", *it);
42 }
43 }
44 }
45
SystemTimeMillisecond()46 int64_t ActiveKeyEvent::SystemTimeMillisecond()
47 {
48 struct timespec t;
49 t.tv_sec = 0;
50 t.tv_nsec = 0;
51 clock_gettime(CLOCK_MONOTONIC, &t);
52 return (int64_t)((t.tv_sec) * TimeUtil::SEC_TO_NANOSEC + t.tv_nsec) / TimeUtil::SEC_TO_MICROSEC;
53 }
54
InitSubscribe(std::set<int32_t> preKeys,int32_t finalKey,int32_t count,int32_t holdTime)55 void ActiveKeyEvent::InitSubscribe(std::set<int32_t> preKeys, int32_t finalKey, int32_t count, int32_t holdTime)
56 {
57 const int32_t maxCount = 5;
58 if (++count > maxCount) {
59 return;
60 }
61 std::shared_ptr<MMI::KeyOption> keyOption = std::make_shared<MMI::KeyOption>();
62 if (keyOption == nullptr) {
63 HIVIEW_LOGE("Invalid key option");
64 return;
65 }
66
67 keyOption->SetPreKeys(preKeys);
68 keyOption->SetFinalKey(finalKey);
69 keyOption->SetFinalKeyDown(true);
70 keyOption->SetFinalKeyDownDuration(holdTime);
71 auto keyEventCallBack = [this] (std::shared_ptr<MMI::KeyEvent> keyEvent) {
72 this->CombinationKeyCallback(keyEvent);
73 };
74 int32_t subscribeId = MMI::InputManager::GetInstance()->SubscribeKeyEvent(keyOption, keyEventCallBack);
75 if (subscribeId < 0) {
76 HIVIEW_LOGE("SubscribeKeyEvent failed, finalKey: %{public}d,"
77 "subscribeId: %{public}d option failed.", finalKey, subscribeId);
78 auto task = [this, preKeys, finalKey, count, holdTime] {
79 this->InitSubscribe(preKeys, finalKey, count, holdTime);
80 taskOutDeps++;
81 };
82 std::string taskName("InitSubscribe" + std::to_string(finalKey) + "_" + std::to_string(count));
83 ffrt::submit(task, {}, {&taskOutDeps}, ffrt::task_attr().name(taskName.c_str()));
84 }
85 std::unique_lock<ffrt::mutex> uniqueLock(mutex_);
86 subscribeIds_.emplace_back(subscribeId);
87 HIVIEW_LOGI("CombinationKeyInit finalKey: %{public}d subscribeId_: %{public}d",
88 finalKey, subscribeId);
89 }
90
Init(std::shared_ptr<LogStoreEx> logStore)91 void ActiveKeyEvent::Init(std::shared_ptr<LogStoreEx> logStore)
92 {
93 HIVIEW_LOGI("CombinationKeyInit");
94 logStore_ = logStore;
95
96 std::set<int32_t> prePowerKeys;
97 prePowerKeys.insert(MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
98 auto initSubscribePower = [this, prePowerKeys] {
99 this->InitSubscribe(prePowerKeys, MMI::KeyEvent::KEYCODE_POWER, 0, 500);
100 };
101 std::set<int32_t> preOnlyPowerKeys;
102 auto initSubscribeOnlyPower = [this, preOnlyPowerKeys] {
103 this->InitSubscribe(preOnlyPowerKeys, MMI::KeyEvent::KEYCODE_POWER, 0, 3000);
104 };
105 ffrt::submit(initSubscribePower, {}, {}, ffrt::task_attr().name("initSubscribePower").qos(ffrt::qos_default));
106 ffrt::submit(initSubscribeOnlyPower, {}, {},
107 ffrt::task_attr().name("initSubscribeOnlyPower").qos(ffrt::qos_default));
108 }
109
HitraceCapture()110 void ActiveKeyEvent::HitraceCapture()
111 {
112 std::shared_ptr<UCollectUtil::TraceCollector> collector = UCollectUtil::TraceCollector::Create();
113 UCollect::TraceCaller caller = UCollect::TraceCaller::BETACLUB;
114 auto result = collector->DumpTrace(caller);
115 if (result.retCode != 0) {
116 HIVIEW_LOGE("get hitrace fail! error code: %{public}d", result.retCode);
117 return;
118 }
119 }
120
SysMemCapture(int fd)121 void ActiveKeyEvent::SysMemCapture(int fd)
122 {
123 FileUtil::SaveStringToFd(fd, "\n\ncatcher cmd : /proc/meminfo\n");
124 std::string content;
125 FileUtil::LoadStringFromFile("/proc/meminfo", content);
126 FileUtil::SaveStringToFd(fd, content);
127 }
128
DumpCapture(int fd)129 void ActiveKeyEvent::DumpCapture(int fd)
130 {
131 SysEventCreator sysEventCreator("HIVIEWDFX", "ACTIVE_KEY", SysEventCreator::FAULT);
132 std::shared_ptr<SysEvent> sysEvent = std::make_shared<SysEvent>("ActiveKeyEvent", nullptr, sysEventCreator);
133 int noNeedJsonFd = -1;
134 std::unique_ptr<EventLogTask> logTask = std::make_unique<EventLogTask>(fd, noNeedJsonFd, sysEvent);
135 for (const std::string& cmd : CMD_LIST) {
136 logTask->AddLog(cmd);
137 }
138
139 auto ret = logTask->StartCompose();
140 if (ret != EventLogTask::TASK_SUCCESS) {
141 HIVIEW_LOGE("capture fail %{public}d", ret);
142 }
143 SysMemCapture(fd);
144 }
145
CombinationKeyHandle(std::shared_ptr<MMI::KeyEvent> keyEvent)146 void ActiveKeyEvent::CombinationKeyHandle(std::shared_ptr<MMI::KeyEvent> keyEvent)
147 {
148 HIVIEW_LOGI("Receive CombinationKeyHandle.");
149 if (logStore_ == nullptr) {
150 return;
151 }
152
153 std::string logFile = "ACTIVE_KEY_EVENT-0-" +
154 TimeUtil::TimestampFormatToDate(TimeUtil::GetMilliseconds() / TimeUtil::SEC_TO_MILLISEC,
155 "%Y%m%d%H%M%S") + ".log";
156 if (FileUtil::FileExists("/data/log/eventlog/" + logFile)) {
157 HIVIEW_LOGW("filename: %{public}s is existed, direct use.", logFile.c_str());
158 return;
159 }
160 int fd = logStore_->CreateLogFile(logFile);
161
162 auto sysStart = ActiveKeyEvent::SystemTimeMillisecond();
163 const uint32_t placeholder = 3;
164 auto start = TimeUtil::GetMilliseconds();
165 uint64_t startTime = start / TimeUtil::SEC_TO_MILLISEC;
166 std::ostringstream startTimeStr;
167 startTimeStr << "start time: " << TimeUtil::TimestampFormatToDate(startTime, "%Y/%m/%d-%H:%M:%S");
168 startTimeStr << ":" << std::setw(placeholder) << std::setfill('0') <<
169 std::to_string(start % TimeUtil::SEC_TO_MILLISEC) << std::endl;
170 std::vector<int32_t> keys = keyEvent->GetPressedKeys();
171 for (auto& i : keys) {
172 startTimeStr << "CombinationKeyCallback key : ";
173 startTimeStr << MMI::KeyEvent::KeyCodeToString(i) << std::endl;
174 }
175 FileUtil::SaveStringToFd(fd, startTimeStr.str());
176
177 auto hitraceCapture = [this] { this->HitraceCapture(); };
178 ffrt::submit(hitraceCapture, {}, {}, ffrt::task_attr().name("HitraceCapture").qos(ffrt::qos_user_initiated));
179
180 DumpCapture(fd);
181 auto end = ActiveKeyEvent::SystemTimeMillisecond();
182 std::string totalTime = "\n\nCatcher log total time is " + std::to_string(end - sysStart) + "ms\n";
183 FileUtil::SaveStringToFd(fd, totalTime);
184 close(fd);
185 }
186
CombinationKeyCallback(std::shared_ptr<MMI::KeyEvent> keyEvent)187 void ActiveKeyEvent::CombinationKeyCallback(std::shared_ptr<MMI::KeyEvent> keyEvent)
188 {
189 HIVIEW_LOGI("Receive CombinationKeyCallback key id: %{public}d.", keyEvent->GetId());
190 uint64_t now = (uint64_t)ActiveKeyEvent::SystemTimeMillisecond();
191 const uint64_t interval = 10000;
192 if (now - triggeringTime_ < interval) {
193 return;
194 }
195 triggeringTime_ = now;
196 auto combinationKeyHandle = [this, keyEvent] { this->CombinationKeyHandle(keyEvent); };
197 ffrt::submit(combinationKeyHandle, {}, {},
198 ffrt::task_attr().name("ActiveKeyEvent").qos(ffrt::qos_user_initiated));
199 }
200 } // namespace HiviewDFX
201 } // namespace OHOS