Java Code Examples for org.chromium.chrome.browser.util.MathUtils

The following examples show how to use org.chromium.chrome.browser.util.MathUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: AndroidChromium   Source File: FontSizePrefs.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the userFontScaleFactor. This is the value that should be displayed to the user.
 */
public float getUserFontScaleFactor() {
    float userFontScaleFactor = mSharedPreferences.getFloat(PREF_USER_FONT_SCALE_FACTOR, 0f);
    if (userFontScaleFactor == 0f) {
        float fontScaleFactor = getFontScaleFactor();

        if (Math.abs(fontScaleFactor - 1f) <= EPSILON) {
            // If the font scale factor is 1, assume that the user hasn't customized their font
            // scale and/or wants the default value
            userFontScaleFactor = 1f;
        } else {
            // Initialize userFontScaleFactor based on fontScaleFactor, since
            // userFontScaleFactor was added long after fontScaleFactor.
            userFontScaleFactor =
                    MathUtils.clamp(fontScaleFactor / getSystemFontScale(), 0.5f, 2f);
        }
        SharedPreferences.Editor sharedPreferencesEditor = mSharedPreferences.edit();
        sharedPreferencesEditor.putFloat(PREF_USER_FONT_SCALE_FACTOR, userFontScaleFactor);
        sharedPreferencesEditor.apply();
    }
    return userFontScaleFactor;
}
 
Example 2
Source Project: delion   Source File: StripLayoutHelper.java    License: Apache License 2.0 6 votes vote down vote up
private void computeTabInitialPositions() {
    // Shift all of the tabs over by the the left margin because we're
    // no longer base lined at 0
    float tabPosition;
    if (!LocalizationUtils.isLayoutRtl()) {
        tabPosition = mScrollOffset + mLeftMargin;
    } else {
        tabPosition = mWidth - mCachedTabWidth - mScrollOffset - mRightMargin;
    }

    for (int i = 0; i < mStripTabs.length; i++) {
        StripLayoutTab tab = mStripTabs[i];
        tab.setIdealX(tabPosition);
        float delta = (tab.getWidth() - mTabOverlapWidth) * tab.getWidthWeight();
        delta = MathUtils.flipSignIf(delta, LocalizationUtils.isLayoutRtl());
        tabPosition += delta;
    }
}
 
Example 3
Source Project: AndroidChromium   Source File: StackLayout.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fling(long time, float x, float y, float vx, float vy) {
    if (mInputMode == SwipeMode.NONE) {
        mInputMode = computeInputMode(
                time, x, y, vx * SWITCH_STACK_FLING_DT, vy * SWITCH_STACK_FLING_DT);
    }

    if (mInputMode == SwipeMode.SEND_TO_STACK) {
        mStacks[getTabStackIndex()].fling(time, x, y, vx, vy);
    } else if (mInputMode == SwipeMode.SWITCH_STACK) {
        final float velocity = getOrientation() == Orientation.PORTRAIT ? vx : vy;
        final float origin = getOrientation() == Orientation.PORTRAIT ? x : y;
        final float max = getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeight();
        final float predicted = origin + velocity * SWITCH_STACK_FLING_DT;
        final float delta = MathUtils.clamp(predicted, 0, max) - origin;
        scrollStacks(delta);
    }
    requestStackUpdate();
}
 
Example 4
Source Project: delion   Source File: Stack.java    License: Apache License 2.0 6 votes vote down vote up
private void updateOverscrollOffset() {
    float clamped = MathUtils.clamp(mScrollOffset, getMinScroll(false), getMaxScroll(false));
    if (!allowOverscroll()) {
        mScrollOffset = clamped;
    }
    float overscroll = mScrollOffset - clamped;

    // Counts the number of overscroll push in the same direction in a row.
    int derivativeState = (int) Math.signum(Math.abs(mOverScrollOffset) - Math.abs(overscroll));
    if (derivativeState != mOverScrollDerivative && derivativeState == 1 && overscroll < 0) {
        mOverScrollCounter++;
    } else if (overscroll > 0 || mCurrentMode == Orientation.LANDSCAPE) {
        mOverScrollCounter = 0;
    }
    mOverScrollDerivative = derivativeState;

    mOverScrollOffset = overscroll;
}
 
Example 5
Source Project: delion   Source File: StackLayout.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fling(long time, float x, float y, float vx, float vy) {
    if (mInputMode == SwipeMode.NONE) {
        mInputMode = computeInputMode(
                time, x, y, vx * SWITCH_STACK_FLING_DT, vy * SWITCH_STACK_FLING_DT);
    }

    if (mInputMode == SwipeMode.SEND_TO_STACK) {
        mStacks[getTabStackIndex()].fling(time, x, y, vx, vy);
    } else if (mInputMode == SwipeMode.SWITCH_STACK) {
        final float velocity = getOrientation() == Orientation.PORTRAIT ? vx : vy;
        final float origin = getOrientation() == Orientation.PORTRAIT ? x : y;
        final float max = getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeight();
        final float predicted = origin + velocity * SWITCH_STACK_FLING_DT;
        final float delta = MathUtils.clamp(predicted, 0, max) - origin;
        scrollStacks(delta);
    }
    requestStackUpdate();
}
 
Example 6
Source Project: 365browser   Source File: StackLayout.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fling(float x, float y, float velocityX, float velocityY) {
    long time = time();
    float vx = velocityX;
    float vy = velocityY;

    if (mInputMode == SwipeMode.NONE) {
        mInputMode = computeInputMode(
                time, x, y, vx * SWITCH_STACK_FLING_DT, vy * SWITCH_STACK_FLING_DT);
    }

    if (mInputMode == SwipeMode.SEND_TO_STACK) {
        mStacks[getTabStackIndex()].fling(time, x, y, vx, vy);
    } else if (mInputMode == SwipeMode.SWITCH_STACK) {
        final float velocity = getOrientation() == Orientation.PORTRAIT ? vx : vy;
        final float origin = getOrientation() == Orientation.PORTRAIT ? x : y;
        final float max =
                getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeight();
        final float predicted = origin + velocity * SWITCH_STACK_FLING_DT;
        final float delta = MathUtils.clamp(predicted, 0, max) - origin;
        scrollStacks(delta);
    }
    requestStackUpdate();
}
 
Example 7
Source Project: 365browser   Source File: ChromeAnimation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Updates the internal timer based on the time delta passed in.  The proper property value
 * is interpolated and passed to setProperty.
 *
 * @param dtMs The amount of time, in milliseconds, that this animation should be
 *         progressed.
 */
public void update(long dtMs) {
    mCurrentTime += dtMs;

    // Bound our time here so that our scale never goes above 1.0.
    mCurrentTime = Math.min(mCurrentTime, mDuration + mStartDelay);

    if (mDelayStartValue && mCurrentTime < mStartDelay) {
        return;
    }

    // Figure out the relative fraction of time we need to animate.
    long relativeTime = MathUtils.clamp(mCurrentTime - mStartDelay, 0, mDuration);

    if (mDuration > 0) {
        setProperty(MathUtils.interpolate(mStart, mEnd,
                mInterpolator.getInterpolation((float) relativeTime / (float) mDuration)));
    } else {
        setProperty(mEnd);
    }
}
 
Example 8
Source Project: AndroidChromium   Source File: StripLayoutHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called on touch fling event. This is called before the onUpOrCancel event.
 * @param time      The current time of the app in ms.
 * @param x         The y coordinate of the start of the fling event.
 * @param y         The y coordinate of the start of the fling event.
 * @param velocityX The amount of velocity in the x direction.
 * @param velocityY The amount of velocity in the y direction.
 */
public void fling(long time, float x, float y, float velocityX, float velocityY) {
    resetResizeTimeout(false);

    velocityX = MathUtils.flipSignIf(velocityX, LocalizationUtils.isLayoutRtl());

    // 1. If we're currently in reorder mode, don't allow the user to fling.
    if (mInReorderMode) return;

    // 2. If we're fast expanding or scrolling, figure out the destination of the scroll so we
    // can apply it to the end of this fling.
    int scrollDeltaRemaining = 0;
    if (!mScroller.isFinished()) {
        scrollDeltaRemaining = mScroller.getFinalX() - mScrollOffset;

        mInteractingTab = null;
        mScroller.forceFinished(true);
    }

    // 3. Kick off the fling.
    mScroller.fling(
            mScrollOffset, 0, (int) velocityX, 0, (int) mMinScrollOffset, 0, 0, 0, 0, 0, time);
    mScroller.setFinalX(mScroller.getFinalX() + scrollDeltaRemaining);
    mUpdateHost.requestUpdate();
}
 
Example 9
Source Project: 365browser   Source File: BottomSheetContentController.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onSheetOffsetChanged(float heightFraction) {
    // If the omnibox is not focused, allow the navigation bar to set its Y translation.
    if (!mOmniboxHasFocus) {
        float offsetY =
                (mBottomSheet.getMinOffset() - mBottomSheet.getSheetOffsetFromBottom())
                + mDistanceBelowToolbarPx;
        setTranslationY(Math.max(offsetY, 0f));

        if (mBottomSheet.getTargetSheetState() != BottomSheet.SHEET_STATE_PEEK
                && mSelectedItemId == PLACEHOLDER_ID) {
            showBottomSheetContent(R.id.action_home);
        }
    }
    setVisibility(MathUtils.areFloatsEqual(heightFraction, 0f) ? View.GONE : View.VISIBLE);

    mSnackbarManager.dismissAllSnackbars();
}
 
Example 10
Source Project: delion   Source File: StripLayoutHelper.java    License: Apache License 2.0 5 votes vote down vote up
private void updateScrollOffsetPosition(int pos) {
    int oldScrollOffset = mScrollOffset;
    mScrollOffset = MathUtils.clamp(pos, (int) mMinScrollOffset, 0);

    if (mInReorderMode && mScroller.isFinished()) {
        int delta = MathUtils.flipSignIf(
                oldScrollOffset - mScrollOffset, LocalizationUtils.isLayoutRtl());
        updateReorderPosition(delta);
    }
}
 
Example 11
Source Project: delion   Source File: StripLayoutHelper.java    License: Apache License 2.0 5 votes vote down vote up
private void reorderTab(int id, int oldIndex, int newIndex, boolean animate) {
    StripLayoutTab tab = findTabById(id);
    if (tab == null || oldIndex == newIndex) return;

    // 1. If the tab is already at the right spot, don't do anything.
    int index = findIndexForTab(id);
    if (index == newIndex) return;

    // 2. Check if it's the tab we are dragging, but we have an old source index.  Ignore in
    // this case because we probably just already moved it.
    if (mInReorderMode && index != oldIndex && tab == mInteractingTab) return;

    // 3. Swap the tabs.
    moveElement(mStripTabs, index, newIndex);

    // 4. Update newIndex to point to the proper element.
    if (index < newIndex) newIndex--;

    // 5. Animate if necessary.
    if (animate) {
        final float flipWidth = mCachedTabWidth - mTabOverlapWidth;
        final int direction = oldIndex <= newIndex ? 1 : -1;
        final float animationLength =
                MathUtils.flipSignIf(direction * flipWidth, LocalizationUtils.isLayoutRtl());
        StripLayoutTab slideTab = mStripTabs[newIndex - direction];
        startAnimation(buildTabMoveAnimation(slideTab, animationLength), true);
    }
}
 
Example 12
Source Project: 365browser   Source File: ToolbarSwipeLayout.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void swipeFlingOccurred(
        long time, float x, float y, float tx, float ty, float vx, float vy) {
    // Use the velocity to add on final step which simulate a fling.
    final float kickRangeX = getWidth() * FLING_MAX_CONTRIBUTION;
    final float kickRangeY = getHeight() * FLING_MAX_CONTRIBUTION;
    final float kickX = MathUtils.clamp(vx * FLING_TIME_STEP, -kickRangeX, kickRangeX);
    final float kickY = MathUtils.clamp(vy * FLING_TIME_STEP, -kickRangeY, kickRangeY);
    swipeUpdated(time, x, y, 0, 0, tx + kickX, ty + kickY);
}
 
Example 13
Source Project: 365browser   Source File: NewTabPageView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the percentage (between 0 and 1) of the transition from the search box to the
 * omnibox at the top of the New Tab Page, which is determined by the amount of scrolling and
 * the position of the search box.
 *
 * @return the transition percentage
 */
private float getToolbarTransitionPercentage() {
    // During startup the view may not be fully initialized, so we only calculate the current
    // percentage if some basic view properties (height of the containing view, position of the
    // search box) are sane.
    if (getRecyclerView().getHeight() == 0) return 0f;

    if (!mRecyclerView.isFirstItemVisible()) {
        // getVerticalScroll is valid only for the RecyclerView if the first item is visible.
        // If the first item is not visible, we must have scrolled quite far and we know the
        // toolbar transition should be 100%. This might be the initial scroll position due to
        // the scroll restore feature, so the search box will not have been laid out yet.
        return 1f;
    }

    int searchBoxTop = mSearchBoxView.getTop();
    if (searchBoxTop == 0) return 0f;

    // For all other calculations, add the search box padding, because it defines where the
    // visible "border" of the search box is.
    searchBoxTop += mSearchBoxView.getPaddingTop();

    final int scrollY = mRecyclerView.computeVerticalScrollOffset();
    final float transitionLength =
            getResources().getDimension(R.dimen.ntp_search_box_transition_length);
    // Tab strip height is zero on phones, nonzero on tablets.
    int tabStripHeight = getResources().getDimensionPixelSize(R.dimen.tab_strip_height);

    // |scrollY - searchBoxTop + tabStripHeight| gives the distance the search bar is from the
    // top of the tab.
    return MathUtils.clamp((scrollY - searchBoxTop + transitionLength + tabStripHeight)
            / transitionLength, 0f, 1f);
}
 
Example 14
Source Project: delion   Source File: Stack.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Bounces back if we happen to overscroll the stack.
 */
private void springBack(long time) {
    if (mScroller.isFinished()) {
        int minScroll = (int) getMinScroll(false);
        int maxScroll = (int) getMaxScroll(false);
        if (mScrollTarget < minScroll || mScrollTarget > maxScroll) {
            mScroller.springBack(0, (int) mScrollTarget, 0, 0, minScroll, maxScroll, time);
            setScrollTarget(MathUtils.clamp(mScrollTarget, minScroll, maxScroll), false);
            requestUpdate();
        }
    }
}
 
Example 15
Source Project: AndroidChromium   Source File: StackLayout.java    License: Apache License 2.0 5 votes vote down vote up
private void scrollStacks(float delta) {
    cancelAnimation(this, Property.STACK_SNAP);
    float fullDistance = getFullScrollDistance();
    mScrollIndexOffset += MathUtils.flipSignIf(delta / fullDistance,
            getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl());
    if (canScrollLinearly(getTabStackIndex())) {
        mRenderedScrollOffset = mScrollIndexOffset;
    } else {
        mRenderedScrollOffset = (int) MathUtils.clamp(
                mScrollIndexOffset, 0, mStacks[1].isDisplayable() ? -1 : 0);
    }
    requestStackUpdate();
}
 
Example 16
Source Project: 365browser   Source File: FadingBackgroundView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the alpha for the fading view. This specifically does not override
 * {@link #setAlpha(float)} so animations can be canceled if this is called.
 * @param alpha The desired alpha for this view.
 */
public void setViewAlpha(float alpha) {
    if (!isEnabled() || MathUtils.areFloatsEqual(alpha, getAlpha())) return;

    setAlpha(alpha);

    if (mOverlayAnimator != null) mOverlayAnimator.cancel();
}
 
Example 17
Source Project: AndroidChromium   Source File: OverlayPanelBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The color to fill the base page when viewport is resized/changes orientation.
 */
public int getBasePageBackgroundColor() {
    // TODO(pedrosimonetti): Get the color from the CVC and apply a proper brightness transform.
    // NOTE(pedrosimonetti): Assumes the background color of the base page to be white (255)
    // and applies a simple brightness transformation based on the base page value.
    int value = Math.round(255 * mBasePageBrightness);
    value = MathUtils.clamp(value, 0, 255);
    return Color.rgb(value, value, value);
}
 
Example 18
Source Project: delion   Source File: StackLayout.java    License: Apache License 2.0 5 votes vote down vote up
float getClampedRenderedScrollOffset() {
    if (mStacks[1].isDisplayable() || mFlingFromModelChange) {
        return MathUtils.clamp(mRenderedScrollOffset, 0, -1);
    } else {
        return 0;
    }
}
 
Example 19
Source Project: delion   Source File: StackLayout.java    License: Apache License 2.0 5 votes vote down vote up
private void scrollStacks(float delta) {
    cancelAnimation(this, Property.STACK_SNAP);
    float fullDistance = getFullScrollDistance();
    mScrollIndexOffset += MathUtils.flipSignIf(delta / fullDistance,
            getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl());
    if (canScrollLinearly(getTabStackIndex())) {
        mRenderedScrollOffset = mScrollIndexOffset;
    } else {
        mRenderedScrollOffset = (int) MathUtils.clamp(
                mScrollIndexOffset, 0, mStacks[1].isDisplayable() ? -1 : 0);
    }
    requestStackUpdate();
}
 
Example 20
Source Project: delion   Source File: ContextualSearchPromoControl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates the appearance of the Promo.
 *
 * @param percentage The completion percentage. 0.f means the Promo is fully collapsed and
 *                   transparent. 1.f means the Promo is fully expanded and opaque.
 */
private void updateAppearance(float percentage) {
    if (mIsVisible) {
        mHeightPx = Math.round(MathUtils.clamp(percentage * mContentHeightPx,
                0.f, mContentHeightPx));
        mOpacity = percentage;
    } else {
        mHeightPx = 0.f;
        mOpacity = 0.f;
    }

    mHost.onUpdatePromoAppearance();
}
 
Example 21
Source Project: delion   Source File: ContextualSearchPeekPromoControl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Interpolates the UI from states Peeked to Expanded.
 *
 * @param percentage The completion percentage.
 */
public void onUpdateFromPeekToExpand(float percentage) {
    if (!isVisible()) return;

    mHeightPx = Math.round(MathUtils.interpolate(mDefaultHeightPx, 0.f, percentage));
    mTextOpacity = MathUtils.interpolate(1.f, 0.f, percentage);
}
 
Example 22
Source Project: delion   Source File: ContextualSearchPeekPromoControl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates the UI for the appearance animation.
 *
 * @param percentage The completion percentage.
 */
private void updateForAppearanceAnimation(float percentage) {
    mRippleWidthPx = Math.round(MathUtils.interpolate(
            mRippleMinimumWidthPx, mRippleMaximumWidthPx, percentage));

    mRippleOpacity = MathUtils.interpolate(0.f, 1.f, percentage);

    float textOpacityDelay = 0.5f;
    float textOpacityPercentage =
            Math.max(0, percentage - textOpacityDelay) / (1.f - textOpacityDelay);
    mTextOpacity = MathUtils.interpolate(0.f, 1.f, textOpacityPercentage);
}
 
Example 23
Source Project: delion   Source File: OverlayPanelAnimation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the animation duration given the |initialVelocity| and a
 * desired |displacement|.
 *
 * @param initialVelocity The initial velocity of the animation in dps per second.
 * @param displacement The displacement of the animation in dps.
 * @return The animation duration in milliseconds.
 */
private long calculateAnimationDuration(float initialVelocity, float displacement) {
    // NOTE(pedrosimonetti): This formula assumes the deceleration curve is
    // quadratic (t^2),
    // hence the duration formula should be:
    // duration = 2 * displacement / initialVelocity
    //
    // We are also converting the duration from seconds to milliseconds,
    // which explains why
    // we are multiplying by 2000 (2 * 1000) instead of 2.
    return MathUtils.clamp(Math.round(Math.abs(2000 * displacement / initialVelocity)),
            MINIMUM_ANIMATION_DURATION_MS, MAXIMUM_ANIMATION_DURATION_MS);
}
 
Example 24
Source Project: delion   Source File: TabModelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void moveTab(int id, int newIndex) {
    newIndex = MathUtils.clamp(newIndex, 0, mTabs.size());

    int curIndex = TabModelUtils.getTabIndexById(this, id);

    if (curIndex == INVALID_TAB_INDEX || curIndex == newIndex || curIndex + 1 == newIndex) {
        return;
    }

    // TODO(dtrainor): Update the list of undoable tabs instead of committing it.
    commitAllTabClosures();

    Tab tab = mTabs.remove(curIndex);
    if (curIndex < newIndex) --newIndex;

    mTabs.add(newIndex, tab);

    if (curIndex == mIndex) {
        mIndex = newIndex;
    } else if (curIndex < mIndex && newIndex >= mIndex) {
        --mIndex;
    } else if (curIndex > mIndex && newIndex <= mIndex) {
        ++mIndex;
    }

    mRewoundList.resetRewoundState();

    for (TabModelObserver obs : mObservers) obs.didMoveTab(tab, newIndex, curIndex);
}
 
Example 25
Source Project: delion   Source File: TabModelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setIndex(int i, final TabSelectionType type) {
    try {
        TraceEvent.begin("TabModelImpl.setIndex");
        int lastId = getLastId(type);

        if (!isCurrentModel()) {
            mModelDelegate.selectModel(isIncognito());
        }

        if (!hasValidTab()) {
            mIndex = INVALID_TAB_INDEX;
        } else {
            mIndex = MathUtils.clamp(i, 0, mTabs.size() - 1);
        }

        Tab tab = TabModelUtils.getCurrentTab(this);

        mModelDelegate.requestToShowTab(tab, type);

        if (tab != null) {
            for (TabModelObserver obs : mObservers) obs.didSelectTab(tab, type, lastId);

            boolean wasAlreadySelected = tab.getId() == lastId;
            if (!wasAlreadySelected && type == TabSelectionType.FROM_USER && mUma != null) {
                // We only want to record when the user actively switches to a different tab.
                mUma.userSwitchedToTab();
            }
        }

    } finally {
        TraceEvent.end("TabModelImpl.setIndex");
    }
}
 
Example 26
Source Project: delion   Source File: CardViewHolder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Change the width, padding and child opacity of the card to give a smooth transition as the
 * user scrolls.
 * @param viewportHeight The height of the containing viewport, i.e. the area inside the
 *          containing view that is available for drawing.
 */
public void updatePeek(int viewportHeight) {
    // The peeking card's resting position is |mMaxPeekPadding| from the bottom of the screen
    // hence |viewportHeight - mMaxPeekPadding|, and it grows the further it gets from this.
    // Also, make sure the |padding| is between 0 and |mMaxPeekPadding|.
    setPeekingStateForPadding(MathUtils.clamp(
            viewportHeight - mMaxPeekPadding - itemView.getTop(), 0, mMaxPeekPadding));
}
 
Example 27
Source Project: delion   Source File: NewTabPageView.java    License: Apache License 2.0 5 votes vote down vote up
private void updateSearchBoxOnScroll() {
    if (mDisableUrlFocusChangeAnimations) return;

    float toolbarTransitionPercentage;
    // During startup the view may not be fully initialized, so we only calculate the current
    // percentage if some basic view properties are sane.
    if (getWrapperView().getHeight() == 0 || mSearchBoxView.getTop() == 0) {
        toolbarTransitionPercentage = 0f;
    } else if (!mUseCardsUi) {
        toolbarTransitionPercentage =
                MathUtils.clamp(getVerticalScroll() / (float) mSearchBoxView.getTop(), 0f, 1f);
    } else {
        if (!mRecyclerView.isFirstItemVisible()) {
            // getVerticalScroll is valid only for the RecyclerView if the first item is
            // visible. Luckily, if the first item is not visible, we know the toolbar
            // transition should be 100%.
            toolbarTransitionPercentage = 1f;
        } else {
            final int scrollY = getVerticalScroll();
            final int top = mSearchBoxView.getTop();  // Relative to mNewTabPageLayout.
            final int transitionLength = getResources()
                    .getDimensionPixelSize(R.dimen.ntp_search_box_transition_length);

            // |scrollY - top| gives the distance the search bar is from the top of the screen.
            toolbarTransitionPercentage = MathUtils.clamp(
                    (scrollY - top + transitionLength) / (float) transitionLength, 0f, 1f);
        }
    }

    updateVisualsForToolbarTransition(toolbarTransitionPercentage);

    if (mSearchBoxScrollListener != null) {
        mSearchBoxScrollListener.onNtpScrollChanged(toolbarTransitionPercentage);
    }
}
 
Example 28
Source Project: 365browser   Source File: SectionHeaderViewHolder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The header height we want to set.
 */
private int getHeaderHeight(int amountScrolled, boolean canTransition) {
    // If the header cannot transition set the height to the maximum so it always displays.
    if (!canTransition) return mMaxSnippetHeaderHeight;

    // Check if snippet header top is within range to start showing. Set the header height,
    // this is a percentage of how much is scrolled. The balance of the scroll will be used
    // to display the peeking card.
    return MathUtils.clamp((int) (amountScrolled * SCROLL_HEADER_HEIGHT_PERCENTAGE),
            0, mMaxSnippetHeaderHeight);
}
 
Example 29
Source Project: 365browser   Source File: Stack.java    License: Apache License 2.0 5 votes vote down vote up
private void setScrollTarget(float offset, boolean immediate) {
    // Ensure that the stack cannot be scrolled too far in either direction.
    // mScrollOffset is clamped between [-min, 0], where offset 0 has the
    // farthest back tab (the first tab) at the top, with everything else
    // pulled down, and -min has the tab at the top of the stack (the last
    // tab) is pulled up and fully visible.
    final boolean overscroll = allowOverscroll();
    mScrollTarget = MathUtils.clamp(offset, getMinScroll(overscroll), getMaxScroll(overscroll));
    if (immediate) mScrollOffset = mScrollTarget;
    mCurrentScrollDirection = Math.signum(mScrollTarget - mScrollOffset);
}
 
Example 30
Source Project: AndroidChromium   Source File: OverlayPanelBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the last panel height within the limits allowable by our UI.
 *
 * @param height The height of the panel in dps.
 */
protected void setClampedPanelHeight(float height) {
    final float clampedHeight = MathUtils.clamp(height,
            getPanelHeightFromState(getMaximumSupportedState()),
            getPanelHeightFromState(PanelState.PEEKED));
    setPanelHeight(clampedHeight);
}