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