/* * 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 "KeyManager.h" #include "ILog.h" constexpr long int KEY_PRESSING = 0; constexpr unsigned int NOT_A_HOLD_KEY_ACTION = 0; KeyManager::KeyManager() { mKeyHal = nullptr; mKeyActionReport = nullptr; mPressingTime = KEY_NOT_PRESSING; mLongClickTime = 0; } KeyManager::KeyManager(std::shared_ptr &keyHal, const KeyActionReport &keyAction, const long int &longClickTime) : mKeyHal(keyHal), mKeyActionReport(keyAction), mLongClickTime(longClickTime) { mPressingTime = KEY_NOT_PRESSING; } KeyManager::~KeyManager() {} void KeyManager::KeyEventTrigger(const KeyHalEvent &event) { std::lock_guard locker(mMutex); ActionReport(mKeyHal->GetKeyName(), event); } void KeyManager::TimerKeyEventTrigger(const KeyHalEvent &event) { std::lock_guard locker(mMutex); if (IsKeyPressing()) { ActionReport(mKeyHal->GetKeyName(), event); } } long int KeyManager::GetHoldPressingTimeMs(void) { return mPressingTime; } bool KeyManager::IsKeyPressing(void) { return mPressingTime >= KEY_PRESSING ? true : false; } void KeyManager::Init(void) { mKeyHal->SetKeyHalOwner(shared_from_this()); } void KeyManager::UnInit(void) {} void KeyManager::ActionReport(const std::string &key, const KeyHalEvent &keyEvent) { if (KEY_PRESSING <= mPressingTime) { mPressingTime += PERIPHERAL_CHECK_PERIOD_MS; } switch (keyEvent) { case KeyHalEvent::PRESSING: KeyPressingTrigger(key); break; case KeyHalEvent::NOT_PRESSING: KeyNotPressingTrigger(key); break; default: break; } } void KeyManager::KeyPressingTrigger(const std::string &key) { if (mLongClickTime <= mPressingTime) // Do not support long click, it should be count in application code. { if (mKeyActionReport) { // mKeyActionReport(key, KeyAction::SF_KEY_ACTION_LONG_CLICK, NOT_A_HOLD_KEY_ACTION); } } if (mPressingTime != KEY_NOT_PRESSING && mPressingTime % KEY_ACTION_HOLD_DWON == 0) { if (mKeyActionReport) { mKeyActionReport(key, KeyAction::HOLD_DOWN, mPressingTime); } } if (KEY_NOT_PRESSING == mPressingTime) { mPressingTime = KEY_PRESSING; } } void KeyManager::KeyNotPressingTrigger(const std::string &key) { if (KEY_ACTION_SHORT_CLICK <= mPressingTime && mPressingTime < KEY_ACTION_HOLD_DWON) { if (mKeyActionReport) { mKeyActionReport(key, KeyAction::SHORT_CLICK, NOT_A_HOLD_KEY_ACTION); } } if (KEY_ACTION_HOLD_DWON <= mPressingTime) { if (mKeyActionReport) { mKeyActionReport(key, KeyAction::HOLD_UP, mPressingTime); } } mPressingTime = KEY_NOT_PRESSING; }