Search in sources :

Example 26 with TLObject

use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.

the class SecretChatHelper method performSendEncryptedRequest.

protected void performSendEncryptedRequest(TLRPC.DecryptedMessage req, TLRPC.Message newMsgObj, TLRPC.EncryptedChat chat, TLRPC.InputEncryptedFile encryptedFile, String originalPath, MessageObject newMsg) {
    if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) {
        return;
    }
    getSendMessagesHelper().putToSendingMessages(newMsgObj, false);
    Utilities.stageQueue.postRunnable(() -> {
        try {
            TLObject toEncryptObject;
            TLRPC.TL_decryptedMessageLayer layer = new TLRPC.TL_decryptedMessageLayer();
            int myLayer = Math.max(46, AndroidUtilities.getMyLayerVersion(chat.layer));
            layer.layer = Math.min(myLayer, Math.max(46, AndroidUtilities.getPeerLayerVersion(chat.layer)));
            layer.message = req;
            layer.random_bytes = new byte[15];
            Utilities.random.nextBytes(layer.random_bytes);
            toEncryptObject = layer;
            if (chat.seq_in == 0 && chat.seq_out == 0) {
                if (chat.admin_id == getUserConfig().getClientUserId()) {
                    chat.seq_out = 1;
                    chat.seq_in = -2;
                } else {
                    chat.seq_in = -1;
                }
            }
            if (newMsgObj.seq_in == 0 && newMsgObj.seq_out == 0) {
                layer.in_seq_no = chat.seq_in > 0 ? chat.seq_in : chat.seq_in + 2;
                layer.out_seq_no = chat.seq_out;
                chat.seq_out += 2;
                if (chat.key_create_date == 0) {
                    chat.key_create_date = getConnectionsManager().getCurrentTime();
                }
                chat.key_use_count_out++;
                if ((chat.key_use_count_out >= 100 || chat.key_create_date < getConnectionsManager().getCurrentTime() - 60 * 60 * 24 * 7) && chat.exchange_id == 0 && chat.future_key_fingerprint == 0) {
                    requestNewSecretChatKey(chat);
                }
                getMessagesStorage().updateEncryptedChatSeq(chat, false);
                newMsgObj.seq_in = layer.in_seq_no;
                newMsgObj.seq_out = layer.out_seq_no;
                getMessagesStorage().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out);
            } else {
                layer.in_seq_no = newMsgObj.seq_in;
                layer.out_seq_no = newMsgObj.seq_out;
            }
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(req + " send message with in_seq = " + layer.in_seq_no + " out_seq = " + layer.out_seq_no);
            }
            int len = toEncryptObject.getObjectSize();
            NativeByteBuffer toEncrypt = new NativeByteBuffer(4 + len);
            toEncrypt.writeInt32(len);
            toEncryptObject.serializeToStream(toEncrypt);
            len = toEncrypt.length();
            int extraLen = len % 16 != 0 ? 16 - len % 16 : 0;
            extraLen += (2 + Utilities.random.nextInt(3)) * 16;
            NativeByteBuffer dataForEncryption = new NativeByteBuffer(len + extraLen);
            toEncrypt.position(0);
            dataForEncryption.writeBytes(toEncrypt);
            if (extraLen != 0) {
                byte[] b = new byte[extraLen];
                Utilities.random.nextBytes(b);
                dataForEncryption.writeBytes(b);
            }
            byte[] messageKey = new byte[16];
            byte[] messageKeyFull;
            boolean incoming = chat.admin_id != getUserConfig().getClientUserId();
            messageKeyFull = Utilities.computeSHA256(chat.auth_key, 88 + (incoming ? 8 : 0), 32, dataForEncryption.buffer, 0, dataForEncryption.buffer.limit());
            System.arraycopy(messageKeyFull, 8, messageKey, 0, 16);
            toEncrypt.reuse();
            MessageKeyData keyData = MessageKeyData.generateMessageKeyData(chat.auth_key, messageKey, incoming, 2);
            Utilities.aesIgeEncryption(dataForEncryption.buffer, keyData.aesKey, keyData.aesIv, true, false, 0, dataForEncryption.limit());
            NativeByteBuffer data = new NativeByteBuffer(8 + messageKey.length + dataForEncryption.length());
            dataForEncryption.position(0);
            data.writeInt64(chat.key_fingerprint);
            data.writeBytes(messageKey);
            data.writeBytes(dataForEncryption);
            dataForEncryption.reuse();
            data.position(0);
            TLObject reqToSend;
            if (encryptedFile == null) {
                if (req instanceof TLRPC.TL_decryptedMessageService) {
                    TLRPC.TL_messages_sendEncryptedService req2 = new TLRPC.TL_messages_sendEncryptedService();
                    req2.data = data;
                    req2.random_id = req.random_id;
                    req2.peer = new TLRPC.TL_inputEncryptedChat();
                    req2.peer.chat_id = chat.id;
                    req2.peer.access_hash = chat.access_hash;
                    reqToSend = req2;
                } else {
                    TLRPC.TL_messages_sendEncrypted req2 = new TLRPC.TL_messages_sendEncrypted();
                    req2.silent = newMsgObj.silent;
                    req2.data = data;
                    req2.random_id = req.random_id;
                    req2.peer = new TLRPC.TL_inputEncryptedChat();
                    req2.peer.chat_id = chat.id;
                    req2.peer.access_hash = chat.access_hash;
                    reqToSend = req2;
                }
            } else {
                TLRPC.TL_messages_sendEncryptedFile req2 = new TLRPC.TL_messages_sendEncryptedFile();
                req2.silent = newMsgObj.silent;
                req2.data = data;
                req2.random_id = req.random_id;
                req2.peer = new TLRPC.TL_inputEncryptedChat();
                req2.peer.chat_id = chat.id;
                req2.peer.access_hash = chat.access_hash;
                req2.file = encryptedFile;
                reqToSend = req2;
            }
            getConnectionsManager().sendRequest(reqToSend, (response, error) -> {
                if (error == null) {
                    if (req.action instanceof TLRPC.TL_decryptedMessageActionNotifyLayer) {
                        TLRPC.EncryptedChat currentChat = getMessagesController().getEncryptedChat(chat.id);
                        if (currentChat == null) {
                            currentChat = chat;
                        }
                        if (currentChat.key_hash == null) {
                            currentChat.key_hash = AndroidUtilities.calcAuthKeyHash(currentChat.auth_key);
                        }
                        if (currentChat.key_hash.length == 16) {
                            try {
                                byte[] sha256 = Utilities.computeSHA256(chat.auth_key, 0, chat.auth_key.length);
                                byte[] key_hash = new byte[36];
                                System.arraycopy(chat.key_hash, 0, key_hash, 0, 16);
                                System.arraycopy(sha256, 0, key_hash, 16, 20);
                                currentChat.key_hash = key_hash;
                                getMessagesStorage().updateEncryptedChat(currentChat);
                            } catch (Throwable e) {
                                FileLog.e(e);
                            }
                        }
                        sendingNotifyLayer.remove((Integer) currentChat.id);
                        currentChat.layer = AndroidUtilities.setMyLayerVersion(currentChat.layer, CURRENT_SECRET_CHAT_LAYER);
                        getMessagesStorage().updateEncryptedChatLayer(currentChat);
                    }
                }
                if (error == null) {
                    String attachPath = newMsgObj.attachPath;
                    TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response;
                    if (isSecretVisibleMessage(newMsgObj)) {
                        newMsgObj.date = res.date;
                    }
                    int existFlags;
                    if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) {
                        updateMediaPaths(newMsg, res.file, req, originalPath);
                        existFlags = newMsg.getMediaExistanceFlags();
                    } else {
                        existFlags = 0;
                    }
                    getMessagesStorage().getStorageQueue().postRunnable(() -> {
                        if (isSecretInvisibleMessage(newMsgObj)) {
                            res.date = 0;
                        }
                        getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, 0, newMsgObj.id, newMsgObj.id, res.date, false, 0);
                        AndroidUtilities.runOnUIThread(() -> {
                            newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
                            getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false);
                            getSendMessagesHelper().processSentMessage(newMsgObj.id);
                            if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) {
                                getSendMessagesHelper().stopVideoService(attachPath);
                            }
                            getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false);
                        });
                    });
                } else {
                    getMessagesStorage().markMessageAsSendError(newMsgObj, false);
                    AndroidUtilities.runOnUIThread(() -> {
                        newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
                        getNotificationCenter().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id);
                        getSendMessagesHelper().processSentMessage(newMsgObj.id);
                        if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) {
                            getSendMessagesHelper().stopVideoService(newMsgObj.attachPath);
                        }
                        getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false);
                    });
                }
            }, ConnectionsManager.RequestFlagInvokeAfter);
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : TLRPC(org.telegram.tgnet.TLRPC) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) TLObject(org.telegram.tgnet.TLObject)

Example 27 with TLObject

use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.

the class ArticleViewer method setParentActivity.

public void setParentActivity(Activity activity, BaseFragment fragment) {
    parentFragment = fragment;
    currentAccount = UserConfig.selectedAccount;
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
    if (parentActivity == activity) {
        updatePaintColors();
        refreshThemeColors();
        return;
    }
    parentActivity = activity;
    SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("articles", Activity.MODE_PRIVATE);
    selectedFont = sharedPreferences.getInt("font_type", 0);
    createPaint(false);
    backgroundPaint = new Paint();
    layerShadowDrawable = activity.getResources().getDrawable(R.drawable.layer_shadow);
    slideDotDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_small);
    slideDotBigDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_big);
    scrimPaint = new Paint();
    windowView = new WindowView(activity);
    windowView.setWillNotDraw(false);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);
    containerView = new FrameLayout(activity) {

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            if (windowView.movingPage) {
                int width = getMeasuredWidth();
                int translationX = (int) listView[0].getTranslationX();
                int clipLeft = 0;
                int clipRight = width;
                if (child == listView[1]) {
                    clipRight = translationX;
                } else if (child == listView[0]) {
                    clipLeft = translationX;
                }
                final int restoreCount = canvas.save();
                canvas.clipRect(clipLeft, 0, clipRight, getHeight());
                final boolean result = super.drawChild(canvas, child, drawingTime);
                canvas.restoreToCount(restoreCount);
                if (translationX != 0) {
                    if (child == listView[0]) {
                        final float alpha = Math.max(0, Math.min((width - translationX) / (float) AndroidUtilities.dp(20), 1.0f));
                        layerShadowDrawable.setBounds(translationX - layerShadowDrawable.getIntrinsicWidth(), child.getTop(), translationX, child.getBottom());
                        layerShadowDrawable.setAlpha((int) (0xff * alpha));
                        layerShadowDrawable.draw(canvas);
                    } else if (child == listView[1]) {
                        float opacity = Math.min(0.8f, (width - translationX) / (float) width);
                        if (opacity < 0) {
                            opacity = 0;
                        }
                        scrimPaint.setColor((int) (((0x99000000 & 0xff000000) >>> 24) * opacity) << 24);
                        canvas.drawRect(clipLeft, 0, clipRight, getHeight(), scrimPaint);
                    }
                }
                return result;
            } else {
                return super.drawChild(canvas, child, drawingTime);
            }
        }
    };
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    // containerView.setFitsSystemWindows(true);
    if (Build.VERSION.SDK_INT >= 21) {
        windowView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener((v, insets) -> {
            if (Build.VERSION.SDK_INT >= 30) {
                return WindowInsets.CONSUMED;
            } else {
                return insets.consumeSystemWindowInsets();
            }
        });
    }
    fullscreenVideoContainer = new FrameLayout(activity);
    fullscreenVideoContainer.setBackgroundColor(0xff000000);
    fullscreenVideoContainer.setVisibility(View.INVISIBLE);
    windowView.addView(fullscreenVideoContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    fullscreenAspectRatioView = new AspectRatioFrameLayout(activity);
    fullscreenAspectRatioView.setVisibility(View.GONE);
    fullscreenVideoContainer.addView(fullscreenAspectRatioView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));
    fullscreenTextureView = new TextureView(activity);
    listView = new RecyclerListView[2];
    adapter = new WebpageAdapter[2];
    layoutManager = new LinearLayoutManager[2];
    for (int i = 0; i < listView.length; i++) {
        WebpageAdapter webpageAdapter = adapter[i] = new WebpageAdapter(parentActivity);
        listView[i] = new RecyclerListView(activity) {

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                super.onLayout(changed, l, t, r, b);
                int count = getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = getChildAt(a);
                    if (child.getTag() instanceof Integer) {
                        Integer tag = (Integer) child.getTag();
                        if (tag == 90) {
                            int bottom = child.getBottom();
                            if (bottom < getMeasuredHeight()) {
                                int height = getMeasuredHeight();
                                child.layout(0, height - child.getMeasuredHeight(), child.getMeasuredWidth(), height);
                                break;
                            }
                        }
                    }
                }
            }

            @Override
            public boolean onInterceptTouchEvent(MotionEvent e) {
                if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
                    pressedLink = null;
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                } else if (pressedLinkOwnerLayout != null && pressedLink != null && e.getAction() == MotionEvent.ACTION_UP) {
                    checkLayoutForLinks(webpageAdapter, e, pressedLinkOwnerView, pressedLinkOwnerLayout, 0, 0);
                }
                return super.onInterceptTouchEvent(e);
            }

            @Override
            public boolean onTouchEvent(MotionEvent e) {
                if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
                    pressedLink = null;
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                }
                return super.onTouchEvent(e);
            }

            @Override
            public void setTranslationX(float translationX) {
                super.setTranslationX(translationX);
                if (windowView.movingPage) {
                    containerView.invalidate();
                    float progress = translationX / getMeasuredWidth();
                    setCurrentHeaderHeight((int) (windowView.startMovingHeaderHeight + (AndroidUtilities.dp(56) - windowView.startMovingHeaderHeight) * progress));
                }
            }
        };
        ((DefaultItemAnimator) listView[i].getItemAnimator()).setDelayAnimations(false);
        listView[i].setLayoutManager(layoutManager[i] = new LinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false));
        listView[i].setAdapter(webpageAdapter);
        listView[i].setClipToPadding(false);
        listView[i].setVisibility(i == 0 ? View.VISIBLE : View.GONE);
        listView[i].setPadding(0, AndroidUtilities.dp(56), 0, 0);
        listView[i].setTopGlowOffset(AndroidUtilities.dp(56));
        containerView.addView(listView[i], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        listView[i].setOnItemLongClickListener((view, position) -> {
            if (view instanceof BlockRelatedArticlesCell) {
                BlockRelatedArticlesCell cell = (BlockRelatedArticlesCell) view;
                showCopyPopup(cell.currentBlock.parent.articles.get(cell.currentBlock.num).url);
                return true;
            }
            return false;
        });
        listView[i].setOnItemClickListener((view, position, x, y) -> {
            if (textSelectionHelper != null) {
                if (textSelectionHelper.isSelectionMode()) {
                    textSelectionHelper.clear();
                    return;
                }
                textSelectionHelper.clear();
            }
            if (view instanceof ReportCell && webpageAdapter.currentPage != null) {
                ReportCell cell = (ReportCell) view;
                if (previewsReqId != 0 || cell.hasViews && x < view.getMeasuredWidth() / 2) {
                    return;
                }
                TLObject object = MessagesController.getInstance(currentAccount).getUserOrChat("previews");
                if (object instanceof TLRPC.TL_user) {
                    openPreviewsChat((TLRPC.User) object, webpageAdapter.currentPage.id);
                } else {
                    final int currentAccount = UserConfig.selectedAccount;
                    final long pageId = webpageAdapter.currentPage.id;
                    showProgressView(true, true);
                    TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
                    req.username = "previews";
                    previewsReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        if (previewsReqId == 0) {
                            return;
                        }
                        previewsReqId = 0;
                        showProgressView(true, false);
                        if (response != null) {
                            TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
                            MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                            MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, false, true);
                            if (!res.users.isEmpty()) {
                                openPreviewsChat(res.users.get(0), pageId);
                            }
                        }
                    }));
                }
            } else if (position >= 0 && position < webpageAdapter.localBlocks.size()) {
                TLRPC.PageBlock pageBlock = webpageAdapter.localBlocks.get(position);
                TLRPC.PageBlock originalBlock = pageBlock;
                pageBlock = getLastNonListPageBlock(pageBlock);
                if (pageBlock instanceof TL_pageBlockDetailsChild) {
                    TL_pageBlockDetailsChild detailsChild = (TL_pageBlockDetailsChild) pageBlock;
                    pageBlock = detailsChild.block;
                }
                if (pageBlock instanceof TLRPC.TL_pageBlockChannel) {
                    TLRPC.TL_pageBlockChannel pageBlockChannel = (TLRPC.TL_pageBlockChannel) pageBlock;
                    MessagesController.getInstance(currentAccount).openByUserName(pageBlockChannel.channel.username, parentFragment, 2);
                    close(false, true);
                } else if (pageBlock instanceof TL_pageBlockRelatedArticlesChild) {
                    TL_pageBlockRelatedArticlesChild pageBlockRelatedArticlesChild = (TL_pageBlockRelatedArticlesChild) pageBlock;
                    openWebpageUrl(pageBlockRelatedArticlesChild.parent.articles.get(pageBlockRelatedArticlesChild.num).url, null);
                } else if (pageBlock instanceof TLRPC.TL_pageBlockDetails) {
                    view = getLastNonListCell(view);
                    if (!(view instanceof BlockDetailsCell)) {
                        return;
                    }
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                    int index = webpageAdapter.blocks.indexOf(originalBlock);
                    if (index < 0) {
                        return;
                    }
                    TLRPC.TL_pageBlockDetails pageBlockDetails = (TLRPC.TL_pageBlockDetails) pageBlock;
                    pageBlockDetails.open = !pageBlockDetails.open;
                    int oldCount = webpageAdapter.getItemCount();
                    webpageAdapter.updateRows();
                    int newCount = webpageAdapter.getItemCount();
                    int changeCount = Math.abs(newCount - oldCount);
                    BlockDetailsCell cell = (BlockDetailsCell) view;
                    cell.arrow.setAnimationProgressAnimated(pageBlockDetails.open ? 0.0f : 1.0f);
                    cell.invalidate();
                    if (changeCount != 0) {
                        if (pageBlockDetails.open) {
                            webpageAdapter.notifyItemRangeInserted(position + 1, changeCount);
                        } else {
                            webpageAdapter.notifyItemRangeRemoved(position + 1, changeCount);
                        }
                    }
                }
            }
        });
        listView[i].setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    textSelectionHelper.stopScrolling();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getChildCount() == 0) {
                    return;
                }
                textSelectionHelper.onParentScrolled();
                headerView.invalidate();
                checkScroll(dy);
            }
        });
    }
    headerPaint.setColor(0xff000000);
    statusBarPaint.setColor(0xff000000);
    headerProgressPaint.setColor(0xff242426);
    headerView = new FrameLayout(activity) {

        @Override
        protected void onDraw(Canvas canvas) {
            int width = getMeasuredWidth();
            int height = getMeasuredHeight();
            canvas.drawRect(0, 0, width, height, headerPaint);
            if (layoutManager == null) {
                return;
            }
            int first = layoutManager[0].findFirstVisibleItemPosition();
            int last = layoutManager[0].findLastVisibleItemPosition();
            int count = layoutManager[0].getItemCount();
            View view;
            if (last >= count - 2) {
                view = layoutManager[0].findViewByPosition(count - 2);
            } else {
                view = layoutManager[0].findViewByPosition(first);
            }
            if (view == null) {
                return;
            }
            float itemProgress = width / (float) (count - 1);
            int childCount = layoutManager[0].getChildCount();
            float viewHeight = view.getMeasuredHeight();
            float viewProgress;
            if (last >= count - 2) {
                viewProgress = (count - 2 - first) * itemProgress * (listView[0].getMeasuredHeight() - view.getTop()) / viewHeight;
            } else {
                viewProgress = itemProgress * (1.0f - (Math.min(0, view.getTop() - listView[0].getPaddingTop()) + viewHeight) / viewHeight);
            }
            float progress = first * itemProgress + viewProgress;
            canvas.drawRect(0, 0, progress, height, headerProgressPaint);
        }
    };
    headerView.setWillNotDraw(false);
    containerView.addView(headerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
    headerView.setOnClickListener(v -> listView[0].smoothScrollToPosition(0));
    titleTextView = new SimpleTextView(activity);
    titleTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    titleTextView.setTextSize(20);
    titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    titleTextView.setTextColor(0xffb3b3b3);
    titleTextView.setPivotX(0.0f);
    titleTextView.setPivotY(AndroidUtilities.dp(28));
    headerView.addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56, Gravity.LEFT | Gravity.TOP, 72, 0, 48 * 2, 0));
    lineProgressView = new LineProgressView(activity);
    lineProgressView.setProgressColor(0xffffffff);
    lineProgressView.setPivotX(0.0f);
    lineProgressView.setPivotY(AndroidUtilities.dp(2));
    headerView.addView(lineProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 1));
    lineProgressTickRunnable = () -> {
        float progressLeft = 0.7f - lineProgressView.getCurrentProgress();
        if (progressLeft > 0.0f) {
            float tick;
            if (progressLeft < 0.25f) {
                tick = 0.01f;
            } else {
                tick = 0.02f;
            }
            lineProgressView.setProgress(lineProgressView.getCurrentProgress() + tick, true);
            AndroidUtilities.runOnUIThread(lineProgressTickRunnable, 100);
        }
    };
    menuContainer = new FrameLayout(activity);
    headerView.addView(menuContainer, LayoutHelper.createFrame(48, 56, Gravity.TOP | Gravity.RIGHT));
    searchShadow = new View(activity);
    searchShadow.setBackgroundResource(R.drawable.header_shadow);
    searchShadow.setAlpha(0.0f);
    containerView.addView(searchShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.TOP, 0, 56, 0, 0));
    searchContainer = new FrameLayout(parentActivity);
    searchContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    searchContainer.setVisibility(View.INVISIBLE);
    if (Build.VERSION.SDK_INT < 21) {
        searchContainer.setAlpha(0.0f);
    }
    headerView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
    searchField = new EditTextBoldCursor(parentActivity) {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (!AndroidUtilities.showKeyboard(this)) {
                    clearFocus();
                    requestFocus();
                }
            }
            return super.onTouchEvent(event);
        }
    };
    searchField.setCursorWidth(1.5f);
    searchField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    searchField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    searchField.setSingleLine(true);
    searchField.setHint(LocaleController.getString("Search", R.string.Search));
    searchField.setBackgroundResource(0);
    searchField.setPadding(0, 0, 0, 0);
    int inputType = searchField.getInputType() | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
    searchField.setInputType(inputType);
    if (Build.VERSION.SDK_INT < 23) {
        searchField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {
            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
    }
    searchField.setOnEditorActionListener((v, actionId, event) -> {
        if (event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            AndroidUtilities.hideKeyboard(searchField);
        }
        return false;
    });
    searchField.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (ignoreOnTextChange) {
                ignoreOnTextChange = false;
                return;
            }
            processSearch(s.toString().toLowerCase());
            if (clearButton != null) {
                if (TextUtils.isEmpty(s)) {
                    if (clearButton.getTag() != null) {
                        clearButton.setTag(null);
                        clearButton.clearAnimation();
                        if (animateClear) {
                            clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(0.0f).setDuration(180).scaleY(0.0f).scaleX(0.0f).rotation(45).withEndAction(() -> clearButton.setVisibility(View.INVISIBLE)).start();
                        } else {
                            clearButton.setAlpha(0.0f);
                            clearButton.setRotation(45);
                            clearButton.setScaleX(0.0f);
                            clearButton.setScaleY(0.0f);
                            clearButton.setVisibility(View.INVISIBLE);
                            animateClear = true;
                        }
                    }
                } else {
                    if (clearButton.getTag() == null) {
                        clearButton.setTag(1);
                        clearButton.clearAnimation();
                        clearButton.setVisibility(View.VISIBLE);
                        if (animateClear) {
                            clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(1.0f).setDuration(180).scaleY(1.0f).scaleX(1.0f).rotation(0).start();
                        } else {
                            clearButton.setAlpha(1.0f);
                            clearButton.setRotation(0);
                            clearButton.setScaleX(1.0f);
                            clearButton.setScaleY(1.0f);
                            animateClear = true;
                        }
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    searchField.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_SEARCH);
    searchField.setTextIsSelectable(false);
    searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 72, 0, 48, 0));
    clearButton = new ImageView(parentActivity) {

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            clearAnimation();
            if (getTag() == null) {
                clearButton.setVisibility(INVISIBLE);
                clearButton.setAlpha(0.0f);
                clearButton.setRotation(45);
                clearButton.setScaleX(0.0f);
                clearButton.setScaleY(0.0f);
            } else {
                clearButton.setAlpha(1.0f);
                clearButton.setRotation(0);
                clearButton.setScaleX(1.0f);
                clearButton.setScaleY(1.0f);
            }
        }
    };
    clearButton.setImageDrawable(new CloseProgressDrawable2());
    clearButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    clearButton.setScaleType(ImageView.ScaleType.CENTER);
    clearButton.setAlpha(0.0f);
    clearButton.setRotation(45);
    clearButton.setScaleX(0.0f);
    clearButton.setScaleY(0.0f);
    clearButton.setOnClickListener(v -> {
        if (searchField.length() != 0) {
            searchField.setText("");
        }
        searchField.requestFocus();
        AndroidUtilities.showKeyboard(searchField);
    });
    clearButton.setContentDescription(LocaleController.getString("ClearButton", R.string.ClearButton));
    searchContainer.addView(clearButton, LayoutHelper.createFrame(48, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
    backButton = new ImageView(activity);
    backButton.setScaleType(ImageView.ScaleType.CENTER);
    backDrawable = new BackDrawable(false);
    backDrawable.setAnimationTime(200.0f);
    backDrawable.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    backDrawable.setRotatedColor(0xffb3b3b3);
    backDrawable.setRotation(1.0f, false);
    backButton.setImageDrawable(backDrawable);
    backButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    headerView.addView(backButton, LayoutHelper.createFrame(54, 56));
    backButton.setOnClickListener(v -> {
        /*if (collapsed) {
                uncollapse();
            } else {
                collapse();
            }*/
        if (searchContainer.getTag() != null) {
            showSearch(false);
        } else {
            close(true, true);
        }
    });
    backButton.setContentDescription(LocaleController.getString("AccDescrGoBack", R.string.AccDescrGoBack));
    menuButton = new ActionBarMenuItem(parentActivity, null, Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, 0xffb3b3b3) {

        @Override
        public void toggleSubMenu() {
            super.toggleSubMenu();
            listView[0].stopScroll();
            checkScrollAnimated();
        }
    };
    menuButton.setLayoutInScreen(true);
    menuButton.setDuplicateParentStateEnabled(false);
    menuButton.setClickable(true);
    menuButton.setIcon(R.drawable.ic_ab_other);
    menuButton.addSubItem(search_item, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search));
    menuButton.addSubItem(share_item, R.drawable.msg_share, LocaleController.getString("ShareFile", R.string.ShareFile));
    menuButton.addSubItem(open_item, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
    menuButton.addSubItem(settings_item, R.drawable.menu_settings, LocaleController.getString("Settings", R.string.Settings));
    menuButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    menuButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    menuContainer.addView(menuButton, LayoutHelper.createFrame(48, 56));
    progressView = new ContextProgressView(activity, 2);
    progressView.setVisibility(View.GONE);
    menuContainer.addView(progressView, LayoutHelper.createFrame(48, 56));
    menuButton.setOnClickListener(v -> menuButton.toggleSubMenu());
    menuButton.setDelegate(id -> {
        if (adapter[0].currentPage == null || parentActivity == null) {
            return;
        }
        if (id == search_item) {
            showSearch(true);
        } else if (id == share_item) {
            showDialog(new ShareAlert(parentActivity, null, adapter[0].currentPage.url, false, adapter[0].currentPage.url, false));
        } else if (id == open_item) {
            String webPageUrl;
            if (!TextUtils.isEmpty(adapter[0].currentPage.cached_page.url)) {
                webPageUrl = adapter[0].currentPage.cached_page.url;
            } else {
                webPageUrl = adapter[0].currentPage.url;
            }
            Browser.openUrl(parentActivity, webPageUrl, true, false);
        } else if (id == settings_item) {
            BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity);
            builder.setApplyTopPadding(false);
            LinearLayout settingsContainer = new LinearLayout(parentActivity);
            settingsContainer.setPadding(0, 0, 0, AndroidUtilities.dp(4));
            settingsContainer.setOrientation(LinearLayout.VERTICAL);
            HeaderCell headerCell = new HeaderCell(parentActivity);
            headerCell.setText(LocaleController.getString("FontSize", R.string.FontSize));
            settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 1, 3, 0));
            TextSizeCell sizeCell = new TextSizeCell(parentActivity);
            settingsContainer.addView(sizeCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 0, 3, 0));
            headerCell = new HeaderCell(parentActivity);
            headerCell.setText(LocaleController.getString("FontType", R.string.FontType));
            settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 4, 3, 2));
            for (int a = 0; a < 2; a++) {
                fontCells[a] = new FontCell(parentActivity);
                switch(a) {
                    case 0:
                        fontCells[a].setTextAndTypeface(LocaleController.getString("Default", R.string.Default), Typeface.DEFAULT);
                        break;
                    case 1:
                        fontCells[a].setTextAndTypeface("Serif", Typeface.SERIF);
                        break;
                }
                fontCells[a].select(a == selectedFont, false);
                fontCells[a].setTag(a);
                fontCells[a].setOnClickListener(v -> {
                    int num = (Integer) v.getTag();
                    selectedFont = num;
                    for (int a1 = 0; a1 < 2; a1++) {
                        fontCells[a1].select(a1 == num, true);
                    }
                    updatePaintFonts();
                    for (int i = 0; i < listView.length; i++) {
                        adapter[i].notifyDataSetChanged();
                    }
                });
                settingsContainer.addView(fontCells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
            }
            builder.setCustomView(settingsContainer);
            showDialog(linkSheet = builder.create());
        }
    });
    searchPanel = new FrameLayout(parentActivity) {

        @Override
        public void onDraw(Canvas canvas) {
            int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
            Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
            Theme.chat_composeShadowDrawable.draw(canvas);
            canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint);
        }
    };
    searchPanel.setOnTouchListener((v, event) -> true);
    searchPanel.setWillNotDraw(false);
    searchPanel.setVisibility(View.INVISIBLE);
    searchPanel.setFocusable(true);
    searchPanel.setFocusableInTouchMode(true);
    searchPanel.setClickable(true);
    searchPanel.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    containerView.addView(searchPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    searchUpButton = new ImageView(parentActivity);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(R.drawable.msg_go_up);
    searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchPanel.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0));
    searchUpButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex - 1));
    searchUpButton.setContentDescription(LocaleController.getString("AccDescrSearchNext", R.string.AccDescrSearchNext));
    searchDownButton = new ImageView(parentActivity);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(R.drawable.msg_go_down);
    searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchPanel.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0));
    searchDownButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex + 1));
    searchDownButton.setContentDescription(LocaleController.getString("AccDescrSearchPrev", R.string.AccDescrSearchPrev));
    searchCountText = new SimpleTextView(parentActivity);
    searchCountText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchCountText.setGravity(Gravity.LEFT);
    searchPanel.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 18, 0, 108, 0));
    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 - 1;
    windowLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
    windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
        if (Build.VERSION.SDK_INT >= 28) {
            windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
    }
    textSelectionHelper = new TextSelectionHelper.ArticleTextSelectionHelper();
    textSelectionHelper.setParentView(listView[0]);
    if (MessagesController.getGlobalMainSettings().getBoolean("translate_button", false)) {
        textSelectionHelper.setOnTranslate((text, fromLang, toLang, onAlertDismiss) -> {
            TranslateAlert.showAlert(parentActivity, parentFragment, fromLang, toLang, text, false, null, onAlertDismiss);
        });
    }
    textSelectionHelper.layoutManager = layoutManager[0];
    textSelectionHelper.setCallback(new TextSelectionHelper.Callback() {

        @Override
        public void onStateChanged(boolean isSelected) {
            if (isSelected) {
                showSearch(false);
            }
        }

        @Override
        public void onTextCopied() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                BulletinFactory.of(containerView, null).createCopyBulletin(LocaleController.getString("TextCopied", R.string.TextCopied)).show();
            }
        }
    });
    containerView.addView(textSelectionHelper.getOverlayView(activity));
    pinchToZoomHelper = new PinchToZoomHelper(containerView, windowView);
    pinchToZoomHelper.setClipBoundsListener(new PinchToZoomHelper.ClipBoundsListener() {

        @Override
        public void getClipTopBottom(float[] topBottom) {
            topBottom[0] = currentHeaderHeight;
            topBottom[1] = listView[0].getMeasuredHeight();
        }
    });
    pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {

        @Override
        public void onZoomStarted(MessageObject messageObject) {
            if (listView[0] != null) {
                listView[0].cancelClickRunnables(true);
            }
        }
    });
    updatePaintColors();
}
Also used : POSITION_FLAG_RIGHT(org.telegram.messenger.MessageObject.POSITION_FLAG_RIGHT) JavascriptInterface(android.webkit.JavascriptInterface) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Property(android.util.Property) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) HorizontalScrollView(android.widget.HorizontalScrollView) Keep(androidx.annotation.Keep) CookieManager(android.webkit.CookieManager) RadioButton(org.telegram.ui.Components.RadioButton) Canvas(android.graphics.Canvas) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) AnimationProperties(org.telegram.ui.Components.AnimationProperties) MetricAffectingSpan(android.text.style.MetricAffectingSpan) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaintSpan(org.telegram.ui.Components.TextPaintSpan) HapticFeedbackConstants(android.view.HapticFeedbackConstants) StaticLayoutEx(org.telegram.ui.Components.StaticLayoutEx) Layout(android.text.Layout) TextPaint(android.text.TextPaint) TextPaintMarkSpan(org.telegram.ui.Components.TextPaintMarkSpan) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) DisplayCutout(android.view.DisplayCutout) WebSettings(android.webkit.WebSettings) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) Menu(android.view.Menu) WebChromeClient(android.webkit.WebChromeClient) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) URLSpan(android.text.style.URLSpan) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) POSITION_FLAG_TOP(org.telegram.messenger.MessageObject.POSITION_FLAG_TOP) File(java.io.File) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) MessagesStorage(org.telegram.messenger.MessagesStorage) ValueAnimator(android.animation.ValueAnimator) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) AnimatedArrowDrawable(org.telegram.ui.Components.AnimatedArrowDrawable) RadialProgress2(org.telegram.ui.Components.RadialProgress2) URLDecoder(java.net.URLDecoder) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) POSITION_FLAG_BOTTOM(org.telegram.messenger.MessageObject.POSITION_FLAG_BOTTOM) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) WebFile(org.telegram.messenger.WebFile) ViewConfiguration(android.view.ViewConfiguration) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) MediaController(org.telegram.messenger.MediaController) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) WebView(android.webkit.WebView) DataSetObserver(android.database.DataSetObserver) POSITION_FLAG_LEFT(org.telegram.messenger.MessageObject.POSITION_FLAG_LEFT) RectF(android.graphics.RectF) ImageLoader(org.telegram.messenger.ImageLoader) IntEvaluator(android.animation.IntEvaluator) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ViewAnimationUtils(android.view.ViewAnimationUtils) TextPaintImageReceiverSpan(org.telegram.ui.Components.TextPaintImageReceiverSpan) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) TableLayout(org.telegram.ui.Components.TableLayout) ViewGroup(android.view.ViewGroup) ShareAlert(org.telegram.ui.Components.ShareAlert) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) SparseArray(android.util.SparseArray) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) WebPlayerView(org.telegram.ui.Components.WebPlayerView) WindowInsets(android.view.WindowInsets) LinkPath(org.telegram.ui.Components.LinkPath) EditorInfo(android.view.inputmethod.EditorInfo) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) Theme(org.telegram.ui.ActionBar.Theme) TextPaintWebpageUrlSpan(org.telegram.ui.Components.TextPaintWebpageUrlSpan) PagerAdapter(androidx.viewpager.widget.PagerAdapter) BulletinFactory(org.telegram.ui.Components.BulletinFactory) TextPaintUrlSpan(org.telegram.ui.Components.TextPaintUrlSpan) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) TranslateAlert(org.telegram.ui.Components.TranslateAlert) PixelFormat(android.graphics.PixelFormat) MenuItem(android.view.MenuItem) SeekBar(org.telegram.ui.Components.SeekBar) VelocityTracker(android.view.VelocityTracker) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) Build(android.os.Build) AnchorSpan(org.telegram.ui.Components.AnchorSpan) SeekBarView(org.telegram.ui.Components.SeekBarView) DownloadController(org.telegram.messenger.DownloadController) Browser(org.telegram.messenger.browser.Browser) LongSparseArray(androidx.collection.LongSparseArray) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) FileLog(org.telegram.messenger.FileLog) LineProgressView(org.telegram.ui.Components.LineProgressView) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) SoundEffectConstants(android.view.SoundEffectConstants) CloseProgressDrawable2(org.telegram.ui.Components.CloseProgressDrawable2) Activity(android.app.Activity) ImageReceiver(org.telegram.messenger.ImageReceiver) Collections(java.util.Collections) RecyclerListView(org.telegram.ui.Components.RecyclerListView) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) SpannableStringBuilder(android.text.SpannableStringBuilder) HeaderCell(org.telegram.ui.Cells.HeaderCell) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CloseProgressDrawable2(org.telegram.ui.Components.CloseProgressDrawable2) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) TLRPC(org.telegram.tgnet.TLRPC) ImageView(android.widget.ImageView) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Canvas(android.graphics.Canvas) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) ActionMode(android.view.ActionMode) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ContextProgressView(org.telegram.ui.Components.ContextProgressView) ShareAlert(org.telegram.ui.Components.ShareAlert) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) WindowManager(android.view.WindowManager) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextureView(android.view.TextureView) Menu(android.view.Menu) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) SharedPreferences(android.content.SharedPreferences) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) MenuItem(android.view.MenuItem) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) WebView(android.webkit.WebView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TextView(android.widget.TextView) WebPlayerView(org.telegram.ui.Components.WebPlayerView) SeekBarView(org.telegram.ui.Components.SeekBarView) TextureView(android.view.TextureView) LineProgressView(org.telegram.ui.Components.LineProgressView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) TLObject(org.telegram.tgnet.TLObject) FrameLayout(android.widget.FrameLayout) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView) LineProgressView(org.telegram.ui.Components.LineProgressView) MessageObject(org.telegram.messenger.MessageObject) LinearLayout(android.widget.LinearLayout)

Example 28 with TLObject

use of org.telegram.tgnet.TLObject 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 29 with TLObject

use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.

the class PhotoViewer method onActionClick.

private void onActionClick(boolean download) {
    if (currentMessageObject == null && currentBotInlineResult == null && pageBlocksAdapter == null || currentFileNames[0] == null) {
        return;
    }
    Uri uri = null;
    File file = null;
    isStreaming = false;
    if (currentMessageObject != null) {
        if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) {
            file = new File(currentMessageObject.messageOwner.attachPath);
            if (!file.exists()) {
                file = null;
            }
        }
        if (file == null) {
            file = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
            if (!file.exists()) {
                file = null;
                if (SharedConfig.streamMedia && !DialogObject.isEncryptedDialog(currentMessageObject.getDialogId()) && currentMessageObject.isVideo() && currentMessageObject.canStreamVideo()) {
                    try {
                        int reference = FileLoader.getInstance(currentMessageObject.currentAccount).getFileReference(currentMessageObject);
                        FileLoader.getInstance(currentAccount).loadFile(currentMessageObject.getDocument(), currentMessageObject, 1, 0);
                        TLRPC.Document document = currentMessageObject.getDocument();
                        String params = "?account=" + currentMessageObject.currentAccount + "&id=" + document.id + "&hash=" + document.access_hash + "&dc=" + document.dc_id + "&size=" + document.size + "&mime=" + URLEncoder.encode(document.mime_type, "UTF-8") + "&rid=" + reference + "&name=" + URLEncoder.encode(FileLoader.getDocumentFileName(document), "UTF-8") + "&reference=" + Utilities.bytesToHex(document.file_reference != null ? document.file_reference : new byte[0]);
                        uri = Uri.parse("tg://" + currentMessageObject.getFileName() + params);
                        isStreaming = true;
                        checkProgress(0, false, false);
                    } catch (Exception ignore) {
                    }
                }
            }
        }
    } else if (currentBotInlineResult != null) {
        if (currentBotInlineResult.document != null) {
            file = FileLoader.getPathToAttach(currentBotInlineResult.document);
            if (!file.exists()) {
                file = null;
            }
        } else if (currentBotInlineResult.content instanceof TLRPC.TL_webDocument) {
            file = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(currentBotInlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(currentBotInlineResult.content.url, "mp4"));
            if (!file.exists()) {
                file = null;
            }
        }
    } else if (pageBlocksAdapter != null) {
        TLObject media = pageBlocksAdapter.getMedia(currentIndex);
        if (!(media instanceof TLRPC.Document)) {
            return;
        }
        file = pageBlocksAdapter.getFile(currentIndex);
        if (file != null && !file.exists()) {
            file = null;
        }
    }
    if (file != null && uri == null) {
        uri = Uri.fromFile(file);
    }
    if (uri == null) {
        if (download) {
            if (currentMessageObject != null) {
                if (!FileLoader.getInstance(currentAccount).isLoadingFile(currentFileNames[0])) {
                    FileLoader.getInstance(currentAccount).loadFile(currentMessageObject.getDocument(), currentMessageObject, 1, 0);
                } else {
                    FileLoader.getInstance(currentAccount).cancelLoadFile(currentMessageObject.getDocument());
                }
            } else if (currentBotInlineResult != null) {
                if (currentBotInlineResult.document != null) {
                    if (!FileLoader.getInstance(currentAccount).isLoadingFile(currentFileNames[0])) {
                        FileLoader.getInstance(currentAccount).loadFile(currentBotInlineResult.document, currentMessageObject, 1, 0);
                    } else {
                        FileLoader.getInstance(currentAccount).cancelLoadFile(currentBotInlineResult.document);
                    }
                } else if (currentBotInlineResult.content instanceof TLRPC.TL_webDocument) {
                    if (!ImageLoader.getInstance().isLoadingHttpFile(currentBotInlineResult.content.url)) {
                        ImageLoader.getInstance().loadHttpFile(currentBotInlineResult.content.url, "mp4", currentAccount);
                    } else {
                        ImageLoader.getInstance().cancelLoadHttpFile(currentBotInlineResult.content.url);
                    }
                }
            } else if (pageBlocksAdapter != null) {
                if (!FileLoader.getInstance(currentAccount).isLoadingFile(currentFileNames[0])) {
                    FileLoader.getInstance(currentAccount).loadFile((TLRPC.Document) pageBlocksAdapter.getMedia(currentIndex), pageBlocksAdapter.getParentObject(), 1, 1);
                } else {
                    FileLoader.getInstance(currentAccount).cancelLoadFile((TLRPC.Document) pageBlocksAdapter.getMedia(currentIndex));
                }
            }
            Drawable drawable = centerImage.getStaticThumb();
            if (drawable instanceof OtherDocumentPlaceholderDrawable) {
                ((OtherDocumentPlaceholderDrawable) drawable).checkFileExist();
            }
        }
    } else {
        if (sharedMediaType == MediaDataController.MEDIA_FILE && !currentMessageObject.canPreviewDocument()) {
            AndroidUtilities.openDocument(currentMessageObject, parentActivity, null);
            return;
        }
        preparePlayer(uri, true, false);
    }
}
Also used : TLObject(org.telegram.tgnet.TLObject) OtherDocumentPlaceholderDrawable(org.telegram.ui.Components.OtherDocumentPlaceholderDrawable) 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) SpannableString(android.text.SpannableString) SecureDocument(org.telegram.messenger.SecureDocument) Uri(android.net.Uri) WebFile(org.telegram.messenger.WebFile) File(java.io.File) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC)

Example 30 with TLObject

use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.

the class FilterUsersActivity method createView.

@Override
public View createView(Context context) {
    searching = false;
    searchWas = false;
    allSpans.clear();
    selectedContacts.clear();
    currentDeletingSpan = null;
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (isInclude) {
        actionBar.setTitle(LocaleController.getString("FilterAlwaysShow", R.string.FilterAlwaysShow));
    } else {
        actionBar.setTitle(LocaleController.getString("FilterNeverShow", R.string.FilterNeverShow));
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                onDonePressed(true);
            }
        }
    });
    fragmentView = new ViewGroup(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(width, height);
            int maxSize;
            if (AndroidUtilities.isTablet() || height > width) {
                maxSize = AndroidUtilities.dp(144);
            } else {
                maxSize = AndroidUtilities.dp(56);
            }
            scrollView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.AT_MOST));
            listView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
            emptyView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
            if (floatingButton != null) {
                int w = AndroidUtilities.dp(Build.VERSION.SDK_INT >= 21 ? 56 : 60);
                floatingButton.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            scrollView.layout(0, 0, scrollView.getMeasuredWidth(), scrollView.getMeasuredHeight());
            listView.layout(0, scrollView.getMeasuredHeight(), listView.getMeasuredWidth(), scrollView.getMeasuredHeight() + listView.getMeasuredHeight());
            emptyView.layout(0, scrollView.getMeasuredHeight(), emptyView.getMeasuredWidth(), scrollView.getMeasuredHeight() + emptyView.getMeasuredHeight());
            if (floatingButton != null) {
                int l = LocaleController.isRTL ? AndroidUtilities.dp(14) : (right - left) - AndroidUtilities.dp(14) - floatingButton.getMeasuredWidth();
                int t = bottom - top - AndroidUtilities.dp(14) - floatingButton.getMeasuredHeight();
                floatingButton.layout(l, t, l + floatingButton.getMeasuredWidth(), t + floatingButton.getMeasuredHeight());
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == listView || child == emptyView) {
                parentLayout.drawHeaderShadow(canvas, scrollView.getMeasuredHeight());
            }
            return result;
        }
    };
    ViewGroup frameLayout = (ViewGroup) fragmentView;
    scrollView = new ScrollView(context) {

        @Override
        public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
            if (ignoreScrollEvent) {
                ignoreScrollEvent = false;
                return false;
            }
            rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
            rectangle.top += fieldY + AndroidUtilities.dp(20);
            rectangle.bottom += fieldY + AndroidUtilities.dp(50);
            return super.requestChildRectangleOnScreen(child, rectangle, immediate);
        }
    };
    scrollView.setVerticalScrollBarEnabled(false);
    AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_windowBackgroundWhite));
    frameLayout.addView(scrollView);
    spansContainer = new SpansContainer(context);
    scrollView.addView(spansContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    spansContainer.setOnClickListener(v -> {
        editText.clearFocus();
        editText.requestFocus();
        AndroidUtilities.showKeyboard(editText);
    });
    editText = new EditTextBoldCursor(context) {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (currentDeletingSpan != null) {
                currentDeletingSpan.cancelDeleteAnimation();
                currentDeletingSpan = null;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (!AndroidUtilities.showKeyboard(this)) {
                    clearFocus();
                    requestFocus();
                }
            }
            return super.onTouchEvent(event);
        }
    };
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    editText.setHintColor(Theme.getColor(Theme.key_groupcreate_hintText));
    editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setCursorColor(Theme.getColor(Theme.key_groupcreate_cursor));
    editText.setCursorWidth(1.5f);
    editText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    editText.setSingleLine(true);
    editText.setBackgroundDrawable(null);
    editText.setVerticalScrollBarEnabled(false);
    editText.setHorizontalScrollBarEnabled(false);
    editText.setTextIsSelectable(false);
    editText.setPadding(0, 0, 0, 0);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    editText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
    spansContainer.addView(editText);
    editText.setHintText(LocaleController.getString("SearchForPeopleAndGroups", R.string.SearchForPeopleAndGroups));
    editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
    // editText.setOnEditorActionListener((v, actionId, event) -> actionId == EditorInfo.IME_ACTION_DONE && onDonePressed(true));
    editText.setOnKeyListener(new View.OnKeyListener() {

        private boolean wasEmpty;

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    wasEmpty = editText.length() == 0;
                } else if (event.getAction() == KeyEvent.ACTION_UP && wasEmpty && !allSpans.isEmpty()) {
                    GroupCreateSpan span = allSpans.get(allSpans.size() - 1);
                    spansContainer.removeSpan(span);
                    if (span.getUid() == Integer.MIN_VALUE) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 1) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 2) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 3) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 4) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_BOTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 5) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                    } else if (span.getUid() == Integer.MIN_VALUE + 6) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
                    } else if (span.getUid() == Integer.MIN_VALUE + 7) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                    }
                    updateHint();
                    checkVisibleRows();
                    return true;
                }
            }
            return false;
        }
    });
    editText.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editText.length() != 0) {
                if (!adapter.searching) {
                    searching = true;
                    searchWas = true;
                    adapter.setSearching(true);
                    listView.setFastScrollVisible(false);
                    listView.setVerticalScrollBarEnabled(true);
                    emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult));
                    emptyView.showProgress();
                }
                adapter.searchDialogs(editText.getText().toString());
            } else {
                closeSearch();
            }
        }
    });
    emptyView = new EmptyTextProgressView(context);
    if (ContactsController.getInstance(currentAccount).isLoadingContacts()) {
        emptyView.showProgress();
    } else {
        emptyView.showTextView();
    }
    emptyView.setShowAtCenter(true);
    emptyView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
    frameLayout.addView(emptyView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
    listView = new RecyclerListView(context);
    listView.setFastScrollEnabled(RecyclerListView.FastScroll.LETTER_TYPE);
    listView.setEmptyView(emptyView);
    listView.setAdapter(adapter = new GroupCreateAdapter(context));
    listView.setLayoutManager(linearLayoutManager);
    listView.setVerticalScrollBarEnabled(false);
    listView.setVerticalScrollbarPosition(LocaleController.isRTL ? View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT);
    listView.addItemDecoration(new ItemDecoration());
    frameLayout.addView(listView);
    listView.setOnItemClickListener((view, position) -> {
        if (view instanceof GroupCreateUserCell) {
            GroupCreateUserCell cell = (GroupCreateUserCell) view;
            Object object = cell.getObject();
            long id;
            if (object instanceof String) {
                int flag;
                if (isInclude) {
                    if (position == 1) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                        id = Integer.MIN_VALUE;
                    } else if (position == 2) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                        id = Integer.MIN_VALUE + 1;
                    } else if (position == 3) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                        id = Integer.MIN_VALUE + 2;
                    } else if (position == 4) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                        id = Integer.MIN_VALUE + 3;
                    } else {
                        flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
                        id = Integer.MIN_VALUE + 4;
                    }
                } else {
                    if (position == 1) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                        id = Integer.MIN_VALUE + 5;
                    } else if (position == 2) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
                        id = Integer.MIN_VALUE + 6;
                    } else {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        id = Integer.MIN_VALUE + 7;
                    }
                }
                if (cell.isChecked()) {
                    filterFlags &= ~flag;
                } else {
                    filterFlags |= flag;
                }
            } else {
                if (object instanceof TLRPC.User) {
                    id = ((TLRPC.User) object).id;
                } else if (object instanceof TLRPC.Chat) {
                    id = -((TLRPC.Chat) object).id;
                } else {
                    return;
                }
            }
            boolean exists;
            if (exists = selectedContacts.indexOfKey(id) >= 0) {
                GroupCreateSpan span = selectedContacts.get(id);
                spansContainer.removeSpan(span);
            } else {
                if (!(object instanceof String) && selectedCount >= 100) {
                    return;
                }
                if (object instanceof TLRPC.User) {
                    TLRPC.User user = (TLRPC.User) object;
                    MessagesController.getInstance(currentAccount).putUser(user, !searching);
                } else if (object instanceof TLRPC.Chat) {
                    TLRPC.Chat chat = (TLRPC.Chat) object;
                    MessagesController.getInstance(currentAccount).putChat(chat, !searching);
                }
                GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
                spansContainer.addSpan(span, true);
                span.setOnClickListener(FilterUsersActivity.this);
            }
            updateHint();
            if (searching || searchWas) {
                AndroidUtilities.showKeyboard(editText);
            } else {
                cell.setChecked(!exists, true);
            }
            if (editText.length() > 0) {
                editText.setText(null);
            }
        }
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(editText);
            }
        }
    });
    floatingButton = new ImageView(context);
    floatingButton.setScaleType(ImageView.ScaleType.CENTER);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    floatingButton.setBackgroundDrawable(drawable);
    floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
    floatingButton.setImageResource(R.drawable.floating_check);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        floatingButton.setStateListAnimator(animator);
        floatingButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    frameLayout.addView(floatingButton);
    floatingButton.setOnClickListener(v -> onDonePressed(true));
    /*floatingButton.setVisibility(View.INVISIBLE);
        floatingButton.setScaleX(0.0f);
        floatingButton.setScaleY(0.0f);
        floatingButton.setAlpha(0.0f);*/
    floatingButton.setContentDescription(LocaleController.getString("Next", R.string.Next));
    for (int position = 1, N = (isInclude ? 5 : 3); position <= N; position++) {
        int id;
        int flag;
        Object object;
        if (isInclude) {
            if (position == 1) {
                object = "contacts";
                flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
            } else if (position == 2) {
                object = "non_contacts";
                flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
            } else if (position == 3) {
                object = "groups";
                flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
            } else if (position == 4) {
                object = "channels";
                flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
            } else {
                object = "bots";
                flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
            }
        } else {
            if (position == 1) {
                object = "muted";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
            } else if (position == 2) {
                object = "read";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
            } else {
                object = "archived";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
            }
        }
        if ((filterFlags & flag) != 0) {
            GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
            spansContainer.addSpan(span, false);
            span.setOnClickListener(FilterUsersActivity.this);
        }
    }
    if (initialIds != null && !initialIds.isEmpty()) {
        TLObject object;
        for (int a = 0, N = initialIds.size(); a < N; a++) {
            Long id = initialIds.get(a);
            if (id > 0) {
                object = getMessagesController().getUser(id);
            } else {
                object = getMessagesController().getChat(-id);
            }
            if (object == null) {
                continue;
            }
            GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
            spansContainer.addSpan(span, false);
            span.setOnClickListener(FilterUsersActivity.this);
        }
    }
    updateHint();
    return fragmentView;
}
Also used : LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) ImageView(android.widget.ImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ActionMode(android.view.ActionMode) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) TLObject(org.telegram.tgnet.TLObject) DialogObject(org.telegram.messenger.DialogObject) UserObject(org.telegram.messenger.UserObject) GroupCreateSpan(org.telegram.ui.Components.GroupCreateSpan) StateListAnimator(android.animation.StateListAnimator) GroupCreateUserCell(org.telegram.ui.Cells.GroupCreateUserCell) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) KeyEvent(android.view.KeyEvent) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) Menu(android.view.Menu) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ViewGroup(android.view.ViewGroup) MenuItem(android.view.MenuItem) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) Outline(android.graphics.Outline) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ScrollView(android.widget.ScrollView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ViewOutlineProvider(android.view.ViewOutlineProvider) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ScrollView(android.widget.ScrollView) TLObject(org.telegram.tgnet.TLObject) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Aggregations

TLObject (org.telegram.tgnet.TLObject)85 TLRPC (org.telegram.tgnet.TLRPC)79 Paint (android.graphics.Paint)36 ArrayList (java.util.ArrayList)36 TextPaint (android.text.TextPaint)25 SuppressLint (android.annotation.SuppressLint)22 ConnectionsManager (org.telegram.tgnet.ConnectionsManager)22 File (java.io.File)21 HashMap (java.util.HashMap)20 Context (android.content.Context)19 Build (android.os.Build)19 TextUtils (android.text.TextUtils)19 MessageObject (org.telegram.messenger.MessageObject)19 Theme (org.telegram.ui.ActionBar.Theme)19 BaseFragment (org.telegram.ui.ActionBar.BaseFragment)18 LongSparseArray (androidx.collection.LongSparseArray)17 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)17 Bundle (android.os.Bundle)16 SpannableStringBuilder (android.text.SpannableStringBuilder)16 ChatObject (org.telegram.messenger.ChatObject)16