blob: 6f31d0ebe3f5a30553f2dc6b6af797a728f168cc [file] [log] [blame]
Yeabkal Wubshit6b662762023-05-22 23:07:31 -07001/*
2 * Copyright 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// clang-format off
18#include "../Macros.h"
19// clang-format on
20
21#include "SlopController.h"
22
23namespace {
24int signOf(float value) {
25 if (value == 0) return 0;
26 if (value > 0) return 1;
27 return -1;
28}
29} // namespace
30
31namespace android {
32
33SlopController::SlopController(float slopThreshold, nsecs_t slopDurationNanos)
34 : mSlopThreshold(slopThreshold), mSlopDurationNanos(slopDurationNanos) {}
35
36SlopController::~SlopController() {}
37
38float SlopController::consumeEvent(nsecs_t eventTimeNanos, float value) {
39 if (mSlopDurationNanos == 0) {
40 return value;
41 }
42
43 if (shouldResetSlopTracking(eventTimeNanos, value)) {
44 mCumulativeValue = 0;
45 mHasSlopBeenMet = false;
46 }
47
48 mLastEventTimeNanos = eventTimeNanos;
49
50 if (mHasSlopBeenMet) {
51 // Since slop has already been met, we know that all of the current value would pass the
52 // slop threshold. So return that, without any further processing.
53 return value;
54 }
55
56 mCumulativeValue += value;
57
58 if (abs(mCumulativeValue) >= mSlopThreshold) {
59 mHasSlopBeenMet = true;
60 // Return the amount of value that exceeds the slop.
61 return signOf(value) * (abs(mCumulativeValue) - mSlopThreshold);
62 }
63
64 return 0;
65}
66
67bool SlopController::shouldResetSlopTracking(nsecs_t eventTimeNanos, float value) {
68 const nsecs_t ageNanos = eventTimeNanos - mLastEventTimeNanos;
69 if (ageNanos >= mSlopDurationNanos) {
70 return true;
71 }
72 if (value == 0) {
73 return false;
74 }
75 if (signOf(mCumulativeValue) != signOf(value)) {
76 return true;
77 }
78 return false;
79}
80
81} // namespace android