• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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/button/render_button.h"
17 
18 #include "base/log/event_report.h"
19 #include "base/log/log.h"
20 #include "base/memory/ace_type.h"
21 #include "core/accessibility/accessibility_node.h"
22 #include "core/animation/keyframe_animation.h"
23 #include "core/common/frontend.h"
24 #include "core/components/button/button_theme.h"
25 #include "core/components/common/properties/alignment.h"
26 #include "core/components/theme/theme_manager.h"
27 #include "core/event/ace_event_helper.h"
28 
29 namespace OHOS::Ace {
30 namespace {
31 
32 // Watch button definitions
33 constexpr Dimension TEXT_BUTTON_MAX_WIDTH = 116.5_vp;
34 
35 // Download button definitions
36 constexpr double DOWNLOAD_FULL_PERCENT = 100.0;
37 constexpr double MAX_TRANSITION_TIME = 5000.0;
38 constexpr double MIN_TRANSITION_TIME = 200.0;
39 constexpr double MILLISECOND_PER_PERCENT = 20.0;
40 constexpr double SECOND_TO_MILLISECOND = 1000.0;
41 
42 // Definition for animation
43 constexpr double TV_EXPAND_SCALE = 1.05;
44 constexpr double TV_REDUCE_SCALE = 0.95;
45 constexpr double WATCH_SCALE = 0.8;
46 constexpr double MASKING_ANIMATION_RATIO = 10.0;
47 constexpr float KEY_TIME_START = 0.0f;
48 constexpr float KEY_TIME_MID = 0.5f;
49 constexpr float KEY_TIME_END = 1.0f;
50 constexpr float PRESS_UP_OPACITY = 1.0f;
51 constexpr float PRESS_DOWN_OPACITY = 0.95f;
52 constexpr int32_t WATCH_DURATION_DOWN = 200;
53 constexpr int32_t WATCH_DURATION_UP = 250;
54 constexpr int32_t TV_CLICK_DURATION = 200;
55 constexpr int32_t TV_FOCUS_SCALE_DURATION = 100;
56 constexpr int32_t HOVER_ANIMATION_DURATION = 250;
57 constexpr int32_t PRESS_ANIMATION_DURATION = 100;
58 
59 } // namespace
60 
RenderButton()61 RenderButton::RenderButton()
62 {
63     Initialize();
64 }
65 
Initialize()66 void RenderButton::Initialize()
67 {
68     auto wp = AceType::WeakClaim(this);
69     touchRecognizer_ = AceType::MakeRefPtr<RawRecognizer>();
70     touchRecognizer_->SetOnTouchDown([wp](const TouchEventInfo&) {
71         auto button = wp.Upgrade();
72         if (button) {
73             button->HandleTouchEvent(true);
74         }
75     });
76     touchRecognizer_->SetOnTouchUp([wp](const TouchEventInfo&) {
77         auto button = wp.Upgrade();
78         if (button) {
79             button->HandleTouchEvent(false);
80         }
81     });
82     touchRecognizer_->SetOnTouchCancel([wp](const TouchEventInfo&) {
83         auto button = wp.Upgrade();
84         if (button) {
85             button->HandleTouchEvent(false);
86         }
87     });
88     touchRecognizer_->SetOnTouchMove([wp](const TouchEventInfo& info) {
89         auto button = wp.Upgrade();
90         if (button) {
91             button->HandleMoveEvent(info);
92         }
93     });
94 
95     clickRecognizer_ = AceType::MakeRefPtr<ClickRecognizer>();
96     clickRecognizer_->SetOnClick([wp](const ClickInfo& info) {
97         auto button = wp.Upgrade();
98         if (button) {
99             const auto context = button->GetContext().Upgrade();
100             if (context && context->GetIsDeclarative()) {
101                 button->HandleClickEvent(info);
102             } else {
103                 button->HandleClickEvent();
104             }
105         }
106     });
107     clickRecognizer_->SetRemoteMessage([wp](const ClickInfo& info) {
108         auto button = wp.Upgrade();
109         if (button) {
110             const auto context = button->GetContext().Upgrade();
111             if (context && context->GetIsDeclarative()) {
112                 button->HandleRemoteMessageEvent(info);
113             } else {
114                 button->HandleRemoteMessageEvent();
115             }
116         }
117     });
118 }
119 
InitAccessibilityEventListener()120 void RenderButton::InitAccessibilityEventListener()
121 {
122     auto refNode = accessibilityNode_.Upgrade();
123     if (!refNode) {
124         return;
125     }
126     refNode->AddSupportAction(AceAction::ACTION_ACCESSIBILITY_FOCUS);
127 
128     auto weakPtr = AceType::WeakClaim(this);
129     refNode->SetActionFocusImpl([weakPtr]() {
130         auto button = weakPtr.Upgrade();
131         if (button) {
132             button->HandleFocusEvent(true);
133         }
134     });
135 }
136 
OnPaintFinish()137 void RenderButton::OnPaintFinish()
138 {
139     if (isFocus_) {
140         if (isTv_) {
141             DisplayFocusAnimation();
142         }
143         if (isPhone_) {
144             UpdateFocusAnimation(INIT_SCALE);
145         }
146     }
147     UpdateAccessibility();
148     InitAccessibilityEventListener();
149 }
150 
UpdateAccessibility()151 void RenderButton::UpdateAccessibility()
152 {
153     const auto& context = context_.Upgrade();
154     if (!context) {
155         return;
156     }
157     auto viewScale = context->GetViewScale();
158     if (NearZero(viewScale)) {
159         return;
160     }
161     auto accessibilityNode = GetAccessibilityNode().Upgrade();
162     if (!accessibilityNode) {
163         return;
164     }
165 #if defined(PREVIEW)
166     Offset globalOffset = GetGlobalOffset();
167     if (isTv_ && isFocus_) {
168         Size size = GetLayoutSize();
169         Offset scaleCenter =
170             Offset(globalOffset.GetX() + size.Width() / 2.0, globalOffset.GetY() + size.Height() / 2.0);
171         accessibilityNode->SetScaleCenter(scaleCenter);
172         accessibilityNode->SetScale(TV_EXPAND_SCALE);
173     }
174 #else
175     // control button without box
176     UpdateAccessibilityPosition();
177 #endif
178     accessibilityNode->SetMarginSize(Size());
179     if (!GetAccessibilityText().empty()) {
180         accessibilityNode->SetAccessibilityLabel(GetAccessibilityText());
181     }
182 }
183 
HandleTouchEvent(bool isTouch)184 void RenderButton::HandleTouchEvent(bool isTouch)
185 {
186     isClicked_ = isTouch;
187     if (isClicked_) {
188         OnStatusStyleChanged(VisualState::PRESSED);
189         isMoveEventValid_ = true;
190     } else {
191         OnStatusStyleChanged(VisualState::NORMAL);
192     }
193     if (isMoveEventValid_ || isWatch_) {
194         PlayTouchAnimation();
195     }
196 }
197 
HandleMoveEvent(const TouchEventInfo & info)198 void RenderButton::HandleMoveEvent(const TouchEventInfo& info)
199 {
200     if (!isMoveEventValid_) {
201         return;
202     }
203     if (info.GetTouches().empty()) {
204         return;
205     }
206     const auto& locationInfo = info.GetTouches().front();
207     double moveDeltaX = locationInfo.GetLocalLocation().GetX();
208     double moveDeltaY = locationInfo.GetLocalLocation().GetY();
209     if ((moveDeltaX < 0 || moveDeltaX > buttonSize_.Width()) || (moveDeltaY < 0 || moveDeltaY > buttonSize_.Height())) {
210         isClicked_ = false;
211         MarkNeedRender();
212         OnStatusStyleChanged(VisualState::NORMAL);
213         isMoveEventValid_ = false;
214     }
215 }
216 
HandleClickEvent(const ClickInfo & info)217 void RenderButton::HandleClickEvent(const ClickInfo& info)
218 {
219     if (!buttonComponent_) {
220         return;
221     }
222     auto onClickWithInfo =
223         AceAsyncEvent<void(const ClickInfo&)>::Create(buttonComponent_->GetClickedEventId(), context_);
224     if (onClickWithInfo) {
225         onClickWithInfo(info);
226     }
227     PlayClickAnimation();
228 }
229 
HandleClickEvent()230 void RenderButton::HandleClickEvent()
231 {
232     if (!buttonComponent_) {
233         return;
234     }
235     auto onClick = AceAsyncEvent<void()>::Create(buttonComponent_->GetClickedEventId(), context_);
236     if (onClick) {
237         onClick();
238     }
239     PlayClickAnimation();
240 }
241 
HandleKeyEnterEvent(const ClickInfo & info)242 bool RenderButton::HandleKeyEnterEvent(const ClickInfo& info)
243 {
244     if (!buttonComponent_) {
245         return false;
246     }
247     auto onEnterWithInfo =
248         AceAsyncEvent<void(const ClickInfo&)>::Create(buttonComponent_->GetKeyEnterEventId(), context_);
249     if (onEnterWithInfo) {
250         onEnterWithInfo(info);
251         return true;
252     }
253     return false;
254 }
255 
HandleKeyEnterEvent()256 void RenderButton::HandleKeyEnterEvent()
257 {
258     if (!buttonComponent_) {
259         return;
260     }
261     auto onEnter = AceAsyncEvent<void()>::Create(buttonComponent_->GetKeyEnterEventId(), context_);
262     if (onEnter) {
263         onEnter();
264     }
265 }
266 
HandleRemoteMessageEvent(const ClickInfo & info)267 void RenderButton::HandleRemoteMessageEvent(const ClickInfo& info)
268 {
269     if (!buttonComponent_) {
270         return;
271     }
272     auto onRemoteMessagekWithInfo =
273         AceAsyncEvent<void(const ClickInfo&)>::Create(buttonComponent_->GetRemoteMessageEventId(), context_);
274     if (onRemoteMessagekWithInfo) {
275         onRemoteMessagekWithInfo(info);
276     }
277     PlayClickAnimation();
278 }
279 
HandleRemoteMessageEvent()280 void RenderButton::HandleRemoteMessageEvent()
281 {
282     if (!buttonComponent_) {
283         return;
284     }
285     auto onRemoteMessage = AceAsyncEvent<void()>::Create(buttonComponent_->GetRemoteMessageEventId(), context_);
286     if (onRemoteMessage) {
287         onRemoteMessage();
288     }
289     PlayClickAnimation();
290 }
291 
OnTouchTestHit(const Offset & coordinateOffset,const TouchRestrict & touchRestrict,TouchTestResult & result)292 void RenderButton::OnTouchTestHit(
293     const Offset& coordinateOffset, const TouchRestrict& touchRestrict, TouchTestResult& result)
294 {
295     if ((!touchRecognizer_) || (!clickRecognizer_)) {
296         return;
297     }
298     touchRecognizer_->SetCoordinateOffset(coordinateOffset);
299     result.emplace_back(touchRecognizer_);
300     result.emplace_back(clickRecognizer_);
301 }
302 
HandleFocusEvent(bool isFocus)303 void RenderButton::HandleFocusEvent(bool isFocus)
304 {
305     isFocus_ = isFocus;
306     needFocusColor_ = isFocus_ && isTv_;
307     MarkNeedRender();
308 }
309 
DisplayFocusAnimation()310 void RenderButton::DisplayFocusAnimation()
311 {
312     if (!animationRunning_ && isTv_) {
313         UpdateAnimationParam(TV_EXPAND_SCALE);
314     }
315 }
316 
AnimateMouseHoverEnter()317 void RenderButton::AnimateMouseHoverEnter()
318 {
319     OnMouseHoverEnterTest();
320 }
OnMouseHoverEnterTest()321 void RenderButton::OnMouseHoverEnterTest()
322 {
323     if (!buttonComponent_) {
324         return;
325     }
326     if (hoverAnimationType_ == HoverAnimationType::NONE) {
327         if (buttonComponent_->IsPopupButton()) {
328             needHoverColor_ = true;
329             MarkNeedRender();
330         }
331         LOGW("HoverAnimationType: %{public}d is not supported in this component.", hoverAnimationType_);
332         return;
333     }
334     ButtonType type = buttonComponent_->GetType();
335     if ((isPhone_ || isTablet_) && ((type == ButtonType::TEXT) || (type == ButtonType::NORMAL))) {
336         needHoverColor_ = true;
337         MarkNeedRender();
338     } else {
339         ResetController(hoverControllerExit_);
340         if (!hoverControllerEnter_) {
341             hoverControllerEnter_ = CREATE_ANIMATOR(context_);
342         }
343         scaleAnimationEnter_ = AceType::MakeRefPtr<KeyframeAnimation<float>>();
344         CreateFloatAnimation(scaleAnimationEnter_, 1.0, 1.05);
345         hoverControllerEnter_->AddInterpolator(scaleAnimationEnter_);
346         hoverControllerEnter_->SetDuration(HOVER_ANIMATION_DURATION);
347         hoverControllerEnter_->Play();
348         hoverControllerEnter_->SetFillMode(FillMode::FORWARDS);
349     }
350 }
351 
AnimateMouseHoverExit()352 void RenderButton::AnimateMouseHoverExit()
353 {
354     OnMouseHoverExitTest();
355 }
OnMouseHoverExitTest()356 void RenderButton::OnMouseHoverExitTest()
357 {
358     if (hoverAnimationType_ == HoverAnimationType::NONE && !buttonComponent_->IsPopupButton()) {
359         LOGW("HoverAnimationType: %{public}d is not supported in this component.", hoverAnimationType_);
360         return;
361     }
362     if (needHoverColor_) {
363         needHoverColor_ = false;
364         MarkNeedRender();
365     } else {
366         ResetController(hoverControllerEnter_);
367         if (!hoverControllerExit_) {
368             hoverControllerExit_ = CREATE_ANIMATOR(context_);
369         }
370         scaleAnimationExit_ = AceType::MakeRefPtr<KeyframeAnimation<float>>();
371         auto begin = scale_;
372         CreateFloatAnimation(scaleAnimationExit_, begin, 1.0);
373         hoverControllerExit_->AddInterpolator(scaleAnimationExit_);
374         hoverControllerExit_->SetDuration(HOVER_ANIMATION_DURATION);
375         hoverControllerExit_->Play();
376         hoverControllerExit_->SetFillMode(FillMode::FORWARDS);
377     }
378 }
379 
OnMouseClickDownAnimation()380 void RenderButton::OnMouseClickDownAnimation()
381 {
382     if (!needHoverColor_) {
383         ResetController(clickControllerUp_);
384         if (!clickControllerDown_) {
385             clickControllerDown_ = CREATE_ANIMATOR(context_);
386         }
387         scaleAnimationDown_ = AceType::MakeRefPtr<KeyframeAnimation<float>>();
388         auto begin = scale_;
389         CreateFloatAnimation(scaleAnimationDown_, begin, 1.0);
390         clickControllerDown_->AddInterpolator(scaleAnimationDown_);
391         clickControllerDown_->SetDuration(HOVER_ANIMATION_DURATION);
392         clickControllerDown_->Play();
393         clickControllerDown_->SetFillMode(FillMode::FORWARDS);
394     }
395 }
396 
OnMouseClickUpAnimation()397 void RenderButton::OnMouseClickUpAnimation()
398 {
399     if (!needHoverColor_) {
400         ResetController(clickControllerDown_);
401         if (!clickControllerUp_) {
402             clickControllerUp_ = CREATE_ANIMATOR(context_);
403         }
404         scaleAnimationUp_ = AceType::MakeRefPtr<KeyframeAnimation<float>>();
405         auto begin = scale_;
406         CreateFloatAnimation(scaleAnimationUp_, begin, 1.05);
407         clickControllerUp_->AddInterpolator(scaleAnimationUp_);
408         clickControllerUp_->SetDuration(HOVER_ANIMATION_DURATION);
409         clickControllerUp_->Play();
410         clickControllerUp_->SetFillMode(FillMode::FORWARDS);
411     }
412 }
413 
CreateFloatAnimation(RefPtr<KeyframeAnimation<float>> & floatAnimation,float beginValue,float endValue)414 void RenderButton::CreateFloatAnimation(
415     RefPtr<KeyframeAnimation<float>>& floatAnimation, float beginValue, float endValue)
416 {
417     if (!floatAnimation) {
418         return;
419     }
420     auto keyframeBegin = AceType::MakeRefPtr<Keyframe<float>>(0.0, beginValue);
421     auto keyframeEnd = AceType::MakeRefPtr<Keyframe<float>>(1.0, endValue);
422     floatAnimation->AddKeyframe(keyframeBegin);
423     floatAnimation->AddKeyframe(keyframeEnd);
424     floatAnimation->AddListener([weakButton = AceType::WeakClaim(this)](float value) {
425         auto button = weakButton.Upgrade();
426         if (button) {
427             button->isHover_ = true;
428             button->scale_ = value;
429             button->MarkNeedRender();
430         }
431     });
432 }
433 
ResetController(RefPtr<Animator> & controller)434 void RenderButton::ResetController(RefPtr<Animator>& controller)
435 {
436     if (controller) {
437         if (!controller->IsStopped()) {
438             controller->Stop();
439         }
440         controller->ClearInterpolators();
441     }
442 }
443 
Update(const RefPtr<Component> & component)444 void RenderButton::Update(const RefPtr<Component>& component)
445 {
446     const RefPtr<ButtonComponent> button = AceType::DynamicCast<ButtonComponent>(component);
447     if (!button) {
448         LOGE("Update error, button component is null");
449         EventReport::SendRenderException(RenderExcepType::RENDER_COMPONENT_ERR);
450         return;
451     }
452     buttonComponent_ = button;
453     if (!controller_) {
454         controller_ = CREATE_ANIMATOR(GetContext());
455     }
456     auto theme = GetTheme<ButtonTheme>();
457     if (theme) {
458         defaultClickedColor_ = theme->GetClickedColor();
459     }
460 
461     hoverAnimationType_ = buttonComponent_->GetMouseAnimationType();
462     width_ = buttonComponent_->GetWidth();
463     height_ = buttonComponent_->GetHeight();
464     aspectRatio_ = buttonComponent_->GetAspectRatio();
465     buttonComponent_->FitTextHeight(height_);
466     layoutFlag_ = button->GetLayoutFlag();
467     // No animation happens on first setting, will animate from background color on click
468     clickedColor_ = AnimatableColor(button->GetClickedColor());
469     backgroundColor_.SetValue(button->GetBackgroundColor().GetValue());
470     stateEffect_ = button->GetStateEffect();
471     isWatch_ = (SystemProperties::GetDeviceType() == DeviceType::WATCH);
472     isTv_ = (SystemProperties::GetDeviceType() == DeviceType::TV);
473     isPhone_ = (SystemProperties::GetDeviceType() == DeviceType::PHONE);
474     isTablet_ = (SystemProperties::GetDeviceType() == DeviceType::TABLET ||
475         SystemProperties::GetDeviceType() == DeviceType::TWO_IN_ONE);
476     auto catchMode =
477         buttonComponent_->GetClickedEventId().IsEmpty() || buttonComponent_->GetClickedEventId().GetCatchMode();
478     static const int32_t bubbleModeVersion = 6;
479     auto pipeline = context_.Upgrade();
480     if (!catchMode) {
481         if (pipeline && pipeline->GetMinPlatformVersion() >= bubbleModeVersion) {
482             catchMode = false;
483         } else {
484             catchMode = true;
485         }
486     }
487     auto catchModeButton = buttonComponent_->GetCatchMode();
488     clickRecognizer_->SetUseCatchMode(catchMode && catchModeButton);
489     SetAccessibilityText(button->GetAccessibilityText());
490     // for control button in container modal
491     if (buttonComponent_->GetClickedEventId().HasPreFunction()) {
492         SetAccessibilityClick(clickRecognizer_);
493     }
494     UpdateDownloadStyles(button);
495 
496     OnStatusStyleChanged(disabled_ ? VisualState::DISABLED : VisualState::NORMAL);
497     MarkNeedLayout();
498 }
499 
PerformLayout()500 void RenderButton::PerformLayout()
501 {
502     if (!buttonComponent_) {
503         LOGE("Fail to perform layout due to buttonComponent is null");
504         return;
505     }
506     minWidth_ = buttonComponent_->GetMinWidth();
507     type_ = buttonComponent_->GetType();
508     widthDefined_ = GreatOrEqual(buttonComponent_->GetWidth().Value(), 0.0);
509     heightDefined_ = GreatOrEqual(buttonComponent_->GetHeight().Value(), 0.0);
510     if (type_ == ButtonType::ARC) {
511         width_ = ARC_BUTTON_WIDTH;
512         height_ = ARC_BUTTON_HEIGHT;
513     }
514     buttonSize_ = Size(NormalizePercentToPx(width_, false), NormalizePercentToPx(height_, true));
515     rrectRadius_ = NormalizeToPx(buttonComponent_->GetRectRadius());
516     layoutSize_ = Measure();
517     SetChildrenLayoutSize();
518     SetLayoutSize(CalculateLayoutSize());
519     SetChildrenAlignment();
520     buttonSize_ = GetLayoutSize() - Size(widthDelta_, widthDelta_);
521     if (type_ == ButtonType::CAPSULE) {
522         rrectRadius_ = buttonSize_.Height() / 2;
523     }
524 }
525 
SetChildrenLayoutSize()526 void RenderButton::SetChildrenLayoutSize()
527 {
528     LayoutParam innerLayoutParam;
529     bool isWatchText = (isWatch_ && (type_ == ButtonType::TEXT));
530     double maxWidth = buttonSize_.Width();
531     if (NearEqual(buttonSize_.Width(), 0.0)) {
532         maxWidth = isWatchText ? NormalizeToPx(TEXT_BUTTON_MAX_WIDTH) : GetLayoutParam().GetMaxSize().Width();
533         maxWidth -= widthDelta_;
534     }
535     double height = buttonSize_.Height();
536     if (buttonComponent_->GetDeclarativeFlag()) {
537         if (!heightDefined_ && type_ != ButtonType::CIRCLE) {
538             height = GetLayoutParam().GetMaxSize().Height();
539         }
540     }
541     innerLayoutParam.SetMaxSize(Size(maxWidth, height));
542     if (GetChildren().empty()) {
543         childrenSize_ = Size();
544     }
545     for (const auto& child : GetChildren()) {
546         child->Layout(innerLayoutParam);
547         childrenSize_.SetWidth(child->GetLayoutSize().Width());
548         childrenSize_.SetHeight(child->GetLayoutSize().Height());
549     }
550 }
551 
CalculateLayoutSize()552 Size RenderButton::CalculateLayoutSize()
553 {
554     Size layoutSize;
555     if (NeedAdaptiveChild()) {
556         double layoutWidth = widthDefined_ ? layoutSize_.Width() : childrenSize_.Width();
557         double layoutHeight = heightDefined_ ? layoutSize_.Height() : childrenSize_.Height();
558         if (GreatNotEqual(aspectRatio_, 0.0)) {
559             // only when height is determined and width is not determined, aspectRatio is calculated base on height
560             if (heightDefined_ && !widthDefined_) {
561                 layoutWidth = layoutHeight * aspectRatio_;
562             } else {
563                 layoutHeight = layoutWidth / aspectRatio_;
564             }
565         }
566         layoutSize = Size(layoutWidth, layoutHeight);
567     } else {
568         if (NearEqual(buttonSize_.Width(), 0.0)) {
569             double width =
570                 (childrenSize_.Width() > NormalizeToPx(minWidth_)) ? childrenSize_.Width() : NormalizeToPx(minWidth_);
571             layoutSize = Size(width, buttonSize_.Height()) + Size(widthDelta_, widthDelta_);
572         } else {
573             layoutSize = layoutSize_;
574         }
575     }
576     if (NeedConstrain()) {
577         layoutSize = GetLayoutParam().Constrain(layoutSize);
578     }
579     return layoutSize;
580 }
581 
NeedAdaptiveChild()582 bool RenderButton::NeedAdaptiveChild()
583 {
584     if (buttonComponent_->GetDeclarativeFlag() && type_ != ButtonType::CIRCLE) {
585         return true;
586     }
587     if ((type_ == ButtonType::TEXT) && isWatch_) {
588         return true;
589     }
590     if ((type_ == ButtonType::ICON) || (type_ == ButtonType::NORMAL)) {
591         return true;
592     }
593     return false;
594 }
595 
NeedConstrain()596 bool RenderButton::NeedConstrain()
597 {
598     if (type_ == ButtonType::CIRCLE) {
599         return false;
600     }
601     if (isWatch_) {
602         if ((type_ == ButtonType::DOWNLOAD) || (type_ == ButtonType::ARC)) {
603             return false;
604         }
605     }
606     return true;
607 }
608 
SetChildrenAlignment()609 void RenderButton::SetChildrenAlignment()
610 {
611     if (GetChildren().empty()) {
612         return;
613     }
614     auto& child = GetChildren().front();
615     Alignment alignment = (type_ == ButtonType::ARC) ? Alignment::TOP_CENTER : Alignment::CENTER;
616     child->SetPosition(Alignment::GetAlignPosition(GetLayoutSize(), child->GetLayoutSize(), alignment));
617 }
618 
SetProgress(uint32_t progress)619 void RenderButton::SetProgress(uint32_t progress)
620 {
621     if (isWatch_) {
622         if (progress >= static_cast<uint32_t>(round(DOWNLOAD_FULL_PERCENT))) {
623             progressDisplay_ = false;
624             return;
625         }
626         progressDisplay_ = progress > 0 ? true : false;
627         progressPercent_ = progress / DOWNLOAD_FULL_PERCENT;
628         progressWidth_ = buttonSize_.Width() * progressPercent_;
629         MarkNeedRender();
630         return;
631     }
632     needUpdateAnimation_ = false;
633     if (!NearEqual(progress, previousValue_)) {
634         animationDuring_ = std::chrono::steady_clock::now() - previousUpdateTime_;
635         percentChange_ = progress - previousValue_;
636         previousValue_ = progress;
637         previousUpdateTime_ = std::chrono::steady_clock::now();
638         needUpdateAnimation_ = true;
639     }
640     UpdateProgressAnimation();
641     MarkNeedLayout();
642 }
643 
UpdateDownloadStyles(const RefPtr<ButtonComponent> & button)644 void RenderButton::UpdateDownloadStyles(const RefPtr<ButtonComponent>& button)
645 {
646     if (button->GetType() != ButtonType::DOWNLOAD) {
647         return;
648     }
649     auto pipelineContext = GetContext().Upgrade();
650     if (pipelineContext) {
651         if (!progressController_) {
652             progressController_ = CREATE_ANIMATOR(pipelineContext);
653         }
654     }
655     progressColor_ = button->GetProgressColor();
656     progressFocusColor_ = button->GetProgressFocusColor();
657     progressDiameter_ = NormalizeToPx(button->GetProgressDiameter());
658     const auto& buttonController = button->GetButtonController();
659     if (buttonController) {
660         buttonController->SetProgressCallback([weak = AceType::WeakClaim(this)](uint32_t progress) {
661             auto renderButton = weak.Upgrade();
662             if (renderButton) {
663                 renderButton->SetProgress(progress);
664             }
665         });
666     }
667 }
668 
UpdateProgressAnimation()669 void RenderButton::UpdateProgressAnimation()
670 {
671     if (!needUpdateAnimation_) {
672         return;
673     }
674     auto animation = AceType::MakeRefPtr<CurveAnimation<double>>(progressPercent_, previousValue_, Curves::EASE_OUT);
675     animation->AddListener([weak = WeakClaim(this)](const double& value) {
676         auto renderButton = weak.Upgrade();
677         if (!renderButton) {
678             return;
679         }
680         renderButton->progressDisplay_ = GreatNotEqual(value, 0.0) ? true : false;
681         renderButton->progressPercent_ = value;
682         renderButton->progressWidth_ =
683             renderButton->buttonSize_.Width() * renderButton->progressPercent_ / DOWNLOAD_FULL_PERCENT;
684         if (GreatOrEqual(renderButton->progressPercent_, DOWNLOAD_FULL_PERCENT)) {
685             renderButton->progressDisplay_ = false;
686         }
687         renderButton->MarkNeedRender();
688     });
689     if (!progressController_) {
690         return;
691     }
692     double change = percentChange_ * MILLISECOND_PER_PERCENT;
693     double during = animationDuring_.count() * SECOND_TO_MILLISECOND;
694     double duration = GreatNotEqual(std::abs(change), during) ? std::abs(change) : during;
695     if (LessNotEqual(duration, MIN_TRANSITION_TIME) || (previousValue_ == DOWNLOAD_FULL_PERCENT)) {
696         duration = MIN_TRANSITION_TIME;
697     }
698     if (GreatNotEqual(duration, MAX_TRANSITION_TIME)) {
699         duration = MAX_TRANSITION_TIME;
700     }
701     progressController_->ClearInterpolators();
702     progressController_->AddInterpolator(animation);
703     progressController_->SetDuration(static_cast<int32_t>(round(duration)));
704     progressController_->SetIteration(1);
705     progressController_->Stop();
706     progressController_->Play();
707 }
708 
UpdateAnimationParam(double value)709 void RenderButton::UpdateAnimationParam(double value)
710 {
711     UpdateFocusAnimation(value);
712     if (!animationRunning_) {
713         return;
714     }
715 
716     if (isWatch_ || isTv_) {
717         scale_ = value;
718     }
719     if (isOpacityAnimation_) {
720         opacity_ = fabs((value - INIT_SCALE) * ratio_);
721     }
722     if (isTouchAnimation_) {
723         maskingOpacity_ = fabs((value - INIT_SCALE) * ratio_ / MASKING_ANIMATION_RATIO);
724     }
725     if (!valueChanged_ && (!NearEqual(value, startValue_))) {
726         valueChanged_ = true;
727     }
728     if ((!isClickAnimation_ && NearEqual(value, endValue_)) || (valueChanged_ && NearEqual(value, startValue_))) {
729         isLastFrame_ = true;
730         valueChanged_ = false;
731         isClickAnimation_ = false;
732     }
733     MarkNeedRender();
734 }
735 
UpdateFocusAnimation(double value)736 void RenderButton::UpdateFocusAnimation(double value)
737 {
738     auto context = context_.Upgrade();
739     if (!context || !isFocus_) {
740         return;
741     }
742     Size sizeDelta = buttonSize_ * (value - INIT_SCALE);
743     Size layoutSize = GetLayoutSize() + sizeDelta;
744     Offset buttonOffset = Offset(sizeDelta.Width() / 2.0, sizeDelta.Height() / 2.0);
745     double radius = rrectRadius_;
746     if (!buttonComponent_) {
747         return;
748     }
749     ButtonType type = buttonComponent_->GetType();
750     if ((type == ButtonType::CIRCLE) || (type == ButtonType::CAPSULE)) {
751         radius = layoutSize.Height() / 2.0;
752     }
753     if (isPhone_ && ((type == ButtonType::TEXT) || (type == ButtonType::NORMAL))) {
754         context->ShowFocusAnimation(RRect::MakeRRect(Rect(Offset(0, 0), layoutSize), Radius(radius)),
755             buttonComponent_->GetFocusAnimationColor(), GetGlobalOffset() - buttonOffset, true);
756         return;
757     }
758     context->ShowFocusAnimation(RRect::MakeRRect(Rect(Offset(0, 0), layoutSize), Radius(radius)),
759         buttonComponent_->GetFocusAnimationColor(), GetGlobalOffset() - buttonOffset);
760     context->ShowShadow(
761         RRect::MakeRRect(Rect(Offset(0, 0), layoutSize), Radius(radius)), GetGlobalOffset() - buttonOffset);
762 }
763 
PlayAnimation(double start,double end,int32_t duration,const FillMode & fillMode)764 void RenderButton::PlayAnimation(double start, double end, int32_t duration, const FillMode& fillMode)
765 {
766     animationRunning_ = true;
767     startValue_ = start;
768     endValue_ = end;
769     if (!NearEqual(start, end)) {
770         ratio_ = INIT_SCALE / (end - start);
771     }
772     auto animation = AceType::MakeRefPtr<CurveAnimation<double>>(start, end, Curves::FRICTION);
773     animation->AddListener(Animation<double>::ValueCallback([weak = AceType::WeakClaim(this)](double value) {
774         auto button = weak.Upgrade();
775         if (button) {
776             button->UpdateAnimationParam(value);
777         }
778     }));
779     if (!controller_) {
780         return;
781     }
782     controller_->ClearInterpolators();
783     controller_->SetDuration(duration);
784     controller_->SetFillMode(fillMode);
785     controller_->AddInterpolator(animation);
786     controller_->Play();
787 }
788 
PlayTouchAnimation()789 void RenderButton::PlayTouchAnimation()
790 {
791     if (isWatch_) {
792         isTouchAnimation_ = true;
793         if (isClicked_) {
794             PlayAnimation(INIT_SCALE, WATCH_SCALE, WATCH_DURATION_DOWN);
795         } else {
796             PlayAnimation(WATCH_SCALE, INIT_SCALE, WATCH_DURATION_UP);
797         }
798     } else {
799         isTouchAnimation_ = true;
800         if (isClicked_) {
801             PlayAnimation(PRESS_UP_OPACITY, PRESS_DOWN_OPACITY, PRESS_ANIMATION_DURATION);
802         } else {
803             PlayAnimation(PRESS_DOWN_OPACITY, PRESS_UP_OPACITY, PRESS_ANIMATION_DURATION);
804         }
805     }
806 }
807 
PlayClickScaleAnimation(float keyTime,int32_t duration)808 void RenderButton::PlayClickScaleAnimation(float keyTime, int32_t duration)
809 {
810     auto startFrame = AceType::MakeRefPtr<Keyframe<double>>(KEY_TIME_START, TV_EXPAND_SCALE);
811     auto midFrame = AceType::MakeRefPtr<Keyframe<double>>(keyTime, TV_REDUCE_SCALE);
812     auto endFrame = AceType::MakeRefPtr<Keyframe<double>>(KEY_TIME_END, TV_EXPAND_SCALE);
813     midFrame->SetCurve(Curves::FRICTION);
814     endFrame->SetCurve(Curves::FRICTION);
815     auto animation = AceType::MakeRefPtr<KeyframeAnimation<double>>();
816     animation->AddKeyframe(startFrame);
817     animation->AddKeyframe(midFrame);
818     animation->AddKeyframe(endFrame);
819     animation->AddListener([weak = AceType::WeakClaim(this)](double value) {
820         auto button = weak.Upgrade();
821         if (button) {
822             button->UpdateAnimationParam(value);
823         }
824     });
825 
826     if (!controller_) {
827         return;
828     }
829     controller_->ClearInterpolators();
830     controller_->AddInterpolator(animation);
831     controller_->SetDuration(duration);
832     controller_->Play();
833 }
834 
PlayClickAnimation()835 void RenderButton::PlayClickAnimation()
836 {
837     if (isPhone_ || isWatch_ || isTablet_) {
838         return;
839     }
840     if (!isFocus_) {
841         return;
842     }
843     animationRunning_ = true;
844     isClickAnimation_ = true;
845     startValue_ = TV_EXPAND_SCALE;
846     endValue_ = TV_REDUCE_SCALE;
847     PlayClickScaleAnimation(KEY_TIME_MID, TV_CLICK_DURATION);
848 }
849 
PlayFocusAnimation(bool isFocus)850 void RenderButton::PlayFocusAnimation(bool isFocus)
851 {
852     if (isWatch_) {
853         return;
854     }
855     if (isPhone_) {
856         UpdateFocusAnimation(INIT_SCALE);
857         return;
858     }
859     if (!isOpacityAnimation_ && isTv_) {
860         isOpacityAnimation_ = true;
861     }
862     if (isTv_) {
863         if (isFocus) {
864             PlayAnimation(INIT_SCALE, TV_EXPAND_SCALE, TV_FOCUS_SCALE_DURATION);
865         } else {
866             PlayAnimation(TV_EXPAND_SCALE, INIT_SCALE, TV_FOCUS_SCALE_DURATION);
867         }
868     }
869 }
870 
OnStatusStyleChanged(const VisualState state)871 void RenderButton::OnStatusStyleChanged(const VisualState state)
872 {
873     RenderNode::OnStatusStyleChanged(state);
874     if (buttonComponent_ == nullptr || !buttonComponent_->HasStateAttributes()) {
875         return;
876     }
877 
878     for (auto attribute : buttonComponent_->GetStateAttributes()->GetAttributesForState(state)) {
879         switch (attribute->id_) {
880             case ButtonStateAttribute::COLOR: {
881                 auto colorState =
882                     AceType::DynamicCast<StateAttributeValue<ButtonStateAttribute, AnimatableColor>>(attribute);
883                 if (state == VisualState::PRESSED) {
884                     LOGD("Click color start %{public}x  end %{public}x", backgroundColor_.GetValue(),
885                         colorState->value_.GetValue());
886                     SetClickedColor(backgroundColor_);  // starting animation color
887                     clickedColor_ = colorState->value_; // End color
888                     setClickColor_ = true;
889                 } else {
890                     LOGD("background color start %{public}x  end %{public}x", clickedColor_.GetValue(),
891                         colorState->value_.GetValue());
892                     backgroundColor_.SetValue(clickedColor_.GetValue()); // Start value
893                     backgroundColor_ = colorState->value_;               // End value and animate
894                 }
895             } break;
896 
897             case ButtonStateAttribute::RADIUS: {
898                 auto radiusState =
899                     AceType::DynamicCast<StateAttributeValue<ButtonStateAttribute, Dimension>>(attribute);
900                 buttonComponent_->SetRectRadius(radiusState->value_);
901             } break;
902 
903             case ButtonStateAttribute::HEIGHT: {
904                 auto valueState =
905                     AceType::DynamicCast<StateAttributeValue<ButtonStateAttribute, AnimatableDimension>>(attribute);
906                 buttonComponent_->SetHeight(valueState->value_);
907                 height_ = valueState->value_;
908             } break;
909 
910             case ButtonStateAttribute::WIDTH: {
911                 auto valueState =
912                     AceType::DynamicCast<StateAttributeValue<ButtonStateAttribute, AnimatableDimension>>(attribute);
913                 buttonComponent_->SetWidth(valueState->value_);
914                 width_ = valueState->value_;
915             } break;
916             default:
917                 break;
918         }
919     }
920     MarkNeedLayout();
921 }
922 
SendAccessibilityEvent()923 void RenderButton::SendAccessibilityEvent()
924 {
925     auto accessibilityNode = GetAccessibilityNode().Upgrade();
926     if (!accessibilityNode) {
927         return;
928     }
929 
930     auto context = context_.Upgrade();
931     if (context) {
932         AccessibilityEvent radioEvent;
933         radioEvent.nodeId = accessibilityNode->GetNodeId();
934         radioEvent.eventType = "click";
935         context->SendEventToAccessibility(radioEvent);
936     }
937 }
938 
939 } // namespace OHOS::Ace
940