1 /* 2 * Copyright (C) 2024-2024 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 #ifndef FRAMEWORKS_INPUTMETHOD_ABILITY_INCLUDE_ACTIONS_ACTION_WAIT_H 17 #define FRAMEWORKS_INPUTMETHOD_ABILITY_INCLUDE_ACTIONS_ACTION_WAIT_H 18 19 #include <cstdint> 20 #include <functional> 21 22 #include "action.h" 23 #include "task_manager.h" 24 #include "tasks/task_inner.h" 25 26 namespace OHOS { 27 namespace MiscServices { 28 29 class ActionWait : public Action { 30 public: 31 using callback_t = std::function<void()>; 32 ActionWait(uint64_t completeId, uint32_t timeoutMs)33 ActionWait(uint64_t completeId, uint32_t timeoutMs) 34 : timeoutMs_(timeoutMs), 35 completeId_(completeId), 36 timeoutId_(Task::GetNextSeqId()) 37 { 38 } 39 ActionWait(uint64_t completeId, uint32_t timeoutMs, callback_t onComplete, callback_t onTimeout)40 ActionWait(uint64_t completeId, uint32_t timeoutMs, callback_t onComplete, callback_t onTimeout) 41 : timeoutMs_(timeoutMs), 42 completeId_(completeId), 43 timeoutId_(Task::GetNextSeqId()), 44 onComplete_(onComplete), 45 onTimeout_(onTimeout) 46 { 47 } 48 49 ~ActionWait() = default; 50 51 RunningState Execute() override 52 { 53 state_ = RUNNING_STATE_PAUSED; 54 // trigger timeout with delay 55 auto task = std::make_shared<TaskResume>(timeoutId_); 56 TaskManager::GetInstance().PostTask(task, timeoutMs_); 57 return state_; 58 } 59 60 RunningState Resume(uint64_t seqId) override 61 { 62 if (state_ != RUNNING_STATE_PAUSED) { 63 return RUNNING_STATE_ERROR; 64 } 65 66 if (seqId == completeId_) { 67 if (onComplete_) { 68 onComplete_(); 69 } 70 state_ = RUNNING_STATE_COMPLETED; 71 return state_; 72 } 73 if (seqId == timeoutId_) { 74 if (onTimeout_) { 75 onTimeout_(); 76 } 77 state_ = RUNNING_STATE_COMPLETED; 78 return state_; 79 } 80 81 return state_; 82 } 83 84 private: 85 const uint32_t timeoutMs_; 86 const uint64_t completeId_; 87 const uint64_t timeoutId_; 88 std::function<void()> onComplete_; 89 std::function<void()> onTimeout_; 90 }; 91 } // namespace MiscServices 92 } // namespace OHOS 93 #endif // FRAMEWORKS_INPUTMETHOD_ABILITY_INCLUDE_ACTIONS_ACTION_WAIT_H