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 #ifndef FOUNDATION_ACE_FRAMEWORKS_COMPONENTS_NG_ANIMATION_CALLBACK_THREAD_WRAPPER_H 17 #define FOUNDATION_ACE_FRAMEWORKS_COMPONENTS_NG_ANIMATION_CALLBACK_THREAD_WRAPPER_H 18 19 #include <functional> 20 #include <mutex> 21 22 #include "core/pipeline/pipeline_base.h" 23 24 namespace OHOS::Ace::NG { 25 class ACE_EXPORT CallbackThreadWrapper { 26 public: CallbackThreadWrapper(const RefPtr<TaskExecutor> & taskExecutor,const std::function<void ()> & callback,bool once)27 CallbackThreadWrapper( 28 const RefPtr<TaskExecutor>& taskExecutor, const std::function<void()>& callback, bool once) 29 : taskExecutor_(taskExecutor), callback_(callback), once_(once) 30 {} ~CallbackThreadWrapper()31 ~CallbackThreadWrapper() 32 { 33 if (callback_ && taskExecutor_ && !taskExecutor_->WillRunOnCurrentThread(TaskExecutor::TaskType::UI)) { 34 auto mutex = std::make_shared<std::mutex>(); 35 std::lock_guard lock(*mutex); 36 taskExecutor_->PostTask( 37 [callback = callback_, mutex]() mutable { 38 std::lock_guard lock(*mutex); 39 callback = nullptr; 40 }, 41 TaskExecutor::TaskType::UI, "ArkUICallbackThreadWrapper", PriorityType::HIGH); 42 callback_ = nullptr; 43 } 44 } operator()45 void operator()() 46 { 47 if (callback_) { 48 callback_(); 49 if (once_) { 50 callback_ = nullptr; 51 } 52 } 53 } 54 private: 55 RefPtr<TaskExecutor> taskExecutor_; 56 std::function<void()> callback_; 57 bool once_ = false; // flag of executing only once 58 }; 59 } // namespace OHOS::Ace::NG 60 61 #endif // FOUNDATION_ACE_FRAMEWORKS_COMPONENTS_NG_ANIMATION_CALLBACK_THREAD_WRAPPER_H 62