michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.gfx; michael@0: michael@0: import java.util.HashMap; michael@0: import java.util.Map; michael@0: michael@0: import org.mozilla.gecko.GeckoAppShell; michael@0: import org.mozilla.gecko.PrefsHelper; michael@0: import org.mozilla.gecko.util.FloatUtils; michael@0: michael@0: import android.util.Log; michael@0: import android.view.View; michael@0: michael@0: /** michael@0: * This class represents the physics for one axis of movement (i.e. either michael@0: * horizontal or vertical). It tracks the different properties of movement michael@0: * like displacement, velocity, viewport dimensions, etc. pertaining to michael@0: * a particular axis. michael@0: */ michael@0: abstract class Axis { michael@0: private static final String LOGTAG = "GeckoAxis"; michael@0: michael@0: private static final String PREF_SCROLLING_FRICTION_SLOW = "ui.scrolling.friction_slow"; michael@0: private static final String PREF_SCROLLING_FRICTION_FAST = "ui.scrolling.friction_fast"; michael@0: private static final String PREF_SCROLLING_MAX_EVENT_ACCELERATION = "ui.scrolling.max_event_acceleration"; michael@0: private static final String PREF_SCROLLING_OVERSCROLL_DECEL_RATE = "ui.scrolling.overscroll_decel_rate"; michael@0: private static final String PREF_SCROLLING_OVERSCROLL_SNAP_LIMIT = "ui.scrolling.overscroll_snap_limit"; michael@0: private static final String PREF_SCROLLING_MIN_SCROLLABLE_DISTANCE = "ui.scrolling.min_scrollable_distance"; michael@0: michael@0: // This fraction of velocity remains after every animation frame when the velocity is low. michael@0: private static float FRICTION_SLOW; michael@0: // This fraction of velocity remains after every animation frame when the velocity is high. michael@0: private static float FRICTION_FAST; michael@0: // Below this velocity (in pixels per frame), the friction starts increasing from FRICTION_FAST michael@0: // to FRICTION_SLOW. michael@0: private static float VELOCITY_THRESHOLD; michael@0: // The maximum velocity change factor between events, per ms, in %. michael@0: // Direction changes are excluded. michael@0: private static float MAX_EVENT_ACCELERATION; michael@0: michael@0: // The rate of deceleration when the surface has overscrolled. michael@0: private static float OVERSCROLL_DECEL_RATE; michael@0: // The percentage of the surface which can be overscrolled before it must snap back. michael@0: private static float SNAP_LIMIT; michael@0: michael@0: // The minimum amount of space that must be present for an axis to be considered scrollable, michael@0: // in pixels. michael@0: private static float MIN_SCROLLABLE_DISTANCE; michael@0: michael@0: private static float getFloatPref(Map prefs, String prefName, int defaultValue) { michael@0: Integer value = (prefs == null ? null : prefs.get(prefName)); michael@0: return (float)(value == null || value < 0 ? defaultValue : value) / 1000f; michael@0: } michael@0: michael@0: private static int getIntPref(Map prefs, String prefName, int defaultValue) { michael@0: Integer value = (prefs == null ? null : prefs.get(prefName)); michael@0: return (value == null || value < 0 ? defaultValue : value); michael@0: } michael@0: michael@0: static void initPrefs() { michael@0: final String[] prefs = { PREF_SCROLLING_FRICTION_FAST, michael@0: PREF_SCROLLING_FRICTION_SLOW, michael@0: PREF_SCROLLING_MAX_EVENT_ACCELERATION, michael@0: PREF_SCROLLING_OVERSCROLL_DECEL_RATE, michael@0: PREF_SCROLLING_OVERSCROLL_SNAP_LIMIT, michael@0: PREF_SCROLLING_MIN_SCROLLABLE_DISTANCE }; michael@0: michael@0: PrefsHelper.getPrefs(prefs, new PrefsHelper.PrefHandlerBase() { michael@0: Map mPrefs = new HashMap(); michael@0: michael@0: @Override public void prefValue(String name, int value) { michael@0: mPrefs.put(name, value); michael@0: } michael@0: michael@0: @Override public void finish() { michael@0: setPrefs(mPrefs); michael@0: } michael@0: }); michael@0: } michael@0: michael@0: static final float MS_PER_FRAME = 1000.0f / 60.0f; michael@0: static final long NS_PER_FRAME = Math.round(1000000000f / 60f); michael@0: private static final float FRAMERATE_MULTIPLIER = (1000f/60f) / MS_PER_FRAME; michael@0: private static final int FLING_VELOCITY_POINTS = 8; michael@0: michael@0: // The values we use for friction are based on a 16.6ms frame, adjust them to currentNsPerFrame: michael@0: static float getFrameAdjustedFriction(float baseFriction, long currentNsPerFrame) { michael@0: float framerateMultiplier = (float)currentNsPerFrame / NS_PER_FRAME; michael@0: return (float)Math.pow(Math.E, (Math.log(baseFriction) / framerateMultiplier)); michael@0: } michael@0: michael@0: static void setPrefs(Map prefs) { michael@0: FRICTION_SLOW = getFloatPref(prefs, PREF_SCROLLING_FRICTION_SLOW, 850); michael@0: FRICTION_FAST = getFloatPref(prefs, PREF_SCROLLING_FRICTION_FAST, 970); michael@0: VELOCITY_THRESHOLD = 10 / FRAMERATE_MULTIPLIER; michael@0: MAX_EVENT_ACCELERATION = getFloatPref(prefs, PREF_SCROLLING_MAX_EVENT_ACCELERATION, GeckoAppShell.getDpi() > 300 ? 100 : 40); michael@0: OVERSCROLL_DECEL_RATE = getFloatPref(prefs, PREF_SCROLLING_OVERSCROLL_DECEL_RATE, 40); michael@0: SNAP_LIMIT = getFloatPref(prefs, PREF_SCROLLING_OVERSCROLL_SNAP_LIMIT, 300); michael@0: MIN_SCROLLABLE_DISTANCE = getFloatPref(prefs, PREF_SCROLLING_MIN_SCROLLABLE_DISTANCE, 500); michael@0: Log.i(LOGTAG, "Prefs: " + FRICTION_SLOW + "," + FRICTION_FAST + "," + VELOCITY_THRESHOLD + "," michael@0: + MAX_EVENT_ACCELERATION + "," + OVERSCROLL_DECEL_RATE + "," + SNAP_LIMIT + "," + MIN_SCROLLABLE_DISTANCE); michael@0: } michael@0: michael@0: static { michael@0: // set the scrolling parameters to default values on startup michael@0: setPrefs(null); michael@0: } michael@0: michael@0: private enum FlingStates { michael@0: STOPPED, michael@0: PANNING, michael@0: FLINGING, michael@0: } michael@0: michael@0: private enum Overscroll { michael@0: NONE, michael@0: MINUS, // Overscrolled in the negative direction michael@0: PLUS, // Overscrolled in the positive direction michael@0: BOTH, // Overscrolled in both directions (page is zoomed to smaller than screen) michael@0: } michael@0: michael@0: private final SubdocumentScrollHelper mSubscroller; michael@0: michael@0: private int mOverscrollMode; /* Default to only overscrolling if we're allowed to scroll in a direction */ michael@0: private float mFirstTouchPos; /* Position of the first touch event on the current drag. */ michael@0: private float mTouchPos; /* Position of the most recent touch event on the current drag. */ michael@0: private float mLastTouchPos; /* Position of the touch event before touchPos. */ michael@0: private float mVelocity; /* Velocity in this direction; pixels per animation frame. */ michael@0: private float[] mRecentVelocities; /* Circular buffer of recent velocities since last touch start. */ michael@0: private int mRecentVelocityCount; /* Number of values put into mRecentVelocities (unbounded). */ michael@0: private boolean mScrollingDisabled; /* Whether movement on this axis is locked. */ michael@0: private boolean mDisableSnap; /* Whether overscroll snapping is disabled. */ michael@0: private float mDisplacement; michael@0: michael@0: private FlingStates mFlingState = FlingStates.STOPPED; /* The fling state we're in on this axis. */ michael@0: michael@0: protected abstract float getOrigin(); michael@0: protected abstract float getViewportLength(); michael@0: protected abstract float getPageStart(); michael@0: protected abstract float getPageLength(); michael@0: protected abstract float getMarginStart(); michael@0: protected abstract float getMarginEnd(); michael@0: protected abstract boolean marginsHidden(); michael@0: michael@0: Axis(SubdocumentScrollHelper subscroller) { michael@0: mSubscroller = subscroller; michael@0: mOverscrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS; michael@0: mRecentVelocities = new float[FLING_VELOCITY_POINTS]; michael@0: } michael@0: michael@0: // Implementors can override these to show effects when the axis overscrolls michael@0: protected void overscrollFling(float velocity) { } michael@0: protected void overscrollPan(float displacement) { } michael@0: michael@0: public void setOverScrollMode(int overscrollMode) { michael@0: mOverscrollMode = overscrollMode; michael@0: } michael@0: michael@0: public int getOverScrollMode() { michael@0: return mOverscrollMode; michael@0: } michael@0: michael@0: private float getViewportEnd() { michael@0: return getOrigin() + getViewportLength(); michael@0: } michael@0: michael@0: private float getPageEnd() { michael@0: return getPageStart() + getPageLength(); michael@0: } michael@0: michael@0: void startTouch(float pos) { michael@0: mVelocity = 0.0f; michael@0: mScrollingDisabled = false; michael@0: mFirstTouchPos = mTouchPos = mLastTouchPos = pos; michael@0: mRecentVelocityCount = 0; michael@0: } michael@0: michael@0: float panDistance(float currentPos) { michael@0: return currentPos - mFirstTouchPos; michael@0: } michael@0: michael@0: void setScrollingDisabled(boolean disabled) { michael@0: mScrollingDisabled = disabled; michael@0: } michael@0: michael@0: void saveTouchPos() { michael@0: mLastTouchPos = mTouchPos; michael@0: } michael@0: michael@0: void updateWithTouchAt(float pos, float timeDelta) { michael@0: float newVelocity = (mTouchPos - pos) / timeDelta * MS_PER_FRAME; michael@0: michael@0: mRecentVelocities[mRecentVelocityCount % FLING_VELOCITY_POINTS] = newVelocity; michael@0: mRecentVelocityCount++; michael@0: michael@0: // If there's a direction change, or current velocity is very low, michael@0: // allow setting of the velocity outright. Otherwise, use the current michael@0: // velocity and a maximum change factor to set the new velocity. michael@0: boolean curVelocityIsLow = Math.abs(mVelocity) < 1.0f / FRAMERATE_MULTIPLIER; michael@0: boolean directionChange = (mVelocity > 0) != (newVelocity > 0); michael@0: if (curVelocityIsLow || (directionChange && !FloatUtils.fuzzyEquals(newVelocity, 0.0f))) { michael@0: mVelocity = newVelocity; michael@0: } else { michael@0: float maxChange = Math.abs(mVelocity * timeDelta * MAX_EVENT_ACCELERATION); michael@0: mVelocity = Math.min(mVelocity + maxChange, Math.max(mVelocity - maxChange, newVelocity)); michael@0: } michael@0: michael@0: mTouchPos = pos; michael@0: } michael@0: michael@0: boolean overscrolled() { michael@0: return getOverscroll() != Overscroll.NONE; michael@0: } michael@0: michael@0: private Overscroll getOverscroll() { michael@0: boolean minus = (getOrigin() < getPageStart()); michael@0: boolean plus = (getViewportEnd() > getPageEnd()); michael@0: if (minus && plus) { michael@0: return Overscroll.BOTH; michael@0: } else if (minus) { michael@0: return Overscroll.MINUS; michael@0: } else if (plus) { michael@0: return Overscroll.PLUS; michael@0: } else { michael@0: return Overscroll.NONE; michael@0: } michael@0: } michael@0: michael@0: // Returns the amount that the page has been overscrolled. If the page hasn't been michael@0: // overscrolled on this axis, returns 0. michael@0: private float getExcess() { michael@0: switch (getOverscroll()) { michael@0: case MINUS: return getPageStart() - getOrigin(); michael@0: case PLUS: return getViewportEnd() - getPageEnd(); michael@0: case BOTH: return (getViewportEnd() - getPageEnd()) + (getPageStart() - getOrigin()); michael@0: default: return 0.0f; michael@0: } michael@0: } michael@0: michael@0: /* michael@0: * Returns true if the page is zoomed in to some degree along this axis such that scrolling is michael@0: * possible and this axis has not been scroll locked while panning. Otherwise, returns false. michael@0: */ michael@0: boolean scrollable() { michael@0: // If we're scrolling a subdocument, ignore the viewport length restrictions (since those michael@0: // apply to the top-level document) and only take into account axis locking. michael@0: if (mSubscroller.scrolling()) { michael@0: return !mScrollingDisabled; michael@0: } michael@0: michael@0: // if we are axis locked, return false michael@0: if (mScrollingDisabled) { michael@0: return false; michael@0: } michael@0: michael@0: // if there are margins on this axis but they are currently hidden, michael@0: // we must be able to scroll in order to make them visible, so allow michael@0: // scrolling in that case michael@0: if (marginsHidden()) { michael@0: return true; michael@0: } michael@0: michael@0: // there is scrollable space, and we're not disabled, or the document fits the viewport michael@0: // but we always allow overscroll anyway michael@0: return getViewportLength() <= getPageLength() - MIN_SCROLLABLE_DISTANCE || michael@0: getOverScrollMode() == View.OVER_SCROLL_ALWAYS; michael@0: } michael@0: michael@0: /* michael@0: * Returns the resistance, as a multiplier, that should be taken into account when michael@0: * tracking or pinching. michael@0: */ michael@0: float getEdgeResistance(boolean forPinching) { michael@0: float excess = getExcess(); michael@0: if (excess > 0.0f && (getOverscroll() == Overscroll.BOTH || !forPinching)) { michael@0: // excess can be greater than viewport length, but the resistance michael@0: // must never drop below 0.0 michael@0: return Math.max(0.0f, SNAP_LIMIT - excess / getViewportLength()); michael@0: } michael@0: return 1.0f; michael@0: } michael@0: michael@0: /* Returns the velocity. If the axis is locked, returns 0. */ michael@0: float getRealVelocity() { michael@0: return scrollable() ? mVelocity : 0f; michael@0: } michael@0: michael@0: void startPan() { michael@0: mFlingState = FlingStates.PANNING; michael@0: } michael@0: michael@0: private float calculateFlingVelocity() { michael@0: int usablePoints = Math.min(mRecentVelocityCount, FLING_VELOCITY_POINTS); michael@0: if (usablePoints <= 1) { michael@0: return mVelocity; michael@0: } michael@0: float average = 0; michael@0: for (int i = 0; i < usablePoints; i++) { michael@0: average += mRecentVelocities[i]; michael@0: } michael@0: return average / usablePoints; michael@0: } michael@0: michael@0: void startFling(boolean stopped) { michael@0: mDisableSnap = mSubscroller.scrolling(); michael@0: michael@0: if (stopped) { michael@0: mFlingState = FlingStates.STOPPED; michael@0: } else { michael@0: mVelocity = calculateFlingVelocity(); michael@0: mFlingState = FlingStates.FLINGING; michael@0: } michael@0: } michael@0: michael@0: /* Advances a fling animation by one step. */ michael@0: boolean advanceFling(long realNsPerFrame) { michael@0: if (mFlingState != FlingStates.FLINGING) { michael@0: return false; michael@0: } michael@0: if (mSubscroller.scrolling() && !mSubscroller.lastScrollSucceeded()) { michael@0: // if the subdocument stopped scrolling, it's because it reached the end michael@0: // of the subdocument. we don't do overscroll on subdocuments, so there's michael@0: // no point in continuing this fling. michael@0: return false; michael@0: } michael@0: michael@0: float excess = getExcess(); michael@0: Overscroll overscroll = getOverscroll(); michael@0: boolean decreasingOverscroll = false; michael@0: if ((overscroll == Overscroll.MINUS && mVelocity > 0) || michael@0: (overscroll == Overscroll.PLUS && mVelocity < 0)) michael@0: { michael@0: decreasingOverscroll = true; michael@0: } michael@0: michael@0: if (mDisableSnap || FloatUtils.fuzzyEquals(excess, 0.0f) || decreasingOverscroll) { michael@0: // If we aren't overscrolled, just apply friction. michael@0: if (Math.abs(mVelocity) >= VELOCITY_THRESHOLD) { michael@0: mVelocity *= getFrameAdjustedFriction(FRICTION_FAST, realNsPerFrame); michael@0: } else { michael@0: float t = mVelocity / VELOCITY_THRESHOLD; michael@0: mVelocity *= FloatUtils.interpolate(getFrameAdjustedFriction(FRICTION_SLOW, realNsPerFrame), michael@0: getFrameAdjustedFriction(FRICTION_FAST, realNsPerFrame), t); michael@0: } michael@0: } else { michael@0: // Otherwise, decrease the velocity linearly. michael@0: float elasticity = 1.0f - excess / (getViewportLength() * SNAP_LIMIT); michael@0: float overscrollDecelRate = getFrameAdjustedFriction(OVERSCROLL_DECEL_RATE, realNsPerFrame); michael@0: if (overscroll == Overscroll.MINUS) { michael@0: mVelocity = Math.min((mVelocity + overscrollDecelRate) * elasticity, 0.0f); michael@0: } else { // must be Overscroll.PLUS michael@0: mVelocity = Math.max((mVelocity - overscrollDecelRate) * elasticity, 0.0f); michael@0: } michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: void stopFling() { michael@0: mVelocity = 0.0f; michael@0: mFlingState = FlingStates.STOPPED; michael@0: } michael@0: michael@0: // Performs displacement of the viewport position according to the current velocity. michael@0: void displace() { michael@0: // if this isn't scrollable just return michael@0: if (!scrollable()) michael@0: return; michael@0: michael@0: if (mFlingState == FlingStates.PANNING) michael@0: mDisplacement += (mLastTouchPos - mTouchPos) * getEdgeResistance(false); michael@0: else michael@0: mDisplacement += mVelocity * getEdgeResistance(false); michael@0: michael@0: // if overscroll is disabled and we're trying to overscroll, reset the displacement michael@0: // to remove any excess. Using getExcess alone isn't enough here since it relies on michael@0: // getOverscroll which doesn't take into account any new displacment being applied. michael@0: // If we using a subscroller, we don't want to alter the scrolling being done michael@0: if (getOverScrollMode() == View.OVER_SCROLL_NEVER && !mSubscroller.scrolling()) { michael@0: float originalDisplacement = mDisplacement; michael@0: michael@0: if (mDisplacement + getOrigin() < getPageStart() - getMarginStart()) { michael@0: mDisplacement = getPageStart() - getMarginStart() - getOrigin(); michael@0: } else if (mDisplacement + getViewportEnd() > getPageEnd() + getMarginEnd()) { michael@0: mDisplacement = getPageEnd() - getMarginEnd() - getViewportEnd(); michael@0: } michael@0: michael@0: // Return the amount of overscroll so that the overscroll controller can draw it for us michael@0: if (originalDisplacement != mDisplacement) { michael@0: if (mFlingState == FlingStates.FLINGING) { michael@0: overscrollFling(mVelocity / MS_PER_FRAME * 1000); michael@0: stopFling(); michael@0: } else if (mFlingState == FlingStates.PANNING) { michael@0: overscrollPan(originalDisplacement - mDisplacement); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: float resetDisplacement() { michael@0: float d = mDisplacement; michael@0: mDisplacement = 0.0f; michael@0: return d; michael@0: } michael@0: michael@0: void setAutoscrollVelocity(float velocity) { michael@0: if (mFlingState != FlingStates.STOPPED) { michael@0: Log.e(LOGTAG, "Setting autoscroll velocity while in a fling is not allowed!"); michael@0: return; michael@0: } michael@0: mVelocity = velocity; michael@0: } michael@0: }