1 /*
2  * Copyright (c) 2023 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 #include "rosen_window.h"
17 #include <chrono>
18 
19 #include "base/log/log.h"
20 
21 namespace OHOS::Ace {
22 
Create(AceView * view)23 std::unique_ptr<PlatformWindow> PlatformWindow::Create(AceView* view)
24 {
25     if (view != nullptr) {
26         return std::make_unique<Platform::RSWindow>();
27     } else {
28         return nullptr;
29     }
30 }
31 
32 namespace Platform {
33 
Destroy()34 void RSWindow::Destroy()
35 {
36     vsyncRequests_.Push(false);
37     vsyncThread_->join();
38 }
39 
RequestFrame()40 void RSWindow::RequestFrame()
41 {
42     if (vsyncThread_ == nullptr) {
43         auto func = std::bind(&RSWindow::VsyncThreadMain, this);
44         vsyncThread_ = std::make_unique<std::thread>(func);
45     }
46 
47     vsyncRequests_.Push(true);
48 }
49 
RegisterVsyncCallback(AceVsyncCallback && callback)50 void RSWindow::RegisterVsyncCallback(AceVsyncCallback&& callback)
51 {
52     std::unique_lock lock(mutex_);
53     pendingVsyncCallbacks_.emplace_back(std::move(callback));
54 }
55 
SetRootRenderNode(const RefPtr<RenderNode> & root)56 void RSWindow::SetRootRenderNode(const RefPtr<RenderNode>& root)
57 {
58 }
59 
SetUiDvsyncSwitch(bool dvsyncSwitch)60 void RSWindow::SetUiDvsyncSwitch(bool dvsyncSwitch)
61 {
62 }
63 
VsyncThreadMain()64 void RSWindow::VsyncThreadMain()
65 {
66     while (true) {
67         bool next = false;
68         vsyncRequests_.PopFront(next);
69         if (!next) {
70             break;
71         }
72 
73         std::this_thread::sleep_for(std::chrono::milliseconds(1));
74         {
75             std::unique_lock lock(mutex_);
76             vsyncCallbacks_.swap(pendingVsyncCallbacks_);
77         }
78         int64_t now = std::chrono::duration_cast<std::chrono::nanoseconds>(
79             std::chrono::steady_clock::now().time_since_epoch()).count();
80         for (auto &callback : vsyncCallbacks_) {
81             callback(now, 0);
82         }
83         vsyncCallbacks_.clear();
84     }
85 }
86 
87 } // namespace Platform
88 } // namespace OHOS::Ace
89