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  #ifndef RS_MAIN_THREAD
17  #define RS_MAIN_THREAD
18  
19  #include <event_handler.h>
20  #include <future>
21  #include <memory>
22  #include <mutex>
23  #include <queue>
24  #include <set>
25  #include <thread>
26  
27  #include "refbase.h"
28  #include "rs_base_render_engine.h"
29  #include "rs_draw_frame.h"
30  #include "vsync_distributor.h"
31  #include "vsync_receiver.h"
32  
33  #include "command/rs_command.h"
34  #include "common/rs_common_def.h"
35  #include "common/rs_thread_handler.h"
36  #include "common/rs_thread_looper.h"
37  #include "drawable/rs_render_node_drawable_adapter.h"
38  #include "ipc_callbacks/iapplication_agent.h"
39  #include "ipc_callbacks/rs_iocclusion_change_callback.h"
40  #include "ipc_callbacks/rs_isurface_occlusion_change_callback.h"
41  #include "ipc_callbacks/rs_iuiextension_callback.h"
42  #include "memory/rs_app_state_listener.h"
43  #include "memory/rs_memory_graphic.h"
44  #include "params/rs_render_thread_params.h"
45  #include "pipeline/rs_context.h"
46  #include "pipeline/rs_draw_frame.h"
47  #include "pipeline/rs_uni_render_judgement.h"
48  #include "platform/common/rs_event_manager.h"
49  #include "platform/drawing/rs_vsync_client.h"
50  #include "transaction/rs_transaction_data.h"
51  #include "transaction/rs_uiextension_data.h"
52  
53  #ifdef RES_SCHED_ENABLE
54  #include "vsync_system_ability_listener.h"
55  #endif
56  
57  namespace OHOS::Rosen {
58  #if defined(ACCESSIBILITY_ENABLE)
59  class AccessibilityObserver;
60  #endif
61  class HgmFrameRateManager;
62  class RSUniRenderVisitor;
63  struct FrameRateRangeData;
64  namespace Detail {
65  template<typename Task>
66  class ScheduledTask : public RefBase {
67  public:
Create(Task && task)68      static auto Create(Task&& task)
69      {
70          sptr<ScheduledTask<Task>> t(new ScheduledTask(std::forward<Task&&>(task)));
71          return std::make_pair(t, t->task_.get_future());
72      }
73  
Run()74      void Run()
75      {
76          task_();
77      }
78  
79  private:
ScheduledTask(Task && task)80      explicit ScheduledTask(Task&& task) : task_(std::move(task)) {}
81      ~ScheduledTask() override = default;
82  
83      using Return = std::invoke_result_t<Task>;
84      std::packaged_task<Return()> task_;
85  };
86  } // namespace Detail
87  
88  class RSMainThread {
89  public:
90      static RSMainThread* Instance();
91  
92      void Init();
93      void Start();
94      void UpdateFocusNodeId(NodeId focusNodeId);
95      void UpdateNeedDrawFocusChange(NodeId id);
96      bool IsNeedProcessBySingleFrameComposer(std::unique_ptr<RSTransactionData>& rsTransactionData);
97      void ProcessDataBySingleFrameComposer(std::unique_ptr<RSTransactionData>& rsTransactionData);
98      void RecvAndProcessRSTransactionDataImmediately(std::unique_ptr<RSTransactionData>& rsTransactionData);
99      void RecvRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
100      void RequestNextVSync(const std::string& fromWhom = "unknown", int64_t lastVSyncTS = 0);
101      void PostTask(RSTaskMessage::RSTask task);
102      void PostTask(RSTaskMessage::RSTask task, const std::string& name, int64_t delayTime,
103          AppExecFwk::EventQueue::Priority priority = AppExecFwk::EventQueue::Priority::IDLE);
104      void RemoveTask(const std::string& name);
105      void PostSyncTask(RSTaskMessage::RSTask task);
106      bool IsIdle() const;
107      void RenderServiceTreeDump(std::string& dumpString, bool forceDumpSingleFrame = true);
108      void SendClientDumpNodeTreeCommands(uint32_t taskId);
109      void CollectClientNodeTreeResult(uint32_t taskId, std::string& dumpString, size_t timeout);
110      void RsEventParamDump(std::string& dumpString);
111      bool IsUIFirstOn() const;
112      void UpdateAnimateNodeFlag();
113      void ResetAnimateNodeFlag();
114      void GetAppMemoryInMB(float& cpuMemSize, float& gpuMemSize);
115      void ClearMemoryCache(ClearMemoryMoment moment, bool deeply = false, pid_t pid = -1);
116      static bool CheckIsHdrSurface(const RSSurfaceRenderNode& surfaceNode);
117  
118      template<typename Task, typename Return = std::invoke_result_t<Task>>
ScheduleTask(Task && task)119      std::future<Return> ScheduleTask(Task&& task)
120      {
121          auto [scheduledTask, taskFuture] = Detail::ScheduledTask<Task>::Create(std::forward<Task&&>(task));
122          PostTask([t(std::move(scheduledTask))]() { t->Run(); });
123          return std::move(taskFuture);
124      }
125  
GetRenderEngine()126      const std::shared_ptr<RSBaseRenderEngine> GetRenderEngine() const
127      {
128          RS_LOGD("You'd better to call GetRenderEngine from RSUniRenderThread directly");
129          return isUniRender_ ? std::move(RSUniRenderThread::Instance().GetRenderEngine()) : renderEngine_;
130      }
131  
GetClearMemoryFinished()132      bool GetClearMemoryFinished() const
133      {
134          return clearMemoryFinished_;
135      }
136  
GetContext()137      RSContext& GetContext()
138      {
139          return *context_;
140      }
141  
Id()142      std::thread::id Id() const
143      {
144          return mainThreadId_;
145      }
146  
CheckIsHardwareEnabledBufferUpdated()147      bool CheckIsHardwareEnabledBufferUpdated() const
148      {
149          return isHardwareEnabledBufferUpdated_;
150      }
151  
SetGlobalDarkColorMode(bool isDark)152      void SetGlobalDarkColorMode(bool isDark)
153      {
154          isGlobalDarkColorMode_ = isDark;
155      }
156  
GetGlobalDarkColorMode()157      bool GetGlobalDarkColorMode() const
158      {
159          return isGlobalDarkColorMode_;
160      }
161  
162      /* Judge if rootnode has to be prepared based on it corresponding process is active
163       * If its pid is in activeProcessPids_ set, return true
164       */
165      bool CheckNodeHasToBePreparedByPid(NodeId nodeId, bool isClassifyByRoot);
166      // check if active app has static drawing cache
167      bool IsDrawingGroupChanged(const RSRenderNode& cacheRootNode) const;
168      // check if active instance only move or scale it's main window surface without rearrangement
169      // instanceNodeId should be MainWindowType, or it cannot grep correct app's info
170      void CheckAndUpdateInstanceContentStaticStatus(std::shared_ptr<RSSurfaceRenderNode> instanceNode) const;
171  
172      void RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app);
173      void UnRegisterApplicationAgent(sptr<IApplicationAgent> app);
174  
175      void RegisterOcclusionChangeCallback(pid_t pid, sptr<RSIOcclusionChangeCallback> callback);
176      void UnRegisterOcclusionChangeCallback(pid_t pid);
177  
178      void RegisterSurfaceOcclusionChangeCallback(
179          NodeId id, pid_t pid, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints);
180      void UnRegisterSurfaceOcclusionChangeCallback(NodeId id);
181      void ClearSurfaceOcclusionChangeCallback(pid_t pid);
182      bool SurfaceOcclusionCallBackIfOnTreeStateChanged();
183  
184      void WaitUtilUniRenderFinished();
185      void NotifyUniRenderFinish();
186  
187      bool WaitHardwareThreadTaskExecute();
188      void NotifyHardwareThreadCanExecuteTask();
189  
190      void ClearTransactionDataPidInfo(pid_t remotePid);
191      void AddTransactionDataPidInfo(pid_t remotePid);
192  
193      void SetFocusAppInfo(
194          int32_t pid, int32_t uid, const std::string& bundleName, const std::string& abilityName, uint64_t focusNodeId);
195      const std::unordered_map<NodeId, bool>& GetCacheCmdSkippedNodes() const;
196  
197      sptr<VSyncDistributor> rsVSyncDistributor_;
198      sptr<VSyncController> rsVSyncController_;
199      sptr<VSyncController> appVSyncController_;
200      sptr<VSyncGenerator> vsyncGenerator_;
201  
202      void ReleaseSurface();
203      void AddToReleaseQueue(std::shared_ptr<Drawing::Surface>&& surface);
204  
205      void AddUiCaptureTask(NodeId id, std::function<void()> task);
206      void ProcessUiCaptureTasks();
207  
208      void SetDirtyFlag(bool isDirty = true);
209      bool GetDirtyFlag();
210      void SetNoNeedToPostTask(bool noNeedToPostTask);
211      void SetAccessibilityConfigChanged();
212      void SetScreenPowerOnChanged(bool val);
213      bool GetScreenPowerOnChanged() const;
214      bool IsAccessibilityConfigChanged() const;
215      bool IsCurtainScreenUsingStatusChanged() const;
216      void ForceRefreshForUni();
217      void TrimMem(std::unordered_set<std::u16string>& argSets, std::string& result);
218      void DumpMem(std::unordered_set<std::u16string>& argSets, std::string& result, std::string& type, pid_t pid = 0);
219      void CountMem(int pid, MemoryGraphic& mem);
220      void CountMem(std::vector<MemoryGraphic>& mems);
221      void SetAppWindowNum(uint32_t num);
222      bool SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes);
223      SystemAnimatedScenes GetSystemAnimatedScenes();
224      void ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool flag);
225      void SetIsCachedSurfaceUpdated(bool isCachedSurfaceUpdated);
226      pid_t GetDesktopPidForRotationScene() const;
SetForceUpdateUniRenderFlag(bool flag)227      void SetForceUpdateUniRenderFlag(bool flag)
228      {
229          forceUpdateUniRenderFlag_ = flag;
230      }
SetIdleTimerExpiredFlag(bool flag)231      void SetIdleTimerExpiredFlag(bool flag)
232      {
233          idleTimerExpiredFlag_ = flag;
234      }
SetRSIdleTimerExpiredFlag(bool flag)235      void SetRSIdleTimerExpiredFlag(bool flag)
236      {
237          rsIdleTimerExpiredFlag_ = flag;
238      }
239      std::shared_ptr<Drawing::Image> GetWatermarkImg();
240      bool GetWatermarkFlag();
241  
IsWatermarkFlagChanged()242      bool IsWatermarkFlagChanged() const
243      {
244          return lastWatermarkFlag_ != watermarkFlag_;
245      }
246  
GetFrameCount()247      uint64_t GetFrameCount() const
248      {
249          return frameCount_;
250      }
GetDrawStatusVec()251      std::vector<NodeId>& GetDrawStatusVec()
252      {
253          return curDrawStatusVec_;
254      }
SetAppVSyncDistributor(const sptr<VSyncDistributor> & appVSyncDistributor)255      void SetAppVSyncDistributor(const sptr<VSyncDistributor>& appVSyncDistributor)
256      {
257          appVSyncDistributor_ = appVSyncDistributor;
258      }
259  
260      DeviceType GetDeviceType() const;
261      bool IsSingleDisplay();
262      bool HasMirrorDisplay() const;
263      bool GetNoNeedToPostTask();
264      uint64_t GetFocusNodeId() const;
265      uint64_t GetFocusLeashWindowId() const;
GetClearMemDeeply()266      bool GetClearMemDeeply() const
267      {
268          return clearMemDeeply_;
269      }
270  
GetClearMoment()271      ClearMemoryMoment GetClearMoment() const
272      {
273          if (!context_) {
274              return ClearMemoryMoment::NO_CLEAR;
275          }
276          return context_->clearMoment_;
277      }
278  
SetClearMoment(ClearMemoryMoment moment)279      void SetClearMoment(ClearMemoryMoment moment)
280      {
281          if (!context_) {
282              return;
283          }
284          context_->clearMoment_ = moment;
285      }
286  
IsPCThreeFingerScenesListScene()287      bool IsPCThreeFingerScenesListScene() const
288      {
289          return !threeFingerScenesList_.empty();
290      }
291  
292      void SurfaceOcclusionChangeCallback(VisibleData& dstCurVisVec);
293      void SurfaceOcclusionCallback();
294      void SubscribeAppState();
295      void HandleOnTrim(Memory::SystemMemoryLevel level);
296      void SetCurtainScreenUsingStatus(bool isCurtainScreenOn);
297      void AddPidNeedDropFrame(std::vector<int32_t> pid);
298      void ClearNeedDropframePidList();
299      bool IsNeedDropFrameByPid(NodeId nodeId);
300      void SetLuminanceChangingStatus(bool isLuminanceChanged);
301      bool ExchangeLuminanceChangingStatus();
302      bool IsCurtainScreenOn() const;
303  
304      bool GetParallelCompositionEnabled();
GetFrameRateMgr()305      std::shared_ptr<HgmFrameRateManager> GetFrameRateMgr() { return frameRateMgr_; };
306      void SetFrameIsRender(bool isRender);
307      const std::vector<std::shared_ptr<RSSurfaceRenderNode>>& GetSelfDrawingNodes() const;
308      const std::vector<DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr>& GetSelfDrawables() const;
309  
IsOnVsync()310      bool IsOnVsync() const
311      {
312          return isOnVsync_.load();
313      }
314  
GetDiscardJankFrames()315      bool GetDiscardJankFrames() const
316      {
317          return discardJankFrames_.load();
318      }
319  
SetDiscardJankFrames(bool discardJankFrames)320      void SetDiscardJankFrames(bool discardJankFrames)
321      {
322          if (discardJankFrames_.load() != discardJankFrames) {
323              discardJankFrames_.store(discardJankFrames);
324          }
325      }
326  
GetSkipJankAnimatorFrame()327      bool GetSkipJankAnimatorFrame() const
328      {
329          return skipJankAnimatorFrame_.load();
330      }
331  
IsFirstFrameOfDrawingCacheDFXSwitch()332      bool IsFirstFrameOfDrawingCacheDFXSwitch() const
333      {
334          return isDrawingCacheDfxEnabledOfCurFrame_ != isDrawingCacheDfxEnabledOfLastFrame_;
335      }
336  
SetDrawingCacheDfxEnabledOfCurFrame(bool isDrawingCacheDfxEnabledOfCurFrame)337      void SetDrawingCacheDfxEnabledOfCurFrame(bool isDrawingCacheDfxEnabledOfCurFrame)
338      {
339          isDrawingCacheDfxEnabledOfCurFrame_ = isDrawingCacheDfxEnabledOfCurFrame;
340      }
341  
SetSkipJankAnimatorFrame(bool skipJankAnimatorFrame)342      void SetSkipJankAnimatorFrame(bool skipJankAnimatorFrame)
343      {
344          skipJankAnimatorFrame_.store(skipJankAnimatorFrame);
345      }
346  
347      bool IsRequestedNextVSync();
348  
GetNextDVsyncAnimateFlag()349      bool GetNextDVsyncAnimateFlag() const
350      {
351          return needRequestNextVsyncAnimate_;
352      }
353  
IsFirstFrameOfPartialRender()354      bool IsFirstFrameOfPartialRender() const
355      {
356          return isFirstFrameOfPartialRender_;
357      }
358  
359      bool IsHardwareEnabledNodesNeedSync();
360      bool IsOcclusionNodesNeedSync(NodeId id, bool useCurWindow);
361  
362      void CallbackDrawContextStatusToWMS(bool isUniRender = false);
363      void SetHardwareTaskNum(uint32_t num);
364      void RegisterUIExtensionCallback(pid_t pid, uint64_t userId, sptr<RSIUIExtensionCallback> callback);
365      void UnRegisterUIExtensionCallback(pid_t pid);
366  
367      void SetAncoForceDoDirect(bool direct);
368  
IsFirstFrameOfOverdrawSwitch()369      bool IsFirstFrameOfOverdrawSwitch() const
370      {
371          return isOverDrawEnabledOfCurFrame_ != isOverDrawEnabledOfLastFrame_;
372      }
373  
374      uint64_t GetRealTimeOffsetOfDvsync(int64_t time);
GetCurrentVsyncTime()375      uint64_t GetCurrentVsyncTime() const
376      {
377          return curTime_;
378      }
379  
GetMultiDisplayChange()380      bool GetMultiDisplayChange() const
381      {
382          return isMultiDisplayChange_;
383      }
GetMultiDisplayStatus()384      bool GetMultiDisplayStatus() const
385      {
386          return isMultiDisplayPre_;
387      }
388  private:
389      using TransactionDataIndexMap = std::unordered_map<pid_t,
390          std::pair<uint64_t, std::vector<std::unique_ptr<RSTransactionData>>>>;
391      using DrawablesVec = std::vector<std::pair<NodeId,
392          DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr>>;
393  
394      RSMainThread();
395      ~RSMainThread() noexcept;
396      RSMainThread(const RSMainThread&) = delete;
397      RSMainThread(const RSMainThread&&) = delete;
398      RSMainThread& operator=(const RSMainThread&) = delete;
399      RSMainThread& operator=(const RSMainThread&&) = delete;
400  
401      void OnVsync(uint64_t timestamp, uint64_t frameCount, void* data);
402      void ProcessCommand();
403      void UpdateSubSurfaceCnt();
404      void Animate(uint64_t timestamp);
405      void ConsumeAndUpdateAllNodes();
406      void CollectInfoForHardwareComposer();
407      void ReleaseAllNodesBuffer();
408      void Render();
409      void OnUniRenderDraw();
410      void SetDeviceType();
411      void UniRender(std::shared_ptr<RSBaseRenderNode> rootNode);
412      bool CheckSurfaceNeedProcess(OcclusionRectISet& occlusionSurfaces, std::shared_ptr<RSSurfaceRenderNode> curSurface);
413      void CalcOcclusionImplementation(std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces,
414          VisibleData& dstCurVisVec, std::map<NodeId, RSVisibleLevel>& dstPidVisMap);
415      void CalcOcclusion();
416      bool CheckSurfaceVisChanged(std::map<NodeId, RSVisibleLevel>& pidVisMap,
417          std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces);
418      void SetVSyncRateByVisibleLevel(std::map<NodeId, RSVisibleLevel>& pidVisMap,
419          std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces);
420      void CallbackToWMS(VisibleData& curVisVec);
421      void SendCommands();
422      void InitRSEventDetector();
423      void RemoveRSEventDetector();
424      void SetRSEventDetectorLoopStartTag();
425      void SetRSEventDetectorLoopFinishTag();
426      void CheckSystemSceneStatus();
427      void UpdateUIFirstSwitch();
428      // ROG: Resolution Online Government
429      void UpdateRogSizeIfNeeded();
430      void UpdateDisplayNodeScreenId();
431      uint32_t GetRefreshRate() const;
432      uint32_t GetDynamicRefreshRate() const;
433      void SkipCommandByNodeId(std::vector<std::unique_ptr<RSTransactionData>>& transactionVec, pid_t pid);
434      static void OnHideNotchStatusCallback(const char *key, const char *value, void *context);
435      static void OnDrawingCacheDfxSwitchCallback(const char *key, const char *value, void *context);
436  
437      bool DoParallelComposition(std::shared_ptr<RSBaseRenderNode> rootNode);
438  
439      void ClassifyRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
440      void ProcessRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData, pid_t pid);
441      void ProcessSyncRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData, pid_t pid);
442      void ProcessSyncTransactionCount(std::unique_ptr<RSTransactionData>& rsTransactionData);
443      void StartSyncTransactionFallbackTask(std::unique_ptr<RSTransactionData>& rsTransactionData);
444      void ProcessAllSyncTransactionData();
445      void ProcessCommandForDividedRender();
446      void ProcessCommandForUniRender();
447      void WaitUntilUnmarshallingTaskFinished();
448      void MergeToEffectiveTransactionDataMap(TransactionDataMap& cachedTransactionDataMap);
449  
450      void ClearDisplayBuffer();
451      void PerfAfterAnim(bool needRequestNextVsync);
452      void PerfForBlurIfNeeded();
453      void PerfMultiWindow();
454      void RenderFrameStart(uint64_t timestamp);
455      void ResetHardwareEnabledState(bool isUniRender);
456      void CheckIfHardwareForcedDisabled();
457      void CheckAndUpdateTransactionIndex(
458          std::shared_ptr<TransactionDataMap>& transactionDataEffective, std::string& transactionFlags);
459  
460      bool IsResidentProcess(pid_t pid) const;
461      bool IsNeedSkip(NodeId instanceRootNodeId, pid_t pid);
462      void UpdateAceDebugBoundaryEnabled();
463  
464      // UIFirst
465      bool CheckParallelSubThreadNodesStatus();
466      void CacheCommands();
467      bool CheckSubThreadNodeStatusIsDoing(NodeId appNodeId) const;
468  
469      // used for informing hgm the bundle name of SurfaceRenderNodes
470      void InformHgmNodeInfo();
471      void CheckIfNodeIsBundle(std::shared_ptr<RSSurfaceRenderNode> node);
472  
473      void SetFocusLeashWindowId();
474      void ProcessHgmFrameRate(uint64_t timestamp);
475      bool IsLastFrameUIFirstEnabled(NodeId appNodeId) const;
476      RSVisibleLevel GetRegionVisibleLevel(const Occlusion::Region& curRegion,
477          const Occlusion::Region& visibleRegion);
478      void PrintCurrentStatus();
479      void ProcessScreenHotPlugEvents();
480      void WaitUntilUploadTextureTaskFinishedForGL();
481  #ifdef RES_SCHED_ENABLE
482      void SubScribeSystemAbility();
483  #endif
484  #if defined(RS_ENABLE_CHIPSET_VSYNC)
485      void ConnectChipsetVsyncSer();
486      void SetVsyncInfo(uint64_t timestamp);
487  #endif
488  
489      bool DoDirectComposition(std::shared_ptr<RSBaseRenderNode> rootNode, bool waitForRT);
490  
491      void RSJankStatsOnVsyncStart(int64_t onVsyncStartTime, int64_t onVsyncStartTimeSteady,
492                                   float onVsyncStartTimeSteadyFloat);
493      void RSJankStatsOnVsyncEnd(int64_t onVsyncStartTime, int64_t onVsyncStartTimeSteady,
494                                 float onVsyncStartTimeSteadyFloat);
495      int64_t GetCurrentSystimeMs() const;
496      int64_t GetCurrentSteadyTimeMs() const;
497      float GetCurrentSteadyTimeMsFloat() const;
498      void RequestNextVsyncForCachedCommand(std::string& transactionFlags, pid_t pid, uint64_t curIndex);
499      void UpdateLuminance();
500      void DvsyncCheckRequestNextVsync();
501  
502      void PrepareUiCaptureTasks(std::shared_ptr<RSUniRenderVisitor> uniVisitor);
503      void UIExtensionNodesTraverseAndCallback();
504      bool CheckUIExtensionCallbackDataChanged() const;
505  
506      void OnCommitDumpClientNodeTree(NodeId nodeId, pid_t pid, uint32_t taskId, const std::string& result);
507  
508      // Used for CommitAndReleaseLayers task
509      void SetFrameInfo(uint64_t frameCount);
510  
511      // Record change status of multi or single display
512      void MultiDisplayChange(bool isMultiDisplay);
513  
514      std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr;
515      std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
516      RSTaskMessage::RSTask mainLoop_;
517      std::unique_ptr<RSVsyncClient> vsyncClient_ = nullptr;
518      std::unordered_map<NodeId, uint64_t> dividedRenderbufferTimestamps_;
519  
520      std::mutex transitionDataMutex_;
521      std::unordered_map<NodeId, std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>>> cachedCommands_;
522      std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> effectiveCommands_;
523      std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> pendingEffectiveCommands_;
524      std::unordered_map<pid_t, std::vector<std::unique_ptr<RSTransactionData>>> syncTransactionData_;
525      std::unordered_map<int32_t, int32_t> subSyncTransactionCounts_;
526  
527      TransactionDataMap cachedTransactionDataMap_;
528      TransactionDataIndexMap effectiveTransactionDataIndexMap_;
529      std::map<pid_t, std::vector<std::unique_ptr<RSTransactionData>>> cachedSkipTransactionDataMap_;
530      std::unordered_map<pid_t, uint64_t> transactionDataLastWaitTime_;
531  
532      uint64_t curTime_ = 0;
533      uint64_t timestamp_ = 0;
534      uint64_t vsyncId_ = 0;
535      uint64_t lastAnimateTimestamp_ = 0;
536      uint64_t prePerfTimestamp_ = 0;
537      uint64_t lastCleanCacheTimestamp_ = 0;
538      pid_t lastCleanCachePid_ = -1;
539      int hardwareTid_ = -1;
540      std::string transactionFlags_ = "";
541      std::unordered_map<uint32_t, sptr<IApplicationAgent>> applicationAgentMap_;
542  
543      std::shared_ptr<RSContext> context_;
544      std::thread::id mainThreadId_;
545      std::shared_ptr<VSyncReceiver> receiver_ = nullptr;
546      std::map<pid_t, sptr<RSIOcclusionChangeCallback>> occlusionListeners_;
547      std::mutex occlusionMutex_;
548  
549      bool isUniRender_ = RSUniRenderJudgement::IsUniRender();
550      RSTaskMessage::RSTask unmarshalBarrierTask_;
551      std::condition_variable unmarshalTaskCond_;
552      std::mutex unmarshalMutex_;
553      int32_t unmarshalFinishedCount_ = 0;
554      bool needWaitUnmarshalFinished_ = true;
555      sptr<VSyncDistributor> appVSyncDistributor_ = nullptr;
556  
557  #if defined(RS_ENABLE_PARALLEL_UPLOAD) && defined(RS_ENABLE_GL)
558      RSTaskMessage::RSTask uploadTextureBarrierTask_;
559      std::condition_variable uploadTextureTaskCond_;
560      std::mutex uploadTextureMutex_;
561      int32_t uploadTextureFinishedCount_ = 0;
562      EGLSyncKHR uploadTextureFence;
563  #endif
564  
565      mutable std::mutex uniRenderMutex_;
566      bool uniRenderFinished_ = false;
567      std::condition_variable uniRenderCond_;
568  
569      bool clearMemoryFinished_ = true;
570      bool clearMemDeeply_ = false;
571  
572      // Used to refresh the whole display when AccessibilityConfig is changed
573      bool isAccessibilityConfigChanged_ = false;
574  
575      // Used to refresh the whole display when curtain screen status is changed
576      bool isCurtainScreenUsingStatusChanged_ = false;
577  
578      // Used to refresh the whole display when luminance is changed
579      std::atomic<bool> isLuminanceChanged_ = false;
580  
581      // used for blocking mainThread when hardwareThread has 2 and more task to Execute
582      mutable std::mutex hardwareThreadTaskMutex_;
583      std::condition_variable hardwareThreadTaskCond_;
584  
585      std::map<NodeId, RSVisibleLevel> lastVisMapForVsyncRate_;
586      VisibleData lastVisVec_;
587      std::map<NodeId, uint64_t> lastDrawStatusMap_;
588      std::vector<NodeId> curDrawStatusVec_;
589      bool qosPidCal_ = false;
590  
591      std::atomic<bool> isDirty_ = false;
592      std::atomic<bool> screenPowerOnChanged_ = false;
593      std::atomic_bool doWindowAnimate_ = false;
594      std::vector<NodeId> lastSurfaceIds_;
595      std::atomic<int32_t> focusAppPid_ = -1;
596      std::atomic<int32_t> focusAppUid_ = -1;
597      const uint8_t opacity_ = 255;
598      std::string focusAppBundleName_ = "";
599      std::string focusAppAbilityName_ = "";
600      std::atomic<uint64_t> focusNodeId_ = 0;
601      uint64_t focusLeashWindowId_ = 0;
602      uint64_t lastFocusNodeId_ = 0;
603      uint32_t appWindowNum_ = 0;
604      std::atomic<uint32_t> requestNextVsyncNum_ = 0;
605      bool lastFrameHasFilter_ = false;
606      bool vsyncControlEnabled_ = true;
607      bool systemAnimatedScenesEnabled_ = false;
608      bool isFoldScreenDevice_ = false;
609      std::atomic<bool> isGlobalDarkColorMode_ = false;
610  
611      std::atomic_bool noNeedToPostTask_ = false;
612  
613      bool isAceDebugBoundaryEnabledOfLastFrame_ = false;
614      bool hasPostUpdateAceDebugBoundaryTask_ = false;
615  
616      std::shared_ptr<RSBaseRenderEngine> renderEngine_;
617      std::shared_ptr<RSBaseRenderEngine> uniRenderEngine_;
618      std::shared_ptr<RSBaseEventDetector> rsCompositionTimeoutDetector_;
619      RSEventManager rsEventManager_;
620  #if defined(ACCESSIBILITY_ENABLE)
621      std::shared_ptr<AccessibilityObserver> accessibilityObserver_;
622  #endif
623  
624      // used for hardware enabled case
625      bool doDirectComposition_ = true;
626      bool needDrawFrame_ = true;
627      bool needPostAndWait_ = true;
628      bool isLastFrameDirectComposition_ = false;
629      bool isNeedResetClearMemoryTask_ = false;
630      bool isHardwareEnabledBufferUpdated_ = false;
631      std::vector<std::shared_ptr<RSSurfaceRenderNode>> hardwareEnabledNodes_;
632      std::vector<std::shared_ptr<RSSurfaceRenderNode>> selfDrawingNodes_;
633      std::vector<DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr> selfDrawables_;
634      bool isHardwareForcedDisabled_ = false; // if app node has shadow or filter, disable hardware composer for all
635      DrawablesVec hardwareEnabledDrwawables_;
636  
637      // for client node tree dump
638      struct NodeTreeDumpTask {
639          size_t count = 0;
640          size_t completionCount = 0;
641          std::map<pid_t, std::optional<std::string>> data;
642      };
643      std::mutex nodeTreeDumpMutex_;
644      std::condition_variable nodeTreeDumpCondVar_;
645      std::unordered_map<uint32_t, NodeTreeDumpTask> nodeTreeDumpTasks_;
646  
647      // used for watermark
648      std::mutex watermarkMutex_;
649      std::shared_ptr<Drawing::Image> watermarkImg_ = nullptr;
650      bool watermarkFlag_ = false;
651      bool lastWatermarkFlag_ = false;
652      bool doParallelComposition_ = false;
653      bool hasProtectedLayer_ = false;
654  
655      std::shared_ptr<HgmFrameRateManager> frameRateMgr_ = nullptr;
656      std::shared_ptr<RSRenderFrameRateLinker> rsFrameRateLinker_ = nullptr;
657      pid_t desktopPidForRotationScene_ = 0;
658      FrameRateRange rsCurrRange_;
659  
660      // UIFirst
661      std::list<std::shared_ptr<RSSurfaceRenderNode>> subThreadNodes_;
662      std::unordered_map<NodeId, bool> cacheCmdSkippedNodes_;
663      std::unordered_map<pid_t, std::pair<std::vector<NodeId>, bool>> cacheCmdSkippedInfo_;
664      std::atomic<uint64_t> frameCount_ = 0;
665      std::set<std::shared_ptr<RSBaseRenderNode>> oldDisplayChildren_;
666      DeviceType deviceType_ = DeviceType::PHONE;
667      bool isCachedSurfaceUpdated_ = false;
668      bool isUiFirstOn_ = false;
669  
670      // used for informing hgm the bundle name of SurfaceRenderNodes
671      bool noBundle_ = false;
672      std::string currentBundleName_ = "";
673      bool forceUpdateUniRenderFlag_ = false;
674      bool idleTimerExpiredFlag_ = false;
675      bool rsIdleTimerExpiredFlag_ = false;
676      // for ui first
677      std::mutex mutex_;
678      std::queue<std::shared_ptr<Drawing::Surface>> tmpSurfaces_;
679  
680      // for surface occlusion change callback
681      std::mutex surfaceOcclusionMutex_;
682      std::vector<NodeId> lastRegisteredSurfaceOnTree_;
683      std::mutex systemAnimatedScenesMutex_;
684      std::list<std::pair<SystemAnimatedScenes, time_t>> systemAnimatedScenesList_;
685      std::list<std::pair<SystemAnimatedScenes, time_t>> threeFingerScenesList_;
686      bool isReduceVSyncBySystemAnimatedScenes_ = false;
687      std::unordered_map<NodeId, // map<node ID, <pid, callback, partition points vector, level>>
688          std::tuple<pid_t, sptr<RSISurfaceOcclusionChangeCallback>,
689          std::vector<float>, uint8_t>> surfaceOcclusionListeners_;
690      std::unordered_map<NodeId, // map<node ID, <surface node, app window node>>
691          std::pair<std::shared_ptr<RSSurfaceRenderNode>, std::shared_ptr<RSSurfaceRenderNode>>> savedAppWindowNode_;
692  
693      std::shared_ptr<RSAppStateListener> rsAppStateListener_;
694      int32_t subscribeFailCount_ = 0;
695      SystemAnimatedScenes systemAnimatedScenes_ = SystemAnimatedScenes::OTHERS;
696      uint32_t leashWindowCount_ = 0;
697  
698      // for drawing cache dfx
699      bool isDrawingCacheDfxEnabledOfCurFrame_ = false;
700      bool isDrawingCacheDfxEnabledOfLastFrame_ = false;
701  
702      // for ui captures
703      std::vector<std::tuple<NodeId, std::function<void()>>> pendingUiCaptureTasks_;
704      std::queue<std::tuple<NodeId, std::function<void()>>> uiCaptureTasks_;
705  
706      // for dvsync (animate requestNextVSync after mark rsnotrendering)
707      bool needRequestNextVsyncAnimate_ = false;
708  
709      bool forceUIFirstChanged_ = false;
710  
711      // uiextension
712      std::mutex uiExtensionMutex_;
713      UIExtensionCallbackData uiExtensionCallbackData_;
714      bool lastFrameUIExtensionDataEmpty_ = false;
715      // <pid, <uid, callback>>
716      std::map<pid_t, std::pair<uint64_t, sptr<RSIUIExtensionCallback>>> uiExtensionListenners_ = {};
717  
718      // overDraw
719      bool isOverDrawEnabledOfCurFrame_ = false;
720      bool isOverDrawEnabledOfLastFrame_ = false;
721  
722  #ifdef RS_PROFILER_ENABLED
723      friend class RSProfiler;
724  #endif
725  #if defined(RS_ENABLE_CHIPSET_VSYNC)
726      bool initVsyncServiceFlag_ = true;
727  #endif
728      pid_t exitedPid_ = -1;
729      std::set<pid_t> exitedPidSet_;
730      RSDrawFrame drawFrame_;
731      std::unique_ptr<RSRenderThreadParams> renderThreadParams_ = nullptr; // sync to render thread
732      RsParallelType rsParallelType_;
733      bool isCurtainScreenOn_ = false;
734      std::unordered_set<int32_t> surfacePidNeedDropFrame_;
735  #ifdef RES_SCHED_ENABLE
736      sptr<VSyncSystemAbilityListener> saStatusChangeListener_ = nullptr;
737  #endif
738      // for statistic of jank frames
739      std::atomic_bool isOnVsync_ = false;
740      std::atomic_bool discardJankFrames_ = false;
741      std::atomic_bool skipJankAnimatorFrame_ = false;
742      ScreenId displayNodeScreenId_ = 0;
743  
744      // partial render
745      bool isFirstFrameOfPartialRender_ = false;
746      bool isPartialRenderEnabledOfLastFrame_ = false;
747      bool isRegionDebugEnabledOfLastFrame_ = false;
748  
749      bool isForceRefresh_ = false;
750  
751      // record multidisplay status change
752      bool isMultiDisplayChange_ = false;
753      bool isMultiDisplayPre_ = false;
754  };
755  } // namespace OHOS::Rosen
756  #endif // RS_MAIN_THREAD
757