Example usage for android.graphics Canvas save

List of usage examples for android.graphics Canvas save

Introduction

In this page you can find the example usage for android.graphics Canvas save.

Prototype

public int save() 

Source Link

Document

Saves the current matrix and clip onto a private stack.

Usage

From source file:org.telegram.ui.ArticleViewer.java

private void drawContent(Canvas canvas) {
    if (photoAnimationInProgress == 1 || !isPhotoVisible && photoAnimationInProgress != 2) {
        return;//from  w w w . j a  va2 s .com
    }

    float currentTranslationY;
    float currentTranslationX;
    float currentScale;
    float aty = -1;

    if (imageMoveAnimation != null) {
        if (!scroller.isFinished()) {
            scroller.abortAnimation();
        }

        float ts = scale + (animateToScale - scale) * animationValue;
        float tx = translationX + (animateToX - translationX) * animationValue;
        float ty = translationY + (animateToY - translationY) * animationValue;

        if (animateToScale == 1 && scale == 1 && translationX == 0) {
            aty = ty;
        }
        currentScale = ts;
        currentTranslationY = ty;
        currentTranslationX = tx;
        photoContainerView.invalidate();
    } else {
        if (animationStartTime != 0) {
            translationX = animateToX;
            translationY = animateToY;
            scale = animateToScale;
            animationStartTime = 0;
            updateMinMax(scale);
            zoomAnimation = false;
        }
        if (!scroller.isFinished()) {
            if (scroller.computeScrollOffset()) {
                if (scroller.getStartX() < maxX && scroller.getStartX() > minX) {
                    translationX = scroller.getCurrX();
                }
                if (scroller.getStartY() < maxY && scroller.getStartY() > minY) {
                    translationY = scroller.getCurrY();
                }
                photoContainerView.invalidate();
            }
        }
        if (switchImageAfterAnimation != 0) {
            if (switchImageAfterAnimation == 1) {
                setImageIndex(currentIndex + 1, false);
            } else if (switchImageAfterAnimation == 2) {
                setImageIndex(currentIndex - 1, false);
            }
            switchImageAfterAnimation = 0;
        }
        currentScale = scale;
        currentTranslationY = translationY;
        currentTranslationX = translationX;
        if (!moving) {
            aty = translationY;
        }
    }

    if (scale == 1 && aty != -1 && !zoomAnimation) {
        float maxValue = getContainerViewHeight() / 4.0f;
        photoBackgroundDrawable
                .setAlpha((int) Math.max(127, 255 * (1.0f - (Math.min(Math.abs(aty), maxValue) / maxValue))));
    } else {
        photoBackgroundDrawable.setAlpha(255);
    }

    ImageReceiver sideImage = null;

    if (scale >= 1.0f && !zoomAnimation && !zooming) {
        if (currentTranslationX > maxX + AndroidUtilities.dp(5)) {
            sideImage = leftImage;
        } else if (currentTranslationX < minX - AndroidUtilities.dp(5)) {
            sideImage = rightImage;
        }
    }
    changingPage = sideImage != null;

    if (sideImage == rightImage) {
        float tranlateX = currentTranslationX;
        float scaleDiff = 0;
        float alpha = 1;
        if (!zoomAnimation && tranlateX < minX) {
            alpha = Math.min(1.0f, (minX - tranlateX) / canvas.getWidth());
            scaleDiff = (1.0f - alpha) * 0.3f;
            tranlateX = -canvas.getWidth() - AndroidUtilities.dp(30) / 2;
        }

        if (sideImage.hasBitmapImage()) {
            canvas.save();
            canvas.translate(getContainerViewWidth() / 2, getContainerViewHeight() / 2);
            canvas.translate(canvas.getWidth() + AndroidUtilities.dp(30) / 2 + tranlateX, 0);
            canvas.scale(1.0f - scaleDiff, 1.0f - scaleDiff);
            int bitmapWidth = sideImage.getBitmapWidth();
            int bitmapHeight = sideImage.getBitmapHeight();

            float scaleX = (float) getContainerViewWidth() / (float) bitmapWidth;
            float scaleY = (float) getContainerViewHeight() / (float) bitmapHeight;
            float scale = scaleX > scaleY ? scaleY : scaleX;
            int width = (int) (bitmapWidth * scale);
            int height = (int) (bitmapHeight * scale);

            sideImage.setAlpha(alpha);
            sideImage.setImageCoords(-width / 2, -height / 2, width, height);
            sideImage.draw(canvas);
            canvas.restore();
        }

        canvas.save();
        canvas.translate(tranlateX, currentTranslationY / currentScale);
        canvas.translate((canvas.getWidth() * (scale + 1) + AndroidUtilities.dp(30)) / 2,
                -currentTranslationY / currentScale);
        radialProgressViews[1].setScale(1.0f - scaleDiff);
        radialProgressViews[1].setAlpha(alpha);
        radialProgressViews[1].onDraw(canvas);
        canvas.restore();
    }

    float translateX = currentTranslationX;
    float scaleDiff = 0;
    float alpha = 1;
    if (!zoomAnimation && translateX > maxX) {
        alpha = Math.min(1.0f, (translateX - maxX) / canvas.getWidth());
        scaleDiff = alpha * 0.3f;
        alpha = 1.0f - alpha;
        translateX = maxX;
    }
    boolean drawTextureView = aspectRatioFrameLayout != null
            && aspectRatioFrameLayout.getVisibility() == View.VISIBLE;
    if (centerImage.hasBitmapImage()) {
        canvas.save();
        canvas.translate(getContainerViewWidth() / 2, getContainerViewHeight() / 2);
        canvas.translate(translateX, currentTranslationY);
        canvas.scale(currentScale - scaleDiff, currentScale - scaleDiff);

        int bitmapWidth = centerImage.getBitmapWidth();
        int bitmapHeight = centerImage.getBitmapHeight();
        if (drawTextureView && textureUploaded) {
            float scale1 = bitmapWidth / (float) bitmapHeight;
            float scale2 = videoTextureView.getMeasuredWidth() / (float) videoTextureView.getMeasuredHeight();
            if (Math.abs(scale1 - scale2) > 0.01f) {
                bitmapWidth = videoTextureView.getMeasuredWidth();
                bitmapHeight = videoTextureView.getMeasuredHeight();
            }
        }

        float scaleX = (float) getContainerViewWidth() / (float) bitmapWidth;
        float scaleY = (float) getContainerViewHeight() / (float) bitmapHeight;
        float scale = scaleX > scaleY ? scaleY : scaleX;
        int width = (int) (bitmapWidth * scale);
        int height = (int) (bitmapHeight * scale);

        if (!drawTextureView || !textureUploaded || !videoCrossfadeStarted || videoCrossfadeAlpha != 1.0f) {
            centerImage.setAlpha(alpha);
            centerImage.setImageCoords(-width / 2, -height / 2, width, height);
            centerImage.draw(canvas);
        }
        if (drawTextureView) {
            if (!videoCrossfadeStarted && textureUploaded) {
                videoCrossfadeStarted = true;
                videoCrossfadeAlpha = 0.0f;
                videoCrossfadeAlphaLastTime = System.currentTimeMillis();
            }
            canvas.translate(-width / 2, -height / 2);
            videoTextureView.setAlpha(alpha * videoCrossfadeAlpha);
            aspectRatioFrameLayout.draw(canvas);
            if (videoCrossfadeStarted && videoCrossfadeAlpha < 1.0f) {
                long newUpdateTime = System.currentTimeMillis();
                long dt = newUpdateTime - videoCrossfadeAlphaLastTime;
                videoCrossfadeAlphaLastTime = newUpdateTime;
                videoCrossfadeAlpha += dt / 300.0f;
                photoContainerView.invalidate();
                if (videoCrossfadeAlpha > 1.0f) {
                    videoCrossfadeAlpha = 1.0f;
                }
            }
        }
        canvas.restore();
    }
    if (!drawTextureView && bottomLayout.getVisibility() != View.VISIBLE) {
        canvas.save();
        canvas.translate(translateX, currentTranslationY / currentScale);
        radialProgressViews[0].setScale(1.0f - scaleDiff);
        radialProgressViews[0].setAlpha(alpha);
        radialProgressViews[0].onDraw(canvas);
        canvas.restore();
    }

    if (sideImage == leftImage) {
        if (sideImage.hasBitmapImage()) {
            canvas.save();
            canvas.translate(getContainerViewWidth() / 2, getContainerViewHeight() / 2);
            canvas.translate(
                    -(canvas.getWidth() * (scale + 1) + AndroidUtilities.dp(30)) / 2 + currentTranslationX, 0);
            int bitmapWidth = sideImage.getBitmapWidth();
            int bitmapHeight = sideImage.getBitmapHeight();

            float scaleX = (float) getContainerViewWidth() / (float) bitmapWidth;
            float scaleY = (float) getContainerViewHeight() / (float) bitmapHeight;
            float scale = scaleX > scaleY ? scaleY : scaleX;
            int width = (int) (bitmapWidth * scale);
            int height = (int) (bitmapHeight * scale);

            sideImage.setAlpha(1.0f);
            sideImage.setImageCoords(-width / 2, -height / 2, width, height);
            sideImage.draw(canvas);
            canvas.restore();
        }

        canvas.save();
        canvas.translate(currentTranslationX, currentTranslationY / currentScale);
        canvas.translate(-(canvas.getWidth() * (scale + 1) + AndroidUtilities.dp(30)) / 2,
                -currentTranslationY / currentScale);
        radialProgressViews[2].setScale(1.0f);
        radialProgressViews[2].setAlpha(1.0f);
        radialProgressViews[2].onDraw(canvas);
        canvas.restore();
    }
}

From source file:cn.ismartv.recyclerview.widget.RecyclerView.java

@Override
public void draw(Canvas c) {
    super.draw(c);

    final int count = mItemDecorations.size();
    for (int i = 0; i < count; i++) {
        mItemDecorations.get(i).onDrawOver(c, this, mState);
    }/*from   w  w w. j  a  va  2  s. c  om*/
    // TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
    // need find children closest to edges. Not sure if it is worth the effort.
    boolean needsInvalidate = false;
    if (mLeftGlow != null && !mLeftGlow.isFinished()) {
        final int restore = c.save();
        final int padding = mClipToPadding ? getPaddingBottom() : 0;
        c.rotate(270);
        c.translate(-getHeight() + padding, 0);
        needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mTopGlow != null && !mTopGlow.isFinished()) {
        final int restore = c.save();
        if (mClipToPadding) {
            c.translate(getPaddingLeft(), getPaddingTop());
        }
        needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mRightGlow != null && !mRightGlow.isFinished()) {
        final int restore = c.save();
        final int width = getWidth();
        final int padding = mClipToPadding ? getPaddingTop() : 0;
        c.rotate(90);
        c.translate(-padding, -width);
        needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mBottomGlow != null && !mBottomGlow.isFinished()) {
        final int restore = c.save();
        c.rotate(180);
        if (mClipToPadding) {
            c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
        } else {
            c.translate(-getWidth(), -getHeight());
        }
        needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
        c.restoreToCount(restore);
    }

    // If some views are animating, ItemDecorators are likely to move/change with them.
    // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
    // display lists are not invalidated.
    if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && mItemAnimator.isRunning()) {
        needsInvalidate = true;
    }

    if (needsInvalidate) {
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

From source file:com.b44t.messenger.support.widget.RecyclerView.java

@Override
public void draw(Canvas c) {
    super.draw(c);

    final int count = mItemDecorations.size();
    for (int i = 0; i < count; i++) {
        mItemDecorations.get(i).onDrawOver(c, this, mState);
    }/*from www .j a v  a 2 s  .com*/
    // TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
    // need find children closest to edges. Not sure if it is worth the effort.
    boolean needsInvalidate = false;
    if (mLeftGlow != null && !mLeftGlow.isFinished()) {
        final int restore = c.save();
        final int padding = mClipToPadding ? getPaddingBottom() : 0;
        c.rotate(270);
        c.translate(-getHeight() + padding, 0);
        needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mTopGlow != null && !mTopGlow.isFinished()) {
        final int restore = c.save();
        if (mClipToPadding) {
            c.translate(getPaddingLeft(), getPaddingTop());
        }
        c.translate(0, topGlowOffset);
        needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mRightGlow != null && !mRightGlow.isFinished()) {
        final int restore = c.save();
        final int width = getWidth();
        final int padding = mClipToPadding ? getPaddingTop() : 0;
        c.rotate(90);
        c.translate(-padding, -width);
        needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mBottomGlow != null && !mBottomGlow.isFinished()) {
        final int restore = c.save();
        c.rotate(180);
        if (mClipToPadding) {
            c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
        } else {
            c.translate(-getWidth(), -getHeight());
        }
        needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
        c.restoreToCount(restore);
    }

    // If some views are animating, ItemDecorators are likely to move/change with them.
    // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
    // display lists are not invalidated.
    if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && mItemAnimator.isRunning()) {
        needsInvalidate = true;
    }

    if (needsInvalidate) {
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

From source file:android.support.v71.widget.RecyclerView.java

@Override
public void draw(Canvas c) {
    super.draw(c);
    //  //from  www.j a v a2 s . c  om
    final int count = mItemDecorations.size();
    for (int i = 0; i < count; i++) {
        mItemDecorations.get(i).onDrawOver(c, this, mState);
    }
    // TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
    // need find children closest to edges. Not sure if it is worth the effort.
    boolean needsInvalidate = false;
    // ?   
    if (mLeftGlow != null && !mLeftGlow.isFinished()) {
        final int restore = c.save();
        final int padding = mClipToPadding ? getPaddingBottom() : 0;
        c.rotate(270);
        c.translate(-getHeight() + padding, 0);
        needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mTopGlow != null && !mTopGlow.isFinished()) {
        final int restore = c.save();
        if (mClipToPadding) {
            c.translate(getPaddingLeft(), getPaddingTop());
        }
        needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mRightGlow != null && !mRightGlow.isFinished()) {
        final int restore = c.save();
        final int width = getWidth();
        final int padding = mClipToPadding ? getPaddingTop() : 0;
        c.rotate(90);
        c.translate(-padding, -width);
        needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mBottomGlow != null && !mBottomGlow.isFinished()) {
        final int restore = c.save();
        c.rotate(180);
        if (mClipToPadding) {
            c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
        } else {
            c.translate(-getWidth(), -getHeight());
        }
        needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
        c.restoreToCount(restore);
    }

    // If some views are animating, ItemDecorators are likely to move/change with them.
    // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
    // display lists are not invalidated.
    //  VIew , Item   ??, ??  ?
    if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && mItemAnimator.isRunning()) {
        needsInvalidate = true;
    }

    if (needsInvalidate) {
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

From source file:cn.ismartv.tvrecyclerview.widget.RecyclerView.java

@Override
public void draw(Canvas c) {
    super.draw(c);

    final int count = mItemDecorations.size();
    for (int i = 0; i < count; i++) {
        mItemDecorations.get(i).onDrawOver(c, this, mState);
    }/*  w ww  . jav  a2  s  .  c om*/
    // TODO If padding is not 0 and clipChildrenToPadding is false, to draw glows properly, we
    // need find children closest to edges. Not sure if it is worth the effort.
    boolean needsInvalidate = false;
    if (mLeftGlow != null && !mLeftGlow.isFinished()) {
        final int restore = c.save();
        final int padding = mClipToPadding ? getPaddingBottom() : 0;
        c.rotate(270);
        c.translate(-getHeight() + padding, 0);
        needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mTopGlow != null && !mTopGlow.isFinished()) {
        final int restore = c.save();
        if (mClipToPadding) {
            c.translate(getPaddingLeft(), getPaddingTop());
        }
        needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mRightGlow != null && !mRightGlow.isFinished()) {
        final int restore = c.save();
        final int width = getWidth();
        final int padding = mClipToPadding ? getPaddingTop() : 0;
        c.rotate(90);
        c.translate(-padding, -width);
        needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mBottomGlow != null && !mBottomGlow.isFinished()) {
        final int restore = c.save();
        c.rotate(180);
        if (mClipToPadding) {
            c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
        } else {
            c.translate(-getWidth(), -getHeight());
        }
        needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
        c.restoreToCount(restore);
    }

    // If some views are animating, ItemDecorators are likely to move/change with them.
    // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
    // display lists are not invalidated.
    if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && mItemAnimator.isRunning()) {
        needsInvalidate = true;
    }

    if (needsInvalidate) {
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

From source file:com.ferdi2005.secondgram.support.widget.RecyclerView.java

@Override
public void draw(Canvas c) {
    super.draw(c);

    final int count = mItemDecorations.size();
    for (int i = 0; i < count; i++) {
        mItemDecorations.get(i).onDrawOver(c, this, mState);
    }/* w  w  w  . j ava 2s.  co m*/
    // TODO If padding is not 0 and clipChildrenToPadding is false, to draw glows properly, we
    // need find children closest to edges. Not sure if it is worth the effort.
    boolean needsInvalidate = false;
    if (mLeftGlow != null && !mLeftGlow.isFinished()) {
        final int restore = c.save();
        final int padding = mClipToPadding ? getPaddingBottom() : 0;
        c.rotate(270);
        c.translate(-getHeight() + padding, 0);
        needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mTopGlow != null && !mTopGlow.isFinished()) {
        final int restore = c.save();
        if (mClipToPadding) {
            c.translate(getPaddingLeft(), getPaddingTop());
        }
        c.translate(0, topGlowOffset);
        needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mRightGlow != null && !mRightGlow.isFinished()) {
        final int restore = c.save();
        final int width = getWidth();
        final int padding = mClipToPadding ? getPaddingTop() : 0;
        c.rotate(90);
        c.translate(-padding, -width);
        needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
        c.restoreToCount(restore);
    }
    if (mBottomGlow != null && !mBottomGlow.isFinished()) {
        final int restore = c.save();
        c.rotate(180);
        if (mClipToPadding) {
            c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
        } else {
            c.translate(-getWidth(), -getHeight());
        }
        needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
        c.restoreToCount(restore);
    }

    // If some views are animating, ItemDecorators are likely to move/change with them.
    // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
    // display lists are not invalidated.
    if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && mItemAnimator.isRunning()) {
        needsInvalidate = true;
    }

    if (needsInvalidate) {
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

From source file:org.telegram.ui.Components.AudioPlayerAlert.java

public AudioPlayerAlert(final Context context) {
    super(context, true);

    MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
    if (messageObject != null) {
        currentAccount = messageObject.currentAccount;
    } else {/*  w  ww  . j  a va2 s.  c om*/
        currentAccount = UserConfig.selectedAccount;
    }

    parentActivity = (LaunchActivity) context;
    noCoverDrawable = context.getResources().getDrawable(R.drawable.nocover).mutate();
    noCoverDrawable.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_player_placeholder), PorterDuff.Mode.MULTIPLY));

    TAG = DownloadController.getInstance(currentAccount).generateObserverTag();
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
    NotificationCenter.getInstance(currentAccount).addObserver(this,
            NotificationCenter.messagePlayingPlayStateChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
    NotificationCenter.getInstance(currentAccount).addObserver(this,
            NotificationCenter.messagePlayingProgressDidChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.musicDidLoad);

    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow).mutate();
    shadowDrawable.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_player_background), PorterDuff.Mode.MULTIPLY));
    paint.setColor(Theme.getColor(Theme.key_player_placeholderBackground));

    containerView = new FrameLayout(context) {

        private boolean ignoreLayout = false;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0 && ev.getY() < scrollOffsetY
                    && placeholderImageView.getTranslationX() == 0) {
                dismiss();
                return true;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            return !isDismissed() && super.onTouchEvent(e);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int contentSize = AndroidUtilities.dp(178) + playlist.size() * AndroidUtilities.dp(56)
                    + backgroundPaddingTop + ActionBar.getCurrentActionBarHeight()
                    + AndroidUtilities.statusBarHeight;
            int padding;
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            if (searching) {
                padding = AndroidUtilities.dp(178) + ActionBar.getCurrentActionBarHeight()
                        + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
            } else {
                if (contentSize < height) {
                    padding = height - contentSize;
                } else {
                    padding = (contentSize < height ? 0 : height - (height / 5 * 3));
                }
                padding += ActionBar.getCurrentActionBarHeight()
                        + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
            }
            if (listView.getPaddingTop() != padding) {
                ignoreLayout = true;
                listView.setPadding(0, padding, 0, AndroidUtilities.dp(8));
                ignoreLayout = false;
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            inFullSize = getMeasuredHeight() >= height;
            int availableHeight = height - ActionBar.getCurrentActionBarHeight()
                    - (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0)
                    - AndroidUtilities.dp(120);
            int maxSize = Math.max(availableHeight, getMeasuredWidth());
            thumbMaxX = (getMeasuredWidth() - maxSize) / 2 - AndroidUtilities.dp(17);
            thumbMaxY = AndroidUtilities.dp(19);
            panelEndTranslation = getMeasuredHeight() - playerLayout.getMeasuredHeight();
            thumbMaxScale = maxSize / (float) placeholderImageView.getMeasuredWidth() - 1.0f;

            endTranslation = ActionBar.getCurrentActionBarHeight() + AndroidUtilities.dp(5);
            int scaledHeight = (int) Math
                    .ceil(placeholderImageView.getMeasuredHeight() * (1.0f + thumbMaxScale));
            if (scaledHeight > availableHeight) {
                endTranslation -= (scaledHeight - availableHeight);
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            int y = actionBar.getMeasuredHeight();
            shadow.layout(shadow.getLeft(), y, shadow.getRight(), y + shadow.getMeasuredHeight());
            updateLayout();

            setFullAnimationProgress(fullAnimationProgress);
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            shadowDrawable.setBounds(0,
                    Math.max(actionBar.getMeasuredHeight(), scrollOffsetY) - backgroundPaddingTop,
                    getMeasuredWidth(), getMeasuredHeight());
            shadowDrawable.draw(canvas);
        }
    };
    containerView.setWillNotDraw(false);
    containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);

    actionBar = new ActionBar(context);
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_player_actionBar));
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setItemsColor(Theme.getColor(Theme.key_player_actionBarItems), false);
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_player_actionBarSelector), false);
    actionBar.setTitleColor(Theme.getColor(Theme.key_player_actionBarTitle));
    actionBar.setSubtitleColor(Theme.getColor(Theme.key_player_actionBarSubtitle));
    actionBar.setAlpha(0.0f);
    actionBar.setTitle("1");
    actionBar.setSubtitle("1");
    actionBar.getTitleTextView().setAlpha(0.0f);
    actionBar.getSubtitleTextView().setAlpha(0.0f);
    avatarContainer = new ChatAvatarContainer(context, null, false);
    avatarContainer.setEnabled(false);
    avatarContainer.setTitleColors(Theme.getColor(Theme.key_player_actionBarTitle),
            Theme.getColor(Theme.key_player_actionBarSubtitle));
    if (messageObject != null) {
        long did = messageObject.getDialogId();
        int lower_id = (int) did;
        int high_id = (int) (did >> 32);
        if (lower_id != 0) {
            if (lower_id > 0) {
                TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id);
                if (user != null) {
                    avatarContainer.setTitle(ContactsController.formatName(user.first_name, user.last_name));
                    avatarContainer.setUserAvatar(user);
                }
            } else {
                TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id);
                if (chat != null) {
                    avatarContainer.setTitle(chat.title);
                    avatarContainer.setChatAvatar(chat);
                }
            }
        } else {
            TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount)
                    .getEncryptedChat(high_id);
            if (encryptedChat != null) {
                TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id);
                if (user != null) {
                    avatarContainer.setTitle(ContactsController.formatName(user.first_name, user.last_name));
                    avatarContainer.setUserAvatar(user);
                }
            }
        }
    }
    avatarContainer.setSubtitle(LocaleController.getString("AudioTitle", R.string.AudioTitle));
    actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0));

    ActionBarMenu menu = actionBar.createMenu();
    menuItem = menu.addItem(0, R.drawable.ic_ab_other);
    menuItem.addSubItem(1, LocaleController.getString("Forward", R.string.Forward));
    menuItem.addSubItem(2, LocaleController.getString("ShareFile", R.string.ShareFile));
    //menuItem.addSubItem(3, LocaleController.getString("Delete", R.string.Delete));
    menuItem.addSubItem(4, LocaleController.getString("ShowInChat", R.string.ShowInChat));
    menuItem.setTranslationX(AndroidUtilities.dp(48));
    menuItem.setAlpha(0.0f);

    searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchCollapse() {
                    avatarContainer.setVisibility(View.VISIBLE);
                    if (hasOptions) {
                        menuItem.setVisibility(View.INVISIBLE);
                    }
                    if (searching) {
                        searchWas = false;
                        searching = false;
                        setAllowNestedScroll(true);
                        listAdapter.search(null);
                    }
                }

                @Override
                public void onSearchExpand() {
                    searchOpenPosition = layoutManager.findLastVisibleItemPosition();
                    View firstVisView = layoutManager.findViewByPosition(searchOpenPosition);
                    searchOpenOffset = ((firstVisView == null) ? 0 : firstVisView.getTop())
                            - listView.getPaddingTop();

                    avatarContainer.setVisibility(View.GONE);
                    if (hasOptions) {
                        menuItem.setVisibility(View.GONE);
                    }
                    searching = true;
                    setAllowNestedScroll(false);
                    listAdapter.notifyDataSetChanged();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    if (editText.length() > 0) {
                        listAdapter.search(editText.getText().toString());
                    } else {
                        searchWas = false;
                        listAdapter.search(null);
                    }
                }
            });
    EditTextBoldCursor editText = searchItem.getSearchField();
    editText.setHint(LocaleController.getString("Search", R.string.Search));
    editText.setTextColor(Theme.getColor(Theme.key_player_actionBarTitle));
    editText.setHintTextColor(Theme.getColor(Theme.key_player_time));
    editText.setCursorColor(Theme.getColor(Theme.key_player_actionBarTitle));

    if (!AndroidUtilities.isTablet()) {
        actionBar.showActionModeTop();
        actionBar.setActionModeTopColor(Theme.getColor(Theme.key_player_actionBarTop));
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                dismiss();
            } else {
                onSubItemClick(id);
            }
        }
    });

    shadow = new View(context);
    shadow.setAlpha(0.0f);
    shadow.setBackgroundResource(R.drawable.header_shadow);

    shadow2 = new View(context);
    shadow2.setAlpha(0.0f);
    shadow2.setBackgroundResource(R.drawable.header_shadow);

    playerLayout = new FrameLayout(context);
    playerLayout.setBackgroundColor(Theme.getColor(Theme.key_player_background));

    placeholderImageView = new BackupImageView(context) {

        private RectF rect = new RectF();

        @Override
        protected void onDraw(Canvas canvas) {
            if (hasNoCover == 1 || hasNoCover == 2
                    && (!getImageReceiver().hasBitmapImage() || getImageReceiver().getCurrentAlpha() != 1.0f)) {
                rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
                canvas.drawRoundRect(rect, getRoundRadius(), getRoundRadius(), paint);
                float plusScale = thumbMaxScale / getScaleX() / 3;
                int s = (int) (AndroidUtilities.dp(63)
                        * Math.max(plusScale / thumbMaxScale, 1.0f / thumbMaxScale));
                int x = (int) (rect.centerX() - s / 2);
                int y = (int) (rect.centerY() - s / 2);
                noCoverDrawable.setBounds(x, y, x + s, y + s);
                noCoverDrawable.draw(canvas);
            }
            if (hasNoCover != 1) {
                super.onDraw(canvas);
            }
        }
    };
    placeholderImageView.setRoundRadius(AndroidUtilities.dp(20));
    placeholderImageView.setPivotX(0);
    placeholderImageView.setPivotY(0);
    placeholderImageView.setOnClickListener(view -> {
        if (animatorSet != null) {
            animatorSet.cancel();
            animatorSet = null;
        }
        animatorSet = new AnimatorSet();
        if (scrollOffsetY <= actionBar.getMeasuredHeight()) {
            animatorSet.playTogether(ObjectAnimator.ofFloat(AudioPlayerAlert.this, "fullAnimationProgress",
                    isInFullMode ? 0.0f : 1.0f));
        } else {
            animatorSet.playTogether(
                    ObjectAnimator.ofFloat(AudioPlayerAlert.this, "fullAnimationProgress",
                            isInFullMode ? 0.0f : 1.0f),
                    ObjectAnimator.ofFloat(actionBar, "alpha", isInFullMode ? 0.0f : 1.0f),
                    ObjectAnimator.ofFloat(shadow, "alpha", isInFullMode ? 0.0f : 1.0f),
                    ObjectAnimator.ofFloat(shadow2, "alpha", isInFullMode ? 0.0f : 1.0f));
        }

        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.setDuration(250);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (animation.equals(animatorSet)) {
                    if (!isInFullMode) {
                        listView.setScrollEnabled(true);
                        if (hasOptions) {
                            menuItem.setVisibility(View.INVISIBLE);
                        }
                        searchItem.setVisibility(View.VISIBLE);
                    } else {
                        if (hasOptions) {
                            menuItem.setVisibility(View.VISIBLE);
                        }
                        searchItem.setVisibility(View.INVISIBLE);
                    }
                    animatorSet = null;
                }
            }
        });
        animatorSet.start();
        if (hasOptions) {
            menuItem.setVisibility(View.VISIBLE);
        }
        searchItem.setVisibility(View.VISIBLE);
        isInFullMode = !isInFullMode;
        listView.setScrollEnabled(false);
        if (isInFullMode) {
            shuffleButton.setAdditionalOffset(-AndroidUtilities.dp(20 + 48));
        } else {
            shuffleButton.setAdditionalOffset(-AndroidUtilities.dp(10));
        }
    });

    titleTextView = new TextView(context);
    titleTextView.setTextColor(Theme.getColor(Theme.key_player_actionBarTitle));
    titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    titleTextView.setEllipsize(TextUtils.TruncateAt.END);
    titleTextView.setSingleLine(true);
    playerLayout.addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 72, 18, 60, 0));

    authorTextView = new TextView(context);
    authorTextView.setTextColor(Theme.getColor(Theme.key_player_time));
    authorTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    authorTextView.setEllipsize(TextUtils.TruncateAt.END);
    authorTextView.setSingleLine(true);
    playerLayout.addView(authorTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 72, 40, 60, 0));

    optionsButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_player_actionBarItems));
    optionsButton.setLongClickEnabled(false);
    optionsButton.setIcon(R.drawable.ic_ab_other);
    optionsButton.setAdditionalOffset(-AndroidUtilities.dp(120));
    playerLayout.addView(optionsButton,
            LayoutHelper.createFrame(40, 40, Gravity.TOP | Gravity.RIGHT, 0, 19, 10, 0));
    optionsButton.addSubItem(1, LocaleController.getString("Forward", R.string.Forward));
    optionsButton.addSubItem(2, LocaleController.getString("ShareFile", R.string.ShareFile));
    //optionsButton.addSubItem(3, LocaleController.getString("Delete", R.string.Delete));
    optionsButton.addSubItem(4, LocaleController.getString("ShowInChat", R.string.ShowInChat));
    optionsButton.setOnClickListener(v -> optionsButton.toggleSubMenu());
    optionsButton.setDelegate(this::onSubItemClick);

    seekBarView = new SeekBarView(context);
    seekBarView.setDelegate(progress -> MediaController.getInstance()
            .seekToProgress(MediaController.getInstance().getPlayingMessageObject(), progress));
    playerLayout.addView(seekBarView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, Gravity.TOP | Gravity.LEFT, 8, 62, 8, 0));

    progressView = new LineProgressView(context);
    progressView.setVisibility(View.INVISIBLE);
    progressView.setBackgroundColor(Theme.getColor(Theme.key_player_progressBackground));
    progressView.setProgressColor(Theme.getColor(Theme.key_player_progress));
    playerLayout.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.TOP | Gravity.LEFT, 20, 78, 20, 0));

    timeTextView = new SimpleTextView(context);
    timeTextView.setTextSize(12);
    timeTextView.setText("0:00");
    timeTextView.setTextColor(Theme.getColor(Theme.key_player_time));
    playerLayout.addView(timeTextView,
            LayoutHelper.createFrame(100, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 92, 0, 0));

    durationTextView = new TextView(context);
    durationTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
    durationTextView.setTextColor(Theme.getColor(Theme.key_player_time));
    durationTextView.setGravity(Gravity.CENTER);
    playerLayout.addView(durationTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT, 0, 90, 20, 0));

    FrameLayout bottomView = new FrameLayout(context) {
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int dist = ((right - left) - AndroidUtilities.dp(8 + 48 * 5)) / 4;
            for (int a = 0; a < 5; a++) {
                int l = AndroidUtilities.dp(4 + 48 * a) + dist * a;
                int t = AndroidUtilities.dp(9);
                buttons[a].layout(l, t, l + buttons[a].getMeasuredWidth(), t + buttons[a].getMeasuredHeight());
            }
        }
    };
    playerLayout.addView(bottomView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 66, Gravity.TOP | Gravity.LEFT, 0, 106, 0, 0));

    buttons[0] = shuffleButton = new ActionBarMenuItem(context, null, 0, 0);
    shuffleButton.setLongClickEnabled(false);
    shuffleButton.setAdditionalOffset(-AndroidUtilities.dp(10));
    bottomView.addView(shuffleButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
    shuffleButton.setOnClickListener(v -> shuffleButton.toggleSubMenu());

    TextView textView = shuffleButton.addSubItem(1,
            LocaleController.getString("ReverseOrder", R.string.ReverseOrder));
    textView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(16), 0);
    playOrderButtons[0] = context.getResources().getDrawable(R.drawable.music_reverse).mutate();
    textView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    textView.setCompoundDrawablesWithIntrinsicBounds(playOrderButtons[0], null, null, null);

    textView = shuffleButton.addSubItem(2, LocaleController.getString("Shuffle", R.string.Shuffle));
    textView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(16), 0);
    playOrderButtons[1] = context.getResources().getDrawable(R.drawable.pl_shuffle).mutate();
    textView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    textView.setCompoundDrawablesWithIntrinsicBounds(playOrderButtons[1], null, null, null);

    shuffleButton.setDelegate(id -> {
        MediaController.getInstance().toggleShuffleMusic(id);
        updateShuffleButton();
        listAdapter.notifyDataSetChanged();
    });

    ImageView prevButton;
    buttons[1] = prevButton = new ImageView(context);
    prevButton.setScaleType(ImageView.ScaleType.CENTER);
    prevButton.setImageDrawable(Theme.createSimpleSelectorDrawable(context, R.drawable.pl_previous,
            Theme.getColor(Theme.key_player_button), Theme.getColor(Theme.key_player_buttonActive)));
    bottomView.addView(prevButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
    prevButton.setOnClickListener(v -> MediaController.getInstance().playPreviousMessage());

    buttons[2] = playButton = new ImageView(context);
    playButton.setScaleType(ImageView.ScaleType.CENTER);
    playButton.setImageDrawable(Theme.createSimpleSelectorDrawable(context, R.drawable.pl_play,
            Theme.getColor(Theme.key_player_button), Theme.getColor(Theme.key_player_buttonActive)));
    bottomView.addView(playButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
    playButton.setOnClickListener(v -> {
        if (MediaController.getInstance().isDownloadingCurrentMessage()) {
            return;
        }
        if (MediaController.getInstance().isMessagePaused()) {
            MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject());
        } else {
            MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject());
        }
    });

    ImageView nextButton;
    buttons[3] = nextButton = new ImageView(context);
    nextButton.setScaleType(ImageView.ScaleType.CENTER);
    nextButton.setImageDrawable(Theme.createSimpleSelectorDrawable(context, R.drawable.pl_next,
            Theme.getColor(Theme.key_player_button), Theme.getColor(Theme.key_player_buttonActive)));
    bottomView.addView(nextButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
    nextButton.setOnClickListener(v -> MediaController.getInstance().playNextMessage());

    buttons[4] = repeatButton = new ImageView(context);
    repeatButton.setScaleType(ImageView.ScaleType.CENTER);
    repeatButton.setPadding(0, 0, AndroidUtilities.dp(8), 0);
    bottomView.addView(repeatButton, LayoutHelper.createFrame(50, 48, Gravity.LEFT | Gravity.TOP));
    repeatButton.setOnClickListener(v -> {
        SharedConfig.toggleRepeatMode();
        updateRepeatButton();
    });

    listView = new RecyclerListView(context) {

        boolean ignoreLayout;

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);

            if (searchOpenPosition != -1 && !actionBar.isSearchFieldVisible()) {
                ignoreLayout = true;
                layoutManager.scrollToPositionWithOffset(searchOpenPosition, searchOpenOffset);
                super.onLayout(false, l, t, r, b);
                ignoreLayout = false;
                searchOpenPosition = -1;
            } else if (scrollToSong) {
                scrollToSong = false;
                boolean found = false;
                MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
                if (playingMessageObject != null) {
                    int count = listView.getChildCount();
                    for (int a = 0; a < count; a++) {
                        View child = listView.getChildAt(a);
                        if (child instanceof AudioPlayerCell) {
                            if (((AudioPlayerCell) child).getMessageObject() == playingMessageObject) {
                                if (child.getBottom() <= getMeasuredHeight()) {
                                    found = true;
                                }
                                break;
                            }
                        }
                    }
                    if (!found) {
                        int idx = playlist.indexOf(playingMessageObject);
                        if (idx >= 0) {
                            ignoreLayout = true;
                            if (SharedConfig.playOrderReversed) {
                                layoutManager.scrollToPosition(idx);
                            } else {
                                layoutManager.scrollToPosition(playlist.size() - idx);
                            }
                            super.onLayout(false, l, t, r, b);
                            ignoreLayout = false;
                        }
                    }
                }
            }
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        protected boolean allowSelectChildAtPosition(float x, float y) {
            float p = playerLayout.getY() + playerLayout.getMeasuredHeight();
            return playerLayout == null || y > playerLayout.getY() + playerLayout.getMeasuredHeight();
        }

        @Override
        public boolean drawChild(Canvas canvas, View child, long drawingTime) {
            canvas.save();
            canvas.clipRect(0,
                    (actionBar != null ? actionBar.getMeasuredHeight() : 0) + AndroidUtilities.dp(50),
                    getMeasuredWidth(), getMeasuredHeight());
            boolean result = super.drawChild(canvas, child, drawingTime);
            canvas.restore();
            return result;
        }
    };
    listView.setPadding(0, 0, 0, AndroidUtilities.dp(8));
    listView.setClipToPadding(false);
    listView.setLayoutManager(
            layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
    listView.setHorizontalScrollBarEnabled(false);
    listView.setVerticalScrollBarEnabled(false);
    containerView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    listView.setAdapter(listAdapter = new ListAdapter(context));
    listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow));
    listView.setOnItemClickListener((view, position) -> {
        if (view instanceof AudioPlayerCell) {
            ((AudioPlayerCell) view).didPressedButton();
        }
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && searching && searchWas) {
                AndroidUtilities.hideKeyboard(getCurrentFocus());
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            updateLayout();
        }
    });

    playlist = MediaController.getInstance().getPlaylist();
    listAdapter.notifyDataSetChanged();

    containerView.addView(playerLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 178));
    containerView.addView(shadow2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));
    containerView.addView(placeholderImageView,
            LayoutHelper.createFrame(40, 40, Gravity.TOP | Gravity.LEFT, 17, 19, 0, 0));
    containerView.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));
    containerView.addView(actionBar);

    updateTitle(false);
    updateRepeatButton();
    updateShuffleButton();
}

From source file:com.cssweb.android.view.TrendView.java

private void drawChart(Canvas canvas) throws JSONException {
    Log.i("@@@@@@@@@draw tick@@@@@@@@@@", quoteArray + ">>>>>>>>>");
    //Log.i("@@@@@@@@@@@@@@@@@@@", quoteArray.length()+">>>>>>>>>");
    if (quoteArray == null || quoteArray.isNull(0))
        return;//from   w  w w.j  a  v  a2  s  . c  om

    canvas.drawColor(GlobalColor.clearSCREEN);

    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(1);

    mpaint = new Paint();
    mpaint.setTypeface(Typeface.DEFAULT_BOLD);
    mpaint.setAntiAlias(true);
    mpaint.setTextAlign(Paint.Align.LEFT);
    mpaint.setStyle(Paint.Style.STROKE);
    mpaint.setTextSize(dTextSize);

    /**
     * ?
     */
    closeLeft = Utils.dataFormation(high, stockdigit);
    closeRight = "00.00%";
    LSpace = (int) (Math.max(mpaint.measureText(closeLeft),
            mpaint.measureText(String.valueOf(Math.round(highvolume)))));
    //???
    //RSpace = (int)(paint.measureText(closeRight) + 10);
    RSpace = 0;

    axisLabelHeight = Font.getFontHeight(dTextSize);

    graphicsQuoteWidth = width - LSpace - RSpace;
    SPACE = graphicsQuoteWidth / MINUTES;
    topTitleHeight = axisLabelHeight;
    graphicsQuoteHeight = height - axisLabelHeight - topTitleHeight;
    price_row_num = 2;//(int)graphicsQuoteHeight/3/25;
    volume_row_num = price_row_num;
    price_row_height = graphicsQuoteHeight / price_row_num / 3;
    volume_row_height = price_row_height;

    calc_zf();

    title1 = ":";
    title7 = ":";
    title8 = quoteArray.getJSONArray(isTrackNumber).getString(3);
    title2 = Utils.dataFormation(quoteArray.getJSONArray(isTrackNumber).getDouble(0), stockdigit);

    mpaint.setColor(GlobalColor.colorLabelName);

    canvas.drawText(title7 + title8.substring(11, 16), LSpace, axisLabelHeight - 5, mpaint);
    canvas.drawText(title1, LSpace + mpaint.measureText(":00:0000"), axisLabelHeight - 5, mpaint);
    if (quoteArray.getJSONArray(isTrackNumber).getDouble(0) == 0) {
        mpaint.setColor(GlobalColor.colorPriceEqual);
    } else if (quoteArray.getJSONArray(isTrackNumber).getDouble(0) > close) {
        mpaint.setColor(GlobalColor.colorpriceUp);
    } else if (quoteArray.getJSONArray(isTrackNumber).getDouble(0) < close) {
        mpaint.setColor(GlobalColor.colorPriceDown);
    } else {
        mpaint.setColor(GlobalColor.colorPriceEqual);
    }
    canvas.drawText(title2, LSpace + mpaint.measureText(":00:0000:"), axisLabelHeight - 5, mpaint);

    if (!this.isZs()) {
        if ("cf".equals(exchange) || "dc".equals(exchange) || "sf".equals(exchange) || "cz".equals(exchange)
                || "hk".equals(exchange)) {
        } else {
            mpaint.setColor(GlobalColor.colorLabelName);
            title9 = "?:";
            canvas.drawText(title9, LSpace + mpaint.measureText(":00:000000:" + title2),
                    axisLabelHeight - 5, mpaint);
            double avePrice = 0;
            double cjje = quoteArray.getJSONArray(isTrackNumber).getDouble(2);
            int scaleCount = 1;
            scaleCount = Utils.getCoefficient(exchange, stockcode);
            double cjsl = quoteArray.getJSONArray(isTrackNumber).getDouble(1) * scaleCount;
            if (cjsl > 0) {
                avePrice = cjje / cjsl;
            } else {
                avePrice = jrkp;
            }
            if (avePrice == 0) {
                mpaint.setColor(GlobalColor.colorPriceEqual);
            } else if (avePrice > close) {
                mpaint.setColor(GlobalColor.colorpriceUp);
            } else if (avePrice < close) {
                mpaint.setColor(GlobalColor.colorPriceDown);
            } else {
                mpaint.setColor(GlobalColor.colorPriceEqual);
            }
            canvas.drawText(Utils.dataFormation(avePrice, stockdigit),
                    LSpace + mpaint.measureText(":00:000000:" + title2 + "?:"),
                    axisLabelHeight - 5, mpaint);
        }
    }

    if (isZs()) {
        if (close == 0)
            close = 1000;
    } else {
        if (close == 0)
            close = 1;
    }

    low = Math.min(low, close);
    //upPrice = close * (1+max_zf);
    //downPrice = close * (1-max_zf);

    paint.setColor(GlobalColor.clrLine);
    canvas.drawLine(LSpace + graphicsQuoteWidth, topTitleHeight, LSpace + graphicsQuoteWidth,
            graphicsQuoteHeight + topTitleHeight, paint);

    // 
    upQuoteX = LSpace;
    upQuoteY = topTitleHeight;
    upQuoteWidth = (int) graphicsQuoteWidth;
    upQuoteHeight = price_row_num * price_row_height;
    for (int i = 0; i < price_row_num; i++) {
        if (i == 0) {
            canvas.drawLine(upQuoteX, upQuoteY + price_row_height * i, upQuoteX + upQuoteWidth,
                    upQuoteY + price_row_height * i, paint);
        } else
            Graphics.drawDashline(canvas, upQuoteX, upQuoteY + price_row_height * i, upQuoteX + upQuoteWidth,
                    upQuoteY + price_row_height * i, paint);
    }

    for (int i = 0; i < DIVIDE_COUNT; i++) {
        if (i == 0) {
            canvas.drawLine(upQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, upQuoteY,
                    upQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, upQuoteY + upQuoteHeight, paint);
        } else
            Graphics.drawDashline(canvas, upQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, upQuoteY,
                    upQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, upQuoteY + upQuoteHeight, paint);
    }
    //scale = close * max_zf / price_row_num;
    scale = Arith.div(close * max_zf, price_row_num, stockdigit + 1);

    mpaint.setTextAlign(Paint.Align.RIGHT);
    mpaint.setColor(GlobalColor.colorPriceEqual);
    canvas.drawText(Utils.dataFormation(close, stockdigit), upQuoteX,
            upQuoteY + upQuoteHeight + axisLabelHeight / 2, mpaint);

    mpaint.setColor(GlobalColor.colorpriceUp);
    for (int i = 1; i <= price_row_num; i++) {
        AxisLabelPrice = close + scale * i;
        canvas.drawText(Utils.dataFormation(AxisLabelPrice, stockdigit), upQuoteX,
                upQuoteY + upQuoteHeight - price_row_height * i + axisLabelHeight / 2, mpaint);
    }

    // 
    downQuoteX = LSpace;
    downQuoteY = topTitleHeight + upQuoteHeight;
    downQuoteWidth = (int) graphicsQuoteWidth;

    downQuoteHeight = upQuoteHeight;

    paint.setColor(GlobalColor.clrLine);
    for (int i = 0; i < price_row_num; i++) {
        if (i == 0) {
            canvas.drawLine(downQuoteX, downQuoteY + price_row_height * i, downQuoteX + downQuoteWidth,
                    downQuoteY + price_row_height * i, paint);
        } else
            Graphics.drawDashline(canvas, downQuoteX, downQuoteY + price_row_height * i,
                    downQuoteX + downQuoteWidth, downQuoteY + price_row_height * i, paint);
    }

    for (int i = 0; i < DIVIDE_COUNT; i++) {
        if (i == 0) {
            canvas.drawLine(downQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, downQuoteY,
                    downQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, downQuoteY + downQuoteHeight + 1, paint);
        } else
            Graphics.drawDashline(canvas, downQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, downQuoteY,
                    downQuoteX + MINUTES / DIVIDE_COUNT * SPACE * i, downQuoteY + downQuoteHeight, paint);
    }

    mpaint.setColor(GlobalColor.colorPriceDown);
    for (int i = 1; i < price_row_num; i++) {
        AxisLabelPrice = close - scale * i;
        canvas.drawText(Utils.dataFormation(AxisLabelPrice, stockdigit), upQuoteX,
                upQuoteY + upQuoteHeight + price_row_height * i + axisLabelHeight / 2, mpaint);
    }

    //  
    // added by hujun for 20110511???
    if (actualDataLen > 0 && !this.isOpenFund()) {
        if ("cf".equals(exchange) || "dc".equals(exchange) || "sf".equals(exchange) || "cz".equals(exchange)) {
            scale = upQuoteHeight / (close * max_zf);
            paint.setColor(GlobalColor.colorFZLine);
            int quotelen = quoteArray.length();
            double x1 = 0;
            double y1 = 0;
            double x2 = 0;
            double y2 = 0;
            double temp = 0;

            x1 = upQuoteX;
            double lastnewp = 0;
            double nownewp = 0;
            nownewp = quoteArray.getJSONArray(0).getDouble(0);
            if (nownewp == 0)
                nownewp = close;
            if (nownewp >= close) {
                temp = (nownewp - close) * scale;
                y1 = topTitleHeight + upQuoteHeight - temp;
            } else {
                temp = (close - nownewp) * scale;
                y1 = topTitleHeight + upQuoteHeight + temp;
            }
            lastnewp = nownewp;
            for (int i = 1; i < quotelen; i++) {
                x2 = upQuoteX + SPACE * i;
                nownewp = quoteArray.getJSONArray(i).getDouble(0);
                if (nownewp == 0)
                    nownewp = lastnewp;
                if (nownewp >= close) {
                    temp = (nownewp - close) * scale;
                    y2 = topTitleHeight + upQuoteHeight - temp;
                } else {
                    temp = (close - nownewp) * scale;
                    y2 = topTitleHeight + upQuoteHeight + temp;
                }
                lastnewp = nownewp;

                canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                x1 = x2;
                y1 = y2;
            } // end for

            paint.setColor(GlobalColor.colorFZAvePriceLine);
            x1 = upQuoteX;
            double cjje = quoteArray.getJSONArray(0).getDouble(0);
            double avePrice = cjje;
            double lastavg = 0;
            if (avePrice > high) {
                avePrice = high;
            }
            if (avePrice < low) {
                avePrice = low;
            }
            if (avePrice >= close) {
                temp = (avePrice - close) * scale;
                y1 = topTitleHeight + upQuoteHeight - temp;
            } else {
                temp = (close - avePrice) * scale;
                y1 = topTitleHeight + upQuoteHeight + temp;
            }
            lastavg = avePrice;
            double xl = quoteArray.getJSONArray(0).getDouble(1);
            double mathpjj = quoteArray.getJSONArray(0).getDouble(0) * xl;
            for (int i = 1; i < quotelen; i++) {
                x2 = upQuoteX + SPACE * i;
                mathpjj += quoteArray.getJSONArray(i).getDouble(0) * (quoteArray.getJSONArray(i).getDouble(1)
                        - quoteArray.getJSONArray(i - 1).getDouble(1));
                if (mathpjj == 0) {
                    if (lastavg == 0) {
                        avePrice = close;
                    } else {
                        avePrice = lastavg;
                    }
                } else {
                    avePrice = mathpjj / quoteArray.getJSONArray(i).getDouble(1);
                }
                lastavg = avePrice;
                if (avePrice > high) {
                    avePrice = high;
                }
                if (avePrice < low) {
                    avePrice = low;
                }
                if (avePrice >= close) {
                    temp = (avePrice - close) * scale;
                    y2 = topTitleHeight + upQuoteHeight - temp;
                } else {
                    temp = (close - avePrice) * scale;
                    y2 = topTitleHeight + upQuoteHeight + temp;
                }
                canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                x1 = x2;
                y1 = y2;
            } // end for
        } else {
            scale = upQuoteHeight / (close * max_zf);
            paint.setColor(GlobalColor.colorFZLine);
            int quotelen = quoteArray.length();
            double x1 = 0;
            double y1 = 0;
            double x2 = 0;
            double y2 = 0;
            double temp = 0;

            x1 = upQuoteX;
            double lastnewp = 0;
            double nownewp = 0;
            nownewp = quoteArray.getJSONArray(0).getDouble(0);
            if (nownewp == 0)
                nownewp = close;
            if (nownewp >= close) {
                temp = (nownewp - close) * scale;
                y1 = topTitleHeight + upQuoteHeight - temp;
            } else {
                temp = (close - nownewp) * scale;
                y1 = topTitleHeight + upQuoteHeight + temp;
            }
            lastnewp = nownewp;
            for (int i = 1; i < quotelen; i++) {
                x2 = upQuoteX + SPACE * i;
                nownewp = quoteArray.getJSONArray(i).getDouble(0);
                if (nownewp == 0)
                    nownewp = lastnewp;
                if (nownewp >= close) {
                    temp = (nownewp - close) * scale;
                    y2 = topTitleHeight + upQuoteHeight - temp;
                } else {
                    temp = (close - nownewp) * scale;
                    y2 = topTitleHeight + upQuoteHeight + temp;
                }
                lastnewp = nownewp;

                canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                x1 = x2;
                y1 = y2;
            } // end for

            if (this.isZs()) {
                // ?   ??
                if ("sz".equals(exchange) || "sh".equals(exchange)) {
                    if (("000001".equals(stockcode) || "399001".equals(stockcode))
                            && !quoteData.isNull("data2")) {
                        paint.setColor(GlobalColor.colorFZAvePriceLine);
                        x1 = upQuoteX;
                        double avePrice = quoteData.getJSONArray("data2").getJSONArray(0).getDouble(0);
                        if (avePrice > high) {
                            avePrice = high;
                        }
                        if (avePrice < low) {
                            avePrice = low;
                        }
                        if (avePrice >= close) {
                            temp = (avePrice - close) * scale;
                            y1 = topTitleHeight + upQuoteHeight - temp;
                        } else {
                            temp = (close - avePrice) * scale;
                            y1 = topTitleHeight + upQuoteHeight + temp;
                        }
                        int len = quoteData.getJSONArray("data2").length();
                        for (int i = 1; i < len; i++) {
                            if ("15:00".equals(quoteData.getJSONArray("data2").getJSONArray(i).getString(1)
                                    .substring(11, 16))) {

                            } else {
                                x2 = upQuoteX + SPACE * i;
                                avePrice = quoteData.getJSONArray("data2").getJSONArray(i).getDouble(0);
                                if (avePrice > high) {
                                    avePrice = high;
                                }
                                if (avePrice < low) {
                                    avePrice = low;
                                }
                                if (avePrice >= close) {
                                    temp = (avePrice - close) * scale;
                                    y2 = topTitleHeight + upQuoteHeight - temp;
                                } else {
                                    temp = (close - avePrice) * scale;
                                    y2 = topTitleHeight + upQuoteHeight + temp;
                                }
                                canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                                x1 = x2;
                                y1 = y2;
                            }
                        } // end for
                    } else {
                        paint.setColor(GlobalColor.colorFZAvePriceLine);
                        x1 = upQuoteX;
                        double cjje = quoteArray.getJSONArray(0).getDouble(0);
                        double avePrice = cjje;
                        double lastavg = 0;
                        if (avePrice > high) {
                            avePrice = high;
                        }
                        if (avePrice < low) {
                            avePrice = low;
                        }
                        if (avePrice >= close) {
                            temp = (avePrice - close) * scale;
                            y1 = topTitleHeight + upQuoteHeight - temp;
                        } else {
                            temp = (close - avePrice) * scale;
                            y1 = topTitleHeight + upQuoteHeight + temp;
                        }
                        lastavg = avePrice;
                        double xl = quoteArray.getJSONArray(0).getDouble(1);
                        double mathpjj = quoteArray.getJSONArray(0).getDouble(0) * xl;
                        for (int i = 1; i < quotelen; i++) {
                            x2 = upQuoteX + SPACE * i;
                            mathpjj += quoteArray.getJSONArray(i).getDouble(0)
                                    * (quoteArray.getJSONArray(i).getDouble(1)
                                            - quoteArray.getJSONArray(i - 1).getDouble(1));
                            if (mathpjj == 0) {
                                if (lastavg == 0) {
                                    avePrice = close;
                                } else {
                                    avePrice = lastavg;
                                }
                            } else {
                                avePrice = mathpjj / quoteArray.getJSONArray(i).getDouble(1);
                            }
                            lastavg = avePrice;
                            if (avePrice > high) {
                                avePrice = high;
                            }
                            if (avePrice < low) {
                                avePrice = low;
                            }
                            if (avePrice >= close) {
                                temp = (avePrice - close) * scale;
                                y2 = topTitleHeight + upQuoteHeight - temp;
                            } else {
                                temp = (close - avePrice) * scale;
                                y2 = topTitleHeight + upQuoteHeight + temp;
                            }
                            canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                            x1 = x2;
                            y1 = y2;
                        } // end for
                    }
                }
            } else {
                paint.setColor(GlobalColor.colorFZAvePriceLine);
                x1 = upQuoteX;
                double cjje = quoteArray.getJSONArray(0).getDouble(2);
                int scaleCount = 1;
                scaleCount = Utils.getCoefficient(exchange, stockcode);
                double cjsl = quoteArray.getJSONArray(0).getDouble(1) * scaleCount;
                double avePrice = cjje / cjsl;
                double lastavg = 0;
                if (cjsl == 0)
                    avePrice = close;
                if (avePrice > high) {
                    avePrice = high;
                }
                if (avePrice < low) {
                    avePrice = low;
                }
                if (avePrice >= close) {
                    temp = (avePrice - close) * scale;
                    y1 = topTitleHeight + upQuoteHeight - temp;
                } else {
                    temp = (close - avePrice) * scale;
                    y1 = topTitleHeight + upQuoteHeight + temp;
                }
                lastavg = avePrice;
                for (int i = 1; i < quotelen; i++) {
                    x2 = upQuoteX + SPACE * i;
                    cjje = quoteArray.getJSONArray(i).getDouble(2);
                    cjsl = quoteArray.getJSONArray(i).getDouble(1) * scaleCount; // ?
                    if (cjsl == 0) {
                        if (lastavg == 0) {
                            avePrice = close;
                        } else {
                            avePrice = lastavg;
                        }
                    } else {
                        avePrice = cjje / cjsl;
                    }
                    lastavg = avePrice;
                    if (avePrice > high) {
                        avePrice = high;
                    }
                    if (avePrice < low) {
                        avePrice = low;
                    }
                    if (avePrice >= close) {
                        temp = (avePrice - close) * scale;
                        y2 = topTitleHeight + upQuoteHeight - temp;
                    } else {
                        temp = (close - avePrice) * scale;
                        y2 = topTitleHeight + upQuoteHeight + temp;
                    }
                    canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);

                    x1 = x2;
                    y1 = y2;
                } // end for
            }
        }
    }

    // ??
    volumeX = LSpace;
    volumeY = topTitleHeight + upQuoteHeight + downQuoteHeight;
    volumeWidth = (int) graphicsQuoteWidth;
    volumeHeight = graphicsQuoteHeight - upQuoteHeight - downQuoteHeight;

    volume_row_height = volumeHeight / volume_row_num;

    paint.setColor(GlobalColor.clrLine);
    for (int i = 0; i <= volume_row_num; i++) {
        if (i == 0) {
            canvas.drawLine(volumeX, volumeY + volume_row_height * i, volumeX + volumeWidth,
                    volumeY + volume_row_height * i, paint);
        } else {
            if (i != volume_row_num)
                Graphics.drawDashline(canvas, volumeX, volumeY + volume_row_height * i, volumeX + volumeWidth,
                        volumeY + volume_row_height * i, paint);
        }
    }

    for (int i = 0; i < DIVIDE_COUNT; i++) {
        if (i == 0) {
            canvas.drawLine(volumeX + MINUTES / DIVIDE_COUNT * SPACE * i, volumeY,
                    volumeX + MINUTES / DIVIDE_COUNT * SPACE * i, volumeY + volumeHeight, paint);
        } else
            Graphics.drawDashline(canvas, volumeX + MINUTES / DIVIDE_COUNT * SPACE * i, volumeY,
                    volumeX + MINUTES / DIVIDE_COUNT * SPACE * i, volumeY + volumeHeight, paint);
    }

    if (this.isZs()) {
        //highVolume =  TickUtil.gethighAmount(quoteData.getJSONArray("data"));
        highVolume = highamount;
    } else {
        //highVolume =  TickUtil.gethighVolume(quoteData.getJSONArray("data"));
        highVolume = highvolume;
    }

    if (highVolume == 0) {
        if (this.isZs()) {
            // ?
            highVolume = volume_row_num * 4 * 100; // ???48highVolume=32
        } else {
            highVolume = volume_row_num * 4 * 100; // ???48highVolume=32
        }
    }
    if (highVolume < volume_row_num + 1)
        highVolume = volume_row_num + 1;
    scale = highVolume / volume_row_num;
    int volumeLabelY = volumeY + Font.getFontHeight(dTextSize) / 2;

    mpaint.setColor(GlobalColor.clr_tick_volume);
    for (int i = 0; i <= volume_row_num; i++) {
        if (i != volume_row_num) {
            AxisLabelVolume = highVolume - scale * i;
            if (this.isZs())
                AxisLabelVolume = Math.round(AxisLabelVolume / 10000);
            else
                AxisLabelVolume = Math.round(AxisLabelVolume);

            canvas.drawText(String.valueOf((int) AxisLabelVolume), upQuoteX,
                    volumeLabelY + volume_row_height * i, mpaint);
        }
    }

    // ??
    if (actualDataLen > 0) {
        scale = volumeHeight / highVolume;
        paint.setColor(GlobalColor.colorVolumeLine);
        double prevVol = 0;
        double temp = 0;
        for (int i = 0; i < actualDataLen; i++) {
            if (this.isZs())
                temp = (quoteArray.getJSONArray(i).getDouble(2) - prevVol) * scale;
            else
                temp = (quoteArray.getJSONArray(i).getDouble(1) - prevVol) * scale;
            float x1 = volumeX + SPACE * i;
            float y1 = (float) (volumeY + volumeHeight - temp);

            float x2 = x1;
            float y2 = volumeY + volumeHeight;
            canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2, paint);
            if (this.isZs())
                prevVol = quoteArray.getJSONArray(i).getDouble(2);
            else
                prevVol = quoteArray.getJSONArray(i).getDouble(1);
        }
    }

    drawTimeX(canvas);

    // 
    paint.setColor(GlobalColor.clrLine);
    canvas.drawLine(LSpace, graphicsQuoteHeight + topTitleHeight, LSpace + graphicsQuoteWidth,
            graphicsQuoteHeight + topTitleHeight, paint);

    if (isTrackStatus) {
        canvas.save();
        //??
        paint.setColor(GlobalColor.colorLine);
        canvas.drawLine(trackLineV, topTitleHeight, trackLineV, graphicsQuoteHeight + topTitleHeight, paint);
        canvas.restore();
    }
}

From source file:net.bluehack.ui.PhotoViewer.java

public void setParentActivity(final Activity activity) {
    if (parentActivity == activity) {
        return;/*from w  w w.  j  av a 2 s.co  m*/
    }
    parentActivity = activity;
    actvityContext = new ContextThemeWrapper(parentActivity, R.style.Theme_TMessages);

    if (progressDrawables == null) {
        progressDrawables = new Drawable[4];
        progressDrawables[0] = parentActivity.getResources().getDrawable(R.drawable.circle_big);
        progressDrawables[1] = parentActivity.getResources().getDrawable(R.drawable.cancel_big);
        progressDrawables[2] = parentActivity.getResources().getDrawable(R.drawable.load_big);
        progressDrawables[3] = parentActivity.getResources().getDrawable(R.drawable.play_big);
    }

    scroller = new Scroller(activity);

    windowView = new FrameLayout(activity) {

        private Runnable attachRunnable;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return isVisible && super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return isVisible && PhotoViewer.this.onTouchEvent(event);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (Build.VERSION.SDK_INT >= 21 && child == animatingImageView && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(),
                        getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                if (AndroidUtilities.incorrectDisplaySizeFix) {
                    if (heightSize > AndroidUtilities.displaySize.y) {
                        heightSize = AndroidUtilities.displaySize.y;
                    }
                    heightSize += AndroidUtilities.statusBarHeight;
                }
                heightSize -= insets.getSystemWindowInsetBottom();
                widthSize -= insets.getSystemWindowInsetRight();
            } else {
                if (heightSize > AndroidUtilities.displaySize.y) {
                    heightSize = AndroidUtilities.displaySize.y;
                }
            }
            setMeasuredDimension(widthSize, heightSize);
            ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams();
            animatingImageView.measure(MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.AT_MOST));
            containerView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
        }

        @SuppressWarnings("DrawAllocation")
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            animatingImageView.layout(0, 0, animatingImageView.getMeasuredWidth(),
                    animatingImageView.getMeasuredHeight());
            containerView.layout(0, 0, containerView.getMeasuredWidth(), containerView.getMeasuredHeight());
            wasLayout = true;
            if (changed) {
                if (!dontResetZoomOnFirstLayout) {
                    scale = 1;
                    translationX = 0;
                    translationY = 0;
                    updateMinMax(scale);
                }

                if (checkImageView != null) {
                    checkImageView.post(new Runnable() {
                        @Override
                        public void run() {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) checkImageView
                                    .getLayoutParams();
                            WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
                                    .getSystemService(Activity.WINDOW_SERVICE);
                            int rotation = manager.getDefaultDisplay().getRotation();
                            layoutParams.topMargin = AndroidUtilities
                                    .dp(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58
                                            : 68)
                                    + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
                            checkImageView.setLayoutParams(layoutParams);
                        }
                    });
                }
            }
            if (dontResetZoomOnFirstLayout) {
                setScaleToFill();
                dontResetZoomOnFirstLayout = false;
            }
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            attachedToWindow = true;
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            attachedToWindow = false;
            wasLayout = false;
        }

        @Override
        public boolean dispatchKeyEventPreIme(KeyEvent event) {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible()) {
                    closeCaptionEnter(false);
                    return false;
                }
                PhotoViewer.getInstance().closePhoto(true, false);
                return true;
            }
            return super.dispatchKeyEventPreIme(event);
        }

        @Override
        public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) {
            if (Build.VERSION.SDK_INT >= 23) {
                View view = parentActivity.findViewById(android.R.id.content);
                if (view instanceof ViewGroup) {
                    try {
                        return ((ViewGroup) view).startActionModeForChild(originalView, callback, type);
                    } catch (Throwable e) {
                        FileLog.e("tmessages", e);
                    }
                }
            }
            return super.startActionModeForChild(originalView, callback, type);
        }
    };
    windowView.setBackgroundDrawable(backgroundDrawable);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);

    animatingImageView = new ClippingImageView(activity);
    animatingImageView.setAnimationValues(animationValues);
    windowView.addView(animatingImageView, LayoutHelper.createFrame(40, 40));

    containerView = new FrameLayoutDrawer(activity);
    containerView.setFocusable(false);
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    if (Build.VERSION.SDK_INT >= 21) {
        //containerView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @SuppressLint("NewApi")
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                lastInsets = insets;
                windowView.requestLayout();
                return insets.consumeSystemWindowInsets();
            }
        });
        //containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
    }

    windowLayoutParams = new WindowManager.LayoutParams();
    windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.format = PixelFormat.TRANSLUCENT;
    windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    } else {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
    }

    actionBar = new ActionBar(activity);
    actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
    actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21);
    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setTitle(LocaleController.formatString("Of", R.string.Of, 1, 1));
    containerView.addView(actionBar,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (needCaptionLayout
                        && (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible())) {
                    closeCaptionEnter(false);
                    return;
                }
                closePhoto(true, false);
            } else if (id == gallery_menu_save) {
                if (Build.VERSION.SDK_INT >= 23 && parentActivity.checkSelfPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    parentActivity
                            .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }

                File f = null;
                if (currentMessageObject != null) {
                    f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                } else if (currentFileLocation != null) {
                    f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                }

                if (f != null && f.exists()) {
                    MediaController.saveFile(f.toString(), parentActivity,
                            currentMessageObject != null && currentMessageObject.isVideo() ? 1 : 0, null, null);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    builder.setMessage(LocaleController.getString("PleaseDownload", R.string.PleaseDownload));
                    showAlertDialog(builder);
                }
            } else if (id == gallery_menu_showall) {
                if (opennedFromMedia) {
                    closePhoto(true, false);
                } else if (currentDialogId != 0) {
                    disableShowCheck = true;
                    Bundle args2 = new Bundle();
                    args2.putLong("dialog_id", currentDialogId);
                    MediaActivity mediaActivity = new MediaActivity(args2);
                    if (parentChatActivity != null) {
                        mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
                    }
                    closePhoto(false, false);
                    ((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
                }
            } else if (id == gallery_menu_send) {
                /*Intent intent = new Intent(this, MessagesActivity.class);
                intent.putExtra("onlySelect", true);
                startActivityForResult(intent, 10);
                if (requestCode == 10) {
                int chatId = data.getIntExtra("chatId", 0);
                int userId = data.getIntExtra("userId", 0);
                int dialog_id = 0;
                if (chatId != 0) {
                    dialog_id = -chatId;
                } else if (userId != 0) {
                    dialog_id = userId;
                }
                TLRPC.FileLocation location = getCurrentFile();
                if (dialog_id != 0 && location != null) {
                    Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class);
                    if (chatId != 0) {
                        intent.putExtra("chatId", chatId);
                    } else {
                        intent.putExtra("userId", userId);
                    }
                    startActivity(intent);
                    NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
                    finish();
                    if (withoutBottom) {
                        MessagesController.getInstance().sendMessage(location, dialog_id);
                    } else {
                        int item = mViewPager.getCurrentItem();
                        MessageObject obj = localPagerAdapter.imagesArr.get(item);
                        MessagesController.getInstance().sendMessage(obj, dialog_id);
                    }
                }
                }*/
            } else if (id == gallery_menu_delete) {
                if (parentActivity == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                if (currentMessageObject != null && currentMessageObject.isVideo()) {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo",
                            R.string.AreYouSureDeleteVideo));
                } else if (currentMessageObject != null && currentMessageObject.isGif()) {
                    builder.setMessage(LocaleController.formatString("AreYouSure", R.string.AreYouSure));
                } else {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto",
                            R.string.AreYouSureDeletePhoto));
                }
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!imagesArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= imagesArr.size()) {
                                        return;
                                    }
                                    MessageObject obj = imagesArr.get(currentIndex);
                                    if (obj.isSent()) {
                                        closePhoto(false, false);
                                        ArrayList<Integer> arr = new ArrayList<>();
                                        arr.add(obj.getId());

                                        ArrayList<Long> random_ids = null;
                                        TLRPC.EncryptedChat encryptedChat = null;
                                        if ((int) obj.getDialogId() == 0 && obj.messageOwner.random_id != 0) {
                                            random_ids = new ArrayList<>();
                                            random_ids.add(obj.messageOwner.random_id);
                                            encryptedChat = MessagesController.getInstance()
                                                    .getEncryptedChat((int) (obj.getDialogId() >> 32));
                                        }

                                        MessagesController.getInstance().deleteMessages(arr, random_ids,
                                                encryptedChat, obj.messageOwner.to_id.channel_id);
                                    }
                                } else if (!avatarsArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
                                        return;
                                    }
                                    TLRPC.Photo photo = avatarsArr.get(currentIndex);
                                    TLRPC.FileLocation currentLocation = imagesArrLocations.get(currentIndex);
                                    if (photo instanceof TLRPC.TL_photoEmpty) {
                                        photo = null;
                                    }
                                    boolean current = false;
                                    if (currentUserAvatarLocation != null) {
                                        if (photo != null) {
                                            for (TLRPC.PhotoSize size : photo.sizes) {
                                                if (size.location.local_id == currentUserAvatarLocation.local_id
                                                        && size.location.volume_id == currentUserAvatarLocation.volume_id) {
                                                    current = true;
                                                    break;
                                                }
                                            }
                                        } else if (currentLocation.local_id == currentUserAvatarLocation.local_id
                                                && currentLocation.volume_id == currentUserAvatarLocation.volume_id) {
                                            current = true;
                                        }
                                    }
                                    if (current) {
                                        MessagesController.getInstance().deleteUserPhoto(null);
                                        closePhoto(false, false);
                                    } else if (photo != null) {
                                        TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                                        inputPhoto.id = photo.id;
                                        inputPhoto.access_hash = photo.access_hash;
                                        MessagesController.getInstance().deleteUserPhoto(inputPhoto);
                                        MessagesStorage.getInstance().clearUserPhoto(avatarsDialogId, photo.id);
                                        imagesArrLocations.remove(currentIndex);
                                        imagesArrLocationsSizes.remove(currentIndex);
                                        avatarsArr.remove(currentIndex);
                                        if (imagesArrLocations.isEmpty()) {
                                            closePhoto(false, false);
                                        } else {
                                            int index = currentIndex;
                                            if (index >= avatarsArr.size()) {
                                                index = avatarsArr.size() - 1;
                                            }
                                            currentIndex = -1;
                                            setImageIndex(index, true);
                                        }
                                    }
                                }
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showAlertDialog(builder);
            } else if (id == gallery_menu_caption_done) {
                closeCaptionEnter(true);
            } else if (id == gallery_menu_share) {
                onSharePressed();
            } else if (id == gallery_menu_openin) {
                try {
                    AndroidUtilities.openForView(currentMessageObject, parentActivity);
                    closePhoto(false, false);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (id == gallery_menu_mute) {
                muteVideo = !muteVideo;
                if (videoPlayer != null) {
                    videoPlayer.setMute(muteVideo);
                }
                if (muteVideo) {
                    actionBar.setTitle(LocaleController.getString("AttachGif", R.string.AttachGif));
                    muteItem.setIcon(R.drawable.volume_off);
                } else {
                    actionBar.setTitle(LocaleController.getString("AttachVideo", R.string.AttachVideo));
                    muteItem.setIcon(R.drawable.volume_on);
                }
            } else if (id == gallery_menu_masks) {
                if (parentActivity == null || currentMessageObject == null
                        || currentMessageObject.messageOwner.media == null
                        || currentMessageObject.messageOwner.media.photo == null) {
                    return;
                }
                StickersAlert stickersAlert = new StickersAlert(parentActivity,
                        currentMessageObject.messageOwner.media.photo);
                stickersAlert.show();
            }
        }

        @Override
        public boolean canOpenMenu() {
            if (currentMessageObject != null) {
                File f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                if (f.exists()) {
                    return true;
                }
            } else if (currentFileLocation != null) {
                File f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                if (f.exists()) {
                    return true;
                }
            }
            return false;
        }
    });

    ActionBarMenu menu = actionBar.createMenu();

    masksItem = menu.addItem(gallery_menu_masks, R.drawable.ic_masks_msk1);
    muteItem = menu.addItem(gallery_menu_mute, R.drawable.volume_on);

    menuItem = menu.addItem(0, R.drawable.ic_ab_other);
    menuItem.addSubItem(gallery_menu_openin,
            LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp), 0);
    menuItem.addSubItem(gallery_menu_showall, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia),
            0);
    menuItem.addSubItem(gallery_menu_share, LocaleController.getString("ShareFile", R.string.ShareFile), 0);
    menuItem.addSubItem(gallery_menu_save, LocaleController.getString("SaveToGallery", R.string.SaveToGallery),
            0);
    menuItem.addSubItem(gallery_menu_delete, LocaleController.getString("Delete", R.string.Delete), 0);

    captionDoneItem = menu.addItemWithWidth(gallery_menu_caption_done, R.drawable.ic_done,
            AndroidUtilities.dp(56));

    bottomLayout = new FrameLayout(actvityContext);
    bottomLayout.setBackgroundColor(0x7f000000);
    containerView.addView(bottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));

    captionTextViewOld = new TextView(actvityContext);
    captionTextViewOld.setMaxLines(10);
    captionTextViewOld.setBackgroundColor(0x7f000000);
    captionTextViewOld.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewOld.setLinkTextColor(0xffffffff);
    captionTextViewOld.setTextColor(0xffffffff);
    captionTextViewOld.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewOld.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewOld.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewOld, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewOld.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    captionTextView = captionTextViewNew = new TextView(actvityContext);
    captionTextViewNew.setMaxLines(10);
    captionTextViewNew.setBackgroundColor(0x7f000000);
    captionTextViewNew.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewNew.setLinkTextColor(0xffffffff);
    captionTextViewNew.setTextColor(0xffffffff);
    captionTextViewNew.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewNew.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewNew.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewNew, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    radialProgressViews[0] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[0].setBackgroundState(0, false);
    radialProgressViews[1] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[1].setBackgroundState(0, false);
    radialProgressViews[2] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[2].setBackgroundState(0, false);

    shareButton = new ImageView(containerView.getContext());
    shareButton.setImageResource(R.drawable.share);
    shareButton.setScaleType(ImageView.ScaleType.CENTER);
    shareButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomLayout.addView(shareButton,
            LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSharePressed();
        }
    });

    nameTextView = new TextView(containerView.getContext());
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setSingleLine(true);
    nameTextView.setMaxLines(1);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setTextColor(0xffffffff);
    nameTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 60, 0));

    dateTextView = new TextView(containerView.getContext());
    dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    dateTextView.setSingleLine(true);
    dateTextView.setMaxLines(1);
    dateTextView.setEllipsize(TextUtils.TruncateAt.END);
    dateTextView.setTextColor(0xffffffff);
    dateTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dateTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 50, 0));

    if (Build.VERSION.SDK_INT >= 16) {
        videoPlayerSeekbar = new SeekBar(containerView.getContext());
        videoPlayerSeekbar.setColors(0x66ffffff, 0xffffffff, 0xffffffff);
        videoPlayerSeekbar.setDelegate(new SeekBar.SeekBarDelegate() {
            @Override
            public void onSeekBarDrag(float progress) {
                if (videoPlayer != null) {
                    videoPlayer.getPlayerControl().seekTo((int) (progress * videoPlayer.getDuration()));
                }
            }
        });

        videoPlayerControlFrameLayout = new FrameLayout(containerView.getContext()) {

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                if (videoPlayerSeekbar.onTouch(event.getAction(), event.getX() - AndroidUtilities.dp(48),
                        event.getY())) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                long duration;
                if (videoPlayer != null) {
                    duration = videoPlayer.getDuration();
                    if (duration == ExoPlayer.UNKNOWN_TIME) {
                        duration = 0;
                    }
                } else {
                    duration = 0;
                }
                duration /= 1000;
                int size = (int) Math
                        .ceil(videoPlayerTime.getPaint().measureText(String.format("%02d:%02d / %02d:%02d",
                                duration / 60, duration % 60, duration / 60, duration % 60)));
                videoPlayerSeekbar.setSize(getMeasuredWidth() - AndroidUtilities.dp(48 + 16) - size,
                        getMeasuredHeight());
            }

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);
                float progress = 0;
                if (videoPlayer != null) {
                    PlayerControl playerControl = videoPlayer.getPlayerControl();
                    progress = playerControl.getCurrentPosition() / (float) playerControl.getDuration();
                }
                videoPlayerSeekbar.setProgress(progress);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.save();
                canvas.translate(AndroidUtilities.dp(48), 0);
                videoPlayerSeekbar.draw(canvas);
                canvas.restore();
            }
        };
        videoPlayerControlFrameLayout.setWillNotDraw(false);
        bottomLayout.addView(videoPlayerControlFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

        videoPlayButton = new ImageView(containerView.getContext());
        videoPlayButton.setScaleType(ImageView.ScaleType.CENTER);
        videoPlayerControlFrameLayout.addView(videoPlayButton,
                LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
        videoPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoPlayer != null) {
                    if (isPlaying) {
                        videoPlayer.getPlayerControl().pause();
                    } else {
                        videoPlayer.getPlayerControl().start();
                    }
                }
            }
        });

        videoPlayerTime = new TextView(containerView.getContext());
        videoPlayerTime.setTextColor(0xffffffff);
        videoPlayerTime.setGravity(Gravity.CENTER_VERTICAL);
        videoPlayerTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
        videoPlayerControlFrameLayout.addView(videoPlayerTime, LayoutHelper.createFrame(
                LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 8, 0));
    }

    pickerView = new PickerBottomLayoutViewer(actvityContext);
    pickerView.setBackgroundColor(0x7f000000);
    containerView.addView(pickerView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    pickerView.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider instanceof EmptyPhotoViewerProvider) {
                closePhoto(false, false);
            } else if (placeProvider != null) {
                closePhoto(!placeProvider.cancelButtonPressed(), false);
            }
        }
    });
    pickerView.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider != null) {
                placeProvider.sendButtonPressed(currentIndex);
                closePhoto(false, false);
            }
        }
    });

    LinearLayout itemsLayout = new LinearLayout(parentActivity);
    itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
    pickerView.addView(itemsLayout,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    tuneItem = new ImageView(parentActivity);
    tuneItem.setScaleType(ImageView.ScaleType.CENTER);
    tuneItem.setImageResource(R.drawable.photo_tools);
    tuneItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(tuneItem, LayoutHelper.createLinear(56, 48));
    tuneItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(2);
        }
    });

    paintItem = new ImageView(parentActivity);
    paintItem.setScaleType(ImageView.ScaleType.CENTER);
    paintItem.setImageResource(R.drawable.photo_paint);
    paintItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(paintItem, LayoutHelper.createLinear(56, 48));
    paintItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(3);
        }
    });

    cropItem = new ImageView(parentActivity);
    cropItem.setScaleType(ImageView.ScaleType.CENTER);
    cropItem.setImageResource(R.drawable.photo_crop);
    cropItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(cropItem, LayoutHelper.createLinear(56, 48));
    cropItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(1);
        }
    });

    editorDoneLayout = new PickerBottomLayoutViewer(actvityContext);
    editorDoneLayout.setBackgroundColor(0x7f000000);
    editorDoneLayout.updateSelectedCount(0, false);
    editorDoneLayout.setVisibility(View.GONE);
    containerView.addView(editorDoneLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    editorDoneLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
            }
            switchToEditMode(0);
        }
    });
    editorDoneLayout.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
                if (imageMoveAnimation != null) {
                    return;
                }
            }
            applyCurrentEditMode();
            switchToEditMode(0);
        }
    });

    ImageView rotateButton = new ImageView(actvityContext);
    rotateButton.setScaleType(ImageView.ScaleType.CENTER);
    rotateButton.setImageResource(R.drawable.tool_rotate);
    rotateButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    editorDoneLayout.addView(rotateButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            centerImage.setOrientation(centerImage.getOrientation() - 90, false);
            photoCropView.setOrientation(centerImage.getOrientation());
            containerView.invalidate();
        }
    });

    gestureDetector = new GestureDetector(containerView.getContext(), this);
    gestureDetector.setOnDoubleTapListener(this);

    ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = new ImageReceiver.ImageReceiverDelegate() {
        @Override
        public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) {
            if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill()) {
                if (!wasLayout) {
                    dontResetZoomOnFirstLayout = true;
                } else {
                    setScaleToFill();
                }
            }
        }
    };

    centerImage.setParentView(containerView);
    centerImage.setCrossfadeAlpha((byte) 2);
    centerImage.setInvalidateAll(true);
    centerImage.setDelegate(imageReceiverDelegate);
    leftImage.setParentView(containerView);
    leftImage.setCrossfadeAlpha((byte) 2);
    leftImage.setInvalidateAll(true);
    leftImage.setDelegate(imageReceiverDelegate);
    rightImage.setParentView(containerView);
    rightImage.setCrossfadeAlpha((byte) 2);
    rightImage.setInvalidateAll(true);
    rightImage.setDelegate(imageReceiverDelegate);

    WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
            .getSystemService(Activity.WINDOW_SERVICE);
    int rotation = manager.getDefaultDisplay().getRotation();

    checkImageView = new CheckBox(containerView.getContext(), R.drawable.selectphoto_large);
    checkImageView.setDrawBackground(true);
    checkImageView.setSize(45);
    checkImageView.setCheckOffset(AndroidUtilities.dp(1));
    checkImageView.setColor(0xff3ccaef);
    checkImageView.setVisibility(View.GONE);
    containerView.addView(checkImageView, LayoutHelper.createFrame(45, 45, Gravity.RIGHT | Gravity.TOP, 0,
            rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 10, 0));
    if (Build.VERSION.SDK_INT >= 21) {
        ((FrameLayout.LayoutParams) checkImageView
                .getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    checkImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (placeProvider != null) {
                placeProvider.setPhotoChecked(currentIndex);
                checkImageView.setChecked(placeProvider.isPhotoChecked(currentIndex), true);
                updateSelectedCount();
            }
        }
    });

    captionEditText = new PhotoViewerCaptionEnterView(actvityContext, containerView, windowView);
    captionEditText.setDelegate(new PhotoViewerCaptionEnterView.PhotoViewerCaptionEnterViewDelegate() {
        @Override
        public void onCaptionEnter() {
            closeCaptionEnter(true);
        }

        @Override
        public void onTextChanged(CharSequence text) {
            if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null
                    && text != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(),
                        parentChatActivity.messages);
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            int height = AndroidUtilities.dp(36 * Math.min(3, mentionsAdapter.getItemCount())
                    + (mentionsAdapter.getItemCount() > 3 ? 18 : 0));
            if (size - ActionBar.getCurrentActionBarHeight() * 2 < height) {
                allowMentions = false;
                if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) {
                    mentionListView.setVisibility(View.INVISIBLE);
                }
            } else {
                allowMentions = true;
                if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) {
                    mentionListView.setVisibility(View.VISIBLE);
                }
            }
        }
    });
    containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, -400));

    mentionListView = new RecyclerListView(actvityContext);
    mentionListView.setTag(5);
    mentionLayoutManager = new LinearLayoutManager(actvityContext) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mentionListView.setLayoutManager(mentionLayoutManager);
    mentionListView.setBackgroundColor(0x7f000000);
    mentionListView.setVisibility(View.GONE);
    mentionListView.setClipToPadding(true);
    mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    containerView.addView(mentionListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(actvityContext, true, 0,
            new MentionsAdapter.MentionsAdapterDelegate() {
                @Override
                public void needChangePanelVisibility(boolean show) {
                    if (show) {
                        FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) mentionListView
                                .getLayoutParams();
                        int height = 36 * Math.min(3, mentionsAdapter.getItemCount())
                                + (mentionsAdapter.getItemCount() > 3 ? 18 : 0);
                        layoutParams3.height = AndroidUtilities.dp(height);
                        layoutParams3.topMargin = -AndroidUtilities.dp(height);
                        mentionListView.setLayoutParams(layoutParams3);

                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.VISIBLE) {
                            mentionListView.setAlpha(1.0f);
                            return;
                        } else {
                            mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                        }
                        if (allowMentions) {
                            mentionListView.setVisibility(View.VISIBLE);
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f, 1.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setAlpha(1.0f);
                            mentionListView.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.GONE) {
                            return;
                        }
                        if (allowMentions) {
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListView.setVisibility(View.GONE);
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onContextSearch(boolean searching) {

                }

                @Override
                public void onContextClick(TLRPC.BotInlineResult result) {

                }
            }));
    mentionsAdapter.setAllowNewMentions(false);

    mentionListView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            int start = mentionsAdapter.getResultStartPosition();
            int len = mentionsAdapter.getResultLength();
            if (object instanceof TLRPC.User) {
                TLRPC.User user = (TLRPC.User) object;
                if (user != null) {
                    captionEditText.replaceWithText(start, len, "@" + user.username + " ");
                }
            } else if (object instanceof String) {
                captionEditText.replaceWithText(start, len, object + " ");
            }
        }
    });

    mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
        @Override
        public boolean onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            if (object instanceof String) {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch));
                builder.setPositiveButton(
                        LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mentionsAdapter.clearRecentHashtags();
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showAlertDialog(builder);
                return true;
            }
            return false;
        }
    });
}

From source file:kr.wdream.ui.PhotoViewer.java

public void setParentActivity(final Activity activity) {
    if (parentActivity == activity) {
        return;//from   www.j  a  v a2s. c  o  m
    }
    parentActivity = activity;
    actvityContext = new ContextThemeWrapper(parentActivity, kr.wdream.storyshop.R.style.Theme_TMessages);

    if (progressDrawables == null) {
        progressDrawables = new Drawable[4];
        progressDrawables[0] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.circle_big);
        progressDrawables[1] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.cancel_big);
        progressDrawables[2] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.load_big);
        progressDrawables[3] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.play_big);
    }

    scroller = new Scroller(activity);

    windowView = new FrameLayout(activity) {

        private Runnable attachRunnable;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return isVisible && super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return isVisible && PhotoViewer.this.onTouchEvent(event);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (Build.VERSION.SDK_INT >= 21 && child == animatingImageView && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(),
                        getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                if (AndroidUtilities.incorrectDisplaySizeFix) {
                    if (heightSize > AndroidUtilities.displaySize.y) {
                        heightSize = AndroidUtilities.displaySize.y;
                    }
                    heightSize += AndroidUtilities.statusBarHeight;
                }
                heightSize -= insets.getSystemWindowInsetBottom();
                widthSize -= insets.getSystemWindowInsetRight();
            } else {
                if (heightSize > AndroidUtilities.displaySize.y) {
                    heightSize = AndroidUtilities.displaySize.y;
                }
            }
            setMeasuredDimension(widthSize, heightSize);
            ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams();
            animatingImageView.measure(MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.AT_MOST));
            containerView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
        }

        @SuppressWarnings("DrawAllocation")
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            animatingImageView.layout(0, 0, animatingImageView.getMeasuredWidth(),
                    animatingImageView.getMeasuredHeight());
            containerView.layout(0, 0, containerView.getMeasuredWidth(), containerView.getMeasuredHeight());
            wasLayout = true;
            if (changed) {
                if (!dontResetZoomOnFirstLayout) {
                    scale = 1;
                    translationX = 0;
                    translationY = 0;
                    updateMinMax(scale);
                }

                if (checkImageView != null) {
                    checkImageView.post(new Runnable() {
                        @Override
                        public void run() {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) checkImageView
                                    .getLayoutParams();
                            WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
                                    .getSystemService(Activity.WINDOW_SERVICE);
                            int rotation = manager.getDefaultDisplay().getRotation();
                            layoutParams.topMargin = AndroidUtilities
                                    .dp(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58
                                            : 68)
                                    + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
                            checkImageView.setLayoutParams(layoutParams);
                        }
                    });
                }
            }
            if (dontResetZoomOnFirstLayout) {
                setScaleToFill();
                dontResetZoomOnFirstLayout = false;
            }
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            attachedToWindow = true;
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            attachedToWindow = false;
            wasLayout = false;
        }

        @Override
        public boolean dispatchKeyEventPreIme(KeyEvent event) {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible()) {
                    closeCaptionEnter(false);
                    return false;
                }
                PhotoViewer.getInstance().closePhoto(true, false);
                return true;
            }
            return super.dispatchKeyEventPreIme(event);
        }

        @Override
        public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) {
            if (Build.VERSION.SDK_INT >= 23) {
                View view = parentActivity.findViewById(android.R.id.content);
                if (view instanceof ViewGroup) {
                    try {
                        return ((ViewGroup) view).startActionModeForChild(originalView, callback, type);
                    } catch (Throwable e) {
                        FileLog.e("tmessages", e);
                    }
                }
            }
            return super.startActionModeForChild(originalView, callback, type);
        }
    };
    windowView.setBackgroundDrawable(backgroundDrawable);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);

    animatingImageView = new ClippingImageView(activity);
    animatingImageView.setAnimationValues(animationValues);
    windowView.addView(animatingImageView, LayoutHelper.createFrame(40, 40));

    containerView = new FrameLayoutDrawer(activity);
    containerView.setFocusable(false);
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    if (Build.VERSION.SDK_INT >= 21) {
        //containerView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @SuppressLint("NewApi")
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                lastInsets = insets;
                windowView.requestLayout();
                return insets.consumeSystemWindowInsets();
            }
        });
        //containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
    }

    windowLayoutParams = new WindowManager.LayoutParams();
    windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.format = PixelFormat.TRANSLUCENT;
    windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    } else {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
    }

    actionBar = new ActionBar(activity);
    actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
    actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21);
    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR);
    actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back);
    actionBar.setTitle(LocaleController.formatString("Of", kr.wdream.storyshop.R.string.Of, 1, 1));
    containerView.addView(actionBar,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (needCaptionLayout
                        && (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible())) {
                    closeCaptionEnter(false);
                    return;
                }
                closePhoto(true, false);
            } else if (id == gallery_menu_save) {
                if (Build.VERSION.SDK_INT >= 23 && parentActivity.checkSelfPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    parentActivity
                            .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }

                File f = null;
                if (currentMessageObject != null) {
                    f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                } else if (currentFileLocation != null) {
                    f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                }

                if (f != null && f.exists()) {
                    MediaController.saveFile(f.toString(), parentActivity,
                            currentMessageObject != null && currentMessageObject.isVideo() ? 1 : 0, null, null);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                    builder.setTitle(
                            LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            null);
                    builder.setMessage(LocaleController.getString("PleaseDownload",
                            kr.wdream.storyshop.R.string.PleaseDownload));
                    showAlertDialog(builder);
                }
            } else if (id == gallery_menu_showall) {
                if (opennedFromMedia) {
                    closePhoto(true, false);
                } else if (currentDialogId != 0) {
                    disableShowCheck = true;
                    Bundle args2 = new Bundle();
                    args2.putLong("dialog_id", currentDialogId);
                    MediaActivity mediaActivity = new MediaActivity(args2);
                    if (parentChatActivity != null) {
                        mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
                    }
                    closePhoto(false, false);
                    ((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
                }
            } else if (id == gallery_menu_send) {
                /*Intent intent = new Intent(this, MessagesActivity.class);
                intent.putExtra("onlySelect", true);
                startActivityForResult(intent, 10);
                if (requestCode == 10) {
                int chatId = data.getIntExtra("chatId", 0);
                int userId = data.getIntExtra("userId", 0);
                int dialog_id = 0;
                if (chatId != 0) {
                    dialog_id = -chatId;
                } else if (userId != 0) {
                    dialog_id = userId;
                }
                TLRPC.FileLocation location = getCurrentFile();
                if (dialog_id != 0 && location != null) {
                    Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class);
                    if (chatId != 0) {
                        intent.putExtra("chatId", chatId);
                    } else {
                        intent.putExtra("userId", userId);
                    }
                    startActivity(intent);
                    NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
                    finish();
                    if (withoutBottom) {
                        MessagesController.getInstance().sendMessage(location, dialog_id);
                    } else {
                        int item = mViewPager.getCurrentItem();
                        MessageObject obj = localPagerAdapter.imagesArr.get(item);
                        MessagesController.getInstance().sendMessage(obj, dialog_id);
                    }
                }
                }*/
            } else if (id == gallery_menu_delete) {
                if (parentActivity == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                if (currentMessageObject != null && currentMessageObject.isVideo()) {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo",
                            kr.wdream.storyshop.R.string.AreYouSureDeleteVideo));
                } else if (currentMessageObject != null && currentMessageObject.isGif()) {
                    builder.setMessage(LocaleController.formatString("AreYouSure",
                            kr.wdream.storyshop.R.string.AreYouSure));
                } else {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto",
                            kr.wdream.storyshop.R.string.AreYouSureDeletePhoto));
                }
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!imagesArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= imagesArr.size()) {
                                        return;
                                    }
                                    MessageObject obj = imagesArr.get(currentIndex);
                                    if (obj.isSent()) {
                                        closePhoto(false, false);
                                        ArrayList<Integer> arr = new ArrayList<>();
                                        arr.add(obj.getId());

                                        ArrayList<Long> random_ids = null;
                                        TLRPC.EncryptedChat encryptedChat = null;
                                        if ((int) obj.getDialogId() == 0 && obj.messageOwner.random_id != 0) {
                                            random_ids = new ArrayList<>();
                                            random_ids.add(obj.messageOwner.random_id);
                                            encryptedChat = MessagesController.getInstance()
                                                    .getEncryptedChat((int) (obj.getDialogId() >> 32));
                                        }

                                        MessagesController.getInstance().deleteMessages(arr, random_ids,
                                                encryptedChat, obj.messageOwner.to_id.channel_id);
                                    }
                                } else if (!avatarsArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
                                        return;
                                    }
                                    TLRPC.Photo photo = avatarsArr.get(currentIndex);
                                    TLRPC.FileLocation currentLocation = imagesArrLocations.get(currentIndex);
                                    if (photo instanceof TLRPC.TL_photoEmpty) {
                                        photo = null;
                                    }
                                    boolean current = false;
                                    if (currentUserAvatarLocation != null) {
                                        if (photo != null) {
                                            for (TLRPC.PhotoSize size : photo.sizes) {
                                                if (size.location.local_id == currentUserAvatarLocation.local_id
                                                        && size.location.volume_id == currentUserAvatarLocation.volume_id) {
                                                    current = true;
                                                    break;
                                                }
                                            }
                                        } else if (currentLocation.local_id == currentUserAvatarLocation.local_id
                                                && currentLocation.volume_id == currentUserAvatarLocation.volume_id) {
                                            current = true;
                                        }
                                    }
                                    if (current) {
                                        MessagesController.getInstance().deleteUserPhoto(null);
                                        closePhoto(false, false);
                                    } else if (photo != null) {
                                        TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                                        inputPhoto.id = photo.id;
                                        inputPhoto.access_hash = photo.access_hash;
                                        MessagesController.getInstance().deleteUserPhoto(inputPhoto);
                                        MessagesStorage.getInstance().clearUserPhoto(avatarsDialogId, photo.id);
                                        imagesArrLocations.remove(currentIndex);
                                        imagesArrLocationsSizes.remove(currentIndex);
                                        avatarsArr.remove(currentIndex);
                                        if (imagesArrLocations.isEmpty()) {
                                            closePhoto(false, false);
                                        } else {
                                            int index = currentIndex;
                                            if (index >= avatarsArr.size()) {
                                                index = avatarsArr.size() - 1;
                                            }
                                            currentIndex = -1;
                                            setImageIndex(index, true);
                                        }
                                    }
                                }
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showAlertDialog(builder);
            } else if (id == gallery_menu_caption_done) {
                closeCaptionEnter(true);
            } else if (id == gallery_menu_share) {
                onSharePressed();
            } else if (id == gallery_menu_openin) {
                try {
                    AndroidUtilities.openForView(currentMessageObject, parentActivity);
                    closePhoto(false, false);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (id == gallery_menu_mute) {
                muteVideo = !muteVideo;
                if (videoPlayer != null) {
                    videoPlayer.setMute(muteVideo);
                }
                if (muteVideo) {
                    actionBar.setTitle(
                            LocaleController.getString("AttachGif", kr.wdream.storyshop.R.string.AttachGif));
                    muteItem.setIcon(kr.wdream.storyshop.R.drawable.volume_off);
                } else {
                    actionBar.setTitle(LocaleController.getString("AttachVideo",
                            kr.wdream.storyshop.R.string.AttachVideo));
                    muteItem.setIcon(kr.wdream.storyshop.R.drawable.volume_on);
                }
            } else if (id == gallery_menu_masks) {
                if (parentActivity == null || currentMessageObject == null
                        || currentMessageObject.messageOwner.media == null
                        || currentMessageObject.messageOwner.media.photo == null) {
                    return;
                }
                StickersAlert stickersAlert = new StickersAlert(parentActivity,
                        currentMessageObject.messageOwner.media.photo);
                stickersAlert.show();
            }
        }

        @Override
        public boolean canOpenMenu() {
            if (currentMessageObject != null) {
                File f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                if (f.exists()) {
                    return true;
                }
            } else if (currentFileLocation != null) {
                File f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                if (f.exists()) {
                    return true;
                }
            }
            return false;
        }
    });

    ActionBarMenu menu = actionBar.createMenu();

    masksItem = menu.addItem(gallery_menu_masks, kr.wdream.storyshop.R.drawable.ic_masks_msk1);
    muteItem = menu.addItem(gallery_menu_mute, kr.wdream.storyshop.R.drawable.volume_on);

    menuItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_other);
    menuItem.addSubItem(gallery_menu_openin,
            LocaleController.getString("OpenInExternalApp", kr.wdream.storyshop.R.string.OpenInExternalApp), 0);
    menuItem.addSubItem(gallery_menu_showall,
            LocaleController.getString("ShowAllMedia", kr.wdream.storyshop.R.string.ShowAllMedia), 0);
    menuItem.addSubItem(gallery_menu_share,
            LocaleController.getString("ShareFile", kr.wdream.storyshop.R.string.ShareFile), 0);
    menuItem.addSubItem(gallery_menu_save,
            LocaleController.getString("SaveToGallery", kr.wdream.storyshop.R.string.SaveToGallery), 0);
    menuItem.addSubItem(gallery_menu_delete,
            LocaleController.getString("Delete", kr.wdream.storyshop.R.string.Delete), 0);

    captionDoneItem = menu.addItemWithWidth(gallery_menu_caption_done, kr.wdream.storyshop.R.drawable.ic_done,
            AndroidUtilities.dp(56));

    bottomLayout = new FrameLayout(actvityContext);
    bottomLayout.setBackgroundColor(0x7f000000);
    containerView.addView(bottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));

    captionTextViewOld = new TextView(actvityContext);
    captionTextViewOld.setMaxLines(10);
    captionTextViewOld.setBackgroundColor(0x7f000000);
    captionTextViewOld.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewOld.setLinkTextColor(0xffffffff);
    captionTextViewOld.setTextColor(0xffffffff);
    captionTextViewOld.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewOld.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewOld.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewOld, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewOld.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    captionTextView = captionTextViewNew = new TextView(actvityContext);
    captionTextViewNew.setMaxLines(10);
    captionTextViewNew.setBackgroundColor(0x7f000000);
    captionTextViewNew.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewNew.setLinkTextColor(0xffffffff);
    captionTextViewNew.setTextColor(0xffffffff);
    captionTextViewNew.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewNew.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewNew.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewNew, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    radialProgressViews[0] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[0].setBackgroundState(0, false);
    radialProgressViews[1] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[1].setBackgroundState(0, false);
    radialProgressViews[2] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[2].setBackgroundState(0, false);

    shareButton = new ImageView(containerView.getContext());
    shareButton.setImageResource(kr.wdream.storyshop.R.drawable.share);
    shareButton.setScaleType(ImageView.ScaleType.CENTER);
    shareButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomLayout.addView(shareButton,
            LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSharePressed();
        }
    });

    nameTextView = new TextView(containerView.getContext());
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setSingleLine(true);
    nameTextView.setMaxLines(1);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setTextColor(0xffffffff);
    nameTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 60, 0));

    dateTextView = new TextView(containerView.getContext());
    dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    dateTextView.setSingleLine(true);
    dateTextView.setMaxLines(1);
    dateTextView.setEllipsize(TextUtils.TruncateAt.END);
    dateTextView.setTextColor(0xffffffff);
    dateTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dateTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 50, 0));

    if (Build.VERSION.SDK_INT >= 16) {
        videoPlayerSeekbar = new SeekBar(containerView.getContext());
        videoPlayerSeekbar.setColors(0x66ffffff, 0xffffffff, 0xffffffff);
        videoPlayerSeekbar.setDelegate(new SeekBar.SeekBarDelegate() {
            @Override
            public void onSeekBarDrag(float progress) {
                if (videoPlayer != null) {
                    videoPlayer.getPlayerControl().seekTo((int) (progress * videoPlayer.getDuration()));
                }
            }
        });

        videoPlayerControlFrameLayout = new FrameLayout(containerView.getContext()) {

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                if (videoPlayerSeekbar.onTouch(event.getAction(), event.getX() - AndroidUtilities.dp(48),
                        event.getY())) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                long duration;
                if (videoPlayer != null) {
                    duration = videoPlayer.getDuration();
                    if (duration == ExoPlayer.UNKNOWN_TIME) {
                        duration = 0;
                    }
                } else {
                    duration = 0;
                }
                duration /= 1000;
                int size = (int) Math
                        .ceil(videoPlayerTime.getPaint().measureText(String.format("%02d:%02d / %02d:%02d",
                                duration / 60, duration % 60, duration / 60, duration % 60)));
                videoPlayerSeekbar.setSize(getMeasuredWidth() - AndroidUtilities.dp(48 + 16) - size,
                        getMeasuredHeight());
            }

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);
                float progress = 0;
                if (videoPlayer != null) {
                    PlayerControl playerControl = videoPlayer.getPlayerControl();
                    progress = playerControl.getCurrentPosition() / (float) playerControl.getDuration();
                }
                videoPlayerSeekbar.setProgress(progress);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.save();
                canvas.translate(AndroidUtilities.dp(48), 0);
                videoPlayerSeekbar.draw(canvas);
                canvas.restore();
            }
        };
        videoPlayerControlFrameLayout.setWillNotDraw(false);
        bottomLayout.addView(videoPlayerControlFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

        videoPlayButton = new ImageView(containerView.getContext());
        videoPlayButton.setScaleType(ImageView.ScaleType.CENTER);
        videoPlayerControlFrameLayout.addView(videoPlayButton,
                LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
        videoPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoPlayer != null) {
                    if (isPlaying) {
                        videoPlayer.getPlayerControl().pause();
                    } else {
                        videoPlayer.getPlayerControl().start();
                    }
                }
            }
        });

        videoPlayerTime = new TextView(containerView.getContext());
        videoPlayerTime.setTextColor(0xffffffff);
        videoPlayerTime.setGravity(Gravity.CENTER_VERTICAL);
        videoPlayerTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
        videoPlayerControlFrameLayout.addView(videoPlayerTime, LayoutHelper.createFrame(
                LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 8, 0));
    }

    pickerView = new PickerBottomLayoutViewer(actvityContext);
    pickerView.setBackgroundColor(0x7f000000);
    containerView.addView(pickerView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    pickerView.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider instanceof EmptyPhotoViewerProvider) {
                closePhoto(false, false);
            } else if (placeProvider != null) {
                closePhoto(!placeProvider.cancelButtonPressed(), false);
            }
        }
    });
    pickerView.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider != null) {
                placeProvider.sendButtonPressed(currentIndex);
                closePhoto(false, false);
            }
        }
    });

    LinearLayout itemsLayout = new LinearLayout(parentActivity);
    itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
    pickerView.addView(itemsLayout,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    tuneItem = new ImageView(parentActivity);
    tuneItem.setScaleType(ImageView.ScaleType.CENTER);
    tuneItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_tools);
    tuneItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(tuneItem, LayoutHelper.createLinear(56, 48));
    tuneItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(2);
        }
    });

    paintItem = new ImageView(parentActivity);
    paintItem.setScaleType(ImageView.ScaleType.CENTER);
    paintItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_paint);
    paintItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(paintItem, LayoutHelper.createLinear(56, 48));
    paintItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(3);
        }
    });

    cropItem = new ImageView(parentActivity);
    cropItem.setScaleType(ImageView.ScaleType.CENTER);
    cropItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_crop);
    cropItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(cropItem, LayoutHelper.createLinear(56, 48));
    cropItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(1);
        }
    });

    editorDoneLayout = new PickerBottomLayoutViewer(actvityContext);
    editorDoneLayout.setBackgroundColor(0x7f000000);
    editorDoneLayout.updateSelectedCount(0, false);
    editorDoneLayout.setVisibility(View.GONE);
    containerView.addView(editorDoneLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    editorDoneLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
            }
            switchToEditMode(0);
        }
    });
    editorDoneLayout.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
                if (imageMoveAnimation != null) {
                    return;
                }
            }
            applyCurrentEditMode();
            switchToEditMode(0);
        }
    });

    ImageView rotateButton = new ImageView(actvityContext);
    rotateButton.setScaleType(ImageView.ScaleType.CENTER);
    rotateButton.setImageResource(kr.wdream.storyshop.R.drawable.tool_rotate);
    rotateButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    editorDoneLayout.addView(rotateButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            centerImage.setOrientation(centerImage.getOrientation() - 90, false);
            photoCropView.setOrientation(centerImage.getOrientation());
            containerView.invalidate();
        }
    });

    gestureDetector = new GestureDetector(containerView.getContext(), this);
    gestureDetector.setOnDoubleTapListener(this);

    ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = new ImageReceiver.ImageReceiverDelegate() {
        @Override
        public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) {
            if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill()) {
                if (!wasLayout) {
                    dontResetZoomOnFirstLayout = true;
                } else {
                    setScaleToFill();
                }
            }
        }
    };

    centerImage.setParentView(containerView);
    centerImage.setCrossfadeAlpha((byte) 2);
    centerImage.setInvalidateAll(true);
    centerImage.setDelegate(imageReceiverDelegate);
    leftImage.setParentView(containerView);
    leftImage.setCrossfadeAlpha((byte) 2);
    leftImage.setInvalidateAll(true);
    leftImage.setDelegate(imageReceiverDelegate);
    rightImage.setParentView(containerView);
    rightImage.setCrossfadeAlpha((byte) 2);
    rightImage.setInvalidateAll(true);
    rightImage.setDelegate(imageReceiverDelegate);

    WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
            .getSystemService(Activity.WINDOW_SERVICE);
    int rotation = manager.getDefaultDisplay().getRotation();

    checkImageView = new CheckBox(containerView.getContext(), kr.wdream.storyshop.R.drawable.selectphoto_large);
    checkImageView.setDrawBackground(true);
    checkImageView.setSize(45);
    checkImageView.setCheckOffset(AndroidUtilities.dp(1));
    checkImageView.setColor(0xff3ccaef);
    checkImageView.setVisibility(View.GONE);
    containerView.addView(checkImageView, LayoutHelper.createFrame(45, 45, Gravity.RIGHT | Gravity.TOP, 0,
            rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 10, 0));
    if (Build.VERSION.SDK_INT >= 21) {
        ((FrameLayout.LayoutParams) checkImageView
                .getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    checkImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (placeProvider != null) {
                placeProvider.setPhotoChecked(currentIndex);
                checkImageView.setChecked(placeProvider.isPhotoChecked(currentIndex), true);
                updateSelectedCount();
            }
        }
    });

    captionEditText = new PhotoViewerCaptionEnterView(actvityContext, containerView, windowView);
    captionEditText.setDelegate(new PhotoViewerCaptionEnterView.PhotoViewerCaptionEnterViewDelegate() {
        @Override
        public void onCaptionEnter() {
            closeCaptionEnter(true);
        }

        @Override
        public void onTextChanged(CharSequence text) {
            if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null
                    && text != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(),
                        parentChatActivity.messages);
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            int height = AndroidUtilities.dp(36 * Math.min(3, mentionsAdapter.getItemCount())
                    + (mentionsAdapter.getItemCount() > 3 ? 18 : 0));
            if (size - ActionBar.getCurrentActionBarHeight() * 2 < height) {
                allowMentions = false;
                if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) {
                    mentionListView.setVisibility(View.INVISIBLE);
                }
            } else {
                allowMentions = true;
                if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) {
                    mentionListView.setVisibility(View.VISIBLE);
                }
            }
        }
    });
    containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, -400));

    mentionListView = new RecyclerListView(actvityContext);
    mentionListView.setTag(5);
    mentionLayoutManager = new LinearLayoutManager(actvityContext) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mentionListView.setLayoutManager(mentionLayoutManager);
    mentionListView.setBackgroundColor(0x7f000000);
    mentionListView.setVisibility(View.GONE);
    mentionListView.setClipToPadding(true);
    mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    containerView.addView(mentionListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(actvityContext, true, 0,
            new MentionsAdapter.MentionsAdapterDelegate() {
                @Override
                public void needChangePanelVisibility(boolean show) {
                    if (show) {
                        FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) mentionListView
                                .getLayoutParams();
                        int height = 36 * Math.min(3, mentionsAdapter.getItemCount())
                                + (mentionsAdapter.getItemCount() > 3 ? 18 : 0);
                        layoutParams3.height = AndroidUtilities.dp(height);
                        layoutParams3.topMargin = -AndroidUtilities.dp(height);
                        mentionListView.setLayoutParams(layoutParams3);

                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.VISIBLE) {
                            mentionListView.setAlpha(1.0f);
                            return;
                        } else {
                            mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                        }
                        if (allowMentions) {
                            mentionListView.setVisibility(View.VISIBLE);
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f, 1.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setAlpha(1.0f);
                            mentionListView.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.GONE) {
                            return;
                        }
                        if (allowMentions) {
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListView.setVisibility(View.GONE);
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onContextSearch(boolean searching) {

                }

                @Override
                public void onContextClick(TLRPC.BotInlineResult result) {

                }
            }));
    mentionsAdapter.setAllowNewMentions(false);

    mentionListView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            int start = mentionsAdapter.getResultStartPosition();
            int len = mentionsAdapter.getResultLength();
            if (object instanceof TLRPC.User) {
                TLRPC.User user = (TLRPC.User) object;
                if (user != null) {
                    captionEditText.replaceWithText(start, len, "@" + user.username + " ");
                }
            } else if (object instanceof String) {
                captionEditText.replaceWithText(start, len, object + " ");
            }
        }
    });

    mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
        @Override
        public boolean onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            if (object instanceof String) {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setMessage(
                        LocaleController.getString("ClearSearch", kr.wdream.storyshop.R.string.ClearSearch));
                builder.setPositiveButton(LocaleController
                        .getString("ClearButton", kr.wdream.storyshop.R.string.ClearButton).toUpperCase(),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mentionsAdapter.clearRecentHashtags();
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showAlertDialog(builder);
                return true;
            }
            return false;
        }
    });
}