1 /* 2 * Copyright (C) 2024 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 package com.android.systemui.touchpad.tutorial.ui.gesture 18 19 import android.view.MotionEvent 20 import androidx.compose.ui.input.pointer.util.VelocityTracker1D 21 import java.util.function.Consumer 22 23 /** Velocity in pixels/ms. */ 24 @JvmInline value class Velocity(val value: Float) 25 26 /** 27 * Tracks velocity for processed MotionEvents. Useful for recognizing gestures based on velocity. 28 */ 29 interface VelocityTracker : Consumer<MotionEvent> { 30 calculateVelocitynull31 fun calculateVelocity(): Velocity 32 } 33 34 class VerticalVelocityTracker( 35 private val velocityTracker: VelocityTracker1D = VelocityTracker1D(isDataDifferential = false) 36 ) : VelocityTracker { 37 38 override fun accept(event: MotionEvent) { 39 val action = event.actionMasked 40 if (action == MotionEvent.ACTION_DOWN) { 41 velocityTracker.resetTracking() 42 } 43 velocityTracker.addDataPoint(event.eventTime, event.y) 44 } 45 46 /** 47 * Calculates velocity on demand - this calculation can be expensive so shouldn't be called 48 * after every event. 49 */ 50 override fun calculateVelocity() = Velocity(velocityTracker.calculateVelocity() / 1000) 51 } 52