Search in sources :

Example 16 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class DialogCell method buildLayout.

public void buildLayout() {
    int thumbSize;
    if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
        Theme.dialogs_namePaint[1].setTextSize(AndroidUtilities.dp(16));
        Theme.dialogs_nameEncryptedPaint[1].setTextSize(AndroidUtilities.dp(16));
        Theme.dialogs_messagePaint[1].setTextSize(AndroidUtilities.dp(15));
        Theme.dialogs_messagePrintingPaint[1].setTextSize(AndroidUtilities.dp(15));
        Theme.dialogs_messagePaint[1].setColor(Theme.dialogs_messagePaint[1].linkColor = Theme.getColor(Theme.key_chats_message_threeLines, resourcesProvider));
        paintIndex = 1;
        thumbSize = 18;
    } else {
        Theme.dialogs_namePaint[0].setTextSize(AndroidUtilities.dp(17));
        Theme.dialogs_nameEncryptedPaint[0].setTextSize(AndroidUtilities.dp(17));
        Theme.dialogs_messagePaint[0].setTextSize(AndroidUtilities.dp(16));
        Theme.dialogs_messagePrintingPaint[0].setTextSize(AndroidUtilities.dp(16));
        Theme.dialogs_messagePaint[0].setColor(Theme.dialogs_messagePaint[0].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider));
        paintIndex = 0;
        thumbSize = 19;
    }
    currentDialogFolderDialogsCount = 0;
    String nameString = "";
    String timeString = "";
    String countString = null;
    String mentionString = null;
    CharSequence messageString = "";
    CharSequence messageNameString = null;
    CharSequence printingString = null;
    if (isDialogCell) {
        printingString = MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, 0, true);
    }
    TextPaint currentMessagePaint = Theme.dialogs_messagePaint[paintIndex];
    boolean checkMessage = true;
    drawNameGroup = false;
    drawNameBroadcast = false;
    drawNameLock = false;
    drawNameBot = false;
    drawVerified = false;
    drawScam = 0;
    drawPinBackground = false;
    hasMessageThumb = false;
    int offsetName = 0;
    boolean showChecks = !UserObject.isUserSelf(user) && !useMeForMyMessages;
    boolean drawTime = true;
    printingStringType = -1;
    int printigStingReplaceIndex = -1;
    String messageFormat;
    boolean hasNameInMessage;
    if (Build.VERSION.SDK_INT >= 18) {
        if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) {
            messageFormat = "%2$s: \u2068%1$s\u2069";
            hasNameInMessage = true;
        } else {
            messageFormat = "\u2068%s\u2069";
            hasNameInMessage = false;
        }
    } else {
        if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) {
            messageFormat = "%2$s: %1$s";
            hasNameInMessage = true;
        } else {
            messageFormat = "%1$s";
            hasNameInMessage = false;
        }
    }
    CharSequence msgText = message != null ? message.messageText : null;
    if (msgText instanceof Spannable) {
        Spannable sp = new SpannableStringBuilder(msgText);
        for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderlineBold.class)) sp.removeSpan(span);
        for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderline.class)) sp.removeSpan(span);
        msgText = sp;
    }
    lastMessageString = msgText;
    if (customDialog != null) {
        if (customDialog.type == 2) {
            drawNameLock = true;
            if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                nameLockTop = AndroidUtilities.dp(12.5f);
                if (!LocaleController.isRTL) {
                    nameLockLeft = AndroidUtilities.dp(72 + 6);
                    nameLeft = AndroidUtilities.dp(72 + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
                } else {
                    nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
                    nameLeft = AndroidUtilities.dp(22);
                }
            } else {
                nameLockTop = AndroidUtilities.dp(16.5f);
                if (!LocaleController.isRTL) {
                    nameLockLeft = AndroidUtilities.dp(72 + 4);
                    nameLeft = AndroidUtilities.dp(72 + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
                } else {
                    nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
                    nameLeft = AndroidUtilities.dp(18);
                }
            }
        } else {
            drawVerified = customDialog.verified;
            if (SharedConfig.drawDialogIcons && customDialog.type == 1) {
                drawNameGroup = true;
                if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                    nameLockTop = AndroidUtilities.dp(13.5f);
                    if (!LocaleController.isRTL) {
                        nameLockLeft = AndroidUtilities.dp(72 + 6);
                        nameLeft = AndroidUtilities.dp(72 + 10) + (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 6) - (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                        nameLeft = AndroidUtilities.dp(22);
                    }
                } else {
                    if (!LocaleController.isRTL) {
                        nameLockTop = AndroidUtilities.dp(17.5f);
                        nameLockLeft = AndroidUtilities.dp(72 + 4);
                        nameLeft = AndroidUtilities.dp(72 + 8) + (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 4) - (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                        nameLeft = AndroidUtilities.dp(18);
                    }
                }
            } else {
                if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                    if (!LocaleController.isRTL) {
                        nameLeft = AndroidUtilities.dp(72 + 6);
                    } else {
                        nameLeft = AndroidUtilities.dp(22);
                    }
                } else {
                    if (!LocaleController.isRTL) {
                        nameLeft = AndroidUtilities.dp(72 + 4);
                    } else {
                        nameLeft = AndroidUtilities.dp(18);
                    }
                }
            }
        }
        if (customDialog.type == 1) {
            messageNameString = LocaleController.getString("FromYou", R.string.FromYou);
            checkMessage = false;
            SpannableStringBuilder stringBuilder;
            if (customDialog.isMedia) {
                currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, message.messageText));
                stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                String mess = customDialog.message;
                if (mess.length() > 150) {
                    mess = mess.substring(0, 150);
                }
                if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                    stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, mess, messageNameString));
                } else {
                    stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, mess.replace('\n', ' '), messageNameString));
                }
            }
            messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(20), false);
        } else {
            messageString = customDialog.message;
            if (customDialog.isMedia) {
                currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
            }
        }
        timeString = LocaleController.stringForMessageListDate(customDialog.date);
        if (customDialog.unread_count != 0) {
            drawCount = true;
            countString = String.format("%d", customDialog.unread_count);
        } else {
            drawCount = false;
        }
        if (customDialog.sent) {
            drawCheck1 = true;
            drawCheck2 = true;
        } else {
            drawCheck1 = false;
            drawCheck2 = false;
        }
        drawClock = false;
        drawError = false;
        nameString = customDialog.name;
    } else {
        if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
            if (!LocaleController.isRTL) {
                nameLeft = AndroidUtilities.dp(72 + 6);
            } else {
                nameLeft = AndroidUtilities.dp(22);
            }
        } else {
            if (!LocaleController.isRTL) {
                nameLeft = AndroidUtilities.dp(72 + 4);
            } else {
                nameLeft = AndroidUtilities.dp(18);
            }
        }
        if (encryptedChat != null) {
            if (currentDialogFolderId == 0) {
                drawNameLock = true;
                if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                    nameLockTop = AndroidUtilities.dp(12.5f);
                    if (!LocaleController.isRTL) {
                        nameLockLeft = AndroidUtilities.dp(72 + 6);
                        nameLeft = AndroidUtilities.dp(72 + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
                        nameLeft = AndroidUtilities.dp(22);
                    }
                } else {
                    nameLockTop = AndroidUtilities.dp(16.5f);
                    if (!LocaleController.isRTL) {
                        nameLockLeft = AndroidUtilities.dp(72 + 4);
                        nameLeft = AndroidUtilities.dp(72 + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
                        nameLeft = AndroidUtilities.dp(18);
                    }
                }
            }
        } else {
            if (currentDialogFolderId == 0) {
                if (chat != null) {
                    if (chat.scam) {
                        drawScam = 1;
                        Theme.dialogs_scamDrawable.checkText();
                    } else if (chat.fake) {
                        drawScam = 2;
                        Theme.dialogs_fakeDrawable.checkText();
                    } else {
                        drawVerified = chat.verified;
                    }
                    if (SharedConfig.drawDialogIcons) {
                        if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                            if (chat.id < 0 || ChatObject.isChannel(chat) && !chat.megagroup) {
                                drawNameBroadcast = true;
                                nameLockTop = AndroidUtilities.dp(12.5f);
                            } else {
                                drawNameGroup = true;
                                nameLockTop = AndroidUtilities.dp(13.5f);
                            }
                            if (!LocaleController.isRTL) {
                                nameLockLeft = AndroidUtilities.dp(72 + 6);
                                nameLeft = AndroidUtilities.dp(72 + 10) + (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                            } else {
                                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 6) - (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                                nameLeft = AndroidUtilities.dp(22);
                            }
                        } else {
                            if (chat.id < 0 || ChatObject.isChannel(chat) && !chat.megagroup) {
                                drawNameBroadcast = true;
                                nameLockTop = AndroidUtilities.dp(16.5f);
                            } else {
                                drawNameGroup = true;
                                nameLockTop = AndroidUtilities.dp(17.5f);
                            }
                            if (!LocaleController.isRTL) {
                                nameLockLeft = AndroidUtilities.dp(72 + 4);
                                nameLeft = AndroidUtilities.dp(72 + 8) + (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                            } else {
                                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 4) - (drawNameGroup ? Theme.dialogs_groupDrawable.getIntrinsicWidth() : Theme.dialogs_broadcastDrawable.getIntrinsicWidth());
                                nameLeft = AndroidUtilities.dp(18);
                            }
                        }
                    }
                } else if (user != null) {
                    if (user.scam) {
                        drawScam = 1;
                        Theme.dialogs_scamDrawable.checkText();
                    } else if (user.fake) {
                        drawScam = 2;
                        Theme.dialogs_fakeDrawable.checkText();
                    } else {
                        drawVerified = user.verified;
                    }
                    if (SharedConfig.drawDialogIcons && user.bot) {
                        drawNameBot = true;
                        if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                            nameLockTop = AndroidUtilities.dp(12.5f);
                            if (!LocaleController.isRTL) {
                                nameLockLeft = AndroidUtilities.dp(72 + 6);
                                nameLeft = AndroidUtilities.dp(72 + 10) + Theme.dialogs_botDrawable.getIntrinsicWidth();
                            } else {
                                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 6) - Theme.dialogs_botDrawable.getIntrinsicWidth();
                                nameLeft = AndroidUtilities.dp(22);
                            }
                        } else {
                            nameLockTop = AndroidUtilities.dp(16.5f);
                            if (!LocaleController.isRTL) {
                                nameLockLeft = AndroidUtilities.dp(72 + 4);
                                nameLeft = AndroidUtilities.dp(72 + 8) + Theme.dialogs_botDrawable.getIntrinsicWidth();
                            } else {
                                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(72 + 4) - Theme.dialogs_botDrawable.getIntrinsicWidth();
                                nameLeft = AndroidUtilities.dp(18);
                            }
                        }
                    }
                }
            }
        }
        int lastDate = lastMessageDate;
        if (lastMessageDate == 0 && message != null) {
            lastDate = message.messageOwner.date;
        }
        if (isDialogCell) {
            draftMessage = MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, 0);
            if (draftMessage != null && (TextUtils.isEmpty(draftMessage.message) && draftMessage.reply_to_msg_id == 0 || lastDate > draftMessage.date && unreadCount != 0) || ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) || chat != null && (chat.left || chat.kicked)) {
                draftMessage = null;
            }
        } else {
            draftMessage = null;
        }
        if (printingString != null) {
            lastPrintString = printingString;
            printingStringType = MessagesController.getInstance(currentAccount).getPrintingStringType(currentDialogId, 0);
            StatusDrawable statusDrawable = Theme.getChatStatusDrawable(printingStringType);
            int startPadding = 0;
            if (statusDrawable != null) {
                startPadding = statusDrawable.getIntrinsicWidth() + AndroidUtilities.dp(3);
            }
            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
            printingString = TextUtils.replace(printingString, new String[] { "..." }, new String[] { "" });
            if (printingStringType == 5) {
                printigStingReplaceIndex = printingString.toString().indexOf("**oo**");
            }
            if (printigStingReplaceIndex >= 0) {
                spannableStringBuilder.append(printingString).setSpan(new FixedWidthSpan(Theme.getChatStatusDrawable(printingStringType).getIntrinsicWidth()), printigStingReplaceIndex, printigStingReplaceIndex + 6, 0);
            } else {
                spannableStringBuilder.append(" ").append(printingString).setSpan(new FixedWidthSpan(startPadding), 0, 1, 0);
            }
            messageString = spannableStringBuilder;
            currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
            checkMessage = false;
        } else {
            lastPrintString = null;
            if (draftMessage != null) {
                checkMessage = false;
                messageNameString = LocaleController.getString("Draft", R.string.Draft);
                if (TextUtils.isEmpty(draftMessage.message)) {
                    if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                        messageString = "";
                    } else {
                        SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(messageNameString);
                        stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        messageString = stringBuilder;
                    }
                } else {
                    String mess = draftMessage.message;
                    if (mess.length() > 150) {
                        mess = mess.substring(0, 150);
                    }
                    Spannable messSpan = new SpannableStringBuilder(mess);
                    MediaDataController.addTextStyleRuns(draftMessage, messSpan, TextStyleSpan.FLAG_STYLE_SPOILER);
                    SpannableStringBuilder stringBuilder = AndroidUtilities.formatSpannable(messageFormat, AndroidUtilities.replaceNewLines(messSpan), messageNameString);
                    if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout) {
                        stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(20), false);
                }
            } else {
                if (clearingDialog) {
                    currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                    messageString = LocaleController.getString("HistoryCleared", R.string.HistoryCleared);
                } else if (message == null) {
                    if (encryptedChat != null) {
                        currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                        if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
                            messageString = LocaleController.getString("EncryptionProcessing", R.string.EncryptionProcessing);
                        } else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
                            messageString = LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, UserObject.getFirstName(user));
                        } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
                            messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected);
                        } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
                            if (encryptedChat.admin_id == UserConfig.getInstance(currentAccount).getClientUserId()) {
                                messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, UserObject.getFirstName(user));
                            } else {
                                messageString = LocaleController.getString("EncryptedChatStartedIncoming", R.string.EncryptedChatStartedIncoming);
                            }
                        }
                    } else {
                        if (dialogsType == 3 && UserObject.isUserSelf(user)) {
                            messageString = LocaleController.getString("SavedMessagesInfo", R.string.SavedMessagesInfo);
                            showChecks = false;
                            drawTime = false;
                        } else {
                            messageString = "";
                        }
                    }
                } else {
                    String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason);
                    TLRPC.User fromUser = null;
                    TLRPC.Chat fromChat = null;
                    long fromId = message.getFromChatId();
                    if (DialogObject.isUserDialog(fromId)) {
                        fromUser = MessagesController.getInstance(currentAccount).getUser(fromId);
                    } else {
                        fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId);
                    }
                    if (dialogsType == 3 && UserObject.isUserSelf(user)) {
                        messageString = LocaleController.getString("SavedMessagesInfo", R.string.SavedMessagesInfo);
                        showChecks = false;
                        drawTime = false;
                    } else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout && currentDialogFolderId != 0) {
                        checkMessage = false;
                        messageString = formatArchivedDialogNames();
                    } else if (message.messageOwner instanceof TLRPC.TL_messageService) {
                        if (ChatObject.isChannelAndNotMegaGroup(chat) && (message.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear || message.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom)) {
                            messageString = "";
                            showChecks = false;
                        } else {
                            messageString = msgText;
                        }
                        currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                    } else {
                        boolean needEmoji = true;
                        if (TextUtils.isEmpty(restrictionReason) && currentDialogFolderId == 0 && encryptedChat == null && !message.needDrawBluredPreview() && (message.isPhoto() || message.isNewGif() || message.isVideo())) {
                            String type = message.isWebpage() ? message.messageOwner.media.webpage.type : null;
                            if (!("app".equals(type) || "profile".equals(type) || "article".equals(type) || type != null && type.startsWith("telegram_"))) {
                                TLRPC.PhotoSize smallThumb = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, 40);
                                TLRPC.PhotoSize bigThumb = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, AndroidUtilities.getPhotoSize());
                                if (smallThumb == bigThumb) {
                                    bigThumb = null;
                                }
                                if (smallThumb != null) {
                                    hasMessageThumb = true;
                                    drawPlay = message.isVideo();
                                    String fileName = FileLoader.getAttachFileName(bigThumb);
                                    if (message.mediaExists || DownloadController.getInstance(currentAccount).canDownloadMedia(message) || FileLoader.getInstance(currentAccount).isLoadingFile(fileName)) {
                                        int size;
                                        if (message.type == MessageObject.TYPE_PHOTO) {
                                            size = bigThumb != null ? bigThumb.size : 0;
                                        } else {
                                            size = 0;
                                        }
                                        thumbImage.setImage(ImageLocation.getForObject(bigThumb, message.photoThumbsObject), "20_20", ImageLocation.getForObject(smallThumb, message.photoThumbsObject), "20_20", size, null, message, 0);
                                    } else {
                                        thumbImage.setImage(null, null, ImageLocation.getForObject(smallThumb, message.photoThumbsObject), "20_20", (Drawable) null, message, 0);
                                    }
                                    needEmoji = false;
                                }
                            }
                        }
                        if (chat != null && chat.id > 0 && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat))) {
                            if (message.isOutOwner()) {
                                messageNameString = LocaleController.getString("FromYou", R.string.FromYou);
                            } else if (message != null && message.messageOwner.fwd_from != null && message.messageOwner.fwd_from.from_name != null) {
                                messageNameString = message.messageOwner.fwd_from.from_name;
                            } else if (fromUser != null) {
                                if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
                                    if (UserObject.isDeleted(fromUser)) {
                                        messageNameString = LocaleController.getString("HiddenName", R.string.HiddenName);
                                    } else {
                                        messageNameString = ContactsController.formatName(fromUser.first_name, fromUser.last_name).replace("\n", "");
                                    }
                                } else {
                                    messageNameString = UserObject.getFirstName(fromUser).replace("\n", "");
                                }
                            } else {
                                messageNameString = "DELETED";
                            }
                            checkMessage = false;
                            SpannableStringBuilder stringBuilder;
                            if (!TextUtils.isEmpty(restrictionReason)) {
                                stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, restrictionReason, messageNameString));
                            } else if (message.caption != null) {
                                CharSequence mess = message.caption.toString();
                                if (mess.length() > 150) {
                                    mess = mess.subSequence(0, 150);
                                }
                                String emoji;
                                if (!needEmoji) {
                                    emoji = "";
                                } else if (message.isVideo()) {
                                    emoji = "\uD83D\uDCF9 ";
                                } else if (message.isVoice()) {
                                    emoji = "\uD83C\uDFA4 ";
                                } else if (message.isMusic()) {
                                    emoji = "\uD83C\uDFA7 ";
                                } else if (message.isPhoto()) {
                                    emoji = "\uD83D\uDDBC ";
                                } else {
                                    emoji = "\uD83D\uDCCE ";
                                }
                                SpannableStringBuilder msgBuilder = new SpannableStringBuilder(mess);
                                MediaDataController.addTextStyleRuns(message.messageOwner.entities, message.caption, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER);
                                stringBuilder = AndroidUtilities.formatSpannable(messageFormat, new SpannableStringBuilder(emoji).append(AndroidUtilities.replaceNewLines(msgBuilder)), messageNameString);
                            } else if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                                currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                                String innerMessage;
                                if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
                                    TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
                                    if (Build.VERSION.SDK_INT >= 18) {
                                        innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question);
                                    } else {
                                        innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question);
                                    }
                                } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                    if (Build.VERSION.SDK_INT >= 18) {
                                        innerMessage = String.format("\uD83C\uDFAE \u2068%s\u2069", message.messageOwner.media.game.title);
                                    } else {
                                        innerMessage = String.format("\uD83C\uDFAE %s", message.messageOwner.media.game.title);
                                    }
                                } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) {
                                    innerMessage = message.messageOwner.media.title;
                                } else if (message.type == 14) {
                                    if (Build.VERSION.SDK_INT >= 18) {
                                        innerMessage = String.format("\uD83C\uDFA7 \u2068%s - %s\u2069", message.getMusicAuthor(), message.getMusicTitle());
                                    } else {
                                        innerMessage = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle());
                                    }
                                } else {
                                    innerMessage = msgText.toString();
                                }
                                innerMessage = innerMessage.replace('\n', ' ');
                                stringBuilder = AndroidUtilities.formatSpannable(messageFormat, innerMessage, messageNameString);
                                try {
                                    stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), hasNameInMessage ? messageNameString.length() + 2 : 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                } catch (Exception e) {
                                    FileLog.e(e);
                                }
                            } else if (message.messageOwner.message != null) {
                                CharSequence mess = message.messageOwner.message;
                                if (message.hasHighlightedWords()) {
                                    if (message.messageTrimmedToHighlight != null) {
                                        mess = message.messageTrimmedToHighlight;
                                    }
                                    int w = getMeasuredWidth() - AndroidUtilities.dp(72 + 23 + 10);
                                    if (hasNameInMessage) {
                                        if (!TextUtils.isEmpty(messageNameString)) {
                                            w -= currentMessagePaint.measureText(messageNameString.toString());
                                        }
                                        w -= currentMessagePaint.measureText(": ");
                                    }
                                    if (w > 0) {
                                        mess = AndroidUtilities.ellipsizeCenterEnd(mess, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
                                    }
                                } else {
                                    if (mess.length() > 150) {
                                        mess = mess.subSequence(0, 150);
                                    }
                                    mess = AndroidUtilities.replaceNewLines(mess);
                                }
                                mess = new SpannableStringBuilder(mess);
                                MediaDataController.addTextStyleRuns(message, (Spannable) mess, TextStyleSpan.FLAG_STYLE_SPOILER);
                                stringBuilder = AndroidUtilities.formatSpannable(messageFormat, mess, messageNameString);
                            } else {
                                stringBuilder = SpannableStringBuilder.valueOf("");
                            }
                            int thumbInsertIndex = 0;
                            if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0 && stringBuilder.length() > 0) {
                                try {
                                    stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage, resourcesProvider), 0, thumbInsertIndex = messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    offsetName = thumbInsertIndex;
                                } catch (Exception e) {
                                    FileLog.e(e);
                                }
                            }
                            messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(20), false);
                            if (message.hasHighlightedWords()) {
                                CharSequence messageH = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
                                if (messageH != null) {
                                    messageString = messageH;
                                }
                            }
                            if (hasMessageThumb) {
                                if (!(messageString instanceof SpannableStringBuilder)) {
                                    messageString = new SpannableStringBuilder(messageString);
                                }
                                checkMessage = false;
                                SpannableStringBuilder builder = (SpannableStringBuilder) messageString;
                                builder.insert(thumbInsertIndex, " ");
                                builder.setSpan(new FixedWidthSpan(AndroidUtilities.dp(thumbSize + 6)), thumbInsertIndex, thumbInsertIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        } else {
                            if (!TextUtils.isEmpty(restrictionReason)) {
                                messageString = restrictionReason;
                            } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty && message.messageOwner.media.ttl_seconds != 0) {
                                messageString = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired);
                            } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && message.messageOwner.media.document instanceof TLRPC.TL_documentEmpty && message.messageOwner.media.ttl_seconds != 0) {
                                messageString = LocaleController.getString("AttachVideoExpired", R.string.AttachVideoExpired);
                            } else if (message.caption != null) {
                                String emoji;
                                if (!needEmoji) {
                                    emoji = "";
                                } else if (message.isVideo()) {
                                    emoji = "\uD83D\uDCF9 ";
                                } else if (message.isVoice()) {
                                    emoji = "\uD83C\uDFA4 ";
                                } else if (message.isMusic()) {
                                    emoji = "\uD83C\uDFA7 ";
                                } else if (message.isPhoto()) {
                                    emoji = "\uD83D\uDDBC ";
                                } else {
                                    emoji = "\uD83D\uDCCE ";
                                }
                                if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
                                    String str = message.messageTrimmedToHighlight;
                                    if (message.messageTrimmedToHighlight != null) {
                                        str = message.messageTrimmedToHighlight;
                                    }
                                    int w = getMeasuredWidth() - AndroidUtilities.dp(72 + 23 + 24);
                                    if (hasNameInMessage) {
                                        if (!TextUtils.isEmpty(messageNameString)) {
                                            w -= currentMessagePaint.measureText(messageNameString.toString());
                                        }
                                        w -= currentMessagePaint.measureText(": ");
                                    }
                                    if (w > 0) {
                                        str = AndroidUtilities.ellipsizeCenterEnd(str, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
                                    }
                                    messageString = emoji + str;
                                } else {
                                    SpannableStringBuilder msgBuilder = new SpannableStringBuilder(message.caption);
                                    MediaDataController.addTextStyleRuns(message.messageOwner.entities, message.caption, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER);
                                    messageString = new SpannableStringBuilder(emoji).append(msgBuilder);
                                }
                            } else {
                                if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
                                    TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
                                    messageString = "\uD83D\uDCCA " + mediaPoll.poll.question;
                                } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                    messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
                                } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) {
                                    messageString = message.messageOwner.media.title;
                                } else if (message.type == 14) {
                                    messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle());
                                } else {
                                    if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
                                        messageString = message.messageTrimmedToHighlight;
                                        if (message.messageTrimmedToHighlight != null) {
                                            messageString = message.messageTrimmedToHighlight;
                                        }
                                        int w = getMeasuredWidth() - AndroidUtilities.dp(72 + 23);
                                        messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
                                    } else {
                                        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(msgText);
                                        MediaDataController.addTextStyleRuns(message, stringBuilder, TextStyleSpan.FLAG_STYLE_SPOILER);
                                        messageString = stringBuilder;
                                    }
                                    AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
                                }
                                if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                                    currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
                                }
                            }
                            if (hasMessageThumb) {
                                if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
                                    messageString = message.messageTrimmedToHighlight;
                                    if (message.messageTrimmedToHighlight != null) {
                                        messageString = message.messageTrimmedToHighlight;
                                    }
                                    int w = getMeasuredWidth() - AndroidUtilities.dp(72 + 23 + thumbSize + 6);
                                    messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
                                } else {
                                    if (messageString.length() > 150) {
                                        messageString = messageString.subSequence(0, 150);
                                    }
                                    messageString = AndroidUtilities.replaceNewLines(messageString);
                                }
                                if (!(messageString instanceof SpannableStringBuilder)) {
                                    messageString = new SpannableStringBuilder(messageString);
                                }
                                checkMessage = false;
                                SpannableStringBuilder builder = (SpannableStringBuilder) messageString;
                                builder.insert(0, " ");
                                builder.setSpan(new FixedWidthSpan(AndroidUtilities.dp(thumbSize + 6)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(17), false);
                                if (message.hasHighlightedWords()) {
                                    CharSequence s = AndroidUtilities.highlightText(builder, message.highlightedWords, resourcesProvider);
                                    if (s != null) {
                                        messageString = s;
                                    }
                                }
                            }
                        }
                    }
                    if (currentDialogFolderId != 0) {
                        messageNameString = formatArchivedDialogNames();
                    }
                }
            }
        }
        if (draftMessage != null) {
            timeString = LocaleController.stringForMessageListDate(draftMessage.date);
        } else if (lastMessageDate != 0) {
            timeString = LocaleController.stringForMessageListDate(lastMessageDate);
        } else if (message != null) {
            timeString = LocaleController.stringForMessageListDate(message.messageOwner.date);
        }
        if (message == null) {
            drawCheck1 = false;
            drawCheck2 = false;
            drawClock = false;
            drawCount = false;
            drawMention = false;
            drawReactionMention = false;
            drawError = false;
        } else {
            if (currentDialogFolderId != 0) {
                if (unreadCount + mentionCount > 0) {
                    if (unreadCount > mentionCount) {
                        drawCount = true;
                        drawMention = false;
                        countString = String.format("%d", unreadCount + mentionCount);
                    } else {
                        drawCount = false;
                        drawMention = true;
                        mentionString = String.format("%d", unreadCount + mentionCount);
                    }
                } else {
                    drawCount = false;
                    drawMention = false;
                }
                drawReactionMention = false;
            } else {
                if (clearingDialog) {
                    drawCount = false;
                    showChecks = false;
                } else if (unreadCount != 0 && (unreadCount != 1 || unreadCount != mentionCount || message == null || !message.messageOwner.mentioned)) {
                    drawCount = true;
                    countString = String.format("%d", unreadCount);
                } else if (markUnread) {
                    drawCount = true;
                    countString = "";
                } else {
                    drawCount = false;
                }
                if (mentionCount != 0) {
                    drawMention = true;
                    mentionString = "@";
                } else {
                    drawMention = false;
                }
                if (reactionMentionCount != 0) {
                    drawReactionMention = true;
                } else {
                    drawReactionMention = false;
                }
            }
            if (message.isOut() && draftMessage == null && showChecks && !(message.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear)) {
                if (message.isSending()) {
                    drawCheck1 = false;
                    drawCheck2 = false;
                    drawClock = true;
                    drawError = false;
                } else if (message.isSendError()) {
                    drawCheck1 = false;
                    drawCheck2 = false;
                    drawClock = false;
                    drawError = true;
                    drawCount = false;
                    drawMention = false;
                } else if (message.isSent()) {
                    drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup;
                    drawCheck2 = true;
                    drawClock = false;
                    drawError = false;
                }
            } else {
                drawCheck1 = false;
                drawCheck2 = false;
                drawClock = false;
                drawError = false;
            }
        }
        promoDialog = false;
        MessagesController messagesController = MessagesController.getInstance(currentAccount);
        if (dialogsType == 0 && messagesController.isPromoDialog(currentDialogId, true)) {
            drawPinBackground = true;
            promoDialog = true;
            if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PROXY) {
                timeString = LocaleController.getString("UseProxySponsor", R.string.UseProxySponsor);
            } else if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PSA) {
                timeString = LocaleController.getString("PsaType_" + messagesController.promoPsaType);
                if (TextUtils.isEmpty(timeString)) {
                    timeString = LocaleController.getString("PsaTypeDefault", R.string.PsaTypeDefault);
                }
                if (!TextUtils.isEmpty(messagesController.promoPsaMessage)) {
                    messageString = messagesController.promoPsaMessage;
                    hasMessageThumb = false;
                }
            }
        }
        if (currentDialogFolderId != 0) {
            nameString = LocaleController.getString("ArchivedChats", R.string.ArchivedChats);
        } else {
            if (chat != null) {
                nameString = chat.title;
            } else if (user != null) {
                if (UserObject.isReplyUser(user)) {
                    nameString = LocaleController.getString("RepliesTitle", R.string.RepliesTitle);
                } else if (UserObject.isUserSelf(user)) {
                    if (useMeForMyMessages) {
                        nameString = LocaleController.getString("FromYou", R.string.FromYou);
                    } else {
                        if (dialogsType == 3) {
                            drawPinBackground = true;
                        }
                        nameString = LocaleController.getString("SavedMessages", R.string.SavedMessages);
                    }
                } else {
                    nameString = UserObject.getUserName(user);
                }
            }
            if (nameString.length() == 0) {
                nameString = LocaleController.getString("HiddenName", R.string.HiddenName);
            }
        }
    }
    int timeWidth;
    if (drawTime) {
        timeWidth = (int) Math.ceil(Theme.dialogs_timePaint.measureText(timeString));
        timeLayout = new StaticLayout(timeString, Theme.dialogs_timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        if (!LocaleController.isRTL) {
            timeLeft = getMeasuredWidth() - AndroidUtilities.dp(15) - timeWidth;
        } else {
            timeLeft = AndroidUtilities.dp(15);
        }
    } else {
        timeWidth = 0;
        timeLayout = null;
        timeLeft = 0;
    }
    int nameWidth;
    if (!LocaleController.isRTL) {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(14) - timeWidth;
    } else {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(77) - timeWidth;
        nameLeft += timeWidth;
    }
    if (drawNameLock) {
        nameWidth -= AndroidUtilities.dp(4) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
    } else if (drawNameGroup) {
        nameWidth -= AndroidUtilities.dp(4) + Theme.dialogs_groupDrawable.getIntrinsicWidth();
    } else if (drawNameBroadcast) {
        nameWidth -= AndroidUtilities.dp(4) + Theme.dialogs_broadcastDrawable.getIntrinsicWidth();
    } else if (drawNameBot) {
        nameWidth -= AndroidUtilities.dp(4) + Theme.dialogs_botDrawable.getIntrinsicWidth();
    }
    if (drawClock) {
        int w = Theme.dialogs_clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (!LocaleController.isRTL) {
            clockDrawLeft = timeLeft - w;
        } else {
            clockDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
            nameLeft += w;
        }
    } else if (drawCheck2) {
        int w = Theme.dialogs_checkDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (drawCheck1) {
            nameWidth -= Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            if (!LocaleController.isRTL) {
                halfCheckDrawLeft = timeLeft - w;
                checkDrawLeft = halfCheckDrawLeft - AndroidUtilities.dp(5.5f);
            } else {
                checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
                halfCheckDrawLeft = checkDrawLeft + AndroidUtilities.dp(5.5f);
                nameLeft += w + Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            }
        } else {
            if (!LocaleController.isRTL) {
                checkDrawLeft1 = timeLeft - w;
            } else {
                checkDrawLeft1 = timeLeft + timeWidth + AndroidUtilities.dp(5);
                nameLeft += w;
            }
        }
    }
    if (dialogMuted && !drawVerified && drawScam == 0) {
        int w = AndroidUtilities.dp(6) + Theme.dialogs_muteDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    } else if (drawVerified) {
        int w = AndroidUtilities.dp(6) + Theme.dialogs_verifiedDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    } else if (drawScam != 0) {
        int w = AndroidUtilities.dp(6) + (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    }
    nameWidth = Math.max(AndroidUtilities.dp(12), nameWidth);
    try {
        CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace('\n', ' '), Theme.dialogs_namePaint[paintIndex], nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
        if (message != null && message.hasHighlightedWords()) {
            CharSequence s = AndroidUtilities.highlightText(nameStringFinal, message.highlightedWords, resourcesProvider);
            if (s != null) {
                nameStringFinal = s;
            }
        }
        nameLayout = new StaticLayout(nameStringFinal, Theme.dialogs_namePaint[paintIndex], nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    } catch (Exception e) {
        FileLog.e(e);
    }
    int messageWidth;
    int avatarLeft;
    int avatarTop;
    int thumbLeft;
    if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
        avatarTop = AndroidUtilities.dp(11);
        messageNameTop = AndroidUtilities.dp(32);
        timeTop = AndroidUtilities.dp(13);
        errorTop = AndroidUtilities.dp(43);
        pinTop = AndroidUtilities.dp(43);
        countTop = AndroidUtilities.dp(43);
        checkDrawTop = AndroidUtilities.dp(13);
        messageWidth = getMeasuredWidth() - AndroidUtilities.dp(72 + 21);
        if (LocaleController.isRTL) {
            messageLeft = messageNameLeft = AndroidUtilities.dp(16);
            avatarLeft = getMeasuredWidth() - AndroidUtilities.dp(66);
            thumbLeft = avatarLeft - AndroidUtilities.dp(13 + 18);
        } else {
            messageLeft = messageNameLeft = AndroidUtilities.dp(72 + 6);
            avatarLeft = AndroidUtilities.dp(10);
            thumbLeft = avatarLeft + AndroidUtilities.dp(56 + 13);
        }
        avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        thumbImage.setImageCoords(thumbLeft, avatarTop + AndroidUtilities.dp(31), AndroidUtilities.dp(18), AndroidUtilities.dp(18));
    } else {
        avatarTop = AndroidUtilities.dp(9);
        messageNameTop = AndroidUtilities.dp(31);
        timeTop = AndroidUtilities.dp(16);
        errorTop = AndroidUtilities.dp(39);
        pinTop = AndroidUtilities.dp(39);
        countTop = AndroidUtilities.dp(39);
        checkDrawTop = AndroidUtilities.dp(17);
        messageWidth = getMeasuredWidth() - AndroidUtilities.dp(72 + 23);
        if (LocaleController.isRTL) {
            messageLeft = messageNameLeft = AndroidUtilities.dp(22);
            avatarLeft = getMeasuredWidth() - AndroidUtilities.dp(64);
            thumbLeft = avatarLeft - AndroidUtilities.dp(11 + thumbSize);
        } else {
            messageLeft = messageNameLeft = AndroidUtilities.dp(72 + 4);
            avatarLeft = AndroidUtilities.dp(10);
            thumbLeft = avatarLeft + AndroidUtilities.dp(56 + 11);
        }
        avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(54), AndroidUtilities.dp(54));
        thumbImage.setImageCoords(thumbLeft, avatarTop + AndroidUtilities.dp(30), AndroidUtilities.dp(thumbSize), AndroidUtilities.dp(thumbSize));
    }
    if (drawPin) {
        if (!LocaleController.isRTL) {
            pinLeft = getMeasuredWidth() - Theme.dialogs_pinnedDrawable.getIntrinsicWidth() - AndroidUtilities.dp(14);
        } else {
            pinLeft = AndroidUtilities.dp(14);
        }
    }
    if (drawError) {
        int w = AndroidUtilities.dp(23 + 8);
        messageWidth -= w;
        if (!LocaleController.isRTL) {
            errorLeft = getMeasuredWidth() - AndroidUtilities.dp(23 + 11);
        } else {
            errorLeft = AndroidUtilities.dp(11);
            messageLeft += w;
            messageNameLeft += w;
        }
    } else if (countString != null || mentionString != null || drawReactionMention) {
        if (countString != null) {
            countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(countString)));
            countLayout = new StaticLayout(countString, Theme.dialogs_countTextPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
            int w = countWidth + AndroidUtilities.dp(18);
            messageWidth -= w;
            if (!LocaleController.isRTL) {
                countLeft = getMeasuredWidth() - countWidth - AndroidUtilities.dp(20);
            } else {
                countLeft = AndroidUtilities.dp(20);
                messageLeft += w;
                messageNameLeft += w;
            }
            drawCount = true;
        } else {
            countWidth = 0;
        }
        if (mentionString != null) {
            if (currentDialogFolderId != 0) {
                mentionWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(mentionString)));
                mentionLayout = new StaticLayout(mentionString, Theme.dialogs_countTextPaint, mentionWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
            } else {
                mentionWidth = AndroidUtilities.dp(12);
            }
            int w = mentionWidth + AndroidUtilities.dp(18);
            messageWidth -= w;
            if (!LocaleController.isRTL) {
                mentionLeft = getMeasuredWidth() - mentionWidth - AndroidUtilities.dp(20) - (countWidth != 0 ? countWidth + AndroidUtilities.dp(18) : 0);
            } else {
                mentionLeft = AndroidUtilities.dp(20) + (countWidth != 0 ? countWidth + AndroidUtilities.dp(18) : 0);
                messageLeft += w;
                messageNameLeft += w;
            }
            drawMention = true;
        }
        if (drawReactionMention) {
            int w = AndroidUtilities.dp(24);
            messageWidth -= w;
            if (!LocaleController.isRTL) {
                reactionMentionLeft = getMeasuredWidth() - AndroidUtilities.dp(32) - (mentionWidth != 0 ? (mentionWidth + AndroidUtilities.dp(18)) : 0) - (countWidth != 0 ? countWidth + AndroidUtilities.dp(18) : 0);
            } else {
                reactionMentionLeft = AndroidUtilities.dp(20) + (countWidth != 0 ? countWidth + AndroidUtilities.dp(18) : 0);
                messageLeft += w;
                messageNameLeft += w;
            }
        }
    } else {
        if (drawPin) {
            int w = Theme.dialogs_pinnedDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8);
            messageWidth -= w;
            if (LocaleController.isRTL) {
                messageLeft += w;
                messageNameLeft += w;
            }
        }
        drawCount = false;
        drawMention = false;
    }
    if (checkMessage) {
        if (messageString == null) {
            messageString = "";
        }
        CharSequence mess = messageString;
        if (mess.length() > 150) {
            mess = mess.subSequence(0, 150);
        }
        if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || messageNameString != null) {
            mess = AndroidUtilities.replaceNewLines(mess);
        } else {
            mess = AndroidUtilities.replaceTwoNewLinesToOne(mess);
        }
        messageString = Emoji.replaceEmoji(mess, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(17), false);
        if (message != null) {
            CharSequence s = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
            if (s != null) {
                messageString = s;
            }
        }
    }
    messageWidth = Math.max(AndroidUtilities.dp(12), messageWidth);
    if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && messageNameString != null && (currentDialogFolderId == 0 || currentDialogFolderDialogsCount == 1)) {
        try {
            if (message != null && message.hasHighlightedWords()) {
                CharSequence s = AndroidUtilities.highlightText(messageNameString, message.highlightedWords, resourcesProvider);
                if (s != null) {
                    messageNameString = s;
                }
            }
            messageNameLayout = StaticLayoutEx.createStaticLayout(messageNameString, Theme.dialogs_messageNamePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false, TextUtils.TruncateAt.END, messageWidth, 1);
        } catch (Exception e) {
            FileLog.e(e);
        }
        messageTop = AndroidUtilities.dp(32 + 19);
        thumbImage.setImageY(avatarTop + AndroidUtilities.dp(40));
    } else {
        messageNameLayout = null;
        if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
            messageTop = AndroidUtilities.dp(32);
            thumbImage.setImageY(avatarTop + AndroidUtilities.dp(21));
        } else {
            messageTop = AndroidUtilities.dp(39);
        }
    }
    try {
        CharSequence messageStringFinal;
        if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && currentDialogFolderId != 0 && currentDialogFolderDialogsCount > 1) {
            messageStringFinal = messageNameString;
            messageNameString = null;
            currentMessagePaint = Theme.dialogs_messagePaint[paintIndex];
        } else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || messageNameString != null) {
            messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
        } else {
            messageStringFinal = messageString;
        }
        // Removing links and bold spans to get rid of underlining and boldness
        if (messageStringFinal instanceof Spannable) {
            Spannable messageStringSpannable = (Spannable) messageStringFinal;
            for (CharacterStyle span : messageStringSpannable.getSpans(0, messageStringSpannable.length(), CharacterStyle.class)) {
                if (span instanceof ClickableSpan || (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == android.graphics.Typeface.BOLD)) {
                    messageStringSpannable.removeSpan(span);
                }
            }
        }
        if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
            if (hasMessageThumb && messageNameString != null) {
                messageWidth += AndroidUtilities.dp(6);
            }
            messageLayout = StaticLayoutEx.createStaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, messageWidth, messageNameString != null ? 1 : 2);
        } else {
            if (hasMessageThumb) {
                messageWidth += thumbSize + AndroidUtilities.dp(6);
                if (LocaleController.isRTL) {
                    messageLeft -= thumbSize + AndroidUtilities.dp(6);
                }
            }
            messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        }
        spoilersPool.addAll(spoilers);
        spoilers.clear();
        SpoilerEffect.addSpoilers(this, messageLayout, spoilersPool, spoilers);
    } catch (Exception e) {
        messageLayout = null;
        FileLog.e(e);
    }
    double widthpx;
    float left;
    if (LocaleController.isRTL) {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineLeft(0);
            widthpx = Math.ceil(nameLayout.getLineWidth(0));
            if (dialogMuted && !drawVerified && drawScam == 0) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - Theme.dialogs_muteDrawable.getIntrinsicWidth());
            } else if (drawVerified) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - Theme.dialogs_verifiedDrawable.getIntrinsicWidth());
            } else if (drawScam != 0) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth());
            }
            if (left == 0) {
                if (widthpx < nameWidth) {
                    nameLeft += (nameWidth - widthpx);
                }
            }
        }
        if (messageLayout != null) {
            int lineCount = messageLayout.getLineCount();
            if (lineCount > 0) {
                int w = Integer.MAX_VALUE;
                for (int a = 0; a < lineCount; a++) {
                    left = messageLayout.getLineLeft(a);
                    if (left == 0) {
                        widthpx = Math.ceil(messageLayout.getLineWidth(a));
                        w = Math.min(w, (int) (messageWidth - widthpx));
                    } else {
                        w = 0;
                        break;
                    }
                }
                if (w != Integer.MAX_VALUE) {
                    messageLeft += w;
                }
            }
        }
        if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) {
            left = messageNameLayout.getLineLeft(0);
            if (left == 0) {
                widthpx = Math.ceil(messageNameLayout.getLineWidth(0));
                if (widthpx < messageWidth) {
                    messageNameLeft += (messageWidth - widthpx);
                }
            }
        }
    } else {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineRight(0);
            if (left == nameWidth) {
                widthpx = Math.ceil(nameLayout.getLineWidth(0));
                if (widthpx < nameWidth) {
                    nameLeft -= (nameWidth - widthpx);
                }
            }
            if (dialogMuted || drawVerified || drawScam != 0) {
                nameMuteLeft = (int) (nameLeft + left + AndroidUtilities.dp(6));
            }
        }
        if (messageLayout != null) {
            int lineCount = messageLayout.getLineCount();
            if (lineCount > 0) {
                left = Integer.MAX_VALUE;
                for (int a = 0; a < lineCount; a++) {
                    left = Math.min(left, messageLayout.getLineLeft(a));
                }
                messageLeft -= left;
            }
        }
        if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) {
            messageNameLeft -= messageNameLayout.getLineLeft(0);
        }
    }
    if (messageLayout != null && hasMessageThumb) {
        try {
            int textLen = messageLayout.getText().length();
            if (offsetName >= textLen) {
                offsetName = textLen - 1;
            }
            float x1 = messageLayout.getPrimaryHorizontal(offsetName);
            float x2 = messageLayout.getPrimaryHorizontal(offsetName + 1);
            int offset = (int) Math.ceil(Math.min(x1, x2));
            if (offset != 0) {
                offset += AndroidUtilities.dp(3);
            }
            thumbImage.setImageX(messageLeft + offset);
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    if (messageLayout != null && printingStringType >= 0) {
        float x1, x2;
        if (printigStingReplaceIndex >= 0 && printigStingReplaceIndex + 1 < messageLayout.getText().length()) {
            x1 = messageLayout.getPrimaryHorizontal(printigStingReplaceIndex);
            x2 = messageLayout.getPrimaryHorizontal(printigStingReplaceIndex + 1);
        } else {
            x1 = messageLayout.getPrimaryHorizontal(0);
            x2 = messageLayout.getPrimaryHorizontal(1);
        }
        if (x1 < x2) {
            statusDrawableLeft = (int) (messageLeft + x1);
        } else {
            statusDrawableLeft = (int) (messageLeft + x2 + AndroidUtilities.dp(3));
        }
    }
}
Also used : MessagesController(org.telegram.messenger.MessagesController) StatusDrawable(org.telegram.ui.Components.StatusDrawable) TLRPC(org.telegram.tgnet.TLRPC) CharacterStyle(android.text.style.CharacterStyle) ForegroundColorSpanThemable(org.telegram.ui.Components.ForegroundColorSpanThemable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) PullForegroundDrawable(org.telegram.ui.Components.PullForegroundDrawable) StatusDrawable(org.telegram.ui.Components.StatusDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) StaticLayout(android.text.StaticLayout) ClickableSpan(android.text.style.ClickableSpan) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) TextPaint(android.text.TextPaint) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) StyleSpan(android.text.style.StyleSpan) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) UserObject(org.telegram.messenger.UserObject) ChatObject(org.telegram.messenger.ChatObject) Spannable(android.text.Spannable) SpannableStringBuilder(android.text.SpannableStringBuilder)

Example 17 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class ReactedUsersListView method load.

@SuppressLint("NotifyDataSetChanged")
private void load() {
    isLoading = true;
    MessagesController ctrl = MessagesController.getInstance(currentAccount);
    TLRPC.TL_messages_getMessageReactionsList getList = new TLRPC.TL_messages_getMessageReactionsList();
    getList.peer = ctrl.getInputPeer(message.getDialogId());
    getList.id = message.getId();
    getList.limit = getLoadCount();
    getList.reaction = filter;
    getList.offset = offset;
    if (filter != null)
        getList.flags |= 1;
    if (offset != null)
        getList.flags |= 2;
    ConnectionsManager.getInstance(currentAccount).sendRequest(getList, (response, error) -> {
        if (response instanceof TLRPC.TL_messages_messageReactionsList) {
            TLRPC.TL_messages_messageReactionsList l = (TLRPC.TL_messages_messageReactionsList) response;
            for (TLRPC.User u : l.users) {
                MessagesController.getInstance(currentAccount).putUser(u, false);
                users.put(u.id, u);
            }
            // It's safer to create a new list to prevent inconsistency
            int prev = userReactions.size();
            List<TLRPC.TL_messagePeerReaction> newReactions = new ArrayList<>(userReactions.size() + l.reactions.size());
            newReactions.addAll(userReactions);
            newReactions.addAll(l.reactions);
            if (onlySeenNow) {
                Collections.sort(newReactions, (o1, o2) -> Integer.compare(o1.reaction != null ? 1 : 0, o2.reaction != null ? 1 : 0));
            }
            AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).doOnIdle(() -> {
                userReactions = newReactions;
                if (onlySeenNow) {
                    onlySeenNow = false;
                    adapter.notifyDataSetChanged();
                } else
                    adapter.notifyItemRangeInserted(prev, l.reactions.size());
                if (!isLoaded) {
                    ValueAnimator anim = ValueAnimator.ofFloat(0, 1).setDuration(150);
                    anim.setInterpolator(CubicBezierInterpolator.DEFAULT);
                    anim.addUpdateListener(animation -> {
                        float val = (float) animation.getAnimatedValue();
                        listView.setAlpha(val);
                        loadingView.setAlpha(1f - val);
                    });
                    anim.addListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            loadingView.setVisibility(GONE);
                        }
                    });
                    anim.start();
                    updateHeight();
                    isLoaded = true;
                }
                offset = l.next_offset;
                if (offset == null)
                    canLoadMore = false;
                isLoading = false;
            }));
        } else
            isLoading = false;
    }, ConnectionsManager.RequestFlagInvokeAfter);
}
Also used : Context(android.content.Context) SvgHelper(org.telegram.messenger.SvgHelper) Theme(org.telegram.ui.ActionBar.Theme) NonNull(androidx.annotation.NonNull) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) ColorDrawable(android.graphics.drawable.ColorDrawable) Animator(android.animation.Animator) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC) View(android.view.View) MessageObject(org.telegram.messenger.MessageObject) RecyclerView(androidx.recyclerview.widget.RecyclerView) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) DocumentObject(org.telegram.messenger.DocumentObject) ImageLocation(org.telegram.messenger.ImageLocation) TextUtils(android.text.TextUtils) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) MessagesController(org.telegram.messenger.MessagesController) NotificationCenter(org.telegram.messenger.NotificationCenter) Gravity(android.view.Gravity) List(java.util.List) TextView(android.widget.TextView) UserObject(org.telegram.messenger.UserObject) TypedValue(android.util.TypedValue) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) LongSparseArray(android.util.LongSparseArray) Collections(java.util.Collections) ValueAnimator(android.animation.ValueAnimator) MessagesController(org.telegram.messenger.MessagesController) ArrayList(java.util.ArrayList) ValueAnimator(android.animation.ValueAnimator) TLRPC(org.telegram.tgnet.TLRPC) SuppressLint(android.annotation.SuppressLint) Animator(android.animation.Animator) ValueAnimator(android.animation.ValueAnimator) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) SuppressLint(android.annotation.SuppressLint)

Example 18 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class VoIPService method initiateActualEncryptedCall.

private void initiateActualEncryptedCall() {
    if (timeoutRunnable != null) {
        AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
        timeoutRunnable = null;
    }
    try {
        if (BuildVars.LOGS_ENABLED) {
            FileLog.d("InitCall: keyID=" + keyFingerprint);
        }
        SharedPreferences nprefs = MessagesController.getNotificationsSettings(currentAccount);
        Set<String> set = nprefs.getStringSet("calls_access_hashes", null);
        HashSet<String> hashes;
        if (set != null) {
            hashes = new HashSet<>(set);
        } else {
            hashes = new HashSet<>();
        }
        hashes.add(privateCall.id + " " + privateCall.access_hash + " " + System.currentTimeMillis());
        while (hashes.size() > 20) {
            String oldest = null;
            long oldestTime = Long.MAX_VALUE;
            Iterator<String> itr = hashes.iterator();
            while (itr.hasNext()) {
                String item = itr.next();
                String[] s = item.split(" ");
                if (s.length < 2) {
                    itr.remove();
                } else {
                    try {
                        long t = Long.parseLong(s[2]);
                        if (t < oldestTime) {
                            oldestTime = t;
                            oldest = item;
                        }
                    } catch (Exception x) {
                        itr.remove();
                    }
                }
            }
            if (oldest != null) {
                hashes.remove(oldest);
            }
        }
        nprefs.edit().putStringSet("calls_access_hashes", hashes).commit();
        boolean sysAecAvailable = false, sysNsAvailable = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            try {
                sysAecAvailable = AcousticEchoCanceler.isAvailable();
            } catch (Exception ignored) {
            }
            try {
                sysNsAvailable = NoiseSuppressor.isAvailable();
            } catch (Exception ignored) {
            }
        }
        final SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        // config
        final MessagesController messagesController = MessagesController.getInstance(currentAccount);
        final double initializationTimeout = messagesController.callConnectTimeout / 1000.0;
        final double receiveTimeout = messagesController.callPacketTimeout / 1000.0;
        final int voipDataSaving = convertDataSavingMode(preferences.getInt("VoipDataSaving", VoIPHelper.getDataSavingDefault()));
        final Instance.ServerConfig serverConfig = Instance.getGlobalServerConfig();
        final boolean enableAec = !(sysAecAvailable && serverConfig.useSystemAec);
        final boolean enableNs = !(sysNsAvailable && serverConfig.useSystemNs);
        final String logFilePath = BuildVars.DEBUG_VERSION ? VoIPHelper.getLogFilePath("voip" + privateCall.id) : VoIPHelper.getLogFilePath(privateCall.id, false);
        final String statisLogFilePath = "";
        final Instance.Config config = new Instance.Config(initializationTimeout, receiveTimeout, voipDataSaving, privateCall.p2p_allowed, enableAec, enableNs, true, false, serverConfig.enableStunMarking, logFilePath, statisLogFilePath, privateCall.protocol.max_layer);
        // persistent state
        final String persistentStateFilePath = new File(ApplicationLoader.applicationContext.getFilesDir(), "voip_persistent_state.json").getAbsolutePath();
        // endpoints
        final boolean forceTcp = preferences.getBoolean("dbg_force_tcp_in_calls", false);
        final int endpointType = forceTcp ? Instance.ENDPOINT_TYPE_TCP_RELAY : Instance.ENDPOINT_TYPE_UDP_RELAY;
        final Instance.Endpoint[] endpoints = new Instance.Endpoint[privateCall.connections.size()];
        for (int i = 0; i < endpoints.length; i++) {
            final TLRPC.PhoneConnection connection = privateCall.connections.get(i);
            endpoints[i] = new Instance.Endpoint(connection instanceof TLRPC.TL_phoneConnectionWebrtc, connection.id, connection.ip, connection.ipv6, connection.port, endpointType, connection.peer_tag, connection.turn, connection.stun, connection.username, connection.password);
        }
        if (forceTcp) {
            AndroidUtilities.runOnUIThread(() -> Toast.makeText(VoIPService.this, "This call uses TCP which will degrade its quality.", Toast.LENGTH_SHORT).show());
        }
        // proxy
        Instance.Proxy proxy = null;
        if (preferences.getBoolean("proxy_enabled", false) && preferences.getBoolean("proxy_enabled_calls", false)) {
            final String server = preferences.getString("proxy_ip", null);
            final String secret = preferences.getString("proxy_secret", null);
            if (!TextUtils.isEmpty(server) && TextUtils.isEmpty(secret)) {
                proxy = new Instance.Proxy(server, preferences.getInt("proxy_port", 0), preferences.getString("proxy_user", null), preferences.getString("proxy_pass", null));
            }
        }
        // encryption key
        final Instance.EncryptionKey encryptionKey = new Instance.EncryptionKey(authKey, isOutgoing);
        boolean newAvailable = "2.7.7".compareTo(privateCall.protocol.library_versions.get(0)) <= 0;
        if (captureDevice[CAPTURE_DEVICE_CAMERA] != 0 && !newAvailable) {
            NativeInstance.destroyVideoCapturer(captureDevice[CAPTURE_DEVICE_CAMERA]);
            captureDevice[CAPTURE_DEVICE_CAMERA] = 0;
            videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_INACTIVE;
        }
        if (!isOutgoing) {
            if (videoCall && (Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
                captureDevice[CAPTURE_DEVICE_CAMERA] = NativeInstance.createVideoCapturer(localSink[CAPTURE_DEVICE_CAMERA], isFrontFaceCamera ? 1 : 0);
                videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_ACTIVE;
            } else {
                videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_INACTIVE;
            }
        }
        // init
        tgVoip[CAPTURE_DEVICE_CAMERA] = Instance.makeInstance(privateCall.protocol.library_versions.get(0), config, persistentStateFilePath, endpoints, proxy, getNetworkType(), encryptionKey, remoteSink[CAPTURE_DEVICE_CAMERA], captureDevice[CAPTURE_DEVICE_CAMERA], (uids, levels, voice) -> {
            if (sharedInstance == null || privateCall == null) {
                return;
            }
            NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.webRtcMicAmplitudeEvent, levels[0]);
        });
        tgVoip[CAPTURE_DEVICE_CAMERA].setOnStateUpdatedListener(this::onConnectionStateChanged);
        tgVoip[CAPTURE_DEVICE_CAMERA].setOnSignalBarsUpdatedListener(this::onSignalBarCountChanged);
        tgVoip[CAPTURE_DEVICE_CAMERA].setOnSignalDataListener(this::onSignalingData);
        tgVoip[CAPTURE_DEVICE_CAMERA].setOnRemoteMediaStateUpdatedListener((audioState, videoState) -> AndroidUtilities.runOnUIThread(() -> {
            remoteAudioState = audioState;
            remoteVideoState = videoState;
            checkIsNear();
            for (int a = 0; a < stateListeners.size(); a++) {
                StateListener l = stateListeners.get(a);
                l.onMediaStateUpdated(audioState, videoState);
            }
        }));
        tgVoip[CAPTURE_DEVICE_CAMERA].setMuteMicrophone(micMute);
        if (newAvailable != isVideoAvailable) {
            isVideoAvailable = newAvailable;
            for (int a = 0; a < stateListeners.size(); a++) {
                StateListener l = stateListeners.get(a);
                l.onVideoAvailableChange(isVideoAvailable);
            }
        }
        destroyCaptureDevice[CAPTURE_DEVICE_CAMERA] = false;
        AndroidUtilities.runOnUIThread(new Runnable() {

            @Override
            public void run() {
                if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) {
                    updateTrafficStats(tgVoip[CAPTURE_DEVICE_CAMERA], null);
                    AndroidUtilities.runOnUIThread(this, 5000);
                }
            }
        }, 5000);
    } catch (Exception x) {
        if (BuildVars.LOGS_ENABLED) {
            FileLog.e("error starting call", x);
        }
        callFailed();
    }
}
Also used : SensorManager(android.hardware.SensorManager) Arrays(java.util.Arrays) Bundle(android.os.Bundle) VoIPFragment(org.telegram.ui.VoIPFragment) Uri(android.net.Uri) LruCache(android.util.LruCache) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) StatsController(org.telegram.messenger.StatsController) Canvas(android.graphics.Canvas) SensorEventListener(android.hardware.SensorEventListener) BigInteger(java.math.BigInteger) ForegroundColorSpan(android.text.style.ForegroundColorSpan) TargetApi(android.annotation.TargetApi) NotificationsController(org.telegram.messenger.NotificationsController) ConnectivityManager(android.net.ConnectivityManager) IntentFilter(android.content.IntentFilter) Set(java.util.Set) NotificationCenter(org.telegram.messenger.NotificationCenter) SoundPool(android.media.SoundPool) Nullable(androidx.annotation.Nullable) LaunchActivity(org.telegram.ui.LaunchActivity) Paint(android.graphics.Paint) DisconnectCause(android.telecom.DisconnectCause) FileLoader(org.telegram.messenger.FileLoader) Path(android.graphics.Path) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AudioFormat(android.media.AudioFormat) BitmapFactory(android.graphics.BitmapFactory) SystemClock(android.os.SystemClock) WebRtcAudioTrack(org.webrtc.voiceengine.WebRtcAudioTrack) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) BuildConfig(org.telegram.messenger.BuildConfig) VoIPFeedbackActivity(org.telegram.ui.VoIPFeedbackActivity) Sensor(android.hardware.Sensor) BluetoothProfile(android.bluetooth.BluetoothProfile) ComponentName(android.content.ComponentName) SpannableString(android.text.SpannableString) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) JoinCallAlert(org.telegram.ui.Components.JoinCallAlert) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Field(java.lang.reflect.Field) File(java.io.File) PorterDuffXfermode(android.graphics.PorterDuffXfermode) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) PhoneAccount(android.telecom.PhoneAccount) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) RingtoneManager(android.media.RingtoneManager) TelecomManager(android.telecom.TelecomManager) ChatObject(org.telegram.messenger.ChatObject) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) KeyguardManager(android.app.KeyguardManager) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) PendingIntent(android.app.PendingIntent) IBinder(android.os.IBinder) PhoneAccountHandle(android.telecom.PhoneAccountHandle) PowerManager(android.os.PowerManager) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) NotificationChannel(android.app.NotificationChannel) View(android.view.View) Method(java.lang.reflect.Method) VoIPPermissionActivity(org.telegram.ui.VoIPPermissionActivity) RemoteViews(android.widget.RemoteViews) ImageLoader(org.telegram.messenger.ImageLoader) Utilities(org.telegram.messenger.Utilities) NotificationManager(android.app.NotificationManager) Service(android.app.Service) NetworkInfo(android.net.NetworkInfo) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BroadcastReceiver(android.content.BroadcastReceiver) AcousticEchoCanceler(android.media.audiofx.AcousticEchoCanceler) UserConfig(org.telegram.messenger.UserConfig) CallAudioState(android.telecom.CallAudioState) MediaRouter(android.media.MediaRouter) Notification(android.app.Notification) BluetoothDevice(android.bluetooth.BluetoothDevice) Context(android.content.Context) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) MediaPlayer(android.media.MediaPlayer) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) AudioTrack(android.media.AudioTrack) AudioManager(android.media.AudioManager) VideoFrame(org.webrtc.VideoFrame) HashSet(java.util.HashSet) XiaomiUtilities(org.telegram.messenger.XiaomiUtilities) SuppressLint(android.annotation.SuppressLint) BluetoothHeadset(android.bluetooth.BluetoothHeadset) SensorEvent(android.hardware.SensorEvent) TelephonyManager(android.telephony.TelephonyManager) TLObject(org.telegram.tgnet.TLObject) AudioAttributes(android.media.AudioAttributes) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) Icon(android.graphics.drawable.Icon) Build(android.os.Build) VideoSink(org.webrtc.VideoSink) Iterator(java.util.Iterator) BluetoothAdapter(android.bluetooth.BluetoothAdapter) NoiseSuppressor(android.media.audiofx.NoiseSuppressor) FileLog(org.telegram.messenger.FileLog) Connection(android.telecom.Connection) MessagesController(org.telegram.messenger.MessagesController) Bitmap(android.graphics.Bitmap) Vibrator(android.os.Vibrator) Activity(android.app.Activity) AccountInstance(org.telegram.messenger.AccountInstance) BuildConfig(org.telegram.messenger.BuildConfig) UserConfig(org.telegram.messenger.UserConfig) SharedConfig(org.telegram.messenger.SharedConfig) MessagesController(org.telegram.messenger.MessagesController) SpannableString(android.text.SpannableString) TLRPC(org.telegram.tgnet.TLRPC) SharedPreferences(android.content.SharedPreferences) IOException(java.io.IOException) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) File(java.io.File)

Example 19 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class ChatActivity method searchLinks.

private void searchLinks(final CharSequence charSequence, final boolean force) {
    if (currentEncryptedChat != null && getMessagesController().secretWebpagePreview == 0 || editingMessageObject != null && !editingMessageObject.isWebpage()) {
        return;
    }
    if (force && foundWebPage != null) {
        if (foundWebPage.url != null) {
            int index = TextUtils.indexOf(charSequence, foundWebPage.url);
            char lastChar = 0;
            boolean lenEqual = false;
            if (index == -1) {
                if (foundWebPage.display_url != null) {
                    index = TextUtils.indexOf(charSequence, foundWebPage.display_url);
                    lenEqual = index != -1 && index + foundWebPage.display_url.length() == charSequence.length();
                    lastChar = index != -1 && !lenEqual ? charSequence.charAt(index + foundWebPage.display_url.length()) : 0;
                }
            } else {
                lenEqual = index + foundWebPage.url.length() == charSequence.length();
                lastChar = !lenEqual ? charSequence.charAt(index + foundWebPage.url.length()) : 0;
            }
            if (index != -1 && (lenEqual || lastChar == ' ' || lastChar == ',' || lastChar == '.' || lastChar == '!' || lastChar == '/')) {
                return;
            }
        }
        pendingLinkSearchString = null;
        foundUrls = null;
        showFieldPanelForWebPage(false, foundWebPage, false);
    }
    final MessagesController messagesController = getMessagesController();
    Utilities.searchQueue.postRunnable(() -> {
        if (linkSearchRequestId != 0) {
            getConnectionsManager().cancelRequest(linkSearchRequestId, true);
            linkSearchRequestId = 0;
        }
        ArrayList<CharSequence> urls = null;
        CharSequence textToCheck;
        try {
            Matcher m = AndroidUtilities.WEB_URL.matcher(charSequence);
            while (m.find()) {
                if (m.start() > 0) {
                    if (charSequence.charAt(m.start() - 1) == '@') {
                        continue;
                    }
                }
                if (urls == null) {
                    urls = new ArrayList<>();
                }
                urls.add(charSequence.subSequence(m.start(), m.end()));
            }
            if (charSequence instanceof Spannable) {
                URLSpanReplacement[] spans = ((Spannable) charSequence).getSpans(0, charSequence.length(), URLSpanReplacement.class);
                if (spans != null && spans.length > 0) {
                    if (urls == null) {
                        urls = new ArrayList<>();
                    }
                    for (int a = 0; a < spans.length; a++) {
                        urls.add(spans[a].getURL());
                    }
                }
            }
            if (urls != null && foundUrls != null && urls.size() == foundUrls.size()) {
                boolean clear = true;
                for (int a = 0; a < urls.size(); a++) {
                    if (!TextUtils.equals(urls.get(a), foundUrls.get(a))) {
                        clear = false;
                    }
                }
                if (clear) {
                    return;
                }
            }
            foundUrls = urls;
            if (urls == null) {
                AndroidUtilities.runOnUIThread(() -> {
                    if (foundWebPage != null) {
                        showFieldPanelForWebPage(false, foundWebPage, false);
                        foundWebPage = null;
                    }
                });
                return;
            }
            textToCheck = TextUtils.join(" ", urls);
        } catch (Exception e) {
            FileLog.e(e);
            String text = charSequence.toString().toLowerCase();
            if (charSequence.length() < 13 || !text.contains("http://") && !text.contains("https://")) {
                AndroidUtilities.runOnUIThread(() -> {
                    if (foundWebPage != null) {
                        showFieldPanelForWebPage(false, foundWebPage, false);
                        foundWebPage = null;
                    }
                });
                return;
            }
            textToCheck = charSequence;
        }
        if (currentEncryptedChat != null && messagesController.secretWebpagePreview == 2) {
            AndroidUtilities.runOnUIThread(() -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> {
                    messagesController.secretWebpagePreview = 1;
                    MessagesController.getGlobalMainSettings().edit().putInt("secretWebpage2", getMessagesController().secretWebpagePreview).commit();
                    foundUrls = null;
                    searchLinks(charSequence, force);
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(LocaleController.getString("SecretLinkPreviewAlert", R.string.SecretLinkPreviewAlert));
                showDialog(builder.create());
                messagesController.secretWebpagePreview = 0;
                MessagesController.getGlobalMainSettings().edit().putInt("secretWebpage2", messagesController.secretWebpagePreview).commit();
            });
            return;
        }
        final TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview();
        if (textToCheck instanceof String) {
            req.message = (String) textToCheck;
        } else {
            req.message = textToCheck.toString();
        }
        linkSearchRequestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
            linkSearchRequestId = 0;
            if (error == null) {
                if (response instanceof TLRPC.TL_messageMediaWebPage) {
                    foundWebPage = ((TLRPC.TL_messageMediaWebPage) response).webpage;
                    if (foundWebPage instanceof TLRPC.TL_webPage || foundWebPage instanceof TLRPC.TL_webPagePending) {
                        if (foundWebPage instanceof TLRPC.TL_webPagePending) {
                            pendingLinkSearchString = req.message;
                        }
                        if (currentEncryptedChat != null && foundWebPage instanceof TLRPC.TL_webPagePending) {
                            foundWebPage.url = req.message;
                        }
                        showFieldPanelForWebPage(true, foundWebPage, false);
                    } else {
                        if (foundWebPage != null) {
                            showFieldPanelForWebPage(false, foundWebPage, false);
                            foundWebPage = null;
                        }
                    }
                } else {
                    if (foundWebPage != null) {
                        showFieldPanelForWebPage(false, foundWebPage, false);
                        foundWebPage = null;
                    }
                }
            }
        }));
        getConnectionsManager().bindRequestToGuid(linkSearchRequestId, classGuid);
    });
}
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) Matcher(java.util.regex.Matcher) SpannableStringBuilder(android.text.SpannableStringBuilder) MessagesController(org.telegram.messenger.MessagesController) SpannableString(android.text.SpannableString) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC) Spannable(android.text.Spannable) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement)

Example 20 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class ChatPullingDownDrawable method getNextUnreadDialog.

public static TLRPC.Dialog getNextUnreadDialog(long currentDialogId, int folderId, int filterId, boolean searchNext, int[] params) {
    MessagesController messagesController = AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController();
    if (params != null) {
        params[0] = 0;
        params[1] = folderId;
        params[2] = filterId;
    }
    ArrayList<TLRPC.Dialog> dialogs;
    if (filterId != 0) {
        MessagesController.DialogFilter filter = messagesController.dialogFiltersById.get(filterId);
        if (filter == null) {
            return null;
        }
        dialogs = filter.dialogs;
    } else {
        dialogs = messagesController.getDialogs(folderId);
    }
    if (dialogs == null) {
        return null;
    }
    for (int i = 0; i < dialogs.size(); i++) {
        TLRPC.Dialog dialog = dialogs.get(i);
        TLRPC.Chat chat = messagesController.getChat(-dialog.id);
        if (chat != null && dialog.id != currentDialogId && dialog.unread_count > 0 && DialogObject.isChannel(dialog) && !chat.megagroup && !messagesController.isPromoDialog(dialog.id, false)) {
            String reason = MessagesController.getRestrictionReason(chat.restriction_reason);
            if (reason == null) {
                return dialog;
            }
        }
    }
    if (searchNext) {
        if (filterId != 0) {
            for (int i = 0; i < messagesController.dialogFilters.size(); i++) {
                int newFilterId = messagesController.dialogFilters.get(i).id;
                if (filterId != newFilterId) {
                    TLRPC.Dialog dialog = getNextUnreadDialog(currentDialogId, folderId, newFilterId, false, params);
                    if (dialog != null) {
                        if (params != null) {
                            params[0] = 1;
                        }
                        return dialog;
                    }
                }
            }
        }
        for (int i = 0; i < messagesController.dialogsByFolder.size(); i++) {
            int newFolderId = messagesController.dialogsByFolder.keyAt(i);
            if (folderId != newFolderId) {
                TLRPC.Dialog dialog = getNextUnreadDialog(currentDialogId, newFolderId, 0, false, params);
                if (dialog != null) {
                    if (params != null) {
                        params[0] = 1;
                    }
                    return dialog;
                }
            }
        }
    }
    return null;
}
Also used : MessagesController(org.telegram.messenger.MessagesController) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) TLRPC(org.telegram.tgnet.TLRPC)

Aggregations

MessagesController (org.telegram.messenger.MessagesController)20 TLRPC (org.telegram.tgnet.TLRPC)18 ArrayList (java.util.ArrayList)10 Paint (android.graphics.Paint)9 SuppressLint (android.annotation.SuppressLint)7 TextPaint (android.text.TextPaint)7 MessageObject (org.telegram.messenger.MessageObject)7 TLObject (org.telegram.tgnet.TLObject)6 View (android.view.View)5 ChatObject (org.telegram.messenger.ChatObject)5 UserObject (org.telegram.messenger.UserObject)5 Animator (android.animation.Animator)4 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)4 ValueAnimator (android.animation.ValueAnimator)4 Context (android.content.Context)4 SharedPreferences (android.content.SharedPreferences)4 Build (android.os.Build)4 TextUtils (android.text.TextUtils)4 ViewGroup (android.view.ViewGroup)4 TextView (android.widget.TextView)4