Search in sources :

Example 1 with ActionBarPopupWindow

use of org.telegram.ui.ActionBar.ActionBarPopupWindow in project Telegram-FOSS by Telegram-FOSS-Team.

the class BackButtonMenu method show.

public static ActionBarPopupWindow show(BaseFragment thisFragment, View backButton, long currentDialogId) {
    if (thisFragment == null) {
        return null;
    }
    final ActionBarLayout parentLayout = thisFragment.getParentLayout();
    final Context context = thisFragment.getParentActivity();
    final View fragmentView = thisFragment.getFragmentView();
    if (parentLayout == null || context == null || fragmentView == null) {
        return null;
    }
    ArrayList<PulledDialog> dialogs = getStackedHistoryDialogs(thisFragment, currentDialogId);
    if (dialogs.size() <= 0) {
        return null;
    }
    ActionBarPopupWindow.ActionBarPopupWindowLayout layout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(context);
    android.graphics.Rect backgroundPaddings = new Rect();
    Drawable shadowDrawable = thisFragment.getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate();
    shadowDrawable.getPadding(backgroundPaddings);
    layout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground));
    AtomicReference<ActionBarPopupWindow> scrimPopupWindowRef = new AtomicReference<>();
    for (int i = 0; i < dialogs.size(); ++i) {
        final PulledDialog pDialog = dialogs.get(i);
        final TLRPC.Chat chat = pDialog.chat;
        final TLRPC.User user = pDialog.user;
        FrameLayout cell = new FrameLayout(context);
        cell.setMinimumWidth(AndroidUtilities.dp(200));
        BackupImageView imageView = new BackupImageView(context);
        imageView.setRoundRadius(AndroidUtilities.dp(32));
        cell.addView(imageView, LayoutHelper.createFrameRelatively(32, 32, Gravity.START | Gravity.CENTER_VERTICAL, 13, 0, 0, 0));
        TextView titleView = new TextView(context);
        titleView.setLines(1);
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        titleView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem));
        titleView.setEllipsize(TextUtils.TruncateAt.END);
        cell.addView(titleView, LayoutHelper.createFrameRelatively(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 59, 0, 12, 0));
        AvatarDrawable avatarDrawable = new AvatarDrawable();
        avatarDrawable.setSmallSize(true);
        if (chat != null) {
            avatarDrawable.setInfo(chat);
            imageView.setImage(ImageLocation.getForChat(chat, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, chat);
            titleView.setText(chat.title);
        } else if (user != null) {
            String name;
            if (pDialog.activity == ChatActivity.class && UserObject.isUserSelf(user)) {
                name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
                avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED);
                imageView.setImageDrawable(avatarDrawable);
            } else if (UserObject.isReplyUser(user)) {
                name = LocaleController.getString("RepliesTitle", R.string.RepliesTitle);
                avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES);
                imageView.setImageDrawable(avatarDrawable);
            } else if (UserObject.isDeleted(user)) {
                name = LocaleController.getString("HiddenName", R.string.HiddenName);
                avatarDrawable.setInfo(user);
                imageView.setImage(ImageLocation.getForUser(user, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, user);
            } else {
                name = UserObject.getUserName(user);
                avatarDrawable.setInfo(user);
                imageView.setImage(ImageLocation.getForUser(user, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, user);
            }
            titleView.setText(name);
        }
        cell.setBackground(Theme.getSelectorDrawable(Theme.getColor(Theme.key_listSelector), false));
        cell.setOnClickListener(e2 -> {
            if (scrimPopupWindowRef.get() != null) {
                scrimPopupWindowRef.getAndSet(null).dismiss();
            }
            if (pDialog.stackIndex >= 0) {
                Long nextFragmentDialogId = null;
                if (parentLayout == null || parentLayout.fragmentsStack == null || pDialog.stackIndex >= parentLayout.fragmentsStack.size()) {
                    nextFragmentDialogId = null;
                } else {
                    BaseFragment nextFragment = parentLayout.fragmentsStack.get(pDialog.stackIndex);
                    if (nextFragment instanceof ChatActivity) {
                        nextFragmentDialogId = ((ChatActivity) nextFragment).getDialogId();
                    } else if (nextFragment instanceof ProfileActivity) {
                        nextFragmentDialogId = ((ProfileActivity) nextFragment).getDialogId();
                    }
                }
                if (nextFragmentDialogId != null && nextFragmentDialogId != pDialog.dialogId) {
                    for (int j = parentLayout.fragmentsStack.size() - 2; j > pDialog.stackIndex; --j) {
                        parentLayout.removeFragmentFromStack(j);
                    }
                } else {
                    if (parentLayout != null && parentLayout.fragmentsStack != null) {
                        for (int j = parentLayout.fragmentsStack.size() - 2; j > pDialog.stackIndex; --j) {
                            if (j >= 0 && j < parentLayout.fragmentsStack.size()) {
                                parentLayout.removeFragmentFromStack(j);
                            }
                        }
                        if (pDialog.stackIndex < parentLayout.fragmentsStack.size()) {
                            parentLayout.showFragment(pDialog.stackIndex);
                            parentLayout.closeLastFragment(true);
                            return;
                        }
                    }
                }
            }
            goToPulledDialog(thisFragment, pDialog);
        });
        layout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
    }
    ActionBarPopupWindow scrimPopupWindow = new ActionBarPopupWindow(layout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
    scrimPopupWindowRef.set(scrimPopupWindow);
    scrimPopupWindow.setPauseNotifications(true);
    scrimPopupWindow.setDismissAnimationDuration(220);
    scrimPopupWindow.setOutsideTouchable(true);
    scrimPopupWindow.setClippingEnabled(true);
    scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation);
    scrimPopupWindow.setFocusable(true);
    layout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
    scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
    scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    scrimPopupWindow.getContentView().setFocusableInTouchMode(true);
    layout.setFitItems(true);
    int popupX = AndroidUtilities.dp(8) - backgroundPaddings.left;
    if (AndroidUtilities.isTablet()) {
        int[] location = new int[2];
        fragmentView.getLocationInWindow(location);
        popupX += location[0];
    }
    int popupY = (int) (backButton.getBottom() - backgroundPaddings.top - AndroidUtilities.dp(8));
    scrimPopupWindow.showAtLocation(fragmentView, Gravity.LEFT | Gravity.TOP, popupX, popupY);
    try {
        fragmentView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
    } catch (Exception ignore) {
    }
    return scrimPopupWindow;
}
Also used : Rect(android.graphics.Rect) ChatActivity(org.telegram.ui.ChatActivity) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) TextView(android.widget.TextView) Context(android.content.Context) Rect(android.graphics.Rect) ProfileActivity(org.telegram.ui.ProfileActivity) Drawable(android.graphics.drawable.Drawable) AtomicReference(java.util.concurrent.atomic.AtomicReference) View(android.view.View) TextView(android.widget.TextView) FrameLayout(android.widget.FrameLayout)

Example 2 with ActionBarPopupWindow

use of org.telegram.ui.ActionBar.ActionBarPopupWindow in project Telegram-FOSS by Telegram-FOSS-Team.

the class ChatActivityEnterView method onSendLongClick.

private boolean onSendLongClick(View view) {
    if (isInScheduleMode()) {
        return false;
    }
    boolean self = parentFragment != null && UserObject.isUserSelf(parentFragment.getCurrentUser());
    if (sendPopupLayout == null) {
        sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity, resourcesProvider);
        sendPopupLayout.setAnimationEnabled(false);
        sendPopupLayout.setOnTouchListener(new OnTouchListener() {

            private android.graphics.Rect popupRect = new android.graphics.Rect();

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
                        v.getHitRect(popupRect);
                        if (!popupRect.contains((int) event.getX(), (int) event.getY())) {
                            sendPopupWindow.dismiss();
                        }
                    }
                }
                return false;
            }
        });
        sendPopupLayout.setDispatchKeyEventListener(keyEvent -> {
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
                sendPopupWindow.dismiss();
            }
        });
        sendPopupLayout.setShownFromBotton(false);
        boolean scheduleButtonValue = parentFragment != null && parentFragment.canScheduleMessage();
        boolean sendWithoutSoundButtonValue = !(self || slowModeTimer > 0 && !isInScheduleMode());
        if (scheduleButtonValue) {
            ActionBarMenuSubItem scheduleButton = new ActionBarMenuSubItem(getContext(), true, !sendWithoutSoundButtonValue, resourcesProvider);
            if (self) {
                scheduleButton.setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule);
            } else {
                scheduleButton.setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_schedule);
            }
            scheduleButton.setMinimumWidth(AndroidUtilities.dp(196));
            scheduleButton.setOnClickListener(v -> {
                if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
                    sendPopupWindow.dismiss();
                }
                AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), this::sendMessageInternal, resourcesProvider);
            });
            sendPopupLayout.addView(scheduleButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
        }
        if (sendWithoutSoundButtonValue) {
            ActionBarMenuSubItem sendWithoutSoundButton = new ActionBarMenuSubItem(getContext(), !scheduleButtonValue, true, resourcesProvider);
            sendWithoutSoundButton.setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off);
            sendWithoutSoundButton.setMinimumWidth(AndroidUtilities.dp(196));
            sendWithoutSoundButton.setOnClickListener(v -> {
                if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
                    sendPopupWindow.dismiss();
                }
                sendMessageInternal(false, 0);
            });
            sendPopupLayout.addView(sendWithoutSoundButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
        }
        sendPopupLayout.setupRadialSelectors(getThemedColor(Theme.key_dialogButtonSelector));
        sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) {

            @Override
            public void dismiss() {
                super.dismiss();
                sendButton.invalidate();
            }
        };
        sendPopupWindow.setAnimationEnabled(false);
        sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2);
        sendPopupWindow.setOutsideTouchable(true);
        sendPopupWindow.setClippingEnabled(true);
        sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
        sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
        sendPopupWindow.getContentView().setFocusableInTouchMode(true);
        SharedConfig.removeScheduledOrNoSuoundHint();
        if (delegate != null) {
            delegate.onSendLongClick();
        }
    }
    sendPopupLayout.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), MeasureSpec.AT_MOST));
    sendPopupWindow.setFocusable(true);
    view.getLocationInWindow(location);
    int y;
    if (keyboardVisible && ChatActivityEnterView.this.getMeasuredHeight() > AndroidUtilities.dp(topView != null && topView.getVisibility() == VISIBLE ? 48 + 58 : 58)) {
        y = location[1] + view.getMeasuredHeight();
    } else {
        y = location[1] - sendPopupLayout.getMeasuredHeight() - AndroidUtilities.dp(2);
    }
    sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - sendPopupLayout.getMeasuredWidth() + AndroidUtilities.dp(8), y);
    sendPopupWindow.dimBehind();
    sendButton.invalidate();
    try {
        view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
    } catch (Exception ignore) {
    }
    return false;
}
Also used : Rect(android.graphics.Rect) Rect(android.graphics.Rect) ImageView(android.widget.ImageView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem)

Example 3 with ActionBarPopupWindow

use of org.telegram.ui.ActionBar.ActionBarPopupWindow in project Telegram-FOSS by Telegram-FOSS-Team.

the class ArticleViewer method showPopup.

private void showPopup(View parent, int gravity, int x, int y) {
    if (popupWindow != null && popupWindow.isShowing()) {
        popupWindow.dismiss();
        return;
    }
    if (popupLayout == null) {
        popupRect = new android.graphics.Rect();
        popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity);
        popupLayout.setPadding(AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1));
        popupLayout.setBackgroundDrawable(parentActivity.getResources().getDrawable(R.drawable.menu_copy));
        popupLayout.setAnimationEnabled(false);
        popupLayout.setOnTouchListener((v, event) -> {
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    v.getHitRect(popupRect);
                    if (!popupRect.contains((int) event.getX(), (int) event.getY())) {
                        popupWindow.dismiss();
                    }
                }
            }
            return false;
        });
        popupLayout.setDispatchKeyEventListener(keyEvent -> {
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        });
        popupLayout.setShownFromBotton(false);
        deleteView = new TextView(parentActivity);
        deleteView.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 2));
        deleteView.setGravity(Gravity.CENTER_VERTICAL);
        deleteView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
        deleteView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        deleteView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        deleteView.setText(LocaleController.getString("Copy", R.string.Copy).toUpperCase());
        deleteView.setOnClickListener(v -> {
            if (pressedLinkOwnerLayout != null) {
                AndroidUtilities.addToClipboard(pressedLinkOwnerLayout.getText());
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                    Toast.makeText(parentActivity, LocaleController.getString("TextCopied", R.string.TextCopied), Toast.LENGTH_SHORT).show();
                }
            }
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss(true);
            }
        });
        popupLayout.addView(deleteView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48));
        popupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
        popupWindow.setAnimationEnabled(false);
        popupWindow.setAnimationStyle(R.style.PopupContextAnimation);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setClippingEnabled(true);
        popupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.setOnDismissListener(() -> {
            if (pressedLinkOwnerView != null) {
                pressedLinkOwnerLayout = null;
                pressedLinkOwnerView.invalidate();
                pressedLinkOwnerView = null;
            }
        });
    }
    deleteView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem));
    if (popupLayout != null) {
        popupLayout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground));
    }
    popupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
    popupWindow.setFocusable(true);
    popupWindow.showAtLocation(parent, gravity, x, y);
    popupWindow.startAnimation();
}
Also used : Rect(android.graphics.Rect) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView)

Example 4 with ActionBarPopupWindow

use of org.telegram.ui.ActionBar.ActionBarPopupWindow in project Telegram-FOSS by Telegram-FOSS-Team.

the class PhotoViewer method setParentActivity.

public void setParentActivity(final Activity activity, Theme.ResourcesProvider resourcesProvider) {
    Theme.createChatResources(activity, false);
    this.resourcesProvider = resourcesProvider;
    currentAccount = UserConfig.selectedAccount;
    centerImage.setCurrentAccount(currentAccount);
    leftImage.setCurrentAccount(currentAccount);
    rightImage.setCurrentAccount(currentAccount);
    if (parentActivity == activity || activity == null) {
        return;
    }
    inBubbleMode = activity instanceof BubbleActivity;
    parentActivity = activity;
    activityContext = new ContextThemeWrapper(parentActivity, R.style.Theme_TMessages);
    touchSlop = ViewConfiguration.get(parentActivity).getScaledTouchSlop();
    if (progressDrawables == null) {
        final Drawable circleDrawable = ContextCompat.getDrawable(parentActivity, R.drawable.circle_big);
        progressDrawables = new Drawable[] { // PROGRESS_EMPTY
        circleDrawable, // PROGRESS_CANCEL
        ContextCompat.getDrawable(parentActivity, R.drawable.cancel_big), // PROGRESS_LOAD
        ContextCompat.getDrawable(parentActivity, R.drawable.load_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
        public boolean dispatchKeyEvent(KeyEvent event) {
            int keyCode = event.getKeyCode();
            if (!muteVideo && sendPhotoType != SELECT_TYPE_AVATAR && isCurrentVideo && videoPlayer != null && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN && (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)) {
                videoPlayer.setVolume(1.0f);
            }
            return super.dispatchKeyEvent(event);
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            if (videoPlayerControlVisible && isPlaying) {
                switch(ev.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_POINTER_DOWN:
                        AndroidUtilities.cancelRunOnUIThread(hideActionBarRunnable);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_POINTER_UP:
                        scheduleActionBarHide();
                        break;
                }
            }
            return super.dispatchTouchEvent(ev);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result;
            try {
                result = super.drawChild(canvas, child, drawingTime);
            } catch (Throwable ignore) {
                result = false;
            }
            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 (!inBubbleMode) {
                    if (AndroidUtilities.incorrectDisplaySizeFix) {
                        if (heightSize > AndroidUtilities.displaySize.y) {
                            heightSize = AndroidUtilities.displaySize.y;
                        }
                        heightSize += AndroidUtilities.statusBarHeight;
                    } else {
                        int insetBottom = insets.getStableInsetBottom();
                        if (insetBottom >= 0 && AndroidUtilities.statusBarHeight >= 0) {
                            int newSize = heightSize - AndroidUtilities.statusBarHeight - insets.getStableInsetBottom();
                            if (newSize > 0 && newSize < 4096) {
                                AndroidUtilities.displaySize.y = newSize;
                            }
                        }
                    }
                }
                int bottomInsets = insets.getSystemWindowInsetBottom();
                if (captionEditText.isPopupShowing()) {
                    bottomInsets -= containerView.getKeyboardHeight();
                }
                heightSize -= bottomInsets;
            } 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(() -> {
                        LayoutParams layoutParams = (LayoutParams) checkImageView.getLayoutParams();
                        WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE);
                        int rotation = manager.getDefaultDisplay().getRotation();
                        int newMargin = (ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(34)) / 2 + (isStatusBarVisible() ? AndroidUtilities.statusBarHeight : 0);
                        if (newMargin != layoutParams.topMargin) {
                            layoutParams.topMargin = newMargin;
                            checkImageView.setLayoutParams(layoutParams);
                        }
                        layoutParams = (LayoutParams) photosCounterView.getLayoutParams();
                        newMargin = (ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(40)) / 2 + (isStatusBarVisible() ? AndroidUtilities.statusBarHeight : 0);
                        if (layoutParams.topMargin != newMargin) {
                            layoutParams.topMargin = newMargin;
                            photosCounterView.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(true);
                    return false;
                }
                PhotoViewer.getInstance().closePhoto(true, false);
                return true;
            }
            return super.dispatchKeyEventPreIme(event);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (Build.VERSION.SDK_INT >= 21 && isVisible && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                if (animationInProgress == 1) {
                    blackPaint.setAlpha((int) (255 * animatingImageView.getAnimationProgress()));
                } else if (animationInProgress == 3) {
                    blackPaint.setAlpha((int) (255 * (1.0f - animatingImageView.getAnimationProgress())));
                } else {
                    blackPaint.setAlpha(backgroundDrawable.getAlpha());
                }
                canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
            }
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            if (parentChatActivity != null) {
                View undoView = parentChatActivity.getUndoView();
                if (undoView.getVisibility() == View.VISIBLE) {
                    canvas.save();
                    View parent = (View) undoView.getParent();
                    canvas.clipRect(parent.getX(), parent.getY(), parent.getX() + parent.getWidth(), parent.getY() + parent.getHeight());
                    canvas.translate(undoView.getX(), undoView.getY());
                    undoView.draw(canvas);
                    canvas.restore();
                    invalidate();
                }
            }
        }
    };
    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((v, insets) -> {
            int newTopInset = insets.getSystemWindowInsetTop();
            if (parentActivity instanceof LaunchActivity && (newTopInset != 0 || AndroidUtilities.isInMultiwindow) && !inBubbleMode && AndroidUtilities.statusBarHeight != newTopInset) {
                AndroidUtilities.statusBarHeight = newTopInset;
                ((LaunchActivity) parentActivity).drawerLayoutContainer.requestLayout();
            }
            WindowInsets oldInsets = (WindowInsets) lastInsets;
            lastInsets = insets;
            if (oldInsets == null || !oldInsets.toString().equals(insets.toString())) {
                if (animationInProgress == 1 || animationInProgress == 3) {
                    animatingImageView.setTranslationX(animatingImageView.getTranslationX() - getLeftInset());
                    animationValues[0][2] = animatingImageView.getTranslationX();
                }
                if (windowView != null) {
                    windowView.requestLayout();
                }
            }
            containerView.setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), 0);
            if (actionBar != null) {
                AndroidUtilities.cancelRunOnUIThread(updateContainerFlagsRunnable);
                if (isVisible && animationInProgress == 0) {
                    AndroidUtilities.runOnUIThread(updateContainerFlagsRunnable, 200);
                }
            }
            if (Build.VERSION.SDK_INT >= 30) {
                return WindowInsets.CONSUMED;
            } else {
                return insets.consumeSystemWindowInsets();
            }
        });
        containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }
    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 >= 28) {
        windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    } else {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
    }
    paintingOverlay = new PaintingOverlay(parentActivity);
    containerView.addView(paintingOverlay, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    actionBar = new ActionBar(activity) {

        @Override
        public void setAlpha(float alpha) {
            super.setAlpha(alpha);
            containerView.invalidate();
        }
    };
    actionBar.setOverlayTitleAnimation(true);
    actionBar.setTitleColor(0xffffffff);
    actionBar.setSubtitleColor(0xffffffff);
    actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
    actionBar.setOccupyStatusBar(isStatusBarVisible());
    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, false);
    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 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && parentActivity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    parentActivity.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }
                File f = null;
                final boolean isVideo;
                if (currentMessageObject != null) {
                    if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && currentMessageObject.messageOwner.media.webpage != null && currentMessageObject.messageOwner.media.webpage.document == null) {
                        TLObject fileLocation = getFileLocation(currentIndex, null);
                        f = FileLoader.getPathToAttach(fileLocation, true);
                    } else {
                        f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                    }
                    isVideo = currentMessageObject.isVideo();
                } else if (currentFileLocationVideo != null) {
                    f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), avatarsDialogId != 0 || isEvent);
                    isVideo = false;
                } else if (pageBlocksAdapter != null) {
                    f = pageBlocksAdapter.getFile(currentIndex);
                    isVideo = pageBlocksAdapter.isVideo(currentIndex);
                } else {
                    isVideo = false;
                }
                if (f != null && f.exists()) {
                    MediaController.saveFile(f.toString(), parentActivity, isVideo ? 1 : 0, null, null, () -> BulletinFactory.createSaveToGalleryBulletin(containerView, isVideo, 0xf9222222, 0xffffffff).show());
                } else {
                    showDownloadAlert();
                }
            } else if (id == gallery_menu_showall) {
                if (currentDialogId != 0) {
                    disableShowCheck = true;
                    Bundle args2 = new Bundle();
                    args2.putLong("dialog_id", currentDialogId);
                    MediaActivity mediaActivity = new MediaActivity(args2, null);
                    if (parentChatActivity != null) {
                        mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
                    }
                    closePhoto(false, false);
                    if (parentActivity instanceof LaunchActivity) {
                        ((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
                    }
                }
            } else if (id == gallery_menu_showinchat) {
                if (currentMessageObject == null) {
                    return;
                }
                Bundle args = new Bundle();
                long dialogId = currentDialogId;
                if (currentMessageObject != null) {
                    dialogId = currentMessageObject.getDialogId();
                }
                if (DialogObject.isEncryptedDialog(dialogId)) {
                    args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId));
                } else if (DialogObject.isUserDialog(dialogId)) {
                    args.putLong("user_id", dialogId);
                } else {
                    TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
                    if (chat != null && chat.migrated_to != null) {
                        args.putLong("migrated_to", dialogId);
                        dialogId = -chat.migrated_to.channel_id;
                    }
                    args.putLong("chat_id", -dialogId);
                }
                args.putInt("message_id", currentMessageObject.getId());
                NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
                if (parentActivity instanceof LaunchActivity) {
                    LaunchActivity launchActivity = (LaunchActivity) parentActivity;
                    boolean remove = launchActivity.getMainFragmentsCount() > 1 || AndroidUtilities.isTablet();
                    launchActivity.presentFragment(new ChatActivity(args), remove, true);
                }
                closePhoto(false, false);
                currentMessageObject = null;
            } else if (id == gallery_menu_send) {
                if (currentMessageObject == null || !(parentActivity instanceof LaunchActivity)) {
                    return;
                }
                ((LaunchActivity) parentActivity).switchToAccount(currentMessageObject.currentAccount, true);
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 3);
                DialogsActivity fragment = new DialogsActivity(args);
                final ArrayList<MessageObject> fmessages = new ArrayList<>();
                fmessages.add(currentMessageObject);
                final ChatActivity parentChatActivityFinal = parentChatActivity;
                fragment.setDelegate((fragment1, dids, message, param) -> {
                    if (dids.size() > 1 || dids.get(0) == UserConfig.getInstance(currentAccount).getClientUserId() || message != null) {
                        for (int a = 0; a < dids.size(); a++) {
                            long did = dids.get(a);
                            if (message != null) {
                                SendMessagesHelper.getInstance(currentAccount).sendMessage(message.toString(), did, null, null, null, true, null, null, null, true, 0, null);
                            }
                            SendMessagesHelper.getInstance(currentAccount).sendMessage(fmessages, did, false, false, true, 0);
                        }
                        fragment1.finishFragment();
                        if (parentChatActivityFinal != null) {
                            if (dids.size() == 1) {
                                parentChatActivityFinal.getUndoView().showWithAction(dids.get(0), UndoView.ACTION_FWD_MESSAGES, fmessages.size());
                            } else {
                                parentChatActivityFinal.getUndoView().showWithAction(0, UndoView.ACTION_FWD_MESSAGES, fmessages.size(), dids.size(), null, null);
                            }
                        }
                    } else {
                        long did = dids.get(0);
                        Bundle args1 = new Bundle();
                        args1.putBoolean("scrollToTopOnResume", true);
                        if (DialogObject.isEncryptedDialog(did)) {
                            args1.putInt("enc_id", DialogObject.getEncryptedChatId(did));
                        } else if (DialogObject.isUserDialog(did)) {
                            args1.putLong("user_id", did);
                        } else {
                            args1.putLong("chat_id", -did);
                        }
                        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
                        ChatActivity chatActivity = new ChatActivity(args1);
                        if (((LaunchActivity) parentActivity).presentFragment(chatActivity, true, false)) {
                            chatActivity.showFieldPanelForForward(true, fmessages);
                        } else {
                            fragment1.finishFragment();
                        }
                    }
                });
                ((LaunchActivity) parentActivity).presentFragment(fragment, false, true);
                closePhoto(false, false);
            } else if (id == gallery_menu_delete) {
                if (parentActivity == null || placeProvider == null) {
                    return;
                }
                boolean isChannel = false;
                if (currentMessageObject != null && !currentMessageObject.scheduled) {
                    long dialogId = currentMessageObject.getDialogId();
                    if (DialogObject.isChatDialog(dialogId)) {
                        isChannel = ChatObject.isChannel(MessagesController.getInstance(currentAccount).getChat(-dialogId));
                    }
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                String text = placeProvider.getDeleteMessageString();
                if (text != null) {
                    builder.setTitle(LocaleController.getString("AreYouSureDeletePhotoTitle", R.string.AreYouSureDeletePhotoTitle));
                    builder.setMessage(text);
                } else if (isEmbedVideo || currentFileLocationVideo != null && currentFileLocationVideo != currentFileLocation || currentMessageObject != null && currentMessageObject.isVideo()) {
                    builder.setTitle(LocaleController.getString("AreYouSureDeleteVideoTitle", R.string.AreYouSureDeleteVideoTitle));
                    if (isChannel) {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideoEveryone", R.string.AreYouSureDeleteVideoEveryone));
                    } else {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo", R.string.AreYouSureDeleteVideo));
                    }
                } else if (currentMessageObject != null && currentMessageObject.isGif()) {
                    builder.setTitle(LocaleController.getString("AreYouSureDeleteGIFTitle", R.string.AreYouSureDeleteGIFTitle));
                    if (isChannel) {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeleteGIFEveryone", R.string.AreYouSureDeleteGIFEveryone));
                    } else {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeleteGIF", R.string.AreYouSureDeleteGIF));
                    }
                } else {
                    builder.setTitle(LocaleController.getString("AreYouSureDeletePhotoTitle", R.string.AreYouSureDeletePhotoTitle));
                    if (isChannel) {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeletePhotoEveryone", R.string.AreYouSureDeletePhotoEveryone));
                    } else {
                        builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto));
                    }
                }
                final boolean[] deleteForAll = new boolean[1];
                if (currentMessageObject != null && !currentMessageObject.scheduled) {
                    long dialogId = currentMessageObject.getDialogId();
                    if (!DialogObject.isEncryptedDialog(dialogId)) {
                        TLRPC.Chat currentChat;
                        TLRPC.User currentUser;
                        if (DialogObject.isUserDialog(dialogId)) {
                            currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId);
                            currentChat = null;
                        } else {
                            currentUser = null;
                            currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
                        }
                        if (currentUser != null || !ChatObject.isChannel(currentChat)) {
                            boolean hasOutgoing = false;
                            int currentDate = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
                            int revokeTimeLimit;
                            if (currentUser != null) {
                                revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimePmLimit;
                            } else {
                                revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimeLimit;
                            }
                            if (currentUser != null && currentUser.id != UserConfig.getInstance(currentAccount).getClientUserId() || currentChat != null) {
                                boolean canRevokeInbox = currentUser != null && MessagesController.getInstance(currentAccount).canRevokePmInbox;
                                if ((currentMessageObject.messageOwner.action == null || currentMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && (currentMessageObject.isOut() || canRevokeInbox || ChatObject.hasAdminRights(currentChat)) && (currentDate - currentMessageObject.messageOwner.date) <= revokeTimeLimit) {
                                    FrameLayout frameLayout = new FrameLayout(parentActivity);
                                    CheckBoxCell cell = new CheckBoxCell(parentActivity, 1, resourcesProvider);
                                    cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                                    if (currentChat != null) {
                                        cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false);
                                    } else {
                                        cell.setText(LocaleController.formatString("DeleteForUser", R.string.DeleteForUser, UserObject.getFirstName(currentUser)), "", false, false);
                                    }
                                    cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
                                    frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
                                    cell.setOnClickListener(v -> {
                                        CheckBoxCell cell1 = (CheckBoxCell) v;
                                        deleteForAll[0] = !deleteForAll[0];
                                        cell1.setChecked(deleteForAll[0], true);
                                    });
                                    builder.setView(frameLayout);
                                    builder.setCustomViewOffset(9);
                                }
                            }
                        }
                    }
                }
                builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, 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<>();
                            if (slideshowMessageId != 0) {
                                arr.add(slideshowMessageId);
                            } else {
                                arr.add(obj.getId());
                            }
                            ArrayList<Long> random_ids = null;
                            TLRPC.EncryptedChat encryptedChat = null;
                            if (DialogObject.isEncryptedDialog(obj.getDialogId()) && obj.messageOwner.random_id != 0) {
                                random_ids = new ArrayList<>();
                                random_ids.add(obj.messageOwner.random_id);
                                encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(obj.getDialogId()));
                            }
                            MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat, obj.getDialogId(), deleteForAll[0], obj.scheduled);
                        }
                    } else if (!avatarsArr.isEmpty()) {
                        if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
                            return;
                        }
                        TLRPC.Message message = imagesArrMessages.get(currentIndex);
                        if (message != null) {
                            ArrayList<Integer> arr = new ArrayList<>();
                            arr.add(message.id);
                            MessagesController.getInstance(currentAccount).deleteMessages(arr, null, null, MessageObject.getDialogId(message), true, false);
                            NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.reloadDialogPhotos);
                        }
                        if (isCurrentAvatarSet()) {
                            if (avatarsDialogId > 0) {
                                MessagesController.getInstance(currentAccount).deleteUserPhoto(null);
                            } else {
                                MessagesController.getInstance(currentAccount).changeChatAvatar(-avatarsDialogId, null, null, null, 0, null, null, null, null);
                            }
                            closePhoto(false, false);
                        } else {
                            TLRPC.Photo photo = avatarsArr.get(currentIndex);
                            if (photo == null) {
                                return;
                            }
                            TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                            inputPhoto.id = photo.id;
                            inputPhoto.access_hash = photo.access_hash;
                            inputPhoto.file_reference = photo.file_reference;
                            if (inputPhoto.file_reference == null) {
                                inputPhoto.file_reference = new byte[0];
                            }
                            if (avatarsDialogId > 0) {
                                MessagesController.getInstance(currentAccount).deleteUserPhoto(inputPhoto);
                            }
                            MessagesStorage.getInstance(currentAccount).clearUserPhoto(avatarsDialogId, photo.id);
                            imagesArrLocations.remove(currentIndex);
                            imagesArrLocationsSizes.remove(currentIndex);
                            imagesArrLocationsVideo.remove(currentIndex);
                            imagesArrMessages.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);
                            }
                            if (message == null) {
                                NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.reloadDialogPhotos);
                            }
                        }
                    } else if (!secureDocuments.isEmpty()) {
                        if (placeProvider == null) {
                            return;
                        }
                        secureDocuments.remove(currentIndex);
                        placeProvider.deleteImageAtIndex(currentIndex);
                        if (secureDocuments.isEmpty()) {
                            closePhoto(false, false);
                        } else {
                            int index = currentIndex;
                            if (index >= secureDocuments.size()) {
                                index = secureDocuments.size() - 1;
                            }
                            currentIndex = -1;
                            setImageIndex(index);
                        }
                    }
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                AlertDialog alertDialog = builder.create();
                showAlertDialog(builder);
                TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (button != null) {
                    button.setTextColor(getThemedColor(Theme.key_dialogTextRed2));
                }
            } else if (id == gallery_menu_share || id == gallery_menu_share2) {
                onSharePressed();
            } else if (id == gallery_menu_speed) {
                menuItemSpeed.setVisibility(View.VISIBLE);
                menuItemSpeed.toggleSubMenu();
                for (int a = 0; a < speedItems.length; a++) {
                    if (a == 0 && Math.abs(currentVideoSpeed - 0.25f) < 0.001f || a == 1 && Math.abs(currentVideoSpeed - 0.5f) < 0.001f || a == 2 && Math.abs(currentVideoSpeed - 1.0f) < 0.001f || a == 3 && Math.abs(currentVideoSpeed - 1.5f) < 0.001f || a == 4 && Math.abs(currentVideoSpeed - 2.0f) < 0.001f) {
                        speedItems[a].setColors(0xff6BB6F9, 0xff6BB6F9);
                    } else {
                        speedItems[a].setColors(0xfffafafa, 0xfffafafa);
                    }
                }
            } else if (id == gallery_menu_openin) {
                try {
                    if (isEmbedVideo) {
                        Browser.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
                        closePhoto(false, false);
                    } else if (currentMessageObject != null) {
                        if (AndroidUtilities.openForView(currentMessageObject, parentActivity, resourcesProvider)) {
                            closePhoto(false, false);
                        } else {
                            showDownloadAlert();
                        }
                    } else if (pageBlocksAdapter != null) {
                        if (AndroidUtilities.openForView(pageBlocksAdapter.getMedia(currentIndex), parentActivity)) {
                            closePhoto(false, false);
                        } else {
                            showDownloadAlert();
                        }
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == gallery_menu_masks || id == gallery_menu_masks2) {
                if (parentActivity == null || currentMessageObject == null) {
                    return;
                }
                TLObject object;
                if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                    object = currentMessageObject.messageOwner.media.photo;
                } else if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                    object = currentMessageObject.messageOwner.media.document;
                } else {
                    return;
                }
                masksAlert = new StickersAlert(parentActivity, currentMessageObject, object, resourcesProvider) {

                    @Override
                    public void dismiss() {
                        super.dismiss();
                        if (masksAlert == this) {
                            masksAlert = null;
                        }
                    }
                };
                masksAlert.show();
            } else if (id == gallery_menu_pip) {
                if (pipItem.getAlpha() != 1.0f) {
                    return;
                }
                if (isEmbedVideo) {
                    pipVideoView = photoViewerWebView.openInPip();
                    if (pipVideoView != null) {
                        if (PipInstance != null) {
                            PipInstance.destroyPhotoViewer();
                        }
                        isInline = true;
                        PipInstance = Instance;
                        Instance = null;
                        isVisible = false;
                        if (currentPlaceObject != null && !currentPlaceObject.imageReceiver.getVisible()) {
                            currentPlaceObject.imageReceiver.setVisible(true, true);
                        }
                        dismissInternal();
                    }
                } else {
                    switchToPip(false);
                }
            } else if (id == gallery_menu_cancel_loading) {
                if (currentMessageObject == null) {
                    return;
                }
                FileLoader.getInstance(currentAccount).cancelLoadFile(currentMessageObject.getDocument());
                releasePlayer(false);
                bottomLayout.setTag(1);
                bottomLayout.setVisibility(View.VISIBLE);
            } else if (id == gallery_menu_savegif) {
                if (currentMessageObject != null) {
                    TLRPC.Document document = currentMessageObject.getDocument();
                    if (parentChatActivity != null && parentChatActivity.chatActivityEnterView != null) {
                        parentChatActivity.chatActivityEnterView.addRecentGif(document);
                    } else {
                        MediaDataController.getInstance(currentAccount).addRecentGif(document, (int) (System.currentTimeMillis() / 1000));
                    }
                    MessagesController.getInstance(currentAccount).saveGif(currentMessageObject, document);
                } else if (pageBlocksAdapter != null) {
                    TLObject object = pageBlocksAdapter.getMedia(currentIndex);
                    if (object instanceof TLRPC.Document) {
                        TLRPC.Document document = (TLRPC.Document) object;
                        MediaDataController.getInstance(currentAccount).addRecentGif(document, (int) (System.currentTimeMillis() / 1000));
                        MessagesController.getInstance(currentAccount).saveGif(pageBlocksAdapter.getParentObject(), document);
                    }
                } else {
                    return;
                }
                if (containerView != null) {
                    BulletinFactory.of(containerView, resourcesProvider).createDownloadBulletin(BulletinFactory.FileType.GIF, resourcesProvider).show();
                }
            } else if (id == gallery_menu_set_as_main) {
                TLRPC.Photo photo = avatarsArr.get(currentIndex);
                if (photo == null || photo.sizes.isEmpty()) {
                    return;
                }
                TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 800);
                TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 90);
                UserConfig userConfig = UserConfig.getInstance(currentAccount);
                if (avatarsDialogId == userConfig.clientUserId) {
                    TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();
                    req.id = new TLRPC.TL_inputPhoto();
                    req.id.id = photo.id;
                    req.id.access_hash = photo.access_hash;
                    req.id.file_reference = photo.file_reference;
                    ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        if (response instanceof TLRPC.TL_photos_photo) {
                            TLRPC.TL_photos_photo photos_photo = (TLRPC.TL_photos_photo) response;
                            MessagesController.getInstance(currentAccount).putUsers(photos_photo.users, false);
                            TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userConfig.clientUserId);
                            if (photos_photo.photo instanceof TLRPC.TL_photo) {
                                int idx = avatarsArr.indexOf(photo);
                                if (idx >= 0) {
                                    avatarsArr.set(idx, photos_photo.photo);
                                }
                                if (user != null) {
                                    user.photo.photo_id = photos_photo.photo.id;
                                    userConfig.setCurrentUser(user);
                                    userConfig.saveConfig(true);
                                }
                            }
                        }
                    }));
                    TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userConfig.clientUserId);
                    if (user != null) {
                        user.photo.photo_id = photo.id;
                        user.photo.dc_id = photo.dc_id;
                        user.photo.photo_small = smallSize.location;
                        user.photo.photo_big = bigSize.location;
                        userConfig.setCurrentUser(user);
                        userConfig.saveConfig(true);
                        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.mainUserInfoChanged);
                    }
                } else {
                    TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-avatarsDialogId);
                    if (chat == null) {
                        return;
                    }
                    TLRPC.TL_inputChatPhoto inputChatPhoto = new TLRPC.TL_inputChatPhoto();
                    inputChatPhoto.id = new TLRPC.TL_inputPhoto();
                    inputChatPhoto.id.id = photo.id;
                    inputChatPhoto.id.access_hash = photo.access_hash;
                    inputChatPhoto.id.file_reference = photo.file_reference;
                    MessagesController.getInstance(currentAccount).changeChatAvatar(-avatarsDialogId, inputChatPhoto, null, null, 0, null, null, null, null);
                    chat.photo.dc_id = photo.dc_id;
                    chat.photo.photo_small = smallSize.location;
                    chat.photo.photo_big = bigSize.location;
                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_AVATAR);
                }
                currentAvatarLocation = ImageLocation.getForPhoto(bigSize, photo);
                avatarsArr.remove(currentIndex);
                avatarsArr.add(0, photo);
                ImageLocation location = imagesArrLocations.get(currentIndex);
                imagesArrLocations.remove(currentIndex);
                imagesArrLocations.add(0, location);
                location = imagesArrLocationsVideo.get(currentIndex);
                imagesArrLocationsVideo.remove(currentIndex);
                imagesArrLocationsVideo.add(0, location);
                Integer size = imagesArrLocationsSizes.get(currentIndex);
                imagesArrLocationsSizes.remove(currentIndex);
                imagesArrLocationsSizes.add(0, size);
                TLRPC.Message message = imagesArrMessages.get(currentIndex);
                imagesArrMessages.remove(currentIndex);
                imagesArrMessages.add(0, message);
                currentIndex = -1;
                setImageIndex(0);
                groupedPhotosListView.clear();
                groupedPhotosListView.fillList();
                hintView.showWithAction(avatarsDialogId, UndoView.ACTION_PROFILE_PHOTO_CHANGED, currentFileLocationVideo == currentFileLocation ? null : 1);
                AndroidUtilities.runOnUIThread(() -> {
                    if (menuItem == null) {
                        return;
                    }
                    menuItem.hideSubItem(gallery_menu_set_as_main);
                }, 300);
            } else if (id == gallery_menu_edit_avatar) {
                File f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), true);
                boolean isVideo = currentFileLocationVideo.imageType == FileLoader.IMAGE_TYPE_ANIMATION;
                String thumb;
                if (isVideo) {
                    thumb = FileLoader.getPathToAttach(getFileLocation(currentFileLocation), getFileLocationExt(currentFileLocation), true).getAbsolutePath();
                } else {
                    thumb = null;
                }
                placeProvider.openPhotoForEdit(f.getAbsolutePath(), thumb, isVideo);
            }
        }

        @Override
        public boolean canOpenMenu() {
            menuItemSpeed.setVisibility(View.INVISIBLE);
            if (currentMessageObject != null || currentSecureDocument != null) {
                return true;
            } else if (currentFileLocationVideo != null) {
                File f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), avatarsDialogId != 0 || isEvent);
                return f.exists();
            } else if (pageBlocksAdapter != null) {
                return true;
            }
            return false;
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    masksItem = menu.addItem(gallery_menu_masks, R.drawable.msg_mask);
    masksItem.setContentDescription(LocaleController.getString("Masks", R.string.Masks));
    pipItem = menu.addItem(gallery_menu_pip, R.drawable.ic_goinline);
    pipItem.setContentDescription(LocaleController.getString("AccDescrPipMode", R.string.AccDescrPipMode));
    sendItem = menu.addItem(gallery_menu_send, R.drawable.msg_forward);
    sendItem.setContentDescription(LocaleController.getString("Forward", R.string.Forward));
    shareItem = menu.addItem(gallery_menu_share2, R.drawable.share);
    shareItem.setContentDescription(LocaleController.getString("ShareFile", R.string.ShareFile));
    menuItem = menu.addItem(0, R.drawable.ic_ab_other);
    menuItemSpeed = new ActionBarMenuItem(parentActivity, null, 0, 0, resourcesProvider);
    menuItemSpeed.setDelegate(id -> {
        if (id >= gallery_menu_speed_veryslow && id <= gallery_menu_speed_veryfast) {
            switch(id) {
                case gallery_menu_speed_veryslow:
                    currentVideoSpeed = 0.25f;
                    break;
                case gallery_menu_speed_slow:
                    currentVideoSpeed = 0.5f;
                    break;
                case gallery_menu_speed_normal:
                    currentVideoSpeed = 1.0f;
                    break;
                case gallery_menu_speed_fast:
                    currentVideoSpeed = 1.5f;
                    break;
                case gallery_menu_speed_veryfast:
                    currentVideoSpeed = 2.0f;
                    break;
            }
            if (currentMessageObject != null) {
                SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("playback_speed", Activity.MODE_PRIVATE);
                if (Math.abs(currentVideoSpeed - 1.0f) < 0.001f) {
                    preferences.edit().remove("speed" + currentMessageObject.getDialogId() + "_" + currentMessageObject.getId()).commit();
                } else {
                    preferences.edit().putFloat("speed" + currentMessageObject.getDialogId() + "_" + currentMessageObject.getId(), currentVideoSpeed).commit();
                }
            }
            if (videoPlayer != null) {
                videoPlayer.setPlaybackSpeed(currentVideoSpeed);
            }
            if (photoViewerWebView != null) {
                photoViewerWebView.setPlaybackSpeed(currentVideoSpeed);
            }
            setMenuItemIcon();
            menuItemSpeed.setVisibility(View.INVISIBLE);
        }
    });
    menuItem.addView(menuItemSpeed);
    menuItemSpeed.setVisibility(View.INVISIBLE);
    speedItem = menuItem.addSubItem(gallery_menu_speed, R.drawable.msg_speed, null, LocaleController.getString("Speed", R.string.Speed), true, false);
    speedItem.setSubtext(LocaleController.getString("SpeedNormal", R.string.SpeedNormal));
    speedItem.setItemHeight(56);
    speedItem.setTag(R.id.width_tag, 240);
    speedItem.setColors(0xfffafafa, 0xfffafafa);
    speedItem.setRightIcon(R.drawable.msg_arrowright);
    speedGap = menuItem.addGap(gallery_menu_gap);
    menuItem.getPopupLayout().setFitItems(true);
    speedItems[0] = menuItemSpeed.addSubItem(gallery_menu_speed_veryslow, R.drawable.msg_speed_0_2, LocaleController.getString("SpeedVerySlow", R.string.SpeedVerySlow)).setColors(0xfffafafa, 0xfffafafa);
    speedItems[1] = menuItemSpeed.addSubItem(gallery_menu_speed_slow, R.drawable.msg_speed_0_5, LocaleController.getString("SpeedSlow", R.string.SpeedSlow)).setColors(0xfffafafa, 0xfffafafa);
    speedItems[2] = menuItemSpeed.addSubItem(gallery_menu_speed_normal, R.drawable.msg_speed_1, LocaleController.getString("SpeedNormal", R.string.SpeedNormal)).setColors(0xfffafafa, 0xfffafafa);
    speedItems[3] = menuItemSpeed.addSubItem(gallery_menu_speed_fast, R.drawable.msg_speed_1_5, LocaleController.getString("SpeedFast", R.string.SpeedFast)).setColors(0xfffafafa, 0xfffafafa);
    speedItems[4] = menuItemSpeed.addSubItem(gallery_menu_speed_veryfast, R.drawable.msg_speed_2, LocaleController.getString("SpeedVeryFast", R.string.SpeedVeryFast)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_openin, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    allMediaItem = menuItem.addSubItem(gallery_menu_showall, R.drawable.msg_media, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia));
    allMediaItem.setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_savegif, R.drawable.msg_gif, LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_showinchat, R.drawable.msg_message, LocaleController.getString("ShowInChat", R.string.ShowInChat)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_masks2, R.drawable.msg_sticker, LocaleController.getString("ShowStickers", R.string.ShowStickers)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_share, R.drawable.msg_shareout, LocaleController.getString("ShareFile", R.string.ShareFile)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_save, R.drawable.msg_gallery, LocaleController.getString("SaveToGallery", R.string.SaveToGallery)).setColors(0xfffafafa, 0xfffafafa);
    // menuItem.addSubItem(gallery_menu_edit_avatar, R.drawable.photo_paint, LocaleController.getString("EditPhoto", R.string.EditPhoto)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_set_as_main, R.drawable.menu_private, LocaleController.getString("SetAsMain", R.string.SetAsMain)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_delete, R.drawable.msg_delete, LocaleController.getString("Delete", R.string.Delete)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.addSubItem(gallery_menu_cancel_loading, R.drawable.msg_cancel, LocaleController.getString("StopDownload", R.string.StopDownload)).setColors(0xfffafafa, 0xfffafafa);
    menuItem.redrawPopup(0xf9222222);
    menuItemSpeed.redrawPopup(0xf9222222);
    setMenuItemIcon();
    menuItem.setSubMenuDelegate(new ActionBarMenuItem.ActionBarSubMenuItemDelegate() {

        @Override
        public void onShowSubMenu() {
            if (videoPlayerControlVisible && isPlaying) {
                AndroidUtilities.cancelRunOnUIThread(hideActionBarRunnable);
            }
        }

        @Override
        public void onHideSubMenu() {
            if (videoPlayerControlVisible && isPlaying) {
                scheduleActionBarHide();
            }
        }
    });
    bottomLayout = new FrameLayout(activityContext) {

        @Override
        protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
            if (child == nameTextView || child == dateTextView) {
                widthUsed = bottomButtonsLayout.getMeasuredWidth();
            }
            super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
        }
    };
    bottomLayout.setBackgroundColor(0x7f000000);
    containerView.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    pressedDrawable[0] = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[] { 0x32000000, 0 });
    pressedDrawable[0].setShape(GradientDrawable.RECTANGLE);
    pressedDrawable[1] = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, new int[] { 0x32000000, 0 });
    pressedDrawable[1].setShape(GradientDrawable.RECTANGLE);
    groupedPhotosListView = new GroupedPhotosListView(activityContext, AndroidUtilities.dp(10));
    containerView.addView(groupedPhotosListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 68, Gravity.BOTTOM | Gravity.LEFT));
    groupedPhotosListView.setDelegate(new GroupedPhotosListView.GroupedPhotosListViewDelegate() {

        @Override
        public int getCurrentIndex() {
            return currentIndex;
        }

        @Override
        public int getCurrentAccount() {
            return currentAccount;
        }

        @Override
        public long getAvatarsDialogId() {
            return avatarsDialogId;
        }

        @Override
        public int getSlideshowMessageId() {
            return slideshowMessageId;
        }

        @Override
        public ArrayList<ImageLocation> getImagesArrLocations() {
            return imagesArrLocations;
        }

        @Override
        public ArrayList<MessageObject> getImagesArr() {
            return imagesArr;
        }

        @Override
        public List<TLRPC.PageBlock> getPageBlockArr() {
            return pageBlocksAdapter != null ? pageBlocksAdapter.getAll() : null;
        }

        @Override
        public Object getParentObject() {
            return pageBlocksAdapter != null ? pageBlocksAdapter.getParentObject() : null;
        }

        @Override
        public void setCurrentIndex(int index) {
            currentIndex = -1;
            if (currentThumb != null) {
                currentThumb.release();
                currentThumb = null;
            }
            dontAutoPlay = true;
            setImageIndex(index);
            dontAutoPlay = false;
        }

        @Override
        public void onShowAnimationStart() {
            containerView.requestLayout();
        }

        @Override
        public void onStopScrolling() {
            if (shouldMessageObjectAutoPlayed(currentMessageObject)) {
                playerAutoStarted = true;
                onActionClick(true);
                checkProgress(0, false, true);
            }
        }

        @Override
        public boolean validGroupId(long groupId) {
            if (placeProvider != null) {
                return placeProvider.validateGroupId(groupId);
            }
            return true;
        }
    });
    for (int a = 0; a < 3; a++) {
        fullscreenButton[a] = new ImageView(parentActivity);
        fullscreenButton[a].setImageResource(R.drawable.msg_maxvideo);
        fullscreenButton[a].setContentDescription(LocaleController.getString("AccSwitchToFullscreen", R.string.AccSwitchToFullscreen));
        fullscreenButton[a].setScaleType(ImageView.ScaleType.CENTER);
        fullscreenButton[a].setBackground(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
        fullscreenButton[a].setVisibility(View.INVISIBLE);
        fullscreenButton[a].setAlpha(1.0f);
        containerView.addView(fullscreenButton[a], LayoutHelper.createFrame(48, 48));
        fullscreenButton[a].setOnClickListener(v -> {
            if (parentActivity == null) {
                return;
            }
            wasRotated = false;
            fullscreenedByButton = 1;
            if (prevOrientation == -10) {
                prevOrientation = parentActivity.getRequestedOrientation();
            }
            WindowManager manager = (WindowManager) parentActivity.getSystemService(Activity.WINDOW_SERVICE);
            int displayRotation = manager.getDefaultDisplay().getRotation();
            if (displayRotation == Surface.ROTATION_270) {
                parentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            } else {
                parentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            toggleActionBar(false, false);
        });
    }
    final LinkMovementMethod captionLinkMovementMethod = new CaptionLinkMovementMethod();
    captionTextViewSwitcher = new CaptionTextViewSwitcher(containerView.getContext());
    captionTextViewSwitcher.setFactory(() -> createCaptionTextView(captionLinkMovementMethod));
    captionTextViewSwitcher.setVisibility(View.INVISIBLE);
    setCaptionHwLayerEnabled(true);
    for (int a = 0; a < 3; a++) {
        photoProgressViews[a] = new PhotoProgressView(containerView) {

            @Override
            protected void onBackgroundStateUpdated(int state) {
                if (this == photoProgressViews[0]) {
                    updateAccessibilityOverlayVisibility();
                }
            }

            @Override
            protected void onVisibilityChanged(boolean visible) {
                if (this == photoProgressViews[0]) {
                    updateAccessibilityOverlayVisibility();
                }
            }
        };
        photoProgressViews[a].setBackgroundState(PROGRESS_EMPTY, false, true);
    }
    miniProgressView = new RadialProgressView(activityContext, resourcesProvider) {

        @Override
        public void setAlpha(float alpha) {
            super.setAlpha(alpha);
            if (containerView != null) {
                containerView.invalidate();
            }
        }

        @Override
        public void invalidate() {
            super.invalidate();
            if (containerView != null) {
                containerView.invalidate();
            }
        }
    };
    miniProgressView.setUseSelfAlpha(true);
    miniProgressView.setProgressColor(0xffffffff);
    miniProgressView.setSize(AndroidUtilities.dp(54));
    miniProgressView.setBackgroundResource(R.drawable.circle_big);
    miniProgressView.setVisibility(View.INVISIBLE);
    miniProgressView.setAlpha(0.0f);
    containerView.addView(miniProgressView, LayoutHelper.createFrame(64, 64, Gravity.CENTER));
    bottomButtonsLayout = new LinearLayout(containerView.getContext());
    bottomButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
    bottomLayout.addView(bottomButtonsLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
    paintButton = new ImageView(containerView.getContext());
    paintButton.setImageResource(R.drawable.photo_paint);
    paintButton.setScaleType(ImageView.ScaleType.CENTER);
    paintButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomButtonsLayout.addView(paintButton, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
    paintButton.setOnClickListener(v -> openCurrentPhotoInPaintModeForSelect());
    paintButton.setContentDescription(LocaleController.getString("AccDescrPhotoEditor", R.string.AccDescrPhotoEditor));
    shareButton = new ImageView(containerView.getContext());
    shareButton.setImageResource(R.drawable.share);
    shareButton.setScaleType(ImageView.ScaleType.CENTER);
    shareButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomButtonsLayout.addView(shareButton, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
    shareButton.setOnClickListener(v -> onSharePressed());
    shareButton.setContentDescription(LocaleController.getString("ShareFile", R.string.ShareFile));
    nameTextView = new FadingTextViewLayout(containerView.getContext()) {

        @Override
        protected void onTextViewCreated(TextView textView) {
            super.onTextViewCreated(textView);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(0xffffffff);
            textView.setGravity(Gravity.LEFT);
        }
    };
    bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 8, 0));
    dateTextView = new FadingTextViewLayout(containerView.getContext(), true) {

        private LocaleController.LocaleInfo lastLocaleInfo = null;

        private int staticCharsCount = 0;

        @Override
        protected void onTextViewCreated(TextView textView) {
            super.onTextViewCreated(textView);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(0xffffffff);
            textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            textView.setGravity(Gravity.LEFT);
        }

        @Override
        protected int getStaticCharsCount() {
            final LocaleController.LocaleInfo localeInfo = LocaleController.getInstance().getCurrentLocaleInfo();
            if (lastLocaleInfo != localeInfo) {
                lastLocaleInfo = localeInfo;
                staticCharsCount = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date()), LocaleController.getInstance().formatterDay.format(new Date())).length();
            }
            return staticCharsCount;
        }

        @Override
        public void setText(CharSequence text, boolean animated) {
            if (animated) {
                boolean dontAnimateUnchangedStaticChars = true;
                if (LocaleController.isRTL) {
                    final int staticCharsCount = getStaticCharsCount();
                    if (staticCharsCount > 0) {
                        if (text.length() != staticCharsCount || getText() == null || getText().length() != staticCharsCount) {
                            dontAnimateUnchangedStaticChars = false;
                        }
                    }
                }
                setText(text, true, dontAnimateUnchangedStaticChars);
            } else {
                setText(text, false, false);
            }
        }
    };
    bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 8, 0));
    createVideoControlsInterface();
    progressView = new RadialProgressView(parentActivity, resourcesProvider);
    progressView.setProgressColor(0xffffffff);
    progressView.setBackgroundResource(R.drawable.circle_big);
    progressView.setVisibility(View.INVISIBLE);
    containerView.addView(progressView, LayoutHelper.createFrame(54, 54, Gravity.CENTER));
    qualityPicker = new PickerBottomLayoutViewer(parentActivity);
    qualityPicker.setBackgroundColor(0x7f000000);
    qualityPicker.updateSelectedCount(0, false);
    qualityPicker.setTranslationY(AndroidUtilities.dp(120));
    qualityPicker.doneButton.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
    qualityPicker.doneButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton));
    containerView.addView(qualityPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    qualityPicker.cancelButton.setOnClickListener(view -> {
        selectedCompression = previousCompression;
        didChangedCompressionLevel(false);
        showQualityView(false);
        requestVideoPreview(2);
    });
    qualityPicker.doneButton.setOnClickListener(view -> {
        showQualityView(false);
        requestVideoPreview(2);
    });
    videoForwardDrawable = new VideoForwardDrawable(false);
    videoForwardDrawable.setDelegate(new VideoForwardDrawable.VideoForwardDrawableDelegate() {

        @Override
        public void onAnimationEnd() {
        }

        @Override
        public void invalidate() {
            containerView.invalidate();
        }
    });
    qualityChooseView = new QualityChooseView(parentActivity);
    qualityChooseView.setTranslationY(AndroidUtilities.dp(120));
    qualityChooseView.setVisibility(View.INVISIBLE);
    qualityChooseView.setBackgroundColor(0x7f000000);
    containerView.addView(qualityChooseView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 70, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
    pickerView = new FrameLayout(activityContext) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            return bottomTouchEnabled && super.dispatchTouchEvent(ev);
        }

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

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return bottomTouchEnabled && super.onTouchEvent(event);
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
                videoTimelineView.setTranslationY(translationY);
                videoAvatarTooltip.setTranslationY(translationY);
            }
            if (videoAvatarTooltip != null && videoAvatarTooltip.getVisibility() != GONE) {
                videoAvatarTooltip.setTranslationY(translationY);
            }
        }

        @Override
        public void setAlpha(float alpha) {
            super.setAlpha(alpha);
            if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
                videoTimelineView.setAlpha(alpha);
            }
        }

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
                videoTimelineView.setVisibility(visibility == VISIBLE ? VISIBLE : INVISIBLE);
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            if (itemsLayout.getVisibility() != GONE) {
                int x = (right - left - AndroidUtilities.dp(70) - itemsLayout.getMeasuredWidth()) / 2;
                itemsLayout.layout(x, itemsLayout.getTop(), x + itemsLayout.getMeasuredWidth(), itemsLayout.getTop() + itemsLayout.getMeasuredHeight());
            }
        }
    };
    pickerView.setBackgroundColor(0x7f000000);
    containerView.addView(pickerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT));
    docNameTextView = new TextView(containerView.getContext());
    docNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    docNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    docNameTextView.setSingleLine(true);
    docNameTextView.setMaxLines(1);
    docNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    docNameTextView.setTextColor(0xffffffff);
    docNameTextView.setGravity(Gravity.LEFT);
    pickerView.addView(docNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 23, 84, 0));
    docInfoTextView = new TextView(containerView.getContext());
    docInfoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    docInfoTextView.setSingleLine(true);
    docInfoTextView.setMaxLines(1);
    docInfoTextView.setEllipsize(TextUtils.TruncateAt.END);
    docInfoTextView.setTextColor(0xffffffff);
    docInfoTextView.setGravity(Gravity.LEFT);
    pickerView.addView(docInfoTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 46, 84, 0));
    videoTimelineView = new VideoTimelinePlayView(parentActivity) {

        @Override
        public void setTranslationY(float translationY) {
            if (getTranslationY() != translationY) {
                super.setTranslationY(translationY);
                containerView.invalidate();
            }
        }
    };
    videoTimelineView.setDelegate(new VideoTimelinePlayView.VideoTimelineViewDelegate() {

        private Runnable seekToRunnable;

        private int seekTo;

        private boolean wasPlaying;

        @Override
        public void onLeftProgressChanged(float progress) {
            if (videoPlayer == null) {
                return;
            }
            if (videoPlayer.isPlaying()) {
                manuallyPaused = false;
                videoPlayer.pause();
                containerView.invalidate();
            }
            updateAvatarStartTime(1);
            seekTo(progress);
            videoPlayerSeekbar.setProgress(0);
            videoTimelineView.setProgress(progress);
            updateVideoInfo();
        }

        @Override
        public void onRightProgressChanged(float progress) {
            if (videoPlayer == null) {
                return;
            }
            if (videoPlayer.isPlaying()) {
                manuallyPaused = false;
                videoPlayer.pause();
                containerView.invalidate();
            }
            updateAvatarStartTime(2);
            seekTo(progress);
            videoPlayerSeekbar.setProgress(1f);
            videoTimelineView.setProgress(progress);
            updateVideoInfo();
        }

        @Override
        public void onPlayProgressChanged(float progress) {
            if (videoPlayer == null) {
                return;
            }
            if (sendPhotoType == SELECT_TYPE_AVATAR) {
                updateAvatarStartTime(0);
            }
            seekTo(progress);
        }

        private void seekTo(float progress) {
            seekTo = (int) (videoDuration * progress);
            if (seekToRunnable == null) {
                AndroidUtilities.runOnUIThread(seekToRunnable = () -> {
                    if (videoPlayer != null) {
                        videoPlayer.seekTo(seekTo);
                    }
                    if (sendPhotoType == SELECT_TYPE_AVATAR) {
                        needCaptureFrameReadyAtTime = seekTo;
                        if (captureFrameReadyAtTime != needCaptureFrameReadyAtTime) {
                            captureFrameReadyAtTime = -1;
                        }
                    }
                    seekToRunnable = null;
                }, 100);
            }
        }

        private void updateAvatarStartTime(int fix) {
            if (sendPhotoType != SELECT_TYPE_AVATAR) {
                return;
            }
            if (fix != 0) {
                if (photoCropView != null && (videoTimelineView.getLeftProgress() > avatarStartProgress || videoTimelineView.getRightProgress() < avatarStartProgress)) {
                    photoCropView.setVideoThumbVisible(false);
                    if (fix == 1) {
                        avatarStartTime = (long) (videoDuration * 1000 * videoTimelineView.getLeftProgress());
                    } else {
                        avatarStartTime = (long) (videoDuration * 1000 * videoTimelineView.getRightProgress());
                    }
                    captureFrameAtTime = -1;
                }
            } else {
                avatarStartProgress = videoTimelineView.getProgress();
                avatarStartTime = (long) (videoDuration * 1000 * avatarStartProgress);
            }
        }

        @Override
        public void didStartDragging(int type) {
            if (type == VideoTimelinePlayView.TYPE_PROGRESS) {
                cancelVideoPlayRunnable();
                if (sendPhotoType == SELECT_TYPE_AVATAR) {
                    cancelFlashAnimations();
                    captureFrameAtTime = -1;
                }
                if (wasPlaying = videoPlayer != null && videoPlayer.isPlaying()) {
                    manuallyPaused = false;
                    videoPlayer.pause();
                    containerView.invalidate();
                }
            }
        }

        @Override
        public void didStopDragging(int type) {
            if (seekToRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(seekToRunnable);
                seekToRunnable.run();
            }
            cancelVideoPlayRunnable();
            if (sendPhotoType == SELECT_TYPE_AVATAR && flashView != null && type == VideoTimelinePlayView.TYPE_PROGRESS) {
                cancelFlashAnimations();
                captureFrameAtTime = avatarStartTime;
                if (captureFrameReadyAtTime == seekTo) {
                    captureCurrentFrame();
                }
            } else {
                if (sendPhotoType == SELECT_TYPE_AVATAR || wasPlaying) {
                    manuallyPaused = false;
                    if (videoPlayer != null) {
                        videoPlayer.play();
                    }
                }
            }
        }
    });
    showVideoTimeline(false, false);
    videoTimelineView.setBackgroundColor(0x7f000000);
    containerView.addView(videoTimelineView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 58, Gravity.LEFT | Gravity.BOTTOM, 0, 8, 0, 0));
    videoAvatarTooltip = new TextView(parentActivity);
    videoAvatarTooltip.setSingleLine(true);
    videoAvatarTooltip.setVisibility(View.GONE);
    videoAvatarTooltip.setText(LocaleController.getString("ChooseCover", R.string.ChooseCover));
    videoAvatarTooltip.setGravity(Gravity.CENTER_HORIZONTAL);
    videoAvatarTooltip.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    videoAvatarTooltip.setTextColor(0xff8c8c8c);
    containerView.addView(videoAvatarTooltip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 0, 8, 0, 0));
    pickerViewSendButton = new ImageView(parentActivity) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            return bottomTouchEnabled && super.dispatchTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return bottomTouchEnabled && super.onTouchEvent(event);
        }

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (captionEditText.getCaptionLimitOffset() < 0) {
                captionLimitView.setVisibility(visibility);
            } else {
                captionLimitView.setVisibility(View.GONE);
            }
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            captionLimitView.setTranslationY(translationY);
        }

        @Override
        public void setAlpha(float alpha) {
            super.setAlpha(alpha);
            captionLimitView.setAlpha(alpha);
        }
    };
    pickerViewSendButton.setScaleType(ImageView.ScaleType.CENTER);
    pickerViewSendDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton));
    pickerViewSendButton.setBackgroundDrawable(pickerViewSendDrawable);
    pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(0xffffffff, PorterDuff.Mode.MULTIPLY));
    pickerViewSendButton.setImageResource(R.drawable.attach_send);
    pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
    containerView.addView(pickerViewSendButton, LayoutHelper.createFrame(56, 56, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 14, 14));
    pickerViewSendButton.setContentDescription(LocaleController.getString("Send", R.string.Send));
    pickerViewSendButton.setOnClickListener(v -> {
        if (captionEditText.getCaptionLimitOffset() < 0) {
            AndroidUtilities.shakeView(captionLimitView, 2, 0);
            Vibrator vibrator = (Vibrator) captionLimitView.getContext().getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(200);
            }
            return;
        }
        if (parentChatActivity != null && parentChatActivity.isInScheduleMode() && !parentChatActivity.isEditingMessageMedia()) {
            showScheduleDatePickerDialog();
        } else {
            sendPressed(true, 0);
        }
    });
    pickerViewSendButton.setOnLongClickListener(view -> {
        if (placeProvider != null && !placeProvider.allowSendingSubmenu()) {
            return false;
        }
        if (parentChatActivity == null || parentChatActivity.isInScheduleMode()) {
            return false;
        }
        if (captionEditText.getCaptionLimitOffset() < 0) {
            return false;
        }
        TLRPC.Chat chat = parentChatActivity.getCurrentChat();
        TLRPC.User user = parentChatActivity.getCurrentUser();
        sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity);
        sendPopupLayout.setAnimationEnabled(false);
        sendPopupLayout.setOnTouchListener((v, event) -> {
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
                    v.getHitRect(hitRect);
                    if (!hitRect.contains((int) event.getX(), (int) event.getY())) {
                        sendPopupWindow.dismiss();
                    }
                }
            }
            return false;
        });
        sendPopupLayout.setDispatchKeyEventListener(keyEvent -> {
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
                sendPopupWindow.dismiss();
            }
        });
        sendPopupLayout.setShownFromBotton(false);
        sendPopupLayout.setBackgroundColor(0xf9222222);
        final boolean canReplace = placeProvider != null && placeProvider.canReplace(currentIndex);
        final int[] order = { 4, 3, 2, 0, 1 };
        for (int i = 0; i < 5; i++) {
            final int a = order[i];
            if (a != 2 && a != 3 && canReplace) {
                continue;
            }
            if (a == 0 && !parentChatActivity.canScheduleMessage()) {
                continue;
            }
            if (a == 0 && placeProvider != null && placeProvider.getSelectedPhotos() != null) {
                HashMap<Object, Object> hashMap = placeProvider.getSelectedPhotos();
                boolean hasTtl = false;
                for (HashMap.Entry<Object, Object> entry : hashMap.entrySet()) {
                    Object object = entry.getValue();
                    if (object instanceof MediaController.PhotoEntry) {
                        MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object;
                        if (photoEntry.ttl != 0) {
                            hasTtl = true;
                            break;
                        }
                    } else if (object instanceof MediaController.SearchImage) {
                        MediaController.SearchImage searchImage = (MediaController.SearchImage) object;
                        if (searchImage.ttl != 0) {
                            hasTtl = true;
                            break;
                        }
                    }
                }
                if (hasTtl) {
                    continue;
                }
            } else if (a == 1 && UserObject.isUserSelf(user)) {
                continue;
            } else if ((a == 2 || a == 3) && !canReplace) {
                continue;
            } else if (a == 4 && (isCurrentVideo || timeItem.getColorFilter() != null)) {
                continue;
            }
            ActionBarMenuSubItem cell = new ActionBarMenuSubItem(parentActivity, a == 0, a == 3, resourcesProvider);
            if (a == 0) {
                if (UserObject.isUserSelf(user)) {
                    cell.setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule);
                } else {
                    cell.setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_schedule);
                }
            } else if (a == 1) {
                cell.setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off);
            } else if (a == 2) {
                cell.setTextAndIcon(LocaleController.getString("ReplacePhoto", R.string.ReplacePhoto), R.drawable.msg_replace);
            } else if (a == 3) {
                cell.setTextAndIcon(LocaleController.getString("SendAsNewPhoto", R.string.SendAsNewPhoto), R.drawable.msg_sendphoto);
            } else if (a == 4) {
                cell.setTextAndIcon(LocaleController.getString("SendWithoutCompression", R.string.SendWithoutCompression), R.drawable.msg_sendfile);
            }
            cell.setMinimumWidth(AndroidUtilities.dp(196));
            cell.setColors(0xffffffff, 0xffffffff);
            sendPopupLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
            cell.setOnClickListener(v -> {
                if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
                    sendPopupWindow.dismiss();
                }
                if (a == 0) {
                    showScheduleDatePickerDialog();
                } else if (a == 1) {
                    sendPressed(false, 0);
                } else if (a == 2) {
                    replacePressed();
                } else if (a == 3) {
                    sendPressed(true, 0);
                } else if (a == 4) {
                    sendPressed(true, 0, false, true);
                }
            });
        }
        if (sendPopupLayout.getChildCount() == 0) {
            return false;
        }
        sendPopupLayout.setupRadialSelectors(0x24ffffff);
        sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
        sendPopupWindow.setAnimationEnabled(false);
        sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2);
        sendPopupWindow.setOutsideTouchable(true);
        sendPopupWindow.setClippingEnabled(true);
        sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
        sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
        sendPopupWindow.getContentView().setFocusableInTouchMode(true);
        sendPopupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
        sendPopupWindow.setFocusable(true);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - sendPopupLayout.getMeasuredWidth() + AndroidUtilities.dp(14), location[1] - sendPopupLayout.getMeasuredHeight() - AndroidUtilities.dp(18));
        view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
        return false;
    });
    captionLimitView = new TextView(parentActivity);
    captionLimitView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    captionLimitView.setTextColor(0xffEC7777);
    captionLimitView.setGravity(Gravity.CENTER);
    captionLimitView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    containerView.addView(captionLimitView, LayoutHelper.createFrame(56, 20, Gravity.BOTTOM | Gravity.RIGHT, 3, 0, 14, 78));
    itemsLayout = new LinearLayout(parentActivity) {

        boolean ignoreLayout;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int visibleItemsCount = 0;
            int count = getChildCount();
            for (int a = 0; a < count; a++) {
                View v = getChildAt(a);
                if (v.getVisibility() != VISIBLE) {
                    continue;
                }
                visibleItemsCount++;
            }
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            if (visibleItemsCount != 0) {
                int itemWidth = Math.min(AndroidUtilities.dp(70), width / visibleItemsCount);
                if (compressItem.getVisibility() == VISIBLE) {
                    ignoreLayout = true;
                    int compressIconWidth;
                    if (selectedCompression < 2) {
                        compressIconWidth = 48;
                    } else {
                        compressIconWidth = 64;
                    }
                    int padding = Math.max(0, (itemWidth - AndroidUtilities.dp(compressIconWidth)) / 2);
                    compressItem.setPadding(padding, 0, padding, 0);
                    ignoreLayout = false;
                }
                for (int a = 0; a < count; a++) {
                    View v = getChildAt(a);
                    if (v.getVisibility() == GONE) {
                        continue;
                    }
                    v.measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
                }
                setMeasuredDimension(itemWidth * visibleItemsCount, height);
            } else {
                setMeasuredDimension(width, height);
            }
        }
    };
    itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
    pickerView.addView(itemsLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 70, 0));
    cropItem = new ImageView(parentActivity);
    cropItem.setScaleType(ImageView.ScaleType.CENTER);
    cropItem.setImageResource(R.drawable.photo_crop);
    cropItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(cropItem, LayoutHelper.createLinear(48, 48));
    cropItem.setOnClickListener(v -> {
        if (captionEditText.getTag() != null) {
            return;
        }
        if (isCurrentVideo) {
            if (!videoConvertSupported) {
                return;
            }
            if (videoTextureView instanceof VideoEditTextureView) {
                VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
                if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
                    return;
                }
            } else {
                return;
            }
        }
        switchToEditMode(1);
    });
    cropItem.setContentDescription(LocaleController.getString("CropImage", R.string.CropImage));
    rotateItem = new ImageView(parentActivity);
    rotateItem.setScaleType(ImageView.ScaleType.CENTER);
    rotateItem.setImageResource(R.drawable.tool_rotate);
    rotateItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(rotateItem, LayoutHelper.createLinear(48, 48));
    rotateItem.setOnClickListener(v -> {
        if (photoCropView == null) {
            return;
        }
        if (photoCropView.rotate()) {
            rotateItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY));
        } else {
            rotateItem.setColorFilter(null);
        }
    });
    rotateItem.setContentDescription(LocaleController.getString("AccDescrRotate", R.string.AccDescrRotate));
    mirrorItem = new ImageView(parentActivity);
    mirrorItem.setScaleType(ImageView.ScaleType.CENTER);
    mirrorItem.setImageResource(R.drawable.photo_flip);
    mirrorItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(mirrorItem, LayoutHelper.createLinear(48, 48));
    mirrorItem.setOnClickListener(v -> {
        if (photoCropView == null) {
            return;
        }
        if (photoCropView.mirror()) {
            mirrorItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY));
        } else {
            mirrorItem.setColorFilter(null);
        }
    });
    mirrorItem.setContentDescription(LocaleController.getString("AccDescrMirror", R.string.AccDescrMirror));
    paintItem = new ImageView(parentActivity);
    paintItem.setScaleType(ImageView.ScaleType.CENTER);
    paintItem.setImageResource(R.drawable.photo_paint);
    paintItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(paintItem, LayoutHelper.createLinear(48, 48));
    paintItem.setOnClickListener(v -> {
        if (captionEditText.getTag() != null) {
            return;
        }
        if (isCurrentVideo) {
            if (!videoConvertSupported) {
                return;
            }
            if (videoTextureView instanceof VideoEditTextureView) {
                VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
                if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
                    return;
                }
            } else {
                return;
            }
        }
        switchToEditMode(3);
    });
    paintItem.setContentDescription(LocaleController.getString("AccDescrPhotoEditor", R.string.AccDescrPhotoEditor));
    muteItem = new ImageView(parentActivity);
    muteItem.setScaleType(ImageView.ScaleType.CENTER);
    muteItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    containerView.addView(muteItem, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 0, 0));
    muteItem.setOnClickListener(v -> {
        if (captionEditText.getTag() != null) {
            return;
        }
        muteVideo = !muteVideo;
        updateMuteButton();
        updateVideoInfo();
        if (muteVideo && !checkImageView.isChecked()) {
            checkImageView.callOnClick();
        } else {
            Object object = imagesArrLocals.get(currentIndex);
            if (object instanceof MediaController.MediaEditState) {
                ((MediaController.MediaEditState) object).editedInfo = getCurrentVideoEditedInfo();
            }
        }
    });
    cameraItem = new ImageView(parentActivity);
    cameraItem.setScaleType(ImageView.ScaleType.CENTER);
    cameraItem.setImageResource(R.drawable.photo_add);
    cameraItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    cameraItem.setContentDescription(LocaleController.getString("AccDescrTakeMorePics", R.string.AccDescrTakeMorePics));
    containerView.addView(cameraItem, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 16, 0));
    cameraItem.setOnClickListener(v -> {
        if (placeProvider == null || captionEditText.getTag() != null) {
            return;
        }
        placeProvider.needAddMorePhotos();
        closePhoto(true, false);
    });
    tuneItem = new ImageView(parentActivity);
    tuneItem.setScaleType(ImageView.ScaleType.CENTER);
    tuneItem.setImageResource(R.drawable.photo_tools);
    tuneItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(tuneItem, LayoutHelper.createLinear(48, 48));
    tuneItem.setOnClickListener(v -> {
        if (captionEditText.getTag() != null) {
            return;
        }
        if (isCurrentVideo) {
            if (!videoConvertSupported) {
                return;
            }
            if (videoTextureView instanceof VideoEditTextureView) {
                VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
                if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
                    return;
                }
            } else {
                return;
            }
        }
        switchToEditMode(2);
    });
    tuneItem.setContentDescription(LocaleController.getString("AccDescrPhotoAdjust", R.string.AccDescrPhotoAdjust));
    compressItem = new ImageView(parentActivity);
    compressItem.setTag(1);
    compressItem.setScaleType(ImageView.ScaleType.CENTER);
    compressItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    selectedCompression = selectCompression();
    int compressIconWidth;
    if (selectedCompression <= 1) {
        compressItem.setImageResource(R.drawable.video_quality1);
    } else if (selectedCompression == 2) {
        compressItem.setImageResource(R.drawable.video_quality2);
    } else {
        selectedCompression = compressionsCount - 1;
        compressItem.setImageResource(R.drawable.video_quality3);
    }
    compressItem.setContentDescription(LocaleController.getString("AccDescrVideoQuality", R.string.AccDescrVideoQuality));
    itemsLayout.addView(compressItem, LayoutHelper.createLinear(48, 48));
    compressItem.setOnClickListener(v -> {
        if (captionEditText.getTag() != null || muteVideo) {
            return;
        }
        if (compressItem.getTag() == null) {
            if (videoConvertSupported) {
                if (tooltip == null) {
                    tooltip = new Tooltip(activity, containerView, 0xcc111111, Color.WHITE);
                }
                tooltip.setText(LocaleController.getString("VideoQualityIsTooLow", R.string.VideoQualityIsTooLow));
                tooltip.show(compressItem);
            }
            return;
        }
        showQualityView(true);
        requestVideoPreview(1);
    });
    timeItem = new ImageView(parentActivity);
    timeItem.setScaleType(ImageView.ScaleType.CENTER);
    timeItem.setImageResource(R.drawable.photo_timer);
    timeItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    timeItem.setContentDescription(LocaleController.getString("SetTimer", R.string.SetTimer));
    itemsLayout.addView(timeItem, LayoutHelper.createLinear(48, 48));
    timeItem.setOnClickListener(v -> {
        if (parentActivity == null || captionEditText.getTag() != null) {
            return;
        }
        BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity, false, resourcesProvider);
        builder.setUseHardwareLayer(false);
        LinearLayout linearLayout = new LinearLayout(parentActivity);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        builder.setCustomView(linearLayout);
        TextView titleView = new TextView(parentActivity);
        titleView.setLines(1);
        titleView.setSingleLine(true);
        titleView.setText(LocaleController.getString("MessageLifetime", R.string.MessageLifetime));
        titleView.setTextColor(0xffffffff);
        titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(8), AndroidUtilities.dp(21), AndroidUtilities.dp(4));
        titleView.setGravity(Gravity.CENTER_VERTICAL);
        linearLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        titleView.setOnTouchListener((v13, event) -> true);
        titleView = new TextView(parentActivity);
        titleView.setText(isCurrentVideo ? LocaleController.getString("MessageLifetimeVideo", R.string.MessageLifetimeVideo) : LocaleController.getString("MessageLifetimePhoto", R.string.MessageLifetimePhoto));
        titleView.setTextColor(0xff808080);
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        titleView.setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), AndroidUtilities.dp(8));
        titleView.setGravity(Gravity.CENTER_VERTICAL);
        linearLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        titleView.setOnTouchListener((v12, event) -> true);
        final BottomSheet bottomSheet = builder.create();
        final NumberPicker numberPicker = new NumberPicker(parentActivity, resourcesProvider);
        numberPicker.setMinValue(0);
        numberPicker.setMaxValue(28);
        Object object = imagesArrLocals.get(currentIndex);
        int currentTTL;
        if (object instanceof MediaController.PhotoEntry) {
            currentTTL = ((MediaController.PhotoEntry) object).ttl;
        } else if (object instanceof MediaController.SearchImage) {
            currentTTL = ((MediaController.SearchImage) object).ttl;
        } else {
            currentTTL = 0;
        }
        if (currentTTL == 0) {
            SharedPreferences preferences1 = MessagesController.getGlobalMainSettings();
            numberPicker.setValue(preferences1.getInt("self_destruct", 7));
        } else {
            if (currentTTL >= 0 && currentTTL < 21) {
                numberPicker.setValue(currentTTL);
            } else {
                numberPicker.setValue(21 + currentTTL / 5 - 5);
            }
        }
        numberPicker.setTextColor(0xffffffff);
        numberPicker.setSelectorColor(0xff4d4d4d);
        numberPicker.setFormatter(value -> {
            if (value == 0) {
                return LocaleController.getString("ShortMessageLifetimeForever", R.string.ShortMessageLifetimeForever);
            } else if (value >= 1 && value < 21) {
                return LocaleController.formatTTLString(value);
            } else {
                return LocaleController.formatTTLString((value - 16) * 5);
            }
        });
        linearLayout.addView(numberPicker, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        FrameLayout buttonsLayout = new FrameLayout(parentActivity) {

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                int count = getChildCount();
                int width = right - left;
                for (int a = 0; a < count; a++) {
                    View child = getChildAt(a);
                    if ((Integer) child.getTag() == Dialog.BUTTON_POSITIVE) {
                        child.layout(width - getPaddingRight() - child.getMeasuredWidth(), getPaddingTop(), width - getPaddingRight(), getPaddingTop() + child.getMeasuredHeight());
                    } else if ((Integer) child.getTag() == Dialog.BUTTON_NEGATIVE) {
                        int x = getPaddingLeft();
                        child.layout(x, getPaddingTop(), x + child.getMeasuredWidth(), getPaddingTop() + child.getMeasuredHeight());
                    } else {
                        child.layout(getPaddingLeft(), getPaddingTop(), getPaddingLeft() + child.getMeasuredWidth(), getPaddingTop() + child.getMeasuredHeight());
                    }
                }
            }
        };
        buttonsLayout.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
        linearLayout.addView(buttonsLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 52));
        TextView textView = new TextView(parentActivity);
        textView.setMinWidth(AndroidUtilities.dp(64));
        textView.setTag(Dialog.BUTTON_POSITIVE);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        textView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton));
        textView.setGravity(Gravity.CENTER);
        textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        textView.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
        textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(0xff49bcf2));
        textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
        buttonsLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.TOP | Gravity.RIGHT));
        textView.setOnClickListener(v1 -> {
            int value = numberPicker.getValue();
            SharedPreferences preferences1 = MessagesController.getGlobalMainSettings();
            SharedPreferences.Editor editor = preferences1.edit();
            editor.putInt("self_destruct", value);
            editor.commit();
            bottomSheet.dismiss();
            int seconds;
            if (value >= 0 && value < 21) {
                seconds = value;
            } else {
                seconds = (value - 16) * 5;
            }
            Object object1 = imagesArrLocals.get(currentIndex);
            if (object1 instanceof MediaController.PhotoEntry) {
                ((MediaController.PhotoEntry) object1).ttl = seconds;
            } else if (object1 instanceof MediaController.SearchImage) {
                ((MediaController.SearchImage) object1).ttl = seconds;
            }
            timeItem.setColorFilter(seconds != 0 ? new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY) : null);
            if (!checkImageView.isChecked()) {
                checkImageView.callOnClick();
            }
        });
        textView = new TextView(parentActivity);
        textView.setMinWidth(AndroidUtilities.dp(64));
        textView.setTag(Dialog.BUTTON_NEGATIVE);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        textView.setTextColor(0xffffffff);
        textView.setGravity(Gravity.CENTER);
        textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        textView.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
        textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(0xffffffff));
        textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
        buttonsLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.TOP | Gravity.RIGHT));
        textView.setOnClickListener(v14 -> bottomSheet.dismiss());
        bottomSheet.show();
        bottomSheet.setBackgroundColor(0xff000000);
    });
    editorDoneLayout = new PickerBottomLayoutViewer(activityContext);
    editorDoneLayout.setBackgroundColor(0xcc000000);
    editorDoneLayout.updateSelectedCount(0, false);
    editorDoneLayout.setVisibility(View.GONE);
    containerView.addView(editorDoneLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    editorDoneLayout.cancelButton.setOnClickListener(view -> {
        cropTransform.setViewTransform(previousHasTransform, previousCropPx, previousCropPy, previousCropRotation, previousCropOrientation, previousCropScale, 1.0f, 1.0f, previousCropPw, previousCropPh, 0, 0, previousCropMirrored);
        switchToEditMode(0);
    });
    editorDoneLayout.doneButton.setOnClickListener(view -> {
        if (currentEditMode == 1 && !photoCropView.isReady()) {
            return;
        }
        applyCurrentEditMode();
        switchToEditMode(0);
    });
    resetButton = new TextView(activityContext);
    resetButton.setVisibility(View.GONE);
    resetButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    resetButton.setTextColor(0xffffffff);
    resetButton.setGravity(Gravity.CENTER);
    resetButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_PICKER_SELECTOR_COLOR, 0));
    resetButton.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
    resetButton.setText(LocaleController.getString("Reset", R.string.CropReset).toUpperCase());
    resetButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    editorDoneLayout.addView(resetButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.CENTER));
    resetButton.setOnClickListener(v -> photoCropView.reset());
    gestureDetector = new GestureDetector2(containerView.getContext(), this);
    gestureDetector.setIsLongpressEnabled(false);
    setDoubleTapEnabled(true);
    ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = (imageReceiver, set, thumb, memCache) -> {
        if (imageReceiver == centerImage && set && !thumb) {
            if (!isCurrentVideo && (currentEditMode == 1 || sendPhotoType == SELECT_TYPE_AVATAR) && photoCropView != null) {
                Bitmap bitmap = imageReceiver.getBitmap();
                if (bitmap != null) {
                    photoCropView.setBitmap(bitmap, imageReceiver.getOrientation(), sendPhotoType != SELECT_TYPE_AVATAR, true, paintingOverlay, cropTransform, null, null);
                }
            }
            if (paintingOverlay.getVisibility() == View.VISIBLE) {
                containerView.requestLayout();
            }
            detectFaces();
        }
        if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill() && !ignoreDidSetImage && sendPhotoType != SELECT_TYPE_AVATAR) {
            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) {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return bottomTouchEnabled && super.onTouchEvent(event);
        }
    };
    checkImageView.setDrawBackground(true);
    checkImageView.setHasBorder(true);
    checkImageView.setSize(34);
    checkImageView.setCheckOffset(AndroidUtilities.dp(1));
    checkImageView.setColor(getThemedColor(Theme.key_dialogFloatingButton), 0xffffffff);
    checkImageView.setVisibility(View.GONE);
    containerView.addView(checkImageView, LayoutHelper.createFrame(34, 34, Gravity.RIGHT | Gravity.TOP, 0, rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 61 : 71, 11, 0));
    if (isStatusBarVisible()) {
        ((FrameLayout.LayoutParams) checkImageView.getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    checkImageView.setOnClickListener(v -> {
        if (captionEditText.getTag() != null) {
            return;
        }
        setPhotoChecked();
    });
    photosCounterView = new CounterView(parentActivity);
    containerView.addView(photosCounterView, LayoutHelper.createFrame(40, 40, Gravity.RIGHT | Gravity.TOP, 0, rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 64, 0));
    if (isStatusBarVisible()) {
        ((FrameLayout.LayoutParams) photosCounterView.getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    photosCounterView.setOnClickListener(v -> {
        if (captionEditText.getTag() != null || placeProvider == null || placeProvider.getSelectedPhotosOrder() == null || placeProvider.getSelectedPhotosOrder().isEmpty()) {
            return;
        }
        togglePhotosListView(!isPhotosListViewVisible, true);
    });
    selectedPhotosListView = new SelectedPhotosListView(parentActivity);
    selectedPhotosListView.setVisibility(View.GONE);
    selectedPhotosListView.setAlpha(0.0f);
    selectedPhotosListView.setLayoutManager(new LinearLayoutManager(parentActivity, LinearLayoutManager.HORIZONTAL, true) {

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
            LinearSmoothScrollerEnd linearSmoothScroller = new LinearSmoothScrollerEnd(recyclerView.getContext()) {

                @Override
                protected int calculateTimeForDeceleration(int dx) {
                    return Math.max(180, super.calculateTimeForDeceleration(dx));
                }
            };
            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }
    });
    selectedPhotosListView.setAdapter(selectedPhotosAdapter = new ListAdapter(parentActivity));
    containerView.addView(selectedPhotosListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 103, Gravity.LEFT | Gravity.TOP));
    selectedPhotosListView.setOnItemClickListener((view, position) -> {
        if (!imagesArrLocals.isEmpty() && currentIndex >= 0 && currentIndex < imagesArrLocals.size()) {
            Object entry = imagesArrLocals.get(currentIndex);
            if (entry instanceof MediaController.MediaEditState) {
                ((MediaController.MediaEditState) entry).editedInfo = getCurrentVideoEditedInfo();
            }
        }
        ignoreDidSetImage = true;
        int idx = imagesArrLocals.indexOf(view.getTag());
        if (idx >= 0) {
            currentIndex = -1;
            setImageIndex(idx);
        }
        ignoreDidSetImage = false;
    });
    captionEditText = new PhotoViewerCaptionEnterView(activityContext, containerView, windowView, resourcesProvider) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            try {
                return !bottomTouchEnabled && super.dispatchTouchEvent(ev);
            } catch (Exception e) {
                FileLog.e(e);
            }
            return false;
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            try {
                return !bottomTouchEnabled && super.onInterceptTouchEvent(ev);
            } catch (Exception e) {
                FileLog.e(e);
            }
            return false;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (bottomTouchEnabled && event.getAction() == MotionEvent.ACTION_DOWN) {
                keyboardAnimationEnabled = true;
            }
            return !bottomTouchEnabled && super.onTouchEvent(event);
        }

        @Override
        protected void extendActionMode(ActionMode actionMode, Menu menu) {
            if (parentChatActivity != null) {
                parentChatActivity.extendActionMode(menu);
            }
        }
    };
    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, false, false);
            }
            int color = getThemedColor(Theme.key_dialogFloatingIcon);
            if (captionEditText.getCaptionLimitOffset() < 0) {
                captionLimitView.setText(Integer.toString(captionEditText.getCaptionLimitOffset()));
                captionLimitView.setVisibility(pickerViewSendButton.getVisibility());
                pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * 0.58f)), PorterDuff.Mode.MULTIPLY));
            } else {
                pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                captionLimitView.setVisibility(View.GONE);
            }
            if (placeProvider != null) {
                placeProvider.onCaptionChanged(text);
            }
        }

        @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);
                }
            }
        }

        @Override
        public void onEmojiViewCloseStart() {
            setOffset(captionEditText.getEmojiPadding());
            if (captionEditText.getTag() != null) {
                if (isCurrentVideo) {
                    actionBar.setTitleAnimated(muteVideo ? LocaleController.getString("GifCaption", R.string.GifCaption) : LocaleController.getString("VideoCaption", R.string.VideoCaption), true, 220);
                } else {
                    actionBar.setTitleAnimated(LocaleController.getString("PhotoCaption", R.string.PhotoCaption), true, 220);
                }
                checkImageView.animate().alpha(0f).setDuration(220).start();
                photosCounterView.animate().alpha(0f).setDuration(220).start();
                selectedPhotosListView.animate().alpha(0.0f).translationY(-AndroidUtilities.dp(10)).setDuration(220).start();
            } else {
                checkImageView.animate().alpha(1f).setDuration(220).start();
                photosCounterView.animate().alpha(1f).setDuration(220).start();
                if (lastTitle != null) {
                    actionBar.setTitleAnimated(lastTitle, false, 220);
                    lastTitle = null;
                }
            }
        }

        @Override
        public void onEmojiViewCloseEnd() {
            setOffset(0);
            captionEditText.setVisibility(View.GONE);
        }

        private void setOffset(int offset) {
            for (int i = 0; i < containerView.getChildCount(); i++) {
                View child = containerView.getChildAt(i);
                if (child == cameraItem || child == muteItem || child == pickerView || child == videoTimelineView || child == pickerViewSendButton || child == captionTextViewSwitcher || muteItem.getVisibility() == View.VISIBLE && child == bottomLayout) {
                    child.setTranslationY(offset);
                }
            }
        }
    });
    if (Build.VERSION.SDK_INT >= 19) {
        captionEditText.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
    }
    captionEditText.setVisibility(View.GONE);
    containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT));
    mentionListView = new RecyclerListView(activityContext, resourcesProvider) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            return !bottomTouchEnabled && super.dispatchTouchEvent(ev);
        }

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

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return !bottomTouchEnabled && super.onTouchEvent(event);
        }
    };
    mentionListView.setTag(5);
    mentionLayoutManager = new LinearLayoutManager(activityContext) {

        @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(RecyclerListView.OVER_SCROLL_NEVER);
    containerView.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));
    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(activityContext, true, 0, 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, View.ALPHA, 0.0f, 1.0f));
                    mentionListAnimation.addListener(new AnimatorListenerAdapter() {

                        @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, View.ALPHA, 0.0f));
                    mentionListAnimation.addListener(new AnimatorListenerAdapter() {

                        @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) {
        }
    }, resourcesProvider));
    mentionListView.setOnItemClickListener((view, 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.username != null) {
                captionEditText.replaceWithText(start, len, "@" + user.username + " ", false);
            } else {
                String name = UserObject.getFirstName(user);
                Spannable spannable = new SpannableString(name + " ");
                spannable.setSpan(new URLSpanUserMentionPhotoViewer("" + user.id, true), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                captionEditText.replaceWithText(start, len, spannable, false);
            }
        } else if (object instanceof String) {
            captionEditText.replaceWithText(start, len, object + " ", false);
        } else if (object instanceof MediaDataController.KeywordResult) {
            String code = ((MediaDataController.KeywordResult) object).emoji;
            captionEditText.addEmojiToRecent(code);
            captionEditText.replaceWithText(start, len, code, true);
        }
    });
    mentionListView.setOnItemLongClickListener((view, position) -> {
        Object object = mentionsAdapter.getItem(position);
        if (object instanceof String) {
            AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider);
            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(), (dialogInterface, i) -> mentionsAdapter.clearRecentHashtags());
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showAlertDialog(builder);
            return true;
        }
        return false;
    });
    hintView = new UndoView(activityContext, null, false, resourcesProvider);
    hintView.setAdditionalTranslationY(AndroidUtilities.dp(112));
    hintView.setColors(0xf9222222, 0xffffffff);
    containerView.addView(hintView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    AccessibilityManager am = (AccessibilityManager) activityContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
    if (am.isEnabled()) {
        playButtonAccessibilityOverlay = new View(activityContext);
        playButtonAccessibilityOverlay.setContentDescription(LocaleController.getString("AccActionPlay", R.string.AccActionPlay));
        playButtonAccessibilityOverlay.setFocusable(true);
        containerView.addView(playButtonAccessibilityOverlay, LayoutHelper.createFrame(64, 64, Gravity.CENTER));
    }
}
Also used : ViewHelper(org.telegram.ui.Components.ViewHelper) Bundle(android.os.Bundle) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) NonNull(androidx.annotation.NonNull) StickersAlert(org.telegram.ui.Components.StickersAlert) Property(android.util.Property) Keep(androidx.annotation.Keep) Map(java.util.Map) ContextCompat(androidx.core.content.ContextCompat) MediaActivity(org.telegram.ui.Components.MediaActivity) C(com.google.android.exoplayer2.C) Surface(android.view.Surface) NotificationCenter(org.telegram.messenger.NotificationCenter) TextViewSwitcher(org.telegram.ui.Components.TextViewSwitcher) Layout(android.text.Layout) Paint(android.graphics.Paint) LinearSmoothScrollerEnd(androidx.recyclerview.widget.LinearSmoothScrollerEnd) PhotoCropView(org.telegram.ui.Components.PhotoCropView) SystemClock(android.os.SystemClock) ExoPlayer(com.google.android.exoplayer2.ExoPlayer) SpannableStringBuilder(android.text.SpannableStringBuilder) Log(com.google.android.exoplayer2.util.Log) TransitionValues(android.transition.TransitionValues) Toast(android.widget.Toast) Menu(android.view.Menu) Settings(android.provider.Settings) PhotoViewerWebView(org.telegram.ui.Components.PhotoViewerWebView) CropView(org.telegram.ui.Components.Crop.CropView) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) URLSpan(android.text.style.URLSpan) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) Field(java.lang.reflect.Field) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) SpoilersTextView(org.telegram.ui.Components.spoilers.SpoilersTextView) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) PackageManager(android.content.pm.PackageManager) NestedScrollView(androidx.core.widget.NestedScrollView) FloatSeekBarAccessibilityDelegate(org.telegram.ui.Components.FloatSeekBarAccessibilityDelegate) Date(java.util.Date) WindowManager(android.view.WindowManager) ClickableSpan(android.text.style.ClickableSpan) URLSpanUserMentionPhotoViewer(org.telegram.ui.Components.URLSpanUserMentionPhotoViewer) Animator(android.animation.Animator) TransitionManager(android.transition.TransitionManager) FloatProperty(android.util.FloatProperty) WebFile(org.telegram.messenger.WebFile) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) SpringAnimation(androidx.dynamicanimation.animation.SpringAnimation) ActivityInfo(android.content.pm.ActivityInfo) RecyclerView(androidx.recyclerview.widget.RecyclerView) Method(java.lang.reflect.Method) RectF(android.graphics.RectF) OverScroller(android.widget.OverScroller) ImageLoader(org.telegram.messenger.ImageLoader) SpringForce(androidx.dynamicanimation.animation.SpringForce) PipVideoView(org.telegram.ui.Components.PipVideoView) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) VideoPlayer(org.telegram.ui.Components.VideoPlayer) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) UserConfig(org.telegram.messenger.UserConfig) LinearInterpolator(android.view.animation.LinearInterpolator) WindowInsets(android.view.WindowInsets) AnalyticsListener(com.google.android.exoplayer2.analytics.AnalyticsListener) CropTransform(org.telegram.ui.Components.Crop.CropTransform) Spanned(android.text.Spanned) LocaleController(org.telegram.messenger.LocaleController) VideoSeekPreviewImage(org.telegram.ui.Components.VideoSeekPreviewImage) ChangeBounds(android.transition.ChangeBounds) SecureDocument(org.telegram.messenger.SecureDocument) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) SharedConfig(org.telegram.messenger.SharedConfig) MessageObject(org.telegram.messenger.MessageObject) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) NumberPicker(org.telegram.ui.Components.NumberPicker) DownloadController(org.telegram.messenger.DownloadController) Scroller(android.widget.Scroller) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) VideoPlayerRewinder(org.telegram.messenger.video.VideoPlayerRewinder) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) OvershootInterpolator(android.view.animation.OvershootInterpolator) Tooltip(org.telegram.ui.Components.Tooltip) Fade(android.transition.Fade) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) Activity(android.app.Activity) ImageReceiver(org.telegram.messenger.ImageReceiver) RecyclerListView(org.telegram.ui.Components.RecyclerListView) Arrays(java.util.Arrays) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) SizeNotifierFrameLayoutPhoto(org.telegram.ui.Components.SizeNotifierFrameLayoutPhoto) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) PickerBottomLayoutViewer(org.telegram.ui.Components.PickerBottomLayoutViewer) Selection(android.text.Selection) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) PhotoViewerCaptionEnterView(org.telegram.ui.Components.PhotoViewerCaptionEnterView) GestureDetector2(org.telegram.ui.Components.GestureDetector2) Canvas(android.graphics.Canvas) AccessibilityEvent(android.view.accessibility.AccessibilityEvent) Emoji(org.telegram.messenger.Emoji) ArrayMap(androidx.collection.ArrayMap) ViewCompat(androidx.core.view.ViewCompat) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) Interpolator(android.view.animation.Interpolator) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) HapticFeedbackConstants(android.view.HapticFeedbackConstants) Nullable(androidx.annotation.Nullable) TextPaint(android.text.TextPaint) VideoEditTextureView(org.telegram.ui.Components.VideoEditTextureView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) ExifInterface(androidx.exifinterface.media.ExifInterface) FileLoader(org.telegram.messenger.FileLoader) Dialog(android.app.Dialog) BitmapFactory(android.graphics.BitmapFactory) PaintingOverlay(org.telegram.ui.Components.PaintingOverlay) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) GradientDrawable(android.graphics.drawable.GradientDrawable) PhotoPickerPhotoCell(org.telegram.ui.Cells.PhotoPickerPhotoCell) BuildConfig(org.telegram.messenger.BuildConfig) GroupedPhotosListView(org.telegram.ui.Components.GroupedPhotosListView) SpannableString(android.text.SpannableString) PhotoPaintView(org.telegram.ui.Components.PhotoPaintView) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) ClippingImageView(org.telegram.ui.Components.ClippingImageView) File(java.io.File) Gravity(android.view.Gravity) TypedValue(android.util.TypedValue) Configuration(android.content.res.Configuration) VideoForwardDrawable(org.telegram.ui.Components.VideoForwardDrawable) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ValueAnimator(android.animation.ValueAnimator) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) FadingTextViewLayout(org.telegram.ui.Components.FadingTextViewLayout) BringAppForegroundService(org.telegram.messenger.BringAppForegroundService) Spannable(android.text.Spannable) Range(android.util.Range) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) LinkMovementMethod(android.text.method.LinkMovementMethod) ViewConfiguration(android.view.ViewConfiguration) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) MediaCodecInfo(android.media.MediaCodecInfo) ContextThemeWrapper(android.view.ContextThemeWrapper) MediaController(org.telegram.messenger.MediaController) View(android.view.View) Transition(android.transition.Transition) Matrix(android.graphics.Matrix) TransitionSet(android.transition.TransitionSet) Utilities(org.telegram.messenger.Utilities) HideViewAfterAnimation(org.telegram.ui.Components.HideViewAfterAnimation) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) Touch(android.text.method.Touch) BitmapDrawable(android.graphics.drawable.BitmapDrawable) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) MediaCodec(android.media.MediaCodec) SparseArray(android.util.SparseArray) List(java.util.List) TextView(android.widget.TextView) FileProvider(androidx.core.content.FileProvider) ViewPropertyAnimator(android.view.ViewPropertyAnimator) OtherDocumentPlaceholderDrawable(org.telegram.ui.Components.OtherDocumentPlaceholderDrawable) PlayPauseDrawable(org.telegram.ui.Components.PlayPauseDrawable) VideoTimelinePlayView(org.telegram.ui.Components.VideoTimelinePlayView) OrientationEventListener(android.view.OrientationEventListener) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) PhotoFilterView(org.telegram.ui.Components.PhotoFilterView) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Context(android.content.Context) StaticLayout(android.text.StaticLayout) KeyEvent(android.view.KeyEvent) CheckBox(org.telegram.ui.Components.CheckBox) Bitmaps(org.telegram.messenger.Bitmaps) Theme(org.telegram.ui.ActionBar.Theme) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) FilterShaders(org.telegram.ui.Components.FilterShaders) HashMap(java.util.HashMap) PixelFormat(android.graphics.PixelFormat) DynamicAnimation(androidx.dynamicanimation.animation.DynamicAnimation) VelocityTracker(android.view.VelocityTracker) SuppressLint(android.annotation.SuppressLint) AccessibilityManager(android.view.accessibility.AccessibilityManager) VideoEditedInfo(org.telegram.messenger.VideoEditedInfo) MotionEvent(android.view.MotionEvent) AnimatorSet(android.animation.AnimatorSet) MediaDataController(org.telegram.messenger.MediaDataController) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) SurfaceTexture(android.graphics.SurfaceTexture) FileLog(org.telegram.messenger.FileLog) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement) MessagesController(org.telegram.messenger.MessagesController) URLEncoder(java.net.URLEncoder) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) VideoPlayerSeekBar(org.telegram.ui.Components.VideoPlayerSeekBar) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) VideoEditTextureView(org.telegram.ui.Components.VideoEditTextureView) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) SecureDocument(org.telegram.messenger.SecureDocument) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) AccessibilityManager(android.view.accessibility.AccessibilityManager) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) VideoForwardDrawable(org.telegram.ui.Components.VideoForwardDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) OtherDocumentPlaceholderDrawable(org.telegram.ui.Components.OtherDocumentPlaceholderDrawable) PlayPauseDrawable(org.telegram.ui.Components.PlayPauseDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) UserConfig(org.telegram.messenger.UserConfig) StickersAlert(org.telegram.ui.Components.StickersAlert) SpannableString(android.text.SpannableString) ActionMode(android.view.ActionMode) UserObject(org.telegram.messenger.UserObject) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) ChatObject(org.telegram.messenger.ChatObject) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ImageLocation(org.telegram.messenger.ImageLocation) FadingTextViewLayout(org.telegram.ui.Components.FadingTextViewLayout) UndoView(org.telegram.ui.Components.UndoView) PaintingOverlay(org.telegram.ui.Components.PaintingOverlay) Menu(android.view.Menu) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) PickerBottomLayoutViewer(org.telegram.ui.Components.PickerBottomLayoutViewer) LocaleController(org.telegram.messenger.LocaleController) GestureDetector2(org.telegram.ui.Components.GestureDetector2) SharedPreferences(android.content.SharedPreferences) LinearSmoothScrollerEnd(androidx.recyclerview.widget.LinearSmoothScrollerEnd) PhotoViewerCaptionEnterView(org.telegram.ui.Components.PhotoViewerCaptionEnterView) VideoTimelinePlayView(org.telegram.ui.Components.VideoTimelinePlayView) Animator(android.animation.Animator) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) ValueAnimator(android.animation.ValueAnimator) ObjectAnimator(android.animation.ObjectAnimator) ViewPropertyAnimator(android.view.ViewPropertyAnimator) TLObject(org.telegram.tgnet.TLObject) RecyclerView(androidx.recyclerview.widget.RecyclerView) Spannable(android.text.Spannable) MediaController(org.telegram.messenger.MediaController) HashMap(java.util.HashMap) SpannableStringBuilder(android.text.SpannableStringBuilder) SizeNotifierFrameLayoutPhoto(org.telegram.ui.Components.SizeNotifierFrameLayoutPhoto) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) ImageReceiver(org.telegram.messenger.ImageReceiver) GroupedPhotosListView(org.telegram.ui.Components.GroupedPhotosListView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) SpoilersTextView(org.telegram.ui.Components.spoilers.SpoilersTextView) TextView(android.widget.TextView) ArrayList(java.util.ArrayList) List(java.util.List) BackupImageView(org.telegram.ui.Components.BackupImageView) ImageView(android.widget.ImageView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) RadialProgressView(org.telegram.ui.Components.RadialProgressView) NumberPicker(org.telegram.ui.Components.NumberPicker) Canvas(android.graphics.Canvas) Tooltip(org.telegram.ui.Components.Tooltip) LinkMovementMethod(android.text.method.LinkMovementMethod) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) GradientDrawable(android.graphics.drawable.GradientDrawable) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) CheckBox(org.telegram.ui.Components.CheckBox) OverScroller(android.widget.OverScroller) Scroller(android.widget.Scroller) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) WebFile(org.telegram.messenger.WebFile) File(java.io.File) AnimatorSet(android.animation.AnimatorSet) WindowManager(android.view.WindowManager) KeyEvent(android.view.KeyEvent) WindowInsets(android.view.WindowInsets) Bitmap(android.graphics.Bitmap) URLSpanUserMentionPhotoViewer(org.telegram.ui.Components.URLSpanUserMentionPhotoViewer) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Bundle(android.os.Bundle) VideoForwardDrawable(org.telegram.ui.Components.VideoForwardDrawable) PhotoCropView(org.telegram.ui.Components.PhotoCropView) PhotoViewerWebView(org.telegram.ui.Components.PhotoViewerWebView) CropView(org.telegram.ui.Components.Crop.CropView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) SpoilersTextView(org.telegram.ui.Components.spoilers.SpoilersTextView) NestedScrollView(androidx.core.widget.NestedScrollView) RecyclerView(androidx.recyclerview.widget.RecyclerView) PipVideoView(org.telegram.ui.Components.PipVideoView) BackupImageView(org.telegram.ui.Components.BackupImageView) TextureView(android.view.TextureView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) PhotoViewerCaptionEnterView(org.telegram.ui.Components.PhotoViewerCaptionEnterView) UndoView(org.telegram.ui.Components.UndoView) VideoEditTextureView(org.telegram.ui.Components.VideoEditTextureView) GroupedPhotosListView(org.telegram.ui.Components.GroupedPhotosListView) PhotoPaintView(org.telegram.ui.Components.PhotoPaintView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) View(android.view.View) TextView(android.widget.TextView) VideoTimelinePlayView(org.telegram.ui.Components.VideoTimelinePlayView) PhotoFilterView(org.telegram.ui.Components.PhotoFilterView) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) Date(java.util.Date) MotionEvent(android.view.MotionEvent) ContextThemeWrapper(android.view.ContextThemeWrapper) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) FrameLayout(android.widget.FrameLayout) MediaActivity(org.telegram.ui.Components.MediaActivity) Vibrator(android.os.Vibrator) MessageObject(org.telegram.messenger.MessageObject) LinearLayout(android.widget.LinearLayout) ClippingImageView(org.telegram.ui.Components.ClippingImageView)

Example 5 with ActionBarPopupWindow

use of org.telegram.ui.ActionBar.ActionBarPopupWindow in project Telegram-FOSS by Telegram-FOSS-Team.

the class GroupCallActivity method showMenuForCell.

private boolean showMenuForCell(View rendererCell) {
    if (itemAnimator.isRunning()) {
        return false;
    }
    if (avatarPriviewTransitionInProgress || avatarsPreviewShowed) {
        dismissAvatarPreview(true);
        return false;
    }
    if (scrimPopupWindow != null) {
        scrimPopupWindow.dismiss();
        scrimPopupWindow = null;
        return false;
    }
    clearScrimView();
    GroupCallUserCell view;
    if (rendererCell instanceof GroupCallGridCell) {
        GroupCallGridCell groupCallGridCell = ((GroupCallGridCell) rendererCell);
        if (groupCallGridCell.getParticipant() == call.videoNotAvailableParticipant) {
            return false;
        }
        view = new GroupCallUserCell(groupCallGridCell.getContext());
        long selfPeerId = MessageObject.getPeerId(selfPeer);
        view.setData(accountInstance, groupCallGridCell.getParticipant().participant, call, selfPeerId, null, false);
        hasScrimAnchorView = false;
        scrimGridView = groupCallGridCell;
        scrimRenderer = groupCallGridCell.getRenderer();
        if (!isTabletMode && !isLandscapeMode) {
            scrimViewAttached = true;
            containerView.addView(view, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 14, 0, 14, 0));
        } else {
            scrimViewAttached = false;
        }
    } else if (rendererCell instanceof GroupCallFullscreenAdapter.GroupCallUserCell) {
        GroupCallFullscreenAdapter.GroupCallUserCell groupCallFullscreenCell = ((GroupCallFullscreenAdapter.GroupCallUserCell) rendererCell);
        if (groupCallFullscreenCell.getParticipant() == call.videoNotAvailableParticipant.participant) {
            return false;
        }
        view = new GroupCallUserCell(groupCallFullscreenCell.getContext());
        long selfPeerId = MessageObject.getPeerId(selfPeer);
        view.setData(accountInstance, groupCallFullscreenCell.getParticipant(), call, selfPeerId, null, false);
        hasScrimAnchorView = false;
        scrimFullscreenView = groupCallFullscreenCell;
        scrimRenderer = groupCallFullscreenCell.getRenderer();
        if (scrimRenderer != null && scrimRenderer.showingInFullscreen) {
            scrimRenderer = null;
        }
        containerView.addView(view, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 14, 0, 14, 0));
        scrimViewAttached = true;
    } else {
        view = (GroupCallUserCell) rendererCell;
        hasScrimAnchorView = true;
        scrimViewAttached = true;
    }
    if (view == null) {
        return false;
    }
    boolean showWithAvatarPreview = !isLandscapeMode && !isTabletMode && !AndroidUtilities.isInMultiwindow;
    TLRPC.TL_groupCallParticipant participant = view.getParticipant();
    Rect rect = new Rect();
    ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext());
    popupLayout.setBackgroundDrawable(null);
    popupLayout.setPadding(0, 0, 0, 0);
    popupLayout.setOnTouchListener(new View.OnTouchListener() {

        private int[] pos = new int[2];

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                if (scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                    View contentView = scrimPopupWindow.getContentView();
                    contentView.getLocationInWindow(pos);
                    rect.set(pos[0], pos[1], pos[0] + contentView.getMeasuredWidth(), pos[1] + contentView.getMeasuredHeight());
                    if (!rect.contains((int) event.getX(), (int) event.getY())) {
                        scrimPopupWindow.dismiss();
                    }
                }
            } else if (event.getActionMasked() == MotionEvent.ACTION_OUTSIDE) {
                if (scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                    scrimPopupWindow.dismiss();
                }
            }
            return false;
        }
    });
    popupLayout.setDispatchKeyEventListener(keyEvent -> {
        if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
            scrimPopupWindow.dismiss();
        }
    });
    LinearLayout buttonsLayout = new LinearLayout(getContext());
    LinearLayout volumeLayout = !participant.muted_by_you ? new LinearLayout(getContext()) : null;
    currentOptionsLayout = buttonsLayout;
    LinearLayout linearLayout = new LinearLayout(getContext()) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            buttonsLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            if (volumeLayout != null) {
                volumeLayout.measure(MeasureSpec.makeMeasureSpec(buttonsLayout.getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                setMeasuredDimension(buttonsLayout.getMeasuredWidth(), buttonsLayout.getMeasuredHeight() + volumeLayout.getMeasuredHeight());
            } else {
                setMeasuredDimension(buttonsLayout.getMeasuredWidth(), buttonsLayout.getMeasuredHeight());
            }
        }
    };
    linearLayout.setMinimumWidth(AndroidUtilities.dp(240));
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    VolumeSlider volumeSlider = null;
    int color = AndroidUtilities.getOffsetColor(Theme.getColor(Theme.key_voipgroup_listViewBackgroundUnscrolled), Theme.getColor(Theme.key_voipgroup_listViewBackground), colorProgress, 1.0f);
    if (volumeLayout != null && !view.isSelfUser() && !participant.muted_by_you && (!participant.muted || participant.can_self_unmute)) {
        Drawable shadowDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
        volumeLayout.setBackgroundDrawable(shadowDrawable);
        linearLayout.addView(volumeLayout, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0));
        volumeSlider = new VolumeSlider(getContext(), participant);
        volumeLayout.addView(volumeSlider, LayoutHelper.MATCH_PARENT, 48);
    }
    buttonsLayout.setMinimumWidth(AndroidUtilities.dp(240));
    buttonsLayout.setOrientation(LinearLayout.VERTICAL);
    Drawable shadowDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
    buttonsLayout.setBackgroundDrawable(shadowDrawable);
    linearLayout.addView(buttonsLayout, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, volumeSlider != null ? -8 : 0, 0, 0));
    ScrollView scrollView;
    if (Build.VERSION.SDK_INT >= 21) {
        scrollView = new ScrollView(getContext(), null, 0, R.style.scrollbarShapeStyle) {

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                setMeasuredDimension(linearLayout.getMeasuredWidth(), getMeasuredHeight());
            }
        };
    } else {
        scrollView = new ScrollView(getContext());
    }
    scrollView.setClipToPadding(false);
    popupLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    long peerId = MessageObject.getPeerId(participant.peer);
    ArrayList<String> items = new ArrayList<>(2);
    ArrayList<Integer> icons = new ArrayList<>(2);
    ArrayList<Integer> options = new ArrayList<>(2);
    boolean isAdmin = false;
    if (participant.peer instanceof TLRPC.TL_peerUser) {
        if (ChatObject.isChannel(currentChat)) {
            TLRPC.ChannelParticipant p = accountInstance.getMessagesController().getAdminInChannel(participant.peer.user_id, currentChat.id);
            isAdmin = p != null && (p instanceof TLRPC.TL_channelParticipantCreator || p.admin_rights.manage_call);
        } else {
            TLRPC.ChatFull chatFull = accountInstance.getMessagesController().getChatFull(currentChat.id);
            if (chatFull != null && chatFull.participants != null) {
                for (int a = 0, N = chatFull.participants.participants.size(); a < N; a++) {
                    TLRPC.ChatParticipant chatParticipant = chatFull.participants.participants.get(a);
                    if (chatParticipant.user_id == participant.peer.user_id) {
                        isAdmin = chatParticipant instanceof TLRPC.TL_chatParticipantAdmin || chatParticipant instanceof TLRPC.TL_chatParticipantCreator;
                        break;
                    }
                }
            }
        }
    } else {
        isAdmin = peerId == -currentChat.id;
    }
    if (view.isSelfUser()) {
        if (view.isHandRaised()) {
            items.add(LocaleController.getString("VoipGroupCancelRaiseHand", R.string.VoipGroupCancelRaiseHand));
            icons.add(R.drawable.msg_handdown);
            options.add(7);
        }
        items.add(view.hasAvatarSet() ? LocaleController.getString("VoipAddPhoto", R.string.VoipAddPhoto) : LocaleController.getString("VoipSetNewPhoto", R.string.VoipSetNewPhoto));
        icons.add(R.drawable.msg_addphoto);
        options.add(9);
        if (peerId > 0) {
            items.add(TextUtils.isEmpty(participant.about) ? LocaleController.getString("VoipAddBio", R.string.VoipAddBio) : LocaleController.getString("VoipEditBio", R.string.VoipEditBio));
        } else {
            items.add(TextUtils.isEmpty(participant.about) ? LocaleController.getString("VoipAddDescription", R.string.VoipAddDescription) : LocaleController.getString("VoipEditDescription", R.string.VoipEditDescription));
        }
        icons.add(TextUtils.isEmpty(participant.about) ? R.drawable.msg_addbio : R.drawable.msg_bio);
        options.add(10);
        items.add(peerId > 0 ? LocaleController.getString("VoipEditName", R.string.VoipEditName) : LocaleController.getString("VoipEditTitle", R.string.VoipEditTitle));
        icons.add(R.drawable.msg_edit);
        options.add(11);
    } else if (ChatObject.canManageCalls(currentChat)) {
        if (!isAdmin || !participant.muted) {
            if (!participant.muted || participant.can_self_unmute) {
                items.add(LocaleController.getString("VoipGroupMute", R.string.VoipGroupMute));
                icons.add(R.drawable.msg_voice_muted);
                options.add(0);
            } else {
                items.add(LocaleController.getString("VoipGroupAllowToSpeak", R.string.VoipGroupAllowToSpeak));
                if (participant.raise_hand_rating != 0) {
                    icons.add(R.drawable.msg_allowspeak);
                } else {
                    icons.add(R.drawable.msg_voice_unmuted);
                }
                options.add(1);
            }
        }
        if (participant.peer.channel_id != 0 && !ChatObject.isMegagroup(currentAccount, participant.peer.channel_id)) {
            items.add(LocaleController.getString("VoipGroupOpenChannel", R.string.VoipGroupOpenChannel));
            icons.add(R.drawable.msg_channel);
            options.add(8);
        } else {
            items.add(LocaleController.getString("VoipGroupOpenProfile", R.string.VoipGroupOpenProfile));
            icons.add(R.drawable.msg_openprofile);
            options.add(6);
        }
        if (!isAdmin && ChatObject.canBlockUsers(currentChat)) {
            items.add(LocaleController.getString("VoipGroupUserRemove", R.string.VoipGroupUserRemove));
            icons.add(R.drawable.msg_block2);
            options.add(2);
        }
    } else {
        if (participant.muted_by_you) {
            items.add(LocaleController.getString("VoipGroupUnmuteForMe", R.string.VoipGroupUnmuteForMe));
            icons.add(R.drawable.msg_voice_unmuted);
            options.add(4);
        } else {
            items.add(LocaleController.getString("VoipGroupMuteForMe", R.string.VoipGroupMuteForMe));
            icons.add(R.drawable.msg_voice_muted);
            options.add(5);
        }
        if (participant.peer.channel_id != 0 && !ChatObject.isMegagroup(currentAccount, participant.peer.channel_id)) {
            items.add(LocaleController.getString("VoipGroupOpenChannel", R.string.VoipGroupOpenChannel));
            icons.add(R.drawable.msg_msgbubble3);
            options.add(8);
        } else {
            items.add(LocaleController.getString("VoipGroupOpenChat", R.string.VoipGroupOpenChat));
            icons.add(R.drawable.msg_msgbubble3);
            options.add(6);
        }
    }
    for (int a = 0, N = items.size(); a < N; a++) {
        ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), a == 0, a == N - 1);
        if (options.get(a) != 2) {
            cell.setColors(Theme.getColor(Theme.key_voipgroup_actionBarItems), Theme.getColor(Theme.key_voipgroup_actionBarItems));
        } else {
            cell.setColors(Theme.getColor(Theme.key_voipgroup_leaveCallMenu), Theme.getColor(Theme.key_voipgroup_leaveCallMenu));
        }
        cell.setSelectorColor(Theme.getColor(Theme.key_voipgroup_listSelector));
        cell.setTextAndIcon(items.get(a), icons.get(a));
        buttonsLayout.addView(cell);
        final int i = a;
        cell.setTag(options.get(a));
        cell.setOnClickListener(v1 -> {
            if (i >= options.size()) {
                return;
            }
            TLRPC.TL_groupCallParticipant participant1 = call.participants.get(MessageObject.getPeerId(participant.peer));
            if (participant1 == null) {
                participant1 = participant;
            }
            processSelectedOption(participant1, MessageObject.getPeerId(participant1.peer), options.get(i));
            if (scrimPopupWindow != null) {
                scrimPopupWindow.dismiss();
            } else {
                if (options.get(i) != 9 && options.get(i) != 10 && options.get(i) != 11) {
                    dismissAvatarPreview(true);
                }
            }
        });
    }
    scrollView.addView(linearLayout, LayoutHelper.createScroll(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
    listView.stopScroll();
    layoutManager.setCanScrollVertically(false);
    scrimView = view;
    scrimView.setAboutVisible(true);
    containerView.invalidate();
    listView.invalidate();
    if (scrimAnimatorSet != null) {
        scrimAnimatorSet.cancel();
    }
    scrimPopupLayout = popupLayout;
    final ImageLocation imageLocation;
    final ImageLocation thumbLocation;
    if (peerId > 0) {
        TLRPC.User currentUser = accountInstance.getMessagesController().getUser(peerId);
        imageLocation = ImageLocation.getForUserOrChat(currentUser, ImageLocation.TYPE_BIG);
        thumbLocation = ImageLocation.getForUserOrChat(currentUser, ImageLocation.TYPE_SMALL);
    } else {
        TLRPC.Chat currentChat = accountInstance.getMessagesController().getChat(-peerId);
        imageLocation = ImageLocation.getForUserOrChat(currentChat, ImageLocation.TYPE_BIG);
        thumbLocation = ImageLocation.getForUserOrChat(currentChat, ImageLocation.TYPE_SMALL);
    }
    boolean hasAttachedRenderer = scrimRenderer != null && scrimRenderer.isAttached();
    if (imageLocation == null && !hasAttachedRenderer) {
        showWithAvatarPreview = false;
    } else if (showWithAvatarPreview) {
        avatarsViewPager.setParentAvatarImage(scrimView.getAvatarImageView());
        avatarsViewPager.setHasActiveVideo(hasAttachedRenderer);
        avatarsViewPager.setData(peerId, true);
        avatarsViewPager.setCreateThumbFromParent(true);
        avatarsViewPager.initIfEmpty(imageLocation, thumbLocation);
        if (scrimRenderer != null) {
            scrimRenderer.setShowingAsScrimView(true, true);
        }
        if (MessageObject.getPeerId(selfPeer) == peerId && currentAvatarUpdater != null && avatarUpdaterDelegate != null && avatarUpdaterDelegate.avatar != null) {
            avatarsViewPager.addUploadingImage(avatarUpdaterDelegate.uploadingImageLocation, ImageLocation.getForLocal(avatarUpdaterDelegate.avatar));
        }
    }
    if (showWithAvatarPreview) {
        avatarsPreviewShowed = true;
        popupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
        containerView.addView(scrimPopupLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
        // scrimFullscreenView == null;
        useBlur = true;
        if (useBlur) {
            prepareBlurBitmap();
        }
        avatarPriviewTransitionInProgress = true;
        avatarPreviewContainer.setVisibility(View.VISIBLE);
        if (volumeSlider != null) {
            volumeSlider.invalidate();
        }
        runAvatarPreviewTransition(true, view);
        if (scrimFullscreenView != null) {
            scrimFullscreenView.getAvatarImageView().setAlpha(0f);
        }
    } else {
        avatarsPreviewShowed = false;
        scrimPopupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) {

            @Override
            public void dismiss() {
                super.dismiss();
                if (scrimPopupWindow != this) {
                    return;
                }
                scrimPopupWindow = null;
                if (scrimAnimatorSet != null) {
                    scrimAnimatorSet.cancel();
                    scrimAnimatorSet = null;
                }
                layoutManager.setCanScrollVertically(true);
                scrimAnimatorSet = new AnimatorSet();
                ArrayList<Animator> animators = new ArrayList<>();
                animators.add(ObjectAnimator.ofInt(scrimPaint, AnimationProperties.PAINT_ALPHA, 0));
                scrimAnimatorSet.playTogether(animators);
                scrimAnimatorSet.setDuration(220);
                scrimAnimatorSet.addListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        clearScrimView();
                        containerView.invalidate();
                        listView.invalidate();
                        if (delayedGroupCallUpdated) {
                            delayedGroupCallUpdated = false;
                            applyCallParticipantUpdates(true);
                        }
                    }
                });
                scrimAnimatorSet.start();
            }
        };
        scrimPopupWindow.setPauseNotifications(true);
        scrimPopupWindow.setDismissAnimationDuration(220);
        scrimPopupWindow.setOutsideTouchable(true);
        scrimPopupWindow.setClippingEnabled(true);
        scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation);
        scrimPopupWindow.setFocusable(true);
        popupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
        scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
        scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
        scrimPopupWindow.getContentView().setFocusableInTouchMode(true);
        int popupX, popupY;
        if (scrimFullscreenView != null) {
            if (isLandscapeMode) {
                popupX = (int) (scrimFullscreenView.getX() + fullscreenUsersListView.getX() + renderersContainer.getX()) - popupLayout.getMeasuredWidth() + AndroidUtilities.dp(32);
                popupY = (int) (scrimFullscreenView.getY() + fullscreenUsersListView.getY() + renderersContainer.getY()) - AndroidUtilities.dp(6);
            } else {
                popupX = (int) (scrimFullscreenView.getX() + fullscreenUsersListView.getX() + renderersContainer.getX()) - AndroidUtilities.dp(14);
                popupY = (int) (scrimFullscreenView.getY() + fullscreenUsersListView.getY() + renderersContainer.getY() - popupLayout.getMeasuredHeight());
            }
        } else {
            popupX = (int) (listView.getX() + listView.getMeasuredWidth() + AndroidUtilities.dp(8) - popupLayout.getMeasuredWidth());
            if (hasScrimAnchorView) {
                popupY = (int) (listView.getY() + view.getY() + view.getClipHeight());
            } else if (scrimGridView != null) {
                popupY = (int) (listView.getY() + scrimGridView.getY() + scrimGridView.getMeasuredHeight());
            } else {
                popupY = (int) listView.getY();
            }
        }
        scrimPopupWindow.showAtLocation(listView, Gravity.LEFT | Gravity.TOP, popupX, popupY);
        scrimAnimatorSet = new AnimatorSet();
        ArrayList<Animator> animators = new ArrayList<>();
        animators.add(ObjectAnimator.ofInt(scrimPaint, AnimationProperties.PAINT_ALPHA, 0, 100));
        scrimAnimatorSet.playTogether(animators);
        scrimAnimatorSet.setDuration(150);
        scrimAnimatorSet.start();
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) AnimatorSet(android.animation.AnimatorSet) TLRPC(org.telegram.tgnet.TLRPC) ImageLocation(org.telegram.messenger.ImageLocation) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) GroupCallFullscreenAdapter(org.telegram.ui.Components.GroupCallFullscreenAdapter) GroupCallUserCell(org.telegram.ui.Cells.GroupCallUserCell) Rect(android.graphics.Rect) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) CellFlickerDrawable(org.telegram.ui.Components.voip.CellFlickerDrawable) BlobDrawable(org.telegram.ui.Components.BlobDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) WaveDrawable(org.telegram.ui.Components.WaveDrawable) RecordStatusDrawable(org.telegram.ui.Components.RecordStatusDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) GroupCallGridCell(org.telegram.ui.Components.voip.GroupCallGridCell) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ProfileGalleryView(org.telegram.ui.Components.ProfileGalleryView) UndoView(org.telegram.ui.Components.UndoView) HintView(org.telegram.ui.Components.HintView) GroupCallMiniTextureView(org.telegram.ui.Components.voip.GroupCallMiniTextureView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) ScrollView(android.widget.ScrollView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ValueAnimator(android.animation.ValueAnimator) Animator(android.animation.Animator) ObjectAnimator(android.animation.ObjectAnimator) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) ScrollView(android.widget.ScrollView) LinearLayout(android.widget.LinearLayout)

Aggregations

ActionBarPopupWindow (org.telegram.ui.ActionBar.ActionBarPopupWindow)16 TextView (android.widget.TextView)12 Rect (android.graphics.Rect)11 SuppressLint (android.annotation.SuppressLint)10 Paint (android.graphics.Paint)10 MotionEvent (android.view.MotionEvent)10 View (android.view.View)10 ImageView (android.widget.ImageView)10 ActionBarMenuSubItem (org.telegram.ui.ActionBar.ActionBarMenuSubItem)10 RecyclerView (androidx.recyclerview.widget.RecyclerView)9 TextPaint (android.text.TextPaint)8 Drawable (android.graphics.drawable.Drawable)7 TLRPC (org.telegram.tgnet.TLRPC)7 SimpleTextView (org.telegram.ui.ActionBar.SimpleTextView)7 BackupImageView (org.telegram.ui.Components.BackupImageView)7 RecyclerListView (org.telegram.ui.Components.RecyclerListView)7 PorterDuffColorFilter (android.graphics.PorterDuffColorFilter)6 FrameLayout (android.widget.FrameLayout)6 LinearLayout (android.widget.LinearLayout)6 Animator (android.animation.Animator)5