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 "luminance/rs_luminance_control.h"
24 #include "offscreen_render/rs_offscreen_render_thread.h"
25 #include "rs_main_thread.h"
26 #include "rs_trace.h"
27 #include "system/rs_system_parameters.h"
28 
29 #include "command/rs_command_verify_helper.h"
30 #include "command/rs_display_node_command.h"
31 #include "command/rs_surface_node_command.h"
32 #include "common/rs_background_thread.h"
33 #include "drawable/rs_canvas_drawing_render_node_drawable.h"
34 #include "include/gpu/GrDirectContext.h"
35 #include "pipeline/parallel_render/rs_sub_thread_manager.h"
36 #include "pipeline/rs_canvas_drawing_render_node.h"
37 #include "pipeline/rs_realtime_refresh_rate_manager.h"
38 #include "pipeline/rs_render_frame_rate_linker_map.h"
39 #include "pipeline/rs_render_node_gc.h"
40 #include "pipeline/rs_render_node_map.h"
41 #include "pipeline/rs_render_service_listener.h"
42 #include "pipeline/rs_surface_buffer_callback_manager.h"
43 #include "pipeline/rs_surface_capture_task.h"
44 #include "pipeline/rs_surface_capture_task_parallel.h"
45 #include "pipeline/rs_ui_capture_task_parallel.h"
46 #include "pipeline/rs_surface_render_node.h"
47 #include "pipeline/rs_task_dispatcher.h"
48 #include "pipeline/rs_uifirst_manager.h"
49 #include "pipeline/rs_uni_render_judgement.h"
50 #include "pipeline/rs_uni_ui_capture.h"
51 #include "pipeline/rs_unmarshal_thread.h"
52 #include "pixel_map_from_surface.h"
53 #include "platform/common/rs_log.h"
54 #include "platform/common/rs_system_properties.h"
55 #include "platform/ohos/rs_jank_stats.h"
56 #include "render/rs_typeface_cache.h"
57 
58 #ifdef TP_FEATURE_ENABLE
59 #include "touch_screen/touch_screen.h"
60 #endif
61 
62 #ifdef RS_ENABLE_VK
63 #include "platform/ohos/backend/rs_vulkan_context.h"
64 #endif
65 
66 namespace OHOS {
67 namespace Rosen {
68 namespace {
69 constexpr int SLEEP_TIME_US = 1000;
70 const std::string REGISTER_NODE = "RegisterNode";
71 }
72 // we guarantee that when constructing this object,
73 // 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)74 RSRenderServiceConnection::RSRenderServiceConnection(
75     pid_t remotePid,
76     wptr<RSRenderService> renderService,
77     RSMainThread* mainThread,
78     sptr<RSScreenManager> screenManager,
79     sptr<IRemoteObject> token,
80     sptr<VSyncDistributor> distributor)
81     : remotePid_(remotePid),
82       renderService_(renderService),
83       mainThread_(mainThread),
84       renderThread_(RSUniRenderThread::Instance()),
85       screenManager_(screenManager),
86       token_(token),
87       connDeathRecipient_(new RSConnectionDeathRecipient(this)),
88       ApplicationDeathRecipient_(new RSApplicationRenderThreadDeathRecipient(this)),
89       appVSyncDistributor_(distributor)
90 {
91     if (!token_->AddDeathRecipient(connDeathRecipient_)) {
92         RS_LOGW("RSRenderServiceConnection: Failed to set death recipient.");
93     }
94 }
95 
~RSRenderServiceConnection()96 RSRenderServiceConnection::~RSRenderServiceConnection() noexcept
97 {
98     if (token_ && connDeathRecipient_) {
99         token_->RemoveDeathRecipient(connDeathRecipient_);
100     }
101     CleanAll();
102 }
103 
CleanVirtualScreens()104 void RSRenderServiceConnection::CleanVirtualScreens() noexcept
105 {
106     std::lock_guard<std::mutex> lock(mutex_);
107 
108     for (const auto id : virtualScreenIds_) {
109         screenManager_->RemoveVirtualScreen(id);
110     }
111     virtualScreenIds_.clear();
112 
113     if (screenChangeCallback_ != nullptr) {
114         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
115         screenChangeCallback_ = nullptr;
116     }
117 }
118 
CleanRenderNodes()119 void RSRenderServiceConnection::CleanRenderNodes() noexcept
120 {
121     auto& context = mainThread_->GetContext();
122     auto& nodeMap = context.GetMutableNodeMap();
123 
124     nodeMap.FilterNodeByPid(remotePid_);
125 }
126 
CleanFrameRateLinkers()127 void RSRenderServiceConnection::CleanFrameRateLinkers() noexcept
128 {
129     auto& context = mainThread_->GetContext();
130     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
131 
132     frameRateLinkerMap.FilterFrameRateLinkerByPid(remotePid_);
133 }
134 
CleanFrameRateLinkerExpectedFpsCallbacks()135 void RSRenderServiceConnection::CleanFrameRateLinkerExpectedFpsCallbacks() noexcept
136 {
137     auto& context = mainThread_->GetContext();
138     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
139     frameRateLinkerMap.UnRegisterExpectedFpsUpdateCallbackByListener(remotePid_);
140 }
141 
CleanAll(bool toDelete)142 void RSRenderServiceConnection::CleanAll(bool toDelete) noexcept
143 {
144     {
145         std::lock_guard<std::mutex> lock(mutex_);
146         if (cleanDone_) {
147             return;
148         }
149     }
150     if (!mainThread_) {
151         return;
152     }
153     RS_LOGD("RSRenderServiceConnection::CleanAll() start.");
154     RsCommandVerifyHelper::GetInstance().RemoveCntWithPid(remotePid_);
155     mainThread_->ScheduleTask(
156         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
157             sptr<RSRenderServiceConnection> connection = weakThis.promote();
158             if (!connection) {
159                 return;
160             }
161             RS_TRACE_NAME_FMT("CleanVirtualScreens %d", connection->remotePid_);
162             connection->CleanVirtualScreens();
163         }).wait();
164     mainThread_->ScheduleTask(
165         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
166             sptr<RSRenderServiceConnection> connection = weakThis.promote();
167             if (!connection) {
168                 return;
169             }
170             RS_TRACE_NAME_FMT("CleanRenderNodes %d", connection->remotePid_);
171             connection->CleanRenderNodes();
172             connection->CleanFrameRateLinkers();
173             connection->CleanFrameRateLinkerExpectedFpsCallbacks();
174         }).wait();
175     mainThread_->ScheduleTask(
176         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
177             sptr<RSRenderServiceConnection> connection = weakThis.promote();
178             if (!connection) {
179                 return;
180             }
181             RS_TRACE_NAME_FMT("ClearTransactionDataPidInfo %d", connection->remotePid_);
182             connection->mainThread_->ClearTransactionDataPidInfo(connection->remotePid_);
183         }).wait();
184     mainThread_->ScheduleTask(
185         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
186             sptr<RSRenderServiceConnection> connection = weakThis.promote();
187             if (!connection) {
188                 return;
189             }
190             RS_TRACE_NAME_FMT("CleanHgmEvent %d", connection->remotePid_);
191             if (connection->mainThread_->GetFrameRateMgr() != nullptr) {
192                 connection->mainThread_->GetFrameRateMgr()->CleanVote(connection->remotePid_);
193             }
194         }).wait();
195     mainThread_->ScheduleTask(
196         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
197             sptr<RSRenderServiceConnection> connection = weakThis.promote();
198             if (!connection) {
199                 return;
200             }
201             RS_TRACE_NAME_FMT("UnRegisterCallback %d", connection->remotePid_);
202             HgmConfigCallbackManager::GetInstance()->UnRegisterHgmConfigChangeCallback(connection->remotePid_);
203             connection->mainThread_->UnRegisterOcclusionChangeCallback(connection->remotePid_);
204             connection->mainThread_->ClearSurfaceOcclusionChangeCallback(connection->remotePid_);
205             connection->mainThread_->UnRegisterUIExtensionCallback(connection->remotePid_);
206         }).wait();
207     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(remotePid_);
208     RSTypefaceCache::Instance().RemoveDrawingTypefacesByPid(remotePid_);
209     {
210         std::lock_guard<std::mutex> lock(mutex_);
211         cleanDone_ = true;
212     }
213 
214     if (toDelete) {
215         auto renderService = renderService_.promote();
216         if (renderService == nullptr) {
217             RS_LOGW("RSRenderServiceConnection::CleanAll() RenderService is dead.");
218         } else {
219             renderService->RemoveConnection(GetToken());
220         }
221     }
222 
223     RS_LOGD("RSRenderServiceConnection::CleanAll() end.");
224 }
225 
RSConnectionDeathRecipient(wptr<RSRenderServiceConnection> conn)226 RSRenderServiceConnection::RSConnectionDeathRecipient::RSConnectionDeathRecipient(
227     wptr<RSRenderServiceConnection> conn) : conn_(conn)
228 {
229 }
230 
OnRemoteDied(const wptr<IRemoteObject> & token)231 void RSRenderServiceConnection::RSConnectionDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
232 {
233     auto tokenSptr = token.promote();
234     if (tokenSptr == nullptr) {
235         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: can't promote remote object.");
236         return;
237     }
238 
239     auto rsConn = conn_.promote();
240     if (rsConn == nullptr) {
241         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: RSRenderServiceConnection was dead, do nothing.");
242         return;
243     }
244 
245     if (rsConn->GetToken() != tokenSptr) {
246         RS_LOGI("RSConnectionDeathRecipient::OnRemoteDied: token doesn't match, ignore it.");
247         return;
248     }
249 
250     rsConn->CleanAll(true);
251 }
252 
RSApplicationRenderThreadDeathRecipient(wptr<RSRenderServiceConnection> conn)253 RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::RSApplicationRenderThreadDeathRecipient(
254     wptr<RSRenderServiceConnection> conn) : conn_(conn)
255 {}
256 
OnRemoteDied(const wptr<IRemoteObject> & token)257 void RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
258 {
259     auto tokenSptr = token.promote();
260     if (tokenSptr == nullptr) {
261         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: can't promote remote object.");
262         return;
263     }
264 
265     auto rsConn = conn_.promote();
266     if (rsConn == nullptr) {
267         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: "
268             "RSRenderServiceConnection was dead, do nothing.");
269         return;
270     }
271 
272     RS_LOGD("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: Unregister.");
273     auto app = iface_cast<IApplicationAgent>(tokenSptr);
274     rsConn->UnRegisterApplicationAgent(app);
275 }
276 
CommitTransaction(std::unique_ptr<RSTransactionData> & transactionData)277 void RSRenderServiceConnection::CommitTransaction(std::unique_ptr<RSTransactionData>& transactionData)
278 {
279     if (!mainThread_) {
280         return;
281     }
282     pid_t callingPid = GetCallingPid();
283     bool isTokenTypeValid = true;
284     bool isNonSystemAppCalling = false;
285     RSInterfaceCodeAccessVerifierBase::GetAccessType(isTokenTypeValid, isNonSystemAppCalling);
286     bool shouldDrop = RSUnmarshalThread::Instance().ReportTransactionDataStatistics(
287         callingPid, transactionData.get(), isNonSystemAppCalling);
288     if (shouldDrop) {
289         RS_LOGW("RSRenderServiceConnection::CommitTransaction data droped");
290         return;
291     }
292     bool isProcessBySingleFrame = mainThread_->IsNeedProcessBySingleFrameComposer(transactionData);
293     if (isProcessBySingleFrame) {
294         mainThread_->ProcessDataBySingleFrameComposer(transactionData);
295     } else {
296         mainThread_->RecvRSTransactionData(transactionData);
297     }
298 }
299 
ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask> & task)300 void RSRenderServiceConnection::ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask>& task)
301 {
302     if (task == nullptr || mainThread_ == nullptr) {
303         RS_LOGW("RSRenderServiceConnection::ExecuteSynchronousTask, task or main thread is null!");
304         return;
305     }
306     // After a synchronous task times out, it will no longer be executed.
307     auto isTimeout = std::make_shared<bool>(0);
308     std::weak_ptr<bool> isTimeoutWeak = isTimeout;
309     std::chrono::nanoseconds span(task->GetTimeout());
310     mainThread_->ScheduleTask([task, mainThread = mainThread_, isTimeoutWeak] {
311         if (task == nullptr || mainThread == nullptr || isTimeoutWeak.expired()) {
312             return;
313         }
314         task->Process(mainThread->GetContext());
315     }).wait_for(span);
316     isTimeout.reset();
317 }
318 
GetUniRenderEnabled()319 bool RSRenderServiceConnection::GetUniRenderEnabled()
320 {
321     return RSUniRenderJudgement::IsUniRender();
322 }
323 
CreateNode(const RSDisplayNodeConfig & displayNodeConfig,NodeId nodeId)324 bool RSRenderServiceConnection::CreateNode(const RSDisplayNodeConfig& displayNodeConfig, NodeId nodeId)
325 {
326     if (!mainThread_) {
327         return false;
328     }
329     std::shared_ptr<RSDisplayRenderNode> node =
330         DisplayNodeCommandHelper::CreateWithConfigInRS(mainThread_->GetContext(), nodeId,
331             displayNodeConfig);
332     if (node == nullptr) {
333         RS_LOGE("RSRenderService::CreateNode Failed.");
334         return false;
335     }
336     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this),
337         mirrorNodeId = displayNodeConfig.mirrorNodeId, isMirrored = displayNodeConfig.isMirrored]() -> void {
338         sptr<RSRenderServiceConnection> connection = weakThis.promote();
339         if (!connection) {
340             return;
341         }
342         auto& context = connection->mainThread_->GetContext();
343         context.GetMutableNodeMap().RegisterDisplayRenderNode(node);
344         context.GetGlobalRootRenderNode()->AddChild(node);
345         if (isMirrored) {
346             auto mirrorSourceNode = context.GetNodeMap()
347                 .GetRenderNode<RSDisplayRenderNode>(mirrorNodeId);
348             if (!mirrorSourceNode) {
349                 return;
350             }
351             node->SetMirrorSource(mirrorSourceNode);
352         }
353     };
354     mainThread_->PostSyncTask(registerNode);
355     return true;
356 }
357 
CreateNode(const RSSurfaceRenderNodeConfig & config)358 bool RSRenderServiceConnection::CreateNode(const RSSurfaceRenderNodeConfig& config)
359 {
360     if (!mainThread_) {
361         return false;
362     }
363     std::shared_ptr<RSSurfaceRenderNode> node =
364         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext());
365     if (node == nullptr) {
366         RS_LOGE("RSRenderService::CreateNode fail");
367         return false;
368     }
369     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
370         sptr<RSRenderServiceConnection> connection = weakThis.promote();
371         if (!connection) {
372             return;
373         }
374         connection->mainThread_->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
375     };
376     mainThread_->PostTask(registerNode);
377     return true;
378 }
379 
CreateNodeAndSurface(const RSSurfaceRenderNodeConfig & config)380 sptr<Surface> RSRenderServiceConnection::CreateNodeAndSurface(const RSSurfaceRenderNodeConfig& config)
381 {
382     if (!mainThread_) {
383         return nullptr;
384     }
385     std::shared_ptr<RSSurfaceRenderNode> node =
386         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext());
387     if (node == nullptr) {
388         RS_LOGE("RSRenderService::CreateNodeAndSurface CreateNode fail");
389         return nullptr;
390     }
391     sptr<IConsumerSurface> surface = IConsumerSurface::Create(config.name);
392     if (surface == nullptr) {
393         RS_LOGE("RSRenderService::CreateNodeAndSurface get consumer surface fail");
394         return nullptr;
395     }
396     const std::string& surfaceName = surface->GetName();
397     RS_LOGI("RsDebug RSRenderService::CreateNodeAndSurface node" \
398         "id:%{public}" PRIu64 " name:%{public}s bundleName:%{public}s surface id:%{public}" PRIu64 " name:%{public}s",
399         node->GetId(), node->GetName().c_str(), node->GetBundleName().c_str(),
400         surface->GetUniqueId(), surfaceName.c_str());
401     auto defaultUsage = surface->GetDefaultUsage();
402     surface->SetDefaultUsage(defaultUsage | BUFFER_USAGE_MEM_DMA | BUFFER_USAGE_HW_COMPOSER);
403     node->GetRSSurfaceHandler()->SetConsumer(surface);
404     RSMainThread* mainThread = mainThread_;
405     std::function<void()> registerNode = [node, mainThread]() -> void {
406         if (auto preNode = mainThread->GetContext().GetNodeMap().GetRenderNode(node->GetId())) {
407             RS_LOGE("CreateNodeAndSurface same id node:%{public}" PRIu64 ", type:%d",
408                 node->GetId(), preNode->GetType());
409             usleep(SLEEP_TIME_US);
410         }
411         mainThread->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
412     };
413     if (config.isSync) {
414         mainThread_->PostSyncTask(registerNode);
415     } else {
416         mainThread_->PostTask(registerNode, REGISTER_NODE, 0, AppExecFwk::EventQueue::Priority::VIP);
417     }
418     std::weak_ptr<RSSurfaceRenderNode> surfaceRenderNode(node);
419     sptr<IBufferConsumerListener> listener = new RSRenderServiceListener(surfaceRenderNode);
420     SurfaceError ret = surface->RegisterConsumerListener(listener);
421     if (ret != SURFACE_ERROR_OK) {
422         RS_LOGE("RSRenderService::CreateNodeAndSurface Register Consumer Listener fail");
423         return nullptr;
424     }
425     sptr<IBufferProducer> producer = surface->GetProducer();
426     sptr<Surface> pSurface = Surface::CreateSurfaceAsProducer(producer);
427     return pSurface;
428 }
429 
CreateVSyncConnection(const std::string & name,const sptr<VSyncIConnectionToken> & token,uint64_t id,NodeId windowNodeId,bool fromXcomponent)430 sptr<IVSyncConnection> RSRenderServiceConnection::CreateVSyncConnection(const std::string& name,
431                                                                         const sptr<VSyncIConnectionToken>& token,
432                                                                         uint64_t id,
433                                                                         NodeId windowNodeId,
434                                                                         bool fromXcomponent)
435 {
436     if (!mainThread_) {
437         return nullptr;
438     }
439     if (fromXcomponent) {
440         const auto& nodeMap = RSMainThread::Instance()->GetContext().GetNodeMap();
441         nodeMap.TraverseSurfaceNodes(
442             [this, &windowNodeId](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
443                 if (surfaceNode == nullptr || surfaceNode->GetRSSurfaceHandler() == nullptr ||
444                     surfaceNode->GetRSSurfaceHandler()->GetConsumer() == nullptr) {
445                     return;
446                 }
447                 if (surfaceNode->GetRSSurfaceHandler()->GetConsumer()->GetUniqueId() == windowNodeId) {
448                     windowNodeId = surfaceNode->GetInstanceRootNodeId();
449                     return;
450                 }
451             }
452         );
453     }
454     sptr<VSyncConnection> conn = new VSyncConnection(appVSyncDistributor_, name, token->AsObject(), 0, windowNodeId);
455     if (ExtractPid(id) == remotePid_) {
456         mainThread_->ScheduleTask([weakThis = wptr<RSRenderServiceConnection>(this), id]() {
457             sptr<RSRenderServiceConnection> connection = weakThis.promote();
458             if (!connection) {
459                 return;
460             }
461             auto linker = std::make_shared<RSRenderFrameRateLinker>(id);
462             auto& context = connection->mainThread_->GetContext();
463             auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
464             frameRateLinkerMap.RegisterFrameRateLinker(linker);
465         }).wait();
466         conn->id_ = id;
467     }
468     auto ret = appVSyncDistributor_->AddConnection(conn, windowNodeId);
469     if (ret != VSYNC_ERROR_OK) {
470         return nullptr;
471     }
472     return conn;
473 }
474 
CreatePixelMapFromSurface(sptr<Surface> surface,const Rect & srcRect)475 std::shared_ptr<Media::PixelMap> RSRenderServiceConnection::CreatePixelMapFromSurface(sptr<Surface> surface,
476     const Rect &srcRect)
477 {
478     OHOS::Media::Rect rect = {
479         .left = srcRect.x,
480         .top = srcRect.y,
481         .width = srcRect.w,
482         .height = srcRect.h,
483     };
484     std::shared_ptr<Media::PixelMap> pixelmap = nullptr;
485     RSBackgroundThread::Instance().PostSyncTask([surface, rect, &pixelmap]() {
486         pixelmap = OHOS::Rosen::CreatePixelMapFromSurface(surface, rect);
487     });
488     return pixelmap;
489 }
490 
SetFocusAppInfo(int32_t pid,int32_t uid,const std::string & bundleName,const std::string & abilityName,uint64_t focusNodeId)491 int32_t RSRenderServiceConnection::SetFocusAppInfo(
492     int32_t pid, int32_t uid, const std::string &bundleName, const std::string &abilityName, uint64_t focusNodeId)
493 {
494     if (mainThread_ == nullptr) {
495         return INVALID_ARGUMENTS;
496     }
497     mainThread_->ScheduleTask(
498         [pid, uid, bundleName, abilityName, focusNodeId, mainThread = mainThread_]() {
499             // don't use 'this' to get mainThread poninter
500             mainThread->SetFocusAppInfo(pid, uid, bundleName, abilityName, focusNodeId);
501         }
502     );
503     return SUCCESS;
504 }
505 
GetDefaultScreenId()506 ScreenId RSRenderServiceConnection::GetDefaultScreenId()
507 {
508     if (!screenManager_) {
509         return StatusCode::SCREEN_NOT_FOUND;
510     }
511     std::lock_guard<std::mutex> lock(mutex_);
512     return screenManager_->GetDefaultScreenId();
513 }
514 
GetActiveScreenId()515 ScreenId RSRenderServiceConnection::GetActiveScreenId()
516 {
517     if (!screenManager_) {
518         return StatusCode::SCREEN_NOT_FOUND;
519     }
520     std::lock_guard<std::mutex> lock(mutex_);
521     return screenManager_->GetActiveScreenId();
522 }
523 
GetAllScreenIds()524 std::vector<ScreenId> RSRenderServiceConnection::GetAllScreenIds()
525 {
526     std::vector<ScreenId> ids;
527     if (!screenManager_) {
528         return ids;
529     }
530     std::lock_guard<std::mutex> lock(mutex_);
531     return screenManager_->GetAllScreenIds();
532 }
533 
CreateVirtualScreen(const std::string & name,uint32_t width,uint32_t height,sptr<Surface> surface,ScreenId mirrorId,int32_t flags,std::vector<NodeId> whiteList)534 ScreenId RSRenderServiceConnection::CreateVirtualScreen(
535     const std::string &name,
536     uint32_t width,
537     uint32_t height,
538     sptr<Surface> surface,
539     ScreenId mirrorId,
540     int32_t flags,
541     std::vector<NodeId> whiteList)
542 {
543     if (!screenManager_) {
544         return StatusCode::SCREEN_NOT_FOUND;
545     }
546     std::lock_guard<std::mutex> lock(mutex_);
547     auto newVirtualScreenId = screenManager_->CreateVirtualScreen(
548         name, width, height, surface, mirrorId, flags, whiteList);
549     virtualScreenIds_.insert(newVirtualScreenId);
550     if (surface != nullptr) {
551         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ, name };
552         NotifyRefreshRateEvent(event);
553     }
554     return newVirtualScreenId;
555 }
556 
SetVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)557 int32_t RSRenderServiceConnection::SetVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
558 {
559     if (!screenManager_) {
560         return StatusCode::SCREEN_NOT_FOUND;
561     }
562     std::lock_guard<std::mutex> lock(mutex_);
563     if (blackListVector.empty()) {
564         RS_LOGW("SetVirtualScreenBlackList blackList is empty.");
565     }
566     return screenManager_->SetVirtualScreenBlackList(id, blackListVector);
567 }
568 
AddVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)569 int32_t RSRenderServiceConnection::AddVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
570 {
571     if (blackListVector.empty()) {
572         RS_LOGW("AddVirtualScreenBlackList blackList is empty.");
573         return StatusCode::BLACKLIST_IS_EMPTY;
574     }
575     std::lock_guard<std::mutex> lock(mutex_);
576     if (!screenManager_) {
577         return StatusCode::SCREEN_NOT_FOUND;
578     }
579     return screenManager_->AddVirtualScreenBlackList(id, blackListVector);
580 }
581 
RemoveVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)582 int32_t RSRenderServiceConnection::RemoveVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
583 {
584     if (blackListVector.empty()) {
585         RS_LOGW("RemoveVirtualScreenBlackList blackList is empty.");
586         return StatusCode::BLACKLIST_IS_EMPTY;
587     }
588     std::lock_guard<std::mutex> lock(mutex_);
589     if (!screenManager_) {
590         return StatusCode::SCREEN_NOT_FOUND;
591     }
592     return screenManager_->RemoveVirtualScreenBlackList(id, blackListVector);
593 }
594 
SetVirtualScreenSecurityExemptionList(ScreenId id,const std::vector<NodeId> & securityExemptionList)595 int32_t RSRenderServiceConnection::SetVirtualScreenSecurityExemptionList(
596     ScreenId id,
597     const std::vector<NodeId>& securityExemptionList)
598 {
599     if (!screenManager_) {
600         return StatusCode::SCREEN_NOT_FOUND;
601     }
602     return screenManager_->SetVirtualScreenSecurityExemptionList(id, securityExemptionList);
603 }
604 
SetCastScreenEnableSkipWindow(ScreenId id,bool enable)605 int32_t RSRenderServiceConnection::SetCastScreenEnableSkipWindow(ScreenId id, bool enable)
606 {
607     if (!screenManager_) {
608         return StatusCode::SCREEN_NOT_FOUND;
609     }
610     std::lock_guard<std::mutex> lock(mutex_);
611     return screenManager_->SetCastScreenEnableSkipWindow(id, enable);
612 }
613 
SetVirtualScreenSurface(ScreenId id,sptr<Surface> surface)614 int32_t RSRenderServiceConnection::SetVirtualScreenSurface(ScreenId id, sptr<Surface> surface)
615 {
616     if (!screenManager_) {
617         return StatusCode::SCREEN_NOT_FOUND;
618     }
619     std::lock_guard<std::mutex> lock(mutex_);
620     return screenManager_->SetVirtualScreenSurface(id, surface);
621 }
622 
RemoveVirtualScreen(ScreenId id)623 void RSRenderServiceConnection::RemoveVirtualScreen(ScreenId id)
624 {
625     if (!screenManager_) {
626         return;
627     }
628     std::lock_guard<std::mutex> lock(mutex_);
629     screenManager_->RemoveVirtualScreen(id);
630     virtualScreenIds_.erase(id);
631     EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
632     NotifyRefreshRateEvent(event);
633 }
634 
SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)635 int32_t RSRenderServiceConnection::SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)
636 {
637     if (!callback) {
638         return INVALID_ARGUMENTS;
639     }
640     std::unique_lock<std::mutex> lock(mutex_);
641     if (screenChangeCallback_ == callback) {
642         return INVALID_ARGUMENTS;
643     }
644 
645     if (screenChangeCallback_ != nullptr) {
646         // remove the old callback
647         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
648     }
649 
650     // update
651     int32_t status = screenManager_->AddScreenChangeCallback(callback);
652     auto tmp = screenChangeCallback_;
653     screenChangeCallback_ = callback;
654     lock.unlock();
655     return status;
656 }
657 
SetScreenActiveMode(ScreenId id,uint32_t modeId)658 void RSRenderServiceConnection::SetScreenActiveMode(ScreenId id, uint32_t modeId)
659 {
660     if (!screenManager_) {
661         return;
662     }
663     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
664     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
665         return RSHardwareThread::Instance().ScheduleTask(
666             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
667     } else {
668         return mainThread_->ScheduleTask(
669             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
670     }
671 }
672 
SetScreenRefreshRate(ScreenId id,int32_t sceneId,int32_t rate)673 void RSRenderServiceConnection::SetScreenRefreshRate(ScreenId id, int32_t sceneId, int32_t rate)
674 {
675     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetScreenRefreshRate");
676     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
677     int32_t setResult = hgmCore.SetScreenRefreshRate(id, sceneId, rate);
678     if (setResult != 0) {
679         RS_LOGW("SetScreenRefreshRate request of screen %{public}" PRIu64 " of rate %{public}d is refused",
680             id, rate);
681         return;
682     }
683     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
684 }
685 
SetRefreshRateMode(int32_t refreshRateMode)686 void RSRenderServiceConnection::SetRefreshRateMode(int32_t refreshRateMode)
687 {
688     if (!mainThread_) {
689         return;
690     }
691     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetRefreshRateMode");
692     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
693     int32_t setResult = hgmCore.SetRefreshRateMode(refreshRateMode);
694     RSSystemProperties::SetHgmRefreshRateModesEnabled(std::to_string(refreshRateMode));
695     if (setResult != 0) {
696         RS_LOGW("SetRefreshRateMode mode %{public}d is not supported", refreshRateMode);
697     }
698     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
699 }
700 
SyncFrameRateRange(FrameRateLinkerId id,const FrameRateRange & range,int32_t animatorExpectedFrameRate)701 void RSRenderServiceConnection::SyncFrameRateRange(FrameRateLinkerId id,
702     const FrameRateRange& range, int32_t animatorExpectedFrameRate)
703 {
704     if (!mainThread_) {
705         return;
706     }
707     mainThread_->ScheduleTask(
708         [weakThis = wptr<RSRenderServiceConnection>(this), id, &range, animatorExpectedFrameRate]() {
709             sptr<RSRenderServiceConnection> connection = weakThis.promote();
710             if (!connection) {
711                 return;
712             }
713             auto& context = connection->mainThread_->GetContext();
714             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
715             auto linker = linkerMap.GetFrameRateLinker(id);
716             if (linker == nullptr) {
717                 RS_LOGW("SyncFrameRateRange there is no frameRateLinker for id %{public}" PRIu64, id);
718                 return;
719             }
720             linker->SetExpectedRange(range);
721             linker->SetAnimatorExpectedFrameRate(animatorExpectedFrameRate);
722         }).wait();
723 }
724 
UnregisterFrameRateLinker(FrameRateLinkerId id)725 void RSRenderServiceConnection::UnregisterFrameRateLinker(FrameRateLinkerId id)
726 {
727     if (!mainThread_) {
728         return;
729     }
730     mainThread_->ScheduleTask(
731         [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
732             sptr<RSRenderServiceConnection> connection = weakThis.promote();
733             if (!connection) {
734                 return;
735             }
736             auto& context = connection->mainThread_->GetContext();
737             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
738             auto linker = linkerMap.GetFrameRateLinker(id);
739             if (linker == nullptr) {
740                 RS_LOGE("UnregisterFrameRateLinker there is no frameRateLinker for id %{public}" PRIu64, id);
741                 return;
742             }
743             linkerMap.UnregisterFrameRateLinker(id);
744         }).wait();
745 }
746 
GetScreenCurrentRefreshRate(ScreenId id)747 uint32_t RSRenderServiceConnection::GetScreenCurrentRefreshRate(ScreenId id)
748 {
749     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
750     uint32_t rate = hgmCore.GetScreenCurrentRefreshRate(id);
751     if (rate == 0) {
752         RS_LOGW("GetScreenCurrentRefreshRate failed to get current refreshrate of"
753             " screen : %{public}" PRIu64 "", id);
754     }
755     return rate;
756 }
757 
GetScreenSupportedRefreshRates(ScreenId id)758 std::vector<int32_t> RSRenderServiceConnection::GetScreenSupportedRefreshRates(ScreenId id)
759 {
760     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
761     std::vector<int32_t> rates = hgmCore.GetScreenComponentRefreshRates(id);
762     return rates;
763 }
764 
GetShowRefreshRateEnabled()765 bool RSRenderServiceConnection::GetShowRefreshRateEnabled()
766 {
767     return RSRealtimeRefreshRateManager::Instance().GetShowRefreshRateEnabled();
768 }
769 
SetShowRefreshRateEnabled(bool enable)770 void RSRenderServiceConnection::SetShowRefreshRateEnabled(bool enable)
771 {
772     return RSRealtimeRefreshRateManager::Instance().SetShowRefreshRateEnabled(enable);
773 }
774 
GetRefreshInfo(pid_t pid)775 std::string RSRenderServiceConnection::GetRefreshInfo(pid_t pid)
776 {
777     if (!mainThread_) {
778         return "";
779     }
780     auto& context = mainThread_->GetContext();
781     auto& nodeMap = context.GetMutableNodeMap();
782     std::string surfaceName = nodeMap.GetSelfDrawSurfaceNameByPid(pid);
783     if (surfaceName.empty()) {
784         return "";
785     }
786     std::string dumpString;
787     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
788     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
789         RSHardwareThread::Instance().ScheduleTask(
790             [this, &dumpString, &surfaceName]() { return screenManager_->FpsDump(dumpString, surfaceName); }).wait();
791     } else {
792         mainThread_->ScheduleTask(
793             [this, &dumpString, &surfaceName]() { return screenManager_->FpsDump(dumpString, surfaceName); }).wait();
794     }
795     return dumpString;
796 }
797 
GetCurrentRefreshRateMode()798 int32_t RSRenderServiceConnection::GetCurrentRefreshRateMode()
799 {
800     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
801     int32_t refreshRateMode = hgmCore.GetCurrentRefreshRateMode();
802     return refreshRateMode;
803 }
804 
SetVirtualScreenResolution(ScreenId id,uint32_t width,uint32_t height)805 int32_t RSRenderServiceConnection::SetVirtualScreenResolution(ScreenId id, uint32_t width, uint32_t height)
806 {
807     if (!screenManager_) {
808         return StatusCode::SCREEN_NOT_FOUND;
809     }
810     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
811     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
812         return RSHardwareThread::Instance().ScheduleTask(
813             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
814     } else {
815         return mainThread_->ScheduleTask(
816             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
817     }
818 }
819 
MarkPowerOffNeedProcessOneFrame()820 void RSRenderServiceConnection::MarkPowerOffNeedProcessOneFrame()
821 {
822     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
823     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
824         renderThread_.PostTask(
825             [weakThis = wptr<RSRenderServiceConnection>(this)]() {
826                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
827                 if (!connection) {
828                     return;
829                 }
830                 connection->screenManager_->MarkPowerOffNeedProcessOneFrame();
831             }
832         );
833     }
834 }
835 
DisablePowerOffRenderControl(ScreenId id)836 void RSRenderServiceConnection::DisablePowerOffRenderControl(ScreenId id)
837 {
838     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
839     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
840         renderThread_.PostTask(
841             [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
842                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
843                 if (!connection) {
844                     return;
845                 }
846                 connection->screenManager_->DisablePowerOffRenderControl(id);
847             }
848         );
849     }
850 }
851 
SetScreenPowerStatus(ScreenId id,ScreenPowerStatus status)852 void RSRenderServiceConnection::SetScreenPowerStatus(ScreenId id, ScreenPowerStatus status)
853 {
854     if (!screenManager_) {
855         return;
856     }
857     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
858     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
859         RSHardwareThread::Instance().ScheduleTask(
860             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
861         mainThread_->SetDiscardJankFrames(true);
862         renderThread_.SetDiscardJankFrames(true);
863         OHOS::Rosen::HgmCore::Instance().NotifyScreenPowerStatus(id, status);
864     } else {
865         mainThread_->ScheduleTask(
866             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
867     }
868 }
869 
870 namespace {
TakeSurfaceCaptureForUiParallel(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)871 void TakeSurfaceCaptureForUiParallel(
872     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
873 {
874     RS_LOGI("TakeSurfaceCaptureForUiParallel nodeId:[%{public}" PRIu64 "], issync:%{public}s", id,
875         captureConfig.isSync ? "true" : "false");
876     std::function<void()> captureTask = [id, callback, captureConfig]() {
877         RSUiCaptureTaskParallel::Capture(id, callback, captureConfig);
878     };
879 
880     if (captureConfig.isSync) {
881         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
882         return;
883     }
884 
885     auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
886     if (!node) {
887         RS_LOGE("RSRenderServiceConnection::TakeSurfaceCaptureForUiParallel node is nullptr");
888         callback->OnSurfaceCapture(id, nullptr);
889         return;
890     }
891 
892     if (node->IsOnTheTree() && !node->IsDirty() && !node->IsSubTreeDirty()) {
893         RSMainThread::Instance()->PostTask(captureTask);
894     } else {
895         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
896     }
897 }
898 
TakeSurfaceCaptureForUIWithUni(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)899 void TakeSurfaceCaptureForUIWithUni(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
900     const RSSurfaceCaptureConfig& captureConfig)
901 {
902     std::function<void()> offscreenRenderTask = [id, callback, captureConfig]() -> void {
903         RS_LOGD("RSRenderService::TakeSurfaceCaptureForUIWithUni callback->OnOffscreenRender"
904             " nodeId:[%{public}" PRIu64 "]", id);
905         ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCaptureForUIWithUni");
906         std::shared_ptr<RSUniUICapture> rsUniUICapture = std::make_shared<RSUniUICapture>(id, captureConfig);
907         std::shared_ptr<Media::PixelMap> pixelmap = rsUniUICapture->TakeLocalCapture();
908         callback->OnSurfaceCapture(id, pixelmap.get());
909         ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
910     };
911     if (!captureConfig.isSync) {
912         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
913     } else {
914         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
915         if (node == nullptr || !node->GetCommandExecuted()) {
916             RSOffscreenRenderThread::Instance().InSertCaptureTask(id, offscreenRenderTask);
917             return;
918         }
919         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
920         node->SetCommandExecuted(false);
921     }
922 }
923 }
924 
TakeSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,RSSurfaceCapturePermissions permissions)925 void RSRenderServiceConnection::TakeSurfaceCapture(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
926     const RSSurfaceCaptureConfig& captureConfig, RSSurfaceCapturePermissions permissions)
927 {
928     if (!mainThread_) {
929         return;
930     }
931     std::function<void()> captureTask = [id, callback, captureConfig,
932         screenCapturePermission = permissions.screenCapturePermission,
933         isSystemCalling = permissions.isSystemCalling,
934         selfCapture = permissions.selfCapture]() -> void {
935         if (captureConfig.captureType == SurfaceCaptureType::UICAPTURE) {
936             // When the isSync flag in captureConfig is true, UI capture processes commands before capture.
937             // When the isSync flag in captureConfig is false, UI capture will check null node independently.
938             // Therefore, a null node is valid for UI capture.
939             auto uiCaptureHasPermission = selfCapture || isSystemCalling;
940             if (!uiCaptureHasPermission) {
941                 RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture uicapture failed, nodeId:[%{public}" PRIu64
942                         "], isSystemCalling: %{public}u, selfCapture: %{public}u",
943                     id, isSystemCalling, selfCapture);
944                 callback->OnSurfaceCapture(id, nullptr);
945                 return;
946             }
947             if (RSUniRenderJudgement::IsUniRender()) {
948                 TakeSurfaceCaptureForUiParallel(id, callback, captureConfig);
949             } else {
950                 TakeSurfaceCaptureForUIWithUni(id, callback, captureConfig);
951             }
952             return;
953         }
954         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
955         if (node == nullptr) {
956             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node is nullptr");
957             callback->OnSurfaceCapture(id, nullptr);
958             return;
959         }
960         auto displayCaptureHasPermission = screenCapturePermission && isSystemCalling;
961         auto surfaceCaptureHasPermission = selfCapture || isSystemCalling;
962         if ((node->GetType() == RSRenderNodeType::DISPLAY_NODE && !displayCaptureHasPermission) ||
963             (node->GetType() == RSRenderNodeType::SURFACE_NODE && !surfaceCaptureHasPermission)) {
964             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node type: %{public}u, "
965                 "screenCapturePermission: %{public}u, isSystemCalling: %{public}u, selfCapture: %{public}u",
966                 node->GetType(), screenCapturePermission, isSystemCalling, selfCapture);
967             callback->OnSurfaceCapture(id, nullptr);
968             return;
969         }
970         if (RSUniRenderJudgement::GetUniRenderEnabledType() == UniRenderEnabledType::UNI_RENDER_DISABLED) {
971             RS_LOGD("RSRenderService::TakeSurfaceCapture captureTaskInner nodeId:[%{public}" PRIu64 "]", id);
972             ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCapture");
973             RSSurfaceCaptureTask task(id, captureConfig);
974             if (!task.Run(callback)) {
975                 callback->OnSurfaceCapture(id, nullptr);
976             }
977             ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
978         } else {
979             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
980             RSSurfaceCaptureTaskParallel::Capture(id, callback, captureConfig, isSystemCalling);
981         }
982     };
983     mainThread_->PostTask(captureTask);
984 }
985 
SetWindowFreezeImmediately(NodeId id,bool isFreeze,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)986 void RSRenderServiceConnection::SetWindowFreezeImmediately(
987     NodeId id, bool isFreeze, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
988 {
989     if (!mainThread_) {
990         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
991         return;
992     }
993     std::function<void()> setWindowFreezeTask = [id, isFreeze, callback, captureConfig]() -> void {
994         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
995         if (node == nullptr) {
996             RS_LOGE("RSRenderServiceConnection::SetWindowFreezeImmediately failed, node is nullptr");
997             if (callback) {
998                 callback->OnSurfaceCapture(id, nullptr);
999             }
1000             return;
1001         }
1002         node->SetStaticCached(isFreeze);
1003         if (isFreeze) {
1004             bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1005                 RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ +
1006                 "::SET_WINDOW_FREEZE_IMMEDIATELY");
1007             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1008             RSSurfaceCaptureTaskParallel::Capture(id, callback, captureConfig, isSystemCalling, isFreeze);
1009         } else {
1010             RSSurfaceCaptureTaskParallel::ClearCacheImageByFreeze(id);
1011         }
1012     };
1013     mainThread_->PostTask(setWindowFreezeTask);
1014 }
1015 
RegisterApplicationAgent(uint32_t pid,sptr<IApplicationAgent> app)1016 void RSRenderServiceConnection::RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app)
1017 {
1018     if (!mainThread_) {
1019         return;
1020     }
1021     auto captureTask = [weakThis = wptr<RSRenderServiceConnection>(this), pid, app]() -> void {
1022         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1023         if (!connection) {
1024             return;
1025         }
1026         connection->mainThread_->RegisterApplicationAgent(pid, app);
1027     };
1028     mainThread_->PostTask(captureTask);
1029 
1030     app->AsObject()->AddDeathRecipient(ApplicationDeathRecipient_);
1031 }
1032 
UnRegisterApplicationAgent(sptr<IApplicationAgent> app)1033 void RSRenderServiceConnection::UnRegisterApplicationAgent(sptr<IApplicationAgent> app)
1034 {
1035     auto captureTask = [app]() -> void {
1036         RSMainThread::Instance()->UnRegisterApplicationAgent(app);
1037     };
1038     RSMainThread::Instance()->ScheduleTask(captureTask).wait();
1039 }
1040 
GetVirtualScreenResolution(ScreenId id)1041 RSVirtualScreenResolution RSRenderServiceConnection::GetVirtualScreenResolution(ScreenId id)
1042 {
1043     RSVirtualScreenResolution virtualScreenResolution;
1044     if (!screenManager_) {
1045         return virtualScreenResolution;
1046     }
1047     screenManager_->GetVirtualScreenResolution(id, virtualScreenResolution);
1048     return virtualScreenResolution;
1049 }
1050 
GetScreenActiveMode(ScreenId id)1051 RSScreenModeInfo RSRenderServiceConnection::GetScreenActiveMode(ScreenId id)
1052 {
1053     RSScreenModeInfo screenModeInfo;
1054     if (!screenManager_) {
1055         return screenModeInfo;
1056     }
1057     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1058     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1059         RSHardwareThread::Instance().ScheduleTask(
1060             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1061     } else {
1062         mainThread_->ScheduleTask(
1063             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1064     }
1065     return screenModeInfo;
1066 }
1067 
GetTotalAppMemSize(float & cpuMemSize,float & gpuMemSize)1068 bool RSRenderServiceConnection::GetTotalAppMemSize(float& cpuMemSize, float& gpuMemSize)
1069 {
1070     RSMainThread::Instance()->GetAppMemoryInMB(cpuMemSize, gpuMemSize);
1071     gpuMemSize += RSSubThreadManager::Instance()->GetAppGpuMemoryInMB();
1072     return true;
1073 }
1074 
GetMemoryGraphic(int pid)1075 MemoryGraphic RSRenderServiceConnection::GetMemoryGraphic(int pid)
1076 {
1077     MemoryGraphic memoryGraphic;
1078     if (!mainThread_) {
1079         return memoryGraphic;
1080     }
1081     if (GetUniRenderEnabled()) {
1082         RSMainThread* mainThread = mainThread_;
1083         mainThread_->ScheduleTask([mainThread, &pid, &memoryGraphic]() {
1084             if (RSMainThread::Instance()->GetContext().GetNodeMap().ContainPid(pid)) {
1085                 mainThread->CountMem(pid, memoryGraphic);
1086             }
1087         }).wait();
1088         return memoryGraphic;
1089     } else {
1090         return memoryGraphic;
1091     }
1092 }
1093 
GetMemoryGraphics()1094 std::vector<MemoryGraphic> RSRenderServiceConnection::GetMemoryGraphics()
1095 {
1096     std::vector<MemoryGraphic> memoryGraphics;
1097     if (!mainThread_) {
1098         return memoryGraphics;
1099     }
1100     if (GetUniRenderEnabled()) {
1101         mainThread_->ScheduleTask(
1102             [weakThis = wptr<RSRenderServiceConnection>(this), &memoryGraphics]() {
1103                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1104                 if (!connection) {
1105                     return;
1106                 }
1107                 return connection->mainThread_->CountMem(memoryGraphics);
1108             }).wait();
1109         return memoryGraphics;
1110     } else {
1111         return memoryGraphics;
1112     }
1113 }
1114 
GetScreenSupportedModes(ScreenId id)1115 std::vector<RSScreenModeInfo> RSRenderServiceConnection::GetScreenSupportedModes(ScreenId id)
1116 {
1117     std::vector<RSScreenModeInfo> screenSupportedModes;
1118     if (!screenManager_) {
1119         return screenSupportedModes;
1120     }
1121     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1122     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1123         return RSHardwareThread::Instance().ScheduleTask(
1124             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1125     } else {
1126         return mainThread_->ScheduleTask(
1127             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1128     }
1129 }
1130 
GetScreenCapability(ScreenId id)1131 RSScreenCapability RSRenderServiceConnection::GetScreenCapability(ScreenId id)
1132 {
1133     RSScreenCapability screenCapability;
1134     if (!screenManager_) {
1135         return screenCapability;
1136     }
1137     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1138     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1139         return RSHardwareThread::Instance().ScheduleTask(
1140             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1141     } else {
1142         return mainThread_->ScheduleTask(
1143             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1144     }
1145 }
1146 
GetScreenPowerStatus(ScreenId id)1147 ScreenPowerStatus RSRenderServiceConnection::GetScreenPowerStatus(ScreenId id)
1148 {
1149     if (!screenManager_) {
1150         return ScreenPowerStatus::INVALID_POWER_STATUS;
1151     }
1152     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1153     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1154         return RSHardwareThread::Instance().ScheduleTask(
1155             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1156     } else {
1157         return mainThread_->ScheduleTask(
1158             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1159     }
1160 }
1161 
GetScreenData(ScreenId id)1162 RSScreenData RSRenderServiceConnection::GetScreenData(ScreenId id)
1163 {
1164     RSScreenData screenData;
1165     if (!screenManager_) {
1166         return screenData;
1167     }
1168     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1169     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1170         return RSHardwareThread::Instance().ScheduleTask(
1171             [=]() { return screenManager_->GetScreenData(id); }).get();
1172     } else {
1173         return mainThread_->ScheduleTask(
1174             [=]() { return screenManager_->GetScreenData(id); }).get();
1175     }
1176 }
1177 
GetScreenBacklight(ScreenId id)1178 int32_t RSRenderServiceConnection::GetScreenBacklight(ScreenId id)
1179 {
1180     if (!screenManager_) {
1181         return INVALID_BACKLIGHT_VALUE;
1182     }
1183     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1184     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1185         return RSHardwareThread::Instance().ScheduleTask(
1186             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1187     } else {
1188         return mainThread_->ScheduleTask(
1189             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1190     }
1191 }
1192 
SetScreenBacklight(ScreenId id,uint32_t level)1193 void RSRenderServiceConnection::SetScreenBacklight(ScreenId id, uint32_t level)
1194 {
1195     if (!screenManager_) {
1196         return;
1197     }
1198     RSLuminanceControl::Get().SetSdrLuminance(id, level);
1199     if (RSLuminanceControl::Get().IsHdrOn(id) && level > 0) {
1200         auto task = [weakThis = wptr<RSRenderServiceConnection>(this)]() {
1201             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1202             if (!connection) {
1203                 RS_LOGE("RSRenderServiceConnection::SetScreenBacklight fail");
1204                 return;
1205             }
1206             connection->mainThread_->SetForceUpdateUniRenderFlag(true);
1207             connection->mainThread_->SetLuminanceChangingStatus(true);
1208             connection->mainThread_->SetDirtyFlag();
1209             connection->mainThread_->RequestNextVSync();
1210         };
1211         mainThread_->PostTask(task);
1212         return;
1213     }
1214 
1215     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1216     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1217         screenManager_->SetScreenBacklight(id, level);
1218     } else {
1219         mainThread_->ScheduleTask(
1220             [=]() { screenManager_->SetScreenBacklight(id, level); }).wait();
1221     }
1222 }
1223 
RegisterBufferClearListener(NodeId id,sptr<RSIBufferClearCallback> callback)1224 void RSRenderServiceConnection::RegisterBufferClearListener(
1225     NodeId id, sptr<RSIBufferClearCallback> callback)
1226 {
1227     if (!mainThread_) {
1228         return;
1229     }
1230     auto registerBufferClearListener =
1231         [id, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1232             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1233             if (!connection) {
1234                 return false;
1235             }
1236             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1237                 node->RegisterBufferClearListener(callback);
1238                 return true;
1239             }
1240             return false;
1241     };
1242     if (!registerBufferClearListener()) {
1243         mainThread_->PostTask(registerBufferClearListener);
1244     }
1245 }
1246 
RegisterBufferAvailableListener(NodeId id,sptr<RSIBufferAvailableCallback> callback,bool isFromRenderThread)1247 void RSRenderServiceConnection::RegisterBufferAvailableListener(
1248     NodeId id, sptr<RSIBufferAvailableCallback> callback, bool isFromRenderThread)
1249 {
1250     if (!mainThread_) {
1251         return;
1252     }
1253     auto registerBufferAvailableListener =
1254         [id, callback, isFromRenderThread, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1255             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1256             if (!connection) {
1257                 return false;
1258             }
1259             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1260                 node->RegisterBufferAvailableListener(callback, isFromRenderThread);
1261                 return true;
1262             }
1263             return false;
1264     };
1265     mainThread_->PostTask(registerBufferAvailableListener);
1266 }
1267 
GetScreenSupportedColorGamuts(ScreenId id,std::vector<ScreenColorGamut> & mode)1268 int32_t RSRenderServiceConnection::GetScreenSupportedColorGamuts(ScreenId id, std::vector<ScreenColorGamut>& mode)
1269 {
1270     if (!screenManager_) {
1271         return StatusCode::SCREEN_NOT_FOUND;
1272     }
1273     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1274     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1275         return RSHardwareThread::Instance().ScheduleTask(
1276             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1277     } else {
1278         return mainThread_->ScheduleTask(
1279             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1280     }
1281 }
1282 
GetScreenSupportedMetaDataKeys(ScreenId id,std::vector<ScreenHDRMetadataKey> & keys)1283 int32_t RSRenderServiceConnection::GetScreenSupportedMetaDataKeys(ScreenId id, std::vector<ScreenHDRMetadataKey>& keys)
1284 {
1285     if (!screenManager_) {
1286         return StatusCode::SCREEN_NOT_FOUND;
1287     }
1288     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1289     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1290         return RSHardwareThread::Instance().ScheduleTask(
1291             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1292     } else {
1293         return mainThread_->ScheduleTask(
1294             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1295     }
1296 }
1297 
GetScreenColorGamut(ScreenId id,ScreenColorGamut & mode)1298 int32_t RSRenderServiceConnection::GetScreenColorGamut(ScreenId id, ScreenColorGamut& mode)
1299 {
1300     if (!screenManager_) {
1301         return StatusCode::SCREEN_NOT_FOUND;
1302     }
1303     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1304     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1305         return RSHardwareThread::Instance().ScheduleTask(
1306             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1307     } else {
1308         return mainThread_->ScheduleTask(
1309             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1310     }
1311 }
1312 
SetScreenColorGamut(ScreenId id,int32_t modeIdx)1313 int32_t RSRenderServiceConnection::SetScreenColorGamut(ScreenId id, int32_t modeIdx)
1314 {
1315     if (!screenManager_) {
1316         return StatusCode::SCREEN_NOT_FOUND;
1317     }
1318     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1319     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1320         return RSHardwareThread::Instance().ScheduleTask(
1321             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1322     } else {
1323         return mainThread_->ScheduleTask(
1324             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1325     }
1326 }
1327 
SetScreenGamutMap(ScreenId id,ScreenGamutMap mode)1328 int32_t RSRenderServiceConnection::SetScreenGamutMap(ScreenId id, ScreenGamutMap mode)
1329 {
1330     if (!screenManager_) {
1331         return StatusCode::SCREEN_NOT_FOUND;
1332     }
1333     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1334     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1335         return RSHardwareThread::Instance().ScheduleTask(
1336             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1337     } else {
1338         return mainThread_->ScheduleTask(
1339             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1340     }
1341 }
1342 
SetScreenCorrection(ScreenId id,ScreenRotation screenRotation)1343 int32_t RSRenderServiceConnection::SetScreenCorrection(ScreenId id, ScreenRotation screenRotation)
1344 {
1345     if (!screenManager_) {
1346         return StatusCode::SCREEN_NOT_FOUND;
1347     }
1348     std::lock_guard<std::mutex> lock(mutex_);
1349     return screenManager_->SetScreenCorrection(id, screenRotation);
1350 }
1351 
SetVirtualMirrorScreenCanvasRotation(ScreenId id,bool canvasRotation)1352 bool RSRenderServiceConnection::SetVirtualMirrorScreenCanvasRotation(ScreenId id, bool canvasRotation)
1353 {
1354     if (!screenManager_) {
1355         return false;
1356     }
1357     std::lock_guard<std::mutex> lock(mutex_);
1358     return screenManager_->SetVirtualMirrorScreenCanvasRotation(id, canvasRotation);
1359 }
1360 
SetGlobalDarkColorMode(bool isDark)1361 bool RSRenderServiceConnection::SetGlobalDarkColorMode(bool isDark)
1362 {
1363     if (!mainThread_) {
1364         return false;
1365     }
1366     std::lock_guard<std::mutex> lock(mutex_);
1367     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isDark]() {
1368         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1369         if (!connection) {
1370             RS_LOGE("RSRenderServiceConnection::SetGlobalDarkColorMode fail");
1371             return;
1372         }
1373         connection->mainThread_->SetGlobalDarkColorMode(isDark);
1374     };
1375     mainThread_->PostTask(task);
1376     return true;
1377 }
1378 
SetVirtualMirrorScreenScaleMode(ScreenId id,ScreenScaleMode scaleMode)1379 bool RSRenderServiceConnection::SetVirtualMirrorScreenScaleMode(ScreenId id, ScreenScaleMode scaleMode)
1380 {
1381     if (!screenManager_) {
1382         return false;
1383     }
1384     std::lock_guard<std::mutex> lock(mutex_);
1385     return screenManager_->SetVirtualMirrorScreenScaleMode(id, scaleMode);
1386 }
1387 
GetScreenGamutMap(ScreenId id,ScreenGamutMap & mode)1388 int32_t RSRenderServiceConnection::GetScreenGamutMap(ScreenId id, ScreenGamutMap& mode)
1389 {
1390     if (!screenManager_) {
1391         return StatusCode::SCREEN_NOT_FOUND;
1392     }
1393     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1394     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1395         return RSHardwareThread::Instance().ScheduleTask(
1396             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1397     } else {
1398         return mainThread_->ScheduleTask(
1399             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1400     }
1401 }
1402 
GetScreenHDRCapability(ScreenId id,RSScreenHDRCapability & screenHdrCapability)1403 int32_t RSRenderServiceConnection::GetScreenHDRCapability(ScreenId id, RSScreenHDRCapability& screenHdrCapability)
1404 {
1405     if (!screenManager_) {
1406         return StatusCode::SCREEN_NOT_FOUND;
1407     }
1408     std::lock_guard<std::mutex> lock(mutex_);
1409     return screenManager_->GetScreenHDRCapability(id, screenHdrCapability);
1410 }
1411 
GetPixelFormat(ScreenId id,GraphicPixelFormat & pixelFormat)1412 int32_t RSRenderServiceConnection::GetPixelFormat(ScreenId id, GraphicPixelFormat& pixelFormat)
1413 {
1414     if (!screenManager_) {
1415         return StatusCode::SCREEN_NOT_FOUND;
1416     }
1417     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1418     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1419         return RSHardwareThread::Instance().ScheduleTask(
1420             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1421     } else {
1422         return mainThread_->ScheduleTask(
1423             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1424     }
1425 }
1426 
SetPixelFormat(ScreenId id,GraphicPixelFormat pixelFormat)1427 int32_t RSRenderServiceConnection::SetPixelFormat(ScreenId id, GraphicPixelFormat pixelFormat)
1428 {
1429     if (!screenManager_) {
1430         return StatusCode::SCREEN_NOT_FOUND;
1431     }
1432     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1433     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1434         return RSHardwareThread::Instance().ScheduleTask(
1435             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1436     } else {
1437         return mainThread_->ScheduleTask(
1438             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1439     }
1440 }
1441 
GetScreenSupportedHDRFormats(ScreenId id,std::vector<ScreenHDRFormat> & hdrFormats)1442 int32_t RSRenderServiceConnection::GetScreenSupportedHDRFormats(ScreenId id, std::vector<ScreenHDRFormat>& hdrFormats)
1443 {
1444     if (!screenManager_) {
1445         return StatusCode::SCREEN_NOT_FOUND;
1446     }
1447     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1448     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1449         return RSHardwareThread::Instance().ScheduleTask(
1450             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1451     } else {
1452         return mainThread_->ScheduleTask(
1453             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1454     }
1455 }
1456 
GetScreenHDRFormat(ScreenId id,ScreenHDRFormat & hdrFormat)1457 int32_t RSRenderServiceConnection::GetScreenHDRFormat(ScreenId id, ScreenHDRFormat& hdrFormat)
1458 {
1459     if (!screenManager_) {
1460         return StatusCode::SCREEN_NOT_FOUND;
1461     }
1462     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1463     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1464         return RSHardwareThread::Instance().ScheduleTask(
1465             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1466     } else {
1467         return mainThread_->ScheduleTask(
1468             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1469     }
1470 }
1471 
SetScreenHDRFormat(ScreenId id,int32_t modeIdx)1472 int32_t RSRenderServiceConnection::SetScreenHDRFormat(ScreenId id, int32_t modeIdx)
1473 {
1474     if (!screenManager_) {
1475         return StatusCode::SCREEN_NOT_FOUND;
1476     }
1477     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1478     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1479         return RSHardwareThread::Instance().ScheduleTask(
1480             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1481     } else {
1482         return mainThread_->ScheduleTask(
1483             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1484     }
1485 }
1486 
GetScreenSupportedColorSpaces(ScreenId id,std::vector<GraphicCM_ColorSpaceType> & colorSpaces)1487 int32_t RSRenderServiceConnection::GetScreenSupportedColorSpaces(
1488     ScreenId id, std::vector<GraphicCM_ColorSpaceType>& colorSpaces)
1489 {
1490     if (!screenManager_) {
1491         return StatusCode::SCREEN_NOT_FOUND;
1492     }
1493     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1494     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1495         return RSHardwareThread::Instance().ScheduleTask(
1496             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
1497     } else {
1498         return mainThread_->ScheduleTask(
1499             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
1500     }
1501 }
1502 
GetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType & colorSpace)1503 int32_t RSRenderServiceConnection::GetScreenColorSpace(ScreenId id, GraphicCM_ColorSpaceType& colorSpace)
1504 {
1505     if (!screenManager_) {
1506         return StatusCode::SCREEN_NOT_FOUND;
1507     }
1508     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1509     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1510         return RSHardwareThread::Instance().ScheduleTask(
1511             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
1512     } else {
1513         return mainThread_->ScheduleTask(
1514             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
1515     }
1516 }
1517 
SetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType colorSpace)1518 int32_t RSRenderServiceConnection::SetScreenColorSpace(ScreenId id, GraphicCM_ColorSpaceType colorSpace)
1519 {
1520     if (!screenManager_) {
1521         return StatusCode::SCREEN_NOT_FOUND;
1522     }
1523     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1524     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1525         return RSHardwareThread::Instance().ScheduleTask(
1526             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
1527     } else {
1528         return mainThread_->ScheduleTask(
1529             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
1530     }
1531 }
1532 
GetScreenType(ScreenId id,RSScreenType & screenType)1533 int32_t RSRenderServiceConnection::GetScreenType(ScreenId id, RSScreenType& screenType)
1534 {
1535     if (!screenManager_) {
1536         return StatusCode::SCREEN_NOT_FOUND;
1537     }
1538     std::lock_guard<std::mutex> lock(mutex_);
1539     return screenManager_->GetScreenType(id, screenType);
1540 }
1541 
GetBitmap(NodeId id,Drawing::Bitmap & bitmap)1542 bool RSRenderServiceConnection::GetBitmap(NodeId id, Drawing::Bitmap& bitmap)
1543 {
1544     if (!mainThread_) {
1545         return false;
1546     }
1547     std::promise<bool> result;
1548     std::future<bool> future = result.get_future();
1549     RSMainThread* mainThread = mainThread_;
1550     RSUniRenderThread* renderThread = &renderThread_;
1551     auto getBitmapTask = [id, &bitmap, mainThread, renderThread, &result]() {
1552         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
1553         if (node == nullptr) {
1554             RS_LOGE("RSRenderServiceConnection::GetBitmap cannot find NodeId: [%{public}" PRIu64 "]", id);
1555             result.set_value(false);
1556             return;
1557         }
1558         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
1559             RS_LOGE("RSRenderServiceConnection::GetBitmap RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
1560             result.set_value(false);
1561             return;
1562         }
1563         auto grContext = renderThread->GetRenderEngine()->GetRenderContext()->GetDrGPUContext();
1564         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
1565         auto getDrawableBitmapTask = [drawableNode, &bitmap, grContext, &result]() {
1566             bitmap = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)
1567                 ->GetBitmap(grContext);
1568             result.set_value(!bitmap.IsEmpty());
1569         };
1570         renderThread->PostTask(getDrawableBitmapTask);
1571     };
1572     mainThread_->PostTask(getBitmapTask);
1573     return future.get();
1574 }
1575 
GetPixelmap(NodeId id,const std::shared_ptr<Media::PixelMap> pixelmap,const Drawing::Rect * rect,std::shared_ptr<Drawing::DrawCmdList> drawCmdList)1576 bool RSRenderServiceConnection::GetPixelmap(NodeId id, const std::shared_ptr<Media::PixelMap> pixelmap,
1577     const Drawing::Rect* rect, std::shared_ptr<Drawing::DrawCmdList> drawCmdList)
1578 {
1579     if (!mainThread_) {
1580         return false;
1581     }
1582     std::promise<bool> result;
1583     std::future<bool> future = result.get_future();
1584     RSMainThread* mainThread = mainThread_;
1585     RSUniRenderThread* renderThread = &renderThread_;
1586     auto getPixelMapTask = [id, pixelmap, rect, drawCmdList, mainThread, renderThread, &result]() {
1587         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
1588         if (node == nullptr) {
1589             RS_LOGD("RSRenderServiceConnection::GetPixelmap: cannot find NodeId: [%{public}" PRIu64 "]", id);
1590             result.set_value(false);
1591             return;
1592         }
1593         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
1594             RS_LOGE("RSRenderServiceConnection::GetPixelmap: RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
1595             result.set_value(false);
1596             return;
1597         }
1598 
1599         auto tid = node->GetTid(); // planning: id may change in subthread
1600         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
1601         if (drawableNode) {
1602             tid = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->GetTid();
1603         }
1604         auto getDrawablePixelmapTask = [drawableNode, pixelmap, rect, &result, tid, drawCmdList]() {
1605             result.set_value(std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->
1606                 GetPixelmap(pixelmap, rect, tid, drawCmdList));
1607         };
1608         if (!node->IsOnTheTree()) {
1609             node->ClearOp();
1610         }
1611         if (tid == UNI_MAIN_THREAD_INDEX) {
1612             if (!mainThread->IsIdle() && mainThread->GetContext().HasActiveNode(node)) {
1613                 result.set_value(false);
1614                 return;
1615             }
1616             result.set_value(node->GetPixelmap(pixelmap, rect, tid, drawCmdList));
1617         } else if (tid == UNI_RENDER_THREAD_INDEX) {
1618             renderThread->PostTask(getDrawablePixelmapTask);
1619         } else {
1620             RSTaskDispatcher::GetInstance().PostTask(
1621                 RSSubThreadManager::Instance()->GetReThreadIndexMap()[tid], getDrawablePixelmapTask, false);
1622         }
1623     };
1624     mainThread_->PostTask(getPixelMapTask);
1625     return future.get();
1626 }
1627 
RegisterTypeface(uint64_t globalUniqueId,std::shared_ptr<Drawing::Typeface> & typeface)1628 bool RSRenderServiceConnection::RegisterTypeface(uint64_t globalUniqueId,
1629     std::shared_ptr<Drawing::Typeface>& typeface)
1630 {
1631     RS_LOGD("RSRenderServiceConnection::RegisterTypeface: pid[%{public}d] register typeface[%{public}u]",
1632         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
1633     RSTypefaceCache::Instance().CacheDrawingTypeface(globalUniqueId, typeface);
1634     return true;
1635 }
1636 
UnRegisterTypeface(uint64_t globalUniqueId)1637 bool RSRenderServiceConnection::UnRegisterTypeface(uint64_t globalUniqueId)
1638 {
1639     RS_LOGD("RSRenderServiceConnection::UnRegisterTypeface: pid[%{public}d] unregister typeface[%{public}u]",
1640         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
1641     RSTypefaceCache::Instance().AddDelayDestroyQueue(globalUniqueId);
1642     return true;
1643 }
1644 
SetScreenSkipFrameInterval(ScreenId id,uint32_t skipFrameInterval)1645 int32_t RSRenderServiceConnection::SetScreenSkipFrameInterval(ScreenId id, uint32_t skipFrameInterval)
1646 {
1647     if (!screenManager_) {
1648         return StatusCode::SCREEN_NOT_FOUND;
1649     }
1650     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1651     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1652         return RSHardwareThread::Instance().ScheduleTask(
1653             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
1654     } else {
1655         return mainThread_->ScheduleTask(
1656             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
1657     }
1658 }
1659 
SetVirtualScreenRefreshRate(ScreenId id,uint32_t maxRefreshRate,uint32_t & actualRefreshRate)1660 int32_t RSRenderServiceConnection::SetVirtualScreenRefreshRate(
1661     ScreenId id, uint32_t maxRefreshRate, uint32_t& actualRefreshRate)
1662 {
1663     if (!screenManager_) {
1664         return StatusCode::SCREEN_NOT_FOUND;
1665     }
1666     return screenManager_->SetVirtualScreenRefreshRate(id, maxRefreshRate, actualRefreshRate);
1667 }
1668 
RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)1669 int32_t RSRenderServiceConnection::RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)
1670 {
1671     if (!mainThread_) {
1672         return StatusCode::INVALID_ARGUMENTS;
1673     }
1674     std::lock_guard<std::mutex> lock(mutex_);
1675     if (!callback) {
1676         RS_LOGD("RSRenderServiceConnection::RegisterOcclusionChangeCallback: callback is nullptr");
1677         return StatusCode::INVALID_ARGUMENTS;
1678     }
1679     mainThread_->RegisterOcclusionChangeCallback(remotePid_, callback);
1680     return StatusCode::SUCCESS;
1681 }
1682 
RegisterSurfaceOcclusionChangeCallback(NodeId id,sptr<RSISurfaceOcclusionChangeCallback> callback,std::vector<float> & partitionPoints)1683 int32_t RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback(
1684     NodeId id, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints)
1685 {
1686     if (!mainThread_) {
1687         return StatusCode::INVALID_ARGUMENTS;
1688     }
1689     std::lock_guard<std::mutex> lock(mutex_);
1690     if (!callback) {
1691         RS_LOGD("RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback: callback is nullptr");
1692         return StatusCode::INVALID_ARGUMENTS;
1693     }
1694     mainThread_->RegisterSurfaceOcclusionChangeCallback(id, remotePid_, callback, partitionPoints);
1695     return StatusCode::SUCCESS;
1696 }
1697 
UnRegisterSurfaceOcclusionChangeCallback(NodeId id)1698 int32_t RSRenderServiceConnection::UnRegisterSurfaceOcclusionChangeCallback(NodeId id)
1699 {
1700     if (!mainThread_) {
1701         return StatusCode::INVALID_ARGUMENTS;
1702     }
1703     std::lock_guard<std::mutex> lock(mutex_);
1704     mainThread_->UnRegisterSurfaceOcclusionChangeCallback(id);
1705     return StatusCode::SUCCESS;
1706 }
1707 
RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)1708 int32_t RSRenderServiceConnection::RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)
1709 {
1710     std::lock_guard<std::mutex> lock(mutex_);
1711     if (!callback) {
1712         RS_LOGD("RSRenderServiceConnection::RegisterHgmConfigChangeCallback: callback is nullptr");
1713         return StatusCode::INVALID_ARGUMENTS;
1714     }
1715 
1716     HgmConfigCallbackManager::GetInstance()->RegisterHgmConfigChangeCallback(remotePid_, callback);
1717     return StatusCode::SUCCESS;
1718 }
1719 
RegisterHgmRefreshRateModeChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)1720 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback(
1721     sptr<RSIHgmConfigChangeCallback> callback)
1722 {
1723     std::lock_guard<std::mutex> lock(mutex_);
1724     if (!callback) {
1725         RS_LOGD("RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback: callback is nullptr");
1726         return StatusCode::INVALID_ARGUMENTS;
1727     }
1728 
1729     HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateModeChangeCallback(remotePid_, callback);
1730     return StatusCode::SUCCESS;
1731 }
1732 
RegisterHgmRefreshRateUpdateCallback(sptr<RSIHgmConfigChangeCallback> callback)1733 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateUpdateCallback(
1734     sptr<RSIHgmConfigChangeCallback> callback)
1735 {
1736     std::lock_guard<std::mutex> lock(mutex_);
1737 
1738     HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateUpdateCallback(remotePid_, callback);
1739     return StatusCode::SUCCESS;
1740 }
1741 
RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)1742 int32_t RSRenderServiceConnection::RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,
1743     sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)
1744 {
1745     if (!mainThread_ || dstPid == 0) {
1746         return StatusCode::INVALID_ARGUMENTS;
1747     }
1748     auto task = [pid = remotePid_, dstPid, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() {
1749         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1750         if (!connection || !connection->mainThread_) {
1751             return;
1752         }
1753         connection->mainThread_->GetContext().GetMutableFrameRateLinkerMap()
1754             .RegisterFrameRateLinkerExpectedFpsUpdateCallback(pid, dstPid, callback);
1755     };
1756     mainThread_->PostTask(task);
1757     return StatusCode::SUCCESS;
1758 }
1759 
SetAppWindowNum(uint32_t num)1760 void RSRenderServiceConnection::SetAppWindowNum(uint32_t num)
1761 {
1762     if (!mainThread_) {
1763         return;
1764     }
1765     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), num]() -> void {
1766         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1767         if (!connection || !connection->mainThread_) {
1768             return;
1769         }
1770         connection->mainThread_->SetAppWindowNum(num);
1771     };
1772     mainThread_->PostTask(task);
1773 }
1774 
SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes)1775 bool RSRenderServiceConnection::SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes)
1776 {
1777     if (!mainThread_) {
1778         return false;
1779     }
1780     RSUifirstManager::Instance().OnProcessAnimateScene(systemAnimatedScenes);
1781     std::lock_guard<std::mutex> lock(mutex_);
1782     return mainThread_->SetSystemAnimatedScenes(systemAnimatedScenes);
1783 }
1784 
ShowWatermark(const std::shared_ptr<Media::PixelMap> & watermarkImg,bool isShow)1785 void RSRenderServiceConnection::ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool isShow)
1786 {
1787     if (!mainThread_) {
1788         return;
1789     }
1790     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), watermarkImg, isShow]() -> void {
1791         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1792         if (!connection) {
1793             return;
1794         }
1795         connection->mainThread_->ShowWatermark(watermarkImg, isShow);
1796     };
1797     mainThread_->PostTask(task);
1798 }
1799 
ResizeVirtualScreen(ScreenId id,uint32_t width,uint32_t height)1800 int32_t RSRenderServiceConnection::ResizeVirtualScreen(ScreenId id, uint32_t width, uint32_t height)
1801 {
1802     if (!screenManager_) {
1803         return StatusCode::SCREEN_NOT_FOUND;
1804     }
1805     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1806     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1807         return RSHardwareThread::Instance().ScheduleTask(
1808             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
1809                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1810                 if (!connection) {
1811                     return RS_CONNECTION_ERROR;
1812                 }
1813                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
1814             }
1815         ).get();
1816     } else {
1817         return mainThread_->ScheduleTask(
1818             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
1819                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1820                 if (!connection) {
1821                     return RS_CONNECTION_ERROR;
1822                 }
1823                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
1824             }
1825         ).get();
1826     }
1827 }
1828 
ReportJankStats()1829 void RSRenderServiceConnection::ReportJankStats()
1830 {
1831     auto task = []() -> void { RSJankStats::GetInstance().ReportJankStats(); };
1832     renderThread_.PostTask(task);
1833 }
1834 
NotifyLightFactorStatus(bool isSafe)1835 void RSRenderServiceConnection::NotifyLightFactorStatus(bool isSafe)
1836 {
1837     if (!mainThread_) {
1838         return;
1839     }
1840     if (mainThread_->GetFrameRateMgr() == nullptr) {
1841         RS_LOGW("RSRenderServiceConnection::NotifyLightFactorStatus: frameRateMgr is nullptr.");
1842         return;
1843     }
1844     mainThread_->GetFrameRateMgr()->HandleLightFactorStatus(remotePid_, isSafe);
1845 }
1846 
NotifyPackageEvent(uint32_t listSize,const std::vector<std::string> & packageList)1847 void RSRenderServiceConnection::NotifyPackageEvent(uint32_t listSize, const std::vector<std::string>& packageList)
1848 {
1849     if (!mainThread_) {
1850         return;
1851     }
1852     if (mainThread_->GetFrameRateMgr() == nullptr) {
1853         RS_LOGW("RSRenderServiceConnection::NotifyPackageEvent: frameRateMgr is nullptr.");
1854         return;
1855     }
1856     mainThread_->GetFrameRateMgr()->HandlePackageEvent(remotePid_, packageList);
1857 }
1858 
NotifyRefreshRateEvent(const EventInfo & eventInfo)1859 void RSRenderServiceConnection::NotifyRefreshRateEvent(const EventInfo& eventInfo)
1860 {
1861     if (!mainThread_) {
1862         return;
1863     }
1864     if (mainThread_->GetFrameRateMgr() == nullptr) {
1865         RS_LOGW("RSRenderServiceConnection::NotifyRefreshRateEvent: frameRateMgr is nullptr.");
1866         return;
1867     }
1868     mainThread_->GetFrameRateMgr()->HandleRefreshRateEvent(remotePid_, eventInfo);
1869 }
1870 
NotifyTouchEvent(int32_t touchStatus,int32_t touchCnt)1871 void RSRenderServiceConnection::NotifyTouchEvent(int32_t touchStatus, int32_t touchCnt)
1872 {
1873     if (!mainThread_) {
1874         return;
1875     }
1876     if (mainThread_->GetFrameRateMgr() == nullptr) {
1877         RS_LOGW("RSRenderServiceConnection::NotifyTouchEvent: frameRateMgr is nullptr.");
1878         return;
1879     }
1880     mainThread_->GetFrameRateMgr()->HandleTouchEvent(remotePid_, touchStatus, touchCnt);
1881 }
1882 
NotifyDynamicModeEvent(bool enableDynamicModeEvent)1883 void RSRenderServiceConnection::NotifyDynamicModeEvent(bool enableDynamicModeEvent)
1884 {
1885     HgmTaskHandleThread::Instance().PostTask([enableDynamicModeEvent] () {
1886         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
1887         if (frameRateMgr == nullptr) {
1888             RS_LOGW("RSRenderServiceConnection::NotifyDynamicModeEvent: frameRateMgr is nullptr.");
1889             return;
1890         }
1891         frameRateMgr->HandleDynamicModeEvent(enableDynamicModeEvent);
1892     });
1893 }
1894 
ReportEventResponse(DataBaseRs info)1895 void RSRenderServiceConnection::ReportEventResponse(DataBaseRs info)
1896 {
1897     auto task = [info]() -> void {
1898         RSJankStats::GetInstance().SetReportEventResponse(info);
1899     };
1900     renderThread_.PostTask(task);
1901     RSUifirstManager::Instance().OnProcessEventResponse(info);
1902 }
1903 
ReportEventComplete(DataBaseRs info)1904 void RSRenderServiceConnection::ReportEventComplete(DataBaseRs info)
1905 {
1906     auto task = [info]() -> void {
1907         RSJankStats::GetInstance().SetReportEventComplete(info);
1908     };
1909     renderThread_.PostTask(task);
1910     RSUifirstManager::Instance().OnProcessEventComplete(info);
1911 }
1912 
ReportEventJankFrame(DataBaseRs info)1913 void RSRenderServiceConnection::ReportEventJankFrame(DataBaseRs info)
1914 {
1915     bool isReportTaskDelayed = renderThread_.IsMainLooping();
1916     auto task = [info, isReportTaskDelayed]() -> void {
1917         RSJankStats::GetInstance().SetReportEventJankFrame(info, isReportTaskDelayed);
1918     };
1919     renderThread_.PostTask(task);
1920 }
1921 
ReportGameStateData(GameStateData info)1922 void RSRenderServiceConnection::ReportGameStateData(GameStateData info)
1923 {
1924     RS_LOGD("RSRenderServiceConnection::ReportGameStateData = %{public}s, uid = %{public}d, state = %{public}d, "
1925             "pid = %{public}d renderTid = %{public}d ",
1926         info.bundleName.c_str(), info.uid, info.state, info.pid, info.renderTid);
1927 
1928     FrameReport::GetInstance().SetGameScene(info.pid, info.state);
1929 }
1930 
SetHardwareEnabled(NodeId id,bool isEnabled,SelfDrawingNodeType selfDrawingType,bool dynamicHardwareEnable)1931 void RSRenderServiceConnection::SetHardwareEnabled(NodeId id, bool isEnabled, SelfDrawingNodeType selfDrawingType,
1932     bool dynamicHardwareEnable)
1933 {
1934     if (!mainThread_) {
1935         return;
1936     }
1937     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, isEnabled, selfDrawingType,
1938         dynamicHardwareEnable]() -> void {
1939         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1940         if (!connection) {
1941             return;
1942         }
1943         auto& context = connection->mainThread_->GetContext();
1944         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
1945         if (node) {
1946             node->SetHardwareEnabled(isEnabled, selfDrawingType, dynamicHardwareEnable);
1947         }
1948     };
1949     mainThread_->PostTask(task);
1950 }
1951 
SetHidePrivacyContent(NodeId id,bool needHidePrivacyContent)1952 uint32_t RSRenderServiceConnection::SetHidePrivacyContent(NodeId id, bool needHidePrivacyContent)
1953 {
1954     if (!mainThread_) {
1955         return static_cast<int32_t>(RSInterfaceErrorCode::UNKNOWN_ERROR);
1956     }
1957     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, needHidePrivacyContent]() -> void {
1958         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1959         if (!connection) {
1960             return;
1961         }
1962         auto& context = connection->mainThread_->GetContext();
1963         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
1964         if (node) {
1965             node->SetHidePrivacyContent(needHidePrivacyContent);
1966         }
1967     };
1968     mainThread_->PostTask(task);
1969     return static_cast<uint32_t>(RSInterfaceErrorCode::NO_ERROR);
1970 }
1971 
SetCacheEnabledForRotation(bool isEnabled)1972 void RSRenderServiceConnection::SetCacheEnabledForRotation(bool isEnabled)
1973 {
1974     if (!mainThread_) {
1975         return;
1976     }
1977     auto task = [isEnabled]() {
1978         RSSystemProperties::SetCacheEnabledForRotation(isEnabled);
1979     };
1980     mainThread_->PostTask(task);
1981 }
1982 
GetActiveDirtyRegionInfo()1983 std::vector<ActiveDirtyRegionInfo> RSRenderServiceConnection::GetActiveDirtyRegionInfo()
1984 {
1985     const auto& activeDirtyRegionInfos = GpuDirtyRegionCollection::GetInstance().GetActiveDirtyRegionInfo();
1986     GpuDirtyRegionCollection::GetInstance().ResetActiveDirtyRegionInfo();
1987     return activeDirtyRegionInfos;
1988 }
1989 
GetGlobalDirtyRegionInfo()1990 GlobalDirtyRegionInfo RSRenderServiceConnection::GetGlobalDirtyRegionInfo()
1991 {
1992     const auto& globalDirtyRegionInfo = GpuDirtyRegionCollection::GetInstance().GetGlobalDirtyRegionInfo();
1993     GpuDirtyRegionCollection::GetInstance().ResetGlobalDirtyRegionInfo();
1994     return globalDirtyRegionInfo;
1995 }
1996 
GetLayerComposeInfo()1997 LayerComposeInfo RSRenderServiceConnection::GetLayerComposeInfo()
1998 {
1999     const auto& layerComposeInfo = LayerComposeCollection::GetInstance().GetLayerComposeInfo();
2000     LayerComposeCollection::GetInstance().ResetLayerComposeInfo();
2001     return layerComposeInfo;
2002 }
2003 
GetHwcDisabledReasonInfo()2004 HwcDisabledReasonInfos RSRenderServiceConnection::GetHwcDisabledReasonInfo()
2005 {
2006     return HwcDisabledReasonCollection::GetInstance().GetHwcDisabledReasonInfo();
2007 }
2008 
SetVmaCacheStatus(bool flag)2009 void RSRenderServiceConnection::SetVmaCacheStatus(bool flag)
2010 {
2011     renderThread_.SetVmaCacheStatus(flag);
2012 }
2013 
2014 #ifdef TP_FEATURE_ENABLE
SetTpFeatureConfig(int32_t feature,const char * config,TpFeatureConfigType tpFeatureConfigType)2015 void RSRenderServiceConnection::SetTpFeatureConfig(int32_t feature, const char* config,
2016     TpFeatureConfigType tpFeatureConfigType)
2017 {
2018     switch (tpFeatureConfigType) {
2019         case TpFeatureConfigType::DEFAULT_TP_FEATURE: {
2020             if (!TOUCH_SCREEN->IsSetFeatureConfigHandleValid()) {
2021                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfigHandl is nullptr");
2022                 return;
2023             }
2024             if (TOUCH_SCREEN->SetFeatureConfig(feature, config) < 0) {
2025                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfig failed");
2026                 return;
2027             }
2028             break;
2029         }
2030         case TpFeatureConfigType::AFT_TP_FEATURE: {
2031             if (!TOUCH_SCREEN->IsSetAftConfigHandleValid()) {
2032                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfigHandl is nullptr");
2033                 return;
2034             }
2035             if (TOUCH_SCREEN->SetAftConfig(config) < 0) {
2036                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfig failed");
2037                 return;
2038             }
2039             break;
2040         }
2041         default: {
2042             RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: unknown TpFeatureConfigType: %" PRIu8"",
2043                 static_cast<uint8_t>(tpFeatureConfigType));
2044             return;
2045         }
2046     }
2047 }
2048 #endif
2049 
SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)2050 void RSRenderServiceConnection::SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)
2051 {
2052     if (isVirtualScreenUsingStatus) {
2053         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ };
2054         NotifyRefreshRateEvent(event);
2055     } else {
2056         EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
2057         NotifyRefreshRateEvent(event);
2058     }
2059     return;
2060 }
2061 
SetCurtainScreenUsingStatus(bool isCurtainScreenOn)2062 void RSRenderServiceConnection::SetCurtainScreenUsingStatus(bool isCurtainScreenOn)
2063 {
2064     if (!mainThread_) {
2065         return;
2066     }
2067     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isCurtainScreenOn]() -> void {
2068         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2069         if (!connection) {
2070             return;
2071         }
2072         connection->mainThread_->SetCurtainScreenUsingStatus(isCurtainScreenOn);
2073     };
2074     mainThread_->PostTask(task);
2075 }
2076 
DropFrameByPid(const std::vector<int32_t> pidList)2077 void RSRenderServiceConnection::DropFrameByPid(const std::vector<int32_t> pidList)
2078 {
2079     if (!mainThread_) {
2080         return;
2081     }
2082     mainThread_->ScheduleTask(
2083         [weakThis = wptr<RSRenderServiceConnection>(this), pidList]() {
2084             // don't use 'this' directly
2085             sptr<RSRenderServiceConnection> connection = weakThis.promote();
2086             if (connection == nullptr || connection->mainThread_ == nullptr) {
2087                 return;
2088             }
2089             connection->mainThread_->AddPidNeedDropFrame(pidList);
2090         }
2091     );
2092 }
2093 
RegisterUIExtensionCallback(uint64_t userId,sptr<RSIUIExtensionCallback> callback)2094 int32_t RSRenderServiceConnection::RegisterUIExtensionCallback(uint64_t userId, sptr<RSIUIExtensionCallback> callback)
2095 {
2096     if (!mainThread_) {
2097         return StatusCode::INVALID_ARGUMENTS;
2098     }
2099     std::lock_guard<std::mutex> lock(mutex_);
2100     if (!callback) {
2101         RS_LOGE("RSRenderServiceConnection::RegisterUIExtensionCallback register null callback, failed.");
2102         return StatusCode::INVALID_ARGUMENTS;
2103     }
2104     mainThread_->RegisterUIExtensionCallback(remotePid_, userId, callback);
2105     return StatusCode::SUCCESS;
2106 }
2107 
SetAncoForceDoDirect(bool direct)2108 bool RSRenderServiceConnection::SetAncoForceDoDirect(bool direct)
2109 {
2110     std::lock_guard<std::mutex> lock(mutex_);
2111     mainThread_->SetAncoForceDoDirect(direct);
2112     return true;
2113 }
2114 
RegisterSurfaceBufferCallback(pid_t pid,uint64_t uid,sptr<RSISurfaceBufferCallback> callback)2115 void RSRenderServiceConnection::RegisterSurfaceBufferCallback(pid_t pid, uint64_t uid,
2116     sptr<RSISurfaceBufferCallback> callback)
2117 {
2118     RSSurfaceBufferCallbackManager::Instance().RegisterSurfaceBufferCallback(pid, uid, callback);
2119 }
2120 
UnregisterSurfaceBufferCallback(pid_t pid,uint64_t uid)2121 void RSRenderServiceConnection::UnregisterSurfaceBufferCallback(pid_t pid, uint64_t uid)
2122 {
2123     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(pid, uid);
2124 }
2125 
SetLayerTop(const std::string & nodeIdStr,bool isTop)2126 void RSRenderServiceConnection::SetLayerTop(const std::string &nodeIdStr, bool isTop)
2127 {
2128     if (mainThread_ == nullptr) {
2129         return;
2130     }
2131     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isTop]() -> void {
2132         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2133         if (!connection) {
2134             return;
2135         }
2136         auto& context = connection->mainThread_->GetContext();
2137         context.GetNodeMap().TraverseSurfaceNodes(
2138             [&nodeIdStr, &isTop](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
2139             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
2140                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
2141                 surfaceNode->SetLayerTop(isTop);
2142                 return;
2143             }
2144         });
2145         // It can be displayed immediately after layer-top changed.
2146         connection->mainThread_->SetDirtyFlag();
2147         connection->mainThread_->RequestNextVSync();
2148     };
2149     mainThread_->PostTask(task);
2150 }
2151 } // namespace Rosen
2152 } // namespace OHOS
2153