2 * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
28 #include "platform/mac/ScrollAnimatorMac.h"
30 #include "platform/PlatformGestureEvent.h"
31 #include "platform/PlatformWheelEvent.h"
32 #include "platform/geometry/FloatPoint.h"
33 #include "platform/mac/BlockExceptions.h"
34 #include "platform/mac/EmptyProtocolDefinitions.h"
35 #include "platform/mac/NSScrollerImpDetails.h"
36 #include "platform/scroll/ScrollView.h"
37 #include "platform/scroll/ScrollableArea.h"
38 #include "platform/scroll/ScrollbarTheme.h"
39 #include "platform/scroll/ScrollbarThemeMacCommon.h"
40 #include "platform/scroll/ScrollbarThemeMacOverlayAPI.h"
41 #include "wtf/MainThread.h"
42 #include "wtf/PassOwnPtr.h"
44 using namespace WebCore;
47 static bool supportsUIStateTransitionProgress()
49 // FIXME: This is temporary until all platforms that support ScrollbarPainter support this part of the API.
50 static bool globalSupportsUIStateTransitionProgress = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(mouseEnteredScroller)];
51 return globalSupportsUIStateTransitionProgress;
54 static bool supportsExpansionTransitionProgress()
56 static bool globalSupportsExpansionTransitionProgress = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(expansionTransitionProgress)];
57 return globalSupportsExpansionTransitionProgress;
60 static bool supportsContentAreaScrolledInDirection()
62 static bool globalSupportsContentAreaScrolledInDirection = [NSClassFromString(@"NSScrollerImpPair") instancesRespondToSelector:@selector(contentAreaScrolledInDirection:)];
63 return globalSupportsContentAreaScrolledInDirection;
66 static ScrollbarThemeMacOverlayAPI* macOverlayScrollbarTheme()
68 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScrollbarThemeMacCommon::isOverlayAPIAvailable());
69 ScrollbarTheme* scrollbarTheme = ScrollbarTheme::theme();
70 return !scrollbarTheme->isMockTheme() ? static_cast<ScrollbarThemeMacOverlayAPI*>(scrollbarTheme) : 0;
73 static ScrollbarPainter scrollbarPainterForScrollbar(Scrollbar* scrollbar)
75 if (ScrollbarThemeMacOverlayAPI* scrollbarTheme = macOverlayScrollbarTheme())
76 return scrollbarTheme->painterForScrollbar(scrollbar);
81 @interface NSObject (ScrollAnimationHelperDetails)
82 - (id)initWithDelegate:(id)delegate;
85 - (NSPoint)targetOrigin;
89 @interface WebScrollAnimationHelperDelegate : NSObject
91 WebCore::ScrollAnimatorMac* _animator;
93 - (id)initWithScrollAnimator:(WebCore::ScrollAnimatorMac*)scrollAnimator;
96 static NSSize abs(NSSize size)
98 NSSize finalSize = size;
99 if (finalSize.width < 0)
100 finalSize.width = -finalSize.width;
101 if (finalSize.height < 0)
102 finalSize.height = -finalSize.height;
106 @implementation WebScrollAnimationHelperDelegate
108 - (id)initWithScrollAnimator:(WebCore::ScrollAnimatorMac*)scrollAnimator
114 _animator = scrollAnimator;
128 WebCore::FloatPoint currentPosition = _animator->currentPosition();
129 return NSMakeRect(currentPosition.x(), currentPosition.y(), 0, 0);
132 - (void)_immediateScrollToPoint:(NSPoint)newPosition
136 _animator->immediateScrollToPointForScrollAnimation(newPosition);
139 - (NSPoint)_pixelAlignProposedScrollPosition:(NSPoint)newOrigin
144 - (NSSize)convertSizeToBase:(NSSize)size
149 - (NSSize)convertSizeFromBase:(NSSize)size
154 - (NSSize)convertSizeToBacking:(NSSize)size
159 - (NSSize)convertSizeFromBacking:(NSSize)size
179 - (void)_recursiveRecomputeToolTips
185 @interface WebScrollbarPainterControllerDelegate : NSObject
187 ScrollableArea* _scrollableArea;
189 - (id)initWithScrollableArea:(ScrollableArea*)scrollableArea;
192 @implementation WebScrollbarPainterControllerDelegate
194 - (id)initWithScrollableArea:(ScrollableArea*)scrollableArea
200 _scrollableArea = scrollableArea;
209 - (NSRect)contentAreaRectForScrollerImpPair:(id)scrollerImpPair
211 if (!_scrollableArea)
214 WebCore::IntSize contentsSize = _scrollableArea->contentsSize();
215 return NSMakeRect(0, 0, contentsSize.width(), contentsSize.height());
218 - (BOOL)inLiveResizeForScrollerImpPair:(id)scrollerImpPair
220 if (!_scrollableArea)
223 return _scrollableArea->inLiveResize();
226 - (NSPoint)mouseLocationInContentAreaForScrollerImpPair:(id)scrollerImpPair
228 if (!_scrollableArea)
231 return _scrollableArea->lastKnownMousePosition();
234 - (NSPoint)scrollerImpPair:(id)scrollerImpPair convertContentPoint:(NSPoint)pointInContentArea toScrollerImp:(id)scrollerImp
237 if (!_scrollableArea || !scrollerImp)
240 WebCore::Scrollbar* scrollbar = 0;
241 if ([scrollerImp isHorizontal])
242 scrollbar = _scrollableArea->horizontalScrollbar();
244 scrollbar = _scrollableArea->verticalScrollbar();
246 // It is possible to have a null scrollbar here since it is possible for this delegate
247 // method to be called between the moment when a scrollbar has been set to 0 and the
248 // moment when its destructor has been called. We should probably de-couple some
249 // of the clean-up work in ScrollbarThemeMac::unregisterScrollbar() to avoid this
254 ASSERT(scrollerImp == scrollbarPainterForScrollbar(scrollbar));
256 return scrollbar->convertFromContainingView(WebCore::IntPoint(pointInContentArea));
259 - (void)scrollerImpPair:(id)scrollerImpPair setContentAreaNeedsDisplayInRect:(NSRect)rect
261 if (!_scrollableArea)
264 if (!_scrollableArea->scrollbarsCanBeActive())
267 _scrollableArea->scrollAnimator()->contentAreaWillPaint();
270 - (void)scrollerImpPair:(id)scrollerImpPair updateScrollerStyleForNewRecommendedScrollerStyle:(NSScrollerStyle)newRecommendedScrollerStyle
272 // Chrome has a single process mode which is used for testing on Mac. In that mode, WebKit runs on a thread in the
273 // browser process. This notification is called by the OS on the main thread in the browser process, and not on the
274 // the WebKit thread. Better to not update the style than crash.
275 // http://crbug.com/126514
279 if (!_scrollableArea)
282 [scrollerImpPair setScrollerStyle:newRecommendedScrollerStyle];
284 static_cast<ScrollAnimatorMac*>(_scrollableArea->scrollAnimator())->updateScrollerStyle();
289 enum FeatureToAnimate {
296 @interface WebScrollbarPartAnimation : NSAnimation
298 Scrollbar* _scrollbar;
299 RetainPtr<ScrollbarPainter> _scrollbarPainter;
300 FeatureToAnimate _featureToAnimate;
304 - (id)initWithScrollbar:(Scrollbar*)scrollbar featureToAnimate:(FeatureToAnimate)featureToAnimate animateFrom:(CGFloat)startValue animateTo:(CGFloat)endValue duration:(NSTimeInterval)duration;
307 @implementation WebScrollbarPartAnimation
309 - (id)initWithScrollbar:(Scrollbar*)scrollbar featureToAnimate:(FeatureToAnimate)featureToAnimate animateFrom:(CGFloat)startValue animateTo:(CGFloat)endValue duration:(NSTimeInterval)duration
311 self = [super initWithDuration:duration animationCurve:NSAnimationEaseInOut];
315 _scrollbar = scrollbar;
316 _featureToAnimate = featureToAnimate;
317 _startValue = startValue;
318 _endValue = endValue;
320 [self setAnimationBlockingMode:NSAnimationNonblocking];
325 - (void)startAnimation
329 _scrollbarPainter = scrollbarPainterForScrollbar(_scrollbar);
331 [super startAnimation];
334 - (void)setStartValue:(CGFloat)startValue
336 _startValue = startValue;
339 - (void)setEndValue:(CGFloat)endValue
341 _endValue = endValue;
344 - (void)setCurrentProgress:(NSAnimationProgress)progress
346 [super setCurrentProgress:progress];
350 CGFloat currentValue;
351 if (_startValue > _endValue)
352 currentValue = 1 - progress;
354 currentValue = progress;
356 switch (_featureToAnimate) {
358 [_scrollbarPainter.get() setKnobAlpha:currentValue];
361 [_scrollbarPainter.get() setTrackAlpha:currentValue];
363 case UIStateTransition:
364 [_scrollbarPainter.get() setUiStateTransitionProgress:currentValue];
366 case ExpansionTransition:
367 [_scrollbarPainter.get() setExpansionTransitionProgress:currentValue];
371 _scrollbar->invalidate();
376 BEGIN_BLOCK_OBJC_EXCEPTIONS;
377 [self stopAnimation];
378 END_BLOCK_OBJC_EXCEPTIONS;
384 @interface WebScrollbarPainterDelegate : NSObject<NSAnimationDelegate>
386 WebCore::Scrollbar* _scrollbar;
388 RetainPtr<WebScrollbarPartAnimation> _knobAlphaAnimation;
389 RetainPtr<WebScrollbarPartAnimation> _trackAlphaAnimation;
390 RetainPtr<WebScrollbarPartAnimation> _uiStateTransitionAnimation;
391 RetainPtr<WebScrollbarPartAnimation> _expansionTransitionAnimation;
393 - (id)initWithScrollbar:(WebCore::Scrollbar*)scrollbar;
394 - (void)cancelAnimations;
397 @implementation WebScrollbarPainterDelegate
399 - (id)initWithScrollbar:(WebCore::Scrollbar*)scrollbar
405 _scrollbar = scrollbar;
409 - (void)cancelAnimations
411 BEGIN_BLOCK_OBJC_EXCEPTIONS;
412 [_knobAlphaAnimation.get() stopAnimation];
413 [_trackAlphaAnimation.get() stopAnimation];
414 [_uiStateTransitionAnimation.get() stopAnimation];
415 [_expansionTransitionAnimation.get() stopAnimation];
416 END_BLOCK_OBJC_EXCEPTIONS;
419 - (ScrollAnimatorMac*)scrollAnimator
421 return static_cast<ScrollAnimatorMac*>(_scrollbar->scrollableArea()->scrollAnimator());
424 - (NSRect)convertRectToBacking:(NSRect)aRect
429 - (NSRect)convertRectFromBacking:(NSRect)aRect
434 - (NSPoint)mouseLocationInScrollerForScrollerImp:(id)scrollerImp
439 ASSERT_UNUSED(scrollerImp, scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
441 return _scrollbar->convertFromContainingView(_scrollbar->scrollableArea()->lastKnownMousePosition());
444 - (void)setUpAlphaAnimation:(RetainPtr<WebScrollbarPartAnimation>&)scrollbarPartAnimation scrollerPainter:(ScrollbarPainter)scrollerPainter part:(WebCore::ScrollbarPart)part animateAlphaTo:(CGFloat)newAlpha duration:(NSTimeInterval)duration
446 // If the user has scrolled the page, then the scrollbars must be animated here.
447 // This overrides the early returns.
448 bool mustAnimate = [self scrollAnimator]->haveScrolledSincePageLoad();
450 if ([self scrollAnimator]->scrollbarPaintTimerIsActive() && !mustAnimate)
453 if (_scrollbar->scrollableArea()->shouldSuspendScrollAnimations() && !mustAnimate) {
454 [self scrollAnimator]->startScrollbarPaintTimer();
458 // At this point, we are definitely going to animate now, so stop the timer.
459 [self scrollAnimator]->stopScrollbarPaintTimer();
461 // If we are currently animating, stop
462 if (scrollbarPartAnimation) {
463 [scrollbarPartAnimation.get() stopAnimation];
464 scrollbarPartAnimation = nil;
467 if (part == WebCore::ThumbPart && _scrollbar->orientation() == VerticalScrollbar) {
469 IntRect thumbRect = IntRect([scrollerPainter rectForPart:NSScrollerKnob]);
470 [self scrollAnimator]->setVisibleScrollerThumbRect(thumbRect);
472 [self scrollAnimator]->setVisibleScrollerThumbRect(IntRect());
475 scrollbarPartAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
476 featureToAnimate:part == ThumbPart ? ThumbAlpha : TrackAlpha
477 animateFrom:part == ThumbPart ? [scrollerPainter knobAlpha] : [scrollerPainter trackAlpha]
480 [scrollbarPartAnimation.get() startAnimation];
483 - (void)scrollerImp:(id)scrollerImp animateKnobAlphaTo:(CGFloat)newKnobAlpha duration:(NSTimeInterval)duration
488 ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
490 ScrollbarPainter scrollerPainter = (ScrollbarPainter)scrollerImp;
491 [self setUpAlphaAnimation:_knobAlphaAnimation scrollerPainter:scrollerPainter part:WebCore::ThumbPart animateAlphaTo:newKnobAlpha duration:duration];
494 - (void)scrollerImp:(id)scrollerImp animateTrackAlphaTo:(CGFloat)newTrackAlpha duration:(NSTimeInterval)duration
499 ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
501 ScrollbarPainter scrollerPainter = (ScrollbarPainter)scrollerImp;
502 [self setUpAlphaAnimation:_trackAlphaAnimation scrollerPainter:scrollerPainter part:WebCore::BackTrackPart animateAlphaTo:newTrackAlpha duration:duration];
505 - (void)scrollerImp:(id)scrollerImp animateUIStateTransitionWithDuration:(NSTimeInterval)duration
510 if (!supportsUIStateTransitionProgress())
513 ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
515 ScrollbarPainter scrollbarPainter = (ScrollbarPainter)scrollerImp;
517 // UIStateTransition always animates to 1. In case an animation is in progress this avoids a hard transition.
518 [scrollbarPainter setUiStateTransitionProgress:1 - [scrollerImp uiStateTransitionProgress]];
520 if (!_uiStateTransitionAnimation)
521 _uiStateTransitionAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
522 featureToAnimate:UIStateTransition
523 animateFrom:[scrollbarPainter uiStateTransitionProgress]
527 // If we don't need to initialize the animation, just reset the values in case they have changed.
528 [_uiStateTransitionAnimation.get() setStartValue:[scrollbarPainter uiStateTransitionProgress]];
529 [_uiStateTransitionAnimation.get() setEndValue:1.0];
530 [_uiStateTransitionAnimation.get() setDuration:duration];
532 [_uiStateTransitionAnimation.get() startAnimation];
535 - (void)scrollerImp:(id)scrollerImp animateExpansionTransitionWithDuration:(NSTimeInterval)duration
540 if (!supportsExpansionTransitionProgress())
543 ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
545 ScrollbarPainter scrollbarPainter = (ScrollbarPainter)scrollerImp;
547 // ExpansionTransition always animates to 1. In case an animation is in progress this avoids a hard transition.
548 [scrollbarPainter setExpansionTransitionProgress:1 - [scrollerImp expansionTransitionProgress]];
550 if (!_expansionTransitionAnimation) {
551 _expansionTransitionAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
552 featureToAnimate:ExpansionTransition
553 animateFrom:[scrollbarPainter expansionTransitionProgress]
557 // If we don't need to initialize the animation, just reset the values in case they have changed.
558 [_expansionTransitionAnimation.get() setStartValue:[scrollbarPainter uiStateTransitionProgress]];
559 [_expansionTransitionAnimation.get() setEndValue:1.0];
560 [_expansionTransitionAnimation.get() setDuration:duration];
562 [_expansionTransitionAnimation.get() startAnimation];
565 - (void)scrollerImp:(id)scrollerImp overlayScrollerStateChangedTo:(NSUInteger)newOverlayScrollerState
572 BEGIN_BLOCK_OBJC_EXCEPTIONS;
573 [_knobAlphaAnimation.get() invalidate];
574 [_trackAlphaAnimation.get() invalidate];
575 [_uiStateTransitionAnimation.get() invalidate];
576 [_expansionTransitionAnimation.get() invalidate];
577 END_BLOCK_OBJC_EXCEPTIONS;
584 PassOwnPtr<ScrollAnimator> ScrollAnimator::create(ScrollableArea* scrollableArea)
586 return adoptPtr(new ScrollAnimatorMac(scrollableArea));
589 ScrollAnimatorMac::ScrollAnimatorMac(ScrollableArea* scrollableArea)
590 : ScrollAnimator(scrollableArea)
591 , m_initialScrollbarPaintTimer(this, &ScrollAnimatorMac::initialScrollbarPaintTimerFired)
592 , m_sendContentAreaScrolledTimer(this, &ScrollAnimatorMac::sendContentAreaScrolledTimerFired)
593 #if USE(RUBBER_BANDING)
594 , m_scrollElasticityController(this)
595 , m_snapRubberBandTimer(this, &ScrollAnimatorMac::snapRubberBandTimerFired)
597 , m_haveScrolledSincePageLoad(false)
598 , m_needsScrollerStyleUpdate(false)
600 m_scrollAnimationHelperDelegate.adoptNS([[WebScrollAnimationHelperDelegate alloc] initWithScrollAnimator:this]);
601 m_scrollAnimationHelper.adoptNS([[NSClassFromString(@"NSScrollAnimationHelper") alloc] initWithDelegate:m_scrollAnimationHelperDelegate.get()]);
603 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
604 m_scrollbarPainterControllerDelegate.adoptNS([[WebScrollbarPainterControllerDelegate alloc] initWithScrollableArea:scrollableArea]);
605 m_scrollbarPainterController = [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease];
606 [m_scrollbarPainterController.get() setDelegate:m_scrollbarPainterControllerDelegate.get()];
607 [m_scrollbarPainterController.get() setScrollerStyle:ScrollbarThemeMacCommon::recommendedScrollerStyle()];
611 ScrollAnimatorMac::~ScrollAnimatorMac()
613 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
614 BEGIN_BLOCK_OBJC_EXCEPTIONS;
615 [m_scrollbarPainterControllerDelegate.get() invalidate];
616 [m_scrollbarPainterController.get() setDelegate:nil];
617 [m_horizontalScrollbarPainterDelegate.get() invalidate];
618 [m_verticalScrollbarPainterDelegate.get() invalidate];
619 [m_scrollAnimationHelperDelegate.get() invalidate];
620 END_BLOCK_OBJC_EXCEPTIONS;
624 static bool scrollAnimationEnabledForSystem()
626 NSString* scrollAnimationDefaultsKey =
627 @"AppleScrollAnimationEnabled";
628 static bool enabled = [[NSUserDefaults standardUserDefaults] boolForKey:scrollAnimationDefaultsKey];
632 #if USE(RUBBER_BANDING)
633 static bool rubberBandingEnabledForSystem()
635 static bool initialized = false;
636 static bool enabled = true;
637 // Caches the result, which is consistent with other apps like the Finder, which all
638 // require a restart after changing this default.
640 // Uses -objectForKey: and not -boolForKey: in order to default to true if the value wasn't set.
641 id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"NSScrollViewRubberbanding"];
642 if ([value isKindOfClass:[NSNumber class]])
643 enabled = [value boolValue];
650 bool ScrollAnimatorMac::scroll(ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float delta)
652 m_haveScrolledSincePageLoad = true;
654 if (!scrollAnimationEnabledForSystem() || !m_scrollableArea->scrollAnimatorEnabled())
655 return ScrollAnimator::scroll(orientation, granularity, step, delta);
657 if (granularity == ScrollByPixel)
658 return ScrollAnimator::scroll(orientation, granularity, step, delta);
660 float currentPos = orientation == HorizontalScrollbar ? m_currentPosX : m_currentPosY;
661 float newPos = std::max<float>(std::min<float>(currentPos + (step * delta), m_scrollableArea->maximumScrollPosition(orientation)), m_scrollableArea->minimumScrollPosition(orientation));
662 if (currentPos == newPos)
666 if ([m_scrollAnimationHelper.get() _isAnimating]) {
667 NSPoint targetOrigin = [m_scrollAnimationHelper.get() targetOrigin];
668 newPoint = orientation == HorizontalScrollbar ? NSMakePoint(newPos, targetOrigin.y) : NSMakePoint(targetOrigin.x, newPos);
670 newPoint = orientation == HorizontalScrollbar ? NSMakePoint(newPos, m_currentPosY) : NSMakePoint(m_currentPosX, newPos);
672 [m_scrollAnimationHelper.get() scrollToPoint:newPoint];
676 void ScrollAnimatorMac::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
678 [m_scrollAnimationHelper.get() _stopRun];
679 immediateScrollTo(offset);
682 FloatPoint ScrollAnimatorMac::adjustScrollPositionIfNecessary(const FloatPoint& position) const
684 if (!m_scrollableArea->constrainsScrollingToContentEdge())
687 IntPoint minPos = m_scrollableArea->minimumScrollPosition();
688 IntPoint maxPos = m_scrollableArea->maximumScrollPosition();
690 float newX = max<float>(min<float>(position.x(), maxPos.x()), minPos.x());
691 float newY = max<float>(min<float>(position.y(), maxPos.y()), minPos.y());
693 return FloatPoint(newX, newY);
696 void ScrollAnimatorMac::immediateScrollTo(const FloatPoint& newPosition)
698 FloatPoint adjustedPosition = adjustScrollPositionIfNecessary(newPosition);
700 bool positionChanged = adjustedPosition.x() != m_currentPosX || adjustedPosition.y() != m_currentPosY;
701 if (!positionChanged && !scrollableArea()->scrollOriginChanged())
704 FloatSize delta = FloatSize(adjustedPosition.x() - m_currentPosX, adjustedPosition.y() - m_currentPosY);
706 m_currentPosX = adjustedPosition.x();
707 m_currentPosY = adjustedPosition.y();
708 notifyContentAreaScrolled(delta);
709 notifyPositionChanged();
712 bool ScrollAnimatorMac::isRubberBandInProgress() const
714 #if !USE(RUBBER_BANDING)
717 return m_scrollElasticityController.isRubberBandInProgress();
721 void ScrollAnimatorMac::immediateScrollToPointForScrollAnimation(const FloatPoint& newPosition)
723 ASSERT(m_scrollAnimationHelper);
724 immediateScrollTo(newPosition);
727 void ScrollAnimatorMac::contentAreaWillPaint() const
729 if (!scrollableArea()->scrollbarsCanBeActive())
731 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
732 [m_scrollbarPainterController.get() contentAreaWillDraw];
735 void ScrollAnimatorMac::mouseEnteredContentArea() const
737 if (!scrollableArea()->scrollbarsCanBeActive())
739 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
740 [m_scrollbarPainterController.get() mouseEnteredContentArea];
743 void ScrollAnimatorMac::mouseExitedContentArea() const
745 if (!scrollableArea()->scrollbarsCanBeActive())
747 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
748 [m_scrollbarPainterController.get() mouseExitedContentArea];
751 void ScrollAnimatorMac::mouseMovedInContentArea() const
753 if (!scrollableArea()->scrollbarsCanBeActive())
755 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
756 [m_scrollbarPainterController.get() mouseMovedInContentArea];
759 void ScrollAnimatorMac::mouseEnteredScrollbar(Scrollbar* scrollbar) const
761 // At this time, only legacy scrollbars needs to send notifications here.
762 if (ScrollbarThemeMacCommon::recommendedScrollerStyle() != NSScrollerStyleLegacy)
765 if (!scrollableArea()->scrollbarsCanBeActive())
768 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
769 if (!supportsUIStateTransitionProgress())
771 if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar))
772 [painter mouseEnteredScroller];
776 void ScrollAnimatorMac::mouseExitedScrollbar(Scrollbar* scrollbar) const
778 // At this time, only legacy scrollbars needs to send notifications here.
779 if (ScrollbarThemeMacCommon::recommendedScrollerStyle() != NSScrollerStyleLegacy)
782 if (!scrollableArea()->scrollbarsCanBeActive())
785 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
786 if (!supportsUIStateTransitionProgress())
788 if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar))
789 [painter mouseExitedScroller];
793 void ScrollAnimatorMac::willStartLiveResize()
795 if (!scrollableArea()->scrollbarsCanBeActive())
797 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
798 [m_scrollbarPainterController.get() startLiveResize];
801 void ScrollAnimatorMac::contentsResized() const
803 if (!scrollableArea()->scrollbarsCanBeActive())
805 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
806 [m_scrollbarPainterController.get() contentAreaDidResize];
809 void ScrollAnimatorMac::willEndLiveResize()
811 if (!scrollableArea()->scrollbarsCanBeActive())
813 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
814 [m_scrollbarPainterController.get() endLiveResize];
817 void ScrollAnimatorMac::contentAreaDidShow() const
819 if (!scrollableArea()->scrollbarsCanBeActive())
821 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
822 [m_scrollbarPainterController.get() windowOrderedIn];
825 void ScrollAnimatorMac::contentAreaDidHide() const
827 if (!scrollableArea()->scrollbarsCanBeActive())
829 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
830 [m_scrollbarPainterController.get() windowOrderedOut];
833 void ScrollAnimatorMac::didBeginScrollGesture() const
835 if (!scrollableArea()->scrollbarsCanBeActive())
837 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
838 [m_scrollbarPainterController.get() beginScrollGesture];
841 void ScrollAnimatorMac::didEndScrollGesture() const
843 if (!scrollableArea()->scrollbarsCanBeActive())
845 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable())
846 [m_scrollbarPainterController.get() endScrollGesture];
849 void ScrollAnimatorMac::mayBeginScrollGesture() const
851 if (!scrollableArea()->scrollbarsCanBeActive())
853 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
856 [m_scrollbarPainterController.get() beginScrollGesture];
857 [m_scrollbarPainterController.get() contentAreaScrolled];
860 void ScrollAnimatorMac::finishCurrentScrollAnimations()
862 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
863 [m_scrollbarPainterController.get() hideOverlayScrollers];
867 void ScrollAnimatorMac::didAddVerticalScrollbar(Scrollbar* scrollbar)
869 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
872 ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
876 ASSERT(!m_verticalScrollbarPainterDelegate);
877 m_verticalScrollbarPainterDelegate.adoptNS([[WebScrollbarPainterDelegate alloc] initWithScrollbar:scrollbar]);
879 [painter setDelegate:m_verticalScrollbarPainterDelegate.get()];
880 [m_scrollbarPainterController.get() setVerticalScrollerImp:painter];
881 if (scrollableArea()->inLiveResize())
882 [painter setKnobAlpha:1];
885 void ScrollAnimatorMac::willRemoveVerticalScrollbar(Scrollbar* scrollbar)
887 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
890 ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
894 ASSERT(m_verticalScrollbarPainterDelegate);
895 [m_verticalScrollbarPainterDelegate.get() invalidate];
896 m_verticalScrollbarPainterDelegate = nullptr;
898 [painter setDelegate:nil];
899 [m_scrollbarPainterController.get() setVerticalScrollerImp:nil];
902 void ScrollAnimatorMac::didAddHorizontalScrollbar(Scrollbar* scrollbar)
904 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
907 ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
911 ASSERT(!m_horizontalScrollbarPainterDelegate);
912 m_horizontalScrollbarPainterDelegate.adoptNS([[WebScrollbarPainterDelegate alloc] initWithScrollbar:scrollbar]);
914 [painter setDelegate:m_horizontalScrollbarPainterDelegate.get()];
915 [m_scrollbarPainterController.get() setHorizontalScrollerImp:painter];
916 if (scrollableArea()->inLiveResize())
917 [painter setKnobAlpha:1];
920 void ScrollAnimatorMac::willRemoveHorizontalScrollbar(Scrollbar* scrollbar)
922 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
925 ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
929 ASSERT(m_horizontalScrollbarPainterDelegate);
930 [m_horizontalScrollbarPainterDelegate.get() invalidate];
931 m_horizontalScrollbarPainterDelegate = nullptr;
933 [painter setDelegate:nil];
934 [m_scrollbarPainterController.get() setHorizontalScrollerImp:nil];
937 bool ScrollAnimatorMac::shouldScrollbarParticipateInHitTesting(Scrollbar* scrollbar)
939 // Non-overlay scrollbars should always participate in hit testing.
940 if (ScrollbarThemeMacCommon::recommendedScrollerStyle() != NSScrollerStyleOverlay)
943 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
946 if (scrollbar->isAlphaLocked())
949 // Overlay scrollbars should participate in hit testing whenever they are at all visible.
950 ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
953 return [painter knobAlpha] > 0;
956 void ScrollAnimatorMac::notifyContentAreaScrolled(const FloatSize& delta)
958 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
961 // This function is called when a page is going into the page cache, but the page
962 // isn't really scrolling in that case. We should only pass the message on to the
963 // ScrollbarPainterController when we're really scrolling on an active page.
964 if (scrollableArea()->scrollbarsCanBeActive())
965 sendContentAreaScrolledSoon(delta);
968 void ScrollAnimatorMac::cancelAnimations()
970 m_haveScrolledSincePageLoad = false;
972 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
973 if (scrollbarPaintTimerIsActive())
974 stopScrollbarPaintTimer();
975 [m_horizontalScrollbarPainterDelegate.get() cancelAnimations];
976 [m_verticalScrollbarPainterDelegate.get() cancelAnimations];
980 void ScrollAnimatorMac::handleWheelEventPhase(PlatformWheelEventPhase phase)
982 // This may not have been set to true yet if the wheel event was handled by the ScrollingTree,
983 // So set it to true here.
984 m_haveScrolledSincePageLoad = true;
986 if (phase == PlatformWheelEventPhaseBegan)
987 didBeginScrollGesture();
988 else if (phase == PlatformWheelEventPhaseEnded || phase == PlatformWheelEventPhaseCancelled)
989 didEndScrollGesture();
990 else if (phase == PlatformWheelEventPhaseMayBegin)
991 mayBeginScrollGesture();
994 #if USE(RUBBER_BANDING)
995 bool ScrollAnimatorMac::handleWheelEvent(const PlatformWheelEvent& wheelEvent)
997 m_haveScrolledSincePageLoad = true;
999 if (!wheelEvent.hasPreciseScrollingDeltas() || !rubberBandingEnabledForSystem())
1000 return ScrollAnimator::handleWheelEvent(wheelEvent);
1002 // FIXME: This is somewhat roundabout hack to allow forwarding wheel events
1003 // up to the parent scrollable area. It takes advantage of the fact that
1004 // the base class implementation of handleWheelEvent will not accept the
1005 // wheel event if there is nowhere to scroll.
1006 if (fabsf(wheelEvent.deltaY()) >= fabsf(wheelEvent.deltaX())) {
1007 if (!allowsVerticalStretching())
1008 return ScrollAnimator::handleWheelEvent(wheelEvent);
1010 if (!allowsHorizontalStretching())
1011 return ScrollAnimator::handleWheelEvent(wheelEvent);
1014 bool didHandleEvent = m_scrollElasticityController.handleWheelEvent(wheelEvent);
1016 // The elasticity controller can return false on a phase end event if rubber banding wasn't in progress.
1017 // In this case, the wheel phase must still be handled so that that overlay scroll bars get hidden.
1018 if (didHandleEvent || wheelEvent.phase() == PlatformWheelEventPhaseEnded || wheelEvent.phase() == PlatformWheelEventPhaseCancelled)
1019 handleWheelEventPhase(wheelEvent.phase());
1021 return didHandleEvent;
1024 bool ScrollAnimatorMac::pinnedInDirection(float deltaX, float deltaY)
1026 FloatSize limitDelta;
1027 if (fabsf(deltaY) >= fabsf(deltaX)) {
1029 // We are trying to scroll up. Make sure we are not pinned to the top
1030 limitDelta.setHeight(m_scrollableArea->visibleContentRect().y() + + m_scrollableArea->scrollOrigin().y());
1032 // We are trying to scroll down. Make sure we are not pinned to the bottom
1033 limitDelta.setHeight(m_scrollableArea->contentsSize().height() - (m_scrollableArea->visibleContentRect().maxY() + m_scrollableArea->scrollOrigin().y()));
1035 } else if (deltaX != 0) {
1037 // We are trying to scroll left. Make sure we are not pinned to the left
1038 limitDelta.setWidth(m_scrollableArea->visibleContentRect().x() + m_scrollableArea->scrollOrigin().x());
1040 // We are trying to scroll right. Make sure we are not pinned to the right
1041 limitDelta.setWidth(m_scrollableArea->contentsSize().width() - (m_scrollableArea->visibleContentRect().maxX() + m_scrollableArea->scrollOrigin().x()));
1045 if ((deltaX != 0 || deltaY != 0) && (limitDelta.width() < 1 && limitDelta.height() < 1))
1050 bool ScrollAnimatorMac::allowsVerticalStretching()
1052 switch (m_scrollableArea->verticalScrollElasticity()) {
1053 case ScrollElasticityAutomatic: {
1054 Scrollbar* hScroller = m_scrollableArea->horizontalScrollbar();
1055 Scrollbar* vScroller = m_scrollableArea->verticalScrollbar();
1056 return (((vScroller && vScroller->enabled()) || (!hScroller || !hScroller->enabled())));
1058 case ScrollElasticityNone:
1060 case ScrollElasticityAllowed:
1064 ASSERT_NOT_REACHED();
1068 bool ScrollAnimatorMac::allowsHorizontalStretching()
1070 switch (m_scrollableArea->horizontalScrollElasticity()) {
1071 case ScrollElasticityAutomatic: {
1072 Scrollbar* hScroller = m_scrollableArea->horizontalScrollbar();
1073 Scrollbar* vScroller = m_scrollableArea->verticalScrollbar();
1074 return (((hScroller && hScroller->enabled()) || (!vScroller || !vScroller->enabled())));
1076 case ScrollElasticityNone:
1078 case ScrollElasticityAllowed:
1082 ASSERT_NOT_REACHED();
1086 IntSize ScrollAnimatorMac::stretchAmount()
1088 return m_scrollableArea->overhangAmount();
1091 bool ScrollAnimatorMac::pinnedInDirection(const FloatSize& direction)
1093 return pinnedInDirection(direction.width(), direction.height());
1096 bool ScrollAnimatorMac::canScrollHorizontally()
1098 Scrollbar* scrollbar = m_scrollableArea->horizontalScrollbar();
1101 return scrollbar->enabled();
1104 bool ScrollAnimatorMac::canScrollVertically()
1106 Scrollbar* scrollbar = m_scrollableArea->verticalScrollbar();
1109 return scrollbar->enabled();
1112 bool ScrollAnimatorMac::shouldRubberBandInDirection(ScrollDirection direction)
1114 return m_scrollableArea->shouldRubberBandInDirection(direction);
1117 IntPoint ScrollAnimatorMac::absoluteScrollPosition()
1119 return m_scrollableArea->visibleContentRect().location() + m_scrollableArea->scrollOrigin();
1122 void ScrollAnimatorMac::immediateScrollByWithoutContentEdgeConstraints(const FloatSize& delta)
1124 m_scrollableArea->setConstrainsScrollingToContentEdge(false);
1125 immediateScrollBy(delta);
1126 m_scrollableArea->setConstrainsScrollingToContentEdge(true);
1129 void ScrollAnimatorMac::immediateScrollBy(const FloatSize& delta)
1131 FloatPoint newPos = adjustScrollPositionIfNecessary(FloatPoint(m_currentPosX, m_currentPosY) + delta);
1132 if (newPos.x() == m_currentPosX && newPos.y() == m_currentPosY)
1135 FloatSize adjustedDelta = FloatSize(newPos.x() - m_currentPosX, newPos.y() - m_currentPosY);
1137 m_currentPosX = newPos.x();
1138 m_currentPosY = newPos.y();
1139 notifyContentAreaScrolled(adjustedDelta);
1140 notifyPositionChanged();
1143 void ScrollAnimatorMac::startSnapRubberbandTimer()
1145 m_snapRubberBandTimer.startRepeating(1.0 / 60.0, FROM_HERE);
1148 void ScrollAnimatorMac::stopSnapRubberbandTimer()
1150 m_snapRubberBandTimer.stop();
1153 void ScrollAnimatorMac::snapRubberBandTimerFired(Timer<ScrollAnimatorMac>*)
1155 m_scrollElasticityController.snapRubberBandTimerFired();
1159 void ScrollAnimatorMac::setIsActive()
1161 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
1164 if (!m_needsScrollerStyleUpdate)
1167 updateScrollerStyle();
1170 void ScrollAnimatorMac::updateScrollerStyle()
1172 if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable())
1175 if (!scrollableArea()->scrollbarsCanBeActive()) {
1176 m_needsScrollerStyleUpdate = true;
1180 ScrollbarThemeMacOverlayAPI* macTheme = macOverlayScrollbarTheme();
1182 m_needsScrollerStyleUpdate = false;
1186 NSScrollerStyle newStyle = [m_scrollbarPainterController.get() scrollerStyle];
1188 if (Scrollbar* verticalScrollbar = scrollableArea()->verticalScrollbar()) {
1189 verticalScrollbar->invalidate();
1191 ScrollbarPainter oldVerticalPainter = [m_scrollbarPainterController.get() verticalScrollerImp];
1192 ScrollbarPainter newVerticalPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:newStyle
1193 controlSize:(NSControlSize)verticalScrollbar->controlSize()
1195 replacingScrollerImp:oldVerticalPainter];
1196 [m_scrollbarPainterController.get() setVerticalScrollerImp:newVerticalPainter];
1197 macTheme->setNewPainterForScrollbar(verticalScrollbar, newVerticalPainter);
1199 // The different scrollbar styles have different thicknesses, so we must re-set the
1200 // frameRect to the new thickness, and the re-layout below will ensure the position
1201 // and length are properly updated.
1202 int thickness = macTheme->scrollbarThickness(verticalScrollbar->controlSize());
1203 verticalScrollbar->setFrameRect(IntRect(0, 0, thickness, thickness));
1206 if (Scrollbar* horizontalScrollbar = scrollableArea()->horizontalScrollbar()) {
1207 horizontalScrollbar->invalidate();
1209 ScrollbarPainter oldHorizontalPainter = [m_scrollbarPainterController.get() horizontalScrollerImp];
1210 ScrollbarPainter newHorizontalPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:newStyle
1211 controlSize:(NSControlSize)horizontalScrollbar->controlSize()
1213 replacingScrollerImp:oldHorizontalPainter];
1214 [m_scrollbarPainterController.get() setHorizontalScrollerImp:newHorizontalPainter];
1215 macTheme->setNewPainterForScrollbar(horizontalScrollbar, newHorizontalPainter);
1217 // The different scrollbar styles have different thicknesses, so we must re-set the
1218 // frameRect to the new thickness, and the re-layout below will ensure the position
1219 // and length are properly updated.
1220 int thickness = macTheme->scrollbarThickness(horizontalScrollbar->controlSize());
1221 horizontalScrollbar->setFrameRect(IntRect(0, 0, thickness, thickness));
1224 // If m_needsScrollerStyleUpdate is true, then the page is restoring from the page cache, and
1225 // a relayout will happen on its own. Otherwise, we must initiate a re-layout ourselves.
1226 if (!m_needsScrollerStyleUpdate)
1227 scrollableArea()->scrollbarStyleChanged();
1229 m_needsScrollerStyleUpdate = false;
1232 void ScrollAnimatorMac::startScrollbarPaintTimer()
1234 m_initialScrollbarPaintTimer.startOneShot(0.1, FROM_HERE);
1237 bool ScrollAnimatorMac::scrollbarPaintTimerIsActive() const
1239 return m_initialScrollbarPaintTimer.isActive();
1242 void ScrollAnimatorMac::stopScrollbarPaintTimer()
1244 m_initialScrollbarPaintTimer.stop();
1247 void ScrollAnimatorMac::initialScrollbarPaintTimerFired(Timer<ScrollAnimatorMac>*)
1249 if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) {
1250 // To force the scrollbars to flash, we have to call hide first. Otherwise, the ScrollbarPainterController
1251 // might think that the scrollbars are already showing and bail early.
1252 [m_scrollbarPainterController.get() hideOverlayScrollers];
1253 [m_scrollbarPainterController.get() flashScrollers];
1257 void ScrollAnimatorMac::sendContentAreaScrolledSoon(const FloatSize& delta)
1259 m_contentAreaScrolledTimerScrollDelta = delta;
1261 if (!m_sendContentAreaScrolledTimer.isActive())
1262 m_sendContentAreaScrolledTimer.startOneShot(0, FROM_HERE);
1265 void ScrollAnimatorMac::sendContentAreaScrolledTimerFired(Timer<ScrollAnimatorMac>*)
1267 if (supportsContentAreaScrolledInDirection()) {
1268 [m_scrollbarPainterController.get() contentAreaScrolledInDirection:NSMakePoint(m_contentAreaScrolledTimerScrollDelta.width(), m_contentAreaScrolledTimerScrollDelta.height())];
1269 m_contentAreaScrolledTimerScrollDelta = FloatSize();
1271 [m_scrollbarPainterController.get() contentAreaScrolled];
1274 void ScrollAnimatorMac::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
1276 IntRect rectInViewCoordinates = scrollerThumb;
1277 if (Scrollbar* verticalScrollbar = m_scrollableArea->verticalScrollbar())
1278 rectInViewCoordinates = verticalScrollbar->convertToContainingView(scrollerThumb);
1280 if (rectInViewCoordinates == m_visibleScrollerThumbRect)
1283 m_visibleScrollerThumbRect = rectInViewCoordinates;
1286 bool ScrollAnimatorMac::canUseCoordinatedScrollbar() {
1287 return ScrollbarThemeMacCommon::isOverlayAPIAvailable();
1290 } // namespace WebCore