1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "key_event_result_handler.h"
17
18 #include <cinttypes>
19
20 #include "global.h"
21 namespace OHOS {
22 namespace MiscServices {
AddKeyEventCbInfo(const KeyEventCbInfo & cbInfo)23 uint64_t KeyEventResultHandler::AddKeyEventCbInfo(const KeyEventCbInfo &cbInfo)
24 {
25 std::lock_guard<std::mutex> lock(keyEventCbHandlersMutex_);
26 auto cbId = GenerateKeyEventCbId();
27 IMSA_HILOGD("%{public}" PRIu64 "add.", cbId);
28 keyEventCbHandlers_.insert_or_assign(cbId, cbInfo);
29 return cbId;
30 }
31
HandleKeyEventResult(uint64_t cbId,bool consumeResult)32 void KeyEventResultHandler::HandleKeyEventResult(uint64_t cbId, bool consumeResult)
33 {
34 IMSA_HILOGD("result:%{public}" PRIu64 "/%{public}d.", cbId, consumeResult);
35 KeyEventCbInfo info;
36 auto ret = GetKeyEventCbInfo(cbId, info);
37 if (ret != ErrorCode::NO_ERROR) {
38 IMSA_HILOGE("%{public}" PRIu64 "not be found.", cbId);
39 return;
40 }
41 if (info.callback == nullptr) {
42 IMSA_HILOGE("%{public}" PRIu64 "callback is nullptr.", cbId);
43 } else {
44 info.callback(info.keyEvent, consumeResult);
45 }
46 RemoveKeyEventCbInfo(cbId);
47 }
48
ClearKeyEventCbInfo()49 void KeyEventResultHandler::ClearKeyEventCbInfo()
50 {
51 std::lock_guard<std::mutex> lock(keyEventCbHandlersMutex_);
52 keyEventCbHandlers_.clear();
53 }
54
RemoveKeyEventCbInfo(uint64_t cbId)55 void KeyEventResultHandler::RemoveKeyEventCbInfo(uint64_t cbId)
56 {
57 std::lock_guard<std::mutex> lock(keyEventCbHandlersMutex_);
58 auto iter = keyEventCbHandlers_.find(cbId);
59 if (iter == keyEventCbHandlers_.end()) {
60 return;
61 }
62 keyEventCbHandlers_.erase(cbId);
63 }
64
GetKeyEventCbInfo(uint64_t cbId,KeyEventCbInfo & info)65 int32_t KeyEventResultHandler::GetKeyEventCbInfo(uint64_t cbId, KeyEventCbInfo &info)
66 {
67 std::lock_guard<std::mutex> lock(keyEventCbHandlersMutex_);
68 auto iter = keyEventCbHandlers_.find(cbId);
69 if (iter != keyEventCbHandlers_.end()) {
70 info = iter->second;
71 return ErrorCode::NO_ERROR;
72 }
73 return ErrorCode::ERROR_BAD_PARAMETERS;
74 }
75
GenerateKeyEventCbId()76 uint64_t KeyEventResultHandler::GenerateKeyEventCbId()
77 {
78 return maxCbId_.fetch_add(1);
79 }
80 } // namespace MiscServices
81 } // namespace OHOS