Search in sources :

Example 1 with StickersAlert

use of org.telegram.ui.Components.StickersAlert in project Telegram-FOSS by Telegram-FOSS-Team.

the class ChannelAdminLogActivity method createMenu.

private void createMenu(View v) {
    MessageObject message = null;
    if (v instanceof ChatMessageCell) {
        message = ((ChatMessageCell) v).getMessageObject();
    } else if (v instanceof ChatActionCell) {
        message = ((ChatActionCell) v).getMessageObject();
    }
    if (message == null) {
        return;
    }
    final int type = getMessageType(message);
    selectedObject = message;
    if (getParentActivity() == null) {
        return;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    ArrayList<CharSequence> items = new ArrayList<>();
    final ArrayList<Integer> options = new ArrayList<>();
    if (selectedObject.type == 0 || selectedObject.caption != null) {
        items.add(LocaleController.getString("Copy", R.string.Copy));
        options.add(3);
    }
    if (type == 1) {
        if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeStickerSet) {
            TLRPC.TL_channelAdminLogEventActionChangeStickerSet action = (TLRPC.TL_channelAdminLogEventActionChangeStickerSet) selectedObject.currentEvent.action;
            TLRPC.InputStickerSet stickerSet = action.new_stickerset;
            if (stickerSet == null || stickerSet instanceof TLRPC.TL_inputStickerSetEmpty) {
                stickerSet = action.prev_stickerset;
            }
            if (stickerSet != null) {
                showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, stickerSet, null, null));
                return;
            }
        } else if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeHistoryTTL) {
            if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) {
                ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), null, currentChat, false, null);
                alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() {

                    @Override
                    public void onAutoDeleteHistory(int ttl, int action) {
                        getMessagesController().setDialogHistoryTTL(-currentChat.id, ttl);
                        TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id);
                        if (chatInfo != null) {
                            undoView.showWithAction(-currentChat.id, action, null, chatInfo.ttl_period, null, null);
                        }
                    }
                });
                showDialog(alert);
            }
        }
    } else if (type == 3) {
        if (selectedObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && MessageObject.isNewGifDocument(selectedObject.messageOwner.media.webpage.document)) {
            items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs));
            options.add(11);
        }
    } else if (type == 4) {
        if (selectedObject.isVideo()) {
            items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
            options.add(4);
            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
            options.add(6);
        } else if (selectedObject.isMusic()) {
            items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic));
            options.add(10);
            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
            options.add(6);
        } else if (selectedObject.getDocument() != null) {
            if (MessageObject.isNewGifDocument(selectedObject.getDocument())) {
                items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs));
                options.add(11);
            }
            items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
            options.add(10);
            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
            options.add(6);
        } else {
            items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
            options.add(4);
        }
    } else if (type == 5) {
        items.add(LocaleController.getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile));
        options.add(5);
        items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
        options.add(10);
        items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
        options.add(6);
    } else if (type == 10) {
        items.add(LocaleController.getString("ApplyThemeFile", R.string.ApplyThemeFile));
        options.add(5);
        items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
        options.add(10);
        items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
        options.add(6);
    } else if (type == 6) {
        items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
        options.add(7);
        items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
        options.add(10);
        items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
        options.add(6);
    } else if (type == 7) {
        if (selectedObject.isMask()) {
            items.add(LocaleController.getString("AddToMasks", R.string.AddToMasks));
        } else {
            items.add(LocaleController.getString("AddToStickers", R.string.AddToStickers));
        }
        options.add(9);
    } else if (type == 8) {
        long uid = selectedObject.messageOwner.media.user_id;
        TLRPC.User user = null;
        if (uid != 0) {
            user = MessagesController.getInstance(currentAccount).getUser(uid);
        }
        if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && ContactsController.getInstance(currentAccount).contactsDict.get(user.id) == null) {
            items.add(LocaleController.getString("AddContactTitle", R.string.AddContactTitle));
            options.add(15);
        }
        if (!TextUtils.isEmpty(selectedObject.messageOwner.media.phone_number)) {
            items.add(LocaleController.getString("Copy", R.string.Copy));
            options.add(16);
            items.add(LocaleController.getString("Call", R.string.Call));
            options.add(17);
        }
    }
    if (options.isEmpty()) {
        return;
    }
    final CharSequence[] finalItems = items.toArray(new CharSequence[0]);
    builder.setItems(finalItems, (dialogInterface, i) -> {
        if (selectedObject == null || i < 0 || i >= options.size()) {
            return;
        }
        processSelectedOption(options.get(i));
    });
    builder.setTitle(LocaleController.getString("Message", R.string.Message));
    showDialog(builder.create());
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) Paint(android.graphics.Paint) StickersAlert(org.telegram.ui.Components.StickersAlert) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) MessageObject(org.telegram.messenger.MessageObject)

Example 2 with StickersAlert

use of org.telegram.ui.Components.StickersAlert 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 3 with StickersAlert

use of org.telegram.ui.Components.StickersAlert in project Telegram-FOSS by Telegram-FOSS-Team.

the class LaunchActivity method handleIntent.

private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) {
    if (AndroidUtilities.handleProxyIntent(this, intent)) {
        actionBarLayout.showLastFragment();
        if (AndroidUtilities.isTablet()) {
            layersActionBarLayout.showLastFragment();
            rightActionBarLayout.showLastFragment();
        }
        return true;
    }
    if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
        if (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) {
            PhotoViewer.getInstance().closePhoto(false, true);
        }
    }
    int flags = intent.getFlags();
    String action = intent.getAction();
    final int[] intentAccount = new int[] { intent.getIntExtra("currentAccount", UserConfig.selectedAccount) };
    switchToAccount(intentAccount[0], true);
    boolean isVoipIntent = action != null && action.equals("voip");
    if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || SharedConfig.isWaitingForPasscodeEnter)) {
        showPasscodeActivity(true, false, -1, -1, null, null);
        UserConfig.getInstance(currentAccount).saveConfig(false);
        if (!isVoipIntent) {
            passcodeSaveIntent = intent;
            passcodeSaveIntentIsNew = isNew;
            passcodeSaveIntentIsRestore = restore;
            return false;
        }
    }
    boolean pushOpened = false;
    long push_user_id = 0;
    long push_chat_id = 0;
    int push_enc_id = 0;
    int push_msg_id = 0;
    int open_settings = 0;
    int open_widget_edit = -1;
    int open_widget_edit_type = -1;
    int open_new_dialog = 0;
    long dialogId = 0;
    boolean showDialogsList = false;
    boolean showPlayer = false;
    boolean showLocations = false;
    boolean showGroupVoip = false;
    boolean showCallLog = false;
    boolean audioCallUser = false;
    boolean videoCallUser = false;
    boolean needCallAlert = false;
    boolean newContact = false;
    boolean newContactAlert = false;
    boolean scanQr = false;
    String searchQuery = null;
    String callSearchQuery = null;
    String newContactName = null;
    String newContactPhone = null;
    photoPathsArray = null;
    videoPath = null;
    sendingText = null;
    sendingLocation = null;
    documentsPathsArray = null;
    documentsOriginalPathsArray = null;
    documentsMimeType = null;
    documentsUrisArray = null;
    exportingChatUri = null;
    contactsToSend = null;
    contactsToSendUri = null;
    importingStickers = null;
    importingStickersEmoji = null;
    importingStickersSoftware = null;
    if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
        if (intent != null && intent.getAction() != null && !restore) {
            if (Intent.ACTION_SEND.equals(intent.getAction())) {
                if (SharedConfig.directShare && intent != null && intent.getExtras() != null) {
                    dialogId = intent.getExtras().getLong("dialogId", 0);
                    String hash = null;
                    if (dialogId == 0) {
                        try {
                            String id = intent.getExtras().getString(ShortcutManagerCompat.EXTRA_SHORTCUT_ID);
                            if (id != null) {
                                List<ShortcutInfoCompat> list = ShortcutManagerCompat.getDynamicShortcuts(ApplicationLoader.applicationContext);
                                for (int a = 0, N = list.size(); a < N; a++) {
                                    ShortcutInfoCompat info = list.get(a);
                                    if (id.equals(info.getId())) {
                                        Bundle extras = info.getIntent().getExtras();
                                        dialogId = extras.getLong("dialogId", 0);
                                        hash = extras.getString("hash", null);
                                        break;
                                    }
                                }
                            }
                        } catch (Throwable e) {
                            FileLog.e(e);
                        }
                    } else {
                        hash = intent.getExtras().getString("hash", null);
                    }
                    if (SharedConfig.directShareHash == null || !SharedConfig.directShareHash.equals(hash)) {
                        dialogId = 0;
                    }
                }
                boolean error = false;
                String type = intent.getType();
                if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) {
                    try {
                        Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            contactsToSend = AndroidUtilities.loadVCardFromStream(uri, currentAccount, false, null, null);
                            if (contactsToSend.size() > 5) {
                                contactsToSend = null;
                                documentsUrisArray = new ArrayList<>();
                                documentsUrisArray.add(uri);
                                documentsMimeType = type;
                            } else {
                                contactsToSendUri = uri;
                            }
                        } else {
                            error = true;
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                        error = true;
                    }
                } else {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text == null) {
                        CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
                        if (textSequence != null) {
                            text = textSequence.toString();
                        }
                    }
                    String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
                    if (!TextUtils.isEmpty(text)) {
                        Matcher m = locationRegex.matcher(text);
                        if (m.find()) {
                            String[] lines = text.split("\\n");
                            String venueTitle = null;
                            String venueAddress = null;
                            if (lines[0].equals("My Position")) {
                            // Use normal GeoPoint message (user position)
                            } else if (!lines[0].contains("geo:")) {
                                venueTitle = lines[0];
                                if (!lines[1].contains("geo:")) {
                                    venueAddress = lines[1];
                                }
                            }
                            sendingLocation = new Location("");
                            sendingLocation.setLatitude(Double.parseDouble(m.group(1)));
                            sendingLocation.setLongitude(Double.parseDouble(m.group(2)));
                            Bundle bundle = new Bundle();
                            bundle.putCharSequence("venueTitle", venueTitle);
                            bundle.putCharSequence("venueAddress", venueAddress);
                            sendingLocation.setExtras(bundle);
                        } else if ((text.startsWith("http://") || text.startsWith("https://")) && !TextUtils.isEmpty(subject)) {
                            text = subject + "\n" + text;
                        }
                        sendingText = text;
                    } else if (!TextUtils.isEmpty(subject)) {
                        sendingText = subject;
                    }
                    Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    if (parcelable != null) {
                        String path;
                        if (!(parcelable instanceof Uri)) {
                            parcelable = Uri.parse(parcelable.toString());
                        }
                        Uri uri = (Uri) parcelable;
                        if (uri != null) {
                            if (AndroidUtilities.isInternalUri(uri)) {
                                error = true;
                            }
                        }
                        if (!error && uri != null) {
                            if (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg")) {
                                if (photoPathsArray == null) {
                                    photoPathsArray = new ArrayList<>();
                                }
                                SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                                info.uri = uri;
                                photoPathsArray.add(info);
                            } else {
                                String originalPath = uri.toString();
                                if (dialogId == 0 && originalPath != null) {
                                    if (BuildVars.LOGS_ENABLED) {
                                        FileLog.d("export path = " + originalPath);
                                    }
                                    Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
                                    String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
                                    for (String u : exportUris) {
                                        try {
                                            Pattern pattern = Pattern.compile(u);
                                            if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
                                                exportingChatUri = uri;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    }
                                    if (exportingChatUri == null) {
                                        if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
                                            exportingChatUri = uri;
                                        }
                                    }
                                }
                                if (exportingChatUri == null) {
                                    path = AndroidUtilities.getPath(uri);
                                    if (!BuildVars.NO_SCOPED_STORAGE) {
                                        path = MediaController.copyFileToCache(uri, "file");
                                    }
                                    if (path != null) {
                                        if (path.startsWith("file:")) {
                                            path = path.replace("file://", "");
                                        }
                                        if (type != null && type.startsWith("video/")) {
                                            videoPath = path;
                                        } else {
                                            if (documentsPathsArray == null) {
                                                documentsPathsArray = new ArrayList<>();
                                                documentsOriginalPathsArray = new ArrayList<>();
                                            }
                                            documentsPathsArray.add(path);
                                            documentsOriginalPathsArray.add(uri.toString());
                                        }
                                    } else {
                                        if (documentsUrisArray == null) {
                                            documentsUrisArray = new ArrayList<>();
                                        }
                                        documentsUrisArray.add(uri);
                                        documentsMimeType = type;
                                    }
                                }
                            }
                        }
                    } else if (sendingText == null && sendingLocation == null) {
                        error = true;
                    }
                }
                if (error) {
                    Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                }
            } else if ("org.telegram.messenger.CREATE_STICKER_PACK".equals(intent.getAction())) {
                try {
                    importingStickers = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    importingStickersEmoji = intent.getStringArrayListExtra("STICKER_EMOJIS");
                    importingStickersSoftware = intent.getStringExtra("IMPORTER");
                } catch (Throwable e) {
                    FileLog.e(e);
                    importingStickers = null;
                    importingStickersEmoji = null;
                    importingStickersSoftware = null;
                }
            } else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
                boolean error = false;
                try {
                    ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    String type = intent.getType();
                    if (uris != null) {
                        for (int a = 0; a < uris.size(); a++) {
                            Parcelable parcelable = uris.get(a);
                            if (!(parcelable instanceof Uri)) {
                                parcelable = Uri.parse(parcelable.toString());
                            }
                            Uri uri = (Uri) parcelable;
                            if (uri != null) {
                                if (AndroidUtilities.isInternalUri(uri)) {
                                    uris.remove(a);
                                    a--;
                                }
                            }
                        }
                        if (uris.isEmpty()) {
                            uris = null;
                        }
                    }
                    if (uris != null) {
                        if (type != null && type.startsWith("image/")) {
                            for (int a = 0; a < uris.size(); a++) {
                                Parcelable parcelable = uris.get(a);
                                if (!(parcelable instanceof Uri)) {
                                    parcelable = Uri.parse(parcelable.toString());
                                }
                                Uri uri = (Uri) parcelable;
                                if (photoPathsArray == null) {
                                    photoPathsArray = new ArrayList<>();
                                }
                                SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                                info.uri = uri;
                                photoPathsArray.add(info);
                            }
                        } else {
                            Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
                            for (int a = 0; a < uris.size(); a++) {
                                Parcelable parcelable = uris.get(a);
                                if (!(parcelable instanceof Uri)) {
                                    parcelable = Uri.parse(parcelable.toString());
                                }
                                Uri uri = (Uri) parcelable;
                                String path = AndroidUtilities.getPath(uri);
                                String originalPath = parcelable.toString();
                                if (originalPath == null) {
                                    originalPath = path;
                                }
                                if (BuildVars.LOGS_ENABLED) {
                                    FileLog.d("export path = " + originalPath);
                                }
                                if (dialogId == 0 && originalPath != null && exportingChatUri == null) {
                                    boolean ok = false;
                                    String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
                                    for (String u : exportUris) {
                                        try {
                                            Pattern pattern = Pattern.compile(u);
                                            if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
                                                exportingChatUri = uri;
                                                ok = true;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    }
                                    if (ok) {
                                        continue;
                                    } else if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
                                        exportingChatUri = uri;
                                        continue;
                                    }
                                }
                                if (path != null) {
                                    if (path.startsWith("file:")) {
                                        path = path.replace("file://", "");
                                    }
                                    if (documentsPathsArray == null) {
                                        documentsPathsArray = new ArrayList<>();
                                        documentsOriginalPathsArray = new ArrayList<>();
                                    }
                                    documentsPathsArray.add(path);
                                    documentsOriginalPathsArray.add(originalPath);
                                } else {
                                    if (documentsUrisArray == null) {
                                        documentsUrisArray = new ArrayList<>();
                                    }
                                    documentsUrisArray.add(uri);
                                    documentsMimeType = type;
                                }
                            }
                        }
                    } else {
                        error = true;
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                    error = true;
                }
                if (error) {
                    Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                }
            } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                Uri data = intent.getData();
                if (data != null) {
                    String username = null;
                    String login = null;
                    String group = null;
                    String sticker = null;
                    HashMap<String, String> auth = null;
                    String unsupportedUrl = null;
                    String botUser = null;
                    String botChat = null;
                    String message = null;
                    String phone = null;
                    String game = null;
                    String voicechat = null;
                    String livestream = null;
                    String phoneHash = null;
                    String lang = null;
                    String theme = null;
                    String code = null;
                    TLRPC.TL_wallPaper wallPaper = null;
                    Integer messageId = null;
                    Long channelId = null;
                    Integer threadId = null;
                    Integer commentId = null;
                    int videoTimestamp = -1;
                    boolean hasUrl = false;
                    final String scheme = data.getScheme();
                    if (scheme != null) {
                        switch(scheme) {
                            case "http":
                            case "https":
                                {
                                    String host = data.getHost().toLowerCase();
                                    if (host.equals("telegram.me") || host.equals("t.me") || host.equals("telegram.dog")) {
                                        String path = data.getPath();
                                        if (path != null && path.length() > 1) {
                                            path = path.substring(1);
                                            if (path.startsWith("bg/")) {
                                                wallPaper = new TLRPC.TL_wallPaper();
                                                wallPaper.settings = new TLRPC.TL_wallPaperSettings();
                                                wallPaper.slug = path.replace("bg/", "");
                                                boolean ok = false;
                                                if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
                                                    try {
                                                        wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
                                                        wallPaper.slug = null;
                                                        ok = true;
                                                    } catch (Exception ignore) {
                                                    }
                                                } else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
                                                    try {
                                                        wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
                                                        wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
                                                        if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
                                                            wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
                                                        }
                                                        if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
                                                            wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
                                                        }
                                                        try {
                                                            String rotation = data.getQueryParameter("rotation");
                                                            if (!TextUtils.isEmpty(rotation)) {
                                                                wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                            }
                                                        } catch (Exception ignore) {
                                                        }
                                                        wallPaper.slug = null;
                                                        ok = true;
                                                    } catch (Exception ignore) {
                                                    }
                                                }
                                                if (!ok) {
                                                    String mode = data.getQueryParameter("mode");
                                                    if (mode != null) {
                                                        mode = mode.toLowerCase();
                                                        String[] modes = mode.split(" ");
                                                        if (modes != null && modes.length > 0) {
                                                            for (int a = 0; a < modes.length; a++) {
                                                                if ("blur".equals(modes[a])) {
                                                                    wallPaper.settings.blur = true;
                                                                } else if ("motion".equals(modes[a])) {
                                                                    wallPaper.settings.motion = true;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    String intensity = data.getQueryParameter("intensity");
                                                    if (!TextUtils.isEmpty(intensity)) {
                                                        wallPaper.settings.intensity = Utilities.parseInt(intensity);
                                                    } else {
                                                        wallPaper.settings.intensity = 50;
                                                    }
                                                    try {
                                                        String bgColor = data.getQueryParameter("bg_color");
                                                        if (!TextUtils.isEmpty(bgColor)) {
                                                            wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
                                                            if (bgColor.length() >= 13) {
                                                                wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(7, 13), 16) | 0xff000000;
                                                                if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
                                                                    wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
                                                                }
                                                                if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
                                                                    wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
                                                                }
                                                            }
                                                        } else {
                                                            wallPaper.settings.background_color = 0xffffffff;
                                                        }
                                                    } catch (Exception ignore) {
                                                    }
                                                    try {
                                                        String rotation = data.getQueryParameter("rotation");
                                                        if (!TextUtils.isEmpty(rotation)) {
                                                            wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                        }
                                                    } catch (Exception ignore) {
                                                    }
                                                }
                                            } else if (path.startsWith("login/")) {
                                                int intCode = Utilities.parseInt(path.replace("login/", ""));
                                                if (intCode != 0) {
                                                    code = "" + intCode;
                                                }
                                            } else if (path.startsWith("joinchat/")) {
                                                group = path.replace("joinchat/", "");
                                            } else if (path.startsWith("+")) {
                                                group = path.replace("+", "");
                                            } else if (path.startsWith("addstickers/")) {
                                                sticker = path.replace("addstickers/", "");
                                            } else if (path.startsWith("msg/") || path.startsWith("share/")) {
                                                message = data.getQueryParameter("url");
                                                if (message == null) {
                                                    message = "";
                                                }
                                                if (data.getQueryParameter("text") != null) {
                                                    if (message.length() > 0) {
                                                        hasUrl = true;
                                                        message += "\n";
                                                    }
                                                    message += data.getQueryParameter("text");
                                                }
                                                if (message.length() > 4096 * 4) {
                                                    message = message.substring(0, 4096 * 4);
                                                }
                                                while (message.endsWith("\n")) {
                                                    message = message.substring(0, message.length() - 1);
                                                }
                                            } else if (path.startsWith("confirmphone")) {
                                                phone = data.getQueryParameter("phone");
                                                phoneHash = data.getQueryParameter("hash");
                                            } else if (path.startsWith("setlanguage/")) {
                                                lang = path.substring(12);
                                            } else if (path.startsWith("addtheme/")) {
                                                theme = path.substring(9);
                                            } else if (path.startsWith("c/")) {
                                                List<String> segments = data.getPathSegments();
                                                if (segments.size() == 3) {
                                                    channelId = Utilities.parseLong(segments.get(1));
                                                    messageId = Utilities.parseInt(segments.get(2));
                                                    if (messageId == 0 || channelId == 0) {
                                                        messageId = null;
                                                        channelId = null;
                                                    }
                                                    threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                                    if (threadId == 0) {
                                                        threadId = null;
                                                    }
                                                }
                                            } else if (path.length() >= 1) {
                                                ArrayList<String> segments = new ArrayList<>(data.getPathSegments());
                                                if (segments.size() > 0 && segments.get(0).equals("s")) {
                                                    segments.remove(0);
                                                }
                                                if (segments.size() > 0) {
                                                    username = segments.get(0);
                                                    if (segments.size() > 1) {
                                                        messageId = Utilities.parseInt(segments.get(1));
                                                        if (messageId == 0) {
                                                            messageId = null;
                                                        }
                                                    }
                                                }
                                                if (messageId != null) {
                                                    videoTimestamp = getTimestampFromLink(data);
                                                }
                                                botUser = data.getQueryParameter("start");
                                                botChat = data.getQueryParameter("startgroup");
                                                game = data.getQueryParameter("game");
                                                voicechat = data.getQueryParameter("voicechat");
                                                livestream = data.getQueryParameter("livestream");
                                                threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                                if (threadId == 0) {
                                                    threadId = null;
                                                }
                                                commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                                if (commentId == 0) {
                                                    commentId = null;
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                            case "tg":
                                {
                                    String url = data.toString();
                                    if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) {
                                        url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        username = data.getQueryParameter("domain");
                                        if ("telegrampassport".equals(username)) {
                                            username = null;
                                            auth = new HashMap<>();
                                            String scope = data.getQueryParameter("scope");
                                            if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
                                                auth.put("nonce", data.getQueryParameter("nonce"));
                                            } else {
                                                auth.put("payload", data.getQueryParameter("payload"));
                                            }
                                            auth.put("bot_id", data.getQueryParameter("bot_id"));
                                            auth.put("scope", scope);
                                            auth.put("public_key", data.getQueryParameter("public_key"));
                                            auth.put("callback_url", data.getQueryParameter("callback_url"));
                                        } else {
                                            botUser = data.getQueryParameter("start");
                                            botChat = data.getQueryParameter("startgroup");
                                            game = data.getQueryParameter("game");
                                            voicechat = data.getQueryParameter("voicechat");
                                            livestream = data.getQueryParameter("livestream");
                                            messageId = Utilities.parseInt(data.getQueryParameter("post"));
                                            if (messageId == 0) {
                                                messageId = null;
                                            }
                                            threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                            if (threadId == 0) {
                                                threadId = null;
                                            }
                                            commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                            if (commentId == 0) {
                                                commentId = null;
                                            }
                                        }
                                    } else if (url.startsWith("tg:privatepost") || url.startsWith("tg://privatepost")) {
                                        url = url.replace("tg:privatepost", "tg://telegram.org").replace("tg://privatepost", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        messageId = Utilities.parseInt(data.getQueryParameter("post"));
                                        channelId = Utilities.parseLong(data.getQueryParameter("channel"));
                                        if (messageId == 0 || channelId == 0) {
                                            messageId = null;
                                            channelId = null;
                                        }
                                        threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                        if (threadId == 0) {
                                            threadId = null;
                                        }
                                        commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                        if (commentId == 0) {
                                            commentId = null;
                                        }
                                    } else if (url.startsWith("tg:bg") || url.startsWith("tg://bg")) {
                                        url = url.replace("tg:bg", "tg://telegram.org").replace("tg://bg", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        wallPaper = new TLRPC.TL_wallPaper();
                                        wallPaper.settings = new TLRPC.TL_wallPaperSettings();
                                        wallPaper.slug = data.getQueryParameter("slug");
                                        if (wallPaper.slug == null) {
                                            wallPaper.slug = data.getQueryParameter("color");
                                        }
                                        boolean ok = false;
                                        if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
                                            try {
                                                wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
                                                wallPaper.slug = null;
                                                ok = true;
                                            } catch (Exception ignore) {
                                            }
                                        } else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
                                            try {
                                                wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
                                                wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
                                                if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
                                                    wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
                                                }
                                                if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
                                                    wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
                                                }
                                                try {
                                                    String rotation = data.getQueryParameter("rotation");
                                                    if (!TextUtils.isEmpty(rotation)) {
                                                        wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                    }
                                                } catch (Exception ignore) {
                                                }
                                                wallPaper.slug = null;
                                                ok = true;
                                            } catch (Exception ignore) {
                                            }
                                        }
                                        if (!ok) {
                                            String mode = data.getQueryParameter("mode");
                                            if (mode != null) {
                                                mode = mode.toLowerCase();
                                                String[] modes = mode.split(" ");
                                                if (modes != null && modes.length > 0) {
                                                    for (int a = 0; a < modes.length; a++) {
                                                        if ("blur".equals(modes[a])) {
                                                            wallPaper.settings.blur = true;
                                                        } else if ("motion".equals(modes[a])) {
                                                            wallPaper.settings.motion = true;
                                                        }
                                                    }
                                                }
                                            }
                                            wallPaper.settings.intensity = Utilities.parseInt(data.getQueryParameter("intensity"));
                                            try {
                                                String bgColor = data.getQueryParameter("bg_color");
                                                if (!TextUtils.isEmpty(bgColor)) {
                                                    wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
                                                    if (bgColor.length() >= 13) {
                                                        wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(8, 13), 16) | 0xff000000;
                                                        if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
                                                            wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
                                                        }
                                                        if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
                                                            wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
                                                        }
                                                    }
                                                }
                                            } catch (Exception ignore) {
                                            }
                                            try {
                                                String rotation = data.getQueryParameter("rotation");
                                                if (!TextUtils.isEmpty(rotation)) {
                                                    wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                }
                                            } catch (Exception ignore) {
                                            }
                                        }
                                    } else if (url.startsWith("tg:join") || url.startsWith("tg://join")) {
                                        url = url.replace("tg:join", "tg://telegram.org").replace("tg://join", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        group = data.getQueryParameter("invite");
                                    } else if (url.startsWith("tg:addstickers") || url.startsWith("tg://addstickers")) {
                                        url = url.replace("tg:addstickers", "tg://telegram.org").replace("tg://addstickers", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        sticker = data.getQueryParameter("set");
                                    } else if (url.startsWith("tg:msg") || url.startsWith("tg://msg") || url.startsWith("tg://share") || url.startsWith("tg:share")) {
                                        url = url.replace("tg:msg", "tg://telegram.org").replace("tg://msg", "tg://telegram.org").replace("tg://share", "tg://telegram.org").replace("tg:share", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        message = data.getQueryParameter("url");
                                        if (message == null) {
                                            message = "";
                                        }
                                        if (data.getQueryParameter("text") != null) {
                                            if (message.length() > 0) {
                                                hasUrl = true;
                                                message += "\n";
                                            }
                                            message += data.getQueryParameter("text");
                                        }
                                        if (message.length() > 4096 * 4) {
                                            message = message.substring(0, 4096 * 4);
                                        }
                                        while (message.endsWith("\n")) {
                                            message = message.substring(0, message.length() - 1);
                                        }
                                    } else if (url.startsWith("tg:confirmphone") || url.startsWith("tg://confirmphone")) {
                                        url = url.replace("tg:confirmphone", "tg://telegram.org").replace("tg://confirmphone", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        phone = data.getQueryParameter("phone");
                                        phoneHash = data.getQueryParameter("hash");
                                    } else if (url.startsWith("tg:login") || url.startsWith("tg://login")) {
                                        url = url.replace("tg:login", "tg://telegram.org").replace("tg://login", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        login = data.getQueryParameter("token");
                                        int intCode = Utilities.parseInt(data.getQueryParameter("code"));
                                        if (intCode != 0) {
                                            code = "" + intCode;
                                        }
                                    } else if (url.startsWith("tg:openmessage") || url.startsWith("tg://openmessage")) {
                                        url = url.replace("tg:openmessage", "tg://telegram.org").replace("tg://openmessage", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        String userID = data.getQueryParameter("user_id");
                                        String chatID = data.getQueryParameter("chat_id");
                                        String msgID = data.getQueryParameter("message_id");
                                        if (userID != null) {
                                            try {
                                                push_user_id = Long.parseLong(userID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        } else if (chatID != null) {
                                            try {
                                                push_chat_id = Long.parseLong(chatID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        }
                                        if (msgID != null) {
                                            try {
                                                push_msg_id = Integer.parseInt(msgID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        }
                                    } else if (url.startsWith("tg:passport") || url.startsWith("tg://passport") || url.startsWith("tg:secureid")) {
                                        url = url.replace("tg:passport", "tg://telegram.org").replace("tg://passport", "tg://telegram.org").replace("tg:secureid", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        auth = new HashMap<>();
                                        String scope = data.getQueryParameter("scope");
                                        if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
                                            auth.put("nonce", data.getQueryParameter("nonce"));
                                        } else {
                                            auth.put("payload", data.getQueryParameter("payload"));
                                        }
                                        auth.put("bot_id", data.getQueryParameter("bot_id"));
                                        auth.put("scope", scope);
                                        auth.put("public_key", data.getQueryParameter("public_key"));
                                        auth.put("callback_url", data.getQueryParameter("callback_url"));
                                    } else if (url.startsWith("tg:setlanguage") || url.startsWith("tg://setlanguage")) {
                                        url = url.replace("tg:setlanguage", "tg://telegram.org").replace("tg://setlanguage", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        lang = data.getQueryParameter("lang");
                                    } else if (url.startsWith("tg:addtheme") || url.startsWith("tg://addtheme")) {
                                        url = url.replace("tg:addtheme", "tg://telegram.org").replace("tg://addtheme", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        theme = data.getQueryParameter("slug");
                                    } else if (url.startsWith("tg:settings") || url.startsWith("tg://settings")) {
                                        if (url.contains("themes")) {
                                            open_settings = 2;
                                        } else if (url.contains("devices")) {
                                            open_settings = 3;
                                        } else if (url.contains("folders")) {
                                            open_settings = 4;
                                        } else if (url.contains("change_number")) {
                                            open_settings = 5;
                                        } else {
                                            open_settings = 1;
                                        }
                                    } else if ((url.startsWith("tg:search") || url.startsWith("tg://search"))) {
                                        url = url.replace("tg:search", "tg://telegram.org").replace("tg://search", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        searchQuery = data.getQueryParameter("query");
                                        if (searchQuery != null) {
                                            searchQuery = searchQuery.trim();
                                        } else {
                                            searchQuery = "";
                                        }
                                    } else if ((url.startsWith("tg:calllog") || url.startsWith("tg://calllog"))) {
                                        showCallLog = true;
                                    } else if ((url.startsWith("tg:call") || url.startsWith("tg://call"))) {
                                        if (UserConfig.getInstance(currentAccount).isClientActivated()) {
                                            final String extraForceCall = "extra_force_call";
                                            if (ContactsController.getInstance(currentAccount).contactsLoaded || intent.hasExtra(extraForceCall)) {
                                                final String callFormat = data.getQueryParameter("format");
                                                final String callUserName = data.getQueryParameter("name");
                                                final String callPhone = data.getQueryParameter("phone");
                                                final List<TLRPC.TL_contact> contacts = findContacts(callUserName, callPhone, false);
                                                if (contacts.isEmpty() && callPhone != null) {
                                                    newContactName = callUserName;
                                                    newContactPhone = callPhone;
                                                    newContactAlert = true;
                                                } else {
                                                    if (contacts.size() == 1) {
                                                        push_user_id = contacts.get(0).user_id;
                                                    }
                                                    if (push_user_id == 0) {
                                                        callSearchQuery = callUserName != null ? callUserName : "";
                                                    }
                                                    if ("video".equalsIgnoreCase(callFormat)) {
                                                        videoCallUser = true;
                                                    } else {
                                                        audioCallUser = true;
                                                    }
                                                    needCallAlert = true;
                                                }
                                            } else {
                                                final Intent copyIntent = new Intent(intent);
                                                copyIntent.removeExtra(EXTRA_ACTION_TOKEN);
                                                copyIntent.putExtra(extraForceCall, true);
                                                ContactsLoadingObserver.observe((contactsLoaded) -> handleIntent(copyIntent, true, false, false), 1000);
                                            }
                                        }
                                    } else if ((url.startsWith("tg:scanqr") || url.startsWith("tg://scanqr"))) {
                                        scanQr = true;
                                    } else if ((url.startsWith("tg:addcontact") || url.startsWith("tg://addcontact"))) {
                                        url = url.replace("tg:addcontact", "tg://telegram.org").replace("tg://addcontact", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        newContactName = data.getQueryParameter("name");
                                        newContactPhone = data.getQueryParameter("phone");
                                        newContact = true;
                                    } else {
                                        unsupportedUrl = url.replace("tg://", "").replace("tg:", "");
                                        int index;
                                        if ((index = unsupportedUrl.indexOf('?')) >= 0) {
                                            unsupportedUrl = unsupportedUrl.substring(0, index);
                                        }
                                    }
                                    break;
                                }
                        }
                    }
                    if (intent.hasExtra(EXTRA_ACTION_TOKEN)) {
                        final boolean success = UserConfig.getInstance(currentAccount).isClientActivated() && "tg".equals(scheme) && unsupportedUrl == null;
                        intent.removeExtra(EXTRA_ACTION_TOKEN);
                    }
                    if (code != null || UserConfig.getInstance(currentAccount).isClientActivated()) {
                        if (phone != null || phoneHash != null) {
                            final Bundle args = new Bundle();
                            args.putString("phone", phone);
                            args.putString("hash", phoneHash);
                            AndroidUtilities.runOnUIThread(() -> presentFragment(new CancelAccountDeletionActivity(args)));
                        } else if (username != null || group != null || sticker != null || message != null || game != null || voicechat != null || auth != null || unsupportedUrl != null || lang != null || code != null || wallPaper != null || channelId != null || theme != null || login != null) {
                            if (message != null && message.startsWith("@")) {
                                message = " " + message;
                            }
                            runLinkRequest(intentAccount[0], username, group, sticker, botUser, botChat, message, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, login, wallPaper, theme, voicechat, livestream, 0, videoTimestamp);
                        } else {
                            try (Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null)) {
                                if (cursor != null) {
                                    if (cursor.moveToFirst()) {
                                        int accountId = Utilities.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                                        for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
                                            if (UserConfig.getInstance(a).getClientUserId() == accountId) {
                                                intentAccount[0] = a;
                                                switchToAccount(intentAccount[0], true);
                                                break;
                                            }
                                        }
                                        long userId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.DATA4));
                                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                                        push_user_id = userId;
                                        String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
                                        if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call")) {
                                            audioCallUser = true;
                                        } else if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video")) {
                                            videoCallUser = true;
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                        }
                    }
                }
            } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) {
                open_settings = 1;
            } else if (intent.getAction().equals("new_dialog")) {
                open_new_dialog = 1;
            } else if (intent.getAction().startsWith("com.tmessages.openchat")) {
                long chatId = intent.getLongExtra("chatId", intent.getIntExtra("chatId", 0));
                long userId = intent.getLongExtra("userId", intent.getIntExtra("userId", 0));
                int encId = intent.getIntExtra("encId", 0);
                int widgetId = intent.getIntExtra("appWidgetId", 0);
                if (widgetId != 0) {
                    open_settings = 6;
                    open_widget_edit = widgetId;
                    open_widget_edit_type = intent.getIntExtra("appWidgetType", 0);
                } else {
                    if (push_msg_id == 0) {
                        push_msg_id = intent.getIntExtra("message_id", 0);
                    }
                    if (chatId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_chat_id = chatId;
                    } else if (userId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_user_id = userId;
                    } else if (encId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_enc_id = encId;
                    } else {
                        showDialogsList = true;
                    }
                }
            } else if (intent.getAction().equals("com.tmessages.openplayer")) {
                showPlayer = true;
            } else if (intent.getAction().equals("org.tmessages.openlocations")) {
                showLocations = true;
            } else if (action.equals("voip_chat")) {
                showGroupVoip = true;
            }
        }
    }
    if (UserConfig.getInstance(currentAccount).isClientActivated()) {
        if (searchQuery != null) {
            final BaseFragment lastFragment = actionBarLayout.getLastFragment();
            if (lastFragment instanceof DialogsActivity) {
                final DialogsActivity dialogsActivity = (DialogsActivity) lastFragment;
                if (dialogsActivity.isMainDialogList()) {
                    if (dialogsActivity.getFragmentView() != null) {
                        dialogsActivity.search(searchQuery, true);
                    } else {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                }
            } else {
                showDialogsList = true;
            }
        }
        if (push_user_id != 0) {
            if (audioCallUser || videoCallUser) {
                if (needCallAlert) {
                    final BaseFragment lastFragment = actionBarLayout.getLastFragment();
                    if (lastFragment != null) {
                        AlertsCreator.createCallDialogAlert(lastFragment, lastFragment.getMessagesController().getUser(push_user_id), videoCallUser);
                    }
                } else {
                    VoIPPendingCall.startOrSchedule(this, push_user_id, videoCallUser, AccountInstance.getInstance(intentAccount[0]));
                }
            } else {
                Bundle args = new Bundle();
                args.putLong("user_id", push_user_id);
                if (push_msg_id != 0) {
                    args.putInt("message_id", push_msg_id);
                }
                if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                    ChatActivity fragment = new ChatActivity(args);
                    if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                        pushOpened = true;
                        drawerLayoutContainer.closeDrawer();
                    }
                }
            }
        } else if (push_chat_id != 0) {
            Bundle args = new Bundle();
            args.putLong("chat_id", push_chat_id);
            if (push_msg_id != 0) {
                args.putInt("message_id", push_msg_id);
            }
            if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                ChatActivity fragment = new ChatActivity(args);
                if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                    pushOpened = true;
                    drawerLayoutContainer.closeDrawer();
                }
            }
        } else if (push_enc_id != 0) {
            Bundle args = new Bundle();
            args.putInt("enc_id", push_enc_id);
            ChatActivity fragment = new ChatActivity(args);
            if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                pushOpened = true;
                drawerLayoutContainer.closeDrawer();
            }
        } else if (showDialogsList) {
            if (!AndroidUtilities.isTablet()) {
                actionBarLayout.removeAllFragments();
            } else {
                if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
                    for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
                        layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
                        a--;
                    }
                    layersActionBarLayout.closeLastFragment(false);
                }
            }
            pushOpened = false;
            isNew = false;
        } else if (showPlayer) {
            if (!actionBarLayout.fragmentsStack.isEmpty()) {
                BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                fragment.showDialog(new AudioPlayerAlert(this, null));
            }
            pushOpened = false;
        } else if (showLocations) {
            if (!actionBarLayout.fragmentsStack.isEmpty()) {
                BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                fragment.showDialog(new SharingLocationsAlert(this, info -> {
                    intentAccount[0] = info.messageObject.currentAccount;
                    switchToAccount(intentAccount[0], true);
                    LocationActivity locationActivity = new LocationActivity(2);
                    locationActivity.setMessageObject(info.messageObject);
                    final long dialog_id = info.messageObject.getDialogId();
                    locationActivity.setDelegate((location, live, notify, scheduleDate) -> SendMessagesHelper.getInstance(intentAccount[0]).sendMessage(location, dialog_id, null, null, null, null, notify, scheduleDate));
                    presentFragment(locationActivity);
                }, null));
            }
            pushOpened = false;
        } else if (exportingChatUri != null) {
            runImportRequest(exportingChatUri, documentsUrisArray);
        } else if (importingStickers != null) {
            AndroidUtilities.runOnUIThread(() -> {
                if (!actionBarLayout.fragmentsStack.isEmpty()) {
                    BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                    fragment.showDialog(new StickersAlert(this, importingStickersSoftware, importingStickers, importingStickersEmoji, null));
                }
            });
            pushOpened = false;
        } else if (videoPath != null || photoPathsArray != null || sendingText != null || sendingLocation != null || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) {
            if (!AndroidUtilities.isTablet()) {
                NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
            }
            if (dialogId == 0) {
                openDialogsToSend(false);
                pushOpened = true;
            } else {
                ArrayList<Long> dids = new ArrayList<>();
                dids.add(dialogId);
                didSelectDialogs(null, dids, null, false);
            }
        } else if (open_settings != 0) {
            BaseFragment fragment;
            boolean closePrevious = false;
            if (open_settings == 1) {
                Bundle args = new Bundle();
                args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId);
                fragment = new ProfileActivity(args);
            } else if (open_settings == 2) {
                fragment = new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC);
            } else if (open_settings == 3) {
                fragment = new SessionsActivity(0);
            } else if (open_settings == 4) {
                fragment = new FiltersSetupActivity();
            } else if (open_settings == 5) {
                fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_CHANGE_PHONE_NUMBER);
                closePrevious = true;
            } else if (open_settings == 6) {
                fragment = new EditWidgetActivity(open_widget_edit_type, open_widget_edit);
            } else {
                fragment = null;
            }
            boolean closePreviousFinal = closePrevious;
            if (open_settings == 6) {
                actionBarLayout.presentFragment(fragment, false, true, true, false);
            } else {
                AndroidUtilities.runOnUIThread(() -> presentFragment(fragment, closePreviousFinal, false));
            }
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (open_new_dialog != 0) {
            Bundle args = new Bundle();
            args.putBoolean("destroyAfterSelect", true);
            actionBarLayout.presentFragment(new ContactsActivity(args), false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (callSearchQuery != null) {
            final Bundle args = new Bundle();
            args.putBoolean("destroyAfterSelect", true);
            args.putBoolean("returnAsResult", true);
            args.putBoolean("onlyUsers", true);
            args.putBoolean("allowSelf", false);
            final ContactsActivity contactsFragment = new ContactsActivity(args);
            contactsFragment.setInitialSearchString(callSearchQuery);
            final boolean videoCall = videoCallUser;
            contactsFragment.setDelegate((user, param, activity) -> {
                final TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(user.id);
                VoIPHelper.startCall(user, videoCall, userFull != null && userFull.video_calls_available, LaunchActivity.this, userFull, AccountInstance.getInstance(intentAccount[0]));
            });
            actionBarLayout.presentFragment(contactsFragment, actionBarLayout.getLastFragment() instanceof ContactsActivity, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (scanQr) {
            ActionIntroActivity fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_QR_LOGIN);
            fragment.setQrLoginDelegate(code -> {
                AlertDialog progressDialog = new AlertDialog(LaunchActivity.this, 3);
                progressDialog.setCanCacnel(false);
                progressDialog.show();
                byte[] token = Base64.decode(code.substring("tg://login?token=".length()), Base64.URL_SAFE);
                TLRPC.TL_auth_acceptLoginToken req = new TLRPC.TL_auth_acceptLoginToken();
                req.token = token;
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception ignore) {
                    }
                    if (!(response instanceof TLRPC.TL_authorization)) {
                        AndroidUtilities.runOnUIThread(() -> AlertsCreator.showSimpleAlert(fragment, LocaleController.getString("AuthAnotherClient", R.string.AuthAnotherClient), LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
                    }
                }));
            });
            actionBarLayout.presentFragment(fragment, false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (newContact) {
            final NewContactActivity fragment = new NewContactActivity();
            if (newContactName != null) {
                final String[] names = newContactName.split(" ", 2);
                fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
            }
            if (newContactPhone != null) {
                fragment.setInitialPhoneNumber(PhoneFormat.stripExceptNumbers(newContactPhone, true), false);
            }
            actionBarLayout.presentFragment(fragment, false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (showGroupVoip) {
            GroupCallActivity.create(this, AccountInstance.getInstance(currentAccount), null, null, false, null);
            if (GroupCallActivity.groupCallInstance != null) {
                GroupCallActivity.groupCallUiVisible = true;
            }
        } else if (newContactAlert) {
            final BaseFragment lastFragment = actionBarLayout.getLastFragment();
            if (lastFragment != null && lastFragment.getParentActivity() != null) {
                final String finalNewContactName = newContactName;
                final String finalNewContactPhone = NewContactActivity.getPhoneNumber(this, UserConfig.getInstance(currentAccount).getCurrentUser(), newContactPhone, false);
                final AlertDialog newContactAlertDialog = new AlertDialog.Builder(lastFragment.getParentActivity()).setTitle(LocaleController.getString("NewContactAlertTitle", R.string.NewContactAlertTitle)).setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("NewContactAlertMessage", R.string.NewContactAlertMessage, PhoneFormat.getInstance().format(finalNewContactPhone)))).setPositiveButton(LocaleController.getString("NewContactAlertButton", R.string.NewContactAlertButton), (d, i) -> {
                    final NewContactActivity fragment = new NewContactActivity();
                    fragment.setInitialPhoneNumber(finalNewContactPhone, false);
                    if (finalNewContactName != null) {
                        final String[] names = finalNewContactName.split(" ", 2);
                        fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
                    }
                    lastFragment.presentFragment(fragment);
                }).setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null).create();
                lastFragment.showDialog(newContactAlertDialog);
                pushOpened = true;
            }
        } else if (showCallLog) {
            actionBarLayout.presentFragment(new CallLogActivity(), false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        }
    }
    if (!pushOpened && !isNew) {
        if (AndroidUtilities.isTablet()) {
            if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
                if (layersActionBarLayout.fragmentsStack.isEmpty()) {
                    layersActionBarLayout.addFragmentToStack(new LoginActivity());
                    drawerLayoutContainer.setAllowOpenDrawer(false, false);
                }
            } else {
                if (actionBarLayout.fragmentsStack.isEmpty()) {
                    DialogsActivity dialogsActivity = new DialogsActivity(null);
                    dialogsActivity.setSideMenu(sideMenu);
                    if (searchQuery != null) {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                    actionBarLayout.addFragmentToStack(dialogsActivity);
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
            }
        } else {
            if (actionBarLayout.fragmentsStack.isEmpty()) {
                if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
                    actionBarLayout.addFragmentToStack(new LoginActivity());
                    drawerLayoutContainer.setAllowOpenDrawer(false, false);
                } else {
                    DialogsActivity dialogsActivity = new DialogsActivity(null);
                    dialogsActivity.setSideMenu(sideMenu);
                    if (searchQuery != null) {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                    actionBarLayout.addFragmentToStack(dialogsActivity);
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
            }
        }
        actionBarLayout.showLastFragment();
        if (AndroidUtilities.isTablet()) {
            layersActionBarLayout.showLastFragment();
            rightActionBarLayout.showLastFragment();
        }
    }
    if (isVoipIntent) {
        VoIPFragment.show(this, intentAccount[0]);
    }
    if (!showGroupVoip && (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) && GroupCallActivity.groupCallInstance != null) {
        GroupCallActivity.groupCallInstance.dismiss();
    }
    intent.setAction(null);
    return pushOpened;
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) AbstractSerializedData(org.telegram.tgnet.AbstractSerializedData) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) StickersAlert(org.telegram.ui.Components.StickersAlert) LocationController(org.telegram.messenger.LocationController) Bulletin(org.telegram.ui.Components.Bulletin) VoIPPendingCall(org.telegram.messenger.voip.VoIPPendingCall) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) ShortcutManagerCompat(androidx.core.content.pm.ShortcutManagerCompat) Manifest(android.Manifest) Matcher(java.util.regex.Matcher) DrawerProfileCell(org.telegram.ui.Cells.DrawerProfileCell) Map(java.util.Map) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) Function(androidx.arch.core.util.Function) UndoView(org.telegram.ui.Components.UndoView) ContactsLoadingObserver(org.telegram.messenger.ContactsLoadingObserver) Set(java.util.Set) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) FileLoader(org.telegram.messenger.FileLoader) GroupCallPip(org.telegram.ui.Components.GroupCallPip) ViewParent(android.view.ViewParent) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleDateFormat(java.text.SimpleDateFormat) SystemClock(android.os.SystemClock) AlertsCreator(org.telegram.ui.Components.AlertsCreator) WebRtcAudioTrack(org.webrtc.voiceengine.WebRtcAudioTrack) ArrayList(java.util.ArrayList) ItemTouchHelper(androidx.recyclerview.widget.ItemTouchHelper) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) PasscodeView(org.telegram.ui.Components.PasscodeView) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) Settings(android.provider.Settings) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) LinearGradient(android.graphics.LinearGradient) Parcelable(android.os.Parcelable) R(org.telegram.messenger.R) LanguageCell(org.telegram.ui.Cells.LanguageCell) SideMenultItemAnimator(org.telegram.ui.Components.SideMenultItemAnimator) TextUtils(android.text.TextUtils) InputStreamReader(java.io.InputStreamReader) DrawerLayoutContainer(org.telegram.ui.ActionBar.DrawerLayoutContainer) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) DrawerAddCell(org.telegram.ui.Cells.DrawerAddCell) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) Configuration(android.content.res.Configuration) Easings(org.telegram.ui.Components.Easings) BufferedReader(java.io.BufferedReader) ChatObject(org.telegram.messenger.ChatObject) CameraController(org.telegram.messenger.camera.CameraController) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) RadialProgress2(org.telegram.ui.Components.RadialProgress2) PackageManager(android.content.pm.PackageManager) Date(java.util.Date) DrawerLayoutAdapter(org.telegram.ui.Adapters.DrawerLayoutAdapter) WindowManager(android.view.WindowManager) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) VideoCapturerDevice(org.telegram.messenger.voip.VideoCapturerDevice) Animator(android.animation.Animator) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ContactsContract(android.provider.ContactsContract) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TermsOfServiceView(org.telegram.ui.Components.TermsOfServiceView) Matrix(android.graphics.Matrix) ParseException(java.text.ParseException) DateFormat(java.text.DateFormat) ImageLoader(org.telegram.messenger.ImageLoader) DrawerUserCell(org.telegram.ui.Cells.DrawerUserCell) Utilities(org.telegram.messenger.Utilities) RLottieImageView(org.telegram.ui.Components.RLottieImageView) ObjectAnimator(android.animation.ObjectAnimator) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) ViewAnimationUtils(android.view.ViewAnimationUtils) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BlockingUpdateView(org.telegram.ui.Components.BlockingUpdateView) ViewGroup(android.view.ViewGroup) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) RelativeLayout(android.widget.RelativeLayout) Pattern(java.util.regex.Pattern) Location(android.location.Location) LocationManager(android.location.LocationManager) Window(android.view.Window) ActivityManager(android.app.ActivityManager) Context(android.content.Context) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) SharingLocationsAlert(org.telegram.ui.Components.SharingLocationsAlert) AudioManager(android.media.AudioManager) MotionEvent(android.view.MotionEvent) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) Cursor(android.database.Cursor) Browser(org.telegram.messenger.browser.Browser) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) Point(android.graphics.Point) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) StatFs(android.os.StatFs) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) ViewTreeObserver(android.view.ViewTreeObserver) UpdateAppAlertDialog(org.telegram.ui.Components.UpdateAppAlertDialog) Activity(android.app.Activity) RecyclerListView(org.telegram.ui.Components.RecyclerListView) StickerSetBulletinLayout(org.telegram.ui.Components.StickerSetBulletinLayout) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) UpdateAppAlertDialog(org.telegram.ui.Components.UpdateAppAlertDialog) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) SharingLocationsAlert(org.telegram.ui.Components.SharingLocationsAlert) ArrayList(java.util.ArrayList) List(java.util.List) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) Parcelable(android.os.Parcelable) StickersAlert(org.telegram.ui.Components.StickersAlert) Matcher(java.util.regex.Matcher) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) Uri(android.net.Uri) Pattern(java.util.regex.Pattern) Bundle(android.os.Bundle) Intent(android.content.Intent) Paint(android.graphics.Paint) Point(android.graphics.Point) ParseException(java.text.ParseException) Location(android.location.Location)

Example 4 with StickersAlert

use of org.telegram.ui.Components.StickersAlert in project Telegram-FOSS by Telegram-FOSS-Team.

the class GroupStickersActivity method createView.

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("GroupStickers", R.string.GroupStickers));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (donePressed) {
                    return;
                }
                donePressed = true;
                if (searching) {
                    showEditDoneProgress(true);
                    return;
                }
                saveStickerSet();
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56), LocaleController.getString("Done", R.string.Done));
    progressView = new ContextProgressView(context, 1);
    progressView.setAlpha(0.0f);
    progressView.setScaleX(0.1f);
    progressView.setScaleY(0.1f);
    progressView.setVisibility(View.INVISIBLE);
    doneItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    nameContainer = new LinearLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(42), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (selectedStickerSet != null) {
                canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, Theme.dividerPaint);
            }
        }
    };
    nameContainer.setWeightSum(1.0f);
    nameContainer.setWillNotDraw(false);
    nameContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    nameContainer.setOrientation(LinearLayout.HORIZONTAL);
    nameContainer.setPadding(AndroidUtilities.dp(17), 0, AndroidUtilities.dp(14), 0);
    editText = new EditTextBoldCursor(context);
    editText.setText(MessagesController.getInstance(currentAccount).linkPrefix + "/addstickers/");
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    editText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setEnabled(false);
    editText.setFocusable(false);
    editText.setBackgroundDrawable(null);
    editText.setPadding(0, 0, 0, 0);
    editText.setGravity(Gravity.CENTER_VERTICAL);
    editText.setSingleLine(true);
    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    nameContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 42));
    usernameTextView = new EditTextBoldCursor(context);
    usernameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    usernameTextView.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    usernameTextView.setCursorSize(AndroidUtilities.dp(20));
    usernameTextView.setCursorWidth(1.5f);
    usernameTextView.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    usernameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    usernameTextView.setMaxLines(1);
    usernameTextView.setLines(1);
    usernameTextView.setBackgroundDrawable(null);
    usernameTextView.setPadding(0, 0, 0, 0);
    usernameTextView.setSingleLine(true);
    usernameTextView.setGravity(Gravity.CENTER_VERTICAL);
    usernameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    usernameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE);
    usernameTextView.setHint(LocaleController.getString("ChooseStickerSetPlaceholder", R.string.ChooseStickerSetPlaceholder));
    usernameTextView.addTextChangedListener(new TextWatcher() {

        boolean ignoreTextChange;

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

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

        @Override
        public void afterTextChanged(Editable s) {
            if (eraseImageView != null) {
                eraseImageView.setVisibility(s.length() > 0 ? View.VISIBLE : View.INVISIBLE);
            }
            if (ignoreTextChange || ignoreTextChanges) {
                return;
            }
            if (s.length() > 5) {
                ignoreTextChange = true;
                try {
                    Uri uri = Uri.parse(s.toString());
                    if (uri != null) {
                        List<String> segments = uri.getPathSegments();
                        if (segments.size() == 2) {
                            if (segments.get(0).toLowerCase().equals("addstickers")) {
                                usernameTextView.setText(segments.get(1));
                                usernameTextView.setSelection(usernameTextView.length());
                            }
                        }
                    }
                } catch (Exception ignore) {
                }
                ignoreTextChange = false;
            }
            resolveStickerSet();
        }
    });
    nameContainer.addView(usernameTextView, LayoutHelper.createLinear(0, 42, 1.0f));
    eraseImageView = new ImageView(context);
    eraseImageView.setScaleType(ImageView.ScaleType.CENTER);
    eraseImageView.setImageResource(R.drawable.ic_close_white);
    eraseImageView.setPadding(AndroidUtilities.dp(16), 0, 0, 0);
    eraseImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3), PorterDuff.Mode.MULTIPLY));
    eraseImageView.setVisibility(View.INVISIBLE);
    eraseImageView.setOnClickListener(v -> {
        searchWas = false;
        selectedStickerSet = null;
        usernameTextView.setText("");
        updateRows();
    });
    nameContainer.addView(eraseImageView, LayoutHelper.createLinear(42, 42, 0.0f));
    if (info != null && info.stickerset != null) {
        ignoreTextChanges = true;
        usernameTextView.setText(info.stickerset.short_name);
        usernameTextView.setSelection(usernameTextView.length());
        ignoreTextChanges = false;
    }
    listAdapter = new ListAdapter(context);
    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    listView = new RecyclerListView(context);
    listView.setFocusable(true);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    layoutManager = new LinearLayoutManager(context) {

        @Override
        public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, boolean immediate, boolean focusedChildVisible) {
            return false;
        }

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setLayoutManager(layoutManager);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener((view, position) -> {
        if (getParentActivity() == null) {
            return;
        }
        if (position == selectedStickerRow) {
            if (selectedStickerSet == null) {
                return;
            }
            showDialog(new StickersAlert(getParentActivity(), GroupStickersActivity.this, null, selectedStickerSet, null));
        } else if (position >= stickersStartRow && position < stickersEndRow) {
            boolean needScroll = selectedStickerRow == -1;
            int row = layoutManager.findFirstVisibleItemPosition();
            int top = Integer.MAX_VALUE;
            RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForAdapterPosition(row);
            if (holder != null) {
                top = holder.itemView.getTop();
            }
            selectedStickerSet = MediaDataController.getInstance(currentAccount).getStickerSets(MediaDataController.TYPE_IMAGE).get(position - stickersStartRow);
            ignoreTextChanges = true;
            usernameTextView.setText(selectedStickerSet.set.short_name);
            usernameTextView.setSelection(usernameTextView.length());
            ignoreTextChanges = false;
            AndroidUtilities.hideKeyboard(usernameTextView);
            updateRows();
            if (needScroll && top != Integer.MAX_VALUE) {
                layoutManager.scrollToPositionWithOffset(row + 1, top);
            }
        }
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        }
    });
    return fragmentView;
}
Also used : ContextProgressView(org.telegram.ui.Components.ContextProgressView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Uri(android.net.Uri) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) List(java.util.List) ArrayList(java.util.ArrayList) ImageView(android.widget.ImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ActionBar(org.telegram.ui.ActionBar.ActionBar) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) StickersAlert(org.telegram.ui.Components.StickersAlert) FrameLayout(android.widget.FrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView) LinearLayout(android.widget.LinearLayout)

Example 5 with StickersAlert

use of org.telegram.ui.Components.StickersAlert in project Telegram-FOSS by Telegram-FOSS-Team.

the class FeaturedStickersActivity method createView.

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("FeaturedStickers", R.string.FeaturedStickers));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });
    listAdapter = new ListAdapter(context);
    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    listView = new RecyclerListView(context);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setFocusable(true);
    listView.setTag(14);
    layoutManager = new LinearLayoutManager(context) {

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setLayoutManager(layoutManager);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener((view, position) -> {
        if (position >= stickersStartRow && position < stickersEndRow && getParentActivity() != null) {
            final TLRPC.StickerSetCovered stickerSet = MediaDataController.getInstance(currentAccount).getFeaturedStickerSets().get(position);
            TLRPC.InputStickerSet inputStickerSet;
            if (stickerSet.set.id != 0) {
                inputStickerSet = new TLRPC.TL_inputStickerSetID();
                inputStickerSet.id = stickerSet.set.id;
            } else {
                inputStickerSet = new TLRPC.TL_inputStickerSetShortName();
                inputStickerSet.short_name = stickerSet.set.short_name;
            }
            inputStickerSet.access_hash = stickerSet.set.access_hash;
            StickersAlert stickersAlert = new StickersAlert(getParentActivity(), FeaturedStickersActivity.this, inputStickerSet, null, null);
            stickersAlert.setInstallDelegate(new StickersAlert.StickersAlertInstallDelegate() {

                @Override
                public void onStickerSetInstalled() {
                    FeaturedStickerSetCell cell = (FeaturedStickerSetCell) view;
                    cell.setDrawProgress(true, true);
                    installingStickerSets.put(stickerSet.set.id, stickerSet);
                }

                @Override
                public void onStickerSetUninstalled() {
                }
            });
            showDialog(stickersAlert);
        }
    });
    return fragmentView;
}
Also used : FeaturedStickerSetCell(org.telegram.ui.Cells.FeaturedStickerSetCell) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) StickersAlert(org.telegram.ui.Components.StickersAlert) FrameLayout(android.widget.FrameLayout) ActionBar(org.telegram.ui.ActionBar.ActionBar)

Aggregations

StickersAlert (org.telegram.ui.Components.StickersAlert)11 TLRPC (org.telegram.tgnet.TLRPC)10 FrameLayout (android.widget.FrameLayout)9 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)9 RecyclerListView (org.telegram.ui.Components.RecyclerListView)9 RecyclerView (androidx.recyclerview.widget.RecyclerView)8 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)8 Paint (android.graphics.Paint)7 MessageObject (org.telegram.messenger.MessageObject)7 Canvas (android.graphics.Canvas)6 Bundle (android.os.Bundle)6 LinearLayout (android.widget.LinearLayout)6 ArrayList (java.util.ArrayList)6 ActionBar (org.telegram.ui.ActionBar.ActionBar)6 Manifest (android.Manifest)5 Animator (android.animation.Animator)5 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)5 ObjectAnimator (android.animation.ObjectAnimator)5 SuppressLint (android.annotation.SuppressLint)5 Activity (android.app.Activity)5