• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "rs_render_service_connection.h"
17 #include <string>
18 
19 #include "frame_report.h"
20 #include "hgm_command.h"
21 #include "hgm_core.h"
22 #include "hgm_frame_rate_manager.h"
23 #include "offscreen_render/rs_offscreen_render_thread.h"
24 #include "rs_main_thread.h"
25 #include "rs_trace.h"
26 //blur predict
27 #include "rs_frame_blur_predict.h"
28 #include "system/rs_system_parameters.h"
29 
30 #include "command/rs_command_verify_helper.h"
31 #include "command/rs_display_node_command.h"
32 #include "command/rs_surface_node_command.h"
33 #include "common/rs_background_thread.h"
34 #include "display_engine/rs_luminance_control.h"
35 #include "drawable/rs_canvas_drawing_render_node_drawable.h"
36 #include "feature/capture/rs_ui_capture.h"
37 #include "feature/capture/rs_uni_ui_capture.h"
38 #include "feature/capture/rs_surface_capture_task.h"
39 #include "feature/capture/rs_ui_capture_task_parallel.h"
40 #include "feature/capture/rs_surface_capture_task_parallel.h"
41 #include "gfx/fps_info/rs_surface_fps_manager.h"
42 #ifdef RS_ENABLE_OVERLAY_DISPLAY
43 #include "feature/overlay_display/rs_overlay_display_manager.h"
44 #endif
45 #include "include/gpu/GrDirectContext.h"
46 #include "info_collection/rs_hdr_collection.h"
47 #ifdef RS_ENABLE_GPU
48 #include "feature/uifirst/rs_sub_thread_manager.h"
49 #endif
50 #include "feature/uifirst/rs_uifirst_manager.h"
51 #include "monitor/self_drawing_node_monitor.h"
52 #include "pipeline/rs_canvas_drawing_render_node.h"
53 #include "pipeline/rs_pointer_window_manager.h"
54 #ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
55 #include "pipeline/magic_pointer_render/rs_magic_pointer_render_manager.h"
56 #endif
57 #include "pipeline/hardware_thread/rs_realtime_refresh_rate_manager.h"
58 #include "pipeline/rs_render_frame_rate_linker_map.h"
59 #include "pipeline/rs_render_node_gc.h"
60 #include "pipeline/rs_render_node_map.h"
61 #include "pipeline/main_thread/rs_render_service_listener.h"
62 #include "pipeline/rs_surface_buffer_callback_manager.h"
63 #include "pipeline/rs_surface_render_node.h"
64 #include "pipeline/rs_task_dispatcher.h"
65 #include "pipeline/rs_uni_render_judgement.h"
66 #include "pixel_map_from_surface.h"
67 #include "platform/common/rs_log.h"
68 #include "platform/common/rs_system_properties.h"
69 #include "platform/ohos/rs_jank_stats.h"
70 #include "render/rs_typeface_cache.h"
71 #include "transaction/rs_unmarshal_thread.h"
72 
73 #ifdef TP_FEATURE_ENABLE
74 #include "screen_manager/touch_screen.h"
75 #endif
76 
77 #ifdef RS_ENABLE_VK
78 #include "platform/ohos/backend/rs_vulkan_context.h"
79 #endif
80 
81 namespace OHOS {
82 namespace Rosen {
83 namespace {
84 constexpr int SLEEP_TIME_US = 1000;
85 const std::string REGISTER_NODE = "RegisterNode";
86 const std::string APS_SET_VSYNC = "APS_SET_VSYNC";
87 }
88 // we guarantee that when constructing this object,
89 // all these pointers are valid, so will not check them.
RSRenderServiceConnection(pid_t remotePid,wptr<RSRenderService> renderService,RSMainThread * mainThread,sptr<RSScreenManager> screenManager,sptr<IRemoteObject> token,sptr<VSyncDistributor> distributor)90 RSRenderServiceConnection::RSRenderServiceConnection(
91     pid_t remotePid,
92     wptr<RSRenderService> renderService,
93     RSMainThread* mainThread,
94     sptr<RSScreenManager> screenManager,
95     sptr<IRemoteObject> token,
96     sptr<VSyncDistributor> distributor)
97     : remotePid_(remotePid),
98       renderService_(renderService),
99       mainThread_(mainThread),
100 #ifdef RS_ENABLE_GPU
101       renderThread_(RSUniRenderThread::Instance()),
102 #endif
103       screenManager_(screenManager),
104       token_(token),
105       connDeathRecipient_(new RSConnectionDeathRecipient(this)),
106       applicationDeathRecipient_(new RSApplicationRenderThreadDeathRecipient(this)),
107       appVSyncDistributor_(distributor)
108 {
109     if (token_ == nullptr || !token_->AddDeathRecipient(connDeathRecipient_)) {
110         RS_LOGW("RSRenderServiceConnection: Failed to set death recipient.");
111     }
112     if (renderService_ == nullptr) {
113         RS_LOGW("RSRenderServiceConnection: renderService_ is nullptr");
114     }
115     if (mainThread_ == nullptr) {
116         RS_LOGW("RSRenderServiceConnection: mainThread_ is nullptr");
117     }
118     if (screenManager_ == nullptr) {
119         RS_LOGW("RSRenderServiceConnection: screenManager_ is nullptr");
120     }
121     if (appVSyncDistributor_ == nullptr) {
122         RS_LOGW("RSRenderServiceConnection: appVSyncDistributor_ is nullptr");
123     }
124 }
125 
~RSRenderServiceConnection()126 RSRenderServiceConnection::~RSRenderServiceConnection() noexcept
127 {
128     if (token_ && connDeathRecipient_) {
129         token_->RemoveDeathRecipient(connDeathRecipient_);
130     }
131     CleanAll();
132 }
133 
CleanVirtualScreens()134 void RSRenderServiceConnection::CleanVirtualScreens() noexcept
135 {
136     std::lock_guard<std::mutex> lock(mutex_);
137 
138     if (screenManager_ != nullptr) {
139         for (const auto id : virtualScreenIds_) {
140             screenManager_->RemoveVirtualScreen(id);
141         }
142     }
143     virtualScreenIds_.clear();
144 
145     if (screenChangeCallback_ != nullptr && screenManager_ != nullptr) {
146         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
147         screenChangeCallback_ = nullptr;
148     }
149 }
150 
CleanRenderNodes()151 void RSRenderServiceConnection::CleanRenderNodes() noexcept
152 {
153     if (mainThread_ == nullptr) {
154         return;
155     }
156     auto& context = mainThread_->GetContext();
157     auto& nodeMap = context.GetMutableNodeMap();
158 
159     nodeMap.FilterNodeByPid(remotePid_);
160 }
161 
CleanFrameRateLinkers()162 void RSRenderServiceConnection::CleanFrameRateLinkers() noexcept
163 {
164     if (mainThread_ == nullptr) {
165         return;
166     }
167     auto& context = mainThread_->GetContext();
168     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
169 
170     frameRateLinkerMap.FilterFrameRateLinkerByPid(remotePid_);
171 }
172 
CleanFrameRateLinkerExpectedFpsCallbacks()173 void RSRenderServiceConnection::CleanFrameRateLinkerExpectedFpsCallbacks() noexcept
174 {
175     if (mainThread_ == nullptr) {
176         return;
177     }
178     auto& context = mainThread_->GetContext();
179     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
180     frameRateLinkerMap.UnRegisterExpectedFpsUpdateCallbackByListener(remotePid_);
181 }
182 
CleanAll(bool toDelete)183 void RSRenderServiceConnection::CleanAll(bool toDelete) noexcept
184 {
185     {
186         std::lock_guard<std::mutex> lock(mutex_);
187         if (cleanDone_) {
188             return;
189         }
190     }
191     if (!mainThread_) {
192         return;
193     }
194     RS_LOGD("RSRenderServiceConnection::CleanAll() start.");
195     RS_TRACE_NAME("RSRenderServiceConnection CleanAll begin, remotePid: " + std::to_string(remotePid_));
196     RsCommandVerifyHelper::GetInstance().RemoveCntWithPid(remotePid_);
197     mainThread_->ScheduleTask(
198         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
199             sptr<RSRenderServiceConnection> connection = weakThis.promote();
200             if (!connection) {
201                 return;
202             }
203             RS_TRACE_NAME_FMT("CleanVirtualScreens %d", connection->remotePid_);
204             connection->CleanVirtualScreens();
205         }).wait();
206     mainThread_->ScheduleTask(
207         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
208             sptr<RSRenderServiceConnection> connection = weakThis.promote();
209             if (!connection) {
210                 return;
211             }
212             RS_TRACE_NAME_FMT("CleanRenderNodes %d", connection->remotePid_);
213             connection->CleanRenderNodes();
214             connection->CleanFrameRateLinkers();
215             connection->CleanFrameRateLinkerExpectedFpsCallbacks();
216         }).wait();
217     mainThread_->ScheduleTask(
218         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
219             sptr<RSRenderServiceConnection> connection = weakThis.promote();
220             if (connection == nullptr || connection->mainThread_ == nullptr) {
221                 return;
222             }
223             RS_TRACE_NAME_FMT("ClearTransactionDataPidInfo %d", connection->remotePid_);
224             connection->mainThread_->ClearTransactionDataPidInfo(connection->remotePid_);
225         }).wait();
226     mainThread_->ScheduleTask(
227         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
228             sptr<RSRenderServiceConnection> connection = weakThis.promote();
229             if (connection == nullptr || connection->mainThread_ == nullptr) {
230                 return;
231             }
232             RS_TRACE_NAME_FMT("UnRegisterCallback %d", connection->remotePid_);
233             connection->mainThread_->UnRegisterOcclusionChangeCallback(connection->remotePid_);
234             connection->mainThread_->ClearSurfaceOcclusionChangeCallback(connection->remotePid_);
235             connection->mainThread_->UnRegisterUIExtensionCallback(connection->remotePid_);
236         }).wait();
237     if (SelfDrawingNodeMonitor::GetInstance().IsListeningEnabled()) {
238         mainThread_->ScheduleTask(
239             [weakThis = wptr<RSRenderServiceConnection>(this)]() {
240                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
241                 if (connection == nullptr) {
242                     return;
243                 }
244                 auto &monitor = SelfDrawingNodeMonitor::GetInstance();
245                 if (connection->remotePid_ == monitor.GetCallingPid()) {
246                     monitor.ClearRectMap();
247                     monitor.UnRegisterRectChangeCallback(connection->remotePid_);
248                 }
249             }).wait();
250     }
251     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(remotePid_);
252     HgmTaskHandleThread::Instance().ScheduleTask([pid = remotePid_] () {
253         RS_TRACE_NAME_FMT("CleanHgmEvent %d", pid);
254         HgmConfigCallbackManager::GetInstance()->UnRegisterHgmConfigChangeCallback(pid);
255         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
256         if (frameRateMgr != nullptr) {
257             frameRateMgr->CleanVote(pid);
258         }
259     }).wait();
260     RSTypefaceCache::Instance().RemoveDrawingTypefacesByPid(remotePid_);
261     {
262         std::lock_guard<std::mutex> lock(mutex_);
263         cleanDone_ = true;
264     }
265 
266     if (toDelete) {
267         auto renderService = renderService_.promote();
268         if (renderService == nullptr) {
269             RS_LOGW("RSRenderServiceConnection::CleanAll() RenderService is dead.");
270         } else {
271             renderService->RemoveConnection(GetToken());
272         }
273     }
274 
275     RS_LOGD("RSRenderServiceConnection::CleanAll() end.");
276     RS_TRACE_NAME("RSRenderServiceConnection CleanAll end, remotePid: " + std::to_string(remotePid_));
277 }
278 
RSConnectionDeathRecipient(wptr<RSRenderServiceConnection> conn)279 RSRenderServiceConnection::RSConnectionDeathRecipient::RSConnectionDeathRecipient(
280     wptr<RSRenderServiceConnection> conn) : conn_(conn)
281 {
282 }
283 
OnRemoteDied(const wptr<IRemoteObject> & token)284 void RSRenderServiceConnection::RSConnectionDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
285 {
286     auto tokenSptr = token.promote();
287     if (tokenSptr == nullptr) {
288         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: can't promote remote object.");
289         return;
290     }
291 
292     auto rsConn = conn_.promote();
293     if (rsConn == nullptr) {
294         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: RSRenderServiceConnection was dead, do nothing.");
295         return;
296     }
297 
298     if (rsConn->GetToken() != tokenSptr) {
299         RS_LOGI("RSConnectionDeathRecipient::OnRemoteDied: token doesn't match, ignore it.");
300         return;
301     }
302 
303     rsConn->CleanAll(true);
304 }
305 
RSApplicationRenderThreadDeathRecipient(wptr<RSRenderServiceConnection> conn)306 RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::RSApplicationRenderThreadDeathRecipient(
307     wptr<RSRenderServiceConnection> conn) : conn_(conn)
308 {}
309 
OnRemoteDied(const wptr<IRemoteObject> & token)310 void RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
311 {
312     auto tokenSptr = token.promote();
313     if (tokenSptr == nullptr) {
314         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: can't promote remote object.");
315         return;
316     }
317 
318     auto rsConn = conn_.promote();
319     if (rsConn == nullptr) {
320         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: "
321             "RSRenderServiceConnection was dead, do nothing.");
322         return;
323     }
324 
325     RS_LOGD("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: Unregister.");
326     auto app = iface_cast<IApplicationAgent>(tokenSptr);
327     rsConn->UnRegisterApplicationAgent(app);
328 }
329 
CommitTransaction(std::unique_ptr<RSTransactionData> & transactionData)330 ErrCode RSRenderServiceConnection::CommitTransaction(std::unique_ptr<RSTransactionData>& transactionData)
331 {
332     if (!mainThread_) {
333         return ERR_INVALID_VALUE;
334     }
335     pid_t callingPid = GetCallingPid();
336     bool isTokenTypeValid = true;
337     bool isNonSystemAppCalling = false;
338     RSInterfaceCodeAccessVerifierBase::GetAccessType(isTokenTypeValid, isNonSystemAppCalling);
339     bool shouldDrop = RSUnmarshalThread::Instance().ReportTransactionDataStatistics(
340         callingPid, transactionData.get(), isNonSystemAppCalling);
341     if (shouldDrop) {
342         RS_LOGW("RSRenderServiceConnection::CommitTransaction data droped");
343         return ERR_INVALID_VALUE;
344     }
345     bool isProcessBySingleFrame = mainThread_->IsNeedProcessBySingleFrameComposer(transactionData);
346     if (isProcessBySingleFrame) {
347         mainThread_->ProcessDataBySingleFrameComposer(transactionData);
348     } else {
349         mainThread_->RecvRSTransactionData(transactionData);
350     }
351     return ERR_OK;
352 }
353 
ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask> & task)354 ErrCode RSRenderServiceConnection::ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask>& task)
355 {
356     if (task == nullptr || mainThread_ == nullptr) {
357         RS_LOGW("RSRenderServiceConnection::ExecuteSynchronousTask, task or main thread is null!");
358         return ERR_INVALID_VALUE;
359     }
360     auto screenManager = CreateOrGetScreenManager();
361     if (screenManager && screenManager->IsScreenPoweringOn() && task->GetType() == RS_NODE_SYNCHRONOUS_READ_PROPERTY) {
362         RS_LOGI("RSRenderServiceConnection::ExecuteSynchronousTask, when screen is powering on, the task is executed "
363                 "in the IPC thread");
364         task->Process(mainThread_->GetContext());
365         return ERR_INVALID_VALUE;
366     }
367     // After a synchronous task times out, it will no longer be executed.
368     auto isTimeout = std::make_shared<bool>(0);
369     std::weak_ptr<bool> isTimeoutWeak = isTimeout;
370     std::chrono::nanoseconds span(task->GetTimeout());
371     mainThread_->ScheduleTask([task, mainThread = mainThread_, isTimeoutWeak] {
372         if (task == nullptr || mainThread == nullptr || isTimeoutWeak.expired()) {
373             return;
374         }
375         task->Process(mainThread->GetContext());
376     }).wait_for(span);
377     isTimeout.reset();
378     return ERR_OK;
379 }
380 
GetUniRenderEnabled(bool & enable)381 ErrCode RSRenderServiceConnection::GetUniRenderEnabled(bool& enable)
382 {
383     enable = RSUniRenderJudgement::IsUniRender();
384     return  ERR_OK;
385 }
386 
CreateNode(const RSDisplayNodeConfig & displayNodeConfig,NodeId nodeId,bool & success)387 ErrCode RSRenderServiceConnection::CreateNode(const RSDisplayNodeConfig& displayNodeConfig, NodeId nodeId,
388     bool& success)
389 {
390     if (!mainThread_) {
391         success = false;
392         return ERR_INVALID_VALUE;
393     }
394     std::shared_ptr<RSDisplayRenderNode> node =
395         DisplayNodeCommandHelper::CreateWithConfigInRS(mainThread_->GetContext(), nodeId,
396             displayNodeConfig);
397     if (node == nullptr) {
398         RS_LOGE("RSRenderService::CreateDisplayNode fail");
399         success = false;
400         return ERR_INVALID_VALUE;
401     }
402     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this),
403         mirrorNodeId = displayNodeConfig.mirrorNodeId]() -> void {
404         sptr<RSRenderServiceConnection> connection = weakThis.promote();
405         if (connection == nullptr || connection->mainThread_ == nullptr) {
406             return;
407         }
408         auto& context = connection->mainThread_->GetContext();
409         context.GetMutableNodeMap().RegisterRenderNode(node);
410         context.GetGlobalRootRenderNode()->AddChild(node);
411         auto mirrorSourceNode = context.GetNodeMap()
412             .GetRenderNode<RSDisplayRenderNode>(mirrorNodeId);
413         if (!mirrorSourceNode) {
414             return;
415         }
416         node->SetMirrorSource(mirrorSourceNode);
417     };
418     mainThread_->PostSyncTask(registerNode);
419     success = true;
420     return ERR_OK;
421 }
422 
CreateNode(const RSSurfaceRenderNodeConfig & config,bool & success)423 ErrCode RSRenderServiceConnection::CreateNode(const RSSurfaceRenderNodeConfig& config, bool& success)
424 {
425     if (!mainThread_) {
426         success = false;
427         return ERR_INVALID_VALUE;
428     }
429     std::shared_ptr<RSSurfaceRenderNode> node =
430         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext());
431     if (node == nullptr) {
432         RS_LOGE("RSRenderService::CreateNode fail");
433         success = false;
434         return ERR_INVALID_VALUE;
435     }
436     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
437         sptr<RSRenderServiceConnection> connection = weakThis.promote();
438         if (connection == nullptr || connection->mainThread_ == nullptr) {
439             return;
440         }
441         connection->mainThread_->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
442     };
443     mainThread_->PostTask(registerNode);
444     success = true;
445     return ERR_OK;
446 }
447 
CreateNodeAndSurface(const RSSurfaceRenderNodeConfig & config,sptr<Surface> & sfc,bool unobscured)448 ErrCode RSRenderServiceConnection::CreateNodeAndSurface(const RSSurfaceRenderNodeConfig& config,
449     sptr<Surface>& sfc, bool unobscured)
450 {
451     if (!mainThread_) {
452         return ERR_INVALID_VALUE;
453     }
454     std::shared_ptr<RSSurfaceRenderNode> node =
455         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext(), unobscured);
456     if (node == nullptr) {
457         RS_LOGE("RSRenderService::CreateNodeAndSurface CreateNode fail");
458         return ERR_INVALID_VALUE;
459     }
460     sptr<IConsumerSurface> surface = IConsumerSurface::Create(config.name);
461     if (surface == nullptr) {
462         RS_LOGE("RSRenderService::CreateNodeAndSurface get consumer surface fail");
463         return ERR_INVALID_VALUE;
464     }
465     const std::string& surfaceName = surface->GetName();
466     RS_LOGI("RsDebug RSRenderService::CreateNodeAndSurface node" \
467         "id:%{public}" PRIu64 " name:%{public}s surface id:%{public}" PRIu64 " name:%{public}s",
468         node->GetId(), node->GetName().c_str(),
469         surface->GetUniqueId(), surfaceName.c_str());
470     auto defaultUsage = surface->GetDefaultUsage();
471     surface->SetDefaultUsage(defaultUsage | BUFFER_USAGE_MEM_DMA | BUFFER_USAGE_HW_COMPOSER);
472     node->GetRSSurfaceHandler()->SetConsumer(surface);
473     RSMainThread* mainThread = mainThread_;
474     std::function<void()> registerNode = [node, mainThread]() -> void {
475         if (auto preNode = mainThread->GetContext().GetNodeMap().GetRenderNode(node->GetId())) {
476             RS_LOGE("CreateNodeAndSurface same id node:%{public}" PRIu64 ", type:%d",
477                 node->GetId(), preNode->GetType());
478             usleep(SLEEP_TIME_US);
479         }
480         RS_LOGI("CreateNodeAndSurface RegisterRenderNode id:%{public}" PRIu64 ", name:%{public}s", node->GetId(),
481             node->GetName().c_str());
482         mainThread->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
483     };
484     if (config.isSync) {
485         mainThread_->PostSyncTask(registerNode);
486     } else {
487         mainThread_->PostTask(registerNode, REGISTER_NODE, 0, AppExecFwk::EventQueue::Priority::VIP);
488     }
489     std::weak_ptr<RSSurfaceRenderNode> surfaceRenderNode(node);
490     sptr<IBufferConsumerListener> listener = new RSRenderServiceListener(surfaceRenderNode);
491     SurfaceError ret = surface->RegisterConsumerListener(listener);
492     if (ret != SURFACE_ERROR_OK) {
493         RS_LOGE("RSRenderService::CreateNodeAndSurface Register Consumer Listener fail");
494         return ERR_INVALID_VALUE;
495     }
496     sptr<IBufferProducer> producer = surface->GetProducer();
497     sfc = Surface::CreateSurfaceAsProducer(producer);
498     return ERR_OK;
499 }
500 
CreateVSyncConnection(const std::string & name,const sptr<VSyncIConnectionToken> & token,uint64_t id,NodeId windowNodeId,bool fromXcomponent)501 sptr<IVSyncConnection> RSRenderServiceConnection::CreateVSyncConnection(const std::string& name,
502                                                                         const sptr<VSyncIConnectionToken>& token,
503                                                                         uint64_t id,
504                                                                         NodeId windowNodeId,
505                                                                         bool fromXcomponent)
506 {
507     if (mainThread_ == nullptr || appVSyncDistributor_ == nullptr) {
508         return nullptr;
509     }
510     if (fromXcomponent) {
511         mainThread_->ScheduleTask([&windowNodeId]() {
512             auto& node = RSMainThread::Instance()->GetContext().GetNodeMap()
513                         .GetRenderNode<RSRenderNode>(windowNodeId);
514             if (node == nullptr) {
515                 RS_LOGE("RSRenderServiceConnection::CreateVSyncConnection:node is nullptr");
516                 return;
517             }
518             windowNodeId = node->GetInstanceRootNodeId();
519         }).wait();
520     }
521     sptr<VSyncConnection> conn = new VSyncConnection(appVSyncDistributor_, name, token->AsObject(), 0, windowNodeId);
522     if (ExtractPid(id) == remotePid_) {
523         auto observer = [] (const RSRenderFrameRateLinker& linker) {
524             if (auto mainThread = RSMainThread::Instance(); mainThread != nullptr) {
525                 HgmCore::Instance().SetHgmTaskFlag(true);
526             }
527         };
528         mainThread_->ScheduleTask([weakThis = wptr<RSRenderServiceConnection>(this), id, observer, name]() {
529             sptr<RSRenderServiceConnection> connection = weakThis.promote();
530             if (connection == nullptr || connection->mainThread_ == nullptr) {
531                 return;
532             }
533             auto linker = std::make_shared<RSRenderFrameRateLinker>(id, observer);
534             linker->SetVsyncName(name);
535             auto& context = connection->mainThread_->GetContext();
536             auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
537             frameRateLinkerMap.RegisterFrameRateLinker(linker);
538         }).wait();
539         conn->id_ = id;
540         RS_LOGD("CreateVSyncConnection connect id: %{public}" PRIu64, id);
541     }
542     auto ret = appVSyncDistributor_->AddConnection(conn, windowNodeId);
543     if (ret != VSYNC_ERROR_OK) {
544         return nullptr;
545     }
546     return conn;
547 }
548 
GetPixelMapByProcessId(std::vector<PixelMapInfo> & pixelMapInfoVector,pid_t pid,int32_t & repCode)549 ErrCode RSRenderServiceConnection::GetPixelMapByProcessId(
550     std::vector<PixelMapInfo>& pixelMapInfoVector, pid_t pid, int32_t& repCode)
551 {
552     if (mainThread_ == nullptr) {
553         repCode = INVALID_ARGUMENTS;
554         return ERR_INVALID_VALUE;
555     }
556     std::vector<std::tuple<sptr<SurfaceBuffer>, std::string, RectI>> sfBufferInfoVector;
557     std::function<void()> getSurfaceBufferByPidTask = [weakThis = wptr<RSRenderServiceConnection>(this),
558                                                           &sfBufferInfoVector, pid]() -> void {
559         sptr<RSRenderServiceConnection> connection = weakThis.promote();
560         if (connection == nullptr || connection->mainThread_ == nullptr) {
561             return;
562         }
563         RS_TRACE_NAME_FMT("RSRenderServiceConnection::GetPixelMapByProcessId getSurfaceBufferByPidTask pid: %d", pid);
564         auto selfDrawingNodeVector =
565             connection->mainThread_->GetContext().GetMutableNodeMap().GetSelfDrawingNodeInProcess(pid);
566         for (auto iter = selfDrawingNodeVector.rbegin(); iter != selfDrawingNodeVector.rend(); ++iter) {
567             auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(*iter);
568             if (auto surfaceNode = node->ReinterpretCastTo<RSSurfaceRenderNode>()) {
569                 auto surfaceBuffer = surfaceNode->GetRSSurfaceHandler()->GetBuffer();
570                 auto surfaceBufferInfo = std::make_tuple(surfaceBuffer, surfaceNode->GetName(),
571                     surfaceNode->GetRenderProperties().GetBoundsGeometry()->GetAbsRect());
572                 sfBufferInfoVector.push_back(surfaceBufferInfo);
573             }
574         }
575     };
576     mainThread_->PostSyncTask(getSurfaceBufferByPidTask);
577 
578     for (uint32_t i = 0; i < sfBufferInfoVector.size(); i++) {
579         auto surfaceBuffer = std::get<0>(sfBufferInfoVector[i]);
580         if (surfaceBuffer) {
581             OHOS::Media::Rect rect = {0, 0, surfaceBuffer->GetWidth(), surfaceBuffer->GetHeight()};
582             std::shared_ptr<Media::PixelMap> pixelmap = nullptr;
583             RSBackgroundThread::Instance().PostSyncTask([&surfaceBuffer, rect, &pixelmap]() {
584                 pixelmap = OHOS::Rosen::CreatePixelMapFromSurfaceBuffer(surfaceBuffer, rect);
585             });
586             PixelMapInfo info;
587             info.pixelMap = pixelmap;
588             RectI absRect = std::get<2>(sfBufferInfoVector[i]);
589             info.location = {absRect.GetLeft(), absRect.GetTop(), absRect.GetWidth(), absRect.GetHeight(), i};
590             info.nodeName = std::get<1>(sfBufferInfoVector[i]);
591             pixelMapInfoVector.push_back(info);
592         } else {
593             RS_LOGE("RSRenderServiceConnection::CreatePixelMapFromSurface surfaceBuffer is null");
594         }
595     }
596     repCode = SUCCESS;
597     return ERR_OK;
598 }
599 
CreatePixelMapFromSurface(sptr<Surface> surface,const Rect & srcRect,std::shared_ptr<Media::PixelMap> & pixelMap)600 ErrCode RSRenderServiceConnection::CreatePixelMapFromSurface(sptr<Surface> surface,
601     const Rect &srcRect, std::shared_ptr<Media::PixelMap> &pixelMap)
602 {
603     OHOS::Media::Rect rect = {
604         .left = srcRect.x,
605         .top = srcRect.y,
606         .width = srcRect.w,
607         .height = srcRect.h,
608     };
609     RSBackgroundThread::Instance().PostSyncTask([surface, rect, &pixelMap]() {
610         pixelMap = OHOS::Rosen::CreatePixelMapFromSurface(surface, rect);
611     });
612     return ERR_OK;
613 }
614 
SetFocusAppInfo(int32_t pid,int32_t uid,const std::string & bundleName,const std::string & abilityName,uint64_t focusNodeId)615 int32_t RSRenderServiceConnection::SetFocusAppInfo(
616     int32_t pid, int32_t uid, const std::string &bundleName, const std::string &abilityName, uint64_t focusNodeId)
617 {
618     if (mainThread_ == nullptr) {
619         return INVALID_ARGUMENTS;
620     }
621     mainThread_->ScheduleTask(
622         [pid, uid, bundleName, abilityName, focusNodeId, mainThread = mainThread_]() {
623             // don't use 'this' to get mainThread poninter
624             mainThread->SetFocusAppInfo(pid, uid, bundleName, abilityName, focusNodeId);
625         }
626     );
627     return SUCCESS;
628 }
629 
SetWatermark(const std::string & name,std::shared_ptr<Media::PixelMap> watermark,bool & success)630 ErrCode RSRenderServiceConnection::SetWatermark(const std::string& name, std::shared_ptr<Media::PixelMap> watermark,
631     bool& success)
632 {
633     if (!mainThread_) {
634         success = false;
635         return ERR_INVALID_VALUE;
636     }
637     mainThread_->SetWatermark(name, watermark);
638     success = true;
639     return ERR_OK;
640 }
641 
GetDefaultScreenId()642 ScreenId RSRenderServiceConnection::GetDefaultScreenId()
643 {
644     std::lock_guard<std::mutex> lock(mutex_);
645     if (!screenManager_) {
646         return INVALID_SCREEN_ID;
647     }
648     return screenManager_->GetDefaultScreenId();
649 }
650 
GetActiveScreenId()651 ScreenId RSRenderServiceConnection::GetActiveScreenId()
652 {
653     std::lock_guard<std::mutex> lock(mutex_);
654     if (!screenManager_) {
655         return INVALID_SCREEN_ID;
656     }
657     return screenManager_->GetActiveScreenId();
658 }
659 
GetAllScreenIds()660 std::vector<ScreenId> RSRenderServiceConnection::GetAllScreenIds()
661 {
662     std::lock_guard<std::mutex> lock(mutex_);
663     if (!screenManager_) {
664         return std::vector<ScreenId>();
665     }
666     return screenManager_->GetAllScreenIds();
667 }
668 
CreateVirtualScreen(const std::string & name,uint32_t width,uint32_t height,sptr<Surface> surface,ScreenId mirrorId,int32_t flags,std::vector<NodeId> whiteList)669 ScreenId RSRenderServiceConnection::CreateVirtualScreen(
670     const std::string &name,
671     uint32_t width,
672     uint32_t height,
673     sptr<Surface> surface,
674     ScreenId mirrorId,
675     int32_t flags,
676     std::vector<NodeId> whiteList)
677 {
678     std::lock_guard<std::mutex> lock(mutex_);
679     if (!screenManager_) {
680         return StatusCode::SCREEN_NOT_FOUND;
681     }
682     auto newVirtualScreenId = screenManager_->CreateVirtualScreen(
683         name, width, height, surface, mirrorId, flags, whiteList);
684     virtualScreenIds_.insert(newVirtualScreenId);
685     if (surface != nullptr) {
686         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ, name };
687         NotifyRefreshRateEvent(event);
688     }
689     return newVirtualScreenId;
690 }
691 
SetVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)692 int32_t RSRenderServiceConnection::SetVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
693 {
694     if (blackListVector.empty()) {
695         RS_LOGW("SetVirtualScreenBlackList blackList is empty.");
696     }
697     std::lock_guard<std::mutex> lock(mutex_);
698     if (!screenManager_) {
699         return StatusCode::SCREEN_NOT_FOUND;
700     }
701     return screenManager_->SetVirtualScreenBlackList(id, blackListVector);
702 }
703 
AddVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector,int32_t & repCode)704 ErrCode RSRenderServiceConnection::AddVirtualScreenBlackList(
705     ScreenId id, std::vector<NodeId>& blackListVector, int32_t& repCode)
706 {
707     if (blackListVector.empty()) {
708         RS_LOGW("AddVirtualScreenBlackList blackList is empty.");
709         repCode = StatusCode::BLACKLIST_IS_EMPTY;
710         return ERR_INVALID_VALUE;
711     }
712     std::lock_guard<std::mutex> lock(mutex_);
713     if (!screenManager_) {
714         repCode = StatusCode::SCREEN_NOT_FOUND;
715         return ERR_INVALID_VALUE;
716     }
717     repCode = screenManager_->AddVirtualScreenBlackList(id, blackListVector);
718     return ERR_OK;
719 }
720 
RemoveVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector,int32_t & repCode)721 ErrCode RSRenderServiceConnection::RemoveVirtualScreenBlackList(
722     ScreenId id, std::vector<NodeId>& blackListVector, int32_t& repCode)
723 {
724     if (blackListVector.empty()) {
725         RS_LOGW("RemoveVirtualScreenBlackList blackList is empty.");
726         repCode = StatusCode::BLACKLIST_IS_EMPTY;
727         return ERR_INVALID_VALUE;
728     }
729     std::lock_guard<std::mutex> lock(mutex_);
730     if (!screenManager_) {
731         repCode = StatusCode::SCREEN_NOT_FOUND;
732         return ERR_INVALID_VALUE;
733     }
734     repCode = screenManager_->RemoveVirtualScreenBlackList(id, blackListVector);
735     return ERR_OK;
736 }
737 
SetVirtualScreenSecurityExemptionList(ScreenId id,const std::vector<NodeId> & securityExemptionList)738 int32_t RSRenderServiceConnection::SetVirtualScreenSecurityExemptionList(
739     ScreenId id,
740     const std::vector<NodeId>& securityExemptionList)
741 {
742     if (!screenManager_) {
743         return StatusCode::SCREEN_NOT_FOUND;
744     }
745     return screenManager_->SetVirtualScreenSecurityExemptionList(id, securityExemptionList);
746 }
747 
SetScreenSecurityMask(ScreenId id,std::shared_ptr<Media::PixelMap> securityMask)748 int32_t RSRenderServiceConnection::SetScreenSecurityMask(ScreenId id,
749     std::shared_ptr<Media::PixelMap> securityMask)
750 {
751     if (!screenManager_) {
752         return StatusCode::SCREEN_NOT_FOUND;
753     }
754     return screenManager_->SetScreenSecurityMask(id, std::move(securityMask));
755 }
756 
SetMirrorScreenVisibleRect(ScreenId id,const Rect & mainScreenRect,bool supportRotation)757 int32_t RSRenderServiceConnection::SetMirrorScreenVisibleRect(ScreenId id, const Rect& mainScreenRect,
758     bool supportRotation)
759 {
760     if (screenManager_ == nullptr) {
761         return StatusCode::SCREEN_NOT_FOUND;
762     }
763     return screenManager_->SetMirrorScreenVisibleRect(id, mainScreenRect, supportRotation);
764 }
765 
SetCastScreenEnableSkipWindow(ScreenId id,bool enable)766 int32_t RSRenderServiceConnection::SetCastScreenEnableSkipWindow(ScreenId id, bool enable)
767 {
768     std::lock_guard<std::mutex> lock(mutex_);
769     if (!screenManager_) {
770         return StatusCode::SCREEN_NOT_FOUND;
771     }
772     return screenManager_->SetCastScreenEnableSkipWindow(id, enable);
773 }
774 
SetVirtualScreenSurface(ScreenId id,sptr<Surface> surface)775 int32_t RSRenderServiceConnection::SetVirtualScreenSurface(ScreenId id, sptr<Surface> surface)
776 {
777     std::lock_guard<std::mutex> lock(mutex_);
778     if (!screenManager_) {
779         return StatusCode::SCREEN_NOT_FOUND;
780     }
781     return screenManager_->SetVirtualScreenSurface(id, surface);
782 }
783 
784 #ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
SetPointerColorInversionConfig(float darkBuffer,float brightBuffer,int64_t interval,int32_t rangeSize)785 int32_t RSRenderServiceConnection::SetPointerColorInversionConfig(float darkBuffer,
786     float brightBuffer, int64_t interval, int32_t rangeSize)
787 {
788     RSMagicPointerRenderManager::GetInstance().SetPointerColorInversionConfig(darkBuffer, brightBuffer,
789         interval, rangeSize);
790     return StatusCode::SUCCESS;
791 }
792 
SetPointerColorInversionEnabled(bool enable)793 int32_t RSRenderServiceConnection::SetPointerColorInversionEnabled(bool enable)
794 {
795     RSMagicPointerRenderManager::GetInstance().SetPointerColorInversionEnabled(enable);
796     return StatusCode::SUCCESS;
797 }
798 
RegisterPointerLuminanceChangeCallback(sptr<RSIPointerLuminanceChangeCallback> callback)799 int32_t RSRenderServiceConnection::RegisterPointerLuminanceChangeCallback(
800     sptr<RSIPointerLuminanceChangeCallback> callback)
801 {
802     if (!callback) {
803         RS_LOGE("RSRenderServiceConnection::RegisterPointerLuminanceChangeCallback: callback is nullptr");
804         return StatusCode::INVALID_ARGUMENTS;
805     }
806     RSMagicPointerRenderManager::GetInstance().RegisterPointerLuminanceChangeCallback(remotePid_, callback);
807     return StatusCode::SUCCESS;
808 }
809 
UnRegisterPointerLuminanceChangeCallback()810 int32_t RSRenderServiceConnection::UnRegisterPointerLuminanceChangeCallback()
811 {
812     RSMagicPointerRenderManager::GetInstance().UnRegisterPointerLuminanceChangeCallback(remotePid_);
813     return StatusCode::SUCCESS;
814 }
815 #endif
816 
RemoveVirtualScreen(ScreenId id)817 void RSRenderServiceConnection::RemoveVirtualScreen(ScreenId id)
818 {
819     std::lock_guard<std::mutex> lock(mutex_);
820     if (!screenManager_) {
821         return;
822     }
823     screenManager_->RemoveVirtualScreen(id);
824     virtualScreenIds_.erase(id);
825     EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
826     NotifyRefreshRateEvent(event);
827 }
828 
SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)829 int32_t RSRenderServiceConnection::SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)
830 {
831     if (!callback) {
832         return INVALID_ARGUMENTS;
833     }
834     std::unique_lock<std::mutex> lock(mutex_);
835     if (screenChangeCallback_ == callback) {
836         return INVALID_ARGUMENTS;
837     }
838     if (screenManager_ == nullptr) {
839         return SCREEN_NOT_FOUND;
840     }
841 
842     if (screenChangeCallback_ != nullptr) {
843         // remove the old callback
844         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
845     }
846 
847     // update
848     int32_t status = screenManager_->AddScreenChangeCallback(callback);
849     screenChangeCallback_ = callback;
850     return status;
851 }
852 
SetScreenActiveMode(ScreenId id,uint32_t modeId)853 void RSRenderServiceConnection::SetScreenActiveMode(ScreenId id, uint32_t modeId)
854 {
855     if (!screenManager_) {
856         return;
857     }
858     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
859     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
860 #ifdef RS_ENABLE_GPU
861         return RSHardwareThread::Instance().ScheduleTask(
862             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
863 #endif
864     } else if (mainThread_ != nullptr) {
865         return mainThread_->ScheduleTask(
866             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
867     }
868 }
869 
SetScreenRefreshRate(ScreenId id,int32_t sceneId,int32_t rate)870 void RSRenderServiceConnection::SetScreenRefreshRate(ScreenId id, int32_t sceneId, int32_t rate)
871 {
872     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetScreenRefreshRate");
873     HgmTaskHandleThread::Instance().PostTask([id, sceneId, rate] () {
874         int32_t setResult = OHOS::Rosen::HgmCore::Instance().SetScreenRefreshRate(id, sceneId, rate);
875         if (setResult != 0) {
876             RS_LOGW("SetScreenRefreshRate request of screen %{public}" PRIu64 " of rate %{public}d is refused",
877                 id, rate);
878             return;
879         }
880     });
881     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
882 }
883 
SetRefreshRateMode(int32_t refreshRateMode)884 void RSRenderServiceConnection::SetRefreshRateMode(int32_t refreshRateMode)
885 {
886     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetRefreshRateMode");
887     HgmTaskHandleThread::Instance().PostTask([refreshRateMode] () {
888         int32_t setResult = OHOS::Rosen::HgmCore::Instance().SetRefreshRateMode(refreshRateMode);
889         RSSystemProperties::SetHgmRefreshRateModesEnabled(std::to_string(refreshRateMode));
890         if (setResult != 0) {
891             RS_LOGW("SetRefreshRateMode mode %{public}d is not supported", refreshRateMode);
892         }
893     });
894     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
895 }
896 
SyncFrameRateRange(FrameRateLinkerId id,const FrameRateRange & range,int32_t animatorExpectedFrameRate)897 void RSRenderServiceConnection::SyncFrameRateRange(FrameRateLinkerId id,
898     const FrameRateRange& range, int32_t animatorExpectedFrameRate)
899 {
900     if (!mainThread_) {
901         return;
902     }
903     mainThread_->ScheduleTask(
904         [weakThis = wptr<RSRenderServiceConnection>(this), id, &range, animatorExpectedFrameRate]() {
905             sptr<RSRenderServiceConnection> connection = weakThis.promote();
906             if (connection == nullptr || connection->mainThread_ == nullptr) {
907                 return;
908             }
909             auto& context = connection->mainThread_->GetContext();
910             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
911             auto linker = linkerMap.GetFrameRateLinker(id);
912             if (linker == nullptr) {
913                 RS_LOGW("SyncFrameRateRange there is no frameRateLinker for id %{public}" PRIu64, id);
914                 return;
915             }
916             linker->SetExpectedRange(range);
917             linker->SetAnimatorExpectedFrameRate(animatorExpectedFrameRate);
918         }).wait();
919 }
920 
UnregisterFrameRateLinker(FrameRateLinkerId id)921 void RSRenderServiceConnection::UnregisterFrameRateLinker(FrameRateLinkerId id)
922 {
923     if (!mainThread_) {
924         return;
925     }
926     mainThread_->ScheduleTask(
927         [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
928             sptr<RSRenderServiceConnection> connection = weakThis.promote();
929             if (connection == nullptr || connection->mainThread_ == nullptr) {
930                 return;
931             }
932             auto& context = connection->mainThread_->GetContext();
933             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
934             auto linker = linkerMap.GetFrameRateLinker(id);
935             if (linker == nullptr) {
936                 RS_LOGE("UnregisterFrameRateLinker there is no frameRateLinker for id %{public}" PRIu64, id);
937                 return;
938             }
939             linkerMap.UnregisterFrameRateLinker(id);
940         }).wait();
941 }
942 
GetScreenCurrentRefreshRate(ScreenId id)943 uint32_t RSRenderServiceConnection::GetScreenCurrentRefreshRate(ScreenId id)
944 {
945     uint32_t rate = HgmTaskHandleThread::Instance().ScheduleTask([id] () -> uint32_t {
946         return OHOS::Rosen::HgmCore::Instance().GetScreenCurrentRefreshRate(id);
947     }).get();
948     if (rate == 0) {
949         RS_LOGW("GetScreenCurrentRefreshRate failed to get current refreshrate of"
950             " screen : %{public}" PRIu64 "", id);
951     }
952     return rate;
953 }
954 
GetScreenSupportedRefreshRates(ScreenId id)955 std::vector<int32_t> RSRenderServiceConnection::GetScreenSupportedRefreshRates(ScreenId id)
956 {
957     return HgmTaskHandleThread::Instance().ScheduleTask([id] () -> std::vector<int32_t> {
958         return OHOS::Rosen::HgmCore::Instance().GetScreenComponentRefreshRates(id);
959     }).get();
960 }
961 
GetShowRefreshRateEnabled()962 bool RSRenderServiceConnection::GetShowRefreshRateEnabled()
963 {
964     return RSRealtimeRefreshRateManager::Instance().GetShowRefreshRateEnabled();
965 }
966 
SetShowRefreshRateEnabled(bool enabled,int32_t type)967 void RSRenderServiceConnection::SetShowRefreshRateEnabled(bool enabled, int32_t type)
968 {
969     return RSRealtimeRefreshRateManager::Instance().SetShowRefreshRateEnabled(enabled, type);
970 }
971 
GetRealtimeRefreshRate(ScreenId screenId)972 uint32_t RSRenderServiceConnection::GetRealtimeRefreshRate(ScreenId screenId)
973 {
974     return RSRealtimeRefreshRateManager::Instance().GetRealtimeRefreshRate(screenId);
975 }
976 
GetRefreshInfo(pid_t pid,std::string & enable)977 ErrCode RSRenderServiceConnection::GetRefreshInfo(pid_t pid, std::string& enable)
978 {
979     if (!mainThread_) {
980         enable = "";
981         return ERR_INVALID_VALUE;
982     }
983     auto& context = mainThread_->GetContext();
984     auto& nodeMap = context.GetMutableNodeMap();
985     std::string surfaceName = nodeMap.GetSelfDrawSurfaceNameByPid(pid);
986     NodeId nodeId = 0;
987     nodeMap.TraverseSurfaceNodesBreakOnCondition(
988         [&nodeId, &surfaceName](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) {
989         if (surfaceNode->GetName() == surfaceName && surfaceNode->IsOnTheTree() == true) {
990             nodeId = surfaceNode->GetId();
991             return true;
992         }
993         return false;
994     });
995     if (surfaceName.empty()) {
996         enable = "";
997         return ERR_INVALID_VALUE;
998     }
999     std::string dumpString;
1000     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1001     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1002 #ifdef RS_ENABLE_GPU
1003         RSHardwareThread::Instance().ScheduleTask(
1004             [weakThis = wptr<RSRenderServiceConnection>(this), &dumpString, &nodeId]() {
1005                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1006                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1007                     return;
1008                 }
1009                 RSSurfaceFpsManager::GetInstance().Dump(dumpString, nodeId);
1010             }).wait();
1011 #endif
1012     } else {
1013         mainThread_->ScheduleTask(
1014             [weakThis = wptr<RSRenderServiceConnection>(this), &dumpString, &nodeId]() {
1015                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1016                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1017                     return;
1018                 }
1019                 RSSurfaceFpsManager::GetInstance().Dump(dumpString, nodeId);
1020             }).wait();
1021     }
1022     enable = dumpString;
1023     return ERR_OK;
1024 }
1025 
GetCurrentRefreshRateMode()1026 int32_t RSRenderServiceConnection::GetCurrentRefreshRateMode()
1027 {
1028     return HgmTaskHandleThread::Instance().ScheduleTask([] () -> int32_t {
1029         return OHOS::Rosen::HgmCore::Instance().GetCurrentRefreshRateMode();
1030     }).get();
1031 }
1032 
SetPhysicalScreenResolution(ScreenId id,uint32_t width,uint32_t height)1033 int32_t RSRenderServiceConnection::SetPhysicalScreenResolution(ScreenId id, uint32_t width, uint32_t height)
1034 {
1035     if (!screenManager_) {
1036         return StatusCode::SCREEN_MANAGER_NULL;
1037     }
1038     return screenManager_->SetPhysicalScreenResolution(id, width, height);
1039 }
1040 
SetVirtualScreenResolution(ScreenId id,uint32_t width,uint32_t height)1041 int32_t RSRenderServiceConnection::SetVirtualScreenResolution(ScreenId id, uint32_t width, uint32_t height)
1042 {
1043     if (!screenManager_) {
1044         return StatusCode::SCREEN_NOT_FOUND;
1045     }
1046     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1047     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1048 #ifdef RS_ENABLE_GPU
1049         return RSHardwareThread::Instance().ScheduleTask(
1050             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
1051 #else
1052         return StatusCode::SCREEN_NOT_FOUND;
1053 #endif
1054     } else if (mainThread_ != nullptr) {
1055         return mainThread_->ScheduleTask(
1056             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
1057     } else {
1058         return StatusCode::SCREEN_NOT_FOUND;
1059     }
1060 }
1061 
MarkPowerOffNeedProcessOneFrame()1062 void RSRenderServiceConnection::MarkPowerOffNeedProcessOneFrame()
1063 {
1064     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1065     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1066 #ifdef RS_ENABLE_GPU
1067         renderThread_.PostTask(
1068             [weakThis = wptr<RSRenderServiceConnection>(this)]() {
1069                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1070                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1071                     return;
1072                 }
1073                 connection->screenManager_->MarkPowerOffNeedProcessOneFrame();
1074             }
1075         );
1076 #endif
1077     }
1078 }
1079 
RepaintEverything()1080 ErrCode RSRenderServiceConnection::RepaintEverything()
1081 {
1082     if (mainThread_ == nullptr) {
1083         RS_LOGE("RepaintEverything, mainThread_ is null, return");
1084         return ERR_INVALID_VALUE;
1085     }
1086     auto task = []() -> void {
1087         RS_LOGI("RepaintEverything, setDirtyflag, forceRefresh in mainThread");
1088         RSMainThread::Instance()->SetDirtyFlag();
1089         RSMainThread::Instance()->ForceRefreshForUni();
1090     };
1091     mainThread_->PostTask(task);
1092     return ERR_OK;
1093 }
1094 
ForceRefreshOneFrameWithNextVSync()1095 void RSRenderServiceConnection::ForceRefreshOneFrameWithNextVSync()
1096 {
1097     if (!mainThread_) {
1098         RS_LOGE("%{public}s mainThread_ is nullptr, return", __func__);
1099         return;
1100     }
1101 
1102     auto task = [weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
1103         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1104         if (connection == nullptr || connection->mainThread_ == nullptr) {
1105             return;
1106         }
1107 
1108         RS_LOGI("ForceRefreshOneFrameWithNextVSync, setDirtyflag, forceRefresh in mainThread");
1109         connection->mainThread_->SetDirtyFlag();
1110         connection->mainThread_->RequestNextVSync();
1111     };
1112     mainThread_->PostTask(task);
1113 }
1114 
DisablePowerOffRenderControl(ScreenId id)1115 void RSRenderServiceConnection::DisablePowerOffRenderControl(ScreenId id)
1116 {
1117     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1118     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1119 #ifdef RS_ENABLE_GPU
1120         renderThread_.PostTask(
1121             [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
1122                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1123                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1124                     return;
1125                 }
1126                 connection->screenManager_->DisablePowerOffRenderControl(id);
1127             }
1128         );
1129 #endif
1130     }
1131 }
1132 
SetScreenPowerStatus(ScreenId id,ScreenPowerStatus status)1133 void RSRenderServiceConnection::SetScreenPowerStatus(ScreenId id, ScreenPowerStatus status)
1134 {
1135     if (screenManager_ == nullptr || mainThread_ == nullptr) {
1136         RS_LOGE("%{public}s screenManager or mainThread is null, id: %{public}" PRIu64, __func__, id);
1137         return;
1138     }
1139     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1140     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1141 #ifdef RS_ENABLE_GPU
1142         RSHardwareThread::Instance().ScheduleTask([=]() {
1143             if (status == ScreenPowerStatus::POWER_STATUS_ON) {
1144                 HgmCore::Instance().SetScreenSwitchDssEnable(id, false);
1145             }
1146             screenManager_->SetScreenPowerStatus(id, status);
1147         }).wait();
1148         mainThread_->SetDiscardJankFrames(true);
1149         renderThread_.SetDiscardJankFrames(true);
1150         HgmTaskHandleThread::Instance().PostTask([id, status]() {
1151             OHOS::Rosen::HgmCore::Instance().NotifyScreenPowerStatus(id, status);
1152         });
1153 #endif
1154     } else {
1155         mainThread_->ScheduleTask(
1156             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
1157     }
1158 }
1159 
1160 namespace {
TakeSurfaceCaptureForUiParallel(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const Drawing::Rect & specifiedAreaRect)1161 void TakeSurfaceCaptureForUiParallel(
1162     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
1163     const Drawing::Rect& specifiedAreaRect)
1164 {
1165 #ifdef RS_ENABLE_GPU
1166     RS_LOGI("TakeSurfaceCaptureForUiParallel nodeId:[%{public}" PRIu64 "], issync:%{public}s", id,
1167         captureConfig.isSync ? "true" : "false");
1168     std::function<void()> captureTask = [id, callback, captureConfig, specifiedAreaRect]() {
1169         RSUiCaptureTaskParallel::Capture(id, callback, captureConfig, specifiedAreaRect);
1170     };
1171     auto& context = RSMainThread::Instance()->GetContext();
1172     if (captureConfig.isSync) {
1173         context.InsertUiCaptureCmdsExecutedFlag(id, false);
1174         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
1175         return;
1176     }
1177 
1178     auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
1179     if (!node) {
1180         RS_LOGE("RSRenderServiceConnection::TakeSurfaceCaptureForUiParallel node is nullptr");
1181         callback->OnSurfaceCapture(id, captureConfig, nullptr);
1182         return;
1183     }
1184 
1185     if (node->IsOnTheTree() && !node->IsDirty() && !node->IsSubTreeDirty()) {
1186         RSMainThread::Instance()->PostTask(captureTask);
1187     } else {
1188         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
1189     }
1190 #endif
1191 }
1192 
TakeSurfaceCaptureForUIWithUni(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)1193 void TakeSurfaceCaptureForUIWithUni(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
1194     const RSSurfaceCaptureConfig& captureConfig)
1195 {
1196 #ifdef RS_ENABLE_GPU
1197     std::function<void()> offscreenRenderTask = [id, callback, captureConfig]() -> void {
1198         RS_LOGD("RSRenderService::TakeSurfaceCaptureForUIWithUni callback->OnOffscreenRender"
1199             " nodeId:[%{public}" PRIu64 "]", id);
1200         ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCaptureForUIWithUni");
1201         std::shared_ptr<RSUniUICapture> rsUniUICapture = std::make_shared<RSUniUICapture>(id, captureConfig);
1202         std::shared_ptr<Media::PixelMap> pixelmap = rsUniUICapture->TakeLocalCapture();
1203         callback->OnSurfaceCapture(id, captureConfig, pixelmap.get());
1204         ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
1205     };
1206     if (!captureConfig.isSync) {
1207         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
1208     } else {
1209         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
1210         if (node == nullptr || !node->GetCommandExecuted()) {
1211             RSOffscreenRenderThread::Instance().InSertCaptureTask(id, offscreenRenderTask);
1212             return;
1213         }
1214         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
1215         node->SetCommandExecuted(false);
1216     }
1217 #endif
1218 }
1219 }
1220 
TakeSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const RSSurfaceCaptureBlurParam & blurParam,const Drawing::Rect & specifiedAreaRect,RSSurfaceCapturePermissions permissions)1221 void RSRenderServiceConnection::TakeSurfaceCapture(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
1222     const RSSurfaceCaptureConfig& captureConfig, const RSSurfaceCaptureBlurParam& blurParam,
1223     const Drawing::Rect& specifiedAreaRect, RSSurfaceCapturePermissions permissions)
1224 {
1225     if (!mainThread_) {
1226         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1227         return;
1228     }
1229     std::function<void()> captureTask = [id, callback, captureConfig, blurParam, specifiedAreaRect,
1230         screenCapturePermission = permissions.screenCapturePermission,
1231         isSystemCalling = permissions.isSystemCalling,
1232         selfCapture = permissions.selfCapture]() -> void {
1233         RS_TRACE_NAME_FMT("RSRenderServiceConnection::TakeSurfaceCapture captureTask nodeId:[%" PRIu64 "]", id);
1234         RS_LOGI("RSRenderServiceConnection::TakeSurfaceCapture captureTask begin nodeId:[%{public}" PRIu64 "]", id);
1235         if (captureConfig.captureType == SurfaceCaptureType::UICAPTURE) {
1236             // When the isSync flag in captureConfig is true, UI capture processes commands before capture.
1237             // When the isSync flag in captureConfig is false, UI capture will check null node independently.
1238             // Therefore, a null node is valid for UI capture.
1239             auto uiCaptureHasPermission = selfCapture || isSystemCalling;
1240             if (!uiCaptureHasPermission) {
1241                 RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture uicapture failed, nodeId:[%{public}" PRIu64
1242                         "], isSystemCalling: %{public}u, selfCapture: %{public}u",
1243                     id, isSystemCalling, selfCapture);
1244                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1245                 return;
1246             }
1247             if (RSUniRenderJudgement::IsUniRender()) {
1248                 TakeSurfaceCaptureForUiParallel(id, callback, captureConfig, specifiedAreaRect);
1249             } else {
1250                 TakeSurfaceCaptureForUIWithUni(id, callback, captureConfig);
1251             }
1252             return;
1253         }
1254         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1255         if (node == nullptr) {
1256             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node is nullptr");
1257             callback->OnSurfaceCapture(id, captureConfig, nullptr);
1258             return;
1259         }
1260         auto displayCaptureHasPermission = screenCapturePermission && isSystemCalling;
1261         auto surfaceCaptureHasPermission = blurParam.isNeedBlur ? isSystemCalling : (selfCapture || isSystemCalling);
1262         if ((node->GetType() == RSRenderNodeType::DISPLAY_NODE && !displayCaptureHasPermission) ||
1263             (node->GetType() == RSRenderNodeType::SURFACE_NODE && !surfaceCaptureHasPermission)) {
1264             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node type: %{public}u, "
1265                 "screenCapturePermission: %{public}u, isSystemCalling: %{public}u, selfCapture: %{public}u",
1266                 node->GetType(), screenCapturePermission, isSystemCalling, selfCapture);
1267             callback->OnSurfaceCapture(id, captureConfig, nullptr);
1268             return;
1269         }
1270         if (RSUniRenderJudgement::GetUniRenderEnabledType() == UniRenderEnabledType::UNI_RENDER_DISABLED) {
1271             RS_LOGD("RSRenderService::TakeSurfaceCapture captureTaskInner nodeId:[%{public}" PRIu64 "]", id);
1272             ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCapture");
1273             RSSurfaceCaptureTask task(id, captureConfig);
1274             if (!task.Run(callback)) {
1275                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1276             }
1277             ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
1278         } else {
1279 #ifdef RS_ENABLE_GPU
1280             RSSurfaceCaptureParam captureParam;
1281             captureParam.id = id;
1282             captureParam.config = captureConfig;
1283             captureParam.isSystemCalling = isSystemCalling;
1284             captureParam.blurParam = blurParam;
1285             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1286             RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1287 #endif
1288         }
1289     };
1290     mainThread_->PostTask(captureTask);
1291 }
1292 
TakeSelfSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)1293 void RSRenderServiceConnection::TakeSelfSurfaceCapture(
1294     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
1295 {
1296     if (!mainThread_) {
1297         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1298         return;
1299     }
1300     std::function<void()> selfCaptureTask = [id, callback, captureConfig]() -> void {
1301         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1302         if (node == nullptr) {
1303             RS_LOGE("RSRenderServiceConnection::TakeSelfSurfaceCapture failed, node is nullptr");
1304             if (callback) {
1305                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1306             }
1307             return;
1308         }
1309         bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1310             RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ +
1311             "::TAKE_SELF_SURFACE_CAPTURE");
1312         RSSurfaceCaptureParam captureParam;
1313         captureParam.id = id;
1314         captureParam.config = captureConfig;
1315         captureParam.isSystemCalling = isSystemCalling;
1316         captureParam.isSelfCapture = true;
1317         RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1318         RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1319     };
1320     mainThread_->PostTask(selfCaptureTask);
1321 }
1322 
SetWindowFreezeImmediately(NodeId id,bool isFreeze,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const RSSurfaceCaptureBlurParam & blurParam)1323 ErrCode RSRenderServiceConnection::SetWindowFreezeImmediately(NodeId id, bool isFreeze,
1324     sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
1325     const RSSurfaceCaptureBlurParam& blurParam)
1326 {
1327     if (!mainThread_) {
1328         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1329         return ERR_INVALID_VALUE;
1330     }
1331     std::function<void()> setWindowFreezeTask = [id, isFreeze, callback, captureConfig, blurParam]() -> void {
1332         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1333         if (node == nullptr) {
1334             RS_LOGE("RSRenderServiceConnection::SetWindowFreezeImmediately failed, node is nullptr");
1335             if (callback) {
1336                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1337             }
1338             return;
1339         }
1340         node->SetStaticCached(isFreeze);
1341         if (isFreeze) {
1342             bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1343                 RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ +
1344                 "::SET_WINDOW_FREEZE_IMMEDIATELY");
1345             RSSurfaceCaptureParam captureParam;
1346             captureParam.id = id;
1347             captureParam.config = captureConfig;
1348             captureParam.isSystemCalling = isSystemCalling;
1349             captureParam.isFreeze = isFreeze;
1350             captureParam.blurParam = blurParam;
1351             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1352             RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1353         } else {
1354             RSSurfaceCaptureTaskParallel::ClearCacheImageByFreeze(id);
1355         }
1356     };
1357     mainThread_->PostTask(setWindowFreezeTask);
1358     return ERR_OK;
1359 }
1360 
SetHwcNodeBounds(int64_t rsNodeId,float positionX,float positionY,float positionZ,float positionW)1361 void RSRenderServiceConnection::SetHwcNodeBounds(int64_t rsNodeId, float positionX, float positionY,
1362     float positionZ, float positionW)
1363 {
1364     if (mainThread_ == nullptr || screenManager_ == nullptr) {
1365         return;
1366     }
1367 
1368     // adapt video scene pointer
1369     if (screenManager_->GetCurrentVirtualScreenNum() > 0 ||
1370         !RSPointerWindowManager::Instance().GetIsPointerEnableHwc()) {
1371         // when has virtual screen or pointer is enable hwc, we can't skip
1372         RSPointerWindowManager::Instance().SetIsPointerCanSkipFrame(false);
1373         RSMainThread::Instance()->RequestNextVSync();
1374     } else {
1375         RSPointerWindowManager::Instance().SetIsPointerCanSkipFrame(true);
1376     }
1377 
1378     RSPointerWindowManager::Instance().SetHwcNodeBounds(rsNodeId, positionX, positionY,
1379         positionZ, positionW);
1380 }
1381 
RegisterApplicationAgent(uint32_t pid,sptr<IApplicationAgent> app)1382 ErrCode RSRenderServiceConnection::RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app)
1383 {
1384     if (!mainThread_) {
1385         RS_LOGE("RSRenderServiceConnection::RegisterApplicationAgent mainThread_ is nullptr");
1386         return ERR_INVALID_VALUE;
1387     }
1388     auto captureTask = [weakThis = wptr<RSRenderServiceConnection>(this), pid, app]() -> void {
1389         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1390         if (connection == nullptr || connection->mainThread_ == nullptr) {
1391             RS_LOGE("RSRenderServiceConnection::RegisterApplicationAgent connection or mainThread_ is nullptr");
1392             return;
1393         }
1394         connection->mainThread_->RegisterApplicationAgent(pid, app);
1395     };
1396     mainThread_->PostTask(captureTask);
1397 
1398     app->AsObject()->AddDeathRecipient(applicationDeathRecipient_);
1399     return ERR_OK;
1400 }
1401 
UnRegisterApplicationAgent(sptr<IApplicationAgent> app)1402 void RSRenderServiceConnection::UnRegisterApplicationAgent(sptr<IApplicationAgent> app)
1403 {
1404     auto captureTask = [=]() -> void {
1405         RSMainThread::Instance()->UnRegisterApplicationAgent(app);
1406     };
1407     RSMainThread::Instance()->ScheduleTask(captureTask).wait();
1408 }
1409 
GetVirtualScreenResolution(ScreenId id)1410 RSVirtualScreenResolution RSRenderServiceConnection::GetVirtualScreenResolution(ScreenId id)
1411 {
1412     RSVirtualScreenResolution virtualScreenResolution;
1413     if (!screenManager_) {
1414         return virtualScreenResolution;
1415     }
1416     screenManager_->GetVirtualScreenResolution(id, virtualScreenResolution);
1417     return virtualScreenResolution;
1418 }
1419 
GetScreenActiveMode(ScreenId id)1420 RSScreenModeInfo RSRenderServiceConnection::GetScreenActiveMode(ScreenId id)
1421 {
1422     RSScreenModeInfo screenModeInfo;
1423     if (!screenManager_) {
1424         return screenModeInfo;
1425     }
1426     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1427     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1428 #ifdef RS_ENABLE_GPU
1429         RSHardwareThread::Instance().ScheduleTask(
1430             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1431 #else
1432         return screenModeInfo;
1433 #endif
1434     } else if (mainThread_ != nullptr) {
1435         mainThread_->ScheduleTask(
1436             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1437     }
1438     return screenModeInfo;
1439 }
1440 
GetTotalAppMemSize(float & cpuMemSize,float & gpuMemSize,bool & success)1441 ErrCode RSRenderServiceConnection::GetTotalAppMemSize(float& cpuMemSize, float& gpuMemSize, bool& success)
1442 {
1443 #ifdef RS_ENABLE_GPU
1444     RSMainThread::Instance()->GetAppMemoryInMB(cpuMemSize, gpuMemSize);
1445     gpuMemSize += RSSubThreadManager::Instance()->GetAppGpuMemoryInMB();
1446 #endif
1447     success = true;
1448     return ERR_OK;
1449 }
1450 
GetMemoryGraphic(int pid,MemoryGraphic & memoryGraphic)1451 ErrCode RSRenderServiceConnection::GetMemoryGraphic(int pid, MemoryGraphic& memoryGraphic)
1452 {
1453     if (!mainThread_) {
1454         return ERR_INVALID_VALUE;
1455     }
1456     bool enable;
1457     if (GetUniRenderEnabled(enable) == ERR_OK && enable) {
1458         RSMainThread* mainThread = mainThread_;
1459         mainThread_->ScheduleTask([mainThread, &pid, &memoryGraphic]() {
1460             if (RSMainThread::Instance()->GetContext().GetNodeMap().ContainPid(pid)) {
1461                 mainThread->CountMem(pid, memoryGraphic);
1462             }
1463         }).wait();
1464         return ERR_OK;
1465     } else {
1466         return ERR_INVALID_VALUE;
1467     }
1468 }
1469 
GetMemoryGraphics(std::vector<MemoryGraphic> & memoryGraphics)1470 ErrCode RSRenderServiceConnection::GetMemoryGraphics(std::vector<MemoryGraphic>& memoryGraphics)
1471 {
1472     bool res;
1473     if (!mainThread_ || GetUniRenderEnabled(res) != ERR_OK || !res) {
1474         return ERR_INVALID_VALUE;
1475     }
1476     mainThread_->ScheduleTask(
1477         [weakThis = wptr<RSRenderServiceConnection>(this), &memoryGraphics]() {
1478             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1479             if (connection == nullptr || connection->mainThread_ == nullptr) {
1480                 return;
1481             }
1482             return connection->mainThread_->CountMem(memoryGraphics);
1483         }).wait();
1484     return ERR_OK;
1485 }
1486 
GetScreenSupportedModes(ScreenId id)1487 std::vector<RSScreenModeInfo> RSRenderServiceConnection::GetScreenSupportedModes(ScreenId id)
1488 {
1489     if (!screenManager_) {
1490         return std::vector<RSScreenModeInfo>();
1491     }
1492     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1493     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1494 #ifdef RS_ENABLE_GPU
1495         return RSHardwareThread::Instance().ScheduleTask(
1496             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1497 #else
1498         return std::vector<RSScreenModeInfo>();
1499 #endif
1500     } else if (mainThread_ != nullptr) {
1501         return mainThread_->ScheduleTask(
1502             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1503     } else {
1504         return std::vector<RSScreenModeInfo>();
1505     }
1506 }
1507 
GetScreenCapability(ScreenId id)1508 RSScreenCapability RSRenderServiceConnection::GetScreenCapability(ScreenId id)
1509 {
1510     RSScreenCapability screenCapability;
1511     if (!screenManager_) {
1512         return screenCapability;
1513     }
1514     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1515     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1516 #ifdef RS_ENABLE_GPU
1517         return RSHardwareThread::Instance().ScheduleTask(
1518             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1519 #else
1520         return screenCapability;
1521 #endif
1522     } else if (mainThread_ != nullptr) {
1523         return mainThread_->ScheduleTask(
1524             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1525     } else {
1526         return screenCapability;
1527     }
1528 }
1529 
GetScreenPowerStatus(ScreenId id)1530 ScreenPowerStatus RSRenderServiceConnection::GetScreenPowerStatus(ScreenId id)
1531 {
1532     if (!screenManager_) {
1533         return ScreenPowerStatus::INVALID_POWER_STATUS;
1534     }
1535     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1536     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1537 #ifdef RS_ENABLE_GPU
1538         return RSHardwareThread::Instance().ScheduleTask(
1539             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1540 #else
1541         return ScreenPowerStatus::INVALID_POWER_STATUS;
1542 #endif
1543     } else if (mainThread_ != nullptr) {
1544         return mainThread_->ScheduleTask(
1545             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1546     } else {
1547         return ScreenPowerStatus::INVALID_POWER_STATUS;
1548     }
1549 }
1550 
GetScreenData(ScreenId id)1551 RSScreenData RSRenderServiceConnection::GetScreenData(ScreenId id)
1552 {
1553     RSScreenData screenData;
1554     if (!screenManager_) {
1555         return screenData;
1556     }
1557     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1558     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1559 #ifdef RS_ENABLE_GPU
1560         return RSHardwareThread::Instance().ScheduleTask(
1561             [=]() { return screenManager_->GetScreenData(id); }).get();
1562 #else
1563         return screenData;
1564 #endif
1565     } else if (mainThread_ != nullptr) {
1566         return mainThread_->ScheduleTask(
1567             [=]() { return screenManager_->GetScreenData(id); }).get();
1568     } else {
1569         return screenData;
1570     }
1571 }
1572 
GetScreenBacklight(ScreenId id)1573 int32_t RSRenderServiceConnection::GetScreenBacklight(ScreenId id)
1574 {
1575     if (!screenManager_) {
1576         return INVALID_BACKLIGHT_VALUE;
1577     }
1578     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1579     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1580 #ifdef RS_ENABLE_GPU
1581         return RSHardwareThread::Instance().ScheduleTask(
1582             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1583 #else
1584         return INVALID_BACKLIGHT_VALUE;
1585 #endif
1586     } else if (mainThread_ != nullptr) {
1587         return mainThread_->ScheduleTask(
1588             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1589     } else {
1590         return INVALID_BACKLIGHT_VALUE;
1591     }
1592 }
1593 
SetScreenBacklight(ScreenId id,uint32_t level)1594 void RSRenderServiceConnection::SetScreenBacklight(ScreenId id, uint32_t level)
1595 {
1596     if (!screenManager_) {
1597         return;
1598     }
1599     RSLuminanceControl::Get().SetSdrLuminance(id, level);
1600     if (RSLuminanceControl::Get().IsHdrOn(id) && level > 0 && mainThread_ != nullptr) {
1601         auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
1602             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1603             if (connection == nullptr || connection->mainThread_ == nullptr) {
1604                 RS_LOGE("RSRenderServiceConnection::SetScreenBacklight fail");
1605                 return;
1606             }
1607             connection->mainThread_->SetLuminanceChangingStatus(id, true);
1608             connection->mainThread_->SetDirtyFlag();
1609             connection->mainThread_->RequestNextVSync();
1610         };
1611         mainThread_->PostTask(task);
1612         return;
1613     }
1614 
1615     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1616     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1617 #ifdef RS_ENABLE_GPU
1618         screenManager_->SetScreenBacklight(id, level);
1619 #endif
1620     } else if (mainThread_ != nullptr) {
1621         mainThread_->ScheduleTask(
1622             [=]() { screenManager_->SetScreenBacklight(id, level); }).wait();
1623     }
1624 }
1625 
RegisterBufferClearListener(NodeId id,sptr<RSIBufferClearCallback> callback)1626 ErrCode RSRenderServiceConnection::RegisterBufferClearListener(
1627     NodeId id, sptr<RSIBufferClearCallback> callback)
1628 {
1629     if (!mainThread_) {
1630         return ERR_INVALID_VALUE;
1631     }
1632     auto registerBufferClearListener =
1633         [id, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1634             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1635             if (connection == nullptr || connection->mainThread_ == nullptr) {
1636                 return false;
1637             }
1638             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1639                 node->RegisterBufferClearListener(callback);
1640                 return true;
1641             }
1642             return false;
1643     };
1644     mainThread_->PostTask(registerBufferClearListener);
1645     return ERR_OK;
1646 }
1647 
RegisterBufferAvailableListener(NodeId id,sptr<RSIBufferAvailableCallback> callback,bool isFromRenderThread)1648 ErrCode RSRenderServiceConnection::RegisterBufferAvailableListener(
1649     NodeId id, sptr<RSIBufferAvailableCallback> callback, bool isFromRenderThread)
1650 {
1651     if (!mainThread_) {
1652         return ERR_INVALID_VALUE;
1653     }
1654     auto registerBufferAvailableListener =
1655         [id, callback, isFromRenderThread, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1656             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1657             if (connection == nullptr || connection->mainThread_ == nullptr) {
1658                 return false;
1659             }
1660             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1661                 node->RegisterBufferAvailableListener(callback, isFromRenderThread);
1662                 return true;
1663             }
1664             return false;
1665     };
1666     mainThread_->PostTask(registerBufferAvailableListener);
1667     return ERR_OK;
1668 }
1669 
GetScreenSupportedColorGamuts(ScreenId id,std::vector<ScreenColorGamut> & mode)1670 int32_t RSRenderServiceConnection::GetScreenSupportedColorGamuts(ScreenId id, std::vector<ScreenColorGamut>& mode)
1671 {
1672     if (!screenManager_) {
1673         return StatusCode::SCREEN_NOT_FOUND;
1674     }
1675     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1676     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1677 #ifdef RS_ENABLE_GPU
1678         return RSHardwareThread::Instance().ScheduleTask(
1679             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1680 #else
1681         return StatusCode::SCREEN_NOT_FOUND;
1682 #endif
1683     } else if (mainThread_ != nullptr) {
1684         return mainThread_->ScheduleTask(
1685             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1686     } else {
1687         return StatusCode::SCREEN_NOT_FOUND;
1688     }
1689 }
1690 
GetScreenSupportedMetaDataKeys(ScreenId id,std::vector<ScreenHDRMetadataKey> & keys)1691 int32_t RSRenderServiceConnection::GetScreenSupportedMetaDataKeys(ScreenId id, std::vector<ScreenHDRMetadataKey>& keys)
1692 {
1693     if (!screenManager_) {
1694         return StatusCode::SCREEN_NOT_FOUND;
1695     }
1696     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1697     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1698 #ifdef RS_ENABLE_GPU
1699         return RSHardwareThread::Instance().ScheduleTask(
1700             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1701 #else
1702         return StatusCode::SCREEN_NOT_FOUND;
1703 #endif
1704     } else if (mainThread_ != nullptr) {
1705         return mainThread_->ScheduleTask(
1706             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1707     } else {
1708         return StatusCode::SCREEN_NOT_FOUND;
1709     }
1710 }
1711 
GetScreenColorGamut(ScreenId id,ScreenColorGamut & mode)1712 int32_t RSRenderServiceConnection::GetScreenColorGamut(ScreenId id, ScreenColorGamut& mode)
1713 {
1714     if (!screenManager_) {
1715         return StatusCode::SCREEN_NOT_FOUND;
1716     }
1717     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1718     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1719 #ifdef RS_ENABLE_GPU
1720         return RSHardwareThread::Instance().ScheduleTask(
1721             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1722 #else
1723         return StatusCode::SCREEN_NOT_FOUND;
1724 #endif
1725     } else if (mainThread_ != nullptr) {
1726         return mainThread_->ScheduleTask(
1727             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1728     } else {
1729         return StatusCode::SCREEN_NOT_FOUND;
1730     }
1731 }
1732 
SetScreenColorGamut(ScreenId id,int32_t modeIdx)1733 int32_t RSRenderServiceConnection::SetScreenColorGamut(ScreenId id, int32_t modeIdx)
1734 {
1735     if (!screenManager_) {
1736         return StatusCode::SCREEN_NOT_FOUND;
1737     }
1738     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1739     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1740 #ifdef RS_ENABLE_GPU
1741         return RSHardwareThread::Instance().ScheduleTask(
1742             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1743 #else
1744         return StatusCode::SCREEN_NOT_FOUND;
1745 #endif
1746     } else if (mainThread_ != nullptr) {
1747         return mainThread_->ScheduleTask(
1748             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1749     } else {
1750         return StatusCode::SCREEN_NOT_FOUND;
1751     }
1752 }
1753 
SetScreenGamutMap(ScreenId id,ScreenGamutMap mode)1754 int32_t RSRenderServiceConnection::SetScreenGamutMap(ScreenId id, ScreenGamutMap mode)
1755 {
1756     if (!screenManager_) {
1757         return StatusCode::SCREEN_NOT_FOUND;
1758     }
1759     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1760     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1761 #ifdef RS_ENABLE_GPU
1762         return RSHardwareThread::Instance().ScheduleTask(
1763             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1764 #else
1765         return StatusCode::SCREEN_NOT_FOUND;
1766 #endif
1767     } else if (mainThread_ != nullptr) {
1768         return mainThread_->ScheduleTask(
1769             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1770     } else {
1771         return StatusCode::SCREEN_NOT_FOUND;
1772     }
1773 }
1774 
SetScreenCorrection(ScreenId id,ScreenRotation screenRotation)1775 int32_t RSRenderServiceConnection::SetScreenCorrection(ScreenId id, ScreenRotation screenRotation)
1776 {
1777     std::lock_guard<std::mutex> lock(mutex_);
1778     if (!screenManager_) {
1779         return StatusCode::SCREEN_NOT_FOUND;
1780     }
1781     return screenManager_->SetScreenCorrection(id, screenRotation);
1782 }
1783 
SetVirtualMirrorScreenCanvasRotation(ScreenId id,bool canvasRotation)1784 bool RSRenderServiceConnection::SetVirtualMirrorScreenCanvasRotation(ScreenId id, bool canvasRotation)
1785 {
1786     std::lock_guard<std::mutex> lock(mutex_);
1787     if (!screenManager_) {
1788         return false;
1789     }
1790     return screenManager_->SetVirtualMirrorScreenCanvasRotation(id, canvasRotation);
1791 }
1792 
SetGlobalDarkColorMode(bool isDark)1793 bool RSRenderServiceConnection::SetGlobalDarkColorMode(bool isDark)
1794 {
1795     std::lock_guard<std::mutex> lock(mutex_);
1796     if (!mainThread_) {
1797         return false;
1798     }
1799     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isDark]() {
1800         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1801         if (connection == nullptr || connection->mainThread_ == nullptr) {
1802             RS_LOGE("RSRenderServiceConnection::SetGlobalDarkColorMode fail");
1803             return;
1804         }
1805         connection->mainThread_->SetGlobalDarkColorMode(isDark);
1806     };
1807     mainThread_->PostTask(task);
1808     return true;
1809 }
1810 
SetVirtualMirrorScreenScaleMode(ScreenId id,ScreenScaleMode scaleMode)1811 bool RSRenderServiceConnection::SetVirtualMirrorScreenScaleMode(ScreenId id, ScreenScaleMode scaleMode)
1812 {
1813     std::lock_guard<std::mutex> lock(mutex_);
1814     if (!screenManager_) {
1815         return false;
1816     }
1817     return screenManager_->SetVirtualMirrorScreenScaleMode(id, scaleMode);
1818 }
1819 
GetScreenGamutMap(ScreenId id,ScreenGamutMap & mode)1820 int32_t RSRenderServiceConnection::GetScreenGamutMap(ScreenId id, ScreenGamutMap& mode)
1821 {
1822     if (!screenManager_) {
1823         return StatusCode::SCREEN_NOT_FOUND;
1824     }
1825     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1826     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1827 #ifdef RS_ENABLE_GPU
1828         return RSHardwareThread::Instance().ScheduleTask(
1829             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1830 #else
1831         return StatusCode::SCREEN_NOT_FOUND;
1832 #endif
1833     } else if (mainThread_ != nullptr) {
1834         return mainThread_->ScheduleTask(
1835             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1836     } else {
1837         return StatusCode::SCREEN_NOT_FOUND;
1838     }
1839 }
1840 
GetScreenHDRCapability(ScreenId id,RSScreenHDRCapability & screenHdrCapability)1841 int32_t RSRenderServiceConnection::GetScreenHDRCapability(ScreenId id, RSScreenHDRCapability& screenHdrCapability)
1842 {
1843     std::lock_guard<std::mutex> lock(mutex_);
1844     if (!screenManager_) {
1845         return StatusCode::SCREEN_NOT_FOUND;
1846     }
1847     return screenManager_->GetScreenHDRCapability(id, screenHdrCapability);
1848 }
1849 
GetPixelFormat(ScreenId id,GraphicPixelFormat & pixelFormat,int32_t & resCode)1850 ErrCode RSRenderServiceConnection::GetPixelFormat(ScreenId id, GraphicPixelFormat& pixelFormat, int32_t& resCode)
1851 {
1852     if (!screenManager_) {
1853         resCode = StatusCode::SCREEN_NOT_FOUND;
1854         return ERR_INVALID_VALUE;
1855     }
1856     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1857     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1858 #ifdef RS_ENABLE_GPU
1859         resCode = RSHardwareThread::Instance().ScheduleTask(
1860             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1861         return ERR_OK;
1862 #else
1863         resCode = StatusCode::SCREEN_NOT_FOUND;
1864         return ERR_INVALID_VALUE;
1865 #endif
1866     } else if (mainThread_ != nullptr) {
1867         resCode = mainThread_->ScheduleTask(
1868             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1869         return ERR_OK;
1870     } else {
1871         resCode = StatusCode::SCREEN_NOT_FOUND;
1872         return ERR_INVALID_VALUE;
1873     }
1874 }
1875 
SetPixelFormat(ScreenId id,GraphicPixelFormat pixelFormat,int32_t & resCode)1876 ErrCode RSRenderServiceConnection::SetPixelFormat(ScreenId id, GraphicPixelFormat pixelFormat, int32_t& resCode)
1877 {
1878     if (!screenManager_) {
1879         resCode = StatusCode::SCREEN_NOT_FOUND;
1880         return ERR_INVALID_VALUE;
1881     }
1882     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1883     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1884 #ifdef RS_ENABLE_GPU
1885         resCode = RSHardwareThread::Instance().ScheduleTask(
1886             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1887         return ERR_OK;
1888 #else
1889         resCode = StatusCode::SCREEN_NOT_FOUND;
1890         return ERR_INVALID_VALUE;
1891 #endif
1892     } else if (mainThread_ != nullptr) {
1893         resCode = mainThread_->ScheduleTask(
1894             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1895         return ERR_OK;
1896     } else {
1897         resCode = StatusCode::SCREEN_NOT_FOUND;
1898         return ERR_INVALID_VALUE;
1899     }
1900 }
1901 
GetScreenSupportedHDRFormats(ScreenId id,std::vector<ScreenHDRFormat> & hdrFormats,int32_t & resCode)1902 ErrCode RSRenderServiceConnection::GetScreenSupportedHDRFormats(
1903     ScreenId id, std::vector<ScreenHDRFormat>& hdrFormats, int32_t& resCode)
1904 {
1905     if (!screenManager_) {
1906         resCode = StatusCode::SCREEN_NOT_FOUND;
1907         return ERR_INVALID_VALUE;
1908     }
1909     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1910     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1911 #ifdef RS_ENABLE_GPU
1912         resCode = RSHardwareThread::Instance().ScheduleTask(
1913             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1914         return ERR_OK;
1915 #else
1916         resCode = StatusCode::SCREEN_NOT_FOUND;
1917         return ERR_INVALID_VALUE;
1918 #endif
1919     } else if (mainThread_ != nullptr) {
1920         resCode = mainThread_->ScheduleTask(
1921             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1922         return ERR_OK;
1923     } else {
1924         resCode = StatusCode::SCREEN_NOT_FOUND;
1925         return ERR_INVALID_VALUE;
1926     }
1927 }
1928 
GetScreenHDRFormat(ScreenId id,ScreenHDRFormat & hdrFormat,int32_t & resCode)1929 ErrCode RSRenderServiceConnection::GetScreenHDRFormat(ScreenId id, ScreenHDRFormat& hdrFormat, int32_t& resCode)
1930 {
1931     if (!screenManager_) {
1932         resCode = StatusCode::SCREEN_NOT_FOUND;
1933         return ERR_INVALID_VALUE;
1934     }
1935     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1936     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1937 #ifdef RS_ENABLE_GPU
1938         resCode = RSHardwareThread::Instance().ScheduleTask(
1939             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1940         return ERR_OK;
1941 #else
1942         resCode = StatusCode::SCREEN_NOT_FOUND;
1943         return ERR_INVALID_VALUE;
1944 #endif
1945     } else if (mainThread_ != nullptr) {
1946         resCode = mainThread_->ScheduleTask(
1947             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1948         return ERR_OK;
1949     } else {
1950         resCode = StatusCode::SCREEN_NOT_FOUND;
1951         return ERR_INVALID_VALUE;
1952     }
1953 }
1954 
SetScreenHDRFormat(ScreenId id,int32_t modeIdx,int32_t & resCode)1955 ErrCode RSRenderServiceConnection::SetScreenHDRFormat(ScreenId id, int32_t modeIdx, int32_t& resCode)
1956 {
1957     if (!screenManager_) {
1958         resCode = StatusCode::SCREEN_NOT_FOUND;
1959         return ERR_INVALID_VALUE;
1960     }
1961     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1962     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1963 #ifdef RS_ENABLE_GPU
1964         resCode = RSHardwareThread::Instance().ScheduleTask(
1965             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1966         return ERR_OK;
1967 #else
1968         resCode = StatusCode::SCREEN_NOT_FOUND;
1969         return ERR_INVALID_VALUE;
1970 #endif
1971     } else if (mainThread_ != nullptr) {
1972         resCode = mainThread_->ScheduleTask(
1973             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1974         return ERR_OK;
1975     } else {
1976         resCode = StatusCode::SCREEN_NOT_FOUND;
1977         return ERR_INVALID_VALUE;
1978     }
1979 }
1980 
GetScreenSupportedColorSpaces(ScreenId id,std::vector<GraphicCM_ColorSpaceType> & colorSpaces,int32_t & resCode)1981 ErrCode RSRenderServiceConnection::GetScreenSupportedColorSpaces(
1982     ScreenId id, std::vector<GraphicCM_ColorSpaceType>& colorSpaces, int32_t& resCode)
1983 {
1984     if (!screenManager_) {
1985         resCode = StatusCode::SCREEN_NOT_FOUND;
1986         return ERR_INVALID_VALUE;
1987     }
1988     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1989     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1990 #ifdef RS_ENABLE_GPU
1991         resCode = RSHardwareThread::Instance().ScheduleTask(
1992             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
1993         return ERR_OK;
1994 #else
1995         resCode = StatusCode::SCREEN_NOT_FOUND;
1996         return ERR_INVALID_VALUE;
1997 #endif
1998     } else if (mainThread_ != nullptr) {
1999         resCode = mainThread_->ScheduleTask(
2000             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
2001         return ERR_OK;
2002     } else {
2003         resCode = StatusCode::SCREEN_NOT_FOUND;
2004         return ERR_INVALID_VALUE;
2005     }
2006 }
2007 
GetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType & colorSpace,int32_t & resCode)2008 ErrCode RSRenderServiceConnection::GetScreenColorSpace(
2009     ScreenId id, GraphicCM_ColorSpaceType& colorSpace, int32_t& resCode)
2010 {
2011     if (!screenManager_) {
2012         resCode = StatusCode::SCREEN_NOT_FOUND;
2013         return ERR_INVALID_VALUE;
2014     }
2015     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2016     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2017 #ifdef RS_ENABLE_GPU
2018         resCode = RSHardwareThread::Instance().ScheduleTask(
2019             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
2020         return ERR_OK;
2021 #else
2022         resCode = StatusCode::SCREEN_NOT_FOUND;
2023         return ERR_INVALID_VALUE;
2024 #endif
2025     } else if (mainThread_ != nullptr) {
2026         resCode = mainThread_->ScheduleTask(
2027             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
2028         return ERR_OK;
2029     } else {
2030         resCode = StatusCode::SCREEN_NOT_FOUND;
2031         return ERR_INVALID_VALUE;
2032     }
2033 }
2034 
SetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType colorSpace,int32_t & resCode)2035 ErrCode RSRenderServiceConnection::SetScreenColorSpace(
2036     ScreenId id, GraphicCM_ColorSpaceType colorSpace, int32_t& resCode)
2037 {
2038     if (!screenManager_) {
2039         resCode = StatusCode::SCREEN_NOT_FOUND;
2040         return ERR_INVALID_VALUE;
2041     }
2042     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2043     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2044 #ifdef RS_ENABLE_GPU
2045         resCode = RSHardwareThread::Instance().ScheduleTask(
2046             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
2047         return ERR_OK;
2048 #else
2049         resCode = StatusCode::SCREEN_NOT_FOUND;
2050         return ERR_INVALID_VALUE;
2051 #endif
2052     } else if (mainThread_ != nullptr) {
2053         resCode = mainThread_->ScheduleTask(
2054             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
2055         return ERR_OK;
2056     } else {
2057         resCode = StatusCode::SCREEN_NOT_FOUND;
2058         return ERR_INVALID_VALUE;
2059     }
2060 }
2061 
GetScreenType(ScreenId id,RSScreenType & screenType)2062 int32_t RSRenderServiceConnection::GetScreenType(ScreenId id, RSScreenType& screenType)
2063 {
2064     std::lock_guard<std::mutex> lock(mutex_);
2065     if (!screenManager_) {
2066         return StatusCode::SCREEN_NOT_FOUND;
2067     }
2068     return screenManager_->GetScreenType(id, screenType);
2069 }
2070 
GetBitmap(NodeId id,Drawing::Bitmap & bitmap,bool & success)2071 ErrCode RSRenderServiceConnection::GetBitmap(NodeId id, Drawing::Bitmap& bitmap, bool& success)
2072 {
2073     if (!mainThread_) {
2074         success = false;
2075         return ERR_INVALID_VALUE;
2076     }
2077     std::promise<bool> result;
2078     std::future<bool> future = result.get_future();
2079     RSMainThread* mainThread = mainThread_;
2080 #ifdef RS_ENABLE_GPU
2081     RSUniRenderThread* renderThread = &renderThread_;
2082     auto getBitmapTask = [id, &bitmap, mainThread, renderThread, &result]() {
2083         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
2084         if (node == nullptr) {
2085             RS_LOGE("RSRenderServiceConnection::GetBitmap cannot find NodeId: [%{public}" PRIu64 "]", id);
2086             result.set_value(false);
2087             return;
2088         }
2089         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
2090             RS_LOGE("RSRenderServiceConnection::GetBitmap RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
2091             result.set_value(false);
2092             return;
2093         }
2094         auto grContext = renderThread->GetRenderEngine()->GetRenderContext()->GetDrGPUContext();
2095         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
2096         auto getDrawableBitmapTask = [drawableNode, &bitmap, grContext, &result]() {
2097             bitmap = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)
2098                 ->GetBitmap(grContext);
2099             result.set_value(!bitmap.IsEmpty());
2100         };
2101         renderThread->PostTask(getDrawableBitmapTask);
2102     };
2103     mainThread_->PostTask(getBitmapTask);
2104 #endif
2105     success = future.get();
2106     return ERR_OK;
2107 }
2108 
GetPixelmap(NodeId id,const std::shared_ptr<Media::PixelMap> pixelmap,const Drawing::Rect * rect,std::shared_ptr<Drawing::DrawCmdList> drawCmdList,bool & success)2109 ErrCode RSRenderServiceConnection::GetPixelmap(NodeId id, const std::shared_ptr<Media::PixelMap> pixelmap,
2110     const Drawing::Rect* rect, std::shared_ptr<Drawing::DrawCmdList> drawCmdList, bool& success)
2111 {
2112     if (!mainThread_) {
2113         success = false;
2114         return ERR_INVALID_VALUE;
2115     }
2116     std::promise<bool> result;
2117     std::future<bool> future = result.get_future();
2118 #ifdef RS_ENABLE_GPU
2119     RSMainThread* mainThread = mainThread_;
2120     RSUniRenderThread* renderThread = &renderThread_;
2121     auto getPixelMapTask = [id, pixelmap, rect, drawCmdList, mainThread, renderThread, &result]() {
2122         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
2123         if (node == nullptr) {
2124             RS_LOGD("RSRenderServiceConnection::GetPixelmap: cannot find NodeId: [%{public}" PRIu64 "]", id);
2125             result.set_value(false);
2126             return;
2127         }
2128         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
2129             RS_LOGE("RSRenderServiceConnection::GetPixelmap: RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
2130             result.set_value(false);
2131             return;
2132         }
2133 
2134         auto tid = node->GetTid(); // planning: id may change in subthread
2135         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
2136         if (drawableNode) {
2137             tid = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->GetTid();
2138         }
2139         auto getDrawablePixelmapTask = [drawableNode, pixelmap, rect, &result, tid, drawCmdList]() {
2140             result.set_value(std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->
2141                 GetPixelmap(pixelmap, rect, tid, drawCmdList));
2142         };
2143         if (!node->IsOnTheTree()) {
2144             node->ClearOp();
2145         }
2146         if (tid == UNI_MAIN_THREAD_INDEX) {
2147             if (!mainThread->IsIdle() && mainThread->GetContext().HasActiveNode(node)) {
2148                 result.set_value(false);
2149                 return;
2150             }
2151             result.set_value(node->GetPixelmap(pixelmap, rect, tid, drawCmdList));
2152         } else if (tid == UNI_RENDER_THREAD_INDEX) {
2153             renderThread->PostTask(getDrawablePixelmapTask);
2154         } else {
2155             RSTaskDispatcher::GetInstance().PostTask(
2156                 RSSubThreadManager::Instance()->GetReThreadIndexMap()[tid], getDrawablePixelmapTask, false);
2157         }
2158     };
2159     mainThread_->PostTask(getPixelMapTask);
2160 #endif
2161     success = future.get();
2162     return ERR_OK;
2163 }
2164 
RegisterTypeface(uint64_t globalUniqueId,std::shared_ptr<Drawing::Typeface> & typeface)2165 bool RSRenderServiceConnection::RegisterTypeface(uint64_t globalUniqueId,
2166     std::shared_ptr<Drawing::Typeface>& typeface)
2167 {
2168     RS_LOGI("RSRenderServiceConnection:reg typeface, pid[%{public}d], familyname:%{public}s, uniqueid:%{public}u",
2169         RSTypefaceCache::GetTypefacePid(globalUniqueId), typeface->GetFamilyName().c_str(),
2170         RSTypefaceCache::GetTypefaceId(globalUniqueId));
2171     RSTypefaceCache::Instance().CacheDrawingTypeface(globalUniqueId, typeface);
2172     return true;
2173 }
2174 
UnRegisterTypeface(uint64_t globalUniqueId)2175 bool RSRenderServiceConnection::UnRegisterTypeface(uint64_t globalUniqueId)
2176 {
2177     RS_LOGW("RSRenderServiceConnection:uneg typeface: pid[%{public}d], uniqueid:%{public}u",
2178         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
2179     RSTypefaceCache::Instance().AddDelayDestroyQueue(globalUniqueId);
2180     return true;
2181 }
2182 
GetDisplayIdentificationData(ScreenId id,uint8_t & outPort,std::vector<uint8_t> & edidData)2183 int32_t RSRenderServiceConnection::GetDisplayIdentificationData(ScreenId id, uint8_t& outPort,
2184     std::vector<uint8_t>& edidData)
2185 {
2186     std::lock_guard<std::mutex> lock(mutex_);
2187     if (!screenManager_) {
2188         return StatusCode::SCREEN_NOT_FOUND;
2189     }
2190     return screenManager_->GetDisplayIdentificationData(id, outPort, edidData);
2191 }
2192 
SetScreenSkipFrameInterval(ScreenId id,uint32_t skipFrameInterval)2193 int32_t RSRenderServiceConnection::SetScreenSkipFrameInterval(ScreenId id, uint32_t skipFrameInterval)
2194 {
2195     if (!screenManager_) {
2196         return StatusCode::SCREEN_NOT_FOUND;
2197     }
2198     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2199     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2200 #ifdef RS_ENABLE_GPU
2201         return RSHardwareThread::Instance().ScheduleTask(
2202             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
2203 #else
2204         return StatusCode::SCREEN_NOT_FOUND;
2205 #endif
2206     } else {
2207         if (!mainThread_) {
2208             return StatusCode::INVALID_ARGUMENTS;
2209         }
2210         return mainThread_->ScheduleTask(
2211             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
2212     }
2213 }
2214 
SetVirtualScreenRefreshRate(ScreenId id,uint32_t maxRefreshRate,uint32_t & actualRefreshRate)2215 int32_t RSRenderServiceConnection::SetVirtualScreenRefreshRate(
2216     ScreenId id, uint32_t maxRefreshRate, uint32_t& actualRefreshRate)
2217 {
2218     if (!screenManager_) {
2219         return StatusCode::SCREEN_NOT_FOUND;
2220     }
2221     return screenManager_->SetVirtualScreenRefreshRate(id, maxRefreshRate, actualRefreshRate);
2222 }
2223 
SetScreenActiveRect(ScreenId id,const Rect & activeRect)2224 uint32_t RSRenderServiceConnection::SetScreenActiveRect(
2225     ScreenId id, const Rect& activeRect)
2226 {
2227     if (!screenManager_) {
2228         return StatusCode::SCREEN_NOT_FOUND;
2229     }
2230     GraphicIRect dstActiveRect {
2231         .x = activeRect.x,
2232         .y = activeRect.y,
2233         .w = activeRect.w,
2234         .h = activeRect.h,
2235     };
2236     if (!mainThread_) {
2237         return StatusCode::INVALID_ARGUMENTS;
2238     }
2239     auto task = [weakScreenManager = wptr<RSScreenManager>(screenManager_), id, dstActiveRect]() -> void {
2240         sptr<RSScreenManager> screenManager = weakScreenManager.promote();
2241         if (!screenManager) {
2242             return;
2243         }
2244         screenManager->SetScreenActiveRect(id, dstActiveRect);
2245     };
2246     mainThread_->ScheduleTask(task).wait();
2247 
2248     HgmTaskHandleThread::Instance().PostTask([id, dstActiveRect]() {
2249             OHOS::Rosen::HgmCore::Instance().NotifyScreenRectFrameRateChange(id, dstActiveRect);
2250     });
2251     return StatusCode::SUCCESS;
2252 }
2253 
RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)2254 int32_t RSRenderServiceConnection::RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)
2255 {
2256     std::lock_guard<std::mutex> lock(mutex_);
2257     if (!mainThread_) {
2258         return StatusCode::INVALID_ARGUMENTS;
2259     }
2260     if (!callback) {
2261         RS_LOGD("RSRenderServiceConnection::RegisterOcclusionChangeCallback: callback is nullptr");
2262         return StatusCode::INVALID_ARGUMENTS;
2263     }
2264     mainThread_->RegisterOcclusionChangeCallback(remotePid_, callback);
2265     return StatusCode::SUCCESS;
2266 }
2267 
RegisterSurfaceOcclusionChangeCallback(NodeId id,sptr<RSISurfaceOcclusionChangeCallback> callback,std::vector<float> & partitionPoints)2268 int32_t RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback(
2269     NodeId id, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints)
2270 {
2271     std::lock_guard<std::mutex> lock(mutex_);
2272     if (!mainThread_) {
2273         return StatusCode::INVALID_ARGUMENTS;
2274     }
2275     if (!callback) {
2276         RS_LOGD("RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback: callback is nullptr");
2277         return StatusCode::INVALID_ARGUMENTS;
2278     }
2279     mainThread_->RegisterSurfaceOcclusionChangeCallback(id, remotePid_, callback, partitionPoints);
2280     return StatusCode::SUCCESS;
2281 }
2282 
UnRegisterSurfaceOcclusionChangeCallback(NodeId id)2283 int32_t RSRenderServiceConnection::UnRegisterSurfaceOcclusionChangeCallback(NodeId id)
2284 {
2285     std::lock_guard<std::mutex> lock(mutex_);
2286     if (!mainThread_) {
2287         return StatusCode::INVALID_ARGUMENTS;
2288     }
2289     mainThread_->UnRegisterSurfaceOcclusionChangeCallback(id);
2290     return StatusCode::SUCCESS;
2291 }
2292 
RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)2293 int32_t RSRenderServiceConnection::RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)
2294 {
2295     std::lock_guard<std::mutex> lock(mutex_);
2296     if (!callback) {
2297         RS_LOGD("RSRenderServiceConnection::RegisterHgmConfigChangeCallback: callback is nullptr");
2298         return StatusCode::INVALID_ARGUMENTS;
2299     }
2300 
2301     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2302         HgmConfigCallbackManager::GetInstance()->RegisterHgmConfigChangeCallback(remotePid_, callback);
2303     });
2304     return StatusCode::SUCCESS;
2305 }
2306 
RegisterHgmRefreshRateModeChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)2307 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback(
2308     sptr<RSIHgmConfigChangeCallback> callback)
2309 {
2310     std::lock_guard<std::mutex> lock(mutex_);
2311     if (!callback) {
2312         RS_LOGD("RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback: callback is nullptr");
2313         return StatusCode::INVALID_ARGUMENTS;
2314     }
2315 
2316     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2317         HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateModeChangeCallback(remotePid_, callback);
2318     });
2319     return StatusCode::SUCCESS;
2320 }
2321 
RegisterHgmRefreshRateUpdateCallback(sptr<RSIHgmConfigChangeCallback> callback)2322 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateUpdateCallback(
2323     sptr<RSIHgmConfigChangeCallback> callback)
2324 {
2325     std::lock_guard<std::mutex> lock(mutex_);
2326 
2327     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2328         HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateUpdateCallback(remotePid_, callback);
2329     });
2330     return StatusCode::SUCCESS;
2331 }
2332 
RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)2333 int32_t RSRenderServiceConnection::RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,
2334     sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)
2335 {
2336     if (!mainThread_ || dstPid == 0) {
2337         return StatusCode::INVALID_ARGUMENTS;
2338     }
2339     auto task = [pid = remotePid_, dstPid, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() {
2340         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2341         if (!connection || !connection->mainThread_) {
2342             return;
2343         }
2344         connection->mainThread_->GetContext().GetMutableFrameRateLinkerMap()
2345             .RegisterFrameRateLinkerExpectedFpsUpdateCallback(pid, dstPid, callback);
2346     };
2347     mainThread_->PostTask(task);
2348     return StatusCode::SUCCESS;
2349 }
2350 
SetAppWindowNum(uint32_t num)2351 ErrCode RSRenderServiceConnection::SetAppWindowNum(uint32_t num)
2352 {
2353     if (!mainThread_) {
2354         return ERR_INVALID_VALUE;
2355     }
2356     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), num]() -> void {
2357         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2358         if (!connection || !connection->mainThread_) {
2359             return;
2360         }
2361         connection->mainThread_->SetAppWindowNum(num);
2362     };
2363     mainThread_->PostTask(task);
2364 
2365     return ERR_OK;
2366 }
2367 
SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes,bool isRegularAnimation)2368 bool RSRenderServiceConnection::SetSystemAnimatedScenes(
2369     SystemAnimatedScenes systemAnimatedScenes, bool isRegularAnimation)
2370 {
2371     std::lock_guard<std::mutex> lock(mutex_);
2372     if (!mainThread_) {
2373         return false;
2374     }
2375 #ifdef RS_ENABLE_GPU
2376     RSUifirstManager::Instance().OnProcessAnimateScene(systemAnimatedScenes);
2377     return mainThread_->SetSystemAnimatedScenes(systemAnimatedScenes, isRegularAnimation);
2378 #else
2379     return false;
2380 #endif
2381 }
2382 
ShowWatermark(const std::shared_ptr<Media::PixelMap> & watermarkImg,bool isShow)2383 void RSRenderServiceConnection::ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool isShow)
2384 {
2385     if (!mainThread_) {
2386         return;
2387     }
2388     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), watermarkImg, isShow]() -> void {
2389         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2390         if (connection == nullptr || connection->mainThread_ == nullptr) {
2391             return;
2392         }
2393         connection->mainThread_->ShowWatermark(watermarkImg, isShow);
2394     };
2395     mainThread_->PostTask(task);
2396 }
2397 
ResizeVirtualScreen(ScreenId id,uint32_t width,uint32_t height)2398 int32_t RSRenderServiceConnection::ResizeVirtualScreen(ScreenId id, uint32_t width, uint32_t height)
2399 {
2400     if (!screenManager_) {
2401         return StatusCode::SCREEN_NOT_FOUND;
2402     }
2403     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2404     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2405 #ifdef RS_ENABLE_GPU
2406         return RSHardwareThread::Instance().ScheduleTask(
2407             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
2408                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
2409                 if (connection == nullptr || connection->screenManager_ == nullptr) {
2410                     return RS_CONNECTION_ERROR;
2411                 }
2412                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
2413             }
2414         ).get();
2415 #else
2416         return StatusCode::SCREEN_NOT_FOUND;
2417 #endif
2418     } else if (mainThread_ != nullptr) {
2419         return mainThread_->ScheduleTask(
2420             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
2421                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
2422                 if (connection == nullptr || connection->screenManager_ == nullptr) {
2423                     return RS_CONNECTION_ERROR;
2424                 }
2425                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
2426             }
2427         ).get();
2428     } else {
2429         return StatusCode::SCREEN_NOT_FOUND;
2430     }
2431 }
2432 
ReportJankStats()2433 ErrCode RSRenderServiceConnection::ReportJankStats()
2434 {
2435 #ifdef RS_ENABLE_GPU
2436     auto task = []() -> void { RSJankStats::GetInstance().ReportJankStats(); };
2437     renderThread_.PostTask(task);
2438 #endif
2439     return ERR_OK;
2440 }
2441 
NotifyLightFactorStatus(int32_t lightFactorStatus)2442 ErrCode RSRenderServiceConnection::NotifyLightFactorStatus(int32_t lightFactorStatus)
2443 {
2444     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, lightFactorStatus]() {
2445         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2446         if (frameRateMgr != nullptr) {
2447             frameRateMgr->HandleLightFactorStatus(pid, lightFactorStatus);
2448         }
2449     });
2450     return ERR_OK;
2451 }
2452 
NotifyPackageEvent(uint32_t listSize,const std::vector<std::string> & packageList)2453 void RSRenderServiceConnection::NotifyPackageEvent(uint32_t listSize, const std::vector<std::string>& packageList)
2454 {
2455     mainThread_->NotifyPackageEvent(packageList);
2456     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, listSize, packageList]() {
2457         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2458         if (frameRateMgr != nullptr) {
2459             frameRateMgr->HandlePackageEvent(pid, packageList);
2460         }
2461     });
2462 }
2463 
NotifyAppStrategyConfigChangeEvent(const std::string & pkgName,uint32_t listSize,const std::vector<std::pair<std::string,std::string>> & newConfig)2464 void RSRenderServiceConnection::NotifyAppStrategyConfigChangeEvent(const std::string& pkgName, uint32_t listSize,
2465     const std::vector<std::pair<std::string, std::string>>& newConfig)
2466 {
2467     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, listSize, pkgName, newConfig] () {
2468         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2469         if (frameRateMgr != nullptr) {
2470             frameRateMgr->HandleAppStrategyConfigEvent(pid, pkgName, newConfig);
2471         }
2472     });
2473 }
2474 
NotifyRefreshRateEvent(const EventInfo & eventInfo)2475 void RSRenderServiceConnection::NotifyRefreshRateEvent(const EventInfo& eventInfo)
2476 {
2477     if (VOTER_SCENE_BLUR == eventInfo.eventName) {
2478         RsFrameBlurPredict::GetInstance().TakeEffectBlurScene(eventInfo);
2479         return;
2480     }
2481 
2482     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, eventInfo]() {
2483         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2484         if (frameRateMgr != nullptr) {
2485             frameRateMgr->HandleRefreshRateEvent(pid, eventInfo);
2486         }
2487     });
2488 }
2489 
NotifySoftVsyncEvent(uint32_t pid,uint32_t rateDiscount)2490 ErrCode RSRenderServiceConnection::NotifySoftVsyncEvent(uint32_t pid, uint32_t rateDiscount)
2491 {
2492     if (!appVSyncDistributor_) {
2493         return ERR_INVALID_VALUE;
2494     }
2495     appVSyncDistributor_->SetQosVSyncRateByPidPublic(pid, rateDiscount, true);
2496     return ERR_OK;
2497 }
2498 
NotifyTouchEvent(int32_t touchStatus,int32_t touchCnt)2499 void RSRenderServiceConnection::NotifyTouchEvent(int32_t touchStatus, int32_t touchCnt)
2500 {
2501     mainThread_->NotifyTouchEvent(touchStatus, touchCnt);
2502     auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2503     if (frameRateMgr != nullptr) {
2504         frameRateMgr->HandleTouchEvent(remotePid_, touchStatus, touchCnt);
2505     }
2506 }
2507 
NotifyDynamicModeEvent(bool enableDynamicModeEvent)2508 void RSRenderServiceConnection::NotifyDynamicModeEvent(bool enableDynamicModeEvent)
2509 {
2510     HgmTaskHandleThread::Instance().PostTask([enableDynamicModeEvent] () {
2511         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2512         if (frameRateMgr == nullptr) {
2513             RS_LOGW("RSRenderServiceConnection::NotifyDynamicModeEvent: frameRateMgr is nullptr.");
2514             return;
2515         }
2516         frameRateMgr->HandleDynamicModeEvent(enableDynamicModeEvent);
2517     });
2518 }
2519 
NotifyHgmConfigEvent(const std::string & eventName,bool state)2520 ErrCode RSRenderServiceConnection::NotifyHgmConfigEvent(const std::string &eventName, bool state)
2521 {
2522     HgmTaskHandleThread::Instance().PostTask([eventName, state] () {
2523         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2524         if (frameRateMgr == nullptr) {
2525             RS_LOGW("RSRenderServiceConnection::NotifyHgmConfigEvent: frameRateMgr is nullptr.");
2526             return;
2527         }
2528         if (eventName == "HGMCONFIG_HIGH_TEMP") {
2529             frameRateMgr->HandleThermalFrameRate(state);
2530         }
2531     });
2532     return ERR_OK;
2533 }
2534 
ReportEventResponse(DataBaseRs info)2535 ErrCode RSRenderServiceConnection::ReportEventResponse(DataBaseRs info)
2536 {
2537     auto task = [info]() -> void {
2538         RSJankStats::GetInstance().SetReportEventResponse(info);
2539     };
2540 #ifdef RS_ENABLE_GPU
2541     renderThread_.PostTask(task);
2542     RSUifirstManager::Instance().OnProcessEventResponse(info);
2543 #endif
2544     return ERR_OK;
2545 }
2546 
ReportEventComplete(DataBaseRs info)2547 ErrCode RSRenderServiceConnection::ReportEventComplete(DataBaseRs info)
2548 {
2549     auto task = [info]() -> void {
2550         RSJankStats::GetInstance().SetReportEventComplete(info);
2551     };
2552 #ifdef RS_ENABLE_GPU
2553     renderThread_.PostTask(task);
2554     RSUifirstManager::Instance().OnProcessEventComplete(info);
2555 #endif
2556     return ERR_OK;
2557 }
2558 
ReportEventJankFrame(DataBaseRs info)2559 ErrCode RSRenderServiceConnection::ReportEventJankFrame(DataBaseRs info)
2560 {
2561 #ifdef RS_ENABLE_GPU
2562     bool isReportTaskDelayed = renderThread_.IsMainLooping();
2563     auto task = [info, isReportTaskDelayed]() -> void {
2564         RSJankStats::GetInstance().SetReportEventJankFrame(info, isReportTaskDelayed);
2565     };
2566     renderThread_.PostTask(task);
2567 #endif
2568     return ERR_OK;
2569 }
2570 
ReportRsSceneJankStart(AppInfo info)2571 void RSRenderServiceConnection::ReportRsSceneJankStart(AppInfo info)
2572 {
2573     auto task = [info]() -> void {
2574         RSJankStats::GetInstance().SetReportRsSceneJankStart(info);
2575     };
2576     renderThread_.PostTask(task);
2577 }
2578 
ReportRsSceneJankEnd(AppInfo info)2579 void RSRenderServiceConnection::ReportRsSceneJankEnd(AppInfo info)
2580 {
2581     auto task = [info]() -> void {
2582         RSJankStats::GetInstance().SetReportRsSceneJankEnd(info);
2583     };
2584     renderThread_.PostTask(task);
2585 }
2586 
ReportGameStateData(GameStateData info)2587 void RSRenderServiceConnection::ReportGameStateData(GameStateData info)
2588 {
2589     RS_LOGD("RSRenderServiceConnection::ReportGameStateData = %{public}s, uid = %{public}d, state = %{public}d, "
2590             "pid = %{public}d renderTid = %{public}d ",
2591         info.bundleName.c_str(), info.uid, info.state, info.pid, info.renderTid);
2592 
2593     FrameReport::GetInstance().SetGameScene(info.pid, info.state);
2594 }
2595 
SetHardwareEnabled(NodeId id,bool isEnabled,SelfDrawingNodeType selfDrawingType,bool dynamicHardwareEnable)2596 ErrCode RSRenderServiceConnection::SetHardwareEnabled(NodeId id, bool isEnabled, SelfDrawingNodeType selfDrawingType,
2597     bool dynamicHardwareEnable)
2598 {
2599     if (!mainThread_) {
2600         return ERR_INVALID_VALUE;
2601     }
2602     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, isEnabled, selfDrawingType,
2603         dynamicHardwareEnable]() -> void {
2604         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2605         if (connection == nullptr || connection->mainThread_ == nullptr) {
2606             return;
2607         }
2608         auto& context = connection->mainThread_->GetContext();
2609         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
2610         if (node) {
2611             node->SetHardwareEnabled(isEnabled, selfDrawingType, dynamicHardwareEnable);
2612         }
2613     };
2614     mainThread_->PostTask(task);
2615     return ERR_OK;
2616 }
2617 
SetHidePrivacyContent(NodeId id,bool needHidePrivacyContent,uint32_t & resCode)2618 ErrCode RSRenderServiceConnection::SetHidePrivacyContent(NodeId id, bool needHidePrivacyContent, uint32_t& resCode)
2619 {
2620     if (!mainThread_) {
2621         resCode = static_cast<int32_t>(RSInterfaceErrorCode::UNKNOWN_ERROR);
2622         return ERR_INVALID_VALUE;
2623     }
2624     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, needHidePrivacyContent]() -> void {
2625         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2626         if (connection == nullptr || connection->mainThread_ == nullptr) {
2627             return;
2628         }
2629         auto& context = connection->mainThread_->GetContext();
2630         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
2631         if (node) {
2632             node->SetHidePrivacyContent(needHidePrivacyContent);
2633         }
2634     };
2635     mainThread_->PostTask(task);
2636     resCode = static_cast<uint32_t>(RSInterfaceErrorCode::NO_ERROR);
2637     return ERR_OK;
2638 }
2639 
SetCacheEnabledForRotation(bool isEnabled)2640 ErrCode RSRenderServiceConnection::SetCacheEnabledForRotation(bool isEnabled)
2641 {
2642     if (!mainThread_) {
2643         return ERR_INVALID_VALUE;
2644     }
2645     auto task = [isEnabled]() {
2646         RSSystemProperties::SetCacheEnabledForRotation(isEnabled);
2647     };
2648     mainThread_->PostTask(task);
2649     return ERR_OK;
2650 }
2651 
GetActiveDirtyRegionInfo()2652 std::vector<ActiveDirtyRegionInfo> RSRenderServiceConnection::GetActiveDirtyRegionInfo()
2653 {
2654 #ifdef RS_ENABLE_GPU
2655     const auto& activeDirtyRegionInfos = GpuDirtyRegionCollection::GetInstance().GetActiveDirtyRegionInfo();
2656     GpuDirtyRegionCollection::GetInstance().ResetActiveDirtyRegionInfo();
2657     return activeDirtyRegionInfos;
2658 #else
2659     return {};
2660 #endif
2661 }
2662 
GetGlobalDirtyRegionInfo()2663 GlobalDirtyRegionInfo RSRenderServiceConnection::GetGlobalDirtyRegionInfo()
2664 {
2665 #ifdef RS_ENABLE_GPU
2666     const auto& globalDirtyRegionInfo = GpuDirtyRegionCollection::GetInstance().GetGlobalDirtyRegionInfo();
2667     GpuDirtyRegionCollection::GetInstance().ResetGlobalDirtyRegionInfo();
2668     return globalDirtyRegionInfo;
2669 #else
2670     return {};
2671 #endif
2672 }
2673 
GetLayerComposeInfo()2674 LayerComposeInfo RSRenderServiceConnection::GetLayerComposeInfo()
2675 {
2676     const auto& layerComposeInfo = LayerComposeCollection::GetInstance().GetLayerComposeInfo();
2677     LayerComposeCollection::GetInstance().ResetLayerComposeInfo();
2678     return layerComposeInfo;
2679 }
2680 
GetHwcDisabledReasonInfo()2681 HwcDisabledReasonInfos RSRenderServiceConnection::GetHwcDisabledReasonInfo()
2682 {
2683     return HwcDisabledReasonCollection::GetInstance().GetHwcDisabledReasonInfo();
2684 }
2685 
GetHdrOnDuration(int64_t & hdrOnDuration)2686 ErrCode RSRenderServiceConnection::GetHdrOnDuration(int64_t& hdrOnDuration)
2687 {
2688     auto rsHdrCollection = RsHdrCollection::GetInstance();
2689     if (rsHdrCollection == nullptr) {
2690         return ERR_INVALID_VALUE;
2691     }
2692     hdrOnDuration = rsHdrCollection->GetHdrOnDuration();
2693     rsHdrCollection->ResetHdrOnDuration();
2694     return ERR_OK;
2695 }
2696 
SetVmaCacheStatus(bool flag)2697 ErrCode RSRenderServiceConnection::SetVmaCacheStatus(bool flag)
2698 {
2699 #ifdef RS_ENABLE_GPU
2700     renderThread_.SetVmaCacheStatus(flag);
2701 #endif
2702     return ERR_OK;
2703 }
2704 
2705 #ifdef TP_FEATURE_ENABLE
SetTpFeatureConfig(int32_t feature,const char * config,TpFeatureConfigType tpFeatureConfigType)2706 void RSRenderServiceConnection::SetTpFeatureConfig(int32_t feature, const char* config,
2707     TpFeatureConfigType tpFeatureConfigType)
2708 {
2709     switch (tpFeatureConfigType) {
2710         case TpFeatureConfigType::DEFAULT_TP_FEATURE: {
2711             if (!TOUCH_SCREEN->IsSetFeatureConfigHandleValid()) {
2712                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfigHandl is nullptr");
2713                 return;
2714             }
2715             if (TOUCH_SCREEN->SetFeatureConfig(feature, config) < 0) {
2716                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfig failed");
2717                 return;
2718             }
2719             break;
2720         }
2721         case TpFeatureConfigType::AFT_TP_FEATURE: {
2722             if (!TOUCH_SCREEN->IsSetAftConfigHandleValid()) {
2723                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfigHandl is nullptr");
2724                 return;
2725             }
2726             if (TOUCH_SCREEN->SetAftConfig(config) < 0) {
2727                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfig failed");
2728                 return;
2729             }
2730             break;
2731         }
2732         default: {
2733             RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: unknown TpFeatureConfigType: %" PRIu8"",
2734                 static_cast<uint8_t>(tpFeatureConfigType));
2735             return;
2736         }
2737     }
2738 }
2739 #endif
2740 
SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)2741 void RSRenderServiceConnection::SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)
2742 {
2743     if (isVirtualScreenUsingStatus) {
2744         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ };
2745         NotifyRefreshRateEvent(event);
2746     } else {
2747         EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
2748         NotifyRefreshRateEvent(event);
2749     }
2750     return;
2751 }
2752 
SetCurtainScreenUsingStatus(bool isCurtainScreenOn)2753 ErrCode RSRenderServiceConnection::SetCurtainScreenUsingStatus(bool isCurtainScreenOn)
2754 {
2755     if (!mainThread_) {
2756         return ERR_INVALID_VALUE;
2757     }
2758     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isCurtainScreenOn]() -> void {
2759         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2760         if (connection == nullptr || connection->mainThread_ == nullptr) {
2761             return;
2762         }
2763         connection->mainThread_->SetCurtainScreenUsingStatus(isCurtainScreenOn);
2764     };
2765     mainThread_->PostTask(task);
2766     return ERR_OK;
2767 }
2768 
DropFrameByPid(const std::vector<int32_t> pidList)2769 void RSRenderServiceConnection::DropFrameByPid(const std::vector<int32_t> pidList)
2770 {
2771     if (!mainThread_) {
2772         return;
2773     }
2774     mainThread_->ScheduleTask(
2775         [weakThis = wptr<RSRenderServiceConnection>(this), pidList]() {
2776             // don't use 'this' directly
2777             sptr<RSRenderServiceConnection> connection = weakThis.promote();
2778             if (connection == nullptr || connection->mainThread_ == nullptr) {
2779                 return;
2780             }
2781             connection->mainThread_->AddPidNeedDropFrame(pidList);
2782         }
2783     );
2784 }
2785 
RegisterUIExtensionCallback(uint64_t userId,sptr<RSIUIExtensionCallback> callback,bool unobscured)2786 int32_t RSRenderServiceConnection::RegisterUIExtensionCallback(uint64_t userId, sptr<RSIUIExtensionCallback> callback,
2787     bool unobscured)
2788 {
2789     std::lock_guard<std::mutex> lock(mutex_);
2790     if (!mainThread_) {
2791         return StatusCode::INVALID_ARGUMENTS;
2792     }
2793     if (!callback) {
2794         RS_LOGE("RSRenderServiceConnection::RegisterUIExtensionCallback register null callback, failed.");
2795         return StatusCode::INVALID_ARGUMENTS;
2796     }
2797     mainThread_->RegisterUIExtensionCallback(remotePid_, userId, callback, unobscured);
2798     return StatusCode::SUCCESS;
2799 }
2800 
SetVirtualScreenStatus(ScreenId id,VirtualScreenStatus screenStatus)2801 bool RSRenderServiceConnection::SetVirtualScreenStatus(ScreenId id, VirtualScreenStatus screenStatus)
2802 {
2803     if (!screenManager_) {
2804         return StatusCode::SCREEN_NOT_FOUND;
2805     }
2806     RS_LOGD("RSRenderServiceConnection::SetVirtualScreenStatus ScreenId:%{public}" PRIu64 " screenStatus:%{public}d",
2807         id, screenStatus);
2808     return screenManager_->SetVirtualScreenStatus(id, screenStatus);
2809 }
2810 
SetAncoForceDoDirect(bool direct,bool & res)2811 ErrCode RSRenderServiceConnection::SetAncoForceDoDirect(bool direct, bool& res)
2812 {
2813     std::lock_guard<std::mutex> lock(mutex_);
2814     if (mainThread_ == nullptr) {
2815         res = false;
2816         return ERR_INVALID_VALUE;
2817     }
2818     mainThread_->SetAncoForceDoDirect(direct);
2819     res = true;
2820     return ERR_OK;
2821 }
2822 
SetFreeMultiWindowStatus(bool enable)2823 void RSRenderServiceConnection::SetFreeMultiWindowStatus(bool enable)
2824 {
2825 #ifdef RS_ENABLE_GPU
2826     if (mainThread_ == nullptr) {
2827         return;
2828     }
2829     auto task = [enable]() -> void {
2830         RSUifirstManager::Instance().SetFreeMultiWindowStatus(enable);
2831     };
2832     mainThread_->PostTask(task);
2833 #endif
2834 }
2835 
RegisterSurfaceBufferCallback(pid_t pid,uint64_t uid,sptr<RSISurfaceBufferCallback> callback)2836 ErrCode RSRenderServiceConnection::RegisterSurfaceBufferCallback(pid_t pid, uint64_t uid,
2837     sptr<RSISurfaceBufferCallback> callback)
2838 {
2839     RSSurfaceBufferCallbackManager::Instance().RegisterSurfaceBufferCallback(pid, uid, callback);
2840     return ERR_OK;
2841 }
2842 
UnregisterSurfaceBufferCallback(pid_t pid,uint64_t uid)2843 ErrCode RSRenderServiceConnection::UnregisterSurfaceBufferCallback(pid_t pid, uint64_t uid)
2844 {
2845     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(pid, uid);
2846     return ERR_OK;
2847 }
2848 
SetLayerTop(const std::string & nodeIdStr,bool isTop)2849 void RSRenderServiceConnection::SetLayerTop(const std::string &nodeIdStr, bool isTop)
2850 {
2851     if (mainThread_ == nullptr) {
2852         return;
2853     }
2854     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isTop]() -> void {
2855         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2856         if (connection == nullptr || connection->mainThread_ == nullptr) {
2857             return;
2858         }
2859         auto& context = connection->mainThread_->GetContext();
2860         context.GetNodeMap().TraverseSurfaceNodes(
2861             [&nodeIdStr, &isTop](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
2862             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
2863                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
2864                 surfaceNode->SetLayerTop(isTop);
2865                 return;
2866             }
2867         });
2868         // It can be displayed immediately after layer-top changed.
2869         connection->mainThread_->SetDirtyFlag();
2870         connection->mainThread_->RequestNextVSync();
2871     };
2872     mainThread_->PostTask(task);
2873 }
2874 
NotifyScreenSwitched()2875 void RSRenderServiceConnection::NotifyScreenSwitched()
2876 {
2877     std::lock_guard<std::mutex> lock(mutex_);
2878     if (!screenManager_) {
2879         RS_LOGE("RSRenderServiceConnection::NotifyScreenSwitched screenManager_ is nullptr");
2880         return;
2881     }
2882     RS_LOGI("RSRenderServiceConnection::NotifyScreenSwitched SetScreenSwitchStatus true");
2883     RS_TRACE_NAME_FMT("NotifyScreenSwitched");
2884     screenManager_->SetScreenSwitchStatus(true);
2885 }
2886 
SetWindowContainer(NodeId nodeId,bool value)2887 ErrCode RSRenderServiceConnection::SetWindowContainer(NodeId nodeId, bool value)
2888 {
2889     if (!mainThread_) {
2890         return ERR_INVALID_VALUE;
2891     }
2892     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeId, value]() -> void {
2893         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2894         if (connection == nullptr || connection->mainThread_ == nullptr) {
2895             return;
2896         }
2897         auto& nodeMap = connection->mainThread_->GetContext().GetNodeMap();
2898         if (auto node = nodeMap.GetRenderNode<RSCanvasRenderNode>(nodeId)) {
2899             auto displayNodeId = node->GetDisplayNodeId();
2900             if (auto displayNode = nodeMap.GetRenderNode<RSDisplayRenderNode>(displayNodeId)) {
2901                 RS_LOGD("RSRenderServiceConnection::SetWindowContainer nodeId: %{public}" PRIu64 ", value: %{public}d",
2902                     nodeId, value);
2903                 displayNode->SetWindowContainer(value ? node : nullptr);
2904             } else {
2905                 RS_LOGE("RSRenderServiceConnection::SetWindowContainer displayNode is nullptr, nodeId: %{public}"
2906                     PRIu64, displayNodeId);
2907             }
2908         } else {
2909             RS_LOGE("RSRenderServiceConnection::SetWindowContainer node is nullptr, nodeId: %{public}" PRIu64,
2910                 nodeId);
2911         }
2912     };
2913     mainThread_->PostTask(task);
2914     return ERR_OK;
2915 }
2916 
RegisterSelfDrawingNodeRectChangeCallback(sptr<RSISelfDrawingNodeRectChangeCallback> callback)2917 int32_t RSRenderServiceConnection::RegisterSelfDrawingNodeRectChangeCallback(
2918     sptr<RSISelfDrawingNodeRectChangeCallback> callback)
2919 {
2920     std::lock_guard<std::mutex> lock(mutex_);
2921 
2922     if (!mainThread_) {
2923         return StatusCode::INVALID_ARGUMENTS;
2924     }
2925     if (!callback) {
2926         RS_LOGE("RSRenderServiceConnection::RegisterSelfDrawingNodeRectChangeCallback register null callback, failed.");
2927         return StatusCode::INVALID_ARGUMENTS;
2928     }
2929 
2930     auto task = [pid = remotePid_, callback]() {
2931         SelfDrawingNodeMonitor::GetInstance().RegisterRectChangeCallback(pid, callback);
2932     };
2933     mainThread_->PostTask(task);
2934     return StatusCode::SUCCESS;
2935 }
2936 
2937 #ifdef RS_ENABLE_OVERLAY_DISPLAY
SetOverlayDisplayMode(int32_t mode)2938 ErrCode RSRenderServiceConnection::SetOverlayDisplayMode(int32_t mode)
2939 {
2940     RS_LOGI("RSRenderServiceConnection::SetOverlayDisplayMode: mode: [%{public}d]", mode);
2941     return RSOverlayDisplayManager::Instance().SetOverlayDisplayMode(mode) == 0 ? ERR_OK : ERR_INVALID_VALUE;
2942 }
2943 #endif
2944 
NotifyPageName(const std::string & packageName,const std::string & pageName,bool isEnter)2945 void RSRenderServiceConnection::NotifyPageName(const std::string &packageName,
2946     const std::string &pageName, bool isEnter)
2947 {
2948     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, packageName, pageName, isEnter]() {
2949         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2950         if (frameRateMgr != nullptr) {
2951             frameRateMgr->NotifyPageName(pid, packageName, pageName, isEnter);
2952         }
2953     });
2954 }
2955 } // namespace Rosen
2956 } // namespace OHOS
2957