1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <chrono> 20 #include <condition_variable> 21 #include <functional> 22 #include <thread> 23 24 namespace android { 25 26 // NOLINTNEXTLINE(misc-unused-using-decls): False positive 27 using std::chrono_literals::operator""s; 28 29 struct FlatConCallbacks { 30 std::function<void()> trigger; 31 }; 32 33 class FlatteningController { 34 public: 35 static auto CreateInstance(FlatConCallbacks &cbks) 36 -> std::shared_ptr<FlatteningController>; 37 Disable()38 void Disable() { 39 auto lock = std::lock_guard<std::mutex>(mutex_); 40 flatten_next_frame_ = false; 41 disabled_ = true; 42 } 43 44 /* Compositor should call this every frame */ 45 bool NewFrame(); 46 ShouldFlatten()47 auto ShouldFlatten() const { 48 return flatten_next_frame_; 49 } 50 StopThread()51 void StopThread() { 52 auto lock = std::lock_guard<std::mutex>(mutex_); 53 cbks_ = {}; 54 cv_.notify_all(); 55 } 56 57 static constexpr auto kTimeout = 1s; 58 59 private: 60 FlatteningController() = default; 61 static void ThreadFn(const std::shared_ptr<FlatteningController> &fc); 62 63 bool flatten_next_frame_{}; 64 bool disabled_{}; decltype(std::chrono::system_clock::now ())65 decltype(std::chrono::system_clock::now()) sleep_until_{}; 66 std::mutex mutex_; 67 std::condition_variable cv_; 68 FlatConCallbacks cbks_; 69 }; 70 71 } // namespace android 72