Example usage for android.graphics Canvas translate

List of usage examples for android.graphics Canvas translate

Introduction

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

Prototype

public void translate(float dx, float dy) 

Source Link

Document

Preconcat the current matrix with the specified translation

Usage

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

@SuppressLint("NewApi")
private void onDraw(Canvas canvas) {
    if (animationInProgress == 1 || !isVisible && animationInProgress != 2) {
        return;/*from   w  ww  . java 2  s  . c om*/
    }

    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 (currentEditMode == 1) {
            photoCropView.setAnimationProgress(animationValue);
        }

        if (animateToScale == 1 && scale == 1 && translationX == 0) {
            aty = ty;
        }
        currentScale = ts;
        currentTranslationY = ty;
        currentTranslationX = tx;
        containerView.invalidate();
    } else {
        if (animationStartTime != 0) {
            translationX = animateToX;
            translationY = animateToY;
            scale = animateToScale;
            animationStartTime = 0;
            if (currentEditMode == 1) {
                photoCropView.setAnimationProgress(1);
            }
            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();
                }
                containerView.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 (currentEditMode == 0 && scale == 1 && aty != -1 && !zoomAnimation) {
        float maxValue = getContainerViewHeight() / 4.0f;
        backgroundDrawable
                .setAlpha((int) Math.max(127, 255 * (1.0f - (Math.min(Math.abs(aty), maxValue) / maxValue))));
    } else {
        backgroundDrawable.setAlpha(255);
    }

    ImageReceiver sideImage = null;
    if (currentEditMode == 0) {
        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 && currentEditMode == 0) {
        alpha = Math.min(1.0f, (translateX - maxX) / canvas.getWidth());
        scaleDiff = alpha * 0.3f;
        alpha = 1.0f - alpha;
        translateX = maxX;
    }
    boolean drawTextureView = Build.VERSION.SDK_INT >= 16 && aspectRatioFrameLayout != null
            && aspectRatioFrameLayout.getVisibility() == View.VISIBLE;
    if (centerImage.hasBitmapImage()) {
        canvas.save();
        canvas.translate(getContainerViewWidth() / 2 + getAdditionX(),
                getContainerViewHeight() / 2 + getAdditionY());
        canvas.translate(translateX, currentTranslationY);
        canvas.scale(currentScale - scaleDiff, currentScale - scaleDiff);

        if (currentEditMode == 1) {
            photoCropView.setBitmapParams(currentScale, translateX, currentTranslationY);
        }

        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;
                containerView.invalidate();
                if (videoCrossfadeAlpha > 1.0f) {
                    videoCrossfadeAlpha = 1.0f;
                }
            }
        }
        canvas.restore();
    }
    if (!drawTextureView && (videoPlayerControlFrameLayout == null
            || videoPlayerControlFrameLayout.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:org.telegram.ui.PassportActivity.java

private void createIdentityInterface(final Context context) {
    languageMap = new HashMap<>();
    try {//from w  w w. jav a2s . c  o  m
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(context.getResources().getAssets().open("countries.txt")));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] args = line.split(";");
            languageMap.put(args[1], args[2]);
        }
        reader.close();
    } catch (Exception e) {
        FileLog.e(e);
    }

    topErrorCell = new TextInfoPrivacyCell(context);
    topErrorCell.setBackgroundDrawable(
            Theme.getThemedDrawable(context, R.drawable.greydivider_top, Theme.key_windowBackgroundGrayShadow));
    topErrorCell.setPadding(0, AndroidUtilities.dp(7), 0, 0);
    linearLayout2.addView(topErrorCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    checkTopErrorCell(true);

    if (currentDocumentsType != null) {
        headerCell = new HeaderCell(context);
        if (documentOnly) {
            headerCell.setText(LocaleController.getString("PassportDocuments", R.string.PassportDocuments));
        } else {
            headerCell.setText(LocaleController.getString("PassportRequiredDocuments",
                    R.string.PassportRequiredDocuments));
        }
        headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        linearLayout2.addView(headerCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        frontLayout = new LinearLayout(context);
        frontLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.addView(frontLayout,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        uploadFrontCell = new TextDetailSettingsCell(context);
        uploadFrontCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        linearLayout2.addView(uploadFrontCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadFrontCell.setOnClickListener(v -> {
            uploadingFileType = UPLOADING_TYPE_FRONT;
            openAttachMenu();
        });

        reverseLayout = new LinearLayout(context);
        reverseLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.addView(reverseLayout,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        boolean divider = currentDocumentsType.selfie_required;

        uploadReverseCell = new TextDetailSettingsCell(context);
        uploadReverseCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        uploadReverseCell.setTextAndValue(
                LocaleController.getString("PassportReverseSide", R.string.PassportReverseSide),
                LocaleController.getString("PassportReverseSideInfo", R.string.PassportReverseSideInfo),
                divider);
        linearLayout2.addView(uploadReverseCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadReverseCell.setOnClickListener(v -> {
            uploadingFileType = UPLOADING_TYPE_REVERSE;
            openAttachMenu();
        });

        if (currentDocumentsType.selfie_required) {
            selfieLayout = new LinearLayout(context);
            selfieLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout2.addView(selfieLayout,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            uploadSelfieCell = new TextDetailSettingsCell(context);
            uploadSelfieCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
            uploadSelfieCell.setTextAndValue(
                    LocaleController.getString("PassportSelfie", R.string.PassportSelfie),
                    LocaleController.getString("PassportSelfieInfo", R.string.PassportSelfieInfo),
                    currentType.translation_required);
            linearLayout2.addView(uploadSelfieCell,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadSelfieCell.setOnClickListener(v -> {
                uploadingFileType = UPLOADING_TYPE_SELFIE;
                openAttachMenu();
            });
        }

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(
                Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(
                LocaleController.getString("PassportPersonalUploadInfo", R.string.PassportPersonalUploadInfo));
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        if (currentDocumentsType.translation_required) {
            headerCell = new HeaderCell(context);
            headerCell.setText(LocaleController.getString("PassportTranslation", R.string.PassportTranslation));
            headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(headerCell,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            translationLayout = new LinearLayout(context);
            translationLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout2.addView(translationLayout,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            uploadTranslationCell = new TextSettingsCell(context);
            uploadTranslationCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
            linearLayout2.addView(uploadTranslationCell,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadTranslationCell.setOnClickListener(v -> {
                uploadingFileType = UPLOADING_TYPE_TRANSLATION;
                openAttachMenu();
            });

            bottomCellTranslation = new TextInfoPrivacyCell(context);
            bottomCellTranslation.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider,
                    Theme.key_windowBackgroundGrayShadow));

            if (currentBotId != 0) {
                noAllTranslationErrorText = LocaleController.getString("PassportAddTranslationUploadInfo",
                        R.string.PassportAddTranslationUploadInfo);
            } else {
                if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypePassport) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddPassportInfo",
                            R.string.PassportAddPassportInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeInternalPassport) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddInternalPassportInfo",
                            R.string.PassportAddInternalPassportInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeIdentityCard) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddIdentityCardInfo",
                            R.string.PassportAddIdentityCardInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeDriverLicense) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddDriverLicenceInfo",
                            R.string.PassportAddDriverLicenceInfo);
                } else {
                    noAllTranslationErrorText = "";
                }
            }

            CharSequence text = noAllTranslationErrorText;
            if (documentsErrors != null) {
                String errorText;
                if ((errorText = documentsErrors.get("translation_all")) != null) {
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(errorText);
                    stringBuilder.append("\n\n");
                    stringBuilder.append(noAllTranslationErrorText);
                    text = stringBuilder;
                    stringBuilder.setSpan(
                            new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)), 0,
                            errorText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    errorsValues.put("translation_all", "");
                }
            }
            bottomCellTranslation.setText(text);
            linearLayout2.addView(bottomCellTranslation,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        }
    } else if (Build.VERSION.SDK_INT >= 18) {
        scanDocumentCell = new TextSettingsCell(context);
        scanDocumentCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        scanDocumentCell.setText(
                LocaleController.getString("PassportScanPassport", R.string.PassportScanPassport), false);
        linearLayout2.addView(scanDocumentCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        scanDocumentCell.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= 23 && getParentActivity()
                    .checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA }, 22);
                return;
            }
            MrzCameraActivity fragment = new MrzCameraActivity();
            fragment.setDelegate(result -> {
                if (!TextUtils.isEmpty(result.firstName)) {
                    inputFields[FIELD_NAME].setText(result.firstName);
                }
                if (!TextUtils.isEmpty(result.middleName)) {
                    inputFields[FIELD_MIDNAME].setText(result.middleName);
                }
                if (!TextUtils.isEmpty(result.lastName)) {
                    inputFields[FIELD_SURNAME].setText(result.lastName);
                }
                if (result.gender != MrzRecognizer.Result.GENDER_UNKNOWN) {
                    switch (result.gender) {
                    case MrzRecognizer.Result.GENDER_MALE:
                        currentGender = "male";
                        inputFields[FIELD_GENDER]
                                .setText(LocaleController.getString("PassportMale", R.string.PassportMale));
                        break;
                    case MrzRecognizer.Result.GENDER_FEMALE:
                        currentGender = "female";
                        inputFields[FIELD_GENDER]
                                .setText(LocaleController.getString("PassportFemale", R.string.PassportFemale));
                        break;
                    }
                }
                if (!TextUtils.isEmpty(result.nationality)) {
                    currentCitizeship = result.nationality;
                    String country = languageMap.get(currentCitizeship);
                    if (country != null) {
                        inputFields[FIELD_CITIZENSHIP].setText(country);
                    }
                }
                if (!TextUtils.isEmpty(result.issuingCountry)) {
                    currentResidence = result.issuingCountry;
                    String country = languageMap.get(currentResidence);
                    if (country != null) {
                        inputFields[FIELD_RESIDENCE].setText(country);
                    }
                }
                if (result.birthDay > 0 && result.birthMonth > 0 && result.birthYear > 0) {
                    inputFields[FIELD_BIRTHDAY].setText(String.format(Locale.US, "%02d.%02d.%d",
                            result.birthDay, result.birthMonth, result.birthYear));
                }
            });
            presentFragment(fragment);
        });

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(
                Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(
                LocaleController.getString("PassportScanPassportInfo", R.string.PassportScanPassportInfo));
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    headerCell = new HeaderCell(context);
    if (documentOnly) {
        headerCell.setText(LocaleController.getString("PassportDocument", R.string.PassportDocument));
    } else {
        headerCell.setText(LocaleController.getString("PassportPersonal", R.string.PassportPersonal));
    }
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    int count = currentDocumentsType != null ? FIELD_IDENTITY_COUNT : FIELD_IDENTITY_NODOC_COUNT;
    inputFields = new EditTextBoldCursor[count];

    for (int a = 0; a < count; a++) {
        final EditTextBoldCursor field = new EditTextBoldCursor(context);
        inputFields[a] = field;

        ViewGroup container = new FrameLayout(context) {

            private StaticLayout errorLayout;
            private float offsetX;

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int width = MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(34);
                errorLayout = field.getErrorLayout(width);
                if (errorLayout != null) {
                    int lineCount = errorLayout.getLineCount();
                    if (lineCount > 1) {
                        int height = AndroidUtilities.dp(64)
                                + (errorLayout.getLineBottom(lineCount - 1) - errorLayout.getLineBottom(0));
                        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
                    }
                    if (LocaleController.isRTL) {
                        float maxW = 0;
                        for (int a = 0; a < lineCount; a++) {
                            float l = errorLayout.getLineLeft(a);
                            if (l != 0) {
                                offsetX = 0;
                                break;
                            }
                            maxW = Math.max(maxW, errorLayout.getLineWidth(a));
                            if (a == lineCount - 1) {
                                offsetX = width - maxW;
                            }
                        }
                    }
                }
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                if (errorLayout != null) {
                    canvas.save();
                    canvas.translate(AndroidUtilities.dp(21) + offsetX,
                            field.getLineY() + AndroidUtilities.dp(3));
                    errorLayout.draw(canvas);
                    canvas.restore();
                }
            }
        };
        container.setWillNotDraw(false);
        linearLayout2.addView(container, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 64));
        container.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));

        if (a == count - 1) {
            extraBackgroundView = new View(context);
            extraBackgroundView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(extraBackgroundView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 6));
        }

        if (documentOnly && currentDocumentsType != null && a < FIELD_CARDNUMBER) {
            container.setVisibility(View.GONE);
            if (extraBackgroundView != null) {
                extraBackgroundView.setVisibility(View.GONE);
            }
        }

        inputFields[a].setTag(a);
        inputFields[a].setSupportRtlHint(true);
        inputFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        inputFields[a].setHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
        inputFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        inputFields[a].setTransformHintToHeader(true);
        inputFields[a].setBackgroundDrawable(null);
        inputFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setCursorSize(AndroidUtilities.dp(20));
        inputFields[a].setCursorWidth(1.5f);
        inputFields[a].setLineColors(Theme.getColor(Theme.key_windowBackgroundWhiteInputField),
                Theme.getColor(Theme.key_windowBackgroundWhiteInputFieldActivated),
                Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        if (a == FIELD_CITIZENSHIP || a == FIELD_RESIDENCE) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    CountrySelectActivity fragment = new CountrySelectActivity(false);
                    fragment.setCountrySelectActivityDelegate((name, shortName) -> {
                        int field12 = (Integer) v.getTag();
                        final EditTextBoldCursor editText = inputFields[field12];
                        if (field12 == FIELD_CITIZENSHIP) {
                            currentCitizeship = shortName;
                        } else {
                            currentResidence = shortName;
                        }
                        editText.setText(name);
                    });
                    presentFragment(fragment);
                }
                return true;
            });
            inputFields[a].setInputType(0);
        } else if (a == FIELD_BIRTHDAY || a == FIELD_EXPIRE) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int monthOfYear = calendar.get(Calendar.MONTH);
                    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
                    try {
                        final EditTextBoldCursor field1 = (EditTextBoldCursor) v;
                        int num = (Integer) field1.getTag();
                        int minYear;
                        int maxYear;
                        int currentYearDiff;
                        String title;
                        if (num == FIELD_EXPIRE) {
                            title = LocaleController.getString("PassportSelectExpiredDate",
                                    R.string.PassportSelectExpiredDate);
                            minYear = 0;
                            maxYear = 20;
                            currentYearDiff = 0;
                        } else {
                            title = LocaleController.getString("PassportSelectBithdayDate",
                                    R.string.PassportSelectBithdayDate);
                            minYear = -120;
                            maxYear = 0;
                            currentYearDiff = -18;
                        }
                        int selectedDay = -1;
                        int selectedMonth = -1;
                        int selectedYear = -1;
                        String args[] = field1.getText().toString().split("\\.");
                        if (args.length == 3) {
                            selectedDay = Utilities.parseInt(args[0]);
                            selectedMonth = Utilities.parseInt(args[1]);
                            selectedYear = Utilities.parseInt(args[2]);
                        }
                        AlertDialog.Builder builder = AlertsCreator.createDatePickerDialog(context, minYear,
                                maxYear, currentYearDiff, selectedDay, selectedMonth, selectedYear, title,
                                num == FIELD_EXPIRE, (year1, month, dayOfMonth1) -> {
                                    if (num == FIELD_EXPIRE) {
                                        currentExpireDate[0] = year1;
                                        currentExpireDate[1] = month + 1;
                                        currentExpireDate[2] = dayOfMonth1;
                                    }
                                    field1.setText(String.format(Locale.US, "%02d.%02d.%d", dayOfMonth1,
                                            month + 1, year1));
                                });
                        if (num == FIELD_EXPIRE) {
                            builder.setNegativeButton(LocaleController.getString("PassportSelectNotExpire",
                                    R.string.PassportSelectNotExpire), (dialog, which) -> {
                                        currentExpireDate[0] = currentExpireDate[1] = currentExpireDate[2] = 0;
                                        field1.setText(LocaleController.getString("PassportNoExpireDate",
                                                R.string.PassportNoExpireDate));
                                    });
                        }
                        showDialog(builder.create());
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            });
            inputFields[a].setInputType(0);
            inputFields[a].setFocusable(false);
        } else if (a == FIELD_GENDER) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(
                            LocaleController.getString("PassportSelectGender", R.string.PassportSelectGender));
                    builder.setItems(
                            new CharSequence[] {
                                    LocaleController.getString("PassportMale", R.string.PassportMale),
                                    LocaleController.getString("PassportFemale", R.string.PassportFemale) },
                            (dialogInterface, i) -> {
                                if (i == 0) {
                                    currentGender = "male";
                                    inputFields[FIELD_GENDER].setText(
                                            LocaleController.getString("PassportMale", R.string.PassportMale));
                                } else if (i == 1) {
                                    currentGender = "female";
                                    inputFields[FIELD_GENDER].setText(LocaleController
                                            .getString("PassportFemale", R.string.PassportFemale));
                                }
                            });
                    builder.setPositiveButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                }
                return true;
            });
            inputFields[a].setInputType(0);
            inputFields[a].setFocusable(false);
        } else {
            inputFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
            inputFields[a].setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        }
        String value;
        final String key;
        HashMap<String, String> values;
        switch (a) {
        case FIELD_NAME:
            if (currentType.native_names) {
                inputFields[a].setHintText(
                        LocaleController.getString("PassportNameLatin", R.string.PassportNameLatin));
            } else {
                inputFields[a].setHintText(LocaleController.getString("PassportName", R.string.PassportName));
            }
            key = "first_name";
            values = currentValues;
            break;
        case FIELD_MIDNAME:
            if (currentType.native_names) {
                inputFields[a].setHintText(
                        LocaleController.getString("PassportMidnameLatin", R.string.PassportMidnameLatin));
            } else {
                inputFields[a]
                        .setHintText(LocaleController.getString("PassportMidname", R.string.PassportMidname));
            }
            key = "middle_name";
            values = currentValues;
            break;
        case FIELD_SURNAME:
            if (currentType.native_names) {
                inputFields[a].setHintText(
                        LocaleController.getString("PassportSurnameLatin", R.string.PassportSurnameLatin));
            } else {
                inputFields[a]
                        .setHintText(LocaleController.getString("PassportSurname", R.string.PassportSurname));
            }
            key = "last_name";
            values = currentValues;
            break;
        case FIELD_BIRTHDAY:
            inputFields[a]
                    .setHintText(LocaleController.getString("PassportBirthdate", R.string.PassportBirthdate));
            key = "birth_date";
            values = currentValues;
            break;
        case FIELD_GENDER:
            inputFields[a].setHintText(LocaleController.getString("PassportGender", R.string.PassportGender));
            key = "gender";
            values = currentValues;
            break;
        case FIELD_CITIZENSHIP:
            inputFields[a].setHintText(
                    LocaleController.getString("PassportCitizenship", R.string.PassportCitizenship));
            key = "country_code";
            values = currentValues;
            break;
        case FIELD_RESIDENCE:
            inputFields[a]
                    .setHintText(LocaleController.getString("PassportResidence", R.string.PassportResidence));
            key = "residence_country_code";
            values = currentValues;
            break;
        case FIELD_CARDNUMBER:
            inputFields[a].setHintText(
                    LocaleController.getString("PassportDocumentNumber", R.string.PassportDocumentNumber));
            key = "document_no";
            values = currentDocumentValues;
            break;
        case FIELD_EXPIRE:
            inputFields[a].setHintText(LocaleController.getString("PassportExpired", R.string.PassportExpired));
            key = "expiry_date";
            values = currentDocumentValues;
            break;
        default:
            continue;
        }
        setFieldValues(values, inputFields[a], key);
        inputFields[a].setSelection(inputFields[a].length());
        if (a == FIELD_NAME || a == FIELD_SURNAME || a == FIELD_MIDNAME) {
            inputFields[a].addTextChangedListener(new TextWatcher() {

                private boolean ignore;

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (ignore) {
                        return;
                    }
                    int num = (Integer) field.getTag();
                    boolean error = false;
                    for (int a = 0; a < s.length(); a++) {
                        char ch = s.charAt(a);
                        if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'
                                || ch == ' ' || ch == '\'' || ch == ',' || ch == '.' || ch == '&' || ch == '-'
                                || ch == '/')) {
                            error = true;
                            break;
                        }
                    }
                    if (error && !allowNonLatinName) {
                        field.setErrorText(LocaleController.getString("PassportUseLatinOnly",
                                R.string.PassportUseLatinOnly));
                    } else {
                        nonLatinNames[num] = error;
                        checkFieldForError(field, key, s, false);
                    }
                }
            });
        } else {
            inputFields[a].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    checkFieldForError(field, key, s, values == currentDocumentValues);
                    int field12 = (Integer) field.getTag();
                    final EditTextBoldCursor editText = inputFields[field12];
                    if (field12 == FIELD_RESIDENCE) {
                        checkNativeFields(true);
                    }
                }
            });
        }

        inputFields[a].setPadding(0, 0, 0, 0);
        inputFields[a]
                .setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
        container.addView(inputFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 21, 0, 21, 0));

        inputFields[a].setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_NEXT) {
                int num = (Integer) textView.getTag();
                num++;
                if (num < inputFields.length) {
                    if (inputFields[num].isFocusable()) {
                        inputFields[num].requestFocus();
                    } else {
                        inputFields[num]
                                .dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0));
                        textView.clearFocus();
                        AndroidUtilities.hideKeyboard(textView);
                    }
                }
                return true;
            }
            return false;
        });
    }

    sectionCell2 = new ShadowSectionCell(context);
    linearLayout2.addView(sectionCell2,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    headerCell = new HeaderCell(context);
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    inputExtraFields = new EditTextBoldCursor[FIELD_NATIVE_COUNT];
    for (int a = 0; a < FIELD_NATIVE_COUNT; a++) {
        final EditTextBoldCursor field = new EditTextBoldCursor(context);
        inputExtraFields[a] = field;

        ViewGroup container = new FrameLayout(context) {

            private StaticLayout errorLayout;
            private float offsetX;

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int width = MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(34);
                errorLayout = field.getErrorLayout(width);
                if (errorLayout != null) {
                    int lineCount = errorLayout.getLineCount();
                    if (lineCount > 1) {
                        int height = AndroidUtilities.dp(64)
                                + (errorLayout.getLineBottom(lineCount - 1) - errorLayout.getLineBottom(0));
                        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
                    }
                    if (LocaleController.isRTL) {
                        float maxW = 0;
                        for (int a = 0; a < lineCount; a++) {
                            float l = errorLayout.getLineLeft(a);
                            if (l != 0) {
                                offsetX = 0;
                                break;
                            }
                            maxW = Math.max(maxW, errorLayout.getLineWidth(a));
                            if (a == lineCount - 1) {
                                offsetX = width - maxW;
                            }
                        }
                    }
                }
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                if (errorLayout != null) {
                    canvas.save();
                    canvas.translate(AndroidUtilities.dp(21) + offsetX,
                            field.getLineY() + AndroidUtilities.dp(3));
                    errorLayout.draw(canvas);
                    canvas.restore();
                }
            }
        };
        container.setWillNotDraw(false);
        linearLayout2.addView(container, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 64));
        container.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));

        if (a == FIELD_NATIVE_COUNT - 1) {
            extraBackgroundView2 = new View(context);
            extraBackgroundView2.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(extraBackgroundView2,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 6));
        }

        inputExtraFields[a].setTag(a);
        inputExtraFields[a].setSupportRtlHint(true);
        inputExtraFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        inputExtraFields[a].setHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
        inputExtraFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputExtraFields[a].setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        inputExtraFields[a].setTransformHintToHeader(true);
        inputExtraFields[a].setBackgroundDrawable(null);
        inputExtraFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputExtraFields[a].setCursorSize(AndroidUtilities.dp(20));
        inputExtraFields[a].setCursorWidth(1.5f);
        inputExtraFields[a].setLineColors(Theme.getColor(Theme.key_windowBackgroundWhiteInputField),
                Theme.getColor(Theme.key_windowBackgroundWhiteInputFieldActivated),
                Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        inputExtraFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        inputExtraFields[a].setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);

        String value;
        final String key;
        HashMap<String, String> values;
        switch (a) {
        case FIELD_NATIVE_NAME:
            key = "first_name_native";
            values = currentValues;
            break;
        case FIELD_NATIVE_MIDNAME:
            key = "middle_name_native";
            values = currentValues;
            break;
        case FIELD_NATIVE_SURNAME:
            key = "last_name_native";
            values = currentValues;
            break;
        default:
            continue;
        }
        setFieldValues(values, inputExtraFields[a], key);
        inputExtraFields[a].setSelection(inputExtraFields[a].length());
        if (a == FIELD_NATIVE_NAME || a == FIELD_NATIVE_SURNAME || a == FIELD_NATIVE_MIDNAME) {
            inputExtraFields[a].addTextChangedListener(new TextWatcher() {

                private boolean ignore;

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (ignore) {
                        return;
                    }
                    checkFieldForError(field, key, s, false);
                }
            });
        }

        inputExtraFields[a].setPadding(0, 0, 0, 0);
        inputExtraFields[a]
                .setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
        container.addView(inputExtraFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 21, 0, 21, 0));

        inputExtraFields[a].setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_NEXT) {
                int num = (Integer) textView.getTag();
                num++;
                if (num < inputExtraFields.length) {
                    if (inputExtraFields[num].isFocusable()) {
                        inputExtraFields[num].requestFocus();
                    } else {
                        inputExtraFields[num]
                                .dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0));
                        textView.clearFocus();
                        AndroidUtilities.hideKeyboard(textView);
                    }
                }
                return true;
            }
            return false;
        });
    }

    nativeInfoCell = new TextInfoPrivacyCell(context);
    linearLayout2.addView(nativeInfoCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    if ((currentBotId != 0 || currentDocumentsType == null) && currentTypeValue != null && !documentOnly
            || currentDocumentsTypeValue != null) {
        if (currentDocumentsTypeValue != null) {
            addDocumentViews(currentDocumentsTypeValue.files);
            if (currentDocumentsTypeValue.front_side instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.front_side,
                        UPLOADING_TYPE_FRONT);
            }
            if (currentDocumentsTypeValue.reverse_side instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.reverse_side,
                        UPLOADING_TYPE_REVERSE);
            }
            if (currentDocumentsTypeValue.selfie instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.selfie,
                        UPLOADING_TYPE_SELFIE);
            }
            addTranslationDocumentViews(currentDocumentsTypeValue.translation);
        }

        TextSettingsCell settingsCell1 = new TextSettingsCell(context);
        settingsCell1.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        settingsCell1.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        if (currentDocumentsType == null) {
            settingsCell1.setText(LocaleController.getString("PassportDeleteInfo", R.string.PassportDeleteInfo),
                    false);
        } else {
            settingsCell1.setText(
                    LocaleController.getString("PassportDeleteDocument", R.string.PassportDeleteDocument),
                    false);
        }
        linearLayout2.addView(settingsCell1,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        settingsCell1.setOnClickListener(v -> createDocumentDeleteAlert());

        nativeInfoCell.setBackgroundDrawable(
                Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));

        sectionCell = new ShadowSectionCell(context);
        sectionCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        linearLayout2.addView(sectionCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    } else {
        nativeInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
    }

    updateInterfaceStringsForDocumentType();
    checkNativeFields(false);
}

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

private void drawContent(Canvas canvas) {
    if (photoAnimationInProgress == 1 || !isPhotoVisible && photoAnimationInProgress != 2) {
        return;//from  w  ww  . j a  v a 2 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);
    }/* www.  j a va2  s. c  o m*/
    // 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  ww w .  ja v  a  2 s.c  o m*/
    // 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);
    //  /*  www  . j  av a2  s . c o  m*/
    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);
    }/*from   w ww  . j  av a 2 s  .com*/
    // 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);
    }/*from   www  .  j  a  v 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());
        }
        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:net.bluehack.ui.PhotoViewer.java

public void setParentActivity(final Activity activity) {
    if (parentActivity == activity) {
        return;/*  w  w w  . j ava  2 s .c  o  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;//w  w  w. j ava  2s .  com
    }
    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;
        }
    });
}