File: ScrollAnimationKeyboard.cpp

package info (click to toggle)
webkit2gtk 2.48.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 429,620 kB
  • sloc: cpp: 3,696,936; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,276; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (239 lines) | stat: -rw-r--r-- 8,910 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*
 * Copyright (C) 2022 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ScrollAnimationKeyboard.h"

#include "FloatPoint.h"
#include "GeometryUtilities.h"
#include "ScrollExtents.h"
#include "ScrollableArea.h"
#include "TimingFunction.h"
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/TextStream.h>

namespace WebCore {

WTF_MAKE_TZONE_ALLOCATED_IMPL(ScrollAnimationKeyboard);

static FloatSize perpendicularAbsoluteUnitVector(ScrollDirection direction)
{
    switch (direction) {
    case ScrollDirection::ScrollUp:
    case ScrollDirection::ScrollDown:
        return { 1, 0 };
    case ScrollDirection::ScrollLeft:
    case ScrollDirection::ScrollRight:
        return { 0, 1 };
    }
    ASSERT_NOT_REACHED();
    return { };
}

static FloatPoint farthestPointInDirection(FloatPoint a, FloatPoint b, ScrollDirection direction)
{
    switch (direction) {
    case ScrollDirection::ScrollUp:
        return { a.x(), std::min(a.y(), b.y()) };
    case ScrollDirection::ScrollDown:
        return { a.x(), std::max(a.y(), b.y()) };
    case ScrollDirection::ScrollLeft:
        return { std::min(a.x(), b.x()), a.y() };
    case ScrollDirection::ScrollRight:
        return { std::max(a.x(), b.x()), a.y() };
    }

    ASSERT_NOT_REACHED();
    return { };
}

RectEdges<bool> ScrollAnimationKeyboard::scrollableDirectionsFromPosition(FloatPoint position)
{
    auto extents = m_client.scrollExtentsForAnimation(*this);

    auto minimumScrollPosition = extents.minimumScrollOffset();
    auto maximumScrollPosition = extents.maximumScrollOffset();

    RectEdges<bool> edges;

    edges.setTop(position.y() > minimumScrollPosition.y());
    edges.setBottom(position.y() < maximumScrollPosition.y());
    edges.setLeft(position.x() > minimumScrollPosition.x());
    edges.setRight(position.x() < maximumScrollPosition.x());

    return edges;
}

ScrollAnimationKeyboard::ScrollAnimationKeyboard(ScrollAnimationClient& client)
    : ScrollAnimation(Type::Keyboard, client)
{
}

ScrollAnimationKeyboard::~ScrollAnimationKeyboard() = default;

bool ScrollAnimationKeyboard::retargetActiveAnimation(const FloatPoint&)
{
    if (!isActive())
        return false;

    return true;
}

void ScrollAnimationKeyboard::serviceAnimation(MonotonicTime currentTime)
{
    animateScroll(currentTime);
}

bool ScrollAnimationKeyboard::startKeyboardScroll(const KeyboardScroll& scrollData)
{
    m_timeAtLastFrame = MonotonicTime::now();
    m_currentKeyboardScroll = scrollData;
    m_scrollTriggeringKeyIsPressed = true;
    m_currentOffset = m_client.scrollOffset(*this);
    m_idealPositionForMinimumTravel = {
        (m_currentOffset + m_currentKeyboardScroll->offset).x(),
        (m_currentOffset + m_currentKeyboardScroll->offset).y() };

    if (!isActive())
        didStart(MonotonicTime::now());

    return true;
}

void ScrollAnimationKeyboard::stopKeyboardScrollAnimation()
{
    if (!m_currentKeyboardScroll)
        return;

    constexpr auto params = KeyboardScrollParameters::parameters();

    // Determine the settling position of the spring, conserving the system's current energy.
    // Kinetic = elastic potential
    // 1/2 * m * v^2 = 1/2 * k * x^2
    // x = sqrt(v^2 * m / k)
    auto displacementMagnitudeSquared = (m_velocity * m_velocity).scaled(params.springMass / params.springStiffness);
    FloatPoint displacement = {
        std::copysign(sqrt(displacementMagnitudeSquared.width()), m_velocity.width()),
        std::copysign(sqrt(displacementMagnitudeSquared.height()), m_velocity.height())
    };

    // If the spring would settle before the minimum travel distance
    // for an instantaneous tap, move the settling position of the spring
    // out to that point.
    FloatPoint farthestPoint = farthestPointInDirection(m_currentOffset + displacement, { m_idealPositionForMinimumTravel.width(), m_idealPositionForMinimumTravel.height() }, m_currentKeyboardScroll->direction);

    auto extents = m_client.scrollExtentsForAnimation(*this);

    m_idealPosition = farthestPoint.constrainedBetween(extents.minimumScrollOffset(), extents.maximumScrollOffset());

    m_currentKeyboardScroll = std::nullopt;
}

void ScrollAnimationKeyboard::finishKeyboardScroll(bool immediate)
{
    if (!m_scrollTriggeringKeyIsPressed && !immediate)
        return;

    if (!immediate)
        stopKeyboardScrollAnimation();
    
    m_scrollTriggeringKeyIsPressed = false;

    if (immediate) {
        didEnd();
        m_velocity = { };
    }
}

bool ScrollAnimationKeyboard::animateScroll(MonotonicTime currentTime)
{
    auto force = FloatSize { };
    auto axesToApplySpring = FloatSize { 1, 1 };
    constexpr auto parameters = KeyboardScrollParameters::parameters();

    if (m_currentKeyboardScroll) {
        auto scrollableDirections = scrollableDirectionsFromPosition(m_currentOffset);
        auto direction = m_currentKeyboardScroll->direction;

        if (scrollableDirections.at(boxSideForDirection(direction))) {
            // Apply the scrolling force. Only apply the spring in the perpendicular axis,
            // otherwise it drags against the direction of motion.
            axesToApplySpring = perpendicularAbsoluteUnitVector(direction);
            force = m_currentKeyboardScroll->force;
        } else {
            // The scroll view cannot scroll in this direction, and is rubber-banding.
            // Apply a constant and significant force; otherwise, the force for a
            // single-line increment is not strong enough to rubber-band perceptibly.
            force = unitVectorForScrollDirection(direction).scaled(parameters.rubberBandForce);
        }

        if (std::abs(m_velocity.width()) >= std::abs(m_currentKeyboardScroll->maximumVelocity.width()))
            force.setWidth(0);

        if (std::abs(m_velocity.height()) >= std::abs(m_currentKeyboardScroll->maximumVelocity.height()))
            force.setHeight(0);
    }

    auto extents = m_client.scrollExtentsForAnimation(*this);

    FloatPoint idealPosition = (IntPoint(m_currentKeyboardScroll ? m_currentOffset : m_idealPosition).constrainedBetween(IntPoint(extents.minimumScrollOffset()), IntPoint(extents.maximumScrollOffset())));
    FloatSize displacement = m_currentOffset - idealPosition;

    auto springForce = -displacement.scaled(parameters.springStiffness) - m_velocity.scaled(parameters.springDamping);
    force += springForce * axesToApplySpring;

    float frameDuration = (currentTime - m_timeAtLastFrame).value();
    m_timeAtLastFrame = currentTime;

    FloatSize acceleration = force.scaled(1. / parameters.springMass);
    m_velocity += acceleration.scaled(frameDuration);
    m_currentOffset = m_currentOffset + m_velocity.scaled(frameDuration);

    m_client.scrollAnimationDidUpdate(*this, m_currentOffset);

    // Stop the spring if it reaches the ideal position.
    FloatSize newDisplacement = m_currentOffset - idealPosition;

    if (axesToApplySpring.width() && displacement.width() * newDisplacement.width() < 0)
        m_velocity.setWidth(0);
    if (axesToApplySpring.height() && displacement.height() * newDisplacement.height() < 0)
        m_velocity.setHeight(0);

    if (!m_scrollTriggeringKeyIsPressed && m_velocity.diagonalLengthSquared() < 1) {
        didEnd();
        m_velocity = { };
    }

    return true;
}

String ScrollAnimationKeyboard::debugDescription() const
{
    TextStream textStream;
    textStream << "ScrollAnimationKeyboard " << this << " active " << isActive() << " current offset " << currentOffset() << " current velocity " << m_velocity;
    return textStream.release();
}

} // namespace WebCore