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