Search in sources :

Example 1 with Size

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

the class RenderView method updateTransform.

private void updateTransform() {
    Matrix matrix = new Matrix();
    float scale = painting != null ? getWidth() / painting.getSize().width : 1.0f;
    if (scale <= 0) {
        scale = 1.0f;
    }
    Size paintingSize = getPainting().getSize();
    matrix.preTranslate(getWidth() / 2.0f, getHeight() / 2.0f);
    matrix.preScale(scale, -scale);
    matrix.preTranslate(-paintingSize.width / 2.0f, -paintingSize.height / 2.0f);
    input.setMatrix(matrix);
    float[] proj = GLMatrix.LoadOrtho(0.0f, internal.bufferWidth, 0.0f, internal.bufferHeight, -1.0f, 1.0f);
    float[] effectiveProjection = GLMatrix.LoadGraphicsMatrix(matrix);
    float[] finalProjection = GLMatrix.MultiplyMat4f(proj, effectiveProjection);
    painting.setRenderProjection(finalProjection);
}
Also used : Size(org.telegram.ui.Components.Size)

Example 2 with Size

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

the class ChatActivity method createMenu.

private void createMenu(View v, boolean single, boolean listView, float x, float y, boolean searchGroup) {
    if (actionBar.isActionModeShowed() || reportType >= 0) {
        return;
    }
    MessageObject message;
    MessageObject primaryMessage;
    if (v instanceof ChatMessageCell) {
        message = ((ChatMessageCell) v).getMessageObject();
        primaryMessage = ((ChatMessageCell) v).getPrimaryMessageObject();
    } else if (v instanceof ChatActionCell) {
        message = ((ChatActionCell) v).getMessageObject();
        primaryMessage = message;
    } else {
        primaryMessage = null;
        message = null;
    }
    if (message == null) {
        return;
    }
    final int type = getMessageType(message);
    if (single) {
        if (message.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
            if (message.getReplyMsgId() != 0) {
                scrollToMessageId(message.getReplyMsgId(), message.messageOwner.id, true, message.getDialogId() == mergeDialogId ? 1 : 0, false, 0);
            } else {
                Toast.makeText(getParentActivity(), LocaleController.getString("MessageNotFound", R.string.MessageNotFound), Toast.LENGTH_SHORT).show();
            }
            return;
        } else if (message.messageOwner.action instanceof TLRPC.TL_messageActionSetMessagesTTL) {
            if (avatarContainer.openSetTimer()) {
                return;
            }
        } else if (message.messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent && message.replyMessageObject != null && message.replyMessageObject.isInvoice()) {
            TLRPC.TL_payments_getPaymentReceipt req = new TLRPC.TL_payments_getPaymentReceipt();
            req.msg_id = message.getId();
            req.peer = getMessagesController().getInputPeer(message.messageOwner.peer_id);
            getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                if (response instanceof TLRPC.TL_payments_paymentReceipt) {
                    presentFragment(new PaymentFormActivity((TLRPC.TL_payments_paymentReceipt) response));
                }
            }), ConnectionsManager.RequestFlagFailOnServerErrors);
            return;
        } else if (message.messageOwner.action instanceof TLRPC.TL_messageActionGroupCall || message.messageOwner.action instanceof TLRPC.TL_messageActionInviteToGroupCall || message.messageOwner.action instanceof TLRPC.TL_messageActionGroupCallScheduled) {
            if (getParentActivity() == null) {
                return;
            }
            VoIPService sharedInstance = VoIPService.getSharedInstance();
            if (sharedInstance != null) {
                if (sharedInstance.groupCall != null && message.messageOwner.action.call.id == sharedInstance.groupCall.call.id) {
                    if (getParentActivity() instanceof LaunchActivity) {
                        GroupCallActivity.create((LaunchActivity) getParentActivity(), AccountInstance.getInstance(currentAccount), null, null, false, null);
                    } else {
                        Intent intent = new Intent(getParentActivity(), LaunchActivity.class).setAction("voip_chat");
                        intent.putExtra("currentAccount", VoIPService.getSharedInstance().getAccount());
                        getParentActivity().startActivity(intent);
                    }
                } else {
                    createGroupCall = getGroupCall() == null;
                    VoIPHelper.startCall(currentChat, null, null, createGroupCall, getParentActivity(), ChatActivity.this, getAccountInstance());
                }
                return;
            } else if (fragmentContextView != null && getGroupCall() != null) {
                if (VoIPService.getSharedInstance() != null) {
                    GroupCallActivity.create((LaunchActivity) getParentActivity(), AccountInstance.getInstance(VoIPService.getSharedInstance().getAccount()), null, null, false, null);
                } else {
                    ChatObject.Call call = getGroupCall();
                    if (call == null) {
                        return;
                    }
                    VoIPHelper.startCall(getMessagesController().getChat(call.chatId), null, null, false, getParentActivity(), ChatActivity.this, getAccountInstance());
                }
                return;
            } else if (ChatObject.canManageCalls(currentChat)) {
                VoIPHelper.showGroupCallAlert(ChatActivity.this, currentChat, null, true, getAccountInstance());
                return;
            }
        } else if (message.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) {
            showChatThemeBottomSheet();
            return;
        }
    }
    if (message.isSponsored() || threadMessageObjects != null && threadMessageObjects.contains(message)) {
        single = true;
    }
    selectedObject = null;
    selectedObjectGroup = null;
    forwardingMessage = null;
    forwardingMessageGroup = null;
    selectedObjectToEditCaption = null;
    for (int a = 1; a >= 0; a--) {
        selectedMessagesCanCopyIds[a].clear();
        selectedMessagesCanStarIds[a].clear();
        selectedMessagesIds[a].clear();
    }
    hideActionMode();
    updatePinnedMessageView(true);
    MessageObject.GroupedMessages groupedMessages;
    if (searchGroup) {
        groupedMessages = getValidGroupedMessage(message);
    } else {
        groupedMessages = null;
    }
    boolean allowChatActions = true;
    boolean allowPin;
    if (chatMode == MODE_SCHEDULED || isThreadChat()) {
        allowPin = false;
    } else if (currentChat != null) {
        allowPin = message.getDialogId() != mergeDialogId && ChatObject.canPinMessages(currentChat);
    } else if (currentEncryptedChat == null) {
        if (UserObject.isDeleted(currentUser)) {
            allowPin = false;
        } else if (userInfo != null) {
            allowPin = userInfo.can_pin_message;
        } else {
            allowPin = false;
        }
    } else {
        allowPin = false;
    }
    allowPin = allowPin && message.getId() > 0 && (message.messageOwner.action == null || message.messageOwner.action instanceof TLRPC.TL_messageActionEmpty);
    boolean noforwards = getMessagesController().isChatNoForwards(currentChat) || message.messageOwner.noforwards;
    boolean allowUnpin = message.getDialogId() != mergeDialogId && allowPin && (pinnedMessageObjects.containsKey(message.getId()) || groupedMessages != null && !groupedMessages.messages.isEmpty() && pinnedMessageObjects.containsKey(groupedMessages.messages.get(0).getId()));
    boolean allowEdit = message.canEditMessage(currentChat) && !chatActivityEnterView.hasAudioToSend() && message.getDialogId() != mergeDialogId;
    if (allowEdit && groupedMessages != null) {
        int captionsCount = 0;
        for (int a = 0, N = groupedMessages.messages.size(); a < N; a++) {
            MessageObject messageObject = groupedMessages.messages.get(a);
            if (a == 0 || !TextUtils.isEmpty(messageObject.caption)) {
                selectedObjectToEditCaption = messageObject;
                if (!TextUtils.isEmpty(messageObject.caption)) {
                    captionsCount++;
                }
            }
        }
        allowEdit = captionsCount < 2;
    }
    if (chatMode == MODE_SCHEDULED || threadMessageObjects != null && threadMessageObjects.contains(message) || message.isSponsored() || type == 1 && message.getDialogId() == mergeDialogId || message.messageOwner.action instanceof TLRPC.TL_messageActionSecureValuesSent || currentEncryptedChat == null && message.getId() < 0 || bottomOverlayChat != null && bottomOverlayChat.getVisibility() == View.VISIBLE || currentChat != null && (ChatObject.isNotInChat(currentChat) && !isThreadChat() || ChatObject.isChannel(currentChat) && !ChatObject.canPost(currentChat) && !currentChat.megagroup || !ChatObject.canSendMessages(currentChat))) {
        allowChatActions = false;
    }
    if (single || type < 2 || type == 20) {
        if (getParentActivity() == null) {
            return;
        }
        ArrayList<Integer> icons = new ArrayList<>();
        ArrayList<CharSequence> items = new ArrayList<>();
        final ArrayList<Integer> options = new ArrayList<>();
        CharSequence messageText = null;
        if (type >= 0 || type == -1 && single && (message.isSending() || message.isEditing()) && currentEncryptedChat == null) {
            selectedObject = message;
            selectedObjectGroup = groupedMessages;
            // used only in translations
            messageText = getMessageCaption(selectedObject, selectedObjectGroup);
            if (messageText == null && selectedObject.isPoll()) {
                try {
                    TLRPC.Poll poll = ((TLRPC.TL_messageMediaPoll) selectedObject.messageOwner.media).poll;
                    StringBuilder pollText = new StringBuilder();
                    pollText = new StringBuilder(poll.question).append("\n");
                    for (TLRPC.TL_pollAnswer answer : poll.answers) pollText.append("\n\uD83D\uDD18 ").append(answer.text);
                    messageText = pollText.toString();
                } catch (Exception e) {
                }
            }
            if (messageText == null)
                messageText = getMessageContent(selectedObject, 0, false);
            if (messageText != null) {
                if (isEmoji(messageText.toString()))
                    // message fully consists of emojis, do not translate
                    messageText = null;
            }
            if (type == -1) {
                if ((selectedObject.type == 0 || selectedObject.isAnimatedEmoji() || getMessageCaption(selectedObject, selectedObjectGroup) != null) && !noforwards) {
                    items.add(LocaleController.getString("Copy", R.string.Copy));
                    options.add(OPTION_COPY);
                    icons.add(R.drawable.msg_copy);
                }
                items.add(LocaleController.getString("CancelSending", R.string.CancelSending));
                options.add(OPTION_CANCEL_SENDING);
                icons.add(R.drawable.msg_delete);
            } else if (type == 0) {
                items.add(LocaleController.getString("Retry", R.string.Retry));
                options.add(OPTION_RETRY);
                icons.add(R.drawable.msg_retry);
                items.add(LocaleController.getString("Delete", R.string.Delete));
                options.add(OPTION_DELETE);
                icons.add(selectedObject.messageOwner.ttl_period != 0 ? R.drawable.msg_delete_auto : R.drawable.msg_delete);
            } else if (type == 1) {
                if (currentChat != null) {
                    if (allowChatActions) {
                        items.add(LocaleController.getString("Reply", R.string.Reply));
                        options.add(OPTION_REPLY);
                        icons.add(R.drawable.msg_reply);
                    }
                    if (!isThreadChat() && chatMode != MODE_SCHEDULED && message.hasReplies() && currentChat.megagroup && message.canViewThread()) {
                        items.add(LocaleController.formatPluralString("ViewReplies", message.getRepliesCount()));
                        options.add(OPTION_VIEW_REPLIES_OR_THREAD);
                        icons.add(R.drawable.msg_viewreplies);
                    }
                    if (allowUnpin) {
                        items.add(LocaleController.getString("UnpinMessage", R.string.UnpinMessage));
                        options.add(OPTION_UNPIN);
                        icons.add(R.drawable.msg_unpin);
                    } else if (allowPin) {
                        items.add(LocaleController.getString("PinMessage", R.string.PinMessage));
                        options.add(OPTION_PIN);
                        icons.add(R.drawable.msg_pin);
                    }
                    if (selectedObject != null && selectedObject.contentType == 0 && (messageText != null && messageText.length() > 0 && !selectedObject.isAnimatedEmoji() && !selectedObject.isDice()) && MessagesController.getGlobalMainSettings().getBoolean("translate_button", false)) {
                        items.add(LocaleController.getString("TranslateMessage", R.string.TranslateMessage));
                        options.add(29);
                        icons.add(R.drawable.msg_translate);
                    }
                    if (message.canEditMessage(currentChat)) {
                        items.add(LocaleController.getString("Edit", R.string.Edit));
                        options.add(OPTION_EDIT);
                        icons.add(R.drawable.msg_edit);
                    }
                    if (selectedObject.contentType == 0 && !selectedObject.isMediaEmptyWebpage() && selectedObject.getId() > 0 && !selectedObject.isOut() && (currentChat != null || currentUser != null && currentUser.bot)) {
                        items.add(LocaleController.getString("ReportChat", R.string.ReportChat));
                        options.add(OPTION_REPORT_CHAT);
                        icons.add(R.drawable.msg_report);
                    }
                } else {
                    if (selectedObject.getId() > 0 && allowChatActions) {
                        items.add(LocaleController.getString("Reply", R.string.Reply));
                        options.add(OPTION_REPLY);
                        icons.add(R.drawable.msg_reply);
                    }
                }
                if (message.canDeleteMessage(chatMode == MODE_SCHEDULED, currentChat) && (threadMessageObjects == null || !threadMessageObjects.contains(message))) {
                    items.add(LocaleController.getString("Delete", R.string.Delete));
                    options.add(OPTION_DELETE);
                    icons.add(selectedObject.messageOwner.ttl_period != 0 ? R.drawable.msg_delete_auto : R.drawable.msg_delete);
                }
            } else if (type == 20) {
                items.add(LocaleController.getString("Retry", R.string.Retry));
                options.add(OPTION_RETRY);
                icons.add(R.drawable.msg_retry);
                if (!noforwards) {
                    items.add(LocaleController.getString("Copy", R.string.Copy));
                    options.add(OPTION_COPY);
                    icons.add(R.drawable.msg_copy);
                }
                items.add(LocaleController.getString("Delete", R.string.Delete));
                options.add(OPTION_DELETE);
                icons.add(selectedObject.messageOwner.ttl_period != 0 ? R.drawable.msg_delete_auto : R.drawable.msg_delete);
            } else {
                if (currentEncryptedChat == null) {
                    if (chatMode == MODE_SCHEDULED) {
                        items.add(LocaleController.getString("MessageScheduleSend", R.string.MessageScheduleSend));
                        options.add(OPTION_SEND_NOW);
                        icons.add(R.drawable.outline_send);
                    }
                    if (selectedObject.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall) {
                        TLRPC.TL_messageActionPhoneCall call = (TLRPC.TL_messageActionPhoneCall) message.messageOwner.action;
                        items.add((call.reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed || call.reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy) && !message.isOutOwner() ? LocaleController.getString("CallBack", R.string.CallBack) : LocaleController.getString("CallAgain", R.string.CallAgain));
                        options.add(OPTION_CALL_AGAIN);
                        icons.add(R.drawable.msg_callback);
                        if (VoIPHelper.canRateCall(call)) {
                            items.add(LocaleController.getString("CallMessageReportProblem", R.string.CallMessageReportProblem));
                            options.add(OPTION_RATE_CALL);
                            icons.add(R.drawable.msg_fave);
                        }
                    }
                    if (allowChatActions) {
                        items.add(LocaleController.getString("Reply", R.string.Reply));
                        options.add(8);
                        icons.add(R.drawable.msg_reply);
                    }
                    if ((selectedObject.type == 0 || selectedObject.isDice() || selectedObject.isAnimatedEmoji() || getMessageCaption(selectedObject, selectedObjectGroup) != null) && !noforwards) {
                        items.add(LocaleController.getString("Copy", R.string.Copy));
                        options.add(3);
                        icons.add(R.drawable.msg_copy);
                    }
                    if (!isThreadChat() && chatMode != MODE_SCHEDULED && currentChat != null && (currentChat.has_link || message.hasReplies()) && currentChat.megagroup && message.canViewThread()) {
                        if (message.hasReplies()) {
                            items.add(LocaleController.formatPluralString("ViewReplies", message.getRepliesCount()));
                        } else {
                            items.add(LocaleController.getString("ViewThread", R.string.ViewThread));
                        }
                        options.add(27);
                        icons.add(R.drawable.msg_viewreplies);
                    }
                    if (!selectedObject.isSponsored() && chatMode != MODE_SCHEDULED && ChatObject.isChannel(currentChat) && selectedObject.getDialogId() != mergeDialogId) {
                        items.add(LocaleController.getString("CopyLink", R.string.CopyLink));
                        options.add(22);
                        icons.add(R.drawable.msg_link);
                    }
                    if (type == 2) {
                        if (chatMode != MODE_SCHEDULED) {
                            if (selectedObject.type == MessageObject.TYPE_POLL && !message.isPollClosed()) {
                                if (message.canUnvote()) {
                                    items.add(LocaleController.getString("Unvote", R.string.Unvote));
                                    options.add(25);
                                    icons.add(R.drawable.msg_unvote);
                                }
                                if (!message.isForwarded() && (message.isOut() && (!ChatObject.isChannel(currentChat) || currentChat.megagroup) || ChatObject.isChannel(currentChat) && !currentChat.megagroup && (currentChat.creator || currentChat.admin_rights != null && currentChat.admin_rights.edit_messages))) {
                                    if (message.isQuiz()) {
                                        items.add(LocaleController.getString("StopQuiz", R.string.StopQuiz));
                                    } else {
                                        items.add(LocaleController.getString("StopPoll", R.string.StopPoll));
                                    }
                                    options.add(26);
                                    icons.add(R.drawable.msg_pollstop);
                                }
                            } else if (selectedObject.isMusic() && !noforwards) {
                                items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic));
                                options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                                icons.add(R.drawable.msg_download);
                            } else if (selectedObject.isDocument() && !noforwards) {
                                items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                                options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                                icons.add(R.drawable.msg_download);
                            }
                        }
                    } else if (type == 3 && !noforwards) {
                        if (selectedObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && MessageObject.isNewGifDocument(selectedObject.messageOwner.media.webpage.document)) {
                            items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs));
                            options.add(11);
                            icons.add(R.drawable.msg_gif);
                        }
                    } else if (type == 4) {
                        if (!noforwards) {
                            if (selectedObject.isVideo()) {
                                if (!selectedObject.needDrawBluredPreview()) {
                                    items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
                                    options.add(4);
                                    icons.add(R.drawable.msg_gallery);
                                    items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                                    options.add(6);
                                    icons.add(R.drawable.msg_shareout);
                                }
                            } else if (selectedObject.isMusic()) {
                                items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic));
                                options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                                icons.add(R.drawable.msg_download);
                                items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                                options.add(6);
                                icons.add(R.drawable.msg_shareout);
                            } else if (selectedObject.getDocument() != null) {
                                if (MessageObject.isNewGifDocument(selectedObject.getDocument())) {
                                    items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs));
                                    options.add(11);
                                    icons.add(R.drawable.msg_gif);
                                }
                                items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                                options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                                icons.add(R.drawable.msg_download);
                                items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                                options.add(6);
                                icons.add(R.drawable.msg_shareout);
                            } else {
                                if (!selectedObject.needDrawBluredPreview()) {
                                    items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
                                    options.add(4);
                                    icons.add(R.drawable.msg_gallery);
                                }
                            }
                        }
                    } else if (type == 5) {
                        items.add(LocaleController.getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile));
                        options.add(5);
                        icons.add(R.drawable.msg_language);
                        if (!noforwards) {
                            items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                            options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                            icons.add(R.drawable.msg_download);
                            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                            options.add(6);
                            icons.add(R.drawable.msg_shareout);
                        }
                    } else if (type == 10) {
                        items.add(LocaleController.getString("ApplyThemeFile", R.string.ApplyThemeFile));
                        options.add(5);
                        icons.add(R.drawable.msg_theme);
                        if (!noforwards) {
                            items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                            options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                            icons.add(R.drawable.msg_download);
                            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                            options.add(6);
                            icons.add(R.drawable.msg_shareout);
                        }
                    } else if (type == 6 && !noforwards) {
                        items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
                        options.add(7);
                        icons.add(R.drawable.msg_gallery);
                        items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                        options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                        icons.add(R.drawable.msg_download);
                        items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                        options.add(6);
                        icons.add(R.drawable.msg_shareout);
                    } else if (type == 7) {
                        if (selectedObject.isMask()) {
                            items.add(LocaleController.getString("AddToMasks", R.string.AddToMasks));
                            options.add(9);
                            icons.add(R.drawable.msg_sticker);
                        } else {
                            items.add(LocaleController.getString("AddToStickers", R.string.AddToStickers));
                            options.add(9);
                            icons.add(R.drawable.msg_sticker);
                            TLRPC.Document document = selectedObject.getDocument();
                            if (!getMediaDataController().isStickerInFavorites(document)) {
                                if (getMediaDataController().canAddStickerToFavorites() && MessageObject.isStickerHasSet(document)) {
                                    items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites));
                                    options.add(20);
                                    icons.add(R.drawable.msg_fave);
                                }
                            } else {
                                items.add(LocaleController.getString("DeleteFromFavorites", R.string.DeleteFromFavorites));
                                options.add(21);
                                icons.add(R.drawable.msg_unfave);
                            }
                        }
                    } else if (type == 8) {
                        long uid = selectedObject.messageOwner.media.user_id;
                        TLRPC.User user = null;
                        if (uid != 0) {
                            user = MessagesController.getInstance(currentAccount).getUser(uid);
                        }
                        if (user != null && user.id != getUserConfig().getClientUserId() && getContactsController().contactsDict.get(user.id) == null) {
                            items.add(LocaleController.getString("AddContactTitle", R.string.AddContactTitle));
                            options.add(15);
                            icons.add(R.drawable.msg_addcontact);
                        }
                        if (!TextUtils.isEmpty(selectedObject.messageOwner.media.phone_number)) {
                            if (!noforwards) {
                                items.add(LocaleController.getString("Copy", R.string.Copy));
                                options.add(16);
                                icons.add(R.drawable.msg_copy);
                            }
                            items.add(LocaleController.getString("Call", R.string.Call));
                            options.add(17);
                            icons.add(R.drawable.msg_callback);
                        }
                    } else if (type == 9) {
                        TLRPC.Document document = selectedObject.getDocument();
                        if (!getMediaDataController().isStickerInFavorites(document)) {
                            if (MessageObject.isStickerHasSet(document)) {
                                items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites));
                                options.add(20);
                                icons.add(R.drawable.msg_fave);
                            }
                        } else {
                            items.add(LocaleController.getString("DeleteFromFavorites", R.string.DeleteFromFavorites));
                            options.add(21);
                            icons.add(R.drawable.msg_unfave);
                        }
                    }
                    if (!selectedObject.isSponsored() && chatMode != MODE_SCHEDULED && !selectedObject.needDrawBluredPreview() && !selectedObject.isLiveLocation() && selectedObject.type != 16 && !noforwards) {
                        items.add(LocaleController.getString("Forward", R.string.Forward));
                        options.add(2);
                        icons.add(R.drawable.msg_forward);
                    }
                    if (allowUnpin) {
                        items.add(LocaleController.getString("UnpinMessage", R.string.UnpinMessage));
                        options.add(14);
                        icons.add(R.drawable.msg_unpin);
                    } else if (allowPin) {
                        items.add(LocaleController.getString("PinMessage", R.string.PinMessage));
                        options.add(13);
                        icons.add(R.drawable.msg_pin);
                    }
                    if (selectedObject != null && selectedObject.contentType == 0 && (messageText != null && messageText.length() > 0 && !selectedObject.isAnimatedEmoji() && !selectedObject.isDice()) && MessagesController.getGlobalMainSettings().getBoolean("translate_button", false)) {
                        items.add(LocaleController.getString("TranslateMessage", R.string.TranslateMessage));
                        options.add(29);
                        icons.add(R.drawable.msg_translate);
                    }
                    if (allowEdit) {
                        items.add(LocaleController.getString("Edit", R.string.Edit));
                        options.add(12);
                        icons.add(R.drawable.msg_edit);
                    }
                    if (chatMode == MODE_SCHEDULED && selectedObject.canEditMessageScheduleTime(currentChat)) {
                        items.add(LocaleController.getString("MessageScheduleEditTime", R.string.MessageScheduleEditTime));
                        options.add(102);
                        icons.add(R.drawable.msg_schedule);
                    }
                    if (chatMode != MODE_SCHEDULED && selectedObject.contentType == 0 && selectedObject.getId() > 0 && !selectedObject.isOut() && (currentChat != null || currentUser != null && currentUser.bot)) {
                        if (UserObject.isReplyUser(currentUser)) {
                            items.add(LocaleController.getString("BlockContact", R.string.BlockContact));
                            options.add(23);
                            icons.add(R.drawable.msg_block2);
                        } else {
                            items.add(LocaleController.getString("ReportChat", R.string.ReportChat));
                            options.add(23);
                            icons.add(R.drawable.msg_report);
                        }
                    }
                    if (message.canDeleteMessage(chatMode == MODE_SCHEDULED, currentChat) && (threadMessageObjects == null || !threadMessageObjects.contains(message))) {
                        items.add(LocaleController.getString("Delete", R.string.Delete));
                        options.add(1);
                        icons.add(selectedObject.messageOwner.ttl_period != 0 ? R.drawable.msg_delete_auto : R.drawable.msg_delete);
                    }
                } else {
                    if (allowChatActions) {
                        items.add(LocaleController.getString("Reply", R.string.Reply));
                        options.add(8);
                        icons.add(R.drawable.msg_reply);
                    }
                    if ((selectedObject.type == 0 || selectedObject.isAnimatedEmoji() || getMessageCaption(selectedObject, selectedObjectGroup) != null) && !noforwards) {
                        items.add(LocaleController.getString("Copy", R.string.Copy));
                        options.add(3);
                        icons.add(R.drawable.msg_copy);
                    }
                    if (!isThreadChat() && chatMode != MODE_SCHEDULED && currentChat != null && (currentChat.has_link || message.hasReplies()) && currentChat.megagroup && message.canViewThread()) {
                        if (message.hasReplies()) {
                            items.add(LocaleController.formatPluralString("ViewReplies", message.getRepliesCount()));
                        } else {
                            items.add(LocaleController.getString("ViewThread", R.string.ViewThread));
                        }
                        options.add(27);
                        icons.add(R.drawable.msg_viewreplies);
                    }
                    if (type == 4 && !noforwards) {
                        if (selectedObject.isVideo()) {
                            items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
                            options.add(4);
                            icons.add(R.drawable.msg_gallery);
                            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                            options.add(6);
                            icons.add(R.drawable.msg_shareout);
                        } else if (selectedObject.isMusic()) {
                            items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic));
                            options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                            icons.add(R.drawable.msg_download);
                            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                            options.add(6);
                            icons.add(R.drawable.msg_shareout);
                        } else if (!selectedObject.isVideo() && selectedObject.getDocument() != null) {
                            items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads));
                            options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC);
                            icons.add(R.drawable.msg_download);
                            items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
                            options.add(6);
                            icons.add(R.drawable.msg_shareout);
                        } else {
                            items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
                            options.add(4);
                            icons.add(R.drawable.msg_gallery);
                        }
                    } else if (type == 5) {
                        items.add(LocaleController.getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile));
                        options.add(5);
                        icons.add(R.drawable.msg_language);
                    } else if (type == 10) {
                        items.add(LocaleController.getString("ApplyThemeFile", R.string.ApplyThemeFile));
                        options.add(5);
                        icons.add(R.drawable.msg_theme);
                    } else if (type == 7) {
                        items.add(LocaleController.getString("AddToStickers", R.string.AddToStickers));
                        options.add(9);
                        icons.add(R.drawable.msg_sticker);
                    } else if (type == 8) {
                        long uid = selectedObject.messageOwner.media.user_id;
                        TLRPC.User user = null;
                        if (uid != 0) {
                            user = MessagesController.getInstance(currentAccount).getUser(uid);
                        }
                        if (user != null && user.id != getUserConfig().getClientUserId() && getContactsController().contactsDict.get(user.id) == null) {
                            items.add(LocaleController.getString("AddContactTitle", R.string.AddContactTitle));
                            options.add(15);
                            icons.add(R.drawable.msg_addcontact);
                        }
                        if (!TextUtils.isEmpty(selectedObject.messageOwner.media.phone_number)) {
                            if (!noforwards) {
                                items.add(LocaleController.getString("Copy", R.string.Copy));
                                options.add(16);
                                icons.add(R.drawable.msg_copy);
                            }
                            items.add(LocaleController.getString("Call", R.string.Call));
                            options.add(17);
                            icons.add(R.drawable.msg_callback);
                        }
                    }
                    items.add(LocaleController.getString("Delete", R.string.Delete));
                    options.add(1);
                    icons.add(selectedObject.messageOwner.ttl_period != 0 ? R.drawable.msg_delete_auto : R.drawable.msg_delete);
                }
            }
        }
        if (options.isEmpty()) {
            return;
        }
        if (scrimPopupWindow != null) {
            closeMenu();
            menuDeleteItem = null;
            scrimPopupWindowItems = null;
            return;
        }
        final AtomicBoolean waitForLangDetection = new AtomicBoolean(false);
        final AtomicReference<Runnable> onLangDetectionDone = new AtomicReference(null);
        Rect rect = new Rect();
        List<TLRPC.TL_availableReaction> availableReacts = getMediaDataController().getEnabledReactionsList();
        boolean isReactionsViewAvailable = !isSecretChat() && !isInScheduleMode() && currentUser == null && message.hasReactions() && (!ChatObject.isChannel(currentChat) || currentChat.megagroup) && !availableReacts.isEmpty() && message.messageOwner.reactions.can_see_list;
        boolean isReactionsAvailable;
        if (message.isForwardedChannelPost()) {
            TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(-message.getFromChatId());
            if (chatInfo == null) {
                isReactionsAvailable = true;
            } else {
                isReactionsAvailable = !isSecretChat() && !isInScheduleMode() && message.isReactionsAvailable() && (chatInfo != null && !chatInfo.available_reactions.isEmpty()) && !availableReacts.isEmpty();
            }
        } else {
            isReactionsAvailable = !isSecretChat() && !isInScheduleMode() && message.isReactionsAvailable() && (chatInfo != null && !chatInfo.available_reactions.isEmpty() || (chatInfo == null && !ChatObject.isChannel(currentChat)) || currentUser != null) && !availableReacts.isEmpty();
        }
        boolean showMessageSeen = !isReactionsViewAvailable && !isInScheduleMode() && currentChat != null && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < getMessagesController().chatReadMarkExpirePeriod) && (ChatObject.isMegagroup(currentChat) || !ChatObject.isChannel(currentChat)) && chatInfo != null && chatInfo.participants_count < getMessagesController().chatReadMarkSizeThreshold && !(message.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByRequest) && (v instanceof ChatMessageCell);
        int flags = 0;
        if (isReactionsViewAvailable || showMessageSeen) {
            flags |= ActionBarPopupWindow.ActionBarPopupWindowLayout.FLAG_USE_SWIPEBACK;
        }
        ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity(), R.drawable.popup_fixed_alert, themeDelegate, flags);
        popupLayout.setMinimumWidth(AndroidUtilities.dp(200));
        Rect backgroundPaddings = new Rect();
        Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate();
        shadowDrawable.getPadding(backgroundPaddings);
        popupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground));
        if (isReactionsViewAvailable) {
            ReactedHeaderView reactedView = new ReactedHeaderView(contentView.getContext(), currentAccount, message, dialog_id);
            int count = 0;
            if (message.messageOwner.reactions != null) {
                for (TLRPC.TL_reactionCount r : message.messageOwner.reactions.results) {
                    count += r.count;
                }
            }
            boolean hasHeader = count > 10;
            LinearLayout linearLayout = new LinearLayout(contentView.getContext()) {

                @Override
                protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                    int size = MeasureSpec.getSize(widthMeasureSpec);
                    if (size < AndroidUtilities.dp(240)) {
                        size = AndroidUtilities.dp(240);
                    }
                    super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), heightMeasureSpec);
                }
            };
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setLayoutParams(new FrameLayout.LayoutParams(AndroidUtilities.dp(200), AndroidUtilities.dp(6 * 48 + (hasHeader ? 44 * 2 + 8 : 44)) + (!hasHeader ? 1 : 0)));
            ActionBarMenuSubItem backCell = new ActionBarMenuSubItem(getParentActivity(), true, false, themeDelegate);
            backCell.setItemHeight(44);
            backCell.setTextAndIcon(LocaleController.getString("Back", R.string.Back), R.drawable.msg_arrow_back);
            backCell.getTextView().setPadding(LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), 0, LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0);
            backCell.setOnClickListener(v1 -> popupLayout.getSwipeBack().closeForeground());
            linearLayout.addView(backCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            int[] foregroundIndex = new int[1];
            if (hasHeader) {
                List<TLRPC.TL_reactionCount> counters = message.messageOwner.reactions.results;
                LinearLayout tabsView = new LinearLayout(contentView.getContext());
                tabsView.setOrientation(LinearLayout.HORIZONTAL);
                ViewPager pager = new ViewPager(contentView.getContext());
                HorizontalScrollView tabsScrollView = new HorizontalScrollView(contentView.getContext());
                AtomicBoolean suppressTabsScroll = new AtomicBoolean();
                int size = counters.size() + 1;
                for (int i = 0; i < size; i++) {
                    ReactionTabHolderView hv = new ReactionTabHolderView(contentView.getContext());
                    if (i == 0) {
                        hv.setCounter(count);
                    } else
                        hv.setCounter(currentAccount, counters.get(i - 1));
                    int finalI = i;
                    hv.setOnClickListener(v1 -> {
                        int from = pager.getCurrentItem();
                        if (finalI == from)
                            return;
                        ReactionTabHolderView fv = (ReactionTabHolderView) tabsView.getChildAt(from);
                        suppressTabsScroll.set(true);
                        pager.setCurrentItem(finalI, true);
                        float fSX = tabsScrollView.getScrollX(), tSX = hv.getX() - (tabsScrollView.getWidth() - hv.getWidth()) / 2f;
                        ValueAnimator a = ValueAnimator.ofFloat(0, 1).setDuration(150);
                        a.setInterpolator(CubicBezierInterpolator.DEFAULT);
                        a.addUpdateListener(animation -> {
                            float f = (float) animation.getAnimatedValue();
                            tabsScrollView.setScrollX((int) (fSX + (tSX - fSX) * f));
                            fv.setOutlineProgress(1f - f);
                            hv.setOutlineProgress(f);
                        });
                        a.start();
                    });
                    tabsView.addView(hv, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL, i == 0 ? 6 : 0, 6, 6, 6));
                }
                tabsScrollView.setHorizontalScrollBarEnabled(false);
                tabsScrollView.addView(tabsView);
                linearLayout.addView(tabsScrollView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 44));
                View divider = new FrameLayout(contentView.getContext());
                divider.setBackgroundColor(Theme.getColor(Theme.key_graySection));
                linearLayout.addView(divider, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) Theme.dividerPaint.getStrokeWidth()));
                int head = AndroidUtilities.dp(44 * 2) + 1;
                SparseArray<ReactedUsersListView> cachedViews = new SparseArray<>();
                SparseIntArray cachedHeights = new SparseIntArray();
                for (int i = 0; i < counters.size() + 1; i++) cachedHeights.put(i, head + AndroidUtilities.dp(ReactedUsersListView.ITEM_HEIGHT_DP * ReactedUsersListView.VISIBLE_ITEMS));
                pager.setAdapter(new PagerAdapter() {

                    @Override
                    public int getCount() {
                        return counters.size() + 1;
                    }

                    @Override
                    public boolean isViewFromObject(View view, Object object) {
                        return view == object;
                    }

                    @Override
                    public Object instantiateItem(ViewGroup container, int position) {
                        View cached = cachedViews.get(position);
                        if (cached != null) {
                            container.addView(cached);
                            return cached;
                        }
                        ReactedUsersListView v = new ReactedUsersListView(container.getContext(), themeDelegate, currentAccount, message, position == 0 ? null : counters.get(position - 1), true).setSeenUsers(reactedView.getSeenUsers()).setOnProfileSelectedListener((view, userId) -> {
                            Bundle args = new Bundle();
                            args.putLong("user_id", userId);
                            ProfileActivity fragment = new ProfileActivity(args);
                            presentFragment(fragment);
                            closeMenu();
                        }).setOnHeightChangedListener((view, newHeight) -> {
                            cachedHeights.put(position, head + newHeight);
                            if (pager.getCurrentItem() == position)
                                popupLayout.getSwipeBack().setNewForegroundHeight(foregroundIndex[0], head + newHeight);
                        });
                        if (position == 0)
                            reactedView.setSeenCallback(v::setSeenUsers);
                        container.addView(v);
                        cachedViews.put(position, v);
                        return v;
                    }

                    @Override
                    public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView((View) object);
                    }
                });
                pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        if (!suppressTabsScroll.get()) {
                            float fX = -1, tX = -1;
                            for (int i = 0; i < tabsView.getChildCount(); i++) {
                                ReactionTabHolderView ch = (ReactionTabHolderView) tabsView.getChildAt(i);
                                ch.setOutlineProgress(i == position ? 1f - positionOffset : i == (position + 1) % size ? positionOffset : 0);
                                if (i == position) {
                                    fX = ch.getX() - (tabsScrollView.getWidth() - ch.getWidth()) / 2f;
                                }
                                if (i == position + 1) {
                                    tX = ch.getX() - (tabsScrollView.getWidth() - ch.getWidth()) / 2f;
                                }
                            }
                            if (fX != -1 && tX != -1)
                                tabsScrollView.setScrollX((int) (fX + (tX - fX) * positionOffset));
                        }
                    }

                    @Override
                    public void onPageSelected(int position) {
                        int h = cachedHeights.get(position);
                        popupLayout.getSwipeBack().setNewForegroundHeight(foregroundIndex[0], h);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        if (state == ViewPager.SCROLL_STATE_IDLE) {
                            suppressTabsScroll.set(false);
                        }
                    }
                });
                linearLayout.addView(pager, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 0, 1f));
            } else {
                View gap = new FrameLayout(contentView.getContext());
                gap.setBackgroundColor(Theme.getColor(Theme.key_graySection));
                linearLayout.addView(gap, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8));
                ReactedUsersListView lv = new ReactedUsersListView(contentView.getContext(), themeDelegate, currentAccount, message, null, true).setSeenUsers(reactedView.getSeenUsers()).setOnProfileSelectedListener((view, userId) -> {
                    Bundle args = new Bundle();
                    args.putLong("user_id", userId);
                    ProfileActivity fragment = new ProfileActivity(args);
                    presentFragment(fragment);
                    closeMenu();
                }).setOnHeightChangedListener((view, newHeight) -> popupLayout.getSwipeBack().setNewForegroundHeight(foregroundIndex[0], AndroidUtilities.dp(44 + 8) + newHeight));
                reactedView.setSeenCallback(lv::setSeenUsers);
                linearLayout.addView(lv, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 0, 1f));
            }
            foregroundIndex[0] = popupLayout.addViewToSwipeBack(linearLayout);
            reactedView.setOnClickListener(v1 -> {
                popupLayout.getSwipeBack().openForeground(foregroundIndex[0]);
            });
            popupLayout.addView(reactedView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
            View gap = new FrameLayout(contentView.getContext());
            gap.setBackgroundColor(Theme.getColor(Theme.key_graySection));
            popupLayout.addView(gap, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8));
        }
        MessageSeenView messageSeenView = null;
        if (showMessageSeen) {
            messageSeenView = new MessageSeenView(contentView.getContext(), currentAccount, message, currentChat);
            FrameLayout messageSeenLayout = new FrameLayout(contentView.getContext());
            messageSeenLayout.addView(messageSeenView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            MessageSeenView finalMessageSeenView = messageSeenView;
            ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true, themeDelegate);
            cell.setItemHeight(44);
            cell.setTextAndIcon(LocaleController.getString("Back", R.string.Back), R.drawable.msg_arrow_back);
            cell.getTextView().setPadding(LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), 0, LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0);
            FrameLayout backContainer = new FrameLayout(contentView.getContext());
            LinearLayout linearLayout = new LinearLayout(contentView.getContext());
            linearLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground));
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            RecyclerListView listView2 = finalMessageSeenView.createListView();
            backContainer.addView(cell);
            linearLayout.addView(backContainer);
            backContainer.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    popupLayout.getSwipeBack().closeForeground();
                }
            });
            int[] foregroundIndex = new int[1];
            messageSeenView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    if (scrimPopupWindow == null || finalMessageSeenView.users.isEmpty()) {
                        return;
                    }
                    if (finalMessageSeenView.users.size() == 1) {
                        TLRPC.User user = finalMessageSeenView.users.get(0);
                        if (user == null) {
                            return;
                        }
                        Bundle args = new Bundle();
                        args.putLong("user_id", user.id);
                        ProfileActivity fragment = new ProfileActivity(args);
                        presentFragment(fragment);
                        closeMenu();
                        return;
                    }
                    int totalHeight = contentView.getHeightWithKeyboard();
                    int availableHeight = totalHeight - scrimPopupY - AndroidUtilities.dp(46 + 16) - (isReactionsAvailable ? AndroidUtilities.dp(52) : 0);
                    if (SharedConfig.messageSeenHintCount > 0 && contentView.getKeyboardHeight() < AndroidUtilities.dp(20)) {
                        availableHeight -= AndroidUtilities.dp(52);
                        Bulletin bulletin = BulletinFactory.of(ChatActivity.this).createErrorBulletin(AndroidUtilities.replaceTags(LocaleController.getString("MessageSeenTooltipMessage", R.string.MessageSeenTooltipMessage)));
                        bulletin.tag = 1;
                        bulletin.setDuration(4000);
                        bulletin.show();
                        SharedConfig.updateMessageSeenHintCount(SharedConfig.messageSeenHintCount - 1);
                    } else if (contentView.getKeyboardHeight() > AndroidUtilities.dp(20)) {
                        availableHeight -= contentView.getKeyboardHeight() / 3f;
                    }
                    int listViewTotalHeight = AndroidUtilities.dp(8) + AndroidUtilities.dp(44) * listView2.getAdapter().getItemCount();
                    if (listViewTotalHeight > availableHeight) {
                        if (availableHeight > AndroidUtilities.dp(620)) {
                            listView2.getLayoutParams().height = AndroidUtilities.dp(620);
                        } else {
                            listView2.getLayoutParams().height = availableHeight;
                        }
                    } else {
                        listView2.getLayoutParams().height = listViewTotalHeight;
                    }
                    linearLayout.getLayoutParams().height = AndroidUtilities.dp(44) + listView2.getLayoutParams().height;
                    listView2.requestLayout();
                    linearLayout.requestLayout();
                    listView2.getAdapter().notifyDataSetChanged();
                    popupLayout.getSwipeBack().openForeground(foregroundIndex[0]);
                }
            });
            linearLayout.addView(listView2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 320));
            listView2.setOnItemClickListener((view1, position) -> {
                TLRPC.User user = finalMessageSeenView.users.get(position);
                if (user == null) {
                    return;
                }
                Bundle args = new Bundle();
                args.putLong("user_id", user.id);
                ProfileActivity fragment = new ProfileActivity(args);
                presentFragment(fragment);
            });
            foregroundIndex[0] = popupLayout.addViewToSwipeBack(linearLayout);
            popupLayout.addView(messageSeenLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 44));
            View gap = new FrameLayout(contentView.getContext());
            gap.setBackgroundColor(Theme.getColor(Theme.key_graySection));
            popupLayout.addView(gap, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8));
        }
        if (popupLayout.getSwipeBack() != null) {
            popupLayout.getSwipeBack().setOnClickListener(e -> closeMenu());
        }
        scrimPopupWindowItems = new ActionBarMenuSubItem[items.size() + (selectedObject.isSponsored() ? 1 : 0)];
        for (int a = 0, N = items.size(); a < N; a++) {
            if (a == 0 && selectedObject.isSponsored()) {
                ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true, themeDelegate);
                cell.setTextAndIcon(LocaleController.getString("SponsoredMessageInfo", R.string.SponsoredMessageInfo), R.drawable.menu_info);
                cell.setItemHeight(56);
                cell.setTag(R.id.width_tag, 240);
                cell.setMultiline();
                scrimPopupWindowItems[scrimPopupWindowItems.length - 1] = cell;
                popupLayout.addView(cell);
                cell.setOnClickListener(v1 -> {
                    if (contentView == null || getParentActivity() == null) {
                        return;
                    }
                    BottomSheet.Builder builder = new BottomSheet.Builder(contentView.getContext());
                    builder.setCustomView(new SponsoredMessageInfoView(getParentActivity(), themeDelegate));
                    builder.show();
                });
                View gap = new View(getParentActivity());
                gap.setMinimumWidth(AndroidUtilities.dp(196));
                gap.setTag(1000);
                gap.setTag(R.id.object_tag, 1);
                popupLayout.addView(gap);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) cell.getLayoutParams();
                if (LocaleController.isRTL) {
                    layoutParams.gravity = Gravity.RIGHT;
                }
                layoutParams.width = LayoutHelper.MATCH_PARENT;
                layoutParams.height = AndroidUtilities.dp(6);
                gap.setLayoutParams(layoutParams);
            }
            ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1, themeDelegate);
            cell.setMinimumWidth(AndroidUtilities.dp(200));
            cell.setTextAndIcon(items.get(a), icons.get(a));
            Integer option = options.get(a);
            if (option == 1 && selectedObject.messageOwner.ttl_period != 0) {
                menuDeleteItem = cell;
                updateDeleteItemRunnable.run();
                cell.setSubtextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText6));
            }
            scrimPopupWindowItems[a] = cell;
            popupLayout.addView(cell);
            final int i = a;
            cell.setOnClickListener(v1 -> {
                if (selectedObject == null || i >= options.size()) {
                    return;
                }
                processSelectedOption(options.get(i));
            });
            if (option == 29) {
                // "Translate" button
                String toLang = LocaleController.getInstance().getCurrentLocale().getLanguage();
                final CharSequence finalMessageText = messageText;
                TranslateAlert.OnLinkPress onLinkPress = (link) -> {
                    didPressMessageUrl(link, false, selectedObject, v instanceof ChatMessageCell ? (ChatMessageCell) v : null);
                };
                TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(dialog_id);
                int messageId = selectedObject.messageOwner.id;
                /*if (LanguageDetector.hasSupport()) {
                        final String[] fromLang = { null };
                        cell.setVisibility(View.GONE);
                        waitForLangDetection.set(true);
                        LanguageDetector.detectLanguage(
                            finalMessageText.toString(),
                            (String lang) -> {
                                fromLang[0] = lang;
                                if (fromLang[0] != null && (!fromLang[0].equals(toLang) || fromLang[0].equals("und")) &&
                                        !RestrictedLanguagesSelectActivity.getRestrictedLanguages().contains(fromLang[0])) {
                                    cell.setVisibility(View.VISIBLE);
                                }
                                waitForLangDetection.set(false);
                                if (onLangDetectionDone.get() != null) {
                                    onLangDetectionDone.get().run();
                                    onLangDetectionDone.set(null);
                                }
                            },
                            (Exception e) -> {
                                FileLog.e("mlkit: failed to detect language in message");
                                e.printStackTrace();
                                waitForLangDetection.set(false);
                                if (onLangDetectionDone.get() != null) {
                                    onLangDetectionDone.get().run();
                                    onLangDetectionDone.set(null);
                                }
                            }
                        );
                        cell.setOnClickListener(e -> {
                            if (selectedObject == null || i >= options.size() || getParentActivity() == null) {
                                return;
                            }
                            TranslateAlert alert = TranslateAlert.showAlert(getParentActivity(), this, currentAccount, inputPeer, messageId, fromLang[0], toLang, finalMessageText, noforwards, onLinkPress, () -> dimBehindView(false));
                            alert.showDim(false);
                            closeMenu(false);
                        });
                        cell.postDelayed(() -> {
                            if (onLangDetectionDone.get() != null) {
                                onLangDetectionDone.getAndSet(null).run();
                            }
                        }, 250);
                    } else {*/
                cell.setOnClickListener(e -> {
                    if (selectedObject == null || i >= options.size() || getParentActivity() == null) {
                        return;
                    }
                    TranslateAlert alert = TranslateAlert.showAlert(getParentActivity(), this, currentAccount, inputPeer, messageId, "und", toLang, finalMessageText, noforwards, onLinkPress, () -> dimBehindView(false));
                    alert.showDim(false);
                    closeMenu(false);
                });
            // }
            }
        }
        ChatScrimPopupContainerLayout scrimPopupContainerLayout = new ChatScrimPopupContainerLayout(contentView.getContext()) {

            @Override
            public boolean dispatchKeyEvent(KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    closeMenu();
                }
                return super.dispatchKeyEvent(event);
            }

            @Override
            public boolean dispatchTouchEvent(MotionEvent ev) {
                boolean b = super.dispatchTouchEvent(ev);
                if (ev.getAction() == MotionEvent.ACTION_DOWN && !b) {
                    closeMenu();
                }
                return b;
            }
        };
        scrimPopupContainerLayout.setOnTouchListener(new View.OnTouchListener() {

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

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    if (scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                        View contentView = scrimPopupWindow.getContentView();
                        contentView.getLocationInWindow(pos);
                        rect.set(pos[0], pos[1], pos[0] + contentView.getMeasuredWidth(), pos[1] + contentView.getMeasuredHeight());
                        if (!rect.contains((int) event.getX(), (int) event.getY())) {
                            closeMenu();
                        }
                    }
                } else if (event.getActionMasked() == MotionEvent.ACTION_OUTSIDE) {
                    closeMenu();
                }
                return false;
            }
        });
        ReactionsContainerLayout reactionsLayout = new ReactionsContainerLayout(contentView.getContext(), currentAccount, getResourceProvider());
        if (isReactionsAvailable) {
            int pad = 22;
            int sPad = 24;
            reactionsLayout.setPadding(AndroidUtilities.dp(4) + (LocaleController.isRTL ? 0 : sPad), AndroidUtilities.dp(4), AndroidUtilities.dp(4) + (LocaleController.isRTL ? sPad : 0), AndroidUtilities.dp(pad));
            reactionsLayout.setDelegate((rView, reaction, longress) -> {
                selectReaction(primaryMessage, reactionsLayout, 0, 0, reaction, false, longress);
            });
            LinearLayout.LayoutParams params = LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 52 + pad, Gravity.RIGHT, 0, 50, 0, -20);
            scrimPopupContainerLayout.addView(reactionsLayout, params);
            scrimPopupContainerLayout.reactionsLayout = reactionsLayout;
            scrimPopupContainerLayout.setClipChildren(false);
            reactionsLayout.setMessage(message, chatInfo);
            reactionsLayout.setTransitionProgress(0);
            if (popupLayout.getSwipeBack() != null) {
                popupLayout.getSwipeBack().setOnSwipeBackProgressListener((layout, toProgress, progress) -> {
                    if (toProgress == 0) {
                        reactionsLayout.startEnterAnimation();
                    } else if (toProgress == 1)
                        reactionsLayout.setAlpha(1f - progress);
                });
            }
        }
        boolean showNoForwards = noforwards && message.messageOwner.action == null && message.isSent() && !message.isEditing() && chatMode != MODE_SCHEDULED;
        scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinearRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, isReactionsAvailable ? 16 : 0, 0, isReactionsAvailable ? 36 : 0, 0));
        scrimPopupContainerLayout.popupWindowLayout = popupLayout;
        if (showNoForwards) {
            popupLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            boolean isChannel = ChatObject.isChannel(currentChat) && !currentChat.megagroup;
            TextView tv = new TextView(contentView.getContext());
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            tv.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem));
            if (getMessagesController().isChatNoForwards(currentChat)) {
                tv.setText(isChannel ? LocaleController.getString("ForwardsRestrictedInfoChannel", R.string.ForwardsRestrictedInfoChannel) : LocaleController.getString("ForwardsRestrictedInfoGroup", R.string.ForwardsRestrictedInfoGroup));
            } else {
                tv.setText(LocaleController.getString("ForwardsRestrictedInfoBot", R.string.ForwardsRestrictedInfoBot));
            }
            tv.setMaxWidth(popupLayout.getMeasuredWidth() - AndroidUtilities.dp(38));
            Drawable shadowDrawable2 = ContextCompat.getDrawable(contentView.getContext(), R.drawable.popup_fixed_alert).mutate();
            shadowDrawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), PorterDuff.Mode.MULTIPLY));
            FrameLayout fl = new FrameLayout(contentView.getContext());
            fl.setBackground(shadowDrawable2);
            fl.addView(tv, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 11, 11, 11, 11));
            scrimPopupContainerLayout.addView(fl, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, isReactionsAvailable ? 16 : 0, -8, isReactionsAvailable ? 36 : 0, 0));
        }
        scrimPopupWindow = new ActionBarPopupWindow(scrimPopupContainerLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) {

            @Override
            public void dismiss() {
                super.dismiss();
                if (scrimPopupWindow != this) {
                    return;
                }
                scrimPopupWindow = null;
                menuDeleteItem = null;
                scrimPopupWindowItems = null;
                chatLayoutManager.setCanScrollVertically(true);
                if (scrimPopupWindowHideDimOnDismiss) {
                    dimBehindView(false);
                } else {
                    scrimPopupWindowHideDimOnDismiss = true;
                }
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setAllowDrawCursor(true);
                }
            }
        };
        scrimPopupWindow.setPauseNotifications(true);
        scrimPopupWindow.setDismissAnimationDuration(220);
        scrimPopupWindow.setOutsideTouchable(true);
        scrimPopupWindow.setClippingEnabled(true);
        scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation);
        scrimPopupWindow.setFocusable(true);
        scrimPopupContainerLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
        scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
        scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
        scrimPopupWindow.getContentView().setFocusableInTouchMode(true);
        popupLayout.setFitItems(true);
        int popupX = v.getLeft() + (int) x - scrimPopupContainerLayout.getMeasuredWidth() + backgroundPaddings.left - AndroidUtilities.dp(28);
        if (popupX < AndroidUtilities.dp(6)) {
            popupX = AndroidUtilities.dp(6);
        } else if (popupX > chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth()) {
            popupX = chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth();
        }
        if (AndroidUtilities.isTablet()) {
            int[] location = new int[2];
            fragmentView.getLocationInWindow(location);
            popupX += location[0];
        }
        int totalHeight = contentView.getHeight();
        int height = scrimPopupContainerLayout.getMeasuredHeight() + AndroidUtilities.dp(48);
        int keyboardHeight = contentView.measureKeyboardHeight();
        if (keyboardHeight > AndroidUtilities.dp(20)) {
            totalHeight += keyboardHeight;
        }
        int popupY;
        if (height < totalHeight) {
            popupY = (int) (chatListView.getY() + v.getTop() + y);
            if (height - backgroundPaddings.top - backgroundPaddings.bottom > AndroidUtilities.dp(240)) {
                popupY += AndroidUtilities.dp(240) - height;
            }
            if (popupY < chatListView.getY() + AndroidUtilities.dp(24)) {
                popupY = (int) (chatListView.getY() + AndroidUtilities.dp(24));
            } else if (popupY > totalHeight - height - AndroidUtilities.dp(8)) {
                popupY = totalHeight - height - AndroidUtilities.dp(8);
            }
        } else {
            popupY = inBubbleMode ? 0 : AndroidUtilities.statusBarHeight;
        }
        final int finalPopupX = scrimPopupX = popupX;
        final int finalPopupY = scrimPopupY = popupY;
        Runnable showMenu = () -> {
            if (scrimPopupWindow == null || fragmentView == null) {
                return;
            }
            scrimPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, finalPopupX, finalPopupY);
            if (isReactionsAvailable) {
                reactionsLayout.startEnterAnimation();
            }
        };
        if (waitForLangDetection.get()) {
            onLangDetectionDone.set(showMenu);
        } else {
            showMenu.run();
        }
        chatListView.stopScroll();
        chatLayoutManager.setCanScrollVertically(false);
        dimBehindView(v, true);
        hideHints(false);
        if (topUndoView != null) {
            topUndoView.hide(true, 1);
        }
        if (undoView != null) {
            undoView.hide(true, 1);
        }
        if (chatActivityEnterView != null) {
            chatActivityEnterView.getEditField().setAllowDrawCursor(false);
        }
        return;
    }
    if (chatActivityEnterView != null && (chatActivityEnterView.isRecordingAudioVideo() || chatActivityEnterView.isRecordLocked())) {
        return;
    }
    final ActionBarMenu actionMode = actionBar.createActionMode();
    View item = actionMode.getItem(delete);
    if (item != null) {
        item.setVisibility(View.VISIBLE);
    }
    bottomMessagesActionContainer.setVisibility(View.VISIBLE);
    int translationY = chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(51);
    if (chatActivityEnterView.getVisibility() == View.VISIBLE) {
        ArrayList<View> views = new ArrayList<>();
        views.add(chatActivityEnterView);
        if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
            views.add(mentionContainer);
        }
        if (stickersPanel != null && stickersPanel.getVisibility() == View.VISIBLE) {
            views.add(stickersPanel);
        }
        actionBar.showActionMode(true, bottomMessagesActionContainer, null, views.toArray(new View[0]), new boolean[] { false, true, true }, chatListView, translationY);
        if (getParentActivity() instanceof LaunchActivity) {
            ((LaunchActivity) getParentActivity()).hideVisibleActionMode();
        }
        chatActivityEnterView.getEditField().setAllowDrawCursor(false);
    } else if (bottomOverlayChat.getVisibility() == View.VISIBLE) {
        actionBar.showActionMode(true, bottomMessagesActionContainer, null, new View[] { bottomOverlayChat }, new boolean[] { true }, chatListView, translationY);
    } else {
        actionBar.showActionMode(true, bottomMessagesActionContainer, null, null, null, chatListView, translationY);
    }
    closeMenu();
    chatLayoutManager.setCanScrollVertically(true);
    updatePinnedMessageView(true);
    AnimatorSet animatorSet = new AnimatorSet();
    ArrayList<Animator> animators = new ArrayList<>();
    for (int a = 0; a < actionModeViews.size(); a++) {
        View view = actionModeViews.get(a);
        view.setPivotY(ActionBar.getCurrentActionBarHeight() / 2);
        AndroidUtilities.clearDrawableAnimation(view);
        animators.add(ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.1f, 1.0f));
    }
    animatorSet.playTogether(animators);
    animatorSet.setDuration(250);
    animatorSet.start();
    addToSelectedMessages(message, listView);
    if (chatActivityEnterView != null) {
        chatActivityEnterView.preventInput = true;
    }
    selectedMessagesCountTextView.setNumber(selectedMessagesIds[0].size() + selectedMessagesIds[1].size(), false);
    updateVisibleRows();
    if (chatActivityEnterView != null) {
        chatActivityEnterView.hideBotCommands();
    }
}
Also used : ViewHelper(org.telegram.ui.Components.ViewHelper) Bundle(android.os.Bundle) BotHelpCell(org.telegram.ui.Cells.BotHelpCell) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) StickersAlert(org.telegram.ui.Components.StickersAlert) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) Property(android.util.Property) HorizontalScrollView(android.widget.HorizontalScrollView) ChatThemeController(org.telegram.messenger.ChatThemeController) MediaStore(android.provider.MediaStore) Map(java.util.Map) Shader(android.graphics.Shader) ContextCompat(androidx.core.content.ContextCompat) NotificationCenter(org.telegram.messenger.NotificationCenter) PinnedLineView(org.telegram.ui.Components.PinnedLineView) CountDownLatch(java.util.concurrent.CountDownLatch) Layout(android.text.Layout) EmojiData(org.telegram.messenger.EmojiData) ForwardingMessagesParams(org.telegram.messenger.ForwardingMessagesParams) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) Paint(android.graphics.Paint) Path(android.graphics.Path) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SystemClock(android.os.SystemClock) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) 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) ChatActivityMemberRequestsDelegate(org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) EditText(android.widget.EditText) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) Animator(android.animation.Animator) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) ChatAttachAlertDocumentLayout(org.telegram.ui.Components.ChatAttachAlertDocumentLayout) DatePickerDialog(android.app.DatePickerDialog) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) StickersAdapter(org.telegram.ui.Adapters.StickersAdapter) RectF(android.graphics.RectF) ReportAlert(org.telegram.ui.Components.ReportAlert) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ShareAlert(org.telegram.ui.Components.ShareAlert) BluredView(org.telegram.ui.Components.BluredView) UserConfig(org.telegram.messenger.UserConfig) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) EmojiThemes(org.telegram.ui.ActionBar.EmojiThemes) InstantCameraView(org.telegram.ui.Components.InstantCameraView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ImportingAlert(org.telegram.ui.Components.ImportingAlert) Spanned(android.text.Spanned) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) SparseIntArray(android.util.SparseIntArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LocaleController(org.telegram.messenger.LocaleController) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) ActionBar(org.telegram.ui.ActionBar.ActionBar) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) TLObject(org.telegram.tgnet.TLObject) Size(org.telegram.ui.Components.Size) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) PollVotesAlert(org.telegram.ui.Components.PollVotesAlert) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) CharacterStyle(android.text.style.CharacterStyle) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) 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) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Matcher(java.util.regex.Matcher) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) Canvas(android.graphics.Canvas) AccessibilityEvent(android.view.accessibility.AccessibilityEvent) Emoji(org.telegram.messenger.Emoji) MessagesSearchAdapter(org.telegram.ui.Adapters.MessagesSearchAdapter) ColorMatrix(android.graphics.ColorMatrix) ForegroundColorSpan(android.text.style.ForegroundColorSpan) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BackButtonMenu(org.telegram.ui.Components.BackButtonMenu) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) ColorMatrixColorFilter(android.graphics.ColorMatrixColorFilter) CounterView(org.telegram.ui.Components.CounterView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) TrendingStickersAlert(org.telegram.ui.Components.TrendingStickersAlert) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) TextPaint(android.text.TextPaint) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) HintView(org.telegram.ui.Components.HintView) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) URLSpanBotCommand(org.telegram.ui.Components.URLSpanBotCommand) ReactionsLayoutInBubble(org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble) ExifInterface(androidx.exifinterface.media.ExifInterface) FileLoader(org.telegram.messenger.FileLoader) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) Space(android.widget.Space) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) BitmapFactory(android.graphics.BitmapFactory) GigagroupConvertAlert(org.telegram.ui.Components.GigagroupConvertAlert) URLSpanMono(org.telegram.ui.Components.URLSpanMono) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) ArrayList(java.util.ArrayList) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) EditTextCaption(org.telegram.ui.Components.EditTextCaption) BuildConfig(org.telegram.messenger.BuildConfig) DialogCell(org.telegram.ui.Cells.DialogCell) SpannableString(android.text.SpannableString) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) ChatUnreadCell(org.telegram.ui.Cells.ChatUnreadCell) ChatLoadingCell(org.telegram.ui.Cells.ChatLoadingCell) ClippingImageView(org.telegram.ui.Components.ClippingImageView) File(java.io.File) ReactionsEffectOverlay(org.telegram.ui.Components.Reactions.ReactionsEffectOverlay) Gravity(android.view.Gravity) PorterDuffXfermode(android.graphics.PorterDuffXfermode) TypedValue(android.util.TypedValue) Configuration(android.content.res.Configuration) StickerCell(org.telegram.ui.Cells.StickerCell) ReactionsContainerLayout(org.telegram.ui.Components.ReactionsContainerLayout) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EmojiView(org.telegram.ui.Components.EmojiView) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ChatScrimPopupContainerLayout(org.telegram.ui.Components.ChatScrimPopupContainerLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Spannable(android.text.Spannable) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ChecksHintView(org.telegram.ui.Components.ChecksHintView) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) Matrix(android.graphics.Matrix) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) BitmapShader(android.graphics.BitmapShader) Utilities(org.telegram.messenger.Utilities) HideViewAfterAnimation(org.telegram.ui.Components.HideViewAfterAnimation) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) SparseArray(android.util.SparseArray) List(java.util.List) TextView(android.widget.TextView) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) SecretChatHelper(org.telegram.messenger.SecretChatHelper) FileProvider(androidx.core.content.FileProvider) Pattern(java.util.regex.Pattern) 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) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ViewOutlineProvider(android.view.ViewOutlineProvider) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) TranslateAlert(org.telegram.ui.Components.TranslateAlert) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClipData(android.content.ClipData) SuppressLint(android.annotation.SuppressLint) 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) FireworksOverlay(org.telegram.ui.Components.FireworksOverlay) LongSparseArray(androidx.collection.LongSparseArray) FileWriter(java.io.FileWriter) FileLog(org.telegram.messenger.FileLog) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement) MessagesController(org.telegram.messenger.MessagesController) NumberTextView(org.telegram.ui.Components.NumberTextView) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Rect(android.graphics.Rect) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) ViewPager(androidx.viewpager.widget.ViewPager) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) SparseIntArray(android.util.SparseIntArray) 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) ChatScrimPopupContainerLayout(org.telegram.ui.Components.ChatScrimPopupContainerLayout) Intent(android.content.Intent) AtomicReference(java.util.concurrent.atomic.AtomicReference) ReactionsContainerLayout(org.telegram.ui.Components.ReactionsContainerLayout) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) Animator(android.animation.Animator) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) ValueAnimator(android.animation.ValueAnimator) ObjectAnimator(android.animation.ObjectAnimator) Bulletin(org.telegram.ui.Components.Bulletin) SpannableStringBuilder(android.text.SpannableStringBuilder) ValueAnimator(android.animation.ValueAnimator) TLRPC(org.telegram.tgnet.TLRPC) PagerAdapter(androidx.viewpager.widget.PagerAdapter) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView) NumberTextView(org.telegram.ui.Components.NumberTextView) TranslateAlert(org.telegram.ui.Components.TranslateAlert) HorizontalScrollView(android.widget.HorizontalScrollView) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) SpannableStringBuilder(android.text.SpannableStringBuilder) ChatObject(org.telegram.messenger.ChatObject) AnimatorSet(android.animation.AnimatorSet) KeyEvent(android.view.KeyEvent) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) VoIPService(org.telegram.messenger.voip.VoIPService) ViewGroup(android.view.ViewGroup) Bundle(android.os.Bundle) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) HorizontalScrollView(android.widget.HorizontalScrollView) PinnedLineView(org.telegram.ui.Components.PinnedLineView) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) RecyclerView(androidx.recyclerview.widget.RecyclerView) BluredView(org.telegram.ui.Components.BluredView) InstantCameraView(org.telegram.ui.Components.InstantCameraView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) 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) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) UndoView(org.telegram.ui.Components.UndoView) CounterView(org.telegram.ui.Components.CounterView) HintView(org.telegram.ui.Components.HintView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) EmojiView(org.telegram.ui.Components.EmojiView) ChecksHintView(org.telegram.ui.Components.ChecksHintView) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) TextView(android.widget.TextView) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) NumberTextView(org.telegram.ui.Components.NumberTextView) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) MotionEvent(android.view.MotionEvent) SparseArray(android.util.SparseArray) LongSparseArray(androidx.collection.LongSparseArray) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) FrameLayout(android.widget.FrameLayout) MessageObject(org.telegram.messenger.MessageObject) LinearLayout(android.widget.LinearLayout)

Example 3 with Size

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

the class ChatActivity method createView.

@Override
public View createView(Context context) {
    textSelectionHelper = new TextSelectionHelper.ChatListTextSelectionHelper() {

        @Override
        public int getParentTopPadding() {
            return (int) chatListViewPaddingTop;
        }

        @Override
        protected int getThemedColor(String key) {
            Integer color = themeDelegate.getColor(key);
            return color != null ? color : super.getThemedColor(key);
        }

        @Override
        protected Theme.ResourcesProvider getResourcesProvider() {
            return themeDelegate;
        }
    };
    if (reportType >= 0) {
        actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefault));
        actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), false);
        actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false);
        actionBar.setTitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
        actionBar.setSubtitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
    }
    actionBarBackgroundPaint.setColor(getThemedColor(Theme.key_actionBarDefault));
    if (chatMessageCellsCache.isEmpty()) {
        for (int a = 0; a < 15; a++) {
            chatMessageCellsCache.add(new ChatMessageCell(context, true, themeDelegate));
        }
    }
    for (int a = 1; a >= 0; a--) {
        selectedMessagesIds[a].clear();
        selectedMessagesCanCopyIds[a].clear();
        selectedMessagesCanStarIds[a].clear();
    }
    scheduledOrNoSoundHint = null;
    infoTopView = null;
    aspectRatioFrameLayout = null;
    videoTextureView = null;
    searchAsListHint = null;
    mediaBanTooltip = null;
    noSoundHintView = null;
    forwardHintView = null;
    checksHintView = null;
    textSelectionHint = null;
    emojiButtonRed = null;
    gifHintTextView = null;
    pollHintView = null;
    timerHintView = null;
    videoPlayerContainer = null;
    voiceHintTextView = null;
    blurredView = null;
    dummyMessageCell = null;
    cantDeleteMessagesCount = 0;
    canEditMessagesCount = 0;
    cantForwardMessagesCount = 0;
    canForwardMessagesCount = 0;
    cantSaveMessagesCount = 0;
    canSaveMusicCount = 0;
    canSaveDocumentsCount = 0;
    hasOwnBackground = true;
    if (chatAttachAlert != null) {
        try {
            if (chatAttachAlert.isShowing()) {
                chatAttachAlert.dismiss();
            }
        } catch (Exception ignore) {
        }
        chatAttachAlert.onDestroy();
        chatAttachAlert = null;
    }
    if (stickersAdapter != null) {
        stickersAdapter.onDestroy();
        stickersAdapter = null;
    }
    Theme.createChatResources(context, false);
    actionBar.setAddToContainer(false);
    if (inPreviewMode) {
        actionBar.setBackButtonDrawable(null);
    } else {
        actionBar.setBackButtonDrawable(new BackDrawable(reportType >= 0));
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(final int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    clearSelectionMode();
                } else {
                    if (!checkRecordLocked(true)) {
                        finishFragment();
                    }
                }
            } else if (id == copy) {
                String str = "";
                long previousUid = 0;
                for (int a = 1; a >= 0; a--) {
                    ArrayList<Integer> ids = new ArrayList<>();
                    for (int b = 0; b < selectedMessagesCanCopyIds[a].size(); b++) {
                        ids.add(selectedMessagesCanCopyIds[a].keyAt(b));
                    }
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (int b = 0; b < ids.size(); b++) {
                        Integer messageId = ids.get(b);
                        MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
                        if (str.length() != 0) {
                            str += "\n\n";
                        }
                        str += getMessageContent(messageObject, previousUid, ids.size() != 1 && (currentUser == null || !currentUser.self));
                        previousUid = messageObject.getFromChatId();
                    }
                }
                if (str.length() != 0) {
                    AndroidUtilities.addToClipboard(str);
                    undoView.showWithAction(0, UndoView.ACTION_TEXT_COPIED, null);
                }
                clearSelectionMode();
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                createDeleteMessagesAlert(null, null);
            } else if (id == forward) {
                openForward(true);
            } else if (id == save_to) {
                ArrayList<MessageObject> messageObjects = new ArrayList<>();
                for (int a = 1; a >= 0; a--) {
                    for (int b = 0; b < selectedMessagesIds[a].size(); b++) {
                        messageObjects.add(selectedMessagesIds[a].valueAt(b));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                    selectedMessagesCanStarIds[a].clear();
                }
                boolean isMusic = canSaveMusicCount > 0;
                hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
                MediaController.saveFilesFromMessages(getParentActivity(), getAccountInstance(), messageObjects, (count) -> {
                    if (count > 0) {
                        if (getParentActivity() == null) {
                            return;
                        }
                        BulletinFactory.of(ChatActivity.this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count, themeDelegate).show();
                    }
                });
            } else if (id == chat_enc_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat, themeDelegate).create());
            } else if (id == clear_history || id == delete_chat || id == auto_delete_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                if (id == auto_delete_timer || id == clear_history && currentEncryptedChat == null && (currentUser != null && !UserObject.isUserSelf(currentUser) && !UserObject.isDeleted(currentUser) || ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES) && (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)))) {
                    ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), currentUser, currentChat, id != auto_delete_timer, themeDelegate);
                    alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() {

                        @Override
                        public void onClearHistory(boolean revoke) {
                            if (revoke && currentUser != null) {
                                getMessagesStorage().getMessagesCount(currentUser.id, (count) -> {
                                    if (count >= 50) {
                                        AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, true, false, true, null, currentUser, false, false, (param) -> performHistoryClear(true), themeDelegate);
                                    } else {
                                        performHistoryClear(true);
                                    }
                                });
                            } else {
                                performHistoryClear(revoke);
                            }
                        }

                        @Override
                        public void onAutoDeleteHistory(int ttl, int action) {
                            getMessagesController().setDialogHistoryTTL(dialog_id, ttl);
                            if (userInfo != null || chatInfo != null) {
                                undoView.showWithAction(dialog_id, action, currentUser, userInfo != null ? userInfo.ttl_period : chatInfo.ttl_period, null, null);
                            }
                        }
                    });
                    showDialog(alert);
                    return;
                }
                AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, id == clear_history, currentChat, currentUser, currentEncryptedChat != null, true, (param) -> {
                    if (id == clear_history && ChatObject.isChannel(currentChat) && (!currentChat.megagroup || !TextUtils.isEmpty(currentChat.username))) {
                        getMessagesController().deleteDialog(dialog_id, 2, param);
                    } else {
                        if (id != clear_history) {
                            getNotificationCenter().removeObserver(ChatActivity.this, NotificationCenter.closeChats);
                            getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
                            finishFragment();
                            getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, dialog_id, currentUser, currentChat, param);
                        } else {
                            performHistoryClear(param);
                        }
                    }
                }, themeDelegate);
            } else if (id == share_contact) {
                if (currentUser == null || getParentActivity() == null) {
                    return;
                }
                if (addToContactsButton.getTag() != null) {
                    shareMyContact((Integer) addToContactsButton.getTag(), null);
                } else {
                    Bundle args = new Bundle();
                    args.putLong("user_id", currentUser.id);
                    args.putBoolean("addContact", true);
                    presentFragment(new ContactAddActivity(args));
                }
            } else if (id == mute) {
                toggleMute(false);
            } else if (id == add_shortcut) {
                try {
                    getMediaDataController().installShortcut(currentUser.id);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == report) {
                AlertsCreator.createReportAlert(getParentActivity(), dialog_id, 0, ChatActivity.this, themeDelegate, null);
            } else if (id == star) {
                for (int a = 0; a < 2; a++) {
                    for (int b = 0; b < selectedMessagesCanStarIds[a].size(); b++) {
                        MessageObject msg = selectedMessagesCanStarIds[a].valueAt(b);
                        getMediaDataController().addRecentSticker(MediaDataController.TYPE_FAVE, msg, msg.getDocument(), (int) (System.currentTimeMillis() / 1000), !hasUnfavedSelected);
                    }
                }
                clearSelectionMode();
            } else if (id == edit) {
                MessageObject messageObject = null;
                for (int a = 1; a >= 0; a--) {
                    if (messageObject == null && selectedMessagesIds[a].size() == 1) {
                        ArrayList<Integer> ids = new ArrayList<>();
                        for (int b = 0; b < selectedMessagesIds[a].size(); b++) {
                            ids.add(selectedMessagesIds[a].keyAt(b));
                        }
                        messageObject = messagesDict[a].get(ids.get(0));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                    selectedMessagesCanStarIds[a].clear();
                }
                startEditingMessageObject(messageObject);
                hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == chat_menu_attach) {
                ActionBarMenuSubItem attach = new ActionBarMenuSubItem(context, false, true, true, getResourceProvider());
                attach.setTextAndIcon(LocaleController.getString("AttachMenu", R.string.AttachMenu), R.drawable.input_attach);
                attach.setOnClickListener(view -> {
                    headerItem.closeSubMenu();
                    if (chatAttachAlert != null) {
                        chatAttachAlert.setEditingMessageObject(null);
                    }
                    openAttachMenu();
                });
                headerItem.toggleSubMenu(attach, attachItem);
            } else if (id == bot_help) {
                getSendMessagesHelper().sendMessage("/help", dialog_id, null, null, null, false, null, null, null, true, 0, null);
            } else if (id == bot_settings) {
                getSendMessagesHelper().sendMessage("/settings", dialog_id, null, null, null, false, null, null, null, true, 0, null);
            } else if (id == search) {
                openSearchWithText(null);
            } else if (id == call || id == video_call) {
                if (currentUser != null && getParentActivity() != null) {
                    VoIPHelper.startCall(currentUser, id == video_call, userInfo != null && userInfo.video_calls_available, getParentActivity(), getMessagesController().getUserFull(currentUser.id), getAccountInstance());
                }
            } else if (id == text_bold) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedBold();
                }
            } else if (id == text_italic) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedItalic();
                }
            } else if (id == text_spoiler) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedSpoiler();
                }
            } else if (id == text_mono) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedMono();
                }
            } else if (id == text_strike) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedStrike();
                }
            } else if (id == text_underline) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedUnderline();
                }
            } else if (id == text_link) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedUrl();
                }
            } else if (id == text_regular) {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
                    chatActivityEnterView.getEditField().makeSelectedRegular();
                }
            } else if (id == change_colors) {
                showChatThemeBottomSheet();
            }
        }
    });
    View backButton = actionBar.getBackButton();
    backButton.setOnLongClickListener(e -> {
        scrimPopupWindow = BackButtonMenu.show(this, backButton, dialog_id);
        if (scrimPopupWindow != null) {
            scrimPopupWindow.setOnDismissListener(() -> {
                scrimPopupWindow = null;
                menuDeleteItem = null;
                scrimPopupWindowItems = null;
                chatLayoutManager.setCanScrollVertically(true);
                if (scrimPopupWindowHideDimOnDismiss) {
                    dimBehindView(false);
                } else {
                    scrimPopupWindowHideDimOnDismiss = true;
                }
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.getEditField().setAllowDrawCursor(true);
                }
            });
            chatListView.stopScroll();
            chatLayoutManager.setCanScrollVertically(false);
            dimBehindView(backButton, 0.3f);
            hideHints(false);
            if (topUndoView != null) {
                topUndoView.hide(true, 1);
            }
            if (undoView != null) {
                undoView.hide(true, 1);
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.getEditField().setAllowDrawCursor(false);
            }
            return true;
        } else {
            return false;
        }
    });
    actionBar.setInterceptTouchEventListener((view, motionEvent) -> {
        if (chatThemeBottomSheet != null) {
            chatThemeBottomSheet.close();
            return true;
        }
        return false;
    });
    if (avatarContainer != null) {
        avatarContainer.onDestroy();
    }
    avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null, themeDelegate);
    AndroidUtilities.updateViewVisibilityAnimated(avatarContainer, true, 1f, false);
    if (inPreviewMode || inBubbleMode) {
        avatarContainer.setOccupyStatusBar(false);
    }
    if (reportType >= 0) {
        if (reportType == 0) {
            actionBar.setTitle(LocaleController.getString("ReportChatSpam", R.string.ReportChatSpam));
        } else if (reportType == 2) {
            actionBar.setTitle(LocaleController.getString("ReportChatViolence", R.string.ReportChatViolence));
        } else if (reportType == 3) {
            actionBar.setTitle(LocaleController.getString("ReportChatChild", R.string.ReportChatChild));
        } else if (reportType == 4) {
            actionBar.setTitle(LocaleController.getString("ReportChatPornography", R.string.ReportChatPornography));
        }
        actionBar.setSubtitle(LocaleController.getString("ReportSelectMessages", R.string.ReportSelectMessages));
    } else if (startLoadFromDate != 0) {
        final int date = startLoadFromDate;
        actionBar.setOnClickListener((v) -> {
            jumpToDate(date);
        });
        actionBar.setTitle(LocaleController.formatDateChat(startLoadFromDate, false));
        actionBar.setSubtitle(LocaleController.getString("Loading", R.string.Loading));
        TLRPC.TL_messages_getHistory gh1 = new TLRPC.TL_messages_getHistory();
        gh1.peer = getMessagesController().getInputPeer(dialog_id);
        gh1.offset_date = startLoadFromDate;
        gh1.limit = 1;
        gh1.add_offset = -1;
        int req = getConnectionsManager().sendRequest(gh1, (response, error) -> {
            if (response instanceof TLRPC.messages_Messages) {
                List<TLRPC.Message> l = ((TLRPC.messages_Messages) response).messages;
                if (!l.isEmpty()) {
                    TLRPC.TL_messages_getHistory gh2 = new TLRPC.TL_messages_getHistory();
                    gh2.peer = getMessagesController().getInputPeer(dialog_id);
                    gh2.offset_date = startLoadFromDate + 60 * 60 * 24;
                    gh2.limit = 1;
                    getConnectionsManager().sendRequest(gh2, (response1, error1) -> {
                        if (response1 instanceof TLRPC.messages_Messages) {
                            List<TLRPC.Message> l2 = ((TLRPC.messages_Messages) response1).messages;
                            int count = 0;
                            if (!l2.isEmpty()) {
                                count = ((TLRPC.messages_Messages) response).offset_id_offset - ((TLRPC.messages_Messages) response1).offset_id_offset;
                            } else {
                                count = ((TLRPC.messages_Messages) response).offset_id_offset;
                            }
                            int finalCount = count;
                            AndroidUtilities.runOnUIThread(() -> {
                                if (finalCount != 0) {
                                    AndroidUtilities.runOnUIThread(() -> actionBar.setSubtitle(LocaleController.formatPluralString("messages", finalCount)));
                                } else {
                                    actionBar.setSubtitle(LocaleController.getString("NoMessagesForThisDay", R.string.NoMessagesForThisDay));
                                }
                            });
                        }
                    });
                } else {
                    actionBar.setSubtitle(LocaleController.getString("NoMessagesForThisDay", R.string.NoMessagesForThisDay));
                }
            }
        });
        getConnectionsManager().bindRequestToGuid(req, classGuid);
    } else {
        actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, !inPreviewMode ? 56 : (chatMode == MODE_PINNED ? 10 : 0), 0, 40, 0));
    }
    ActionBarMenu menu = actionBar.createMenu();
    if (currentEncryptedChat == null && chatMode == 0 && reportType < 0) {
        searchIconItem = menu.addItem(search, R.drawable.ic_ab_search);
        searchItem = menu.addItem(0, R.drawable.ic_ab_search, themeDelegate).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

            boolean searchWas;

            @Override
            public boolean canCollapseSearch() {
                if (messagesSearchListView.getTag() != null) {
                    showMessagesSearchListView(false);
                    return false;
                }
                return true;
            }

            @Override
            public void onSearchCollapse() {
                searchCalendarButton.setVisibility(View.VISIBLE);
                if (searchUserButton != null) {
                    searchUserButton.setVisibility(View.VISIBLE);
                }
                if (searchingForUser) {
                    mentionsAdapter.searchUsernameOrHashtag(null, 0, null, false, true);
                    searchingForUser = false;
                }
                mentionLayoutManager.setReverseLayout(false);
                mentionsAdapter.setSearchingMentions(false);
                searchingUserMessages = null;
                searchingChatMessages = null;
                searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
                searchItem.setSearchFieldCaption(null);
                AndroidUtilities.updateViewVisibilityAnimated(avatarContainer, true, 0.95f, true);
                if (editTextItem != null && editTextItem.getTag() != null) {
                    if (headerItem != null) {
                        headerItem.setVisibility(View.GONE);
                    }
                    if (editTextItem != null) {
                        editTextItem.setVisibility(View.VISIBLE);
                    }
                    if (attachItem != null) {
                        attachItem.setVisibility(View.GONE);
                    }
                    if (searchIconItem != null && showSearchAsIcon) {
                        searchIconItem.setVisibility(View.GONE);
                    }
                    if (audioCallIconItem != null && showAudioCallAsIcon) {
                        audioCallIconItem.setVisibility(View.GONE);
                    }
                } else if (chatActivityEnterView.hasText() && TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer()) && (currentChat == null || ChatObject.canSendMessages(currentChat))) {
                    if (headerItem != null) {
                        headerItem.setVisibility(View.GONE);
                    }
                    if (editTextItem != null) {
                        editTextItem.setVisibility(View.GONE);
                    }
                    if (attachItem != null) {
                        attachItem.setVisibility(View.VISIBLE);
                    }
                    if (searchIconItem != null && showSearchAsIcon) {
                        searchIconItem.setVisibility(View.GONE);
                    }
                    if (audioCallIconItem != null && showAudioCallAsIcon) {
                        audioCallIconItem.setVisibility(View.GONE);
                    }
                } else {
                    if (headerItem != null) {
                        headerItem.setVisibility(View.VISIBLE);
                    }
                    if (audioCallIconItem != null && showAudioCallAsIcon) {
                        audioCallIconItem.setVisibility(View.VISIBLE);
                    }
                    if (searchIconItem != null && showSearchAsIcon) {
                        searchIconItem.setVisibility(View.VISIBLE);
                    }
                    if (editTextItem != null) {
                        editTextItem.setVisibility(View.GONE);
                    }
                    if (attachItem != null) {
                        attachItem.setVisibility(View.GONE);
                    }
                }
                if (threadMessageId == 0 && !UserObject.isReplyUser(currentUser) || threadMessageObject != null && threadMessageObject.getRepliesCount() == 0) {
                    searchItem.setVisibility(View.GONE);
                }
                searchItemVisible = false;
                getMediaDataController().clearFoundMessageObjects();
                if (messagesSearchAdapter != null) {
                    messagesSearchAdapter.notifyDataSetChanged();
                }
                removeSelectedMessageHighlight();
                updateBottomOverlay();
                updatePinnedMessageView(true);
                updateVisibleRows();
            }

            @Override
            public void onSearchExpand() {
                if (threadMessageId != 0 || UserObject.isReplyUser(currentUser)) {
                    openSearchWithText(null);
                }
                if (!openSearchKeyboard) {
                    return;
                }
                saveKeyboardPositionBeforeTransition();
                AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
                AndroidUtilities.runOnUIThread(() -> {
                    searchWas = false;
                    searchItem.getSearchField().requestFocus();
                    AndroidUtilities.showKeyboard(searchItem.getSearchField());
                    removeKeyboardPositionBeforeTransition();
                }, 500);
            }

            @Override
            public void onSearchPressed(EditText editText) {
                searchWas = true;
                updateSearchButtons(0, 0, -1);
                getMediaDataController().searchMessagesInChat(editText.getText().toString(), dialog_id, mergeDialogId, classGuid, 0, threadMessageId, searchingUserMessages, searchingChatMessages);
            }

            @Override
            public void onTextChanged(EditText editText) {
                showMessagesSearchListView(false);
                if (searchingForUser) {
                    mentionsAdapter.searchUsernameOrHashtag("@" + editText.getText().toString(), 0, messages, true, true);
                } else if (searchingUserMessages == null && searchingChatMessages == null && searchUserButton != null && TextUtils.equals(editText.getText(), LocaleController.getString("SearchFrom", R.string.SearchFrom))) {
                    searchUserButton.callOnClick();
                }
            }

            @Override
            public void onCaptionCleared() {
                if (searchingUserMessages != null || searchingChatMessages != null) {
                    searchUserButton.callOnClick();
                } else {
                    if (searchingForUser) {
                        mentionsAdapter.searchUsernameOrHashtag(null, 0, null, false, true);
                        searchingForUser = false;
                        searchItem.setSearchFieldText("", true);
                    }
                    searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
                    searchCalendarButton.setVisibility(View.VISIBLE);
                    searchUserButton.setVisibility(View.VISIBLE);
                    searchingUserMessages = null;
                    searchingChatMessages = null;
                }
            }

            @Override
            public boolean forceShowClear() {
                return searchingForUser;
            }
        });
        searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
        if (threadMessageId == 0 && !UserObject.isReplyUser(currentUser) || threadMessageObject != null && threadMessageObject.getRepliesCount() == 0) {
            searchItem.setVisibility(View.GONE);
        }
        searchItemVisible = false;
    }
    if (chatMode == 0 && threadMessageId == 0 && !UserObject.isReplyUser(currentUser) && reportType < 0 && !inMenuMode) {
        TLRPC.UserFull userFull = null;
        if (currentUser != null) {
            audioCallIconItem = menu.addItem(call, R.drawable.ic_call, themeDelegate);
            userFull = getMessagesController().getUserFull(currentUser.id);
            if (userFull != null && userFull.phone_calls_available) {
                showAudioCallAsIcon = !inPreviewMode;
                audioCallIconItem.setVisibility(View.VISIBLE);
            } else {
                showAudioCallAsIcon = false;
                audioCallIconItem.setVisibility(View.GONE);
            }
        }
        headerItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate);
        headerItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
        if (currentUser != null) {
            headerItem.addSubItem(call, R.drawable.msg_callback, LocaleController.getString("Call", R.string.Call), themeDelegate);
            if (Build.VERSION.SDK_INT >= 18) {
                headerItem.addSubItem(video_call, R.drawable.msg_videocall, LocaleController.getString("VideoCall", R.string.VideoCall), themeDelegate);
            }
            if (userFull != null && userFull.phone_calls_available) {
                headerItem.showSubItem(call);
                if (userFull.video_calls_available) {
                    headerItem.showSubItem(video_call);
                } else {
                    headerItem.hideSubItem(video_call);
                }
            } else {
                headerItem.hideSubItem(call);
                headerItem.hideSubItem(video_call);
            }
        }
        editTextItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate);
        editTextItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
        editTextItem.setTag(null);
        editTextItem.setVisibility(View.GONE);
        editTextItem.addSubItem(text_spoiler, LocaleController.getString("Spoiler", R.string.Spoiler));
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(LocaleController.getString("Bold", R.string.Bold));
        stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editTextItem.addSubItem(text_bold, stringBuilder);
        stringBuilder = new SpannableStringBuilder(LocaleController.getString("Italic", R.string.Italic));
        stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/ritalic.ttf")), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editTextItem.addSubItem(text_italic, stringBuilder);
        stringBuilder = new SpannableStringBuilder(LocaleController.getString("Mono", R.string.Mono));
        stringBuilder.setSpan(new TypefaceSpan(Typeface.MONOSPACE), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editTextItem.addSubItem(text_mono, stringBuilder);
        if (currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 101) {
            stringBuilder = new SpannableStringBuilder(LocaleController.getString("Strike", R.string.Strike));
            TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
            run.flags |= TextStyleSpan.FLAG_STYLE_STRIKE;
            stringBuilder.setSpan(new TextStyleSpan(run), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            editTextItem.addSubItem(text_strike, stringBuilder);
            stringBuilder = new SpannableStringBuilder(LocaleController.getString("Underline", R.string.Underline));
            run = new TextStyleSpan.TextStyleRun();
            run.flags |= TextStyleSpan.FLAG_STYLE_UNDERLINE;
            stringBuilder.setSpan(new TextStyleSpan(run), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            editTextItem.addSubItem(text_underline, stringBuilder);
        }
        editTextItem.addSubItem(text_link, LocaleController.getString("CreateLink", R.string.CreateLink));
        editTextItem.addSubItem(text_regular, LocaleController.getString("Regular", R.string.Regular));
        if (searchItem != null) {
            headerItem.addSubItem(search, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search), themeDelegate);
        }
        if (currentChat != null && !currentChat.creator && !ChatObject.hasAdminRights(currentChat)) {
            headerItem.addSubItem(report, R.drawable.msg_report, LocaleController.getString("ReportChat", R.string.ReportChat), themeDelegate);
        }
        if (currentUser != null) {
            addContactItem = headerItem.addSubItem(share_contact, R.drawable.msg_addcontact, "", themeDelegate);
        }
        if (currentEncryptedChat != null) {
            timeItem2 = headerItem.addSubItem(chat_enc_timer, R.drawable.msg_timer, LocaleController.getString("SetTimer", R.string.SetTimer), themeDelegate);
        }
        if (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)) {
            headerItem.addSubItem(clear_history, R.drawable.msg_clear, LocaleController.getString("ClearHistory", R.string.ClearHistory), themeDelegate);
        } else if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) {
            headerItem.addSubItem(auto_delete_timer, R.drawable.msg_timer, LocaleController.getString("AutoDeleteSetTimer", R.string.AutoDeleteSetTimer), themeDelegate);
        }
        if (themeDelegate.isThemeChangeAvailable()) {
            headerItem.addSubItem(change_colors, R.drawable.msg_colors, LocaleController.getString("ChangeColors", R.string.ChangeColors), themeDelegate);
        }
        if (currentUser == null || !currentUser.self) {
            muteItem = headerItem.addSubItem(mute, R.drawable.msg_mute, null, themeDelegate);
        }
        if (ChatObject.isChannel(currentChat) && !currentChat.creator) {
            if (!ChatObject.isNotInChat(currentChat)) {
                if (currentChat.megagroup) {
                    headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveMegaMenu", R.string.LeaveMegaMenu), themeDelegate);
                } else {
                    headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveChannelMenu", R.string.LeaveChannelMenu), themeDelegate);
                }
            }
        } else if (!ChatObject.isChannel(currentChat)) {
            if (currentChat != null) {
                headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), themeDelegate);
            } else {
                headerItem.addSubItem(delete_chat, R.drawable.msg_delete, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), themeDelegate);
            }
        }
        if (currentUser != null && currentUser.self) {
            headerItem.addSubItem(add_shortcut, R.drawable.msg_home, LocaleController.getString("AddShortcut", R.string.AddShortcut), themeDelegate);
        }
        if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
            headerItem.addSubItem(bot_settings, R.drawable.menu_settings, LocaleController.getString("BotSettings", R.string.BotSettings), themeDelegate);
            headerItem.addSubItem(bot_help, R.drawable.menu_help, LocaleController.getString("BotHelp", R.string.BotHelp), themeDelegate);
            updateBotButtons();
        }
    }
    updateTitle();
    avatarContainer.updateOnlineCount();
    avatarContainer.updateSubtitle();
    updateTitleIcons();
    if (chatMode == 0 && !isThreadChat() && reportType < 0) {
        attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other, themeDelegate).setOverrideMenuClick(true).setAllowCloseAnimation(false);
        attachItem.setContentDescription(LocaleController.getString("AccDescrAttachButton", R.string.AccDescrAttachButton));
        attachItem.setVisibility(View.GONE);
    }
    actionModeViews.clear();
    if (inPreviewMode) {
        if (headerItem != null) {
            headerItem.setAlpha(0.0f);
        }
        if (attachItem != null) {
            attachItem.setAlpha(0.0f);
        }
    }
    final ActionBarMenu actionMode = actionBar.createActionMode();
    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
    actionMode.addView(selectedMessagesCountTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    selectedMessagesCountTextView.setOnTouchListener((v, event) -> true);
    if (currentEncryptedChat == null) {
        actionModeViews.add(actionMode.addItemWithWidth(save_to, R.drawable.msg_download, AndroidUtilities.dp(54), LocaleController.getString("SaveToMusic", R.string.SaveToMusic)));
        actionModeViews.add(actionMode.addItemWithWidth(edit, R.drawable.msg_edit, AndroidUtilities.dp(54), LocaleController.getString("Edit", R.string.Edit)));
        actionModeViews.add(actionMode.addItemWithWidth(star, R.drawable.msg_fave, AndroidUtilities.dp(54), LocaleController.getString("AddToFavorites", R.string.AddToFavorites)));
        actionModeViews.add(actionMode.addItemWithWidth(copy, R.drawable.msg_copy, AndroidUtilities.dp(54), LocaleController.getString("Copy", R.string.Copy)));
        actionModeViews.add(actionMode.addItemWithWidth(forward, R.drawable.msg_forward, AndroidUtilities.dp(54), LocaleController.getString("Forward", R.string.Forward)));
        actionModeViews.add(actionMode.addItemWithWidth(delete, R.drawable.msg_delete, AndroidUtilities.dp(54), LocaleController.getString("Delete", R.string.Delete)));
    } else {
        actionModeViews.add(actionMode.addItemWithWidth(edit, R.drawable.msg_edit, AndroidUtilities.dp(54), LocaleController.getString("Edit", R.string.Edit)));
        actionModeViews.add(actionMode.addItemWithWidth(star, R.drawable.msg_fave, AndroidUtilities.dp(54), LocaleController.getString("AddToFavorites", R.string.AddToFavorites)));
        actionModeViews.add(actionMode.addItemWithWidth(copy, R.drawable.msg_copy, AndroidUtilities.dp(54), LocaleController.getString("Copy", R.string.Copy)));
        actionModeViews.add(actionMode.addItemWithWidth(delete, R.drawable.msg_delete, AndroidUtilities.dp(54), LocaleController.getString("Delete", R.string.Delete)));
    }
    actionMode.getItem(edit).setVisibility(canEditMessagesCount == 1 && selectedMessagesIds[0].size() + selectedMessagesIds[1].size() == 1 ? View.VISIBLE : View.GONE);
    actionMode.getItem(copy).setVisibility(!getMessagesController().isChatNoForwards(currentChat) && selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0 ? View.VISIBLE : View.GONE);
    actionMode.getItem(star).setVisibility(selectedMessagesCanStarIds[0].size() + selectedMessagesCanStarIds[1].size() != 0 ? View.VISIBLE : View.GONE);
    actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
    checkActionBarMenu(false);
    scrimPaint = new Paint();
    fragmentView = new SizeNotifierFrameLayout(context, parentLayout) {

        int inputFieldHeight = 0;

        int lastHeight;

        int lastWidth;

        ArrayList<ChatMessageCell> drawTimeAfter = new ArrayList<>();

        ArrayList<ChatMessageCell> drawNamesAfter = new ArrayList<>();

        ArrayList<ChatMessageCell> drawCaptionAfter = new ArrayList<>();

        Paint backgroundPaint;

        int backgroundColor;

        @Override
        protected void drawList(Canvas blurCanvas, boolean top) {
            float cilpTop = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
            for (int i = 0; i < chatListView.getChildCount(); i++) {
                View child = chatListView.getChildAt(i);
                if (top && child.getY() > cilpTop + AndroidUtilities.dp(40)) {
                    continue;
                }
                if (!top && child.getY() + child.getMeasuredHeight() < AndroidUtilities.dp(203)) {
                    continue;
                }
                blurCanvas.save();
                blurCanvas.translate(chatListView.getX() + child.getX(), chatListView.getY() + child.getY());
                child.draw(blurCanvas);
                blurCanvas.restore();
            }
        }

        @Override
        protected int getScrollOffset() {
            return chatListView.computeVerticalScrollOffset();
        }

        @Override
        protected float getBottomOffset() {
            return chatListView.getBottom();
        }

        AdjustPanLayoutHelper adjustPanLayoutHelper = new AdjustPanLayoutHelper(this) {

            @Override
            protected void onTransitionStart(boolean keyboardVisible, int contentHeight) {
                wasManualScroll = true;
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.onAdjustPanTransitionStart(keyboardVisible);
                }
            }

            @Override
            protected void onTransitionEnd() {
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.onAdjustPanTransitionEnd();
                }
            }

            @Override
            protected void onPanTranslationUpdate(float y, float progress, boolean keyboardVisible) {
                if (getParentLayout() != null && getParentLayout().isPreviewOpenAnimationInProgress()) {
                    return;
                }
                contentPanTranslation = y;
                if (chatAttachAlert != null && chatAttachAlert.isShowing()) {
                    setNonNoveTranslation(y);
                } else {
                    actionBar.setTranslationY(y);
                    emptyViewContainer.setTranslationY(y / 2);
                    progressView.setTranslationY(y / 2);
                    contentView.setBackgroundTranslation((int) y);
                    instantCameraView.onPanTranslationUpdate(y);
                    if (blurredView != null) {
                        blurredView.drawable.onPanTranslationUpdate(y);
                    }
                    setFragmentPanTranslationOffset((int) y);
                    invalidateChatListViewTopPadding();
                    invalidateMessagesVisiblePart();
                }
                chatListView.invalidate();
                updateBulletinLayout();
            }

            @Override
            protected boolean heightAnimationEnabled() {
                ActionBarLayout actionBarLayout = getParentLayout();
                if (inPreviewMode || inBubbleMode || AndroidUtilities.isInMultiwindow || actionBarLayout == null || fixedKeyboardHeight > 0) {
                    return false;
                }
                if (System.currentTimeMillis() - activityResumeTime < 250) {
                    return false;
                }
                if ((ChatActivity.this == actionBarLayout.getLastFragment() && actionBarLayout.isTransitionAnimationInProgress()) || actionBarLayout.isPreviewOpenAnimationInProgress() || isPaused || !openAnimationEnded || (chatAttachAlert != null && chatAttachAlert.isShowing())) {
                    return false;
                }
                if (chatActivityEnterView != null && chatActivityEnterView.getTrendingStickersAlert() != null && chatActivityEnterView.getTrendingStickersAlert().isShowing()) {
                    return false;
                }
                return true;
            }

            @Override
            protected int startOffset() {
                int keyboardSize = getKeyboardHeight();
                if (keyboardSize <= AndroidUtilities.dp(20) && chatActivityEnterView.isPopupShowing()) {
                    return chatActivityEnterView.getEmojiPadding();
                }
                return 0;
            }
        };

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            adjustPanLayoutHelper.onAttach();
            chatActivityEnterView.setAdjustPanLayoutHelper(adjustPanLayoutHelper);
            MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
            if (messageObject != null && (messageObject.isRoundVideo() || messageObject.isVideo()) && messageObject.eventId == 0 && messageObject.getDialogId() == dialog_id) {
                MediaController.getInstance().setTextureView(createTextureView(false), aspectRatioFrameLayout, videoPlayerContainer, true);
            }
            if (pullingDownDrawable != null) {
                pullingDownDrawable.onAttach();
            }
            emojiAnimationsOverlay.onAttachedToWindow();
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            adjustPanLayoutHelper.onDetach();
            if (pullingDownDrawable != null) {
                pullingDownDrawable.onDetach();
                pullingDownDrawable = null;
            }
            emojiAnimationsOverlay.onDetachedFromWindow();
            AndroidUtilities.runOnUIThread(() -> {
                ReactionsEffectOverlay.removeCurrent(true);
            });
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            float expandY;
            if (AndroidUtilities.isInMultiwindow || isInBubbleMode()) {
                expandY = chatActivityEnterView.getEmojiView() != null ? chatActivityEnterView.getEmojiView().getY() : chatActivityEnterView.getY();
            } else {
                expandY = chatActivityEnterView.getY();
            }
            if (scrimView != null || chatActivityEnterView != null && chatActivityEnterView.isStickersExpanded() && ev.getY() < expandY) {
                return false;
            }
            lastTouchY = ev.getY();
            TextSelectionHelper.TextSelectionOverlay selectionOverlay = textSelectionHelper.getOverlayView(context);
            ev.offsetLocation(-selectionOverlay.getX(), -selectionOverlay.getY());
            if (textSelectionHelper.isSelectionMode() && textSelectionHelper.getOverlayView(context).onTouchEvent(ev)) {
                return true;
            } else {
                ev.offsetLocation(selectionOverlay.getX(), selectionOverlay.getY());
            }
            if (selectionOverlay.checkOnTap(ev)) {
                ev.setAction(MotionEvent.ACTION_CANCEL);
            }
            if (ev.getAction() == MotionEvent.ACTION_DOWN && textSelectionHelper.isSelectionMode() && (ev.getY() < chatListView.getTop() || ev.getY() > chatListView.getBottom())) {
                ev.offsetLocation(-selectionOverlay.getX(), -selectionOverlay.getY());
                if (textSelectionHelper.getOverlayView(context).onTouchEvent(ev)) {
                    ev.offsetLocation(selectionOverlay.getX(), selectionOverlay.getY());
                    return super.dispatchTouchEvent(ev);
                } else {
                    return true;
                }
            }
            if (pinchToZoomHelper.isInOverlayMode()) {
                return pinchToZoomHelper.onTouchEvent(ev);
            }
            if (AvatarPreviewer.hasVisibleInstance()) {
                AvatarPreviewer.getInstance().onTouchEvent(ev);
                return true;
            }
            return super.dispatchTouchEvent(ev);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) != null) {
                return;
            }
            if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) == null && (instantCameraView.blurFullyDrawing() || (blurredView != null && blurredView.fullyDrawing() && blurredView.getTag() != null))) {
                return;
            }
            super.onDraw(canvas);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            if ((scrimView != null || messageEnterTransitionContainer.isRunning()) && (child == pagedownButton || child == mentiondownButton || child == floatingDateView || child == fireworksOverlay || child == reactionsMentiondownButton || child == gifHintTextView)) {
                return false;
            }
            if (child == fragmentContextView && fragmentContextView.isCallStyle()) {
                return true;
            }
            if (child == undoView && PhotoViewer.getInstance().isVisible()) {
                return true;
            }
            if (toPullingDownTransition && child == chatListView) {
                return true;
            }
            if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) != null) {
                boolean needBlur;
                if (((int) getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND)) == BlurBehindDrawable.STATIC_CONTENT) {
                    needBlur = child == actionBar || child == fragmentContextView || child == pinnedMessageView;
                } else {
                    needBlur = child == chatListView || child == chatActivityEnterView || chatActivityEnterView.isPopupView(child);
                }
                if (!needBlur) {
                    return false;
                }
            } else if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) == null && (instantCameraView.blurFullyDrawing() || (blurredView != null && blurredView.fullyDrawing() && blurredView.getTag() != null))) {
                boolean needBlur = child == actionBar || child == chatListView || child == pinnedMessageView || child == fragmentContextView;
                if (needBlur) {
                    return false;
                }
            }
            boolean result;
            MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
            boolean isRoundVideo = false;
            boolean isVideo = messageObject != null && messageObject.eventId == 0 && ((isRoundVideo = messageObject.isRoundVideo()) || messageObject.isVideo());
            if (child == videoPlayerContainer) {
                canvas.save();
                float transitionOffset = 0;
                if (pullingDownAnimateProgress != 0) {
                    transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
                }
                canvas.translate(0, -pullingDownOffset - transitionOffset);
                if (messageObject != null && messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
                    if (Theme.chat_roundVideoShadow != null && aspectRatioFrameLayout.isDrawingReady()) {
                        int x = (int) child.getX() - AndroidUtilities.dp(3);
                        int y = (int) child.getY() - AndroidUtilities.dp(2);
                        canvas.save();
                        canvas.scale(videoPlayerContainer.getScaleX(), videoPlayerContainer.getScaleY(), child.getX(), child.getY());
                        Theme.chat_roundVideoShadow.setAlpha(255);
                        Theme.chat_roundVideoShadow.setBounds(x, y, x + AndroidUtilities.roundPlayingMessageSize + AndroidUtilities.dp(6), y + AndroidUtilities.roundPlayingMessageSize + AndroidUtilities.dp(6));
                        Theme.chat_roundVideoShadow.draw(canvas);
                        canvas.restore();
                    }
                    result = super.drawChild(canvas, child, drawingTime);
                } else {
                    if (child.getTag() == null) {
                        float oldTranslation = child.getTranslationY();
                        child.setTranslationY(-AndroidUtilities.dp(1000));
                        result = super.drawChild(canvas, child, drawingTime);
                        child.setTranslationY(oldTranslation);
                    } else {
                        result = false;
                    }
                }
                canvas.restore();
            } else {
                result = super.drawChild(canvas, child, drawingTime);
                if (isVideo && child == chatListView && messageObject.type != 5 && videoPlayerContainer != null && videoPlayerContainer.getTag() != null) {
                    canvas.save();
                    float transitionOffset = 0;
                    if (pullingDownAnimateProgress != 0) {
                        transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
                    }
                    canvas.translate(0, -pullingDownOffset - transitionOffset);
                    super.drawChild(canvas, videoPlayerContainer, drawingTime);
                    if (drawLaterRoundProgressCell != null) {
                        canvas.save();
                        canvas.translate(drawLaterRoundProgressCell.getX(), drawLaterRoundProgressCell.getTop() + chatListView.getY());
                        if (isRoundVideo) {
                            drawLaterRoundProgressCell.drawRoundProgress(canvas);
                            invalidate();
                            drawLaterRoundProgressCell.invalidate();
                        } else {
                            drawLaterRoundProgressCell.drawOverlays(canvas);
                            if (drawLaterRoundProgressCell.needDrawTime()) {
                                drawLaterRoundProgressCell.drawTime(canvas, drawLaterRoundProgressCell.getAlpha(), true);
                            }
                        }
                        canvas.restore();
                    }
                    canvas.restore();
                }
            }
            if (child == actionBar && parentLayout != null) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? (int) actionBar.getTranslationY() + actionBar.getMeasuredHeight() + (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) : 0);
            }
            return result;
        }

        @Override
        protected boolean isActionBarVisible() {
            return actionBar.getVisibility() == VISIBLE;
        }

        private void drawChildElement(Canvas canvas, float listTop, ChatMessageCell cell, int type) {
            canvas.save();
            float canvasOffsetX = chatListView.getLeft() + cell.getLeft();
            float canvasOffsetY = chatListView.getY() + cell.getY();
            float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
            canvas.clipRect(chatListView.getLeft(), listTop, chatListView.getRight(), chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset);
            canvas.translate(canvasOffsetX, canvasOffsetY);
            cell.setInvalidatesParent(true);
            if (type == 0) {
                cell.drawTime(canvas, alpha, true);
            } else if (type == 1) {
                cell.drawNamesLayout(canvas, alpha);
            } else {
                cell.drawCaptionLayout(canvas, cell.getCurrentPosition() != null && (cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_LEFT) == 0, alpha);
            }
            cell.setInvalidatesParent(false);
            canvas.restore();
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            chatActivityEnterView.checkAnimation();
            updateChatListViewTopPadding();
            if (invalidateMessagesVisiblePart || (chatListItemAnimator != null && chatListItemAnimator.isRunning())) {
                invalidateMessagesVisiblePart = false;
                updateMessagesVisiblePart(false);
            }
            updateTextureViewPosition(false);
            updatePagedownButtonsPosition();
            super.dispatchDraw(canvas);
            if (fragmentContextView != null && fragmentContextView.isCallStyle()) {
                float alpha = (blurredView != null && blurredView.getVisibility() == View.VISIBLE) ? 1f - blurredView.getAlpha() : 1f;
                if (alpha > 0) {
                    if (alpha == 1f) {
                        canvas.save();
                    } else {
                        canvas.saveLayerAlpha(fragmentContextView.getX(), fragmentContextView.getY() - AndroidUtilities.dp(30), fragmentContextView.getX() + fragmentContextView.getMeasuredWidth(), fragmentContextView.getY() + fragmentContextView.getMeasuredHeight(), (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
                    }
                    canvas.translate(fragmentContextView.getX(), fragmentContextView.getY());
                    fragmentContextView.setDrawOverlay(true);
                    fragmentContextView.draw(canvas);
                    fragmentContextView.setDrawOverlay(false);
                    canvas.restore();
                }
            }
            if (chatActivityEnterView != null) {
                if (chatActivityEnterView.pannelAniamationInProgress() && chatActivityEnterView.getEmojiPadding() < bottomPanelTranslationY) {
                    int color = getThemedColor(Theme.key_chat_emojiPanelBackground);
                    if (backgroundPaint == null) {
                        backgroundPaint = new Paint();
                    }
                    if (backgroundColor != color) {
                        backgroundPaint.setColor(backgroundColor = color);
                    }
                    int offset = (int) (bottomPanelTranslationY - chatActivityEnterView.getEmojiPadding()) + 3;
                    canvas.drawRect(0, getMeasuredHeight() - offset, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
                    setFragmentPanTranslationOffset(chatActivityEnterView.getEmojiPadding());
                }
            }
            for (int a = 0, N = animateSendingViews.size(); a < N; a++) {
                ChatMessageCell cell = animateSendingViews.get(a);
                MessageObject.SendAnimationData data = cell.getMessageObject().sendAnimationData;
                if (data != null) {
                    canvas.save();
                    ImageReceiver imageReceiver = cell.getPhotoImage();
                    canvas.translate(data.currentX, data.currentY);
                    canvas.scale(data.currentScale, data.currentScale);
                    canvas.translate(-imageReceiver.getCenterX(), -imageReceiver.getCenterY());
                    cell.setTimeAlpha(data.timeAlpha);
                    animateSendingViews.get(a).draw(canvas);
                    canvas.restore();
                }
            }
            if (scrimViewReaction == null || scrimView == null) {
                scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (scrimView != null ? scrimViewAlpha : 1f)));
                canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
            }
            if (scrimView != null) {
                if (scrimView == reactionsMentiondownButton || scrimView == mentiondownButton) {
                    if (scrimViewAlpha < 1f) {
                        scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
                        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
                    }
                } else if (scrimView instanceof ImageView) {
                    int c = canvas.save();
                    if (scrimViewAlpha < 1f) {
                        canvas.saveLayerAlpha(scrimView.getLeft(), scrimView.getTop(), scrimView.getRight(), scrimView.getBottom(), (int) (255 * scrimViewAlpha), Canvas.ALL_SAVE_FLAG);
                    }
                    canvas.translate(scrimView.getLeft(), scrimView.getTop());
                    if (scrimView == actionBar.getBackButton()) {
                        int r = Math.max(scrimView.getMeasuredWidth(), scrimView.getMeasuredHeight()) / 2;
                        canvas.drawCircle(r, r, r * 0.8f, actionBarBackgroundPaint);
                    }
                    scrimView.draw(canvas);
                    canvas.restoreToCount(c);
                    if (scrimViewAlpha < 1f) {
                        scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
                        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
                    }
                } else {
                    float listTop = chatListView.getY() + chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
                    MessageObject.GroupedMessages scrimGroup;
                    if (scrimView instanceof ChatMessageCell) {
                        scrimGroup = ((ChatMessageCell) scrimView).getCurrentMessagesGroup();
                    } else {
                        scrimGroup = null;
                    }
                    boolean groupedBackgroundWasDraw = false;
                    int count = chatListView.getChildCount();
                    for (int num = 0; num < count; num++) {
                        View child = chatListView.getChildAt(num);
                        MessageObject.GroupedMessages group;
                        MessageObject.GroupedMessagePosition position;
                        ChatMessageCell cell;
                        if (child instanceof ChatMessageCell) {
                            cell = (ChatMessageCell) child;
                            group = cell.getCurrentMessagesGroup();
                            position = cell.getCurrentPosition();
                        } else {
                            position = null;
                            group = null;
                            cell = null;
                        }
                        if (child != scrimView && (scrimGroup == null || scrimGroup != group) || child.getAlpha() == 0f) {
                            continue;
                        }
                        if (!groupedBackgroundWasDraw && cell != null && scrimGroup != null && scrimGroup.transitionParams.cell != null) {
                            float x = scrimGroup.transitionParams.cell.getNonAnimationTranslationX(true);
                            float l = (scrimGroup.transitionParams.left + x + scrimGroup.transitionParams.offsetLeft);
                            float t = (scrimGroup.transitionParams.top + scrimGroup.transitionParams.offsetTop);
                            float r = (scrimGroup.transitionParams.right + x + scrimGroup.transitionParams.offsetRight);
                            float b = (scrimGroup.transitionParams.bottom + scrimGroup.transitionParams.offsetBottom);
                            if (!scrimGroup.transitionParams.backgroundChangeBounds) {
                                t += scrimGroup.transitionParams.cell.getTranslationY();
                                b += scrimGroup.transitionParams.cell.getTranslationY();
                            }
                            if (t < chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20)) {
                                t = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20);
                            }
                            if (b > chatListView.getMeasuredHeight() + AndroidUtilities.dp(20)) {
                                b = chatListView.getMeasuredHeight() + AndroidUtilities.dp(20);
                            }
                            boolean selected = true;
                            for (int a = 0, N = scrimGroup.messages.size(); a < N; a++) {
                                MessageObject object = scrimGroup.messages.get(a);
                                int index = object.getDialogId() == dialog_id ? 0 : 1;
                                if (selectedMessagesIds[index].indexOfKey(object.getId()) < 0) {
                                    selected = false;
                                    break;
                                }
                            }
                            canvas.save();
                            canvas.clipRect(0, listTop, getMeasuredWidth(), chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset);
                            canvas.translate(0, chatListView.getY());
                            scrimGroup.transitionParams.cell.drawBackground(canvas, (int) l, (int) t, (int) r, (int) b, scrimGroup.transitionParams.pinnedTop, scrimGroup.transitionParams.pinnedBotton, selected, contentView.getKeyboardHeight());
                            canvas.restore();
                            groupedBackgroundWasDraw = true;
                        }
                        if (cell != null && cell.getPhotoImage().isAnimationRunning()) {
                            invalidate();
                        }
                        float viewClipLeft = chatListView.getLeft();
                        float viewClipTop = listTop;
                        float viewClipRight = chatListView.getRight();
                        float viewClipBottom = chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset;
                        if (cell == null || !cell.getTransitionParams().animateBackgroundBoundsInner) {
                            viewClipLeft = Math.max(viewClipLeft, chatListView.getLeft() + child.getX());
                            viewClipTop = Math.max(viewClipTop, chatListView.getTop() + child.getY());
                            viewClipRight = Math.min(viewClipRight, chatListView.getLeft() + child.getX() + child.getMeasuredWidth());
                            viewClipBottom = Math.min(viewClipBottom, chatListView.getY() + child.getY() + child.getMeasuredHeight());
                        }
                        if (viewClipTop < viewClipBottom) {
                            if (child.getAlpha() != 1f) {
                                canvas.saveLayerAlpha(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom, (int) (255 * child.getAlpha()), Canvas.ALL_SAVE_FLAG);
                            } else {
                                canvas.save();
                            }
                            if (cell != null) {
                                cell.setInvalidatesParent(true);
                                cell.setScrimReaction(scrimViewReaction);
                            }
                            canvas.clipRect(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom);
                            canvas.translate(chatListView.getLeft() + child.getX(), chatListView.getY() + child.getY());
                            if (cell != null && scrimGroup == null && cell.drawBackgroundInParent()) {
                                cell.drawBackgroundInternal(canvas, true);
                            }
                            child.draw(canvas);
                            if (cell != null && cell.hasOutboundsContent()) {
                                cell.drawOutboundsContent(canvas);
                            }
                            canvas.restore();
                            if (cell != null) {
                                cell.setInvalidatesParent(false);
                                cell.setScrimReaction(null);
                            }
                        }
                        if (position != null || (cell != null && cell.getTransitionParams().animateBackgroundBoundsInner)) {
                            if (position == null || position.last || position.minX == 0 && position.minY == 0) {
                                if (position == null || position.last) {
                                    drawTimeAfter.add(cell);
                                }
                                if (position == null || (position.minX == 0 && position.minY == 0 && cell.hasNameLayout())) {
                                    drawNamesAfter.add(cell);
                                }
                            }
                            if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
                                drawCaptionAfter.add(cell);
                            }
                        }
                        if (scrimViewReaction != null && cell != null) {
                            scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * scrimViewAlpha));
                            canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
                            if (viewClipTop < viewClipBottom) {
                                float alpha = child.getAlpha() * scrimViewAlpha;
                                if (alpha < 1f) {
                                    canvas.saveLayerAlpha(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom, (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
                                } else {
                                    canvas.save();
                                }
                                canvas.clipRect(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom);
                                canvas.translate(chatListView.getLeft() + child.getX(), chatListView.getY() + child.getY());
                                cell.drawScrimReaction(canvas, scrimViewReaction);
                                canvas.restore();
                            }
                        }
                    }
                    int size = drawTimeAfter.size();
                    if (size > 0) {
                        for (int a = 0; a < size; a++) {
                            drawChildElement(canvas, listTop, drawTimeAfter.get(a), 0);
                        }
                        drawTimeAfter.clear();
                    }
                    size = drawNamesAfter.size();
                    if (size > 0) {
                        for (int a = 0; a < size; a++) {
                            drawChildElement(canvas, listTop, drawNamesAfter.get(a), 1);
                        }
                        drawNamesAfter.clear();
                    }
                    size = drawCaptionAfter.size();
                    if (size > 0) {
                        for (int a = 0; a < size; a++) {
                            ChatMessageCell cell = drawCaptionAfter.get(a);
                            if (cell.getCurrentPosition() == null && !cell.getTransitionParams().animateBackgroundBoundsInner) {
                                continue;
                            }
                            drawChildElement(canvas, listTop, cell, 2);
                        }
                        drawCaptionAfter.clear();
                    }
                }
                if (scrimViewReaction == null && scrimViewAlpha < 1f) {
                    scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
                    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
                }
            }
            if (scrimView != null || messageEnterTransitionContainer.isRunning()) {
                if (pagedownButton != null && pagedownButton.getTag() != null) {
                    super.drawChild(canvas, pagedownButton, SystemClock.uptimeMillis());
                }
                if (mentiondownButton != null && mentiondownButton.getTag() != null) {
                    super.drawChild(canvas, mentiondownButton, SystemClock.uptimeMillis());
                }
                if (reactionsMentiondownButton != null && reactionsMentiondownButton.getTag() != null) {
                    super.drawChild(canvas, reactionsMentiondownButton, SystemClock.uptimeMillis());
                }
                if (floatingDateView != null && floatingDateView.getTag() != null) {
                    super.drawChild(canvas, floatingDateView, SystemClock.uptimeMillis());
                }
                if (fireworksOverlay != null) {
                    super.drawChild(canvas, fireworksOverlay, SystemClock.uptimeMillis());
                }
                if (gifHintTextView != null) {
                    super.drawChild(canvas, gifHintTextView, SystemClock.uptimeMillis());
                }
            }
            if (fixedKeyboardHeight > 0 && keyboardHeight < AndroidUtilities.dp(20)) {
                int color = getThemedColor(Theme.key_windowBackgroundWhite);
                if (backgroundPaint == null) {
                    backgroundPaint = new Paint();
                }
                if (backgroundColor != color) {
                    backgroundPaint.setColor(backgroundColor = color);
                }
                canvas.drawRect(0, getMeasuredHeight() - fixedKeyboardHeight, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
            }
            if (pullingDownDrawable != null && pullingDownDrawable.needDrawBottomPanel()) {
                int top, bottom;
                if (chatActivityEnterView != null && chatActivityEnterView.getVisibility() == View.VISIBLE) {
                    top = chatActivityEnterView.getTop() + AndroidUtilities.dp2(2);
                    bottom = chatActivityEnterView.getBottom();
                } else {
                    top = bottomOverlayChat.getTop() + AndroidUtilities.dp2(2);
                    bottom = bottomOverlayChat.getBottom();
                }
                pullingDownDrawable.drawBottomPanel(canvas, top, bottom, getMeasuredWidth());
            }
            if (pullingDownAnimateToActivity != null) {
                canvas.saveLayerAlpha(0, 0, getMeasuredWidth(), getMeasuredHeight(), (int) (255 * pullingDownAnimateProgress), Canvas.ALL_SAVE_FLAG);
                pullingDownAnimateToActivity.fragmentView.draw(canvas);
                canvas.restore();
            }
            emojiAnimationsOverlay.draw(canvas);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int allHeight;
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = allHeight = MeasureSpec.getSize(heightMeasureSpec);
            if (lastWidth != widthSize) {
                globalIgnoreLayout = true;
                lastWidth = widthMeasureSpec;
                if (!inPreviewMode && currentUser != null && currentUser.self) {
                    SimpleTextView textView = avatarContainer.getTitleTextView();
                    int textWidth = (int) textView.getPaint().measureText(textView.getText(), 0, textView.getText().length());
                    if (widthSize - AndroidUtilities.dp(96 + 56) > textWidth + AndroidUtilities.dp(10)) {
                        showSearchAsIcon = !showAudioCallAsIcon;
                    } else {
                        showSearchAsIcon = false;
                    }
                } else {
                    showSearchAsIcon = false;
                }
                if (showSearchAsIcon || showAudioCallAsIcon) {
                    if (avatarContainer != null && avatarContainer.getLayoutParams() != null) {
                        ((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(96);
                    }
                } else {
                    if (avatarContainer != null && avatarContainer.getLayoutParams() != null) {
                        ((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(40);
                    }
                }
                if (showSearchAsIcon) {
                    if (!actionBar.isSearchFieldVisible() && searchIconItem != null) {
                        searchIconItem.setVisibility(View.VISIBLE);
                    }
                    if (headerItem != null) {
                        headerItem.hideSubItem(search);
                    }
                } else {
                    if (headerItem != null) {
                        headerItem.showSubItem(search);
                    }
                    if (searchIconItem != null) {
                        searchIconItem.setVisibility(View.GONE);
                    }
                }
                if (!actionBar.isSearchFieldVisible() && audioCallIconItem != null) {
                    audioCallIconItem.setVisibility((showAudioCallAsIcon && !showSearchAsIcon) ? View.VISIBLE : View.GONE);
                }
                if (headerItem != null) {
                    TLRPC.UserFull userInfo = getCurrentUserInfo();
                    if (showAudioCallAsIcon) {
                        headerItem.hideSubItem(call);
                    } else if (userInfo != null && userInfo.phone_calls_available) {
                        headerItem.showSubItem(call);
                    }
                }
                globalIgnoreLayout = false;
            }
            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();
            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            if (actionBar.getVisibility() == VISIBLE) {
                heightSize -= actionBarHeight;
            }
            int keyboardHeightOld = keyboardHeight + chatEmojiViewPadding;
            boolean keyboardVisibleOld = keyboardHeight + chatEmojiViewPadding >= AndroidUtilities.dp(20);
            if (lastHeight != allHeight) {
                measureKeyboardHeight();
            }
            int keyboardSize = getKeyboardHeight();
            if (fixedKeyboardHeight > 0 && keyboardSize <= AndroidUtilities.dp(20)) {
                chatEmojiViewPadding = fixedKeyboardHeight;
            } else {
                if (keyboardSize <= AndroidUtilities.dp(20)) {
                    chatEmojiViewPadding = chatActivityEnterView.isPopupShowing() ? chatActivityEnterView.getEmojiPadding() : 0;
                } else {
                    chatEmojiViewPadding = 0;
                }
            }
            setEmojiKeyboardHeight(chatEmojiViewPadding);
            boolean keyboardVisible = keyboardHeight + chatEmojiViewPadding >= AndroidUtilities.dp(20);
            boolean waitingChatListItemAnimator = false;
            if (MediaController.getInstance().getPlayingMessageObject() != null && MediaController.getInstance().getPlayingMessageObject().isRoundVideo() && keyboardVisibleOld != keyboardVisible) {
                for (int i = 0; i < chatListView.getChildCount(); i++) {
                    View child = chatListView.getChildAt(i);
                    if (child instanceof ChatMessageCell) {
                        MessageObject messageObject = ((ChatMessageCell) child).getMessageObject();
                        if (messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) {
                            int p = chatListView.getChildAdapterPosition(child);
                            if (p >= 0) {
                                chatLayoutManager.scrollToPositionWithOffset(p, (int) ((chatListView.getMeasuredHeight() - chatListViewPaddingTop + (keyboardHeight + chatEmojiViewPadding - keyboardHeightOld) - (keyboardVisible ? AndroidUtilities.roundMessageSize : AndroidUtilities.roundPlayingMessageSize)) / 2), false);
                                chatAdapter.notifyItemChanged(p);
                                adjustPanLayoutHelper.delayAnimation();
                                waitingChatListItemAnimator = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (!waitingChatListItemAnimator) {
                chatActivityEnterView.runEmojiPanelAnimation();
            }
            int childCount = getChildCount();
            measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int listViewTopHeight;
            if (inPreviewMode) {
                inputFieldHeight = 0;
                listViewTopHeight = 0;
            } else {
                inputFieldHeight = chatActivityEnterView.getMeasuredHeight();
                listViewTopHeight = AndroidUtilities.dp(49);
            }
            blurredViewTopOffset = 0;
            blurredViewBottomOffset = 0;
            if (SharedConfig.chatBlurEnabled()) {
                blurredViewTopOffset = actionBarHeight;
                blurredViewBottomOffset = AndroidUtilities.dp(203);
            }
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView || child == actionBar) {
                    continue;
                }
                if (child == backgroundView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == blurredView) {
                    int h = allHeight;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        h += keyboardSize;
                    }
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == chatListView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int h = heightSize - listViewTopHeight - (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) + blurredViewTopOffset + blurredViewBottomOffset;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        h += keyboardSize;
                    }
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), h), MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == progressView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), heightSize - inputFieldHeight - (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) + AndroidUtilities.dp(2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))), MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == instantCameraView || child == overlayView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight - inputFieldHeight - chatEmojiViewPadding + AndroidUtilities.dp(3), MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == emptyViewContainer) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == messagesSearchListView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight - actionBarHeight - AndroidUtilities.dp(48), MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (inBubbleMode) {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - inputFieldHeight + actionBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
                    } else if (AndroidUtilities.isInMultiwindow) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320), heightSize - inputFieldHeight + actionBarHeight - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - inputFieldHeight + actionBarHeight - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else if (child == mentionContainer) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer.getLayoutParams();
                    if (mentionsAdapter.isBannedInline()) {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST));
                    } else {
                        int height;
                        mentionListViewIgnoreLayout = true;
                        if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
                            int size = mentionGridLayoutManager.getRowsCount(widthSize);
                            int maxHeight = size * 102;
                            if (mentionsAdapter.isBotContext()) {
                                if (mentionsAdapter.getBotContextSwitch() != null) {
                                    maxHeight += 34;
                                }
                            }
                            height = heightSize - chatActivityEnterView.getMeasuredHeight() + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                            int padding = Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f)));
                            if (mentionLayoutManager.getReverseLayout()) {
                                mentionListView.setPadding(0, 0, 0, padding);
                            } else {
                                mentionListView.setPadding(0, padding, 0, 0);
                            }
                        } else {
                            int size = mentionsAdapter.getItemCount();
                            int maxHeight = 0;
                            if (mentionsAdapter.isBotContext()) {
                                if (mentionsAdapter.getBotContextSwitch() != null) {
                                    maxHeight += 36;
                                    size -= 1;
                                }
                                maxHeight += size * 68;
                            } else {
                                maxHeight += size * 36;
                            }
                            height = heightSize - chatActivityEnterView.getMeasuredHeight() + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                            int padding = Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f)));
                            if (mentionLayoutManager.getReverseLayout()) {
                                mentionListView.setPadding(0, 0, 0, padding);
                            } else {
                                mentionListView.setPadding(0, padding, 0, 0);
                            }
                        }
                        layoutParams.height = height;
                        layoutParams.topMargin = 0;
                        mentionListViewIgnoreLayout = false;
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
                    }
                } else if (child == textSelectionHelper.getOverlayView(context)) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int h = heightSize + blurredViewTopOffset;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        h += keyboardSize;
                        textSelectionHelper.setKeyboardSize(keyboardSize);
                    } else {
                        textSelectionHelper.setKeyboardSize(0);
                    }
                    child.measure(contentWidthSpec, MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
                } else if (child == forwardingPreviewView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int h = allHeight - AndroidUtilities.statusBarHeight;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        h += keyboardSize;
                    }
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
            if (fixPaddingsInLayout) {
                globalIgnoreLayout = true;
                invalidateChatListViewTopPadding();
                invalidateMessagesVisiblePart();
                fixPaddingsInLayout = false;
                chatListView.measure(MeasureSpec.makeMeasureSpec(chatListView.getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(chatListView.getMeasuredHeight(), MeasureSpec.EXACTLY));
                globalIgnoreLayout = false;
            }
            if (scrollToPositionOnRecreate != -1) {
                final int scrollTo = scrollToPositionOnRecreate;
                AndroidUtilities.runOnUIThread(() -> chatLayoutManager.scrollToPositionWithOffset(scrollTo, scrollToOffsetOnRecreate));
                scrollToPositionOnRecreate = -1;
            }
            updateBulletinLayout();
            lastHeight = allHeight;
        }

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

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();
            int keyboardSize = getKeyboardHeight();
            int paddingBottom;
            if (fixedKeyboardHeight > 0 && keyboardSize <= AndroidUtilities.dp(20)) {
                paddingBottom = fixedKeyboardHeight;
            } else {
                paddingBottom = keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !inBubbleMode ? chatActivityEnterView.getEmojiPadding() : 0;
            }
            if (!SharedConfig.smoothKeyboard) {
                setBottomClip(paddingBottom);
            }
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();
                int childLeft;
                int childTop;
                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }
                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
                switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        childLeft = r - width - lp.rightMargin;
                        break;
                    case Gravity.LEFT:
                    default:
                        childLeft = lp.leftMargin;
                }
                switch(verticalGravity) {
                    case Gravity.TOP:
                        childTop = lp.topMargin + getPaddingTop();
                        if (child != actionBar && actionBar.getVisibility() == VISIBLE) {
                            childTop += actionBar.getMeasuredHeight();
                            if (inPreviewMode && Build.VERSION.SDK_INT >= 21) {
                                childTop += AndroidUtilities.statusBarHeight;
                            }
                        }
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = lp.topMargin;
                }
                if (child == blurredView || child == backgroundView) {
                    childTop = 0;
                } else if (child instanceof HintView || child instanceof ChecksHintView) {
                    childTop = 0;
                } else if (child == mentionContainer) {
                    childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
                } else if (child == pagedownButton || child == mentiondownButton || child == reactionsMentiondownButton) {
                    if (!inPreviewMode) {
                        childTop -= chatActivityEnterView.getMeasuredHeight();
                    }
                } else if (child == emptyViewContainer) {
                    childTop -= inputFieldHeight / 2 - (actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() / 2 : 0);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow || inBubbleMode) {
                        childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight() + AndroidUtilities.dp(1);
                    } else {
                        childTop = chatActivityEnterView.getBottom();
                    }
                } else if (child == gifHintTextView || child == voiceHintTextView || child == mediaBanTooltip) {
                    childTop -= inputFieldHeight;
                } else if (child == chatListView || child == floatingDateView || child == infoTopView) {
                    childTop -= blurredViewTopOffset;
                    if (!inPreviewMode) {
                        childTop -= (inputFieldHeight - AndroidUtilities.dp(51));
                    }
                    childTop -= paddingBottom;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        childTop -= keyboardSize;
                    }
                } else if (child == progressView) {
                    if (chatActivityEnterView.isTopViewVisible()) {
                        childTop -= AndroidUtilities.dp(48);
                    }
                } else if (child == actionBar) {
                    if (inPreviewMode && Build.VERSION.SDK_INT >= 21) {
                        childTop += AndroidUtilities.statusBarHeight;
                    }
                    childTop -= getPaddingTop();
                } else if (child == videoPlayerContainer) {
                    childTop = actionBar.getMeasuredHeight();
                    childTop -= paddingBottom;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        childTop -= keyboardSize;
                    }
                } else if (child == instantCameraView || child == overlayView || child == animatingImageView) {
                    childTop = 0;
                } else if (child == textSelectionHelper.getOverlayView(context)) {
                    childTop -= paddingBottom;
                    if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
                        childTop -= keyboardSize;
                    }
                    childTop -= blurredViewTopOffset;
                } else if (chatActivityEnterView != null && child == chatActivityEnterView.botCommandsMenuContainer) {
                    childTop -= inputFieldHeight;
                } else if (child == forwardingPreviewView) {
                    childTop = AndroidUtilities.statusBarHeight;
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
            invalidateChatListViewTopPadding();
            invalidateMessagesVisiblePart();
            updateTextureViewPosition(false);
            if (!scrollingChatListView) {
                checkAutoDownloadMessages(false);
            }
            notifyHeightChanged();
        }

        private void setNonNoveTranslation(float y) {
            contentView.setTranslationY(y);
            actionBar.setTranslationY(0);
            emptyViewContainer.setTranslationY(0);
            progressView.setTranslationY(0);
            contentPanTranslation = 0;
            contentView.setBackgroundTranslation(0);
            instantCameraView.onPanTranslationUpdate(0);
            if (blurredView != null) {
                blurredView.drawable.onPanTranslationUpdate(0);
            }
            setFragmentPanTranslationOffset(0);
            invalidateChatListViewTopPadding();
        }

        @Override
        public void setPadding(int left, int top, int right, int bottom) {
            contentPaddingTop = top;
            invalidateChatListViewTopPadding();
            invalidateMessagesVisiblePart();
        }

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == 1 && forwardingPreviewView != null && forwardingPreviewView.isShowing()) {
                forwardingPreviewView.dismiss(true);
                return true;
            }
            return super.dispatchKeyEvent(event);
        }

        protected Drawable getNewDrawable() {
            Drawable drawable = themeDelegate.getWallpaperDrawable();
            return drawable != null ? drawable : super.getNewDrawable();
        }
    };
    contentView = (SizeNotifierFrameLayout) fragmentView;
    contentView.needBlur = true;
    if (inBubbleMode) {
        contentView.setOccupyStatusBar(false);
    }
    contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion());
    emptyViewContainer = new FrameLayout(context);
    emptyViewContainer.setVisibility(View.INVISIBLE);
    contentView.addView(emptyViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    emptyViewContainer.setOnTouchListener((v, event) -> true);
    int distance = getArguments().getInt("nearby_distance", -1);
    if ((distance >= 0 || preloadedGreetingsSticker != null) && currentUser != null && !userBlocked) {
        greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate);
        greetingsViewContainer.setListener((sticker) -> {
            animatingDocuments.put(sticker, 0);
            SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0);
        });
        greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
        emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0));
    } else if (currentEncryptedChat == null) {
        if (!isThreadChat() && chatMode == 0 && (currentUser != null && currentUser.self || currentChat != null && currentChat.creator)) {
            bigEmptyView = new ChatBigEmptyView(context, contentView, currentChat != null ? ChatBigEmptyView.EMPTY_VIEW_TYPE_GROUP : ChatBigEmptyView.EMPTY_VIEW_TYPE_SAVED, themeDelegate);
            emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
            if (currentChat != null) {
                bigEmptyView.setStatusText(AndroidUtilities.replaceTags(LocaleController.getString("GroupEmptyTitle1", R.string.GroupEmptyTitle1)));
            }
        } else {
            String emptyMessage = null;
            if (isThreadChat()) {
                if (isComments) {
                    emptyMessage = LocaleController.getString("NoComments", R.string.NoComments);
                } else {
                    emptyMessage = LocaleController.getString("NoReplies", R.string.NoReplies);
                }
            } else if (chatMode == MODE_SCHEDULED) {
                emptyMessage = LocaleController.getString("NoScheduledMessages", R.string.NoScheduledMessages);
            } else if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000 && currentUser.id != 4244000 && MessagesController.isSupportUser(currentUser)) {
                emptyMessage = LocaleController.getString("GotAQuestion", R.string.GotAQuestion);
            } else if (currentUser == null || currentUser.self || currentUser.deleted || userBlocked) {
                emptyMessage = LocaleController.getString("NoMessages", R.string.NoMessages);
            }
            if (emptyMessage == null) {
                greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate);
                greetingsViewContainer.setListener((sticker) -> {
                    animatingDocuments.put(sticker, 0);
                    SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0);
                });
                greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
                emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0));
            } else {
                emptyView = new TextView(context);
                emptyView.setText(emptyMessage);
                emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
                emptyView.setGravity(Gravity.CENTER);
                emptyView.setTextColor(getThemedColor(Theme.key_chat_serviceText));
                emptyView.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(6), emptyView, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
                emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
                emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10), AndroidUtilities.dp(3));
                emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
            }
        }
    } else {
        bigEmptyView = new ChatBigEmptyView(context, contentView, ChatBigEmptyView.EMPTY_VIEW_TYPE_SECRET, themeDelegate);
        if (currentEncryptedChat.admin_id == getUserConfig().getClientUserId()) {
            bigEmptyView.setStatusText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, UserObject.getFirstName(currentUser)));
        } else {
            bigEmptyView.setStatusText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, UserObject.getFirstName(currentUser)));
        }
        emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }
    CharSequence oldMessage;
    if (chatActivityEnterView != null) {
        chatActivityEnterView.onDestroy();
        if (!chatActivityEnterView.isEditingMessage()) {
            oldMessage = chatActivityEnterView.getFieldText();
        } else {
            oldMessage = null;
        }
    } else {
        oldMessage = null;
    }
    if (mentionsAdapter != null) {
        mentionsAdapter.onDestroy();
    }
    chatListView = new RecyclerListView(context, themeDelegate) {

        private int lastWidth;

        private final ArrayList<ChatMessageCell> drawTimeAfter = new ArrayList<>();

        private final ArrayList<ChatMessageCell> drawNamesAfter = new ArrayList<>();

        private final ArrayList<ChatMessageCell> drawCaptionAfter = new ArrayList<>();

        private final ArrayList<MessageObject.GroupedMessages> drawingGroups = new ArrayList<>(10);

        private boolean slideAnimationInProgress;

        private int startedTrackingX;

        private int startedTrackingY;

        private int startedTrackingPointerId;

        private long lastTrackingAnimationTime;

        private float trackAnimationProgress;

        private float endTrackingX;

        private boolean wasTrackingVibrate;

        private float replyButtonProgress;

        private long lastReplyButtonAnimationTime;

        private boolean ignoreLayout;

        int lastH = 0;

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

        @Override
        public void setTranslationY(float translationY) {
            if (translationY != getTranslationY()) {
                super.setTranslationY(translationY);
                if (emptyViewContainer != null) {
                    if (chatActivityEnterView != null && chatActivityEnterView.pannelAniamationInProgress()) {
                        emptyViewContainer.setTranslationY(translationY / 2f);
                    } else {
                        emptyViewContainer.setTranslationY(translationY / 1.7f);
                    }
                }
                if (chatActivityEnterView != null && chatActivityEnterView.botCommandsMenuContainer != null) {
                    chatActivityEnterView.botCommandsMenuContainer.setTranslationY(translationY);
                }
                invalidateChatListViewTopPadding();
                invalidateMessagesVisiblePart();
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            if (lastWidth != r - l) {
                lastWidth = r - l;
                hideHints(false);
            }
            int height = getMeasuredHeight();
            if (lastH != height) {
                ignoreLayout = true;
                if (chatListItemAnimator != null) {
                    chatListItemAnimator.endAnimations();
                }
                chatScrollHelper.cancel();
                ignoreLayout = false;
                lastH = height;
            }
            forceScrollToTop = false;
            if (textSelectionHelper != null && textSelectionHelper.isSelectionMode()) {
                textSelectionHelper.invalidate();
            }
        }

        private void setGroupTranslationX(ChatMessageCell view, float dx) {
            MessageObject.GroupedMessages group = view.getCurrentMessagesGroup();
            if (group == null) {
                return;
            }
            int count = getChildCount();
            for (int a = 0; a < count; a++) {
                View child = getChildAt(a);
                if (child == view || !(child instanceof ChatMessageCell)) {
                    continue;
                }
                ChatMessageCell cell = (ChatMessageCell) child;
                if (cell.getCurrentMessagesGroup() == group) {
                    cell.setSlidingOffset(dx);
                    cell.invalidate();
                }
            }
            invalidate();
        }

        @Override
        public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
            if (scrimPopupWindow != null) {
                return false;
            }
            return super.requestChildRectangleOnScreen(child, rect, immediate);
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent e) {
            textSelectionHelper.checkSelectionCancel(e);
            if (isFastScrollAnimationRunning()) {
                return false;
            }
            boolean result = super.onInterceptTouchEvent(e);
            if (actionBar.isActionModeShowed() || reportType >= 0) {
                return result;
            }
            processTouchEvent(e);
            return result;
        }

        @Override
        public void setItemAnimator(ItemAnimator animator) {
            if (isFastScrollAnimationRunning()) {
                return;
            }
            super.setItemAnimator(animator);
        }

        private void drawReplyButton(Canvas canvas) {
            if (slidingView == null) {
                return;
            }
            float translationX = slidingView.getNonAnimationTranslationX(false);
            long newTime = System.currentTimeMillis();
            long dt = Math.min(17, newTime - lastReplyButtonAnimationTime);
            lastReplyButtonAnimationTime = newTime;
            boolean showing;
            if (showing = (translationX <= -AndroidUtilities.dp(50))) {
                if (replyButtonProgress < 1.0f) {
                    replyButtonProgress += dt / 180.0f;
                    if (replyButtonProgress > 1.0f) {
                        replyButtonProgress = 1.0f;
                    } else {
                        invalidate();
                    }
                }
            } else {
                if (replyButtonProgress > 0.0f) {
                    replyButtonProgress -= dt / 180.0f;
                    if (replyButtonProgress < 0.0f) {
                        replyButtonProgress = 0;
                    } else {
                        invalidate();
                    }
                }
            }
            int alpha;
            int alpha2;
            Paint chatActionBackgroundPaint = getThemedPaint(Theme.key_paint_chatActionBackground);
            int oldAlpha = chatActionBackgroundPaint.getAlpha();
            float scale;
            if (showing) {
                if (replyButtonProgress <= 0.8f) {
                    scale = 1.2f * (replyButtonProgress / 0.8f);
                } else {
                    scale = 1.2f - 0.2f * ((replyButtonProgress - 0.8f) / 0.2f);
                }
                alpha = (int) Math.min(255, 255 * (replyButtonProgress / 0.8f));
                alpha2 = (int) Math.min(oldAlpha, oldAlpha * (replyButtonProgress / 0.8f));
            } else {
                scale = replyButtonProgress;
                alpha = (int) Math.min(255, 255 * replyButtonProgress);
                alpha2 = (int) Math.min(oldAlpha, oldAlpha * replyButtonProgress);
            }
            chatActionBackgroundPaint.setAlpha(alpha2);
            float x = getMeasuredWidth() + slidingView.getNonAnimationTranslationX(false) / 2;
            float y = slidingView.getTop() + slidingView.getMeasuredHeight() / 2;
            AndroidUtilities.rectTmp.set((int) (x - AndroidUtilities.dp(16) * scale), (int) (y - AndroidUtilities.dp(16) * scale), (int) (x + AndroidUtilities.dp(16) * scale), (int) (y + AndroidUtilities.dp(16) * scale));
            Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() + AndroidUtilities.rectTmp.top);
            canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), chatActionBackgroundPaint);
            if (themeDelegate.hasGradientService()) {
                canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundGradientDarkenPaint);
            }
            chatActionBackgroundPaint.setAlpha(oldAlpha);
            Drawable replyIconDrawable = getThemedDrawable(Theme.key_drawable_replyIcon);
            replyIconDrawable.setAlpha(alpha);
            replyIconDrawable.setBounds((int) (x - AndroidUtilities.dp(7) * scale), (int) (y - AndroidUtilities.dp(6) * scale), (int) (x + AndroidUtilities.dp(7) * scale), (int) (y + AndroidUtilities.dp(5) * scale));
            replyIconDrawable.draw(canvas);
            replyIconDrawable.setAlpha(255);
        }

        private void processTouchEvent(MotionEvent e) {
            if (e != null) {
                wasManualScroll = true;
            }
            if (e != null && e.getAction() == MotionEvent.ACTION_DOWN && !startedTrackingSlidingView && !maybeStartTrackingSlidingView && slidingView == null && !inPreviewMode) {
                View view = getPressedChildView();
                if (view instanceof ChatMessageCell) {
                    if (slidingView != null) {
                        slidingView.setSlidingOffset(0);
                    }
                    slidingView = (ChatMessageCell) view;
                    MessageObject message = slidingView.getMessageObject();
                    if (chatMode != 0 || threadMessageObjects != null && threadMessageObjects.contains(message) || getMessageType(message) == 1 && (message.getDialogId() == mergeDialogId || message.needDrawBluredPreview()) || currentEncryptedChat == null && message.getId() < 0 || bottomOverlayChat != null && bottomOverlayChat.getVisibility() == View.VISIBLE || currentChat != null && (ChatObject.isNotInChat(currentChat) && !isThreadChat() || ChatObject.isChannel(currentChat) && !ChatObject.canPost(currentChat) && !currentChat.megagroup || !ChatObject.canSendMessages(currentChat)) || textSelectionHelper.isSelectionMode()) {
                        slidingView.setSlidingOffset(0);
                        slidingView = null;
                        return;
                    }
                    startedTrackingPointerId = e.getPointerId(0);
                    maybeStartTrackingSlidingView = true;
                    startedTrackingX = (int) e.getX();
                    startedTrackingY = (int) e.getY();
                }
            } else if (slidingView != null && e != null && e.getAction() == MotionEvent.ACTION_MOVE && e.getPointerId(0) == startedTrackingPointerId) {
                int dx = Math.max(AndroidUtilities.dp(-80), Math.min(0, (int) (e.getX() - startedTrackingX)));
                int dy = Math.abs((int) e.getY() - startedTrackingY);
                if (getScrollState() == SCROLL_STATE_IDLE && maybeStartTrackingSlidingView && !startedTrackingSlidingView && dx <= -AndroidUtilities.getPixelsInCM(0.4f, true) && Math.abs(dx) / 3 > dy) {
                    MotionEvent event = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
                    slidingView.onTouchEvent(event);
                    super.onInterceptTouchEvent(event);
                    event.recycle();
                    chatLayoutManager.setCanScrollVertically(false);
                    maybeStartTrackingSlidingView = false;
                    startedTrackingSlidingView = true;
                    startedTrackingX = (int) e.getX();
                    if (getParent() != null) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                } else if (startedTrackingSlidingView) {
                    if (Math.abs(dx) >= AndroidUtilities.dp(50)) {
                        if (!wasTrackingVibrate) {
                            try {
                                performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                            } catch (Exception ignore) {
                            }
                            wasTrackingVibrate = true;
                        }
                    } else {
                        wasTrackingVibrate = false;
                    }
                    slidingView.setSlidingOffset(dx);
                    MessageObject messageObject = slidingView.getMessageObject();
                    if (messageObject.isRoundVideo() || messageObject.isVideo()) {
                        updateTextureViewPosition(false);
                    }
                    setGroupTranslationX(slidingView, dx);
                    invalidate();
                }
            } else if (slidingView != null && (e == null || e.getPointerId(0) == startedTrackingPointerId && (e.getAction() == MotionEvent.ACTION_CANCEL || e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_POINTER_UP))) {
                if (e != null && e.getAction() != MotionEvent.ACTION_CANCEL && Math.abs(slidingView.getNonAnimationTranslationX(false)) >= AndroidUtilities.dp(50)) {
                    showFieldPanelForReply(slidingView.getMessageObject());
                }
                endTrackingX = slidingView.getSlidingOffsetX();
                if (endTrackingX == 0) {
                    slidingView = null;
                }
                lastTrackingAnimationTime = System.currentTimeMillis();
                trackAnimationProgress = 0.0f;
                invalidate();
                maybeStartTrackingSlidingView = false;
                startedTrackingSlidingView = false;
                chatLayoutManager.setCanScrollVertically(true);
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            textSelectionHelper.checkSelectionCancel(e);
            if (e.getAction() == MotionEvent.ACTION_DOWN) {
                scrollByTouch = true;
            }
            if (pullingDownOffset != 0 && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
                float progress = Math.min(1f, pullingDownOffset / AndroidUtilities.dp(110));
                if (e.getAction() == MotionEvent.ACTION_UP && progress == 1 && pullingDownDrawable != null && !pullingDownDrawable.emptyStub) {
                    if (pullingDownDrawable.animationIsRunning()) {
                        ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, pullingDownOffset + AndroidUtilities.dp(8));
                        pullingDownBackAnimator = animator;
                        animator.addUpdateListener(valueAnimator -> {
                            pullingDownOffset = (float) valueAnimator.getAnimatedValue();
                            chatListView.invalidate();
                        });
                        animator.setDuration(200);
                        animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
                        animator.start();
                        pullingDownDrawable.runOnAnimationFinish(() -> {
                            animateToNextChat();
                        });
                    } else {
                        animateToNextChat();
                    }
                } else {
                    if (pullingDownDrawable != null && pullingDownDrawable.emptyStub && (System.currentTimeMillis() - pullingDownDrawable.lastShowingReleaseTime) < 500 && pullingDownDrawable.animateSwipeToRelease) {
                        AnimatorSet animatorSet = new AnimatorSet();
                        pullingDownBackAnimator = animatorSet;
                        if (pullingDownDrawable != null) {
                            pullingDownDrawable.showBottomPanel(false);
                        }
                        ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, AndroidUtilities.dp(111));
                        animator.addUpdateListener(valueAnimator -> {
                            pullingDownOffset = (float) valueAnimator.getAnimatedValue();
                            chatListView.invalidate();
                        });
                        animator.setDuration(400);
                        animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
                        ValueAnimator animator2 = ValueAnimator.ofFloat(AndroidUtilities.dp(111), 0);
                        animator2.addUpdateListener(valueAnimator -> {
                            pullingDownOffset = (float) valueAnimator.getAnimatedValue();
                            chatListView.invalidate();
                        });
                        animator2.setStartDelay(600);
                        animator2.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
                        animator2.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
                        animatorSet.playSequentially(animator, animator2);
                        animatorSet.start();
                    } else {
                        ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, 0);
                        pullingDownBackAnimator = animator;
                        if (pullingDownDrawable != null) {
                            pullingDownDrawable.showBottomPanel(false);
                        }
                        animator.addUpdateListener(valueAnimator -> {
                            pullingDownOffset = (float) valueAnimator.getAnimatedValue();
                            chatListView.invalidate();
                        });
                        animator.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
                        animator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
                        animator.start();
                    }
                }
            }
            if (isFastScrollAnimationRunning()) {
                return false;
            }
            boolean result = super.onTouchEvent(e);
            if (actionBar.isActionModeShowed() || reportType >= 0) {
                return result;
            }
            processTouchEvent(e);
            return startedTrackingSlidingView || result;
        }

        @Override
        public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            super.requestDisallowInterceptTouchEvent(disallowIntercept);
            if (slidingView != null) {
                processTouchEvent(null);
            }
        }

        @Override
        protected void onChildPressed(View child, float x, float y, boolean pressed) {
            super.onChildPressed(child, x, y, pressed);
            if (child instanceof ChatMessageCell) {
                ChatMessageCell chatMessageCell = (ChatMessageCell) child;
                MessageObject object = chatMessageCell.getMessageObject();
                if (object.isMusic() || object.isDocument()) {
                    return;
                }
                MessageObject.GroupedMessages groupedMessages = chatMessageCell.getCurrentMessagesGroup();
                if (groupedMessages != null) {
                    int count = getChildCount();
                    for (int a = 0; a < count; a++) {
                        View item = getChildAt(a);
                        if (item == child || !(item instanceof ChatMessageCell)) {
                            continue;
                        }
                        ChatMessageCell cell = (ChatMessageCell) item;
                        if (cell.getCurrentMessagesGroup() == groupedMessages) {
                            cell.setPressed(pressed);
                        }
                    }
                }
            }
        }

        @Override
        public void onDraw(Canvas c) {
            super.onDraw(c);
            if (slidingView != null) {
                float translationX = slidingView.getSlidingOffsetX();
                if (!maybeStartTrackingSlidingView && !startedTrackingSlidingView && endTrackingX != 0 && translationX != 0) {
                    long newTime = System.currentTimeMillis();
                    long dt = newTime - lastTrackingAnimationTime;
                    trackAnimationProgress += dt / 180.0f;
                    if (trackAnimationProgress > 1.0f) {
                        trackAnimationProgress = 1.0f;
                    }
                    lastTrackingAnimationTime = newTime;
                    translationX = endTrackingX * (1.0f - AndroidUtilities.decelerateInterpolator.getInterpolation(trackAnimationProgress));
                    if (translationX == 0) {
                        endTrackingX = 0;
                    }
                    setGroupTranslationX(slidingView, translationX);
                    slidingView.setSlidingOffset(translationX);
                    MessageObject messageObject = slidingView.getMessageObject();
                    if (messageObject.isRoundVideo() || messageObject.isVideo()) {
                        updateTextureViewPosition(false);
                    }
                    if (trackAnimationProgress == 1f || trackAnimationProgress == 0f) {
                        slidingView.setSlidingOffset(0);
                        slidingView = null;
                    }
                    invalidate();
                }
                drawReplyButton(c);
            }
            if (pullingDownOffset != 0) {
                c.save();
                float transitionOffset = 0;
                if (pullingDownAnimateProgress != 0) {
                    transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
                }
                c.translate(0, getMeasuredHeight() - blurredViewBottomOffset - transitionOffset);
                if (pullingDownDrawable == null) {
                    pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId, themeDelegate);
                    pullingDownDrawable.onAttach();
                }
                pullingDownDrawable.setWidth(getMeasuredWidth());
                float progress = Math.min(1f, pullingDownOffset / AndroidUtilities.dp(110));
                pullingDownDrawable.draw(c, chatListView, progress, 1f - pullingDownAnimateProgress);
                c.restore();
                if (pullingDownAnimateToActivity != null) {
                    c.saveLayerAlpha(0, 0, pullingDownAnimateToActivity.chatListView.getMeasuredWidth(), pullingDownAnimateToActivity.chatListView.getMeasuredHeight(), (int) (255 * pullingDownAnimateProgress), Canvas.ALL_SAVE_FLAG);
                    c.translate(0, getMeasuredHeight() - pullingDownOffset - transitionOffset);
                    pullingDownAnimateToActivity.chatListView.draw(c);
                    c.restore();
                }
            } else if (pullingDownDrawable != null) {
                pullingDownDrawable.reset();
            }
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            drawLaterRoundProgressCell = null;
            canvas.save();
            canvas.clipRect(0, chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4), getMeasuredWidth(), getMeasuredHeight() - blurredViewBottomOffset);
            selectorRect.setEmpty();
            if (pullingDownOffset != 0) {
                canvas.save();
                float transitionOffset = 0;
                if (pullingDownAnimateProgress != 0) {
                    transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
                }
                canvas.translate(0, drawingChatLisViewYoffset = -pullingDownOffset - transitionOffset);
                drawChatBackgroundElements(canvas);
                super.dispatchDraw(canvas);
                canvas.restore();
            } else {
                drawChatBackgroundElements(canvas);
                super.dispatchDraw(canvas);
            }
            canvas.restore();
        }

        private void drawChatBackgroundElements(Canvas canvas) {
            int count = getChildCount();
            MessageObject.GroupedMessages lastDrawnGroup = null;
            for (int a = 0; a < count; a++) {
                View child = getChildAt(a);
                if (chatAdapter.isBot && child instanceof BotHelpCell) {
                    BotHelpCell botCell = (BotHelpCell) child;
                    float top = getMeasuredHeight() / 2 - child.getMeasuredHeight() / 2 + chatListViewPaddingTop;
                    if (!botCell.animating() && !chatListView.fastScrollAnimationRunning) {
                        if (child.getTop() > top) {
                            child.setTranslationY(top - child.getTop());
                        } else {
                            child.setTranslationY(0);
                        }
                    }
                    break;
                } else if (child instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) child;
                    MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
                    if (group == null || group != lastDrawnGroup) {
                        lastDrawnGroup = group;
                        MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
                        MessageBackgroundDrawable backgroundDrawable = cell.getBackgroundDrawable();
                        if ((backgroundDrawable.isAnimationInProgress() || cell.isDrawingSelectionBackground()) && (position == null || (position.flags & MessageObject.POSITION_FLAG_RIGHT) != 0)) {
                            if (cell.isHighlighted() || cell.isHighlightedAnimated()) {
                                if (position == null) {
                                    Paint backgroundPaint = getThemedPaint(Theme.key_paint_chatMessageBackgroundSelected);
                                    if (themeDelegate.isDark || backgroundPaint == null) {
                                        backgroundPaint = Theme.chat_replyLinePaint;
                                        backgroundPaint.setColor(getThemedColor(Theme.key_chat_selectedBackground));
                                    }
                                    canvas.save();
                                    canvas.translate(0, cell.getTranslationY());
                                    int wasAlpha = backgroundPaint.getAlpha();
                                    backgroundPaint.setAlpha((int) (wasAlpha * cell.getHightlightAlpha() * cell.getAlpha()));
                                    if (themeDelegate != null) {
                                        themeDelegate.applyServiceShaderMatrix(getMeasuredWidth(), cell.getHeight(), 0, cell.getTop());
                                    } else {
                                        Theme.applyServiceShaderMatrix(getMeasuredWidth(), cell.getHeight(), 0, cell.getTop());
                                    }
                                    canvas.drawRect(0, cell.getTop(), getMeasuredWidth(), cell.getBottom(), backgroundPaint);
                                    backgroundPaint.setAlpha(wasAlpha);
                                    canvas.restore();
                                }
                            } else {
                                int y = (int) cell.getY();
                                int height;
                                canvas.save();
                                if (position == null) {
                                    height = cell.getMeasuredHeight();
                                } else {
                                    height = y + cell.getMeasuredHeight();
                                    long time = 0;
                                    float touchX = 0;
                                    float touchY = 0;
                                    for (int i = 0; i < count; i++) {
                                        View inner = getChildAt(i);
                                        if (inner instanceof ChatMessageCell) {
                                            ChatMessageCell innerCell = (ChatMessageCell) inner;
                                            MessageObject.GroupedMessages innerGroup = innerCell.getCurrentMessagesGroup();
                                            if (innerGroup == group) {
                                                MessageBackgroundDrawable drawable = innerCell.getBackgroundDrawable();
                                                y = Math.min(y, (int) innerCell.getY());
                                                height = Math.max(height, (int) innerCell.getY() + innerCell.getMeasuredHeight());
                                                long touchTime = drawable.getLastTouchTime();
                                                if (touchTime > time) {
                                                    touchX = drawable.getTouchX() + innerCell.getX();
                                                    touchY = drawable.getTouchY() + innerCell.getY();
                                                    time = touchTime;
                                                }
                                            }
                                        }
                                    }
                                    backgroundDrawable.setTouchCoordsOverride(touchX, touchY - y);
                                    height -= y;
                                }
                                canvas.clipRect(0, y, getMeasuredWidth(), y + height);
                                Paint selectedBackgroundPaint = getThemedPaint(Theme.key_paint_chatMessageBackgroundSelected);
                                if (!themeDelegate.isDark && selectedBackgroundPaint != null) {
                                    backgroundDrawable.setCustomPaint(selectedBackgroundPaint);
                                    if (themeDelegate != null) {
                                        themeDelegate.applyServiceShaderMatrix(getMeasuredWidth(), height, 0, 0);
                                    } else {
                                        Theme.applyServiceShaderMatrix(getMeasuredWidth(), height, 0, 0);
                                    }
                                } else {
                                    backgroundDrawable.setCustomPaint(null);
                                    backgroundDrawable.setColor(getThemedColor(Theme.key_chat_selectedBackground));
                                }
                                backgroundDrawable.setBounds(0, y, getMeasuredWidth(), y + height);
                                backgroundDrawable.draw(canvas);
                                canvas.restore();
                            }
                        }
                    }
                    if (scrimView != cell && group == null && cell.drawBackgroundInParent()) {
                        canvas.save();
                        canvas.translate(cell.getX(), cell.getY());
                        if (cell.getScaleX() != 1f) {
                            canvas.scale(cell.getScaleX(), cell.getScaleY(), cell.getPivotX(), (cell.getHeight() >> 1));
                        }
                        cell.drawBackgroundInternal(canvas, true);
                        canvas.restore();
                    }
                } else if (child instanceof ChatActionCell) {
                    ChatActionCell cell = (ChatActionCell) child;
                    if (cell.hasGradientService()) {
                        canvas.save();
                        canvas.translate(cell.getX(), cell.getY());
                        canvas.scale(cell.getScaleX(), cell.getScaleY(), cell.getMeasuredWidth() / 2f, cell.getMeasuredHeight() / 2f);
                        cell.drawBackground(canvas, true);
                        canvas.restore();
                    }
                }
            }
            MessageObject.GroupedMessages scrimGroup = null;
            if (scrimView instanceof ChatMessageCell) {
                scrimGroup = ((ChatMessageCell) scrimView).getCurrentMessagesGroup();
            }
            for (int k = 0; k < 3; k++) {
                drawingGroups.clear();
                if (k == 2 && !chatListView.isFastScrollAnimationRunning()) {
                    continue;
                }
                for (int i = 0; i < count; i++) {
                    View child = chatListView.getChildAt(i);
                    if (child instanceof ChatMessageCell) {
                        ChatMessageCell cell = (ChatMessageCell) child;
                        if (child.getY() > chatListView.getHeight() || child.getY() + child.getHeight() < 0) {
                            continue;
                        }
                        MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
                        if (group == null || (k == 0 && group.messages.size() == 1) || (k == 1 && !group.transitionParams.drawBackgroundForDeletedItems)) {
                            continue;
                        }
                        if ((k == 0 && cell.getMessageObject().deleted) || (k == 1 && !cell.getMessageObject().deleted)) {
                            continue;
                        }
                        if ((k == 2 && !cell.willRemovedAfterAnimation()) || (k != 2 && cell.willRemovedAfterAnimation())) {
                            continue;
                        }
                        if (!drawingGroups.contains(group)) {
                            group.transitionParams.left = 0;
                            group.transitionParams.top = 0;
                            group.transitionParams.right = 0;
                            group.transitionParams.bottom = 0;
                            group.transitionParams.pinnedBotton = false;
                            group.transitionParams.pinnedTop = false;
                            group.transitionParams.cell = cell;
                            drawingGroups.add(group);
                        }
                        group.transitionParams.pinnedTop = cell.isPinnedTop();
                        group.transitionParams.pinnedBotton = cell.isPinnedBottom();
                        int left = (cell.getLeft() + cell.getBackgroundDrawableLeft());
                        int right = (cell.getLeft() + cell.getBackgroundDrawableRight());
                        int top = (cell.getTop() + cell.getBackgroundDrawableTop());
                        int bottom = (cell.getTop() + cell.getBackgroundDrawableBottom());
                        if ((cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_TOP) == 0) {
                            top -= AndroidUtilities.dp(10);
                        }
                        if ((cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
                            bottom += AndroidUtilities.dp(10);
                        }
                        if (cell.willRemovedAfterAnimation()) {
                            group.transitionParams.cell = cell;
                        }
                        if (group.transitionParams.top == 0 || top < group.transitionParams.top) {
                            group.transitionParams.top = top;
                        }
                        if (group.transitionParams.bottom == 0 || bottom > group.transitionParams.bottom) {
                            group.transitionParams.bottom = bottom;
                        }
                        if (group.transitionParams.left == 0 || left < group.transitionParams.left) {
                            group.transitionParams.left = left;
                        }
                        if (group.transitionParams.right == 0 || right > group.transitionParams.right) {
                            group.transitionParams.right = right;
                        }
                    }
                }
                for (int i = 0; i < drawingGroups.size(); i++) {
                    MessageObject.GroupedMessages group = drawingGroups.get(i);
                    if (group == scrimGroup) {
                        continue;
                    }
                    float x = group.transitionParams.cell.getNonAnimationTranslationX(true);
                    float l = (group.transitionParams.left + x + group.transitionParams.offsetLeft);
                    float t = (group.transitionParams.top + group.transitionParams.offsetTop);
                    float r = (group.transitionParams.right + x + group.transitionParams.offsetRight);
                    float b = (group.transitionParams.bottom + group.transitionParams.offsetBottom);
                    if (!group.transitionParams.backgroundChangeBounds) {
                        t += group.transitionParams.cell.getTranslationY();
                        b += group.transitionParams.cell.getTranslationY();
                    }
                    if (t < chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20)) {
                        t = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20);
                    }
                    if (b > chatListView.getMeasuredHeight() + AndroidUtilities.dp(20)) {
                        b = chatListView.getMeasuredHeight() + AndroidUtilities.dp(20);
                    }
                    boolean useScale = group.transitionParams.cell.getScaleX() != 1f || group.transitionParams.cell.getScaleY() != 1f;
                    if (useScale) {
                        canvas.save();
                        canvas.scale(group.transitionParams.cell.getScaleX(), group.transitionParams.cell.getScaleY(), l + (r - l) / 2, t + (b - t) / 2);
                    }
                    boolean selected = true;
                    for (int a = 0, N = group.messages.size(); a < N; a++) {
                        MessageObject object = group.messages.get(a);
                        int index = object.getDialogId() == dialog_id ? 0 : 1;
                        if (selectedMessagesIds[index].indexOfKey(object.getId()) < 0) {
                            selected = false;
                            break;
                        }
                    }
                    group.transitionParams.cell.drawBackground(canvas, (int) l, (int) t, (int) r, (int) b, group.transitionParams.pinnedTop, group.transitionParams.pinnedBotton, selected, contentView.getKeyboardHeight());
                    group.transitionParams.cell = null;
                    group.transitionParams.drawCaptionLayout = group.hasCaption;
                    if (useScale) {
                        canvas.restore();
                        for (int ii = 0; ii < count; ii++) {
                            View child = chatListView.getChildAt(ii);
                            if (child instanceof ChatMessageCell && ((ChatMessageCell) child).getCurrentMessagesGroup() == group) {
                                ChatMessageCell cell = ((ChatMessageCell) child);
                                int left = cell.getLeft();
                                int top = cell.getTop();
                                child.setPivotX(l - left + (r - l) / 2);
                                child.setPivotY(t - top + (b - t) / 2);
                            }
                        }
                    }
                }
            }
        }

        @Override
        public boolean drawChild(Canvas canvas, View child, long drawingTime) {
            int clipLeft = 0;
            int clipBottom = 0;
            boolean skipDraw = child == scrimView;
            ChatMessageCell cell;
            float cilpTop = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
            if (child.getY() > getMeasuredHeight() || child.getY() + child.getMeasuredHeight() < cilpTop) {
                skipDraw = true;
            }
            MessageObject.GroupedMessages group = null;
            if (child instanceof ChatMessageCell) {
                cell = (ChatMessageCell) child;
                if (animateSendingViews.contains(cell)) {
                    skipDraw = true;
                }
                MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
                group = cell.getCurrentMessagesGroup();
                if (position != null) {
                    if (position.pw != position.spanSize && position.spanSize == 1000 && position.siblingHeights == null && group.hasSibling) {
                        clipLeft = cell.getBackgroundDrawableLeft();
                    } else if (position.siblingHeights != null) {
                        clipBottom = child.getBottom() - AndroidUtilities.dp(1 + (cell.isPinnedBottom() ? 1 : 0));
                    }
                }
                if (cell.needDelayRoundProgressDraw()) {
                    drawLaterRoundProgressCell = cell;
                }
                if (!skipDraw && scrimView instanceof ChatMessageCell) {
                    ChatMessageCell cell2 = (ChatMessageCell) scrimView;
                    if (cell2.getCurrentMessagesGroup() != null && cell2.getCurrentMessagesGroup() == group) {
                        skipDraw = true;
                    }
                }
                if (skipDraw) {
                    cell.getPhotoImage().skipDraw();
                }
            } else {
                cell = null;
            }
            if (clipLeft != 0) {
                canvas.save();
            } else if (clipBottom != 0) {
                canvas.save();
            }
            boolean result;
            if (!skipDraw) {
                boolean clipToGroupBounds = group != null && group.transitionParams.backgroundChangeBounds;
                if (clipToGroupBounds) {
                    canvas.save();
                    float x = cell.getNonAnimationTranslationX(true);
                    float l = (group.transitionParams.left + x + group.transitionParams.offsetLeft);
                    float t = (group.transitionParams.top + group.transitionParams.offsetTop);
                    float r = (group.transitionParams.right + x + group.transitionParams.offsetRight);
                    float b = (group.transitionParams.bottom + group.transitionParams.offsetBottom);
                    canvas.clipRect(l + AndroidUtilities.dp(4), t + AndroidUtilities.dp(4), r - AndroidUtilities.dp(4), b - AndroidUtilities.dp(4));
                }
                if (cell != null && clipToGroupBounds) {
                    cell.clipToGroupBounds = true;
                    result = super.drawChild(canvas, child, drawingTime);
                    cell.clipToGroupBounds = false;
                } else {
                    result = super.drawChild(canvas, child, drawingTime);
                }
                if (clipToGroupBounds) {
                    canvas.restore();
                }
                if (cell != null && cell.hasOutboundsContent()) {
                    canvas.save();
                    canvas.translate(cell.getX(), cell.getY());
                    cell.drawOutboundsContent(canvas);
                    canvas.restore();
                }
            } else {
                result = false;
            }
            if (clipLeft != 0 || clipBottom != 0) {
                canvas.restore();
            }
            if (child.getTranslationY() != 0) {
                canvas.save();
                canvas.translate(0, child.getTranslationY());
            }
            if (cell != null) {
                cell.drawCheckBox(canvas);
            }
            if (child.getTranslationY() != 0) {
                canvas.restore();
            }
            int num = 0;
            int count = getChildCount();
            for (int a = 0; a < count; a++) {
                if (getChildAt(a) == child) {
                    num = a;
                    break;
                }
            }
            if (num == count - 1) {
                int size = drawTimeAfter.size();
                if (size > 0) {
                    for (int a = 0; a < size; a++) {
                        cell = drawTimeAfter.get(a);
                        canvas.save();
                        canvas.translate(cell.getLeft() + cell.getNonAnimationTranslationX(false), cell.getY());
                        cell.drawTime(canvas, cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f, true);
                        canvas.restore();
                    }
                    drawTimeAfter.clear();
                }
                size = drawNamesAfter.size();
                if (size > 0) {
                    for (int a = 0; a < size; a++) {
                        cell = drawNamesAfter.get(a);
                        float canvasOffsetX = cell.getLeft() + cell.getNonAnimationTranslationX(false);
                        float canvasOffsetY = cell.getY();
                        float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
                        canvas.save();
                        canvas.translate(canvasOffsetX, canvasOffsetY);
                        cell.setInvalidatesParent(true);
                        cell.drawNamesLayout(canvas, alpha);
                        cell.setInvalidatesParent(false);
                        canvas.restore();
                    }
                    drawNamesAfter.clear();
                }
                size = drawCaptionAfter.size();
                if (size > 0) {
                    for (int a = 0; a < size; a++) {
                        cell = drawCaptionAfter.get(a);
                        boolean selectionOnly = false;
                        if (cell.getCurrentPosition() != null) {
                            selectionOnly = (cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_LEFT) == 0;
                        }
                        float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
                        float canvasOffsetX = cell.getLeft() + cell.getNonAnimationTranslationX(false);
                        float canvasOffsetY = cell.getY();
                        canvas.save();
                        MessageObject.GroupedMessages groupedMessages = cell.getCurrentMessagesGroup();
                        if (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds) {
                            float x = cell.getNonAnimationTranslationX(true);
                            float l = (groupedMessages.transitionParams.left + x + groupedMessages.transitionParams.offsetLeft);
                            float t = (groupedMessages.transitionParams.top + groupedMessages.transitionParams.offsetTop);
                            float r = (groupedMessages.transitionParams.right + x + groupedMessages.transitionParams.offsetRight);
                            float b = (groupedMessages.transitionParams.bottom + groupedMessages.transitionParams.offsetBottom);
                            if (!groupedMessages.transitionParams.backgroundChangeBounds) {
                                t += cell.getTranslationY();
                                b += cell.getTranslationY();
                            }
                            canvas.clipRect(l + AndroidUtilities.dp(8), t + AndroidUtilities.dp(8), r - AndroidUtilities.dp(8), b - AndroidUtilities.dp(8));
                        }
                        canvas.translate(canvasOffsetX, canvasOffsetY);
                        cell.setInvalidatesParent(true);
                        cell.drawCaptionLayout(canvas, selectionOnly, alpha);
                        cell.setInvalidatesParent(false);
                        canvas.restore();
                    }
                    drawCaptionAfter.clear();
                }
            }
            if (child.getTranslationY() != 0) {
                canvas.save();
                canvas.translate(0, child.getTranslationY());
            }
            if (child instanceof ChatMessageCell) {
                ChatMessageCell chatMessageCell = (ChatMessageCell) child;
                MessageObject.GroupedMessagePosition position = chatMessageCell.getCurrentPosition();
                if (position != null || chatMessageCell.getTransitionParams().animateBackgroundBoundsInner) {
                    if (position == null || (position.last || position.minX == 0 && position.minY == 0)) {
                        if (num == count - 1) {
                            float alpha = chatMessageCell.shouldDrawAlphaLayer() ? chatMessageCell.getAlpha() : 1f;
                            float canvasOffsetX = chatMessageCell.getLeft() + chatMessageCell.getNonAnimationTranslationX(false);
                            float canvasOffsetY = chatMessageCell.getTop();
                            canvas.save();
                            canvas.translate(canvasOffsetX, canvasOffsetY);
                            cell.setInvalidatesParent(true);
                            if (position == null || position.last) {
                                chatMessageCell.drawTime(canvas, alpha, true);
                            }
                            if (position == null || (position.minX == 0 && position.minY == 0)) {
                                chatMessageCell.drawNamesLayout(canvas, alpha);
                            }
                            cell.setInvalidatesParent(false);
                            canvas.restore();
                        } else {
                            if (position == null || position.last) {
                                drawTimeAfter.add(chatMessageCell);
                            }
                            if ((position == null || (position.minX == 0 && position.minY == 0)) && chatMessageCell.hasNameLayout()) {
                                drawNamesAfter.add(chatMessageCell);
                            }
                        }
                    }
                    if (position != null || chatMessageCell.getTransitionParams().transformGroupToSingleMessage || chatMessageCell.getTransitionParams().animateBackgroundBoundsInner) {
                        if (num == count - 1) {
                            float alpha = chatMessageCell.shouldDrawAlphaLayer() ? chatMessageCell.getAlpha() : 1f;
                            float canvasOffsetX = chatMessageCell.getLeft() + chatMessageCell.getNonAnimationTranslationX(false);
                            float canvasOffsetY = chatMessageCell.getTop();
                            canvas.save();
                            MessageObject.GroupedMessages groupedMessages = chatMessageCell.getCurrentMessagesGroup();
                            if (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds) {
                                float x = chatMessageCell.getNonAnimationTranslationX(true);
                                float l = (groupedMessages.transitionParams.left + x + groupedMessages.transitionParams.offsetLeft);
                                float t = (groupedMessages.transitionParams.top + groupedMessages.transitionParams.offsetTop);
                                float r = (groupedMessages.transitionParams.right + x + groupedMessages.transitionParams.offsetRight);
                                float b = (groupedMessages.transitionParams.bottom + groupedMessages.transitionParams.offsetBottom);
                                if (groupedMessages.transitionParams.backgroundChangeBounds) {
                                    t -= chatMessageCell.getTranslationY();
                                    b -= chatMessageCell.getTranslationY();
                                }
                                canvas.clipRect(l + AndroidUtilities.dp(8), t + AndroidUtilities.dp(8), r - AndroidUtilities.dp(8), b - AndroidUtilities.dp(8));
                            }
                            canvas.translate(canvasOffsetX, canvasOffsetY);
                            if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
                                boolean selectionOnly = position != null && (position.flags & MessageObject.POSITION_FLAG_LEFT) == 0;
                                chatMessageCell.setInvalidatesParent(true);
                                chatMessageCell.drawCaptionLayout(canvas, selectionOnly, alpha);
                                chatMessageCell.setInvalidatesParent(false);
                            }
                            canvas.restore();
                        } else {
                            if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
                                drawCaptionAfter.add(chatMessageCell);
                            }
                        }
                    }
                }
                MessageObject message = chatMessageCell.getMessageObject();
                if (videoPlayerContainer != null && (message.isRoundVideo() || message.isVideo()) && MediaController.getInstance().isPlayingMessage(message)) {
                    ImageReceiver imageReceiver = chatMessageCell.getPhotoImage();
                    float newX = imageReceiver.getImageX() + chatMessageCell.getX();
                    float newY = chatMessageCell.getY() + imageReceiver.getImageY() + chatListView.getY() - videoPlayerContainer.getTop();
                    if (videoPlayerContainer.getTranslationX() != newX || videoPlayerContainer.getTranslationY() != newY) {
                        videoPlayerContainer.setTranslationX(newX);
                        videoPlayerContainer.setTranslationY(newY);
                        fragmentView.invalidate();
                        videoPlayerContainer.invalidate();
                    }
                }
                ImageReceiver imageReceiver = chatMessageCell.getAvatarImage();
                if (imageReceiver != null) {
                    MessageObject.GroupedMessages groupedMessages = getValidGroupedMessage(message);
                    if (chatMessageCell.getMessageObject().deleted) {
                        if (child.getTranslationY() != 0) {
                            canvas.restore();
                        }
                        imageReceiver.setVisible(false, false);
                        return result;
                    }
                    boolean replaceAnimation = chatListView.isFastScrollAnimationRunning() || (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds);
                    int top = replaceAnimation ? child.getTop() : (int) child.getY();
                    if (chatMessageCell.drawPinnedBottom()) {
                        int p;
                        if (chatMessageCell.willRemovedAfterAnimation()) {
                            p = chatScrollHelper.positionToOldView.indexOfValue(child);
                            if (p >= 0) {
                                p = chatScrollHelper.positionToOldView.keyAt(p);
                            }
                        } else {
                            ViewHolder holder = chatListView.getChildViewHolder(child);
                            p = holder.getAdapterPosition();
                        }
                        if (p >= 0) {
                            int nextPosition;
                            if (groupedMessages != null && position != null) {
                                int idx = groupedMessages.posArray.indexOf(position);
                                int size = groupedMessages.posArray.size();
                                if ((position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
                                    nextPosition = p - size + idx;
                                } else {
                                    nextPosition = p - 1;
                                    for (int a = idx + 1; a < size; a++) {
                                        if (groupedMessages.posArray.get(a).minY > position.maxY) {
                                            break;
                                        } else {
                                            nextPosition--;
                                        }
                                    }
                                }
                            } else {
                                nextPosition = p - 1;
                            }
                            if (chatMessageCell.willRemovedAfterAnimation()) {
                                View view = chatScrollHelper.positionToOldView.get(nextPosition);
                                if (view != null) {
                                    if (child.getTranslationY() != 0) {
                                        canvas.restore();
                                    }
                                    imageReceiver.setVisible(false, false);
                                    return result;
                                }
                            } else {
                                ViewHolder holder = chatListView.findViewHolderForAdapterPosition(nextPosition);
                                if (holder != null) {
                                    if (child.getTranslationY() != 0) {
                                        canvas.restore();
                                    }
                                    imageReceiver.setVisible(false, false);
                                    return result;
                                }
                            }
                        }
                    }
                    float tx = chatMessageCell.getSlidingOffsetX() + chatMessageCell.getCheckBoxTranslation();
                    int y = (int) ((replaceAnimation ? child.getTop() : child.getY()) + chatMessageCell.getLayoutHeight() + chatMessageCell.getTransitionParams().deltaBottom);
                    int maxY = chatListView.getMeasuredHeight() - chatListView.getPaddingBottom();
                    if (chatMessageCell.isPlayingRound() || chatMessageCell.getTransitionParams().animatePlayingRound) {
                        if (chatMessageCell.getTransitionParams().animatePlayingRound) {
                            float progressLocal = chatMessageCell.getTransitionParams().animateChangeProgress;
                            if (!chatMessageCell.isPlayingRound()) {
                                progressLocal = 1f - progressLocal;
                            }
                            int fromY = y;
                            int toY = Math.min(y, maxY);
                            y = (int) (fromY * progressLocal + toY * (1f - progressLocal));
                        }
                    } else {
                        if (y > maxY) {
                            y = maxY;
                        }
                    }
                    if (!replaceAnimation && child.getTranslationY() != 0) {
                        canvas.restore();
                    }
                    if (chatMessageCell.drawPinnedTop()) {
                        int p;
                        if (chatMessageCell.willRemovedAfterAnimation()) {
                            p = chatScrollHelper.positionToOldView.indexOfValue(child);
                            if (p >= 0) {
                                p = chatScrollHelper.positionToOldView.keyAt(p);
                            }
                        } else {
                            ViewHolder holder = chatListView.getChildViewHolder(child);
                            p = holder.getAdapterPosition();
                        }
                        if (p >= 0) {
                            int tries = 0;
                            while (true) {
                                if (tries >= 20) {
                                    break;
                                }
                                tries++;
                                int prevPosition;
                                if (groupedMessages != null && position != null) {
                                    int idx = groupedMessages.posArray.indexOf(position);
                                    if (idx < 0) {
                                        break;
                                    }
                                    int size = groupedMessages.posArray.size();
                                    if ((position.flags & MessageObject.POSITION_FLAG_TOP) != 0) {
                                        prevPosition = p + idx + 1;
                                    } else {
                                        prevPosition = p + 1;
                                        for (int a = idx - 1; a >= 0; a--) {
                                            if (groupedMessages.posArray.get(a).maxY < position.minY) {
                                                break;
                                            } else {
                                                prevPosition++;
                                            }
                                        }
                                    }
                                } else {
                                    prevPosition = p + 1;
                                }
                                if (chatMessageCell.willRemovedAfterAnimation()) {
                                    View view = chatScrollHelper.positionToOldView.get(prevPosition);
                                    if (view != null) {
                                        top = view.getTop();
                                        if (view instanceof ChatMessageCell) {
                                            cell = (ChatMessageCell) view;
                                            if (!cell.drawPinnedTop()) {
                                                break;
                                            } else {
                                                p = prevPosition;
                                            }
                                        } else {
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                } else {
                                    ViewHolder holder = chatListView.findViewHolderForAdapterPosition(prevPosition);
                                    if (holder != null) {
                                        top = holder.itemView.getTop();
                                        if (holder.itemView instanceof ChatMessageCell) {
                                            cell = (ChatMessageCell) holder.itemView;
                                            if (!cell.drawPinnedTop()) {
                                                break;
                                            } else {
                                                p = prevPosition;
                                            }
                                        } else {
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (y - AndroidUtilities.dp(48) < top) {
                        y = top + AndroidUtilities.dp(48);
                    }
                    if (!chatMessageCell.drawPinnedBottom()) {
                        int cellBottom = replaceAnimation ? chatMessageCell.getBottom() : (int) (chatMessageCell.getY() + chatMessageCell.getMeasuredHeight() + chatMessageCell.getTransitionParams().deltaBottom);
                        if (y > cellBottom) {
                            y = cellBottom;
                        }
                    }
                    canvas.save();
                    if (tx != 0) {
                        canvas.translate(tx, 0);
                    }
                    if (chatMessageCell.getCurrentMessagesGroup() != null) {
                        if (chatMessageCell.getCurrentMessagesGroup().transitionParams.backgroundChangeBounds) {
                            y -= chatMessageCell.getTranslationY();
                        }
                    }
                    imageReceiver.setImageY(y - AndroidUtilities.dp(44));
                    if (cell.shouldDrawAlphaLayer()) {
                        imageReceiver.setAlpha(cell.getAlpha());
                        canvas.scale(chatMessageCell.getScaleX(), chatMessageCell.getScaleY(), chatMessageCell.getX() + chatMessageCell.getPivotX(), chatMessageCell.getY() + (chatMessageCell.getHeight() >> 1));
                    } else {
                        imageReceiver.setAlpha(1f);
                    }
                    imageReceiver.setVisible(true, false);
                    imageReceiver.draw(canvas);
                    canvas.restore();
                    if (!replaceAnimation && child.getTranslationY() != 0) {
                        canvas.save();
                    }
                }
            }
            if (child.getTranslationY() != 0) {
                canvas.restore();
            }
            return result;
        }

        @Override
        public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
            if (currentEncryptedChat != null) {
                return;
            }
            super.onInitializeAccessibilityNodeInfo(info);
            if (Build.VERSION.SDK_INT >= 19) {
                AccessibilityNodeInfo.CollectionInfo collection = info.getCollectionInfo();
                if (collection != null) {
                    info.setCollectionInfo(AccessibilityNodeInfo.CollectionInfo.obtain(collection.getRowCount(), 1, false));
                }
            }
        }

        @Override
        public AccessibilityNodeInfo createAccessibilityNodeInfo() {
            if (currentEncryptedChat != null) {
                return null;
            }
            return super.createAccessibilityNodeInfo();
        }

        @Override
        public void invalidate() {
            super.invalidate();
            contentView.invalidateBlur();
        }
    };
    if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 19) {
        chatListView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
    }
    chatListView.setAccessibilityEnabled(false);
    chatListView.setNestedScrollingEnabled(false);
    chatListView.setInstantClick(true);
    chatListView.setDisableHighlightState(true);
    chatListView.setTag(1);
    chatListView.setVerticalScrollBarEnabled(true);
    chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
    chatListView.setClipToPadding(false);
    chatListView.setAnimateEmptyView(true, 1);
    chatListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    chatListViewPaddingTop = 0;
    invalidateChatListViewTopPadding();
    if (MessagesController.getGlobalMainSettings().getBoolean("view_animations", true)) {
        chatListItemAnimator = new ChatListItemAnimator(this, chatListView, themeDelegate) {

            Runnable finishRunnable;

            @Override
            public void checkIsRunning() {
                if (scrollAnimationIndex == -1) {
                    scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, allowedNotificationsDuringChatListAnimations, false);
                }
            }

            @Override
            public void onAnimationStart() {
                if (scrollAnimationIndex == -1) {
                    scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, allowedNotificationsDuringChatListAnimations, false);
                }
                if (finishRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(finishRunnable);
                    finishRunnable = null;
                }
                if (BuildVars.LOGS_ENABLED) {
                    FileLog.d("chatItemAnimator disable notifications");
                }
                chatActivityEnterView.getAdjustPanLayoutHelper().runDelayedAnimation();
                chatActivityEnterView.runEmojiPanelAnimation();
            }

            @Override
            protected void onAllAnimationsDone() {
                super.onAllAnimationsDone();
                if (finishRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(finishRunnable);
                }
                AndroidUtilities.runOnUIThread(finishRunnable = () -> {
                    if (scrollAnimationIndex != -1) {
                        getNotificationCenter().onAnimationFinish(scrollAnimationIndex);
                        scrollAnimationIndex = -1;
                    }
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("chatItemAnimator enable notifications");
                    }
                });
            }

            @Override
            public void endAnimations() {
                super.endAnimations();
                if (finishRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(finishRunnable);
                }
                AndroidUtilities.runOnUIThread(finishRunnable = () -> {
                    if (scrollAnimationIndex != -1) {
                        getNotificationCenter().onAnimationFinish(scrollAnimationIndex);
                        scrollAnimationIndex = -1;
                    }
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("chatItemAnimator enable notifications");
                    }
                });
            }
        };
    }
    chatLayoutManager = new GridLayoutManagerFixed(context, 1000, LinearLayoutManager.VERTICAL, true) {

        boolean computingScroll;

        @Override
        public int getStarForFixGap() {
            int padding = (int) chatListViewPaddingTop;
            if (isThreadChat() && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
                padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
            }
            return padding;
        }

        @Override
        protected int getParentStart() {
            if (computingScroll) {
                return (int) chatListViewPaddingTop;
            }
            return 0;
        }

        @Override
        public int getStartAfterPadding() {
            if (computingScroll) {
                return (int) chatListViewPaddingTop;
            }
            return super.getStartAfterPadding();
        }

        @Override
        public int getTotalSpace() {
            if (computingScroll) {
                return (int) (getHeight() - chatListViewPaddingTop - getPaddingBottom());
            }
            return super.getTotalSpace();
        }

        @Override
        public int computeVerticalScrollExtent(RecyclerView.State state) {
            computingScroll = true;
            int r = super.computeVerticalScrollExtent(state);
            computingScroll = false;
            return r;
        }

        @Override
        public int computeVerticalScrollOffset(RecyclerView.State state) {
            computingScroll = true;
            int r = super.computeVerticalScrollOffset(state);
            computingScroll = false;
            return r;
        }

        @Override
        public int computeVerticalScrollRange(RecyclerView.State state) {
            computingScroll = true;
            int r = super.computeVerticalScrollRange(state);
            computingScroll = false;
            return r;
        }

        @Override
        public void scrollToPositionWithOffset(int position, int offset, boolean bottom) {
            if (!bottom) {
                offset = (int) (offset - getPaddingTop() + chatListViewPaddingTop);
            }
            super.scrollToPositionWithOffset(position, offset, bottom);
        }

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return true;
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
            scrollByTouch = false;
            LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE);
            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }

        @Override
        public boolean shouldLayoutChildFromOpositeSide(View child) {
            if (child instanceof ChatMessageCell) {
                return !((ChatMessageCell) child).getMessageObject().isOutOwner();
            }
            return false;
        }

        @Override
        protected boolean hasSiblingChild(int position) {
            if (position >= chatAdapter.messagesStartRow && position < chatAdapter.messagesEndRow) {
                int index = position - chatAdapter.messagesStartRow;
                if (index >= 0 && index < messages.size()) {
                    MessageObject message = messages.get(index);
                    MessageObject.GroupedMessages group = getValidGroupedMessage(message);
                    if (group != null) {
                        MessageObject.GroupedMessagePosition pos = group.positions.get(message);
                        if (pos.minX == pos.maxX || pos.minY != pos.maxY || pos.minY == 0) {
                            return false;
                        }
                        int count = group.posArray.size();
                        for (int a = 0; a < count; a++) {
                            MessageObject.GroupedMessagePosition p = group.posArray.get(a);
                            if (p == pos) {
                                continue;
                            }
                            if (p.minY <= pos.minY && p.maxY >= pos.minY) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            if (BuildVars.DEBUG_PRIVATE_VERSION) {
                super.onLayoutChildren(recycler, state);
            } else {
                try {
                    super.onLayoutChildren(recycler, state);
                } catch (Exception e) {
                    FileLog.e(e);
                    AndroidUtilities.runOnUIThread(() -> chatAdapter.notifyDataSetChanged(false));
                }
            }
        }

        @Override
        public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
            if (dy < 0 && pullingDownOffset != 0) {
                pullingDownOffset += dy;
                if (pullingDownOffset < 0) {
                    dy = (int) pullingDownOffset;
                    pullingDownOffset = 0;
                    chatListView.invalidate();
                } else {
                    dy = 0;
                }
            }
            int n = chatListView.getChildCount();
            int scrolled = 0;
            boolean foundTopView = false;
            for (int i = 0; i < n; i++) {
                View child = chatListView.getChildAt(i);
                float padding = chatListViewPaddingTop;
                if (isThreadChat() && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
                    padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
                }
                if (chatListView.getChildAdapterPosition(child) == chatAdapter.getItemCount() - 1) {
                    int dyLocal = dy;
                    if (child.getTop() - dy > padding) {
                        dyLocal = (int) (child.getTop() - padding);
                    }
                    scrolled = super.scrollVerticallyBy(dyLocal, recycler, state);
                    foundTopView = true;
                    break;
                }
            }
            if (!foundTopView) {
                scrolled = super.scrollVerticallyBy(dy, recycler, state);
            }
            if (dy > 0 && scrolled == 0 && ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && !chatListView.isFastScrollAnimationRunning() && !chatListView.isMultiselect()) {
                if (pullingDownOffset == 0 && pullingDownDrawable != null) {
                    pullingDownDrawable.updateDialog();
                }
                if (pullingDownBackAnimator != null) {
                    pullingDownBackAnimator.removeAllListeners();
                    pullingDownBackAnimator.cancel();
                }
                float k;
                if (pullingDownOffset < AndroidUtilities.dp(110)) {
                    float progress = pullingDownOffset / AndroidUtilities.dp(110);
                    k = 0.65f * (1f - progress) + 0.45f * progress;
                } else if (pullingDownOffset < AndroidUtilities.dp(160)) {
                    float progress = (pullingDownOffset - AndroidUtilities.dp(110)) / AndroidUtilities.dp(50);
                    k = 0.45f * (1f - progress) + 0.05f * progress;
                } else {
                    k = 0.05f;
                }
                pullingDownOffset += dy * k;
                ReactionsEffectOverlay.onScrolled((int) (dy * k));
                chatListView.invalidate();
            }
            if (pullingDownOffset == 0) {
                chatListView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
            } else {
                chatListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            }
            if (pullingDownDrawable != null) {
                pullingDownDrawable.showBottomPanel(pullingDownOffset > 0 && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING);
            }
            return scrolled;
        }
    };
    chatLayoutManager.setSpanSizeLookup(new GridLayoutManagerFixed.SpanSizeLookup() {

        @Override
        public int getSpanSize(int position) {
            if (position >= chatAdapter.messagesStartRow && position < chatAdapter.messagesEndRow) {
                int idx = position - chatAdapter.messagesStartRow;
                if (idx >= 0 && idx < messages.size()) {
                    MessageObject message = messages.get(idx);
                    MessageObject.GroupedMessages groupedMessages = getValidGroupedMessage(message);
                    if (groupedMessages != null) {
                        return groupedMessages.positions.get(message).spanSize;
                    }
                }
            }
            return 1000;
        }
    });
    chatListView.setLayoutManager(chatLayoutManager);
    chatListView.addItemDecoration(new RecyclerView.ItemDecoration() {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.bottom = 0;
            if (view instanceof ChatMessageCell) {
                ChatMessageCell cell = (ChatMessageCell) view;
                MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
                if (group != null) {
                    MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
                    if (position != null && position.siblingHeights != null) {
                        float maxHeight = Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.5f;
                        int h = cell.getExtraInsetHeight();
                        for (int a = 0; a < position.siblingHeights.length; a++) {
                            h += (int) Math.ceil(maxHeight * position.siblingHeights[a]);
                        }
                        h += (position.maxY - position.minY) * Math.round(7 * AndroidUtilities.density);
                        int count = group.posArray.size();
                        for (int a = 0; a < count; a++) {
                            MessageObject.GroupedMessagePosition pos = group.posArray.get(a);
                            if (pos.minY != position.minY || pos.minX == position.minX && pos.maxX == position.maxX && pos.minY == position.minY && pos.maxY == position.maxY) {
                                continue;
                            }
                            if (pos.minY == position.minY) {
                                h -= (int) Math.ceil(maxHeight * pos.ph) - AndroidUtilities.dp(4);
                                break;
                            }
                        }
                        outRect.bottom = -h;
                    }
                }
            }
        }
    });
    contentView.addView(chatListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    chatListView.setOnItemLongClickListener(onItemLongClickListener);
    chatListView.setOnItemClickListener(onItemClickListener);
    chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        private float totalDy = 0;

        private boolean scrollUp;

        private final int scrollValue = AndroidUtilities.dp(100);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                if (pollHintCell != null) {
                    pollHintView.showForMessageCell(pollHintCell, -1, pollHintX, pollHintY, true);
                    pollHintCell = null;
                }
                scrollingFloatingDate = false;
                scrollingChatListView = false;
                checkTextureViewPosition = false;
                hideFloatingDateView(true);
                checkAutoDownloadMessages(scrollUp);
                if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
                    NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 512);
                }
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startSpoilers);
                chatListView.setOverScrollMode(RecyclerView.OVER_SCROLL_ALWAYS);
                textSelectionHelper.stopScrolling();
                updateVisibleRows();
                scrollByTouch = false;
            } else {
                if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    wasManualScroll = true;
                    scrollingChatListView = true;
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    pollHintCell = null;
                    wasManualScroll = true;
                    scrollingFloatingDate = true;
                    checkTextureViewPosition = true;
                    scrollingChatListView = true;
                }
                if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
                    NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopAllHeavyOperations, 512);
                }
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopSpoilers);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            chatListView.invalidate();
            scrollUp = dy < 0;
            int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
            if (dy != 0 && (scrollByTouch && recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING) || recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
                if (forceNextPinnedMessageId != 0) {
                    if ((!scrollUp || forceScrollToFirst)) {
                        forceNextPinnedMessageId = 0;
                    } else if (!chatListView.isFastScrollAnimationRunning() && firstVisibleItem != RecyclerView.NO_POSITION) {
                        int lastVisibleItem = chatLayoutManager.findLastVisibleItemPosition();
                        MessageObject messageObject = null;
                        boolean foundForceNextPinnedView = false;
                        for (int i = lastVisibleItem; i >= firstVisibleItem; i--) {
                            View view = chatLayoutManager.findViewByPosition(i);
                            if (view instanceof ChatMessageCell) {
                                messageObject = ((ChatMessageCell) view).getMessageObject();
                            } else if (view instanceof ChatActionCell) {
                                messageObject = ((ChatActionCell) view).getMessageObject();
                            }
                            if (messageObject != null) {
                                if (forceNextPinnedMessageId == messageObject.getId()) {
                                    foundForceNextPinnedView = true;
                                    break;
                                }
                            }
                        }
                        if (!foundForceNextPinnedView && messageObject != null && messageObject.getId() < forceNextPinnedMessageId) {
                            forceNextPinnedMessageId = 0;
                        }
                    }
                }
            }
            if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
                forceScrollToFirst = false;
                if (!wasManualScroll && dy != 0) {
                    wasManualScroll = true;
                }
            }
            if (dy != 0) {
                hideHints(true);
            }
            if (dy != 0 && scrollingFloatingDate && !currentFloatingTopIsNotMessage) {
                if (highlightMessageId != Integer.MAX_VALUE) {
                    removeSelectedMessageHighlight();
                    updateVisibleRows();
                }
                showFloatingDateView(true);
            }
            checkScrollForLoad(true);
            if (firstVisibleItem != RecyclerView.NO_POSITION) {
                int totalItemCount = chatAdapter.getItemCount();
                if (firstVisibleItem == 0 && forwardEndReached[0]) {
                    if (dy >= 0) {
                        canShowPagedownButton = false;
                        updatePagedownButtonVisibility(true);
                    }
                } else {
                    if (dy > 0) {
                        if (pagedownButton.getTag() == null) {
                            totalDy += dy;
                            if (totalDy > scrollValue) {
                                totalDy = 0;
                                canShowPagedownButton = true;
                                updatePagedownButtonVisibility(true);
                                pagedownButtonShowedByScroll = true;
                            }
                        }
                    } else {
                        if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
                            totalDy += dy;
                            if (totalDy < -scrollValue) {
                                canShowPagedownButton = false;
                                updatePagedownButtonVisibility(true);
                                totalDy = 0;
                            }
                        }
                    }
                }
            }
            invalidateMessagesVisiblePart();
            textSelectionHelper.onParentScrolled();
            emojiAnimationsOverlay.onScrolled(dy);
            ReactionsEffectOverlay.onScrolled(dy);
        }
    });
    animatingImageView = new ClippingImageView(context);
    animatingImageView.setVisibility(View.GONE);
    contentView.addView(animatingImageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    progressView2 = new View(context);
    progressView2.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), progressView2, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
    progressView.addView(progressView2, LayoutHelper.createFrame(36, 36, Gravity.CENTER));
    progressBar = new RadialProgressView(context, themeDelegate);
    progressBar.setSize(AndroidUtilities.dp(28));
    progressBar.setProgressColor(getThemedColor(Theme.key_chat_serviceText));
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));
    floatingDateView = new ChatActionCell(context, false, themeDelegate) {

        @Override
        public void setTranslationY(float translationY) {
            if (getTranslationY() != translationY) {
                invalidate();
            }
            super.setTranslationY(translationY);
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
                return false;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
                return false;
            }
            return super.onTouchEvent(event);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            float clipTop = chatListView.getY() + chatListViewPaddingTop - getY();
            clipTop -= AndroidUtilities.dp(4);
            if (clipTop > 0) {
                if (clipTop < getMeasuredHeight()) {
                    canvas.save();
                    canvas.clipRect(0, clipTop, getMeasuredWidth(), getMeasuredHeight());
                    super.onDraw(canvas);
                    canvas.restore();
                }
            } else {
                super.onDraw(canvas);
            }
        }
    };
    floatingDateView.setCustomDate((int) (System.currentTimeMillis() / 1000), false, false);
    floatingDateView.setAlpha(0.0f);
    floatingDateView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
    floatingDateView.setInvalidateColors(true);
    contentView.addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 4, 0, 0));
    floatingDateView.setOnClickListener(view -> {
        if (floatingDateView.getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis((long) floatingDateView.getCustomDate() * 1000);
        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.clear();
        calendar.set(year, monthOfYear, dayOfMonth);
        jumpToDate((int) (calendar.getTime().getTime() / 1000));
    });
    if (currentChat != null) {
        pendingRequestsDelegate = new ChatActivityMemberRequestsDelegate(this, currentChat, this::invalidateChatListViewTopPadding);
        pendingRequestsDelegate.setChatInfo(chatInfo, false);
        contentView.addView(pendingRequestsDelegate.getView(), ViewGroup.LayoutParams.MATCH_PARENT, pendingRequestsDelegate.getViewHeight());
    }
    if (currentEncryptedChat == null) {
        pinnedMessageView = new ChatBlurredFrameLayout(context, ChatActivity.this) {

            float lastY;

            float startY;

            {
                setOnLongClickListener(v -> {
                    if (AndroidUtilities.isTablet() || isThreadChat()) {
                        return false;
                    }
                    startY = lastY;
                    openPinnedMessagesList(true);
                    return true;
                });
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                lastY = event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    finishPreviewFragment();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    float dy = startY - lastY;
                    movePreviewFragment(dy);
                    if (dy < 0) {
                        startY = lastY;
                    }
                }
                return super.onTouchEvent(event);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                if (setPinnedTextTranslationX) {
                    for (int a = 0; a < pinnedNextAnimation.length; a++) {
                        if (pinnedNextAnimation[a] != null) {
                            pinnedNextAnimation[a].start();
                        }
                    }
                    setPinnedTextTranslationX = false;
                }
            }

            @Override
            protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
                if (child == pinnedLineView) {
                    canvas.save();
                    canvas.clipRect(0, 0, getMeasuredWidth(), AndroidUtilities.dp(48));
                }
                boolean result;
                if (child == pinnedMessageTextView[0] || child == pinnedMessageTextView[1]) {
                    canvas.save();
                    canvas.clipRect(0, 0, getMeasuredWidth() - AndroidUtilities.dp(38), getMeasuredHeight());
                    result = super.drawChild(canvas, child, drawingTime);
                    canvas.restore();
                } else {
                    result = super.drawChild(canvas, child, drawingTime);
                    if (child == pinnedLineView) {
                        canvas.restore();
                    }
                }
                return result;
            }
        };
        pinnedMessageView.setTag(1);
        pinnedMessageEnterOffset = -AndroidUtilities.dp(50);
        pinnedMessageView.setVisibility(View.GONE);
        pinnedMessageView.setBackgroundResource(R.drawable.blockpanel);
        pinnedMessageView.backgroundColor = getThemedColor(Theme.key_chat_topPanelBackground);
        pinnedMessageView.backgroundPaddingBottom = AndroidUtilities.dp(2);
        pinnedMessageView.getBackground().mutate().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
        contentView.addView(pinnedMessageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
        pinnedMessageView.setOnClickListener(v -> {
            wasManualScroll = true;
            if (isThreadChat()) {
                scrollToMessageId(threadMessageId, 0, true, 0, true, 0);
            } else if (currentPinnedMessageId != 0) {
                int currentPinned = currentPinnedMessageId;
                int forceNextPinnedMessageId = 0;
                if (!pinnedMessageIds.isEmpty()) {
                    if (currentPinned == pinnedMessageIds.get(pinnedMessageIds.size() - 1)) {
                        forceNextPinnedMessageId = pinnedMessageIds.get(0) + 1;
                        forceScrollToFirst = true;
                    } else {
                        forceNextPinnedMessageId = currentPinned - 1;
                        forceScrollToFirst = false;
                    }
                }
                this.forceNextPinnedMessageId = forceNextPinnedMessageId;
                if (!forceScrollToFirst) {
                    forceNextPinnedMessageId = -forceNextPinnedMessageId;
                }
                scrollToMessageId(currentPinned, 0, true, 0, true, forceNextPinnedMessageId);
                updateMessagesVisiblePart(false);
            }
        });
        View selector = new View(context);
        selector.setBackground(Theme.getSelectorDrawable(false));
        pinnedMessageView.addView(selector, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 2));
        pinnedLineView = new PinnedLineView(context, themeDelegate);
        pinnedMessageView.addView(pinnedLineView, LayoutHelper.createFrame(2, 48, Gravity.LEFT | Gravity.TOP, 8, 0, 0, 0));
        pinnedCounterTextView = new NumberTextView(context);
        pinnedCounterTextView.setAddNumber();
        pinnedCounterTextView.setTextSize(14);
        pinnedCounterTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
        pinnedCounterTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        pinnedMessageView.addView(pinnedCounterTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7, 44, 0));
        for (int a = 0; a < 2; a++) {
            pinnedNameTextView[a] = new SimpleTextView(context) {

                @Override
                protected boolean createLayout(int width) {
                    boolean result = super.createLayout(width);
                    if (this == pinnedNameTextView[0] && pinnedCounterTextView != null) {
                        int newX = getTextWidth() + AndroidUtilities.dp(4);
                        if (newX != pinnedCounterTextViewX) {
                            pinnedCounterTextView.setTranslationX(pinnedCounterTextViewX = newX);
                        }
                    }
                    return result;
                }
            };
            pinnedNameTextView[a].setTextSize(14);
            pinnedNameTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
            pinnedNameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            pinnedMessageView.addView(pinnedNameTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7.3f, 44, 0));
            pinnedMessageTextView[a] = new SimpleTextView(context) {

                @Override
                public void setTranslationY(float translationY) {
                    super.setTranslationY(translationY);
                    if (this == pinnedMessageTextView[0] && pinnedNextAnimation[1] != null) {
                        if (forceScrollToFirst && translationY < 0) {
                            pinnedLineView.setTranslationY(translationY / 2);
                        } else {
                            pinnedLineView.setTranslationY(0);
                        }
                    }
                }
            };
            pinnedMessageTextView[a].setTextSize(14);
            pinnedMessageTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelMessage));
            pinnedMessageView.addView(pinnedMessageTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 25.3f, 44, 0));
            pinnedMessageImageView[a] = new BackupImageView(context);
            pinnedMessageImageView[a].setRoundRadius(AndroidUtilities.dp(2));
            pinnedMessageView.addView(pinnedMessageImageView[a], LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));
            if (a == 1) {
                pinnedMessageTextView[a].setVisibility(View.INVISIBLE);
                pinnedNameTextView[a].setVisibility(View.INVISIBLE);
                pinnedMessageImageView[a].setVisibility(View.INVISIBLE);
            }
        }
        pinnedListButton = new ImageView(context);
        pinnedListButton.setImageResource(R.drawable.menu_pinnedlist);
        pinnedListButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
        pinnedListButton.setScaleType(ImageView.ScaleType.CENTER);
        pinnedListButton.setContentDescription(LocaleController.getString("AccPinnedMessagesList", R.string.AccPinnedMessagesList));
        pinnedListButton.setVisibility(View.INVISIBLE);
        pinnedListButton.setAlpha(0.0f);
        pinnedListButton.setScaleX(0.4f);
        pinnedListButton.setScaleY(0.4f);
        if (Build.VERSION.SDK_INT >= 21) {
            pinnedListButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff));
        }
        pinnedMessageView.addView(pinnedListButton, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 7, 0));
        pinnedListButton.setOnClickListener(v -> openPinnedMessagesList(false));
        closePinned = new ImageView(context);
        closePinned.setImageResource(R.drawable.miniplayer_close);
        closePinned.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
        closePinned.setScaleType(ImageView.ScaleType.CENTER);
        closePinned.setContentDescription(LocaleController.getString("Close", R.string.Close));
        pinnedProgress = new RadialProgressView(context, themeDelegate);
        pinnedProgress.setVisibility(View.GONE);
        pinnedProgress.setSize(AndroidUtilities.dp(16));
        pinnedProgress.setStrokeWidth(2f);
        pinnedProgress.setProgressColor(getThemedColor(Theme.key_chat_topPanelLine));
        pinnedMessageView.addView(pinnedProgress, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
        if (threadMessageId != 0) {
            closePinned.setVisibility(View.GONE);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            closePinned.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14)));
        }
        pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
        closePinned.setOnClickListener(v -> {
            if (getParentActivity() == null) {
                return;
            }
            boolean allowPin;
            if (currentChat != null) {
                allowPin = ChatObject.canPinMessages(currentChat);
            } else if (currentEncryptedChat == null) {
                if (userInfo != null) {
                    allowPin = userInfo.can_pin_message;
                } else {
                    allowPin = false;
                }
            } else {
                allowPin = false;
            }
            if (allowPin) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                builder.setTitle(LocaleController.getString("UnpinMessageAlertTitle", R.string.UnpinMessageAlertTitle));
                builder.setMessage(LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert));
                builder.setPositiveButton(LocaleController.getString("UnpinMessage", R.string.UnpinMessage), (dialogInterface, i) -> {
                    MessageObject messageObject = pinnedMessageObjects.get(currentPinnedMessageId);
                    if (messageObject == null) {
                        messageObject = messagesDict[0].get(currentPinnedMessageId);
                    }
                    unpinMessage(messageObject);
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (!pinnedMessageIds.isEmpty()) {
                SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                preferences.edit().putInt("pin_" + dialog_id, pinnedMessageIds.get(0)).commit();
                updatePinnedMessageView(true);
            }
        });
    }
    topChatPanelView = new ChatBlurredFrameLayout(context, this) {

        private boolean ignoreLayout;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE && reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
                width = (width - AndroidUtilities.dp(31)) / 2;
            }
            ignoreLayout = true;
            if (reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) reportSpamButton.getLayoutParams();
                layoutParams.width = width;
                if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE) {
                    reportSpamButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
                    layoutParams.leftMargin = width;
                    layoutParams.width -= AndroidUtilities.dp(15);
                } else {
                    reportSpamButton.setPadding(AndroidUtilities.dp(48), 0, AndroidUtilities.dp(48), 0);
                    layoutParams.leftMargin = 0;
                }
            }
            if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) addToContactsButton.getLayoutParams();
                layoutParams.width = width;
                if (reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
                    addToContactsButton.setPadding(AndroidUtilities.dp(11), 0, AndroidUtilities.dp(4), 0);
                } else {
                    addToContactsButton.setPadding(AndroidUtilities.dp(48), 0, AndroidUtilities.dp(48), 0);
                    layoutParams.leftMargin = 0;
                }
            }
            ignoreLayout = false;
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    topChatPanelView.backgroundColor = getThemedColor(Theme.key_chat_topPanelBackground);
    topChatPanelView.backgroundPaddingBottom = AndroidUtilities.dp(2);
    topChatPanelView.setTag(1);
    topChatPanelViewOffset = -AndroidUtilities.dp(50);
    invalidateChatListViewTopPadding();
    topChatPanelView.setVisibility(View.GONE);
    topChatPanelView.setBackgroundResource(R.drawable.blockpanel);
    topChatPanelView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
    contentView.addView(topChatPanelView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
    reportSpamButton = new TextView(context);
    reportSpamButton.setTextColor(getThemedColor(Theme.key_chat_reportSpam));
    if (Build.VERSION.SDK_INT >= 21) {
        reportSpamButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_reportSpam) & 0x19ffffff, 2));
    }
    reportSpamButton.setTag(Theme.key_chat_reportSpam);
    reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    reportSpamButton.setSingleLine(true);
    reportSpamButton.setMaxLines(1);
    reportSpamButton.setGravity(Gravity.CENTER);
    topChatPanelView.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 1));
    reportSpamButton.setOnClickListener(v2 -> AlertsCreator.showBlockReportSpamAlert(ChatActivity.this, dialog_id, currentUser, currentChat, currentEncryptedChat, reportSpamButton.getTag(R.id.object_tag) != null, chatInfo, param -> {
        if (param == 0) {
            updateTopPanel(true);
        } else {
            finishFragment();
        }
    }, themeDelegate));
    addToContactsButton = new TextView(context);
    addToContactsButton.setTextColor(getThemedColor(Theme.key_chat_addContact));
    addToContactsButton.setVisibility(View.GONE);
    addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    addToContactsButton.setSingleLine(true);
    addToContactsButton.setMaxLines(1);
    addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
    addToContactsButton.setGravity(Gravity.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        addToContactsButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_addContact) & 0x19ffffff, 2));
    }
    topChatPanelView.addView(addToContactsButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 1));
    addToContactsButton.setOnClickListener(v -> {
        if (addToContactsButtonArchive) {
            getMessagesController().addDialogToFolder(dialog_id, 0, 0, 0);
            undoView.showWithAction(dialog_id, UndoView.ACTION_CHAT_UNARCHIVED, null);
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("dialog_bar_archived" + dialog_id, false);
            editor.putBoolean("dialog_bar_block" + dialog_id, false);
            editor.putBoolean("dialog_bar_report" + dialog_id, false);
            editor.commit();
            updateTopPanel(false);
            getNotificationsController().clearDialogNotificationsSettings(dialog_id);
        } else if (addToContactsButton.getTag() != null && (Integer) addToContactsButton.getTag() == 4) {
            if (chatInfo != null && chatInfo.participants != null) {
                LongSparseArray<TLObject> users = new LongSparseArray<>();
                for (int a = 0; a < chatInfo.participants.participants.size(); a++) {
                    users.put(chatInfo.participants.participants.get(a).user_id, null);
                }
                long chatId = chatInfo.id;
                InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, users, chatInfo.id, ChatActivity.this, themeDelegate);
                bottomSheet.setDelegate((users1, fwdCount) -> {
                    for (int a = 0, N = users1.size(); a < N; a++) {
                        TLRPC.User user = users1.get(a);
                        getMessagesController().addUserToChat(chatId, user, fwdCount, null, ChatActivity.this, null);
                    }
                    getMessagesController().hidePeerSettingsBar(dialog_id, currentUser, currentChat);
                    updateTopPanel(true);
                    updateInfoTopView(true);
                });
                bottomSheet.show();
            }
        } else if (addToContactsButton.getTag() != null) {
            shareMyContact(1, null);
        } else {
            Bundle args = new Bundle();
            args.putLong("user_id", currentUser.id);
            args.putBoolean("addContact", true);
            ContactAddActivity activity = new ContactAddActivity(args);
            activity.setDelegate(() -> undoView.showWithAction(dialog_id, UndoView.ACTION_CONTACT_ADDED, currentUser));
            presentFragment(activity);
        }
    });
    closeReportSpam = new ImageView(context);
    closeReportSpam.setImageResource(R.drawable.miniplayer_close);
    closeReportSpam.setContentDescription(LocaleController.getString("Close", R.string.Close));
    if (Build.VERSION.SDK_INT >= 21) {
        closeReportSpam.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_topPanelClose) & 0x19ffffff));
    }
    closeReportSpam.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
    closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
    topChatPanelView.addView(closeReportSpam, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
    closeReportSpam.setOnClickListener(v -> {
        long did = dialog_id;
        if (currentEncryptedChat != null) {
            did = currentUser.id;
        }
        getMessagesController().hidePeerSettingsBar(did, currentUser, currentChat);
        updateTopPanel(true);
        updateInfoTopView(true);
    });
    alertView = new FrameLayout(context);
    alertView.setTag(1);
    alertView.setVisibility(View.GONE);
    alertView.setBackgroundResource(R.drawable.blockpanel);
    alertView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
    contentView.addView(alertView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
    alertNameTextView = new TextView(context);
    alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertNameTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
    alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    alertNameTextView.setSingleLine(true);
    alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertNameTextView.setMaxLines(1);
    alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));
    alertTextView = new TextView(context);
    alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelMessage));
    alertTextView.setSingleLine(true);
    alertTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertTextView.setMaxLines(1);
    alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));
    pagedownButton = new FrameLayout(context);
    pagedownButton.setVisibility(View.INVISIBLE);
    contentView.addView(pagedownButton, LayoutHelper.createFrame(66, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -3, 5));
    pagedownButton.setOnClickListener(view -> {
        wasManualScroll = true;
        textSelectionHelper.cancelTextSelectionRunnable();
        if (createUnreadMessageAfterId != 0) {
            scrollToMessageId(createUnreadMessageAfterId, 0, false, returnToLoadIndex, true, 0);
        } else if (returnToMessageId > 0) {
            scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex, true, 0);
        } else {
            scrollToLastMessage(false);
            if (!pinnedMessageIds.isEmpty()) {
                forceScrollToFirst = true;
                forceNextPinnedMessageId = pinnedMessageIds.get(0);
            }
        }
    });
    mentiondownButton = new FrameLayout(context);
    mentiondownButton.setVisibility(View.INVISIBLE);
    contentView.addView(mentiondownButton, LayoutHelper.createFrame(46, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    mentiondownButton.setOnClickListener(new View.OnClickListener() {

        private void loadLastUnreadMention() {
            wasManualScroll = true;
            if (hasAllMentionsLocal) {
                getMessagesStorage().getUnreadMention(dialog_id, param -> {
                    if (param == 0) {
                        hasAllMentionsLocal = false;
                        loadLastUnreadMention();
                    } else {
                        scrollToMessageId(param, 0, false, 0, true, 0);
                    }
                });
            } else {
                final MessagesStorage messagesStorage = getMessagesStorage();
                TLRPC.TL_messages_getUnreadMentions req = new TLRPC.TL_messages_getUnreadMentions();
                req.peer = getMessagesController().getInputPeer(dialog_id);
                req.limit = 1;
                req.add_offset = newMentionsCount - 1;
                getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
                    if (error != null || res.messages.isEmpty()) {
                        if (res != null) {
                            newMentionsCount = res.count;
                        } else {
                            newMentionsCount = 0;
                        }
                        messagesStorage.resetMentionsCount(dialog_id, newMentionsCount);
                        if (newMentionsCount == 0) {
                            hasAllMentionsLocal = true;
                            showMentionDownButton(false, true);
                        } else {
                            mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
                            loadLastUnreadMention();
                        }
                    } else {
                        int id = res.messages.get(0).id;
                        MessageObject object = messagesDict[0].get(id);
                        messagesStorage.markMessageAsMention(dialog_id, id);
                        if (object != null) {
                            object.messageOwner.media_unread = true;
                            object.messageOwner.mentioned = true;
                        }
                        scrollToMessageId(id, 0, false, 0, true, 0);
                    }
                }));
            }
        }

        @Override
        public void onClick(View view) {
            loadLastUnreadMention();
        }
    });
    mentiondownButton.setOnLongClickListener(view -> {
        scrimPopupWindow = ReadAllMentionsMenu.show(ReadAllMentionsMenu.TYPE_MENTIONS, getParentActivity(), contentView, view, getResourceProvider(), () -> {
            for (int a = 0; a < messages.size(); a++) {
                MessageObject messageObject = messages.get(a);
                if (messageObject.messageOwner.mentioned && !messageObject.isContentUnread()) {
                    messageObject.setContentIsRead();
                }
            }
            newMentionsCount = 0;
            getMessagesController().markMentionsAsRead(dialog_id);
            hasAllMentionsLocal = true;
            showMentionDownButton(false, true);
            if (scrimPopupWindow != null) {
                scrimPopupWindow.dismiss();
            }
        });
        dimBehindView(mentiondownButton, true);
        scrimPopupWindow.setOnDismissListener(() -> {
            scrimPopupWindow = null;
            menuDeleteItem = null;
            scrimPopupWindowItems = null;
            chatLayoutManager.setCanScrollVertically(true);
            dimBehindView(false);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.getEditField().setAllowDrawCursor(true);
            }
        });
        view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
        return true;
    });
    mentionContainer = new FrameLayout(context) {

        private Rect padding;

        @Override
        public void onDraw(Canvas canvas) {
            if (mentionListView.getChildCount() <= 0) {
                return;
            }
            if (mentionLayoutManager.getReverseLayout()) {
                float top = mentionListView.getY() + mentionListViewScrollOffsetY + AndroidUtilities.dp(2);
                float bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
                Theme.chat_composeShadowDrawable.setBounds(0, (int) bottom, getMeasuredWidth(), (int) top);
                Theme.chat_composeShadowDrawable.draw(canvas);
                canvas.drawRect(0, 0, getMeasuredWidth(), top, getThemedPaint(Theme.key_paint_chatComposeBackground));
            } else {
                int top = (int) mentionListView.getY();
                if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout() && mentionsAdapter.getBotContextSwitch() == null) {
                    top += mentionListViewScrollOffsetY - AndroidUtilities.dp(4);
                } else {
                    top += mentionListViewScrollOffsetY - AndroidUtilities.dp(2);
                }
                if (mentionsAdapter.isMediaLayout()) {
                    if (padding == null) {
                        padding = new Rect();
                        Theme.chat_composeShadowRoundDrawable.getPadding(padding);
                    }
                    int bottom = top + Theme.chat_composeShadowRoundDrawable.getIntrinsicHeight();
                    Theme.chat_composeShadowRoundDrawable.setBounds(-padding.left, top - padding.top - AndroidUtilities.dp(8), getMeasuredWidth() + padding.right, (int) (bottomPanelTranslationYReverse + getMeasuredHeight()));
                    Theme.chat_composeShadowRoundDrawable.draw(canvas);
                } else {
                    int bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
                    Theme.chat_composeShadowDrawable.setBounds(0, top, getMeasuredWidth(), bottom);
                    Theme.chat_composeShadowDrawable.draw(canvas);
                    canvas.drawRect(0, bottom, getMeasuredWidth(), bottomPanelTranslationYReverse + getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
                }
            }
        }

        @Override
        public void requestLayout() {
            if (mentionListViewIgnoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    mentionContainer.setVisibility(View.GONE);
    updateMessageListAccessibilityVisibility();
    mentionContainer.setWillNotDraw(false);
    contentView.addView(mentionContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));
    final ContentPreviewViewer.ContentPreviewViewerDelegate contentPreviewViewerDelegate = new ContentPreviewViewer.ContentPreviewViewerDelegate() {

        @Override
        public void sendSticker(TLRPC.Document sticker, String query, Object parent, boolean notify, int scheduleDate) {
            chatActivityEnterView.onStickerSelected(sticker, query, parent, null, true, notify, scheduleDate);
        }

        @Override
        public boolean needSend() {
            return false;
        }

        @Override
        public boolean canSchedule() {
            return ChatActivity.this.canScheduleMessage();
        }

        @Override
        public boolean isInScheduleMode() {
            return chatMode == MODE_SCHEDULED;
        }

        @Override
        public void openSet(TLRPC.InputStickerSet set, boolean clearsInputField) {
            if (set == null || getParentActivity() == null) {
                return;
            }
            TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID();
            inputStickerSet.access_hash = set.access_hash;
            inputStickerSet.id = set.id;
            StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate);
            alert.setCalcMandatoryInsets(isKeyboardVisible());
            alert.setClearsInputField(clearsInputField);
            showDialog(alert);
        }

        @Override
        public long getDialogId() {
            return dialog_id;
        }
    };
    mentionListView = new RecyclerListView(context, themeDelegate) {

        private int lastWidth;

        private int lastHeight;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if (mentionLayoutManager.getReverseLayout()) {
                if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() > mentionListViewScrollOffsetY) {
                    return false;
                }
            } else {
                if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
            }
            boolean result = !mentionListViewIsScrolling && ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, mentionListView, 0, null, themeDelegate);
            if (mentionsAdapter.isStickers() && event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
                mentionsAdapter.doSomeStickersAction();
            }
            return super.onInterceptTouchEvent(event) || result;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (mentionLayoutManager.getReverseLayout()) {
                if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() > mentionListViewScrollOffsetY) {
                    return false;
                }
            } else {
                if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
            }
            // supress warning
            return super.onTouchEvent(event);
        }

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

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            int width = r - l;
            int height = b - t;
            int newPosition = -1;
            int newTop = 0;
            if (!mentionLayoutManager.getReverseLayout() && mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth && height - lastHeight != 0) {
                newPosition = mentionListViewLastViewPosition;
                newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
            }
            super.onLayout(changed, l, t, r, b);
            if (newPosition != -1) {
                mentionListViewIgnoreLayout = true;
                if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
                    mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                } else {
                    mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                }
                super.onLayout(false, l, t, r, b);
                mentionListViewIgnoreLayout = false;
            }
            lastHeight = height;
            lastWidth = width;
            mentionListViewUpdateLayout();
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            mentionContainer.invalidate();
        }
    };
    mentionListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, mentionListView, 0, mentionsOnItemClickListener, mentionsAdapter.isStickers() ? contentPreviewViewerDelegate : null, themeDelegate));
    mentionListView.setTag(2);
    mentionLayoutManager = new LinearLayoutManager(context) {

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }

        @Override
        public void setReverseLayout(boolean reverseLayout) {
            super.setReverseLayout(reverseLayout);
            invalidateChatListViewTopPadding();
        }
    };
    mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {

        private Size size = new Size();

        @Override
        protected Size getSizeForItem(int i) {
            if (mentionsAdapter.getBotContextSwitch() != null) {
                i++;
            }
            size.width = 0;
            size.height = 0;
            Object object = mentionsAdapter.getItem(i);
            if (object instanceof TLRPC.BotInlineResult) {
                TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
                if (inlineResult.document != null) {
                    TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(inlineResult.document.thumbs, 90);
                    size.width = thumb != null ? thumb.w : 100;
                    size.height = thumb != null ? thumb.h : 100;
                    for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                } else if (inlineResult.content != null) {
                    for (int b = 0; b < inlineResult.content.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = inlineResult.content.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                } else if (inlineResult.thumb != null) {
                    for (int b = 0; b < inlineResult.thumb.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = inlineResult.thumb.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                } else if (inlineResult.photo != null) {
                    TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(inlineResult.photo.sizes, AndroidUtilities.photoSize);
                    if (photoSize != null) {
                        size.width = photoSize.w;
                        size.height = photoSize.h;
                    }
                }
            }
            return size;
        }

        @Override
        protected int getFlowItemCount() {
            if (mentionsAdapter.getBotContextSwitch() != null) {
                return getItemCount() - 1;
            }
            return super.getFlowItemCount();
        }
    };
    mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

        @Override
        public int getSpanSize(int position) {
            Object object = mentionsAdapter.getItem(position);
            if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                return 100;
            } else if (object instanceof TLRPC.Document) {
                return 20;
            } else {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    position--;
                }
                return mentionGridLayoutManager.getSpanSizeForItem(position);
            }
        }
    });
    mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.top = 0;
            outRect.bottom = 0;
            if (parent.getLayoutManager() == mentionGridLayoutManager) {
                int position = parent.getChildAdapterPosition(view);
                if (mentionsAdapter.isStickers()) {
                    return;
                } else if (mentionsAdapter.getBotContextSwitch() != null) {
                    if (position == 0) {
                        return;
                    }
                    position--;
                    if (!mentionGridLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                } else {
                    outRect.top = AndroidUtilities.dp(2);
                }
                outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
            }
        }
    });
    mentionListView.setItemAnimator(null);
    mentionListView.setLayoutAnimation(null);
    mentionListView.setClipToPadding(false);
    mentionListView.setLayoutManager(mentionLayoutManager);
    mentionListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    mentionContainer.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id, threadMessageId, new MentionsAdapter.MentionsAdapterDelegate() {

        @Override
        public void needChangePanelVisibility(boolean show) {
            if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
                mentionListView.setLayoutManager(mentionGridLayoutManager);
            } else {
                mentionListView.setLayoutManager(mentionLayoutManager);
            }
            if (show && bottomOverlay.getVisibility() == View.VISIBLE && !searchingForUser) {
                show = false;
            }
            if (show) {
                if (mentionListAnimation != null) {
                    mentionListAnimation.cancel();
                    mentionListAnimation = null;
                }
                if (mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setAlpha(1.0f);
                    return;
                }
                if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
                    mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
                } else if (!mentionLayoutManager.getReverseLayout()) {
                    mentionLayoutManager.scrollToPositionWithOffset(0, mentionLayoutManager.getReverseLayout() ? -10000 : 10000);
                }
                if (allowStickersPanel && (!mentionsAdapter.isBotContext() || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
                        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                        if (!preferences.getBoolean("secretbot", false)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setMessage(LocaleController.getString("SecretChatContextBotAlert", R.string.SecretChatContextBotAlert));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                            showDialog(builder.create());
                            preferences.edit().putBoolean("secretbot", true).commit();
                        }
                    }
                    mentionContainer.setVisibility(View.VISIBLE);
                    updateMessageListAccessibilityVisibility();
                    mentionContainer.setTag(null);
                    mentionListAnimation = new AnimatorSet();
                    mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionContainer, View.ALPHA, 0.0f, 1.0f));
                    mentionListAnimation.addListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
                                mentionListAnimation = null;
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
                                mentionListAnimation = null;
                            }
                        }
                    });
                    mentionListAnimation.setDuration(200);
                    mentionListAnimation.start();
                } else {
                    mentionContainer.setAlpha(1.0f);
                    mentionContainer.setVisibility(View.INVISIBLE);
                    updateMessageListAccessibilityVisibility();
                }
            } else {
                if (mentionListAnimation != null) {
                    mentionListAnimation.cancel();
                    mentionListAnimation = null;
                }
                if (mentionContainer.getVisibility() == View.GONE) {
                    return;
                }
                if (allowStickersPanel) {
                    mentionListAnimation = new AnimatorSet();
                    mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionContainer, View.ALPHA, 0.0f));
                    mentionListAnimation.addListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
                                mentionContainer.setVisibility(View.GONE);
                                mentionContainer.setTag(null);
                                updateMessageListAccessibilityVisibility();
                                mentionListAnimation = null;
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
                                mentionListAnimation = null;
                            }
                        }
                    });
                    mentionListAnimation.setDuration(200);
                    mentionListAnimation.start();
                } else {
                    mentionContainer.setTag(null);
                    mentionContainer.setVisibility(View.GONE);
                    updateMessageListAccessibilityVisibility();
                }
            }
        }

        @Override
        public void onContextSearch(boolean searching) {
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
                chatActivityEnterView.showContextProgress(searching);
            }
        }

        @Override
        public void onContextClick(TLRPC.BotInlineResult result) {
            if (getParentActivity() == null || result.content == null) {
                return;
            }
            if (result.type.equals("video") || result.type.equals("web_player_video")) {
                int[] size = MessageObject.getInlineResultWidthAndHeight(result);
                EmbedBottomSheet.show(getParentActivity(), null, botContextProvider, result.title != null ? result.title : "", result.description, result.content.url, result.content.url, size[0], size[1], isKeyboardVisible());
            } else {
                processExternalUrl(0, result.content.url, false);
            }
        }
    }, themeDelegate));
    if (!ChatObject.isChannel(currentChat) || currentChat.megagroup) {
        mentionsAdapter.setBotInfo(botInfo);
    }
    mentionsAdapter.setParentFragment(this);
    mentionsAdapter.setChatInfo(chatInfo);
    mentionsAdapter.setNeedUsernames(currentChat != null);
    mentionsAdapter.setNeedBotContext(true);
    mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
    mentionListView.setOnItemClickListener(mentionsOnItemClickListener = (view, position) -> {
        if (mentionsAdapter.isBannedInline()) {
            return;
        }
        Object object = mentionsAdapter.getItem(position);
        int start = mentionsAdapter.getResultStartPosition();
        int len = mentionsAdapter.getResultLength();
        if (object instanceof TLRPC.TL_document) {
            if (chatMode == 0 && checkSlowMode(view)) {
                return;
            }
            MessageObject.SendAnimationData sendAnimationData = null;
            if (view instanceof StickerCell) {
                sendAnimationData = ((StickerCell) view).getSendAnimationData();
            }
            TLRPC.TL_document document = (TLRPC.TL_document) object;
            Object parent = mentionsAdapter.getItemParent(position);
            if (chatMode == MODE_SCHEDULED) {
                String query = stickersAdapter.getQuery();
                AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> SendMessagesHelper.getInstance(currentAccount).sendSticker(document, query, dialog_id, replyingMessageObject, getThreadMessage(), parent, null, notify, scheduleDate), themeDelegate);
            } else {
                getSendMessagesHelper().sendSticker(document, stickersAdapter.getQuery(), dialog_id, replyingMessageObject, getThreadMessage(), parent, sendAnimationData, true, 0);
            }
            hideFieldPanel(false);
            chatActivityEnterView.addStickerToRecent(document);
            chatActivityEnterView.setFieldText("");
        } else if (object instanceof TLRPC.Chat) {
            TLRPC.Chat chat = (TLRPC.Chat) object;
            if (searchingForUser && searchContainer.getVisibility() == View.VISIBLE) {
                searchUserMessages(null, chat);
            } else {
                if (chat.username != null) {
                    chatActivityEnterView.replaceWithText(start, len, "@" + chat.username + " ", false);
                }
            }
        } else if (object instanceof TLRPC.User) {
            TLRPC.User user = (TLRPC.User) object;
            if (searchingForUser && searchContainer.getVisibility() == View.VISIBLE) {
                searchUserMessages(user, null);
            } else {
                if (user.username != null) {
                    chatActivityEnterView.replaceWithText(start, len, "@" + user.username + " ", false);
                } else {
                    String name = UserObject.getFirstName(user, false);
                    Spannable spannable = new SpannableString(name + " ");
                    spannable.setSpan(new URLSpanUserMention("" + user.id, 3), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    chatActivityEnterView.replaceWithText(start, len, spannable, false);
                }
            }
        } else if (object instanceof String) {
            if (mentionsAdapter.isBotCommands()) {
                if (chatMode == MODE_SCHEDULED) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> {
                        getSendMessagesHelper().sendMessage((String) object, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, notify, scheduleDate, null);
                        chatActivityEnterView.setFieldText("");
                        hideFieldPanel(false);
                    }, themeDelegate);
                } else {
                    if (checkSlowMode(view)) {
                        return;
                    }
                    getSendMessagesHelper().sendMessage((String) object, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, true, 0, null);
                    chatActivityEnterView.setFieldText("");
                    hideFieldPanel(false);
                }
            } else {
                chatActivityEnterView.replaceWithText(start, len, object + " ", false);
            }
        } else if (object instanceof TLRPC.BotInlineResult) {
            if (chatActivityEnterView.getFieldText() == null || chatMode != MODE_SCHEDULED && checkSlowMode(view)) {
                return;
            }
            TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
            if (currentEncryptedChat != null) {
                int error = 0;
                if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto && "game".equals(result.type)) {
                    error = 1;
                } else if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaInvoice) {
                    error = 2;
                }
                if (error != 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                    builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle));
                    if (error == 1) {
                        builder.setMessage(LocaleController.getString("GameCantSendSecretChat", R.string.GameCantSendSecretChat));
                    } else {
                        builder.setMessage(LocaleController.getString("InvoiceCantSendSecretChat", R.string.InvoiceCantSendSecretChat));
                    }
                    builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null);
                    showDialog(builder.create());
                    return;
                }
            }
            if ((result.type.equals("photo") && (result.photo != null || result.content != null) || result.type.equals("gif") && (result.document != null || result.content != null) || result.type.equals("video") && (result.document != null))) {
                ArrayList<Object> arrayList = botContextResults = new ArrayList<>(mentionsAdapter.getSearchResultBotContext());
                PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate);
                PhotoViewer.getInstance().openPhotoForSelect(arrayList, mentionsAdapter.getItemPosition(position), 3, false, botContextProvider, ChatActivity.this);
            } else {
                if (chatMode == MODE_SCHEDULED) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> sendBotInlineResult(result, notify, scheduleDate), themeDelegate);
                } else {
                    sendBotInlineResult(result, true, 0);
                }
            }
        } else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
            processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
        } else if (object instanceof MediaDataController.KeywordResult) {
            String code = ((MediaDataController.KeywordResult) object).emoji;
            chatActivityEnterView.addEmojiToRecent(code);
            chatActivityEnterView.replaceWithText(start, len, code, true);
        }
    });
    mentionListView.setOnItemLongClickListener((view, position) -> {
        if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
            return false;
        }
        Object object = mentionsAdapter.getItem(position);
        if (object instanceof String) {
            if (mentionsAdapter.isBotCommands()) {
                if (URLSpanBotCommand.enabled) {
                    chatActivityEnterView.setFieldText("");
                    chatActivityEnterView.setCommand(null, (String) object, true, currentChat != null && currentChat.megagroup);
                    return true;
                }
                return false;
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                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);
                showDialog(builder.create());
                return true;
            }
        }
        return false;
    });
    mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            mentionListViewIsScrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
            mentionListViewIsDragging = newState == RecyclerView.SCROLL_STATE_DRAGGING;
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int lastVisibleItem;
            if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
                lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
            } else {
                lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
            }
            int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
            if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
                mentionsAdapter.searchForContextBotForNextOffset();
            }
            mentionListViewUpdateLayout();
        }
    });
    pagedownButtonImage = new ImageView(context);
    pagedownButtonImage.setImageResource(R.drawable.pagedown);
    pagedownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
    pagedownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
    pagedownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0);
    Drawable drawable;
    if (Build.VERSION.SDK_INT >= 21) {
        pagedownButtonImage.setOutlineProvider(new ViewOutlineProvider() {

            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
            }
        });
        drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
    } else {
        drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
    }
    Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
    CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
    combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
    drawable = combinedDrawable;
    pagedownButtonImage.setBackgroundDrawable(drawable);
    pagedownButton.addView(pagedownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM));
    pagedownButton.setContentDescription(LocaleController.getString("AccDescrPageDown", R.string.AccDescrPageDown));
    pagedownButtonCounter = new CounterView(context, themeDelegate) {

        @Override
        public void invalidate() {
            if (isInOutAnimation()) {
                contentView.invalidate();
            }
            super.invalidate();
        }
    };
    pagedownButtonCounter.setReverse(true);
    pagedownButton.addView(pagedownButtonCounter, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP | Gravity.LEFT));
    mentiondownButtonImage = new ImageView(context);
    mentiondownButtonImage.setImageResource(R.drawable.mentionbutton);
    mentiondownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
    mentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
    mentiondownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0);
    if (Build.VERSION.SDK_INT >= 21) {
        pagedownButtonImage.setOutlineProvider(new ViewOutlineProvider() {

            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
            }
        });
        drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
    } else {
        drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
    }
    shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
    combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
    combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
    drawable = combinedDrawable;
    mentiondownButtonImage.setBackgroundDrawable(drawable);
    mentiondownButton.addView(mentiondownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));
    mentiondownButtonCounter = new SimpleTextView(context);
    mentiondownButtonCounter.setVisibility(View.INVISIBLE);
    mentiondownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    mentiondownButtonCounter.setTextSize(13);
    mentiondownButtonCounter.setTextColor(getThemedColor(Theme.key_chat_goDownButtonCounter));
    mentiondownButtonCounter.setGravity(Gravity.CENTER);
    mentiondownButtonCounter.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(11.5f), getThemedColor(Theme.key_chat_goDownButtonCounterBackground)));
    mentiondownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
    mentiondownButtonCounter.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(1), AndroidUtilities.dp(8), 0);
    mentiondownButton.addView(mentiondownButtonCounter, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
    mentiondownButton.setContentDescription(LocaleController.getString("AccDescrMentionDown", R.string.AccDescrMentionDown));
    reactionsMentiondownButton = new FrameLayout(context);
    reactionsMentiondownButton.setOnClickListener(view -> {
        wasManualScroll = true;
        getMessagesController().getNextReactionMention(dialog_id, reactionsMentionCount, (messageId) -> {
            if (messageId == 0) {
                reactionsMentionCount = 0;
                updateReactionsMentionButton(true);
                getMessagesController().markReactionsAsRead(dialog_id);
            } else {
                updateReactionsMentionButton(true);
                scrollToMessageId(messageId, 0, false, 0, true, 0);
            }
        });
    });
    reactionsMentiondownButton.setOnLongClickListener(view -> {
        scrimPopupWindow = ReadAllMentionsMenu.show(ReadAllMentionsMenu.TYPE_REACTIONS, getParentActivity(), contentView, view, getResourceProvider(), () -> {
            for (int i = 0; i < messages.size(); i++) {
                messages.get(i).markReactionsAsRead();
            }
            reactionsMentionCount = 0;
            updateReactionsMentionButton(true);
            getMessagesController().markReactionsAsRead(dialog_id);
            if (scrimPopupWindow != null) {
                scrimPopupWindow.dismiss();
            }
        });
        dimBehindView(reactionsMentiondownButton, true);
        scrimPopupWindow.setOnDismissListener(() -> {
            scrimPopupWindow = null;
            menuDeleteItem = null;
            scrimPopupWindowItems = null;
            chatLayoutManager.setCanScrollVertically(true);
            dimBehindView(false);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.getEditField().setAllowDrawCursor(true);
            }
        });
        view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
        return false;
    });
    contentView.addView(reactionsMentiondownButton, LayoutHelper.createFrame(46, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    reactionsMentiondownButtonImage = new ImageView(context);
    reactionsMentiondownButtonImage.setImageResource(R.drawable.reactionbutton);
    reactionsMentiondownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
    reactionsMentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
    if (Build.VERSION.SDK_INT >= 21) {
        reactionsMentiondownButtonImage.setOutlineProvider(new ViewOutlineProvider() {

            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
            }
        });
        drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
    } else {
        drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
    }
    shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
    combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
    combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
    drawable = combinedDrawable;
    reactionsMentiondownButtonImage.setBackgroundDrawable(drawable);
    reactionsMentiondownButton.addView(reactionsMentiondownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));
    reactionsMentiondownButtonCounter = new CounterView(context, themeDelegate);
    reactionsMentiondownButton.addView(reactionsMentiondownButtonCounter, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP | Gravity.LEFT));
    reactionsMentiondownButton.setContentDescription(LocaleController.getString("AccDescrReactionMentionDown", R.string.AccDescrReactionMentionDown));
    if (!inMenuMode) {
        fragmentLocationContextView = new FragmentContextView(context, this, true, themeDelegate);
        fragmentContextView = new FragmentContextView(context, this, false, themeDelegate) {

            @Override
            protected void playbackSpeedChanged(float value) {
                if (Math.abs(value - 1.0f) < 0.001f || Math.abs(value - 1.8f) < 0.001f) {
                    undoView.showWithAction(0, Math.abs(value - 1.0f) > 0.001f ? UndoView.ACTION_PLAYBACK_SPEED_ENABLED : UndoView.ACTION_PLAYBACK_SPEED_DISABLED, value, null, null);
                }
            }
        };
        contentView.addView(fragmentLocationContextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
        contentView.addView(fragmentContextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
        fragmentContextView.setAdditionalContextView(fragmentLocationContextView);
        fragmentLocationContextView.setAdditionalContextView(fragmentContextView);
    }
    if (chatMode != 0) {
        fragmentContextView.setSupportsCalls(false);
    }
    messagesSearchListView = new RecyclerListView(context, themeDelegate);
    messagesSearchListView.setBackgroundColor(getThemedColor(Theme.key_windowBackgroundWhite));
    LinearLayoutManager messagesSearchLayoutManager = new LinearLayoutManager(context);
    messagesSearchLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    messagesSearchListView.setLayoutManager(messagesSearchLayoutManager);
    messagesSearchListView.setVisibility(View.GONE);
    messagesSearchListView.setAlpha(0.0f);
    messagesSearchListView.setAdapter(messagesSearchAdapter = new MessagesSearchAdapter(context, themeDelegate));
    contentView.addView(messagesSearchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48));
    messagesSearchListView.setOnItemClickListener((view, position) -> {
        getMediaDataController().jumpToSearchedMessage(classGuid, position);
        showMessagesSearchListView(false);
    });
    messagesSearchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int lastVisibleItem = messagesSearchLayoutManager.findLastVisibleItemPosition();
            int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
            if (visibleItemCount > 0 && lastVisibleItem > messagesSearchLayoutManager.getItemCount() - 5) {
                getMediaDataController().loadMoreSearchMessages();
            }
        }
    });
    topUndoView = new UndoView(context, this, true, themeDelegate) {

        @Override
        public void didPressUrl(CharacterStyle span) {
            didPressMessageUrl(span, false, null, null);
        }

        @Override
        public void showWithAction(long did, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) {
            setAdditionalTranslationY(fragmentContextView != null && fragmentContextView.isCallTypeVisible() ? AndroidUtilities.dp(fragmentContextView.getStyleHeight()) : 0);
            super.showWithAction(did, action, infoObject, infoObject2, actionRunnable, cancelRunnable);
        }
    };
    contentView.addView(topUndoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 8, 8, 0));
    contentView.addView(actionBar);
    overlayView = new View(context);
    overlayView.setOnTouchListener((v, event) -> {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            checkRecordLocked(false);
        }
        overlayView.getParent().requestDisallowInterceptTouchEvent(true);
        return true;
    });
    contentView.addView(overlayView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    overlayView.setVisibility(View.GONE);
    contentView.setClipChildren(false);
    instantCameraView = new InstantCameraView(context, this, themeDelegate);
    contentView.addView(instantCameraView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    bottomMessagesActionContainer = new FrameLayout(context) {

        @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(), getThemedPaint(Theme.key_paint_chatComposeBackground));
        }
    };
    bottomMessagesActionContainer.setVisibility(View.INVISIBLE);
    bottomMessagesActionContainer.setWillNotDraw(false);
    bottomMessagesActionContainer.setPadding(0, AndroidUtilities.dp(2), 0, 0);
    contentView.addView(bottomMessagesActionContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomMessagesActionContainer.setOnTouchListener((v, event) -> true);
    chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true, themeDelegate) {

        int lastContentViewHeight;

        int messageEditTextPredrawHeigth;

        int messageEditTextPredrawScrollY;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getAlpha() != 1.0f) {
                return false;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (getAlpha() != 1.0f) {
                return false;
            }
            return super.onTouchEvent(event);
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            if (getAlpha() != 1.0f) {
                return false;
            }
            return super.dispatchTouchEvent(ev);
        }

        @Override
        protected boolean pannelAnimationEnabled() {
            if (!openAnimationEnded) {
                return false;
            }
            return true;
        }

        @Override
        public void checkAnimation() {
            if (actionBar.isActionModeShowed() || reportType >= 0) {
                if (messageEditTextAnimator != null) {
                    messageEditTextAnimator.cancel();
                }
                if (changeBoundAnimator != null) {
                    changeBoundAnimator.cancel();
                }
                chatActivityEnterViewAnimateFromTop = 0;
                shouldAnimateEditTextWithBounds = false;
            } else {
                int t = getBackgroundTop();
                if (chatActivityEnterViewAnimateFromTop != 0 && t != chatActivityEnterViewAnimateFromTop && lastContentViewHeight == contentView.getMeasuredHeight()) {
                    int dy = animatedTop + chatActivityEnterViewAnimateFromTop - t;
                    animatedTop = dy;
                    if (changeBoundAnimator != null) {
                        changeBoundAnimator.removeAllListeners();
                        changeBoundAnimator.cancel();
                    }
                    chatListView.setTranslationY(dy);
                    if (topView != null && topView.getVisibility() == View.VISIBLE) {
                        topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
                        if (topLineView != null) {
                            topLineView.setTranslationY(animatedTop);
                        }
                    }
                    changeBoundAnimator = ValueAnimator.ofFloat(1f, 0);
                    changeBoundAnimator.addUpdateListener(a -> {
                        int v = (int) (dy * (float) a.getAnimatedValue());
                        animatedTop = v;
                        if (topView != null && topView.getVisibility() == View.VISIBLE) {
                            topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
                            if (topLineView != null) {
                                topLineView.setTranslationY(animatedTop);
                            }
                        } else {
                            if (mentionContainer != null) {
                                mentionContainer.setTranslationY(v);
                            }
                            chatListView.setTranslationY(v);
                            invalidateChatListViewTopPadding();
                            invalidateMessagesVisiblePart();
                        }
                        invalidate();
                    });
                    changeBoundAnimator.addListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            animatedTop = 0;
                            if (topView != null && topView.getVisibility() == View.VISIBLE) {
                                topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
                                if (topLineView != null) {
                                    topLineView.setTranslationY(animatedTop);
                                }
                            } else {
                                chatListView.setTranslationY(0);
                            }
                            changeBoundAnimator = null;
                        }
                    });
                    changeBoundAnimator.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
                    changeBoundAnimator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
                    if (!waitingForSendingMessageLoad) {
                        changeBoundAnimator.start();
                    }
                    invalidateChatListViewTopPadding();
                    invalidateMessagesVisiblePart();
                    chatActivityEnterViewAnimateFromTop = 0;
                } else if (lastContentViewHeight != contentView.getMeasuredHeight()) {
                    chatActivityEnterViewAnimateFromTop = 0;
                }
                if (shouldAnimateEditTextWithBounds) {
                    float dy = (messageEditTextPredrawHeigth - messageEditText.getMeasuredHeight()) + (messageEditTextPredrawScrollY - messageEditText.getScrollY());
                    messageEditText.setOffsetY(messageEditText.getOffsetY() - dy);
                    ValueAnimator a = ValueAnimator.ofFloat(messageEditText.getOffsetY(), 0);
                    a.addUpdateListener(animation -> messageEditText.setOffsetY((float) animation.getAnimatedValue()));
                    if (messageEditTextAnimator != null) {
                        messageEditTextAnimator.cancel();
                    }
                    messageEditTextAnimator = a;
                    a.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
                    // a.setStartDelay(chatActivityEnterViewAnimateBeforeSending ? 20 : 0);
                    a.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
                    a.start();
                    shouldAnimateEditTextWithBounds = false;
                }
                lastContentViewHeight = contentView.getMeasuredHeight();
                chatActivityEnterViewAnimateBeforeSending = false;
            }
        }

        @Override
        protected void onLineCountChanged(int oldLineCount, int newLineCount) {
            if (chatActivityEnterView != null) {
                shouldAnimateEditTextWithBounds = true;
                messageEditTextPredrawHeigth = messageEditText.getMeasuredHeight();
                messageEditTextPredrawScrollY = messageEditText.getScrollY();
                contentView.invalidate();
                chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
            }
        }
    };
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {

        int lastSize;

        @Override
        public int getContentViewHeight() {
            return contentView.getHeight();
        }

        @Override
        public int measureKeyboardHeight() {
            return contentView.measureKeyboardHeight();
        }

        @Override
        public TLRPC.TL_channels_sendAsPeers getSendAsPeers() {
            return sendAsPeersObj;
        }

        @Override
        public void onMessageSend(CharSequence message, boolean notify, int scheduleDate) {
            if (chatListItemAnimator != null) {
                chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
                if (chatActivityEnterViewAnimateFromTop != 0) {
                    chatActivityEnterViewAnimateBeforeSending = true;
                }
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.addHashtagsFromMessage(message);
            }
            if (scheduleDate != 0) {
                if (scheduledMessagesCount == -1) {
                    scheduledMessagesCount = 0;
                }
                if (message != null) {
                    scheduledMessagesCount++;
                }
                if (forwardingMessages != null && !forwardingMessages.messages.isEmpty()) {
                    scheduledMessagesCount += forwardingMessages.messages.size();
                }
                updateScheduledInterface(false);
            }
            hideFieldPanel(notify, scheduleDate, true);
            if (chatActivityEnterView != null && chatActivityEnterView.getEmojiView() != null) {
                chatActivityEnterView.getEmojiView().onMessageSend();
            }
        }

        @Override
        public void onSwitchRecordMode(boolean video) {
            showVoiceHint(false, video);
        }

        @Override
        public void onPreAudioVideoRecord() {
            showVoiceHint(true, false);
        }

        @Override
        public void onUpdateSlowModeButton(View button, boolean show, CharSequence time) {
            showSlowModeHint(button, show, time);
            if (headerItem != null && headerItem.getVisibility() != View.VISIBLE) {
                headerItem.setVisibility(View.VISIBLE);
                if (attachItem != null) {
                    attachItem.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onTextSelectionChanged(int start, int end) {
            if (editTextItem == null) {
                return;
            }
            if (end - start > 0) {
                if (editTextItem.getTag() == null) {
                    editTextItem.setTag(1);
                    editTextItem.setVisibility(View.VISIBLE);
                    headerItem.setVisibility(View.GONE);
                    attachItem.setVisibility(View.GONE);
                }
                editTextStart = start;
                editTextEnd = end;
            } else {
                if (editTextItem.getTag() != null) {
                    editTextItem.setTag(null);
                    editTextItem.setVisibility(View.GONE);
                    if (chatActivityEnterView.hasText() && TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer())) {
                        headerItem.setVisibility(View.GONE);
                        attachItem.setVisibility(View.VISIBLE);
                    } else {
                        headerItem.setVisibility(View.VISIBLE);
                        attachItem.setVisibility(View.GONE);
                    }
                }
            }
        }

        @Override
        public void onTextChanged(final CharSequence text, boolean bigChange) {
            MediaController.getInstance().setInputFieldHasText(!TextUtils.isEmpty(text) || chatActivityEnterView.isEditingMessage());
            if (stickersAdapter != null && chatActivityEnterView != null && chatActivityEnterView.getVisibility() == View.VISIBLE && (bottomOverlay == null || bottomOverlay.getVisibility() != View.VISIBLE)) {
                stickersAdapter.searchEmojiByKeyword(text);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(), chatActivityEnterView.getCursorPosition(), messages, false, false);
            }
            if (waitingForCharaterEnterRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
                waitingForCharaterEnterRunnable = null;
            }
            if ((currentChat == null || ChatObject.canSendEmbed(currentChat)) && chatActivityEnterView.isMessageWebPageSearchEnabled() && (!chatActivityEnterView.isEditingMessage() || !chatActivityEnterView.isEditingCaption())) {
                if (bigChange) {
                    searchLinks(text, true);
                } else {
                    waitingForCharaterEnterRunnable = new Runnable() {

                        @Override
                        public void run() {
                            if (this == waitingForCharaterEnterRunnable) {
                                searchLinks(text, false);
                                waitingForCharaterEnterRunnable = null;
                            }
                        }
                    };
                    AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable, AndroidUtilities.WEB_URL == null ? 3000 : 1000);
                }
            }
        }

        @Override
        public void onTextSpansChanged(CharSequence text) {
            searchLinks(text, true);
        }

        @Override
        public void needSendTyping() {
            getMessagesController().sendTyping(dialog_id, threadMessageId, 0, classGuid);
        }

        @Override
        public void onAttachButtonHidden() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (editTextItem != null) {
                editTextItem.setVisibility(View.GONE);
            }
            if (TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer())) {
                if (headerItem != null) {
                    headerItem.setVisibility(View.GONE);
                }
                if (attachItem != null) {
                    attachItem.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void onAttachButtonShow() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.VISIBLE);
            }
            if (editTextItem != null) {
                editTextItem.setVisibility(View.GONE);
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onMessageEditEnd(boolean loading) {
            if (chatListItemAnimator != null) {
                chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
                if (chatActivityEnterViewAnimateFromTop != 0) {
                    chatActivityEnterViewAnimateBeforeSending = true;
                }
            }
            if (!loading) {
                mentionsAdapter.setNeedBotContext(true);
                if (editingMessageObject != null) {
                    AndroidUtilities.runOnUIThread(() -> hideFieldPanel(true), 30);
                }
                boolean waitingForKeyboard = false;
                if (chatActivityEnterView.isPopupShowing()) {
                    chatActivityEnterView.setFieldFocused();
                    waitingForKeyboard = true;
                }
                chatActivityEnterView.setAllowStickersAndGifs(true, true, waitingForKeyboard);
                if (editingMessageObjectReqId != 0) {
                    getConnectionsManager().cancelRequest(editingMessageObjectReqId, true);
                    editingMessageObjectReqId = 0;
                }
                updatePinnedMessageView(true);
                updateBottomOverlay();
                updateVisibleRows();
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
                allowStickersPanel = false;
                if (stickersPanel.getVisibility() == View.VISIBLE) {
                    stickersPanel.setVisibility(View.INVISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setVisibility(View.INVISIBLE);
                    updateMessageListAccessibilityVisibility();
                }
            } else {
                allowStickersPanel = true;
                if (stickersPanel.getVisibility() == View.INVISIBLE) {
                    stickersPanel.setVisibility(View.VISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE && (!mentionsAdapter.isBotContext() || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    mentionContainer.setVisibility(View.VISIBLE);
                    mentionContainer.setTag(null);
                    updateMessageListAccessibilityVisibility();
                }
            }
            allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
            checkContextBotPanel();
            int size2 = size + (chatActivityEnterView.isPopupShowing() ? 1 << 16 : 0);
            if (lastSize != size2) {
                chatActivityEnterViewAnimateFromTop = 0;
                chatActivityEnterViewAnimateBeforeSending = false;
            }
            lastSize = size2;
        }

        @Override
        public void onStickersTab(boolean opened) {
            if (emojiButtonRed != null) {
                emojiButtonRed.setVisibility(View.GONE);
            }
            allowContextBotPanelSecond = !opened;
            checkContextBotPanel();
        }

        @Override
        public void didPressAttachButton() {
            if (chatAttachAlert != null) {
                chatAttachAlert.setEditingMessageObject(null);
            }
            openAttachMenu();
        }

        @Override
        public void needStartRecordVideo(int state, boolean notify, int scheduleDate) {
            if (instantCameraView != null) {
                if (state == 0) {
                    instantCameraView.showCamera();
                    chatListView.stopScroll();
                    chatAdapter.updateRowsSafe();
                } else if (state == 1 || state == 3 || state == 4) {
                    instantCameraView.send(state, notify, scheduleDate);
                } else if (state == 2 || state == 5) {
                    instantCameraView.cancel(state == 2);
                }
            }
        }

        @Override
        public void needChangeVideoPreviewState(int state, float seekProgress) {
            if (instantCameraView != null) {
                instantCameraView.changeVideoPreviewState(state, seekProgress);
            }
        }

        @Override
        public void needStartRecordAudio(int state) {
            int visibility = state == 0 ? View.GONE : View.VISIBLE;
            if (overlayView.getVisibility() != visibility) {
                overlayView.setVisibility(visibility);
            }
        }

        @Override
        public void needShowMediaBanHint() {
            showMediaBannedHint();
        }

        @Override
        public void onStickersExpandedChange() {
            checkRaiseSensors();
            if (chatActivityEnterView.isStickersExpanded()) {
                AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid);
                if (Bulletin.getVisibleBulletin() != null && Bulletin.getVisibleBulletin().isShowing()) {
                    Bulletin.getVisibleBulletin().hide();
                }
            } else {
                AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
            }
        }

        @Override
        public void scrollToSendingMessage() {
            int id = getSendMessagesHelper().getSendingMessageId(dialog_id);
            if (id != 0) {
                scrollToMessageId(id, 0, true, 0, true, 0);
            }
        }

        @Override
        public boolean hasScheduledMessages() {
            return scheduledMessagesCount > 0 && chatMode == 0;
        }

        @Override
        public void onSendLongClick() {
            if (scheduledOrNoSoundHint != null) {
                scheduledOrNoSoundHint.hide();
            }
        }

        @Override
        public void openScheduledMessages() {
            ChatActivity.this.openScheduledMessages();
        }

        @Override
        public void onAudioVideoInterfaceUpdated() {
            updatePagedownButtonVisibility(true);
        }

        @Override
        public void bottomPanelTranslationYChanged(float translation) {
            if (translation != 0) {
                wasManualScroll = true;
            }
            bottomPanelTranslationY = chatActivityEnterView.pannelAniamationInProgress() ? chatActivityEnterView.getEmojiPadding() - translation : 0;
            bottomPanelTranslationYReverse = chatActivityEnterView.pannelAniamationInProgress() ? translation : 0;
            chatActivityEnterView.setTranslationY(translation);
            contentView.setEmojiOffset(chatActivityEnterView.pannelAniamationInProgress(), bottomPanelTranslationY);
            translation += chatActivityEnterView.getTopViewTranslation();
            chatListView.setTranslationY(translation);
            invalidateChatListViewTopPadding();
            invalidateMessagesVisiblePart();
            updateTextureViewPosition(false);
            contentView.invalidate();
            updateBulletinLayout();
        }

        @Override
        public void prepareMessageSending() {
            waitingForSendingMessageLoad = true;
        }

        @Override
        public void onTrendingStickersShowed(boolean show) {
            if (show) {
                AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid);
                fragmentView.requestLayout();
            } else {
                AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
            }
        }

        @Override
        public boolean hasForwardingMessages() {
            return forwardingMessages != null && !forwardingMessages.messages.isEmpty();
        }
    });
    chatActivityEnterView.setDialogId(dialog_id, currentAccount);
    if (chatInfo != null) {
        chatActivityEnterView.setChatInfo(chatInfo);
    }
    chatActivityEnterView.setId(id_chat_compose_panel);
    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, false);
    chatActivityEnterView.setMinimumHeight(AndroidUtilities.dp(51));
    chatActivityEnterView.setAllowStickersAndGifs(true, currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
    if (inPreviewMode) {
        chatActivityEnterView.setVisibility(View.INVISIBLE);
    }
    if (!ChatObject.isChannel(currentChat) || currentChat.megagroup) {
        chatActivityEnterView.setBotInfo(botInfo);
    }
    contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
    chatActivityEnterTopView = new ChatActivityEnterTopView(context) {

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.invalidate();
            }
            if (getVisibility() != GONE) {
                hideHints(true);
                if (chatListView != null) {
                    chatListView.setTranslationY(translationY);
                }
                if (progressView != null) {
                    progressView.setTranslationY(translationY);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(translationY);
                }
                invalidateChatListViewTopPadding();
                invalidateMessagesVisiblePart();
                if (fragmentView != null) {
                    fragmentView.invalidate();
                }
            }
        }

        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (visibility == GONE) {
                if (chatListView != null) {
                    chatListView.setTranslationY(0);
                }
                if (progressView != null) {
                    progressView.setTranslationY(0);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(0);
                }
            }
        }
    };
    replyLineView = new View(context);
    replyLineView.setBackgroundColor(getThemedColor(Theme.key_chat_replyPanelLine));
    chatActivityEnterView.addTopView(chatActivityEnterTopView, replyLineView, 48);
    final FrameLayout replyLayout = new FrameLayout(context);
    chatActivityEnterTopView.addReplyView(replyLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, 0, 52, 0));
    replyLayout.setOnClickListener(v -> {
        if (forwardingMessages != null && !forwardingMessages.messages.isEmpty()) {
            SharedConfig.forwardingOptionsHintHintShowed();
            openForwardingPreview();
        } else if (replyingMessageObject != null && (!isThreadChat() || replyingMessageObject.getId() != threadMessageId)) {
            scrollToMessageId(replyingMessageObject.getId(), 0, true, 0, true, 0);
        } else if (editingMessageObject != null) {
            if (editingMessageObject.canEditMedia() && editingMessageObjectReqId == 0) {
                if (chatAttachAlert == null) {
                    createChatAttachView();
                }
                chatAttachAlert.setEditingMessageObject(editingMessageObject);
                openAttachMenu();
            } else {
                scrollToMessageId(editingMessageObject.getId(), 0, true, 0, true, 0);
            }
        }
    });
    replyIconImageView = new ImageView(context);
    replyIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelIcons), PorterDuff.Mode.MULTIPLY));
    replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));
    replyCloseImageView = new ImageView(context);
    replyCloseImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelClose), PorterDuff.Mode.MULTIPLY));
    replyCloseImageView.setImageResource(R.drawable.input_clear);
    replyCloseImageView.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        replyCloseImageView.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(18)));
    }
    chatActivityEnterTopView.addView(replyCloseImageView, LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
    replyCloseImageView.setOnClickListener(v -> {
        if (forwardingMessages == null || forwardingMessages.messages.isEmpty()) {
            showFieldPanel(false, null, null, null, foundWebPage, true, 0, true, true);
        } else {
            openAnotherForward();
        }
    });
    replyNameTextView = new SimpleTextView(context);
    replyNameTextView.setTextSize(14);
    replyNameTextView.setTextColor(getThemedColor(Theme.key_chat_replyPanelName));
    replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    replyLayout.addView(replyNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));
    replyObjectTextView = new SimpleTextView(context);
    replyObjectTextView.setTextSize(14);
    replyObjectTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
    replyLayout.addView(replyObjectTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0));
    replyObjectHintTextView = new SimpleTextView(context);
    replyObjectHintTextView.setTextSize(14);
    replyObjectHintTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
    replyObjectHintTextView.setText(LocaleController.getString("TapForForwardingOptions", R.string.TapForForwardingOptions));
    replyObjectHintTextView.setAlpha(0f);
    replyLayout.addView(replyObjectHintTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0));
    replyImageView = new BackupImageView(context);
    replyImageView.setRoundRadius(AndroidUtilities.dp(2));
    replyLayout.addView(replyImageView, LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));
    stickersPanel = new FrameLayout(context);
    stickersPanel.setVisibility(View.GONE);
    contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));
    final ChatActivityEnterTopView.EditView editView = new ChatActivityEnterTopView.EditView(context);
    editView.setMotionEventSplittingEnabled(false);
    editView.setOrientation(LinearLayout.HORIZONTAL);
    editView.setOnClickListener(v -> {
        if (editingMessageObject != null) {
            scrollToMessageId(editingMessageObject.getId(), 0, true, 0, true, 0);
        }
    });
    chatActivityEnterTopView.addEditView(editView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, 0, 48, 0));
    for (int i = 0; i < 2; i++) {
        final boolean firstButton = i == 0;
        final ChatActivityEnterTopView.EditViewButton button = new ChatActivityEnterTopView.EditViewButton(context) {

            @Override
            public void setEditButton(boolean editButton) {
                super.setEditButton(editButton);
                if (firstButton) {
                    getTextView().setMaxWidth(editButton ? AndroidUtilities.dp(116) : Integer.MAX_VALUE);
                }
            }

            @Override
            public void updateColors() {
                final int leftInset = firstButton ? AndroidUtilities.dp(14) : 0;
                setBackground(Theme.createCircleSelectorDrawable(getThemedColor(Theme.key_chat_replyPanelName) & 0x19ffffff, leftInset, 0));
                getImageView().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelName), PorterDuff.Mode.MULTIPLY));
                getTextView().setTextColor(getThemedColor(Theme.key_chat_replyPanelName));
            }
        };
        button.setOrientation(LinearLayout.HORIZONTAL);
        ViewHelper.setPadding(button, 10, 0, 10, 0);
        editView.addButton(button, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
        final ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        imageView.setImageResource(firstButton ? R.drawable.msg_photoeditor : R.drawable.msg_replace);
        button.addImageView(imageView, LayoutHelper.createLinear(24, LayoutHelper.MATCH_PARENT));
        button.addView(new Space(context), LayoutHelper.createLinear(10, LayoutHelper.MATCH_PARENT));
        final TextView textView = new TextView(context);
        textView.setMaxLines(1);
        textView.setSingleLine(true);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        button.addTextView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
        button.updateColors();
        button.setOnClickListener(v -> {
            if (editingMessageObject == null || !editingMessageObject.canEditMedia() || editingMessageObjectReqId != 0) {
                return;
            }
            if (button.isEditButton()) {
                openEditingMessageInPhotoEditor();
            } else {
                replyLayout.callOnClick();
            }
        });
    }
    stickersListView = new RecyclerListView(context, themeDelegate) {

        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView, 0, contentPreviewViewerDelegate, themeDelegate);
            return super.onInterceptTouchEvent(event) || result;
        }
    };
    stickersListView.setTag(3);
    stickersListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersListView, 0, stickersOnItemClickListener, contentPreviewViewerDelegate, themeDelegate));
    stickersListView.setDisallowInterceptTouchEvents(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    stickersListView.setLayoutManager(layoutManager);
    stickersListView.setClipToPadding(false);
    stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
    initStickers();
    stickersPanelArrow = new ImageView(context);
    stickersPanelArrow.setImageResource(R.drawable.stickers_back_arrow);
    stickersPanelArrow.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY));
    stickersPanel.addView(stickersPanelArrow, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 53, 0));
    searchContainer = new FrameLayout(context) {

        @Override
        public void onDraw(Canvas canvas) {
            int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
            if (chatActivityEnterView.getVisibility() != View.VISIBLE) {
                Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
                Theme.chat_composeShadowDrawable.draw(canvas);
            }
            canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
        }

        @Override
        protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
            if (child == searchCountText) {
                int leftMargin = 14;
                if (searchCalendarButton != null && searchCalendarButton.getVisibility() != GONE) {
                    leftMargin += 48;
                }
                if (searchUserButton != null && searchUserButton.getVisibility() != GONE) {
                    leftMargin += 48;
                }
                ((MarginLayoutParams) child.getLayoutParams()).leftMargin = AndroidUtilities.dp(leftMargin);
            }
            super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
        }
    };
    searchContainer.setWillNotDraw(false);
    searchContainer.setVisibility(View.INVISIBLE);
    searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    searchContainer.setClipToPadding(false);
    searchAsListTogglerView = new View(context);
    searchAsListTogglerView.setOnTouchListener((v, event) -> getMediaDataController().getFoundMessageObjects().size() <= 1);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        searchAsListTogglerView.setBackground(Theme.getSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false));
    }
    searchAsListTogglerView.setOnClickListener(v -> {
        if (getMediaDataController().getFoundMessageObjects().size() > 1) {
            if (searchAsListHint != null) {
                searchAsListHint.hide();
            }
            toggleMesagesSearchListView();
            if (!SharedConfig.searchMessagesAsListUsed) {
                SharedConfig.setSearchMessagesAsListUsed(true);
            }
        }
    });
    final float paddingTop = Theme.chat_composeShadowDrawable.getIntrinsicHeight() / AndroidUtilities.density - 3f;
    searchContainer.addView(searchAsListTogglerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, paddingTop, 0, 0));
    searchUpButton = new ImageView(context);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(R.drawable.msg_go_up);
    searchUpButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
    searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0));
    searchUpButton.setOnClickListener(view -> {
        getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1, threadMessageId, searchingUserMessages, searchingChatMessages);
        showMessagesSearchListView(false);
        if (!SharedConfig.searchMessagesAsListUsed && SharedConfig.searchMessagesAsListHintShows < 3 && !searchAsListHintShown && Math.random() <= 0.25) {
            showSearchAsListHint();
            searchAsListHintShown = true;
            SharedConfig.increaseSearchAsListHintShows();
        }
    });
    searchUpButton.setContentDescription(LocaleController.getString("AccDescrSearchNext", R.string.AccDescrSearchNext));
    searchDownButton = new ImageView(context);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(R.drawable.msg_go_down);
    searchDownButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
    searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchContainer.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0));
    searchDownButton.setOnClickListener(view -> {
        getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2, threadMessageId, searchingUserMessages, searchingChatMessages);
        showMessagesSearchListView(false);
    });
    searchDownButton.setContentDescription(LocaleController.getString("AccDescrSearchPrev", R.string.AccDescrSearchPrev));
    if (currentChat != null && (!ChatObject.isChannel(currentChat) || currentChat.megagroup)) {
        searchUserButton = new ImageView(context);
        searchUserButton.setScaleType(ImageView.ScaleType.CENTER);
        searchUserButton.setImageResource(R.drawable.msg_usersearch);
        searchUserButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
        searchUserButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
        searchContainer.addView(searchUserButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
        searchUserButton.setOnClickListener(view -> {
            mentionLayoutManager.setReverseLayout(true);
            mentionsAdapter.setSearchingMentions(true);
            searchCalendarButton.setVisibility(View.GONE);
            searchUserButton.setVisibility(View.GONE);
            searchingForUser = true;
            searchingUserMessages = null;
            searchingChatMessages = null;
            searchItem.setSearchFieldHint(LocaleController.getString("SearchMembers", R.string.SearchMembers));
            searchItem.setSearchFieldCaption(LocaleController.getString("SearchFrom", R.string.SearchFrom));
            AndroidUtilities.showKeyboard(searchItem.getSearchField());
            searchItem.clearSearchText();
        });
        searchUserButton.setContentDescription(LocaleController.getString("AccDescrSearchByUser", R.string.AccDescrSearchByUser));
    }
    searchCalendarButton = new ImageView(context);
    searchCalendarButton.setScaleType(ImageView.ScaleType.CENTER);
    searchCalendarButton.setImageResource(R.drawable.msg_calendar);
    searchCalendarButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
    searchCalendarButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchContainer.addView(searchCalendarButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
    searchCalendarButton.setOnClickListener(view -> {
        if (getParentActivity() == null) {
            return;
        }
        AndroidUtilities.hideKeyboard(searchItem.getSearchField());
        showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, new MessagesStorage.IntCallback() {

            @Override
            public void run(int param) {
                jumpToDate(param);
            }
        }, themeDelegate).create());
    });
    searchCalendarButton.setContentDescription(LocaleController.getString("JumpToDate", R.string.JumpToDate));
    searchCountText = new SearchCounterView(context, themeDelegate);
    searchCountText.setGravity(Gravity.LEFT);
    searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 0, 108, 0));
    bottomOverlay = new FrameLayout(context) {

        @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(), getThemedPaint(Theme.key_paint_chatComposeBackground));
        }
    };
    bottomOverlay.setWillNotDraw(false);
    bottomOverlay.setVisibility(View.INVISIBLE);
    bottomOverlay.setFocusable(true);
    bottomOverlay.setFocusableInTouchMode(true);
    bottomOverlay.setClickable(true);
    bottomOverlay.setPadding(0, AndroidUtilities.dp(2), 0, 0);
    contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayText = new TextView(context);
    bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    bottomOverlayText.setGravity(Gravity.CENTER);
    bottomOverlayText.setMaxLines(2);
    bottomOverlayText.setEllipsize(TextUtils.TruncateAt.END);
    bottomOverlayText.setLineSpacing(AndroidUtilities.dp(2), 1);
    bottomOverlayText.setTextColor(getThemedColor(Theme.key_chat_secretChatStatusText));
    bottomOverlay.addView(bottomOverlayText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 14, 0, 14, 0));
    bottomOverlayChat = new ChatBlurredFrameLayout(context, this) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int allWidth = MeasureSpec.getSize(widthMeasureSpec);
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) bottomOverlayChatText.getLayoutParams();
            layoutParams.width = allWidth;
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
            Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
            Theme.chat_composeShadowDrawable.draw(canvas);
            if (SharedConfig.chatBlurEnabled()) {
                if (backgroundPaint == null) {
                    backgroundPaint = new Paint();
                }
                backgroundPaint.setColor(getThemedColor(Theme.key_chat_messagePanelBackground));
                AndroidUtilities.rectTmp2.set(0, bottom, getMeasuredWidth(), getMeasuredHeight());
                contentView.drawBlur(canvas, getY(), AndroidUtilities.rectTmp2, backgroundPaint, false);
            } else {
                canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
            }
            super.dispatchDraw(canvas);
        }
    };
    bottomOverlayChat.isTopView = false;
    bottomOverlayChat.drawBlur = false;
    bottomOverlayChat.setWillNotDraw(false);
    bottomOverlayChat.setPadding(0, AndroidUtilities.dp(1.5f), 0, 0);
    bottomOverlayChat.setVisibility(View.INVISIBLE);
    bottomOverlayChat.setClipChildren(false);
    contentView.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayChatText = new UnreadCounterTextView(context);
    bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 0, 1.5f, 0, 0));
    bottomOverlayChatText.setOnClickListener(view -> {
        if (getParentActivity() == null || pullingDownOffset != 0) {
            return;
        }
        if (reportType >= 0) {
            showDialog(new ReportAlert(getParentActivity(), reportType) {

                @Override
                protected void onSend(int type, String message) {
                    ArrayList<Integer> ids = new ArrayList<>();
                    for (int b = 0; b < selectedMessagesIds[0].size(); b++) {
                        ids.add(selectedMessagesIds[0].keyAt(b));
                    }
                    TLRPC.InputPeer peer = currentUser != null ? MessagesController.getInputPeer(currentUser) : MessagesController.getInputPeer(currentChat);
                    AlertsCreator.sendReport(peer, reportType, message, ids);
                    finishFragment();
                    chatActivityDelegate.onReport();
                }
            });
        } else if (chatMode == MODE_PINNED) {
            finishFragment();
            chatActivityDelegate.onUnpin(true, bottomOverlayChatText.getTag() == null);
        } else if (currentUser != null && userBlocked) {
            if (currentUser.bot) {
                String botUserLast = botUser;
                botUser = null;
                getMessagesController().unblockPeer(currentUser.id);
                if (botUserLast != null && botUserLast.length() != 0) {
                    getMessagesController().sendBotStart(currentUser, botUserLast);
                } else {
                    getSendMessagesHelper().sendMessage("/start", dialog_id, null, null, null, false, null, null, null, true, 0, null);
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> getMessagesController().unblockPeer(currentUser.id));
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            }
        } else if (UserObject.isReplyUser(currentUser)) {
            toggleMute(true);
        } else if (currentUser != null && currentUser.bot && botUser != null) {
            if (botUser.length() != 0) {
                getMessagesController().sendBotStart(currentUser, botUser);
            } else {
                getSendMessagesHelper().sendMessage("/start", dialog_id, null, null, null, false, null, null, null, true, 0, null);
            }
            botUser = null;
            updateBottomOverlay();
        } else {
            if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
                if (ChatObject.isNotInChat(currentChat)) {
                    if (chatInviteRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(chatInviteRunnable);
                        chatInviteRunnable = null;
                    }
                    showBottomOverlayProgress(true, true);
                    getMessagesController().addUserToChat(currentChat.id, getUserConfig().getCurrentUser(), 0, null, ChatActivity.this, null);
                    NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.closeSearchByActiveAction);
                    if (hasReportSpam() && reportSpamButton.getTag(R.id.object_tag) != null) {
                        SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                        preferences.edit().putInt("dialog_bar_vis3" + dialog_id, 3).commit();
                        getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, dialog_id);
                    }
                } else {
                    toggleMute(true);
                }
            } else {
                AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, false, currentChat, currentUser, currentEncryptedChat != null, true, (param) -> {
                    getNotificationCenter().removeObserver(ChatActivity.this, NotificationCenter.closeChats);
                    getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
                    finishFragment();
                    getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, dialog_id, currentUser, currentChat, param);
                }, themeDelegate);
            }
        }
    });
    bottomOverlayProgress = new RadialProgressView(context, themeDelegate);
    bottomOverlayProgress.setSize(AndroidUtilities.dp(22));
    bottomOverlayProgress.setProgressColor(getThemedColor(Theme.key_chat_fieldOverlayText));
    bottomOverlayProgress.setVisibility(View.INVISIBLE);
    bottomOverlayProgress.setScaleX(0.1f);
    bottomOverlayProgress.setScaleY(0.1f);
    bottomOverlayProgress.setAlpha(1.0f);
    bottomOverlayChat.addView(bottomOverlayProgress, LayoutHelper.createFrame(30, 30, Gravity.CENTER));
    bottomOverlayImage = new ImageView(context);
    int color = getThemedColor(Theme.key_chat_fieldOverlayText);
    bottomOverlayImage.setImageResource(R.drawable.log_info);
    bottomOverlayImage.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
    bottomOverlayImage.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        bottomOverlayImage.setBackgroundDrawable(Theme.createSelectorDrawable(Color.argb(24, Color.red(color), Color.green(color), Color.blue(color)), 1));
    }
    bottomOverlayChat.addView(bottomOverlayImage, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 3, 1.5f, 0, 0));
    bottomOverlayImage.setContentDescription(LocaleController.getString("SettingsHelp", R.string.SettingsHelp));
    bottomOverlayImage.setOnClickListener(v -> undoView.showWithAction(dialog_id, UndoView.ACTION_TEXT_INFO, LocaleController.getString("BroadcastGroupInfo", R.string.BroadcastGroupInfo)));
    replyButton = new TextView(context);
    replyButton.setText(LocaleController.getString("Reply", R.string.Reply));
    replyButton.setGravity(Gravity.CENTER_VERTICAL);
    replyButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    replyButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(21), 0);
    replyButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3));
    replyButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
    replyButton.setCompoundDrawablePadding(AndroidUtilities.dp(7));
    replyButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    Drawable image = context.getResources().getDrawable(R.drawable.input_reply).mutate();
    image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY));
    replyButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
    replyButton.setOnClickListener(v -> {
        MessageObject messageObject = null;
        for (int a = 1; a >= 0; a--) {
            if (messageObject == null && selectedMessagesIds[a].size() != 0) {
                messageObject = messagesDict[a].get(selectedMessagesIds[a].keyAt(0));
            }
            selectedMessagesIds[a].clear();
            selectedMessagesCanCopyIds[a].clear();
            selectedMessagesCanStarIds[a].clear();
        }
        hideActionMode();
        if (messageObject != null && (messageObject.messageOwner.id > 0 || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
            showFieldPanelForReply(messageObject);
        }
        updatePinnedMessageView(true);
        updateVisibleRows();
    });
    bottomMessagesActionContainer.addView(replyButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    forwardButton = new TextView(context);
    forwardButton.setText(LocaleController.getString("Forward", R.string.Forward));
    forwardButton.setGravity(Gravity.CENTER_VERTICAL);
    forwardButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    forwardButton.setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
    forwardButton.setCompoundDrawablePadding(AndroidUtilities.dp(6));
    forwardButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3));
    forwardButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
    forwardButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    image = context.getResources().getDrawable(R.drawable.input_forward).mutate();
    image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY));
    forwardButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
    forwardButton.setOnClickListener(v -> openForward(false));
    bottomMessagesActionContainer.addView(forwardButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP));
    contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    contentView.addView(messageEnterTransitionContainer = new MessageEnterTransitionContainer(contentView, currentAccount));
    undoView = new UndoView(context, this, false, themeDelegate);
    undoView.setAdditionalTranslationY(AndroidUtilities.dp(51));
    contentView.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    if (currentChat != null) {
        slowModeHint = new HintView(getParentActivity(), 2, themeDelegate);
        slowModeHint.setAlpha(0.0f);
        slowModeHint.setVisibility(View.INVISIBLE);
        contentView.addView(slowModeHint, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 19, 0, 19, 0));
    }
    chatAdapter.updateRowsSafe();
    if (loading && messages.isEmpty()) {
        showProgressView(chatAdapter.botInfoRow < 0);
        chatListView.setEmptyView(null);
    } else {
        showProgressView(false);
        chatListView.setEmptyView(emptyViewContainer);
    }
    checkBotKeyboard();
    updateBottomOverlay();
    updateSecretStatus();
    updateTopPanel(false);
    updatePinnedMessageView(false);
    updateInfoTopView(false);
    chatScrollHelper = new RecyclerAnimationScrollHelper(chatListView, chatLayoutManager);
    chatScrollHelper.setScrollListener(this::invalidateMessagesVisiblePart);
    chatScrollHelper.setAnimationCallback(chatScrollHelperCallback);
    if (currentEncryptedChat != null && (SharedConfig.passcodeHash.length() == 0 || SharedConfig.allowScreenCapture)) {
        unregisterFlagSecurePasscode = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
    }
    if (getMessagesController().isChatNoForwards(currentChat)) {
        unregisterFlagSecureNoforwards = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
    }
    if (oldMessage != null) {
        chatActivityEnterView.setFieldText(oldMessage);
    }
    fixLayoutInternal();
    textSelectionHelper.setCallback(new TextSelectionHelper.Callback() {

        @Override
        public void onStateChanged(boolean isSelected) {
            swipeBackEnabled = !isSelected;
            if (isSelected) {
                if (slidingView != null) {
                    slidingView.setSlidingOffset(0);
                    slidingView = null;
                }
                maybeStartTrackingSlidingView = false;
                startedTrackingSlidingView = false;
                if (textSelectionHint != null) {
                    textSelectionHint.hide();
                }
            }
            updatePagedownButtonVisibility(true);
        }

        @Override
        public void onTextCopied() {
            if (actionBar != null && actionBar.isActionModeShowed()) {
                clearSelectionMode();
            }
            undoView.showWithAction(0, UndoView.ACTION_TEXT_COPIED, null);
        }
    });
    contentView.addView(textSelectionHelper.getOverlayView(context));
    fireworksOverlay = new FireworksOverlay(context);
    contentView.addView(fireworksOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    textSelectionHelper.setParentView(chatListView);
    long searchFromUserId = getArguments().getInt("search_from_user_id", 0);
    long searchFromChatId = getArguments().getInt("search_from_chat_id", 0);
    if (searchFromUserId != 0) {
        TLRPC.User user = getMessagesController().getUser(searchFromUserId);
        if (user != null) {
            openSearchWithText("");
            searchUserButton.callOnClick();
            searchUserMessages(user, null);
        }
    } else if (searchFromChatId != 0) {
        TLRPC.Chat chat = getMessagesController().getChat(searchFromChatId);
        if (chat != null) {
            openSearchWithText("");
            searchUserButton.callOnClick();
            searchUserMessages(null, chat);
        }
    }
    if (replyingMessageObject != null) {
        chatActivityEnterView.setReplyingMessageObject(replyingMessageObject);
    }
    ViewGroup decorView;
    if (Build.VERSION.SDK_INT >= 21) {
        decorView = (ViewGroup) getParentActivity().getWindow().getDecorView();
    } else {
        decorView = contentView;
    }
    pinchToZoomHelper = new PinchToZoomHelper(decorView, contentView) {

        @Override
        protected void drawOverlays(Canvas canvas, float alpha, float parentOffsetX, float parentOffsetY, float clipTop, float clipBottom) {
            if (alpha > 0) {
                View view = getChild();
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    int top = (int) Math.max(clipTop, parentOffsetY);
                    int bottom = (int) Math.min(clipBottom, parentOffsetY + cell.getMeasuredHeight());
                    AndroidUtilities.rectTmp.set(parentOffsetX, top, parentOffsetX + cell.getMeasuredWidth(), bottom);
                    canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
                    canvas.translate(parentOffsetX, parentOffsetY);
                    cell.drawFromPinchToZoom = true;
                    cell.drawOverlays(canvas);
                    if (cell.shouldDrawTimeOnMedia() && cell.getCurrentMessagesGroup() == null) {
                        cell.drawTime(canvas, 1f, false);
                    }
                    cell.drawFromPinchToZoom = false;
                    canvas.restore();
                }
            }
        }
    };
    pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {

        @Override
        public TextureView getCurrentTextureView() {
            return videoTextureView;
        }

        @Override
        public void onZoomStarted(MessageObject messageObject) {
            chatListView.cancelClickRunnables(true);
            chatListView.stopScroll();
            if (MediaController.getInstance().isPlayingMessage(messageObject)) {
                contentView.removeView(videoPlayerContainer);
                videoPlayerContainer = null;
                videoTextureView = null;
                aspectRatioFrameLayout = null;
            }
            for (int i = 0; i < chatListView.getChildCount(); i++) {
                if (chatListView.getChildAt(i) instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) chatListView.getChildAt(i);
                    if (cell.getMessageObject().getId() == messageObject.getId()) {
                        cell.getPhotoImage().setVisible(false, true);
                    }
                }
            }
        }

        @Override
        public void onZoomFinished(MessageObject messageObject) {
            if (messageObject == null) {
                return;
            }
            if (MediaController.getInstance().isPlayingMessage(messageObject)) {
                for (int i = 0; i < chatListView.getChildCount(); i++) {
                    if (chatListView.getChildAt(i) instanceof ChatMessageCell) {
                        ChatMessageCell cell = (ChatMessageCell) chatListView.getChildAt(i);
                        if (cell.getMessageObject().getId() == messageObject.getId()) {
                            AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
                            if (animation.isRunning()) {
                                animation.stop();
                            }
                            if (animation != null) {
                                Bitmap bitmap = animation.getAnimatedBitmap();
                                if (bitmap != null) {
                                    try {
                                        Bitmap src = pinchToZoomHelper.getVideoBitmap(bitmap.getWidth(), bitmap.getHeight());
                                        Canvas canvas = new Canvas(bitmap);
                                        canvas.drawBitmap(src, 0, 0, null);
                                        src.recycle();
                                    } catch (Throwable e) {
                                        FileLog.e(e);
                                    }
                                }
                            }
                        }
                    }
                }
                createTextureView(true);
                MediaController.getInstance().setTextureView(videoTextureView, aspectRatioFrameLayout, videoPlayerContainer, true);
            }
            chatListView.invalidate();
        }
    });
    pinchToZoomHelper.setClipBoundsListener(topBottom -> {
        topBottom[1] = chatListView.getBottom();
        topBottom[0] = chatListView.getTop() + chatListViewPaddingTop - AndroidUtilities.dp(4);
    });
    emojiAnimationsOverlay = new EmojiAnimationsOverlay(ChatActivity.this, contentView, chatListView, currentAccount, dialog_id, threadMessageId);
    actionBar.setDrawBlurBackground(contentView);
    TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(dialog_id);
    if (dialog != null) {
        reactionsMentionCount = dialog.unread_reactions_count;
        updateReactionsMentionButton(false);
    }
    return fragmentView;
}
Also used : ViewHelper(org.telegram.ui.Components.ViewHelper) Bundle(android.os.Bundle) BotHelpCell(org.telegram.ui.Cells.BotHelpCell) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) StickersAlert(org.telegram.ui.Components.StickersAlert) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) Property(android.util.Property) HorizontalScrollView(android.widget.HorizontalScrollView) ChatThemeController(org.telegram.messenger.ChatThemeController) MediaStore(android.provider.MediaStore) Map(java.util.Map) Shader(android.graphics.Shader) ContextCompat(androidx.core.content.ContextCompat) NotificationCenter(org.telegram.messenger.NotificationCenter) PinnedLineView(org.telegram.ui.Components.PinnedLineView) CountDownLatch(java.util.concurrent.CountDownLatch) Layout(android.text.Layout) EmojiData(org.telegram.messenger.EmojiData) ForwardingMessagesParams(org.telegram.messenger.ForwardingMessagesParams) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) Paint(android.graphics.Paint) Path(android.graphics.Path) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SystemClock(android.os.SystemClock) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) 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) ChatActivityMemberRequestsDelegate(org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) EditText(android.widget.EditText) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) Animator(android.animation.Animator) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) ChatAttachAlertDocumentLayout(org.telegram.ui.Components.ChatAttachAlertDocumentLayout) DatePickerDialog(android.app.DatePickerDialog) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) StickersAdapter(org.telegram.ui.Adapters.StickersAdapter) RectF(android.graphics.RectF) ReportAlert(org.telegram.ui.Components.ReportAlert) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ShareAlert(org.telegram.ui.Components.ShareAlert) BluredView(org.telegram.ui.Components.BluredView) UserConfig(org.telegram.messenger.UserConfig) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) EmojiThemes(org.telegram.ui.ActionBar.EmojiThemes) InstantCameraView(org.telegram.ui.Components.InstantCameraView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ImportingAlert(org.telegram.ui.Components.ImportingAlert) Spanned(android.text.Spanned) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) SparseIntArray(android.util.SparseIntArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LocaleController(org.telegram.messenger.LocaleController) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) ActionBar(org.telegram.ui.ActionBar.ActionBar) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) TLObject(org.telegram.tgnet.TLObject) Size(org.telegram.ui.Components.Size) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) PollVotesAlert(org.telegram.ui.Components.PollVotesAlert) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) CharacterStyle(android.text.style.CharacterStyle) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) 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) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Matcher(java.util.regex.Matcher) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) Canvas(android.graphics.Canvas) AccessibilityEvent(android.view.accessibility.AccessibilityEvent) Emoji(org.telegram.messenger.Emoji) MessagesSearchAdapter(org.telegram.ui.Adapters.MessagesSearchAdapter) ColorMatrix(android.graphics.ColorMatrix) ForegroundColorSpan(android.text.style.ForegroundColorSpan) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BackButtonMenu(org.telegram.ui.Components.BackButtonMenu) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) ColorMatrixColorFilter(android.graphics.ColorMatrixColorFilter) CounterView(org.telegram.ui.Components.CounterView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) TrendingStickersAlert(org.telegram.ui.Components.TrendingStickersAlert) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) TextPaint(android.text.TextPaint) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) HintView(org.telegram.ui.Components.HintView) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) URLSpanBotCommand(org.telegram.ui.Components.URLSpanBotCommand) ReactionsLayoutInBubble(org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble) ExifInterface(androidx.exifinterface.media.ExifInterface) FileLoader(org.telegram.messenger.FileLoader) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) Space(android.widget.Space) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) BitmapFactory(android.graphics.BitmapFactory) GigagroupConvertAlert(org.telegram.ui.Components.GigagroupConvertAlert) URLSpanMono(org.telegram.ui.Components.URLSpanMono) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) ArrayList(java.util.ArrayList) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) EditTextCaption(org.telegram.ui.Components.EditTextCaption) BuildConfig(org.telegram.messenger.BuildConfig) DialogCell(org.telegram.ui.Cells.DialogCell) SpannableString(android.text.SpannableString) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) ChatUnreadCell(org.telegram.ui.Cells.ChatUnreadCell) ChatLoadingCell(org.telegram.ui.Cells.ChatLoadingCell) ClippingImageView(org.telegram.ui.Components.ClippingImageView) File(java.io.File) ReactionsEffectOverlay(org.telegram.ui.Components.Reactions.ReactionsEffectOverlay) Gravity(android.view.Gravity) PorterDuffXfermode(android.graphics.PorterDuffXfermode) TypedValue(android.util.TypedValue) Configuration(android.content.res.Configuration) StickerCell(org.telegram.ui.Cells.StickerCell) ReactionsContainerLayout(org.telegram.ui.Components.ReactionsContainerLayout) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EmojiView(org.telegram.ui.Components.EmojiView) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ChatScrimPopupContainerLayout(org.telegram.ui.Components.ChatScrimPopupContainerLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Spannable(android.text.Spannable) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ChecksHintView(org.telegram.ui.Components.ChecksHintView) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) Matrix(android.graphics.Matrix) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) BitmapShader(android.graphics.BitmapShader) Utilities(org.telegram.messenger.Utilities) HideViewAfterAnimation(org.telegram.ui.Components.HideViewAfterAnimation) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) SparseArray(android.util.SparseArray) List(java.util.List) TextView(android.widget.TextView) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) SecretChatHelper(org.telegram.messenger.SecretChatHelper) FileProvider(androidx.core.content.FileProvider) Pattern(java.util.regex.Pattern) 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) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ViewOutlineProvider(android.view.ViewOutlineProvider) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) TranslateAlert(org.telegram.ui.Components.TranslateAlert) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClipData(android.content.ClipData) SuppressLint(android.annotation.SuppressLint) 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) FireworksOverlay(org.telegram.ui.Components.FireworksOverlay) LongSparseArray(androidx.collection.LongSparseArray) FileWriter(java.io.FileWriter) FileLog(org.telegram.messenger.FileLog) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement) MessagesController(org.telegram.messenger.MessagesController) NumberTextView(org.telegram.ui.Components.NumberTextView) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) MessagesStorage(org.telegram.messenger.MessagesStorage) Size(org.telegram.ui.Components.Size) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) Space(android.widget.Space) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) Rect(android.graphics.Rect) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) StickersAlert(org.telegram.ui.Components.StickersAlert) TrendingStickersAlert(org.telegram.ui.Components.TrendingStickersAlert) SpannableString(android.text.SpannableString) ChecksHintView(org.telegram.ui.Components.ChecksHintView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) UndoView(org.telegram.ui.Components.UndoView) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) Calendar(java.util.Calendar) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) MediaDataController(org.telegram.messenger.MediaDataController) FireworksOverlay(org.telegram.ui.Components.FireworksOverlay) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) CounterView(org.telegram.ui.Components.CounterView) SearchCounterView(org.telegram.ui.Components.SearchCounterView) RecyclerView(androidx.recyclerview.widget.RecyclerView) Spannable(android.text.Spannable) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) ValueAnimator(android.animation.ValueAnimator) TLRPC(org.telegram.tgnet.TLRPC) ImageReceiver(org.telegram.messenger.ImageReceiver) StickerCell(org.telegram.ui.Cells.StickerCell) ArrayList(java.util.ArrayList) List(java.util.List) ActionBar(org.telegram.ui.ActionBar.ActionBar) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) Canvas(android.graphics.Canvas) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) PinnedLineView(org.telegram.ui.Components.PinnedLineView) LongSparseArray(androidx.collection.LongSparseArray) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) CharacterStyle(android.text.style.CharacterStyle) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) NumberTextView(org.telegram.ui.Components.NumberTextView) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) ViewGroup(android.view.ViewGroup) HorizontalScrollView(android.widget.HorizontalScrollView) PinnedLineView(org.telegram.ui.Components.PinnedLineView) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) RecyclerView(androidx.recyclerview.widget.RecyclerView) BluredView(org.telegram.ui.Components.BluredView) InstantCameraView(org.telegram.ui.Components.InstantCameraView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) 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) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) UndoView(org.telegram.ui.Components.UndoView) CounterView(org.telegram.ui.Components.CounterView) HintView(org.telegram.ui.Components.HintView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) EmojiView(org.telegram.ui.Components.EmojiView) ChecksHintView(org.telegram.ui.Components.ChecksHintView) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) TextView(android.widget.TextView) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) NumberTextView(org.telegram.ui.Components.NumberTextView) MotionEvent(android.view.MotionEvent) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) FrameLayout(android.widget.FrameLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) MessageObject(org.telegram.messenger.MessageObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) EditText(android.widget.EditText) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) 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) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) SharedPreferences(android.content.SharedPreferences) ReportAlert(org.telegram.ui.Components.ReportAlert) Outline(android.graphics.Outline) ViewOutlineProvider(android.view.ViewOutlineProvider) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) Animator(android.animation.Animator) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) ValueAnimator(android.animation.ValueAnimator) ObjectAnimator(android.animation.ObjectAnimator) SpannableStringBuilder(android.text.SpannableStringBuilder) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) BackupImageView(org.telegram.ui.Components.BackupImageView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView) NumberTextView(org.telegram.ui.Components.NumberTextView) BotHelpCell(org.telegram.ui.Cells.BotHelpCell) BackupImageView(org.telegram.ui.Components.BackupImageView) ImageView(android.widget.ImageView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ChatActivityMemberRequestsDelegate(org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate) InstantCameraView(org.telegram.ui.Components.InstantCameraView) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) AnimatorSet(android.animation.AnimatorSet) MessagesSearchAdapter(org.telegram.ui.Adapters.MessagesSearchAdapter) KeyEvent(android.view.KeyEvent) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) Bitmap(android.graphics.Bitmap) TextureView(android.view.TextureView) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) Bundle(android.os.Bundle) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) SearchCounterView(org.telegram.ui.Components.SearchCounterView) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) HintView(org.telegram.ui.Components.HintView) ChecksHintView(org.telegram.ui.Components.ChecksHintView) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) SpannableStringBuilder(android.text.SpannableStringBuilder) ClippingImageView(org.telegram.ui.Components.ClippingImageView)

Example 4 with Size

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

the class ChatActivity method didReceivedNotification.

@Override
public void didReceivedNotification(int id, int account, final Object... args) {
    if (id == NotificationCenter.messagesDidLoad) {
        int guid = (Integer) args[10];
        if (guid != classGuid) {
            return;
        }
        int queryLoadIndex = (Integer) args[11];
        boolean doNotRemoveLoadIndex;
        if (queryLoadIndex < 0) {
            doNotRemoveLoadIndex = true;
            queryLoadIndex = -queryLoadIndex;
        } else {
            doNotRemoveLoadIndex = false;
        }
        if (!doNotRemoveLoadIndex && !fragmentBeginToShow && !paused) {
            int[] alowedNotifications = new int[] { NotificationCenter.messagesDidLoad, NotificationCenter.chatInfoDidLoad, NotificationCenter.groupCallUpdated, NotificationCenter.dialogsNeedReload, NotificationCenter.scheduledMessagesUpdated, NotificationCenter.closeChats, NotificationCenter.botKeyboardDidLoad, NotificationCenter.userInfoDidLoad, NotificationCenter.pinnedInfoDidLoad, NotificationCenter.needDeleteDialog /*, NotificationCenter.botInfoDidLoad*/
            };
            if (transitionAnimationIndex == 0) {
                transitionAnimationIndex = getNotificationCenter().setAnimationInProgress(transitionAnimationIndex, alowedNotifications);
                AndroidUtilities.runOnUIThread(() -> getNotificationCenter().onAnimationFinish(transitionAnimationIndex), 800);
            } else {
                getNotificationCenter().updateAllowedNotifications(transitionAnimationIndex, alowedNotifications);
            }
        }
        int index = waitingForLoad.indexOf(queryLoadIndex);
        long currentUserId = getUserConfig().getClientUserId();
        int mode = (Integer) args[14];
        boolean isCache = (Boolean) args[3];
        boolean postponedScroll = postponedScrollToLastMessageQueryIndex > 0 && queryLoadIndex == postponedScrollToLastMessageQueryIndex;
        if (postponedScroll) {
            postponedScrollToLastMessageQueryIndex = 0;
        }
        if (index == -1) {
            if (chatMode == MODE_SCHEDULED && mode == MODE_SCHEDULED && !isCache) {
                waitingForReplyMessageLoad = true;
                waitingForLoad.add(lastLoadIndex);
                getMessagesController().loadMessages(dialog_id, mergeDialogId, false, AndroidUtilities.isTablet() ? 30 : 20, 0, 0, true, 0, classGuid, 2, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
            }
            return;
        } else if (!doNotRemoveLoadIndex) {
            waitingForLoad.remove(index);
        }
        ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[2];
        if (messages.isEmpty() && messArr.size() == 1 && MessageObject.isSystemSignUp(messArr.get(0))) {
            forceHistoryEmpty = true;
            endReached[0] = endReached[1] = true;
            forwardEndReached[0] = forwardEndReached[1] = true;
            firstLoading = false;
            showProgressView(false);
            if (chatListView != null) {
                if (!fragmentOpened) {
                    chatListView.setAnimateEmptyView(false, 1);
                    chatListView.setEmptyView(emptyViewContainer);
                    chatListView.setAnimateEmptyView(true, 1);
                } else {
                    chatListView.setEmptyView(emptyViewContainer);
                }
                chatAdapter.notifyDataSetChanged(true);
            }
            resumeDelayedFragmentAnimation();
            MessageObject messageObject = messArr.get(0);
            getMessagesController().markDialogAsRead(dialog_id, messageObject.getId(), messageObject.getId(), messageObject.messageOwner.date, false, 0, 0, true, 0);
            AndroidUtilities.cancelRunOnUIThread(fragmentTransitionRunnable);
            fragmentTransitionRunnable.run();
            return;
        }
        if (chatMode != mode) {
            if (chatMode != MODE_SCHEDULED) {
                scheduledMessagesCount = messArr.size();
                updateScheduledInterface(true);
            }
            return;
        }
        boolean createUnreadLoading = false;
        boolean showDateAfter = waitingForReplyMessageLoad;
        if (waitingForReplyMessageLoad) {
            if (chatMode != MODE_SCHEDULED && !createUnreadMessageAfterIdLoading) {
                boolean found = false;
                for (int a = 0; a < messArr.size(); a++) {
                    MessageObject obj = messArr.get(a);
                    if (obj.getId() == startLoadFromMessageId) {
                        found = true;
                        break;
                    }
                    if (a + 1 < messArr.size()) {
                        MessageObject obj2 = messArr.get(a + 1);
                        if (obj.getId() >= startLoadFromMessageId && obj2.getId() < startLoadFromMessageId) {
                            startLoadFromMessageId = obj.getId();
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    startLoadFromMessageId = 0;
                    return;
                }
            }
            int startLoadFrom = startLoadFromMessageId;
            boolean needSelect = needSelectFromMessageId;
            int unreadAfterId = createUnreadMessageAfterId;
            createUnreadLoading = createUnreadMessageAfterIdLoading;
            clearChatData();
            if (chatMode == 0) {
                createUnreadMessageAfterId = unreadAfterId;
                startLoadFromMessageId = startLoadFrom;
                needSelectFromMessageId = needSelect;
            }
        }
        loadsCount++;
        long did = (Long) args[0];
        int loadIndex = did == dialog_id ? 0 : 1;
        int count = (Integer) args[1];
        int fnid = (Integer) args[4];
        int last_unread_date = (Integer) args[7];
        int load_type = (Integer) args[8];
        boolean isEnd = (Boolean) args[9];
        int loaded_max_id = (Integer) args[12];
        int loaded_mentions_count = chatWasReset ? 0 : (Integer) args[13];
        if (loaded_mentions_count < 0) {
            loaded_mentions_count *= -1;
            hasAllMentionsLocal = false;
        } else if (first) {
            hasAllMentionsLocal = true;
        }
        if (load_type == 4) {
            startLoadFromMessageId = loaded_max_id;
            for (int a = messArr.size() - 1; a > 0; a--) {
                MessageObject obj = messArr.get(a);
                if (obj.type < 0 && obj.getId() == startLoadFromMessageId) {
                    startLoadFromMessageId = messArr.get(a - 1).getId();
                    break;
                }
            }
        }
        if (postponedScroll) {
            if (load_type == 0 && isCache && messArr.size() < count) {
                postponedScrollToLastMessageQueryIndex = lastLoadIndex;
                waitingForLoad.add(lastLoadIndex);
                getMessagesController().loadMessages(dialog_id, mergeDialogId, false, count, 0, 0, false, 0, classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
                return;
            }
            if (load_type == 4) {
                postponedScrollMessageId = startLoadFromMessageId;
            }
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            showPinnedProgress(false);
            if (postponedScrollIsCanceled) {
                return;
            }
            if (postponedScrollMessageId == 0) {
                clearChatData();
            } else {
                if (showScrollToMessageError) {
                    boolean found = false;
                    for (int k = 0; k < messArr.size(); k++) {
                        if (messArr.get(k).getId() == postponedScrollMessageId) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        if (isThreadChat()) {
                            Bundle bundle = new Bundle();
                            if (currentEncryptedChat != null) {
                                bundle.putInt("enc_id", currentEncryptedChat.id);
                            } else if (currentChat != null) {
                                bundle.putLong("chat_id", currentChat.id);
                            } else {
                                bundle.putLong("user_id", currentUser.id);
                            }
                            bundle.putInt("message_id", postponedScrollMessageId);
                            presentFragment(new ChatActivity(bundle), true);
                        } else {
                            BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show();
                        }
                        return;
                    }
                    showScrollToMessageError = false;
                }
                int startLoadFrom = startLoadFromMessageId;
                boolean needSelect = needSelectFromMessageId;
                int unreadAfterId = createUnreadMessageAfterId;
                createUnreadLoading = createUnreadMessageAfterIdLoading;
                clearChatData();
                if (chatMode == 0) {
                    createUnreadMessageAfterId = unreadAfterId;
                    startLoadFromMessageId = startLoadFrom;
                    needSelectFromMessageId = needSelect;
                }
            }
        }
        if (chatListItemAnimator != null) {
            chatListItemAnimator.setShouldAnimateEnterFromBottom(false);
        }
        int unread_to_load = 0;
        if (fnid != 0) {
            if (!chatWasReset) {
                last_message_id = (Integer) args[5];
            }
            if (load_type == 3) {
                if (loadingFromOldPosition) {
                    if (!chatWasReset) {
                        unread_to_load = (Integer) args[6];
                        if (unread_to_load != 0) {
                            createUnreadMessageAfterId = fnid;
                        }
                    }
                    loadingFromOldPosition = false;
                }
                first_unread_id = 0;
            } else {
                first_unread_id = fnid;
                if (!chatWasReset) {
                    unread_to_load = (Integer) args[6];
                }
            }
        } else if (!chatWasReset && startLoadFromMessageId != 0 && (load_type == 3 || load_type == 4)) {
            last_message_id = (Integer) args[5];
        }
        if (isThreadChat() && threadUnreadMessagesCount != 0) {
            unread_to_load = threadUnreadMessagesCount;
            threadUnreadMessagesCount = 0;
        }
        int newRowsCount = 0;
        if (load_type != 0 && (isThreadChat() && first_unread_id != 0 || startLoadFromMessageId != 0 || last_message_id != 0)) {
            forwardEndReached[loadIndex] = false;
            hideForwardEndReached = false;
        }
        if ((load_type == 1 || load_type == 3) && loadIndex == 1) {
            endReached[0] = cacheEndReached[0] = true;
            forwardEndReached[0] = false;
            hideForwardEndReached = false;
            minMessageId[0] = 0;
        }
        if (chatMode == MODE_SCHEDULED) {
            endReached[0] = cacheEndReached[0] = true;
            forwardEndReached[0] = forwardEndReached[0] = true;
        }
        if (ChatObject.isChannel(currentChat) && !getMessagesController().dialogs_dict.containsKey(dialog_id) && load_type == 2 && isCache && loadIndex == 0) {
            forwardEndReached[0] = false;
            hideForwardEndReached = true;
        }
        if (loadsCount == 1 && messArr.size() > 20) {
            loadsCount++;
        }
        boolean isFirstLoading = firstLoading;
        if (firstLoading) {
            if (!forwardEndReached[loadIndex]) {
                messages.clear();
                messagesByDays.clear();
                groupedMessagesMap.clear();
                threadMessageAdded = false;
                for (int a = 0; a < 2; a++) {
                    messagesDict[a].clear();
                    if (currentEncryptedChat == null) {
                        maxMessageId[a] = Integer.MAX_VALUE;
                        minMessageId[a] = Integer.MIN_VALUE;
                    } else {
                        maxMessageId[a] = Integer.MIN_VALUE;
                        minMessageId[a] = Integer.MAX_VALUE;
                    }
                    maxDate[a] = Integer.MIN_VALUE;
                    minDate[a] = 0;
                }
            }
            firstLoading = false;
            AndroidUtilities.runOnUIThread(() -> {
                getNotificationCenter().runDelayedNotifications();
                resumeDelayedFragmentAnimation();
                AndroidUtilities.cancelRunOnUIThread(fragmentTransitionRunnable);
                fragmentTransitionRunnable.run();
            });
        }
        if (isThreadChat() && (load_type == 2 || load_type == 3) && !isCache) {
            if (load_type == 3 && scrollToThreadMessage) {
                startLoadFromMessageId = threadMessageId;
            }
            int beforMax = 0;
            int afterMax = 0;
            boolean hasMaxId = false;
            for (int a = 0, N = messArr.size(); a < N; a++) {
                MessageObject message = messArr.get(a);
                int mid = message.getId();
                if (mid == loaded_max_id) {
                    hasMaxId = true;
                }
                if (mid > loaded_max_id) {
                    afterMax++;
                } else {
                    beforMax++;
                }
            }
            int num;
            if (load_type == 2) {
                num = 10;
            } else {
                num = count / 2;
            }
            if (hasMaxId) {
                num++;
            }
            if (beforMax < num) {
                endReached[0] = true;
            }
            if (!chatWasReset && afterMax < count - num) {
                forwardEndReached[0] = true;
            }
        }
        if (chatMode == MODE_PINNED) {
            endReached[loadIndex] = true;
        }
        if (load_type == 0 && forwardEndReached[0] && !pendingSendMessages.isEmpty()) {
            for (int a = 0, N = messArr.size(); a < N; a++) {
                MessageObject existing = pendingSendMessagesDict.get(messArr.get(a).getId());
                if (existing != null) {
                    pendingSendMessagesDict.remove(existing.getId());
                    pendingSendMessages.remove(existing);
                }
            }
            if (!pendingSendMessages.isEmpty()) {
                int pasteIndex = 0;
                int date = pendingSendMessages.get(0).messageOwner.date;
                if (!messArr.isEmpty()) {
                    if (date >= messArr.get(0).messageOwner.date) {
                        pasteIndex = 0;
                    } else if (date <= messArr.get(messArr.size() - 1).messageOwner.date) {
                        pasteIndex = messArr.size();
                    } else {
                        for (int a = 0, N = messArr.size(); a < N - 1; a++) {
                            if (messArr.get(a).messageOwner.date >= date && messArr.get(a + 1).messageOwner.date <= date) {
                                pasteIndex = a + 1;
                            }
                        }
                    }
                }
                messArr = new ArrayList<>(messArr);
                messArr.addAll(pasteIndex, pendingSendMessages);
                pendingSendMessages.clear();
                pendingSendMessagesDict.clear();
            }
        }
        if (!threadMessageAdded && isThreadChat() && (load_type == 0 && messArr.size() < count || (load_type == 2 || load_type == 3) && endReached[0])) {
            TLRPC.Message msg = new TLRPC.TL_message();
            if (threadMessageObject.getRepliesCount() == 0) {
                if (isComments) {
                    msg.message = LocaleController.getString("NoComments", R.string.NoComments);
                } else {
                    msg.message = LocaleController.getString("NoReplies", R.string.NoReplies);
                }
            } else {
                msg.message = LocaleController.getString("DiscussionStarted", R.string.DiscussionStarted);
            }
            msg.id = 0;
            msg.date = threadMessageObject.messageOwner.date;
            replyMessageHeaderObject = new MessageObject(currentAccount, msg, false, false);
            replyMessageHeaderObject.type = 10;
            replyMessageHeaderObject.contentType = 1;
            replyMessageHeaderObject.isDateObject = true;
            replyMessageHeaderObject.stableId = lastStableId++;
            messArr.add(replyMessageHeaderObject);
            updateReplyMessageHeader(false);
            messArr.addAll(threadMessageObjects);
            count += 2;
            threadMessageAdded = true;
        }
        if (load_type == 1) {
            Collections.reverse(messArr);
        }
        if (currentEncryptedChat == null) {
            getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode == MODE_SCHEDULED, null);
        }
        int approximateHeightSum = 0;
        if (!chatWasReset && (load_type == 2 || load_type == 1) && messArr.isEmpty() && !isCache) {
            forwardEndReached[0] = true;
        }
        LongSparseArray<MessageObject.GroupedMessages> newGroups = null;
        LongSparseArray<MessageObject.GroupedMessages> changedGroups = null;
        MediaController mediaController = MediaController.getInstance();
        TLRPC.MessageAction dropPhotoAction = null;
        boolean createdWas = false;
        boolean moveCurrentDateObject = false;
        boolean scrolledToUnread = false;
        for (int a = 0, N = messArr.size(); a < N; a++) {
            MessageObject obj = messArr.get(N - a - 1);
            TLRPC.MessageAction action = obj.messageOwner.action;
            if (a == 0 && action instanceof TLRPC.TL_messageActionChatCreate) {
                createdWas = true;
            } else if (!createdWas) {
                break;
            } else if (a < 2 && action instanceof TLRPC.TL_messageActionChatEditPhoto) {
                dropPhotoAction = action;
            }
        }
        for (int a = 0; a < messArr.size(); a++) {
            MessageObject obj = messArr.get(a);
            if (obj.replyMessageObject != null) {
                repliesMessagesDict.put(obj.replyMessageObject.getId(), obj.replyMessageObject);
                addReplyMessageOwner(obj, 0);
            }
            int messageId = obj.getId();
            if (threadMessageId != 0) {
                if (messageId <= (obj.isOut() ? threadMaxOutboxReadId : threadMaxInboxReadId)) {
                    obj.setIsRead();
                }
            }
            approximateHeightSum += obj.getApproximateHeight();
            if (currentUser != null) {
                if (currentUser.self) {
                    obj.messageOwner.out = true;
                }
                if (chatMode != MODE_SCHEDULED && (currentUser.bot && obj.isOut() || currentUser.id == currentUserId)) {
                    obj.setIsRead();
                }
            }
            if (messagesDict[loadIndex].indexOfKey(messageId) >= 0) {
                continue;
            }
            if (threadMessageId != 0 && obj.messageOwner instanceof TLRPC.TL_messageEmpty) {
                continue;
            }
            if (currentEncryptedChat != null && obj.messageOwner.stickerVerified == 0) {
                getMediaDataController().verifyAnimatedStickerMessage(obj.messageOwner);
            }
            addToPolls(obj, null);
            if (isSecretChat()) {
                checkSecretMessageForLocation(obj);
            }
            if (mediaController.isPlayingMessage(obj)) {
                MessageObject player = mediaController.getPlayingMessageObject();
                obj.audioProgress = player.audioProgress;
                obj.audioProgressSec = player.audioProgressSec;
                obj.audioPlayerDuration = player.audioPlayerDuration;
            }
            if (loadIndex == 0 && ChatObject.isChannel(currentChat) && messageId == 1) {
                endReached[loadIndex] = true;
                cacheEndReached[loadIndex] = true;
            }
            if (messageId > 0) {
                maxMessageId[loadIndex] = Math.min(messageId, maxMessageId[loadIndex]);
                minMessageId[loadIndex] = Math.max(messageId, minMessageId[loadIndex]);
            } else if (currentEncryptedChat != null) {
                maxMessageId[loadIndex] = Math.max(messageId, maxMessageId[loadIndex]);
                minMessageId[loadIndex] = Math.min(messageId, minMessageId[loadIndex]);
            }
            if (obj.messageOwner.date != 0) {
                maxDate[loadIndex] = Math.max(maxDate[loadIndex], obj.messageOwner.date);
                if (minDate[loadIndex] == 0 || obj.messageOwner.date < minDate[loadIndex]) {
                    minDate[loadIndex] = obj.messageOwner.date;
                }
            }
            if (!chatWasReset && messageId != 0 && messageId == last_message_id) {
                forwardEndReached[loadIndex] = true;
            }
            TLRPC.MessageAction action = obj.messageOwner.action;
            if (obj.type < 0 || loadIndex == 1 && action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                continue;
            }
            if (currentChat != null && currentChat.creator && (action instanceof TLRPC.TL_messageActionChatCreate || dropPhotoAction != null && action == dropPhotoAction)) {
                continue;
            }
            if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom) {
                continue;
            }
            if (needAnimateToMessage != null && needAnimateToMessage.getId() == messageId && messageId < 0 && chatMode != MODE_SCHEDULED) {
                obj = needAnimateToMessage;
                animatingMessageObjects.add(obj);
                needAnimateToMessage = null;
            }
            messagesDict[loadIndex].put(messageId, obj);
            ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);
            if (dayArray == null) {
                dayArray = new ArrayList<>();
                messagesByDays.put(obj.dateKey, dayArray);
                TLRPC.Message dateMsg = new TLRPC.TL_message();
                if (chatMode == MODE_SCHEDULED) {
                    if (obj.messageOwner.date == 0x7ffffffe) {
                        dateMsg.message = LocaleController.getString("MessageScheduledUntilOnline", R.string.MessageScheduledUntilOnline);
                    } else {
                        dateMsg.message = LocaleController.formatString("MessageScheduledOn", R.string.MessageScheduledOn, LocaleController.formatDateChat(obj.messageOwner.date, true));
                    }
                } else {
                    dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
                }
                dateMsg.id = 0;
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(((long) obj.messageOwner.date) * 1000);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                dateMsg.date = (int) (calendar.getTimeInMillis() / 1000);
                MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
                dateObj.type = 10;
                dateObj.contentType = 1;
                dateObj.isDateObject = true;
                dateObj.stableId = lastStableId++;
                if (load_type == 1) {
                    messages.add(0, dateObj);
                } else {
                    messages.add(dateObj);
                }
                newRowsCount++;
            } else {
                if (!moveCurrentDateObject && !messages.isEmpty() && messages.get(messages.size() - 1).isDateObject) {
                    messages.get(messages.size() - 1).stableId = lastStableId++;
                    moveCurrentDateObject = true;
                }
            }
            if (obj.hasValidGroupId()) {
                MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(obj.getGroupIdForUse());
                if (groupedMessages != null) {
                    if (messages.size() > 1) {
                        MessageObject previous;
                        if (load_type == 1) {
                            previous = messages.get(0);
                        } else {
                            previous = messages.get(messages.size() - 2);
                        }
                        if (previous.getGroupIdForUse() == obj.getGroupIdForUse()) {
                            if (previous.localGroupId != 0) {
                                obj.localGroupId = previous.localGroupId;
                                groupedMessages = groupedMessagesMap.get(previous.localGroupId);
                            }
                        } else if (previous.getGroupIdForUse() != obj.getGroupIdForUse()) {
                            obj.localGroupId = Utilities.random.nextLong();
                            groupedMessages = null;
                        }
                    }
                }
                if (groupedMessages == null) {
                    groupedMessages = new MessageObject.GroupedMessages();
                    groupedMessages.groupId = obj.getGroupId();
                    groupedMessagesMap.put(groupedMessages.groupId, groupedMessages);
                } else if (newGroups == null || newGroups.indexOfKey(obj.getGroupId()) < 0) {
                    if (changedGroups == null) {
                        changedGroups = new LongSparseArray<>();
                    }
                    changedGroups.put(obj.getGroupId(), groupedMessages);
                }
                if (newGroups == null) {
                    newGroups = new LongSparseArray<>();
                }
                newGroups.put(groupedMessages.groupId, groupedMessages);
                if (load_type == 1) {
                    groupedMessages.messages.add(obj);
                } else {
                    groupedMessages.messages.add(0, obj);
                }
            } else if (obj.getGroupIdForUse() != 0) {
                obj.messageOwner.grouped_id = 0;
                obj.localSentGroupId = 0;
            }
            newRowsCount++;
            dayArray.add(obj);
            obj.stableId = lastStableId++;
            if (load_type == 1) {
                messages.add(0, obj);
            } else {
                messages.get(messages.size() - 1).stableId = lastStableId++;
                messages.add(messages.size() - 1, obj);
            }
            MessageObject prevObj;
            if (currentEncryptedChat == null) {
                if (createUnreadMessageAfterId != 0 && load_type != 1 && a + 1 < messArr.size()) {
                    prevObj = messArr.get(a + 1);
                    if (obj.isOut() && !obj.messageOwner.from_scheduled || prevObj.getId() >= createUnreadMessageAfterId) {
                        prevObj = null;
                    }
                } else {
                    prevObj = null;
                }
            } else {
                if (createUnreadMessageAfterId != 0 && load_type != 1 && a - 1 >= 0) {
                    prevObj = messArr.get(a - 1);
                    if (obj.isOut() && !obj.messageOwner.from_scheduled || prevObj.getId() >= createUnreadMessageAfterId) {
                        prevObj = null;
                    }
                } else {
                    prevObj = null;
                }
            }
            if (load_type == 2 && messageId != 0 && messageId == first_unread_id) {
                if ((approximateHeightSum > AndroidUtilities.displaySize.y / 2 || isThreadChat()) || !forwardEndReached[0]) {
                    if (!isThreadChat() || threadMaxInboxReadId != 0) {
                        TLRPC.Message dateMsg = new TLRPC.TL_message();
                        dateMsg.message = "";
                        dateMsg.id = 0;
                        MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
                        dateObj.type = 6;
                        dateObj.contentType = 2;
                        dateObj.stableId = lastStableId++;
                        messages.add(messages.size() - 1, dateObj);
                        unreadMessageObject = dateObj;
                        scrollToMessage = unreadMessageObject;
                    } else {
                        scrollToMessage = obj;
                    }
                    scrollToMessagePosition = -10000;
                    scrolledToUnread = true;
                    newRowsCount++;
                }
            } else if ((load_type == 3 || load_type == 4) && (startLoadFromMessageId < 0 && messageId == startLoadFromMessageId || startLoadFromMessageId > 0 && messageId > 0 && messageId <= startLoadFromMessageId)) {
                removeSelectedMessageHighlight();
                if (needSelectFromMessageId && messageId == startLoadFromMessageId) {
                    highlightMessageId = messageId;
                }
                if (showScrollToMessageError && messageId != startLoadFromMessageId) {
                    BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show();
                }
                scrollToMessage = obj;
                if (postponedScroll) {
                    postponedScrollMessageId = scrollToMessage.getId();
                }
                startLoadFromMessageId = 0;
                if (scrollToMessagePosition == -10000) {
                    scrollToMessagePosition = -9000;
                }
            }
            if (load_type != 2 && unreadMessageObject == null && createUnreadMessageAfterId != 0 && (currentEncryptedChat == null && (!obj.isOut() || obj.messageOwner.from_scheduled) && messageId >= createUnreadMessageAfterId || currentEncryptedChat != null && (!obj.isOut() || obj.messageOwner.from_scheduled) && messageId <= createUnreadMessageAfterId) && (load_type == 1 || prevObj != null || prevObj == null && createUnreadLoading && a == messArr.size() - 1)) {
                TLRPC.Message dateMsg = new TLRPC.TL_message();
                dateMsg.message = "";
                dateMsg.id = 0;
                MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
                dateObj.type = 6;
                dateObj.contentType = 2;
                dateObj.stableId = lastStableId++;
                if (load_type == 1) {
                    messages.add(1, dateObj);
                } else {
                    messages.add(messages.size() - 1, dateObj);
                }
                unreadMessageObject = dateObj;
                if (load_type == 3) {
                    scrollToMessage = unreadMessageObject;
                    startLoadFromMessageId = 0;
                    scrollToMessagePosition = -9000;
                }
                newRowsCount++;
            }
        }
        if (createUnreadLoading) {
            createUnreadMessageAfterId = 0;
        }
        if (load_type == 0 && newRowsCount == 0) {
            loadsCount--;
        }
        if (forwardEndReached[loadIndex] && loadIndex != 1) {
            first_unread_id = 0;
            last_message_id = 0;
            createUnreadMessageAfterId = 0;
        }
        if (load_type == 1) {
            if (!chatWasReset && messArr.size() != count && (!isCache || currentEncryptedChat != null || forwardEndReached[loadIndex])) {
                forwardEndReached[loadIndex] = true;
                if (loadIndex != 1) {
                    first_unread_id = 0;
                    last_message_id = 0;
                    createUnreadMessageAfterId = 0;
                    chatAdapter.notifyItemRemoved(chatAdapter.loadingDownRow);
                }
                startLoadFromMessageId = 0;
            }
            if (newRowsCount > 0) {
                int firstVisPos = chatLayoutManager.findFirstVisibleItemPosition();
                int lastVisPos = chatLayoutManager.findLastVisibleItemPosition();
                int top = 0;
                MessageObject scrollToMessageObject = null;
                if (firstVisPos != RecyclerView.NO_POSITION) {
                    for (int i = firstVisPos; i <= lastVisPos; i++) {
                        View v = chatLayoutManager.findViewByPosition(i);
                        if (v instanceof ChatMessageCell) {
                            scrollToMessageObject = ((ChatMessageCell) v).getMessageObject();
                            top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
                            break;
                        } else if (v instanceof ChatActionCell) {
                            scrollToMessageObject = ((ChatActionCell) v).getMessageObject();
                            top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
                            break;
                        }
                    }
                }
                if (!postponedScroll) {
                    chatAdapter.notifyItemRangeInserted(1, newRowsCount);
                    if (scrollToMessageObject != null) {
                        int scrollToIndex = messages.indexOf(scrollToMessageObject);
                        if (scrollToIndex > 0) {
                            chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + scrollToIndex, top);
                        }
                    }
                }
            }
            loadingForward = false;
        } else {
            if (messArr.size() < count && load_type != 3 && load_type != 4) {
                if (isCache) {
                    if (currentEncryptedChat != null || loadIndex == 1 && mergeDialogId != 0 && isEnd) {
                        endReached[loadIndex] = true;
                    }
                    if (load_type != 2) {
                        cacheEndReached[loadIndex] = true;
                    }
                } else if (load_type != 2 || messArr.size() == 0 && messages.isEmpty()) {
                    endReached[loadIndex] = true;
                }
            }
            loading = false;
            if (chatListView != null && chatScrollHelper != null) {
                if (first || scrollToTopOnResume || forceScrollToTop) {
                    forceScrollToTop = false;
                    if (!postponedScroll) {
                        chatAdapter.notifyDataSetChanged(true);
                    }
                    if (scrollToMessage != null) {
                        addSponsoredMessages(!isFirstLoading);
                        loadSendAsPeers();
                        int yOffset;
                        boolean bottom = true;
                        if (startLoadFromMessageOffset != Integer.MAX_VALUE) {
                            yOffset = -startLoadFromMessageOffset - chatListView.getPaddingBottom();
                            startLoadFromMessageOffset = Integer.MAX_VALUE;
                        } else if (scrollToMessagePosition == -9000) {
                            yOffset = getScrollOffsetForMessage(scrollToMessage);
                            bottom = false;
                        } else if (scrollToMessagePosition == -10000) {
                            yOffset = -AndroidUtilities.dp(11);
                            if (scrolledToUnread && threadMessageId != 0) {
                                yOffset += AndroidUtilities.dp(48);
                            }
                            bottom = false;
                        } else {
                            yOffset = scrollToMessagePosition;
                        }
                        // in case pinned message view is visible
                        yOffset += AndroidUtilities.dp(50);
                        if (!postponedScroll) {
                            if (!messages.isEmpty()) {
                                if (chatAdapter.loadingUpRow >= 0 && !messages.isEmpty() && (messages.get(messages.size() - 1) == scrollToMessage || messages.get(messages.size() - 2) == scrollToMessage)) {
                                    chatLayoutManager.scrollToPositionWithOffset(chatAdapter.loadingUpRow, yOffset, bottom);
                                } else {
                                    chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + messages.indexOf(scrollToMessage), yOffset, bottom);
                                }
                            }
                        }
                        chatListView.invalidate();
                        if (scrollToMessagePosition == -10000 || scrollToMessagePosition == -9000) {
                            canShowPagedownButton = true;
                            updatePagedownButtonVisibility(true);
                            if (unread_to_load != 0) {
                                if (pagedownButtonCounter != null) {
                                    if (prevSetUnreadCount != newUnreadMessageCount) {
                                        pagedownButtonCounter.setCount(newUnreadMessageCount = unread_to_load, openAnimationEnded);
                                        prevSetUnreadCount = newUnreadMessageCount;
                                    }
                                }
                            }
                        }
                        scrollToMessagePosition = -10000;
                        scrollToMessage = null;
                    } else {
                        addSponsoredMessages(!isFirstLoading);
                        moveScrollToLastMessage(true);
                    }
                    if (loaded_mentions_count != 0) {
                        showMentionDownButton(true, true);
                        if (mentiondownButtonCounter != null) {
                            mentiondownButtonCounter.setVisibility(View.VISIBLE);
                            mentiondownButtonCounter.setText(String.format("%d", newMentionsCount = loaded_mentions_count));
                        }
                    }
                } else {
                    if (newRowsCount != 0) {
                        int firstVisPos = chatLayoutManager.findFirstVisibleItemPosition();
                        int lastVisPos = chatLayoutManager.findLastVisibleItemPosition();
                        int top = 0;
                        MessageObject scrollToMessageObject = null;
                        if (firstVisPos != RecyclerView.NO_POSITION) {
                            for (int i = firstVisPos; i <= lastVisPos; i++) {
                                View v = chatLayoutManager.findViewByPosition(i);
                                if (v instanceof ChatMessageCell) {
                                    scrollToMessageObject = ((ChatMessageCell) v).getMessageObject();
                                    top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
                                    break;
                                } else if (v instanceof ChatActionCell) {
                                    scrollToMessageObject = ((ChatActionCell) v).getMessageObject();
                                    top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
                                    break;
                                }
                            }
                        }
                        int insertStart = chatAdapter.messagesEndRow;
                        int loadingUpRow = chatAdapter.loadingUpRow;
                        chatAdapter.updateRowsInternal();
                        if (loadingUpRow >= 0 && chatAdapter.loadingUpRow < 0) {
                            chatAdapter.notifyItemRemoved(loadingUpRow);
                        }
                        if (newRowsCount > 0) {
                            if (moveCurrentDateObject) {
                                chatAdapter.notifyItemRemoved(insertStart - 1);
                                chatAdapter.notifyItemRangeInserted(insertStart - 1, newRowsCount + 1);
                            } else {
                                chatAdapter.notifyItemChanged(insertStart - 1);
                                chatAdapter.notifyItemRangeInserted(insertStart, newRowsCount);
                            }
                        }
                        if (!postponedScroll && scrollToMessageObject != null) {
                            int scrollToIndex = messages.indexOf(scrollToMessageObject);
                            if (scrollToIndex > 0) {
                                chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + scrollToIndex, top);
                            }
                        }
                    } else if (chatAdapter.loadingUpRow >= 0 && endReached[loadIndex] && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
                        chatAdapter.notifyItemRemoved(chatAdapter.loadingUpRow);
                    } else {
                        chatAdapter.notifyDataSetChanged(true);
                    }
                }
                if (paused) {
                    scrollToTopOnResume = true;
                    if (scrollToMessage != null) {
                        scrollToTopUnReadOnResume = true;
                    }
                }
                if (first) {
                    if (chatListView != null) {
                        if (!fragmentBeginToShow) {
                            chatListView.setAnimateEmptyView(false, 1);
                            chatListView.setEmptyView(emptyViewContainer);
                            chatListView.setAnimateEmptyView(true, 1);
                        } else {
                            chatListView.setEmptyView(emptyViewContainer);
                        }
                    }
                }
            } else {
                scrollToTopOnResume = true;
                if (scrollToMessage != null) {
                    scrollToTopUnReadOnResume = true;
                }
            }
        }
        if (newGroups != null) {
            for (int a = 0; a < newGroups.size(); a++) {
                MessageObject.GroupedMessages groupedMessages = newGroups.valueAt(a);
                groupedMessages.calculate();
                if (chatAdapter != null && changedGroups != null && changedGroups.indexOfKey(newGroups.keyAt(a)) >= 0) {
                    MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
                    int idx = messages.indexOf(messageObject);
                    if (idx >= 0) {
                        if (chatListItemAnimator != null) {
                            chatListItemAnimator.groupWillChanged(groupedMessages);
                        }
                        chatAdapter.notifyItemRangeChanged(idx + chatAdapter.messagesStartRow, groupedMessages.messages.size());
                    }
                }
            }
        }
        if (first && messages.size() > 0) {
            first = false;
            if (isThreadChat()) {
                invalidateMessagesVisiblePart();
            }
            if (startLoadFromDate != 0) {
                int dateObjectIndex = -1;
                int closeDateObjectIndex = -1;
                int closeDateDiff = 0;
                for (int i = 0; i < messages.size(); i++) {
                    if (messages.get(i).isDateObject && Math.abs(startLoadFromDate - messages.get(i).messageOwner.date) <= 100) {
                        dateObjectIndex = i;
                        break;
                    }
                    if (messages.get(i).isDateObject) {
                        int timeDiff = Math.abs(startLoadFromDate - messages.get(i).messageOwner.date);
                        if (closeDateObjectIndex == -1 || timeDiff < closeDateDiff) {
                            closeDateDiff = timeDiff;
                            closeDateObjectIndex = i;
                        }
                    }
                }
                if (dateObjectIndex >= 0) {
                    chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + dateObjectIndex, (int) (AndroidUtilities.dp(4)), false);
                } else if (closeDateObjectIndex >= 0) {
                    chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + closeDateObjectIndex, chatListView.getMeasuredHeight() / 2 - AndroidUtilities.dp(24), false);
                }
            }
        }
        if (messages.isEmpty() && currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
            botUser = "";
            updateBottomOverlay();
        }
        if (newRowsCount == 0 && (mergeDialogId != 0 && loadIndex == 0 || currentEncryptedChat != null && !endReached[0])) {
            first = true;
            if (chatListView != null) {
                chatListView.setEmptyView(null);
            }
            if (emptyViewContainer != null) {
                emptyViewContainer.setVisibility(View.INVISIBLE);
            }
        } else {
            showProgressView(false);
        }
        if (newRowsCount == 0 && mergeDialogId != 0 && loadIndex == 0) {
            getNotificationCenter().updateAllowedNotifications(transitionAnimationIndex, new int[] { NotificationCenter.chatInfoDidLoad, NotificationCenter.groupCallUpdated, NotificationCenter.dialogsNeedReload, NotificationCenter.scheduledMessagesUpdated, NotificationCenter.closeChats, NotificationCenter.messagesDidLoad, NotificationCenter.botKeyboardDidLoad, NotificationCenter.userInfoDidLoad, NotificationCenter.pinnedInfoDidLoad, NotificationCenter.needDeleteDialog /*, NotificationCenter.botInfoDidLoad*/
            });
        }
        if (showDateAfter) {
            showFloatingDateView(false);
        }
        addSponsoredMessages(!isFirstLoading);
        loadSendAsPeers();
        checkScrollForLoad(false);
        if (postponedScroll) {
            chatAdapter.notifyDataSetChanged(true);
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            updatePinnedListButton(false);
            if (postponedScrollMessageId == 0) {
                chatScrollHelperCallback.scrollTo = null;
                chatScrollHelperCallback.lastBottom = true;
                chatScrollHelperCallback.lastItemOffset = 0;
                chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop;
                chatScrollHelper.scrollToPosition(0, 0, true, true);
            } else {
                MessageObject object = messagesDict[loadIndex].get(postponedScrollMessageId);
                if (object != null) {
                    MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(object.getGroupId());
                    if (object.getGroupId() != 0 && groupedMessages != null) {
                        MessageObject primary = groupedMessages.findPrimaryMessageObject();
                        if (primary != null) {
                            object = primary;
                        }
                    }
                }
                if (object != null) {
                    int k = messages.indexOf(object);
                    if (k >= 0) {
                        int fromPosition = chatLayoutManager.findFirstVisibleItemPosition();
                        highlightMessageId = object.getId();
                        int direction;
                        if (postponedScrollMinMessageId != 0) {
                            if (highlightMessageId < 0 && postponedScrollMinMessageId < 0) {
                                direction = highlightMessageId < postponedScrollMinMessageId ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
                            } else {
                                direction = highlightMessageId > postponedScrollMinMessageId ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
                            }
                        } else {
                            direction = fromPosition > k ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
                        }
                        chatScrollHelper.setScrollDirection(direction);
                        if (!needSelectFromMessageId) {
                            removeSelectedMessageHighlight();
                        }
                        int yOffset = getScrollOffsetForMessage(object);
                        chatScrollHelperCallback.scrollTo = object;
                        chatScrollHelperCallback.lastBottom = false;
                        chatScrollHelperCallback.lastItemOffset = yOffset;
                        chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop;
                        chatScrollHelper.scrollToPosition(chatAdapter.messagesStartRow + k, yOffset, false, true);
                    }
                }
            }
        }
        chatWasReset = false;
    } else if (id == NotificationCenter.invalidateMotionBackground) {
        if (chatListView != null) {
            chatListView.invalidateViews();
        }
        if (messageEnterTransitionContainer != null) {
            messageEnterTransitionContainer.invalidate();
        }
    } else if (id == NotificationCenter.emojiLoaded) {
        if (chatListView != null) {
            chatListView.invalidateViews();
        }
        if (replyObjectTextView != null) {
            replyObjectTextView.invalidate();
        }
        if (alertTextView != null) {
            alertTextView.invalidate();
        }
        for (int a = 0; a < 2; a++) {
            if (pinnedMessageTextView[a] != null) {
                pinnedMessageTextView[a].invalidate();
            }
        }
        if (mentionListView != null) {
            mentionListView.invalidateViews();
        }
        if (stickersListView != null) {
            stickersListView.invalidateViews();
        }
        if (messagesSearchListView != null) {
            messagesSearchListView.invalidateViews();
        }
        if (undoView != null) {
            undoView.invalidate();
        }
        if (chatActivityEnterView != null) {
            EditTextBoldCursor editText = chatActivityEnterView.getEditField();
            int color = editText.getCurrentTextColor();
            editText.setTextColor(0xffffffff);
            editText.setTextColor(color);
        }
    } else if (id == NotificationCenter.didUpdateConnectionState) {
        int state = ConnectionsManager.getInstance(account).getConnectionState();
        if (state == ConnectionsManager.ConnectionStateConnected) {
            checkAutoDownloadMessages(false);
        }
    } else if (id == NotificationCenter.chatOnlineCountDidLoad) {
        Long chatId = (Long) args[0];
        if (chatInfo == null || currentChat == null || currentChat.id != chatId) {
            return;
        }
        chatInfo.online_count = (Integer) args[1];
        if (avatarContainer != null) {
            avatarContainer.updateOnlineCount();
            avatarContainer.updateSubtitle();
        }
    } else if (id == NotificationCenter.updateDefaultSendAsPeer) {
        long chatId = (long) args[0];
        if (chatId == dialog_id) {
            chatActivityEnterView.updateSendAsButton();
        }
    } else if (id == NotificationCenter.updateInterfaces) {
        int updateMask = (Integer) args[0];
        if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
            if (currentChat != null) {
                TLRPC.Chat chat = getMessagesController().getChat(currentChat.id);
                if (chat != null) {
                    currentChat = chat;
                }
            } else if (currentUser != null) {
                TLRPC.User user = getMessagesController().getUser(currentUser.id);
                if (user != null) {
                    currentUser = user;
                }
            }
            updateTitle();
        }
        boolean updateSubtitle = false;
        if (!isThreadChat() && ((updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0)) {
            if (currentChat != null && avatarContainer != null) {
                avatarContainer.updateOnlineCount();
            }
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) {
            checkAndUpdateAvatar();
            updateVisibleRows();
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_CHAT) != 0 && currentChat != null) {
            boolean fwdBefore = getMessagesController().isChatNoForwards(currentChat);
            TLRPC.Chat chat = getMessagesController().getChat(currentChat.id);
            if (chat == null) {
                return;
            }
            currentChat = chat;
            boolean fwdChanged = getMessagesController().isChatNoForwards(currentChat) != fwdBefore;
            updateSubtitle = !isThreadChat();
            updateBottomOverlay();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setDialogId(dialog_id, currentAccount);
            }
            if (currentEncryptedChat != null && SharedConfig.passcodeHash.length() == 0 && !SharedConfig.allowScreenCapture && unregisterFlagSecurePasscode == null) {
                unregisterFlagSecurePasscode = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
            }
            if (fwdChanged) {
                boolean value = getMessagesController().isChatNoForwards(currentChat);
                if (!value && unregisterFlagSecureNoforwards != null) {
                    unregisterFlagSecureNoforwards.run();
                    unregisterFlagSecureNoforwards = null;
                } else if (value && unregisterFlagSecureNoforwards == null) {
                    unregisterFlagSecureNoforwards = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
                }
            }
        }
        if (avatarContainer != null && updateSubtitle) {
            avatarContainer.updateSubtitle(true);
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) {
            updateTopPanel(true);
        }
    } else if (id == NotificationCenter.didReceiveNewMessages) {
        long did = (Long) args[0];
        ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
        if (did == dialog_id) {
            boolean scheduled = (Boolean) args[2];
            if (scheduled != (chatMode == MODE_SCHEDULED)) {
                if (chatMode != MODE_SCHEDULED && !isPaused && forwardingMessages == null) {
                    if (!arr.isEmpty() && arr.get(0).getId() < 0) {
                        openScheduledMessages();
                    }
                }
                return;
            }
            processNewMessages(arr);
        } else if (ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatInfo != null && did == -chatInfo.linked_chat_id) {
            for (int a = 0, N = arr.size(); a < N; a++) {
                MessageObject messageObject = arr.get(a);
                if (messageObject.isReply()) {
                    waitingForReplies.put(messageObject.getId(), messageObject);
                }
            }
            checkWaitingForReplies();
        }
    } else if (id == NotificationCenter.didLoadSendAsPeers) {
        loadSendAsPeers();
    } else if (id == NotificationCenter.didLoadSponsoredMessages) {
        addSponsoredMessages(true);
    } else if (id == NotificationCenter.closeChats) {
        if (args != null && args.length > 0) {
            long did = (Long) args[0];
            if (did == dialog_id) {
                finishFragment();
            }
        } else {
            if (AndroidUtilities.isTablet() && parentLayout != null && parentLayout.fragmentsStack.size() > 1) {
                finishFragment();
            } else {
                removeSelfFromStack();
            }
        }
    } else if (id == NotificationCenter.commentsRead) {
        long channelId = (Long) args[0];
        if (currentChat != null && currentChat.id == channelId) {
            int mid = (Integer) args[1];
            MessageObject obj = messagesDict[0].get(mid);
            if (obj != null && obj.hasReplies()) {
                int maxReadId = (Integer) args[2];
                if (paused) {
                    if (delayedReadRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(delayedReadRunnable);
                        delayedReadRunnable = null;
                    }
                    obj.messageOwner.replies.read_max_id = maxReadId;
                } else {
                    AndroidUtilities.runOnUIThread(delayedReadRunnable = () -> {
                        delayedReadRunnable = null;
                        obj.messageOwner.replies.read_max_id = maxReadId;
                    }, 500);
                }
            }
        }
    } else if (id == NotificationCenter.changeRepliesCounter) {
        long channelId = (Long) args[0];
        if (currentChat != null && currentChat.id == channelId) {
            int mid = (Integer) args[1];
            MessageObject obj = messagesDict[0].get(mid);
            if (obj != null && obj.messageOwner.replies != null) {
                Integer count = (Integer) args[2];
                obj.messageOwner.replies.replies += count;
                if (count > 0) {
                    TLRPC.Peer peer = getMessagesController().getPeer(ChatObject.getSendAsPeerId(currentChat, getMessagesController().getChatFull(currentChat.id)));
                    for (int c = 0, N = obj.messageOwner.replies.recent_repliers.size(); c < N; c++) {
                        if (MessageObject.getPeerId(obj.messageOwner.replies.recent_repliers.get(c)) == MessageObject.getPeerId(peer)) {
                            obj.messageOwner.replies.recent_repliers.remove(c);
                            break;
                        }
                    }
                    obj.messageOwner.replies.recent_repliers.add(0, peer);
                }
                if (obj.messageOwner.replies.replies < 0) {
                    obj.messageOwner.replies.replies = 0;
                }
            }
        }
    } else if (id == NotificationCenter.threadMessagesRead) {
        long did = (Long) args[0];
        if (dialog_id != did) {
            return;
        }
        int threadId = (Integer) args[1];
        if (threadId != threadMessageId) {
            return;
        }
        int inbox = (Integer) args[2];
        int outbox = (Integer) args[3];
        if (inbox > threadMaxInboxReadId) {
            threadMaxInboxReadId = inbox;
            for (int a = 0, size2 = messages.size(); a < size2; a++) {
                MessageObject obj = messages.get(a);
                int messageId = obj.getId();
                if (!obj.isOut() && messageId > 0 && messageId <= threadMaxInboxReadId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    if (chatAdapter != null) {
                        chatAdapter.invalidateRowWithMessageObject(obj);
                    }
                }
            }
        }
        if (outbox > threadMaxOutboxReadId) {
            threadMaxOutboxReadId = outbox;
            for (int a = 0, size2 = messages.size(); a < size2; a++) {
                MessageObject obj = messages.get(a);
                int messageId = obj.getId();
                if (obj.isOut() && messageId > 0 && messageId <= threadMaxOutboxReadId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    if (chatAdapter != null) {
                        chatAdapter.updateRowWithMessageObject(obj, false);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.messagesRead) {
        if (chatMode == MODE_SCHEDULED) {
            return;
        }
        LongSparseIntArray inbox = (LongSparseIntArray) args[0];
        LongSparseIntArray outbox = (LongSparseIntArray) args[1];
        boolean updated = false;
        if (inbox != null) {
            for (int b = 0, size = inbox.size(); b < size; b++) {
                long key = inbox.keyAt(b);
                long messageId = inbox.get(key);
                if (key != dialog_id) {
                    continue;
                }
                for (int a = 0, size2 = messages.size(); a < size2; a++) {
                    MessageObject obj = messages.get(a);
                    if (!obj.isOut() && obj.getId() > 0 && obj.getId() <= (int) messageId) {
                        if (!obj.isUnread()) {
                            break;
                        }
                        obj.setIsRead();
                        if (chatAdapter != null) {
                            chatAdapter.invalidateRowWithMessageObject(obj);
                        }
                        updated = true;
                        newUnreadMessageCount--;
                    }
                }
                removeUnreadPlane(false);
                break;
            }
        }
        if (updated) {
            if (newUnreadMessageCount < 0) {
                newUnreadMessageCount = 0;
            }
            if (pagedownButtonCounter != null) {
                if (prevSetUnreadCount != newUnreadMessageCount) {
                    prevSetUnreadCount = newUnreadMessageCount;
                    pagedownButtonCounter.setCount(newUnreadMessageCount, true);
                }
            }
        }
        if (outbox != null) {
            for (int b = 0, size = outbox.size(); b < size; b++) {
                long key = outbox.keyAt(b);
                int messageId = (int) outbox.get(key);
                if (key != dialog_id) {
                    continue;
                }
                for (int a = 0, size2 = messages.size(); a < size2; a++) {
                    MessageObject obj = messages.get(a);
                    if (obj.isOut() && obj.getId() > 0 && obj.getId() <= messageId) {
                        obj.setIsRead();
                        if (chatAdapter != null) {
                            chatAdapter.invalidateRowWithMessageObject(obj);
                        }
                    }
                }
                break;
            }
        }
    } else if (id == NotificationCenter.historyCleared) {
        long did = (Long) args[0];
        if (did != dialog_id) {
            return;
        }
        int max_id = (Integer) args[1];
        if (!pinnedMessageIds.isEmpty()) {
            pinnedMessageIds.clear();
            pinnedMessageObjects.clear();
            currentPinnedMessageId = 0;
            loadedPinnedMessagesCount = 0;
            totalPinnedMessagesCount = 0;
            updatePinnedMessageView(true);
        }
        boolean updated = false;
        for (int b = 0; b < messages.size(); b++) {
            MessageObject obj = messages.get(b);
            int mid = obj.getId();
            if (mid <= 0 || mid > max_id) {
                continue;
            }
            messages.remove(b);
            b--;
            messagesDict[0].remove(mid);
            ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey);
            if (dayArr != null) {
                dayArr.remove(obj);
                if (dayArr.isEmpty()) {
                    messagesByDays.remove(obj.dateKey);
                    if (b >= 0 && b < messages.size()) {
                        messages.remove(b);
                        b--;
                    }
                }
            }
            updated = true;
        }
        if (messages.isEmpty()) {
            if (!endReached[0] && !loading) {
                showProgressView(false);
                if (chatListView != null) {
                    chatListView.setEmptyView(null);
                }
                if (currentEncryptedChat == null) {
                    maxMessageId[0] = maxMessageId[1] = Integer.MAX_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MIN_VALUE;
                } else {
                    maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE;
                }
                maxDate[0] = maxDate[1] = Integer.MIN_VALUE;
                minDate[0] = minDate[1] = 0;
                waitingForLoad.add(lastLoadIndex);
                getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
                loading = true;
            } else {
                if (botButtons != null) {
                    botButtons = null;
                    if (chatActivityEnterView != null) {
                        chatActivityEnterView.setButtons(null, false);
                    }
                }
                if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
                    botUser = "";
                    updateBottomOverlay();
                }
            }
        }
        canShowPagedownButton = false;
        updatePagedownButtonVisibility(true);
        showMentionDownButton(false, true);
        removeUnreadPlane(true);
        if (updated && chatAdapter != null) {
            chatAdapter.notifyDataSetChanged(false);
        }
    } else if (id == NotificationCenter.messagesDeleted) {
        boolean scheduled = (Boolean) args[2];
        if (scheduled != (chatMode == MODE_SCHEDULED)) {
            return;
        }
        ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
        long channelId = (Long) args[1];
        processDeletedMessages(markAsDeletedMessages, channelId);
    } else if (id == NotificationCenter.messageReceivedByServer) {
        Boolean scheduled = (Boolean) args[6];
        if (scheduled != (chatMode == MODE_SCHEDULED)) {
            return;
        }
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (isThreadChat() && pendingSendMessagesDict.size() > 0) {
            MessageObject object = pendingSendMessagesDict.get(msgId);
            if (object != null) {
                Integer newMsgId = (Integer) args[1];
                pendingSendMessagesDict.put(newMsgId, object);
            }
        }
        if (obj != null) {
            checkChecksHint();
            if (obj.shouldRemoveVideoEditedInfo) {
                obj.videoEditedInfo = null;
                obj.shouldRemoveVideoEditedInfo = false;
            }
            Integer newMsgId = (Integer) args[1];
            if (!newMsgId.equals(msgId) && messagesDict[0].indexOfKey(newMsgId) >= 0) {
                MessageObject removed = messagesDict[0].get(msgId);
                messagesDict[0].remove(msgId);
                if (removed != null) {
                    int index = messages.indexOf(removed);
                    messages.remove(index);
                    ArrayList<MessageObject> dayArr = messagesByDays.get(removed.dateKey);
                    dayArr.remove(obj);
                    if (dayArr.isEmpty()) {
                        messagesByDays.remove(obj.dateKey);
                        if (index >= 0 && index < messages.size()) {
                            messages.remove(index);
                        }
                    }
                    if (chatAdapter != null) {
                        chatAdapter.notifyDataSetChanged(true);
                    }
                }
                return;
            }
            TLRPC.Message newMsgObj = (TLRPC.Message) args[2];
            Long grouped_id;
            if (args.length >= 4) {
                grouped_id = (Long) args[4];
            } else {
                grouped_id = 0L;
            }
            boolean mediaUpdated = false;
            boolean updatedForward = false;
            if (newMsgObj != null) {
                try {
                    updatedForward = obj.isForwarded() && (obj.messageOwner.reply_markup == null && newMsgObj.reply_markup != null || !obj.messageOwner.message.equals(newMsgObj.message));
                    mediaUpdated = updatedForward || obj.messageOwner.params != null && obj.messageOwner.params.containsKey("query_id") || newMsgObj.media != null && obj.messageOwner.media != null && !newMsgObj.media.getClass().equals(obj.messageOwner.media.getClass());
                } catch (Exception e) {
                    FileLog.e(e);
                }
                if (obj.getGroupId() != 0 && newMsgObj.grouped_id != 0) {
                    MessageObject.GroupedMessages oldGroup = groupedMessagesMap.get(obj.getGroupId());
                    if (oldGroup != null) {
                        groupedMessagesMap.put(newMsgObj.grouped_id, oldGroup);
                    }
                    obj.localSentGroupId = obj.messageOwner.grouped_id;
                    obj.messageOwner.grouped_id = grouped_id;
                }
                TLRPC.MessageFwdHeader fwdHeader = obj.messageOwner.fwd_from;
                obj.messageOwner = newMsgObj;
                if (fwdHeader != null && newMsgObj.fwd_from != null && !TextUtils.isEmpty(newMsgObj.fwd_from.from_name)) {
                    obj.messageOwner.fwd_from = fwdHeader;
                }
                obj.generateThumbs(true);
                obj.setType();
                if (newMsgObj.media instanceof TLRPC.TL_messageMediaGame) {
                    obj.applyNewText();
                }
            }
            if (updatedForward) {
                obj.measureInlineBotButtons();
            }
            messagesDict[0].remove(msgId);
            messagesDict[0].put(newMsgId, obj);
            obj.messageOwner.id = newMsgId;
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            obj.forceUpdate = mediaUpdated;
            addReplyMessageOwner(obj, msgId);
            if (args.length >= 6) {
                obj.applyMediaExistanceFlags((Integer) args[5]);
            }
            addToPolls(obj, null);
            ArrayList<MessageObject> messArr = new ArrayList<>();
            messArr.add(obj);
            if (currentEncryptedChat == null) {
                getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode == MODE_SCHEDULED, null);
            }
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj, false);
            }
            if (chatLayoutManager != null) {
                if (mediaUpdated && chatLayoutManager.findFirstVisibleItemPosition() == 0) {
                    moveScrollToLastMessage(false);
                }
            }
            getNotificationsController().playOutChatSound();
        }
    } else if (id == NotificationCenter.messageReceivedByAck) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj, false);
            }
        }
    } else if (id == NotificationCenter.messageSendError) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.groupCallUpdated) {
        Long chatId = (Long) args[0];
        if (dialog_id == -chatId) {
            groupCall = getMessagesController().getGroupCall(currentChat.id, false);
            if (fragmentContextView != null) {
                fragmentContextView.checkCall(openAnimationStartTime == 0 || SystemClock.elapsedRealtime() < openAnimationStartTime + 150);
            }
            checkGroupCallJoin(false);
        }
    } else if (id == NotificationCenter.didLoadChatInviter) {
        long chatId = (Long) args[0];
        if (dialog_id == -chatId && chatInviterId == 0) {
            chatInviterId = (Long) args[1];
            if (chatInfo != null) {
                chatInfo.inviterId = chatInviterId;
            }
            updateInfoTopView(openAnimationStartTime != 0 && SystemClock.elapsedRealtime() >= openAnimationStartTime + 150);
        }
    } else if (id == NotificationCenter.chatInfoDidLoad) {
        TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0];
        if (currentChat != null && chatFull.id == currentChat.id) {
            if (chatFull instanceof TLRPC.TL_channelFull) {
                if (currentChat.megagroup) {
                    int lastDate = 0;
                    if (chatFull.participants != null) {
                        for (int a = 0; a < chatFull.participants.participants.size(); a++) {
                            lastDate = Math.max(chatFull.participants.participants.get(a).date, lastDate);
                        }
                    }
                    if (lastDate == 0 || Math.abs(System.currentTimeMillis() / 1000 - lastDate) > 60 * 60) {
                        getMessagesController().loadChannelParticipants(currentChat.id);
                    }
                }
                if (chatFull.participants == null && chatInfo != null) {
                    chatFull.participants = chatInfo.participants;
                }
            }
            showGigagroupConvertAlert();
            long prevLinkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0;
            chatInfo = chatFull;
            groupCall = getMessagesController().getGroupCall(currentChat.id, true);
            if (ChatObject.isChannel(currentChat) && currentChat.megagroup && fragmentContextView != null) {
                fragmentContextView.checkCall(openAnimationStartTime == 0 || SystemClock.elapsedRealtime() < openAnimationStartTime + 150);
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.updateSendAsButton();
                chatActivityEnterView.updateFieldHint(false);
            }
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged(true);
            }
            if (prevLinkedChatId != chatInfo.linked_chat_id) {
                if (prevLinkedChatId != 0) {
                    TLRPC.Chat chat = getMessagesController().getChat(prevLinkedChatId);
                    getMessagesController().startShortPoll(chat, classGuid, true);
                }
                if (chatInfo.linked_chat_id != 0) {
                    TLRPC.Chat chat = getMessagesController().getChat(chatInfo.linked_chat_id);
                    if (chat != null && chat.megagroup) {
                        getMessagesController().startShortPoll(chat, classGuid, false);
                    }
                }
            }
            boolean animated = openAnimationStartTime != 0 && SystemClock.elapsedRealtime() >= openAnimationStartTime + 150;
            checkActionBarMenu(animated);
            if (chatInviterId == 0) {
                fillInviterId(true);
                updateInfoTopView(animated);
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setChatInfo(chatInfo);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setChatInfo(chatInfo);
            }
            if (!isThreadChat()) {
                if (avatarContainer != null) {
                    avatarContainer.updateOnlineCount();
                    avatarContainer.updateSubtitle();
                }
                if (!inMenuMode && !loadingPinnedMessagesList && !pinnedMessageIds.isEmpty() && chatInfo.pinned_msg_id > pinnedMessageIds.get(0)) {
                    getMediaDataController().loadPinnedMessages(dialog_id, 0, chatInfo.pinned_msg_id);
                    loadingPinnedMessagesList = true;
                }
            }
            if (chatInfo instanceof TLRPC.TL_chatFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = false;
                for (int a = 0; a < chatInfo.participants.participants.size(); a++) {
                    TLRPC.ChatParticipant participant = chatInfo.participants.participants.get(a);
                    TLRPC.User user = getMessagesController().getUser(participant.user_id);
                    if (user != null && user.bot) {
                        URLSpanBotCommand.enabled = true;
                        botsCount++;
                        if (!isThreadChat()) {
                            hasBotsCommands = true;
                        }
                        getMediaDataController().loadBotInfo(user.id, -chatInfo.id, true, classGuid);
                    }
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
            } else if (chatInfo instanceof TLRPC.TL_channelFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = !chatInfo.bot_info.isEmpty() && currentChat != null && currentChat.megagroup;
                botsCount = chatInfo.bot_info.size();
                for (int a = 0; a < chatInfo.bot_info.size(); a++) {
                    TLRPC.BotInfo bot = chatInfo.bot_info.get(a);
                    if (!isThreadChat() && !bot.commands.isEmpty() && (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup)) {
                        hasBotsCommands = true;
                    }
                    botInfo.put(bot.user_id, bot);
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
                if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
                    if (mentionsAdapter != null) {
                        mentionsAdapter.setBotInfo(botInfo);
                    }
                    if (chatActivityEnterView != null) {
                        chatActivityEnterView.setBotInfo(botInfo);
                    }
                }
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, true);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setBotsCount(botsCount);
            }
            if (chatMode == 0 && ChatObject.isChannel(currentChat) && mergeDialogId == 0 && chatInfo.migrated_from_chat_id != 0 && !isThreadChat()) {
                mergeDialogId = -chatInfo.migrated_from_chat_id;
                maxMessageId[1] = chatInfo.migrated_from_max_id;
                if (chatAdapter != null) {
                    chatAdapter.notifyDataSetChanged(true);
                }
                if (mergeDialogId != 0 && endReached[0]) {
                    checkScrollForLoad(false);
                }
            }
            checkGroupCallJoin((Boolean) args[3]);
            checkThemeEmoticon();
            if (pendingRequestsDelegate != null) {
                pendingRequestsDelegate.setChatInfo(chatInfo, true);
            }
        }
    } else if (id == NotificationCenter.chatInfoCantLoad) {
        long chatId = (Long) args[0];
        if (currentChat != null && currentChat.id == chatId) {
            int reason = (Integer) args[1];
            if (getParentActivity() == null || closeChatDialog != null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            if (reason == 0) {
                if (currentChat.has_link) {
                    builder.setMessage(LocaleController.getString("ChannelCantOpenBannedByAdmin", R.string.ChannelCantOpenBannedByAdmin));
                } else {
                    builder.setMessage(LocaleController.getString("ChannelCantOpenPrivate", R.string.ChannelCantOpenPrivate));
                }
            } else if (reason == 1) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenNa", R.string.ChannelCantOpenNa));
            } else if (reason == 2) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenBanned", R.string.ChannelCantOpenBanned));
            } else if (reason == 3) {
                builder.setMessage(LocaleController.getString("JoinByPeekChannelText", R.string.JoinByPeekChannelText));
            }
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
            if (showDialog(closeChatDialog = builder.create()) == null) {
                showCloseChatDialogLater = true;
            }
            loading = false;
            showProgressView(false);
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged(false);
            }
        }
    } else if (id == NotificationCenter.contactsDidLoad) {
        updateTopPanel(true);
        if (!isThreadChat() && avatarContainer != null) {
            avatarContainer.updateSubtitle();
        }
    } else if (id == NotificationCenter.encryptedChatUpdated) {
        TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0];
        if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) {
            currentEncryptedChat = chat;
            updateTopPanel(true);
            updateSecretStatus();
            initStickers();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setAllowStickersAndGifs(true, true);
                chatActivityEnterView.checkRoundVideo();
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setNeedBotContext(!chatActivityEnterView.isEditingMessage());
            }
        }
    } else if (id == NotificationCenter.messagesReadEncrypted) {
        int encId = (Integer) args[0];
        if (currentEncryptedChat != null && currentEncryptedChat.id == encId) {
            int date = (Integer) args[1];
            for (MessageObject obj : messages) {
                if (!obj.isOut()) {
                    continue;
                } else if (obj.isOut() && !obj.isUnread()) {
                    break;
                }
                if (obj.messageOwner.date - 1 <= date) {
                    obj.setIsRead();
                    if (chatAdapter != null) {
                        chatAdapter.invalidateRowWithMessageObject(obj);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.removeAllMessagesFromDialog) {
        long did = (Long) args[0];
        if (dialog_id == did) {
            if (threadMessageId != 0) {
                if (forwardEndReached[0]) {
                    forwardEndReached[0] = false;
                    hideForwardEndReached = false;
                    chatAdapter.notifyItemInserted(0);
                }
                getMessagesController().addToViewsQueue(threadMessageObject);
            } else {
                clearHistory((Boolean) args[1], (TLRPC.TL_updates_channelDifferenceTooLong) args[2]);
            }
        }
    } else if (id == NotificationCenter.screenshotTook) {
        updateInformationForScreenshotDetector();
    } else if (id == NotificationCenter.blockedUsersDidLoad) {
        if (currentUser != null && !UserObject.isReplyUser(currentUser)) {
            boolean oldValue = userBlocked;
            userBlocked = getMessagesController().blockePeers.indexOfKey(currentUser.id) >= 0;
            if (oldValue != userBlocked) {
                updateBottomOverlay();
            }
        }
    } else if (id == NotificationCenter.fileNewChunkAvailable) {
        MessageObject messageObject = (MessageObject) args[0];
        long finalSize = (Long) args[3];
        if (finalSize != 0 && dialog_id == messageObject.getDialogId()) {
            MessageObject currentObject = messagesDict[0].get(messageObject.getId());
            if (currentObject != null && currentObject.messageOwner.media.document != null) {
                currentObject.messageOwner.media.document.size = (int) finalSize;
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.didCreatedNewDeleteTask) {
        long dialogId = (Long) args[0];
        if (dialogId != dialog_id) {
            return;
        }
        SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[1];
        boolean changed = false;
        for (int i = 0; i < mids.size(); i++) {
            int key = mids.keyAt(i);
            ArrayList<Integer> arr = mids.get(key);
            for (int a = 0; a < arr.size(); a++) {
                Integer mid = arr.get(a);
                MessageObject messageObject = messagesDict[0].get(mid);
                if (messageObject != null) {
                    messageObject.messageOwner.destroyTime = key;
                    changed = true;
                }
            }
        }
        if (changed) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.messagePlayingDidStart) {
        MessageObject messageObject = (MessageObject) args[0];
        if (messageObject.eventId != 0) {
            return;
        }
        sendSecretMessageRead(messageObject, true);
        if ((messageObject.isRoundVideo() || messageObject.isVideo()) && fragmentView != null && fragmentView.getParent() != null) {
            MediaController.getInstance().setTextureView(createTextureView(true), aspectRatioFrameLayout, videoPlayerContainer, true);
            updateTextureViewPosition(true);
        }
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject1 = cell.getMessageObject();
                    if (messageObject1 != null) {
                        boolean isVideo = messageObject1.isVideo();
                        if (messageObject1.isRoundVideo() || isVideo) {
                            cell.checkVideoPlayback(!messageObject.equals(messageObject1), null);
                            if (!MediaController.getInstance().isPlayingMessage(messageObject1)) {
                                if (isVideo && !MediaController.getInstance().isGoingToShowMessageObject(messageObject1)) {
                                    AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
                                    if (animation != null) {
                                        animation.start();
                                    }
                                }
                                if (messageObject1.audioProgress != 0) {
                                    messageObject1.resetPlayingProgress();
                                    cell.invalidate();
                                }
                            } else if (isVideo) {
                                cell.updateButtonState(false, true, false);
                            }
                            if (messageObject1.isRoundVideo()) {
                                int position = chatListView.getChildAdapterPosition(cell);
                                if (position >= 0) {
                                    if (MediaController.getInstance().isPlayingMessage(messageObject1)) {
                                        boolean keyboardIsVisible = contentView.getKeyboardHeight() >= AndroidUtilities.dp(20);
                                        chatLayoutManager.scrollToPositionWithOffset(position, (int) ((chatListView.getMeasuredHeight() - chatListViewPaddingTop - (keyboardIsVisible ? AndroidUtilities.roundMessageSize : AndroidUtilities.roundPlayingMessageSize)) / 2), false);
                                    }
                                    chatAdapter.notifyItemChanged(position);
                                }
                            }
                        } else if (messageObject1.isVoice() || messageObject1.isMusic()) {
                            cell.updateButtonState(false, true, false);
                        }
                    }
                }
            }
            count = mentionListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = mentionListView.getChildAt(a);
                if (view instanceof ContextLinkCell) {
                    ContextLinkCell cell = (ContextLinkCell) view;
                    MessageObject messageObject1 = cell.getMessageObject();
                    if (messageObject1 != null && (messageObject1.isVoice() || messageObject1.isMusic())) {
                        cell.updateButtonState(false, true);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.messagePlayingGoingToStop) {
        boolean injecting = (Boolean) args[1];
        if (injecting) {
            contentView.removeView(videoPlayerContainer);
            videoPlayerContainer = null;
            videoTextureView = null;
            aspectRatioFrameLayout = null;
        } else {
            if (chatListView != null && videoPlayerContainer != null && videoPlayerContainer.getTag() != null) {
                MessageObject messageObject = (MessageObject) args[0];
                int count = chatListView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View view = chatListView.getChildAt(a);
                    if (view instanceof ChatMessageCell) {
                        ChatMessageCell cell = (ChatMessageCell) view;
                        MessageObject messageObject1 = cell.getMessageObject();
                        if (messageObject == messageObject1) {
                            AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
                            if (animation != null) {
                                Bitmap bitmap = animation.getAnimatedBitmap();
                                if (bitmap != null) {
                                    try {
                                        Bitmap src = videoTextureView.getBitmap(bitmap.getWidth(), bitmap.getHeight());
                                        Canvas canvas = new Canvas(bitmap);
                                        canvas.drawBitmap(src, 0, 0, null);
                                        src.recycle();
                                    } catch (Throwable e) {
                                        FileLog.e(e);
                                    }
                                }
                                animation.seekTo(messageObject.audioProgressMs, !getFileLoader().isLoadingVideo(messageObject.getDocument(), true));
                            }
                            break;
                        }
                    }
                }
            }
        }
    } else if (id == NotificationCenter.messagePlayingDidReset || id == NotificationCenter.messagePlayingPlayStateChanged) {
        if (id == NotificationCenter.messagePlayingDidReset) {
            AndroidUtilities.runOnUIThread(destroyTextureViewRunnable);
        }
        int messageId = (int) args[0];
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null) {
                        if (messageObject.isVoice() || messageObject.isMusic()) {
                            cell.updateButtonState(false, true, false);
                        } else if (messageObject.isVideo()) {
                            cell.updateButtonState(false, true, false);
                            if (!MediaController.getInstance().isPlayingMessage(messageObject) && !MediaController.getInstance().isGoingToShowMessageObject(messageObject)) {
                                AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
                                if (animation != null) {
                                    animation.start();
                                }
                            }
                        } else if (messageObject.isRoundVideo()) {
                            if (!MediaController.getInstance().isPlayingMessage(messageObject)) {
                                Bitmap bitmap = null;
                                if (id == NotificationCenter.messagePlayingDidReset && cell.getMessageObject().getId() == messageId && videoTextureView != null) {
                                    bitmap = videoTextureView.getBitmap();
                                    if (bitmap != null && bitmap.getPixel(0, 0) == Color.TRANSPARENT) {
                                        bitmap = null;
                                    }
                                }
                                cell.checkVideoPlayback(true, bitmap);
                            }
                            int position = chatListView.getChildAdapterPosition(cell);
                            messageObject.forceUpdate = true;
                            if (position >= 0) {
                                chatAdapter.notifyItemChanged(position);
                            }
                        }
                    }
                }
            }
            count = mentionListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = mentionListView.getChildAt(a);
                if (view instanceof ContextLinkCell) {
                    ContextLinkCell cell = (ContextLinkCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
                        cell.updateButtonState(false, true);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.messagePlayingProgressDidChanged) {
        Integer mid = (Integer) args[0];
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject playing = cell.getMessageObject();
                    if (playing != null && playing.getId() == mid) {
                        MessageObject player = MediaController.getInstance().getPlayingMessageObject();
                        if (player != null && !cell.getSeekBar().isDragging()) {
                            playing.audioProgress = player.audioProgress;
                            playing.audioProgressSec = player.audioProgressSec;
                            playing.audioPlayerDuration = player.audioPlayerDuration;
                            cell.updatePlayingMessageProgress();
                            if (drawLaterRoundProgressCell == cell) {
                                fragmentView.invalidate();
                            }
                        }
                        break;
                    }
                }
            }
        }
    } else if (id == NotificationCenter.didUpdatePollResults) {
        long pollId = (Long) args[0];
        ArrayList<MessageObject> arrayList = polls.get(pollId);
        if (arrayList != null) {
            TLRPC.TL_poll poll = (TLRPC.TL_poll) args[1];
            TLRPC.PollResults results = (TLRPC.PollResults) args[2];
            View pollView = null;
            boolean isVotedChanged = false;
            boolean isQuiz = false;
            for (int a = 0, N = arrayList.size(); a < N; a++) {
                MessageObject object = arrayList.get(a);
                boolean isVoted = object.isVoted();
                TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
                if (poll != null) {
                    media.poll = poll;
                    isQuiz = poll.quiz;
                } else if (media.poll != null) {
                    isQuiz = media.poll.quiz;
                }
                MessageObject.updatePollResults(media, results);
                if (chatAdapter != null) {
                    pollView = chatAdapter.updateRowWithMessageObject(object, true);
                }
                if (isVoted != object.isVoted()) {
                    isVotedChanged = true;
                }
            }
            if (isVotedChanged && isQuiz && undoView != null && pollView instanceof ChatMessageCell) {
                ChatMessageCell cell = (ChatMessageCell) pollView;
                if (cell.isAnimatingPollAnswer()) {
                    for (int a = 0, N = results.results.size(); a < N; a++) {
                        TLRPC.TL_pollAnswerVoters voters = results.results.get(a);
                        if (voters.chosen) {
                            if (voters.correct) {
                                fireworksOverlay.start();
                                pollView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                            } else {
                                ((ChatMessageCell) pollView).shakeView();
                                pollView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                                showPollSolution(cell.getMessageObject(), results);
                                cell.showHintButton(false, true, 0);
                            }
                            break;
                        }
                    }
                }
            }
        }
    } else if (id == NotificationCenter.didUpdateReactions) {
        long did = (Long) args[0];
        if (did == dialog_id || did == mergeDialogId) {
            int msgId = (Integer) args[1];
            MessageObject messageObject = messagesDict[did == dialog_id ? 0 : 1].get(msgId);
            if (messageObject != null) {
                MessageObject.updateReactions(messageObject.messageOwner, (TLRPC.TL_messageReactions) args[2]);
                messageObject.forceUpdate = true;
                messageObject.reactionsChanged = true;
                updateMessageAnimated(messageObject, true);
            }
        }
    } else if (id == NotificationCenter.didVerifyMessagesStickers) {
        ArrayList<TLRPC.Message> messages = (ArrayList<TLRPC.Message>) args[0];
        for (int a = 0, N = messages.size(); a < N; a++) {
            TLRPC.Message message = messages.get(a);
            MessageObject existMessageObject = messagesDict[0].get(message.id);
            if (existMessageObject != null) {
                existMessageObject.messageOwner.stickerVerified = message.stickerVerified;
                existMessageObject.setType();
                if (chatAdapter != null) {
                    chatAdapter.updateRowWithMessageObject(existMessageObject, false);
                }
            }
        }
    } else if (id == NotificationCenter.updateMessageMedia) {
        TLRPC.Message message = (TLRPC.Message) args[0];
        MessageObject existMessageObject = messagesDict[0].get(message.id);
        if (existMessageObject != null) {
            existMessageObject.messageOwner.media = message.media;
            existMessageObject.messageOwner.attachPath = message.attachPath;
            existMessageObject.generateThumbs(false);
            if (existMessageObject.getGroupId() != 0 && (existMessageObject.photoThumbs == null || existMessageObject.photoThumbs.isEmpty())) {
                MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(existMessageObject.getGroupId());
                if (groupedMessages != null) {
                    int idx = groupedMessages.messages.indexOf(existMessageObject);
                    if (idx >= 0) {
                        int updateCount = groupedMessages.messages.size();
                        MessageObject messageObject = null;
                        if (idx > 0 && idx < groupedMessages.messages.size() - 1) {
                            MessageObject.GroupedMessages slicedGroup = new MessageObject.GroupedMessages();
                            slicedGroup.groupId = Utilities.random.nextLong();
                            slicedGroup.messages.addAll(groupedMessages.messages.subList(idx + 1, groupedMessages.messages.size()));
                            for (int b = 0; b < slicedGroup.messages.size(); b++) {
                                slicedGroup.messages.get(b).localGroupId = slicedGroup.groupId;
                                groupedMessages.messages.remove(idx + 1);
                            }
                            groupedMessagesMap.put(slicedGroup.groupId, slicedGroup);
                            messageObject = slicedGroup.messages.get(slicedGroup.messages.size() - 1);
                            slicedGroup.calculate();
                        }
                        groupedMessages.messages.remove(idx);
                        if (groupedMessages.messages.isEmpty()) {
                            groupedMessagesMap.remove(groupedMessages.groupId);
                        } else {
                            if (messageObject == null) {
                                messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
                            }
                            groupedMessages.calculate();
                            int index = messages.indexOf(messageObject);
                            if (index >= 0) {
                                if (chatAdapter != null) {
                                    chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, updateCount);
                                }
                            }
                        }
                    }
                }
            }
            if (message.media.ttl_seconds != 0 && (message.media.photo instanceof TLRPC.TL_photoEmpty || message.media.document instanceof TLRPC.TL_documentEmpty)) {
                existMessageObject.setType();
                if (chatAdapter != null) {
                    chatAdapter.updateRowWithMessageObject(existMessageObject, false);
                }
            } else {
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.replaceMessagesObjects) {
        long did = (long) args[0];
        if (did != dialog_id && did != mergeDialogId) {
            return;
        }
        int loadIndex = did == dialog_id ? 0 : 1;
        ArrayList<MessageObject> messageObjects = (ArrayList<MessageObject>) args[1];
        replaceMessageObjects(messageObjects, loadIndex, false);
    } else if (id == NotificationCenter.notificationsSettingsUpdated) {
        updateTitleIcons();
        if (ChatObject.isChannel(currentChat) || UserObject.isReplyUser(currentUser)) {
            updateBottomOverlay();
        }
    } else if (id == NotificationCenter.replyMessagesDidLoad) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            ArrayList<MessageObject> loadedMessages = (ArrayList<MessageObject>) args[1];
            LongSparseArray<SparseArray<ArrayList<MessageObject>>> replyMessageOwners = (LongSparseArray<SparseArray<ArrayList<MessageObject>>>) args[2];
            for (int a = 0, N = loadedMessages.size(); a < N; a++) {
                MessageObject obj = loadedMessages.get(a);
                repliesMessagesDict.put(obj.getId(), obj);
            }
            if (replyMessageOwners != null) {
                for (int a = 0, N = replyMessageOwners.size(); a < N; a++) {
                    SparseArray<ArrayList<MessageObject>> sparseArray = replyMessageOwners.valueAt(a);
                    for (int c = 0, N3 = sparseArray.size(); c < N3; c++) {
                        ArrayList<MessageObject> arrayList = sparseArray.valueAt(c);
                        for (int b = 0, N2 = arrayList.size(); b < N2; b++) {
                            addReplyMessageOwner(arrayList.get(b), 0);
                        }
                    }
                }
            }
            updateVisibleRows();
        } else if (waitingForReplies.size() != 0 && ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatInfo != null && did == -chatInfo.linked_chat_id) {
            checkWaitingForReplies();
        }
        updateReplyMessageHeader(true);
    } else if (id == NotificationCenter.didLoadPinnedMessages) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            ArrayList<Integer> ids = (ArrayList<Integer>) args[1];
            boolean pin = (Boolean) args[2];
            ArrayList<MessageObject> arrayList = (ArrayList<MessageObject>) args[3];
            HashMap<Integer, MessageObject> dict = null;
            if (ids != null) {
                HashMap<Integer, MessageObject> replaceObjects = (HashMap<Integer, MessageObject>) args[4];
                int maxId = (Integer) args[5];
                int totalPinnedCount = (Integer) args[6];
                boolean endReached = (Boolean) args[7];
                HashMap<Integer, MessageObject> oldPinned = new HashMap<>(pinnedMessageObjects);
                if (replaceObjects != null) {
                    loadingPinnedMessagesList = false;
                    if (maxId == 0) {
                        pinnedMessageIds.clear();
                        pinnedMessageObjects.clear();
                    }
                    totalPinnedMessagesCount = totalPinnedCount;
                    pinnedEndReached = endReached;
                }
                boolean updated = false;
                if (arrayList != null) {
                    getMediaDataController().loadReplyMessagesForMessages(arrayList, dialog_id, false, null);
                }
                for (int a = 0, N = ids.size(); a < N; a++) {
                    Integer mid = ids.get(a);
                    if (pin) {
                        if (pinnedMessageObjects.containsKey(mid)) {
                            continue;
                        }
                        pinnedMessageIds.add(mid);
                        MessageObject object = oldPinned.get(mid);
                        if (object == null) {
                            object = messagesDict[0].get(mid);
                        }
                        if (object == null && arrayList != null) {
                            if (dict == null) {
                                dict = new HashMap<>();
                                for (int b = 0, N2 = arrayList.size(); b < N2; b++) {
                                    MessageObject obj = arrayList.get(b);
                                    if (obj != null) {
                                        dict.put(obj.getId(), obj);
                                    }
                                }
                            }
                            object = dict.get(mid);
                        }
                        if (object == null && replaceObjects != null) {
                            object = replaceObjects.get(mid);
                        }
                        pinnedMessageObjects.put(mid, object);
                        if (replaceObjects == null) {
                            totalPinnedMessagesCount++;
                        }
                    } else {
                        if (!pinnedMessageObjects.containsKey(mid)) {
                            continue;
                        }
                        pinnedMessageObjects.remove(mid);
                        pinnedMessageIds.remove(mid);
                        if (replaceObjects == null) {
                            totalPinnedMessagesCount--;
                        }
                    }
                    loadedPinnedMessagesCount = pinnedMessageIds.size();
                    if (chatAdapter != null) {
                        MessageObject obj = messagesDict[0].get(mid);
                        if (obj != null) {
                            if (obj.hasValidGroupId()) {
                                MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(obj.getGroupId());
                                if (groupedMessages != null) {
                                    int index = messages.indexOf(groupedMessages.messages.get(groupedMessages.messages.size() - 1));
                                    if (index >= 0) {
                                        chatAdapter.notifyItemRangeChanged(index, groupedMessages.messages.size());
                                    }
                                }
                            } else {
                                chatAdapter.updateRowWithMessageObject(obj, false);
                            }
                        }
                    }
                    updated = true;
                }
                if (updated) {
                    if (chatMode == MODE_PINNED && avatarContainer != null) {
                        avatarContainer.setTitle(LocaleController.formatPluralString("PinnedMessagesCount", getPinnedMessagesCount()));
                    }
                    Collections.sort(pinnedMessageIds, (o1, o2) -> o2.compareTo(o1));
                    if (pinnedMessageIds.isEmpty()) {
                        hidePinnedMessageView(true);
                    } else {
                        updateMessagesVisiblePart(false);
                    }
                }
                if (chatMode == MODE_PINNED) {
                    if (pin) {
                        if (arrayList != null) {
                            processNewMessages(arrayList);
                        }
                    } else {
                        processDeletedMessages(ids, ChatObject.isChannel(currentChat) ? dialog_id : 0);
                    }
                }
            } else {
                if (pin) {
                    for (int a = 0, N = arrayList.size(); a < N; a++) {
                        MessageObject message = arrayList.get(a);
                        if (pinnedMessageObjects.containsKey(message.getId())) {
                            pinnedMessageObjects.put(message.getId(), message);
                        }
                        loadingPinnedMessages.remove(message.getId());
                    }
                    getMediaDataController().loadReplyMessagesForMessages(arrayList, dialog_id, false, null);
                    updateMessagesVisiblePart(false);
                } else {
                    pinnedMessageIds.clear();
                    pinnedMessageObjects.clear();
                    currentPinnedMessageId = 0;
                    loadedPinnedMessagesCount = 0;
                    totalPinnedMessagesCount = 0;
                    hidePinnedMessageView(true);
                }
            }
        }
    } else if (id == NotificationCenter.didReceivedWebpages) {
        ArrayList<TLRPC.Message> arrayList = (ArrayList<TLRPC.Message>) args[0];
        boolean updated = false;
        for (int a = 0; a < arrayList.size(); a++) {
            TLRPC.Message message = arrayList.get(a);
            long did = MessageObject.getDialogId(message);
            if (did != dialog_id && did != mergeDialogId) {
                continue;
            }
            MessageObject currentMessage = messagesDict[did == dialog_id ? 0 : 1].get(message.id);
            if (currentMessage != null) {
                currentMessage.messageOwner.media = new TLRPC.TL_messageMediaWebPage();
                currentMessage.messageOwner.media.webpage = message.media.webpage;
                currentMessage.generateThumbs(true);
                updated = true;
            }
        }
        if (updated) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.didReceivedWebpagesInUpdates) {
        if (foundWebPage != null) {
            LongSparseArray<TLRPC.WebPage> hashMap = (LongSparseArray<TLRPC.WebPage>) args[0];
            for (int a = 0; a < hashMap.size(); a++) {
                TLRPC.WebPage webPage = hashMap.valueAt(a);
                if (webPage.id == foundWebPage.id) {
                    showFieldPanelForWebPage(!(webPage instanceof TLRPC.TL_webPageEmpty), webPage, false);
                    break;
                }
            }
        }
    } else if (id == NotificationCenter.messagesReadContent) {
        long did = (Long) args[0];
        if (did != dialog_id && (ChatObject.isChannel(currentChat) || did != 0)) {
            return;
        }
        ArrayList<Integer> arrayList = (ArrayList<Integer>) args[1];
        for (int a = 0, N = arrayList.size(); a < N; a++) {
            int mid = arrayList.get(a);
            MessageObject currentMessage = messagesDict[0].get(mid);
            if (currentMessage != null) {
                currentMessage.setContentIsRead();
                if (currentMessage.messageOwner.mentioned) {
                    newMentionsCount--;
                    if (newMentionsCount <= 0) {
                        newMentionsCount = 0;
                        hasAllMentionsLocal = true;
                        showMentionDownButton(false, true);
                    } else {
                        if (mentiondownButtonCounter != null) {
                            mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
                        }
                    }
                }
                if (chatAdapter != null) {
                    chatAdapter.invalidateRowWithMessageObject(currentMessage);
                }
            }
        }
    } else if (id == NotificationCenter.botInfoDidLoad) {
        int guid = (Integer) args[1];
        if (classGuid == guid || guid == 0) {
            TLRPC.BotInfo info = (TLRPC.BotInfo) args[0];
            if (currentEncryptedChat == null) {
                if (!info.commands.isEmpty() && !ChatObject.isChannel(currentChat) && !isThreadChat()) {
                    hasBotsCommands = true;
                }
                botInfo.put(info.user_id, info);
                if (chatAdapter != null) {
                    int prevRow = chatAdapter.botInfoRow;
                    chatAdapter.updateRowsInternal();
                    if (prevRow < 0 && chatAdapter.botInfoRow >= 0) {
                        chatAdapter.notifyItemInserted(chatAdapter.botInfoRow);
                    } else if (prevRow >= 0 && chatAdapter.botInfoRow < 0) {
                        chatAdapter.notifyItemRemoved(prevRow);
                    } else if (prevRow >= 0 && chatAdapter.botInfoRow >= 0) {
                        chatAdapter.notifyItemChanged(chatAdapter.botInfoRow);
                    }
                }
                if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
                    if (mentionsAdapter != null) {
                        mentionsAdapter.setBotInfo(botInfo);
                    }
                    if (chatActivityEnterView != null) {
                        chatActivityEnterView.setBotInfo(botInfo);
                    }
                }
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, true);
                }
            }
            updateBotButtons();
        }
    } else if (id == NotificationCenter.botKeyboardDidLoad) {
        if (dialog_id == (Long) args[1]) {
            TLRPC.Message message = (TLRPC.Message) args[0];
            if (message != null && !userBlocked) {
                botButtons = new MessageObject(currentAccount, message, false, false);
                checkBotKeyboard();
            } else {
                botButtons = null;
                if (chatActivityEnterView != null) {
                    if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
                        botReplyButtons = null;
                        hideFieldPanel(true);
                    }
                    chatActivityEnterView.setButtons(botButtons);
                }
            }
        }
    } else if (id == NotificationCenter.chatSearchResultsAvailable) {
        if (classGuid == (Integer) args[0]) {
            boolean jumpToMessage = (Boolean) args[6];
            if (jumpToMessage) {
                int messageId = (Integer) args[1];
                long did = (Long) args[3];
                if (messageId != 0) {
                    scrollToMessageId(messageId, 0, true, did == dialog_id ? 0 : 1, true, 0);
                } else {
                    updateVisibleRows();
                }
                updateSearchButtons((Integer) args[2], (Integer) args[4], (Integer) args[5]);
                if (searchItem != null) {
                    searchItem.setShowSearchProgress(false);
                }
            }
            if (messagesSearchAdapter != null) {
                messagesSearchAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.chatSearchResultsLoading) {
        if (classGuid == (Integer) args[0]) {
            if (searchItem != null) {
                searchItem.setShowSearchProgress(true);
            }
            if (messagesSearchAdapter != null) {
                messagesSearchAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.didUpdateMessagesViews) {
        LongSparseArray<SparseIntArray> channelViews = (LongSparseArray<SparseIntArray>) args[0];
        LongSparseArray<SparseIntArray> channelForwards = (LongSparseArray<SparseIntArray>) args[1];
        LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelReplies = (LongSparseArray<SparseArray<TLRPC.MessageReplies>>) args[2];
        boolean addingReplies = (Boolean) args[3];
        boolean updated = false;
        LongSparseArray<MessageObject.GroupedMessages> newGroups = null;
        ArrayList<Integer> updatedRows = null;
        for (int b = 0; b < 2; b++) {
            LongSparseArray<SparseIntArray> sparseArray = b == 0 ? channelViews : channelForwards;
            if (sparseArray == null) {
                continue;
            }
            SparseIntArray array = sparseArray.get(dialog_id);
            if (array != null) {
                for (int a = 0; a < array.size(); a++) {
                    int messageId = array.keyAt(a);
                    MessageObject messageObject = messagesDict[0].get(messageId);
                    if (messageObject != null) {
                        int newValue = array.get(messageId);
                        if (b == 0) {
                            if (newValue <= messageObject.messageOwner.views) {
                                continue;
                            }
                            messageObject.messageOwner.views = newValue;
                        } else {
                            if (newValue <= messageObject.messageOwner.forwards) {
                                continue;
                            }
                            messageObject.messageOwner.forwards = newValue;
                        }
                        if (messageObject.hasValidGroupId()) {
                            MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(messageObject.getGroupId());
                            if (groupedMessages != null) {
                                if (newGroups == null) {
                                    newGroups = new LongSparseArray<>();
                                }
                                newGroups.put(groupedMessages.groupId, groupedMessages);
                            }
                        }
                        if (chatAdapter != null) {
                            chatAdapter.updateRowWithMessageObject(messageObject, false);
                        }
                    }
                }
            }
        }
        if (channelReplies != null) {
            SparseArray<TLRPC.MessageReplies> array = channelReplies.get(dialog_id);
            boolean hasChatInBack = false;
            if (threadMessageObject != null && parentLayout != null) {
                for (int a = 0, N = parentLayout.fragmentsStack.size() - 1; a < N; a++) {
                    BaseFragment fragment = parentLayout.fragmentsStack.get(a);
                    if (fragment != this && fragment instanceof ChatActivity) {
                        ChatActivity chatActivity = (ChatActivity) fragment;
                        if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getChatMode() == getChatMode()) {
                            hasChatInBack = true;
                            break;
                        }
                    }
                }
            }
            if (array != null) {
                for (int a = 0; a < array.size(); a++) {
                    int messageId = array.keyAt(a);
                    MessageObject messageObject = messagesDict[0].get(messageId);
                    if (messageObject != null && messageObject != threadMessageObject) {
                        TLRPC.MessageReplies newValue = array.get(messageId);
                        if (newValue == null || !addingReplies && messageObject.messageOwner.replies != null && newValue.replies_pts <= messageObject.messageOwner.replies.replies_pts && newValue.read_max_id <= messageObject.messageOwner.replies.read_max_id && newValue.max_id <= messageObject.messageOwner.replies.max_id) {
                            continue;
                        }
                        if (addingReplies) {
                            if (!hasChatInBack) {
                                if (messageObject.messageOwner.replies == null) {
                                    messageObject.messageOwner.replies = new TLRPC.TL_messageReplies();
                                }
                                messageObject.messageOwner.replies.replies += newValue.replies;
                                for (int c = 0, N = newValue.recent_repliers.size(); c < N; c++) {
                                    messageObject.messageOwner.replies.recent_repliers.remove(newValue.recent_repliers.get(c));
                                }
                                messageObject.messageOwner.replies.recent_repliers.addAll(0, newValue.recent_repliers);
                                while (messageObject.messageOwner.replies.recent_repliers.size() > 3) {
                                    messageObject.messageOwner.replies.recent_repliers.remove(0);
                                }
                            }
                        } else {
                            if (messageObject.messageOwner.replies != null && messageObject.messageOwner.replies.read_max_id > newValue.read_max_id) {
                                newValue.read_max_id = messageObject.messageOwner.replies.read_max_id;
                            }
                            messageObject.messageOwner.replies = newValue;
                        }
                        if (messageObject.hasValidGroupId()) {
                            MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(messageObject.getGroupId());
                            if (groupedMessages != null) {
                                if (newGroups == null) {
                                    newGroups = new LongSparseArray<>();
                                }
                                newGroups.put(groupedMessages.groupId, groupedMessages);
                                for (int b = 0, N2 = groupedMessages.messages.size(); b < N2; b++) {
                                    groupedMessages.messages.get(b).animateComments = true;
                                }
                            }
                        } else if (chatAdapter != null) {
                            int row = messages.indexOf(messageObject);
                            if (row >= 0) {
                                if (updatedRows == null) {
                                    updatedRows = new ArrayList<>();
                                }
                                updatedRows.add(row + chatAdapter.messagesStartRow);
                            }
                            messageObject.animateComments = true;
                        }
                        updated = true;
                    }
                }
            }
        }
        if (updated) {
            if (chatAdapter != null) {
                if (newGroups != null) {
                    for (int b = 0, N = newGroups.size(); b < N; b++) {
                        MessageObject.GroupedMessages groupedMessages = newGroups.valueAt(b);
                        MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
                        int index = messages.indexOf(messageObject);
                        if (index >= 0) {
                            chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, groupedMessages.messages.size());
                        }
                    }
                }
                if (updatedRows != null) {
                    for (int b = 0, N = updatedRows.size(); b < N; b++) {
                        chatAdapter.notifyItemChanged(updatedRows.get(b));
                    }
                }
            }
            updateVisibleRows();
            updateReplyMessageHeader(true);
        }
    } else if (id == NotificationCenter.peerSettingsDidLoad) {
        long did = (Long) args[0];
        if (did == dialog_id || currentUser != null && currentUser.id == did) {
            updateTopPanel(!paused);
            updateInfoTopView(true);
        }
    } else if (id == NotificationCenter.newDraftReceived) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            applyDraftMaybe(true);
        }
    } else if (id == NotificationCenter.pinnedInfoDidLoad) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            ArrayList<Integer> pinnedMessages = (ArrayList<Integer>) args[1];
            if (chatMode == MODE_PINNED) {
                pinnedMessageIds = new ArrayList<>(pinnedMessages);
                pinnedMessageObjects = new HashMap<>((HashMap<Integer, MessageObject>) args[2]);
            } else {
                pinnedMessageIds = pinnedMessages;
                pinnedMessageObjects = (HashMap<Integer, MessageObject>) args[2];
            }
            loadedPinnedMessagesCount = pinnedMessageIds.size();
            totalPinnedMessagesCount = (Integer) args[3];
            pinnedEndReached = (Boolean) args[4];
            getMediaDataController().loadReplyMessagesForMessages(new ArrayList<>(pinnedMessageObjects.values()), dialog_id, false, null);
            if (!inMenuMode && !loadingPinnedMessagesList && totalPinnedMessagesCount == 0 && !pinnedEndReached) {
                getMediaDataController().loadPinnedMessages(dialog_id, 0, pinnedMessageIds.isEmpty() ? 0 : pinnedMessageIds.get(0));
                loadingPinnedMessagesList = true;
            }
        }
    } else if (id == NotificationCenter.userInfoDidLoad) {
        Long uid = (Long) args[0];
        if (currentUser != null && currentUser.id == uid) {
            userInfo = (TLRPC.UserFull) args[1];
            checkThemeEmoticon();
            if (headerItem != null) {
                showAudioCallAsIcon = userInfo.phone_calls_available && !inPreviewMode;
                if (userInfo.phone_calls_available) {
                    if (showAudioCallAsIcon) {
                        if (audioCallIconItem != null) {
                            if (openAnimationStartTime != 0 && audioCallIconItem.getVisibility() != View.VISIBLE) {
                                audioCallIconItem.setAlpha(0f);
                                audioCallIconItem.animate().alpha(1f).setDuration(150).start();
                            }
                            audioCallIconItem.setVisibility(View.VISIBLE);
                        }
                    } else {
                        headerItem.showSubItem(call);
                    }
                    if (userInfo.video_calls_available) {
                        headerItem.showSubItem(video_call);
                    } else {
                        headerItem.hideSubItem(video_call);
                    }
                } else {
                    headerItem.hideSubItem(call);
                    headerItem.hideSubItem(video_call);
                    if (audioCallIconItem != null) {
                        audioCallIconItem.setVisibility(View.GONE);
                    }
                }
            }
            checkActionBarMenu(false);
            if (!inMenuMode && !loadingPinnedMessagesList && !pinnedMessageIds.isEmpty() && userInfo.pinned_msg_id > pinnedMessageIds.get(0)) {
                getMediaDataController().loadPinnedMessages(dialog_id, 0, userInfo.pinned_msg_id);
                loadingPinnedMessagesList = true;
            }
        }
    } else if (id == NotificationCenter.didSetNewWallpapper) {
        if (fragmentView != null) {
            contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion());
            progressView2.invalidate();
            if (emptyView != null) {
                emptyView.invalidate();
            }
            if (bigEmptyView != null) {
                bigEmptyView.invalidate();
            }
            if (floatingDateView != null) {
                floatingDateView.invalidate();
            }
            chatListView.invalidateViews();
        }
    } else if (id == NotificationCenter.didApplyNewTheme) {
        if (undoView == null || paused) {
            return;
        }
        Theme.ThemeInfo themeInfo = (Theme.ThemeInfo) args[0];
        Theme.ThemeAccent themeAccent = (Theme.ThemeAccent) args[1];
        if (!themeInfo.firstAccentIsDefault || themeAccent == null || themeAccent.id != Theme.DEFALT_THEME_ACCENT_ID) {
            return;
        }
        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        if (preferences.getBoolean("themehint", false)) {
            return;
        }
        preferences.edit().putBoolean("themehint", true).commit();
        boolean deleteTheme = (Boolean) args[2];
        undoView.showWithAction(0, UndoView.ACTION_THEME_CHANGED, null, () -> {
            if (themeAccent != null) {
                Theme.ThemeAccent prevAccent = themeInfo.getAccent(false);
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false, null, themeAccent.id);
                if (deleteTheme) {
                    Theme.deleteThemeAccent(themeInfo, prevAccent, true);
                }
            } else {
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false, null, -1);
            }
        });
    } else if (id == NotificationCenter.goingToPreviewTheme) {
        isPauseOnThemePreview = true;
        if (chatLayoutManager != null) {
            scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition();
            RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate);
            if (holder != null) {
                scrollToOffsetOnRecreate = chatListView.getMeasuredHeight() - holder.itemView.getBottom() - chatListView.getPaddingBottom();
            } else {
                scrollToPositionOnRecreate = -1;
            }
        }
    } else if (id == NotificationCenter.channelRightsUpdated) {
        TLRPC.Chat chat = (TLRPC.Chat) args[0];
        if (currentChat != null && chat.id == currentChat.id && chatActivityEnterView != null) {
            currentChat = chat;
            chatActivityEnterView.checkChannelRights();
            checkRaiseSensors();
            updateSecretStatus();
            if (currentChat.gigagroup) {
                updateBottomOverlay();
            }
        }
    } else if (id == NotificationCenter.updateMentionsCount) {
        if (dialog_id == (Long) args[0]) {
            int count = (int) args[1];
            if (newMentionsCount > count) {
                newMentionsCount = count;
                if (newMentionsCount <= 0) {
                    newMentionsCount = 0;
                    hasAllMentionsLocal = true;
                    showMentionDownButton(false, true);
                } else {
                    mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
                }
            }
        }
    } else if (id == NotificationCenter.audioRecordTooShort) {
        int guid = (Integer) args[0];
        if (guid != classGuid) {
            return;
        }
        int time = (Integer) args[2];
        if (time < 100) {
            showVoiceHint(false, (Boolean) args[1]);
        }
    } else if (id == NotificationCenter.videoLoadingStateChanged) {
        if (chatListView != null) {
            String fileName = (String) args[0];
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View child = chatListView.getChildAt(a);
                if (!(child instanceof ChatMessageCell)) {
                    continue;
                }
                ChatMessageCell cell = (ChatMessageCell) child;
                TLRPC.Document document = cell.getStreamingMedia();
                if (document == null) {
                    continue;
                }
                if (FileLoader.getAttachFileName(document).equals(fileName)) {
                    cell.updateButtonState(false, true, false);
                }
            }
        }
    } else if (id == NotificationCenter.scheduledMessagesUpdated) {
        long did = (Long) args[0];
        if (dialog_id == did) {
            scheduledMessagesCount = (Integer) args[1];
            updateScheduledInterface(openAnimationEnded);
        }
    } else if (id == NotificationCenter.diceStickersDidLoad) {
        if (chatListView == null) {
            return;
        }
        int count = chatListView.getChildCount();
        for (int a = 0; a < count; a++) {
            View child = chatListView.getChildAt(a);
            if (!(child instanceof ChatMessageCell)) {
                continue;
            }
            ChatMessageCell cell = (ChatMessageCell) child;
            if (cell.getMessageObject().isDice()) {
                cell.setCurrentDiceValue(true);
            }
        }
    } else if (id == NotificationCenter.dialogDeleted) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            if (parentLayout != null && parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1) == this) {
                finishFragment();
            } else {
                removeSelfFromStack();
            }
        }
    } else if (id == NotificationCenter.needSetDayNightTheme) {
        Theme.ThemeInfo theme = (Theme.ThemeInfo) args[0];
        if (theme != null) {
            if (chatThemeBottomSheet != null) {
                chatThemeBottomSheet.setupLightDarkTheme(theme.isDark());
            } else {
                themeDelegate.setCurrentTheme(themeDelegate.chatTheme, true, theme.isDark());
            }
        }
    } else if (id == NotificationCenter.chatAvailableReactionsUpdated) {
        long chatId = (long) args[0];
        if (chatId == -dialog_id) {
            chatInfo = getMessagesController().getChatFull(chatId);
        }
    } else if (id == NotificationCenter.dialogsUnreadReactionsCounterChanged) {
        long dialogId = (long) args[0];
        if (dialogId == dialog_id) {
            reactionsMentionCount = (int) args[1];
            ArrayList<Integer> messages = null;
            if (args[2] != null) {
                messages = (ArrayList<Integer>) args[2];
            }
            if (messages != null) {
                for (int i = 0; i < messages.size(); i++) {
                    int messageId = messages.get(i);
                    ChatMessageCell cell = findMessageCell(messageId, true);
                    if (cell != null && reactionsMentionCount > 0) {
                        reactionsMentionCount--;
                        getMessagesStorage().markMessageReactionsAsRead(getDialogId(), cell.getMessageObject().getId(), true);
                        AndroidUtilities.runOnUIThread(() -> {
                            playReactionAnimation(messageId);
                        }, 200);
                    }
                }
            }
            if (reactionsMentionCount <= 0) {
                reactionsMentionCount = 0;
                getMessagesController().markReactionsAsRead(dialogId);
            }
            updateReactionsMentionButton(true);
        }
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ViewHelper(org.telegram.ui.Components.ViewHelper) Bundle(android.os.Bundle) BotHelpCell(org.telegram.ui.Cells.BotHelpCell) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) StickersAlert(org.telegram.ui.Components.StickersAlert) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) Property(android.util.Property) HorizontalScrollView(android.widget.HorizontalScrollView) ChatThemeController(org.telegram.messenger.ChatThemeController) MediaStore(android.provider.MediaStore) Map(java.util.Map) Shader(android.graphics.Shader) ContextCompat(androidx.core.content.ContextCompat) NotificationCenter(org.telegram.messenger.NotificationCenter) PinnedLineView(org.telegram.ui.Components.PinnedLineView) CountDownLatch(java.util.concurrent.CountDownLatch) Layout(android.text.Layout) EmojiData(org.telegram.messenger.EmojiData) ForwardingMessagesParams(org.telegram.messenger.ForwardingMessagesParams) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) Paint(android.graphics.Paint) Path(android.graphics.Path) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SystemClock(android.os.SystemClock) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) 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) ChatActivityMemberRequestsDelegate(org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) EditText(android.widget.EditText) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) Animator(android.animation.Animator) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) ChatAttachAlertDocumentLayout(org.telegram.ui.Components.ChatAttachAlertDocumentLayout) DatePickerDialog(android.app.DatePickerDialog) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) StickersAdapter(org.telegram.ui.Adapters.StickersAdapter) RectF(android.graphics.RectF) ReportAlert(org.telegram.ui.Components.ReportAlert) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ShareAlert(org.telegram.ui.Components.ShareAlert) BluredView(org.telegram.ui.Components.BluredView) UserConfig(org.telegram.messenger.UserConfig) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) EmojiThemes(org.telegram.ui.ActionBar.EmojiThemes) InstantCameraView(org.telegram.ui.Components.InstantCameraView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ImportingAlert(org.telegram.ui.Components.ImportingAlert) Spanned(android.text.Spanned) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) SparseIntArray(android.util.SparseIntArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LocaleController(org.telegram.messenger.LocaleController) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) ActionBar(org.telegram.ui.ActionBar.ActionBar) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) TLObject(org.telegram.tgnet.TLObject) Size(org.telegram.ui.Components.Size) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) PollVotesAlert(org.telegram.ui.Components.PollVotesAlert) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) CharacterStyle(android.text.style.CharacterStyle) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) 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) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Matcher(java.util.regex.Matcher) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) Canvas(android.graphics.Canvas) AccessibilityEvent(android.view.accessibility.AccessibilityEvent) Emoji(org.telegram.messenger.Emoji) MessagesSearchAdapter(org.telegram.ui.Adapters.MessagesSearchAdapter) ColorMatrix(android.graphics.ColorMatrix) ForegroundColorSpan(android.text.style.ForegroundColorSpan) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BackButtonMenu(org.telegram.ui.Components.BackButtonMenu) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) ColorMatrixColorFilter(android.graphics.ColorMatrixColorFilter) CounterView(org.telegram.ui.Components.CounterView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) TrendingStickersAlert(org.telegram.ui.Components.TrendingStickersAlert) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) TextPaint(android.text.TextPaint) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) HintView(org.telegram.ui.Components.HintView) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) URLSpanBotCommand(org.telegram.ui.Components.URLSpanBotCommand) ReactionsLayoutInBubble(org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble) ExifInterface(androidx.exifinterface.media.ExifInterface) FileLoader(org.telegram.messenger.FileLoader) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) Space(android.widget.Space) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) BitmapFactory(android.graphics.BitmapFactory) GigagroupConvertAlert(org.telegram.ui.Components.GigagroupConvertAlert) URLSpanMono(org.telegram.ui.Components.URLSpanMono) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) ArrayList(java.util.ArrayList) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) EditTextCaption(org.telegram.ui.Components.EditTextCaption) BuildConfig(org.telegram.messenger.BuildConfig) DialogCell(org.telegram.ui.Cells.DialogCell) SpannableString(android.text.SpannableString) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) ChatUnreadCell(org.telegram.ui.Cells.ChatUnreadCell) ChatLoadingCell(org.telegram.ui.Cells.ChatLoadingCell) ClippingImageView(org.telegram.ui.Components.ClippingImageView) File(java.io.File) ReactionsEffectOverlay(org.telegram.ui.Components.Reactions.ReactionsEffectOverlay) Gravity(android.view.Gravity) PorterDuffXfermode(android.graphics.PorterDuffXfermode) TypedValue(android.util.TypedValue) Configuration(android.content.res.Configuration) StickerCell(org.telegram.ui.Cells.StickerCell) ReactionsContainerLayout(org.telegram.ui.Components.ReactionsContainerLayout) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EmojiView(org.telegram.ui.Components.EmojiView) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ChatScrimPopupContainerLayout(org.telegram.ui.Components.ChatScrimPopupContainerLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Spannable(android.text.Spannable) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ChecksHintView(org.telegram.ui.Components.ChecksHintView) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) Matrix(android.graphics.Matrix) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) BitmapShader(android.graphics.BitmapShader) Utilities(org.telegram.messenger.Utilities) HideViewAfterAnimation(org.telegram.ui.Components.HideViewAfterAnimation) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) SparseArray(android.util.SparseArray) List(java.util.List) TextView(android.widget.TextView) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) SecretChatHelper(org.telegram.messenger.SecretChatHelper) FileProvider(androidx.core.content.FileProvider) Pattern(java.util.regex.Pattern) 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) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ViewOutlineProvider(android.view.ViewOutlineProvider) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) TranslateAlert(org.telegram.ui.Components.TranslateAlert) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClipData(android.content.ClipData) SuppressLint(android.annotation.SuppressLint) 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) FireworksOverlay(org.telegram.ui.Components.FireworksOverlay) LongSparseArray(androidx.collection.LongSparseArray) FileWriter(java.io.FileWriter) FileLog(org.telegram.messenger.FileLog) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement) MessagesController(org.telegram.messenger.MessagesController) NumberTextView(org.telegram.ui.Components.NumberTextView) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) MediaController(org.telegram.messenger.MediaController) HashMap(java.util.HashMap) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) Canvas(android.graphics.Canvas) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) SparseIntArray(android.util.SparseIntArray) LongSparseArray(androidx.collection.LongSparseArray) RecyclerListView(org.telegram.ui.Components.RecyclerListView) Bitmap(android.graphics.Bitmap) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Calendar(java.util.Calendar) HorizontalScrollView(android.widget.HorizontalScrollView) PinnedLineView(org.telegram.ui.Components.PinnedLineView) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) RecyclerView(androidx.recyclerview.widget.RecyclerView) BluredView(org.telegram.ui.Components.BluredView) InstantCameraView(org.telegram.ui.Components.InstantCameraView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) 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) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) UndoView(org.telegram.ui.Components.UndoView) CounterView(org.telegram.ui.Components.CounterView) HintView(org.telegram.ui.Components.HintView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) EmojiView(org.telegram.ui.Components.EmojiView) ChecksHintView(org.telegram.ui.Components.ChecksHintView) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) TextView(android.widget.TextView) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) NumberTextView(org.telegram.ui.Components.NumberTextView) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) SparseArray(android.util.SparseArray) LongSparseArray(androidx.collection.LongSparseArray) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) Theme(org.telegram.ui.ActionBar.Theme) MessageObject(org.telegram.messenger.MessageObject)

Aggregations

Manifest (android.Manifest)3 Animator (android.animation.Animator)3 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)3 AnimatorSet (android.animation.AnimatorSet)3 ObjectAnimator (android.animation.ObjectAnimator)3 ValueAnimator (android.animation.ValueAnimator)3 SuppressLint (android.annotation.SuppressLint)3 TargetApi (android.annotation.TargetApi)3 Activity (android.app.Activity)3 DatePickerDialog (android.app.DatePickerDialog)3 Dialog (android.app.Dialog)3 ClipData (android.content.ClipData)3 Context (android.content.Context)3 DialogInterface (android.content.DialogInterface)3 Intent (android.content.Intent)3 SharedPreferences (android.content.SharedPreferences)3 PackageManager (android.content.pm.PackageManager)3 Configuration (android.content.res.Configuration)3 Bitmap (android.graphics.Bitmap)3 BitmapFactory (android.graphics.BitmapFactory)3