• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 "core/components_ng/render/adapter/rosen_render_context.h"
17 
18 #include <memory>
19 
20 #include "include/utils/SkParsePath.h"
21 #include "modifier/rs_property.h"
22 #include "render_service_base/include/property/rs_properties_def.h"
23 #include "render_service_base/include/render/rs_mask.h"
24 #include "render_service_client/core/modifier/rs_property_modifier.h"
25 #include "render_service_client/core/pipeline/rs_node_map.h"
26 #include "render_service_client/core/transaction/rs_transaction.h"
27 #include "render_service_client/core/transaction/rs_interfaces.h"
28 #include "render_service_client/core/ui/rs_canvas_drawing_node.h"
29 #include "render_service_client/core/ui/rs_canvas_node.h"
30 #include "render_service_client/core/ui/rs_effect_node.h"
31 #include "render_service_client/core/ui/rs_node.h"
32 #include "render_service_client/core/ui/rs_root_node.h"
33 #include "render_service_client/core/ui/rs_surface_node.h"
34 #include "rosen_render_context.h"
35 
36 #include "base/geometry/calc_dimension.h"
37 #include "base/geometry/dimension.h"
38 #include "base/geometry/matrix4.h"
39 #include "base/log/dump_log.h"
40 #include "base/utils/utils.h"
41 #include "core/animation/native_curve_helper.h"
42 #include "core/components/theme/app_theme.h"
43 #include "core/components/theme/blur_style_theme.h"
44 #include "core/components_ng/pattern/overlay/accessibility_focus_paint_node_pattern.h"
45 #include "core/components_ng/pattern/particle/particle_pattern.h"
46 #include "core/components_ng/pattern/stage/page_pattern.h"
47 #include "core/components_ng/render/adapter/background_modifier.h"
48 #include "core/components_ng/render/adapter/border_image_modifier.h"
49 #include "core/components_ng/render/adapter/component_snapshot.h"
50 #include "core/components_ng/render/adapter/debug_boundary_modifier.h"
51 #include "core/components_ng/render/adapter/focus_state_modifier.h"
52 #include "core/components_ng/render/adapter/gradient_style_modifier.h"
53 #include "core/components_ng/render/adapter/mouse_select_modifier.h"
54 #include "core/components_ng/render/adapter/overlay_modifier.h"
55 #include "core/components_ng/render/adapter/pixelmap_image.h"
56 #include "core/components_ng/render/adapter/rosen_window.h"
57 #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
58 #include "render_service_client/core/pipeline/rs_render_thread.h"
59 #endif
60 #include "core/components_ng/render/adapter/rosen/drawing_decoration_painter.h"
61 #include "core/components_ng/render/adapter/rosen/drawing_image.h"
62 #include "core/components_ng/pattern/checkbox/checkbox_paint_property.h"
63 #include "core/components_ng/render/border_image_painter.h"
64 #include "core/components_ng/render/debug_boundary_painter.h"
65 #include "core/components_ng/render/image_painter.h"
66 #include "interfaces/inner_api/ace_kit/include/ui/view/draw/modifier.h"
67 
68 namespace OHOS::Ace::NG {
69 
70 using namespace OHOS::Rosen;
71 namespace {
72 RefPtr<PixelMap> g_pixelMap {};
73 std::mutex g_mutex;
74 std::condition_variable thumbnailGet;
75 constexpr std::chrono::duration<int, std::milli> PIXELMAP_TIMEOUT_DURATION(1000);
76 constexpr float ANIMATION_CURVE_VELOCITY_LIGHT_OR_MIDDLE = 10.0f;
77 constexpr float ANIMATION_CURVE_VELOCITY_HEAVY = 0.0f;
78 constexpr float ANIMATION_CURVE_MASS = 1.0f;
79 constexpr float ANIMATION_CURVE_STIFFNESS_LIGHT = 410.0f;
80 constexpr float ANIMATION_CURVE_STIFFNESS_MIDDLE = 350.0f;
81 constexpr float ANIMATION_CURVE_STIFFNESS_HEAVY = 240.0f;
82 constexpr float ANIMATION_CURVE_DAMPING_LIGHT = 38.0f;
83 constexpr float ANIMATION_CURVE_DAMPING_MIDDLE = 35.0f;
84 constexpr float ANIMATION_CURVE_DAMPING_HEAVY = 28.0f;
85 constexpr float DEFAULT_SCALE_LIGHT = 0.9f;
86 constexpr float DEFAULT_SCALE_MIDDLE_OR_HEAVY = 0.95f;
87 constexpr int32_t DEFAULT_OPTION_DURATION = 100;
88 constexpr int32_t PLATFORM_VERSION_TEN = 10;
89 constexpr int32_t PARTICLE_DEFAULT_COLOR = 0xFFFFFFFF;
90 constexpr float PARTICLE_DEFAULT_OPACITY = 1.0f;
91 constexpr float PARTICLE_DEFAULT_SCALE = 1.0f;
92 constexpr float PARTICLE_DEFAULT_SPEED = 0.0f;
93 constexpr float PARTICLE_DEFAULT_ANGLE = 0.0f;
94 constexpr float PARTICLE_DEFAULT_SPIN = 0.0f;
95 constexpr int64_t PARTICLE_DEFAULT_LIFETIME = 1000;
96 constexpr int32_t PARTICLE_DEFAULT_EMITTER_RATE = 5;
97 constexpr uint32_t DRAW_REGION_CONTENT_MODIFIER_INDEX = 0;
98 constexpr uint32_t DRAW_REGION_OVERLAY_MODIFIER_INDEX = 1;
99 constexpr uint32_t DRAW_REGION_FOCUS_MODIFIER_INDEX = 2;
100 constexpr uint32_t DRAW_REGION_ACCESSIBILITY_FOCUS_MODIFIER_INDEX = 3;
101 constexpr uint32_t DRAW_REGION_OVERLAY_TEXT_MODIFIER_INDEX = 4;
102 constexpr uint32_t DRAW_REGION_DEBUG_BOUNDARY_MODIFIER_INDEX = 5;
103 constexpr uint32_t DRAW_REGION_FOREGROUND_MODIFIER_INDEX = 6;
104 constexpr int32_t RIGHT_ANGLE = 90;
105 constexpr int32_t STRAIGHT_ANGLE = 180;
106 constexpr int32_t REFLEX_ANGLE = 270;
107 constexpr int32_t FULL_ROTATION = 360;
108 constexpr int32_t ACCESSIBILITY_FOCUS_WITHOUT_EVENT = -2100001;
109 const Color MASK_COLOR = Color::FromARGB(25, 0, 0, 0);
110 const Color DEFAULT_MASK_COLOR = Color::FromARGB(0, 0, 0, 0);
111 constexpr Dimension DASH_GEP_WIDTH = -1.0_px;
112 constexpr uint16_t NO_FORCE_ROUND = static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_START) |
113                                     static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_TOP) |
114                                     static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_END) |
115                                     static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_BOTTOM);
116 
DrawNodeChangeCallback(std::shared_ptr<RSNode> rsNode,bool isPositionZ)117 static void DrawNodeChangeCallback(std::shared_ptr<RSNode> rsNode, bool isPositionZ)
118 {
119     if (!SystemProperties::GetContainerDeleteFlag()) {
120         return;
121     }
122     CHECK_NULL_VOID(rsNode);
123     auto uiNode = ElementRegister::GetInstance()->GetUINodeById(rsNode->GetFrameNodeId());
124     auto frameNode = AceType::DynamicCast<NG::FrameNode>(uiNode);
125     CHECK_NULL_VOID(frameNode);
126     if (isPositionZ) {
127         frameNode->SetPositionZ(true);
128         auto pipeline = uiNode->GetContext();
129         CHECK_NULL_VOID(pipeline);
130         pipeline->AddPositionZNode(rsNode->GetFrameNodeId());
131         return;
132     }
133 
134     if (frameNode->GetRenderContext()) {
135         frameNode->GetRenderContext()->AddNodeToRsTree();
136     }
137 }
138 
SetDrawNodeChangeCallback()139 bool SetDrawNodeChangeCallback()
140 {
141     Rosen::RSNode::SetDrawNodeChangeCallback(DrawNodeChangeCallback);
142     return true;
143 }
144 
GetRosenGravity(RenderFit renderFit)145 Rosen::Gravity GetRosenGravity(RenderFit renderFit)
146 {
147     static const LinearEnumMapNode<RenderFit, Rosen::Gravity> gravityMap[] = {
148         { RenderFit::CENTER, Rosen::Gravity::CENTER },
149         { RenderFit::TOP, Rosen::Gravity::TOP },
150         { RenderFit::BOTTOM, Rosen::Gravity::BOTTOM },
151         { RenderFit::LEFT, Rosen::Gravity::LEFT },
152         { RenderFit::RIGHT, Rosen::Gravity::RIGHT },
153         { RenderFit::TOP_LEFT, Rosen::Gravity::TOP_LEFT },
154         { RenderFit::TOP_RIGHT, Rosen::Gravity::TOP_RIGHT },
155         { RenderFit::BOTTOM_LEFT, Rosen::Gravity::BOTTOM_LEFT },
156         { RenderFit::BOTTOM_RIGHT, Rosen::Gravity::BOTTOM_RIGHT },
157         { RenderFit::RESIZE_FILL, Rosen::Gravity::RESIZE },
158         { RenderFit::RESIZE_CONTAIN, Rosen::Gravity::RESIZE_ASPECT },
159         { RenderFit::RESIZE_CONTAIN_TOP_LEFT, Rosen::Gravity::RESIZE_ASPECT_TOP_LEFT },
160         { RenderFit::RESIZE_CONTAIN_BOTTOM_RIGHT, Rosen::Gravity::RESIZE_ASPECT_BOTTOM_RIGHT },
161         { RenderFit::RESIZE_COVER, Rosen::Gravity::RESIZE_ASPECT_FILL },
162         { RenderFit::RESIZE_COVER_TOP_LEFT, Rosen::Gravity::RESIZE_ASPECT_FILL_TOP_LEFT },
163         { RenderFit::RESIZE_COVER_BOTTOM_RIGHT, Rosen::Gravity::RESIZE_ASPECT_FILL_BOTTOM_RIGHT },
164     };
165     int64_t idx = BinarySearchFindIndex(gravityMap, ArraySize(gravityMap), renderFit);
166     return idx != -1 ? gravityMap[idx].value : Rosen::Gravity::DEFAULT;
167 }
168 
GetResourceColorMode(PipelineContext * pipeline)169 ColorMode GetResourceColorMode(PipelineContext* pipeline)
170 {
171     auto themeManager = pipeline->GetThemeManager();
172     CHECK_NULL_RETURN(themeManager, ColorMode::LIGHT);
173     auto themeConstants = themeManager->GetThemeConstants();
174     CHECK_NULL_RETURN(themeConstants, ColorMode::LIGHT);
175     auto resourceAdapter = themeConstants->GetResourceAdapter();
176     CHECK_NULL_RETURN(resourceAdapter, ColorMode::LIGHT);
177     return resourceAdapter->GetResourceColorMode();
178 }
179 
CreateRSMaterialFilter(const BlurStyleOption & blurStyleOption,PipelineContext * pipeline,const SysOptions & sysOptions)180 std::shared_ptr<Rosen::RSFilter> CreateRSMaterialFilter(
181     const BlurStyleOption& blurStyleOption, PipelineContext* pipeline, const SysOptions& sysOptions)
182 {
183     auto blurStyleTheme = pipeline->GetTheme<BlurStyleTheme>();
184     if (!blurStyleTheme) {
185         LOGW("cannot find theme of blurStyle, create blurStyle failed");
186         return nullptr;
187     }
188     ThemeColorMode colorMode = blurStyleOption.colorMode;
189     if (blurStyleOption.colorMode == ThemeColorMode::SYSTEM) {
190         colorMode = GetResourceColorMode(pipeline) == ColorMode::DARK ? ThemeColorMode::DARK : ThemeColorMode::LIGHT;
191     }
192     auto blurParam = blurStyleTheme->GetBlurParameter(blurStyleOption.blurStyle, colorMode);
193     CHECK_NULL_RETURN(blurParam, nullptr);
194     auto ratio = blurStyleOption.scale;
195     auto maskColor = blurParam->maskColor.BlendOpacity(ratio);
196     auto radiusPx = blurParam->radius * pipeline->GetDipScale();
197     auto radiusBlur = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx) * ratio;
198     auto saturation = (blurParam->saturation - 1) * ratio + 1.0;
199     auto brightness = (blurParam->brightness - 1) * ratio + 1.0;
200     return Rosen::RSFilter::CreateMaterialFilter(radiusBlur, saturation, brightness, maskColor.GetValue(),
201         static_cast<Rosen::BLUR_COLOR_MODE>(blurStyleOption.adaptiveColor), sysOptions.disableSystemAdaptation);
202 }
203 
GetRsPen(uint32_t strokeColor,float strokeWidth)204 RSPen GetRsPen(uint32_t strokeColor, float strokeWidth)
205 {
206     RSColor rsStrokeColor;
207     rsStrokeColor.SetColorQuad(strokeColor);
208 
209     RSPen pen;
210     pen.SetColor(rsStrokeColor);
211     pen.SetWidth(strokeWidth);
212 
213     return pen;
214 }
215 
GetRsBrush(uint32_t fillColor)216 RSBrush GetRsBrush(uint32_t fillColor)
217 {
218     RSColor color;
219     color.SetColorQuad(fillColor);
220     RSBrush brush(color);
221 
222     return brush;
223 }
224 
225 template<typename ModifierName, typename T>
GetAnimatablePropertyStagingValue(std::shared_ptr<ModifierName> & modifier)226 T GetAnimatablePropertyStagingValue(std::shared_ptr<ModifierName>& modifier)
227 {
228     CHECK_NULL_RETURN(modifier, {});
229     auto property = std::static_pointer_cast<Rosen::RSAnimatableProperty<T>>(modifier->GetProperty());
230     CHECK_NULL_RETURN(property, {});
231     return property->GetStagingValue();
232 }
233 } // namespace
234 
235 bool RosenRenderContext::initDrawNodeChangeCallback_ = SetDrawNodeChangeCallback();
236 
ConvertDimensionToScaleBySize(const Dimension & dimension,float size)237 float RosenRenderContext::ConvertDimensionToScaleBySize(const Dimension& dimension, float size)
238 {
239     if (dimension.Unit() == DimensionUnit::PERCENT) {
240         return static_cast<float>(dimension.Value());
241     }
242     return size > 0.0f ? static_cast<float>(dimension.ConvertToPx() / size) : 0.5f;
243 }
244 
~RosenRenderContext()245 RosenRenderContext::~RosenRenderContext()
246 {
247     StopRecordingIfNeeded();
248     DetachModifiers();
249     auto host = GetHost();
250     CHECK_NULL_VOID(host);
251     host->RemoveExtraCustomProperty("RS_NODE");
252 }
253 
DetachModifiers()254 void RosenRenderContext::DetachModifiers()
255 {
256     auto pipeline = PipelineContext::GetCurrentContextPtrSafelyWithCheck();
257     if (pipeline && densityChangedCallbackId_ != DEFAULT_CALLBACK_ID) {
258         pipeline->UnregisterDensityChangedCallback(densityChangedCallbackId_);
259     }
260     CHECK_NULL_VOID(rsNode_ && rsNode_->GetType() == Rosen::RSUINodeType::SURFACE_NODE);
261     if (transitionEffect_) {
262         transitionEffect_->Detach(this);
263     }
264     if (translateXYUserModifier_) {
265         rsNode_->RemoveModifier(translateXYUserModifier_);
266     }
267     if (translateZUserModifier_) {
268         rsNode_->RemoveModifier(translateZUserModifier_);
269     }
270     if (scaleXYUserModifier_) {
271         rsNode_->RemoveModifier(scaleXYUserModifier_);
272     }
273     if (pipeline) {
274         pipeline->RequestFrame();
275     }
276 }
277 
StartRecording()278 void RosenRenderContext::StartRecording()
279 {
280     CHECK_NULL_VOID(rsNode_);
281     auto rsCanvasNode = rsNode_->ReinterpretCastTo<Rosen::RSCanvasNode>();
282     CHECK_NULL_VOID(rsCanvasNode);
283     rsCanvasNode->BeginRecording(ceil(rsCanvasNode->GetPaintWidth()), ceil(rsCanvasNode->GetPaintHeight()));
284 }
285 
StopRecordingIfNeeded()286 void RosenRenderContext::StopRecordingIfNeeded()
287 {
288     auto rsCanvasNode = Rosen::RSNode::ReinterpretCast<Rosen::RSCanvasNode>(rsNode_);
289     if (rsCanvasNode) {
290         rsCanvasNode->FinishRecording();
291     }
292 }
293 
OnNodeAppear(bool recursive)294 void RosenRenderContext::OnNodeAppear(bool recursive)
295 {
296     isDisappearing_ = false;
297     auto host = GetHost();
298     CHECK_NULL_VOID(host);
299     // restore eventHub state when node appears.
300     auto eventHub = host->GetEventHubOnly<EventHub>();
301     if (eventHub) {
302         eventHub->RestoreEnabled();
303     }
304     if (recursive && !propTransitionAppearing_ && !transitionEffect_) {
305         // recursive and has no transition, no need to handle transition.
306         return;
307     }
308 
309     isBreakingPoint_ = !recursive;
310     if (isSynced_) {
311         // has set size before, trigger transition directly.
312         auto rect = GetPaintRectWithoutTransform();
313         NotifyTransitionInner(rect.GetSize(), true);
314         return;
315     }
316     // pending transition in animation, will start on first layout
317     firstTransitionIn_ = true;
318 }
319 
OnNodeDisappear(bool recursive)320 void RosenRenderContext::OnNodeDisappear(bool recursive)
321 {
322     isDisappearing_ = true;
323     bool noneOrDefaultTransition = !propTransitionDisappearing_ && (!transitionEffect_ || hasDefaultTransition_);
324     if (recursive && noneOrDefaultTransition) {
325         // recursive, and has no transition or has default transition, no need to trigger transition.
326         return;
327     }
328     CHECK_NULL_VOID(rsNode_);
329     auto host = GetHost();
330     if (!recursive && host && host->GetEventHub<EventHub>()) {
331         host->GetEventHub<EventHub>()->SetEnabledInternal(false);
332     }
333     auto rect = GetPaintRectWithoutTransform();
334     // only start default transition on the break point of render node tree.
335     isBreakingPoint_ = !recursive;
336     NotifyTransitionInner(rect.GetSize(), false);
337 }
338 
SetPivot(float xPivot,float yPivot,float zPivot)339 void RosenRenderContext::SetPivot(float xPivot, float yPivot, float zPivot)
340 {
341     // change pivot without animation
342     CHECK_NULL_VOID(rsNode_);
343     auto changed = true;
344     if (pivotProperty_) {
345         changed = pivotProperty_->Get().x_ != xPivot || pivotProperty_->Get().y_ != yPivot;
346         pivotProperty_->Set({ xPivot, yPivot });
347     } else {
348         pivotProperty_ = std::make_shared<Rosen::RSProperty<Rosen::Vector2f>>(Rosen::Vector2f(xPivot, yPivot));
349         auto modifier = std::make_shared<Rosen::RSPivotModifier>(pivotProperty_);
350         rsNode_->AddModifier(modifier);
351     }
352     rsNode_->SetPivotZ(zPivot);
353     NotifyHostTransformUpdated(changed);
354 }
355 
SetTransitionPivot(const SizeF & frameSize,bool transitionIn)356 void RosenRenderContext::SetTransitionPivot(const SizeF& frameSize, bool transitionIn)
357 {
358     auto& transitionEffect = transitionIn ? propTransitionAppearing_ : propTransitionDisappearing_;
359     CHECK_NULL_VOID(transitionEffect);
360     float xPivot = 0.0f;
361     float yPivot = 0.0f;
362     float zPivot = 0.0f;
363     if (transitionEffect->HasRotate()) {
364         xPivot = ConvertDimensionToScaleBySize(transitionEffect->GetRotateValue().centerX, frameSize.Width());
365         yPivot = ConvertDimensionToScaleBySize(transitionEffect->GetRotateValue().centerY, frameSize.Height());
366         zPivot = static_cast<float>(transitionEffect->GetRotateValue().centerZ.ConvertToVp());
367     } else if (transitionEffect->HasScale()) {
368         xPivot = ConvertDimensionToScaleBySize(transitionEffect->GetScaleValue().centerX, frameSize.Width());
369         yPivot = ConvertDimensionToScaleBySize(transitionEffect->GetScaleValue().centerY, frameSize.Height());
370     } else {
371         return;
372     }
373     SetPivot(xPivot, yPivot, zPivot);
374 }
375 
SetSurfaceChangedCallBack(const std::function<void (float,float,float,float)> & callback)376 void RosenRenderContext::SetSurfaceChangedCallBack(const std::function<void(float, float, float, float)>& callback)
377 {
378 #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
379     if (rsNode_) {
380         RSRenderThread::Instance().AddSurfaceChangedCallBack(rsNode_->GetId(), callback);
381     }
382 #endif
383 }
384 
RemoveSurfaceChangedCallBack()385 void RosenRenderContext::RemoveSurfaceChangedCallBack()
386 {
387 #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
388     if (rsNode_) {
389         RSRenderThread::Instance().RemoveSurfaceChangedCallBack(rsNode_->GetId());
390     }
391 #endif
392 }
393 
AddFrameNodeInfoToRsNode()394 void RosenRenderContext::AddFrameNodeInfoToRsNode()
395 {
396     if (rsNode_) {
397         rsNode_->SetInstanceId(Container::CurrentId());
398         auto frameNodePtr = GetHost();
399         CHECK_NULL_VOID(frameNodePtr);
400         rsNode_->SetFrameNodeInfo(frameNodePtr->GetId(), frameNodePtr->GetTag());
401     }
402 }
403 
SetHostNode(const WeakPtr<FrameNode> & host)404 void RosenRenderContext::SetHostNode(const WeakPtr<FrameNode>& host)
405 {
406     RenderContext::SetHostNode(host);
407     AddFrameNodeInfoToRsNode();
408     auto frameNode = GetHost();
409     CHECK_NULL_VOID(frameNode);
410     frameNode->AddExtraCustomProperty("RS_NODE", rsNode_.get());
411 }
412 
InitContext(bool isRoot,const std::optional<ContextParam> & param,bool isLayoutNode)413 void RosenRenderContext::InitContext(bool isRoot, const std::optional<ContextParam>& param, bool isLayoutNode)
414 {
415     if (isLayoutNode) {
416         return;
417     }
418     InitContext(isRoot, param);
419 }
420 
InitContext(bool isRoot,const std::optional<ContextParam> & param)421 void RosenRenderContext::InitContext(bool isRoot, const std::optional<ContextParam>& param)
422 {
423     // skip if node already created
424     CHECK_NULL_VOID(!rsNode_);
425     auto isTextureExportNode = ViewStackProcessor::GetInstance()->IsExportTexture();
426     if (isRoot) {
427         rsNode_ = Rosen::RSRootNode::Create(false, isTextureExportNode);
428         AddFrameNodeInfoToRsNode();
429         return;
430     } else if (!param.has_value()) {
431         rsNode_ = Rosen::RSCanvasNode::Create(false, isTextureExportNode);
432         AddFrameNodeInfoToRsNode();
433         return;
434     }
435 
436     patternType_ = param->patternType;
437 
438     // create proper RSNode base on input
439     switch (param->type) {
440         case ContextType::CANVAS:
441             rsNode_ = Rosen::RSCanvasNode::Create(false, isTextureExportNode);
442             break;
443         case ContextType::ROOT:
444             rsNode_ = Rosen::RSRootNode::Create(false, isTextureExportNode);
445             break;
446         case ContextType::SURFACE: {
447             Rosen::RSSurfaceNodeConfig surfaceNodeConfig = { .SurfaceNodeName = param->surfaceName.value_or(""),
448                 .isTextureExportNode = isTextureExportNode };
449             rsNode_ = Rosen::RSSurfaceNode::Create(surfaceNodeConfig, false);
450             break;
451         }
452         case ContextType::HARDWARE_SURFACE: {
453             rsNode_ = CreateHardwareSurface(param, isTextureExportNode);
454             break;
455         }
456 #ifdef RENDER_EXTRACT_SUPPORTED
457         case ContextType::HARDWARE_TEXTURE: {
458             rsNode_ = CreateHardwareTexture(param, isTextureExportNode);
459             break;
460         }
461 #endif
462         case ContextType::EFFECT:
463             rsNode_ = Rosen::RSEffectNode::Create(false, isTextureExportNode);
464             break;
465         case ContextType::INCREMENTAL_CANVAS:
466             rsNode_ = Rosen::RSCanvasDrawingNode::Create(false, isTextureExportNode);
467             break;
468         case ContextType::EXTERNAL:
469             break;
470         default:
471             break;
472     }
473 
474     AddFrameNodeInfoToRsNode();
475 }
476 
CreateHardwareSurface(const std::optional<ContextParam> & param,bool isTextureExportNode)477 std::shared_ptr<Rosen::RSNode> RosenRenderContext::CreateHardwareSurface(
478     const std::optional<ContextParam>& param, bool isTextureExportNode)
479 {
480     Rosen::RSSurfaceNodeConfig surfaceNodeConfig = { .SurfaceNodeName = param->surfaceName.value_or(""),
481         .isTextureExportNode = isTextureExportNode, .isSync = true };
482     auto surfaceNode = Rosen::RSSurfaceNode::Create(surfaceNodeConfig, false);
483     if (surfaceNode) {
484         if (param->patternType == PatternType::VIDEO) {
485             surfaceNode->SetHardwareEnabled(true, SelfDrawingNodeType::VIDEO);
486         } else if (param->patternType == PatternType::XCOM) {
487             surfaceNode->SetHardwareEnabled(true, SelfDrawingNodeType::XCOM);
488         } else {
489             surfaceNode->SetHardwareEnabled(true, SelfDrawingNodeType::DEFAULT);
490         }
491         surfaceNode->SetApiCompatibleVersion(Container::GetCurrentApiTargetVersion());
492     }
493     return surfaceNode;
494 }
495 
496 #ifdef RENDER_EXTRACT_SUPPORTED
CreateHardwareTexture(const std::optional<ContextParam> & param,bool isTextureExportNode)497 std::shared_ptr<Rosen::RSNode> RosenRenderContext::CreateHardwareTexture(
498     const std::optional<ContextParam>& param, bool isTextureExportNode)
499 {
500     Rosen::RSSurfaceNodeConfig surfaceNodeConfig = { .SurfaceNodeName = param->surfaceName.value_or(""),
501         .isTextureExportNode = isTextureExportNode };
502     auto surfaceNode = Rosen::RSSurfaceNode::Create(surfaceNodeConfig, RSSurfaceNodeType::SURFACE_TEXTURE_NODE, false);
503     return surfaceNode;
504 }
505 #endif
506 
SetSandBox(const std::optional<OffsetF> & parentPosition,bool force)507 void RosenRenderContext::SetSandBox(const std::optional<OffsetF>& parentPosition, bool force)
508 {
509     CHECK_NULL_VOID(rsNode_);
510     auto host = GetHost();
511     CHECK_NULL_VOID(host);
512     if (parentPosition.has_value()) {
513         if (!force) {
514             sandBoxCount_++;
515         }
516         Rosen::Vector2f value = { parentPosition.value().GetX(), parentPosition.value().GetY() };
517         TAG_LOGI(AceLogTag::ACE_GEOMETRY_TRANSITION, "node[%{public}s] Set SandBox",
518             std::to_string(rsNode_->GetId()).c_str());
519         rsNode_->SetSandBox(value);
520     } else {
521         if (!force) {
522             sandBoxCount_--;
523             if (sandBoxCount_ > 0) {
524                 return;
525             }
526         }
527         TAG_LOGI(AceLogTag::ACE_GEOMETRY_TRANSITION, "node[%{public}s] Remove SandBox",
528             std::to_string(rsNode_->GetId()).c_str());
529         sandBoxCount_ = 0;
530         rsNode_->SetSandBox(std::nullopt);
531     }
532 }
533 
SetFrameWithoutAnimation(const RectF & paintRect)534 void RosenRenderContext::SetFrameWithoutAnimation(const RectF& paintRect)
535 {
536     CHECK_NULL_VOID(rsNode_ && paintRect.IsValid());
537     RSNode::ExecuteWithoutAnimation([&]() { SyncGeometryFrame(paintRect); });
538 }
539 
SyncGeometryProperties(GeometryNode *,bool,uint8_t)540 void RosenRenderContext::SyncGeometryProperties(GeometryNode* /*geometryNode*/, bool /* isRound */, uint8_t /* flag */)
541 {
542     CHECK_NULL_VOID(rsNode_);
543     auto host = GetHost();
544     CHECK_NULL_VOID(host);
545     if (isNeedAnimate_) {
546         SyncGeometryProperties(paintRect_);
547     } else {
548         RSNode::ExecuteWithoutAnimation([&]() { SyncGeometryProperties(paintRect_); });
549     }
550     host->OnPixelRoundFinish(paintRect_.GetSize());
551 }
552 
SyncGeometryFrame(const RectF & paintRect)553 void RosenRenderContext::SyncGeometryFrame(const RectF& paintRect)
554 {
555     CHECK_NULL_VOID(rsNode_);
556     rsNode_->SetBounds(paintRect.GetX(), paintRect.GetY(), paintRect.Width(), paintRect.Height());
557     if (rsTextureExport_) {
558         rsTextureExport_->UpdateBufferInfo(paintRect.GetX(), paintRect.GetY(), paintRect.Width(), paintRect.Height());
559     }
560     if (handleChildBounds_) {
561         SetChildBounds(paintRect);
562     }
563     if (useContentRectForRSFrame_) {
564         SetContentRectToFrame(paintRect);
565     } else {
566         rsNode_->SetFrame(paintRect.GetX(), paintRect.GetY(), paintRect.Width(), paintRect.Height());
567     }
568     if (frameOffset_.has_value()) {
569         rsNode_->SetFrame(paintRect.GetX() + frameOffset_->GetX(), paintRect.GetY() + frameOffset_->GetY(),
570             paintRect.Width(), paintRect.Height());
571     }
572     auto host = GetHost();
573     CHECK_NULL_VOID(host);
574     host->OnSyncGeometryFrameFinish(paintRect);
575 }
576 
SetChildBounds(const RectF & paintRect) const577 void RosenRenderContext::SetChildBounds(const RectF& paintRect) const
578 {
579     auto childRsNodeId = rsNode_->GetChildIdByIndex(0);
580     if (childRsNodeId.has_value()) {
581         auto childRsNode = Rosen::RSNodeMap::Instance().GetNode(childRsNodeId.value());
582         childRsNode->SetBounds(0.0f, 0.0f, paintRect.Width(), paintRect.Height());
583     }
584 }
585 
SyncGeometryProperties(const RectF & paintRect)586 void RosenRenderContext::SyncGeometryProperties(const RectF& paintRect)
587 {
588     CHECK_NULL_VOID(rsNode_);
589     if (isDisappearing_ && !paintRect.IsValid()) {
590         return;
591     }
592     if (SystemProperties::GetSyncDebugTraceEnabled()) {
593         auto host = GetHost();
594         ACE_LAYOUT_SCOPED_TRACE("SyncGeometryProperties [%s][self:%d] set bounds %s", host->GetTag().c_str(),
595             host->GetId(), paintRect.ToString().c_str());
596     }
597     if (extraOffset_.has_value()) {
598         SyncGeometryFrame(paintRect + extraOffset_.value());
599     } else {
600         SyncGeometryFrame(paintRect);
601     }
602 
603     if (!isSynced_) {
604         isSynced_ = true;
605         auto borderRadius = GetBorderRadius();
606         if (borderRadius.has_value()) {
607             OnBorderRadiusUpdate(borderRadius.value());
608         }
609     }
610 
611     if (firstTransitionIn_) {
612         // need to perform transitionIn early so not influence the following SetPivot
613         NotifyTransitionInner(paintRect.GetSize(), true);
614         firstTransitionIn_ = false;
615     }
616 
617     SyncPartialRsProperties();
618     SyncAdditionalGeometryProperties(paintRect);
619 }
620 
SyncAdditionalGeometryProperties(const RectF & paintRect)621 void RosenRenderContext::SyncAdditionalGeometryProperties(const RectF& paintRect)
622 {
623     if (propPointLight_ && propPointLight_->HasLightPosition()) {
624         // if lightPosition unit is percent, it is related with frameSize
625         OnLightPositionUpdate(propPointLight_->GetLightPositionValue());
626     }
627 
628     if (bgLoadingCtx_ && bgImage_) {
629         PaintBackground();
630     }
631 
632     auto sourceFromImage = GetBorderSourceFromImage().value_or(false);
633     if (sourceFromImage && bdImageLoadingCtx_ && bdImage_) {
634         PaintBorderImage();
635     } else if (!sourceFromImage && GetBorderImageGradient()) {
636         PaintBorderImageGradient();
637     }
638 
639     if (propGradient_) {
640         PaintGradient(paintRect.GetSize());
641     }
642 
643     if (propClip_) {
644         PaintClip(paintRect.GetSize());
645     }
646 
647     if (HasProgressMask() && GetProgressMaskValue()) {
648         PaintProgressMask();
649     }
650 
651     if (propGraphics_) {
652         PaintGraphics();
653     }
654 
655     if (propOverlay_) {
656         PaintOverlayText();
657     }
658 
659     if (SystemProperties::GetDebugBoundaryEnabled()) {
660         PaintDebugBoundary(true);
661     }
662 
663     if (propParticleOptionArray_.has_value()) {
664         if (!measureTriggered_ || particleAnimationPlaying_) {
665             measureTriggered_ = true;
666             OnParticleOptionArrayUpdate(propParticleOptionArray_.value());
667         }
668     }
669 }
670 
PaintDebugBoundary(bool flag)671 void RosenRenderContext::PaintDebugBoundary(bool flag)
672 {
673     if (!flag && !debugBoundaryModifier_) {
674         return;
675     }
676     if (!NeedDebugBoundary()) {
677         return;
678     }
679     CHECK_NULL_VOID(rsNode_);
680     auto host = GetHost();
681     CHECK_NULL_VOID(host);
682     auto geometryNode = host->GetGeometryNode();
683     auto paintTask = [contentSize = geometryNode->GetFrameSize(), frameSize = geometryNode->GetMarginFrameSize(),
684                          offset = geometryNode->GetMarginFrameOffset(), frameOffset = geometryNode->GetFrameOffset(),
685                          flag](RSCanvas& rsCanvas) mutable {
686         if (!flag) {
687             return;
688         }
689         DebugBoundaryPainter painter(contentSize, frameSize);
690         painter.SetFrameOffset(frameOffset);
691         painter.DrawDebugBoundaries(rsCanvas, offset);
692     };
693 
694     if (!debugBoundaryModifier_ && rsNode_->IsInstanceOf<Rosen::RSCanvasNode>()) {
695         debugBoundaryModifier_ = std::make_shared<DebugBoundaryModifier>();
696         debugBoundaryModifier_->SetPaintTask(std::move(paintTask));
697         debugBoundaryModifier_->SetNoNeedUICaptured(true);
698         auto rect = GetPaintRectWithoutTransform();
699         auto marginOffset = geometryNode->GetMarginFrameOffset();
700         std::shared_ptr<Rosen::RectF> drawRect =
701             std::make_shared<Rosen::RectF>(marginOffset.GetX() - rect.GetX(), marginOffset.GetY() - rect.GetY(),
702                 geometryNode->GetMarginFrameSize().Width(), geometryNode->GetMarginFrameSize().Height());
703         UpdateDrawRegion(DRAW_REGION_DEBUG_BOUNDARY_MODIFIER_INDEX, drawRect);
704         rsNode_->AddModifier(debugBoundaryModifier_);
705         // SetCustomData(AttachProperty to rs modifier) must be called after AddModifier.
706         debugBoundaryModifier_->SetCustomData(flag);
707     } else if (debugBoundaryModifier_) {
708         debugBoundaryModifier_->SetPaintTask(std::move(paintTask));
709         auto rect = GetPaintRectWithoutTransform();
710         auto marginOffset = geometryNode->GetMarginFrameOffset();
711         std::shared_ptr<Rosen::RectF> drawRect =
712             std::make_shared<Rosen::RectF>(marginOffset.GetX() - rect.GetX(), marginOffset.GetY() - rect.GetY(),
713                 geometryNode->GetMarginFrameSize().Width(), geometryNode->GetMarginFrameSize().Height());
714         UpdateDrawRegion(DRAW_REGION_DEBUG_BOUNDARY_MODIFIER_INDEX, drawRect);
715         debugBoundaryModifier_->SetCustomData(flag);
716     }
717 }
718 
OnBackgroundColorUpdate(const Color & value)719 void RosenRenderContext::OnBackgroundColorUpdate(const Color& value)
720 {
721     CHECK_NULL_VOID(rsNode_);
722     rsNode_->SetBackgroundColor(value.GetValue());
723     RequestNextFrame();
724 }
725 
OnForegroundColorUpdate(const Color & value)726 void RosenRenderContext::OnForegroundColorUpdate(const Color& value)
727 {
728     CHECK_NULL_VOID(rsNode_);
729     rsNode_->SetEnvForegroundColor(value.GetValue());
730     RequestNextFrame();
731     auto host = GetHost();
732     CHECK_NULL_VOID(host);
733     host->OnPropertyChangeMeasure();
734 }
735 
OnForegroundEffectUpdate(float radius)736 void RosenRenderContext::OnForegroundEffectUpdate(float radius)
737 {
738     CHECK_NULL_VOID(rsNode_);
739     auto context = PipelineBase::GetCurrentContext();
740     CHECK_NULL_VOID(context);
741     CalcDimension value;
742     value.SetValue(static_cast<double>(radius));
743     float radiusPx = context->NormalizeToPx(value);
744     float foreRadius = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx);
745     rsNode_->SetForegroundEffectRadius(foreRadius);
746     RequestNextFrame();
747 }
748 
OnForegroundColorStrategyUpdate(const ForegroundColorStrategy & value)749 void RosenRenderContext::OnForegroundColorStrategyUpdate(const ForegroundColorStrategy& value)
750 {
751     CHECK_NULL_VOID(rsNode_);
752     Rosen::ForegroundColorStrategyType rsStrategy = Rosen::ForegroundColorStrategyType::INVALID;
753     switch (value) {
754         case ForegroundColorStrategy::INVERT:
755             rsStrategy = Rosen::ForegroundColorStrategyType::INVERT_BACKGROUNDCOLOR;
756             break;
757         default:
758             break;
759     }
760     rsNode_->SetEnvForegroundColorStrategy(rsStrategy);
761     RequestNextFrame();
762 }
763 
CreateBgImageDataReadyCallback()764 DataReadyNotifyTask RosenRenderContext::CreateBgImageDataReadyCallback()
765 {
766     auto task = [weak = WeakClaim(this)](const ImageSourceInfo& sourceInfo) {
767         if (SystemProperties::GetDebugEnabled()) {
768             TAG_LOGD(AceLogTag::ACE_IMAGE, "backgroundImageDataReady src = %{private}s", sourceInfo.ToString().c_str());
769         }
770         auto rosenRenderContext = weak.Upgrade();
771         CHECK_NULL_VOID(rosenRenderContext);
772         auto imageSourceInfo = rosenRenderContext->GetBackgroundImage().value_or(ImageSourceInfo(""));
773         if (imageSourceInfo != sourceInfo) {
774             return;
775         }
776         rosenRenderContext->bgLoadingCtx_->MakeCanvasImage(SizeF(), true, ImageFit::NONE);
777     };
778     return task;
779 }
780 
CreateBgImageLoadSuccessCallback()781 LoadSuccessNotifyTask RosenRenderContext::CreateBgImageLoadSuccessCallback()
782 {
783     auto task = [weak = WeakClaim(this)](const ImageSourceInfo& sourceInfo) {
784         if (SystemProperties::GetDebugEnabled()) {
785             TAG_LOGD(
786                 AceLogTag::ACE_IMAGE, "backgroundImageLoadSuccess src = %{private}s", sourceInfo.ToString().c_str());
787         }
788         auto ctx = weak.Upgrade();
789         CHECK_NULL_VOID(ctx);
790         auto imageSourceInfo = ctx->GetBackgroundImage().value_or(ImageSourceInfo(""));
791         if (imageSourceInfo != sourceInfo) {
792             return;
793         }
794         ctx->bgImage_ = ctx->bgLoadingCtx_->MoveCanvasImage();
795         CHECK_NULL_VOID(ctx->bgImage_);
796         if (ctx->GetHost()->GetGeometryNode()->GetFrameSize().IsPositive()) {
797             ctx->PaintBackground();
798             ctx->RequestNextFrame();
799         }
800     };
801     return task;
802 }
803 
PaintBackground()804 void RosenRenderContext::PaintBackground()
805 {
806     CHECK_NULL_VOID(rsNode_);
807     if (InstanceOf<PixelMapImage>(bgImage_)) {
808         PaintPixmapBgImage();
809     } else if (InstanceOf<DrawingImage>(bgImage_)) {
810         PaintRSBgImage();
811     } else {
812         if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_TWELVE)) {
813             rsNode_->SetBgImage(nullptr);
814         }
815         return;
816     }
817     auto srcSize = bgLoadingCtx_->GetImageSize();
818     SizeF renderSize = ImagePainter::CalculateBgImageSize(paintRect_.GetSize(), srcSize, GetBackgroundImageSize());
819     OffsetF positionOffset =
820         ImagePainter::CalculateBgImagePosition(paintRect_.GetSize(), renderSize, GetBackgroundImagePosition());
821     auto slice = GetBackgroundImageResizableSliceValue(ImageResizableSlice());
822     Rosen::Vector4f rect(slice.left.ConvertToPxWithSize(srcSize.Width()),
823         slice.top.ConvertToPxWithSize(srcSize.Height()),
824         srcSize.Width() - (slice.left + slice.right).ConvertToPxWithSize(srcSize.Width()),
825         srcSize.Height() - (slice.top + slice.bottom).ConvertToPxWithSize(srcSize.Height()));
826     rsNode_->SetBgImageWidth(renderSize.Width());
827     rsNode_->SetBgImageHeight(renderSize.Height());
828     rsNode_->SetBgImagePositionX(positionOffset.GetX());
829     rsNode_->SetBgImagePositionY(positionOffset.GetY());
830     rsNode_->SetBgImageInnerRect(rect);
831 }
832 
OnBackgroundImageUpdate(const ImageSourceInfo & src)833 void RosenRenderContext::OnBackgroundImageUpdate(const ImageSourceInfo& src)
834 {
835     CHECK_NULL_VOID(rsNode_);
836     if (src.GetSrc().empty() && src.GetPixmap() == nullptr) {
837         bgImage_ = nullptr;
838         bgLoadingCtx_ = nullptr;
839         auto frameNode = GetHost();
840         if (frameNode) {
841             frameNode->SetColorModeUpdateCallback(nullptr);
842         }
843         PaintBackground();
844         return;
845     }
846     if (!bgLoadingCtx_ || src != bgLoadingCtx_->GetSourceInfo()) {
847         auto frameNode = GetHost();
848         auto callback = [src, weak = WeakClaim(this)] {
849             auto renderContext = weak.Upgrade();
850             CHECK_NULL_VOID(renderContext);
851             renderContext->OnBackgroundImageUpdate(src);
852         };
853         frameNode->SetColorModeUpdateCallback(std::move(callback));
854     }
855     LoadNotifier bgLoadNotifier(CreateBgImageDataReadyCallback(), CreateBgImageLoadSuccessCallback(), nullptr);
856     auto syncMode = GetBackgroundImageSyncMode().value_or(false);
857     bgLoadingCtx_ = AceType::MakeRefPtr<ImageLoadingContext>(src, std::move(bgLoadNotifier), syncMode);
858     CHECK_NULL_VOID(bgLoadingCtx_);
859     bgLoadingCtx_->LoadImageData();
860 }
861 
OnBackgroundImageRepeatUpdate(const ImageRepeat &)862 void RosenRenderContext::OnBackgroundImageRepeatUpdate(const ImageRepeat& /*imageRepeat*/)
863 {
864     CHECK_NULL_VOID(rsNode_);
865     PaintBackground();
866 }
867 
OnBackgroundImageSyncModeUpdate(bool)868 void RosenRenderContext::OnBackgroundImageSyncModeUpdate(bool /*syncMode*/)
869 {
870     CHECK_NULL_VOID(rsNode_);
871     PaintBackground();
872 }
873 
OnBackgroundImageSizeUpdate(const BackgroundImageSize &)874 void RosenRenderContext::OnBackgroundImageSizeUpdate(const BackgroundImageSize& /*bgImgSize*/)
875 {
876     CHECK_NULL_VOID(rsNode_);
877     PaintBackground();
878 }
879 
OnBackgroundImagePositionUpdate(const BackgroundImagePosition &)880 void RosenRenderContext::OnBackgroundImagePositionUpdate(const BackgroundImagePosition& /*bgImgPosition*/)
881 {
882     CHECK_NULL_VOID(rsNode_);
883     PaintBackground();
884 }
885 
OnBackgroundImageResizableSliceUpdate(const ImageResizableSlice &)886 void RosenRenderContext::OnBackgroundImageResizableSliceUpdate(const ImageResizableSlice& /*ImageResizableSlice*/)
887 {
888     CHECK_NULL_VOID(rsNode_);
889     PaintBackground();
890 }
891 
HasValidBgImageResizable()892 bool RosenRenderContext::HasValidBgImageResizable()
893 {
894     CHECK_NULL_RETURN(bgLoadingCtx_, false);
895     auto srcSize = bgLoadingCtx_->GetImageSize();
896     auto slice = GetBackgroundImageResizableSliceValue(ImageResizableSlice());
897     auto left = slice.left.ConvertToPxWithSize(srcSize.Width());
898     auto right = slice.right.ConvertToPxWithSize(srcSize.Width());
899     auto top = slice.top.ConvertToPxWithSize(srcSize.Width());
900     auto bottom = slice.bottom.ConvertToPxWithSize(srcSize.Width());
901     return srcSize.Width() > left + right && srcSize.Height() > top + bottom && right > 0 && bottom > 0;
902 }
903 
SetBackBlurFilter()904 void RosenRenderContext::SetBackBlurFilter()
905 {
906     CHECK_NULL_VOID(rsNode_);
907     auto context = GetPipelineContext();
908     CHECK_NULL_VOID(context);
909     const auto& background = GetBackground();
910     CHECK_NULL_VOID(background);
911     const auto& blurStyleOption = background->propBlurStyleOption;
912     auto sysOptions = background->propSysOptions.value_or(SysOptions());
913     std::shared_ptr<Rosen::RSFilter> backFilter;
914     if (!blurStyleOption.has_value()) {
915         const auto& radius = background->propBlurRadius;
916         if (radius.has_value() && radius->IsValid()) {
917             float radiusPx = context->NormalizeToPx(radius.value());
918             float backblurRadius = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx);
919             backFilter =
920                 Rosen::RSFilter::CreateBlurFilter(backblurRadius, backblurRadius, sysOptions.disableSystemAdaptation);
921         }
922     } else {
923         backFilter = CreateRSMaterialFilter(blurStyleOption.value(), context, sysOptions);
924     }
925     rsNode_->SetBackgroundFilter(backFilter);
926 }
927 
UpdateWindowFocusState(bool isFocused)928 void RosenRenderContext::UpdateWindowFocusState(bool isFocused)
929 {
930     if (GetBackBlurStyle().has_value() &&
931         GetBackBlurStyle()->policy == BlurStyleActivePolicy::FOLLOWS_WINDOW_ACTIVE_STATE) {
932         auto blurStyle = GetBackBlurStyle().value();
933         blurStyle.isWindowFocused = isFocused;
934         UpdateBackBlurStyle(blurStyle);
935     }
936     if (GetBackgroundEffect().has_value() &&
937         GetBackgroundEffect()->policy == BlurStyleActivePolicy::FOLLOWS_WINDOW_ACTIVE_STATE) {
938         auto effect = GetBackgroundEffect().value();
939         effect.isWindowFocused = isFocused;
940         UpdateBackgroundEffect(effect);
941     }
942 }
943 
UpdateWindowActiveState(bool isActive)944 void RosenRenderContext::UpdateWindowActiveState(bool isActive)
945 {
946     auto useEffect = GetUseEffect().value_or(false);
947     auto effectType = GetUseEffectType().value_or(EffectType::DEFAULT);
948     if (effectType == EffectType::WINDOW_EFFECT) {
949         OnUseEffectUpdate(useEffect);
950     }
951 }
952 
SetFrontBlurFilter()953 void RosenRenderContext::SetFrontBlurFilter()
954 {
955     CHECK_NULL_VOID(rsNode_);
956     auto context = GetPipelineContext();
957     CHECK_NULL_VOID(context);
958     const auto& foreground = GetForeground();
959     CHECK_NULL_VOID(foreground);
960     const auto& blurStyleOption = foreground->propBlurStyleOption;
961     auto sysOptions = foreground->propSysOptionsForBlur.value_or(SysOptions());
962     std::shared_ptr<Rosen::RSFilter> frontFilter;
963     if (!blurStyleOption.has_value()) {
964         const auto& radius = foreground->propBlurRadius;
965         if (radius.has_value() && radius->IsValid()) {
966             float radiusPx = context->NormalizeToPx(radius.value());
967             float backblurRadius = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx);
968             frontFilter =
969                 Rosen::RSFilter::CreateBlurFilter(backblurRadius, backblurRadius, sysOptions.disableSystemAdaptation);
970         }
971     } else {
972         frontFilter = CreateRSMaterialFilter(blurStyleOption.value(), context, sysOptions);
973     }
974 
975     rsNode_->SetFilter(frontFilter);
976 }
977 
UpdateBlurBackgroundColor(const std::optional<BlurStyleOption> & bgBlurStyle)978 bool RosenRenderContext::UpdateBlurBackgroundColor(const std::optional<BlurStyleOption>& bgBlurStyle)
979 {
980     if (!bgBlurStyle.has_value()) {
981         return false;
982     }
983     bool blurEnable =
984         bgBlurStyle->policy == BlurStyleActivePolicy::ALWAYS_ACTIVE ||
985         (bgBlurStyle->policy == BlurStyleActivePolicy::FOLLOWS_WINDOW_ACTIVE_STATE && bgBlurStyle->isWindowFocused);
986     if (bgBlurStyle->isValidColor) {
987         if (blurEnable) {
988             rsNode_->SetBackgroundColor(GetBackgroundColor().value_or(Color::TRANSPARENT).GetValue());
989         } else {
990             rsNode_->SetBackgroundColor(bgBlurStyle->inactiveColor.GetValue());
991         }
992     }
993     return blurEnable;
994 }
995 
UpdateBlurBackgroundColor(const std::optional<EffectOption> & efffectOption)996 bool RosenRenderContext::UpdateBlurBackgroundColor(const std::optional<EffectOption>& efffectOption)
997 {
998     bool blurEnable =
999         efffectOption->policy == BlurStyleActivePolicy::ALWAYS_ACTIVE ||
1000         (efffectOption->policy == BlurStyleActivePolicy::FOLLOWS_WINDOW_ACTIVE_STATE && efffectOption->isWindowFocused);
1001     if (efffectOption->isValidColor) {
1002         if (blurEnable) {
1003             rsNode_->SetBackgroundColor(GetBackgroundColor().value_or(Color::TRANSPARENT).GetValue());
1004         } else {
1005             rsNode_->SetBackgroundColor(efffectOption->inactiveColor.GetValue());
1006         }
1007     }
1008     return blurEnable;
1009 }
1010 
UpdateBackBlurStyle(const std::optional<BlurStyleOption> & bgBlurStyle,const SysOptions & sysOptions)1011 void RosenRenderContext::UpdateBackBlurStyle(
1012     const std::optional<BlurStyleOption>& bgBlurStyle, const SysOptions& sysOptions)
1013 {
1014     CHECK_NULL_VOID(rsNode_);
1015     const auto& groupProperty = GetOrCreateBackground();
1016     if (groupProperty->CheckBlurStyleOption(bgBlurStyle) && groupProperty->CheckSystemAdaptationSame(sysOptions)) {
1017         // Same with previous value.
1018         // If colorMode is following system and has valid blurStyle, still needs updating
1019         if (bgBlurStyle->colorMode != ThemeColorMode::SYSTEM) {
1020             return;
1021         }
1022         if (bgBlurStyle->blurOption.grayscale.size() > 1) {
1023             Rosen::Vector2f grayScale(bgBlurStyle->blurOption.grayscale[0], bgBlurStyle->blurOption.grayscale[1]);
1024             rsNode_->SetGreyCoef(grayScale);
1025         }
1026     } else {
1027         groupProperty->propBlurStyleOption = bgBlurStyle;
1028         groupProperty->propSysOptions = sysOptions;
1029     }
1030 
1031     if (!UpdateBlurBackgroundColor(bgBlurStyle)) {
1032         rsNode_->SetBackgroundFilter(nullptr);
1033         return;
1034     }
1035     SetBackBlurFilter();
1036 }
1037 
UpdateBackgroundEffect(const std::optional<EffectOption> & effectOption,const SysOptions & sysOptions)1038 void RosenRenderContext::UpdateBackgroundEffect(
1039     const std::optional<EffectOption>& effectOption, const SysOptions& sysOptions)
1040 {
1041     CHECK_NULL_VOID(rsNode_);
1042     const auto& groupProperty = GetOrCreateBackground();
1043     if (groupProperty->CheckEffectOption(effectOption) && groupProperty->CheckSystemAdaptationSame(sysOptions)) {
1044         return;
1045     }
1046     groupProperty->propEffectOption = effectOption;
1047     groupProperty->propSysOptions = sysOptions;
1048     if (!effectOption.has_value()) {
1049         return;
1050     }
1051     if (!UpdateBlurBackgroundColor(effectOption)) {
1052         rsNode_->SetBackgroundFilter(nullptr);
1053         return;
1054     }
1055     auto context = PipelineBase::GetCurrentContext();
1056     CHECK_NULL_VOID(context);
1057     float radiusPx = context->NormalizeToPx(effectOption->radius);
1058     float backblurRadius = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx);
1059     auto fastAverage = Rosen::BLUR_COLOR_MODE::DEFAULT;
1060     if (effectOption->adaptiveColor == AdaptiveColor::AVERAGE) {
1061         fastAverage = Rosen::BLUR_COLOR_MODE::FASTAVERAGE;
1062     }
1063     std::shared_ptr<Rosen::RSFilter> backFilter =
1064         Rosen::RSFilter::CreateMaterialFilter(backblurRadius, static_cast<float>(effectOption->saturation),
1065             static_cast<float>(effectOption->brightness), effectOption->color.GetValue(),
1066             static_cast<Rosen::BLUR_COLOR_MODE>(fastAverage), sysOptions.disableSystemAdaptation);
1067     rsNode_->SetBackgroundFilter(backFilter);
1068     if (effectOption->blurOption.grayscale.size() > 1) {
1069         Rosen::Vector2f grayScale(effectOption->blurOption.grayscale[0], effectOption->blurOption.grayscale[1]);
1070         rsNode_->SetGreyCoef(grayScale);
1071     }
1072 }
1073 
UpdateFrontBlurStyle(const std::optional<BlurStyleOption> & fgBlurStyle,const SysOptions & sysOptions)1074 void RosenRenderContext::UpdateFrontBlurStyle(
1075     const std::optional<BlurStyleOption>& fgBlurStyle, const SysOptions& sysOptions)
1076 {
1077     CHECK_NULL_VOID(rsNode_);
1078     const auto& groupProperty = GetOrCreateForeground();
1079     if (groupProperty->CheckBlurStyleOption(fgBlurStyle) && groupProperty->CheckSysOptionsForBlurSame(sysOptions)) {
1080         // Same with previous value.
1081         // If colorMode is following system and has valid blurStyle, still needs updating
1082         if (fgBlurStyle->colorMode != ThemeColorMode::SYSTEM) {
1083             return;
1084         }
1085         if (fgBlurStyle->blurOption.grayscale.size() > 1) {
1086             Rosen::Vector2f grayScale(fgBlurStyle->blurOption.grayscale[0], fgBlurStyle->blurOption.grayscale[1]);
1087             rsNode_->SetGreyCoef(grayScale);
1088         }
1089     } else {
1090         groupProperty->propBlurStyleOption = fgBlurStyle;
1091         groupProperty->propSysOptionsForBlur = sysOptions;
1092     }
1093     SetFrontBlurFilter();
1094 }
1095 
UpdateForegroundEffectDisableSystemAdaptation(const SysOptions & sysOptions)1096 void RosenRenderContext::UpdateForegroundEffectDisableSystemAdaptation(const SysOptions& sysOptions)
1097 {
1098     CHECK_NULL_VOID(rsNode_);
1099     const auto& groupProperty = GetOrCreateForeground();
1100     if (groupProperty->CheckSysOptionsForEffectSame(sysOptions)) {
1101         return;
1102     }
1103     groupProperty->propSysOptionsForForeEffect = sysOptions;
1104     rsNode_->SetForegroundEffectDisableSystemAdaptation(sysOptions.disableSystemAdaptation);
1105 }
1106 
ResetBackBlurStyle()1107 void RosenRenderContext::ResetBackBlurStyle()
1108 {
1109     const auto& groupProperty = GetOrCreateBackground();
1110     groupProperty->propBlurStyleOption.reset();
1111     SetBackBlurFilter();
1112 }
1113 
OnSphericalEffectUpdate(double radio)1114 void RosenRenderContext::OnSphericalEffectUpdate(double radio)
1115 {
1116     CHECK_NULL_VOID(rsNode_);
1117     rsNode_->SetSpherizeDegree(static_cast<float>(radio));
1118     RequestNextFrame();
1119 }
1120 
OnPixelStretchEffectUpdate(const PixStretchEffectOption & option)1121 void RosenRenderContext::OnPixelStretchEffectUpdate(const PixStretchEffectOption& option)
1122 {
1123     CHECK_NULL_VOID(rsNode_);
1124     Rosen::Vector4f pixStretchVector;
1125     if (option.IsPercentOption()) {
1126         pixStretchVector.SetValues(static_cast<float>(option.left.Value()), static_cast<float>(option.top.Value()),
1127             static_cast<float>(option.right.Value()), static_cast<float>(option.bottom.Value()));
1128         rsNode_->SetPixelStretchPercent(pixStretchVector);
1129         rsNode_->SetPixelStretch({ 0, 0, 0, 0 });
1130     } else {
1131         pixStretchVector.SetValues(static_cast<float>(option.left.ConvertToPx()),
1132             static_cast<float>(option.top.ConvertToPx()), static_cast<float>(option.right.ConvertToPx()),
1133             static_cast<float>(option.bottom.ConvertToPx()));
1134         rsNode_->SetPixelStretch(pixStretchVector);
1135         rsNode_->SetPixelStretchPercent({ 0, 0, 0, 0 });
1136     }
1137     RequestNextFrame();
1138 }
1139 
OnLightUpEffectUpdate(double radio)1140 void RosenRenderContext::OnLightUpEffectUpdate(double radio)
1141 {
1142     CHECK_NULL_VOID(rsNode_);
1143     rsNode_->SetLightUpEffectDegree(static_cast<float>(radio));
1144     RequestNextFrame();
1145 }
1146 
OnParticleOptionArrayUpdate(const std::list<ParticleOption> & optionList)1147 void RosenRenderContext::OnParticleOptionArrayUpdate(const std::list<ParticleOption>& optionList)
1148 {
1149     CHECK_NULL_VOID(rsNode_);
1150     RectF rect = GetPaintRectWithoutTransform();
1151     if (rect.IsEmpty()) {
1152         return;
1153     }
1154     if (NeedPreloadImage(optionList, rect)) {
1155         return;
1156     }
1157     auto pattern = GetHost()->GetPattern();
1158     auto particlePattern = AceType::DynamicCast<ParticlePattern>(pattern);
1159     if (particlePattern->HaveUnVisibleParent()) {
1160         return;
1161     }
1162     particleAnimationPlaying_ = true;
1163     std::vector<OHOS::Rosen::ParticleParams> particleParams;
1164     for (auto& item : optionList) {
1165         particleParams.emplace_back(ConvertParticleOptionToParams(item, rect));
1166     }
1167     auto finishCallback = [weak = WeakClaim(this)]() {
1168         auto renderContext = weak.Upgrade();
1169         CHECK_NULL_VOID(renderContext);
1170         renderContext->particleAnimationPlaying_ = false;
1171     };
1172     rsNode_->SetParticleParams(particleParams, finishCallback);
1173     RequestNextFrame();
1174 }
1175 
OnClickEffectLevelUpdate(const ClickEffectInfo & info)1176 void RosenRenderContext::OnClickEffectLevelUpdate(const ClickEffectInfo& info)
1177 {
1178     if (HasClickEffectLevel()) {
1179         InitEventClickEffect();
1180     }
1181 }
1182 
UpdateVisualEffect(const OHOS::Rosen::VisualEffect * visualEffect)1183 void RosenRenderContext::UpdateVisualEffect(const OHOS::Rosen::VisualEffect* visualEffect)
1184 {
1185     CHECK_NULL_VOID(visualEffect);
1186     rsNode_->SetVisualEffect(visualEffect);
1187 }
1188 
UpdateBackgroundFilter(const OHOS::Rosen::Filter * backgroundFilter)1189 void RosenRenderContext::UpdateBackgroundFilter(const OHOS::Rosen::Filter* backgroundFilter)
1190 {
1191     CHECK_NULL_VOID(backgroundFilter);
1192     rsNode_->SetUIBackgroundFilter(backgroundFilter);
1193 }
1194 
UpdateForegroundFilter(const OHOS::Rosen::Filter * foregroundFilter)1195 void RosenRenderContext::UpdateForegroundFilter(const OHOS::Rosen::Filter* foregroundFilter)
1196 {
1197     CHECK_NULL_VOID(foregroundFilter);
1198     rsNode_->SetUIForegroundFilter(foregroundFilter);
1199 }
1200 
UpdateCompositingFilter(const OHOS::Rosen::Filter * compositingFilter)1201 void RosenRenderContext::UpdateCompositingFilter(const OHOS::Rosen::Filter* compositingFilter)
1202 {
1203     CHECK_NULL_VOID(compositingFilter);
1204     rsNode_->SetUICompositingFilter(compositingFilter);
1205 }
1206 
NeedPreloadImage(const std::list<ParticleOption> & optionList,RectF & rect)1207 bool RosenRenderContext::NeedPreloadImage(const std::list<ParticleOption>& optionList, RectF& rect)
1208 {
1209     bool flag = false;
1210     std::vector<OHOS::Rosen::ParticleParams> particleParams;
1211     for (auto& item : optionList) {
1212         auto emitterOption = item.GetEmitterOption();
1213         auto particle = emitterOption.GetParticle();
1214         auto particleType = particle.GetParticleType();
1215         auto particleConfig = particle.GetConfig();
1216         if (particleType == ParticleType::IMAGE) {
1217             auto imageParameter = particleConfig.GetImageParticleParameter();
1218             auto imageSize = imageParameter.GetSize();
1219             auto imageWidth = Dimension(ConvertDimensionToPx(imageSize.first, rect.Width()), DimensionUnit::PX);
1220             auto imageHeight = Dimension(ConvertDimensionToPx(imageSize.second, rect.Height()), DimensionUnit::PX);
1221             auto canvasImageIter = particleImageMap_.find(imageParameter.GetImageSource());
1222             bool imageHasData = true;
1223             if (canvasImageIter->second) {
1224                 imageHasData = canvasImageIter->second->HasData();
1225             }
1226             if (canvasImageIter == particleImageMap_.end() || !imageHasData) {
1227                 LoadParticleImage(imageParameter.GetImageSource(), imageWidth, imageHeight);
1228                 flag = true;
1229             }
1230         }
1231     }
1232     return flag;
1233 }
1234 
ConvertParticleOptionToParams(const ParticleOption & particleOption,const RectF & rect)1235 Rosen::ParticleParams RosenRenderContext::ConvertParticleOptionToParams(
1236     const ParticleOption& particleOption, const RectF& rect)
1237 {
1238     auto emitterOption = particleOption.GetEmitterOption();
1239     auto colorOptionOpt = particleOption.GetParticleColorOption();
1240     auto opacityOptionOpt = particleOption.GetParticleOpacityOption();
1241     auto scaleOptionOpt = particleOption.GetParticleScaleOption();
1242     auto velocityOptionOpt = particleOption.GetParticleVelocityOption();
1243     auto accelerationOpt = particleOption.GetParticleAccelerationOption();
1244     auto spinOptionOpt = particleOption.GetParticleSpinOption();
1245     auto rsEmitterConfig = ConvertParticleEmitterOption(emitterOption, rect);
1246     std::optional<OHOS::Rosen::ParticleColorParaType> rsColorOpt;
1247     std::optional<OHOS::Rosen::ParticleParaType<float>> rsSpinOpt;
1248     std::optional<OHOS::Rosen::ParticleVelocity> rsVelocityOpt;
1249     std::optional<OHOS::Rosen::ParticleParaType<float>> rsOpacityOpt;
1250     std::optional<OHOS::Rosen::ParticleParaType<float>> rsScaleOpt;
1251     std::optional<OHOS::Rosen::ParticleAcceleration> rsAccelerationOpt;
1252     if (colorOptionOpt.has_value()) {
1253         rsColorOpt = ConvertParticleColorOption(colorOptionOpt.value());
1254     } else {
1255         rsColorOpt = ConvertParticleDefaultColorOption(std::nullopt);
1256     }
1257     if (opacityOptionOpt.has_value()) {
1258         rsOpacityOpt = ConvertParticleFloatOption(opacityOptionOpt.value());
1259     } else {
1260         OHOS::Rosen::Range<float> rsInitRange(PARTICLE_DEFAULT_OPACITY, PARTICLE_DEFAULT_OPACITY);
1261         rsOpacityOpt = ConvertParticleDefaultFloatOption(rsInitRange);
1262     }
1263     if (scaleOptionOpt.has_value()) {
1264         rsScaleOpt = ConvertParticleFloatOption(scaleOptionOpt.value());
1265     } else {
1266         OHOS::Rosen::Range<float> rsInitRange(PARTICLE_DEFAULT_SCALE, PARTICLE_DEFAULT_SCALE);
1267         rsScaleOpt = ConvertParticleDefaultFloatOption(rsInitRange);
1268     }
1269     if (velocityOptionOpt.has_value()) {
1270         rsVelocityOpt = ConvertParticleVelocityOption(velocityOptionOpt.value());
1271     } else {
1272         rsVelocityOpt = ConvertParticleDefaultVelocityOption();
1273     }
1274     if (accelerationOpt.has_value()) {
1275         rsAccelerationOpt = ConvertParticleAccelerationOption(accelerationOpt.value());
1276     } else {
1277         rsAccelerationOpt = ConvertParticleDefaultAccelerationOption();
1278     }
1279     if (spinOptionOpt.has_value()) {
1280         rsSpinOpt = ConvertParticleFloatOption(spinOptionOpt.value());
1281     } else {
1282         OHOS::Rosen::Range<float> rsInitRange(PARTICLE_DEFAULT_SPIN, PARTICLE_DEFAULT_SPIN);
1283         rsSpinOpt = ConvertParticleDefaultFloatOption(rsInitRange);
1284     }
1285     return OHOS::Rosen::ParticleParams(rsEmitterConfig, rsVelocityOpt.value(), rsAccelerationOpt.value(),
1286         rsColorOpt.value(), rsOpacityOpt.value(), rsScaleOpt.value(), rsSpinOpt.value());
1287 }
1288 
ConvertParticleEmitterOption(const EmitterOption & emitterOption,const RectF & rect)1289 Rosen::EmitterConfig RosenRenderContext::ConvertParticleEmitterOption(
1290     const EmitterOption& emitterOption, const RectF& rect)
1291 {
1292     auto emitterRateOpt = emitterOption.GetEmitterRate();
1293     auto pointOpt = emitterOption.GetPosition();
1294     auto sizeOpt = emitterOption.GetSize();
1295     auto shapeOpt = emitterOption.GetShape();
1296     auto particle = emitterOption.GetParticle();
1297     auto particleType = particle.GetParticleType();
1298     auto particleConfig = particle.GetConfig();
1299     auto particleCount = particle.GetCount();
1300     auto lifeTimeOpt = particle.GetLifeTime();
1301     auto lifeTimeRangeOpt = particle.GetLifeTimeRange();
1302     std::optional<int64_t> lifeTimeMin = 0;
1303     std::optional<int64_t> lifeTimeMax = lifeTimeOpt.value() + lifeTimeRangeOpt.value();
1304     if (lifeTimeOpt.value() == -1) {
1305         // when lifeTime == -1 particle life cycle is infinite
1306         lifeTimeMin = -1;
1307         lifeTimeMax = -1;
1308     } else if (lifeTimeOpt.value() - lifeTimeRangeOpt.value() > 0) {
1309         lifeTimeMin = lifeTimeOpt.value() - lifeTimeRangeOpt.value();
1310     }
1311     auto rsPoint = pointOpt.has_value()
1312                        ? OHOS::Rosen::Vector2f(ConvertDimensionToPx(pointOpt.value().first, rect.Width()),
1313                              ConvertDimensionToPx(pointOpt.value().second, rect.Height()))
1314                        : OHOS::Rosen::Vector2f(0.0f, 0.0f);
1315     auto rsSize = sizeOpt.has_value() ? OHOS::Rosen::Vector2f(ConvertDimensionToPx(sizeOpt.value().first, rect.Width()),
1316                                             ConvertDimensionToPx(sizeOpt.value().second, rect.Height()))
1317                                       : OHOS::Rosen::Vector2f(rect.Width(), rect.Height());
1318     auto shapeInt = static_cast<int32_t>(shapeOpt.value_or(ParticleEmitterShape::RECTANGLE));
1319     auto lifeTimeRange = OHOS::Rosen::Range<int64_t>(
1320         lifeTimeMin.value_or(PARTICLE_DEFAULT_LIFETIME), lifeTimeMax.value_or(PARTICLE_DEFAULT_LIFETIME));
1321     if (particleType == ParticleType::IMAGE) {
1322         auto imageParameter = particleConfig.GetImageParticleParameter();
1323         auto imageSource = imageParameter.GetImageSource();
1324         auto imageSize = imageParameter.GetSize();
1325         auto imageWidth = Dimension(ConvertDimensionToPx(imageSize.first, rect.Width()), DimensionUnit::PX);
1326         auto imageHeight = Dimension(ConvertDimensionToPx(imageSize.second, rect.Height()), DimensionUnit::PX);
1327         auto rsImagePtr = std::make_shared<Rosen::RSImage>();
1328         if (particleImageMap_.find(imageSource) != particleImageMap_.end()) {
1329             SetRsParticleImage(rsImagePtr, imageSource);
1330         }
1331         rsImagePtr->SetImageFit(static_cast<int32_t>(imageParameter.GetImageFit().value_or(ImageFit::COVER)));
1332         OHOS::Rosen::Vector2f rsImageSize(imageWidth.ConvertToPx(), imageHeight.ConvertToPx());
1333         return OHOS::Rosen::EmitterConfig(emitterRateOpt.value_or(PARTICLE_DEFAULT_EMITTER_RATE),
1334             static_cast<OHOS::Rosen::ShapeType>(shapeInt), rsPoint, rsSize, particleCount, lifeTimeRange,
1335             OHOS::Rosen::ParticleType::IMAGES, 0.0f, rsImagePtr, rsImageSize);
1336     } else {
1337         auto pointParameter = particleConfig.GetPointParticleParameter();
1338         auto radius = pointParameter.GetRadius();
1339         return OHOS::Rosen::EmitterConfig(emitterRateOpt.value_or(PARTICLE_DEFAULT_EMITTER_RATE),
1340             static_cast<OHOS::Rosen::ShapeType>(shapeInt), rsPoint, rsSize, particleCount, lifeTimeRange,
1341             OHOS::Rosen::ParticleType::POINTS, radius, std::make_shared<OHOS::Rosen::RSImage>(),
1342             OHOS::Rosen::Vector2f());
1343     }
1344 }
1345 
SetRsParticleImage(std::shared_ptr<Rosen::RSImage> & rsImagePtr,std::string & imageSource)1346 void RosenRenderContext::SetRsParticleImage(std::shared_ptr<Rosen::RSImage>& rsImagePtr, std::string& imageSource)
1347 {
1348     auto it = particleImageMap_.find(imageSource);
1349     if (it == particleImageMap_.end()) {
1350         return;
1351     }
1352     auto image = it->second;
1353     CHECK_NULL_VOID(image);
1354 
1355     if (InstanceOf<PixelMapImage>(image)) {
1356         auto pixmap = image->GetPixelMap();
1357         CHECK_NULL_VOID(pixmap);
1358         auto pixMapPtr = pixmap->GetPixelMapSharedPtr();
1359         rsImagePtr->SetPixelMap(pixMapPtr);
1360         if (pixMapPtr) {
1361             rsImagePtr->SetSrcRect(Rosen::RectF(0, 0, pixMapPtr->GetWidth(), pixMapPtr->GetHeight()));
1362         }
1363     } else if (InstanceOf<DrawingImage>(image)) {
1364         auto drawingImage = DynamicCast<DrawingImage>(image);
1365         CHECK_NULL_VOID(drawingImage);
1366         auto compressData = drawingImage->GetCompressData();
1367         if (compressData) {
1368             rsImagePtr->SetCompressData(compressData, drawingImage->GetUniqueID(), drawingImage->GetCompressWidth(),
1369                 drawingImage->GetCompressHeight());
1370             rsImagePtr->SetSrcRect(
1371                 Rosen::RectF(0, 0, drawingImage->GetCompressWidth(), drawingImage->GetCompressHeight()));
1372         } else {
1373             rsImagePtr->SetImage(drawingImage->GetImage());
1374             if (drawingImage->GetImage()) {
1375                 rsImagePtr->SetSrcRect(
1376                     Rosen::RectF(0, 0, drawingImage->GetImage()->GetWidth(), drawingImage->GetImage()->GetHeight()));
1377             }
1378         }
1379         if (!HasValidBgImageResizable()) {
1380             rsImagePtr->SetImageRepeat(static_cast<int>(GetBackgroundImageRepeat().value_or(ImageRepeat::NO_REPEAT)));
1381         }
1382     }
1383 }
1384 
LoadParticleImage(const std::string & src,Dimension & width,Dimension & height)1385 void RosenRenderContext::LoadParticleImage(const std::string& src, Dimension& width, Dimension& height)
1386 {
1387     if (particleImageContextMap_.find(src) != particleImageContextMap_.end()) {
1388         return;
1389     }
1390     ImageSourceInfo imageSourceInfo(src, width, height);
1391     imageSourceInfo.SetNeedCache(false);
1392     auto preLoadCallback = [weak = WeakClaim(this), imageSrc = src](const ImageSourceInfo& sourceInfo) {
1393         auto renderContent = weak.Upgrade();
1394         CHECK_NULL_VOID(renderContent);
1395         auto& imageContext = renderContent->particleImageContextMap_[imageSrc];
1396         CHECK_NULL_VOID(imageContext);
1397         imageContext->MakeCanvasImage(SizeF(), true, ImageFit::NONE);
1398     };
1399     auto loadingSuccessCallback = [weak = WeakClaim(this), imageSrc = src](const ImageSourceInfo& sourceInfo) {
1400         auto renderContent = weak.Upgrade();
1401         CHECK_NULL_VOID(renderContent);
1402         auto& imageContext = renderContent->particleImageContextMap_[imageSrc];
1403         CHECK_NULL_VOID(imageContext);
1404         auto imagePtr = imageContext->MoveCanvasImage();
1405         renderContent->OnParticleImageLoaded(imageSrc, imagePtr);
1406     };
1407     auto loadingErrorCallback = [weak = WeakClaim(this), imageSrc = src](
1408                                     const ImageSourceInfo& sourceInfo, const std::string& errorMsg) {
1409         auto renderContent = weak.Upgrade();
1410         CHECK_NULL_VOID(renderContent);
1411         renderContent->OnParticleImageLoaded(imageSrc, nullptr);
1412     };
1413     LoadNotifier loadNotifier(preLoadCallback, loadingSuccessCallback, loadingErrorCallback);
1414     auto particleImageLoadingCtx = AceType::MakeRefPtr<ImageLoadingContext>(imageSourceInfo, std::move(loadNotifier));
1415     imageSourceInfo.SetSrc(src, Color(0x00000000));
1416     particleImageLoadingCtx->LoadImageData();
1417     particleImageContextMap_.try_emplace(src, particleImageLoadingCtx);
1418 }
1419 
OnParticleImageLoaded(const std::string & src,RefPtr<CanvasImage> canvasImage)1420 void RosenRenderContext::OnParticleImageLoaded(const std::string& src, RefPtr<CanvasImage> canvasImage)
1421 {
1422     particleImageMap_.try_emplace(src, canvasImage);
1423     if (particleImageContextMap_.find(src) != particleImageContextMap_.end()) {
1424         particleImageContextMap_.erase(src);
1425     }
1426     if (particleImageContextMap_.empty() && propParticleOptionArray_.has_value()) {
1427         OnParticleOptionArrayUpdate(propParticleOptionArray_.value());
1428     }
1429 }
1430 
ConvertDimensionToPx(Dimension & src,float size)1431 float RosenRenderContext::ConvertDimensionToPx(Dimension& src, float size)
1432 {
1433     if (src.Unit() == DimensionUnit::PERCENT) {
1434         return src.ConvertToPxWithSize(size);
1435     }
1436     return src.ConvertToPx();
1437 }
1438 
ConvertParticleVelocityOption(const VelocityProperty & velocity)1439 Rosen::ParticleVelocity RosenRenderContext::ConvertParticleVelocityOption(const VelocityProperty& velocity)
1440 {
1441     auto rsSpeedRange = OHOS::Rosen::Range<float>(velocity.GetSpeedRange().first, velocity.GetSpeedRange().second);
1442     auto rsAngleRange = OHOS::Rosen::Range<float>(velocity.GetAngleRange().first, velocity.GetAngleRange().second);
1443     return OHOS::Rosen::ParticleVelocity(rsSpeedRange, rsAngleRange);
1444 }
1445 
ConvertParticleDefaultVelocityOption()1446 Rosen::ParticleVelocity RosenRenderContext::ConvertParticleDefaultVelocityOption()
1447 {
1448     auto rsSpeedRange = OHOS::Rosen::Range<float>(PARTICLE_DEFAULT_SPEED, PARTICLE_DEFAULT_SPEED);
1449     auto rsAngleRange = OHOS::Rosen::Range<float>(PARTICLE_DEFAULT_ANGLE, PARTICLE_DEFAULT_ANGLE);
1450     return OHOS::Rosen::ParticleVelocity(rsSpeedRange, rsAngleRange);
1451 }
1452 
ConvertParticleAccelerationOption(const AccelerationProperty & acceleration)1453 Rosen::ParticleAcceleration RosenRenderContext::ConvertParticleAccelerationOption(
1454     const AccelerationProperty& acceleration)
1455 {
1456     auto speedOpt = acceleration.GetSpeed();
1457     auto angleOpt = acceleration.GetAngle();
1458     std::optional<OHOS::Rosen::ParticleParaType<float>> rsSpeedOpt;
1459     std::optional<OHOS::Rosen::ParticleParaType<float>> rsAngleOpt;
1460     OHOS::Rosen::Range<float> rsInitSpeedRange(PARTICLE_DEFAULT_SPEED, PARTICLE_DEFAULT_SPEED);
1461     if (speedOpt.has_value()) {
1462         rsSpeedOpt = ConvertParticleFloatOption(speedOpt.value());
1463     } else {
1464         rsSpeedOpt = ConvertParticleDefaultFloatOption(rsInitSpeedRange);
1465     }
1466     OHOS::Rosen::Range<float> rsInitAngleRange(PARTICLE_DEFAULT_ANGLE, PARTICLE_DEFAULT_ANGLE);
1467     if (angleOpt.has_value()) {
1468         rsAngleOpt = ConvertParticleFloatOption(angleOpt.value());
1469     } else {
1470         rsAngleOpt = ConvertParticleDefaultFloatOption(rsInitAngleRange);
1471     }
1472     return OHOS::Rosen::ParticleAcceleration(rsSpeedOpt.value(), rsAngleOpt.value());
1473 }
1474 
ConvertParticleDefaultAccelerationOption()1475 Rosen::ParticleAcceleration RosenRenderContext::ConvertParticleDefaultAccelerationOption()
1476 {
1477     OHOS::Rosen::Range<float> rsInitRange(PARTICLE_DEFAULT_SPEED, PARTICLE_DEFAULT_SPEED);
1478     return OHOS::Rosen::ParticleAcceleration(
1479         ConvertParticleDefaultFloatOption(rsInitRange), ConvertParticleDefaultFloatOption(rsInitRange));
1480 }
1481 
ConvertParticleColorOption(const ParticleColorPropertyOption & colorOption)1482 Rosen::ParticleColorParaType RosenRenderContext::ConvertParticleColorOption(
1483     const ParticleColorPropertyOption& colorOption)
1484 {
1485     auto initRange = colorOption.GetRange();
1486     auto colorDist = colorOption.GetDistribution();
1487     auto updaterOpt = colorOption.GetUpdater();
1488     OHOS::Rosen::Range<OHOS::Rosen::RSColor> rsInitRange(
1489         OHOS::Rosen::RSColor(initRange.first.GetRed(), initRange.first.GetGreen(), initRange.first.GetBlue(),
1490             initRange.first.GetAlpha()),
1491         OHOS::Rosen::RSColor(initRange.second.GetRed(), initRange.second.GetGreen(), initRange.second.GetBlue(),
1492             initRange.second.GetAlpha()));
1493     auto colorDistInt = static_cast<int32_t>(colorDist.value_or(DistributionType::UNIFORM));
1494     if (updaterOpt.has_value()) {
1495         auto updater = updaterOpt.value();
1496         auto updateType = updater.GetUpdateType();
1497         auto config = updater.GetConfig();
1498         if (updateType == UpdaterType::RANDOM) {
1499             auto randomConfig = config.GetRandomConfig();
1500             auto redRandom = randomConfig.GetRedRandom();
1501             auto greenRandom = randomConfig.GetGreenRandom();
1502             auto blueRandom = randomConfig.GetBlueRandom();
1503             auto alphaRandom = randomConfig.GetAlphaRandom();
1504             OHOS::Rosen::Range<float> rsRedRandom(redRandom.first, redRandom.second);
1505             OHOS::Rosen::Range<float> rsGreenRandom(greenRandom.first, greenRandom.second);
1506             OHOS::Rosen::Range<float> rsBlueRandom(blueRandom.first, blueRandom.second);
1507             OHOS::Rosen::Range<float> rsAlphaRandom(alphaRandom.first, alphaRandom.second);
1508             std::vector<OHOS::Rosen::Change<OHOS::Rosen::RSColor>> invalidCurve;
1509             return OHOS::Rosen::ParticleColorParaType(rsInitRange,
1510                 static_cast<OHOS::Rosen::DistributionType>(colorDistInt), OHOS::Rosen::ParticleUpdator::RANDOM,
1511                 rsRedRandom, rsGreenRandom, rsBlueRandom, rsAlphaRandom, invalidCurve);
1512         } else if (updateType == UpdaterType::CURVE) {
1513             auto& curveConfig = config.GetAnimationArray();
1514             std::vector<OHOS::Rosen::Change<OHOS::Rosen::RSColor>> valChangeOverLife;
1515             for (const auto& colorAnimationConfig : curveConfig) {
1516                 auto fromColor = colorAnimationConfig.GetFrom();
1517                 auto toColor = colorAnimationConfig.GetTo();
1518                 auto startMills = colorAnimationConfig.GetStartMills();
1519                 auto endMills = colorAnimationConfig.GetEndMills();
1520                 auto curve = colorAnimationConfig.GetCurve();
1521                 auto rsCurve = NativeCurveHelper::ToNativeCurve(curve);
1522                 valChangeOverLife.emplace_back(OHOS::Rosen::Change<OHOS::Rosen::RSColor>(
1523                     OHOS::Rosen::RSColor(
1524                         fromColor.GetRed(), fromColor.GetGreen(), fromColor.GetBlue(), fromColor.GetAlpha()),
1525                     OHOS::Rosen::RSColor(toColor.GetRed(), toColor.GetGreen(), toColor.GetBlue(), toColor.GetAlpha()),
1526                     startMills, endMills, rsCurve));
1527             }
1528             return OHOS::Rosen::ParticleColorParaType(rsInitRange,
1529                 static_cast<OHOS::Rosen::DistributionType>(colorDistInt), ParticleUpdator::CURVE,
1530                 OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(),
1531                 OHOS::Rosen::Range<float>(), valChangeOverLife);
1532         }
1533     }
1534     return ConvertParticleDefaultColorOption(rsInitRange);
1535 }
1536 
ConvertParticleDefaultColorOption(std::optional<OHOS::Rosen::Range<OHOS::Rosen::RSColor>> rsInitRangeOpt)1537 Rosen::ParticleColorParaType RosenRenderContext::ConvertParticleDefaultColorOption(
1538     std::optional<OHOS::Rosen::Range<OHOS::Rosen::RSColor>> rsInitRangeOpt)
1539 {
1540     std::vector<OHOS::Rosen::Change<OHOS::Rosen::RSColor>> invalidCurve;
1541     if (rsInitRangeOpt.has_value()) {
1542         return OHOS::Rosen::ParticleColorParaType(rsInitRangeOpt.value(), OHOS::Rosen::DistributionType::UNIFORM,
1543             OHOS::Rosen::ParticleUpdator::NONE, OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(),
1544             OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(), invalidCurve);
1545     }
1546     return OHOS::Rosen::ParticleColorParaType(
1547         OHOS::Rosen::Range<OHOS::Rosen::RSColor>(
1548             OHOS::Rosen::RSColor(PARTICLE_DEFAULT_COLOR), OHOS::Rosen::RSColor(PARTICLE_DEFAULT_COLOR)),
1549         OHOS::Rosen::DistributionType::UNIFORM, OHOS::Rosen::ParticleUpdator::NONE, OHOS::Rosen::Range<float>(),
1550         OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(), OHOS::Rosen::Range<float>(), invalidCurve);
1551 }
1552 
ConvertParticleFloatOption(const ParticleFloatPropertyOption & floatOption)1553 Rosen::ParticleParaType<float> RosenRenderContext::ConvertParticleFloatOption(
1554     const ParticleFloatPropertyOption& floatOption)
1555 {
1556     auto initRange = floatOption.GetRange();
1557     OHOS::Rosen::Range<float> rsInitRange(initRange.first, initRange.second);
1558     auto updaterOpt = floatOption.GetUpdater();
1559     if (updaterOpt.has_value()) {
1560         auto updater = updaterOpt.value();
1561         auto updateType = updater.GetUpdaterType();
1562         auto& config = updater.GetConfig();
1563         if (updateType == UpdaterType::RANDOM) {
1564             auto& randomRangeConfig = config.GetRandomConfig();
1565             std::vector<OHOS::Rosen::Change<float>> invalidChangeInOverLifeArray;
1566             return OHOS::Rosen::ParticleParaType<float>(rsInitRange, OHOS::Rosen::ParticleUpdator::RANDOM,
1567                 OHOS::Rosen::Range<float>(randomRangeConfig.first, randomRangeConfig.second),
1568                 invalidChangeInOverLifeArray);
1569         } else if (updateType == UpdaterType::CURVE) {
1570             auto curveConfig = config.GetAnimations();
1571             std::vector<OHOS::Rosen::Change<float>> valChangeOverLife;
1572             for (auto& animationConfig : curveConfig) {
1573                 auto from = animationConfig.GetFrom();
1574                 auto to = animationConfig.GetTo();
1575                 auto startMills = animationConfig.GetStartMills();
1576                 auto endMills = animationConfig.GetEndMills();
1577                 auto rsCurve = NativeCurveHelper::ToNativeCurve(animationConfig.GetCurve());
1578                 valChangeOverLife.emplace_back(OHOS::Rosen::Change<float>(from, to, startMills, endMills, rsCurve));
1579             }
1580             OHOS::Rosen::Range<float> rsInvalidRange;
1581             return OHOS::Rosen::ParticleParaType<float>(
1582                 rsInitRange, OHOS::Rosen::ParticleUpdator::CURVE, rsInvalidRange, valChangeOverLife);
1583         }
1584     }
1585     return ConvertParticleDefaultFloatOption(rsInitRange);
1586 }
1587 
ConvertParticleDefaultFloatOption(OHOS::Rosen::Range<float> & rsInitRange)1588 Rosen::ParticleParaType<float> RosenRenderContext::ConvertParticleDefaultFloatOption(
1589     OHOS::Rosen::Range<float>& rsInitRange)
1590 {
1591     std::vector<OHOS::Rosen::Change<float>> invalidChangeInOverLifeArray;
1592     return OHOS::Rosen::ParticleParaType<float>(
1593         rsInitRange, OHOS::Rosen::ParticleUpdator::NONE, OHOS::Rosen::Range<float>(), invalidChangeInOverLifeArray);
1594 }
1595 
OnOpacityUpdate(double opacity)1596 void RosenRenderContext::OnOpacityUpdate(double opacity)
1597 {
1598     CHECK_NULL_VOID(rsNode_);
1599     if (AnimationUtils::IsImplicitAnimationOpen() && GetHost()) {
1600         auto preOpacity = rsNode_->GetStagingProperties().GetAlpha();
1601         if (!NearEqual(preOpacity, opacity)) {
1602             auto host = GetHost();
1603             ACE_SCOPED_TRACE("opacity from %f to %f, id:%d, tag:%s", rsNode_->GetStagingProperties().GetAlpha(),
1604                 opacity, host->GetId(), host->GetTag().c_str());
1605         }
1606     }
1607     rsNode_->SetAlpha(opacity);
1608     RequestNextFrame();
1609 }
1610 
OnDynamicRangeModeUpdate(DynamicRangeMode dynamicRangeMode)1611 void RosenRenderContext::OnDynamicRangeModeUpdate(DynamicRangeMode dynamicRangeMode)
1612 {
1613     auto rsCanvasDrawingNode = Rosen::RSNode::ReinterpretCast<Rosen::RSCanvasNode>(rsNode_);
1614     CHECK_NULL_VOID(rsCanvasDrawingNode);
1615     if (dynamicRangeMode < DynamicRangeMode::STANDARD && !isHdr_) {
1616         TAG_LOGD(AceLogTag::ACE_IMAGE, "Set HDRPresent True.");
1617         isHdr_ = true;
1618         rsCanvasDrawingNode->SetHDRPresent(true);
1619     } else if (isHdr_) {
1620         TAG_LOGD(AceLogTag::ACE_IMAGE, "Set HDRPresent False.");
1621         isHdr_ = false;
1622         rsCanvasDrawingNode->SetHDRPresent(false);
1623     }
1624 }
1625 
SetAlphaOffscreen(bool isOffScreen)1626 void RosenRenderContext::SetAlphaOffscreen(bool isOffScreen)
1627 {
1628     CHECK_NULL_VOID(rsNode_);
1629     rsNode_->SetAlphaOffscreen(isOffScreen);
1630 }
1631 
1632 class DrawDragThumbnailCallback : public SurfaceCaptureCallback {
1633 public:
OnSurfaceCapture(std::shared_ptr<Media::PixelMap> pixelMap)1634     void OnSurfaceCapture(std::shared_ptr<Media::PixelMap> pixelMap) override
1635     {
1636         if (pixelMap) {
1637 #ifdef PIXEL_MAP_SUPPORTED
1638             g_pixelMap = PixelMap::CreatePixelMap(reinterpret_cast<void*>(&pixelMap));
1639 #endif // PIXEL_MAP_SUPPORTED
1640         } else {
1641             g_pixelMap = nullptr;
1642             TAG_LOGE(AceLogTag::ACE_DRAG, "get thumbnail pixelMap failed!");
1643         }
1644 
1645         if (callback_ == nullptr) {
1646             std::unique_lock<std::mutex> lock(g_mutex);
1647             thumbnailGet.notify_all();
1648             return;
1649         }
1650         callback_(g_pixelMap);
1651     }
1652 
1653     std::function<void(const RefPtr<PixelMap>&)> callback_;
1654 };
1655 
GetThumbnailPixelMap(bool needScale,bool isOffline)1656 RefPtr<PixelMap> RosenRenderContext::GetThumbnailPixelMap(bool needScale, bool isOffline)
1657 {
1658     CHECK_NULL_RETURN(rsNode_, nullptr);
1659     std::shared_ptr<DrawDragThumbnailCallback> drawDragThumbnailCallback =
1660         std::make_shared<DrawDragThumbnailCallback>();
1661     CHECK_NULL_RETURN(drawDragThumbnailCallback, nullptr);
1662     drawDragThumbnailCallback->callback_ = nullptr;
1663     float scaleX = 1.0f;
1664     float scaleY = 1.0f;
1665     if (needScale) {
1666         UpdateThumbnailPixelMapScale(scaleX, scaleY);
1667     }
1668     AddRsNodeForCapture();
1669     auto ret = RSInterfaces::GetInstance().TakeSurfaceCaptureForUI(rsNode_, drawDragThumbnailCallback, scaleX, scaleY,
1670         isOffline);
1671     if (!ret) {
1672         LOGE("TakeSurfaceCaptureForUI failed!");
1673         return nullptr;
1674     }
1675     std::unique_lock<std::mutex> lock(g_mutex);
1676     if (thumbnailGet.wait_for(lock, PIXELMAP_TIMEOUT_DURATION) == std::cv_status::timeout) {
1677         LOGE("get thumbnail pixelMap timeout!");
1678         return nullptr;
1679     }
1680     return g_pixelMap;
1681 }
1682 
CreateThumbnailPixelMapAsyncTask(bool needScale,std::function<void (const RefPtr<PixelMap>)> && callback)1683 bool RosenRenderContext::CreateThumbnailPixelMapAsyncTask(
1684     bool needScale, std::function<void(const RefPtr<PixelMap>)>&& callback)
1685 {
1686     CHECK_NULL_RETURN(rsNode_, false);
1687     std::shared_ptr<DrawDragThumbnailCallback> thumbnailCallback = std::make_shared<DrawDragThumbnailCallback>();
1688     CHECK_NULL_RETURN(thumbnailCallback, false);
1689     thumbnailCallback->callback_ = std::move(callback);
1690     float scaleX = 1.0f;
1691     float scaleY = 1.0f;
1692     if (needScale) {
1693         UpdateThumbnailPixelMapScale(scaleX, scaleY);
1694     }
1695     AddRsNodeForCapture();
1696     return RSInterfaces::GetInstance().TakeSurfaceCaptureForUI(rsNode_, thumbnailCallback, scaleX, scaleY, true);
1697 }
1698 
UpdateThumbnailPixelMapScale(float & scaleX,float & scaleY)1699 void RosenRenderContext::UpdateThumbnailPixelMapScale(float& scaleX, float& scaleY)
1700 {
1701     CHECK_NULL_VOID(rsNode_);
1702     auto scale = rsNode_->GetStagingProperties().GetScale();
1703     auto frameNode = GetHost();
1704     CHECK_NULL_VOID(frameNode);
1705     auto context = frameNode->GetRenderContext();
1706     CHECK_NULL_VOID(context);
1707     auto parent = frameNode->GetAncestorNodeOfFrame(true);
1708     while (parent) {
1709         auto parentRenderContext = parent->GetRenderContext();
1710         CHECK_NULL_VOID(parentRenderContext);
1711         auto parentScale = parentRenderContext->GetTransformScale();
1712         if (parentScale) {
1713             scale[0] *= parentScale.value().x;
1714             scale[1] *= parentScale.value().y;
1715         }
1716         parent = parent->GetAncestorNodeOfFrame(true);
1717     }
1718     scaleX = scale[0];
1719     scaleY = scale[1];
1720 }
1721 
GetBitmap(RSBitmap & bitmap,std::shared_ptr<RSDrawCmdList> drawCmdList)1722 bool RosenRenderContext::GetBitmap(RSBitmap& bitmap, std::shared_ptr<RSDrawCmdList> drawCmdList)
1723 {
1724     auto rsCanvasDrawingNode = Rosen::RSNode::ReinterpretCast<Rosen::RSCanvasDrawingNode>(rsNode_);
1725     if (!rsCanvasDrawingNode) {
1726         return false;
1727     }
1728     return rsCanvasDrawingNode->GetBitmap(bitmap, drawCmdList);
1729 }
1730 
GetPixelMap(const std::shared_ptr<Media::PixelMap> & pixelMap,std::shared_ptr<RSDrawCmdList> drawCmdList,Rosen::Drawing::Rect * rect)1731 bool RosenRenderContext::GetPixelMap(const std::shared_ptr<Media::PixelMap>& pixelMap,
1732     std::shared_ptr<RSDrawCmdList> drawCmdList, Rosen::Drawing::Rect* rect)
1733 {
1734     auto rsCanvasDrawingNode = Rosen::RSNode::ReinterpretCast<Rosen::RSCanvasDrawingNode>(rsNode_);
1735     if (!rsCanvasDrawingNode) {
1736         return false;
1737     }
1738     return rsCanvasDrawingNode->GetPixelmap(pixelMap, drawCmdList, rect);
1739 }
1740 
1741 template<typename ModifierName, typename T>
SetAnimatableProperty(std::shared_ptr<ModifierName> & modifier,const T & value)1742 void RosenRenderContext::SetAnimatableProperty(std::shared_ptr<ModifierName>& modifier, const T& value)
1743 {
1744     if (modifier) {
1745         auto property = std::static_pointer_cast<Rosen::RSAnimatableProperty<T>>(modifier->GetProperty());
1746         CHECK_NULL_VOID(property);
1747         property->Set(value);
1748     } else {
1749         auto property = std::make_shared<Rosen::RSAnimatableProperty<T>>(value);
1750         modifier = std::make_shared<ModifierName>(property);
1751         rsNode_->AddModifier(modifier);
1752     }
1753 }
1754 
OnTransformScaleUpdate(const VectorF & scale)1755 void RosenRenderContext::OnTransformScaleUpdate(const VectorF& scale)
1756 {
1757     CHECK_NULL_VOID(rsNode_);
1758     auto curScale = rsNode_->GetStagingProperties().GetScale();
1759     hasScales_ = !NearEqual(curScale, Vector2f(1.0f, 1.0f)) && !NearEqual(scale, VectorF(1.0f, 1.0f));
1760     if (AnimationUtils::IsImplicitAnimationOpen() && scaleXYUserModifier_ && GetHost()) {
1761         auto preScale =
1762             GetAnimatablePropertyStagingValue<Rosen::RSScaleModifier, Rosen::Vector2f>(scaleXYUserModifier_);
1763         if (!(NearEqual(preScale[0], scale.x) && NearEqual(preScale[1], scale.y))) {
1764             auto host = GetHost();
1765             ACE_SCOPED_TRACE("scale from (%f, %f) to (%f, %f), id:%d, tag:%s", preScale[0], preScale[1], scale.x,
1766                 scale.y, host->GetId(), host->GetTag().c_str());
1767         }
1768     }
1769     SetAnimatableProperty<Rosen::RSScaleModifier, Rosen::Vector2f>(scaleXYUserModifier_, { scale.x, scale.y });
1770     NotifyHostTransformUpdated();
1771     RequestNextFrame();
1772 }
1773 
MarshallTranslate(const TranslateOptions & translate)1774 Vector3F RosenRenderContext::MarshallTranslate(const TranslateOptions& translate)
1775 {
1776     float xValue = 0.0f;
1777     float yValue = 0.0f;
1778     if (translate.x.Unit() == DimensionUnit::PERCENT || translate.y.Unit() == DimensionUnit::PERCENT) {
1779         auto rect = GetPaintRectWithoutTransform();
1780         if (rect.IsEmpty()) {
1781             // size is not determined yet
1782             return Vector3F();
1783         }
1784         xValue = translate.x.ConvertToPxWithSize(rect.Width());
1785         yValue = translate.y.ConvertToPxWithSize(rect.Height());
1786     } else {
1787         xValue = translate.x.ConvertToPx();
1788         yValue = translate.y.ConvertToPx();
1789     }
1790     // translateZ doesn't support percentage
1791     float zValue = translate.z.ConvertToPx();
1792     return Vector3F(xValue, yValue, zValue);
1793 }
1794 
OnTransformTranslateUpdate(const TranslateOptions & translate)1795 void RosenRenderContext::OnTransformTranslateUpdate(const TranslateOptions& translate)
1796 {
1797     CHECK_NULL_VOID(rsNode_);
1798     auto translateVec = MarshallTranslate(translate);
1799     auto changed = true;
1800     Rosen::Vector2f preTranslate;
1801     if (translateXYUserModifier_) {
1802         preTranslate =
1803             GetAnimatablePropertyStagingValue<Rosen::RSTranslateModifier, Rosen::Vector2f>(translateXYUserModifier_);
1804         changed = !NearEqual(preTranslate[0], translateVec.x) || !NearEqual(preTranslate[1], translateVec.y);
1805     }
1806     if (AnimationUtils::IsImplicitAnimationOpen() && translateXYUserModifier_ && GetHost()) {
1807         if (!(NearEqual(preTranslate[0], translateVec.x) && NearEqual(preTranslate[1], translateVec.y))) {
1808             auto host = GetHost();
1809             ACE_SCOPED_TRACE("translate from (%f, %f) to (%f, %f), id:%d, tag:%s", preTranslate[0], preTranslate[1],
1810                 translateVec.x, translateVec.y, host->GetId(), host->GetTag().c_str());
1811         }
1812     }
1813     SetAnimatableProperty<Rosen::RSTranslateModifier, Rosen::Vector2f>(
1814         translateXYUserModifier_, { translateVec.x, translateVec.y });
1815     SetAnimatableProperty<Rosen::RSTranslateZModifier, float>(translateZUserModifier_, translateVec.z);
1816     ElementRegister::GetInstance()->ReSyncGeometryTransition(GetHost());
1817     NotifyHostTransformUpdated(changed);
1818     RequestNextFrame();
1819 }
1820 
OnTransformRotateUpdate(const Vector5F & rotate)1821 void RosenRenderContext::OnTransformRotateUpdate(const Vector5F& rotate)
1822 {
1823     CHECK_NULL_VOID(rsNode_);
1824     float norm = std::sqrt(std::pow(rotate.x, 2) + std::pow(rotate.y, 2) + std::pow(rotate.z, 2));
1825     if (NearZero(norm)) {
1826         norm = 1.0f;
1827     }
1828     // for rosen backend, the rotation angles in the x and y directions should be set to opposite angles
1829     rsNode_->SetRotation(-rotate.w * rotate.x / norm, -rotate.w * rotate.y / norm, rotate.w * rotate.z / norm);
1830     // set camera distance
1831     rsNode_->SetCameraDistance(rotate.v);
1832     NotifyHostTransformUpdated();
1833     RequestNextFrame();
1834 }
1835 
OnTransformCenterUpdate(const DimensionOffset & center)1836 void RosenRenderContext::OnTransformCenterUpdate(const DimensionOffset& center)
1837 {
1838     RectF rect = GetPaintRectWithoutTransform();
1839     if (!RectIsNull()) {
1840         float xPivot = ConvertDimensionToScaleBySize(center.GetX(), rect.Width());
1841         float yPivot = ConvertDimensionToScaleBySize(center.GetY(), rect.Height());
1842         float zPivot = 0.0f;
1843         auto& z = center.GetZ();
1844         if (z.has_value()) {
1845             zPivot = static_cast<float>(z.value().ConvertToVp());
1846         }
1847         SetPivot(xPivot, yPivot, zPivot);
1848         NotifyHostTransformUpdated();
1849     }
1850     RequestNextFrame();
1851 }
1852 
OnTransformMatrixUpdate(const Matrix4 & matrix)1853 void RosenRenderContext::OnTransformMatrixUpdate(const Matrix4& matrix)
1854 {
1855     CHECK_NULL_VOID(rsNode_);
1856     if (!transformMatrixModifier_.has_value()) {
1857         transformMatrixModifier_ = TransformMatrixModifier();
1858     }
1859     DecomposedTransform transform;
1860     if (!TransformUtil::DecomposeTransform(transform, matrix)) {
1861         // fallback to basic matrix decompose
1862         Rosen::Vector2f xyTranslateValue { static_cast<float>(matrix.Get(0, 3)), static_cast<float>(matrix.Get(1, 3)) };
1863         Rosen::Vector2f scaleValue { 0.0f, 0.0f };
1864         AddOrChangeTranslateModifier(rsNode_, transformMatrixModifier_->translateXY,
1865             transformMatrixModifier_->translateXYValue, xyTranslateValue);
1866         AddOrChangeScaleModifier(
1867             rsNode_, transformMatrixModifier_->scaleXY, transformMatrixModifier_->scaleXYValue, scaleValue);
1868     } else {
1869         Rosen::Vector4f perspectiveValue { transform.perspective[0], transform.perspective[1], 0.0f,
1870             1.0f };
1871         Rosen::Vector2f xyTranslateValue { transform.translate[0], transform.translate[1] };
1872         Rosen::Quaternion quaternion { static_cast<float>(transform.quaternion.GetX()),
1873             static_cast<float>(transform.quaternion.GetY()), static_cast<float>(transform.quaternion.GetZ()),
1874             static_cast<float>(transform.quaternion.GetW()) };
1875         Rosen::Vector2f xyScaleValue { transform.scale[0], transform.scale[1] };
1876         Rosen::Vector3f skewValue { transform.skew[0], transform.skew[1], 0.0f };
1877 
1878         AddOrChangePerspectiveModifier(rsNode_, transformMatrixModifier_->perspective,
1879             transformMatrixModifier_->perspectiveValue, perspectiveValue);
1880         AddOrChangeTranslateModifier(rsNode_, transformMatrixModifier_->translateXY,
1881             transformMatrixModifier_->translateXYValue, xyTranslateValue);
1882         AddOrChangeScaleModifier(
1883             rsNode_, transformMatrixModifier_->scaleXY, transformMatrixModifier_->scaleXYValue, xyScaleValue);
1884         AddOrChangeSkewModifier(
1885             rsNode_, transformMatrixModifier_->skew, transformMatrixModifier_->skewValue, skewValue);
1886         AddOrChangeQuaternionModifier(
1887             rsNode_, transformMatrixModifier_->quaternion, transformMatrixModifier_->quaternionValue, quaternion);
1888     }
1889     NotifyHostTransformUpdated();
1890     RequestNextFrame();
1891 }
1892 
1893 RectF gRect;
1894 
Degree2Radian(int32_t degree)1895 double Degree2Radian(int32_t degree)
1896 {
1897     const float pi = 3.14159265;
1898     degree = degree % FULL_ROTATION;
1899     if (degree < 0) {
1900         degree += FULL_ROTATION;
1901     }
1902     return degree * pi / STRAIGHT_ANGLE;
1903 }
1904 
SetCorner(double & x,double & y,double width,double height,int32_t degree)1905 void SetCorner(double& x, double& y, double width, double height, int32_t degree)
1906 {
1907     if (degree == RIGHT_ANGLE) {
1908         x = 0;
1909         y = height;
1910     } else if (degree == STRAIGHT_ANGLE) {
1911         x = width;
1912         y = height;
1913     } else if (degree == REFLEX_ANGLE) {
1914         x = width;
1915         y = 0;
1916     }
1917 }
1918 
SkewRect(float sx,float sy,RectF & rect)1919 void SkewRect(float sx, float sy, RectF& rect)
1920 {
1921     auto left = rect.Left();
1922     auto right = rect.Right();
1923     auto top = rect.Top();
1924     auto bottom = rect.Bottom();
1925 
1926     auto leftAfterSkew = sx > 0 ? left + sx * top : left + sx * bottom;
1927     auto rightAfterSkew = sx > 0 ? right + sx * bottom : right + sx * top;
1928     auto topAfterSkew = sy > 0 ? top + sy * left : top + sy * right;
1929     auto bottomAfterSkew = sy > 0 ? bottom + sy * right : bottom + sy * left;
1930 
1931     rect.SetLeft(leftAfterSkew);
1932     rect.SetWidth(rightAfterSkew - leftAfterSkew);
1933     rect.SetTop(topAfterSkew);
1934     rect.SetHeight(bottomAfterSkew - topAfterSkew);
1935 }
1936 
PerspectiveRect(float px,float py,RectF & rect)1937 void PerspectiveRect(float px, float py, RectF& rect)
1938 {
1939     auto left = rect.Left();
1940     auto right = rect.Right();
1941     auto top = rect.Top();
1942     auto bottom = rect.Bottom();
1943 
1944     auto leftAfterSkew = Infinity<double>();
1945     auto rightAfterSkew = -Infinity<double>();
1946     auto topAfterSkew = Infinity<double>();
1947     auto bottomAfterSkew = -Infinity<double>();
1948 
1949     double xValues[] = { left, right };
1950     double yValues[] = { top, bottom };
1951 
1952     for (uint32_t i = 0; i < 2; i++) {
1953         for (uint32_t j = 0; j < 2; j++) {
1954             double perspectiveValue = px * xValues[i] + py * yValues[j] + 1;
1955             if (NearZero(perspectiveValue)) {
1956                 return;
1957             }
1958             leftAfterSkew = std::min(leftAfterSkew, xValues[i] / perspectiveValue);
1959             rightAfterSkew = std::max(rightAfterSkew, xValues[i] / perspectiveValue);
1960             topAfterSkew = std::min(topAfterSkew, yValues[i] / perspectiveValue);
1961             bottomAfterSkew = std::max(bottomAfterSkew, yValues[i] / perspectiveValue);
1962         }
1963     }
1964 
1965     rect.SetLeft(leftAfterSkew);
1966     rect.SetWidth(rightAfterSkew - leftAfterSkew);
1967     rect.SetTop(topAfterSkew);
1968     rect.SetHeight(bottomAfterSkew - topAfterSkew);
1969 }
1970 
SkewPoint(float sx,float sy,PointF & point)1971 void SkewPoint(float sx, float sy, PointF& point)
1972 {
1973     auto x = point.GetX();
1974     auto y = point.GetY();
1975 
1976     point.SetX(x + y * sx);
1977     point.SetY(y + x * sy);
1978 }
1979 
GetPaintRectWithTransform()1980 RectF RosenRenderContext::GetPaintRectWithTransform()
1981 {
1982     RectF rect;
1983 
1984     CHECK_NULL_RETURN(rsNode_, rect);
1985     rect = GetPaintRectWithoutTransform();
1986     auto translate = rsNode_->GetStagingProperties().GetTranslate();
1987     auto skew = rsNode_->GetStagingProperties().GetSkew();
1988     auto perspective = rsNode_->GetStagingProperties().GetPersp();
1989     auto scale = rsNode_->GetStagingProperties().GetScale();
1990     auto center = rsNode_->GetStagingProperties().GetPivot();
1991     auto degree = rsNode_->GetStagingProperties().GetRotation();
1992     // calculate new pos.
1993     auto centOffset = OffsetF(center[0] * rect.Width(), center[1] * rect.Height());
1994     auto centerPos = rect.GetOffset() + centOffset;
1995     auto newPos = centerPos - OffsetF(centOffset.GetX() * scale[0], centOffset.GetY() * scale[1]);
1996     newPos = newPos + OffsetF(translate[0], translate[1]);
1997     rect.SetOffset(newPos);
1998     // calculate new size.
1999     auto oldSize = rect.GetSize();
2000     auto newSize = SizeF(oldSize.Width() * scale[0], oldSize.Height() * scale[1]);
2001     rect.SetSize(newSize);
2002     // calculate skew
2003     SkewRect(skew[0], skew[1], rect);
2004     // calculate rotate
2005     degree = static_cast<int32_t>(degree) % FULL_ROTATION;
2006     auto radian = Degree2Radian(degree);
2007     if (degree != 0) {
2008         auto newRect = GetPaintRectWithoutTransform();
2009         double leftX = 0.0;
2010         double leftY = 0.0;
2011         degree = degree < 0 ? degree + FULL_ROTATION : degree;
2012         SetCorner(leftX, leftY, oldSize.Width(), oldSize.Height(), degree);
2013         double centerX = oldSize.Width() * center[0];
2014         double centerY = oldSize.Height() * center[1];
2015         auto tmp = leftX;
2016         leftX = (leftX - centerX) * cos(-1 * radian) + (leftY - centerY) * sin(-1 * radian);
2017         leftY = -1 * (tmp - centerX) * sin(-1 * radian) + (leftY - centerY) * cos(-1 * radian);
2018         leftX += newRect.GetOffset().GetX() + centerX;
2019         leftY += newRect.GetOffset().GetY() + centerY;
2020         auto offset = OffsetF(leftX + translate[0], leftY + translate[1]);
2021         rect.SetOffset(offset);
2022         if (degree == STRAIGHT_ANGLE) {
2023             newSize = SizeF(oldSize.Width() * scale[0], oldSize.Height() * scale[1]);
2024         } else {
2025             newSize = SizeF(oldSize.Height() * scale[1], oldSize.Width() * scale[0]);
2026         }
2027         rect.SetSize(newSize);
2028 
2029         // calculate perspective
2030         PerspectiveRect(perspective[0], perspective[1], rect);
2031     }
2032     gRect = rect;
2033     return rect;
2034 }
2035 
GetPaintRectWithTranslate()2036 std::pair<RectF, bool> RosenRenderContext::GetPaintRectWithTranslate()
2037 {
2038     RectF rect;
2039     bool error = hasScales_;
2040     CHECK_NULL_RETURN(rsNode_, std::make_pair(rect, error));
2041     if (rsNode_->GetStagingProperties().GetRotation()) {
2042         return std::make_pair(RectF(0, 0, -1, -1), error);
2043     }
2044     rect = GetPaintRectWithoutTransform();
2045     auto translate = rsNode_->GetStagingProperties().GetTranslate();
2046     rect.SetOffset(rect.GetOffset() + OffsetF(translate[0], translate[1]));
2047     return std::make_pair(rect, error);
2048 }
2049 
GetRevertMatrix()2050 Matrix4 RosenRenderContext::GetRevertMatrix()
2051 {
2052     CHECK_NULL_RETURN(rsNode_, {});
2053     auto center = rsNode_->GetStagingProperties().GetPivot();
2054     Matrix4 rotateMat;
2055     if (transformMatrixModifier_ && !transformMatrixModifier_->quaternionValue->GetStagingValue().IsIdentity()) {
2056         auto quaternionValue = transformMatrixModifier_->quaternionValue->GetStagingValue();
2057         // 2: parameter index, 3: parameter index
2058         rotateMat =
2059             Matrix4::QuaternionToMatrix(quaternionValue[0], quaternionValue[1], quaternionValue[2], quaternionValue[3]);
2060     } else {
2061         int32_t degree = rsNode_->GetStagingProperties().GetRotation();
2062         if (rsNode_->GetType() == RSUINodeType::DISPLAY_NODE && degree != 0) {
2063             degree = 0;
2064             return Matrix4();
2065         }
2066         rotateMat = Matrix4::CreateRotate(degree, 0, 0, 1);
2067     }
2068 
2069     auto translate = rsNode_->GetStagingProperties().GetTranslate();
2070     auto skew = rsNode_->GetStagingProperties().GetSkew();
2071     auto scale = rsNode_->GetStagingProperties().GetScale();
2072     auto perspective = rsNode_->GetStagingProperties().GetPersp();
2073 
2074     RectF rect = GetPaintRectWithoutTransform();
2075     auto centOffset = OffsetF(center[0] * rect.Width(), center[1] * rect.Height());
2076     auto centerPos = rect.GetOffset() + centOffset;
2077 
2078     auto perspectiveMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2079                           Matrix4::CreateFactorPerspective(perspective[0], perspective[1]) *
2080                           Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2081     auto translateMat = Matrix4::CreateTranslate(translate[0], translate[1], 0);
2082     auto rotationMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) * rotateMat *
2083                        Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2084     auto skewMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2085                    Matrix4::CreateFactorSkew(skew[0], skew[1]) *
2086                    Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2087     auto scaleMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2088                     Matrix4::CreateScale(scale[0], scale[1], 1) *
2089                     Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2090 
2091     return Matrix4::Invert(perspectiveMat * translateMat * rotationMat * skewMat * scaleMat);
2092 }
2093 
GetMatrix()2094 Matrix4 RosenRenderContext::GetMatrix()
2095 {
2096     CHECK_NULL_RETURN(rsNode_, {});
2097     auto center = rsNode_->GetStagingProperties().GetPivot();
2098     int32_t degree = rsNode_->GetStagingProperties().GetRotation();
2099     if (rsNode_->GetType() == RSUINodeType::DISPLAY_NODE && degree != 0) {
2100         degree = 0;
2101         return Matrix4();
2102     }
2103 
2104     auto translate = rsNode_->GetStagingProperties().GetTranslate();
2105     auto skew = rsNode_->GetStagingProperties().GetSkew();
2106     auto scale = rsNode_->GetStagingProperties().GetScale();
2107 
2108     RectF rect = GetPaintRectWithoutTransform();
2109     auto centOffset = OffsetF(center[0] * rect.Width(), center[1] * rect.Height());
2110     auto centerPos = rect.GetOffset() + centOffset;
2111 
2112     auto translateMat = Matrix4::CreateTranslate(translate[0], translate[1], 0);
2113     auto rotationMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2114                        Matrix4::CreateRotate(degree, 0, 0, 1) *
2115                        Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2116     auto skewMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2117                    Matrix4::CreateFactorSkew(skew[0], skew[1]) *
2118                    Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2119     auto scaleMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2120                     Matrix4::CreateScale(scale[0], scale[1], 1) *
2121                     Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2122 
2123     return translateMat * rotationMat * skewMat * scaleMat;
2124 }
2125 
2126 // only for GetPositionToXXXWithTransform in FrameNode.
2127 // contains rotate and perspective matrix set by tranform.
GetMatrixWithTransformRotate()2128 Matrix4 RosenRenderContext::GetMatrixWithTransformRotate()
2129 {
2130     CHECK_NULL_RETURN(rsNode_, {});
2131     auto center = rsNode_->GetStagingProperties().GetPivot();
2132 
2133     Matrix4 rotateMat;
2134     if (transformMatrixModifier_ && !transformMatrixModifier_->quaternionValue->GetStagingValue().IsIdentity()) {
2135         auto quaternionValue = transformMatrixModifier_->quaternionValue->GetStagingValue();
2136         // 2: parameter index, 3: parameter index
2137         rotateMat =
2138             Matrix4::QuaternionToMatrix(quaternionValue[0], quaternionValue[1], quaternionValue[2], quaternionValue[3]);
2139     } else {
2140         int32_t degree = rsNode_->GetStagingProperties().GetRotation();
2141         if (rsNode_->GetType() == RSUINodeType::DISPLAY_NODE && degree != 0) {
2142             degree = 0;
2143             return Matrix4();
2144         }
2145         rotateMat = Matrix4::CreateRotate(degree, 0, 0, 1);
2146     }
2147 
2148     auto translate = rsNode_->GetStagingProperties().GetTranslate();
2149     auto skew = rsNode_->GetStagingProperties().GetSkew();
2150     auto scale = rsNode_->GetStagingProperties().GetScale();
2151     auto perspective = rsNode_->GetStagingProperties().GetPersp();
2152 
2153     RectF rect = GetPaintRectWithoutTransform();
2154     auto centOffset = OffsetF(center[0] * rect.Width(), center[1] * rect.Height());
2155     auto centerPos = rect.GetOffset() + centOffset;
2156 
2157     auto perspectiveMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2158                           Matrix4::CreateFactorPerspective(perspective[0], perspective[1]) *
2159                           Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2160     auto translateMat = Matrix4::CreateTranslate(translate[0], translate[1], 0);
2161     auto rotationMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) * rotateMat *
2162                        Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2163     auto skewMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2164                    Matrix4::CreateFactorSkew(skew[0], skew[1]) *
2165                    Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2166     auto scaleMat = Matrix4::CreateTranslate(centerPos.GetX(), centerPos.GetY(), 0) *
2167                     Matrix4::CreateScale(scale[0], scale[1], 1) *
2168                     Matrix4::CreateTranslate(-centerPos.GetX(), -centerPos.GetY(), 0);
2169 
2170     return perspectiveMat * translateMat * rotationMat * skewMat * scaleMat;
2171 }
2172 
GetLocalTransformMatrix()2173 Matrix4 RosenRenderContext::GetLocalTransformMatrix()
2174 {
2175     auto invertMat = GetRevertMatrix();
2176     RectF rect = GetPaintRectWithoutTransform();
2177     auto transformMat = Matrix4::CreateTranslate(-rect.GetOffset().GetX(), -rect.GetOffset().GetY(), 0) * invertMat;
2178     return transformMat;
2179 }
2180 
GetPointWithRevert(PointF & point)2181 void RosenRenderContext::GetPointWithRevert(PointF& point)
2182 {
2183     auto invertMat = GetRevertMatrix();
2184     Point tmp(point.GetX(), point.GetY());
2185     auto invertPoint = invertMat * tmp;
2186     point.SetX(invertPoint.GetX());
2187     point.SetY(invertPoint.GetY());
2188 }
2189 
GetPointTransform(PointF & point)2190 void RosenRenderContext::GetPointTransform(PointF& point)
2191 {
2192     auto transformMat = GetMatrix();
2193     Point tmp(point.GetX(), point.GetY());
2194     auto transformPoint = transformMat * tmp;
2195     point.SetX(transformPoint.GetX());
2196     point.SetY(transformPoint.GetY());
2197 }
2198 
2199 // only for GetPositionToXXXWithTransform in FrameNode
GetPointTransformRotate(PointF & point)2200 void RosenRenderContext::GetPointTransformRotate(PointF& point)
2201 {
2202     auto transformMat = GetMatrixWithTransformRotate();
2203     Point tmp(point.GetX(), point.GetY());
2204     auto transformPoint = transformMat * tmp;
2205     point.SetX(transformPoint.GetX());
2206     point.SetY(transformPoint.GetY());
2207 }
2208 
GetPointWithTransform(PointF & point)2209 void RosenRenderContext::GetPointWithTransform(PointF& point)
2210 {
2211     CHECK_NULL_VOID(rsNode_);
2212     auto skew = rsNode_->GetStagingProperties().GetSkew();
2213     auto scale = rsNode_->GetStagingProperties().GetScale();
2214     point = PointF(point.GetX() / scale[0], point.GetY() / scale[1]);
2215     SkewPoint(skew[0], skew[1], point);
2216     int32_t degree = rsNode_->GetStagingProperties().GetRotation();
2217     if (degree != 0 && rsNode_->GetType() == RSUINodeType::DISPLAY_NODE) {
2218         degree = 0;
2219     }
2220     degree = degree % FULL_ROTATION;
2221     if (degree != 0) {
2222         auto translate = rsNode_->GetStagingProperties().GetTranslate();
2223         auto perspective = rsNode_->GetStagingProperties().GetPersp();
2224         RectF rect = GetPaintRectWithoutTransform();
2225         auto center = rsNode_->GetStagingProperties().GetPivot();
2226         auto radian = Degree2Radian(degree);
2227         point = point + gRect.GetOffset();
2228         point = point - OffsetF(translate[0], translate[1]);
2229         auto centOffset = OffsetF(center[0] * gRect.Width(), center[1] * gRect.Height());
2230         auto centerPos = gRect.GetOffset() + centOffset - OffsetF(translate[0], translate[1]);
2231         auto centerX = centerPos.GetX();
2232         auto centerY = centerPos.GetY();
2233 
2234         double currentPointX = (point.GetX() - centerX) * cos(radian) + (point.GetY() - centerY) * sin(radian);
2235         double currentPointY = -1 * (point.GetX() - centerX) * sin(radian) + (point.GetY() - centerY) * cos(radian);
2236         currentPointX += centerX - rect.Left();
2237         currentPointY += centerY - rect.Top();
2238 
2239         double perspectiveValue = perspective[0] * currentPointX + perspective[1] * currentPointY + 1;
2240         if (NearZero(perspectiveValue)) {
2241             point.SetX(currentPointX);
2242             point.SetY(currentPointY);
2243             return;
2244         }
2245 
2246         point.SetX(currentPointX / perspectiveValue);
2247         point.SetY(currentPointY / perspectiveValue);
2248     }
2249 }
2250 
2251 // comparing to frameRect of geometryNode,
2252 // paint rect has position, offset, markAnchor, pixelGridRound and safeArea properties
GetPaintRectWithoutTransform()2253 RectF RosenRenderContext::GetPaintRectWithoutTransform()
2254 {
2255     return paintRect_;
2256 }
2257 
UpdateTranslateInXY(const OffsetF & offset)2258 void RosenRenderContext::UpdateTranslateInXY(const OffsetF& offset)
2259 {
2260     CHECK_NULL_VOID(rsNode_);
2261     auto xValue = offset.GetX();
2262     auto yValue = offset.GetY();
2263     bool changed = true;
2264     if (translateXY_) {
2265         auto propertyXY = std::static_pointer_cast<RSAnimatableProperty<Vector2f>>(translateXY_->GetProperty());
2266         if (propertyXY) {
2267             auto translate = propertyXY->Get();
2268             changed = !NearEqual(translate[0], xValue) || !NearEqual(translate[1], yValue);
2269             propertyXY->Set({ xValue, yValue });
2270         }
2271     } else {
2272         auto propertyXY = std::make_shared<RSAnimatableProperty<Vector2f>>(Vector2f(xValue, yValue));
2273         translateXY_ = std::make_shared<Rosen::RSTranslateModifier>(propertyXY);
2274         rsNode_->AddModifier(translateXY_);
2275     }
2276     ElementRegister::GetInstance()->ReSyncGeometryTransition(GetHost());
2277     NotifyHostTransformUpdated(changed);
2278 }
2279 
GetShowingTranslateProperty()2280 OffsetF RosenRenderContext::GetShowingTranslateProperty()
2281 {
2282     OffsetF offset;
2283     CHECK_NULL_RETURN(translateXY_, offset);
2284     auto property = std::static_pointer_cast<RSAnimatableProperty<Vector2f>>(translateXY_->GetProperty());
2285     CHECK_NULL_RETURN(property, offset);
2286     auto result = property->GetShowingValueAndCancelAnimation();
2287     if (!result) {
2288         return offset;
2289     }
2290     auto translate = property->Get();
2291     offset.SetX(translate[0]);
2292     offset.SetY(translate[1]);
2293     return offset;
2294 }
2295 
CancelTranslateXYAnimation()2296 void RosenRenderContext::CancelTranslateXYAnimation()
2297 {
2298     CHECK_NULL_VOID(translateXY_);
2299     auto property = std::static_pointer_cast<RSAnimatableProperty<Vector2f>>(translateXY_->GetProperty());
2300     CHECK_NULL_VOID(property);
2301     property->RequestCancelAnimation();
2302 }
2303 
GetTranslateXYProperty()2304 OffsetF RosenRenderContext::GetTranslateXYProperty()
2305 {
2306     OffsetF offset;
2307     CHECK_NULL_RETURN(translateXY_, offset);
2308     auto property = std::static_pointer_cast<RSAnimatableProperty<Vector2f>>(translateXY_->GetProperty());
2309     CHECK_NULL_RETURN(property, offset);
2310     auto translate = property->Get();
2311     offset.SetX(translate[0]);
2312     offset.SetY(translate[1]);
2313     return offset;
2314 }
2315 
NotifyTransitionInner(const SizeF & frameSize,bool isTransitionIn)2316 void RosenRenderContext::NotifyTransitionInner(const SizeF& frameSize, bool isTransitionIn)
2317 {
2318     CHECK_NULL_VOID(rsNode_);
2319     if (propTransitionAppearing_ || propTransitionDisappearing_) {
2320         // old transition
2321         auto& transOptions = isTransitionIn ? propTransitionAppearing_ : propTransitionDisappearing_;
2322         auto effect = GetRSTransitionWithoutType(transOptions, frameSize);
2323         CHECK_NULL_VOID(effect);
2324         SetTransitionPivot(frameSize, isTransitionIn);
2325         // notice that we have been in animateTo, so do not need to use Animation closure to notify transition.
2326         rsNode_->NotifyTransition(effect, isTransitionIn);
2327         return;
2328     }
2329     // add default transition effect on the 'breaking point' of render tree, if no user-defined transition effect
2330     // and triggered in AnimateTo closure.
2331     // Note: this default transition effect will be removed after all transitions finished, implemented in
2332     // OnTransitionInFinish. and OnTransitionOutFinish.
2333     if (isBreakingPoint_ && !transitionEffect_ && AnimationUtils::IsImplicitAnimationOpen()) {
2334         hasDefaultTransition_ = true;
2335         transitionEffect_ = RosenTransitionEffect::CreateDefaultRosenTransitionEffect();
2336         RSNode::ExecuteWithoutAnimation([this, isTransitionIn]() {
2337             // transitionIn effects should be initialized as active if is transitionIn.
2338             transitionEffect_->Attach(Claim(this), isTransitionIn);
2339         });
2340     }
2341     NotifyTransition(isTransitionIn);
2342 }
2343 
OpacityAnimation(const AnimationOption & option,double begin,double end)2344 void RosenRenderContext::OpacityAnimation(const AnimationOption& option, double begin, double end)
2345 {
2346     CHECK_NULL_VOID(rsNode_);
2347     rsNode_->SetAlpha(begin);
2348     AnimationUtils::Animate(
2349         option,
2350         [rsNode = rsNode_, endAlpha = end]() {
2351             CHECK_NULL_VOID(rsNode);
2352             rsNode->SetAlpha(endAlpha);
2353         },
2354         option.GetOnFinishEvent());
2355 }
2356 
ScaleAnimation(const AnimationOption & option,double begin,double end)2357 void RosenRenderContext::ScaleAnimation(const AnimationOption& option, double begin, double end)
2358 {
2359     CHECK_NULL_VOID(rsNode_);
2360     SetScale(begin, begin);
2361     AnimationUtils::Animate(
2362         option, [this, end]() { SetScale(end, end); }, option.GetOnFinishEvent());
2363 }
2364 
SetBorderRadius(const BorderRadiusProperty & value)2365 void RosenRenderContext::SetBorderRadius(const BorderRadiusProperty& value)
2366 {
2367     CHECK_NULL_VOID(rsNode_);
2368     auto paintRect = AdjustPaintRect();
2369     if (isDisappearing_ && !paintRect.IsValid()) {
2370         return;
2371     }
2372     double width = paintRect.Width();
2373     Rosen::Vector4f cornerRadius;
2374     cornerRadius.SetValues(static_cast<float>(value.radiusTopLeft.value_or(Dimension()).ConvertToPxWithSize(width)),
2375         static_cast<float>(value.radiusTopRight.value_or(Dimension()).ConvertToPxWithSize(width)),
2376         static_cast<float>(value.radiusBottomRight.value_or(Dimension()).ConvertToPxWithSize(width)),
2377         static_cast<float>(value.radiusBottomLeft.value_or(Dimension()).ConvertToPxWithSize(width)));
2378     rsNode_->SetCornerRadius(cornerRadius);
2379     RequestNextFrame();
2380 }
2381 
RegisterDensityChangedCallback()2382 void RosenRenderContext::RegisterDensityChangedCallback()
2383 {
2384     if (densityChangedCallbackId_ == DEFAULT_CALLBACK_ID) {
2385         auto context = GetPipelineContext();
2386         CHECK_NULL_VOID(context);
2387         densityChangedCallbackId_ = context->RegisterDensityChangedCallback(
2388             [self = WeakClaim(this)](double density) {
2389             auto renderContext = self.Upgrade();
2390             CHECK_NULL_VOID(renderContext);
2391             auto borderRadius = renderContext->GetBorderRadius();
2392             if (borderRadius.has_value()) {
2393                 renderContext->SetBorderRadius(borderRadius.value());
2394             }
2395             auto outerBorderRadius = renderContext->GetOuterBorderRadius();
2396             if (outerBorderRadius.has_value()) {
2397                 renderContext->SetOuterBorderRadius(outerBorderRadius.value());
2398             }
2399         });
2400     }
2401 }
2402 
OnBorderRadiusUpdate(const BorderRadiusProperty & value)2403 void RosenRenderContext::OnBorderRadiusUpdate(const BorderRadiusProperty& value)
2404 {
2405     RegisterDensityChangedCallback();
2406     CHECK_NULL_VOID(isSynced_);
2407     SetBorderRadius(value);
2408 }
2409 
OnBorderColorUpdate(const BorderColorProperty & value)2410 void RosenRenderContext::OnBorderColorUpdate(const BorderColorProperty& value)
2411 {
2412     SetBorderColor(value);
2413 }
2414 
SetBorderColor(const BorderColorProperty & value)2415 void RosenRenderContext::SetBorderColor(const BorderColorProperty& value)
2416 {
2417     CHECK_NULL_VOID(rsNode_);
2418     rsNode_->SetBorderColor(value.leftColor.value_or(Color::BLACK).GetValue(),
2419         value.topColor.value_or(Color::BLACK).GetValue(), value.rightColor.value_or(Color::BLACK).GetValue(),
2420         value.bottomColor.value_or(Color::BLACK).GetValue());
2421     RequestNextFrame();
2422 }
2423 
SetBorderWidth(const BorderWidthProperty & value)2424 void RosenRenderContext::SetBorderWidth(const BorderWidthProperty& value)
2425 {
2426     CHECK_NULL_VOID(rsNode_);
2427     Rosen::Vector4f cornerBorderWidth;
2428     cornerBorderWidth.SetValues(static_cast<float>((value.leftDimen.value()).ConvertToPx()),
2429         static_cast<float>((value.topDimen.value()).ConvertToPx()),
2430         static_cast<float>((value.rightDimen.value()).ConvertToPx()),
2431         static_cast<float>((value.bottomDimen.value()).ConvertToPx()));
2432     rsNode_->SetBorderWidth(cornerBorderWidth);
2433     borderWidth_ = cornerBorderWidth;
2434     RequestNextFrame();
2435 }
2436 
UpdateBorderWidthF(const BorderWidthPropertyF & value)2437 void RosenRenderContext::UpdateBorderWidthF(const BorderWidthPropertyF& value)
2438 {
2439     CHECK_NULL_VOID(rsNode_);
2440     Rosen::Vector4f cornerBorderWidth;
2441     cornerBorderWidth.SetValues(value.leftDimen.value_or(0), static_cast<float>(value.topDimen.value_or(0)),
2442         static_cast<float>(value.rightDimen.value_or(0)), static_cast<float>(value.bottomDimen.value_or(0)));
2443     rsNode_->SetBorderWidth(cornerBorderWidth);
2444     borderWidth_ = cornerBorderWidth;
2445     RequestNextFrame();
2446 }
2447 
OnBorderStyleUpdate(const BorderStyleProperty & value)2448 void RosenRenderContext::OnBorderStyleUpdate(const BorderStyleProperty& value)
2449 {
2450     SetBorderStyle(value);
2451 }
2452 
SetBorderStyle(const BorderStyleProperty & value)2453 void RosenRenderContext::SetBorderStyle(const BorderStyleProperty& value)
2454 {
2455     CHECK_NULL_VOID(rsNode_);
2456     rsNode_->SetBorderStyle(static_cast<uint32_t>(value.styleLeft.value_or(BorderStyle::SOLID)),
2457         static_cast<uint32_t>(value.styleTop.value_or(BorderStyle::SOLID)),
2458         static_cast<uint32_t>(value.styleRight.value_or(BorderStyle::SOLID)),
2459         static_cast<uint32_t>(value.styleBottom.value_or(BorderStyle::SOLID)));
2460     RequestNextFrame();
2461 }
2462 
OnDashGapUpdate(const BorderWidthProperty & value)2463 void RosenRenderContext::OnDashGapUpdate(const BorderWidthProperty& value)
2464 {
2465     SetDashGap(value);
2466 }
2467 
SetDashGap(const BorderWidthProperty & value)2468 void RosenRenderContext::SetDashGap(const BorderWidthProperty& value)
2469 {
2470     CHECK_NULL_VOID(rsNode_);
2471     Rosen::Vector4f cornerDashGap;
2472     cornerDashGap.SetValues(static_cast<float>((value.leftDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2473         static_cast<float>((value.topDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2474         static_cast<float>((value.rightDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2475         static_cast<float>((value.bottomDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()));
2476     rsNode_->SetBorderDashGap(cornerDashGap);
2477     RequestNextFrame();
2478 }
2479 
OnDashWidthUpdate(const BorderWidthProperty & value)2480 void RosenRenderContext::OnDashWidthUpdate(const BorderWidthProperty& value)
2481 {
2482     SetDashWidth(value);
2483 }
2484 
SetDashWidth(const BorderWidthProperty & value)2485 void RosenRenderContext::SetDashWidth(const BorderWidthProperty& value)
2486 {
2487     CHECK_NULL_VOID(rsNode_);
2488     Rosen::Vector4f cornerDashWidth;
2489     cornerDashWidth.SetValues(static_cast<float>((value.leftDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2490         static_cast<float>((value.topDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2491         static_cast<float>((value.rightDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()),
2492         static_cast<float>((value.bottomDimen.value_or(DASH_GEP_WIDTH)).ConvertToPx()));
2493     rsNode_->SetBorderDashWidth(cornerDashWidth);
2494     RequestNextFrame();
2495 }
2496 
OnOuterBorderRadiusUpdate(const BorderRadiusProperty & value)2497 void RosenRenderContext::OnOuterBorderRadiusUpdate(const BorderRadiusProperty& value)
2498 {
2499     RegisterDensityChangedCallback();
2500     SetOuterBorderRadius(value);
2501 }
2502 
SetOuterBorderRadius(const BorderRadiusProperty & value)2503 void RosenRenderContext::SetOuterBorderRadius(const BorderRadiusProperty& value)
2504 {
2505     CHECK_NULL_VOID(rsNode_);
2506     auto paintRect = AdjustPaintRect();
2507     if (isDisappearing_ && !paintRect.IsValid()) {
2508         return;
2509     }
2510     double radiusX = paintRect.Width();
2511     Rosen::Vector4f cornerRadius;
2512     cornerRadius.SetValues(
2513         static_cast<float>(value.radiusTopLeft.value_or(Dimension(0.0)).ConvertToPxWithSize(radiusX)),
2514         static_cast<float>(value.radiusTopRight.value_or(Dimension(0.0)).ConvertToPxWithSize(radiusX)),
2515         static_cast<float>(value.radiusBottomRight.value_or(Dimension(0.0)).ConvertToPxWithSize(radiusX)),
2516         static_cast<float>(value.radiusBottomLeft.value_or(Dimension(0.0)).ConvertToPxWithSize(radiusX)));
2517     rsNode_->SetOuterBorderRadius(cornerRadius);
2518     RequestNextFrame();
2519 }
2520 
OnOuterBorderColorUpdate(const BorderColorProperty & value)2521 void RosenRenderContext::OnOuterBorderColorUpdate(const BorderColorProperty& value)
2522 {
2523     SetOuterBorderColor(value);
2524 }
2525 
SetOuterBorderColor(const BorderColorProperty & value)2526 void RosenRenderContext::SetOuterBorderColor(const BorderColorProperty& value)
2527 {
2528     CHECK_NULL_VOID(rsNode_);
2529     Rosen::Vector4<Rosen::RSColor> color(Rosen::RSColor::FromArgbInt(value.leftColor.value_or(Color::BLACK).GetValue()),
2530         Rosen::RSColor::FromArgbInt(value.topColor.value_or(Color::BLACK).GetValue()),
2531         Rosen::RSColor::FromArgbInt(value.rightColor.value_or(Color::BLACK).GetValue()),
2532         Rosen::RSColor::FromArgbInt(value.bottomColor.value_or(Color::BLACK).GetValue()));
2533     rsNode_->SetOuterBorderColor(color);
2534     RequestNextFrame();
2535 }
2536 
OnOuterBorderWidthUpdate(const BorderWidthProperty & value)2537 void RosenRenderContext::OnOuterBorderWidthUpdate(const BorderWidthProperty& value)
2538 {
2539     SetOuterBorderWidth(value);
2540 }
2541 
SetOuterBorderWidth(const BorderWidthProperty & value)2542 void RosenRenderContext::SetOuterBorderWidth(const BorderWidthProperty& value)
2543 {
2544     CHECK_NULL_VOID(rsNode_);
2545     Rosen::Vector4f cornerBorderWidth;
2546     cornerBorderWidth.SetValues(static_cast<float>((value.leftDimen.value_or(Dimension(0.0))).ConvertToPx()),
2547         static_cast<float>((value.topDimen.value_or(Dimension(0.0))).ConvertToPx()),
2548         static_cast<float>((value.rightDimen.value_or(Dimension(0.0))).ConvertToPx()),
2549         static_cast<float>((value.bottomDimen.value_or(Dimension(0.0))).ConvertToPx()));
2550     rsNode_->SetOuterBorderWidth(cornerBorderWidth);
2551     RequestNextFrame();
2552 }
2553 
SetExtraOffset(const std::optional<OffsetF> & offset)2554 void RosenRenderContext::SetExtraOffset(const std::optional<OffsetF>& offset)
2555 {
2556     extraOffset_ = offset;
2557 }
2558 
OnOuterBorderStyleUpdate(const BorderStyleProperty & value)2559 void RosenRenderContext::OnOuterBorderStyleUpdate(const BorderStyleProperty& value)
2560 {
2561     SetOuterBorderStyle(value);
2562 }
2563 
SetOuterBorderStyle(const BorderStyleProperty & value)2564 void RosenRenderContext::SetOuterBorderStyle(const BorderStyleProperty& value)
2565 {
2566     CHECK_NULL_VOID(rsNode_);
2567     Rosen::Vector4<Rosen::BorderStyle> borderStyle(
2568         static_cast<Rosen::BorderStyle>(static_cast<uint32_t>(value.styleLeft.value_or(BorderStyle::SOLID))),
2569         static_cast<Rosen::BorderStyle>(static_cast<uint32_t>(value.styleTop.value_or(BorderStyle::SOLID))),
2570         static_cast<Rosen::BorderStyle>(static_cast<uint32_t>(value.styleRight.value_or(BorderStyle::SOLID))),
2571         static_cast<Rosen::BorderStyle>(static_cast<uint32_t>(value.styleBottom.value_or(BorderStyle::SOLID))));
2572     rsNode_->SetOuterBorderStyle(borderStyle);
2573     RequestNextFrame();
2574 }
2575 
OnAccessibilityFocusUpdate(bool isAccessibilityFocus,const int64_t accessibilityIdForVirtualNode)2576 void RosenRenderContext::OnAccessibilityFocusUpdate(
2577     bool isAccessibilityFocus, const int64_t accessibilityIdForVirtualNode)
2578 {
2579     auto uiNode = GetHost();
2580     CHECK_NULL_VOID(uiNode);
2581     UpdateAccessibilityFocus(isAccessibilityFocus);
2582     if (isAccessibilityFocus) {
2583         PaintAccessibilityFocus();
2584     } else {
2585         ClearAccessibilityFocus();
2586     }
2587 
2588     if (accessibilityIdForVirtualNode == ACCESSIBILITY_FOCUS_WITHOUT_EVENT) {
2589         return;
2590     }
2591 
2592     if (accessibilityIdForVirtualNode == INVALID_PARENT_ID) {
2593         uiNode->OnAccessibilityEvent(isAccessibilityFocus ? AccessibilityEventType::ACCESSIBILITY_FOCUSED
2594                                                           : AccessibilityEventType::ACCESSIBILITY_FOCUS_CLEARED);
2595     } else {
2596         uiNode->OnAccessibilityEventForVirtualNode(isAccessibilityFocus
2597                                                        ? AccessibilityEventType::ACCESSIBILITY_FOCUSED
2598                                                        : AccessibilityEventType::ACCESSIBILITY_FOCUS_CLEARED,
2599             accessibilityIdForVirtualNode);
2600     }
2601 }
2602 
OnAccessibilityFocusRectUpdate(RectT<int32_t> accessibilityFocusRect)2603 void RosenRenderContext::OnAccessibilityFocusRectUpdate(RectT<int32_t> accessibilityFocusRect)
2604 {
2605     auto isAccessibilityFocus = GetAccessibilityFocus().value_or(false);
2606     if (isAccessibilityFocus) {
2607         PaintAccessibilityFocus();
2608     }
2609 }
2610 
GetStatusByEffectTypeAndWindow()2611 bool RosenRenderContext::GetStatusByEffectTypeAndWindow()
2612 {
2613     auto pipeline = GetPipelineContext();
2614     CHECK_NULL_RETURN(pipeline, false);
2615     auto isWindowActivated = pipeline->IsWindowActivated();
2616     auto effectType = GetUseEffectType().value_or(EffectType::DEFAULT);
2617     return effectType == EffectType::WINDOW_EFFECT && !isWindowActivated;
2618 }
2619 
OnUseEffectUpdate(bool useEffect)2620 void RosenRenderContext::OnUseEffectUpdate(bool useEffect)
2621 {
2622     CHECK_NULL_VOID(rsNode_);
2623     if (GetStatusByEffectTypeAndWindow()) {
2624         rsNode_->SetUseEffect(false);
2625     } else {
2626         rsNode_->SetUseEffect(useEffect);
2627     }
2628 }
2629 
OnUseEffectTypeUpdate(EffectType effectType)2630 void RosenRenderContext::OnUseEffectTypeUpdate(EffectType effectType)
2631 {
2632     CHECK_NULL_VOID(rsNode_);
2633     auto effectTypeParam = static_cast<Rosen::UseEffectType>(effectType);
2634     rsNode_->SetUseEffectType(effectTypeParam);
2635     auto useEffect = GetUseEffect().value_or(false);
2636     OnUseEffectUpdate(useEffect);
2637 }
2638 
OnUseShadowBatchingUpdate(bool useShadowBatching)2639 void RosenRenderContext::OnUseShadowBatchingUpdate(bool useShadowBatching)
2640 {
2641     CHECK_NULL_VOID(rsNode_);
2642     rsNode_->SetUseShadowBatching(useShadowBatching);
2643 }
2644 
OnFreezeUpdate(bool isFreezed)2645 void RosenRenderContext::OnFreezeUpdate(bool isFreezed)
2646 {
2647     CHECK_NULL_VOID(rsNode_);
2648     rsNode_->SetFreeze(isFreezed);
2649 }
2650 
PaintAccessibilityFocus()2651 void RosenRenderContext::PaintAccessibilityFocus()
2652 {
2653     CHECK_NULL_VOID(rsNode_);
2654     Dimension focusPaddingVp = Dimension(0.0, DimensionUnit::VP);
2655     constexpr uint32_t ACCESSIBILITY_FOCUS_COLOR = 0xbf39b500;
2656     constexpr double ACCESSIBILITY_FOCUS_WIDTH = 4.0;
2657     constexpr float kAccessibilityMinSize = 1.0f;
2658     double lineWidth = ACCESSIBILITY_FOCUS_WIDTH * PipelineBase::GetCurrentDensity();
2659     Color paintColor(ACCESSIBILITY_FOCUS_COLOR);
2660     Dimension paintWidth(lineWidth, DimensionUnit::PX);
2661     const auto& bounds = rsNode_->GetStagingProperties().GetBounds();
2662     RoundRect frameRect;
2663     double noGreenBorderWidth = (bounds.w_ - (2 * lineWidth)) > 0 ? (bounds.w_ - (2 * lineWidth)) : 0;
2664     double noGreenBorderHeight = (bounds.z_ - (2 * lineWidth)) > 0 ? (bounds.z_ - (2 * lineWidth)) : 0;
2665     frameRect.SetRect(RectF(lineWidth, lineWidth, noGreenBorderHeight, noGreenBorderWidth));
2666     RectT<int32_t> localRect = GetAccessibilityFocusRect().value_or(RectT<int32_t>());
2667     if (localRect != RectT<int32_t>()) {
2668         RectT<int32_t> containerRect;
2669         containerRect.SetRect(0, 0, bounds.z_, bounds.w_);
2670         RectF globalRect = frameRect.GetRect();
2671         auto localRectWidth = localRect.Width() - 2 * lineWidth;
2672         auto localRectHeight = localRect.Height() - 2 * lineWidth;
2673         if (NonPositive(localRectWidth)) {
2674             localRectWidth = kAccessibilityMinSize;
2675         }
2676         if (NonPositive(localRectHeight)) {
2677             localRectHeight = kAccessibilityMinSize;
2678         }
2679         globalRect.SetRect(globalRect.GetX() + localRect.GetX(), globalRect.GetY() + localRect.GetY(),
2680             localRectWidth, localRectHeight);
2681         if (globalRect.IsEmpty()) {
2682             ClearAccessibilityFocus();
2683             return;
2684         }
2685         frameRect.SetRect(globalRect);
2686     }
2687     PaintFocusState(frameRect, focusPaddingVp, paintColor, paintWidth, { true, false });
2688 }
2689 
UpdateAccessibilityRoundRect()2690 void RosenRenderContext::UpdateAccessibilityRoundRect()
2691 {
2692     CHECK_NULL_VOID(accessibilityFocusStateModifier_);
2693     const constexpr double accessibilityFocusWidth = 4.0;
2694     double lineWidth = accessibilityFocusWidth * PipelineBase::GetCurrentDensity();
2695     Dimension paintWidth(lineWidth, DimensionUnit::PX);
2696     Dimension focusPaddingVp = Dimension(0.0, DimensionUnit::VP);
2697 
2698     auto paintWidthPx = static_cast<float>(paintWidth.ConvertToPx());
2699     auto borderPaddingPx = static_cast<float>(focusPaddingVp.ConvertToPx());
2700 
2701     auto node = GetHost();
2702     CHECK_NULL_VOID(node);
2703     if (node->GetTag() == V2::ACCESSIBILITY_FOCUS_PAINT_NODE_TAG) {
2704         auto paintNodePattern = AceType::DynamicCast<AccessibilityFocusPaintNodePattern>(node->GetPattern());
2705         CHECK_NULL_VOID(paintNodePattern);
2706         auto focusNode = paintNodePattern->GetFocusNode().Upgrade();
2707         CHECK_NULL_VOID(focusNode);
2708         auto pipeline = focusNode->GetContextRefPtr();
2709         CHECK_NULL_VOID(pipeline);
2710         auto rect = pipeline->GetRootRect();
2711         std::shared_ptr<Rosen::RectF> drawRect =
2712             std::make_shared<Rosen::RectF>(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
2713         UpdateDrawRegion(DRAW_REGION_ACCESSIBILITY_FOCUS_MODIFIER_INDEX, drawRect);
2714     }
2715     auto nodeWidth = node->GetGeometryNode()->GetFrameSize().Width();
2716     auto nodeHeight = node->GetGeometryNode()->GetFrameSize().Height();
2717 
2718     double noGreenBorderWidth = GreatOrEqual(nodeWidth - (2 * lineWidth), 0.0) ? (nodeWidth - (2 * lineWidth)) : 0;
2719     double noGreenBorderHeight = GreatOrEqual(nodeHeight - (2 * lineWidth), 0.0) ? (nodeHeight - (2 * lineWidth)) : 0;
2720 
2721     RoundRect frameRect;
2722     std::shared_ptr<FocusStateModifier> modifier;
2723     modifier = accessibilityFocusStateModifier_;
2724     frameRect.SetRect(RectF(lineWidth - borderPaddingPx - paintWidthPx / 2,
2725         lineWidth - borderPaddingPx - paintWidthPx / 2, noGreenBorderWidth + 2 * borderPaddingPx + paintWidthPx,
2726         noGreenBorderHeight + 2 * borderPaddingPx + paintWidthPx)); // 2: framenode to graphic specification
2727     modifier->SetRoundRect(frameRect, paintWidthPx);
2728 }
ClearAccessibilityFocus()2729 void RosenRenderContext::ClearAccessibilityFocus()
2730 {
2731     CHECK_NULL_VOID(rsNode_);
2732     CHECK_NULL_VOID(accessibilityFocusStateModifier_);
2733     rsNode_->RemoveModifier(accessibilityFocusStateModifier_);
2734     RequestNextFrame();
2735 }
2736 
BdImagePaintTask(RSCanvas & canvas)2737 void RosenRenderContext::BdImagePaintTask(RSCanvas& canvas)
2738 {
2739     CHECK_NULL_VOID(GetBorderImage());
2740     auto paintRect = GetPaintRectWithoutTransform();
2741     if (NearZero(paintRect.Width()) || NearZero(paintRect.Height())) {
2742         return;
2743     }
2744 
2745     auto host = GetHost();
2746     CHECK_NULL_VOID(host);
2747     auto layoutProps = host->GetLayoutProperty();
2748     CHECK_NULL_VOID(layoutProps);
2749     const auto& widthProp = layoutProps->GetBorderWidthProperty();
2750 
2751     auto pipeline = host->GetContextRefPtr();
2752     CHECK_NULL_VOID(pipeline);
2753     auto dipScale = pipeline->GetDipScale();
2754     auto lpxScale = pipeline->GetLogicScale();
2755 
2756     CHECK_NULL_VOID(bdImage_);
2757     std::shared_ptr<RSImage> image;
2758     if (InstanceOf<DrawingImage>(bdImage_)) {
2759         image = DynamicCast<DrawingImage>(bdImage_)->GetImage();
2760     } else if (InstanceOf<PixelMapImage>(bdImage_)) {
2761         auto pixmap = DynamicCast<PixelMapImage>(bdImage_)->GetPixelMap();
2762         CHECK_NULL_VOID(pixmap);
2763         image = DrawingImage::MakeRSImageFromPixmap(pixmap);
2764     } else {
2765         return;
2766     }
2767     CHECK_NULL_VOID(image);
2768     BorderImagePainter borderImagePainter(
2769         *GetBdImage(), widthProp, paintRect.GetSize(), *image, { dipScale, lpxScale });
2770     if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_FOURTEEN)) {
2771         auto rect = borderImagePainter.GetDrawRect(OffsetF(0.0, 0.0));
2772         std::shared_ptr<Rosen::RectF> drawRect =
2773             std::make_shared<Rosen::RectF>(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
2774         UpdateDrawRegion(DRAW_REGION_FOREGROUND_MODIFIER_INDEX, drawRect);
2775     }
2776     borderImagePainter.PaintBorderImage(OffsetF(0.0, 0.0), canvas);
2777 }
2778 
PaintBorderImage()2779 void RosenRenderContext::PaintBorderImage()
2780 {
2781     CHECK_NULL_VOID(rsNode_);
2782 
2783     auto paintTask = [weak = WeakClaim(this)](RSCanvas& canvas) {
2784         auto ctx = weak.Upgrade();
2785         CHECK_NULL_VOID(ctx);
2786         ctx->BdImagePaintTask(canvas);
2787     };
2788 
2789     if (!borderImageModifier_) {
2790         borderImageModifier_ = std::make_shared<BorderImageModifier>();
2791         rsNode_->AddModifier(borderImageModifier_);
2792     }
2793     borderImageModifier_->SetPaintTask(std::move(paintTask));
2794     borderImageModifier_->Modify();
2795 }
2796 
CreateBorderImageDataReadyCallback()2797 DataReadyNotifyTask RosenRenderContext::CreateBorderImageDataReadyCallback()
2798 {
2799     return [weak = WeakClaim(this)](const ImageSourceInfo& sourceInfo) {
2800         auto rosenRenderContext = weak.Upgrade();
2801         CHECK_NULL_VOID(rosenRenderContext);
2802         auto imageSourceInfo = rosenRenderContext->GetBorderImageSource().value_or(ImageSourceInfo(""));
2803         if (imageSourceInfo != sourceInfo) {
2804             return;
2805         }
2806         rosenRenderContext->bdImageLoadingCtx_->MakeCanvasImage(SizeF(), true, ImageFit::NONE);
2807     };
2808 }
2809 
CreateBorderImageLoadSuccessCallback()2810 LoadSuccessNotifyTask RosenRenderContext::CreateBorderImageLoadSuccessCallback()
2811 {
2812     return [weak = WeakClaim(this)](const ImageSourceInfo& sourceInfo) {
2813         auto ctx = weak.Upgrade();
2814         CHECK_NULL_VOID(ctx);
2815         auto imageSourceInfo = ctx->GetBorderImageSource().value_or(ImageSourceInfo(""));
2816         if (imageSourceInfo != sourceInfo) {
2817             return;
2818         }
2819         ctx->bdImage_ = ctx->bdImageLoadingCtx_->MoveCanvasImage();
2820         CHECK_NULL_VOID(ctx->bdImage_);
2821         if (ctx->GetHost()->GetGeometryNode()->GetFrameSize().IsPositive()) {
2822             ctx->PaintBorderImage();
2823             ctx->RequestNextFrame();
2824         }
2825     };
2826 }
2827 
OnBackgroundAlignUpdate(const Alignment & align)2828 void RosenRenderContext::OnBackgroundAlignUpdate(const Alignment& align)
2829 {
2830     CHECK_NULL_VOID(rsNode_);
2831     if (!backgroundModifier_) {
2832         backgroundModifier_ = std::make_shared<BackgroundModifier>();
2833         rsNode_->AddModifier(backgroundModifier_);
2834     }
2835     backgroundModifier_->SetAlign(align);
2836     backgroundModifier_->Modify();
2837     RequestNextFrame();
2838 }
2839 
OnBackgroundPixelMapUpdate(const RefPtr<PixelMap> & pixelMap)2840 void RosenRenderContext::OnBackgroundPixelMapUpdate(const RefPtr<PixelMap>& pixelMap)
2841 {
2842     CHECK_NULL_VOID(rsNode_);
2843     if (!backgroundModifier_) {
2844         backgroundModifier_ = std::make_shared<BackgroundModifier>();
2845         rsNode_->AddModifier(backgroundModifier_);
2846     }
2847     auto node = GetHost();
2848     auto nodeWidth = node->GetGeometryNode()->GetFrameSize().Width();
2849     auto nodeHeight = node->GetGeometryNode()->GetFrameSize().Height();
2850     backgroundModifier_->SetInitialNodeSize(nodeWidth, nodeHeight);
2851     backgroundModifier_->SetPixelMap(pixelMap);
2852     backgroundModifier_->SetHostNode(node);
2853     backgroundModifier_->Modify();
2854     RequestNextFrame();
2855 }
2856 
CreateBackgroundPixelMap(const RefPtr<FrameNode> & customNode)2857 void RosenRenderContext::CreateBackgroundPixelMap(const RefPtr<FrameNode>& customNode)
2858 {
2859     NG::ComponentSnapshot::JsCallback callback = [weak = WeakPtr(GetHost()), containerId = Container::CurrentId()](
2860                                                      std::shared_ptr<Media::PixelMap> pixmap, int32_t errCode,
2861                                                      std::function<void()> finishCallback) {
2862         CHECK_NULL_VOID(pixmap);
2863         auto frameNode = weak.Upgrade();
2864         CHECK_NULL_VOID(frameNode);
2865         ContainerScope scope(containerId);
2866         std::shared_ptr<Media::PixelMap> pmap = std::move(pixmap);
2867         auto pixelmap = PixelMap::CreatePixelMap(&pmap);
2868         auto task = [pixelmap, frameNode]() {
2869             auto context = frameNode->GetRenderContext();
2870             if (context) {
2871                 context->UpdateBackgroundPixelMap(pixelmap);
2872                 context->RequestNextFrame();
2873             }
2874         };
2875         auto taskExecutor = Container::CurrentTaskExecutor();
2876         CHECK_NULL_VOID(taskExecutor);
2877         taskExecutor->PostTask(task, TaskExecutor::TaskType::UI, "ArkUICreateBackgroundPixelMap");
2878     };
2879     auto firstCallback = callback;
2880     SnapshotParam firstParam;
2881     firstParam.delay = 0;
2882     firstParam.checkImageStatus = true;
2883     firstParam.options.waitUntilRenderFinished = true;
2884     NG::ComponentSnapshot::Create(customNode, std::move(firstCallback), false, firstParam, true);
2885 
2886     SnapshotParam param;
2887     NG::ComponentSnapshot::Create(customNode, std::move(callback), false, param, false);
2888 }
2889 
OnBorderImageUpdate(const RefPtr<BorderImage> &)2890 void RosenRenderContext::OnBorderImageUpdate(const RefPtr<BorderImage>& /*borderImage*/)
2891 {
2892     CHECK_NULL_VOID(rsNode_);
2893     if (bdImageLoadingCtx_ && bdImage_) {
2894         PaintBorderImage();
2895         RequestNextFrame();
2896     }
2897 }
2898 
OnBorderImageSourceUpdate(const ImageSourceInfo & borderImageSourceInfo)2899 void RosenRenderContext::OnBorderImageSourceUpdate(const ImageSourceInfo& borderImageSourceInfo)
2900 {
2901     CHECK_NULL_VOID(rsNode_);
2902     if (!bdImageLoadingCtx_ || borderImageSourceInfo != bdImageLoadingCtx_->GetSourceInfo()) {
2903         LoadNotifier bgLoadNotifier(
2904             CreateBorderImageDataReadyCallback(), CreateBorderImageLoadSuccessCallback(), nullptr);
2905         bdImageLoadingCtx_ = AceType::MakeRefPtr<ImageLoadingContext>(borderImageSourceInfo, std::move(bgLoadNotifier));
2906         CHECK_NULL_VOID(bdImageLoadingCtx_);
2907         bdImageLoadingCtx_->LoadImageData();
2908     }
2909     RequestNextFrame();
2910 }
2911 
OnBorderImageGradientUpdate(const Gradient & gradient)2912 void RosenRenderContext::OnBorderImageGradientUpdate(const Gradient& gradient)
2913 {
2914     CHECK_NULL_VOID(rsNode_);
2915     if (!gradient.IsValid()) {
2916         return;
2917     }
2918     if (GetHost()->GetGeometryNode()->GetFrameSize().IsPositive()) {
2919         PaintBorderImageGradient();
2920     }
2921     RequestNextFrame();
2922 }
2923 
PaintBorderImageGradient()2924 void RosenRenderContext::PaintBorderImageGradient()
2925 {
2926     CHECK_NULL_VOID(rsNode_);
2927     CHECK_NULL_VOID(GetBorderImage());
2928     CHECK_NULL_VOID(GetBorderImageGradient());
2929     auto gradient = GetBorderImageGradient().value();
2930     if (!gradient.IsValid()) {
2931         return;
2932     }
2933     auto paintSize = GetPaintRectWithoutTransform().GetSize();
2934     if (NearZero(paintSize.Width()) || NearZero(paintSize.Height())) {
2935         return;
2936     }
2937     auto layoutProperty = GetHost()->GetLayoutProperty();
2938     CHECK_NULL_VOID(layoutProperty);
2939 
2940     auto borderImageProperty = *GetBdImage();
2941     auto&& borderWidthProperty = layoutProperty->GetBorderWidthProperty();
2942     auto paintTask = [weak = WeakClaim(this), paintSize, borderImageProperty, &borderWidthProperty, gradient](
2943                          RSCanvas& rsCanvas) mutable {
2944         auto rsImage = DrawingDecorationPainter::CreateBorderImageGradient(gradient, paintSize);
2945         auto pattern = weak.Upgrade();
2946         CHECK_NULL_VOID(pattern);
2947         auto host = pattern->GetHost();
2948         CHECK_NULL_VOID(host);
2949         auto pipeline = host->GetContext();
2950         CHECK_NULL_VOID(pipeline);
2951         BorderImagePainter borderImagePainter(borderImageProperty, borderWidthProperty, paintSize, rsImage,
2952             { pipeline->GetDipScale(), pipeline->GetLogicScale() });
2953         borderImagePainter.PaintBorderImage(OffsetF(0.0, 0.0), rsCanvas);
2954     };
2955 
2956     if (!borderImageModifier_) {
2957         borderImageModifier_ = std::make_shared<BorderImageModifier>();
2958         rsNode_->AddModifier(borderImageModifier_);
2959     }
2960     borderImageModifier_->SetPaintTask(std::move(paintTask));
2961     borderImageModifier_->Modify();
2962 }
2963 
OnModifyDone()2964 void RosenRenderContext::OnModifyDone()
2965 {
2966     if (HasClickEffectLevel()) {
2967         InitEventClickEffect();
2968     }
2969 }
2970 
GetPropertyOfPosition()2971 RectF RosenRenderContext::GetPropertyOfPosition()
2972 {
2973     return AdjustPaintRect();
2974 }
2975 
AdjustPaintRect()2976 RectF RosenRenderContext::AdjustPaintRect()
2977 {
2978     RectF rect;
2979     auto frameNode = GetHost();
2980     CHECK_NULL_RETURN(frameNode, rect);
2981     CHECK_NULL_RETURN(rsNode_, rect);
2982     const auto& geometryNode = frameNode->GetGeometryNode();
2983     rect = geometryNode->GetFrameRect();
2984     if (Container::LessThanAPIVersion(PlatformVersion::VERSION_TEN)) {
2985         if (!rect.GetSize().IsPositive()) {
2986             geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
2987             return rect;
2988         }
2989     } else {
2990         if (!rect.GetSize().IsPositive() && !frameNode->IsLayoutComplete()) {
2991             geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
2992             return rect;
2993         }
2994     }
2995     bool hasPosition = (HasPosition() || HasPositionEdges()) && IsUsingPosition(frameNode);
2996     bool hasOffset = HasOffset() || HasOffsetEdges();
2997     if (!HasAnchor() && !hasOffset && !hasPosition) {
2998         geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
2999         return rect;
3000     }
3001     auto percentReference = GetPercentReference(frameNode);
3002     auto widthPercentReference = percentReference.Width();
3003     auto heightPercentReference = percentReference.Height();
3004     auto anchor = GetAnchorValue({});
3005     auto anchorWidthReference = rect.Width();
3006     auto anchorHeightReference = rect.Height();
3007     auto anchorX = ConvertToPx(anchor.GetX(), ScaleProperty::CreateScaleProperty(), anchorWidthReference);
3008     auto anchorY = ConvertToPx(anchor.GetY(), ScaleProperty::CreateScaleProperty(), anchorHeightReference);
3009     Dimension resultX;
3010     Dimension resultY;
3011     Dimension parentPaddingLeft;
3012     Dimension parentPaddingTop;
3013     GetPaddingOfFirstFrameNodeParent(parentPaddingLeft, parentPaddingTop);
3014     // Position properties take precedence over offset locations.
3015     if (HasPosition() && IsUsingPosition(frameNode)) {
3016         CombineMarginAndPosition(
3017             resultX, resultY, parentPaddingLeft, parentPaddingTop, widthPercentReference, heightPercentReference);
3018         rect.SetLeft(resultX.ConvertToPx() - anchorX.value_or(0));
3019         rect.SetTop(resultY.ConvertToPx() - anchorY.value_or(0));
3020         geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
3021         return rect;
3022     }
3023     if (HasPositionEdges() && IsUsingPosition(frameNode)) {
3024         auto positionEdges = GetPositionEdgesValue(EdgesParam {});
3025         OffsetF rectOffset =
3026             GetRectOffsetWithPositionEdges(positionEdges, widthPercentReference, heightPercentReference);
3027         rect.SetLeft(rectOffset.GetX() - anchorX.value_or(0));
3028         rect.SetTop(rectOffset.GetY() - anchorY.value_or(0));
3029         geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
3030         return rect;
3031     }
3032     if (HasOffset()) {
3033         auto offset = GetOffsetValue({});
3034         if (PipelineBase::GetCurrentContext() &&
3035             PipelineBase::GetCurrentContext()->GetMinPlatformVersion() < PLATFORM_VERSION_TEN) {
3036             offset += OffsetT<Dimension>(parentPaddingLeft, parentPaddingTop);
3037         }
3038         auto offsetX = ConvertToPx(offset.GetX(), ScaleProperty::CreateScaleProperty(), widthPercentReference);
3039         auto offsetY = ConvertToPx(offset.GetY(), ScaleProperty::CreateScaleProperty(), heightPercentReference);
3040         rect.SetLeft(rect.GetX() + offsetX.value_or(0) - anchorX.value_or(0));
3041         rect.SetTop(rect.GetY() + offsetY.value_or(0) - anchorY.value_or(0));
3042         geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
3043         return rect;
3044     }
3045     if (HasOffsetEdges()) {
3046         auto offsetEdges = GetOffsetEdgesValue(EdgesParam {});
3047         OffsetF rectOffset = GetRectOffsetWithOffsetEdges(offsetEdges, widthPercentReference, heightPercentReference);
3048         rect.SetLeft(rect.GetX() + rectOffset.GetX() - anchorX.value_or(0));
3049         rect.SetTop(rect.GetY() + rectOffset.GetY() - anchorY.value_or(0));
3050         geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
3051         return rect;
3052     }
3053     rect.SetLeft(rect.GetX() - anchorX.value_or(0));
3054     rect.SetTop(rect.GetY() - anchorY.value_or(0));
3055     geometryNode->SetPixelGridRoundOffset(rect.GetOffset());
3056     return rect;
3057 }
3058 
RoundValueToPixelGrid(float value)3059 float RosenRenderContext::RoundValueToPixelGrid(float value)
3060 {
3061     float fractials = fmod(value, 1.0f);
3062     if (fractials < 0.0f) {
3063         ++fractials;
3064     }
3065     if (NearEqual(fractials, 1.0f) || GreatOrEqual(fractials, 0.75f)) {
3066         return (value - fractials + 1.0f);
3067     } else if (NearEqual(fractials, 0.0f) || !GreatOrEqual(fractials, 0.25f)) {
3068         return (value - fractials);
3069     } else {
3070         return (value - fractials + 0.5f);
3071     }
3072 }
3073 
GetRectOffsetWithOffsetEdges(const EdgesParam & offsetEdges,float widthPercentReference,float heightPercentReference)3074 OffsetF RosenRenderContext::GetRectOffsetWithOffsetEdges(
3075     const EdgesParam& offsetEdges, float widthPercentReference, float heightPercentReference)
3076 {
3077     OffsetF rectOffset;
3078     if (offsetEdges.top.has_value()) {
3079         rectOffset.SetY(
3080             ConvertToPx(offsetEdges.top.value(), ScaleProperty::CreateScaleProperty(), heightPercentReference)
3081                 .value_or(0));
3082     }
3083     if (offsetEdges.left.has_value()) {
3084         rectOffset.SetX(
3085             ConvertToPx(offsetEdges.left.value(), ScaleProperty::CreateScaleProperty(), widthPercentReference)
3086                 .value_or(0));
3087     }
3088     if (!offsetEdges.top.has_value() && offsetEdges.bottom.has_value()) {
3089         rectOffset.SetY(
3090             -ConvertToPx(offsetEdges.bottom.value(), ScaleProperty::CreateScaleProperty(), heightPercentReference)
3091                  .value_or(0));
3092     }
3093     if (!offsetEdges.left.has_value() && offsetEdges.right.has_value()) {
3094         rectOffset.SetX(
3095             -ConvertToPx(offsetEdges.right.value(), ScaleProperty::CreateScaleProperty(), widthPercentReference)
3096                  .value_or(0));
3097     }
3098     return rectOffset;
3099 }
3100 
GetRectOffsetWithPositionEdges(const EdgesParam & positionEdges,float widthPercentReference,float heightPercentReference)3101 OffsetF RosenRenderContext::GetRectOffsetWithPositionEdges(
3102     const EdgesParam& positionEdges, float widthPercentReference, float heightPercentReference)
3103 {
3104     float rectTop = 0.0f;
3105     float rectLeft = 0.0f;
3106 
3107     auto frameNode = GetHost();
3108     CHECK_NULL_RETURN(frameNode, OffsetF {});
3109     auto layoutProperty = frameNode->GetLayoutProperty();
3110     CHECK_NULL_RETURN(layoutProperty, OffsetF {});
3111     auto& marginOri = layoutProperty->GetMarginProperty();
3112     std::unique_ptr<MarginProperty> margin(
3113         marginOri ? std::make_unique<MarginProperty>(*marginOri) : std::make_unique<MarginProperty>());
3114 
3115     auto parentNode = frameNode->GetAncestorNodeOfFrame(true);
3116     CHECK_NULL_RETURN(parentNode, OffsetF {});
3117     auto parentLayoutProperty = parentNode->GetLayoutProperty();
3118     CHECK_NULL_RETURN(parentLayoutProperty, OffsetF {});
3119     auto& parentPaddingOri = parentLayoutProperty->GetPaddingProperty();
3120     std::unique_ptr<PaddingProperty> parentPadding(
3121         parentPaddingOri ? std::make_unique<PaddingProperty>(*parentPaddingOri) : std::make_unique<PaddingProperty>());
3122 
3123     auto parenPercentRef = GetPercentReference(parentNode);
3124     float parentWidthRef = parenPercentRef.Width();
3125     float parentHeightRef = parenPercentRef.Height();
3126 
3127     SizeF selfSize = frameNode->GetGeometryNode()->GetFrameSize();
3128     float selfWidth = selfSize.Width();
3129     float selfHeight = selfSize.Height();
3130     SizeF parentSize = parentNode->GetGeometryNode()->GetFrameSize();
3131     float parentWidth = parentSize.Width();
3132     float parentHeight = parentSize.Height();
3133 
3134     if (positionEdges.top.has_value()) {
3135         rectTop = ConvertToPx(parentPadding->top.value_or(CalcLength(Dimension(0))).GetDimension(),
3136                       ScaleProperty::CreateScaleProperty(), parentHeightRef)
3137                       .value_or(0) +
3138                   ConvertToPx(margin->top.value_or(CalcLength(Dimension(0))).GetDimension(),
3139                       ScaleProperty::CreateScaleProperty(), heightPercentReference)
3140                       .value_or(0) +
3141                   ConvertToPx(positionEdges.top.value(), ScaleProperty::CreateScaleProperty(), heightPercentReference)
3142                       .value_or(0);
3143     }
3144     if (positionEdges.left.has_value()) {
3145         rectLeft = ConvertToPx(parentPadding->left.value_or(CalcLength(Dimension(0))).GetDimension(),
3146                        ScaleProperty::CreateScaleProperty(), parentWidthRef)
3147                        .value_or(0) +
3148                    ConvertToPx(margin->left.value_or(CalcLength(Dimension(0))).GetDimension(),
3149                        ScaleProperty::CreateScaleProperty(), widthPercentReference)
3150                        .value_or(0) +
3151                    ConvertToPx(positionEdges.left.value(), ScaleProperty::CreateScaleProperty(), widthPercentReference)
3152                        .value_or(0);
3153     }
3154     if (!positionEdges.top.has_value() && positionEdges.bottom.has_value()) {
3155         rectTop =
3156             parentHeight - selfHeight -
3157             ConvertToPx(parentPadding->bottom.value_or(CalcLength(Dimension(0))).GetDimension(),
3158                 ScaleProperty::CreateScaleProperty(), parentHeightRef)
3159                 .value_or(0) -
3160             ConvertToPx(margin->bottom.value_or(CalcLength(Dimension(0))).GetDimension(),
3161                 ScaleProperty::CreateScaleProperty(), heightPercentReference)
3162                 .value_or(0) -
3163             ConvertToPx(positionEdges.bottom.value(), ScaleProperty::CreateScaleProperty(), heightPercentReference)
3164                 .value_or(0);
3165     }
3166     if (!positionEdges.left.has_value() && positionEdges.right.has_value()) {
3167         rectLeft = parentWidth - selfWidth -
3168                    ConvertToPx(parentPadding->right.value_or(CalcLength(Dimension(0))).GetDimension(),
3169                        ScaleProperty::CreateScaleProperty(), parentWidthRef)
3170                        .value_or(0) -
3171                    ConvertToPx(margin->right.value_or(CalcLength(Dimension(0))).GetDimension(),
3172                        ScaleProperty::CreateScaleProperty(), widthPercentReference)
3173                        .value_or(0) -
3174                    ConvertToPx(positionEdges.right.value(), ScaleProperty::CreateScaleProperty(), widthPercentReference)
3175                        .value_or(0);
3176     }
3177     return OffsetF(rectLeft, rectTop);
3178 }
3179 
RoundValueToPixelGrid(float value,bool isRound,bool forceCeil,bool forceFloor)3180 float RosenRenderContext::RoundValueToPixelGrid(float value, bool isRound, bool forceCeil, bool forceFloor)
3181 {
3182     float fractials = fmod(value, 1.0f);
3183     if (fractials < 0.0f) {
3184         ++fractials;
3185     }
3186     if (forceCeil) {
3187         return (value - fractials + 1.0f);
3188     } else if (forceFloor) {
3189         return (value - fractials);
3190     } else if (isRound) {
3191         if (NearEqual(fractials, 1.0f) || GreatOrEqual(fractials, 0.75f)) {
3192             return (value - fractials + 1.0f);
3193         } else if (NearEqual(fractials, 0.0f) || !GreatOrEqual(fractials, 0.25f)) {
3194             return (value - fractials);
3195         } else {
3196             return (value - fractials + 0.5f);
3197         }
3198     }
3199     return value;
3200 }
3201 
OnePixelValueRounding(float value)3202 float RosenRenderContext::OnePixelValueRounding(float value)
3203 {
3204     float fractials = fmod(value, 1.0f);
3205     if (fractials < 0.0f) {
3206         ++fractials;
3207     }
3208     if (NearEqual(fractials, 1.0f) || GreatOrEqual(fractials, 0.5f)) {
3209         return (value - fractials + 1.0f);
3210     } else {
3211         return (value - fractials);
3212     }
3213 }
3214 
OnePixelValueRounding(float value,bool isRound,bool forceCeil,bool forceFloor)3215 float RosenRenderContext::OnePixelValueRounding(float value, bool isRound, bool forceCeil, bool forceFloor)
3216 {
3217     float fractials = fmod(value, 1.0f);
3218     if (fractials < 0.0f) {
3219         ++fractials;
3220     }
3221     if (forceCeil) {
3222         return (value - fractials + 1.0f);
3223     } else if (forceFloor) {
3224         return (value - fractials);
3225     } else if (isRound) {
3226         if (NearEqual(fractials, 1.0f) || GreatOrEqual(fractials, 0.5f)) {
3227             return (value - fractials + 1.0f);
3228         } else {
3229             return (value - fractials);
3230         }
3231     }
3232     return value;
3233 }
3234 
RoundToPixelGrid()3235 void RosenRenderContext::RoundToPixelGrid()
3236 {
3237     auto frameNode = GetHost();
3238     CHECK_NULL_VOID(frameNode);
3239     auto geometryNode = frameNode->GetGeometryNode();
3240     float relativeLeft = geometryNode->GetPixelGridRoundOffset().GetX();
3241     float relativeTop = geometryNode->GetPixelGridRoundOffset().GetY();
3242     float nodeWidth = geometryNode->GetFrameSize().Width();
3243     float nodeHeight = geometryNode->GetFrameSize().Height();
3244     float absoluteRight = relativeLeft + nodeWidth;
3245     float absoluteBottom = relativeTop + nodeHeight;
3246     // round node
3247     float nodeLeftI = RoundValueToPixelGrid(relativeLeft);
3248     float nodeTopI = RoundValueToPixelGrid(relativeTop);
3249     geometryNode->SetPixelGridRoundOffset(OffsetF(nodeLeftI, nodeTopI));
3250     float nodeWidthI = RoundValueToPixelGrid(absoluteRight) - nodeLeftI;
3251     float nodeHeightI = RoundValueToPixelGrid(absoluteBottom) - nodeTopI;
3252     geometryNode->SetPixelGridRoundSize(SizeF(nodeWidthI, nodeHeightI));
3253     if (borderWidth_ != Rosen::Vector4f(0.0f, 0.0f, 0.0f, 0.0f)) {
3254         // round inner
3255         float innerLeft = relativeLeft + borderWidth_[0];
3256         float innerRight = relativeLeft + nodeWidth - borderWidth_[2];
3257         float innerTop = relativeTop + borderWidth_[1];
3258         float innerBottom = relativeTop + nodeHeight - borderWidth_[3];
3259         float innerWidthI = RoundValueToPixelGrid(innerRight) - RoundValueToPixelGrid(innerLeft);
3260         float innerHeightI = RoundValueToPixelGrid(innerBottom) - RoundValueToPixelGrid(innerTop);
3261         // update border
3262         float borderLeftI = RoundValueToPixelGrid(borderWidth_[0]);
3263         float borderTopI = RoundValueToPixelGrid(borderWidth_[1]);
3264         float borderRightI = nodeWidthI - innerWidthI - borderLeftI;
3265         float borderBottomI = nodeHeightI - innerHeightI - borderTopI;
3266         BorderWidthPropertyF borderWidthPropertyF;
3267         borderWidthPropertyF.leftDimen = borderLeftI;
3268         borderWidthPropertyF.topDimen = borderTopI;
3269         borderWidthPropertyF.rightDimen = borderRightI;
3270         borderWidthPropertyF.bottomDimen = borderBottomI;
3271         UpdateBorderWidthF(borderWidthPropertyF);
3272     }
3273 }
3274 
RoundToPixelGrid(bool isRound,uint16_t flag)3275 void RosenRenderContext::RoundToPixelGrid(bool isRound, uint16_t flag)
3276 {
3277     CHECK_NULL_VOID(rsNode_);
3278     auto frameNode = GetHost();
3279     CHECK_NULL_VOID(frameNode);
3280     auto geometryNode = frameNode->GetGeometryNode();
3281     float relativeLeft = geometryNode->GetPixelGridRoundOffset().GetX();
3282     float relativeTop = geometryNode->GetPixelGridRoundOffset().GetY();
3283     float nodeWidth = geometryNode->GetFrameSize().Width();
3284     float nodeHeight = geometryNode->GetFrameSize().Height();
3285     float absoluteRight = relativeLeft + nodeWidth;
3286     float absoluteBottom = relativeTop + nodeHeight;
3287     bool ceilLeft = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_START);
3288     bool floorLeft = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_START);
3289     bool ceilTop = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_TOP);
3290     bool floorTop = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_TOP);
3291     bool ceilRight = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_END);
3292     bool floorRight = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_END);
3293     bool ceilBottom = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_BOTTOM);
3294     bool floorBottom = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_BOTTOM);
3295     // round node
3296     float nodeLeftI = RoundValueToPixelGrid(relativeLeft, isRound, ceilLeft, floorLeft);
3297     float nodeTopI = RoundValueToPixelGrid(relativeTop, isRound, ceilTop, floorTop);
3298     geometryNode->SetPixelGridRoundOffset(OffsetF(nodeLeftI, nodeTopI));
3299     float nodeWidthI = RoundValueToPixelGrid(absoluteRight, isRound, ceilRight, floorRight) - nodeLeftI;
3300     float nodeHeightI = RoundValueToPixelGrid(absoluteBottom, isRound, ceilBottom, floorBottom) - nodeTopI;
3301     geometryNode->SetPixelGridRoundSize(SizeF(nodeWidthI, nodeHeightI));
3302     if (borderWidth_ != Rosen::Vector4f(0.0f, 0.0f, 0.0f, 0.0f)) {
3303         // round inner
3304         float innerLeft = relativeLeft + borderWidth_[0];
3305         float innerRight = relativeLeft + nodeWidth - borderWidth_[2];
3306         float innerTop = relativeTop + borderWidth_[1];
3307         float innerBottom = relativeTop + nodeHeight - borderWidth_[3];
3308         float innerWidthI = RoundValueToPixelGrid(innerRight, isRound, ceilRight, floorRight) -
3309                             RoundValueToPixelGrid(innerLeft, isRound, ceilLeft, floorLeft);
3310         float innerHeightI = RoundValueToPixelGrid(innerBottom, isRound, ceilBottom, floorBottom) -
3311                              RoundValueToPixelGrid(innerTop, isRound, ceilTop, floorTop);
3312         // update border
3313         float borderLeftI = RoundValueToPixelGrid(borderWidth_[0], isRound, ceilLeft, floorLeft);
3314         float borderTopI = RoundValueToPixelGrid(borderWidth_[1], isRound, ceilTop, floorTop);
3315         float borderRightI = nodeWidthI - innerWidthI - borderLeftI;
3316         float borderBottomI = nodeHeightI - innerHeightI - borderTopI;
3317         BorderWidthPropertyF borderWidthPropertyF;
3318         borderWidthPropertyF.leftDimen = borderLeftI;
3319         borderWidthPropertyF.topDimen = borderTopI;
3320         borderWidthPropertyF.rightDimen = borderRightI;
3321         borderWidthPropertyF.bottomDimen = borderBottomI;
3322         UpdateBorderWidthF(borderWidthPropertyF);
3323     }
3324 }
3325 
OnePixelRounding()3326 void RosenRenderContext::OnePixelRounding()
3327 {
3328     auto frameNode = GetHost();
3329     CHECK_NULL_VOID(frameNode);
3330     auto geometryNode = frameNode->GetGeometryNode();
3331     float relativeLeft = geometryNode->GetPixelGridRoundOffset().GetX();
3332     float relativeTop = geometryNode->GetPixelGridRoundOffset().GetY();
3333     float nodeWidth = geometryNode->GetFrameSize().Width();
3334     float nodeHeight = geometryNode->GetFrameSize().Height();
3335     float roundToPixelErrorX = 0.0f;
3336     float roundToPixelErrorY = 0.0f;
3337     float absoluteRight = relativeLeft + nodeWidth;
3338     float absoluteBottom = relativeTop + nodeHeight;
3339 
3340     float nodeLeftI = OnePixelValueRounding(relativeLeft);
3341     float nodeTopI = OnePixelValueRounding(relativeTop);
3342     roundToPixelErrorX += nodeLeftI - relativeLeft;
3343     roundToPixelErrorY += nodeTopI - relativeTop;
3344     geometryNode->SetPixelGridRoundOffset(OffsetF(nodeLeftI, nodeTopI));
3345 
3346     float nodeWidthI = OnePixelValueRounding(absoluteRight) - nodeLeftI;
3347     float nodeWidthTemp = OnePixelValueRounding(nodeWidth);
3348     roundToPixelErrorX += nodeWidthI - nodeWidth;
3349     if (roundToPixelErrorX > 0.5f) {
3350         nodeWidthI -= 1.0f;
3351         roundToPixelErrorX -= 1.0f;
3352     }
3353     if (roundToPixelErrorX < -0.5f) {
3354         nodeWidthI += 1.0f;
3355         roundToPixelErrorX += 1.0f;
3356     }
3357     if (nodeWidthI < nodeWidthTemp) {
3358         roundToPixelErrorX += nodeWidthTemp - nodeWidthI;
3359         nodeWidthI = nodeWidthTemp;
3360     }
3361 
3362     float nodeHeightI = OnePixelValueRounding(absoluteBottom) - nodeTopI;
3363     float nodeHeightTemp = OnePixelValueRounding(nodeHeight);
3364     roundToPixelErrorY += nodeHeightI - nodeHeight;
3365     if (roundToPixelErrorY > 0.5f) {
3366         nodeHeightI -= 1.0f;
3367         roundToPixelErrorY -= 1.0f;
3368     }
3369     if (roundToPixelErrorY < -0.5f) {
3370         nodeHeightI += 1.0f;
3371         roundToPixelErrorY += 1.0f;
3372     }
3373     if (nodeHeightI < nodeHeightTemp) {
3374         roundToPixelErrorY += nodeHeightTemp - nodeHeightI;
3375         nodeHeightI = nodeHeightTemp;
3376     }
3377     geometryNode->SetPixelGridRoundSize(SizeF(nodeWidthI, nodeHeightI));
3378 }
3379 
OnePixelRounding(uint16_t flag)3380 void RosenRenderContext::OnePixelRounding(uint16_t flag)
3381 {
3382     auto frameNode = GetHost();
3383     CHECK_NULL_VOID(frameNode);
3384     auto geometryNode = frameNode->GetGeometryNode();
3385     float relativeLeft = geometryNode->GetPixelGridRoundOffset().GetX();
3386     float relativeTop = geometryNode->GetPixelGridRoundOffset().GetY();
3387     float nodeWidth = geometryNode->GetFrameSize().Width();
3388     float nodeHeight = geometryNode->GetFrameSize().Height();
3389     float roundToPixelErrorX = 0.0f;
3390     float roundToPixelErrorY = 0.0f;
3391     float absoluteRight = relativeLeft + nodeWidth;
3392     float absoluteBottom = relativeTop + nodeHeight;
3393     bool ceilLeft = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_START);
3394     bool floorLeft = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_START);
3395     bool noRoundLeft = flag & static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_START);
3396     bool ceilTop = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_TOP);
3397     bool floorTop = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_TOP);
3398     bool noRoundTop = flag & static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_TOP);
3399     bool ceilRight = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_END);
3400     bool floorRight = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_END);
3401     bool noRoundRight = flag & static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_END);
3402     bool ceilBottom = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_CEIL_BOTTOM);
3403     bool floorBottom = flag & static_cast<uint16_t>(PixelRoundPolicy::FORCE_FLOOR_BOTTOM);
3404     bool noRoundBottom = flag & static_cast<uint16_t>(PixelRoundPolicy::NO_FORCE_ROUND_BOTTOM);
3405 
3406     float nodeLeftI = OnePixelValueRounding(relativeLeft, !noRoundLeft, ceilLeft, floorLeft);
3407     float nodeTopI = OnePixelValueRounding(relativeTop, !noRoundTop, ceilTop, floorTop);
3408     roundToPixelErrorX += nodeLeftI - relativeLeft;
3409     roundToPixelErrorY += nodeTopI - relativeTop;
3410     geometryNode->SetPixelGridRoundOffset(OffsetF(nodeLeftI, nodeTopI));
3411 
3412     float nodeWidthI = OnePixelValueRounding(absoluteRight, !noRoundRight, ceilRight, floorRight) - nodeLeftI;
3413     float nodeWidthTemp = OnePixelValueRounding(nodeWidth, !noRoundRight, ceilRight, floorRight);
3414     roundToPixelErrorX += nodeWidthI - nodeWidth;
3415     if (roundToPixelErrorX > 0.5f) {
3416         nodeWidthI -= 1.0f;
3417         roundToPixelErrorX -= 1.0f;
3418     }
3419     if (roundToPixelErrorX < -0.5f) {
3420         nodeWidthI += 1.0f;
3421         roundToPixelErrorX += 1.0f;
3422     }
3423     if (nodeWidthI < nodeWidthTemp) {
3424         roundToPixelErrorX += nodeWidthTemp - nodeWidthI;
3425         nodeWidthI = nodeWidthTemp;
3426     }
3427 
3428     float nodeHeightI = OnePixelValueRounding(absoluteBottom, !noRoundBottom, ceilBottom, floorBottom) - nodeTopI;
3429     float nodeHeightTemp = OnePixelValueRounding(nodeHeight, !noRoundBottom, ceilBottom, floorBottom);
3430     roundToPixelErrorY += nodeHeightI - nodeHeight;
3431     if (roundToPixelErrorY > 0.5f) {
3432         nodeHeightI -= 1.0f;
3433         roundToPixelErrorY -= 1.0f;
3434     }
3435     if (roundToPixelErrorY < -0.5f) {
3436         nodeHeightI += 1.0f;
3437         roundToPixelErrorY += 1.0f;
3438     }
3439     if (nodeHeightI < nodeHeightTemp) {
3440         roundToPixelErrorY += nodeHeightTemp - nodeHeightI;
3441         nodeHeightI = nodeHeightTemp;
3442     }
3443     geometryNode->SetPixelGridRoundSize(SizeF(nodeWidthI, nodeHeightI));
3444 }
3445 
CombineMarginAndPosition(Dimension & resultX,Dimension & resultY,const Dimension & parentPaddingLeft,const Dimension & parentPaddingTop,float widthPercentReference,float heightPercentReference)3446 void RosenRenderContext::CombineMarginAndPosition(Dimension& resultX, Dimension& resultY,
3447     const Dimension& parentPaddingLeft, const Dimension& parentPaddingTop, float widthPercentReference,
3448     float heightPercentReference)
3449 {
3450     Dimension selfMarginLeft;
3451     Dimension selfMarginTop;
3452     auto frameNode = GetHost();
3453     if (frameNode && frameNode->GetLayoutProperty() && frameNode->GetLayoutProperty()->GetMarginProperty()) {
3454         auto& margin = frameNode->GetLayoutProperty()->GetMarginProperty();
3455         if (margin->left.has_value()) {
3456             selfMarginLeft = margin->left.value().GetDimension();
3457         }
3458         if (margin->top.has_value()) {
3459             selfMarginTop = margin->top.value().GetDimension();
3460         }
3461     }
3462     // to distinguish cases ex. margin has percentage unit and padding has vp unit
3463     // final rect offset will be affected by parent padding, self margin and position property
3464     if (selfMarginLeft.Unit() != GetPositionValue({}).GetX().Unit() ||
3465         selfMarginLeft.Unit() != parentPaddingLeft.Unit() ||
3466         parentPaddingLeft.Unit() != GetPositionValue({}).GetX().Unit()) {
3467         resultX = Dimension(
3468             ConvertToPx(parentPaddingLeft, ScaleProperty::CreateScaleProperty(), widthPercentReference).value_or(0) +
3469                 ConvertToPx(selfMarginLeft, ScaleProperty::CreateScaleProperty(), widthPercentReference).value_or(0) +
3470                 ConvertToPx(GetPositionValue({}).GetX(), ScaleProperty::CreateScaleProperty(), widthPercentReference)
3471                     .value_or(0),
3472             DimensionUnit::PX);
3473     } else {
3474         resultX = selfMarginLeft + GetPositionValue({}).GetX() + parentPaddingLeft;
3475     }
3476     if (selfMarginTop.Unit() != GetPositionValue({}).GetY().Unit() || selfMarginTop.Unit() != parentPaddingTop.Unit() ||
3477         parentPaddingTop.Unit() != GetPositionValue({}).GetY().Unit()) {
3478         resultY = Dimension(
3479             ConvertToPx(parentPaddingTop, ScaleProperty::CreateScaleProperty(), heightPercentReference).value_or(0) +
3480                 ConvertToPx(selfMarginTop, ScaleProperty::CreateScaleProperty(), heightPercentReference).value_or(0) +
3481                 ConvertToPx(GetPositionValue({}).GetY(), ScaleProperty::CreateScaleProperty(), heightPercentReference)
3482                     .value_or(0),
3483             DimensionUnit::PX);
3484     } else {
3485         resultY = selfMarginTop + GetPositionValue({}).GetY() + parentPaddingTop;
3486     }
3487 }
3488 
IsUsingPosition(const RefPtr<FrameNode> & frameNode)3489 bool RosenRenderContext::IsUsingPosition(const RefPtr<FrameNode>& frameNode)
3490 {
3491     auto layoutProperty = frameNode->GetLayoutProperty();
3492     bool isUsingPosition = true;
3493     if (layoutProperty) {
3494         isUsingPosition = layoutProperty->IsUsingPosition();
3495     }
3496     return isUsingPosition;
3497 }
3498 
GetPaddingOfFirstFrameNodeParent(Dimension & parentPaddingLeft,Dimension & parentPaddingTop)3499 void RosenRenderContext::GetPaddingOfFirstFrameNodeParent(Dimension& parentPaddingLeft, Dimension& parentPaddingTop)
3500 {
3501     auto frameNode = GetHost();
3502     CHECK_NULL_VOID(frameNode);
3503     auto frameNodeParent = frameNode->GetAncestorNodeOfFrame(true);
3504     CHECK_NULL_VOID(frameNodeParent);
3505     auto layoutProperty = frameNodeParent->GetLayoutProperty();
3506     if (layoutProperty && layoutProperty->GetPaddingProperty()) {
3507         parentPaddingLeft =
3508             layoutProperty->GetPaddingProperty()->left.value_or(CalcLength(Dimension(0))).GetDimension();
3509         parentPaddingTop = layoutProperty->GetPaddingProperty()->top.value_or(CalcLength(Dimension(0))).GetDimension();
3510     }
3511 }
3512 
GetPercentReference(const RefPtr<FrameNode> & frameNode)3513 SizeF RosenRenderContext::GetPercentReference(const RefPtr<FrameNode>& frameNode)
3514 {
3515     SizeF percentReference = SizeF(PipelineContext::GetCurrentRootWidth(), PipelineContext::GetCurrentRootHeight());
3516     CHECK_NULL_RETURN(frameNode, percentReference);
3517     const auto& layoutConstraint = frameNode->GetGeometryNode()->GetParentLayoutConstraint();
3518     if (layoutConstraint.has_value()) {
3519         percentReference.SetWidth(layoutConstraint->percentReference.Width());
3520         percentReference.SetHeight(layoutConstraint->percentReference.Height());
3521     }
3522     return percentReference;
3523 }
3524 
SetPositionToRSNode()3525 void RosenRenderContext::SetPositionToRSNode()
3526 {
3527     auto frameNode = GetHost();
3528     CHECK_NULL_VOID(frameNode);
3529     CHECK_NULL_VOID(rsNode_);
3530     auto rect = AdjustPaintRect();
3531     if (!rect.GetSize().IsPositive()) {
3532         return;
3533     }
3534     paintRect_ = rect;
3535     if (frameNode->ParentExpansive() && !frameNode->SelfExpansive()) {
3536         // Dynamically modify position, need consider parent expand
3537         frameNode->AdjustNotExpandNode();
3538         rect = paintRect_;
3539     }
3540     if (AnimationUtils::IsImplicitAnimationOpen()) {
3541         auto preBounds = rsNode_->GetStagingProperties().GetBounds();
3542         if (!NearEqual(preBounds[0], rect.GetX()) || !NearEqual(preBounds[1], rect.GetY())) {
3543             ACE_SCOPED_TRACE("SetPosition, bounds from (%f, %f, %f, %f) to (%f, %f, %f, %f), id:%d, tag:%s",
3544                 preBounds[0], preBounds[1], preBounds[2], preBounds[3], rect.GetX(), rect.GetY(), rect.Width(),
3545                 rect.Height(), frameNode->GetId(), frameNode->GetTag().c_str());
3546         }
3547     }
3548     rsNode_->SetBounds(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
3549     if (useContentRectForRSFrame_) {
3550         SetContentRectToFrame(rect);
3551     } else {
3552         rsNode_->SetFrame(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
3553     }
3554     if (frameOffset_.has_value()) {
3555         rsNode_->SetFrame(
3556             rect.GetX() + frameOffset_->GetX(), rect.GetY() + frameOffset_->GetY(), rect.Width(), rect.Height());
3557     }
3558     frameNode->OnSyncGeometryFrameFinish(rect);
3559     ElementRegister::GetInstance()->ReSyncGeometryTransition(GetHost());
3560 }
3561 
OnPositionUpdate(const OffsetT<Dimension> &)3562 void RosenRenderContext::OnPositionUpdate(const OffsetT<Dimension>& /*value*/)
3563 {
3564     SetPositionToRSNode();
3565 }
3566 
OnPositionEdgesUpdate(const EdgesParam &)3567 void RosenRenderContext::OnPositionEdgesUpdate(const EdgesParam& /*value*/)
3568 {
3569     SetPositionToRSNode();
3570 }
3571 
OnOffsetUpdate(const OffsetT<Dimension> &)3572 void RosenRenderContext::OnOffsetUpdate(const OffsetT<Dimension>& /*value*/)
3573 {
3574     SetPositionToRSNode();
3575 }
3576 
OnOffsetEdgesUpdate(const EdgesParam &)3577 void RosenRenderContext::OnOffsetEdgesUpdate(const EdgesParam& /*value*/)
3578 {
3579     SetPositionToRSNode();
3580 }
3581 
OnAnchorUpdate(const OffsetT<Dimension> &)3582 void RosenRenderContext::OnAnchorUpdate(const OffsetT<Dimension>& /*value*/)
3583 {
3584     SetPositionToRSNode();
3585 }
3586 
RecalculatePosition()3587 void RosenRenderContext::RecalculatePosition()
3588 {
3589     SetPositionToRSNode();
3590 }
3591 
OnZIndexUpdate(int32_t value)3592 void RosenRenderContext::OnZIndexUpdate(int32_t value)
3593 {
3594     CHECK_NULL_VOID(rsNode_);
3595     // When zindex is combined with transform/rotate, zindex has the action of controlling camera height
3596     rsNode_->SetPositionZApplicableCamera3D(Container::LessThanAPITargetVersion(PlatformVersion::VERSION_FOURTEEN));
3597     rsNode_->SetPositionZ(static_cast<float>(value));
3598     auto uiNode = GetHost();
3599     CHECK_NULL_VOID(uiNode);
3600     auto parent = uiNode->GetAncestorNodeOfFrame(true);
3601     CHECK_NULL_VOID(parent);
3602     parent->MarkNeedSyncRenderTree();
3603     parent->RebuildRenderContextTree();
3604 }
3605 
ResetBlendBgColor()3606 void RosenRenderContext::ResetBlendBgColor()
3607 {
3608     CHECK_NULL_VOID(rsNode_);
3609     blendColor_ = Color::TRANSPARENT;
3610     auto blendColor =
3611         GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(blendColor_).BlendColor(hoveredColor_);
3612     rsNode_->SetBackgroundColor(blendColor.GetValue());
3613     RequestNextFrame();
3614 }
3615 
BlendBgColor(const Color & color)3616 void RosenRenderContext::BlendBgColor(const Color& color)
3617 {
3618     CHECK_NULL_VOID(rsNode_);
3619     blendColor_ = color;
3620     auto blendColor =
3621         GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(blendColor_).BlendColor(hoveredColor_);
3622     rsNode_->SetBackgroundColor(blendColor.GetValue());
3623     RequestNextFrame();
3624 }
3625 
ResetBlendBorderColor()3626 void RosenRenderContext::ResetBlendBorderColor()
3627 {
3628     CHECK_NULL_VOID(rsNode_);
3629     auto leftColor = (Color::TRANSPARENT).GetValue();
3630     auto topColor = (Color::TRANSPARENT).GetValue();
3631     auto rightColor = (Color::TRANSPARENT).GetValue();
3632     auto bottomColor = (Color::TRANSPARENT).GetValue();
3633     if (GetBorderColor().has_value()) {
3634         leftColor = GetBorderColor()->leftColor.value_or(Color::TRANSPARENT).GetValue();
3635         topColor = GetBorderColor()->topColor.value_or(Color::TRANSPARENT).GetValue();
3636         rightColor = GetBorderColor()->rightColor.value_or(Color::TRANSPARENT).GetValue();
3637         bottomColor = GetBorderColor()->bottomColor.value_or(Color::TRANSPARENT).GetValue();
3638     }
3639     rsNode_->SetBorderColor(leftColor, topColor, rightColor, bottomColor);
3640     RequestNextFrame();
3641 }
3642 
BlendBorderColor(const Color & color)3643 void RosenRenderContext::BlendBorderColor(const Color& color)
3644 {
3645     CHECK_NULL_VOID(rsNode_);
3646     auto leftColor = color.GetValue();
3647     auto topColor = color.GetValue();
3648     auto rightColor = color.GetValue();
3649     auto bottomColor = color.GetValue();
3650     if (GetBorderColor().has_value()) {
3651         leftColor = (GetBorderColor()->leftColor.value_or(Color::TRANSPARENT).BlendColor(color)).GetValue();
3652         topColor = (GetBorderColor()->topColor.value_or(Color::TRANSPARENT).BlendColor(color)).GetValue();
3653         rightColor = (GetBorderColor()->rightColor.value_or(Color::TRANSPARENT).BlendColor(color)).GetValue();
3654         bottomColor = (GetBorderColor()->bottomColor.value_or(Color::TRANSPARENT).BlendColor(color)).GetValue();
3655     }
3656     rsNode_->SetBorderColor(leftColor, topColor, rightColor, bottomColor);
3657     RequestNextFrame();
3658 }
3659 
PaintFocusState(const RoundRect & paintRect,const Color & paintColor,const Dimension & paintWidth,bool isAccessibilityFocus,bool isFocusBoxGlow)3660 void RosenRenderContext::PaintFocusState(const RoundRect& paintRect, const Color& paintColor,
3661     const Dimension& paintWidth, bool isAccessibilityFocus, bool isFocusBoxGlow)
3662 {
3663 #ifndef IS_RELEASE_VERSION
3664     TAG_LOGD(AceLogTag::ACE_FOCUS,
3665         "PaintFocusState rect is (%{public}f, %{public}f, %{public}f, %{public}f). Color is %{public}s, PainWidth is "
3666         "%{public}s",
3667         paintRect.GetRect().Left(), paintRect.GetRect().Top(), paintRect.GetRect().Width(),
3668         paintRect.GetRect().Height(), paintColor.ColorToString().c_str(), paintWidth.ToString().c_str());
3669 #endif
3670     CHECK_NULL_VOID(paintRect.GetRect().IsValid());
3671     CHECK_NULL_VOID(rsNode_);
3672     auto borderWidthPx = static_cast<float>(paintWidth.ConvertToPx());
3673     isFocusBoxGlow_ = isFocusBoxGlow;
3674     if (isAccessibilityFocus) {
3675         InitAccessibilityFocusModidifer(paintRect, paintColor, borderWidthPx);
3676         auto host = GetHost();
3677         if (host && host->GetTag() != V2::ACCESSIBILITY_FOCUS_PAINT_NODE_TAG) {
3678             UpdateDrawRegion(
3679                 DRAW_REGION_ACCESSIBILITY_FOCUS_MODIFIER_INDEX, accessibilityFocusStateModifier_->GetOverlayRect());
3680         }
3681         rsNode_->AddModifier(accessibilityFocusStateModifier_);
3682         accessibilityFocusStateModifier_->AttachAnimationRectProperty();
3683         RequestNextFrame();
3684         return;
3685     }
3686     if (!isFocusBoxGlow_) {
3687         InitFocusStateModidifer(paintRect, paintColor, borderWidthPx);
3688         UpdateDrawRegion(DRAW_REGION_FOCUS_MODIFIER_INDEX, focusStateModifier_->GetOverlayRect());
3689         rsNode_->AddModifier(focusStateModifier_);
3690         focusStateModifier_->AttachAnimationRectProperty();
3691     } else {
3692         InitFocusAnimationModidifer(paintRect, paintColor, borderWidthPx);
3693         UpdateDrawRegion(DRAW_REGION_FOCUS_MODIFIER_INDEX, focusAnimationModifier_->GetOverlayRect());
3694         auto modifierAdapter =
3695             std::static_pointer_cast<OverlayModifierAdapter>(ConvertOverlayModifier(focusAnimationModifier_));
3696         rsNode_->AddModifier(modifierAdapter);
3697         modifierAdapter->AttachProperties();
3698         focusAnimationModifier_->StartFocusAnimation();
3699     }
3700     RequestNextFrame();
3701 }
3702 
InitAccessibilityFocusModidifer(const RoundRect & paintRect,const Color & paintColor,float borderWidthPx)3703 void RosenRenderContext::InitAccessibilityFocusModidifer(
3704     const RoundRect& paintRect, const Color& paintColor, float borderWidthPx)
3705 {
3706     auto frameNode = GetHost();
3707     if (!accessibilityFocusStateModifier_) {
3708         accessibilityFocusStateModifier_ = std::make_shared<FocusStateModifier>();
3709     }
3710     rsNode_->AddModifier(accessibilityFocusStateModifier_);
3711     accessibilityFocusStateModifier_->SetRoundRect(paintRect, borderWidthPx);
3712     accessibilityFocusStateModifier_->SetPaintColor(paintColor);
3713     accessibilityFocusStateModifier_->SetFrameNode(frameNode);
3714     accessibilityFocusStateModifier_->SetNoNeedUICaptured(true);
3715 }
3716 
InitFocusStateModidifer(const RoundRect & paintRect,const Color & paintColor,float borderWidthPx)3717 void RosenRenderContext::InitFocusStateModidifer(
3718     const RoundRect& paintRect, const Color& paintColor, float borderWidthPx)
3719 {
3720     auto frameNode = GetHost();
3721     if (!focusStateModifier_) {
3722         focusStateModifier_ = std::make_shared<FocusStateModifier>();
3723     }
3724     focusStateModifier_->SetRoundRect(paintRect, borderWidthPx);
3725     focusStateModifier_->SetPaintColor(paintColor);
3726     focusStateModifier_->SetFrameNode(frameNode);
3727 }
3728 
InitFocusAnimationModidifer(const RoundRect & paintRect,const Color & paintColor,float borderWidthPx)3729 void RosenRenderContext::InitFocusAnimationModidifer(
3730     const RoundRect& paintRect, const Color& paintColor, float borderWidthPx)
3731 {
3732     auto frameNode = GetHost();
3733     if (!focusAnimationModifier_) {
3734         focusAnimationModifier_ = AceType::MakeRefPtr<FocusAnimationModifier>();
3735     }
3736     focusAnimationModifier_->SetRoundRect(paintRect, borderWidthPx);
3737     focusAnimationModifier_->SetPaintColor(paintColor);
3738     focusAnimationModifier_->SetFrameNode(frameNode);
3739 }
3740 
PaintFocusState(const RoundRect & paintRect,const Dimension & focusPaddingVp,const Color & paintColor,const Dimension & paintWidth,const PaintFocusExtraInfo & paintFocusExtraInfo)3741 void RosenRenderContext::PaintFocusState(const RoundRect& paintRect, const Dimension& focusPaddingVp,
3742     const Color& paintColor, const Dimension& paintWidth, const PaintFocusExtraInfo& paintFocusExtraInfo)
3743 {
3744     auto paintWidthPx = static_cast<float>(paintWidth.ConvertToPx());
3745     auto borderPaddingPx = static_cast<float>(focusPaddingVp.ConvertToPx());
3746     auto focusPaintRectLeft = paintRect.GetRect().Left() - borderPaddingPx - paintWidthPx / 2;
3747     auto focusPaintRectTop = paintRect.GetRect().Top() - borderPaddingPx - paintWidthPx / 2;
3748     auto focusPaintRectWidth = paintRect.GetRect().Width() + 2 * borderPaddingPx + paintWidthPx;
3749     auto focusPaintRectHeight = paintRect.GetRect().Height() + 2 * borderPaddingPx + paintWidthPx;
3750 
3751     EdgeF diffRadius = { borderPaddingPx + paintWidthPx / 2, borderPaddingPx + paintWidthPx / 2 };
3752     auto focusPaintCornerTopLeft = paintRect.GetCornerRadius(RoundRect::CornerPos::TOP_LEFT_POS) + diffRadius;
3753     auto focusPaintCornerTopRight = paintRect.GetCornerRadius(RoundRect::CornerPos::TOP_RIGHT_POS) + diffRadius;
3754     auto focusPaintCornerBottomLeft = paintRect.GetCornerRadius(RoundRect::CornerPos::BOTTOM_LEFT_POS) + diffRadius;
3755     auto focusPaintCornerBottomRight = paintRect.GetCornerRadius(RoundRect::CornerPos::BOTTOM_RIGHT_POS) + diffRadius;
3756 
3757     RoundRect focusPaintRect;
3758     focusPaintRect.SetRect(RectF(focusPaintRectLeft, focusPaintRectTop, focusPaintRectWidth, focusPaintRectHeight));
3759     focusPaintRect.SetCornerRadius(
3760         RoundRect::CornerPos::TOP_LEFT_POS, focusPaintCornerTopLeft.x, focusPaintCornerTopLeft.y);
3761     focusPaintRect.SetCornerRadius(
3762         RoundRect::CornerPos::TOP_RIGHT_POS, focusPaintCornerTopRight.x, focusPaintCornerTopRight.y);
3763     focusPaintRect.SetCornerRadius(
3764         RoundRect::CornerPos::BOTTOM_LEFT_POS, focusPaintCornerBottomLeft.x, focusPaintCornerBottomLeft.y);
3765     focusPaintRect.SetCornerRadius(
3766         RoundRect::CornerPos::BOTTOM_RIGHT_POS, focusPaintCornerBottomRight.x, focusPaintCornerBottomRight.y);
3767 
3768     PaintFocusState(focusPaintRect, paintColor, paintWidth, paintFocusExtraInfo.isAccessibilityFocus,
3769         paintFocusExtraInfo.isFocusBoxGlow);
3770 }
3771 
PaintFocusState(const Dimension & focusPaddingVp,const Color & paintColor,const Dimension & paintWidth,bool isFocusBoxGlow)3772 void RosenRenderContext::PaintFocusState(
3773     const Dimension& focusPaddingVp, const Color& paintColor, const Dimension& paintWidth, bool isFocusBoxGlow)
3774 {
3775     CHECK_NULL_VOID(rsNode_);
3776     const auto& bounds = rsNode_->GetStagingProperties().GetBounds();
3777     const auto& radius = rsNode_->GetStagingProperties().GetCornerRadius();
3778 
3779     RoundRect frameRect;
3780     frameRect.SetRect(RectF(0, 0, bounds.z_, bounds.w_));
3781     frameRect.SetCornerRadius(RoundRect::CornerPos::TOP_LEFT_POS, radius.x_, radius.x_);
3782     frameRect.SetCornerRadius(RoundRect::CornerPos::TOP_RIGHT_POS, radius.y_, radius.y_);
3783     frameRect.SetCornerRadius(RoundRect::CornerPos::BOTTOM_RIGHT_POS, radius.z_, radius.z_);
3784     frameRect.SetCornerRadius(RoundRect::CornerPos::BOTTOM_LEFT_POS, radius.w_, radius.w_);
3785 
3786     PaintFocusState(frameRect, focusPaddingVp, paintColor, paintWidth, { false, isFocusBoxGlow });
3787 }
3788 
ClearFocusState()3789 void RosenRenderContext::ClearFocusState()
3790 {
3791     TAG_LOGD(AceLogTag::ACE_FOCUS, "Clear focus state.");
3792     CHECK_NULL_VOID(rsNode_);
3793     auto context = PipelineBase::GetCurrentContext();
3794     CHECK_NULL_VOID(context);
3795     if (!isFocusBoxGlow_) {
3796         CHECK_NULL_VOID(focusStateModifier_);
3797         UpdateDrawRegion(DRAW_REGION_FOCUS_MODIFIER_INDEX, focusStateModifier_->GetOverlayRect());
3798         rsNode_->RemoveModifier(focusStateModifier_);
3799         RequestNextFrame();
3800         return;
3801     }
3802     CHECK_NULL_VOID(focusAnimationModifier_);
3803     focusAnimationModifier_->StopFocusAnimation();
3804     UpdateDrawRegion(DRAW_REGION_FOCUS_MODIFIER_INDEX, focusAnimationModifier_->GetOverlayRect());
3805     auto modifierAdapter =
3806         std::static_pointer_cast<OverlayModifierAdapter>(ConvertOverlayModifier(focusAnimationModifier_));
3807     rsNode_->RemoveModifier(modifierAdapter);
3808     RequestNextFrame();
3809 }
3810 
FlushContentDrawFunction(CanvasDrawFunction && contentDraw)3811 void RosenRenderContext::FlushContentDrawFunction(CanvasDrawFunction&& contentDraw)
3812 {
3813     CHECK_NULL_VOID(rsNode_);
3814     CHECK_NULL_VOID(contentDraw);
3815     rsNode_->DrawOnNode(
3816         Rosen::RSModifierType::CONTENT_STYLE,
3817         [contentDraw = std::move(contentDraw)](std::shared_ptr<RSCanvas> canvas) {
3818             CHECK_NULL_VOID(canvas);
3819             contentDraw(*canvas);
3820         });
3821 }
3822 
FlushContentModifier(const RefPtr<Modifier> & modifier)3823 void RosenRenderContext::FlushContentModifier(const RefPtr<Modifier>& modifier)
3824 {
3825     CHECK_NULL_VOID(rsNode_);
3826     CHECK_NULL_VOID(modifier);
3827     auto modifierAdapter = std::static_pointer_cast<ContentModifierAdapter>(ConvertContentModifier(modifier));
3828     auto contentModifier = AceType::DynamicCast<ContentModifier>(modifier);
3829     CHECK_NULL_VOID(contentModifier);
3830     auto rect = contentModifier->GetBoundsRect();
3831     if (rect.has_value()) {
3832         std::shared_ptr<Rosen::RectF> overlayRect =
3833             std::make_shared<Rosen::RectF>(rect->GetX(), rect->GetY(), rect->Width(), rect->Height());
3834         UpdateDrawRegion(DRAW_REGION_CONTENT_MODIFIER_INDEX, overlayRect);
3835     }
3836     rsNode_->SetIsCustomTextType(contentModifier->GetIsCustomFont());
3837     rsNode_->AddModifier(modifierAdapter);
3838     modifierAdapter->AttachProperties();
3839 }
3840 
FlushKitContentModifier(const RefPtr<Kit::Modifier> & modifier)3841 void RosenRenderContext::FlushKitContentModifier(const RefPtr<Kit::Modifier>& modifier)
3842 {
3843     CHECK_NULL_VOID(rsNode_);
3844     CHECK_NULL_VOID(modifier);
3845 
3846     auto modifierAdapter = ConvertKitContentModifier(modifier);
3847     rsNode_->AddModifier(modifierAdapter);
3848     modifier->OnAttached();
3849 }
3850 
FlushForegroundDrawFunction(CanvasDrawFunction && foregroundDraw)3851 void RosenRenderContext::FlushForegroundDrawFunction(CanvasDrawFunction&& foregroundDraw)
3852 {
3853     CHECK_NULL_VOID(rsNode_);
3854     CHECK_NULL_VOID(foregroundDraw);
3855     rsNode_->DrawOnNode(Rosen::RSModifierType::FOREGROUND_STYLE,
3856         [foregroundDraw = std::move(foregroundDraw)](std::shared_ptr<RSCanvas> canvas) {
3857             CHECK_NULL_VOID(canvas);
3858             foregroundDraw(*canvas);
3859         });
3860 }
3861 
FlushOverlayDrawFunction(CanvasDrawFunction && overlayDraw)3862 void RosenRenderContext::FlushOverlayDrawFunction(CanvasDrawFunction&& overlayDraw)
3863 {
3864     CHECK_NULL_VOID(rsNode_);
3865     CHECK_NULL_VOID(overlayDraw);
3866     rsNode_->DrawOnNode(
3867         Rosen::RSModifierType::OVERLAY_STYLE,
3868         [overlayDraw = std::move(overlayDraw)](std::shared_ptr<RSCanvas> canvas) {
3869             CHECK_NULL_VOID(canvas);
3870             overlayDraw(*canvas);
3871         });
3872 }
3873 
FlushOverlayModifier(const RefPtr<Modifier> & modifier)3874 void RosenRenderContext::FlushOverlayModifier(const RefPtr<Modifier>& modifier)
3875 {
3876     CHECK_NULL_VOID(rsNode_);
3877     CHECK_NULL_VOID(modifier);
3878     auto modifierAdapter = std::static_pointer_cast<OverlayModifierAdapter>(ConvertOverlayModifier(modifier));
3879     auto overlayModifier = AceType::DynamicCast<OverlayModifier>(modifier);
3880     CHECK_NULL_VOID(overlayModifier);
3881     auto rect = overlayModifier->GetBoundsRect();
3882     std::shared_ptr<Rosen::RectF> overlayRect =
3883         std::make_shared<Rosen::RectF>(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
3884     UpdateDrawRegion(DRAW_REGION_OVERLAY_MODIFIER_INDEX, overlayRect);
3885     rsNode_->AddModifier(modifierAdapter);
3886     modifierAdapter->AttachProperties();
3887 }
3888 
FlushForegroundModifier(const RefPtr<Modifier> & modifier)3889 void RosenRenderContext::FlushForegroundModifier(const RefPtr<Modifier>& modifier)
3890 {
3891     CHECK_NULL_VOID(rsNode_);
3892     CHECK_NULL_VOID(modifier);
3893     auto modifierAdapter = std::static_pointer_cast<ForegroundModifierAdapter>(ConvertForegroundModifier(modifier));
3894     auto foregroundModifier = AceType::DynamicCast<ForegroundModifier>(modifier);
3895     CHECK_NULL_VOID(foregroundModifier);
3896     auto rect = foregroundModifier->GetBoundsRect();
3897     std::shared_ptr<Rosen::RectF> foregroundRect =
3898         std::make_shared<Rosen::RectF>(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
3899     UpdateDrawRegion(DRAW_REGION_OVERLAY_MODIFIER_INDEX, foregroundRect);
3900     rsNode_->AddModifier(modifierAdapter);
3901     modifierAdapter->AttachProperties();
3902 }
3903 
GetRSNode()3904 const std::shared_ptr<Rosen::RSNode>& RosenRenderContext::GetRSNode()
3905 {
3906     return rsNode_;
3907 }
3908 
RebuildFrame(FrameNode *,const std::list<RefPtr<FrameNode>> & children)3909 void RosenRenderContext::RebuildFrame(FrameNode* /*self*/, const std::list<RefPtr<FrameNode>>& children)
3910 {
3911     ReCreateRsNodeTree(children);
3912     RequestNextFrame();
3913 }
3914 
GetChildrenRSNodes(const std::list<RefPtr<FrameNode>> & frameChildren,std::unordered_map<Rosen::NodeId,bool> & nodeIdMap)3915 std::vector<std::shared_ptr<Rosen::RSNode>> RosenRenderContext::GetChildrenRSNodes(
3916     const std::list<RefPtr<FrameNode>>& frameChildren, std::unordered_map<Rosen::NodeId, bool>& nodeIdMap)
3917 {
3918     std::vector<std::shared_ptr<Rosen::RSNode>> rsNodes;
3919     for (const auto& child : frameChildren) {
3920         if (!child) {
3921             continue;
3922         }
3923         auto rosenRenderContext = DynamicCast<RosenRenderContext>(child->renderContext_);
3924         if (!rosenRenderContext) {
3925             continue;
3926         }
3927         auto rsnode = rosenRenderContext->GetRSNode();
3928         if (!rsnode) {
3929             continue;
3930         }
3931         auto result = nodeIdMap.try_emplace(rsnode->GetId(), false);
3932         if (result.second) {
3933             rsNodes.emplace_back(rsnode);
3934         }
3935     }
3936     return rsNodes;
3937 }
3938 
SetDrawNode()3939 void RosenRenderContext::SetDrawNode()
3940 {
3941     CHECK_NULL_VOID(rsNode_);
3942     rsNode_->SetDrawNode();
3943 }
3944 
AddNodeToRsTree()3945 bool RosenRenderContext::AddNodeToRsTree()
3946 {
3947     auto node = GetHost();
3948     if (!node || !node->GetIsDelete()) {
3949         return true;
3950     }
3951     if (SystemProperties::GetDebugEnabled()) {
3952         TAG_LOGD(AceLogTag::ACE_DEFAULT_DOMAIN, "AddNodeToRsTree node(%{public}d, %{public}s)", node->GetId(),
3953             node->GetTag().c_str());
3954     }
3955 
3956     std::list<RefPtr<FrameNode>> childNodes;
3957     // get not be deleted children of node
3958     GetLiveChildren(node, childNodes);
3959 
3960     auto rsNode = GetRsNodeByFrame(node);
3961     CHECK_NULL_RETURN(rsNode, false);
3962 
3963     size_t rsNodeIndex = rsNode->GetChildren().size();
3964     for (auto& child : childNodes) {
3965         auto childRsNode = GetRsNodeByFrame(child);
3966         rsNode->AddChild(childRsNode, rsNodeIndex);
3967         rsNodeIndex++;
3968     }
3969     node->SetDeleteRsNode(false);
3970     // rebuild parent node
3971     auto parentNode = node->GetParentFrameNode();
3972     CHECK_NULL_RETURN(parentNode, false);
3973     parentNode->MarkNeedSyncRenderTree();
3974     parentNode->RebuildRenderContextTree();
3975     return true;
3976 }
3977 
GetRsNodeByFrame(const RefPtr<FrameNode> & frameNode)3978 std::shared_ptr<Rosen::RSNode> RosenRenderContext::GetRsNodeByFrame(const RefPtr<FrameNode>& frameNode)
3979 {
3980     if (!frameNode) {
3981         return nullptr;
3982     }
3983     auto rosenRenderContext = DynamicCast<RosenRenderContext>(frameNode->renderContext_);
3984     if (!rosenRenderContext) {
3985         return nullptr;
3986     }
3987     auto rsnode = rosenRenderContext->GetRSNode();
3988     return rsnode;
3989 }
3990 
CanNodeBeDeleted(const RefPtr<FrameNode> & node) const3991 bool RosenRenderContext::CanNodeBeDeleted(const RefPtr<FrameNode>& node) const
3992 {
3993     CHECK_NULL_RETURN(node, false);
3994     auto rsNode = GetRsNodeByFrame(node);
3995     CHECK_NULL_RETURN(rsNode, false);
3996     std::list <RefPtr<FrameNode>> childChildrenList;
3997     node->GenerateOneDepthVisibleFrameWithTransition(childChildrenList);
3998     if (rsNode->GetIsDrawn() || rsNode->GetType() != Rosen::RSUINodeType::CANVAS_NODE
3999         || childChildrenList.empty() || node->GetTag() == V2::PAGE_ETS_TAG
4000         || node->GetTag() == V2::STAGE_ETS_TAG) {
4001         return false;
4002     }
4003     return true;
4004 }
4005 
GetLiveChildren(const RefPtr<FrameNode> & node,std::list<RefPtr<FrameNode>> & childNodes)4006 void RosenRenderContext::GetLiveChildren(const RefPtr<FrameNode>& node, std::list<RefPtr<FrameNode>>& childNodes)
4007 {
4008     CHECK_NULL_VOID(node);
4009     std::list<RefPtr<FrameNode>> childrenList;
4010     auto pipeline = node->GetContext();
4011     CHECK_NULL_VOID(pipeline);
4012     node->GenerateOneDepthVisibleFrameWithTransition(childrenList);
4013     for (auto& child : childrenList) {
4014         if (!CanNodeBeDeleted(child)) {
4015             childNodes.emplace_back(child);
4016             if (pipeline && child->HasPositionZ()) {
4017                 pipeline->AddPositionZNode(child->GetId());
4018             }
4019         } else {
4020             child->SetDeleteRsNode(true);
4021             GetLiveChildren(child, childNodes);
4022         }
4023     }
4024     auto accessibilityFocusPaintNode = node->GetFocusPaintNode();
4025     if (accessibilityFocusPaintNode) {
4026         childNodes.emplace_back(accessibilityFocusPaintNode);
4027         if (accessibilityFocusPaintNode->HasPositionZ()) {
4028             pipeline->AddPositionZNode(accessibilityFocusPaintNode->GetId());
4029         }
4030     }
4031     auto overlayNode = node->GetOverlayNode();
4032     CHECK_NULL_VOID(overlayNode);
4033     auto property = overlayNode->GetLayoutProperty();
4034     if (property && property->GetVisibilityValue(VisibleType::VISIBLE) == VisibleType::VISIBLE) {
4035         if (!CanNodeBeDeleted(overlayNode)) {
4036             childNodes.emplace_back(overlayNode);
4037             if (pipeline && overlayNode->HasPositionZ()) {
4038                 pipeline->AddPositionZNode(overlayNode->GetId());
4039             }
4040         } else {
4041             overlayNode->SetDeleteRsNode(true);
4042             GetLiveChildren(overlayNode, childNodes);
4043         }
4044     }
4045 }
4046 
AddRsNodeForCapture()4047 void RosenRenderContext::AddRsNodeForCapture()
4048 {
4049     CHECK_NULL_VOID(rsNode_);
4050     auto host = GetHost();
4051     if (host && host->GetIsDelete()) {
4052         rsNode_->SetDrawNode();
4053         auto pipeline = host->GetContext();
4054         if (pipeline) {
4055             pipeline->FlushMessages();
4056         }
4057     }
4058 }
4059 
ReCreateRsNodeTree(const std::list<RefPtr<FrameNode>> & children)4060 void RosenRenderContext::ReCreateRsNodeTree(const std::list<RefPtr<FrameNode>>& children)
4061 {
4062     if (!rsNode_ || !isNeedRebuildRSTree_) {
4063         return;
4064     }
4065     auto childNodesNew = children;
4066     if (SystemProperties::GetContainerDeleteFlag()) {
4067         auto frameNode = GetHost();
4068         if (frameNode->GetIsDelete()) {
4069             return;
4070         }
4071         childNodesNew.clear();
4072         GetLiveChildren(frameNode, childNodesNew);
4073     }
4074     // now rsNode's children, key is id of rsNode, value means whether the node exists in previous children of rsNode.
4075     std::unordered_map<Rosen::NodeId, bool> childNodeMap;
4076     auto nowRSNodes = GetChildrenRSNodes(childNodesNew, childNodeMap);
4077     std::vector<Rosen::NodeId> childNodeIds;
4078     for (auto& child : nowRSNodes) {
4079         childNodeIds.emplace_back(child->GetId());
4080     }
4081     if (childNodeIds == rsNode_->GetChildren()) {
4082         return;
4083     }
4084     if (childNodeIds.empty()) {
4085         rsNode_->ClearChildren();
4086         return;
4087     }
4088     // save a copy of previous children because for loop will delete child
4089     auto preChildNodeIds = rsNode_->GetChildren();
4090     for (auto nodeId : preChildNodeIds) {
4091         auto iter = childNodeMap.find(nodeId);
4092         if (iter == childNodeMap.end()) {
4093             rsNode_->RemoveChildByNodeId(nodeId);
4094         } else {
4095             iter->second = true;
4096         }
4097     }
4098     for (size_t index = 0; index != childNodeIds.size(); ++index) {
4099         auto nodeId = rsNode_->GetChildIdByIndex(index);
4100         if (!(nodeId.has_value() && nodeId.value() == childNodeIds[index])) {
4101             auto iter = childNodeMap.find(childNodeIds[index]);
4102             if (iter == childNodeMap.end()) {
4103                 continue;
4104             }
4105             if (iter->second) {
4106                 rsNode_->MoveChild(nowRSNodes[index], index);
4107             } else {
4108                 rsNode_->AddChild(nowRSNodes[index], index);
4109             }
4110         }
4111     }
4112 }
4113 
AddFrameChildren(FrameNode *,const std::list<RefPtr<FrameNode>> & children)4114 void RosenRenderContext::AddFrameChildren(FrameNode* /*self*/, const std::list<RefPtr<FrameNode>>& children)
4115 {
4116     CHECK_NULL_VOID(rsNode_);
4117     for (const auto& child : children) {
4118         if (!child) {
4119             continue;
4120         }
4121         auto rosenRenderContext = DynamicCast<RosenRenderContext>(child->renderContext_);
4122         if (!rosenRenderContext) {
4123             continue;
4124         }
4125         auto rsNode = rosenRenderContext->GetRSNode();
4126         if (rsNode) {
4127             rsNode_->AddChild(rsNode, -1);
4128         }
4129     }
4130 }
4131 
RemoveFrameChildren(FrameNode *,const std::list<RefPtr<FrameNode>> & children)4132 void RosenRenderContext::RemoveFrameChildren(FrameNode* /*self*/, const std::list<RefPtr<FrameNode>>& children)
4133 {
4134     CHECK_NULL_VOID(rsNode_);
4135     for (const auto& child : children) {
4136         if (!child) {
4137             continue;
4138         }
4139         auto rosenRenderContext = DynamicCast<RosenRenderContext>(child->renderContext_);
4140         if (!rosenRenderContext) {
4141             continue;
4142         }
4143         auto rsNode = rosenRenderContext->GetRSNode();
4144         if (rsNode) {
4145             rsNode_->RemoveChild(rsNode);
4146         }
4147     }
4148 }
4149 
MoveFrame(FrameNode *,const RefPtr<FrameNode> & child,int32_t index)4150 void RosenRenderContext::MoveFrame(FrameNode* /*self*/, const RefPtr<FrameNode>& child, int32_t index)
4151 {
4152     CHECK_NULL_VOID(rsNode_);
4153     CHECK_NULL_VOID(child);
4154     auto rosenRenderContext = DynamicCast<RosenRenderContext>(child->renderContext_);
4155     CHECK_NULL_VOID(rosenRenderContext);
4156     auto rsNode = rosenRenderContext->GetRSNode();
4157     // no need to check nullptr since MoveChild will take care of it
4158     rsNode_->MoveChild(rsNode, index);
4159 }
4160 
AnimateHoverEffectScale(bool isHovered)4161 void RosenRenderContext::AnimateHoverEffectScale(bool isHovered)
4162 {
4163     if ((isHovered && isHoveredScale_) || (!isHovered && !isHoveredScale_)) {
4164         return;
4165     }
4166     CHECK_NULL_VOID(rsNode_);
4167     auto pipeline = PipelineBase::GetCurrentContext();
4168     CHECK_NULL_VOID(pipeline);
4169     auto appTheme = pipeline->GetTheme<AppTheme>();
4170     CHECK_NULL_VOID(appTheme);
4171 
4172     float hoverScaleFrom = isHovered ? appTheme->GetHoverScaleStart() : appTheme->GetHoverScaleEnd();
4173     float hoverColorTo = isHovered ? appTheme->GetHoverScaleEnd() : appTheme->GetHoverScaleStart();
4174     float scaleStart = hoverScaleFrom;
4175     float scaleEnd = hoverColorTo;
4176     int32_t themeDuration = appTheme->GetHoverDuration();
4177 
4178     SetScale(scaleStart, scaleStart);
4179     Rosen::RSAnimationTimingProtocol protocol;
4180     protocol.SetDuration(themeDuration);
4181     RSNode::Animate(protocol, Rosen::RSAnimationTimingCurve::CreateCubicCurve(0.2f, 0.0f, 0.2f, 1.0f),
4182         [this, scaleEnd]() { SetScale(scaleEnd, scaleEnd); });
4183     isHoveredScale_ = isHovered;
4184 }
4185 
AnimateHoverEffectBoard(bool isHovered)4186 void RosenRenderContext::AnimateHoverEffectBoard(bool isHovered)
4187 {
4188     if ((isHovered && isHoveredBoard_) || (!isHovered && !isHoveredBoard_)) {
4189         return;
4190     }
4191     CHECK_NULL_VOID(rsNode_);
4192     auto pipeline = PipelineBase::GetCurrentContext();
4193     CHECK_NULL_VOID(pipeline);
4194     auto appTheme = pipeline->GetTheme<AppTheme>();
4195     CHECK_NULL_VOID(appTheme);
4196 
4197     Color hoverColorFrom = isHovered ? appTheme->GetHoverHighlightStart() : appTheme->GetHoverHighlightEnd();
4198     Color hoverColorTo = isHovered ? appTheme->GetHoverHighlightEnd() : appTheme->GetHoverHighlightStart();
4199     Color highlightStart =
4200         GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(blendColor_).BlendColor(hoverColorFrom);
4201     Color highlightEnd =
4202         GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(blendColor_).BlendColor(hoverColorTo);
4203     int32_t themeDuration = appTheme->GetHoverDuration();
4204 
4205     rsNode_->SetBackgroundColor(highlightStart.GetValue());
4206     Rosen::RSAnimationTimingProtocol protocol;
4207     protocol.SetDuration(themeDuration);
4208     RSNode::Animate(protocol, Rosen::RSAnimationTimingCurve::CreateCubicCurve(0.2f, 0.0f, 0.2f, 1.0f),
4209         [rsNode = rsNode_, highlightEnd]() {
4210             CHECK_NULL_VOID(rsNode);
4211             rsNode->SetBackgroundColor(highlightEnd.GetValue());
4212         });
4213     hoveredColor_ = hoverColorTo;
4214     isHoveredBoard_ = isHovered;
4215 }
4216 
UpdateBackBlurRadius(const Dimension & radius)4217 void RosenRenderContext::UpdateBackBlurRadius(const Dimension& radius)
4218 {
4219     const auto& groupProperty = GetOrCreateBackground();
4220     if (groupProperty->CheckBlurRadiusChanged(radius)) {
4221         // Same with previous value
4222         return;
4223     }
4224     groupProperty->propBlurRadius = radius;
4225     SetBackBlurFilter();
4226 }
4227 
UpdateMotionBlur(const MotionBlurOption & motionBlurOption)4228 void RosenRenderContext::UpdateMotionBlur(const MotionBlurOption& motionBlurOption)
4229 {
4230     CHECK_NULL_VOID(rsNode_);
4231     const auto& groupProperty = GetOrCreateForeground();
4232     groupProperty->propMotionBlur = motionBlurOption;
4233     Rosen::Vector2f anchor(motionBlurOption.anchor.x, motionBlurOption.anchor.y);
4234     rsNode_->SetMotionBlurPara(motionBlurOption.radius, anchor);
4235 }
4236 
UpdateBackBlur(const Dimension & radius,const BlurOption & blurOption,const SysOptions & sysOptions)4237 void RosenRenderContext::UpdateBackBlur(
4238     const Dimension& radius, const BlurOption& blurOption, const SysOptions& sysOptions)
4239 {
4240     CHECK_NULL_VOID(rsNode_);
4241     const auto& groupProperty = GetOrCreateBackground();
4242     if (groupProperty->CheckBlurRadiusChanged(radius) && groupProperty->CheckSystemAdaptationSame(sysOptions)) {
4243         // Same with previous value
4244         return;
4245     }
4246     groupProperty->propBlurRadius = radius;
4247     groupProperty->propSysOptions = sysOptions;
4248     SetBackBlurFilter();
4249     if (blurOption.grayscale.size() > 1) {
4250         Rosen::Vector2f grayScale(blurOption.grayscale[0], blurOption.grayscale[0]);
4251         rsNode_->SetGreyCoef(grayScale);
4252     }
4253 }
4254 
UpdateNodeBackBlur(const Dimension & radius,const BlurOption & blurOption)4255 void RosenRenderContext::UpdateNodeBackBlur(const Dimension& radius, const BlurOption& blurOption)
4256 {
4257     CHECK_NULL_VOID(rsNode_);
4258     const auto& groupProperty = GetOrCreateBackground();
4259     groupProperty->propBackdropBlurOption = blurOption;
4260     if (groupProperty->CheckBlurRadiusChanged(radius) && groupProperty->CheckBlurOptionChanged(blurOption)) {
4261         // Same with previous value
4262         return;
4263     }
4264     groupProperty->propBlurRadius = radius;
4265     SetBackBlurFilter();
4266     if (blurOption.grayscale.size() > 1) {
4267         Rosen::Vector2f grayScale(blurOption.grayscale[0], blurOption.grayscale[1]);
4268         rsNode_->SetGreyCoef(grayScale);
4269     }
4270 }
4271 
UpdateFrontBlurRadius(const Dimension & radius)4272 void RosenRenderContext::UpdateFrontBlurRadius(const Dimension& radius)
4273 {
4274     const auto& groupProperty = GetOrCreateForeground();
4275     if (groupProperty->CheckBlurRadiusChanged(radius)) {
4276         // Same with previous value
4277         return;
4278     }
4279     groupProperty->propBlurRadius = radius;
4280     SetFrontBlurFilter();
4281 }
4282 
UpdateFrontBlur(const Dimension & radius,const BlurOption & blurOption,const SysOptions & sysOptions)4283 void RosenRenderContext::UpdateFrontBlur(
4284     const Dimension& radius, const BlurOption& blurOption, const SysOptions& sysOptions)
4285 {
4286     CHECK_NULL_VOID(rsNode_);
4287     const auto& groupProperty = GetOrCreateForeground();
4288     if (groupProperty->CheckBlurRadiusChanged(radius) && groupProperty->CheckSysOptionsForBlurSame(sysOptions)) {
4289         // Same with previous value
4290         return;
4291     }
4292     groupProperty->propBlurRadius = radius;
4293     groupProperty->propSysOptionsForBlur = sysOptions;
4294     SetFrontBlurFilter();
4295     if (blurOption.grayscale.size() > 1) {
4296         Rosen::Vector2f grayScale(blurOption.grayscale[0], blurOption.grayscale[1]);
4297         rsNode_->SetGreyCoef(grayScale);
4298     }
4299 }
4300 
ToShadowColorStrategy(ShadowColorStrategy shadowColorStrategy)4301 Rosen::SHADOW_COLOR_STRATEGY RosenRenderContext::ToShadowColorStrategy(ShadowColorStrategy shadowColorStrategy)
4302 {
4303     if (shadowColorStrategy == ShadowColorStrategy::NONE) {
4304         return Rosen::SHADOW_COLOR_STRATEGY::COLOR_STRATEGY_NONE;
4305     } else if (shadowColorStrategy == ShadowColorStrategy::AVERAGE) {
4306         return Rosen::SHADOW_COLOR_STRATEGY::COLOR_STRATEGY_AVERAGE;
4307     } else if (shadowColorStrategy == ShadowColorStrategy::PRIMARY) {
4308         return Rosen::SHADOW_COLOR_STRATEGY::COLOR_STRATEGY_MAIN;
4309     } else {
4310         return Rosen::SHADOW_COLOR_STRATEGY::COLOR_STRATEGY_NONE;
4311     }
4312 }
4313 
OnBackShadowUpdate(const Shadow & shadow)4314 void RosenRenderContext::OnBackShadowUpdate(const Shadow& shadow)
4315 {
4316     CHECK_NULL_VOID(rsNode_);
4317     if (!shadow.IsValid()) {
4318         if (shadow.GetHardwareAcceleration()) {
4319             rsNode_->SetShadowElevation(0.0);
4320         } else {
4321             rsNode_->SetShadowRadius(0.0);
4322         }
4323         RequestNextFrame();
4324         return;
4325     }
4326     rsNode_->SetShadowColor(shadow.GetColor().GetValue());
4327     rsNode_->SetShadowOffsetX(shadow.GetOffset().GetX());
4328     rsNode_->SetShadowOffsetY(shadow.GetOffset().GetY());
4329     rsNode_->SetShadowMask(shadow.GetShadowType() == ShadowType::BLUR);
4330     rsNode_->SetShadowIsFilled(shadow.GetIsFilled());
4331     rsNode_->SetShadowColorStrategy(ToShadowColorStrategy(shadow.GetShadowColorStrategy()));
4332     if (shadow.GetHardwareAcceleration()) {
4333         rsNode_->SetShadowElevation(shadow.GetElevation());
4334     } else {
4335         rsNode_->SetShadowRadius(DrawingDecorationPainter::ConvertRadiusToSigma(shadow.GetBlurRadius()));
4336     }
4337     RequestNextFrame();
4338 }
4339 
OnBackBlendModeUpdate(BlendMode blendMode)4340 void RosenRenderContext::OnBackBlendModeUpdate(BlendMode blendMode)
4341 {
4342     CHECK_NULL_VOID(rsNode_);
4343     if (blendMode == BlendMode::BACK_COMPAT_SOURCE_IN) {
4344         rsNode_->SetBackgroundShader(nullptr);
4345         rsNode_->SetColorBlendMode(Rosen::RSColorBlendMode::NONE);
4346     } else {
4347         auto rsBlendMode = static_cast<Rosen::RSColorBlendMode>(blendMode);
4348         rsNode_->SetColorBlendMode(rsBlendMode);
4349     }
4350     RequestNextFrame();
4351 }
4352 
OnBackBlendApplyTypeUpdate(BlendApplyType blendApplyType)4353 void RosenRenderContext::OnBackBlendApplyTypeUpdate(BlendApplyType blendApplyType)
4354 {
4355     CHECK_NULL_VOID(rsNode_);
4356     if (blendApplyType == BlendApplyType::FAST) {
4357         rsNode_->SetColorBlendApplyType(Rosen::RSColorBlendApplyType::FAST);
4358     } else if (Container::LessThanAPITargetVersion(PlatformVersion::VERSION_EIGHTEEN)) {
4359         rsNode_->SetColorBlendApplyType(Rosen::RSColorBlendApplyType::SAVE_LAYER_ALPHA);
4360     } else {
4361         rsNode_->SetColorBlendApplyType(Rosen::RSColorBlendApplyType::SAVE_LAYER);
4362     }
4363     RequestNextFrame();
4364 }
4365 
UpdateBrightnessBlender(const OHOS::Rosen::BrightnessBlender * brightnessBlender)4366 void RosenRenderContext::UpdateBrightnessBlender(const OHOS::Rosen::BrightnessBlender* brightnessBlender)
4367 {
4368     CHECK_NULL_VOID(rsNode_);
4369     CHECK_NULL_VOID(brightnessBlender);
4370     rsNode_->SetBlender(brightnessBlender);
4371     RequestNextFrame();
4372 }
4373 
4374 // called when frameNode size changes
PaintGraphics()4375 void RosenRenderContext::PaintGraphics()
4376 {
4377     CHECK_NULL_VOID(rsNode_);
4378     auto&& graphicProps = GetOrCreateGraphics();
4379 
4380     if (!graphics_) {
4381         graphics_ = std::make_unique<GraphicModifiers>();
4382     }
4383     if (graphicProps->HasFrontGrayScale()) {
4384         auto grayScale = graphicProps->GetFrontGrayScaleValue();
4385         OnFrontGrayScaleUpdate(grayScale);
4386     }
4387 
4388     if (graphicProps->HasFrontBrightness()) {
4389         auto brightness = graphicProps->GetFrontBrightnessValue();
4390         OnFrontBrightnessUpdate(brightness);
4391     }
4392 
4393     if (graphicProps->HasFrontContrast()) {
4394         auto contrast = graphicProps->GetFrontContrastValue();
4395         OnFrontContrastUpdate(contrast);
4396     }
4397 
4398     if (graphicProps->HasFrontSaturate()) {
4399         auto saturate = graphicProps->GetFrontSaturateValue();
4400         OnFrontSaturateUpdate(saturate);
4401     }
4402 
4403     if (graphicProps->HasFrontSepia()) {
4404         auto sepia = graphicProps->GetFrontSepiaValue();
4405         OnFrontSepiaUpdate(sepia);
4406     }
4407 
4408     if (graphicProps->HasFrontInvert()) {
4409         auto invert = graphicProps->GetFrontInvertValue();
4410         OnFrontInvertUpdate(invert);
4411     }
4412 
4413     if (graphicProps->HasFrontHueRotate()) {
4414         auto hueRotate = graphicProps->GetFrontHueRotateValue();
4415         OnFrontHueRotateUpdate(hueRotate);
4416     }
4417 
4418     if (graphicProps->HasFrontColorBlend()) {
4419         auto colorBlend = graphicProps->GetFrontColorBlendValue();
4420         OnFrontColorBlendUpdate(colorBlend);
4421     }
4422 }
4423 
4424 // helper function to check if frame react is valid
RectIsNull()4425 bool RosenRenderContext::RectIsNull()
4426 {
4427     RectF rect = GetPaintRectWithoutTransform();
4428     return NearZero(rect.Width()) || NearZero(rect.Height());
4429 }
4430 
4431 template<typename T, typename D>
SetGraphicModifier(std::shared_ptr<T> & modifier,D data)4432 void RosenRenderContext::SetGraphicModifier(std::shared_ptr<T>& modifier, D data)
4433 {
4434     CHECK_NULL_VOID(rsNode_);
4435     if (!modifier) {
4436         modifier = std::make_shared<T>();
4437         rsNode_->AddModifier(modifier);
4438     }
4439     modifier->SetCustomData(data);
4440 
4441     auto borderRadius = GetBorderRadius();
4442     if (borderRadius.has_value()) {
4443         Rosen::Vector4f rsRadius;
4444         ConvertRadius(*borderRadius, rsRadius);
4445         modifier->SetCornerRadius(rsRadius);
4446     }
4447 }
4448 
AddModifier(const std::shared_ptr<Rosen::RSModifier> & modifier)4449 void RosenRenderContext::AddModifier(const std::shared_ptr<Rosen::RSModifier>& modifier)
4450 {
4451     CHECK_NULL_VOID(modifier);
4452     CHECK_NULL_VOID(rsNode_);
4453     rsNode_->AddModifier(modifier);
4454 }
4455 
RemoveModifier(const std::shared_ptr<Rosen::RSModifier> & modifier)4456 void RosenRenderContext::RemoveModifier(const std::shared_ptr<Rosen::RSModifier>& modifier)
4457 {
4458     CHECK_NULL_VOID(modifier);
4459     CHECK_NULL_VOID(rsNode_);
4460     rsNode_->RemoveModifier(modifier);
4461 }
4462 
4463 // helper function to update one of the graphic effects
4464 template<typename T, typename D>
UpdateGraphic(std::shared_ptr<T> & modifier,D data)4465 void RosenRenderContext::UpdateGraphic(std::shared_ptr<T>& modifier, D data)
4466 {
4467     CHECK_NULL_VOID(!RectIsNull());
4468     SetGraphicModifier(modifier, data);
4469     RequestNextFrame();
4470 }
4471 
OnFrontBrightnessUpdate(const Dimension & brightness)4472 void RosenRenderContext::OnFrontBrightnessUpdate(const Dimension& brightness)
4473 {
4474     CHECK_NULL_VOID(rsNode_);
4475     rsNode_->SetBrightness(brightness.Value());
4476     RequestNextFrame();
4477 }
4478 
OnFrontGrayScaleUpdate(const Dimension & grayScale)4479 void RosenRenderContext::OnFrontGrayScaleUpdate(const Dimension& grayScale)
4480 {
4481     CHECK_NULL_VOID(rsNode_);
4482     rsNode_->SetGrayScale(grayScale.Value());
4483     RequestNextFrame();
4484 }
4485 
OnFrontContrastUpdate(const Dimension & contrast)4486 void RosenRenderContext::OnFrontContrastUpdate(const Dimension& contrast)
4487 {
4488     CHECK_NULL_VOID(rsNode_);
4489     rsNode_->SetContrast(contrast.Value());
4490     RequestNextFrame();
4491 }
4492 
OnFrontSaturateUpdate(const Dimension & saturate)4493 void RosenRenderContext::OnFrontSaturateUpdate(const Dimension& saturate)
4494 {
4495     CHECK_NULL_VOID(rsNode_);
4496     rsNode_->SetSaturate(saturate.Value());
4497     RequestNextFrame();
4498 }
4499 
OnFrontSepiaUpdate(const Dimension & sepia)4500 void RosenRenderContext::OnFrontSepiaUpdate(const Dimension& sepia)
4501 {
4502     CHECK_NULL_VOID(rsNode_);
4503     rsNode_->SetSepia(sepia.Value());
4504     RequestNextFrame();
4505 }
4506 
OnFrontInvertUpdate(const InvertVariant & invert)4507 void RosenRenderContext::OnFrontInvertUpdate(const InvertVariant& invert)
4508 {
4509     CHECK_NULL_VOID(rsNode_);
4510     if (invert.index() == 0) {
4511         rsNode_->SetInvert(std::get<float>(invert));
4512     } else {
4513         InvertOption option = std::get<InvertOption>(invert);
4514         Rosen::Vector4f invertVector;
4515         invertVector.SetValues(option.low_, option.high_, option.threshold_, option.thresholdRange_);
4516         rsNode_->SetAiInvert(invertVector);
4517     }
4518     RequestNextFrame();
4519 }
4520 
OnSystemBarEffectUpdate(bool systemBarEffect)4521 void RosenRenderContext::OnSystemBarEffectUpdate(bool systemBarEffect)
4522 {
4523     CHECK_NULL_VOID(rsNode_);
4524     rsNode_->SetSystemBarEffect();
4525     RequestNextFrame();
4526 }
4527 
OnFrontHueRotateUpdate(float hueRotate)4528 void RosenRenderContext::OnFrontHueRotateUpdate(float hueRotate)
4529 {
4530     CHECK_NULL_VOID(rsNode_);
4531     rsNode_->SetHueRotate(hueRotate);
4532     RequestNextFrame();
4533 }
4534 
OnFrontColorBlendUpdate(const Color & colorBlend)4535 void RosenRenderContext::OnFrontColorBlendUpdate(const Color& colorBlend)
4536 {
4537     CHECK_NULL_VOID(rsNode_);
4538     rsNode_->SetColorBlend(colorBlend.GetValue());
4539     RequestNextFrame();
4540 }
4541 
OnLinearGradientBlurUpdate(const NG::LinearGradientBlurPara & blurPara)4542 void RosenRenderContext::OnLinearGradientBlurUpdate(const NG::LinearGradientBlurPara& blurPara)
4543 {
4544     float blurRadius = 0.0f;
4545     if (blurPara.blurRadius_.IsValid()) {
4546         float radiusPx = blurPara.blurRadius_.ConvertToPx();
4547         blurRadius = radiusPx;
4548     }
4549 
4550     CHECK_NULL_VOID(rsNode_);
4551     std::shared_ptr<Rosen::RSLinearGradientBlurPara> rsLinearGradientBlurPara(
4552         std::make_shared<Rosen::RSLinearGradientBlurPara>(
4553             blurRadius, blurPara.fractionStops_, static_cast<Rosen::GradientDirection>(blurPara.direction_)));
4554 
4555     rsNode_->SetLinearGradientBlurPara(rsLinearGradientBlurPara);
4556     RequestNextFrame();
4557 }
4558 
OnMagnifierUpdate(const MagnifierParams & magnifierParams)4559 void RosenRenderContext::OnMagnifierUpdate(const MagnifierParams& magnifierParams)
4560 {
4561     CHECK_NULL_VOID(rsNode_);
4562     std::shared_ptr<Rosen::RSMagnifierParams> rsMagnifierParams(std::make_shared<Rosen::RSMagnifierParams>());
4563     rsMagnifierParams->factor_ = magnifierParams.factor_;
4564     rsMagnifierParams->width_ = magnifierParams.width_;
4565     rsMagnifierParams->height_ = magnifierParams.height_;
4566     rsMagnifierParams->borderWidth_ = magnifierParams.borderWidth_;
4567     rsMagnifierParams->cornerRadius_ = magnifierParams.cornerRadius_;
4568     rsMagnifierParams->offsetX_ = magnifierParams.offsetX_;
4569     rsMagnifierParams->offsetY_ = magnifierParams.offsetY_;
4570     rsMagnifierParams->shadowOffsetX_ = magnifierParams.shadowOffsetX_;
4571     rsMagnifierParams->shadowOffsetY_ = magnifierParams.shadowOffsetY_;
4572     rsMagnifierParams->shadowSize_ = magnifierParams.shadowSize_;
4573     rsMagnifierParams->shadowStrength_ = magnifierParams.shadowStrength_;
4574     rsMagnifierParams->gradientMaskColor1_ = magnifierParams.gradientMaskColor1_;
4575     rsMagnifierParams->gradientMaskColor2_ = magnifierParams.gradientMaskColor2_;
4576     rsMagnifierParams->outerContourColor1_ = magnifierParams.outerContourColor1_;
4577     rsMagnifierParams->outerContourColor2_ = magnifierParams.outerContourColor2_;
4578     rsNode_->SetMagnifierParams(rsMagnifierParams);
4579     RequestNextFrame();
4580 }
OnDynamicDimDegreeUpdate(const float degree)4581 void RosenRenderContext::OnDynamicDimDegreeUpdate(const float degree)
4582 {
4583     CHECK_NULL_VOID(rsNode_);
4584     rsNode_->SetDynamicDimDegree(degree);
4585     RequestNextFrame();
4586 }
4587 
OnDynamicLightUpRateUpdate(const float rate)4588 void RosenRenderContext::OnDynamicLightUpRateUpdate(const float rate)
4589 {
4590     CHECK_NULL_VOID(rsNode_);
4591     rsNode_->SetDynamicLightUpRate(rate);
4592     RequestNextFrame();
4593 }
4594 
OnDynamicLightUpDegreeUpdate(const float degree)4595 void RosenRenderContext::OnDynamicLightUpDegreeUpdate(const float degree)
4596 {
4597     CHECK_NULL_VOID(rsNode_);
4598     rsNode_->SetDynamicLightUpDegree(degree);
4599     RequestNextFrame();
4600 }
4601 
OnBgDynamicBrightnessOptionUpdate(const std::optional<BrightnessOption> & brightnessOption)4602 void RosenRenderContext::OnBgDynamicBrightnessOptionUpdate(const std::optional<BrightnessOption>& brightnessOption)
4603 {
4604     if (!brightnessOption.has_value()) {
4605         return;
4606     }
4607     CHECK_NULL_VOID(rsNode_);
4608     rsNode_->SetBgBrightnessParams({ brightnessOption->rate, brightnessOption->lightUpDegree,
4609         brightnessOption->cubicCoeff, brightnessOption->quadCoeff, brightnessOption->saturation,
4610         { brightnessOption->posRGB[0], brightnessOption->posRGB[1], brightnessOption->posRGB[2] },
4611         { brightnessOption->negRGB[0], brightnessOption->negRGB[1], brightnessOption->negRGB[2] } });
4612     rsNode_->SetBgBrightnessFract(brightnessOption->fraction);
4613     RequestNextFrame();
4614 }
4615 
OnFgDynamicBrightnessOptionUpdate(const std::optional<BrightnessOption> & brightnessOption)4616 void RosenRenderContext::OnFgDynamicBrightnessOptionUpdate(const std::optional<BrightnessOption>& brightnessOption)
4617 {
4618     if (!brightnessOption.has_value()) {
4619         return;
4620     }
4621     CHECK_NULL_VOID(rsNode_);
4622     rsNode_->SetFgBrightnessParams({ brightnessOption->rate, brightnessOption->lightUpDegree,
4623         brightnessOption->cubicCoeff, brightnessOption->quadCoeff, brightnessOption->saturation,
4624         { brightnessOption->posRGB[0], brightnessOption->posRGB[1], brightnessOption->posRGB[2] },
4625         { brightnessOption->negRGB[0], brightnessOption->negRGB[1], brightnessOption->negRGB[2] } });
4626     rsNode_->SetFgBrightnessFract(brightnessOption->fraction);
4627     RequestNextFrame();
4628 }
4629 
UpdateTransition(const TransitionOptions & options)4630 void RosenRenderContext::UpdateTransition(const TransitionOptions& options)
4631 {
4632     CHECK_NULL_VOID(rsNode_);
4633     if (options.Type == TransitionType::ALL || options.Type == TransitionType::APPEARING) {
4634         if (!propTransitionAppearing_) {
4635             propTransitionAppearing_ = std::make_unique<TransitionOptions>(options);
4636         } else {
4637             *propTransitionAppearing_ = options;
4638         }
4639         propTransitionAppearing_->Type = TransitionType::APPEARING;
4640     }
4641     if (options.Type == TransitionType::ALL || options.Type == TransitionType::DISAPPEARING) {
4642         if (!propTransitionDisappearing_) {
4643             propTransitionDisappearing_ = std::make_unique<TransitionOptions>(options);
4644         } else {
4645             *propTransitionDisappearing_ = options;
4646         }
4647         propTransitionDisappearing_->Type = TransitionType::DISAPPEARING;
4648     }
4649     NotifyHostTransformUpdated();
4650 }
4651 
CleanTransition()4652 void RosenRenderContext::CleanTransition()
4653 {
4654     propTransitionDisappearing_.reset();
4655     propTransitionDisappearing_.reset();
4656 }
4657 
GetRSTransitionWithoutType(const std::unique_ptr<TransitionOptions> & options,const SizeF & frameSize)4658 std::shared_ptr<Rosen::RSTransitionEffect> RosenRenderContext::GetRSTransitionWithoutType(
4659     const std::unique_ptr<TransitionOptions>& options, const SizeF& frameSize)
4660 {
4661     if (options == nullptr) {
4662         return nullptr;
4663     }
4664     std::shared_ptr<Rosen::RSTransitionEffect> effect = Rosen::RSTransitionEffect::Create();
4665     if (options->HasOpacity()) {
4666         effect = effect->Opacity(options->GetOpacityValue());
4667     }
4668     if (options->HasTranslate()) {
4669         const auto& translate = options->GetTranslateValue();
4670         effect = effect->Translate({ static_cast<float>(translate.x.ConvertToPxWithSize(frameSize.Width())),
4671             static_cast<float>(translate.y.ConvertToPxWithSize(frameSize.Height())),
4672             static_cast<float>(translate.z.ConvertToPx()) });
4673     }
4674     if (options->HasScale()) {
4675         const auto& scale = options->GetScaleValue();
4676         effect = effect->Scale({ scale.xScale, scale.yScale, scale.zScale });
4677     }
4678     if (options->HasRotate()) {
4679         const auto& rotate = options->GetRotateValue();
4680         effect = effect->Rotate({ rotate.xDirection, rotate.yDirection, rotate.zDirection, rotate.angle });
4681     }
4682     return effect;
4683 }
4684 
SetBackgroundShader(const std::shared_ptr<Rosen::RSShader> & shader)4685 void RosenRenderContext::SetBackgroundShader(const std::shared_ptr<Rosen::RSShader>& shader)
4686 {
4687     CHECK_NULL_VOID(rsNode_);
4688     // temporary code for back compat
4689     auto& graphicProps = GetOrCreateGraphics();
4690     if (graphicProps->GetBackBlendMode() == BlendMode::BACK_COMPAT_SOURCE_IN) {
4691         rsNode_->SetBackgroundShader(nullptr);
4692         return;
4693     }
4694     rsNode_->SetBackgroundShader(shader);
4695 }
4696 
PaintGradient(const SizeF & frameSize)4697 void RosenRenderContext::PaintGradient(const SizeF& frameSize)
4698 {
4699     CHECK_NULL_VOID(rsNode_);
4700     auto& gradientProperty = GetOrCreateGradient();
4701     Gradient gradient;
4702     if (gradientProperty->HasLastGradientType()) {
4703         switch (gradientProperty->GetLastGradientTypeValue()) {
4704             case GradientType::LINEAR:
4705                 gradient = gradientProperty->GetLinearGradientValue();
4706                 break;
4707             case GradientType::RADIAL:
4708                 gradient = gradientProperty->GetRadialGradientValue();
4709                 break;
4710             case GradientType::SWEEP:
4711                 gradient = gradientProperty->GetSweepGradientValue();
4712                 break;
4713             default:
4714                 return;
4715         }
4716     } else {
4717         if (gradientProperty->HasLinearGradient()) {
4718             gradient = gradientProperty->GetLinearGradientValue();
4719         }
4720         if (gradientProperty->HasRadialGradient()) {
4721             gradient = gradientProperty->GetRadialGradientValue();
4722         }
4723         if (gradientProperty->HasSweepGradient()) {
4724             gradient = gradientProperty->GetSweepGradientValue();
4725         }
4726     }
4727     if (!gradientStyleModifier_) {
4728         gradientStyleModifier_ = std::make_shared<GradientStyleModifier>(WeakClaim(this));
4729         rsNode_->AddModifier(gradientStyleModifier_);
4730     }
4731     gradientStyleModifier_->SetGradient(gradient);
4732     gradientStyleModifier_->SetSizeF(frameSize);
4733 }
4734 
OnLinearGradientUpdate(const NG::Gradient & gradient)4735 void RosenRenderContext::OnLinearGradientUpdate(const NG::Gradient& gradient)
4736 {
4737     RectF rect = GetPaintRectWithoutTransform();
4738     if (!RectIsNull()) {
4739         PaintGradient(rect.GetSize());
4740     }
4741     RequestNextFrame();
4742 }
4743 
OnRadialGradientUpdate(const NG::Gradient & gradient)4744 void RosenRenderContext::OnRadialGradientUpdate(const NG::Gradient& gradient)
4745 {
4746     RectF rect = GetPaintRectWithoutTransform();
4747     if (!RectIsNull()) {
4748         PaintGradient(rect.GetSize());
4749     }
4750     RequestNextFrame();
4751 }
4752 
OnSweepGradientUpdate(const NG::Gradient & gradient)4753 void RosenRenderContext::OnSweepGradientUpdate(const NG::Gradient& gradient)
4754 {
4755     RectF rect = GetPaintRectWithoutTransform();
4756     if (!RectIsNull()) {
4757         PaintGradient(rect.GetSize());
4758     }
4759     RequestNextFrame();
4760 }
4761 
PaintClipShape(const std::unique_ptr<ClipProperty> & clip,const SizeF & frameSize)4762 void RosenRenderContext::PaintClipShape(const std::unique_ptr<ClipProperty>& clip, const SizeF& frameSize)
4763 {
4764     CHECK_NULL_VOID(rsNode_);
4765     auto basicShape = clip->GetClipShapeValue();
4766     auto rsPath = DrawingDecorationPainter::DrawingCreatePath(basicShape, frameSize);
4767     auto shapePath = Rosen::RSPath::CreateRSPath(rsPath);
4768     if (!clipBoundModifier_) {
4769         auto prop = std::make_shared<RSProperty<std::shared_ptr<Rosen::RSPath>>>(shapePath);
4770         clipBoundModifier_ = std::make_shared<Rosen::RSClipBoundsModifier>(prop);
4771         rsNode_->AddModifier(clipBoundModifier_);
4772     } else {
4773         auto property =
4774             std::static_pointer_cast<RSProperty<std::shared_ptr<Rosen::RSPath>>>(clipBoundModifier_->GetProperty());
4775         property->Set(shapePath);
4776     }
4777 }
4778 
PaintClipMask(const std::unique_ptr<ClipProperty> & clip,const SizeF & frameSize)4779 void RosenRenderContext::PaintClipMask(const std::unique_ptr<ClipProperty>& clip, const SizeF& frameSize)
4780 {
4781     CHECK_NULL_VOID(rsNode_);
4782     auto basicShape = clip->GetClipMaskValue();
4783     auto rsPath = DrawingDecorationPainter::DrawingCreatePath(basicShape, frameSize);
4784 
4785     RSColor rsStrokeColor;
4786     rsStrokeColor.SetColorQuad(basicShape->GetStrokeColor());
4787     RSPen pen;
4788     pen.SetColor(rsStrokeColor);
4789     pen.SetWidth(basicShape->GetStrokeWidth());
4790 
4791     auto maskPath =
4792         Rosen::RSMask::CreatePathMask(rsPath, pen, DrawingDecorationPainter::CreateMaskDrawingBrush(basicShape));
4793     if (!clipMaskModifier_) {
4794         auto prop = std::make_shared<RSProperty<std::shared_ptr<RSMask>>>(maskPath);
4795         clipMaskModifier_ = std::make_shared<Rosen::RSMaskModifier>(prop);
4796         rsNode_->AddModifier(clipMaskModifier_);
4797     } else {
4798         auto property = std::static_pointer_cast<RSProperty<std::shared_ptr<RSMask>>>(clipMaskModifier_->GetProperty());
4799         property->Set(maskPath);
4800     }
4801 }
4802 
PaintClip(const SizeF & frameSize)4803 void RosenRenderContext::PaintClip(const SizeF& frameSize)
4804 {
4805     CHECK_NULL_VOID(rsNode_);
4806     auto& clip = GetOrCreateClip();
4807     if (clip->HasClipShape()) {
4808         PaintClipShape(clip, frameSize);
4809     }
4810 
4811     if (clip->HasClipMask()) {
4812         PaintClipMask(clip, frameSize);
4813     }
4814 }
4815 
PaintProgressMask()4816 void RosenRenderContext::PaintProgressMask()
4817 {
4818     CHECK_NULL_VOID(rsNode_);
4819     if (!moonProgressModifier_) {
4820         auto host = GetHost();
4821         CHECK_NULL_VOID(host);
4822         moonProgressModifier_ = AceType::MakeRefPtr<MoonProgressModifier>(host);
4823         auto modifierAdapter =
4824             std::static_pointer_cast<OverlayModifierAdapter>(ConvertOverlayModifier(moonProgressModifier_));
4825         rsNode_->AddModifier(modifierAdapter);
4826         modifierAdapter->AttachProperties();
4827     }
4828     auto progress = GetProgressMaskValue();
4829     moonProgressModifier_->SetMaskColor(LinearColor(progress->GetColor()));
4830     moonProgressModifier_->SetMaxValue(progress->GetMaxValue());
4831     if (progress->GetValue() > moonProgressModifier_->GetMaxValue()) {
4832         progress->SetValue(moonProgressModifier_->GetMaxValue());
4833     }
4834     moonProgressModifier_->SetValue(progress->GetValue());
4835     moonProgressModifier_->SetEnableBreathe(progress->GetEnableBreathe());
4836 }
4837 
SetClipBoundsWithCommands(const std::string & commands)4838 void RosenRenderContext::SetClipBoundsWithCommands(const std::string& commands)
4839 {
4840     CHECK_NULL_VOID(rsNode_);
4841     RSRecordingPath rsPath;
4842     rsPath.BuildFromSVGString(commands);
4843     rsNode_->SetClipBounds(Rosen::RSPath::CreateRSPath(rsPath));
4844 }
4845 
ClipWithRect(const RectF & rectF)4846 void RosenRenderContext::ClipWithRect(const RectF& rectF)
4847 {
4848     CHECK_NULL_VOID(rsNode_);
4849     RSRecordingPath rsPath;
4850     rsPath.AddRect({ rectF.GetX(), rectF.GetY(), rectF.GetX() + rectF.Width(), rectF.GetY() + rectF.Height() });
4851     rsNode_->SetClipBounds(Rosen::RSPath::CreateRSPath(rsPath));
4852 }
4853 
ClipWithRoundRect(const RoundRect & roundRect)4854 void RosenRenderContext::ClipWithRoundRect(const RoundRect& roundRect)
4855 {
4856     CHECK_NULL_VOID(rsNode_);
4857     RSRoundRect rsRoundRect;
4858 
4859     RSRect rsRect(roundRect.GetRect().Left(), roundRect.GetRect().Top(), roundRect.GetRect().Right(),
4860         roundRect.GetRect().Bottom());
4861     rsRoundRect.SetRect(rsRect);
4862 
4863     EdgeF edge = roundRect.GetCornerRadius(RoundRect::TOP_LEFT_POS);
4864     rsRoundRect.SetCornerRadius(RSRoundRect::TOP_LEFT_POS, edge.x, edge.y);
4865     edge = roundRect.GetCornerRadius(RoundRect::TOP_RIGHT_POS);
4866     rsRoundRect.SetCornerRadius(RSRoundRect::TOP_RIGHT_POS, edge.x, edge.y);
4867     edge = roundRect.GetCornerRadius(RoundRect::BOTTOM_LEFT_POS);
4868     rsRoundRect.SetCornerRadius(RSRoundRect::BOTTOM_LEFT_POS, edge.x, edge.y);
4869     edge = roundRect.GetCornerRadius(RoundRect::BOTTOM_RIGHT_POS);
4870     rsRoundRect.SetCornerRadius(RSRoundRect::BOTTOM_RIGHT_POS, edge.x, edge.y);
4871     RSRecordingPath rsPath;
4872     rsPath.AddRoundRect(rsRoundRect);
4873     rsNode_->SetClipBounds(Rosen::RSPath::CreateRSPath(rsPath));
4874 }
4875 
ClipWithOval(const RectF & rectF)4876 void RosenRenderContext::ClipWithOval(const RectF& rectF)
4877 {
4878     CHECK_NULL_VOID(rsNode_);
4879     RSRecordingPath rsPath;
4880     rsPath.AddOval({ rectF.GetX(), rectF.GetY(), rectF.GetX() + rectF.Width(), rectF.GetY() + rectF.Height() });
4881     rsNode_->SetClipBounds(Rosen::RSPath::CreateRSPath(rsPath));
4882 }
4883 
ClipWithCircle(const Circle & circle)4884 void RosenRenderContext::ClipWithCircle(const Circle& circle)
4885 {
4886     CHECK_NULL_VOID(rsNode_);
4887     RSRecordingPath rsPath;
4888     rsPath.AddCircle(circle.GetAxisX().Value(), circle.GetAxisY().Value(), circle.GetRadius().Value());
4889     rsNode_->SetClipBounds(Rosen::RSPath::CreateRSPath(rsPath));
4890 }
4891 
ClipWithRRect(const RectF & rectF,const RadiusF & radiusF)4892 void RosenRenderContext::ClipWithRRect(const RectF& rectF, const RadiusF& radiusF)
4893 {
4894     CHECK_NULL_VOID(rsNode_);
4895     Rosen::Vector4f rect;
4896     Rosen::Vector4f radius;
4897     rect.SetValues(rectF.GetX(), rectF.GetY(), rectF.GetX() + rectF.Width(), rectF.GetY() + rectF.Height());
4898     radius.SetValues(radiusF.GetCorner(RoundRect::CornerPos::TOP_LEFT_POS).x,
4899         radiusF.GetCorner(RoundRect::CornerPos::TOP_RIGHT_POS).x,
4900         radiusF.GetCorner(RoundRect::CornerPos::BOTTOM_LEFT_POS).x,
4901         radiusF.GetCorner(RoundRect::CornerPos::BOTTOM_RIGHT_POS).x);
4902     rsNode_->SetClipRRect(rect, radius);
4903     RequestNextFrame();
4904 }
4905 
SetContentClip(const std::variant<RectF,RefPtr<ShapeRect>> & rect)4906 void RosenRenderContext::SetContentClip(const std::variant<RectF, RefPtr<ShapeRect>>& rect)
4907 {
4908     CHECK_NULL_VOID(rsNode_);
4909     RectF rectF;
4910     if (std::holds_alternative<RectF>(rect)) {
4911         rectF = std::get<RectF>(rect);
4912         rsNode_->SetCustomClipToFrame(
4913             { rectF.GetX(), rectF.GetY(), rectF.GetX() + rectF.Width(), rectF.GetY() + rectF.Height() });
4914     } else {
4915         auto shape = std::get<RefPtr<ShapeRect>>(rect);
4916         CHECK_NULL_VOID(shape);
4917         using helper = DrawingDecorationPainter;
4918 
4919         const float x =
4920             helper::DrawingDimensionToPx(shape->GetOffset().GetX(), paintRect_.GetSize(), LengthMode::HORIZONTAL);
4921         const float y =
4922             helper::DrawingDimensionToPx(shape->GetOffset().GetY(), paintRect_.GetSize(), LengthMode::VERTICAL);
4923         const float width =
4924             helper::DrawingDimensionToPx(shape->GetWidth(), paintRect_.GetSize(), LengthMode::HORIZONTAL);
4925         const float height =
4926             helper::DrawingDimensionToPx(shape->GetHeight(), paintRect_.GetSize(), LengthMode::VERTICAL);
4927         rectF = RectF(x, y, width, height);
4928         rsNode_->SetCustomClipToFrame({ x, y, x + width, y + height });
4929     }
4930     if (!contentClip_ || rectF != *contentClip_) {
4931         contentClip_ = std::make_unique<RectF>(rectF);
4932         GetHost()->AddFrameNodeChangeInfoFlag(FRAME_NODE_CONTENT_CLIP_CHANGE);
4933     }
4934 }
4935 
RemoveClipWithRRect()4936 void RosenRenderContext::RemoveClipWithRRect()
4937 {
4938     std::weak_ptr<Rosen::RSNode> weakRsNode = rsNode_;
4939     AnimationUtils::ExecuteWithoutAnimation([weakRsNode]() {
4940         auto rsNode = weakRsNode.lock();
4941         CHECK_NULL_VOID(rsNode);
4942         rsNode->SetClipRRect(nullptr);
4943     });
4944     RequestNextFrame();
4945 }
4946 
OnClipShapeUpdate(const RefPtr<BasicShape> & basicShape)4947 void RosenRenderContext::OnClipShapeUpdate(const RefPtr<BasicShape>& basicShape)
4948 {
4949     CHECK_NULL_VOID(rsNode_);
4950     if (basicShape) {
4951         if (!RectIsNull()) {
4952             RectF rect = GetPaintRectWithoutTransform();
4953             PaintClipShape(GetOrCreateClip(), rect.GetSize());
4954         }
4955     } else if (clipBoundModifier_) {
4956         rsNode_->RemoveModifier(clipBoundModifier_);
4957         clipBoundModifier_ = nullptr;
4958     }
4959     RequestNextFrame();
4960 }
4961 
OnClipEdgeUpdate(bool isClip)4962 void RosenRenderContext::OnClipEdgeUpdate(bool isClip)
4963 {
4964     CHECK_NULL_VOID(rsNode_);
4965     if (isClip) {
4966         rsNode_->SetClipToBounds(true);
4967     } else {
4968         // In the internal implementation, some nodes call SetClipToBounds(true), some call SetClipToFrame(true).
4969         // If the developer set clip to false, we should disable all internal clips
4970         // so that the child component can go beyond the parent component
4971         rsNode_->SetClipToBounds(false);
4972         rsNode_->SetClipToFrame(false);
4973     }
4974     RequestNextFrame();
4975 }
4976 
OnClipMaskUpdate(const RefPtr<BasicShape> & basicShape)4977 void RosenRenderContext::OnClipMaskUpdate(const RefPtr<BasicShape>& basicShape)
4978 {
4979     CHECK_NULL_VOID(rsNode_);
4980     if (basicShape) {
4981         if (!RectIsNull()) {
4982             RectF rect = GetPaintRectWithoutTransform();
4983             PaintClipMask(GetOrCreateClip(), rect.GetSize());
4984         }
4985     } else if (clipMaskModifier_) {
4986         rsNode_->RemoveModifier(clipMaskModifier_);
4987         clipMaskModifier_ = nullptr;
4988     }
4989     RequestNextFrame();
4990 }
4991 
OnProgressMaskUpdate(const RefPtr<ProgressMaskProperty> & progress)4992 void RosenRenderContext::OnProgressMaskUpdate(const RefPtr<ProgressMaskProperty>& progress)
4993 {
4994     CHECK_NULL_VOID(rsNode_);
4995     if (progress) {
4996         if (!RectIsNull()) {
4997             PaintProgressMask();
4998         }
4999         rsNode_->SetClipToBounds(true);
5000     } else if (moonProgressModifier_) {
5001         auto modifierAdapter =
5002             std::static_pointer_cast<OverlayModifierAdapter>(ConvertOverlayModifier(moonProgressModifier_));
5003         rsNode_->RemoveModifier(modifierAdapter);
5004         moonProgressModifier_ = nullptr;
5005     }
5006     RequestNextFrame();
5007 }
5008 
PaintOverlayText()5009 void RosenRenderContext::PaintOverlayText()
5010 {
5011     CHECK_NULL_VOID(rsNode_);
5012     auto& overlay = GetOrCreateOverlay();
5013     if (overlay->HasOverlayText()) {
5014         auto overlayText = overlay->GetOverlayTextValue();
5015         auto paintRect = GetPaintRectWithTransform();
5016         std::shared_ptr<Rosen::RectF> overlayRect;
5017         if (modifier_) {
5018             modifier_->SetCustomData(NG::OverlayTextData(overlayText));
5019             auto overlayOffset = modifier_->GetOverlayOffset();
5020             auto paragraphSize = modifier_->GetParagraphSize(paintRect.Width());
5021             overlayRect = std::make_shared<Rosen::RectF>(overlayOffset.GetX(), overlayOffset.GetY(),
5022                 std::max(paragraphSize.Width(), paintRect.Width()),
5023                 std::max(paragraphSize.Height(), paintRect.Height()));
5024             rsNode_->SetIsCustomTextType(modifier_->IsCustomFont());
5025             UpdateDrawRegion(DRAW_REGION_OVERLAY_TEXT_MODIFIER_INDEX, overlayRect);
5026         } else {
5027             modifier_ = std::make_shared<OverlayTextModifier>();
5028             rsNode_->AddModifier(modifier_);
5029             modifier_->SetCustomData(NG::OverlayTextData(overlayText));
5030             auto overlayOffset = modifier_->GetOverlayOffset();
5031             auto paragraphSize = modifier_->GetParagraphSize(paintRect.Width());
5032             overlayRect = std::make_shared<Rosen::RectF>(overlayOffset.GetX(), overlayOffset.GetY(),
5033                 std::max(paragraphSize.Width(), paintRect.Width()),
5034                 std::max(paragraphSize.Height(), paintRect.Height()));
5035             rsNode_->SetIsCustomTextType(modifier_->IsCustomFont());
5036             UpdateDrawRegion(DRAW_REGION_OVERLAY_TEXT_MODIFIER_INDEX, overlayRect);
5037         }
5038     }
5039 }
5040 
OnOverlayTextUpdate(const OverlayOptions & overlay)5041 void RosenRenderContext::OnOverlayTextUpdate(const OverlayOptions& overlay)
5042 {
5043     if (!RectIsNull()) {
5044         PaintOverlayText();
5045     }
5046     RequestNextFrame();
5047 }
5048 
OnMotionPathUpdate(const MotionPathOption & motionPath)5049 void RosenRenderContext::OnMotionPathUpdate(const MotionPathOption& motionPath)
5050 {
5051     CHECK_NULL_VOID(rsNode_);
5052     if (!motionPath.IsValid()) {
5053         rsNode_->SetMotionPathOption(nullptr);
5054         return;
5055     }
5056     auto motionOption = Rosen::RSMotionPathOption(motionPath.GetPath());
5057     motionOption.SetBeginFraction(motionPath.GetBegin());
5058     motionOption.SetEndFraction(motionPath.GetEnd());
5059     motionOption.SetRotationMode(
5060         motionPath.GetRotate() ? Rosen::RotationMode::ROTATE_AUTO : Rosen::RotationMode::ROTATE_NONE);
5061     motionOption.SetPathNeedAddOrigin(HasOffset());
5062     rsNode_->SetMotionPathOption(std::make_shared<Rosen::RSMotionPathOption>(motionOption));
5063     RequestNextFrame();
5064 }
5065 
OnLightPositionUpdate(const TranslateOptions & translate)5066 void RosenRenderContext::OnLightPositionUpdate(const TranslateOptions& translate)
5067 {
5068     CHECK_NULL_VOID(rsNode_);
5069     float xValue = 0.0f;
5070     float yValue = 0.0f;
5071     if (translate.x.Unit() == DimensionUnit::PERCENT || translate.y.Unit() == DimensionUnit::PERCENT) {
5072         auto rect = GetPaintRectWithoutTransform();
5073         if (rect.IsEmpty()) {
5074             // size is not determined yet
5075             return;
5076         }
5077         xValue = translate.x.ConvertToPxWithSize(rect.Width());
5078         yValue = translate.y.ConvertToPxWithSize(rect.Height());
5079     } else {
5080         xValue = translate.x.ConvertToPx();
5081         yValue = translate.y.ConvertToPx();
5082     }
5083     // translateZ doesn't support percentage
5084     float zValue = translate.z.ConvertToPx();
5085     rsNode_->SetLightPosition(xValue, yValue, zValue);
5086     RequestNextFrame();
5087 }
5088 
OnLightIntensityUpdate(const float lightIntensity)5089 void RosenRenderContext::OnLightIntensityUpdate(const float lightIntensity)
5090 {
5091     CHECK_NULL_VOID(rsNode_);
5092     rsNode_->SetLightIntensity(lightIntensity);
5093     RequestNextFrame();
5094 }
5095 
OnLightColorUpdate(const Color & lightColor)5096 void RosenRenderContext::OnLightColorUpdate(const Color& lightColor)
5097 {
5098     CHECK_NULL_VOID(rsNode_);
5099     rsNode_->SetLightColor(lightColor.GetValue());
5100     RequestNextFrame();
5101 }
5102 
OnLightIlluminatedUpdate(const uint32_t lightIlluminated)5103 void RosenRenderContext::OnLightIlluminatedUpdate(const uint32_t lightIlluminated)
5104 {
5105     CHECK_NULL_VOID(rsNode_);
5106     rsNode_->SetIlluminatedType(lightIlluminated);
5107     RequestNextFrame();
5108 }
5109 
OnIlluminatedBorderWidthUpdate(const Dimension & illuminatedBorderWidth)5110 void RosenRenderContext::OnIlluminatedBorderWidthUpdate(const Dimension& illuminatedBorderWidth)
5111 {
5112     CHECK_NULL_VOID(rsNode_);
5113     rsNode_->SetIlluminatedBorderWidth(static_cast<float>(illuminatedBorderWidth.ConvertToPx()));
5114     RequestNextFrame();
5115 }
5116 
OnBloomUpdate(const float bloomIntensity)5117 void RosenRenderContext::OnBloomUpdate(const float bloomIntensity)
5118 {
5119     CHECK_NULL_VOID(rsNode_);
5120     rsNode_->SetBloom(bloomIntensity);
5121     RequestNextFrame();
5122 }
5123 
SetSharedTranslate(float xTranslate,float yTranslate)5124 void RosenRenderContext::SetSharedTranslate(float xTranslate, float yTranslate)
5125 {
5126     if (!sharedTransitionModifier_) {
5127         sharedTransitionModifier_ = std::make_unique<SharedTransitionModifier>();
5128     }
5129     AddOrChangeTranslateModifier(rsNode_, sharedTransitionModifier_->translateXY,
5130         sharedTransitionModifier_->translateXYValue, { xTranslate, yTranslate });
5131     NotifyHostTransformUpdated();
5132 }
5133 
ResetSharedTranslate()5134 void RosenRenderContext::ResetSharedTranslate()
5135 {
5136     CHECK_NULL_VOID(sharedTransitionModifier_);
5137     CHECK_NULL_VOID(sharedTransitionModifier_->translateXY);
5138     CHECK_NULL_VOID(rsNode_);
5139     rsNode_->RemoveModifier(sharedTransitionModifier_->translateXY);
5140     sharedTransitionModifier_->translateXYValue = nullptr;
5141     sharedTransitionModifier_->translateXY = nullptr;
5142     NotifyHostTransformUpdated();
5143 }
5144 
AddChild(const RefPtr<RenderContext> & renderContext,int index)5145 void RosenRenderContext::AddChild(const RefPtr<RenderContext>& renderContext, int index)
5146 {
5147     CHECK_NULL_VOID(rsNode_);
5148     auto rosenRenderContext = AceType::DynamicCast<RosenRenderContext>(renderContext);
5149     CHECK_NULL_VOID(rosenRenderContext);
5150     auto child = rosenRenderContext->GetRSNode();
5151     rsNode_->AddChild(child, index);
5152 }
5153 
RemoveChild(const RefPtr<RenderContext> & renderContext)5154 void RosenRenderContext::RemoveChild(const RefPtr<RenderContext>& renderContext)
5155 {
5156     CHECK_NULL_VOID(rsNode_);
5157     auto rosenRenderContext = AceType::DynamicCast<RosenRenderContext>(renderContext);
5158     CHECK_NULL_VOID(rosenRenderContext);
5159     auto child = rosenRenderContext->GetRSNode();
5160     rsNode_->RemoveChild(child);
5161 }
5162 
ClearChildren()5163 void RosenRenderContext::ClearChildren()
5164 {
5165     CHECK_NULL_VOID(rsNode_);
5166     rsNode_->ClearChildren();
5167 }
5168 
SetBounds(float positionX,float positionY,float width,float height)5169 void RosenRenderContext::SetBounds(float positionX, float positionY, float width, float height)
5170 {
5171     CHECK_NULL_VOID(rsNode_);
5172     paintRect_ = RectF(positionX, positionY, width, height);
5173     rsNode_->SetBounds(positionX, positionY, width, height);
5174 }
5175 
SetUsingContentRectForRenderFrame(bool value,bool adjustRSFrameByContentRect)5176 void RosenRenderContext::SetUsingContentRectForRenderFrame(bool value, bool adjustRSFrameByContentRect)
5177 {
5178     useContentRectForRSFrame_ = value;
5179     adjustRSFrameByContentRect_ = adjustRSFrameByContentRect;
5180 }
5181 
SetSecurityLayer(bool isSecure)5182 void RosenRenderContext::SetSecurityLayer(bool isSecure)
5183 {
5184     CHECK_NULL_VOID(rsNode_);
5185     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5186     CHECK_NULL_VOID(rsSurfaceNode);
5187     rsSurfaceNode->SetSecurityLayer(isSecure);
5188 }
5189 
SetHDRBrightness(float hdrBrightness)5190 void RosenRenderContext::SetHDRBrightness(float hdrBrightness)
5191 {
5192     CHECK_NULL_VOID(rsNode_);
5193     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5194     CHECK_NULL_VOID(rsSurfaceNode);
5195     rsSurfaceNode->SetHDRBrightness(hdrBrightness);
5196 }
5197 
SetTransparentLayer(bool isTransparentLayer)5198 void RosenRenderContext::SetTransparentLayer(bool isTransparentLayer)
5199 {
5200     CHECK_NULL_VOID(rsNode_);
5201     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5202     CHECK_NULL_VOID(rsSurfaceNode);
5203     rsSurfaceNode->SetHardwareEnableHint(isTransparentLayer);
5204 }
5205 
SetScreenId(uint64_t screenId)5206 void RosenRenderContext::SetScreenId(uint64_t screenId)
5207 {
5208     CHECK_NULL_VOID(rsNode_);
5209     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5210     CHECK_NULL_VOID(rsSurfaceNode);
5211     rsSurfaceNode->SetSourceVirtualDisplayId(screenId);
5212 }
5213 
SetFrameGravity(OHOS::Rosen::Gravity gravity)5214 void RosenRenderContext::SetFrameGravity(OHOS::Rosen::Gravity gravity)
5215 {
5216     CHECK_NULL_VOID(rsNode_);
5217     rsNode_->SetFrameGravity(gravity);
5218 }
5219 
SetUIFirstSwitch(OHOS::Rosen::RSUIFirstSwitch uiFirstSwitch)5220 void RosenRenderContext::SetUIFirstSwitch(OHOS::Rosen::RSUIFirstSwitch uiFirstSwitch)
5221 {
5222     CHECK_NULL_VOID(rsNode_);
5223     rsNode_->SetUIFirstSwitch(uiFirstSwitch);
5224 }
5225 
CalcExpectedFrameRate(const std::string & scene,float speed)5226 int32_t RosenRenderContext::CalcExpectedFrameRate(const std::string& scene, float speed)
5227 {
5228     if (rsNode_ == nullptr) {
5229         return 0;
5230     }
5231     return rsNode_->CalcExpectedFrameRate(scene, speed);
5232 }
5233 
DoTextureExport(uint64_t surfaceId)5234 bool RosenRenderContext::DoTextureExport(uint64_t surfaceId)
5235 {
5236     CHECK_NULL_RETURN(rsNode_, false);
5237     rsNode_->RemoveFromTree();
5238     if (!rsTextureExport_) {
5239         rsTextureExport_ = std::make_shared<Rosen::RSTextureExport>(rsNode_, surfaceId);
5240     }
5241     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5242     if (rsSurfaceNode) {
5243         rsSurfaceNode->SetTextureExport(true);
5244     }
5245     return rsTextureExport_->DoTextureExport();
5246 }
5247 
StopTextureExport()5248 bool RosenRenderContext::StopTextureExport()
5249 {
5250     CHECK_NULL_RETURN(rsNode_, false);
5251     CHECK_NULL_RETURN(rsTextureExport_, false);
5252     rsTextureExport_->StopTextureExport();
5253     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5254     if (rsSurfaceNode) {
5255         rsSurfaceNode->SetTextureExport(false);
5256     }
5257     return true;
5258 }
5259 
SetSurfaceRotation(bool isLock)5260 void RosenRenderContext::SetSurfaceRotation(bool isLock)
5261 {
5262     CHECK_NULL_VOID(rsNode_);
5263     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5264     if (rsSurfaceNode) {
5265         rsSurfaceNode->SetForceHardwareAndFixRotation(isLock);
5266     }
5267 }
5268 
SetRenderFit(RenderFit renderFit)5269 void RosenRenderContext::SetRenderFit(RenderFit renderFit)
5270 {
5271     CHECK_NULL_VOID(rsNode_);
5272     propRenderFit_ = renderFit;
5273     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
5274     if (rsSurfaceNode) {
5275         rsSurfaceNode->SetFrameGravity(GetRosenGravity(renderFit));
5276     }
5277 }
5278 
ClearDrawCommands()5279 void RosenRenderContext::ClearDrawCommands()
5280 {
5281     StartRecording();
5282     StopRecordingIfNeeded();
5283 }
5284 
RemoveContentModifier(const RefPtr<ContentModifier> & modifier)5285 void RosenRenderContext::RemoveContentModifier(const RefPtr<ContentModifier>& modifier)
5286 {
5287     CHECK_NULL_VOID(rsNode_);
5288     CHECK_NULL_VOID(modifier);
5289     auto modifierAdapter = std::static_pointer_cast<ContentModifierAdapter>(ConvertContentModifier(modifier));
5290     CHECK_NULL_VOID(modifierAdapter);
5291     rsNode_->RemoveModifier(modifierAdapter);
5292 }
5293 
SetRSNode(const std::shared_ptr<RSNode> & externalNode)5294 void RosenRenderContext::SetRSNode(const std::shared_ptr<RSNode>& externalNode)
5295 {
5296     // Update rsNode_ to externalNode.
5297     if (externalNode == rsNode_) {
5298         return;
5299     }
5300     rsNode_ = externalNode;
5301     AddFrameNodeInfoToRsNode();
5302     auto host = GetHost();
5303     CHECK_NULL_VOID(host);
5304     host->AddExtraCustomProperty("RS_NODE", rsNode_.get());
5305 
5306     ResetTransform();
5307     ResetTransformMatrix();
5308 
5309     // after update, tell parent to update RSNode hierarchy.
5310     auto uiNode = GetHost();
5311     CHECK_NULL_VOID(uiNode);
5312     auto parentUINode = uiNode->GetParent();
5313     CHECK_NULL_VOID(parentUINode);
5314     parentUINode->MarkNeedSyncRenderTree();
5315     parentUINode->RebuildRenderContextTree();
5316 }
5317 
OnMouseSelectUpdate(bool isSelected,const Color & fillColor,const Color & strokeColor)5318 void RosenRenderContext::OnMouseSelectUpdate(bool isSelected, const Color& fillColor, const Color& strokeColor)
5319 {
5320     auto host = GetHost();
5321     CHECK_NULL_VOID(host);
5322 
5323     RectF rect = RectF();
5324     if (isSelected) {
5325         auto geometryNode = host->GetGeometryNode();
5326         CHECK_NULL_VOID(geometryNode);
5327         rect = geometryNode->GetFrameRect();
5328         rect.SetOffset(OffsetF());
5329     }
5330 
5331     UpdateMouseSelectWithRect(rect, fillColor, strokeColor);
5332 }
5333 
UpdateMouseSelectWithRect(const RectF & rect,const Color & fillColor,const Color & strokeColor)5334 void RosenRenderContext::UpdateMouseSelectWithRect(const RectF& rect, const Color& fillColor, const Color& strokeColor)
5335 {
5336     if (!rect.IsValid()) {
5337         return;
5338     }
5339     PaintMouseSelectRect(rect, fillColor, strokeColor);
5340     RequestNextFrame();
5341 }
5342 
PaintMouseSelectRect(const RectF & rect,const Color & fillColor,const Color & strokeColor)5343 void RosenRenderContext::PaintMouseSelectRect(const RectF& rect, const Color& fillColor, const Color& strokeColor)
5344 {
5345     CHECK_NULL_VOID(rsNode_);
5346     if (mouseSelectModifier_) {
5347         mouseSelectModifier_->SetSelectRect(rect);
5348         return;
5349     }
5350 
5351     auto paintTask = [&fillColor, &strokeColor](const RectF& rect, RSCanvas& rsCanvas) mutable {
5352         RSBrush brush;
5353         brush.SetColor(ToRSColor(fillColor));
5354         rsCanvas.AttachBrush(brush);
5355         rsCanvas.DrawRect(ToRSRect(rect));
5356         rsCanvas.DetachBrush();
5357         RSPen pen;
5358         pen.SetColor(ToRSColor(strokeColor));
5359         rsCanvas.AttachPen(pen);
5360         rsCanvas.DrawRect(ToRSRect(rect));
5361         rsCanvas.DetachPen();
5362     };
5363 
5364     mouseSelectModifier_ = std::make_shared<MouseSelectModifier>();
5365     mouseSelectModifier_->SetPaintTask(std::move(paintTask));
5366     rsNode_->AddModifier(mouseSelectModifier_);
5367 }
5368 
DumpInfo()5369 void RosenRenderContext::DumpInfo()
5370 {
5371     if (rsNode_) {
5372         DumpLog::GetInstance().AddDesc("------------start print rsNode");
5373         DumpLog::GetInstance().AddDesc(rsNode_->DumpNode(0));
5374         auto center = rsNode_->GetStagingProperties().GetPivot();
5375         if (!NearEqual(center[0], 0.5) || !NearEqual(center[1], 0.5)) {
5376             DumpLog::GetInstance().AddDesc(std::string("Center: x:")
5377                                                .append(std::to_string(center[0]))
5378                                                .append(" y:")
5379                                                .append(std::to_string(center[1])));
5380         }
5381         if (!NearZero(rsNode_->GetStagingProperties().GetPivotZ())) {
5382             DumpLog::GetInstance().AddDesc(
5383                 std::string("PivotZ:").append(std::to_string(rsNode_->GetStagingProperties().GetPivotZ())));
5384         }
5385         std::string res = "";
5386         if (!NearZero(rsNode_->GetStagingProperties().GetRotation())) {
5387             res.append(" Rotation:").append(std::to_string(rsNode_->GetStagingProperties().GetRotation()));
5388         }
5389         if (!NearZero(rsNode_->GetStagingProperties().GetRotationX())) {
5390             res.append(" RotationX:").append(std::to_string(rsNode_->GetStagingProperties().GetRotationX()));
5391         }
5392         if (!NearZero(rsNode_->GetStagingProperties().GetRotationY())) {
5393             res.append(" RotationY:").append(std::to_string(rsNode_->GetStagingProperties().GetRotationY()));
5394         }
5395         if (!res.empty()) {
5396             DumpLog::GetInstance().AddDesc(res);
5397             res.clear();
5398         }
5399         const auto& groupProperty = GetOrCreateBackground();
5400         if (groupProperty->propEffectOption.has_value()) {
5401             auto backgroundEffect = groupProperty->propEffectOption->ToJsonValue()->ToString();
5402             DumpLog::GetInstance().AddDesc(std::string("backgroundEffect:").append(backgroundEffect));
5403         }
5404         if (groupProperty->propSysOptions.has_value()) {
5405             DumpLog::GetInstance().AddDesc(
5406                 std::string("backDisable:")
5407                     .append(std::to_string(groupProperty->propSysOptions->disableSystemAdaptation)));
5408         }
5409         const auto& foregroundProperty = GetOrCreateForeground();
5410         if (foregroundProperty->propSysOptionsForBlur.has_value()) {
5411             DumpLog::GetInstance().AddDesc(
5412                 std::string("blurDisable:")
5413                     .append(std::to_string(foregroundProperty->propSysOptionsForBlur->disableSystemAdaptation)));
5414         }
5415         if (foregroundProperty->propSysOptionsForForeEffect.has_value()) {
5416             DumpLog::GetInstance().AddDesc(
5417                 std::string("foreEffectDisable:")
5418                     .append(std::to_string(foregroundProperty->propSysOptionsForForeEffect->disableSystemAdaptation)));
5419         }
5420         auto&& graphicProps = GetOrCreateGraphics();
5421         if (graphicProps->propFgDynamicBrightnessOption.has_value()) {
5422             auto fgDynamicBrightness = graphicProps->propFgDynamicBrightnessOption->GetJsonObject();
5423             DumpLog::GetInstance().AddDesc(
5424                 std::string("foregroundBrightness:").append(fgDynamicBrightness->ToString().c_str()));
5425         }
5426         if (graphicProps->propBgDynamicBrightnessOption.has_value()) {
5427             auto bgDynamicBrightness = graphicProps->propBgDynamicBrightnessOption->GetJsonObject();
5428             DumpLog::GetInstance().AddDesc(
5429                 std::string("backgroundBrightnessInternal:").append(bgDynamicBrightness->ToString().c_str()));
5430         }
5431         if (!NearZero(rsNode_->GetStagingProperties().GetCameraDistance())) {
5432             DumpLog::GetInstance().AddDesc(
5433                 std::string("CameraDistance:")
5434                     .append(std::to_string(rsNode_->GetStagingProperties().GetCameraDistance())));
5435         }
5436         if (!NearZero(rsNode_->GetStagingProperties().GetTranslateZ())) {
5437             DumpLog::GetInstance().AddDesc(
5438                 std::string("TranslateZ:").append(std::to_string(rsNode_->GetStagingProperties().GetTranslateZ())));
5439         }
5440         if (!NearZero(rsNode_->GetStagingProperties().GetBgImageWidth())) {
5441             res.append(" BgImageWidth:").append(std::to_string(rsNode_->GetStagingProperties().GetBgImageWidth()));
5442         }
5443         if (!NearZero(rsNode_->GetStagingProperties().GetBgImageHeight())) {
5444             res.append(" BgImageHeight:").append(std::to_string(rsNode_->GetStagingProperties().GetBgImageHeight()));
5445         }
5446         if (!NearZero(rsNode_->GetStagingProperties().GetBgImagePositionX())) {
5447             res.append(" BgImagePositionX")
5448                 .append(std::to_string(rsNode_->GetStagingProperties().GetBgImagePositionX()));
5449         }
5450         if (!NearZero(rsNode_->GetStagingProperties().GetBgImagePositionY())) {
5451             res.append(" BgImagePositionY")
5452                 .append(std::to_string(rsNode_->GetStagingProperties().GetBgImagePositionY()));
5453         }
5454         if (!res.empty()) {
5455             DumpLog::GetInstance().AddDesc(res);
5456             res.clear();
5457         }
5458         if (!NearZero(rsNode_->GetStagingProperties().GetShadowOffsetX())) {
5459             res.append(" ShadowOffsetX:").append(std::to_string(rsNode_->GetStagingProperties().GetShadowOffsetX()));
5460         }
5461         if (!NearZero(rsNode_->GetStagingProperties().GetShadowOffsetY())) {
5462             res.append(" ShadowOffsetY:").append(std::to_string(rsNode_->GetStagingProperties().GetShadowOffsetY()));
5463         }
5464         if (!NearZero(rsNode_->GetStagingProperties().GetShadowAlpha())) {
5465             res.append(" ShadowAlpha:").append(std::to_string(rsNode_->GetStagingProperties().GetShadowAlpha()));
5466         }
5467         if (!NearZero(rsNode_->GetStagingProperties().GetShadowElevation())) {
5468             res.append(" ShadowElevation:")
5469                 .append(std::to_string(rsNode_->GetStagingProperties().GetShadowElevation()));
5470         }
5471         if (!NearZero(rsNode_->GetStagingProperties().GetShadowRadius())) {
5472             res.append(" ShadowRadius:").append(std::to_string(rsNode_->GetStagingProperties().GetShadowRadius()));
5473         }
5474         if (!res.empty()) {
5475             DumpLog::GetInstance().AddDesc(res);
5476             res.clear();
5477         }
5478         if (!NearZero(rsNode_->GetStagingProperties().GetSpherizeDegree())) {
5479             DumpLog::GetInstance().AddDesc(
5480                 std::string("SpherizeDegree:")
5481                     .append(std::to_string(rsNode_->GetStagingProperties().GetSpherizeDegree())));
5482         }
5483         if (!NearZero(rsNode_->GetStagingProperties().GetLightUpEffectDegree())) {
5484             DumpLog::GetInstance().AddDesc(
5485                 std::string("LightUpEffectDegree:")
5486                     .append(std::to_string(rsNode_->GetStagingProperties().GetLightUpEffectDegree())));
5487         }
5488         if (!NearEqual(rsNode_->GetStagingProperties().GetAlpha(), 1)) {
5489             DumpLog::GetInstance().AddDesc(
5490                 std::string("Alpha:").append(std::to_string(rsNode_->GetStagingProperties().GetAlpha())));
5491         }
5492         auto translate = rsNode_->GetStagingProperties().GetTranslate();
5493         if (!(NearZero(translate[0]) && NearZero(translate[1]))) {
5494             DumpLog::GetInstance().AddDesc(
5495                 std::string("translate(x,y): ")
5496                     .append(std::to_string(translate[0]).append(",").append(std::to_string(translate[1]))));
5497         }
5498         auto scale = rsNode_->GetStagingProperties().GetScale();
5499         if (!(NearEqual(scale[0], 1) && NearEqual(scale[1], 1))) {
5500             DumpLog::GetInstance().AddDesc(
5501                 std::string("scale(x,y): ")
5502                     .append(std::to_string(scale[0]).append(",").append(std::to_string(scale[1]))));
5503         }
5504         auto rect = GetPaintRectWithoutTransform();
5505         if (HasTransformTranslate()) {
5506             auto translateArk = GetTransformTranslate().value();
5507             auto arkTranslateX = translateArk.x.ConvertToPxWithSize(rect.Width());
5508             auto arkTranslateY = translateArk.y.ConvertToPxWithSize(rect.Height());
5509             if (!NearEqual(arkTranslateX, translate[0])) {
5510                 DumpLog::GetInstance().AddDesc(
5511                     std::string("TranlateX has difference,arkui:").append(std::to_string(arkTranslateX)));
5512             }
5513             if (!NearEqual(arkTranslateY, translate[1])) {
5514                 DumpLog::GetInstance().AddDesc(
5515                     std::string("TranlateY has difference,arkui:").append(std::to_string(arkTranslateY)));
5516             }
5517         }
5518         if (HasTransformScale()) {
5519             auto arkTransformScale = GetTransformScale().value();
5520             if (!NearEqual(arkTransformScale.x, scale[0])) {
5521                 DumpLog::GetInstance().AddDesc(
5522                     std::string("scaleX has difference,arkui:").append(std::to_string(arkTransformScale.x)));
5523             }
5524             if (!NearEqual(arkTransformScale.y, scale[1])) {
5525                 DumpLog::GetInstance().AddDesc(
5526                     std::string("scaleY has difference,arkui:").append(std::to_string(arkTransformScale.y)));
5527             }
5528         }
5529         if (HasOpacity()) {
5530             auto arkAlpha = GetOpacity();
5531             if (!NearEqual(arkAlpha.value(), rsNode_->GetStagingProperties().GetAlpha())) {
5532                 DumpLog::GetInstance().AddDesc(
5533                     std::string("Alpha has difference,arkui:").append(std::to_string(arkAlpha.value())));
5534             }
5535         }
5536         if (HasPosition()) {
5537             auto position = GetPosition();
5538             DumpLog::GetInstance().AddDesc(std::string("PositionX :")
5539                                                .append(position->GetX().ToString().c_str())
5540                                                .append(std::string(",PositionY :"))
5541                                                .append(position->GetY().ToString().c_str()));
5542         }
5543         if (HasOffset()) {
5544             auto offset = GetOffset();
5545             DumpLog::GetInstance().AddDesc(std::string("OffsetX :")
5546                                                .append(offset->GetX().ToString().c_str())
5547                                                .append(std::string(",OffsetY :"))
5548                                                .append(offset->GetY().ToString().c_str()));
5549         }
5550         if (HasPositionEdges()) {
5551             auto positionEdges = GetPositionEdges();
5552             DumpLog::GetInstance().AddDesc(std::string("positionEdges :").append(positionEdges->ToString().c_str()));
5553         }
5554         if (HasOffsetEdges()) {
5555             auto offsetEdges = GetOffsetEdges();
5556             DumpLog::GetInstance().AddDesc(std::string("offsetEdges :").append(offsetEdges->ToString().c_str()));
5557         }
5558         if (HasAnchor()) {
5559             auto anchor = GetAnchor();
5560             DumpLog::GetInstance().AddDesc(std::string("anchorX :")
5561                                                .append(anchor->GetX().ToString().c_str())
5562                                                .append(std::string(",anchorY :"))
5563                                                .append(anchor->GetY().ToString().c_str()));
5564         }
5565 
5566         auto rsBlendMode = static_cast<int16_t>(rsNode_->GetStagingProperties().GetColorBlendMode());
5567         if (GetBackBlendMode().has_value() || rsBlendMode) {
5568             DumpLog::GetInstance().AddDesc(
5569                 std::string("blendMode:") + std::to_string(rsBlendMode));
5570             auto blendMode = static_cast<int16_t>(GetBackBlendMode().value_or(BlendMode::NONE));
5571             if (rsBlendMode != blendMode) {
5572                 DumpLog::GetInstance().AddDesc(
5573                     std::string("blendMode has difference,arkui:") + std::to_string(blendMode));
5574             }
5575         }
5576 
5577         auto rsBlendApplyType = static_cast<int16_t>(rsNode_->GetStagingProperties().GetColorBlendApplyType());
5578         if (GetBackBlendApplyType().has_value() || rsBlendApplyType) {
5579             DumpLog::GetInstance().AddDesc(
5580                 std::string("blendApplyType:") + std::to_string(rsBlendApplyType));
5581             auto blendApplyType = static_cast<int16_t>(GetBackBlendApplyType().value_or(BlendApplyType::FAST));
5582             if (rsBlendApplyType != blendApplyType) {
5583                 DumpLog::GetInstance().AddDesc(
5584                     std::string("blendApplyType has difference,arkui:") + std::to_string(blendApplyType));
5585             }
5586         }
5587     }
5588     if (disappearingTransitionCount_) {
5589         DumpLog::GetInstance().AddDesc(
5590             std::string("transitionCnt:").append(std::to_string(disappearingTransitionCount_))
5591         );
5592     }
5593 }
5594 
DumpAdvanceInfo()5595 void RosenRenderContext::DumpAdvanceInfo()
5596 {
5597     if (GetBackgroundAlign().has_value()) {
5598         DumpLog::GetInstance().AddDesc("BackgroundAlign:" + GetBackgroundAlign().value().ToString());
5599     }
5600     if (GetBackgroundImage().has_value()) {
5601         DumpLog::GetInstance().AddDesc("BackgroundImage:" + GetBackgroundImage().value().ToString());
5602     }
5603     if (GetSphericalEffect().has_value()) {
5604         DumpLog::GetInstance().AddDesc("SphericalEffect:" + std::to_string(GetSphericalEffect().value()));
5605     }
5606     if (GetPixelStretchEffect().has_value()) {
5607         DumpLog::GetInstance().AddDesc("PixelStretchEffect:" + GetPixelStretchEffect().value().ToString());
5608     }
5609     if (GetLightUpEffect().has_value()) {
5610         DumpLog::GetInstance().AddDesc("LightUpEffect:" + std::to_string(GetLightUpEffect().value()));
5611     }
5612     if (GetBorderColor().has_value()) {
5613         DumpLog::GetInstance().AddDesc("BorderColor:" + GetBorderColor().value().ToString());
5614     }
5615     if (GetBorderWidth().has_value()) {
5616         DumpLog::GetInstance().AddDesc("BorderWidth:" + GetBorderWidth().value().ToString());
5617     }
5618     if (GetOuterBorderRadius().has_value()) {
5619         DumpLog::GetInstance().AddDesc("OuterBorderRadius:" + GetOuterBorderRadius().value().ToString());
5620     }
5621     if (GetOuterBorderColor().has_value()) {
5622         DumpLog::GetInstance().AddDesc("OuterBorderColor:" + GetOuterBorderColor().value().ToString());
5623     }
5624     if (GetOuterBorderWidth().has_value()) {
5625         DumpLog::GetInstance().AddDesc("OuterBorderWidth:" + GetOuterBorderWidth().value().ToString());
5626     }
5627     if (GetDynamicLightUpRate().has_value()) {
5628         DumpLog::GetInstance().AddDesc("DynamicLightUpRate:" + std::to_string(GetDynamicLightUpRate().value()));
5629     }
5630     if (GetDynamicLightUpDegree().has_value()) {
5631         DumpLog::GetInstance().AddDesc("DynamicLightUpDegree:" + std::to_string(GetDynamicLightUpDegree().value()));
5632     }
5633     if (GetBackBlendMode().has_value()) {
5634         DumpLog::GetInstance().AddDesc("BlendMode:" + std::to_string(static_cast<int>(GetBackBlendMode().value())));
5635     }
5636     if (GetLinearGradient().has_value()) {
5637         DumpLog::GetInstance().AddDesc("LinearGradient:" + GetLinearGradient().value().ToString());
5638     }
5639     if (GetSweepGradient().has_value()) {
5640         DumpLog::GetInstance().AddDesc("SweepGradient:" + GetSweepGradient().value().ToString());
5641     }
5642     if (GetRadialGradient().has_value()) {
5643         DumpLog::GetInstance().AddDesc("RadialGradient:" + GetRadialGradient().value().ToString());
5644     }
5645     if (GetFrontBrightness().has_value()) {
5646         DumpLog::GetInstance().AddDesc("FrontBrightness:" + GetFrontBrightness().value().ToString());
5647     }
5648     if (GetFrontGrayScale().has_value()) {
5649         DumpLog::GetInstance().AddDesc("FrontGrayScale:" + GetFrontGrayScale().value().ToString());
5650     }
5651     if (GetFrontContrast().has_value()) {
5652         DumpLog::GetInstance().AddDesc("FrontContrast:" + GetFrontContrast().value().ToString());
5653     }
5654     if (GetFrontSaturate().has_value()) {
5655         DumpLog::GetInstance().AddDesc("FrontSaturate:" + GetFrontSaturate().value().ToString());
5656     }
5657     if (GetFrontSepia().has_value()) {
5658         DumpLog::GetInstance().AddDesc("FrontSepia:" + GetFrontSepia().value().ToString());
5659     }
5660     if (GetFrontHueRotate().has_value()) {
5661         DumpLog::GetInstance().AddDesc("FrontHueRotate:" + std::to_string(GetFrontHueRotate().value()));
5662     }
5663     if (GetFrontColorBlend().has_value()) {
5664         DumpLog::GetInstance().AddDesc("FrontColorBlend:" + GetFrontColorBlend().value().ColorToString());
5665     }
5666     if (GetBorderImageSource().has_value()) {
5667         DumpLog::GetInstance().AddDesc("BorderImageSource:" + GetBorderImageSource().value().ToString());
5668     }
5669     if (GetBorderImageGradient().has_value()) {
5670         DumpLog::GetInstance().AddDesc("BorderImageGradient:" + GetBorderImageGradient().value().ToString());
5671     }
5672     if (GetForegroundColor().has_value()) {
5673         DumpLog::GetInstance().AddDesc("ForegroundColor:" + GetForegroundColor().value().ColorToString());
5674     }
5675     if (GetLightIntensity().has_value()) {
5676         DumpLog::GetInstance().AddDesc("LightIntensity:" + std::to_string(GetLightIntensity().value()));
5677     }
5678     if (GetLightIlluminated().has_value()) {
5679         DumpLog::GetInstance().AddDesc("LightIlluminated:" + std::to_string(GetLightIlluminated().value()));
5680     }
5681     if (GetIlluminatedBorderWidth().has_value()) {
5682         DumpLog::GetInstance().AddDesc("IlluminatedBorderWidth:" + GetIlluminatedBorderWidth().value().ToString());
5683     }
5684     if (GetBloom().has_value()) {
5685         DumpLog::GetInstance().AddDesc("Bloom:" + std::to_string(GetBloom().value()));
5686     }
5687 }
5688 
MarkContentChanged(bool isChanged)5689 void RosenRenderContext::MarkContentChanged(bool isChanged)
5690 {
5691     CHECK_NULL_VOID(rsNode_);
5692     rsNode_->MarkContentChanged(isChanged);
5693 }
5694 
MarkDrivenRender(bool flag)5695 void RosenRenderContext::MarkDrivenRender(bool flag)
5696 {
5697     CHECK_NULL_VOID(rsNode_);
5698     rsNode_->MarkDrivenRender(flag);
5699 }
5700 
MarkDrivenRenderItemIndex(int32_t index)5701 void RosenRenderContext::MarkDrivenRenderItemIndex(int32_t index)
5702 {
5703     CHECK_NULL_VOID(rsNode_);
5704     rsNode_->MarkDrivenRenderItemIndex(index);
5705 }
5706 
MarkDrivenRenderFramePaintState(bool flag)5707 void RosenRenderContext::MarkDrivenRenderFramePaintState(bool flag)
5708 {
5709     CHECK_NULL_VOID(rsNode_);
5710     rsNode_->MarkDrivenRenderFramePaintState(flag);
5711 }
5712 
UpdateChainedTransition(const RefPtr<NG::ChainedTransitionEffect> & effect)5713 void RosenRenderContext::UpdateChainedTransition(const RefPtr<NG::ChainedTransitionEffect>& effect)
5714 {
5715     if (transitionEffect_) {
5716         // use effect to update rosenTransitionEffect activeValue
5717         if (RosenTransitionEffect::UpdateRosenTransitionEffect(transitionEffect_, effect)) {
5718             return;
5719         }
5720         transitionEffect_->Detach(this);
5721     }
5722     transitionEffect_ = RosenTransitionEffect::ConvertToRosenTransitionEffect(effect);
5723     hasDefaultTransition_ = false;
5724     CHECK_NULL_VOID(transitionEffect_);
5725     auto frameNode = GetHost();
5726     CHECK_NULL_VOID(frameNode);
5727     bool isOnTheTree = frameNode->IsOnMainTree();
5728     // transition effects should be initialized without animation.
5729     RSNode::ExecuteWithoutAnimation([this, isOnTheTree]() {
5730         // transitionIn effects should be initialized as active if currently not on the tree.
5731         transitionEffect_->Attach(Claim(this), !isOnTheTree);
5732     });
5733 }
5734 
NotifyTransition(bool isTransitionIn)5735 void RosenRenderContext::NotifyTransition(bool isTransitionIn)
5736 {
5737     CHECK_NULL_VOID(transitionEffect_);
5738 
5739     auto frameNode = GetHost();
5740     CHECK_NULL_VOID(frameNode);
5741 
5742     RSNode::ExecuteWithoutAnimation([this, &frameNode, isTransitionIn]() {
5743         if (isTransitionIn && disappearingTransitionCount_ == 0 && appearingTransitionCount_ == 0) {
5744             // transitionIn, reset to state before attaching in case of node reappear
5745             transitionEffect_->Attach(Claim(this), true);
5746         }
5747         auto pipeline = PipelineBase::GetCurrentContext();
5748         CHECK_NULL_VOID(pipeline);
5749         SizeF rootSize(pipeline->GetRootWidth(), pipeline->GetRootHeight());
5750         auto parentOffset = frameNode->GetPaintRectOffset(true);
5751         auto rect = GetPaintRectWithoutTransform();
5752         // Do not consider the position after its own transform, as the transition modifier also affects the transform
5753         rect.SetOffset(parentOffset + rect.GetOffset());
5754 
5755         transitionEffect_->UpdateTransitionContext(Claim(this), rect, rootSize);
5756     });
5757 
5758     if (isTransitionIn) {
5759         // Isolate the animation callback function, to avoid changing the callback timing of current implicit animation.
5760         AnimationUtils::AnimateWithCurrentOptions(
5761             [this]() {
5762                 transitionEffect_->Appear();
5763                 ++appearingTransitionCount_;
5764             },
5765             [weakThis = WeakClaim(this)]() {
5766                 auto context = weakThis.Upgrade();
5767                 CHECK_NULL_VOID(context);
5768                 context->OnTransitionInFinish();
5769             },
5770             false);
5771     } else {
5772         if (!transitionEffect_->HasDisappearTransition()) {
5773             if (frameNode->GetTag() == V2::WINDOW_SCENE_ETS_TAG) {
5774                 auto frameParent = frameNode->GetAncestorNodeOfFrame(false);
5775                 CHECK_NULL_VOID(frameParent);
5776                 // for window surfaceNode, remove surfaceNode explicitly
5777                 frameParent->GetRenderContext()->RemoveChild(Claim(this));
5778             }
5779             if (transitionUserCallback_ && !disappearingTransitionCount_) {
5780                 PostTransitionUserOutCallback();
5781             }
5782             return;
5783         }
5784         // Re-use current implicit animation timing params, only replace the finish callback function.
5785         // The finish callback function will perform all the necessary cleanup work.
5786         // Important Note on timing:
5787         // 1. If any transition animations are created, the finish callback function will only be called when ALL
5788         //    animations have finished. This is accomplished by sharing the same shared_ptr<AnimationFinishCallback>
5789         //    among all animations.
5790         // 2. If no transition animations are created, the finish callback function will be called IMMEDIATELY. This
5791         //    is accomplished by setting the last param (timing sensitive) to false, which avoids creating an empty
5792         //    'timer' animation.
5793         AnimationUtils::AnimateWithCurrentOptions(
5794             [this]() {
5795                 transitionEffect_->Disappear();
5796                 // update transition out count
5797                 ++disappearingTransitionCount_;
5798             },
5799             [weakThis = WeakClaim(this), nodeId = frameNode->GetId(), id = Container::CurrentId()]() {
5800                 auto context = weakThis.Upgrade();
5801                 CHECK_NULL_VOID(context);
5802                 // update transition out count
5803                 context->OnTransitionOutFinish();
5804             },
5805             false);
5806     }
5807     auto host = GetHost();
5808     CHECK_NULL_VOID(host);
5809     host->OnNodeTransitionInfoUpdate();
5810 }
5811 
RemoveDefaultTransition()5812 void RosenRenderContext::RemoveDefaultTransition()
5813 {
5814     if (hasDefaultTransition_ && transitionEffect_ && disappearingTransitionCount_ == 0 &&
5815         appearingTransitionCount_ == 0) {
5816         transitionEffect_->Detach(this);
5817         transitionEffect_ = nullptr;
5818         hasDefaultTransition_ = false;
5819     }
5820 }
5821 
OnTransitionInFinish()5822 void RosenRenderContext::OnTransitionInFinish()
5823 {
5824     --appearingTransitionCount_;
5825     // make sure we are the last transition out animation, if not, return.
5826     if (appearingTransitionCount_ > 0) {
5827         return;
5828     }
5829     if (appearingTransitionCount_ < 0) {
5830         appearingTransitionCount_ = 0;
5831     }
5832     // when all transition in/out animations are finished, we should remove the default transition effect.
5833     RemoveDefaultTransition();
5834     auto host = GetHost();
5835     CHECK_NULL_VOID(host);
5836     FireTransitionUserCallback(true);
5837     auto parent = host->GetParent();
5838     CHECK_NULL_VOID(parent);
5839     if (host->IsVisible()) {
5840         // trigger transition through visibility
5841         if (transitionInCallback_) {
5842             transitionInCallback_();
5843         }
5844     }
5845 }
5846 
OnTransitionOutFinish()5847 void RosenRenderContext::OnTransitionOutFinish()
5848 {
5849     // update transition out count
5850     --disappearingTransitionCount_;
5851     // make sure we are the last transition out animation, if not, return.
5852     if (disappearingTransitionCount_ > 0) {
5853         return;
5854     }
5855     if (disappearingTransitionCount_ < 0) {
5856         disappearingTransitionCount_ = 0;
5857     }
5858     // when all transition in/out animations are finished, we should remove the default transition effect.
5859     RemoveDefaultTransition();
5860     auto host = GetHost();
5861     CHECK_NULL_VOID(host);
5862     auto parent = host->GetParent();
5863     CHECK_NULL_VOID(parent);
5864     if (!host->IsVisible()) {
5865         // trigger transition through visibility
5866         if (host->IsOnMainTree()) {
5867             if (transitionOutCallback_) {
5868                 transitionOutCallback_();
5869             }
5870             parent->MarkNeedSyncRenderTree();
5871             parent->RebuildRenderContextTree();
5872             FireTransitionUserCallback(false);
5873             return;
5874         }
5875         parent->MarkNeedSyncRenderTree();
5876         parent->RebuildRenderContextTree();
5877     }
5878     RefPtr<UINode> breakPointChild = host;
5879     RefPtr<UINode> breakPointParent = breakPointChild->GetParent();
5880     UINode::GetBestBreakPoint(breakPointChild, breakPointParent);
5881     // if can not find the breakPoint, means the node is not disappearing (reappear? or the node of subtree), return.
5882     if (!breakPointParent) {
5883         FireTransitionUserCallback(false);
5884         return;
5885     }
5886     if (breakPointChild->RemoveImmediately()) {
5887         breakPointChild->OnRemoveFromParent(false);
5888         // remove breakPoint
5889         breakPointParent->RemoveDisappearingChild(breakPointChild);
5890         breakPointParent->MarkNeedSyncRenderTree();
5891         breakPointParent->RebuildRenderContextTree();
5892     }
5893     if (isModalRootNode_ && breakPointParent->GetChildren().empty()) {
5894         auto grandParent = breakPointParent->GetParent();
5895         CHECK_NULL_VOID(grandParent);
5896         grandParent->RemoveChild(breakPointParent);
5897         grandParent->RebuildRenderContextTree();
5898     }
5899     FireTransitionUserCallback(false);
5900 }
5901 
FireTransitionUserCallback(bool isTransitionIn)5902 void RosenRenderContext::FireTransitionUserCallback(bool isTransitionIn)
5903 {
5904     if (transitionUserCallback_) {
5905         auto callback = transitionUserCallback_;
5906         callback(isTransitionIn);
5907     }
5908 }
5909 
PostTransitionUserOutCallback()5910 void RosenRenderContext::PostTransitionUserOutCallback()
5911 {
5912     auto taskExecutor = Container::CurrentTaskExecutor();
5913     CHECK_NULL_VOID(taskExecutor);
5914     // post the callback to let it run on isolate environment
5915     taskExecutor->PostTask(
5916         [callback = transitionUserCallback_]() {
5917             if (callback) {
5918                 callback(false);
5919             }
5920         },
5921         TaskExecutor::TaskType::UI, "ArkUITransitionOutFinishCallback", PriorityType::HIGH);
5922 }
5923 
SetActualForegroundColor(const Color & value)5924 void RosenRenderContext::SetActualForegroundColor(const Color& value)
5925 {
5926     CHECK_NULL_VOID(rsNode_);
5927     rsNode_->SetForegroundColor(value.GetValue());
5928     RequestNextFrame();
5929 }
5930 
AttachNodeAnimatableProperty(RefPtr<NodeAnimatablePropertyBase> property)5931 void RosenRenderContext::AttachNodeAnimatableProperty(RefPtr<NodeAnimatablePropertyBase> property)
5932 {
5933     CHECK_NULL_VOID(rsNode_);
5934     CHECK_NULL_VOID(property);
5935     if (!property->GetModifyImpl()) {
5936         auto nodeModifierImpl = std::make_shared<RSNodeModifierImpl>();
5937         CHECK_NULL_VOID(nodeModifierImpl);
5938         property->SetModifyImpl(nodeModifierImpl);
5939         rsNode_->AddModifier(nodeModifierImpl);
5940         nodeModifierImpl->AddProperty(property->GetProperty());
5941     }
5942 }
5943 
DetachNodeAnimatableProperty(const RefPtr<NodeAnimatablePropertyBase> & property)5944 void RosenRenderContext::DetachNodeAnimatableProperty(const RefPtr<NodeAnimatablePropertyBase>& property)
5945 {
5946     CHECK_NULL_VOID(rsNode_);
5947     CHECK_NULL_VOID(property);
5948     std::shared_ptr<RSNodeModifierImpl> modifier =
5949         std::static_pointer_cast<RSNodeModifierImpl>(property->GetModifyImpl());
5950     RemoveModifier(modifier);
5951 }
5952 
InitEventClickEffect()5953 void RosenRenderContext::InitEventClickEffect()
5954 {
5955     if (touchListener_) {
5956         return;
5957     }
5958     auto host = GetHost();
5959     CHECK_NULL_VOID(host);
5960     auto gesture = host->GetOrCreateGestureEventHub();
5961     CHECK_NULL_VOID(gesture);
5962     auto touchCallback = [weak = WeakClaim(this)](const TouchEventInfo& info) {
5963         auto renderContext = weak.Upgrade();
5964         CHECK_NULL_VOID(renderContext);
5965         renderContext->ClickEffectPlayAnimation(info.GetTouches().front().GetTouchType());
5966     };
5967     touchListener_ = MakeRefPtr<TouchEventImpl>(std::move(touchCallback));
5968     gesture->AddTouchEvent(touchListener_);
5969 }
5970 
ClickEffectPlayAnimation(const TouchType & touchType)5971 void RosenRenderContext::ClickEffectPlayAnimation(const TouchType& touchType)
5972 {
5973     if (touchType != TouchType::DOWN && touchType != TouchType::UP && touchType != TouchType::CANCEL) {
5974         return;
5975     }
5976     auto value = GetClickEffectLevelValue();
5977     auto level = value.level;
5978     auto scaleValue = value.scaleNumber;
5979     auto springCurve = UpdatePlayAnimationValue(level, scaleValue);
5980 
5981     AnimationOption option;
5982     option.SetCurve(springCurve);
5983     option.SetDuration(DEFAULT_OPTION_DURATION);
5984 
5985     if (touchType == TouchType::DOWN && level != ClickEffectLevel::UNDEFINED) {
5986         if (isTouchUpFinished_) {
5987             auto defaultScale = VectorF(1.0f, 1.0f);
5988             auto currentScale = GetTransformScaleValue(defaultScale);
5989             currentScale_ = currentScale;
5990             UpdateTransformScale(currentScale_);
5991 
5992             AnimationUtils::OpenImplicitAnimation(option, springCurve, nullptr);
5993             VectorF valueScale(scaleValue, scaleValue);
5994             UpdateTransformScale(valueScale);
5995             AnimationUtils::CloseImplicitAnimation();
5996         }
5997         isTouchUpFinished_ = false;
5998     }
5999 
6000     if ((touchType == TouchType::UP || touchType == TouchType::CANCEL) && level != ClickEffectLevel::UNDEFINED) {
6001         AnimationUtils::OpenImplicitAnimation(option, springCurve, nullptr);
6002         UpdateTransformScale(currentScale_);
6003         AnimationUtils::CloseImplicitAnimation();
6004         isTouchUpFinished_ = true;
6005     }
6006 }
6007 
UpdatePlayAnimationValue(const ClickEffectLevel & level,float & scaleValue)6008 RefPtr<Curve> RosenRenderContext::UpdatePlayAnimationValue(const ClickEffectLevel& level, float& scaleValue)
6009 {
6010     float velocity = 0.0f;
6011     float mass = 0.0f;
6012     float stiffness = 0.0f;
6013     float damping = 0.0f;
6014     if (level == ClickEffectLevel::LIGHT) {
6015         velocity = ANIMATION_CURVE_VELOCITY_LIGHT_OR_MIDDLE;
6016         mass = ANIMATION_CURVE_MASS;
6017         stiffness = ANIMATION_CURVE_STIFFNESS_LIGHT;
6018         damping = ANIMATION_CURVE_DAMPING_LIGHT;
6019         if (GreatOrEqual(scaleValue, 0.0) && LessOrEqual(scaleValue, 1.0)) {
6020             scaleValue = sqrt(scaleValue);
6021         } else {
6022             scaleValue = sqrt(DEFAULT_SCALE_LIGHT);
6023         }
6024     } else if (level == ClickEffectLevel::MIDDLE) {
6025         velocity = ANIMATION_CURVE_VELOCITY_LIGHT_OR_MIDDLE;
6026         mass = ANIMATION_CURVE_MASS;
6027         stiffness = ANIMATION_CURVE_STIFFNESS_MIDDLE;
6028         damping = ANIMATION_CURVE_DAMPING_MIDDLE;
6029         if (GreatOrEqual(scaleValue, 0.0) && LessOrEqual(scaleValue, 1.0)) {
6030             scaleValue = sqrt(scaleValue);
6031         } else {
6032             scaleValue = sqrt(DEFAULT_SCALE_MIDDLE_OR_HEAVY);
6033         }
6034     } else if (level == ClickEffectLevel::HEAVY) {
6035         velocity = ANIMATION_CURVE_VELOCITY_HEAVY;
6036         mass = ANIMATION_CURVE_MASS;
6037         stiffness = ANIMATION_CURVE_STIFFNESS_HEAVY;
6038         damping = ANIMATION_CURVE_DAMPING_HEAVY;
6039         if (GreatOrEqual(scaleValue, 0.0) && LessOrEqual(scaleValue, 1.0)) {
6040             scaleValue = sqrt(scaleValue);
6041         } else {
6042             scaleValue = sqrt(DEFAULT_SCALE_MIDDLE_OR_HEAVY);
6043         }
6044     }
6045     return AceType::MakeRefPtr<InterpolatingSpring>(velocity, mass, stiffness, damping);
6046 }
6047 
RegisterSharedTransition(const RefPtr<RenderContext> & other,const bool isInSameWindow)6048 void RosenRenderContext::RegisterSharedTransition(const RefPtr<RenderContext>& other, const bool isInSameWindow)
6049 {
6050     auto otherContext = AceType::DynamicCast<RosenRenderContext>(other);
6051     if (!otherContext) {
6052         return;
6053     }
6054     CHECK_NULL_VOID(rsNode_);
6055     RSNode::RegisterTransitionPair(rsNode_->GetId(), otherContext->rsNode_->GetId(), isInSameWindow);
6056 }
6057 
UnregisterSharedTransition(const RefPtr<RenderContext> & other)6058 void RosenRenderContext::UnregisterSharedTransition(const RefPtr<RenderContext>& other)
6059 {
6060     auto otherContext = AceType::DynamicCast<RosenRenderContext>(other);
6061     if (!otherContext) {
6062         // the paired node is already destroyed, we don't need to unregister it, Rosen will handle it.
6063         return;
6064     }
6065     CHECK_NULL_VOID(rsNode_);
6066     RSNode::UnregisterTransitionPair(rsNode_->GetId(), otherContext->rsNode_->GetId());
6067 }
6068 
ConvertRadius(const BorderRadiusProperty & value,Rosen::Vector4f & cornerRadius)6069 inline void RosenRenderContext::ConvertRadius(const BorderRadiusProperty& value, Rosen::Vector4f& cornerRadius)
6070 {
6071     cornerRadius.SetValues(static_cast<float>(value.radiusTopLeft.value_or(Dimension()).ConvertToPx()),
6072         static_cast<float>(value.radiusTopRight.value_or(Dimension()).ConvertToPx()),
6073         static_cast<float>(value.radiusBottomRight.value_or(Dimension()).ConvertToPx()),
6074         static_cast<float>(value.radiusBottomLeft.value_or(Dimension()).ConvertToPx()));
6075 }
6076 
PaintRSBgImage()6077 void RosenRenderContext::PaintRSBgImage()
6078 {
6079     auto image = DynamicCast<NG::DrawingImage>(bgImage_);
6080     CHECK_NULL_VOID(bgLoadingCtx_ && image);
6081     CHECK_NULL_VOID(rsNode_);
6082     auto rosenImage = std::make_shared<Rosen::RSImage>();
6083     auto compressData = image->GetCompressData();
6084     if (compressData) {
6085         rosenImage->SetCompressData(
6086             compressData, image->GetUniqueID(), image->GetCompressWidth(), image->GetCompressHeight());
6087     } else {
6088         rosenImage->SetImage(image->GetImage());
6089     }
6090     if (!HasValidBgImageResizable()) {
6091         rosenImage->SetImageRepeat(static_cast<int>(GetBackgroundImageRepeat().value_or(ImageRepeat::NO_REPEAT)));
6092     }
6093     rsNode_->SetBgImage(rosenImage);
6094 }
6095 
PaintPixmapBgImage()6096 void RosenRenderContext::PaintPixmapBgImage()
6097 {
6098     CHECK_NULL_VOID(rsNode_);
6099     auto image = DynamicCast<NG::PixelMapImage>(bgImage_);
6100     CHECK_NULL_VOID(bgLoadingCtx_ && image);
6101     auto pixmap = image->GetPixelMap();
6102     CHECK_NULL_VOID(pixmap);
6103 
6104     auto rosenImage = std::make_shared<Rosen::RSImage>();
6105     rosenImage->SetPixelMap(pixmap->GetPixelMapSharedPtr());
6106     if (!HasValidBgImageResizable()) {
6107         rosenImage->SetImageRepeat(static_cast<int>(GetBackgroundImageRepeat().value_or(ImageRepeat::NO_REPEAT)));
6108     }
6109     rsNode_->SetBgImage(rosenImage);
6110 }
6111 
OnRenderGroupUpdate(bool isRenderGroup)6112 void RosenRenderContext::OnRenderGroupUpdate(bool isRenderGroup)
6113 {
6114     CHECK_NULL_VOID(rsNode_);
6115     rsNode_->MarkNodeGroup(isRenderGroup);
6116 }
6117 
UpdateRenderGroup(bool isRenderGroup,bool isForced,bool includeProperty)6118 void RosenRenderContext::UpdateRenderGroup(bool isRenderGroup, bool isForced, bool includeProperty)
6119 {
6120     CHECK_NULL_VOID(rsNode_);
6121     rsNode_->MarkNodeGroup(isRenderGroup, isForced, includeProperty);
6122 }
6123 
OnNodeNameUpdate(const std::string & id)6124 void RosenRenderContext::OnNodeNameUpdate(const std::string& id)
6125 {
6126     CHECK_NULL_VOID(rsNode_);
6127     rsNode_->SetNodeName(id);
6128 }
6129 
OnSuggestedRenderGroupUpdate(bool isRenderGroup)6130 void RosenRenderContext::OnSuggestedRenderGroupUpdate(bool isRenderGroup)
6131 {
6132     CHECK_NULL_VOID(rsNode_);
6133     rsNode_->MarkNodeGroup(isRenderGroup, false);
6134 }
6135 
OnRenderFitUpdate(RenderFit renderFit)6136 void RosenRenderContext::OnRenderFitUpdate(RenderFit renderFit)
6137 {
6138     CHECK_NULL_VOID(rsNode_);
6139     rsNode_->SetFrameGravity(GetRosenGravity(renderFit));
6140 }
6141 
SetContentRectToFrame(RectF rect)6142 void RosenRenderContext::SetContentRectToFrame(RectF rect)
6143 {
6144     CHECK_NULL_VOID(rsNode_);
6145     auto host = GetHost();
6146     CHECK_NULL_VOID(host);
6147     if (adjustRSFrameByContentRect_) {
6148         auto geometryNode = host->GetGeometryNode();
6149         CHECK_NULL_VOID(geometryNode);
6150         auto contentRect = geometryNode->GetContentRect();
6151         rect.SetOffset(rect.GetOffset() + contentRect.GetOffset());
6152         rect.SetSize(contentRect.GetSize());
6153     } else {
6154         auto&& padding = host->GetGeometryNode()->GetPadding();
6155         // minus padding to get contentRect
6156         if (padding) {
6157             rect.SetOffset(rect.GetOffset() + OffsetF { padding->left.value_or(0), padding->top.value_or(0) });
6158             auto size = rect.GetSize();
6159             MinusPaddingToSize(*padding, size);
6160             rect.SetSize(size);
6161         }
6162     }
6163     rsNode_->SetFrame(rect.GetX(), rect.GetY(), rect.Width(), rect.Height());
6164 }
6165 
MarkNewFrameAvailable(void * nativeWindow)6166 void RosenRenderContext::MarkNewFrameAvailable(void* nativeWindow)
6167 {
6168     CHECK_NULL_VOID(rsNode_);
6169     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
6170     CHECK_NULL_VOID(rsSurfaceNode);
6171 #if defined(ANDROID_PLATFORM)
6172     rsSurfaceNode->MarkUiFrameAvailable(true);
6173 #endif
6174 #if defined(IOS_PLATFORM)
6175 #if defined(PLATFORM_VIEW_SUPPORTED)
6176     if (patternType_ == PatternType::PLATFORM_VIEW) {
6177         RSSurfaceExtConfig config = {
6178             .type = RSSurfaceExtType::SURFACE_PLATFORM_TEXTURE,
6179             .additionalData = nativeWindow,
6180         };
6181         rsSurfaceNode->SetSurfaceTexture(config);
6182         rsSurfaceNode->MarkUiFrameAvailable(true);
6183         return;
6184     }
6185 #endif
6186     RSSurfaceExtConfig config = {
6187         .type = RSSurfaceExtType::SURFACE_TEXTURE,
6188         .additionalData = nativeWindow,
6189     };
6190     rsSurfaceNode->SetSurfaceTexture(config);
6191 #endif
6192 }
6193 
AddAttachCallBack(const std::function<void (int64_t,bool)> & attachCallback)6194 void RosenRenderContext::AddAttachCallBack(const std::function<void(int64_t, bool)>& attachCallback)
6195 {
6196     CHECK_NULL_VOID(rsNode_);
6197 #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
6198     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
6199     CHECK_NULL_VOID(rsSurfaceNode);
6200     rsSurfaceNode->SetSurfaceTextureAttachCallBack(attachCallback);
6201 #endif
6202 }
6203 
AddUpdateCallBack(const std::function<void (std::vector<float> &)> & updateCallback)6204 void RosenRenderContext::AddUpdateCallBack(const std::function<void(std::vector<float>&)>& updateCallback)
6205 {
6206     CHECK_NULL_VOID(rsNode_);
6207 #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
6208     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
6209     CHECK_NULL_VOID(rsSurfaceNode);
6210     rsSurfaceNode->SetSurfaceTextureUpdateCallBack(updateCallback);
6211 #endif
6212 }
6213 
AddInitTypeCallBack(const std::function<void (int32_t &)> & initTypeCallback)6214 void RosenRenderContext::AddInitTypeCallBack(const std::function<void(int32_t&)>& initTypeCallback)
6215 {
6216     CHECK_NULL_VOID(rsNode_);
6217 #if defined(IOS_PLATFORM)
6218     auto rsSurfaceNode = rsNode_->ReinterpretCastTo<Rosen::RSSurfaceNode>();
6219     CHECK_NULL_VOID(rsSurfaceNode);
6220     rsSurfaceNode->SetSurfaceTextureInitTypeCallBack(initTypeCallback);
6221 #endif
6222 }
6223 
IsUniRenderEnabled()6224 bool RosenRenderContext::IsUniRenderEnabled()
6225 {
6226     return Rosen::RSSystemProperties::GetUniRenderEnabled();
6227 }
6228 
SetRotation(float rotationX,float rotationY,float rotationZ)6229 void RosenRenderContext::SetRotation(float rotationX, float rotationY, float rotationZ)
6230 {
6231     CHECK_NULL_VOID(rsNode_);
6232     rsNode_->SetRotation(rotationX, rotationY, rotationZ);
6233     NotifyHostTransformUpdated();
6234 }
6235 
SetShadowColor(uint32_t color)6236 void RosenRenderContext::SetShadowColor(uint32_t color)
6237 {
6238     CHECK_NULL_VOID(rsNode_);
6239     rsNode_->SetShadowColor(color);
6240 }
6241 
SetShadowOffset(float offsetX,float offsetY)6242 void RosenRenderContext::SetShadowOffset(float offsetX, float offsetY)
6243 {
6244     CHECK_NULL_VOID(rsNode_);
6245     rsNode_->SetShadowOffset(offsetX, offsetY);
6246 }
6247 
SetShadowAlpha(float alpha)6248 void RosenRenderContext::SetShadowAlpha(float alpha)
6249 {
6250     CHECK_NULL_VOID(rsNode_);
6251     rsNode_->SetShadowAlpha(alpha);
6252 }
6253 
SetShadowElevation(float elevation)6254 void RosenRenderContext::SetShadowElevation(float elevation)
6255 {
6256     CHECK_NULL_VOID(rsNode_);
6257     rsNode_->SetShadowElevation(elevation);
6258 }
6259 
SetShadowRadius(float radius)6260 void RosenRenderContext::SetShadowRadius(float radius)
6261 {
6262     CHECK_NULL_VOID(rsNode_);
6263     rsNode_->SetShadowRadius(radius);
6264 }
6265 
SetRenderFrameOffset(const OffsetF & offset)6266 void RosenRenderContext::SetRenderFrameOffset(const OffsetF& offset)
6267 {
6268     frameOffset_ = offset;
6269 }
6270 
SetScale(float scaleX,float scaleY)6271 void RosenRenderContext::SetScale(float scaleX, float scaleY)
6272 {
6273     CHECK_NULL_VOID(rsNode_);
6274     SetAnimatableProperty<Rosen::RSScaleModifier, Rosen::Vector2f>(scaleXYUserModifier_, { scaleX, scaleY });
6275     NotifyHostTransformUpdated();
6276 }
6277 
SetBackgroundColor(uint32_t colorValue)6278 void RosenRenderContext::SetBackgroundColor(uint32_t colorValue)
6279 {
6280     CHECK_NULL_VOID(rsNode_);
6281     rsNode_->SetBackgroundColor(colorValue);
6282 }
6283 
SetRenderPivot(float pivotX,float pivotY)6284 void RosenRenderContext::SetRenderPivot(float pivotX, float pivotY)
6285 {
6286     CHECK_NULL_VOID(rsNode_);
6287     rsNode_->SetPivot(pivotX, pivotY);
6288     NotifyHostTransformUpdated();
6289 }
6290 
SetFrame(float positionX,float positionY,float width,float height)6291 void RosenRenderContext::SetFrame(float positionX, float positionY, float width, float height)
6292 {
6293     CHECK_NULL_VOID(rsNode_);
6294     rsNode_->SetFrame(positionX, positionY, width, height);
6295 }
6296 
SetOpacity(float opacity)6297 void RosenRenderContext::SetOpacity(float opacity)
6298 {
6299     CHECK_NULL_VOID(rsNode_);
6300     rsNode_->SetAlpha(opacity);
6301 }
6302 
SetOpacityMultiplier(float opacity)6303 void RosenRenderContext::SetOpacityMultiplier(float opacity)
6304 {
6305     CHECK_NULL_VOID(rsNode_);
6306     SetAnimatableProperty<Rosen::RSAlphaModifier, float>(alphaModifier_, opacity);
6307 }
6308 
SetTranslate(float translateX,float translateY,float translateZ)6309 void RosenRenderContext::SetTranslate(float translateX, float translateY, float translateZ)
6310 {
6311     CHECK_NULL_VOID(rsNode_);
6312     SetAnimatableProperty<Rosen::RSTranslateModifier, Rosen::Vector2f>(
6313         translateXYUserModifier_, { translateX, translateY });
6314     SetAnimatableProperty<Rosen::RSTranslateZModifier, float>(translateZUserModifier_, translateZ);
6315     NotifyHostTransformUpdated();
6316 }
6317 
SetTransitionInCallback(std::function<void ()> && callback)6318 void RosenRenderContext::SetTransitionInCallback(std::function<void()>&& callback)
6319 {
6320     transitionInCallback_ = std::move(callback);
6321 }
6322 
SetTransitionOutCallback(std::function<void ()> && callback)6323 void RosenRenderContext::SetTransitionOutCallback(std::function<void()>&& callback)
6324 {
6325     transitionOutCallback_ = std::move(callback);
6326 }
6327 
SetTransitionUserCallback(TransitionFinishCallback && callback)6328 void RosenRenderContext::SetTransitionUserCallback(TransitionFinishCallback&& callback)
6329 {
6330     transitionUserCallback_ = std::move(callback);
6331 }
6332 
SetRectMask(const RectF & rect,const ShapeMaskProperty & property)6333 void RosenRenderContext::SetRectMask(const RectF& rect, const ShapeMaskProperty& property)
6334 {
6335     CHECK_NULL_VOID(rsNode_);
6336     RSPath path;
6337     path.AddRect(rect.Left(), rect.Top(), rect.Right(), rect.Bottom());
6338 
6339     RSBrush brush = GetRsBrush(property.fillColor);
6340     RSPen pen = GetRsPen(property.strokeColor, property.strokeWidth);
6341 
6342     std::shared_ptr<RSMask> mask = RSMask::CreatePathMask(path, pen, brush);
6343     rsNode_->SetMask(mask);
6344 }
6345 
SetCircleMask(const Circle & circle,const ShapeMaskProperty & property)6346 void RosenRenderContext::SetCircleMask(const Circle& circle, const ShapeMaskProperty& property)
6347 {
6348     CHECK_NULL_VOID(rsNode_);
6349     RSPath path;
6350     path.AddCircle(circle.GetAxisX().Value(), circle.GetAxisY().Value(), circle.GetRadius().Value());
6351 
6352     RSBrush brush = GetRsBrush(property.fillColor);
6353     RSPen pen = GetRsPen(property.strokeColor, property.strokeWidth);
6354 
6355     std::shared_ptr<RSMask> mask = RSMask::CreatePathMask(path, pen, brush);
6356     rsNode_->SetMask(mask);
6357 }
6358 
SetRoundRectMask(const RoundRect & roundRect,const ShapeMaskProperty & property)6359 void RosenRenderContext::SetRoundRectMask(const RoundRect& roundRect, const ShapeMaskProperty& property)
6360 {
6361     CHECK_NULL_VOID(rsNode_);
6362     RSRoundRect rsRoundRect;
6363 
6364     RSRect rsRect(roundRect.GetRect().Left(), roundRect.GetRect().Top(), roundRect.GetRect().Right(),
6365         roundRect.GetRect().Bottom());
6366     rsRoundRect.SetRect(rsRect);
6367 
6368     EdgeF edge = roundRect.GetCornerRadius(RoundRect::TOP_LEFT_POS);
6369     rsRoundRect.SetCornerRadius(RSRoundRect::TOP_LEFT_POS, edge.x, edge.y);
6370     edge = roundRect.GetCornerRadius(RoundRect::TOP_RIGHT_POS);
6371     rsRoundRect.SetCornerRadius(RSRoundRect::TOP_RIGHT_POS, edge.x, edge.y);
6372     edge = roundRect.GetCornerRadius(RoundRect::BOTTOM_LEFT_POS);
6373     rsRoundRect.SetCornerRadius(RSRoundRect::BOTTOM_LEFT_POS, edge.x, edge.y);
6374     edge = roundRect.GetCornerRadius(RoundRect::BOTTOM_RIGHT_POS);
6375     rsRoundRect.SetCornerRadius(RSRoundRect::BOTTOM_RIGHT_POS, edge.x, edge.y);
6376 
6377     RSPath path;
6378     path.AddRoundRect(rsRoundRect);
6379 
6380     RSBrush brush = GetRsBrush(property.fillColor);
6381     RSPen pen = GetRsPen(property.strokeColor, property.strokeWidth);
6382 
6383     std::shared_ptr<RSMask> mask = Rosen::RSMask::CreatePathMask(path, pen, brush);
6384     rsNode_->SetMask(mask);
6385 }
6386 
SetOvalMask(const RectF & rect,const ShapeMaskProperty & property)6387 void RosenRenderContext::SetOvalMask(const RectF& rect, const ShapeMaskProperty& property)
6388 {
6389     CHECK_NULL_VOID(rsNode_);
6390     RSRect rsRect(rect.Left(), rect.Top(), rect.Right(), rect.Bottom());
6391     RSPath path;
6392     path.AddOval(rsRect);
6393 
6394     RSBrush brush = GetRsBrush(property.fillColor);
6395     RSPen pen = GetRsPen(property.strokeColor, property.strokeWidth);
6396 
6397     std::shared_ptr<RSMask> mask = RSMask::CreatePathMask(path, pen, brush);
6398     rsNode_->SetMask(mask);
6399 }
6400 
SetCommandPathMask(const std::string & commands,const ShapeMaskProperty & property)6401 void RosenRenderContext::SetCommandPathMask(const std::string& commands, const ShapeMaskProperty& property)
6402 {
6403     CHECK_NULL_VOID(rsNode_);
6404     RSPath path;
6405     path.BuildFromSVGString(commands);
6406 
6407     RSBrush brush = GetRsBrush(property.fillColor);
6408     RSPen pen = GetRsPen(property.strokeColor, property.strokeWidth);
6409 
6410     std::shared_ptr<RSMask> mask = RSMask::CreatePathMask(path, pen, brush);
6411     rsNode_->SetMask(mask);
6412 }
6413 
SetMarkNodeGroup(bool isNodeGroup)6414 void RosenRenderContext::SetMarkNodeGroup(bool isNodeGroup)
6415 {
6416     CHECK_NULL_VOID(rsNode_);
6417     rsNode_->MarkNodeGroup(isNodeGroup);
6418 }
6419 
GetRotateDegree()6420 int32_t RosenRenderContext::GetRotateDegree()
6421 {
6422     CHECK_NULL_RETURN(rsNode_, 0);
6423     return static_cast<int32_t>(rsNode_->GetStagingProperties().GetRotation());
6424 }
6425 
ResetSurface(int width,int height)6426 void RosenRenderContext::ResetSurface(int width, int height)
6427 {
6428     auto rsCanvasDrawingNode = Rosen::RSNode::ReinterpretCast<Rosen::RSCanvasDrawingNode>(rsNode_);
6429     CHECK_NULL_VOID(rsCanvasDrawingNode);
6430     rsCanvasDrawingNode->ResetSurface(width, height);
6431 }
6432 
SavePaintRect(bool isRound,uint16_t flag)6433 void RosenRenderContext::SavePaintRect(bool isRound, uint16_t flag)
6434 {
6435     auto host = GetHost();
6436     CHECK_NULL_VOID(host);
6437     const auto& geometryNode = host->GetGeometryNode();
6438     CHECK_NULL_VOID(geometryNode);
6439     AdjustPaintRect();
6440     if (!SystemProperties::GetPixelRoundEnabled()) {
6441         // isRound is the switch of pixelRound of lower version
6442         isRound = false;
6443         // flag is the switch of pixelRound of upper version
6444         flag = NO_FORCE_ROUND;
6445     }
6446     if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_TWELVE)) {
6447         OnePixelRounding(flag);
6448     } else {
6449         if (isRound && flag == 0) {
6450             RoundToPixelGrid(); // call RoundToPixelGrid without param to improve performance
6451         } else {
6452             RoundToPixelGrid(isRound, flag);
6453         }
6454     }
6455     paintRect_ = RectF(geometryNode->GetPixelGridRoundOffset(), geometryNode->GetPixelGridRoundSize());
6456     if (SystemProperties::GetSyncDebugTraceEnabled()) {
6457         ACE_LAYOUT_SCOPED_TRACE("SavePaintRect[%s][self:%d] rs SavePaintRect %s", host->GetTag().c_str(), host->GetId(),
6458             paintRect_.ToString().c_str());
6459     }
6460 }
6461 
UpdatePaintRect(const RectF & paintRect)6462 void RosenRenderContext::UpdatePaintRect(const RectF& paintRect)
6463 {
6464     paintRect_ = paintRect;
6465 }
6466 
SyncPartialRsProperties()6467 void RosenRenderContext::SyncPartialRsProperties()
6468 {
6469     if (propTransform_ && propTransform_->HasTransformCenter()) {
6470         auto vec = propTransform_->GetTransformCenterValue();
6471         float xPivot = ConvertDimensionToScaleBySize(vec.GetX(), paintRect_.Width());
6472         float yPivot = ConvertDimensionToScaleBySize(vec.GetY(), paintRect_.Height());
6473         if (vec.GetZ().has_value()) {
6474             float zPivot = static_cast<float>(vec.GetZ().value().ConvertToVp());
6475             SetPivot(xPivot, yPivot, zPivot);
6476         } else {
6477             SetPivot(xPivot, yPivot);
6478         }
6479     }
6480 
6481     if (propTransform_ && propTransform_->HasTransformTranslate()) {
6482         // if translate unit is percent, it is related with frameSize
6483         OnTransformTranslateUpdate(propTransform_->GetTransformTranslateValue());
6484     }
6485 }
6486 
UpdateDrawRegion(uint32_t index,const std::shared_ptr<Rosen::RectF> & rect)6487 void RosenRenderContext::UpdateDrawRegion(uint32_t index, const std::shared_ptr<Rosen::RectF>& rect)
6488 {
6489     if (drawRegionRects_[index] && rect && *drawRegionRects_[index] == *rect) {
6490         return;
6491     } else if (!drawRegionRects_[index] && !rect) {
6492         return;
6493     }
6494     // the drawRegion of this index has changed
6495     drawRegionRects_[index] = rect;
6496     std::shared_ptr<Rosen::RectF> result;
6497     for (size_t index = 0; index < DRAW_REGION_RECT_COUNT; ++index) {
6498         if (drawRegionRects_[index]) {
6499             if (result) {
6500                 *result = result->JoinRect(*drawRegionRects_[index]);
6501             } else {
6502                 result = std::make_shared<Rosen::RectF>(*drawRegionRects_[index]);
6503             }
6504         }
6505     }
6506     if (!result) {
6507         return;
6508     }
6509     rsNode_->SetDrawRegion(result);
6510 }
6511 
NotifyHostTransformUpdated(bool changed)6512 void RosenRenderContext::NotifyHostTransformUpdated(bool changed)
6513 {
6514     auto host = GetHost();
6515     CHECK_NULL_VOID(host);
6516     host->NotifyTransformInfoChanged();
6517     host->OnNodeTransformInfoUpdate(changed);
6518     host->UpdateAccessibilityNodeRect();
6519 }
6520 
SuggestOpIncNode(bool isOpincNode,bool isNeedCalculate)6521 void RosenRenderContext::SuggestOpIncNode(bool isOpincNode, bool isNeedCalculate)
6522 {
6523     CHECK_NULL_VOID(rsNode_);
6524     rsNode_->MarkSuggestOpincNode(isOpincNode, isNeedCalculate);
6525 }
6526 
OnAttractionEffectUpdate(const AttractionEffect & effect)6527 void RosenRenderContext::OnAttractionEffectUpdate(const AttractionEffect& effect)
6528 {
6529     CHECK_NULL_VOID(rsNode_);
6530     Rosen::Vector2f destinationPoint(effect.destinationX.ConvertToPx(), effect.destinationY.ConvertToPx());
6531     rsNode_->SetAttractionEffect(effect.fraction, destinationPoint);
6532     RequestNextFrame();
6533 }
6534 
GetPipelineContext() const6535 PipelineContext* RosenRenderContext::GetPipelineContext() const
6536 {
6537     auto host = GetHost();
6538     if (host) {
6539         return host->GetContextWithCheck();
6540     }
6541     return PipelineContext::GetCurrentContextPtrSafelyWithCheck();
6542 }
6543 
UpdateWindowBlur()6544 void RosenRenderContext::UpdateWindowBlur()
6545 {
6546     auto pipeline = GetPipelineContext();
6547     CHECK_NULL_VOID(pipeline);
6548     if (pipeline->IsFormRender()) {
6549         return;
6550     }
6551     auto blurStyleTheme = pipeline->GetTheme<BlurStyleTheme>();
6552     if (!blurStyleTheme) {
6553         LOGW("cannot find theme of blurStyle, create blurStyle failed");
6554         return;
6555     }
6556     ThemeColorMode colorMode =
6557         GetResourceColorMode(pipeline) == ColorMode::DARK ? ThemeColorMode::DARK : ThemeColorMode::LIGHT;
6558     auto blurParam = blurStyleTheme->GetBlurParameter(BlurStyle::COMPONENT_ULTRA_THICK_WINDOW, colorMode);
6559     if (NearZero(blurParam->radius)) {
6560         return;
6561     }
6562     auto maskColor = LinearColor(blurParam->maskColor.GetValue());
6563     auto rgbaColor = (static_cast<uint32_t>(std::clamp<uint16_t>(maskColor.GetAlpha(), 0, UINT8_MAX))) |
6564                      (static_cast<uint32_t>((std::clamp<uint16_t>(maskColor.GetBlue(), 0, UINT8_MAX)) << 8)) |
6565                      (static_cast<uint32_t>((std::clamp<uint16_t>(maskColor.GetGreen(), 0, UINT8_MAX)) << 16)) |
6566                      (static_cast<uint32_t>((std::clamp<uint16_t>(maskColor.GetRed(), 0, UINT8_MAX)) << 24));
6567     if (!windowBlurModifier_.has_value()) {
6568         windowBlurModifier_ = WindowBlurModifier();
6569     }
6570     auto window = reinterpret_cast<RosenWindow*>(pipeline->GetWindow());
6571     CHECK_NULL_VOID(window);
6572     auto rsWindow = window->GetRSWindow();
6573     CHECK_NULL_VOID(rsWindow);
6574     auto surfaceNode = rsWindow->GetSurfaceNode();
6575     CHECK_NULL_VOID(surfaceNode);
6576     auto rsNodeTmp = Rosen::RSNodeMap::Instance().GetNode(surfaceNode->GetId());
6577     AnimationOption option;
6578     const int32_t duration = 400;
6579     option.SetDuration(duration);
6580     option.SetCurve(Curves::FRICTION);
6581     AnimationUtils::OpenImplicitAnimation(option, option.GetCurve(), nullptr);
6582     WindowBlurModifier::AddOrChangeRadiusModifier(rsNodeTmp, windowBlurModifier_->radius,
6583         windowBlurModifier_->radiusValue, blurParam->radius);
6584     WindowBlurModifier::AddOrChangeSaturationModifier(
6585         rsNodeTmp, windowBlurModifier_->saturation, windowBlurModifier_->saturationValue, blurParam->saturation);
6586     WindowBlurModifier::AddOrChangeMaskColorModifier(rsNodeTmp, windowBlurModifier_->maskColor,
6587         windowBlurModifier_->maskColorValue, Rosen::RSColor(rgbaColor));
6588     WindowBlurModifier::AddOrChangeBrightnessModifier(
6589         rsNodeTmp, windowBlurModifier_->brightness, windowBlurModifier_->brightnessValue, blurParam->brightness);
6590     AnimationUtils::CloseImplicitAnimation();
6591 }
6592 
MarkUiFirstNode(bool isUiFirstNode)6593 void RosenRenderContext::MarkUiFirstNode(bool isUiFirstNode)
6594 {
6595     CHECK_NULL_VOID(rsNode_);
6596     rsNode_->MarkUifirstNode(isUiFirstNode);
6597 }
6598 
BuildShadowInfo(std::unique_ptr<JsonValue> & json)6599 void RosenRenderContext::BuildShadowInfo(std::unique_ptr<JsonValue>& json)
6600 {
6601     if (!NearZero(rsNode_->GetStagingProperties().GetShadowOffsetY())) {
6602         json->Put("ShadowOffsetY", rsNode_->GetStagingProperties().GetShadowOffsetY());
6603     }
6604     if (!NearZero(rsNode_->GetStagingProperties().GetShadowAlpha())) {
6605         json->Put("ShadowAlpha", rsNode_->GetStagingProperties().GetShadowAlpha());
6606     }
6607     if (!NearZero(rsNode_->GetStagingProperties().GetShadowElevation())) {
6608         json->Put("ShadowElevation", rsNode_->GetStagingProperties().GetShadowElevation());
6609     }
6610     if (!NearZero(rsNode_->GetStagingProperties().GetShadowRadius())) {
6611         json->Put("ShadowRadius", rsNode_->GetStagingProperties().GetShadowRadius());
6612     }
6613 }
6614 
BuildStagingInfo(std::unique_ptr<JsonValue> & json)6615 void RosenRenderContext::BuildStagingInfo(std::unique_ptr<JsonValue>& json)
6616 {
6617     if (!NearZero(rsNode_->GetStagingProperties().GetPivotZ())) {
6618         json->Put("PivotZ", rsNode_->GetStagingProperties().GetPivotZ());
6619     }
6620     if (!NearZero(rsNode_->GetStagingProperties().GetRotation())) {
6621         json->Put("Rotation", rsNode_->GetStagingProperties().GetRotation());
6622     }
6623     if (!NearZero(rsNode_->GetStagingProperties().GetRotationX())) {
6624         json->Put("RotationX", rsNode_->GetStagingProperties().GetRotationX());
6625     }
6626     if (!NearZero(rsNode_->GetStagingProperties().GetRotationY())) {
6627         json->Put("RotationY", rsNode_->GetStagingProperties().GetRotationY());
6628     }
6629     if (!NearZero(rsNode_->GetStagingProperties().GetCameraDistance())) {
6630         json->Put("CameraDistance", rsNode_->GetStagingProperties().GetCameraDistance());
6631     }
6632     if (!NearZero(rsNode_->GetStagingProperties().GetTranslateZ())) {
6633         json->Put("TranslateZ", rsNode_->GetStagingProperties().GetTranslateZ());
6634     }
6635     if (!NearZero(rsNode_->GetStagingProperties().GetBgImageWidth())) {
6636         json->Put("BgImageWidth", rsNode_->GetStagingProperties().GetBgImageWidth());
6637     }
6638     if (!NearZero(rsNode_->GetStagingProperties().GetBgImageHeight())) {
6639         json->Put("BgImageHeight", rsNode_->GetStagingProperties().GetBgImageHeight());
6640     }
6641     if (!NearZero(rsNode_->GetStagingProperties().GetBgImagePositionX())) {
6642         json->Put("BgImagePositionX", rsNode_->GetStagingProperties().GetBgImagePositionX());
6643     }
6644     if (!NearZero(rsNode_->GetStagingProperties().GetBgImagePositionY())) {
6645         json->Put("BgImagePositionY", rsNode_->GetStagingProperties().GetBgImagePositionY());
6646     }
6647     BuildShadowInfo(json);
6648     if (!NearZero(rsNode_->GetStagingProperties().GetSpherizeDegree())) {
6649         json->Put("SpherizeDegree", rsNode_->GetStagingProperties().GetSpherizeDegree());
6650     }
6651     if (!NearZero(rsNode_->GetStagingProperties().GetLightUpEffectDegree())) {
6652         json->Put("LightUpEffectDegree", rsNode_->GetStagingProperties().GetLightUpEffectDegree());
6653     }
6654     if (!NearEqual(rsNode_->GetStagingProperties().GetAlpha(), 1)) {
6655         json->Put("Alpha", rsNode_->GetStagingProperties().GetAlpha());
6656     }
6657 }
6658 
BuildPositionInfo(std::unique_ptr<JsonValue> & json)6659 void RosenRenderContext::BuildPositionInfo(std::unique_ptr<JsonValue>& json)
6660 {
6661     json->Put("rsNode", rsNode_->DumpNode(0).c_str());
6662     auto center = rsNode_->GetStagingProperties().GetPivot();
6663     if (!NearEqual(center[0], 0.5) || !NearEqual(center[1], 0.5)) {
6664         auto child = JsonUtil::Create(true);
6665         child->Put("x", center[0]);
6666         child->Put("y", center[1]);
6667         json->Put("Center", child);
6668     }
6669     BuildStagingInfo(json);
6670     auto translate = rsNode_->GetStagingProperties().GetTranslate();
6671     if (!(NearZero(translate[0]) && NearZero(translate[1]))) {
6672         auto child = JsonUtil::Create(true);
6673         child->Put("x", translate[0]);
6674         child->Put("y", translate[1]);
6675         json->Put("translate", child);
6676     }
6677     auto scale = rsNode_->GetStagingProperties().GetScale();
6678     if (!(NearEqual(scale[0], 1) && NearEqual(scale[1], 1))) {
6679         auto child = JsonUtil::Create(true);
6680         child->Put("x", scale[0]);
6681         child->Put("y", scale[1]);
6682         json->Put("scale", child);
6683     }
6684     auto rect = GetPaintRectWithoutTransform();
6685     if (HasTransformTranslate()) {
6686         auto translateArk = GetTransformTranslate().value();
6687         auto arkTranslateX = translateArk.x.ConvertToPxWithSize(rect.Width());
6688         auto arkTranslateY = translateArk.y.ConvertToPxWithSize(rect.Height());
6689         if (!NearEqual(arkTranslateX, translate[0])) {
6690             json->Put("TranlateX has difference,arkui", std::to_string(arkTranslateX).c_str());
6691         }
6692         if (!NearEqual(arkTranslateY, translate[1])) {
6693             json->Put("TranlateY has difference,arkui", std::to_string(arkTranslateY).c_str());
6694         }
6695     }
6696     if (HasTransformScale()) {
6697         auto arkTransformScale = GetTransformScale().value();
6698         if (!NearEqual(arkTransformScale.x, scale[0])) {
6699             json->Put("scaleX has difference,arkui", std::to_string(arkTransformScale.x).c_str());
6700         }
6701         if (!NearEqual(arkTransformScale.y, scale[1])) {
6702             json->Put("scaleY has difference,arkui", std::to_string(arkTransformScale.y).c_str());
6703         }
6704     }
6705 }
6706 
DumpInfo(std::unique_ptr<JsonValue> & json)6707 void RosenRenderContext::DumpInfo(std::unique_ptr<JsonValue>& json)
6708 {
6709     if (rsNode_) {
6710         auto children = JsonUtil::Create(true);
6711         BuildPositionInfo(children);
6712         if (HasOpacity()) {
6713             auto arkAlpha = GetOpacity();
6714             if (!NearEqual(arkAlpha.value(), rsNode_->GetStagingProperties().GetAlpha())) {
6715                 children->Put("Alpha has difference,arkui", std::to_string(arkAlpha.value()).c_str());
6716             }
6717         }
6718         if (HasPosition()) {
6719             auto position = GetPosition();
6720             children->Put("PositionX", position->GetX().ToString().c_str());
6721             children->Put("PositionY", position->GetY().ToString().c_str());
6722         }
6723         if (HasOffset()) {
6724             auto offset = GetOffset();
6725             children->Put("OffsetX", offset->GetX().ToString().c_str());
6726             children->Put("OffsetY", offset->GetY().ToString().c_str());
6727         }
6728         if (HasPositionEdges()) {
6729             auto positionEdges = GetPositionEdges();
6730             children->Put("positionEdges", positionEdges->ToString().c_str());
6731         }
6732         if (HasOffsetEdges()) {
6733             auto offsetEdges = GetOffsetEdges();
6734             children->Put("offsetEdges", offsetEdges->ToString().c_str());
6735         }
6736         if (HasAnchor()) {
6737             auto anchor = GetAnchor();
6738             children->Put("anchorX", anchor->GetX().ToString().c_str());
6739             children->Put("anchorY", anchor->GetY().ToString().c_str());
6740         }
6741         json->Put("rsNode", children);
6742     }
6743 }
6744 
DumpAdvanceInfo(std::unique_ptr<JsonValue> & json)6745 void RosenRenderContext::DumpAdvanceInfo(std::unique_ptr<JsonValue>& json)
6746 {
6747     if (GetBackgroundAlign().has_value()) {
6748         json->Put("BackgroundAlign", GetBackgroundAlign().value().ToString().c_str());
6749     }
6750     if (GetBackgroundImage().has_value()) {
6751         json->Put("BackgroundImage", GetBackgroundImage().value().ToString().c_str());
6752     }
6753     if (GetSphericalEffect().has_value()) {
6754         json->Put("SphericalEffect", std::to_string(GetSphericalEffect().value()).c_str());
6755     }
6756     if (GetPixelStretchEffect().has_value()) {
6757         json->Put("PixelStretchEffect", GetPixelStretchEffect().value().ToString().c_str());
6758     }
6759     if (GetLightUpEffect().has_value()) {
6760         json->Put("LightUpEffect", std::to_string(GetLightUpEffect().value()).c_str());
6761     }
6762     if (GetBorderColor().has_value()) {
6763         json->Put("BorderColor", GetBorderColor().value().ToString().c_str());
6764     }
6765     if (GetBorderWidth().has_value()) {
6766         json->Put("BorderWidth", GetBorderWidth().value().ToString().c_str());
6767     }
6768     if (GetOuterBorderRadius().has_value()) {
6769         json->Put("OuterBorderRadius", GetOuterBorderRadius().value().ToString().c_str());
6770     }
6771     if (GetOuterBorderColor().has_value()) {
6772         json->Put("OuterBorderColor", GetOuterBorderColor().value().ToString().c_str());
6773     }
6774     if (GetOuterBorderWidth().has_value()) {
6775         json->Put("OuterBorderWidth", GetOuterBorderWidth().value().ToString().c_str());
6776     }
6777     if (GetDynamicLightUpRate().has_value()) {
6778         json->Put("DynamicLightUpRate", std::to_string(GetDynamicLightUpRate().value()).c_str());
6779     }
6780     if (GetDynamicLightUpDegree().has_value()) {
6781         json->Put("DynamicLightUpDegree", std::to_string(GetDynamicLightUpDegree().value()).c_str());
6782     }
6783     if (GetBackBlendMode().has_value()) {
6784         json->Put("BlendMode", static_cast<int>(GetBackBlendMode().value()));
6785     }
6786     if (GetLinearGradient().has_value()) {
6787         json->Put("LinearGradient", GetLinearGradient().value().ToString().c_str());
6788     }
6789     if (GetSweepGradient().has_value()) {
6790         json->Put("SweepGradient", GetSweepGradient().value().ToString().c_str());
6791     }
6792     SetAdvanceInfo(json);
6793 }
6794 
SetAdvanceInfo(std::unique_ptr<JsonValue> & json)6795 void RosenRenderContext::SetAdvanceInfo(std::unique_ptr<JsonValue>& json)
6796 {
6797     if (GetRadialGradient().has_value()) {
6798         json->Put("RadialGradient", GetRadialGradient().value().ToString().c_str());
6799     }
6800     if (GetFrontBrightness().has_value()) {
6801         json->Put("FrontBrightness", GetFrontBrightness().value().ToString().c_str());
6802     }
6803     if (GetFrontGrayScale().has_value()) {
6804         json->Put("FrontGrayScale", GetFrontGrayScale().value().ToString().c_str());
6805     }
6806     if (GetFrontContrast().has_value()) {
6807         json->Put("FrontContrast", GetFrontContrast().value().ToString().c_str());
6808     }
6809     if (GetFrontSaturate().has_value()) {
6810         json->Put("FrontSaturate", GetFrontSaturate().value().ToString().c_str());
6811     }
6812     if (GetFrontSepia().has_value()) {
6813         json->Put("FrontSepia", GetFrontSepia().value().ToString().c_str());
6814     }
6815     if (GetFrontHueRotate().has_value()) {
6816         json->Put("FrontHueRotate", std::to_string(GetFrontHueRotate().value()).c_str());
6817     }
6818     if (GetFrontColorBlend().has_value()) {
6819         json->Put("FrontColorBlend", GetFrontColorBlend().value().ColorToString().c_str());
6820     }
6821     if (GetBorderImageSource().has_value()) {
6822         json->Put("BorderImageSource", GetBorderImageSource().value().ToString().c_str());
6823     }
6824     if (GetBorderImageGradient().has_value()) {
6825         json->Put("BorderImageGradient", GetBorderImageGradient().value().ToString().c_str());
6826     }
6827     if (GetForegroundColor().has_value()) {
6828         json->Put("ForegroundColor", GetForegroundColor().value().ColorToString().c_str());
6829     }
6830     if (GetLightIntensity().has_value()) {
6831         json->Put("LightIntensity", std::to_string(GetLightIntensity().value()).c_str());
6832     }
6833     if (GetLightIlluminated().has_value()) {
6834         json->Put("LightIlluminated", std::to_string(GetLightIlluminated().value()).c_str());
6835     }
6836     if (GetIlluminatedBorderWidth().has_value()) {
6837         json->Put("IlluminatedBorderWidth", GetIlluminatedBorderWidth().value().ToString().c_str());
6838     }
6839     if (GetBloom().has_value()) {
6840         json->Put("Bloom", std::to_string(GetBloom().value()).c_str());
6841     }
6842 }
6843 
DumpSimplifyInfo(std::unique_ptr<JsonValue> & json)6844 void RosenRenderContext::DumpSimplifyInfo(std::unique_ptr<JsonValue>& json)
6845 {
6846     if (rsNode_) {
6847         DumpSimplifyStagingProperties(json);
6848         if (!NearZero(rsNode_->GetStagingProperties().GetPivotZ())) {
6849             json->Put("PivotZ", std::to_string(rsNode_->GetStagingProperties().GetPivotZ()).c_str());
6850         }
6851         if (!NearZero(rsNode_->GetStagingProperties().GetRotation())) {
6852             json->Put("Rotation", std::to_string(rsNode_->GetStagingProperties().GetRotation()).c_str());
6853         }
6854         if (!NearZero(rsNode_->GetStagingProperties().GetRotationX())) {
6855             json->Put("RotationX", std::to_string(rsNode_->GetStagingProperties().GetRotationX()).c_str());
6856         }
6857         if (!NearZero(rsNode_->GetStagingProperties().GetRotationY())) {
6858             json->Put("RotationY", std::to_string(rsNode_->GetStagingProperties().GetRotationY()).c_str());
6859         }
6860         if (!NearEqual(rsNode_->GetStagingProperties().GetAlpha(), 1)) {
6861             json->Put("Alpha", std::to_string(rsNode_->GetStagingProperties().GetAlpha()).c_str());
6862         }
6863         if (HasPosition()) {
6864             auto position = GetPosition();
6865             json->Put("Position",
6866                 position->GetX().ToString().append(",").append(position->GetY().ToString()).c_str());
6867         }
6868         if (HasOffset()) {
6869             auto offset = GetOffset();
6870             json->Put("Offset", offset->GetX().ToString().append(",").append(offset->GetY().ToString()).c_str());
6871         }
6872         if (HasPositionEdges()) {
6873             auto positionEdges = GetPositionEdges();
6874             json->Put("PositionEdges", positionEdges->ToString().c_str());
6875         }
6876         if (HasOffsetEdges()) {
6877             auto offsetEdges = GetOffsetEdges();
6878             json->Put("OffsetEdges", offsetEdges->ToString().c_str());
6879         }
6880         if (HasAnchor()) {
6881             auto anchor = GetAnchor();
6882             json->Put("Anchor", anchor->GetX().ToString().append(",").append(anchor->GetY().ToString()).c_str());
6883         }
6884     }
6885 }
6886 
DumpSimplifyStagingProperties(std::unique_ptr<JsonValue> & json)6887 void RosenRenderContext::DumpSimplifyStagingProperties(std::unique_ptr<JsonValue>& json)
6888 {
6889     auto center = rsNode_->GetStagingProperties().GetPivot();
6890     if (!NearEqual(center[0], 0.5) || !NearEqual(center[1], 0.5)) {
6891         json->Put("Center", std::to_string(center[0]).append(",").append(std::to_string(center[1])).c_str());
6892     }
6893     auto translate = rsNode_->GetStagingProperties().GetTranslate();
6894     if (!(NearZero(translate[0]) && NearZero(translate[1]))) {
6895         json->Put("Translate",
6896             std::to_string(translate[0]).append(",").append(std::to_string(translate[1])).c_str());
6897     }
6898     auto scale = rsNode_->GetStagingProperties().GetScale();
6899     if (!(NearEqual(scale[0], 1) && NearEqual(scale[1], 1))) {
6900         json->Put("Scale", std::to_string(scale[0]).append(",").append(std::to_string(scale[1])).c_str());
6901     }
6902     if (HasTransformScale()) {
6903         auto arkTransformScale = GetTransformScale().value();
6904         if (!NearEqual(arkTransformScale.x, scale[0])) {
6905             json->Put("TransformScaleX", std::to_string(arkTransformScale.x).c_str());
6906         }
6907         if (!NearEqual(arkTransformScale.y, scale[1])) {
6908             json->Put("TransformScaleY", std::to_string(arkTransformScale.y).c_str());
6909         }
6910     }
6911     auto rect = GetPaintRectWithoutTransform();
6912     if (HasTransformTranslate()) {
6913         auto translateArk = GetTransformTranslate().value();
6914         auto arkTranslateX = translateArk.x.ConvertToPxWithSize(rect.Width());
6915         auto arkTranslateY = translateArk.y.ConvertToPxWithSize(rect.Height());
6916         if (!NearEqual(arkTranslateX, translate[0])) {
6917             json->Put("TransformTranslateX", std::to_string(arkTranslateX).c_str());
6918         }
6919         if (!NearEqual(arkTranslateY, translate[1])) {
6920             json->Put("TransformTranslateY", std::to_string(arkTranslateY).c_str());
6921         }
6922     }
6923     if (HasOpacity()) {
6924         auto arkAlpha = GetOpacity();
6925         if (!NearEqual(arkAlpha.value(), rsNode_->GetStagingProperties().GetAlpha())) {
6926             json->Put("TransformAlpha", std::to_string(arkAlpha.value()).c_str());
6927         }
6928     }
6929 }
6930 
FreezeCanvasNode(bool freezeFlag)6931 void RosenRenderContext::FreezeCanvasNode(bool freezeFlag)
6932 {
6933     if (canvasNode_) {
6934         TAG_LOGD(AceLogTag::ACE_WINDOW, "FreezeCanvasNode. %{public}d", freezeFlag);
6935         canvasNode_->SetFreeze(freezeFlag);
6936     }
6937 }
6938 
RemoveCanvasNode()6939 void RosenRenderContext::RemoveCanvasNode()
6940 {
6941     if (canvasNode_) {
6942         TAG_LOGD(AceLogTag::ACE_WINDOW, "RemoveCanvasNode.");
6943         canvasNode_->RemoveFromTree();
6944         canvasNode_ = nullptr;
6945     }
6946 }
6947 
CheckAnimationParametersValid(int32_t & animationParam)6948 void RosenRenderContext::CheckAnimationParametersValid(int32_t& animationParam)
6949 {
6950     const int32_t maxTime = 2000;
6951     const int32_t defaultTime = 100;
6952     if (animationParam <= 0 || animationParam > maxTime) {
6953         animationParam = defaultTime;
6954     }
6955 }
6956 
SetCanvasNodeOpacityAnimation(int32_t duration,int32_t delay,bool isDragEnd)6957 bool RosenRenderContext::SetCanvasNodeOpacityAnimation(int32_t duration, int32_t delay, bool isDragEnd)
6958 {
6959     static bool animationFlag = false;
6960     if (animationFlag) {
6961         TAG_LOGD(AceLogTag::ACE_WINDOW, "animationFlag is true.");
6962         return false;
6963     }
6964     if (!canvasNode_) {
6965         return true;
6966     }
6967 
6968     FreezeCanvasNode(true);
6969     canvasNode_->SetAlpha(1.0f);
6970     Rosen::RSTransaction::FlushImplicitTransaction();
6971 
6972     CheckAnimationParametersValid(duration);
6973     CheckAnimationParametersValid(delay);
6974     AnimationOption option;
6975     option.SetDuration(duration);
6976     option.SetDelay(delay);
6977     option.SetCurve(Curves::EASE_OUT);
6978     AnimationUtils::Animate(option,
6979         [this]() {
6980             if (canvasNode_) {
6981                 animationFlag = true;
6982                 canvasNode_->SetAlpha(0.0f);
6983             }
6984         },
6985         [this, isDragEnd]() {
6986             if (canvasNode_) {
6987                 canvasNode_->SetAlpha(1.0f);
6988             }
6989             FreezeCanvasNode(false);
6990             if (isDragEnd) {
6991                 RemoveCanvasNode();
6992             }
6993             if (callbackAnimateEnd_) {
6994                 callbackAnimateEnd_();
6995             }
6996             Rosen::RSTransaction::FlushImplicitTransaction();
6997             animationFlag = false;
6998             if (callbackCachedAnimateAction_) {
6999                 callbackCachedAnimateAction_();
7000             }
7001         });
7002         return true;
7003 }
7004 
LinkCanvasNodeToRootNode(const RefPtr<FrameNode> & rootNode)7005 void RosenRenderContext::LinkCanvasNodeToRootNode(const RefPtr<FrameNode>& rootNode)
7006 {
7007     if (canvasNode_ && rootNode) {
7008         TAG_LOGD(AceLogTag::ACE_WINDOW, "SetLinkedRootNodeId");
7009         canvasNode_->SetLinkedRootNodeId(rootNode->GetRenderContext()->GetNodeId());
7010         Rosen::RSTransaction::FlushImplicitTransaction();
7011     }
7012 }
7013 
GetCanvasNode()7014 std::shared_ptr<Rosen::RSCanvasNode> RosenRenderContext::GetCanvasNode()
7015 {
7016     if (!canvasNode_) {
7017         TAG_LOGD(AceLogTag::ACE_WINDOW, "Create RSCanvasNode.");
7018         canvasNode_ = Rosen::RSCanvasNode::Create();
7019         Rosen::RSTransaction::FlushImplicitTransaction();
7020     }
7021     return canvasNode_;
7022 }
7023 } // namespace OHOS::Ace::NG
7024