hunting/utils/KeyControl/src/KeyControl.cpp
2024-02-16 21:44:01 -08:00

106 lines
3.1 KiB
C++

/*
* Copyright (c) 2023 Fancy Code.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "KeyControl.h"
#include "ILog.h"
constexpr long int KEY_PRESSING = 0;
constexpr unsigned int NOT_A_HOLD_KEY_ACTION = 0;
KeyControl::KeyControl()
{
mPressingTime = KEY_NOT_PRESSING;
mLongClickTime = 0;
}
KeyControl::~KeyControl() {}
bool KeyControl::IsKeyPressing(void) { return mPressingTime >= KEY_PRESSING ? true : false; }
void KeyControl::UnInit(void) {}
void KeyControl::KeyHalEventHandle(const std::string &key, const KeyHalEvent &keyEvent)
{
if (KEY_PRESSING <= mPressingTime) {
mPressingTime += GetStatusCheckPeriodMs();
}
switch (keyEvent) {
case KeyHalEvent::PRESSING:
KeyPressingTrigger(key);
break;
case KeyHalEvent::NOT_PRESSING:
KeyNotPressingTrigger(key);
break;
default:
break;
}
}
void KeyControl::TimerKeyEventTrigger(const KeyHalEvent &event)
{
std::lock_guard<std::mutex> locker(mMutex);
if (IsKeyPressing()) {
KeyHalEventHandle(GetKeyName(), event);
}
}
void KeyControl::KeyHalEventTrigger(const KeyHalEvent &event)
{
std::lock_guard<std::mutex> locker(mMutex);
KeyHalEventHandle(GetKeyName(), event);
}
long int KeyControl::GetHoldPressingTimeMs(void)
{
//
return mPressingTime;
}
void KeyControl::KeyPressingTrigger(const std::string &key)
{
if (mLongClickTime <= mPressingTime) {
/**
* @brief Long press events are not currently supported here. Developers believe that it is better to handle
* long press events at the application level.
*/
}
if (mPressingTime != KEY_NOT_PRESSING && mPressingTime % KEY_ACTION_HOLD_DWON == 0) {
KeyEventTrigger(key, KeyEvent::HOLD_DOWN, mPressingTime);
}
if (KEY_NOT_PRESSING == mPressingTime) {
mPressingTime = KEY_PRESSING;
}
}
void KeyControl::KeyNotPressingTrigger(const std::string &key)
{
if (KEY_ACTION_SHORT_CLICK <= mPressingTime && mPressingTime < KEY_ACTION_HOLD_DWON) {
KeyEventTrigger(key, KeyEvent::SHORT_CLICK, mPressingTime);
}
if (KEY_ACTION_HOLD_DWON <= mPressingTime) {
KeyEventTrigger(key, KeyEvent::HOLD_UP, mPressingTime);
}
mPressingTime = KEY_NOT_PRESSING;
}
const char *PrintKeyEvent(const KeyEvent &event)
{
switch (event) {
case KeyEvent::SHORT_CLICK: {
return "SHORT_CLICK";
break;
}
case KeyEvent::HOLD_DOWN: {
return "HOLD_DOWN";
break;
}
case KeyEvent::HOLD_UP: {
return "HOLD_UP";
break;
}
default:
return "unknown event";
break;
}
}